1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 // #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
37 #include "wx/cursor.h"
41 // In some mingws there is a missing extern "C" int the winsock header,
42 // so we put it here just to be safe. Note that this must appear _before_
43 // #include "wx/msw/private.h" which itself includes <windows.h>, as this
44 // one in turn includes <winsock.h> unless we define WIN32_LEAN_AND_MEAN.
46 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
48 #include <winsock.h> // we use socket functions in wxGetFullHostName()
52 #include "wx/msw/private.h" // includes <windows.h>
56 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
64 #if defined(__CYGWIN__) && !defined(__TWIN32__)
65 #include <sys/unistd.h>
67 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
70 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
71 // this (3.1 I believe) and how to test for it.
72 // If this works for Borland 4.0 as well, then no worries.
76 // VZ: there is some code using NetXXX() functions to get the full user name:
77 // I don't think it's a good idea because they don't work under Win95 and
78 // seem to return the same as wxGetUserId() under NT. If you really want
79 // to use them, just #define USE_NET_API
86 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
95 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
100 //// BEGIN for console support: VC++ only
103 #include "wx/msw/msvcrt.h"
107 #include "wx/ioswrap.h"
109 /* Need to undef new if including crtdbg.h */
118 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
119 # define new new(__TFILE__,__LINE__)
124 /// END for console support
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 // In the WIN.INI file
131 static const wxChar WX_SECTION
[] = wxT("wxWindows");
132 static const wxChar eUSERNAME
[] = wxT("UserName");
134 // these are only used under Win16
135 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
136 static const wxChar eHOSTNAME
[] = wxT("HostName");
137 static const wxChar eUSERID
[] = wxT("UserId");
140 #ifndef __WXMICROWIN__
142 // ============================================================================
144 // ============================================================================
146 // ----------------------------------------------------------------------------
147 // get host name and related
148 // ----------------------------------------------------------------------------
150 // Get hostname only (without domain name)
151 bool wxGetHostName(wxChar
*buf
, int maxSize
)
153 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
154 DWORD nSize
= maxSize
;
155 if ( !::GetComputerName(buf
, &nSize
) )
157 wxLogLastError(wxT("GetComputerName"));
165 const wxChar
*default_host
= wxT("noname");
167 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
168 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
170 wxStrncpy(buf
, sysname
, maxSize
- 1);
171 buf
[maxSize
] = wxT('\0');
172 return *buf
? TRUE
: FALSE
;
176 // get full hostname (with domain name if possible)
177 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
179 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
180 // TODO should use GetComputerNameEx() when available
182 if ( WSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
186 if ( gethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
188 // gethostname() won't usually include the DNS domain name, for
189 // this we need to work a bit more
190 if ( !strchr(bufA
, '.') )
192 struct hostent
*pHostEnt
= gethostbyname(bufA
);
196 // Windows will use DNS internally now
197 pHostEnt
= gethostbyaddr(pHostEnt
->h_addr
, 4, PF_INET
);
202 host
= pHostEnt
->h_name
;
211 wxStrncpy(buf
, host
, maxSize
);
218 return wxGetHostName(buf
, maxSize
);
221 // Get user ID e.g. jacs
222 bool wxGetUserId(wxChar
*buf
, int maxSize
)
224 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
225 DWORD nSize
= maxSize
;
226 if ( ::GetUserName(buf
, &nSize
) == 0 )
228 // actually, it does happen on Win9x if the user didn't log on
229 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
238 #else // Win16 or Win32s
240 const wxChar
*default_id
= wxT("anonymous");
242 // Can't assume we have NIS (PC-NFS) or some other ID daemon
244 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
245 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
247 // Use wxWindows configuration data (comming soon)
248 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
252 wxStrncpy(buf
, user
, maxSize
- 1);
255 return *buf
? TRUE
: FALSE
;
259 // Get user name e.g. Julian Smart
260 bool wxGetUserName(wxChar
*buf
, int maxSize
)
262 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
263 extern HANDLE g_hPenWin
; // PenWindows Running?
266 // PenWindows Does have a user concept!
267 // Get the current owner of the recognizer
268 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
269 strncpy(buf
, wxBuffer
, maxSize
- 1);
275 CHAR szUserName
[256];
276 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
279 // TODO how to get the domain name?
282 // the code is based on the MSDN example (also see KB article Q119670)
283 WCHAR wszUserName
[256]; // Unicode user name
284 WCHAR wszDomain
[256];
287 USER_INFO_2
*ui2
; // User structure
289 // Convert ANSI user name and domain to Unicode
290 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
291 wszUserName
, WXSIZEOF(wszUserName
) );
292 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
293 wszDomain
, WXSIZEOF(wszDomain
) );
295 // Get the computer name of a DC for the domain.
296 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
298 wxLogError(wxT("Can not find domain controller"));
303 // Look up the user on the DC
304 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
305 (LPWSTR
)&wszUserName
,
306 2, // level - we want USER_INFO_2
314 case NERR_InvalidComputer
:
315 wxLogError(wxT("Invalid domain controller name."));
319 case NERR_UserNotFound
:
320 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
325 wxLogSysError(wxT("Can't get information about user"));
330 // Convert the Unicode full name to ANSI
331 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
332 buf
, maxSize
, NULL
, NULL
);
337 wxLogError(wxT("Couldn't look up full user name."));
340 #else // !USE_NET_API
341 // Could use NIS, MS-Mail or other site specific programs
342 // Use wxWindows configuration data
343 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
346 ok
= wxGetUserId(buf
, maxSize
);
351 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
359 const wxChar
* wxGetHomeDir(wxString
*pstr
)
361 wxString
& strDir
= *pstr
;
363 #if defined(__UNIX__) && !defined(__TWIN32__)
364 const wxChar
*szHome
= wxGetenv("HOME");
365 if ( szHome
== NULL
) {
367 wxLogWarning(_("can't find user's HOME, using current directory."));
373 // add a trailing slash if needed
374 if ( strDir
.Last() != wxT('/') )
378 // Cygwin returns unix type path but that does not work well
379 static wxChar windowsPath
[MAX_PATH
];
380 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
381 strDir
= windowsPath
;
385 const wxChar
*szHome
= wxGetenv(wxT("HOMEDRIVE"));
386 if ( szHome
!= NULL
)
388 szHome
= wxGetenv(wxT("HOMEPATH"));
389 if ( szHome
!= NULL
) {
392 // the idea is that under NT these variables have default values
393 // of "%systemdrive%:" and "\\". As we don't want to create our
394 // config files in the root directory of the system drive, we will
395 // create it in our program's dir. However, if the user took care
396 // to set HOMEPATH to something other than "\\", we suppose that he
397 // knows what he is doing and use the supplied value.
398 if ( wxStrcmp(szHome
, wxT("\\")) != 0 )
399 return strDir
.c_str();
403 // Win16 has no idea about home, so use the working directory instead
406 // 260 was taken from windef.h
412 ::GetModuleFileName(::GetModuleHandle(NULL
),
413 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
414 strPath
.UngetWriteBuf();
416 // extract the dir name
417 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
421 return strDir
.c_str();
424 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
426 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
427 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
428 // static buffer and sometimes I don't even know what.
429 static wxString s_home
;
431 return (wxChar
*)wxGetHomeDir(&s_home
);
434 bool wxDirExists(const wxString
& dir
)
436 #ifdef __WXMICROWIN__
437 return wxPathExist(dir
);
438 #elif defined(__WIN32__)
439 DWORD attribs
= GetFileAttributes(dir
);
440 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
443 struct ffblk fileInfo
;
445 struct find_t fileInfo
;
447 // In Borland findfirst has a different argument
448 // ordering from _dos_findfirst. But _dos_findfirst
449 // _should_ be ok in both MS and Borland... why not?
451 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
452 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
454 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
455 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
460 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
465 // old w32api don't have ULARGE_INTEGER
466 #if defined(__WIN32__) && \
467 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
468 // GetDiskFreeSpaceEx() is not available under original Win95, check for
470 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
476 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
478 ::GetModuleHandle(_T("kernel32.dll")),
480 "GetDiskFreeSpaceExW"
482 "GetDiskFreeSpaceExA"
486 if ( pGetDiskFreeSpaceEx
)
488 ULARGE_INTEGER bytesFree
, bytesTotal
;
490 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
491 if ( !pGetDiskFreeSpaceEx(path
,
496 wxLogLastError(_T("GetDiskFreeSpaceEx"));
501 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
502 // two 32 bit fields which may be or may be not named - try to make it
503 // compile in all cases
504 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
511 *pTotal
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
516 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
522 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
523 // should be used instead - but if it's not available, fall back on
524 // GetDiskFreeSpace() nevertheless...
526 DWORD lSectorsPerCluster
,
528 lNumberOfFreeClusters
,
529 lTotalNumberOfClusters
;
531 // FIXME: this is wrong, we should extract the root drive from path
532 // instead, but this is the job for wxFileName...
533 if ( !::GetDiskFreeSpace(path
,
536 &lNumberOfFreeClusters
,
537 &lTotalNumberOfClusters
) )
539 wxLogLastError(_T("GetDiskFreeSpace"));
544 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
545 lBytesPerCluster
*= lBytesPerSector
;
549 *pTotal
= lBytesPerCluster
;
550 *pTotal
*= lTotalNumberOfClusters
;
555 *pFree
= lBytesPerCluster
;
556 *pFree
*= lNumberOfFreeClusters
;
563 // ----------------------------------------------------------------------------
565 // ----------------------------------------------------------------------------
567 bool wxGetEnv(const wxString
& var
, wxString
*value
)
570 const wxChar
* ret
= wxGetenv(var
);
579 // first get the size of the buffer
580 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
583 // this means that there is no such variable
589 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
590 value
->UngetWriteBuf();
597 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
599 // some compilers have putenv() or _putenv() or _wputenv() but it's better
600 // to always use Win32 function directly instead of dealing with them
601 #if defined(__WIN32__)
602 if ( !::SetEnvironmentVariable(var
, value
) )
604 wxLogLastError(_T("SetEnvironmentVariable"));
610 #else // no way to set env vars
615 // ----------------------------------------------------------------------------
616 // process management
617 // ----------------------------------------------------------------------------
621 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
622 struct wxFindByPidParams
624 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
626 // the HWND used to return the result
629 // the PID we're looking from
633 // wxKill helper: EnumWindows() callback which is used to find the first (top
634 // level) window belonging to the given process
635 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
638 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
640 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
641 if ( pid
== params
->pid
)
643 // remember the window we found
646 // return FALSE to stop the enumeration
650 // continue enumeration
656 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
659 // get the process handle to operate on
660 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
662 PROCESS_QUERY_INFORMATION
,
663 FALSE
, // not inheritable
665 if ( hProcess
== NULL
)
669 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
671 *krc
= wxKILL_ACCESS_DENIED
;
675 *krc
= wxKILL_NO_PROCESS
;
686 // kill the process forcefully returning -1 as error code
687 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
689 wxLogSysError(_("Failed to kill process %d"), pid
);
693 // this is not supposed to happen if we could open the
703 // do nothing, we just want to test for process existence
707 // any other signal means "terminate"
709 wxFindByPidParams params
;
710 params
.pid
= (DWORD
)pid
;
712 // EnumWindows() has nice semantics: it returns 0 if it found
713 // something or if an error occured and non zero if it
714 // enumerated all the window
715 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
717 // did we find any window?
720 // tell the app to close
722 // NB: this is the harshest way, the app won't have
723 // opportunity to save any files, for example, but
724 // this is probably what we want here. If not we
725 // can also use SendMesageTimeout(WM_CLOSE)
726 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
728 wxLogLastError(_T("PostMessage(WM_QUIT)"));
731 else // it was an error then
733 wxLogLastError(_T("EnumWindows"));
738 else // no windows for this PID
755 // as we wait for a short time, we can use just WaitForSingleObject()
756 // and not MsgWaitForMultipleObjects()
757 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
760 // process terminated
761 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
763 wxLogLastError(_T("GetExitCodeProcess"));
768 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
772 wxLogLastError(_T("WaitForSingleObject"));
787 // just to suppress the warnings about uninitialized variable
791 ::CloseHandle(hProcess
);
793 // the return code is the same as from Unix kill(): 0 if killed
794 // successfully or -1 on error
795 if ( sig
== wxSIGNONE
)
797 if ( ok
&& rc
== STILL_ACTIVE
)
799 // there is such process => success
805 if ( ok
&& rc
!= STILL_ACTIVE
)
812 wxFAIL_MSG( _T("not implemented") );
813 #endif // Win32/Win16
819 // Execute a program in an Interactive Shell
820 bool wxShell(const wxString
& command
)
822 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
824 shell
= wxT("\\COMMAND.COM");
834 // pass the command to execute to the command processor
835 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
838 return wxExecute(cmd
, TRUE
/* sync */) != 0;
841 // ----------------------------------------------------------------------------
843 // ----------------------------------------------------------------------------
845 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
846 long wxGetFreeMemory()
848 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
849 MEMORYSTATUS memStatus
;
850 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
851 GlobalMemoryStatus(&memStatus
);
852 return memStatus
.dwAvailPhys
;
854 return (long)GetFreeSpace(0);
861 ::MessageBeep((UINT
)-1); // default sound
864 wxString
wxGetOsDescription()
872 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
873 if ( ::GetVersionEx(&info
) )
875 switch ( info
.dwPlatformId
)
877 case VER_PLATFORM_WIN32s
:
878 str
= _("Win32s on Windows 3.1");
881 case VER_PLATFORM_WIN32_WINDOWS
:
882 str
.Printf(_("Windows 9%c"),
883 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
884 if ( !wxIsEmpty(info
.szCSDVersion
) )
886 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
890 case VER_PLATFORM_WIN32_NT
:
891 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
895 if ( !wxIsEmpty(info
.szCSDVersion
) )
897 str
<< _T(", ") << info
.szCSDVersion
;
905 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
910 return _("Windows 3.1");
914 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
916 #if defined(__WIN32__) && !defined(__SC__)
917 static int ver
= -1, major
= -1, minor
= -1;
925 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
926 if ( ::GetVersionEx(&info
) )
928 major
= info
.dwMajorVersion
;
929 minor
= info
.dwMinorVersion
;
931 switch ( info
.dwPlatformId
)
933 case VER_PLATFORM_WIN32s
:
937 case VER_PLATFORM_WIN32_WINDOWS
:
941 case VER_PLATFORM_WIN32_NT
:
948 if (majorVsn
&& major
!= -1)
950 if (minorVsn
&& minor
!= -1)
955 int retValue
= wxWINDOWS
;
956 #ifdef __WINDOWS_386__
959 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
960 extern HANDLE g_hPenWin
;
961 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
974 // ----------------------------------------------------------------------------
976 // ----------------------------------------------------------------------------
982 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
983 static bool gs_inTimer
= FALSE
;
985 class wxSleepTimer
: public wxTimer
988 virtual void Notify()
995 static wxTimer
*wxTheSleepTimer
= NULL
;
997 void wxUsleep(unsigned long milliseconds
)
1000 ::Sleep(milliseconds
);
1005 wxTheSleepTimer
= new wxSleepTimer
;
1007 wxTheSleepTimer
->Start(milliseconds
);
1010 if (wxTheApp
->Pending())
1011 wxTheApp
->Dispatch();
1013 delete wxTheSleepTimer
;
1014 wxTheSleepTimer
= NULL
;
1015 #endif // Win32/!Win32
1018 void wxSleep(int nSecs
)
1023 wxTheSleepTimer
= new wxSleepTimer
;
1025 wxTheSleepTimer
->Start(nSecs
*1000);
1028 if (wxTheApp
->Pending())
1029 wxTheApp
->Dispatch();
1031 delete wxTheSleepTimer
;
1032 wxTheSleepTimer
= NULL
;
1035 // Consume all events until no more left
1036 void wxFlushEvents()
1041 #endif // wxUSE_TIMER
1043 #elif defined(__WIN32__) // wxUSE_GUI
1045 void wxUsleep(unsigned long milliseconds
)
1047 ::Sleep(milliseconds
);
1050 void wxSleep(int nSecs
)
1052 wxUsleep(1000*nSecs
);
1055 #endif // wxUSE_GUI/!wxUSE_GUI
1056 #endif // __WXMICROWIN__
1058 // ----------------------------------------------------------------------------
1059 // deprecated (in favour of wxLog) log functions
1060 // ----------------------------------------------------------------------------
1062 #if WXWIN_COMPATIBILITY_2_2
1064 // Output a debug mess., in a system dependent fashion.
1065 #ifndef __WXMICROWIN__
1066 void wxDebugMsg(const wxChar
*fmt
...)
1069 static wxChar buffer
[512];
1071 if (!wxTheApp
->GetWantDebugOutput())
1076 wvsprintf(buffer
,fmt
,ap
) ;
1077 OutputDebugString((LPCTSTR
)buffer
) ;
1082 // Non-fatal error: pop up message box and (possibly) continue
1083 void wxError(const wxString
& msg
, const wxString
& title
)
1085 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
1086 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
1087 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
1091 // Fatal error: pop up message box and abort
1092 void wxFatalError(const wxString
& msg
, const wxString
& title
)
1094 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
1095 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
1097 #endif // __WXMICROWIN__
1099 #endif // WXWIN_COMPATIBILITY_2_2
1103 // ----------------------------------------------------------------------------
1104 // functions to work with .INI files
1105 // ----------------------------------------------------------------------------
1107 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1109 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
1111 if (file
!= wxT(""))
1112 // Don't know what the correct cast should be, but it doesn't
1113 // compile in BC++/16-bit without this cast.
1114 #if !defined(__WIN32__)
1115 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
1117 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
1120 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
1123 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
1126 buf
.Printf(wxT("%.4f"), value
);
1128 return wxWriteResource(section
, entry
, buf
, file
);
1131 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1134 buf
.Printf(wxT("%ld"), value
);
1136 return wxWriteResource(section
, entry
, buf
, file
);
1139 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1142 buf
.Printf(wxT("%d"), value
);
1144 return wxWriteResource(section
, entry
, buf
, file
);
1147 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1149 static const wxChar defunkt
[] = wxT("$$default");
1150 if (file
!= wxT(""))
1152 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1153 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1154 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1159 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1160 (LPTSTR
)wxBuffer
, 1000);
1161 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1164 if (*value
) delete[] (*value
);
1165 *value
= copystring(wxBuffer
);
1169 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1172 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1175 *value
= (float)wxStrtod(s
, NULL
);
1182 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1185 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1188 *value
= wxStrtol(s
, NULL
, 10);
1195 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1198 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1201 *value
= (int)wxStrtol(s
, NULL
, 10);
1207 #endif // wxUSE_RESOURCES
1209 // ---------------------------------------------------------------------------
1210 // helper functions for showing a "busy" cursor
1211 // ---------------------------------------------------------------------------
1213 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1214 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1215 static int gs_wxBusyCursorCount
= 0;
1217 extern HCURSOR
wxGetCurrentBusyCursor()
1219 return gs_wxBusyCursor
;
1222 // Set the cursor to the busy cursor for all windows
1223 void wxBeginBusyCursor(wxCursor
*cursor
)
1225 if ( gs_wxBusyCursorCount
++ == 0 )
1227 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1228 #ifndef __WXMICROWIN__
1229 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1232 //else: nothing to do, already set
1235 // Restore cursor to normal
1236 void wxEndBusyCursor()
1238 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1239 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1241 if ( --gs_wxBusyCursorCount
== 0 )
1243 #ifndef __WXMICROWIN__
1244 ::SetCursor(gs_wxBusyCursorOld
);
1246 gs_wxBusyCursorOld
= 0;
1250 // TRUE if we're between the above two calls
1253 return gs_wxBusyCursorCount
> 0;
1256 // Check whether this window wants to process messages, e.g. Stop button
1257 // in long calculations.
1258 bool wxCheckForInterrupt(wxWindow
*wnd
)
1260 wxCHECK( wnd
, FALSE
);
1263 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1265 ::TranslateMessage(&msg
);
1266 ::DispatchMessage(&msg
);
1272 // MSW only: get user-defined resource from the .res file.
1273 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1275 #ifndef __WXMICROWIN__
1276 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1278 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1279 if ( hResource
== 0 )
1282 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1286 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1290 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1291 // so we need to find the length of the resource.
1292 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1293 wxChar
*s
= new wxChar
[len
+1];
1294 wxStrncpy(s
,theText
,len
);
1297 // wxChar *s = copystring(theText);
1299 // Obsolete in WIN32
1301 UnlockResource(hData
);
1305 // GlobalFree(hData);
1309 #endif // __WXMICROWIN__
1311 // ----------------------------------------------------------------------------
1313 // ----------------------------------------------------------------------------
1315 // See also the wxGetMousePosition in window.cpp
1316 // Deprecated: use wxPoint wxGetMousePosition() instead
1317 void wxGetMousePosition( int* x
, int* y
)
1320 GetCursorPos( & pt
);
1325 // Return TRUE if we have a colour display
1326 bool wxColourDisplay()
1328 #ifdef __WXMICROWIN__
1332 // this function is called from wxDC ctor so it is called a *lot* of times
1333 // hence we optimize it a bit but doign the check only once
1335 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1337 static int s_isColour
= -1;
1339 if ( s_isColour
== -1 )
1342 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1344 s_isColour
= (noCols
== -1) || (noCols
> 2);
1347 return s_isColour
!= 0;
1351 // Returns depth of screen
1352 int wxDisplayDepth()
1355 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1358 // Get size of display
1359 void wxDisplaySize(int *width
, int *height
)
1361 #ifdef __WXMICROWIN__
1363 HWND hWnd
= GetDesktopWindow();
1364 ::GetWindowRect(hWnd
, & rect
);
1367 *width
= rect
.right
- rect
.left
;
1369 *height
= rect
.bottom
- rect
.top
;
1370 #else // !__WXMICROWIN__
1374 *width
= ::GetDeviceCaps(dc
, HORZRES
);
1376 *height
= ::GetDeviceCaps(dc
, VERTRES
);
1377 #endif // __WXMICROWIN__/!__WXMICROWIN__
1380 void wxDisplaySizeMM(int *width
, int *height
)
1382 #ifdef __WXMICROWIN__
1392 *width
= ::GetDeviceCaps(dc
, HORZSIZE
);
1394 *height
= ::GetDeviceCaps(dc
, VERTSIZE
);
1398 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1400 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1402 wxDisplaySize(width
, height
);
1404 // Determine the desktop dimensions minus the taskbar and any other
1405 // special decorations...
1408 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1411 if (width
) *width
= r
.right
- r
.left
;
1412 if (height
) *height
= r
.bottom
- r
.top
;
1416 // ---------------------------------------------------------------------------
1417 // window information functions
1418 // ---------------------------------------------------------------------------
1420 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1426 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1427 ::GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1428 str
.UngetWriteBuf();
1434 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1439 #ifndef __WXMICROWIN__
1442 int len
= 256; // some starting value
1446 int count
= ::GetClassName((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1448 str
.UngetWriteBuf();
1451 // the class name might have been truncated, retry with larger
1461 #endif // !__WXMICROWIN__
1466 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1469 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1471 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1475 // ----------------------------------------------------------------------------
1477 // ----------------------------------------------------------------------------
1479 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1483 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1484 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1485 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1486 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1488 *x
*= (iWidthMM
* 100);
1490 *y
*= (iHeightMM
* 100);
1494 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1498 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1499 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1500 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1501 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1504 *x
/= (iWidthMM
* 100);
1506 *y
/= (iHeightMM
* 100);
1511 #ifdef __WXMICROWIN__
1512 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1515 if (majorVsn
) *majorVsn
= 0;
1516 if (minorVsn
) *minorVsn
= 0;
1519 #endif // __WXMICROWIN__
1521 // ----------------------------------------------------------------------------
1522 // Win32 codepage conversion functions
1523 // ----------------------------------------------------------------------------
1525 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1527 // wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1528 #if wxUSE_GUI && !defined(__WXUNIVERSAL__)
1530 #include "wx/fontmap.h"
1532 // VZ: the new version of wxCharsetToCodepage() is more politically correct
1533 // and should work on other Windows versions as well but the old version is
1534 // still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
1536 extern long wxEncodingToCodepage(wxFontEncoding encoding
)
1538 // translate encoding into the Windows CHARSET
1539 wxNativeEncodingInfo natveEncInfo
;
1540 if ( !wxGetNativeFontEncoding(encoding
, &natveEncInfo
) )
1543 // translate CHARSET to code page
1544 CHARSETINFO csetInfo
;
1545 if ( !::TranslateCharsetInfo((DWORD
*)(DWORD
)natveEncInfo
.charset
,
1549 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1554 return csetInfo
.ciACP
;
1559 extern long wxCharsetToCodepage(const wxChar
*name
)
1561 // first get the font encoding for this charset
1565 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(name
, FALSE
);
1566 if ( enc
== wxFONTENCODING_SYSTEM
)
1569 // the use the helper function
1570 return wxEncodingToCodepage(enc
);
1573 #endif // wxUSE_FONTMAP
1577 // include old wxCharsetToCodepage() by OK if needed
1578 #if !wxUSE_GUI || !wxUSE_FONTMAP
1580 #include "wx/msw/registry.h"
1582 // this should work if Internet Exploiter is installed
1583 extern long wxCharsetToCodepage(const wxChar
*name
)
1592 wxString
path(wxT("MIME\\Database\\Charset\\"));
1594 wxRegKey
key(wxRegKey::HKCR
, path
);
1596 if (!key
.Exists()) break;
1598 // two cases: either there's an AliasForCharset string,
1599 // or there are Codepage and InternetEncoding dwords.
1600 // The InternetEncoding gives us the actual encoding,
1601 // the Codepage just says which Windows character set to
1602 // use when displaying the data.
1603 if (key
.HasValue(wxT("InternetEncoding")) &&
1604 key
.QueryValue(wxT("InternetEncoding"), &CP
)) break;
1606 // no encoding, see if it's an alias
1607 if (!key
.HasValue(wxT("AliasForCharset")) ||
1608 !key
.QueryValue(wxT("AliasForCharset"), cn
)) break;
1614 #endif // !wxUSE_GUI || !wxUSE_FONTMAP