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