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