1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/msw/utils.cpp
3 // Purpose:     Various utilities
4 // Author:      Julian Smart
5 // Modified by:
6 // Created:     04/01/98
7 // Copyright:   (c) Julian Smart
8 // Licence:     wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10 
11 // ============================================================================
12 // declarations
13 // ============================================================================
14 
15 // ----------------------------------------------------------------------------
16 // headers
17 // ----------------------------------------------------------------------------
18 
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21 
22 #ifdef __BORLANDC__
23     #pragma hdrstop
24 #endif
25 
26 #ifndef WX_PRECOMP
27     #include "wx/utils.h"
28     #include "wx/app.h"
29     #include "wx/intl.h"
30     #include "wx/log.h"
31 #endif  //WX_PRECOMP
32 
33 #include "wx/msw/registry.h"
34 #include "wx/apptrait.h"
35 #include "wx/dynlib.h"
36 #include "wx/dynload.h"
37 #include "wx/scopeguard.h"
38 #include "wx/filename.h"
39 #include "wx/fontenc.h"
40 
41 #include "wx/confbase.h"        // for wxExpandEnvVars()
42 
43 #include "wx/msw/private.h"     // includes <windows.h>
44 #include "wx/msw/private/hiddenwin.h"
45 #include "wx/msw/missing.h"     // for CHARSET_HANGUL
46 
47 #if defined(__CYGWIN__)
48     //CYGWIN gives annoying warning about runtime stuff if we don't do this
49 #   define USE_SYS_TYPES_FD_SET
50 #   include <sys/types.h>
51 #endif
52 
53 // Doesn't work with Cygwin at present
54 #if wxUSE_SOCKETS && (defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) || defined(__CYGWIN32__))
55     // apparently we need to include winsock.h to get WSADATA and other stuff
56     // used in wxGetFullHostName() with the old mingw32 versions
57     #include <winsock.h>
58 #endif
59 
60 #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
61     #include <direct.h>
62 
63     #include <dos.h>
64 #endif  //GNUWIN32
65 
66 #if defined(__CYGWIN__)
67     #include <sys/unistd.h>
68     #include <sys/stat.h>
69     #include <sys/cygwin.h> // for cygwin_conv_path()
70     // and cygwin_conv_to_full_win32_path()
71     #include <cygwin/version.h>
72 #endif  //GNUWIN32
73 
74 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
75                     // this (3.1 I believe) and how to test for it.
76                     // If this works for Borland 4.0 as well, then no worries.
77     #include <dir.h>
78 #endif
79 
80 // VZ: there is some code using NetXXX() functions to get the full user name:
81 //     I don't think it's a good idea because they don't work under Win95 and
82 //     seem to return the same as wxGetUserId() under NT. If you really want
83 //     to use them, just #define USE_NET_API
84 #undef USE_NET_API
85 
86 #ifdef USE_NET_API
87     #include <lm.h>
88 #endif // USE_NET_API
89 
90 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
91     #ifndef __UNIX__
92         #include <io.h>
93     #endif
94 
95     #ifndef __GNUWIN32__
96         #include <shellapi.h>
97     #endif
98 #endif
99 
100 #ifndef __WATCOMC__
101     #if !(defined(_MSC_VER) && (_MSC_VER > 800))
102         #include <errno.h>
103     #endif
104 #endif
105 
106 // For wxKillAllChildren
107 #include <tlhelp32.h>
108 
109 // ----------------------------------------------------------------------------
110 // constants
111 // ----------------------------------------------------------------------------
112 
113 // In the WIN.INI file
114 #if (!defined(USE_NET_API) && !defined(__WXWINCE__)) || defined(__WXMICROWIN__)
115 static const wxChar WX_SECTION[] = wxT("wxWindows");
116 #endif
117 
118 #if (!defined(USE_NET_API) && !defined(__WXWINCE__))
119 static const wxChar eUSERNAME[]  = wxT("UserName");
120 #endif
121 
122 WXDLLIMPEXP_DATA_BASE(const wxChar *) wxUserResourceStr = wxT("TEXT");
123 
124 // ============================================================================
125 // implementation
126 // ============================================================================
127 
128 // ----------------------------------------------------------------------------
129 // get host name and related
130 // ----------------------------------------------------------------------------
131 
132 // Get hostname only (without domain name)
wxGetHostName(wxChar * buf,int maxSize)133 bool wxGetHostName(wxChar *buf, int maxSize)
134 {
135 #if defined(__WXWINCE__)
136     // GetComputerName() is not supported but the name seems to be stored in
137     // this location in the registry, at least for PPC2003 and WM5
138     wxString hostName;
139     wxRegKey regKey(wxRegKey::HKLM, wxT("Ident"));
140     if ( !regKey.HasValue(wxT("Name")) ||
141             !regKey.QueryValue(wxT("Name"), hostName) )
142         return false;
143 
144     wxStrlcpy(buf, hostName.t_str(), maxSize);
145 #else // !__WXWINCE__
146     DWORD nSize = maxSize;
147     if ( !::GetComputerName(buf, &nSize) )
148     {
149         wxLogLastError(wxT("GetComputerName"));
150 
151         return false;
152     }
153 #endif // __WXWINCE__/!__WXWINCE__
154 
155     return true;
156 }
157 
158 // get full hostname (with domain name if possible)
wxGetFullHostName(wxChar * buf,int maxSize)159 bool wxGetFullHostName(wxChar *buf, int maxSize)
160 {
161 #if !defined( __WXMICROWIN__) && wxUSE_DYNLIB_CLASS && wxUSE_SOCKETS
162     // TODO should use GetComputerNameEx() when available
163 
164     // we don't want to always link with Winsock DLL as we might not use it at
165     // all, so load it dynamically here if needed (and don't complain if it is
166     // missing, we handle this)
167     wxLogNull noLog;
168 
169     wxDynamicLibrary dllWinsock(wxT("ws2_32.dll"), wxDL_VERBATIM);
170     if ( dllWinsock.IsLoaded() )
171     {
172         typedef int (PASCAL *WSAStartup_t)(WORD, WSADATA *);
173         typedef int (PASCAL *gethostname_t)(char *, int);
174         typedef hostent* (PASCAL *gethostbyname_t)(const char *);
175         typedef hostent* (PASCAL *gethostbyaddr_t)(const char *, int , int);
176         typedef int (PASCAL *WSACleanup_t)(void);
177 
178         #define LOAD_WINSOCK_FUNC(func)                                       \
179             func ## _t                                                        \
180                 pfn ## func = (func ## _t)dllWinsock.GetSymbol(wxT(#func))
181 
182         LOAD_WINSOCK_FUNC(WSAStartup);
183 
184         WSADATA wsa;
185         if ( pfnWSAStartup && pfnWSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
186         {
187             LOAD_WINSOCK_FUNC(gethostname);
188 
189             wxString host;
190             if ( pfngethostname )
191             {
192                 char bufA[256];
193                 if ( pfngethostname(bufA, WXSIZEOF(bufA)) == 0 )
194                 {
195                     // gethostname() won't usually include the DNS domain name,
196                     // for this we need to work a bit more
197                     if ( !strchr(bufA, '.') )
198                     {
199                         LOAD_WINSOCK_FUNC(gethostbyname);
200 
201                         struct hostent *pHostEnt = pfngethostbyname
202                                                     ? pfngethostbyname(bufA)
203                                                     : NULL;
204 
205                         if ( pHostEnt )
206                         {
207                             // Windows will use DNS internally now
208                             LOAD_WINSOCK_FUNC(gethostbyaddr);
209 
210                             pHostEnt = pfngethostbyaddr
211                                         ? pfngethostbyaddr(pHostEnt->h_addr,
212                                                            4, AF_INET)
213                                         : NULL;
214                         }
215 
216                         if ( pHostEnt )
217                         {
218                             host = wxString::FromAscii(pHostEnt->h_name);
219                         }
220                     }
221                 }
222             }
223 
224             LOAD_WINSOCK_FUNC(WSACleanup);
225             if ( pfnWSACleanup )
226                 pfnWSACleanup();
227 
228 
229             if ( !host.empty() )
230             {
231                 wxStrlcpy(buf, host.c_str(), maxSize);
232 
233                 return true;
234             }
235         }
236     }
237 #endif // !__WXMICROWIN__
238 
239     return wxGetHostName(buf, maxSize);
240 }
241 
242 // Get user ID e.g. jacs
wxGetUserId(wxChar * WXUNUSED_IN_WINCE (buf),int WXUNUSED_IN_WINCE (maxSize))243 bool wxGetUserId(wxChar *WXUNUSED_IN_WINCE(buf),
244                  int WXUNUSED_IN_WINCE(maxSize))
245 {
246 #if defined(__WXWINCE__)
247     // TODO-CE
248     return false;
249 #else
250     DWORD nSize = maxSize;
251     if ( ::GetUserName(buf, &nSize) == 0 )
252     {
253         // actually, it does happen on Win9x if the user didn't log on
254         DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
255         if ( res == 0 )
256         {
257             // not found
258             return false;
259         }
260     }
261 
262     return true;
263 #endif
264 }
265 
266 // Get user name e.g. Julian Smart
wxGetUserName(wxChar * buf,int maxSize)267 bool wxGetUserName(wxChar *buf, int maxSize)
268 {
269     wxCHECK_MSG( buf && ( maxSize > 0 ), false,
270                     wxT("empty buffer in wxGetUserName") );
271 #if defined(__WXWINCE__) && wxUSE_REGKEY
272     wxLogNull noLog;
273     wxRegKey key(wxRegKey::HKCU, wxT("ControlPanel\\Owner"));
274     if(!key.Open(wxRegKey::Read))
275         return false;
276     wxString name;
277     if(!key.QueryValue(wxT("Owner"),name))
278         return false;
279     wxStrlcpy(buf, name.c_str(), maxSize);
280     return true;
281 #elif defined(USE_NET_API)
282     CHAR szUserName[256];
283     if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
284         return false;
285 
286     // TODO how to get the domain name?
287     CHAR *szDomain = "";
288 
289     // the code is based on the MSDN example (also see KB article Q119670)
290     WCHAR wszUserName[256];          // Unicode user name
291     WCHAR wszDomain[256];
292     LPBYTE ComputerName;
293 
294     USER_INFO_2 *ui2;         // User structure
295 
296     // Convert ANSI user name and domain to Unicode
297     MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
298             wszUserName, WXSIZEOF(wszUserName) );
299     MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
300             wszDomain, WXSIZEOF(wszDomain) );
301 
302     // Get the computer name of a DC for the domain.
303     if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
304     {
305         wxLogError(wxT("Cannot find domain controller"));
306 
307         goto error;
308     }
309 
310     // Look up the user on the DC
311     NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
312             (LPWSTR)&wszUserName,
313             2, // level - we want USER_INFO_2
314             (LPBYTE *) &ui2 );
315     switch ( status )
316     {
317         case NERR_Success:
318             // ok
319             break;
320 
321         case NERR_InvalidComputer:
322             wxLogError(wxT("Invalid domain controller name."));
323 
324             goto error;
325 
326         case NERR_UserNotFound:
327             wxLogError(wxT("Invalid user name '%s'."), szUserName);
328 
329             goto error;
330 
331         default:
332             wxLogSysError(wxT("Can't get information about user"));
333 
334             goto error;
335     }
336 
337     // Convert the Unicode full name to ANSI
338     WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
339             buf, maxSize, NULL, NULL );
340 
341     return true;
342 
343 error:
344     wxLogError(wxT("Couldn't look up full user name."));
345 
346     return false;
347 #else  // !USE_NET_API
348     // Could use NIS, MS-Mail or other site specific programs
349     // Use wxWidgets configuration data
350     bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0;
351     if ( !ok )
352     {
353         ok = wxGetUserId(buf, maxSize);
354     }
355 
356     if ( !ok )
357     {
358         wxStrlcpy(buf, wxT("Unknown User"), maxSize);
359     }
360 
361     return true;
362 #endif // Win32/16
363 }
364 
wxGetHomeDir(wxString * pstr)365 const wxChar* wxGetHomeDir(wxString *pstr)
366 {
367     wxString& strDir = *pstr;
368 
369     // first branch is for Cygwin
370 #if defined(__UNIX__) && !defined(__WINE__)
371     const wxChar *szHome = wxGetenv(wxT("HOME"));
372     if ( szHome == NULL ) {
373       // we're homeless...
374       wxLogWarning(_("can't find user's HOME, using current directory."));
375       strDir = wxT(".");
376     }
377     else
378        strDir = szHome;
379 
380     // add a trailing slash if needed
381     if ( strDir.Last() != wxT('/') )
382       strDir << wxT('/');
383 
384     #ifdef __CYGWIN__
385         // Cygwin returns unix type path but that does not work well
386         static wxChar windowsPath[MAX_PATH];
387         #if CYGWIN_VERSION_DLL_MAJOR >= 1007
388             cygwin_conv_path(CCP_POSIX_TO_WIN_W, strDir.c_str(), windowsPath, MAX_PATH);
389         #else
390             cygwin_conv_to_full_win32_path(strDir.c_str(), windowsPath);
391         #endif
392         strDir = windowsPath;
393     #endif
394 #elif defined(__WXWINCE__)
395     strDir = wxT("\\");
396 #else
397     strDir.clear();
398 
399     // If we have a valid HOME directory, as is used on many machines that
400     // have unix utilities on them, we should use that.
401     const wxChar *szHome = wxGetenv(wxT("HOME"));
402 
403     if ( szHome != NULL )
404     {
405         strDir = szHome;
406     }
407     else // no HOME, try HOMEDRIVE/PATH
408     {
409         szHome = wxGetenv(wxT("HOMEDRIVE"));
410         if ( szHome != NULL )
411             strDir << szHome;
412         szHome = wxGetenv(wxT("HOMEPATH"));
413 
414         if ( szHome != NULL )
415         {
416             strDir << szHome;
417 
418             // the idea is that under NT these variables have default values
419             // of "%systemdrive%:" and "\\". As we don't want to create our
420             // config files in the root directory of the system drive, we will
421             // create it in our program's dir. However, if the user took care
422             // to set HOMEPATH to something other than "\\", we suppose that he
423             // knows what he is doing and use the supplied value.
424             if ( wxStrcmp(szHome, wxT("\\")) == 0 )
425                 strDir.clear();
426         }
427     }
428 
429     if ( strDir.empty() )
430     {
431         // If we have a valid USERPROFILE directory, as is the case in
432         // Windows NT, 2000 and XP, we should use that as our home directory.
433         szHome = wxGetenv(wxT("USERPROFILE"));
434 
435         if ( szHome != NULL )
436             strDir = szHome;
437     }
438 
439     if ( !strDir.empty() )
440     {
441         // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
442         // value once again, it shouldn't hurt anyhow
443         strDir = wxExpandEnvVars(strDir);
444     }
445     else // fall back to the program directory
446     {
447         // extract the directory component of the program file name
448         wxFileName::SplitPath(wxGetFullModuleName(), &strDir, NULL, NULL);
449     }
450 #endif  // UNIX/Win
451 
452     return strDir.c_str();
453 }
454 
wxGetUserHome(const wxString & user)455 wxString wxGetUserHome(const wxString& user)
456 {
457     wxString home;
458 
459     if ( user.empty() || user == wxGetUserId() )
460         wxGetHomeDir(&home);
461 
462     return home;
463 }
464 
wxGetDiskSpace(const wxString & WXUNUSED_IN_WINCE (path),wxDiskspaceSize_t * WXUNUSED_IN_WINCE (pTotal),wxDiskspaceSize_t * WXUNUSED_IN_WINCE (pFree))465 bool wxGetDiskSpace(const wxString& WXUNUSED_IN_WINCE(path),
466                     wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pTotal),
467                     wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pFree))
468 {
469 #ifdef __WXWINCE__
470     // TODO-CE
471     return false;
472 #else
473     if ( path.empty() )
474         return false;
475 
476 // old w32api don't have ULARGE_INTEGER
477 #if defined(__WIN32__) && \
478     (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
479     // GetDiskFreeSpaceEx() is not available under original Win95, check for
480     // it
481     typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
482                                                 PULARGE_INTEGER,
483                                                 PULARGE_INTEGER,
484                                                 PULARGE_INTEGER);
485 
486     GetDiskFreeSpaceEx_t
487         pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
488                               (
489                                 ::GetModuleHandle(wxT("kernel32.dll")),
490 #if wxUSE_UNICODE
491                                 "GetDiskFreeSpaceExW"
492 #else
493                                 "GetDiskFreeSpaceExA"
494 #endif
495                               );
496 
497     if ( pGetDiskFreeSpaceEx )
498     {
499         ULARGE_INTEGER bytesFree, bytesTotal;
500 
501         // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
502         if ( !pGetDiskFreeSpaceEx(path.t_str(),
503                                   &bytesFree,
504                                   &bytesTotal,
505                                   NULL) )
506         {
507             wxLogLastError(wxT("GetDiskFreeSpaceEx"));
508 
509             return false;
510         }
511 
512         // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
513         // two 32 bit fields which may be or may be not named - try to make it
514         // compile in all cases
515 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
516         #define UL(ul) ul.u
517 #else // anon union
518         #define UL(ul) ul
519 #endif
520         if ( pTotal )
521         {
522 #if wxUSE_LONGLONG
523             *pTotal = wxDiskspaceSize_t(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
524 #else
525             *pTotal = wxDiskspaceSize_t(UL(bytesTotal).LowPart);
526 #endif
527         }
528 
529         if ( pFree )
530         {
531 #if wxUSE_LONGLONG
532             *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
533 #else
534             *pFree = wxDiskspaceSize_t(UL(bytesFree).LowPart);
535 #endif
536         }
537     }
538     else
539 #endif // Win32
540     {
541         // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
542         // should be used instead - but if it's not available, fall back on
543         // GetDiskFreeSpace() nevertheless...
544 
545         DWORD lSectorsPerCluster,
546               lBytesPerSector,
547               lNumberOfFreeClusters,
548               lTotalNumberOfClusters;
549 
550         // FIXME: this is wrong, we should extract the root drive from path
551         //        instead, but this is the job for wxFileName...
552         if ( !::GetDiskFreeSpace(path.t_str(),
553                                  &lSectorsPerCluster,
554                                  &lBytesPerSector,
555                                  &lNumberOfFreeClusters,
556                                  &lTotalNumberOfClusters) )
557         {
558             wxLogLastError(wxT("GetDiskFreeSpace"));
559 
560             return false;
561         }
562 
563         wxDiskspaceSize_t lBytesPerCluster = (wxDiskspaceSize_t) lSectorsPerCluster;
564         lBytesPerCluster *= lBytesPerSector;
565 
566         if ( pTotal )
567         {
568             *pTotal = lBytesPerCluster;
569             *pTotal *= lTotalNumberOfClusters;
570         }
571 
572         if ( pFree )
573         {
574             *pFree = lBytesPerCluster;
575             *pFree *= lNumberOfFreeClusters;
576         }
577     }
578 
579     return true;
580 #endif
581     // __WXWINCE__
582 }
583 
584 // ----------------------------------------------------------------------------
585 // env vars
586 // ----------------------------------------------------------------------------
587 
wxGetEnv(const wxString & WXUNUSED_IN_WINCE (var),wxString * WXUNUSED_IN_WINCE (value))588 bool wxGetEnv(const wxString& WXUNUSED_IN_WINCE(var),
589               wxString *WXUNUSED_IN_WINCE(value))
590 {
591 #ifdef __WXWINCE__
592     // no environment variables under CE
593     return false;
594 #else // Win32
595     // first get the size of the buffer
596     DWORD dwRet = ::GetEnvironmentVariable(var.t_str(), NULL, 0);
597     if ( !dwRet )
598     {
599         // this means that there is no such variable
600         return false;
601     }
602 
603     if ( value )
604     {
605         (void)::GetEnvironmentVariable(var.t_str(),
606                                        wxStringBuffer(*value, dwRet),
607                                        dwRet);
608     }
609 
610     return true;
611 #endif // WinCE/32
612 }
613 
wxDoSetEnv(const wxString & var,const wxChar * value)614 bool wxDoSetEnv(const wxString& var, const wxChar *value)
615 {
616 #ifdef __WXWINCE__
617     // no environment variables under CE
618     wxUnusedVar(var);
619     wxUnusedVar(value);
620     return false;
621 #else // !__WXWINCE__
622     // update the CRT environment if possible as people expect getenv() to also
623     // work and it is not affected by Win32 SetEnvironmentVariable() call (OTOH
624     // the CRT does use Win32 call to update the process environment block so
625     // there is no need to call it)
626     //
627     // TODO: add checks for the other compilers (and update wxSetEnv()
628     //       documentation in interface/wx/utils.h accordingly)
629 #if defined(__VISUALC__) || defined(__MINGW32__)
630     // notice that Microsoft _putenv() has different semantics from POSIX
631     // function with almost the same name: in particular it makes a copy of the
632     // string instead of using it as part of environment so we can safely call
633     // it here without going through all the troubles with wxSetEnvModule as in
634     // src/unix/utilsunx.cpp
635     wxString envstr = var;
636     envstr += '=';
637     if ( value )
638         envstr += value;
639     if ( _tputenv(envstr.t_str()) != 0 )
640         return false;
641 #else // other compiler
642     if ( !::SetEnvironmentVariable(var.t_str(), value) )
643     {
644         wxLogLastError(wxT("SetEnvironmentVariable"));
645 
646         return false;
647     }
648 #endif // compiler
649 
650     return true;
651 #endif // __WXWINCE__/!__WXWINCE__
652 }
653 
wxSetEnv(const wxString & variable,const wxString & value)654 bool wxSetEnv(const wxString& variable, const wxString& value)
655 {
656     return wxDoSetEnv(variable, value.t_str());
657 }
658 
wxUnsetEnv(const wxString & variable)659 bool wxUnsetEnv(const wxString& variable)
660 {
661     return wxDoSetEnv(variable, NULL);
662 }
663 
664 // ----------------------------------------------------------------------------
665 // process management
666 // ----------------------------------------------------------------------------
667 
668 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
669 struct wxFindByPidParams
670 {
wxFindByPidParamswxFindByPidParams671     wxFindByPidParams() { hwnd = 0; pid = 0; }
672 
673     // the HWND used to return the result
674     HWND hwnd;
675 
676     // the PID we're looking from
677     DWORD pid;
678 
679     wxDECLARE_NO_COPY_CLASS(wxFindByPidParams);
680 };
681 
682 // wxKill helper: EnumWindows() callback which is used to find the first (top
683 // level) window belonging to the given process
wxEnumFindByPidProc(HWND hwnd,LPARAM lParam)684 BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
685 {
686     DWORD pid;
687     (void)::GetWindowThreadProcessId(hwnd, &pid);
688 
689     wxFindByPidParams *params = (wxFindByPidParams *)lParam;
690     if ( pid == params->pid )
691     {
692         // remember the window we found
693         params->hwnd = hwnd;
694 
695         // return FALSE to stop the enumeration
696         return FALSE;
697     }
698 
699     // continue enumeration
700     return TRUE;
701 }
702 
703 int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc);
704 
wxKill(long pid,wxSignal sig,wxKillError * krc,int flags)705 int wxKill(long pid, wxSignal sig, wxKillError *krc, int flags)
706 {
707     if (flags & wxKILL_CHILDREN)
708         wxKillAllChildren(pid, sig, krc);
709 
710     // get the process handle to operate on
711     DWORD dwAccess = PROCESS_QUERY_INFORMATION | SYNCHRONIZE;
712     if ( sig == wxSIGKILL )
713         dwAccess |= PROCESS_TERMINATE;
714 
715     HANDLE hProcess = ::OpenProcess(dwAccess, FALSE, (DWORD)pid);
716     if ( hProcess == NULL )
717     {
718         if ( krc )
719         {
720             // recognize wxKILL_ACCESS_DENIED as special because this doesn't
721             // mean that the process doesn't exist and this is important for
722             // wxProcess::Exists()
723             *krc = ::GetLastError() == ERROR_ACCESS_DENIED
724                         ? wxKILL_ACCESS_DENIED
725                         : wxKILL_NO_PROCESS;
726         }
727 
728         return -1;
729     }
730 
731     wxON_BLOCK_EXIT1(::CloseHandle, hProcess);
732 
733     // Default timeout for waiting for the process termination after killing
734     // it. It should be long enough to allow the process to terminate even on a
735     // busy system but short enough to avoid blocking the main thread for too
736     // long.
737     DWORD waitTimeout = 500; // ms
738 
739     bool ok = true;
740     switch ( sig )
741     {
742         case wxSIGKILL:
743             // kill the process forcefully returning -1 as error code
744             if ( !::TerminateProcess(hProcess, (UINT)-1) )
745             {
746                 wxLogSysError(_("Failed to kill process %d"), pid);
747 
748                 if ( krc )
749                 {
750                     // this is not supposed to happen if we could open the
751                     // process
752                     *krc = wxKILL_ERROR;
753                 }
754 
755                 ok = false;
756             }
757             break;
758 
759         case wxSIGNONE:
760             // Opening the process handle may succeed for a process even if it
761             // doesn't run any more (typically because open handles to it still
762             // exist elsewhere, possibly in this process itself if we're
763             // killing a child process) so we still need check if it hasn't
764             // terminated yet but, unlike when killing it, we don't need to
765             // wait for any time at all.
766             waitTimeout = 0;
767             break;
768 
769         default:
770             // any other signal means "terminate"
771             {
772                 wxFindByPidParams params;
773                 params.pid = (DWORD)pid;
774 
775                 // EnumWindows() has nice semantics: it returns 0 if it found
776                 // something or if an error occurred and non zero if it
777                 // enumerated all the window
778                 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
779                 {
780                     // did we find any window?
781                     if ( params.hwnd )
782                     {
783                         // tell the app to close
784                         //
785                         // NB: this is the harshest way, the app won't have an
786                         //     opportunity to save any files, for example, but
787                         //     this is probably what we want here. If not we
788                         //     can also use SendMesageTimeout(WM_CLOSE)
789                         if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
790                         {
791                             wxLogLastError(wxT("PostMessage(WM_QUIT)"));
792                         }
793                     }
794                     else // it was an error then
795                     {
796                         wxLogLastError(wxT("EnumWindows"));
797 
798                         ok = false;
799                     }
800                 }
801                 else // no windows for this PID
802                 {
803                     if ( krc )
804                         *krc = wxKILL_ERROR;
805 
806                     ok = false;
807                 }
808             }
809     }
810 
811     // the return code
812     if ( ok )
813     {
814         // as we wait for a short time, we can use just WaitForSingleObject()
815         // and not MsgWaitForMultipleObjects()
816         switch ( ::WaitForSingleObject(hProcess, waitTimeout) )
817         {
818             case WAIT_OBJECT_0:
819                 // Process terminated: normally this indicates that we
820                 // successfully killed it but when testing for the process
821                 // existence, this means failure.
822                 if ( sig == wxSIGNONE )
823                 {
824                     if ( krc )
825                         *krc = wxKILL_NO_PROCESS;
826 
827                     ok = false;
828                 }
829                 break;
830 
831             default:
832                 wxFAIL_MSG( wxT("unexpected WaitForSingleObject() return") );
833                 // fall through
834 
835             case WAIT_FAILED:
836                 wxLogLastError(wxT("WaitForSingleObject"));
837                 // fall through
838 
839             case WAIT_TIMEOUT:
840                 // Process didn't terminate: normally this is a failure but not
841                 // when we're just testing for its existence.
842                 if ( sig != wxSIGNONE )
843                 {
844                     if ( krc )
845                         *krc = wxKILL_ERROR;
846 
847                     ok = false;
848                 }
849                 break;
850         }
851     }
852 
853 
854     // the return code is the same as from Unix kill(): 0 if killed
855     // successfully or -1 on error
856     if ( !ok )
857         return -1;
858 
859     if ( krc )
860         *krc = wxKILL_OK;
861 
862     return 0;
863 }
864 
865 typedef HANDLE (WINAPI *CreateToolhelp32Snapshot_t)(DWORD,DWORD);
866 typedef BOOL (WINAPI *Process32_t)(HANDLE,LPPROCESSENTRY32);
867 
868 CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot;
869 Process32_t lpfProcess32First, lpfProcess32Next;
870 
InitToolHelp32()871 static void InitToolHelp32()
872 {
873     static bool s_initToolHelpDone = false;
874 
875     if (s_initToolHelpDone)
876         return;
877 
878     s_initToolHelpDone = true;
879 
880     lpfCreateToolhelp32Snapshot = NULL;
881     lpfProcess32First = NULL;
882     lpfProcess32Next = NULL;
883 
884 #if wxUSE_DYNLIB_CLASS
885 
886     wxDynamicLibrary dllKernel(wxT("kernel32.dll"), wxDL_VERBATIM);
887 
888     // Get procedure addresses.
889     // We are linking to these functions of Kernel32
890     // explicitly, because otherwise a module using
891     // this code would fail to load under Windows NT,
892     // which does not have the Toolhelp32
893     // functions in the Kernel 32.
894     lpfCreateToolhelp32Snapshot =
895         (CreateToolhelp32Snapshot_t)dllKernel.RawGetSymbol(wxT("CreateToolhelp32Snapshot"));
896 
897     lpfProcess32First =
898         (Process32_t)dllKernel.RawGetSymbol(wxT("Process32First"));
899 
900     lpfProcess32Next =
901         (Process32_t)dllKernel.RawGetSymbol(wxT("Process32Next"));
902 
903 #endif // wxUSE_DYNLIB_CLASS
904 }
905 
906 // By John Skiff
wxKillAllChildren(long pid,wxSignal sig,wxKillError * krc)907 int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc)
908 {
909     InitToolHelp32();
910 
911     if (krc)
912         *krc = wxKILL_OK;
913 
914     // If not implemented for this platform (e.g. NT 4.0), silently ignore
915     if (!lpfCreateToolhelp32Snapshot || !lpfProcess32First || !lpfProcess32Next)
916         return 0;
917 
918     // Take a snapshot of all processes in the system.
919     HANDLE hProcessSnap = lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
920     if (hProcessSnap == INVALID_HANDLE_VALUE) {
921         if (krc)
922             *krc = wxKILL_ERROR;
923         return -1;
924     }
925 
926     //Fill in the size of the structure before using it.
927     PROCESSENTRY32 pe;
928     wxZeroMemory(pe);
929     pe.dwSize = sizeof(PROCESSENTRY32);
930 
931     // Walk the snapshot of the processes, and for each process,
932     // kill it if its parent is pid.
933     if (!lpfProcess32First(hProcessSnap, &pe)) {
934         // Can't get first process.
935         if (krc)
936             *krc = wxKILL_ERROR;
937         CloseHandle (hProcessSnap);
938         return -1;
939     }
940 
941     do {
942         if (pe.th32ParentProcessID == (DWORD) pid) {
943             if (wxKill(pe.th32ProcessID, sig, krc))
944                 return -1;
945         }
946     } while (lpfProcess32Next (hProcessSnap, &pe));
947 
948 
949     return 0;
950 }
951 
952 // Execute a program in an Interactive Shell
wxShell(const wxString & command)953 bool wxShell(const wxString& command)
954 {
955     wxString cmd;
956 
957 #ifdef __WXWINCE__
958     cmd = command;
959 #else
960     wxChar *shell = wxGetenv(wxT("COMSPEC"));
961     if ( !shell )
962         shell = (wxChar*) wxT("\\COMMAND.COM");
963 
964     if ( !command )
965     {
966         // just the shell
967         cmd = shell;
968     }
969     else
970     {
971         // pass the command to execute to the command processor
972         cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
973     }
974 #endif
975 
976     return wxExecute(cmd, wxEXEC_SYNC) == 0;
977 }
978 
979 // Shutdown or reboot the PC
wxShutdown(int WXUNUSED_IN_WINCE (flags))980 bool wxShutdown(int WXUNUSED_IN_WINCE(flags))
981 {
982 #ifdef __WXWINCE__
983     // TODO-CE
984     return false;
985 #elif defined(__WIN32__)
986     bool bOK = true;
987 
988     if ( wxGetOsVersion(NULL, NULL) == wxOS_WINDOWS_NT ) // if is NT or 2K
989     {
990         // Get a token for this process.
991         HANDLE hToken;
992         bOK = ::OpenProcessToken(GetCurrentProcess(),
993                                  TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
994                                  &hToken) != 0;
995         if ( bOK )
996         {
997             TOKEN_PRIVILEGES tkp;
998 
999             // Get the LUID for the shutdown privilege.
1000             bOK = ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
1001                                          &tkp.Privileges[0].Luid) != 0;
1002 
1003             if ( bOK )
1004             {
1005                 tkp.PrivilegeCount = 1;  // one privilege to set
1006                 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1007 
1008                 // Get the shutdown privilege for this process.
1009                 ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
1010                                         (PTOKEN_PRIVILEGES)NULL, 0);
1011 
1012                 // Cannot test the return value of AdjustTokenPrivileges.
1013                 bOK = ::GetLastError() == ERROR_SUCCESS;
1014             }
1015 
1016             ::CloseHandle(hToken);
1017         }
1018     }
1019 
1020     if ( bOK )
1021     {
1022         UINT wFlags = 0;
1023         if ( flags & wxSHUTDOWN_FORCE )
1024         {
1025             wFlags = EWX_FORCE;
1026             flags &= ~wxSHUTDOWN_FORCE;
1027         }
1028 
1029         switch ( flags )
1030         {
1031             case wxSHUTDOWN_POWEROFF:
1032                 wFlags |= EWX_POWEROFF;
1033                 break;
1034 
1035             case wxSHUTDOWN_REBOOT:
1036                 wFlags |= EWX_REBOOT;
1037                 break;
1038 
1039             case wxSHUTDOWN_LOGOFF:
1040                 wFlags |= EWX_LOGOFF;
1041                 break;
1042 
1043             default:
1044                 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
1045                 return false;
1046         }
1047 
1048         bOK = ::ExitWindowsEx(wFlags, 0) != 0;
1049     }
1050 
1051     return bOK;
1052 #endif // WinCE/!WinCE
1053 }
1054 
1055 // ----------------------------------------------------------------------------
1056 // misc
1057 // ----------------------------------------------------------------------------
1058 
1059 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
wxGetFreeMemory()1060 wxMemorySize wxGetFreeMemory()
1061 {
1062 #if defined(__WIN64__)
1063     MEMORYSTATUSEX memStatex;
1064     memStatex.dwLength = sizeof (memStatex);
1065     ::GlobalMemoryStatusEx (&memStatex);
1066     return (wxMemorySize)memStatex.ullAvailPhys;
1067 #else /* if defined(__WIN32__) */
1068     MEMORYSTATUS memStatus;
1069     memStatus.dwLength = sizeof(MEMORYSTATUS);
1070     ::GlobalMemoryStatus(&memStatus);
1071     return (wxMemorySize)memStatus.dwAvailPhys;
1072 #endif
1073 }
1074 
wxGetProcessId()1075 unsigned long wxGetProcessId()
1076 {
1077     return ::GetCurrentProcessId();
1078 }
1079 
wxIsDebuggerRunning()1080 bool wxIsDebuggerRunning()
1081 {
1082 #if wxUSE_DYNLIB_CLASS
1083     // IsDebuggerPresent() is not available under Win95, so load it dynamically
1084     wxDynamicLibrary dll(wxT("kernel32.dll"), wxDL_VERBATIM);
1085 
1086     typedef BOOL (WINAPI *IsDebuggerPresent_t)();
1087     if ( !dll.HasSymbol(wxT("IsDebuggerPresent")) )
1088     {
1089         // no way to know, assume no
1090         return false;
1091     }
1092 
1093     return (*(IsDebuggerPresent_t)dll.GetSymbol(wxT("IsDebuggerPresent")))() != 0;
1094 #else
1095     return false;
1096 #endif
1097 }
1098 
1099 // ----------------------------------------------------------------------------
1100 // working with MSW resources
1101 // ----------------------------------------------------------------------------
1102 
1103 bool
wxLoadUserResource(const void ** outData,size_t * outLen,const wxString & resourceName,const wxChar * resourceType,WXHINSTANCE instance)1104 wxLoadUserResource(const void **outData,
1105                    size_t *outLen,
1106                    const wxString& resourceName,
1107                    const wxChar* resourceType,
1108                    WXHINSTANCE instance)
1109 {
1110     wxCHECK_MSG( outData && outLen, false, "output pointers can't be NULL" );
1111 
1112     HRSRC hResource = ::FindResource(instance,
1113                                      resourceName.t_str(),
1114                                      resourceType);
1115     if ( !hResource )
1116         return false;
1117 
1118     HGLOBAL hData = ::LoadResource(instance, hResource);
1119     if ( !hData )
1120     {
1121         wxLogSysError(_("Failed to load resource \"%s\"."), resourceName);
1122         return false;
1123     }
1124 
1125     *outData = ::LockResource(hData);
1126     if ( !*outData )
1127     {
1128         wxLogSysError(_("Failed to lock resource \"%s\"."), resourceName);
1129         return false;
1130     }
1131 
1132     *outLen = ::SizeofResource(instance, hResource);
1133 
1134     // Notice that we do not need to call neither UnlockResource() (which is
1135     // obsolete in Win32) nor GlobalFree() (resources are freed on process
1136     // termination only)
1137 
1138     return true;
1139 }
1140 
1141 char *
wxLoadUserResource(const wxString & resourceName,const wxChar * resourceType,int * pLen,WXHINSTANCE instance)1142 wxLoadUserResource(const wxString& resourceName,
1143                    const wxChar* resourceType,
1144                    int* pLen,
1145                    WXHINSTANCE instance)
1146 {
1147     const void *data;
1148     size_t len;
1149     if ( !wxLoadUserResource(&data, &len, resourceName, resourceType, instance) )
1150         return NULL;
1151 
1152     char *s = new char[len + 1];
1153     memcpy(s, data, len);
1154     s[len] = '\0'; // NUL-terminate in case the resource itself wasn't
1155 
1156     if (pLen)
1157       *pLen = len;
1158 
1159     return s;
1160 }
1161 
1162 // ----------------------------------------------------------------------------
1163 // OS version
1164 // ----------------------------------------------------------------------------
1165 
1166 namespace
1167 {
1168 
1169 // Helper function wrapping Windows GetVersionEx() which is deprecated since
1170 // Windows 8. For now, all we do in this wrapper is to avoid the deprecation
1171 // warnings but this is not enough as the function now actually doesn't return
1172 // the correct value any more and we need to use VerifyVersionInfo() to perform
1173 // binary search to find the real Windows version.
wxGetWindowsVersionInfo()1174 OSVERSIONINFOEX wxGetWindowsVersionInfo()
1175 {
1176     OSVERSIONINFOEX info;
1177     wxZeroMemory(info);
1178 
1179 #ifdef __VISUALC__
1180     #pragma warning(push)
1181     #pragma warning(disable:4996) // 'xxx': was declared deprecated
1182 #endif
1183 
1184     info.dwOSVersionInfoSize = sizeof(info);
1185     if ( !::GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&info)) )
1186     {
1187         // This really shouldn't ever happen.
1188         wxFAIL_MSG( "GetVersionEx() unexpectedly failed" );
1189     }
1190 
1191 #ifdef __VISUALC__
1192     #pragma warning(pop)
1193 #endif
1194 
1195     return info;
1196 }
1197 
1198 // check if we're running under a server or workstation Windows system: it
1199 // returns true or false with obvious meaning as well as -1 if the system type
1200 // couldn't be determined
1201 //
1202 // this function is currently private but we may want to expose it later if
1203 // it's really useful
1204 
wxIsWindowsServer()1205 int wxIsWindowsServer()
1206 {
1207 #ifdef VER_NT_WORKSTATION
1208     switch ( wxGetWindowsVersionInfo().wProductType )
1209     {
1210         case VER_NT_WORKSTATION:
1211             return false;
1212 
1213         case VER_NT_SERVER:
1214         case VER_NT_DOMAIN_CONTROLLER:
1215             return true;
1216     }
1217 #endif // VER_NT_WORKSTATION
1218 
1219     return -1;
1220 }
1221 
1222 } // anonymous namespace
1223 
wxGetOsDescription()1224 wxString wxGetOsDescription()
1225 {
1226     wxString str;
1227 
1228     const OSVERSIONINFOEX info = wxGetWindowsVersionInfo();
1229     switch ( info.dwPlatformId )
1230     {
1231 #ifdef VER_PLATFORM_WIN32_CE
1232         case VER_PLATFORM_WIN32_CE:
1233             str.Printf(_("Windows CE (%d.%d)"),
1234                        info.dwMajorVersion,
1235                        info.dwMinorVersion);
1236             break;
1237 #endif
1238         case VER_PLATFORM_WIN32s:
1239             str = _("Win32s on Windows 3.1");
1240             break;
1241 
1242         case VER_PLATFORM_WIN32_WINDOWS:
1243             switch (info.dwMinorVersion)
1244             {
1245                 case 0:
1246                     if ( info.szCSDVersion[1] == 'B' ||
1247                          info.szCSDVersion[1] == 'C' )
1248                     {
1249                         str = _("Windows 95 OSR2");
1250                     }
1251                     else
1252                     {
1253                         str = _("Windows 95");
1254                     }
1255                     break;
1256                 case 10:
1257                     if ( info.szCSDVersion[1] == 'B' ||
1258                          info.szCSDVersion[1] == 'C' )
1259                     {
1260                         str = _("Windows 98 SE");
1261                     }
1262                     else
1263                     {
1264                         str = _("Windows 98");
1265                     }
1266                     break;
1267                 case 90:
1268                     str = _("Windows ME");
1269                     break;
1270                 default:
1271                     str.Printf(_("Windows 9x (%d.%d)"),
1272                                info.dwMajorVersion,
1273                                info.dwMinorVersion);
1274                     break;
1275             }
1276             if ( !wxIsEmpty(info.szCSDVersion) )
1277             {
1278                 str << wxT(" (") << info.szCSDVersion << wxT(')');
1279             }
1280             break;
1281 
1282         case VER_PLATFORM_WIN32_NT:
1283             switch ( info.dwMajorVersion )
1284             {
1285                 case 5:
1286                     switch ( info.dwMinorVersion )
1287                     {
1288                         case 0:
1289                             str = _("Windows 2000");
1290                             break;
1291 
1292                         case 2:
1293                             // we can't distinguish between XP 64 and 2003
1294                             // as they both are 5.2, so examine the product
1295                             // type to resolve this ambiguity
1296                             if ( wxIsWindowsServer() == 1 )
1297                             {
1298                                 str = _("Windows Server 2003");
1299                                 break;
1300                             }
1301                             //else: must be XP, fall through
1302 
1303                         case 1:
1304                             str = _("Windows XP");
1305                             break;
1306                     }
1307                     break;
1308 
1309                 case 6:
1310                     switch ( info.dwMinorVersion )
1311                     {
1312                         case 0:
1313                             str = wxIsWindowsServer() == 1
1314                                     ? _("Windows Server 2008")
1315                                     : _("Windows Vista");
1316                             break;
1317 
1318                         case 1:
1319                             str = wxIsWindowsServer() == 1
1320                                     ? _("Windows Server 2008 R2")
1321                                     : _("Windows 7");
1322                             break;
1323 
1324                         case 2:
1325                             str = wxIsWindowsServer() == 1
1326                                     ? _("Windows Server 2012")
1327                                     : _("Windows 8");
1328                             break;
1329 
1330                         case 3:
1331                             str = wxIsWindowsServer() == 1
1332                                     ? _("Windows Server 2012 R2")
1333                                     : _("Windows 8.1");
1334                             break;
1335                     }
1336                     break;
1337 
1338                 case 10:
1339                     str = wxIsWindowsServer() == 1
1340                             ? _("Windows Server 2016")
1341                             : _("Windows 10");
1342                     break;
1343             }
1344 
1345             if ( str.empty() )
1346             {
1347                 str.Printf(_("Windows NT %lu.%lu"),
1348                            info.dwMajorVersion,
1349                            info.dwMinorVersion);
1350             }
1351 
1352             str << wxT(" (")
1353                 << wxString::Format(_("build %lu"), info.dwBuildNumber);
1354             if ( !wxIsEmpty(info.szCSDVersion) )
1355             {
1356                 str << wxT(", ") << info.szCSDVersion;
1357             }
1358             str << wxT(')');
1359 
1360             if ( wxIsPlatform64Bit() )
1361                 str << _(", 64-bit edition");
1362             break;
1363     }
1364 
1365     return str;
1366 }
1367 
wxIsPlatform64Bit()1368 bool wxIsPlatform64Bit()
1369 {
1370 #if defined(__WIN64__)
1371     return true;  // 64-bit programs run only on Win64
1372 #elif wxUSE_DYNLIB_CLASS // Win32
1373     // 32-bit programs run on both 32-bit and 64-bit Windows so check
1374     typedef BOOL (WINAPI *IsWow64Process_t)(HANDLE, BOOL *);
1375 
1376     wxDynamicLibrary dllKernel32(wxT("kernel32.dll"));
1377     IsWow64Process_t pfnIsWow64Process =
1378         (IsWow64Process_t)dllKernel32.RawGetSymbol(wxT("IsWow64Process"));
1379 
1380     BOOL wow64 = FALSE;
1381     if ( pfnIsWow64Process )
1382     {
1383         pfnIsWow64Process(::GetCurrentProcess(), &wow64);
1384     }
1385     //else: running under a system without Win64 support
1386 
1387     return wow64 != FALSE;
1388 #else
1389     return false;
1390 #endif // Win64/Win32
1391 }
1392 
wxGetOsVersion(int * verMaj,int * verMin)1393 wxOperatingSystemId wxGetOsVersion(int *verMaj, int *verMin)
1394 {
1395     static struct
1396     {
1397         bool initialized;
1398 
1399         wxOperatingSystemId os;
1400 
1401         int verMaj,
1402             verMin;
1403     } s_version;
1404 
1405     // query the OS info only once as it's not supposed to change
1406     if ( !s_version.initialized )
1407     {
1408         const OSVERSIONINFOEX info = wxGetWindowsVersionInfo();
1409 
1410         s_version.initialized = true;
1411 
1412 #if defined(__WXWINCE__)
1413         s_version.os = wxOS_WINDOWS_CE;
1414 #elif defined(__WXMICROWIN__)
1415         s_version.os = wxOS_WINDOWS_MICRO;
1416 #else // "normal" desktop Windows system, use run-time detection
1417         switch ( info.dwPlatformId )
1418         {
1419             case VER_PLATFORM_WIN32_NT:
1420                 s_version.os = wxOS_WINDOWS_NT;
1421                 break;
1422 
1423             case VER_PLATFORM_WIN32_WINDOWS:
1424                 s_version.os = wxOS_WINDOWS_9X;
1425                 break;
1426         }
1427 #endif // Windows versions
1428 
1429         s_version.verMaj = info.dwMajorVersion;
1430         s_version.verMin = info.dwMinorVersion;
1431     }
1432 
1433     if ( verMaj )
1434         *verMaj = s_version.verMaj;
1435     if ( verMin )
1436         *verMin = s_version.verMin;
1437 
1438     return s_version.os;
1439 }
1440 
wxGetWinVersion()1441 wxWinVersion wxGetWinVersion()
1442 {
1443     int verMaj,
1444         verMin;
1445     switch ( wxGetOsVersion(&verMaj, &verMin) )
1446     {
1447         case wxOS_WINDOWS_9X:
1448             if ( verMaj == 4 )
1449             {
1450                 switch ( verMin )
1451                 {
1452                     case 0:
1453                         return wxWinVersion_95;
1454 
1455                     case 10:
1456                         return wxWinVersion_98;
1457 
1458                     case 90:
1459                         return wxWinVersion_ME;
1460                 }
1461             }
1462             break;
1463 
1464         case wxOS_WINDOWS_NT:
1465             switch ( verMaj )
1466             {
1467                 case 3:
1468                     return wxWinVersion_NT3;
1469 
1470                 case 4:
1471                     return wxWinVersion_NT4;
1472 
1473                 case 5:
1474                     switch ( verMin )
1475                     {
1476                         case 0:
1477                             return wxWinVersion_2000;
1478 
1479                         case 1:
1480                             return wxWinVersion_XP;
1481 
1482                         case 2:
1483                             return wxWinVersion_2003;
1484                     }
1485                     break;
1486 
1487                 case 6:
1488                     switch ( verMin )
1489                     {
1490                         case 0:
1491                             return wxWinVersion_Vista;
1492 
1493                         case 1:
1494                             return wxWinVersion_7;
1495 
1496                         case 2:
1497                             return wxWinVersion_8;
1498 
1499                         case 3:
1500                             // For now, map to wxWinVersion_8. In case program
1501                             // does not have a manifest indicating 8.1 or 10
1502                             // support, Windows already performs this mapping
1503                             // for us.
1504                             return wxWinVersion_8;
1505                     }
1506                     break;
1507 
1508                 case 10:
1509                     return wxWinVersion_8;
1510             }
1511         default:
1512             // Do nothing just to silence GCC warning
1513             break;
1514     }
1515 
1516     return wxWinVersion_Unknown;
1517 }
1518 
1519 // ----------------------------------------------------------------------------
1520 // sleep functions
1521 // ----------------------------------------------------------------------------
1522 
wxMilliSleep(unsigned long milliseconds)1523 void wxMilliSleep(unsigned long milliseconds)
1524 {
1525     ::Sleep(milliseconds);
1526 }
1527 
wxMicroSleep(unsigned long microseconds)1528 void wxMicroSleep(unsigned long microseconds)
1529 {
1530     wxMilliSleep(microseconds/1000);
1531 }
1532 
wxSleep(int nSecs)1533 void wxSleep(int nSecs)
1534 {
1535     wxMilliSleep(1000*nSecs);
1536 }
1537 
1538 // ----------------------------------------------------------------------------
1539 // font encoding <-> Win32 codepage conversion functions
1540 // ----------------------------------------------------------------------------
1541 
wxEncodingToCharset(wxFontEncoding encoding)1542 extern WXDLLIMPEXP_BASE long wxEncodingToCharset(wxFontEncoding encoding)
1543 {
1544     switch ( encoding )
1545     {
1546         // although this function is supposed to return an exact match, do do
1547         // some mappings here for the most common case of "standard" encoding
1548         case wxFONTENCODING_SYSTEM:
1549             return DEFAULT_CHARSET;
1550 
1551         case wxFONTENCODING_ISO8859_1:
1552         case wxFONTENCODING_ISO8859_15:
1553         case wxFONTENCODING_CP1252:
1554             return ANSI_CHARSET;
1555 
1556 #if !defined(__WXMICROWIN__)
1557         // The following four fonts are multi-byte charsets
1558         case wxFONTENCODING_CP932:
1559             return SHIFTJIS_CHARSET;
1560 
1561         case wxFONTENCODING_CP936:
1562             return GB2312_CHARSET;
1563 
1564 #ifndef __WXWINCE__
1565         case wxFONTENCODING_CP949:
1566             return HANGUL_CHARSET;
1567 #endif
1568 
1569         case wxFONTENCODING_CP950:
1570             return CHINESEBIG5_CHARSET;
1571 
1572         // The rest are single byte encodings
1573         case wxFONTENCODING_CP1250:
1574             return EASTEUROPE_CHARSET;
1575 
1576         case wxFONTENCODING_CP1251:
1577             return RUSSIAN_CHARSET;
1578 
1579         case wxFONTENCODING_CP1253:
1580             return GREEK_CHARSET;
1581 
1582         case wxFONTENCODING_CP1254:
1583             return TURKISH_CHARSET;
1584 
1585         case wxFONTENCODING_CP1255:
1586             return HEBREW_CHARSET;
1587 
1588         case wxFONTENCODING_CP1256:
1589             return ARABIC_CHARSET;
1590 
1591         case wxFONTENCODING_CP1257:
1592             return BALTIC_CHARSET;
1593 
1594         case wxFONTENCODING_CP874:
1595             return THAI_CHARSET;
1596 #endif // !__WXMICROWIN__
1597 
1598         case wxFONTENCODING_CP437:
1599             return OEM_CHARSET;
1600 
1601         default:
1602             // no way to translate this encoding into a Windows charset
1603             return -1;
1604     }
1605 }
1606 
1607 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1608 // looks up the vlaues in the registry and the new one which is more
1609 // politically correct and has more chances to work on other Windows versions
1610 // as well but the old version is still needed for !wxUSE_FONTMAP case
1611 
wxEncodingToCodepage(wxFontEncoding encoding)1612 extern WXDLLIMPEXP_BASE long wxEncodingToCodepage(wxFontEncoding encoding)
1613 {
1614     // There don't seem to be symbolic names for
1615     // these under Windows so I just copied the
1616     // values from MSDN.
1617 
1618     unsigned int ret;
1619 
1620     switch (encoding)
1621     {
1622         case wxFONTENCODING_ISO8859_1:      ret = 28591; break;
1623         case wxFONTENCODING_ISO8859_2:      ret = 28592; break;
1624         case wxFONTENCODING_ISO8859_3:      ret = 28593; break;
1625         case wxFONTENCODING_ISO8859_4:      ret = 28594; break;
1626         case wxFONTENCODING_ISO8859_5:      ret = 28595; break;
1627         case wxFONTENCODING_ISO8859_6:      ret = 28596; break;
1628         case wxFONTENCODING_ISO8859_7:      ret = 28597; break;
1629         case wxFONTENCODING_ISO8859_8:      ret = 28598; break;
1630         case wxFONTENCODING_ISO8859_9:      ret = 28599; break;
1631         case wxFONTENCODING_ISO8859_10:     ret = 28600; break;
1632         case wxFONTENCODING_ISO8859_11:     ret = 874; break;
1633         // case wxFONTENCODING_ISO8859_12,      // doesn't exist currently, but put it
1634         case wxFONTENCODING_ISO8859_13:     ret = 28603; break;
1635         // case wxFONTENCODING_ISO8859_14:     ret = 28604; break; // no correspondence on Windows
1636         case wxFONTENCODING_ISO8859_15:     ret = 28605; break;
1637 
1638         case wxFONTENCODING_KOI8:           ret = 20866; break;
1639         case wxFONTENCODING_KOI8_U:         ret = 21866; break;
1640 
1641         case wxFONTENCODING_CP437:          ret = 437; break;
1642         case wxFONTENCODING_CP850:          ret = 850; break;
1643         case wxFONTENCODING_CP852:          ret = 852; break;
1644         case wxFONTENCODING_CP855:          ret = 855; break;
1645         case wxFONTENCODING_CP866:          ret = 866; break;
1646         case wxFONTENCODING_CP874:          ret = 874; break;
1647         case wxFONTENCODING_CP932:          ret = 932; break;
1648         case wxFONTENCODING_CP936:          ret = 936; break;
1649         case wxFONTENCODING_CP949:          ret = 949; break;
1650         case wxFONTENCODING_CP950:          ret = 950; break;
1651         case wxFONTENCODING_CP1250:         ret = 1250; break;
1652         case wxFONTENCODING_CP1251:         ret = 1251; break;
1653         case wxFONTENCODING_CP1252:         ret = 1252; break;
1654         case wxFONTENCODING_CP1253:         ret = 1253; break;
1655         case wxFONTENCODING_CP1254:         ret = 1254; break;
1656         case wxFONTENCODING_CP1255:         ret = 1255; break;
1657         case wxFONTENCODING_CP1256:         ret = 1256; break;
1658         case wxFONTENCODING_CP1257:         ret = 1257; break;
1659 
1660         case wxFONTENCODING_EUC_JP:         ret = 20932; break;
1661 
1662         case wxFONTENCODING_MACROMAN:       ret = 10000; break;
1663         case wxFONTENCODING_MACJAPANESE:    ret = 10001; break;
1664         case wxFONTENCODING_MACCHINESETRAD: ret = 10002; break;
1665         case wxFONTENCODING_MACKOREAN:      ret = 10003; break;
1666         case wxFONTENCODING_MACARABIC:      ret = 10004; break;
1667         case wxFONTENCODING_MACHEBREW:      ret = 10005; break;
1668         case wxFONTENCODING_MACGREEK:       ret = 10006; break;
1669         case wxFONTENCODING_MACCYRILLIC:    ret = 10007; break;
1670         case wxFONTENCODING_MACTHAI:        ret = 10021; break;
1671         case wxFONTENCODING_MACCHINESESIMP: ret = 10008; break;
1672         case wxFONTENCODING_MACCENTRALEUR:  ret = 10029; break;
1673         case wxFONTENCODING_MACCROATIAN:    ret = 10082; break;
1674         case wxFONTENCODING_MACICELANDIC:   ret = 10079; break;
1675         case wxFONTENCODING_MACROMANIAN:    ret = 10010; break;
1676 
1677         case wxFONTENCODING_ISO2022_JP:     ret = 50222; break;
1678 
1679         case wxFONTENCODING_UTF7:           ret = 65000; break;
1680         case wxFONTENCODING_UTF8:           ret = 65001; break;
1681 
1682         default:                            return -1;
1683     }
1684 
1685     if (::IsValidCodePage(ret) == 0)
1686         return -1;
1687 
1688     CPINFO info;
1689     if (::GetCPInfo(ret, &info) == 0)
1690         return -1;
1691 
1692     return (long) ret;
1693 }
1694 
1695 #if wxUSE_FONTMAP
1696 
1697 #include "wx/fontmap.h"
1698 
wxCharsetToCodepage(const char * name)1699 extern long wxCharsetToCodepage(const char *name)
1700 {
1701     // first get the font encoding for this charset
1702     if ( !name )
1703         return -1;
1704 
1705     wxFontEncoding enc = wxFontMapperBase::Get()->CharsetToEncoding(name, false);
1706     if ( enc == wxFONTENCODING_SYSTEM )
1707         return -1;
1708 
1709     // the use the helper function
1710     return wxEncodingToCodepage(enc);
1711 }
1712 
1713 #else // !wxUSE_FONTMAP
1714 
1715 #include "wx/msw/registry.h"
1716 
1717 // this should work if Internet Exploiter is installed
wxCharsetToCodepage(const char * name)1718 extern long wxCharsetToCodepage(const char *name)
1719 {
1720     if (!name)
1721         return GetACP();
1722 
1723     long CP = -1;
1724 
1725 #if wxUSE_REGKEY
1726     wxString path(wxT("MIME\\Database\\Charset\\"));
1727     wxString cn(name);
1728 
1729     // follow the alias loop
1730     for ( ;; )
1731     {
1732         wxRegKey key(wxRegKey::HKCR, path + cn);
1733 
1734         if (!key.Exists())
1735             break;
1736 
1737         // two cases: either there's an AliasForCharset string,
1738         // or there are Codepage and InternetEncoding dwords.
1739         // The InternetEncoding gives us the actual encoding,
1740         // the Codepage just says which Windows character set to
1741         // use when displaying the data.
1742         if (key.HasValue(wxT("InternetEncoding")) &&
1743             key.QueryValue(wxT("InternetEncoding"), &CP))
1744             break;
1745 
1746         // no encoding, see if it's an alias
1747         if (!key.HasValue(wxT("AliasForCharset")) ||
1748             !key.QueryValue(wxT("AliasForCharset"), cn))
1749             break;
1750     }
1751 #endif // wxUSE_REGKEY
1752 
1753     return CP;
1754 }
1755 
1756 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1757 
1758 extern "C" WXDLLIMPEXP_BASE HWND
wxCreateHiddenWindow(LPCTSTR * pclassname,LPCTSTR classname,WNDPROC wndproc)1759 wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc)
1760 {
1761     wxCHECK_MSG( classname && pclassname && wndproc, NULL,
1762                     wxT("NULL parameter in wxCreateHiddenWindow") );
1763 
1764     // register the class fi we need to first
1765     if ( *pclassname == NULL )
1766     {
1767         WNDCLASS wndclass;
1768         wxZeroMemory(wndclass);
1769 
1770         wndclass.lpfnWndProc   = wndproc;
1771         wndclass.hInstance     = wxGetInstance();
1772         wndclass.lpszClassName = classname;
1773 
1774         if ( !::RegisterClass(&wndclass) )
1775         {
1776             wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1777 
1778             return NULL;
1779         }
1780 
1781         *pclassname = classname;
1782     }
1783 
1784     // next create the window
1785     HWND hwnd = ::CreateWindow
1786                   (
1787                     *pclassname,
1788                     NULL,
1789                     0, 0, 0, 0,
1790                     0,
1791                     (HWND) NULL,
1792                     (HMENU)NULL,
1793                     wxGetInstance(),
1794                     (LPVOID) NULL
1795                   );
1796 
1797     if ( !hwnd )
1798     {
1799         wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));
1800     }
1801 
1802     return hwnd;
1803 }
1804