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