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