bool MusikTaskBarIcon::SetIcon(const wxIcon& icon, const wxString& tooltip ) { bool bRes = false; #ifndef __WXMSW__ bRes = wxTaskBarIcon::SetIcon(icon,tooltip); #else if(m_dwShellDllVersion < PACKVERSION(5,00)) bRes = wxTaskBarIcon::SetIcon(icon,tooltip); else { // we can use NOTIFYICONDATA V2,where the szTip has 128 chars instead of 64 bRes = wxTaskBarIcon::SetIcon(icon,wxEmptyString);//just set the icon. if(!tooltip.empty()) {// now set the tooltip text with the help of NOTIFYICONDATA V2 struct. NOTIFYICONDATA nid; memset(&nid,0,sizeof(nid)); nid.cbSize = NOTIFYICONDATAW_V2_SIZE; nid.hWnd = (HWND)m_win->GetHWND(); nid.uID = 99; nid.uFlags = NIF_TIP; wxStrncpy(nid.szTip, tooltip.c_str(), WXSIZEOF(nid.szTip)); Shell_NotifyIcon(NIM_MODIFY, &nid); } } #endif return bRes; }
bool wxGetFullHostName(wxChar *buf, int sz) { bool ok = wxGetHostNameInternal(buf, sz); if ( ok ) { if ( !wxStrchr(buf, wxT('.')) ) { struct hostent *host = gethostbyname(wxConvertWX2MB(buf)); if ( !host ) { wxLogSysError(_("Cannot get the official hostname")); ok = false; } else { // the canonical name wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz); } } //else: it's already a FQDN (BSD behaves this way) } return ok; }
static BOOL CALLBACK wxEnumSymbolsCallback(PSYMBOL_INFO pSymInfo, ULONG SymbolSize, PVOID UserContext) { wxEnumSymbolsCallbackBridge& bridge = *static_cast<wxEnumSymbolsCallbackBridge*>(UserContext); const wxWCharBuffer buf = wxConvLocal.cMB2WC(pSymInfo->Name); const size_t len = buf.length(); // Allocate enough space for the wide char version of the struct. // // Note that there is no +1 here because sizeof(SYMBOL_INFOW) already // includes 1 byte of the name. wxScopedArray<BYTE> symbolBuffer(sizeof(SYMBOL_INFOW) + len*sizeof(WCHAR)); SYMBOL_INFOW* const infoW = (SYMBOL_INFOW*)symbolBuffer.get(); // Copy the original struct contents except for the last byte, which is the // first byte of its (narrow) name that we don't need. CopyMemory(infoW, pSymInfo, sizeof(SYMBOL_INFO) - sizeof(CHAR)); // Size is different for narrow and wide variants of the struct, so fix it // up now. infoW->SizeOfStruct = sizeof(SYMBOL_INFOW); // Finally copy the converted name, which is the reason for doing all this. wxStrncpy(infoW->Name, buf.data(), len); return (*bridge.m_callback)(infoW, SymbolSize, bridge.m_data); }
bool wxTestFontEncoding( const wxNativeEncodingInfo& rInfo ) { FATTRS vLogFont; HPS hPS; hPS = ::WinGetPS(HWND_DESKTOP); memset(&vLogFont, '\0', sizeof(FATTRS)); // all default values vLogFont.usRecordLength = sizeof(FATTRS); vLogFont.usCodePage = rInfo.charset; vLogFont.lMaxBaselineExt = 0L; // Outline fonts should use 0 vLogFont.lAveCharWidth = 0L; // Outline fonts should use 0 vLogFont.fsFontUse = FATTR_FONTUSE_OUTLINE | // only outline fonts allowed FATTR_FONTUSE_TRANSFORMABLE; // may be transformed wxStrncpy((wxChar*)vLogFont.szFacename, rInfo.facename.c_str(), WXSIZEOF(vLogFont.szFacename)); if (!::GpiCreateLogFont( hPS ,NULL ,1L ,&vLogFont )) { ::WinReleasePS(hPS); return FALSE; } ::WinReleasePS(hPS); return TRUE; } // end of wxTestFontEncoding
bool wxGetClipboardFormatName(wxDataFormat dataFormat, char *formatName, int maxCount) { wxStrncpy( formatName, dataFormat.GetId().c_str(), maxCount ); return true; }
// Get hostname only (without domain name) bool wxGetHostName(wxChar *WXUNUSED_IN_WINCE(buf), int WXUNUSED_IN_WINCE(maxSize)) { #if defined(__WXWINCE__) // TODO-CE return false; #elif defined(__WIN32__) && !defined(__WXMICROWIN__) DWORD nSize = maxSize; if ( !::GetComputerName(buf, &nSize) ) { wxLogLastError(wxT("GetComputerName")); return false; } return true; #else wxChar *sysname; const wxChar *default_host = wxT("noname"); if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) { GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1); } else wxStrncpy(buf, sysname, maxSize - 1); buf[maxSize] = wxT('\0'); return *buf ? true : false; #endif }
// retrieve either the hostname or FQDN depending on platform (caller must // check whether it's one or the other, this is why this function is for // private use only) static bool wxGetHostNameInternal(wxChar *buf, int sz) { wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") ); *buf = wxT('\0'); // we're using uname() which is POSIX instead of less standard sysinfo() #if defined(HAVE_UNAME) struct utsname uts; bool ok = uname(&uts) != -1; if ( ok ) { wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1); buf[sz] = wxT('\0'); } #elif defined(HAVE_GETHOSTNAME) bool ok = gethostname(buf, sz) != -1; #else // no uname, no gethostname wxFAIL_MSG(wxT("don't know host name for this machine")); bool ok = false; #endif // uname/gethostname if ( !ok ) { wxLogSysError(_("Cannot get the hostname")); } return ok; }
// Get user name e.g. Julian Smart bool wxGetUserName(wxChar *buf, int maxSize) { *buf = wxT('\0'); // buffer allocation MemHandle handle = MemHandleNew(maxSize-1); if( handle == NULL ) return false; // lock the buffer char *id = (char *)MemHandleLock(handle); if( id == NULL ) return false; // get user's name if( DlkGetSyncInfo(NULL, NULL, NULL, id, NULL, NULL) != errNone ) { MemPtrUnlock(id); return false; } wxStrncpy (buf, wxConvertMB2WX(id), maxSize - 1); // free the buffer MemPtrUnlock(id); return true; }
bool wxGetUserName( wxChar* zBuf, int nMaxSize ) { #ifdef USE_NET_API wxGetUserId( zBuf, nMaxSize ); #else wxStrncpy(zBuf, _T("Unknown User"), nMaxSize); #endif return true; }
void BugsGridTable::SetValue( int row, int col, const wxString& value ) { BugsGridData& gd = gs_dataBugsGrid[row]; switch ( col ) { case Col_Id: case Col_Priority: case Col_Opened: wxFAIL_MSG(_T("unexpected column")); break; case Col_Severity: { size_t n; for ( n = 0; n < WXSIZEOF(severities); n++ ) { if ( severities[n] == value ) { gd.severity = (Severity)n; break; } } if ( n == WXSIZEOF(severities) ) { wxLogWarning(_T("Invalid severity value '%s'."), value.c_str()); gd.severity = Sev_Normal; } } break; case Col_Summary: wxStrncpy(gd.summary, value, WXSIZEOF(gd.summary)); break; case Col_Platform: wxStrncpy(gd.platform, value, WXSIZEOF(gd.platform)); break; } }
// Get Full RFC822 style email address bool wxGetEmailAddress(wxChar *address, int maxSize) { wxString email = wxGetEmailAddress(); if ( !email ) return false; wxStrncpy(address, email, maxSize - 1); address[maxSize - 1] = wxT('\0'); return true; }
bool wxGetUserName(wxChar *buf, int sz) { struct passwd *who; *buf = wxT('\0'); if ((who = getpwuid (getuid ())) != NULL) { // pw_gecos field in struct passwd is not standard #ifdef HAVE_PW_GECOS char *comma = strchr(who->pw_gecos, ','); if (comma) *comma = '\0'; // cut off non-name comment fields wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1); #else // !HAVE_PW_GECOS wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1); #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS return true; } return false; }
bool wxGetUserId(wxChar *buf, int sz) { struct passwd *who; *buf = wxT('\0'); if ((who = getpwuid(getuid ())) != NULL) { wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1); return true; } return false; }
bool MusikTaskBarIcon::ShowBalloonInfo(const wxString &sTitle,const wxString & sText) { bool bRes = true; if(m_dwShellDllVersion >= PACKVERSION(5,00)) { NOTIFYICONDATA nid; memset(&nid,0,sizeof(nid)); nid.cbSize = NOTIFYICONDATAW_V2_SIZE; nid.hWnd = (HWND)m_win->GetHWND(); nid.uID = 99; nid.uFlags = NIF_INFO; wxStrncpy(nid.szInfo, sText.c_str(), WXSIZEOF(nid.szInfo)); wxStrncpy(nid.szInfoTitle, sTitle.c_str(), WXSIZEOF(nid.szInfoTitle)); nid.dwInfoFlags = NIIF_NOSOUND|NIIF_INFO; nid.uTimeout = 5000; Shell_NotifyIcon(NIM_MODIFY, &nid); } else return false; return bRes; }
void BalloonTaskBar::ShowBalloon(wxString title, wxString msg, int iconID, unsigned int timeout) { wxConfigBase* config = wxConfigBase::Get(true); long show_notification = config->Read(_T("SHOW_NOTIFICATION"), 1L); if (show_notification == 0) return; NOTIFYICONDATA nid; memset(&nid,0,sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = (HWND)m_win->GetHWND(); nid.uID = 99; nid.uFlags = NIF_INFO; wxStrncpy(nid.szInfo, msg.c_str(), WXSIZEOF(nid.szInfo)); wxStrncpy(nid.szInfoTitle, title.c_str(), WXSIZEOF(nid.szInfoTitle)); nid.dwInfoFlags = iconID | NIIF_NOSOUND; nid.uTimeout = timeout; Shell_NotifyIcon(NIM_MODIFY, &nid); }
// Get full hostname (eg. DoDo.BSn-Germany.crg.de) bool wxGetHostName( wxChar* zBuf, int nMaxSize ) { if (!zBuf) return false; #if defined(wxUSE_NET_API) && wxUSE_NET_API char zServer[256]; char zComputer[256]; unsigned long ulLevel = 0; unsigned char* zBuffer = NULL; unsigned long ulBuffer = 256; unsigned long* pulTotalAvail = NULL; NetBios32GetInfo( (const unsigned char*)zServer ,(const unsigned char*)zComputer ,ulLevel ,zBuffer ,ulBuffer ,pulTotalAvail ); strcpy(zBuf, zServer); #else wxChar* zSysname; const wxChar* zDefaultHost = _T("noname"); if ((zSysname = wxGetenv(_T("SYSTEM_NAME"))) == NULL) { ::PrfQueryProfileString( HINI_PROFILE ,(PSZ)WX_SECTION ,(PSZ)eHOSTNAME ,(PSZ)zDefaultHost ,(void*)zBuf ,(ULONG)nMaxSize - 1 ); } else { wxStrncpy(zBuf, zSysname, nMaxSize - 1); } zBuf[nMaxSize] = _T('\0'); #endif return *zBuf ? true : false; }
FirebirdParameter::FirebirdParameter(FirebirdInterface* pInterface, XSQLVAR* pVar, const wxString& strValue, const wxCSConv* conv) { m_pInterface = pInterface; m_pParameter = pVar; m_strValue = strValue; SetEncoding(conv); // Set to SQL_TEXT manually m_pParameter->sqltype = SQL_TEXT; wxCharBuffer valueBuffer = ConvertToUnicodeStream(m_strValue); size_t length = GetEncodedStreamLength(m_strValue); wxStrncpy((wxChar*)m_pParameter->sqldata, (wxChar*)(const char*)valueBuffer, length); //(char*)(m_pParameter->sqldata) = valueBuffer; m_pParameter->sqllen = length; m_nNullFlag = 0; m_pParameter->sqlind = &m_nNullFlag; // NULL indicator }
bool wxTestFontEncoding(const wxNativeEncodingInfo& info) { // try to create such font LOGFONT lf; wxZeroMemory(lf); // all default values lf.lfCharSet = (BYTE)info.charset; wxStrncpy(lf.lfFaceName, info.facename, WXSIZEOF(lf.lfFaceName)); HFONT hfont = ::CreateFontIndirect(&lf); if ( !hfont ) { // no such font return false; } ::DeleteObject((HGDIOBJ)hfont); return true; }
void CopyAllBefore() { wxASSERT_MSG( m_fmtOrig && m_fmt.data() == NULL, "logic error" ); // the modified format string is guaranteed to be no longer than // 3/2 of the original (worst case: the entire format string consists // of "%s" repeated and is expanded to "%ls" on Unix), so we can // allocate the buffer now and not worry about running out of space if // we over-allocate a bit: size_t fmtLen = wxStrlen(m_fmtOrig); // worst case is of even length, so there's no rounding error in *3/2: m_fmt.extend(fmtLen * 3 / 2); if ( m_nCopied > 0 ) wxStrncpy(m_fmt.data(), m_fmtOrig, m_nCopied); m_fmtLast = m_fmt.data() + m_nCopied; // we won't need it any longer and resetting it also indicates that we // modified the format m_fmtOrig = NULL; }
// Get user ID e.g. jacs bool wxGetUserId(wxChar *WXUNUSED_IN_WINCE(buf), int WXUNUSED_IN_WINCE(maxSize)) { #if defined(__WXWINCE__) // TODO-CE return false; #elif defined(__WIN32__) && !defined(__WXMICROWIN__) DWORD nSize = maxSize; if ( ::GetUserName(buf, &nSize) == 0 ) { // actually, it does happen on Win9x if the user didn't log on DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize); if ( res == 0 ) { // not found return false; } } return true; #else // __WXMICROWIN__ wxChar *user; const wxChar *default_id = wxT("anonymous"); // Can't assume we have NIS (PC-NFS) or some other ID daemon // So we ... if ( (user = wxGetenv(wxT("USER"))) == NULL && (user = wxGetenv(wxT("LOGNAME"))) == NULL ) { // Use wxWidgets configuration data (comming soon) GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1); } else { wxStrncpy(buf, user, maxSize - 1); } return *buf ? true : false; #endif }
// Get user name e.g. Julian Smart bool wxGetUserName(wxChar *buf, int maxSize) { wxCHECK_MSG( buf && ( maxSize > 0 ), false, _T("empty buffer in wxGetUserName") ); #if defined(__WXWINCE__) wxLogNull noLog; wxRegKey key(wxRegKey::HKCU, wxT("ControlPanel\\Owner")); if(!key.Open(wxRegKey::Read)) return false; wxString name; if(!key.QueryValue(wxT("Owner"),name)) return false; wxStrncpy(buf, name.c_str(), maxSize-1); buf[maxSize-1] = _T('\0'); return true; #elif defined(USE_NET_API) CHAR szUserName[256]; if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) ) return false; // TODO how to get the domain name? CHAR *szDomain = ""; // the code is based on the MSDN example (also see KB article Q119670) WCHAR wszUserName[256]; // Unicode user name WCHAR wszDomain[256]; LPBYTE ComputerName; USER_INFO_2 *ui2; // User structure // Convert ANSI user name and domain to Unicode MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1, wszUserName, WXSIZEOF(wszUserName) ); MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1, wszDomain, WXSIZEOF(wszDomain) ); // Get the computer name of a DC for the domain. if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success ) { wxLogError(wxT("Can not find domain controller")); goto error; } // Look up the user on the DC NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName, (LPWSTR)&wszUserName, 2, // level - we want USER_INFO_2 (LPBYTE *) &ui2 ); switch ( status ) { case NERR_Success: // ok break; case NERR_InvalidComputer: wxLogError(wxT("Invalid domain controller name.")); goto error; case NERR_UserNotFound: wxLogError(wxT("Invalid user name '%s'."), szUserName); goto error; default: wxLogSysError(wxT("Can't get information about user")); goto error; } // Convert the Unicode full name to ANSI WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1, buf, maxSize, NULL, NULL ); return true; error: wxLogError(wxT("Couldn't look up full user name.")); return false; #else // !USE_NET_API // Could use NIS, MS-Mail or other site specific programs // Use wxWidgets configuration data bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0; if ( !ok ) { ok = wxGetUserId(buf, maxSize); } if ( !ok ) { wxStrncpy(buf, wxT("Unknown User"), maxSize); } return true; #endif // Win32/16 }
// get full hostname (with domain name if possible) bool wxGetFullHostName(wxChar *buf, int maxSize) { #if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER && wxUSE_SOCKETS // TODO should use GetComputerNameEx() when available // we don't want to always link with Winsock DLL as we might not use it at // all, so load it dynamically here if needed (and don't complain if it is // missing, we handle this) wxLogNull noLog; wxDynamicLibrary dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM); if ( dllWinsock.IsLoaded() ) { typedef int (PASCAL *WSAStartup_t)(WORD, WSADATA *); typedef int (PASCAL *gethostname_t)(char *, int); typedef hostent* (PASCAL *gethostbyname_t)(const char *); typedef hostent* (PASCAL *gethostbyaddr_t)(const char *, int , int); typedef int (PASCAL *WSACleanup_t)(void); #define LOAD_WINSOCK_FUNC(func) \ func ## _t \ pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func)) LOAD_WINSOCK_FUNC(WSAStartup); WSADATA wsa; if ( pfnWSAStartup && pfnWSAStartup(MAKEWORD(1, 1), &wsa) == 0 ) { LOAD_WINSOCK_FUNC(gethostname); wxString host; if ( pfngethostname ) { char bufA[256]; if ( pfngethostname(bufA, WXSIZEOF(bufA)) == 0 ) { // gethostname() won't usually include the DNS domain name, // for this we need to work a bit more if ( !strchr(bufA, '.') ) { LOAD_WINSOCK_FUNC(gethostbyname); struct hostent *pHostEnt = pfngethostbyname ? pfngethostbyname(bufA) : NULL; if ( pHostEnt ) { // Windows will use DNS internally now LOAD_WINSOCK_FUNC(gethostbyaddr); pHostEnt = pfngethostbyaddr ? pfngethostbyaddr(pHostEnt->h_addr, 4, AF_INET) : NULL; } if ( pHostEnt ) { host = wxString::FromAscii(pHostEnt->h_name); } } } } LOAD_WINSOCK_FUNC(WSACleanup); if ( pfnWSACleanup ) pfnWSACleanup(); if ( !host.empty() ) { wxStrncpy(buf, host, maxSize); return true; } } } #endif // !__WXMICROWIN__ return wxGetHostName(buf, maxSize); }
// get error message from system const wxChar *wxSysErrorMsg(unsigned long nErrCode) { if ( nErrCode == 0 ) nErrCode = wxSysErrorCode(); #if defined(__WXMSW__) && !defined(__WXMICROWIN__) static wxChar s_szBuf[1024]; // get error message from system LPVOID lpMsgBuf; if ( ::FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, nErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL ) == 0 ) { // if this happens, something is seriously wrong, so don't use _() here // for safety wxSprintf(s_szBuf, _T("unknown error %lx"), nErrCode); return s_szBuf; } // copy it to our buffer and free memory // Crashes on SmartPhone (FIXME) #if !defined(__SMARTPHONE__) /* of WinCE */ if( lpMsgBuf != 0 ) { wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1); s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0'); LocalFree(lpMsgBuf); // returned string is capitalized and ended with '\r\n' - bad s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]); size_t len = wxStrlen(s_szBuf); if ( len > 0 ) { // truncate string if ( s_szBuf[len - 2] == wxT('\r') ) s_szBuf[len - 2] = wxT('\0'); } } else #endif // !__SMARTPHONE__ { s_szBuf[0] = wxT('\0'); } return s_szBuf; #else // !__WXMSW__ #if wxUSE_UNICODE static wchar_t s_wzBuf[1024]; wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode), WXSIZEOF(s_wzBuf) - 1); return s_wzBuf; #else return strerror((int)nErrCode); #endif #endif // __WXMSW__/!__WXMSW__ }
int CProxyParse::RunFromMem( wxString content ) { char *pBuffer; //http://www.51proxied.com/http_non_anonymous.html //wxString path = wxT("f:/work/windows/wxUrlRefresh/data/最新透明HTTP代理服务器.htm"); //wxString path1 = wxT("f:/work/windows/wxUrlRefresh/data/result.xml"); wxString data_path = wxGetCwd() + "/data/"; wxString path1 = data_path + "_tmp.xml"; if (!wxDirExists(data_path)) wxMkdir(data_path); pBuffer = (char*)calloc(content.Length()+1, 1); wxStrncpy(pBuffer, content, content.Len()+1); wxLogMessage("Run Tidy!"); TidyBuffer output; TidyBuffer errbuf; int rc = -1; Bool ok; TidyDoc tdoc = tidyCreate(); // Initialize "document" tidyBufInit( &output ); tidyBufInit( &errbuf ); //printf( "Tidying:\t\%s\\n", input ); tidySetCharEncoding(tdoc, "utf8"); ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes ); // Convert to XHTML if ( ok ) rc = tidySetErrorBuffer( tdoc, &errbuf ); // Capture diagnostics if ( rc >= 0 ) rc = tidyParseString( tdoc, pBuffer ); // Parse the input if ( rc >= 0 ) rc = tidyCleanAndRepair( tdoc ); // Tidy it up! if ( rc >= 0 ) rc = tidyRunDiagnostics( tdoc ); // Kvetch if ( rc > 1 ) // If error, force output. rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 ); if ( rc >= 0 ) rc = tidySaveBuffer( tdoc, &output ); // Pretty Print if ( rc >= 0 ) { #ifdef _DEBUG //if ( rc > 0 ) // WriteAllToFile("f:/work/windows/wxUrlRefresh/data/error.xml", (char*)errbuf.bp, errbuf.size); WriteAllToFile(path1, (char*)output.bp, output.size); #endif } else wxLogError("tidyFail"); tidyBufFree( &output ); tidyBufFree( &errbuf ); tidyRelease( tdoc ); if (pBuffer) free(pBuffer); wxLogMessage("Fetch data!"); // 解析数据 TiXmlDocument doc(path1); if (doc.LoadFile()) { // root CTiXmlProxyVistor vistor(&m_array); TiXmlElement *pRoot = doc.RootElement(); pRoot->Accept(&vistor); } else { wxLogMessage("shit"); return -2; } return 0; }
int FileDialog::ShowModal() { HWND hWnd = 0; if (m_parent) hWnd = (HWND) m_parent->GetHWND(); if (!hWnd && wxTheApp->GetTopWindow()) hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND(); static wxChar fileNameBuffer [ wxMAXPATH ]; // the file-name wxChar titleBuffer [ wxMAXFILE+1+wxMAXEXT ]; // the file-name, without path *fileNameBuffer = wxT('\0'); *titleBuffer = wxT('\0'); #if WXWIN_COMPATIBILITY_2_4 long msw_flags = 0; if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) ) msw_flags |= OFN_HIDEREADONLY; #else long msw_flags = OFN_HIDEREADONLY; #endif if ( m_dialogStyle & wxFILE_MUST_EXIST ) msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; /* If the window has been moved the programmer is probably trying to center or position it. Thus we set the callback or hook function so that we can actually adjust the position. Without moving or centering the dlg, it will just stay in the upper left of the frame, it does not center automatically.. One additional note, when the hook is enabled, the PLACES BAR in the dlg (shown on later versions of windows (2000 and XP) will automatically be turned off according to the MSDN docs. This is normal. If the programmer needs the PLACES BAR (left side of dlg) they just shouldn't move or center the dlg. */ if (m_bMovedWindow) // we need these flags. { msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK; #ifndef __WXWINCE__ msw_flags |= OFN_ENABLESIZING; #endif } if (m_dialogStyle & wxMULTIPLE ) { // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT; } // if wxCHANGE_DIR flag is not given we shouldn't change the CWD which the // standard dialog does by default (notice that under NT it does it anyhow, // OFN_NOCHANGEDIR or not, see below) if ( !(m_dialogStyle & wxCHANGE_DIR) ) { msw_flags |= OFN_NOCHANGEDIR; } if ( m_dialogStyle & wxOVERWRITE_PROMPT ) { msw_flags |= OFN_OVERWRITEPROMPT; } if ( m_dialogStyle & wxRESIZE_BORDER ) { msw_flags |= OFN_ENABLESIZING; } if ( m_callback != NULL ) { msw_flags |= OFN_SHOWHELP | OFN_EXPLORER | OFN_ENABLEHOOK; } // We always need EXPLORER and ENABLEHOOK to use our filtering code msw_flags |= OFN_EXPLORER | OFN_ENABLEHOOK; OPENFILENAME of; wxZeroMemory(of); // Allow Places bar to show on supported platforms if ( wxGetOsVersion() == wxWINDOWS_NT ) { of.lStructSize = sizeof(OPENFILENAME); } else { of.lStructSize = OPENFILENAME_SIZE_VERSION_400; } of.hwndOwner = hWnd; of.lpstrTitle = WXSTRINGCAST m_message; of.lpstrFileTitle = titleBuffer; of.nMaxFileTitle = wxMAXFILE + 1 + wxMAXEXT; // Windows 3.0 and 3.1 of.lCustData = (LPARAM) this; // Convert forward slashes to backslashes (file selector doesn't like // forward slashes) and also squeeze multiple consecutive slashes into one // as it doesn't like two backslashes in a row neither wxString dir; size_t i, len = m_dir.length(); dir.reserve(len); for ( i = 0; i < len; i++ ) { wxChar ch = m_dir[i]; switch ( ch ) { case _T('/'): // convert to backslash ch = _T('\\'); // fall through case _T('\\'): while ( i < len - 1 ) { wxChar chNext = m_dir[i + 1]; if ( chNext != _T('\\') && chNext != _T('/') ) break; // ignore the next one, unless it is at the start of a UNC path if (i > 0) i++; else break; } // fall through default: // normal char dir += ch; } } of.lpstrInitialDir = dir.c_str(); of.Flags = msw_flags; of.lpfnHook = FileDialogHookFunction; wxArrayString wildDescriptions; size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, m_FilterGroups); wxASSERT_MSG( items > 0 , _T("empty wildcard list") ); wxString filterBuffer; for (i = 0; i < items ; i++) { filterBuffer += wildDescriptions[i]; filterBuffer += wxT("|"); filterBuffer += wxT("*.*"); filterBuffer += wxT("|"); } // Replace | with \0 for (i = 0; i < filterBuffer.Len(); i++ ) { if ( filterBuffer.GetChar(i) == wxT('|') ) { filterBuffer[i] = wxT('\0'); } } of.lpstrFilter = (LPTSTR)filterBuffer.c_str(); of.nFilterIndex = m_filterIndex + 1; ParseFilter(of.nFilterIndex); //=== Setting defaultFileName >>========================================= wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 ); fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0'); of.lpstrFile = fileNameBuffer; // holds returned filename of.nMaxFile = wxMAXPATH; // we must set the default extension because otherwise Windows would check // for the existing of a wrong file with wxOVERWRITE_PROMPT (i.e. if the // user types "foo" and the default extension is ".bar" we should force it // to check for "foo.bar" existence and not "foo") wxString defextBuffer; // we need it to be alive until GetSaveFileName()! if (m_dialogStyle & wxSAVE && m_dialogStyle & wxOVERWRITE_PROMPT) { const wxChar* extension = filterBuffer; int maxFilter = (int)(of.nFilterIndex*2L) - 1; for( int i = 0; i < maxFilter; i++ ) // get extension extension = extension + wxStrlen( extension ) + 1; // use dummy name a to avoid assert in AppendExtension defextBuffer = AppendExtension(wxT("a"), extension); if (defextBuffer.StartsWith(wxT("a."))) { defextBuffer.Mid(2); of.lpstrDefExt = defextBuffer.c_str(); } } // store off before the standard windows dialog can possibly change it const wxString cwdOrig = wxGetCwd(); //== Execute FileDialog >>================================================= bool success = (m_dialogStyle & wxSAVE ? GetSaveFileName(&of) : GetOpenFileName(&of)) != 0; #ifdef __WXWINCE__ DWORD errCode = GetLastError(); #else DWORD errCode = CommDlgExtendedError(); // GetOpenFileName will always change the current working directory on // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag // OFN_NOCHANGEDIR has no effect. If the user did not specify wxCHANGE_DIR // let's restore the current working directory to what it was before the // dialog was shown (assuming this behavior extends to Windows Server 2003 // seems safe). if ( success && (msw_flags & OFN_NOCHANGEDIR) && wxGetOsVersion() == wxWINDOWS_NT ) { wxSetWorkingDirectory(cwdOrig); } #ifdef __WIN32__ if (!success && (errCode == CDERR_STRUCTSIZE)) { // The struct size has changed so try a smaller or bigger size int oldStructSize = of.lStructSize; of.lStructSize = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD)); success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0) : (GetOpenFileName(&of) != 0); errCode = CommDlgExtendedError(); if (!success && (errCode == CDERR_STRUCTSIZE)) { of.lStructSize = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD)); success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0) : (GetOpenFileName(&of) != 0); } } #endif // __WIN32__ #endif // __WXWINCE__ if ( success ) { m_fileNames.Empty(); if ( ( m_dialogStyle & wxMULTIPLE ) && #if defined(OFN_EXPLORER) ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') ) #else ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') ) #endif // OFN_EXPLORER ) { #if defined(OFN_EXPLORER) m_dir = fileNameBuffer; i = of.nFileOffset; m_fileName = &fileNameBuffer[i]; m_fileNames.Add(m_fileName); i += m_fileName.Len() + 1; while (fileNameBuffer[i] != wxT('\0')) { m_fileNames.Add(&fileNameBuffer[i]); i += wxStrlen(&fileNameBuffer[i]) + 1; } #else wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n")); m_dir = toke.GetNextToken(); m_fileName = toke.GetNextToken(); m_fileNames.Add(m_fileName); while (toke.HasMoreTokens()) m_fileNames.Add(toke.GetNextToken()); #endif // OFN_EXPLORER wxString dir(m_dir); if ( m_dir.Last() != _T('\\') ) dir += _T('\\'); m_path = dir + m_fileName; m_filterIndex = (int)of.nFilterIndex - 1; } else { //=== Adding the correct extension >>================================= m_filterIndex = (int)of.nFilterIndex - 1; #if 0 // LLL: Removed to prevent adding extension during Export // processing. if ( !of.nFileExtension || (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) ) { // User has typed a filename without an extension: const wxChar* extension = filterBuffer; int maxFilter = (int)(of.nFilterIndex*2L) - 1; for( int i = 0; i < maxFilter; i++ ) // get extension extension = extension + wxStrlen( extension ) + 1; m_fileName = AppendExtension(fileNameBuffer, extension); wxStrncpy(fileNameBuffer, m_fileName.c_str(), wxMin(m_fileName.Len(), wxMAXPATH-1)); fileNameBuffer[wxMin(m_fileName.Len(), wxMAXPATH-1)] = wxT('\0'); } #endif m_path = fileNameBuffer; m_fileName = wxFileNameFromPath(fileNameBuffer); m_fileNames.Add(m_fileName); m_dir = wxPathOnly(fileNameBuffer); } } else { // common dialog failed - why? #ifdef __WXDEBUG__ #ifdef __WXWINCE__ if (errCode == 0) { // OK, user cancelled the dialog } else if (errCode == ERROR_INVALID_PARAMETER) { wxLogError(wxT("Invalid parameter passed to file dialog function.")); } else if (errCode == ERROR_OUTOFMEMORY) { wxLogError(wxT("Out of memory when calling file dialog function.")); } else if (errCode == ERROR_CALL_NOT_IMPLEMENTED) { wxLogError(wxT("Call not implemented when calling file dialog function.")); } else { wxLogError(wxT("Unknown error %d when calling file dialog function."), errCode); } #else DWORD dwErr = CommDlgExtendedError(); if ( dwErr != 0 ) { // this msg is only for developers wxLogError(wxT("Common dialog failed with error code %0lx."), dwErr); } //else: it was just cancelled #endif #endif } return success ? wxID_OK : wxID_CANCEL; }
void wxOS2SelectMatchingFontByName( PFATTRS pFattrs , PFACENAMEDESC pFaceName , PFONTMETRICS pFM , int nNumFonts , const wxFont* pFont ) { int i; int nPointSize; int nIs; int nMinDiff0; int anDiff[16]; int anMinDiff[16]; int nIndex = 0; wxChar zFontFaceName[FACESIZE]; wxString sFaceName; USHORT usWeightClass; int fsSelection = 0; nMinDiff0 = 0xf000; for(i = 0;i < 16; i++) anMinDiff[i] = nMinDiff0; switch (pFont->GetFamily()) { case wxSCRIPT: sFaceName = wxT("Tms Rmn"); break; case wxDECORATIVE: sFaceName = wxT("WarpSans"); break; case wxROMAN: sFaceName = wxT("Tms Rmn"); break; case wxTELETYPE: sFaceName = wxT("Courier") ; break; case wxMODERN: sFaceName = wxT("System VIO") ; break; case wxSWISS: sFaceName = wxT("Helv") ; break; case wxDEFAULT: default: sFaceName = wxT("System VIO") ; } switch (pFont->GetWeight()) { default: wxFAIL_MSG(_T("unknown font weight")); // fall through usWeightClass = FWEIGHT_DONT_CARE; break; case wxNORMAL: usWeightClass = FWEIGHT_NORMAL; break; case wxLIGHT: usWeightClass = FWEIGHT_LIGHT; break; case wxBOLD: usWeightClass = FWEIGHT_BOLD; break; case wxFONTWEIGHT_MAX: usWeightClass = FWEIGHT_ULTRA_BOLD; break; } pFaceName->usWeightClass = usWeightClass; switch (pFont->GetStyle()) { case wxITALIC: case wxSLANT: fsSelection = FM_SEL_ITALIC; pFaceName->flOptions = FTYPE_ITALIC; break; default: wxFAIL_MSG(wxT("unknown font slant")); // fall through case wxNORMAL: fsSelection = 0; break; } wxStrncpy(zFontFaceName, sFaceName.c_str(), WXSIZEOF(zFontFaceName)); nPointSize = pFont->GetPointSize(); // // Matching logic to find the right FM struct // nIndex = 0; for(i = 0, nIs = 0; i < nNumFonts; i++) { int nEmHeight = 0; int nXHeight = 0; anDiff[0] = wxGpiStrcmp((wxChar*)pFM[i].szFacename, zFontFaceName); anDiff[1] = abs(pFM[i].lEmHeight - nPointSize); anDiff[2] = abs(pFM[i].usWeightClass - usWeightClass); anDiff[3] = abs((pFM[i].fsSelection & 0x2f) - fsSelection); if(anDiff[0] == 0) { nEmHeight = (int)pFM[i].lEmHeight; nXHeight =(int)pFM[i].lXHeight; if( (nIs & 0x01) == 0) { nIs = 1; nIndex = i; anMinDiff[1] = anDiff[1]; anMinDiff[2] = anDiff[2]; anMinDiff[3] = anDiff[3]; } else if(anDiff[3] < anMinDiff[3]) { nIndex = i; anMinDiff[3] = anDiff[3]; } else if(anDiff[2] < anMinDiff[2]) { nIndex = i; anMinDiff[2] = anDiff[2]; } else if(anDiff[1] < anMinDiff[1]) { nIndex = i; anMinDiff[1] = anDiff[1]; } anMinDiff[0] = 0; } else if(anDiff[0] < anMinDiff[0]) { nIs = 2; nIndex = i; anMinDiff[3] = anDiff[3]; anMinDiff[2] = anDiff[2]; anMinDiff[1] = anDiff[1]; anMinDiff[0] = anDiff[0]; } else if(anDiff[0] == anMinDiff[0]) { if(anDiff[3] < anMinDiff[3]) { nIndex = i; anMinDiff[3] = anDiff[3]; nIs = 2; } else if(anDiff[2] < anMinDiff[2]) { nIndex = i; anMinDiff[2] = anDiff[2]; nIs = 2; } else if(anDiff[1] < anMinDiff[1]) { nIndex = i; anMinDiff[1] = anDiff[1]; nIs = 2; } } } // // Fill in the FATTRS with the best match from FONTMETRICS // pFattrs->usRecordLength = sizeof(FATTRS); // Sets size of structure pFattrs->lMatch = pFM[nIndex].lMatch; // Force match pFattrs->idRegistry = 0; pFattrs->usCodePage = 0; pFattrs->fsFontUse = 0; pFattrs->fsType = 0; pFattrs->lMaxBaselineExt = 0; pFattrs->lAveCharWidth = 0; wxStrcpy((wxChar*)pFattrs->szFacename, (wxChar*)pFM[nIndex].szFacename); if (pFont->GetWeight() == wxNORMAL) pFattrs->fsSelection = 0; else pFattrs->fsSelection = FATTR_SEL_BOLD; if (pFont->GetStyle() == wxITALIC || pFont->GetStyle() == wxSLANT) pFattrs->fsSelection |= FATTR_SEL_ITALIC; if (pFont->GetUnderlined()) pFattrs->fsSelection |= FATTR_SEL_UNDERSCORE; } // end of wxOS2SelectMatchingFontByName
/* static */ void wxCrashReport::SetFileName(const wxChar *filename) { wxStrncpy(gs_reportFilename, filename, WXSIZEOF(gs_reportFilename) - 1); gs_reportFilename[WXSIZEOF(gs_reportFilename) - 1] = _T('\0'); }
bool wxWindowsPrintNativeData::TransferFrom( const wxPrintData &data ) { HGLOBAL hDevMode = (HGLOBAL)(DWORD) m_devMode; HGLOBAL hDevNames = (HGLOBAL)(DWORD) m_devNames; if (!hDevMode) { // Use PRINTDLG as a way of creating a DEVMODE object PRINTDLG pd; // GNU-WIN32 has the wrong size PRINTDLG - can't work out why. #ifdef __GNUWIN32__ memset(&pd, 0, 66); pd.lStructSize = 66; #else memset(&pd, 0, sizeof(PRINTDLG)); #ifdef __WXWINCE__ pd.cbStruct = sizeof(PRINTDLG); #else pd.lStructSize = sizeof(PRINTDLG); #endif #endif pd.hwndOwner = (HWND)NULL; pd.hDevMode = NULL; // Will be created by PrintDlg pd.hDevNames = NULL; // Ditto //pd.hInstance = (HINSTANCE) wxGetInstance(); pd.Flags = PD_RETURNDEFAULT; pd.nCopies = 1; // Fill out the DEVMODE structure // so we can use it as input in the 'real' PrintDlg if (!PrintDlg(&pd)) { if ( pd.hDevMode ) GlobalFree(pd.hDevMode); if ( pd.hDevNames ) GlobalFree(pd.hDevNames); pd.hDevMode = NULL; pd.hDevNames = NULL; #if defined(__WXDEBUG__) && defined(__WIN32__) wxString str(wxT("Printing error: ")); str += wxGetPrintDlgError(); wxLogDebug(str); #endif } else { hDevMode = pd.hDevMode; m_devMode = (void*)(long) hDevMode; pd.hDevMode = NULL; // We'll create a new DEVNAMEs structure below. if ( pd.hDevNames ) GlobalFree(pd.hDevNames); pd.hDevNames = NULL; // hDevNames = pd->hDevNames; // m_devNames = (void*)(long) hDevNames; // pd->hDevnames = NULL; } } if ( hDevMode ) { LPDEVMODE devMode = (LPDEVMODE) GlobalLock(hDevMode); //// Orientation devMode->dmOrientation = (short)data.GetOrientation(); //// Collation devMode->dmCollate = (data.GetCollate() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE); devMode->dmFields |= DM_COLLATE; //// Number of copies devMode->dmCopies = (short)data.GetNoCopies(); devMode->dmFields |= DM_COPIES; //// Printer name wxString name = data.GetPrinterName(); if (!name.empty()) { //int len = wxMin(31, m_printerName.Len()); wxStrncpy((wxChar*)devMode->dmDeviceName,name.c_str(),31); devMode->dmDeviceName[31] = wxT('\0'); } //// Colour if (data.GetColour()) devMode->dmColor = DMCOLOR_COLOR; else devMode->dmColor = DMCOLOR_MONOCHROME; devMode->dmFields |= DM_COLOR; //// Paper size if (data.GetPaperId() == wxPAPER_NONE) { // DEVMODE is in tenths of a milimeter devMode->dmPaperWidth = (short)(data.GetPaperSize().x * 10); devMode->dmPaperLength = (short)(data.GetPaperSize().y * 10); if(m_customWindowsPaperId != 0) devMode->dmPaperSize = m_customWindowsPaperId; else devMode->dmPaperSize = DMPAPER_USER; devMode->dmFields |= DM_PAPERWIDTH; devMode->dmFields |= DM_PAPERLENGTH; } else { if (wxThePrintPaperDatabase) { wxPrintPaperType* paper = wxThePrintPaperDatabase->FindPaperType( data.GetPaperId() ); if (paper) { devMode->dmPaperSize = (short)paper->GetPlatformId(); devMode->dmFields |= DM_PAPERSIZE; } else { // Fall back on specifying the paper size explicitly devMode->dmPaperWidth = (short)(data.GetPaperSize().x * 10); devMode->dmPaperLength = (short)(data.GetPaperSize().y * 10); devMode->dmPaperSize = DMPAPER_USER; devMode->dmFields |= DM_PAPERWIDTH; devMode->dmFields |= DM_PAPERLENGTH; } } } //// Duplex short duplex; switch (data.GetDuplex()) { case wxDUPLEX_HORIZONTAL: duplex = DMDUP_HORIZONTAL; break; case wxDUPLEX_VERTICAL: duplex = DMDUP_VERTICAL; break; default: // in fact case wxDUPLEX_SIMPLEX: duplex = DMDUP_SIMPLEX; break; } devMode->dmDuplex = duplex; devMode->dmFields |= DM_DUPLEX; //// Quality short quality; switch (data.GetQuality()) { case wxPRINT_QUALITY_MEDIUM: quality = DMRES_MEDIUM; break; case wxPRINT_QUALITY_LOW: quality = DMRES_LOW; break; case wxPRINT_QUALITY_DRAFT: quality = DMRES_DRAFT; break; case wxPRINT_QUALITY_HIGH: quality = DMRES_HIGH; break; default: quality = (short)data.GetQuality(); break; } devMode->dmPrintQuality = quality; devMode->dmFields |= DM_PRINTQUALITY; if (data.GetPrivDataLen() > 0) { memcpy( (char *)devMode+devMode->dmSize, data.GetPrivData(), data.GetPrivDataLen() ); devMode->dmDriverExtra = (WXWORD)data.GetPrivDataLen(); } if (data.GetBin() != wxPRINTBIN_DEFAULT) { switch (data.GetBin()) { case wxPRINTBIN_ONLYONE: devMode->dmDefaultSource = DMBIN_ONLYONE; break; case wxPRINTBIN_LOWER: devMode->dmDefaultSource = DMBIN_LOWER; break; case wxPRINTBIN_MIDDLE: devMode->dmDefaultSource = DMBIN_MIDDLE; break; case wxPRINTBIN_MANUAL: devMode->dmDefaultSource = DMBIN_MANUAL; break; case wxPRINTBIN_ENVELOPE: devMode->dmDefaultSource = DMBIN_ENVELOPE; break; case wxPRINTBIN_ENVMANUAL: devMode->dmDefaultSource = DMBIN_ENVMANUAL; break; case wxPRINTBIN_AUTO: devMode->dmDefaultSource = DMBIN_AUTO; break; case wxPRINTBIN_TRACTOR: devMode->dmDefaultSource = DMBIN_TRACTOR; break; case wxPRINTBIN_SMALLFMT: devMode->dmDefaultSource = DMBIN_SMALLFMT; break; case wxPRINTBIN_LARGEFMT: devMode->dmDefaultSource = DMBIN_LARGEFMT; break; case wxPRINTBIN_LARGECAPACITY: devMode->dmDefaultSource = DMBIN_LARGECAPACITY; break; case wxPRINTBIN_CASSETTE: devMode->dmDefaultSource = DMBIN_CASSETTE; break; case wxPRINTBIN_FORMSOURCE: devMode->dmDefaultSource = DMBIN_FORMSOURCE; break; default: devMode->dmDefaultSource = (short)(DMBIN_USER + data.GetBin() - wxPRINTBIN_USER); break; } devMode->dmFields |= DM_DEFAULTSOURCE; } GlobalUnlock(hDevMode); } if ( hDevNames ) { GlobalFree(hDevNames); } // TODO: I hope it's OK to pass some empty strings to DEVNAMES. m_devNames = (void*) (long) wxCreateDevNames(wxEmptyString, data.GetPrinterName(), wxEmptyString); return true; }
int wxFileDialog::ShowModal() { HWND hWnd = 0; if (m_parent) hWnd = (HWND) m_parent->GetHWND(); if (!hWnd && wxTheApp->GetTopWindow()) hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND(); static wxChar fileNameBuffer [ wxMAXPATH ]; // the file-name wxChar titleBuffer [ wxMAXFILE+1+wxMAXEXT ]; // the file-name, without path *fileNameBuffer = wxT('\0'); *titleBuffer = wxT('\0'); #if WXWIN_COMPATIBILITY_2_4 long msw_flags = 0; if ( HasFdFlag(wxHIDE_READONLY) || HasFdFlag(wxFD_SAVE) ) msw_flags |= OFN_HIDEREADONLY; #else long msw_flags = OFN_HIDEREADONLY; #endif if ( HasFdFlag(wxFD_FILE_MUST_EXIST) ) msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; /* If the window has been moved the programmer is probably trying to center or position it. Thus we set the callback or hook function so that we can actually adjust the position. Without moving or centering the dlg, it will just stay in the upper left of the frame, it does not center automatically. */ if (m_bMovedWindow) // we need these flags. { msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK; #ifndef __WXWINCE__ msw_flags |= OFN_ENABLESIZING; #endif } if ( HasFdFlag(wxFD_MULTIPLE) ) { // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT; } // if wxFD_CHANGE_DIR flag is not given we shouldn't change the CWD which the // standard dialog does by default (notice that under NT it does it anyhow, // OFN_NOCHANGEDIR or not, see below) if ( !HasFdFlag(wxFD_CHANGE_DIR) ) { msw_flags |= OFN_NOCHANGEDIR; } if ( HasFdFlag(wxFD_OVERWRITE_PROMPT) ) { msw_flags |= OFN_OVERWRITEPROMPT; } wxOPENFILENAME of; wxZeroMemory(of); of.lStructSize = gs_ofStructSize; of.hwndOwner = hWnd; of.lpstrTitle = WXSTRINGCAST m_message; of.lpstrFileTitle = titleBuffer; of.nMaxFileTitle = wxMAXFILE + 1 + wxMAXEXT; // Convert forward slashes to backslashes (file selector doesn't like // forward slashes) and also squeeze multiple consecutive slashes into one // as it doesn't like two backslashes in a row neither wxString dir; size_t i, len = m_dir.length(); dir.reserve(len); for ( i = 0; i < len; i++ ) { wxChar ch = m_dir[i]; switch ( ch ) { case _T('/'): // convert to backslash ch = _T('\\'); // fall through case _T('\\'): while ( i < len - 1 ) { wxChar chNext = m_dir[i + 1]; if ( chNext != _T('\\') && chNext != _T('/') ) break; // ignore the next one, unless it is at the start of a UNC path if (i > 0) i++; else break; } // fall through default: // normal char dir += ch; } } of.lpstrInitialDir = dir.c_str(); of.Flags = msw_flags; of.lpfnHook = wxFileDialogHookFunction; wxArrayString wildDescriptions, wildFilters; size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, wildFilters); wxASSERT_MSG( items > 0 , _T("empty wildcard list") ); wxString filterBuffer; for (i = 0; i < items ; i++) { filterBuffer += wildDescriptions[i]; filterBuffer += wxT("|"); filterBuffer += wildFilters[i]; filterBuffer += wxT("|"); } // Replace | with \0 for (i = 0; i < filterBuffer.length(); i++ ) { if ( filterBuffer.GetChar(i) == wxT('|') ) { filterBuffer[i] = wxT('\0'); } } of.lpstrFilter = (LPTSTR)filterBuffer.c_str(); of.nFilterIndex = m_filterIndex + 1; //=== Setting defaultFileName >>========================================= wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 ); fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0'); of.lpstrFile = fileNameBuffer; // holds returned filename of.nMaxFile = wxMAXPATH; // we must set the default extension because otherwise Windows would check // for the existing of a wrong file with wxFD_OVERWRITE_PROMPT (i.e. if the // user types "foo" and the default extension is ".bar" we should force it // to check for "foo.bar" existence and not "foo") wxString defextBuffer; // we need it to be alive until GetSaveFileName()! if (HasFdFlag(wxFD_SAVE)) { const wxChar* extension = filterBuffer; int maxFilter = (int)(of.nFilterIndex*2L) - 1; for( int i = 0; i < maxFilter; i++ ) // get extension extension = extension + wxStrlen( extension ) + 1; // use dummy name a to avoid assert in AppendExtension defextBuffer = AppendExtension(wxT("a"), extension); if (defextBuffer.StartsWith(wxT("a."))) { defextBuffer = defextBuffer.Mid(2); // remove "a." of.lpstrDefExt = defextBuffer.c_str(); } } // store off before the standard windows dialog can possibly change it const wxString cwdOrig = wxGetCwd(); //== Execute FileDialog >>================================================= DWORD errCode; bool success = DoShowCommFileDialog(&of, m_windowStyle, &errCode); #ifdef wxTRY_SMALLER_OPENFILENAME // the system might be too old to support the new version file dialog // boxes, try with the old size if ( !success && errCode == CDERR_STRUCTSIZE && of.lStructSize != wxOPENFILENAME_V4_SIZE ) { of.lStructSize = wxOPENFILENAME_V4_SIZE; success = DoShowCommFileDialog(&of, m_windowStyle, &errCode); if ( success || !errCode ) { // use this struct size for subsequent dialogs gs_ofStructSize = of.lStructSize; } } #endif // wxTRY_SMALLER_OPENFILENAME if ( success ) { // GetOpenFileName will always change the current working directory on // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag // OFN_NOCHANGEDIR has no effect. If the user did not specify // wxFD_CHANGE_DIR let's restore the current working directory to what it // was before the dialog was shown. if ( msw_flags & OFN_NOCHANGEDIR ) { wxSetWorkingDirectory(cwdOrig); } m_fileNames.Empty(); if ( ( HasFdFlag(wxFD_MULTIPLE) ) && #if defined(OFN_EXPLORER) ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') ) #else ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') ) #endif // OFN_EXPLORER ) { #if defined(OFN_EXPLORER) m_dir = fileNameBuffer; i = of.nFileOffset; m_fileName = &fileNameBuffer[i]; m_fileNames.Add(m_fileName); i += m_fileName.length() + 1; while (fileNameBuffer[i] != wxT('\0')) { m_fileNames.Add(&fileNameBuffer[i]); i += wxStrlen(&fileNameBuffer[i]) + 1; } #else wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n")); m_dir = toke.GetNextToken(); m_fileName = toke.GetNextToken(); m_fileNames.Add(m_fileName); while (toke.HasMoreTokens()) m_fileNames.Add(toke.GetNextToken()); #endif // OFN_EXPLORER wxString dir(m_dir); if ( m_dir.Last() != _T('\\') ) dir += _T('\\'); m_path = dir + m_fileName; m_filterIndex = (int)of.nFilterIndex - 1; } else { //=== Adding the correct extension >>================================= m_filterIndex = (int)of.nFilterIndex - 1; if ( !of.nFileExtension || (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) ) { // User has typed a filename without an extension: const wxChar* extension = filterBuffer; int maxFilter = (int)(of.nFilterIndex*2L) - 1; for( int i = 0; i < maxFilter; i++ ) // get extension extension = extension + wxStrlen( extension ) + 1; m_fileName = AppendExtension(fileNameBuffer, extension); wxStrncpy(fileNameBuffer, m_fileName.c_str(), wxMin(m_fileName.length(), wxMAXPATH-1)); fileNameBuffer[wxMin(m_fileName.length(), wxMAXPATH-1)] = wxT('\0'); } m_path = fileNameBuffer; m_fileName = wxFileNameFromPath(fileNameBuffer); m_fileNames.Add(m_fileName); m_dir = wxPathOnly(fileNameBuffer); } } #ifdef __WXDEBUG__ else { // common dialog failed - why? if ( errCode != 0 ) { // this msg is only for developers so don't translate it wxLogError(wxT("Common dialog failed with error code %0lx."), errCode); } //else: it was just cancelled } #endif // __WXDEBUG__ return success ? wxID_OK : wxID_CANCEL; }