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 #include "wx/msw/private.h" // includes <windows.h>
43 #ifdef __GNUWIN32_OLD__
44 // apparently we need to include winsock.h to get WSADATA and other stuff
45 // used in wxGetFullHostName() with the old mingw32 versions
51 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
59 #if defined(__CYGWIN__) && !defined(__TWIN32__)
60 #include <sys/unistd.h>
62 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
65 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
66 // this (3.1 I believe) and how to test for it.
67 // If this works for Borland 4.0 as well, then no worries.
71 // VZ: there is some code using NetXXX() functions to get the full user name:
72 // I don't think it's a good idea because they don't work under Win95 and
73 // seem to return the same as wxGetUserId() under NT. If you really want
74 // to use them, just #define USE_NET_API
81 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
90 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
95 //// BEGIN for console support: VC++ only
98 #include "wx/msw/msvcrt.h"
102 #include "wx/ioswrap.h"
104 /* Need to undef new if including crtdbg.h */
113 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
114 # define new new(__TFILE__,__LINE__)
119 /// END for console support
121 // ----------------------------------------------------------------------------
123 // ----------------------------------------------------------------------------
125 // In the WIN.INI file
126 static const wxChar WX_SECTION
[] = wxT("wxWindows");
127 static const wxChar eUSERNAME
[] = wxT("UserName");
129 // these are only used under Win16
130 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
131 static const wxChar eHOSTNAME
[] = wxT("HostName");
132 static const wxChar eUSERID
[] = wxT("UserId");
135 #ifndef __WXMICROWIN__
137 // ============================================================================
139 // ============================================================================
141 // ----------------------------------------------------------------------------
142 // get host name and related
143 // ----------------------------------------------------------------------------
145 // Get hostname only (without domain name)
146 bool wxGetHostName(wxChar
*buf
, int maxSize
)
148 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
149 DWORD nSize
= maxSize
;
150 if ( !::GetComputerName(buf
, &nSize
) )
152 wxLogLastError(wxT("GetComputerName"));
160 const wxChar
*default_host
= wxT("noname");
162 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
163 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
165 wxStrncpy(buf
, sysname
, maxSize
- 1);
166 buf
[maxSize
] = wxT('\0');
167 return *buf
? TRUE
: FALSE
;
171 // get full hostname (with domain name if possible)
172 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
174 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
175 // TODO should use GetComputerNameEx() when available
177 // the idea is that if someone had set wxUSE_SOCKETS to 0 the code
178 // shouldn't use winsock.dll (a.k.a. ws2_32.dll) at all so only use this
179 // code if we link with it anyhow
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, AF_INET
);
202 host
= pHostEnt
->h_name
;
211 wxStrncpy(buf
, host
, maxSize
);
216 #endif // wxUSE_SOCKETS
220 return wxGetHostName(buf
, maxSize
);
223 // Get user ID e.g. jacs
224 bool wxGetUserId(wxChar
*buf
, int maxSize
)
226 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
227 DWORD nSize
= maxSize
;
228 if ( ::GetUserName(buf
, &nSize
) == 0 )
230 // actually, it does happen on Win9x if the user didn't log on
231 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
240 #else // Win16 or Win32s
242 const wxChar
*default_id
= wxT("anonymous");
244 // Can't assume we have NIS (PC-NFS) or some other ID daemon
246 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
247 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
249 // Use wxWindows configuration data (comming soon)
250 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
254 wxStrncpy(buf
, user
, maxSize
- 1);
257 return *buf
? TRUE
: FALSE
;
261 // Get user name e.g. Julian Smart
262 bool wxGetUserName(wxChar
*buf
, int maxSize
)
264 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
265 extern HANDLE g_hPenWin
; // PenWindows Running?
268 // PenWindows Does have a user concept!
269 // Get the current owner of the recognizer
270 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
271 strncpy(buf
, wxBuffer
, maxSize
- 1);
277 CHAR szUserName
[256];
278 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
281 // TODO how to get the domain name?
284 // the code is based on the MSDN example (also see KB article Q119670)
285 WCHAR wszUserName
[256]; // Unicode user name
286 WCHAR wszDomain
[256];
289 USER_INFO_2
*ui2
; // User structure
291 // Convert ANSI user name and domain to Unicode
292 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
293 wszUserName
, WXSIZEOF(wszUserName
) );
294 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
295 wszDomain
, WXSIZEOF(wszDomain
) );
297 // Get the computer name of a DC for the domain.
298 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
300 wxLogError(wxT("Can not find domain controller"));
305 // Look up the user on the DC
306 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
307 (LPWSTR
)&wszUserName
,
308 2, // level - we want USER_INFO_2
316 case NERR_InvalidComputer
:
317 wxLogError(wxT("Invalid domain controller name."));
321 case NERR_UserNotFound
:
322 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
327 wxLogSysError(wxT("Can't get information about user"));
332 // Convert the Unicode full name to ANSI
333 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
334 buf
, maxSize
, NULL
, NULL
);
339 wxLogError(wxT("Couldn't look up full user name."));
342 #else // !USE_NET_API
343 // Could use NIS, MS-Mail or other site specific programs
344 // Use wxWindows configuration data
345 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
348 ok
= wxGetUserId(buf
, maxSize
);
353 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
361 const wxChar
* wxGetHomeDir(wxString
*pstr
)
363 wxString
& strDir
= *pstr
;
365 #if defined(__UNIX__) && !defined(__TWIN32__)
366 const wxChar
*szHome
= wxGetenv("HOME");
367 if ( szHome
== NULL
) {
369 wxLogWarning(_("can't find user's HOME, using current directory."));
375 // add a trailing slash if needed
376 if ( strDir
.Last() != wxT('/') )
380 // Cygwin returns unix type path but that does not work well
381 static wxChar windowsPath
[MAX_PATH
];
382 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
383 strDir
= windowsPath
;
389 // If we have a valid HOME directory, as is used on many machines that
390 // have unix utilities on them, we should use that.
391 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
393 if ( szHome
!= NULL
)
397 else // no HOME, try HOMEDRIVE/PATH
399 szHome
= wxGetenv(wxT("HOMEDRIVE"));
400 if ( szHome
!= NULL
)
402 szHome
= wxGetenv(wxT("HOMEPATH"));
404 if ( szHome
!= NULL
)
408 // the idea is that under NT these variables have default values
409 // of "%systemdrive%:" and "\\". As we don't want to create our
410 // config files in the root directory of the system drive, we will
411 // create it in our program's dir. However, if the user took care
412 // to set HOMEPATH to something other than "\\", we suppose that he
413 // knows what he is doing and use the supplied value.
414 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
419 if ( strDir
.empty() )
421 // If we have a valid USERPROFILE directory, as is the case in
422 // Windows NT, 2000 and XP, we should use that as our home directory.
423 szHome
= wxGetenv(wxT("USERPROFILE"));
425 if ( szHome
!= NULL
)
429 if ( !strDir
.empty() )
431 return strDir
.c_str();
433 //else: fall back to the prograrm directory
435 // Win16 has no idea about home, so use the executable directory instead
438 // 260 was taken from windef.h
444 ::GetModuleFileName(::GetModuleHandle(NULL
),
445 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
446 strPath
.UngetWriteBuf();
448 // extract the dir name
449 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
453 return strDir
.c_str();
456 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
458 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
459 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
460 // static buffer and sometimes I don't even know what.
461 static wxString s_home
;
463 return (wxChar
*)wxGetHomeDir(&s_home
);
466 bool wxDirExists(const wxString
& dir
)
468 #ifdef __WXMICROWIN__
469 return wxPathExist(dir
);
470 #elif defined(__WIN32__)
471 DWORD attribs
= GetFileAttributes(dir
);
472 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
475 struct ffblk fileInfo
;
477 struct find_t fileInfo
;
479 // In Borland findfirst has a different argument
480 // ordering from _dos_findfirst. But _dos_findfirst
481 // _should_ be ok in both MS and Borland... why not?
483 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
484 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
486 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
487 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
492 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
497 // old w32api don't have ULARGE_INTEGER
498 #if defined(__WIN32__) && \
499 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
500 // GetDiskFreeSpaceEx() is not available under original Win95, check for
502 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
508 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
510 ::GetModuleHandle(_T("kernel32.dll")),
512 "GetDiskFreeSpaceExW"
514 "GetDiskFreeSpaceExA"
518 if ( pGetDiskFreeSpaceEx
)
520 ULARGE_INTEGER bytesFree
, bytesTotal
;
522 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
523 if ( !pGetDiskFreeSpaceEx(path
,
528 wxLogLastError(_T("GetDiskFreeSpaceEx"));
533 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
534 // two 32 bit fields which may be or may be not named - try to make it
535 // compile in all cases
536 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
543 *pTotal
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
548 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
554 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
555 // should be used instead - but if it's not available, fall back on
556 // GetDiskFreeSpace() nevertheless...
558 DWORD lSectorsPerCluster
,
560 lNumberOfFreeClusters
,
561 lTotalNumberOfClusters
;
563 // FIXME: this is wrong, we should extract the root drive from path
564 // instead, but this is the job for wxFileName...
565 if ( !::GetDiskFreeSpace(path
,
568 &lNumberOfFreeClusters
,
569 &lTotalNumberOfClusters
) )
571 wxLogLastError(_T("GetDiskFreeSpace"));
576 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
577 lBytesPerCluster
*= lBytesPerSector
;
581 *pTotal
= lBytesPerCluster
;
582 *pTotal
*= lTotalNumberOfClusters
;
587 *pFree
= lBytesPerCluster
;
588 *pFree
*= lNumberOfFreeClusters
;
595 // ----------------------------------------------------------------------------
597 // ----------------------------------------------------------------------------
599 bool wxGetEnv(const wxString
& var
, wxString
*value
)
602 const wxChar
* ret
= wxGetenv(var
);
611 // first get the size of the buffer
612 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
615 // this means that there is no such variable
621 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
622 value
->UngetWriteBuf();
629 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
631 // some compilers have putenv() or _putenv() or _wputenv() but it's better
632 // to always use Win32 function directly instead of dealing with them
633 #if defined(__WIN32__)
634 if ( !::SetEnvironmentVariable(var
, value
) )
636 wxLogLastError(_T("SetEnvironmentVariable"));
642 #else // no way to set env vars
647 // ----------------------------------------------------------------------------
648 // process management
649 // ----------------------------------------------------------------------------
653 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
654 struct wxFindByPidParams
656 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
658 // the HWND used to return the result
661 // the PID we're looking from
665 // wxKill helper: EnumWindows() callback which is used to find the first (top
666 // level) window belonging to the given process
667 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
670 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
672 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
673 if ( pid
== params
->pid
)
675 // remember the window we found
678 // return FALSE to stop the enumeration
682 // continue enumeration
688 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
691 // get the process handle to operate on
692 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
694 PROCESS_QUERY_INFORMATION
,
695 FALSE
, // not inheritable
697 if ( hProcess
== NULL
)
701 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
703 *krc
= wxKILL_ACCESS_DENIED
;
707 *krc
= wxKILL_NO_PROCESS
;
718 // kill the process forcefully returning -1 as error code
719 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
721 wxLogSysError(_("Failed to kill process %d"), pid
);
725 // this is not supposed to happen if we could open the
735 // do nothing, we just want to test for process existence
739 // any other signal means "terminate"
741 wxFindByPidParams params
;
742 params
.pid
= (DWORD
)pid
;
744 // EnumWindows() has nice semantics: it returns 0 if it found
745 // something or if an error occured and non zero if it
746 // enumerated all the window
747 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
749 // did we find any window?
752 // tell the app to close
754 // NB: this is the harshest way, the app won't have
755 // opportunity to save any files, for example, but
756 // this is probably what we want here. If not we
757 // can also use SendMesageTimeout(WM_CLOSE)
758 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
760 wxLogLastError(_T("PostMessage(WM_QUIT)"));
763 else // it was an error then
765 wxLogLastError(_T("EnumWindows"));
770 else // no windows for this PID
787 // as we wait for a short time, we can use just WaitForSingleObject()
788 // and not MsgWaitForMultipleObjects()
789 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
792 // process terminated
793 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
795 wxLogLastError(_T("GetExitCodeProcess"));
800 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
804 wxLogLastError(_T("WaitForSingleObject"));
819 // just to suppress the warnings about uninitialized variable
823 ::CloseHandle(hProcess
);
825 // the return code is the same as from Unix kill(): 0 if killed
826 // successfully or -1 on error
827 if ( sig
== wxSIGNONE
)
829 if ( ok
&& rc
== STILL_ACTIVE
)
831 // there is such process => success
837 if ( ok
&& rc
!= STILL_ACTIVE
)
844 wxFAIL_MSG( _T("not implemented") );
845 #endif // Win32/Win16
851 // Execute a program in an Interactive Shell
852 bool wxShell(const wxString
& command
)
854 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
856 shell
= (wxChar
*) wxT("\\COMMAND.COM");
866 // pass the command to execute to the command processor
867 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
870 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
873 // Shutdown or reboot the PC
874 bool wxShutdown(wxShutdownFlags wFlags
)
879 if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_NT
) // if is NT or 2K
881 // Get a token for this process.
883 bOK
= ::OpenProcessToken(GetCurrentProcess(),
884 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
889 TOKEN_PRIVILEGES tkp
;
891 // Get the LUID for the shutdown privilege.
892 ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
893 &tkp
.Privileges
[0].Luid
);
895 tkp
.PrivilegeCount
= 1; // one privilege to set
896 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
898 // Get the shutdown privilege for this process.
899 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
900 (PTOKEN_PRIVILEGES
)NULL
, 0);
902 // Cannot test the return value of AdjustTokenPrivileges.
903 bOK
= ::GetLastError() == ERROR_SUCCESS
;
910 UINT flags
= EWX_SHUTDOWN
| EWX_FORCE
;
913 case wxSHUTDOWN_POWEROFF
:
914 flags
|= EWX_POWEROFF
;
917 case wxSHUTDOWN_REBOOT
:
922 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
926 bOK
= ::ExitWindowsEx(EWX_SHUTDOWN
| EWX_FORCE
| EWX_REBOOT
, 0) != 0;
935 // ----------------------------------------------------------------------------
937 // ----------------------------------------------------------------------------
939 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
940 long wxGetFreeMemory()
942 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
943 MEMORYSTATUS memStatus
;
944 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
945 GlobalMemoryStatus(&memStatus
);
946 return memStatus
.dwAvailPhys
;
948 return (long)GetFreeSpace(0);
952 unsigned long wxGetProcessId()
955 return ::GetCurrentProcessId();
964 ::MessageBeep((UINT
)-1); // default sound
967 wxString
wxGetOsDescription()
975 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
976 if ( ::GetVersionEx(&info
) )
978 switch ( info
.dwPlatformId
)
980 case VER_PLATFORM_WIN32s
:
981 str
= _("Win32s on Windows 3.1");
984 case VER_PLATFORM_WIN32_WINDOWS
:
985 str
.Printf(_("Windows 9%c"),
986 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
987 if ( !wxIsEmpty(info
.szCSDVersion
) )
989 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
993 case VER_PLATFORM_WIN32_NT
:
994 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
998 if ( !wxIsEmpty(info
.szCSDVersion
) )
1000 str
<< _T(", ") << info
.szCSDVersion
;
1008 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1013 return _("Windows 3.1");
1017 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1019 #if defined(__WIN32__) && !defined(__SC__)
1020 static int ver
= -1, major
= -1, minor
= -1;
1028 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1029 if ( ::GetVersionEx(&info
) )
1031 major
= info
.dwMajorVersion
;
1032 minor
= info
.dwMinorVersion
;
1034 switch ( info
.dwPlatformId
)
1036 case VER_PLATFORM_WIN32s
:
1040 case VER_PLATFORM_WIN32_WINDOWS
:
1044 case VER_PLATFORM_WIN32_NT
:
1051 if (majorVsn
&& major
!= -1)
1053 if (minorVsn
&& minor
!= -1)
1058 int retValue
= wxWINDOWS
;
1059 #ifdef __WINDOWS_386__
1060 retValue
= wxWIN386
;
1062 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
1063 extern HANDLE g_hPenWin
;
1064 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
1077 // ----------------------------------------------------------------------------
1079 // ----------------------------------------------------------------------------
1085 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1086 static bool gs_inTimer
= FALSE
;
1088 class wxSleepTimer
: public wxTimer
1091 virtual void Notify()
1098 static wxTimer
*wxTheSleepTimer
= NULL
;
1100 void wxUsleep(unsigned long milliseconds
)
1103 ::Sleep(milliseconds
);
1108 wxTheSleepTimer
= new wxSleepTimer
;
1110 wxTheSleepTimer
->Start(milliseconds
);
1113 if (wxTheApp
->Pending())
1114 wxTheApp
->Dispatch();
1116 delete wxTheSleepTimer
;
1117 wxTheSleepTimer
= NULL
;
1118 #endif // Win32/!Win32
1121 void wxSleep(int nSecs
)
1126 wxTheSleepTimer
= new wxSleepTimer
;
1128 wxTheSleepTimer
->Start(nSecs
*1000);
1131 if (wxTheApp
->Pending())
1132 wxTheApp
->Dispatch();
1134 delete wxTheSleepTimer
;
1135 wxTheSleepTimer
= NULL
;
1138 // Consume all events until no more left
1139 void wxFlushEvents()
1144 #endif // wxUSE_TIMER
1146 #elif defined(__WIN32__) // wxUSE_GUI
1148 void wxUsleep(unsigned long milliseconds
)
1150 ::Sleep(milliseconds
);
1153 void wxSleep(int nSecs
)
1155 wxUsleep(1000*nSecs
);
1158 #endif // wxUSE_GUI/!wxUSE_GUI
1159 #endif // __WXMICROWIN__
1161 // ----------------------------------------------------------------------------
1162 // deprecated (in favour of wxLog) log functions
1163 // ----------------------------------------------------------------------------
1165 #if WXWIN_COMPATIBILITY_2_2
1167 // Output a debug mess., in a system dependent fashion.
1168 #ifndef __WXMICROWIN__
1169 void wxDebugMsg(const wxChar
*fmt
...)
1172 static wxChar buffer
[512];
1174 if (!wxTheApp
->GetWantDebugOutput())
1179 wvsprintf(buffer
,fmt
,ap
);
1180 OutputDebugString((LPCTSTR
)buffer
);
1185 // Non-fatal error: pop up message box and (possibly) continue
1186 void wxError(const wxString
& msg
, const wxString
& title
)
1188 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
1189 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
1190 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
1194 // Fatal error: pop up message box and abort
1195 void wxFatalError(const wxString
& msg
, const wxString
& title
)
1197 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
1198 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
1200 #endif // __WXMICROWIN__
1202 #endif // WXWIN_COMPATIBILITY_2_2
1206 // ----------------------------------------------------------------------------
1207 // functions to work with .INI files
1208 // ----------------------------------------------------------------------------
1210 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1212 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
1214 if (file
!= wxT(""))
1215 // Don't know what the correct cast should be, but it doesn't
1216 // compile in BC++/16-bit without this cast.
1217 #if !defined(__WIN32__)
1218 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
1220 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
1223 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
1226 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
1229 buf
.Printf(wxT("%.4f"), value
);
1231 return wxWriteResource(section
, entry
, buf
, file
);
1234 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1237 buf
.Printf(wxT("%ld"), value
);
1239 return wxWriteResource(section
, entry
, buf
, file
);
1242 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1245 buf
.Printf(wxT("%d"), value
);
1247 return wxWriteResource(section
, entry
, buf
, file
);
1250 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1252 static const wxChar defunkt
[] = wxT("$$default");
1253 if (file
!= wxT(""))
1255 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1256 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1257 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1262 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1263 (LPTSTR
)wxBuffer
, 1000);
1264 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1267 if (*value
) delete[] (*value
);
1268 *value
= copystring(wxBuffer
);
1272 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1275 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1278 *value
= (float)wxStrtod(s
, NULL
);
1285 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1288 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1291 *value
= wxStrtol(s
, NULL
, 10);
1298 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1301 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1304 *value
= (int)wxStrtol(s
, NULL
, 10);
1310 #endif // wxUSE_RESOURCES
1312 // ---------------------------------------------------------------------------
1313 // helper functions for showing a "busy" cursor
1314 // ---------------------------------------------------------------------------
1316 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1317 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1318 static int gs_wxBusyCursorCount
= 0;
1320 extern HCURSOR
wxGetCurrentBusyCursor()
1322 return gs_wxBusyCursor
;
1325 // Set the cursor to the busy cursor for all windows
1326 void wxBeginBusyCursor(wxCursor
*cursor
)
1328 if ( gs_wxBusyCursorCount
++ == 0 )
1330 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1331 #ifndef __WXMICROWIN__
1332 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1335 //else: nothing to do, already set
1338 // Restore cursor to normal
1339 void wxEndBusyCursor()
1341 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1342 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1344 if ( --gs_wxBusyCursorCount
== 0 )
1346 #ifndef __WXMICROWIN__
1347 ::SetCursor(gs_wxBusyCursorOld
);
1349 gs_wxBusyCursorOld
= 0;
1353 // TRUE if we're between the above two calls
1356 return gs_wxBusyCursorCount
> 0;
1359 // Check whether this window wants to process messages, e.g. Stop button
1360 // in long calculations.
1361 bool wxCheckForInterrupt(wxWindow
*wnd
)
1363 wxCHECK( wnd
, FALSE
);
1366 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1368 ::TranslateMessage(&msg
);
1369 ::DispatchMessage(&msg
);
1375 // MSW only: get user-defined resource from the .res file.
1376 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1378 #ifndef __WXMICROWIN__
1379 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1381 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1382 if ( hResource
== 0 )
1385 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1389 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1393 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1394 // so we need to find the length of the resource.
1395 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1396 wxChar
*s
= new wxChar
[len
+1];
1397 wxStrncpy(s
,theText
,len
);
1400 // wxChar *s = copystring(theText);
1402 // Obsolete in WIN32
1404 UnlockResource(hData
);
1408 // GlobalFree(hData);
1412 #endif // __WXMICROWIN__
1414 // ----------------------------------------------------------------------------
1416 // ----------------------------------------------------------------------------
1418 // See also the wxGetMousePosition in window.cpp
1419 // Deprecated: use wxPoint wxGetMousePosition() instead
1420 void wxGetMousePosition( int* x
, int* y
)
1423 GetCursorPos( & pt
);
1428 // Return TRUE if we have a colour display
1429 bool wxColourDisplay()
1431 #ifdef __WXMICROWIN__
1435 // this function is called from wxDC ctor so it is called a *lot* of times
1436 // hence we optimize it a bit but doign the check only once
1438 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1440 static int s_isColour
= -1;
1442 if ( s_isColour
== -1 )
1445 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1447 s_isColour
= (noCols
== -1) || (noCols
> 2);
1450 return s_isColour
!= 0;
1454 // Returns depth of screen
1455 int wxDisplayDepth()
1458 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1461 // Get size of display
1462 void wxDisplaySize(int *width
, int *height
)
1464 #ifdef __WXMICROWIN__
1466 HWND hWnd
= GetDesktopWindow();
1467 ::GetWindowRect(hWnd
, & rect
);
1470 *width
= rect
.right
- rect
.left
;
1472 *height
= rect
.bottom
- rect
.top
;
1473 #else // !__WXMICROWIN__
1477 *width
= ::GetDeviceCaps(dc
, HORZRES
);
1479 *height
= ::GetDeviceCaps(dc
, VERTRES
);
1480 #endif // __WXMICROWIN__/!__WXMICROWIN__
1483 void wxDisplaySizeMM(int *width
, int *height
)
1485 #ifdef __WXMICROWIN__
1495 *width
= ::GetDeviceCaps(dc
, HORZSIZE
);
1497 *height
= ::GetDeviceCaps(dc
, VERTSIZE
);
1501 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1503 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1505 wxDisplaySize(width
, height
);
1507 // Determine the desktop dimensions minus the taskbar and any other
1508 // special decorations...
1511 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1514 if (width
) *width
= r
.right
- r
.left
;
1515 if (height
) *height
= r
.bottom
- r
.top
;
1519 // ---------------------------------------------------------------------------
1520 // window information functions
1521 // ---------------------------------------------------------------------------
1523 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1529 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1530 ::GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1531 str
.UngetWriteBuf();
1537 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1542 #ifndef __WXMICROWIN__
1545 int len
= 256; // some starting value
1549 int count
= ::GetClassName((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1551 str
.UngetWriteBuf();
1554 // the class name might have been truncated, retry with larger
1564 #endif // !__WXMICROWIN__
1569 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1572 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1574 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1578 // ----------------------------------------------------------------------------
1580 // ----------------------------------------------------------------------------
1582 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1586 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1587 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1588 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1589 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1591 *x
*= (iWidthMM
* 100);
1593 *y
*= (iHeightMM
* 100);
1597 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1601 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1602 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1603 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1604 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1607 *x
/= (iWidthMM
* 100);
1609 *y
/= (iHeightMM
* 100);
1614 #ifdef __WXMICROWIN__
1615 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1618 if (majorVsn
) *majorVsn
= 0;
1619 if (minorVsn
) *minorVsn
= 0;
1622 #endif // __WXMICROWIN__
1624 // ----------------------------------------------------------------------------
1625 // Win32 codepage conversion functions
1626 // ----------------------------------------------------------------------------
1628 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1630 // wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1631 #if wxUSE_GUI && !defined(__WXUNIVERSAL__)
1633 #include "wx/fontmap.h"
1635 // VZ: the new version of wxCharsetToCodepage() is more politically correct
1636 // and should work on other Windows versions as well but the old version is
1637 // still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
1639 extern long wxEncodingToCodepage(wxFontEncoding encoding
)
1641 // translate encoding into the Windows CHARSET
1642 wxNativeEncodingInfo natveEncInfo
;
1643 if ( !wxGetNativeFontEncoding(encoding
, &natveEncInfo
) )
1646 // translate CHARSET to code page
1647 CHARSETINFO csetInfo
;
1648 if ( !::TranslateCharsetInfo((DWORD
*)(DWORD
)natveEncInfo
.charset
,
1652 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1657 return csetInfo
.ciACP
;
1662 extern long wxCharsetToCodepage(const wxChar
*name
)
1664 // first get the font encoding for this charset
1668 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(name
, FALSE
);
1669 if ( enc
== wxFONTENCODING_SYSTEM
)
1672 // the use the helper function
1673 return wxEncodingToCodepage(enc
);
1676 #endif // wxUSE_FONTMAP
1680 // include old wxCharsetToCodepage() by OK if needed
1681 #if !wxUSE_GUI || !wxUSE_FONTMAP
1683 #include "wx/msw/registry.h"
1685 // this should work if Internet Exploiter is installed
1686 extern long wxCharsetToCodepage(const wxChar
*name
)
1695 wxString
path(wxT("MIME\\Database\\Charset\\"));
1697 wxRegKey
key(wxRegKey::HKCR
, path
);
1699 if (!key
.Exists()) break;
1701 // two cases: either there's an AliasForCharset string,
1702 // or there are Codepage and InternetEncoding dwords.
1703 // The InternetEncoding gives us the actual encoding,
1704 // the Codepage just says which Windows character set to
1705 // use when displaying the data.
1706 if (key
.HasValue(wxT("InternetEncoding")) &&
1707 key
.QueryValue(wxT("InternetEncoding"), &CP
)) break;
1709 // no encoding, see if it's an alias
1710 if (!key
.HasValue(wxT("AliasForCharset")) ||
1711 !key
.QueryValue(wxT("AliasForCharset"), cn
)) break;
1717 #endif // !wxUSE_GUI || !wxUSE_FONTMAP