1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
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(__SALFORDC__) && !defined(__WXMICROWIN__)
59 #if defined(__CYGWIN__)
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(__WXMICROWIN__)
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
97 //// BEGIN for console support: VC++ only
100 #include "wx/msw/msvcrt.h"
104 #include "wx/ioswrap.h"
106 /* Need to undef new if including crtdbg.h */
115 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
116 # define new new(__TFILE__,__LINE__)
121 /// END for console support
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // In the WIN.INI file
128 static const wxChar WX_SECTION
[] = wxT("wxWindows");
129 static const wxChar eUSERNAME
[] = wxT("UserName");
131 // these are only used under Win16
132 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
133 static const wxChar eHOSTNAME
[] = wxT("HostName");
134 static const wxChar eUSERID
[] = wxT("UserId");
137 #ifndef __WXMICROWIN__
139 // ============================================================================
141 // ============================================================================
143 // ----------------------------------------------------------------------------
144 // get host name and related
145 // ----------------------------------------------------------------------------
147 // Get hostname only (without domain name)
148 bool wxGetHostName(wxChar
*buf
, int maxSize
)
150 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
151 DWORD nSize
= maxSize
;
152 if ( !::GetComputerName(buf
, &nSize
) )
154 wxLogLastError(wxT("GetComputerName"));
162 const wxChar
*default_host
= wxT("noname");
164 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
165 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
167 wxStrncpy(buf
, sysname
, maxSize
- 1);
168 buf
[maxSize
] = wxT('\0');
169 return *buf
? TRUE
: FALSE
;
173 // get full hostname (with domain name if possible)
174 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
176 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
177 // TODO should use GetComputerNameEx() when available
179 // the idea is that if someone had set wxUSE_SOCKETS to 0 the code
180 // shouldn't use winsock.dll (a.k.a. ws2_32.dll) at all so only use this
181 // code if we link with it anyhow
185 if ( WSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
189 if ( gethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
191 // gethostname() won't usually include the DNS domain name, for
192 // this we need to work a bit more
193 if ( !strchr(bufA
, '.') )
195 struct hostent
*pHostEnt
= gethostbyname(bufA
);
199 // Windows will use DNS internally now
200 pHostEnt
= gethostbyaddr(pHostEnt
->h_addr
, 4, AF_INET
);
205 host
= wxString::FromAscii(pHostEnt
->h_name
);
214 wxStrncpy(buf
, host
, maxSize
);
220 #endif // wxUSE_SOCKETS
224 return wxGetHostName(buf
, maxSize
);
227 // Get user ID e.g. jacs
228 bool wxGetUserId(wxChar
*buf
, int maxSize
)
230 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__WXMICROWIN__)
231 DWORD nSize
= maxSize
;
232 if ( ::GetUserName(buf
, &nSize
) == 0 )
234 // actually, it does happen on Win9x if the user didn't log on
235 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
244 #else // Win16 or Win32s
246 const wxChar
*default_id
= wxT("anonymous");
248 // Can't assume we have NIS (PC-NFS) or some other ID daemon
250 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
251 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
253 // Use wxWindows configuration data (comming soon)
254 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
258 wxStrncpy(buf
, user
, maxSize
- 1);
261 return *buf
? TRUE
: FALSE
;
265 // Get user name e.g. Julian Smart
266 bool wxGetUserName(wxChar
*buf
, int maxSize
)
268 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
269 extern HANDLE g_hPenWin
; // PenWindows Running?
272 // PenWindows Does have a user concept!
273 // Get the current owner of the recognizer
274 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
275 strncpy(buf
, wxBuffer
, maxSize
- 1);
281 CHAR szUserName
[256];
282 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
285 // TODO how to get the domain name?
288 // the code is based on the MSDN example (also see KB article Q119670)
289 WCHAR wszUserName
[256]; // Unicode user name
290 WCHAR wszDomain
[256];
293 USER_INFO_2
*ui2
; // User structure
295 // Convert ANSI user name and domain to Unicode
296 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
297 wszUserName
, WXSIZEOF(wszUserName
) );
298 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
299 wszDomain
, WXSIZEOF(wszDomain
) );
301 // Get the computer name of a DC for the domain.
302 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
304 wxLogError(wxT("Can not find domain controller"));
309 // Look up the user on the DC
310 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
311 (LPWSTR
)&wszUserName
,
312 2, // level - we want USER_INFO_2
320 case NERR_InvalidComputer
:
321 wxLogError(wxT("Invalid domain controller name."));
325 case NERR_UserNotFound
:
326 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
331 wxLogSysError(wxT("Can't get information about user"));
336 // Convert the Unicode full name to ANSI
337 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
338 buf
, maxSize
, NULL
, NULL
);
343 wxLogError(wxT("Couldn't look up full user name."));
346 #else // !USE_NET_API
347 // Could use NIS, MS-Mail or other site specific programs
348 // Use wxWindows configuration data
349 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
352 ok
= wxGetUserId(buf
, maxSize
);
357 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
365 const wxChar
* wxGetHomeDir(wxString
*pstr
)
367 wxString
& strDir
= *pstr
;
369 #if defined(__UNIX__)
370 const wxChar
*szHome
= wxGetenv("HOME");
371 if ( szHome
== NULL
) {
373 wxLogWarning(_("can't find user's HOME, using current directory."));
379 // add a trailing slash if needed
380 if ( strDir
.Last() != wxT('/') )
384 // Cygwin returns unix type path but that does not work well
385 static wxChar windowsPath
[MAX_PATH
];
386 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
387 strDir
= windowsPath
;
393 // If we have a valid HOME directory, as is used on many machines that
394 // have unix utilities on them, we should use that.
395 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
397 if ( szHome
!= NULL
)
401 else // no HOME, try HOMEDRIVE/PATH
403 szHome
= wxGetenv(wxT("HOMEDRIVE"));
404 if ( szHome
!= NULL
)
406 szHome
= wxGetenv(wxT("HOMEPATH"));
408 if ( szHome
!= NULL
)
412 // the idea is that under NT these variables have default values
413 // of "%systemdrive%:" and "\\". As we don't want to create our
414 // config files in the root directory of the system drive, we will
415 // create it in our program's dir. However, if the user took care
416 // to set HOMEPATH to something other than "\\", we suppose that he
417 // knows what he is doing and use the supplied value.
418 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
423 if ( strDir
.empty() )
425 // If we have a valid USERPROFILE directory, as is the case in
426 // Windows NT, 2000 and XP, we should use that as our home directory.
427 szHome
= wxGetenv(wxT("USERPROFILE"));
429 if ( szHome
!= NULL
)
433 if ( !strDir
.empty() )
435 return strDir
.c_str();
437 //else: fall back to the prograrm directory
439 // Win16 has no idea about home, so use the executable directory instead
442 // 260 was taken from windef.h
448 ::GetModuleFileName(::GetModuleHandle(NULL
),
449 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
450 strPath
.UngetWriteBuf();
452 // extract the dir name
453 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
457 return strDir
.c_str();
460 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
462 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
463 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
464 // static buffer and sometimes I don't even know what.
465 static wxString s_home
;
467 return (wxChar
*)wxGetHomeDir(&s_home
);
470 bool wxDirExists(const wxString
& dir
)
472 #ifdef __WXMICROWIN__
473 return wxPathExist(dir
);
474 #elif defined(__WIN32__)
475 DWORD attribs
= GetFileAttributes(dir
);
476 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
479 struct ffblk fileInfo
;
481 struct find_t fileInfo
;
483 // In Borland findfirst has a different argument
484 // ordering from _dos_findfirst. But _dos_findfirst
485 // _should_ be ok in both MS and Borland... why not?
487 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
488 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
490 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
491 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
496 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
501 // old w32api don't have ULARGE_INTEGER
502 #if defined(__WIN32__) && \
503 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
504 // GetDiskFreeSpaceEx() is not available under original Win95, check for
506 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
512 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
514 ::GetModuleHandle(_T("kernel32.dll")),
516 "GetDiskFreeSpaceExW"
518 "GetDiskFreeSpaceExA"
522 if ( pGetDiskFreeSpaceEx
)
524 ULARGE_INTEGER bytesFree
, bytesTotal
;
526 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
527 if ( !pGetDiskFreeSpaceEx(path
,
532 wxLogLastError(_T("GetDiskFreeSpaceEx"));
537 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
538 // two 32 bit fields which may be or may be not named - try to make it
539 // compile in all cases
540 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
547 *pTotal
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
552 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
558 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
559 // should be used instead - but if it's not available, fall back on
560 // GetDiskFreeSpace() nevertheless...
562 DWORD lSectorsPerCluster
,
564 lNumberOfFreeClusters
,
565 lTotalNumberOfClusters
;
567 // FIXME: this is wrong, we should extract the root drive from path
568 // instead, but this is the job for wxFileName...
569 if ( !::GetDiskFreeSpace(path
,
572 &lNumberOfFreeClusters
,
573 &lTotalNumberOfClusters
) )
575 wxLogLastError(_T("GetDiskFreeSpace"));
580 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
581 lBytesPerCluster
*= lBytesPerSector
;
585 *pTotal
= lBytesPerCluster
;
586 *pTotal
*= lTotalNumberOfClusters
;
591 *pFree
= lBytesPerCluster
;
592 *pFree
*= lNumberOfFreeClusters
;
599 // ----------------------------------------------------------------------------
601 // ----------------------------------------------------------------------------
603 bool wxGetEnv(const wxString
& var
, wxString
*value
)
606 const wxChar
* ret
= wxGetenv(var
);
617 // first get the size of the buffer
618 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
621 // this means that there is no such variable
627 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
628 value
->UngetWriteBuf();
635 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
637 // some compilers have putenv() or _putenv() or _wputenv() but it's better
638 // to always use Win32 function directly instead of dealing with them
639 #if defined(__WIN32__)
640 if ( !::SetEnvironmentVariable(var
, value
) )
642 wxLogLastError(_T("SetEnvironmentVariable"));
648 #else // no way to set env vars
653 // ----------------------------------------------------------------------------
654 // process management
655 // ----------------------------------------------------------------------------
657 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
658 struct wxFindByPidParams
660 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
662 // the HWND used to return the result
665 // the PID we're looking from
668 DECLARE_NO_COPY_CLASS(wxFindByPidParams
)
671 // wxKill helper: EnumWindows() callback which is used to find the first (top
672 // level) window belonging to the given process
673 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
676 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
678 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
679 if ( pid
== params
->pid
)
681 // remember the window we found
684 // return FALSE to stop the enumeration
688 // continue enumeration
692 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
694 // get the process handle to operate on
695 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
697 PROCESS_QUERY_INFORMATION
,
698 FALSE
, // not inheritable
700 if ( hProcess
== NULL
)
704 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
706 *krc
= wxKILL_ACCESS_DENIED
;
710 *krc
= wxKILL_NO_PROCESS
;
721 // kill the process forcefully returning -1 as error code
722 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
724 wxLogSysError(_("Failed to kill process %d"), pid
);
728 // this is not supposed to happen if we could open the
738 // do nothing, we just want to test for process existence
742 // any other signal means "terminate"
744 wxFindByPidParams params
;
745 params
.pid
= (DWORD
)pid
;
747 // EnumWindows() has nice semantics: it returns 0 if it found
748 // something or if an error occured and non zero if it
749 // enumerated all the window
750 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
752 // did we find any window?
755 // tell the app to close
757 // NB: this is the harshest way, the app won't have
758 // opportunity to save any files, for example, but
759 // this is probably what we want here. If not we
760 // can also use SendMesageTimeout(WM_CLOSE)
761 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
763 wxLogLastError(_T("PostMessage(WM_QUIT)"));
766 else // it was an error then
768 wxLogLastError(_T("EnumWindows"));
773 else // no windows for this PID
790 // as we wait for a short time, we can use just WaitForSingleObject()
791 // and not MsgWaitForMultipleObjects()
792 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
795 // process terminated
796 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
798 wxLogLastError(_T("GetExitCodeProcess"));
803 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
807 wxLogLastError(_T("WaitForSingleObject"));
822 // just to suppress the warnings about uninitialized variable
826 ::CloseHandle(hProcess
);
828 // the return code is the same as from Unix kill(): 0 if killed
829 // successfully or -1 on error
831 // be careful to interpret rc correctly: for wxSIGNONE we return success if
832 // the process exists, for all the other sig values -- if it doesn't
834 ((sig
== wxSIGNONE
) == (rc
== STILL_ACTIVE
)) )
848 // Execute a program in an Interactive Shell
849 bool wxShell(const wxString
& command
)
851 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
853 shell
= (wxChar
*) wxT("\\COMMAND.COM");
863 // pass the command to execute to the command processor
864 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
867 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
870 // Shutdown or reboot the PC
871 bool wxShutdown(wxShutdownFlags wFlags
)
876 if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_NT
) // if is NT or 2K
878 // Get a token for this process.
880 bOK
= ::OpenProcessToken(GetCurrentProcess(),
881 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
885 TOKEN_PRIVILEGES tkp
;
887 // Get the LUID for the shutdown privilege.
888 ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
889 &tkp
.Privileges
[0].Luid
);
891 tkp
.PrivilegeCount
= 1; // one privilege to set
892 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
894 // Get the shutdown privilege for this process.
895 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
896 (PTOKEN_PRIVILEGES
)NULL
, 0);
898 // Cannot test the return value of AdjustTokenPrivileges.
899 bOK
= ::GetLastError() == ERROR_SUCCESS
;
905 UINT flags
= EWX_SHUTDOWN
| EWX_FORCE
;
908 case wxSHUTDOWN_POWEROFF
:
909 flags
|= EWX_POWEROFF
;
912 case wxSHUTDOWN_REBOOT
:
917 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
921 bOK
= ::ExitWindowsEx(EWX_SHUTDOWN
| EWX_FORCE
| EWX_REBOOT
, 0) != 0;
930 // ----------------------------------------------------------------------------
932 // ----------------------------------------------------------------------------
934 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
935 long wxGetFreeMemory()
937 #if defined(__WIN32__) && !defined(__BORLANDC__)
938 MEMORYSTATUS memStatus
;
939 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
940 GlobalMemoryStatus(&memStatus
);
941 return memStatus
.dwAvailPhys
;
943 return (long)GetFreeSpace(0);
947 unsigned long wxGetProcessId()
950 return ::GetCurrentProcessId();
959 ::MessageBeep((UINT
)-1); // default sound
962 wxString
wxGetOsDescription()
970 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
971 if ( ::GetVersionEx(&info
) )
973 switch ( info
.dwPlatformId
)
975 case VER_PLATFORM_WIN32s
:
976 str
= _("Win32s on Windows 3.1");
979 case VER_PLATFORM_WIN32_WINDOWS
:
980 str
.Printf(_("Windows 9%c"),
981 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
982 if ( !wxIsEmpty(info
.szCSDVersion
) )
984 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
988 case VER_PLATFORM_WIN32_NT
:
989 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
993 if ( !wxIsEmpty(info
.szCSDVersion
) )
995 str
<< _T(", ") << info
.szCSDVersion
;
1003 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1008 return _("Windows 3.1");
1012 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1014 #if defined(__WIN32__)
1015 static int ver
= -1, major
= -1, minor
= -1;
1023 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1024 if ( ::GetVersionEx(&info
) )
1026 major
= info
.dwMajorVersion
;
1027 minor
= info
.dwMinorVersion
;
1029 switch ( info
.dwPlatformId
)
1031 case VER_PLATFORM_WIN32s
:
1035 case VER_PLATFORM_WIN32_WINDOWS
:
1039 case VER_PLATFORM_WIN32_NT
:
1046 if (majorVsn
&& major
!= -1)
1048 if (minorVsn
&& minor
!= -1)
1053 int retValue
= wxWINDOWS
;
1054 #ifdef __WINDOWS_386__
1055 retValue
= wxWIN386
;
1057 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
1058 extern HANDLE g_hPenWin
;
1059 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
1072 // ----------------------------------------------------------------------------
1074 // ----------------------------------------------------------------------------
1080 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1081 static bool gs_inTimer
= FALSE
;
1083 class wxSleepTimer
: public wxTimer
1086 virtual void Notify()
1093 static wxTimer
*wxTheSleepTimer
= NULL
;
1095 void wxUsleep(unsigned long milliseconds
)
1098 ::Sleep(milliseconds
);
1102 if (miliseconds
<= 0)
1105 wxTheSleepTimer
= new wxSleepTimer
;
1107 wxTheSleepTimer
->Start(milliseconds
);
1110 if (wxTheApp
->Pending())
1111 wxTheApp
->Dispatch();
1113 delete wxTheSleepTimer
;
1114 wxTheSleepTimer
= NULL
;
1115 #endif // Win32/!Win32
1118 void wxSleep(int nSecs
)
1125 wxTheSleepTimer
= new wxSleepTimer
;
1127 wxTheSleepTimer
->Start(nSecs
*1000);
1130 if (wxTheApp
->Pending())
1131 wxTheApp
->Dispatch();
1133 delete wxTheSleepTimer
;
1134 wxTheSleepTimer
= NULL
;
1137 // Consume all events until no more left
1138 void wxFlushEvents()
1143 #endif // wxUSE_TIMER
1145 #elif defined(__WIN32__) // wxUSE_GUI
1147 void wxUsleep(unsigned long milliseconds
)
1149 ::Sleep(milliseconds
);
1152 void wxSleep(int nSecs
)
1154 wxUsleep(1000*nSecs
);
1157 #endif // wxUSE_GUI/!wxUSE_GUI
1158 #endif // __WXMICROWIN__
1160 // ----------------------------------------------------------------------------
1161 // deprecated (in favour of wxLog) log functions
1162 // ----------------------------------------------------------------------------
1164 #if WXWIN_COMPATIBILITY_2_2
1166 // Output a debug mess., in a system dependent fashion.
1167 #ifndef __WXMICROWIN__
1168 void wxDebugMsg(const wxChar
*fmt
...)
1171 static wxChar buffer
[512];
1173 if (!wxTheApp
->GetWantDebugOutput())
1178 wvsprintf(buffer
,fmt
,ap
);
1179 OutputDebugString((LPCTSTR
)buffer
);
1184 // Non-fatal error: pop up message box and (possibly) continue
1185 void wxError(const wxString
& msg
, const wxString
& title
)
1187 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
1188 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
1189 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
1193 // Fatal error: pop up message box and abort
1194 void wxFatalError(const wxString
& msg
, const wxString
& title
)
1196 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
1197 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
1199 #endif // __WXMICROWIN__
1201 #endif // WXWIN_COMPATIBILITY_2_2
1205 // ----------------------------------------------------------------------------
1206 // functions to work with .INI files
1207 // ----------------------------------------------------------------------------
1209 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1211 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
1213 if (file
!= wxT(""))
1214 // Don't know what the correct cast should be, but it doesn't
1215 // compile in BC++/16-bit without this cast.
1216 #if !defined(__WIN32__)
1217 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
1219 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
1222 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
1225 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
1228 buf
.Printf(wxT("%.4f"), value
);
1230 return wxWriteResource(section
, entry
, buf
, file
);
1233 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1236 buf
.Printf(wxT("%ld"), value
);
1238 return wxWriteResource(section
, entry
, buf
, file
);
1241 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1244 buf
.Printf(wxT("%d"), value
);
1246 return wxWriteResource(section
, entry
, buf
, file
);
1249 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1251 static const wxChar defunkt
[] = wxT("$$default");
1252 if (file
!= wxT(""))
1254 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1255 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1256 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1261 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1262 (LPTSTR
)wxBuffer
, 1000);
1263 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1266 if (*value
) delete[] (*value
);
1267 *value
= copystring(wxBuffer
);
1271 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1274 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1277 *value
= (float)wxStrtod(s
, NULL
);
1284 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1287 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1290 *value
= wxStrtol(s
, NULL
, 10);
1297 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1300 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1303 *value
= (int)wxStrtol(s
, NULL
, 10);
1309 #endif // wxUSE_RESOURCES
1311 // ---------------------------------------------------------------------------
1312 // helper functions for showing a "busy" cursor
1313 // ---------------------------------------------------------------------------
1315 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1316 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1317 static int gs_wxBusyCursorCount
= 0;
1319 #ifdef __DIGITALMARS__
1320 extern "C" HCURSOR
wxGetCurrentBusyCursor()
1322 extern HCURSOR
wxGetCurrentBusyCursor()
1325 return gs_wxBusyCursor
;
1328 // Set the cursor to the busy cursor for all windows
1329 void wxBeginBusyCursor(wxCursor
*cursor
)
1331 if ( gs_wxBusyCursorCount
++ == 0 )
1333 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1334 #ifndef __WXMICROWIN__
1335 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1338 //else: nothing to do, already set
1341 // Restore cursor to normal
1342 void wxEndBusyCursor()
1344 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1345 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1347 if ( --gs_wxBusyCursorCount
== 0 )
1349 #ifndef __WXMICROWIN__
1350 ::SetCursor(gs_wxBusyCursorOld
);
1352 gs_wxBusyCursorOld
= 0;
1356 // TRUE if we're between the above two calls
1359 return gs_wxBusyCursorCount
> 0;
1362 // Check whether this window wants to process messages, e.g. Stop button
1363 // in long calculations.
1364 bool wxCheckForInterrupt(wxWindow
*wnd
)
1366 wxCHECK( wnd
, FALSE
);
1369 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1371 ::TranslateMessage(&msg
);
1372 ::DispatchMessage(&msg
);
1378 // MSW only: get user-defined resource from the .res file.
1379 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1381 #ifndef __WXMICROWIN__
1382 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1384 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1385 if ( hResource
== 0 )
1388 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1392 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1396 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1397 // so we need to find the length of the resource.
1398 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1399 wxChar
*s
= new wxChar
[len
+1];
1400 wxStrncpy(s
,theText
,len
);
1403 // wxChar *s = copystring(theText);
1405 // Obsolete in WIN32
1407 UnlockResource(hData
);
1411 // GlobalFree(hData);
1415 #endif // __WXMICROWIN__
1417 // ----------------------------------------------------------------------------
1419 // ----------------------------------------------------------------------------
1421 // See also the wxGetMousePosition in window.cpp
1422 // Deprecated: use wxPoint wxGetMousePosition() instead
1423 void wxGetMousePosition( int* x
, int* y
)
1426 GetCursorPos( & pt
);
1431 // Return TRUE if we have a colour display
1432 bool wxColourDisplay()
1434 #ifdef __WXMICROWIN__
1438 // this function is called from wxDC ctor so it is called a *lot* of times
1439 // hence we optimize it a bit but doign the check only once
1441 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1443 static int s_isColour
= -1;
1445 if ( s_isColour
== -1 )
1448 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1450 s_isColour
= (noCols
== -1) || (noCols
> 2);
1453 return s_isColour
!= 0;
1457 // Returns depth of screen
1458 int wxDisplayDepth()
1461 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1464 // Get size of display
1465 void wxDisplaySize(int *width
, int *height
)
1467 #ifdef __WXMICROWIN__
1469 HWND hWnd
= GetDesktopWindow();
1470 ::GetWindowRect(hWnd
, & rect
);
1473 *width
= rect
.right
- rect
.left
;
1475 *height
= rect
.bottom
- rect
.top
;
1476 #else // !__WXMICROWIN__
1480 *width
= ::GetDeviceCaps(dc
, HORZRES
);
1482 *height
= ::GetDeviceCaps(dc
, VERTRES
);
1483 #endif // __WXMICROWIN__/!__WXMICROWIN__
1486 void wxDisplaySizeMM(int *width
, int *height
)
1488 #ifdef __WXMICROWIN__
1498 *width
= ::GetDeviceCaps(dc
, HORZSIZE
);
1500 *height
= ::GetDeviceCaps(dc
, VERTSIZE
);
1504 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1506 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1508 wxDisplaySize(width
, height
);
1510 // Determine the desktop dimensions minus the taskbar and any other
1511 // special decorations...
1514 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1517 if (width
) *width
= r
.right
- r
.left
;
1518 if (height
) *height
= r
.bottom
- r
.top
;
1522 // ---------------------------------------------------------------------------
1523 // window information functions
1524 // ---------------------------------------------------------------------------
1526 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1532 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1533 ::GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1534 str
.UngetWriteBuf();
1540 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1545 #ifndef __WXMICROWIN__
1548 int len
= 256; // some starting value
1552 int count
= ::GetClassName((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1554 str
.UngetWriteBuf();
1557 // the class name might have been truncated, retry with larger
1567 #endif // !__WXMICROWIN__
1572 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1575 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1577 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1581 // ----------------------------------------------------------------------------
1583 // ----------------------------------------------------------------------------
1585 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1589 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1590 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1591 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1592 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1594 *x
*= (iWidthMM
* 100);
1596 *y
*= (iHeightMM
* 100);
1600 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1604 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1605 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1606 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1607 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1610 *x
/= (iWidthMM
* 100);
1612 *y
/= (iHeightMM
* 100);
1617 #ifdef __WXMICROWIN__
1618 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1621 if (majorVsn
) *majorVsn
= 0;
1622 if (minorVsn
) *minorVsn
= 0;
1625 #endif // __WXMICROWIN__
1627 // ----------------------------------------------------------------------------
1628 // Win32 codepage conversion functions
1629 // ----------------------------------------------------------------------------
1631 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1633 // wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1634 #if wxUSE_GUI && !defined(__WXUNIVERSAL__)
1636 #include "wx/fontmap.h"
1638 // VZ: the new version of wxCharsetToCodepage() is more politically correct
1639 // and should work on other Windows versions as well but the old version is
1640 // still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
1642 extern long wxEncodingToCodepage(wxFontEncoding encoding
)
1644 // translate encoding into the Windows CHARSET
1645 wxNativeEncodingInfo natveEncInfo
;
1646 if ( !wxGetNativeFontEncoding(encoding
, &natveEncInfo
) )
1649 // translate CHARSET to code page
1650 CHARSETINFO csetInfo
;
1651 if ( !::TranslateCharsetInfo((DWORD
*)(DWORD
)natveEncInfo
.charset
,
1655 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1660 return csetInfo
.ciACP
;
1665 extern long wxCharsetToCodepage(const wxChar
*name
)
1667 // first get the font encoding for this charset
1671 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(name
, FALSE
);
1672 if ( enc
== wxFONTENCODING_SYSTEM
)
1675 // the use the helper function
1676 return wxEncodingToCodepage(enc
);
1679 #endif // wxUSE_FONTMAP
1683 // include old wxCharsetToCodepage() by OK if needed
1684 #if !wxUSE_GUI || !wxUSE_FONTMAP
1686 #include "wx/msw/registry.h"
1688 // this should work if Internet Exploiter is installed
1689 extern long wxCharsetToCodepage(const wxChar
*name
)
1698 wxString
path(wxT("MIME\\Database\\Charset\\"));
1700 wxRegKey
key(wxRegKey::HKCR
, path
);
1702 if (!key
.Exists()) break;
1704 // two cases: either there's an AliasForCharset string,
1705 // or there are Codepage and InternetEncoding dwords.
1706 // The InternetEncoding gives us the actual encoding,
1707 // the Codepage just says which Windows character set to
1708 // use when displaying the data.
1709 if (key
.HasValue(wxT("InternetEncoding")) &&
1710 key
.QueryValue(wxT("InternetEncoding"), &CP
)) break;
1712 // no encoding, see if it's an alias
1713 if (!key
.HasValue(wxT("AliasForCharset")) ||
1714 !key
.QueryValue(wxT("AliasForCharset"), cn
)) break;
1720 #endif // !wxUSE_GUI || !wxUSE_FONTMAP