1 ///////////////////////////////////////////////////////////////////////////// 
   3 // Purpose:     Various utilities 
   4 // Author:      Julian Smart 
   8 // Copyright:   (c) Julian Smart 
   9 // Licence:     wxWindows licence 
  10 ///////////////////////////////////////////////////////////////////////////// 
  12 // ============================================================================ 
  14 // ============================================================================ 
  16 // ---------------------------------------------------------------------------- 
  18 // ---------------------------------------------------------------------------- 
  20 // For compilers that support precompilation, includes "wx.h". 
  21 #include "wx/wxprec.h" 
  34 #include "wx/apptrait.h" 
  35 #include "wx/dynload.h" 
  37 #include "wx/confbase.h"        // for wxExpandEnvVars() 
  39 #include "wx/msw/private.h"     // includes <windows.h> 
  40 #include "wx/msw/missing.h"     // CHARSET_HANGUL 
  42 #if defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) \ 
  43     || defined(__CYGWIN32__) 
  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__) && !defined(__WXWINCE__) 
  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__) && !defined(__WXWINCE__) 
  92     #if !(defined(_MSC_VER) && (_MSC_VER > 800)) 
  97 // For wxKillAllChildren 
 100 // ---------------------------------------------------------------------------- 
 102 // ---------------------------------------------------------------------------- 
 104 // In the WIN.INI file 
 105 static const wxChar WX_SECTION
[] = wxT("wxWindows"); 
 106 static const wxChar eUSERNAME
[]  = wxT("UserName"); 
 108 // ============================================================================ 
 110 // ============================================================================ 
 112 // ---------------------------------------------------------------------------- 
 113 // get host name and related 
 114 // ---------------------------------------------------------------------------- 
 116 // Get hostname only (without domain name) 
 117 bool wxGetHostName(wxChar 
*buf
, int maxSize
) 
 119 #if defined(__WXWINCE__) 
 121 #elif defined(__WIN32__) && !defined(__WXMICROWIN__) 
 122     DWORD nSize 
= maxSize
; 
 123     if ( !::GetComputerName(buf
, &nSize
) ) 
 125         wxLogLastError(wxT("GetComputerName")); 
 133     const wxChar 
*default_host 
= wxT("noname"); 
 135     if ((sysname 
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) { 
 136         GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize 
- 1); 
 138         wxStrncpy(buf
, sysname
, maxSize 
- 1); 
 139     buf
[maxSize
] = wxT('\0'); 
 140     return *buf 
? true : false; 
 144 // get full hostname (with domain name if possible) 
 145 bool wxGetFullHostName(wxChar 
*buf
, int maxSize
) 
 147 #if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER 
 148     // TODO should use GetComputerNameEx() when available 
 150     // we don't want to always link with Winsock DLL as we might not use it at 
 151     // all, so load it dynamically here if needed (and don't complain if it is 
 152     // missing, we handle this) 
 155     wxDynamicLibrary 
dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM
); 
 156     if ( dllWinsock
.IsLoaded() ) 
 158         typedef int (PASCAL 
*WSAStartup_t
)(WORD
, WSADATA 
*); 
 159         typedef int (PASCAL 
*gethostname_t
)(char *, int); 
 160         typedef hostent
* (PASCAL 
*gethostbyname_t
)(const char *); 
 161         typedef hostent
* (PASCAL 
*gethostbyaddr_t
)(const char *, int , int); 
 162         typedef int (PASCAL 
*WSACleanup_t
)(void); 
 164         #define LOAD_WINSOCK_FUNC(func)                                       \ 
 166                 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func)) 
 168         LOAD_WINSOCK_FUNC(WSAStartup
); 
 171         if ( pfnWSAStartup 
&& pfnWSAStartup(MAKEWORD(1, 1), &wsa
) == 0 ) 
 173             LOAD_WINSOCK_FUNC(gethostname
); 
 176             if ( pfngethostname 
) 
 179                 if ( pfngethostname(bufA
, WXSIZEOF(bufA
)) == 0 ) 
 181                     // gethostname() won't usually include the DNS domain name, 
 182                     // for this we need to work a bit more 
 183                     if ( !strchr(bufA
, '.') ) 
 185                         LOAD_WINSOCK_FUNC(gethostbyname
); 
 187                         struct hostent 
*pHostEnt 
= pfngethostbyname
 
 188                                                     ? pfngethostbyname(bufA
) 
 193                             // Windows will use DNS internally now 
 194                             LOAD_WINSOCK_FUNC(gethostbyaddr
); 
 196                             pHostEnt 
= pfngethostbyaddr
 
 197                                         ? pfngethostbyaddr(pHostEnt
->h_addr
, 
 204                             host 
= wxString::FromAscii(pHostEnt
->h_name
); 
 210             LOAD_WINSOCK_FUNC(WSACleanup
); 
 217                 wxStrncpy(buf
, host
, maxSize
); 
 223 #endif // !__WXMICROWIN__ 
 225     return wxGetHostName(buf
, maxSize
); 
 228 // Get user ID e.g. jacs 
 229 bool wxGetUserId(wxChar 
*buf
, int maxSize
) 
 231 #if defined(__WXWINCE__) 
 233 #elif defined(__WIN32__) && !defined(__WXMICROWIN__) 
 234     DWORD nSize 
= maxSize
; 
 235     if ( ::GetUserName(buf
, &nSize
) == 0 ) 
 237         // actually, it does happen on Win9x if the user didn't log on 
 238         DWORD res 
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
); 
 247 #else   // __WXMICROWIN__ 
 249     const wxChar 
*default_id 
= wxT("anonymous"); 
 251     // Can't assume we have NIS (PC-NFS) or some other ID daemon 
 253     if (  (user 
= wxGetenv(wxT("USER"))) == NULL 
&& 
 254             (user 
= wxGetenv(wxT("LOGNAME"))) == NULL 
) 
 256         // Use wxWidgets configuration data (comming soon) 
 257         GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize 
- 1); 
 261         wxStrncpy(buf
, user
, maxSize 
- 1); 
 264     return *buf 
? true : false; 
 268 // Get user name e.g. Julian Smart 
 269 bool wxGetUserName(wxChar 
*buf
, int maxSize
) 
 271 #if defined(__WXWINCE__) 
 273 #elif defined(USE_NET_API) 
 274     CHAR szUserName
[256]; 
 275     if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) ) 
 278     // TODO how to get the domain name? 
 281     // the code is based on the MSDN example (also see KB article Q119670) 
 282     WCHAR wszUserName
[256];          // Unicode user name 
 283     WCHAR wszDomain
[256]; 
 286     USER_INFO_2 
*ui2
;         // User structure 
 288     // Convert ANSI user name and domain to Unicode 
 289     MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1, 
 290             wszUserName
, WXSIZEOF(wszUserName
) ); 
 291     MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1, 
 292             wszDomain
, WXSIZEOF(wszDomain
) ); 
 294     // Get the computer name of a DC for the domain. 
 295     if ( NetGetDCName( NULL
, wszDomain
, &ComputerName 
) != NERR_Success 
) 
 297         wxLogError(wxT("Can not find domain controller")); 
 302     // Look up the user on the DC 
 303     NET_API_STATUS status 
= NetUserGetInfo( (LPWSTR
)ComputerName
, 
 304             (LPWSTR
)&wszUserName
, 
 305             2, // level - we want USER_INFO_2 
 313         case NERR_InvalidComputer
: 
 314             wxLogError(wxT("Invalid domain controller name.")); 
 318         case NERR_UserNotFound
: 
 319             wxLogError(wxT("Invalid user name '%s'."), szUserName
); 
 324             wxLogSysError(wxT("Can't get information about user")); 
 329     // Convert the Unicode full name to ANSI 
 330     WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1, 
 331             buf
, maxSize
, NULL
, NULL 
); 
 336     wxLogError(wxT("Couldn't look up full user name.")); 
 339 #else  // !USE_NET_API 
 340     // Could use NIS, MS-Mail or other site specific programs 
 341     // Use wxWidgets configuration data 
 342     bool ok 
= GetProfileString(WX_SECTION
, eUSERNAME
, wxEmptyString
, buf
, maxSize 
- 1) != 0; 
 345         ok 
= wxGetUserId(buf
, maxSize
); 
 350         wxStrncpy(buf
, wxT("Unknown User"), maxSize
); 
 357 const wxChar
* wxGetHomeDir(wxString 
*pstr
) 
 359     wxString
& strDir 
= *pstr
; 
 361     // first branch is for Cygwin 
 362 #if defined(__UNIX__) 
 363     const wxChar 
*szHome 
= wxGetenv("HOME"); 
 364     if ( szHome 
== NULL 
) { 
 366       wxLogWarning(_("can't find user's HOME, using current directory.")); 
 372     // add a trailing slash if needed 
 373     if ( strDir
.Last() != wxT('/') ) 
 377         // Cygwin returns unix type path but that does not work well 
 378         static wxChar windowsPath
[MAX_PATH
]; 
 379         cygwin_conv_to_full_win32_path(strDir
, windowsPath
); 
 380         strDir 
= windowsPath
; 
 382 #elif defined(__WXWINCE__) 
 387     // If we have a valid HOME directory, as is used on many machines that 
 388     // have unix utilities on them, we should use that. 
 389     const wxChar 
*szHome 
= wxGetenv(wxT("HOME")); 
 391     if ( szHome 
!= NULL 
) 
 395     else // no HOME, try HOMEDRIVE/PATH 
 397         szHome 
= wxGetenv(wxT("HOMEDRIVE")); 
 398         if ( szHome 
!= NULL 
) 
 400         szHome 
= wxGetenv(wxT("HOMEPATH")); 
 402         if ( szHome 
!= NULL 
) 
 406             // the idea is that under NT these variables have default values 
 407             // of "%systemdrive%:" and "\\". As we don't want to create our 
 408             // config files in the root directory of the system drive, we will 
 409             // create it in our program's dir. However, if the user took care 
 410             // to set HOMEPATH to something other than "\\", we suppose that he 
 411             // knows what he is doing and use the supplied value. 
 412             if ( wxStrcmp(szHome
, wxT("\\")) == 0 ) 
 417     if ( strDir
.empty() ) 
 419         // If we have a valid USERPROFILE directory, as is the case in 
 420         // Windows NT, 2000 and XP, we should use that as our home directory. 
 421         szHome 
= wxGetenv(wxT("USERPROFILE")); 
 423         if ( szHome 
!= NULL 
) 
 427     if ( !strDir
.empty() ) 
 429         // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the 
 430         // value once again, it shouldn't hurt anyhow 
 431         strDir 
= wxExpandEnvVars(strDir
); 
 433     else // fall back to the program directory 
 435         // extract the directory component of the program file name 
 436         wxSplitPath(wxGetFullModuleName(), &strDir
, NULL
, NULL
); 
 440     return strDir
.c_str(); 
 443 wxChar 
*wxGetUserHome(const wxString
& WXUNUSED(user
)) 
 445     // VZ: the old code here never worked for user != "" anyhow! Moreover, it 
 446     //     returned sometimes a malloc()'d pointer, sometimes a pointer to a 
 447     //     static buffer and sometimes I don't even know what. 
 448     static wxString s_home
; 
 450     return (wxChar 
*)wxGetHomeDir(&s_home
); 
 453 bool wxDirExists(const wxString
& dir
) 
 455 #ifdef __WXMICROWIN__ 
 456     return wxPathExist(dir
); 
 457 #elif defined(__WIN32__) 
 458     DWORD attribs 
= GetFileAttributes(dir
); 
 459     return ((attribs 
!= (DWORD
)-1) && (attribs 
& FILE_ATTRIBUTE_DIRECTORY
)); 
 460 #endif // Win32/__WXMICROWIN__ 
 463 bool wxGetDiskSpace(const wxString
& path
, wxLongLong 
*pTotal
, wxLongLong 
*pFree
) 
 471 // old w32api don't have ULARGE_INTEGER 
 472 #if defined(__WIN32__) && \ 
 473     (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 )) 
 474     // GetDiskFreeSpaceEx() is not available under original Win95, check for 
 476     typedef BOOL (WINAPI 
*GetDiskFreeSpaceEx_t
)(LPCTSTR
, 
 482         pGetDiskFreeSpaceEx 
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
 
 484                                 ::GetModuleHandle(_T("kernel32.dll")), 
 486                                 "GetDiskFreeSpaceExW" 
 488                                 "GetDiskFreeSpaceExA" 
 492     if ( pGetDiskFreeSpaceEx 
) 
 494         ULARGE_INTEGER bytesFree
, bytesTotal
; 
 496         // may pass the path as is, GetDiskFreeSpaceEx() is smart enough 
 497         if ( !pGetDiskFreeSpaceEx(path
, 
 502             wxLogLastError(_T("GetDiskFreeSpaceEx")); 
 507         // ULARGE_INTEGER is a union of a 64 bit value and a struct containing 
 508         // two 32 bit fields which may be or may be not named - try to make it 
 509         // compile in all cases 
 510 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT) 
 517             *pTotal 
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
); 
 522             *pFree 
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
); 
 528         // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx() 
 529         // should be used instead - but if it's not available, fall back on 
 530         // GetDiskFreeSpace() nevertheless... 
 532         DWORD lSectorsPerCluster
, 
 534               lNumberOfFreeClusters
, 
 535               lTotalNumberOfClusters
; 
 537         // FIXME: this is wrong, we should extract the root drive from path 
 538         //        instead, but this is the job for wxFileName... 
 539         if ( !::GetDiskFreeSpace(path
, 
 542                                  &lNumberOfFreeClusters
, 
 543                                  &lTotalNumberOfClusters
) ) 
 545             wxLogLastError(_T("GetDiskFreeSpace")); 
 550         wxLongLong lBytesPerCluster 
= lSectorsPerCluster
; 
 551         lBytesPerCluster 
*= lBytesPerSector
; 
 555             *pTotal 
= lBytesPerCluster
; 
 556             *pTotal 
*= lTotalNumberOfClusters
; 
 561             *pFree 
= lBytesPerCluster
; 
 562             *pFree 
*= lNumberOfFreeClusters
; 
 571 // ---------------------------------------------------------------------------- 
 573 // ---------------------------------------------------------------------------- 
 575 bool wxGetEnv(const wxString
& var
, wxString 
*value
) 
 580     // first get the size of the buffer 
 581     DWORD dwRet 
= ::GetEnvironmentVariable(var
, NULL
, 0); 
 584         // this means that there is no such variable 
 590         (void)::GetEnvironmentVariable(var
, wxStringBuffer(*value
, dwRet
), 
 598 bool wxSetEnv(const wxString
& var
, const wxChar 
*value
) 
 600     // some compilers have putenv() or _putenv() or _wputenv() but it's better 
 601     // to always use Win32 function directly instead of dealing with them 
 602 #if defined(__WIN32__) && !defined(__WXWINCE__) 
 603     if ( !::SetEnvironmentVariable(var
, value
) ) 
 605         wxLogLastError(_T("SetEnvironmentVariable")); 
 611 #else // no way to set env vars 
 616 // ---------------------------------------------------------------------------- 
 617 // process management 
 618 // ---------------------------------------------------------------------------- 
 620 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc() 
 621 struct wxFindByPidParams
 
 623     wxFindByPidParams() { hwnd 
= 0; pid 
= 0; } 
 625     // the HWND used to return the result 
 628     // the PID we're looking from 
 631     DECLARE_NO_COPY_CLASS(wxFindByPidParams
) 
 634 // wxKill helper: EnumWindows() callback which is used to find the first (top 
 635 // level) window belonging to the given process 
 636 BOOL CALLBACK 
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
) 
 639     (void)::GetWindowThreadProcessId(hwnd
, &pid
); 
 641     wxFindByPidParams 
*params 
= (wxFindByPidParams 
*)lParam
; 
 642     if ( pid 
== params
->pid 
) 
 644         // remember the window we found 
 647         // return FALSE to stop the enumeration 
 651     // continue enumeration 
 655 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError 
*krc
); 
 657 int wxKill(long pid
, wxSignal sig
, wxKillError 
*krc
, int flags
) 
 659     if (flags 
& wxKILL_CHILDREN
) 
 660         wxKillAllChildren(pid
, sig
, krc
); 
 662     // get the process handle to operate on 
 663     HANDLE hProcess 
= ::OpenProcess(SYNCHRONIZE 
| 
 665                                     PROCESS_QUERY_INFORMATION
, 
 666                                     FALSE
, // not inheritable 
 668     if ( hProcess 
== NULL 
) 
 672             if ( ::GetLastError() == ERROR_ACCESS_DENIED 
) 
 674                 *krc 
= wxKILL_ACCESS_DENIED
; 
 678                 *krc 
= wxKILL_NO_PROCESS
; 
 689             // kill the process forcefully returning -1 as error code 
 690             if ( !::TerminateProcess(hProcess
, (UINT
)-1) ) 
 692                 wxLogSysError(_("Failed to kill process %d"), pid
); 
 696                     // this is not supposed to happen if we could open the 
 706             // do nothing, we just want to test for process existence 
 710             // any other signal means "terminate" 
 712                 wxFindByPidParams params
; 
 713                 params
.pid 
= (DWORD
)pid
; 
 715                 // EnumWindows() has nice semantics: it returns 0 if it found 
 716                 // something or if an error occured and non zero if it 
 717                 // enumerated all the window 
 718                 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) ) 
 720                     // did we find any window? 
 723                         // tell the app to close 
 725                         // NB: this is the harshest way, the app won't have 
 726                         //     opportunity to save any files, for example, but 
 727                         //     this is probably what we want here. If not we 
 728                         //     can also use SendMesageTimeout(WM_CLOSE) 
 729                         if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) ) 
 731                             wxLogLastError(_T("PostMessage(WM_QUIT)")); 
 734                     else // it was an error then 
 736                         wxLogLastError(_T("EnumWindows")); 
 741                 else // no windows for this PID 
 758         // as we wait for a short time, we can use just WaitForSingleObject() 
 759         // and not MsgWaitForMultipleObjects() 
 760         switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) ) 
 763                 // process terminated 
 764                 if ( !::GetExitCodeProcess(hProcess
, &rc
) ) 
 766                     wxLogLastError(_T("GetExitCodeProcess")); 
 771                 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") ); 
 775                 wxLogLastError(_T("WaitForSingleObject")); 
 790         // just to suppress the warnings about uninitialized variable 
 794     ::CloseHandle(hProcess
); 
 796     // the return code is the same as from Unix kill(): 0 if killed 
 797     // successfully or -1 on error 
 799     // be careful to interpret rc correctly: for wxSIGNONE we return success if 
 800     // the process exists, for all the other sig values -- if it doesn't 
 802             ((sig 
== wxSIGNONE
) == (rc 
== STILL_ACTIVE
)) ) 
 816 HANDLE (WINAPI 
*lpfCreateToolhelp32Snapshot
)(DWORD
,DWORD
) ; 
 817 BOOL (WINAPI 
*lpfProcess32First
)(HANDLE
,LPPROCESSENTRY32
) ; 
 818 BOOL (WINAPI 
*lpfProcess32Next
)(HANDLE
,LPPROCESSENTRY32
) ; 
 820 static void InitToolHelp32() 
 822     static bool s_initToolHelpDone 
= false; 
 824     if (s_initToolHelpDone
) 
 827     s_initToolHelpDone 
= true; 
 829     lpfCreateToolhelp32Snapshot 
= NULL
; 
 830     lpfProcess32First 
= NULL
; 
 831     lpfProcess32Next 
= NULL
; 
 833     HINSTANCE hInstLib 
= LoadLibraryA( "Kernel32.DLL" ) ; 
 834     if( hInstLib 
== NULL 
) 
 837     // Get procedure addresses. 
 838     // We are linking to these functions of Kernel32 
 839     // explicitly, because otherwise a module using 
 840     // this code would fail to load under Windows NT, 
 841     // which does not have the Toolhelp32 
 842     // functions in the Kernel 32. 
 843     lpfCreateToolhelp32Snapshot
= 
 844         (HANDLE(WINAPI 
*)(DWORD
,DWORD
)) 
 845         GetProcAddress( hInstLib
, 
 846         "CreateToolhelp32Snapshot" ) ; 
 849         (BOOL(WINAPI 
*)(HANDLE
,LPPROCESSENTRY32
)) 
 850         GetProcAddress( hInstLib
, "Process32First" ) ; 
 853         (BOOL(WINAPI 
*)(HANDLE
,LPPROCESSENTRY32
)) 
 854         GetProcAddress( hInstLib
, "Process32Next" ) ; 
 856     FreeLibrary( hInstLib 
) ; 
 860 int wxKillAllChildren(long pid
, wxSignal sig
, wxKillError 
*krc
) 
 867     // If not implemented for this platform (e.g. NT 4.0), silently ignore 
 868     if (!lpfCreateToolhelp32Snapshot 
|| !lpfProcess32First 
|| !lpfProcess32Next
) 
 871     // Take a snapshot of all processes in the system. 
 872     HANDLE hProcessSnap 
= lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0); 
 873     if (hProcessSnap 
== INVALID_HANDLE_VALUE
) { 
 879     //Fill in the size of the structure before using it. 
 880     PROCESSENTRY32 pe 
= {0}; 
 881     pe
.dwSize 
= sizeof(PROCESSENTRY32
); 
 883     // Walk the snapshot of the processes, and for each process, 
 884     // kill it if its parent is pid. 
 885     if (!lpfProcess32First(hProcessSnap
, &pe
)) { 
 886         // Can't get first process. 
 889         CloseHandle (hProcessSnap
); 
 894         if (pe
.th32ParentProcessID 
== (DWORD
) pid
) { 
 895             if (wxKill(pe
.th32ProcessID
, sig
, krc
)) 
 898     } while (lpfProcess32Next (hProcessSnap
, &pe
)); 
 904 // Execute a program in an Interactive Shell 
 905 bool wxShell(const wxString
& command
) 
 912     wxChar 
*shell 
= wxGetenv(wxT("COMSPEC")); 
 914         shell 
= (wxChar
*) wxT("\\COMMAND.COM"); 
 923         // pass the command to execute to the command processor 
 924         cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str()); 
 928     return wxExecute(cmd
, wxEXEC_SYNC
) == 0; 
 931 // Shutdown or reboot the PC 
 932 bool wxShutdown(wxShutdownFlags wFlags
) 
 936 #elif defined(__WIN32__) 
 939     if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_NT 
) // if is NT or 2K 
 941         // Get a token for this process. 
 943         bOK 
= ::OpenProcessToken(GetCurrentProcess(), 
 944                                  TOKEN_ADJUST_PRIVILEGES 
| TOKEN_QUERY
, 
 948             TOKEN_PRIVILEGES tkp
; 
 950             // Get the LUID for the shutdown privilege. 
 951             ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, 
 952                                    &tkp
.Privileges
[0].Luid
); 
 954             tkp
.PrivilegeCount 
= 1;  // one privilege to set 
 955             tkp
.Privileges
[0].Attributes 
= SE_PRIVILEGE_ENABLED
; 
 957             // Get the shutdown privilege for this process. 
 958             ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0, 
 959                                     (PTOKEN_PRIVILEGES
)NULL
, 0); 
 961             // Cannot test the return value of AdjustTokenPrivileges. 
 962             bOK 
= ::GetLastError() == ERROR_SUCCESS
; 
 968         UINT flags 
= EWX_SHUTDOWN 
| EWX_FORCE
; 
 971             case wxSHUTDOWN_POWEROFF
: 
 972                 flags 
|= EWX_POWEROFF
; 
 975             case wxSHUTDOWN_REBOOT
: 
 980                 wxFAIL_MSG( _T("unknown wxShutdown() flag") ); 
 984         bOK 
= ::ExitWindowsEx(flags
, 0) != 0; 
 991 // ---------------------------------------------------------------------------- 
 993 // ---------------------------------------------------------------------------- 
 995 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX) 
 996 long wxGetFreeMemory() 
 998 #if defined(__WIN32__) && !defined(__BORLANDC__) 
 999     MEMORYSTATUS memStatus
; 
1000     memStatus
.dwLength 
= sizeof(MEMORYSTATUS
); 
1001     GlobalMemoryStatus(&memStatus
); 
1002     return memStatus
.dwAvailPhys
; 
1004     return (long)GetFreeSpace(0); 
1008 unsigned long wxGetProcessId() 
1010     return ::GetCurrentProcessId(); 
1016     ::MessageBeep((UINT
)-1);        // default sound 
1019 wxString 
wxGetOsDescription() 
1026     info
.dwOSVersionInfoSize 
= sizeof(OSVERSIONINFO
); 
1027     if ( ::GetVersionEx(&info
) ) 
1029         switch ( info
.dwPlatformId 
) 
1031             case VER_PLATFORM_WIN32s
: 
1032                 str 
= _("Win32s on Windows 3.1"); 
1035             case VER_PLATFORM_WIN32_WINDOWS
: 
1036                 switch (info
.dwMinorVersion
) 
1039                         if ( info
.szCSDVersion
[1] == 'B' || 
1040                              info
.szCSDVersion
[1] == 'C' ) 
1042                             str 
= _("Windows 95 OSR2"); 
1046                             str 
= _("Windows 95"); 
1050                         if ( info
.szCSDVersion
[1] == 'B' || 
1051                              info
.szCSDVersion
[1] == 'C' ) 
1053                             str 
= _("Windows 98 SE"); 
1057                             str 
= _("Windows 98"); 
1061                         str 
= _("Windows ME"); 
1064                         str
.Printf(_("Windows 9x (%d.%d)"), 
1065                                    info
.dwMajorVersion
, 
1066                                    info
.dwMinorVersion
); 
1069                 if ( !wxIsEmpty(info
.szCSDVersion
) ) 
1071                     str 
<< _T(" (") << info
.szCSDVersion 
<< _T(')'); 
1075             case VER_PLATFORM_WIN32_NT
: 
1076                 if ( info
.dwMajorVersion 
== 5 ) 
1078                     switch ( info
.dwMinorVersion 
) 
1081                             str
.Printf(_("Windows 2000 (build %lu"), 
1082                                        info
.dwBuildNumber
); 
1085                             str
.Printf(_("Windows XP (build %lu"), 
1086                                        info
.dwBuildNumber
); 
1089                             str
.Printf(_("Windows Server 2003 (build %lu"), 
1090                                        info
.dwBuildNumber
); 
1094                 if ( wxIsEmpty(str
) ) 
1096                     str
.Printf(_("Windows NT %lu.%lu (build %lu"), 
1097                            info
.dwMajorVersion
, 
1098                            info
.dwMinorVersion
, 
1099                            info
.dwBuildNumber
); 
1101                 if ( !wxIsEmpty(info
.szCSDVersion
) ) 
1103                     str 
<< _T(", ") << info
.szCSDVersion
; 
1111         wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen 
1117 wxToolkitInfo
& wxAppTraits::GetToolkitInfo() 
1119     // cache the version info, it's not going to change 
1121     // NB: this is MT-safe, we may use these static vars from different threads 
1122     //     but as they always have the same value it doesn't matter 
1123     static int s_ver 
= -1, 
1133         info
.dwOSVersionInfoSize 
= sizeof(OSVERSIONINFO
); 
1134         if ( ::GetVersionEx(&info
) ) 
1136             s_major 
= info
.dwMajorVersion
; 
1137             s_minor 
= info
.dwMinorVersion
; 
1139             switch ( info
.dwPlatformId 
) 
1141                 case VER_PLATFORM_WIN32s
: 
1145                 case VER_PLATFORM_WIN32_WINDOWS
: 
1149                 case VER_PLATFORM_WIN32_NT
: 
1150                     s_ver 
= wxWINDOWS_NT
; 
1153                 case VER_PLATFORM_WIN32_CE
: 
1154                     s_ver 
= wxWINDOWS_CE
; 
1161     static wxToolkitInfo info
; 
1162     info
.versionMajor 
= s_major
; 
1163     info
.versionMinor 
= s_minor
; 
1165     info
.name 
= _T("wxBase"); 
1169 // ---------------------------------------------------------------------------- 
1171 // ---------------------------------------------------------------------------- 
1173 void wxMilliSleep(unsigned long milliseconds
) 
1175     ::Sleep(milliseconds
); 
1178 void wxMicroSleep(unsigned long microseconds
) 
1180     wxMilliSleep(microseconds
/1000); 
1183 void wxSleep(int nSecs
) 
1185     wxMilliSleep(1000*nSecs
); 
1188 // ---------------------------------------------------------------------------- 
1189 // font encoding <-> Win32 codepage conversion functions 
1190 // ---------------------------------------------------------------------------- 
1192 extern WXDLLIMPEXP_BASE 
long wxEncodingToCharset(wxFontEncoding encoding
) 
1196         // although this function is supposed to return an exact match, do do 
1197         // some mappings here for the most common case of "standard" encoding 
1198         case wxFONTENCODING_SYSTEM
: 
1199             return DEFAULT_CHARSET
; 
1201         case wxFONTENCODING_ISO8859_1
: 
1202         case wxFONTENCODING_ISO8859_15
: 
1203         case wxFONTENCODING_CP1252
: 
1204             return ANSI_CHARSET
; 
1206 #if !defined(__WXMICROWIN__) 
1207         // The following four fonts are multi-byte charsets 
1208         case wxFONTENCODING_CP932
: 
1209             return SHIFTJIS_CHARSET
; 
1211         case wxFONTENCODING_CP936
: 
1212             return GB2312_CHARSET
; 
1214         case wxFONTENCODING_CP949
: 
1215             return HANGUL_CHARSET
; 
1217         case wxFONTENCODING_CP950
: 
1218             return CHINESEBIG5_CHARSET
; 
1220         // The rest are single byte encodings 
1221         case wxFONTENCODING_CP1250
: 
1222             return EASTEUROPE_CHARSET
; 
1224         case wxFONTENCODING_CP1251
: 
1225             return RUSSIAN_CHARSET
; 
1227         case wxFONTENCODING_CP1253
: 
1228             return GREEK_CHARSET
; 
1230         case wxFONTENCODING_CP1254
: 
1231             return TURKISH_CHARSET
; 
1233         case wxFONTENCODING_CP1255
: 
1234             return HEBREW_CHARSET
; 
1236         case wxFONTENCODING_CP1256
: 
1237             return ARABIC_CHARSET
; 
1239         case wxFONTENCODING_CP1257
: 
1240             return BALTIC_CHARSET
; 
1242         case wxFONTENCODING_CP874
: 
1243             return THAI_CHARSET
; 
1244 #endif // !__WXMICROWIN__ 
1246         case wxFONTENCODING_CP437
: 
1250             // no way to translate this encoding into a Windows charset 
1255 // we have 2 versions of wxCharsetToCodepage(): the old one which directly 
1256 // looks up the vlaues in the registry and the new one which is more 
1257 // politically correct and has more chances to work on other Windows versions 
1258 // as well but the old version is still needed for !wxUSE_FONTMAP case 
1261 #include "wx/fontmap.h" 
1263 extern WXDLLIMPEXP_BASE 
long wxEncodingToCodepage(wxFontEncoding encoding
) 
1265     // translate encoding into the Windows CHARSET 
1266     long charset 
= wxEncodingToCharset(encoding
); 
1267     if ( charset 
== -1 ) 
1270     // translate CHARSET to code page 
1271     CHARSETINFO csetInfo
; 
1272     if ( !::TranslateCharsetInfo((DWORD 
*)(DWORD
)charset
, 
1276         wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)")); 
1281     return csetInfo
.ciACP
; 
1284 extern long wxCharsetToCodepage(const wxChar 
*name
) 
1286     // first get the font encoding for this charset 
1290     wxFontEncoding enc 
= wxFontMapper::Get()->CharsetToEncoding(name
, false); 
1291     if ( enc 
== wxFONTENCODING_SYSTEM 
) 
1294     // the use the helper function 
1295     return wxEncodingToCodepage(enc
); 
1298 #else // !wxUSE_FONTMAP 
1300 #include "wx/msw/registry.h" 
1302 // this should work if Internet Exploiter is installed 
1303 extern long wxCharsetToCodepage(const wxChar 
*name
) 
1310     wxString 
path(wxT("MIME\\Database\\Charset\\")); 
1313     // follow the alias loop 
1316         wxRegKey 
key(wxRegKey::HKCR
, path 
+ cn
); 
1321         // two cases: either there's an AliasForCharset string, 
1322         // or there are Codepage and InternetEncoding dwords. 
1323         // The InternetEncoding gives us the actual encoding, 
1324         // the Codepage just says which Windows character set to 
1325         // use when displaying the data. 
1326         if (key
.HasValue(wxT("InternetEncoding")) && 
1327             key
.QueryValue(wxT("InternetEncoding"), &CP
)) 
1330         // no encoding, see if it's an alias 
1331         if (!key
.HasValue(wxT("AliasForCharset")) || 
1332             !key
.QueryValue(wxT("AliasForCharset"), cn
)) 
1339 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP 
1342   Creates a hidden window with supplied window proc registering the class for 
1343   it if necesssary (i.e. the first time only). Caller is responsible for 
1344   destroying the window and unregistering the class (note that this must be 
1345   done because wxWidgets may be used as a DLL and so may be loaded/unloaded 
1346   multiple times into/from the same process so we cna't rely on automatic 
1347   Windows class unregistration). 
1349   pclassname is a pointer to a caller stored classname, which must initially be 
1350   NULL. classname is the desired wndclass classname. If function succesfully 
1351   registers the class, pclassname will be set to classname. 
1353 extern "C" WXDLLIMPEXP_BASE HWND
 
1354 wxCreateHiddenWindow(LPCTSTR 
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
) 
1356     wxCHECK_MSG( classname 
&& pclassname 
&& wndproc
, NULL
, 
1357                     _T("NULL parameter in wxCreateHiddenWindow") ); 
1359     // register the class fi we need to first 
1360     if ( *pclassname 
== NULL 
) 
1363         wxZeroMemory(wndclass
); 
1365         wndclass
.lpfnWndProc   
= wndproc
; 
1366         wndclass
.hInstance     
= wxGetInstance(); 
1367         wndclass
.lpszClassName 
= classname
; 
1369         if ( !::RegisterClass(&wndclass
) ) 
1371             wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow")); 
1376         *pclassname 
= classname
; 
1379     // next create the window 
1380     HWND hwnd 
= ::CreateWindow
 
1394         wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));