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