]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utils.cpp
Take best fitting type for available memory measurement.
[wxWidgets.git] / src / msw / utils.cpp
CommitLineData
2bda0e17 1/////////////////////////////////////////////////////////////////////////////
8caa4ed1 2// Name: msw/utils.cpp
2bda0e17
KB
3// Purpose: Various utilities
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
6c9a19aa 8// Copyright: (c) Julian Smart
65571936 9// Licence: wxWindows licence
2bda0e17
KB
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
2bda0e17
KB
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
a4f96412 24 #pragma hdrstop
2bda0e17
KB
25#endif
26
27#ifndef WX_PRECOMP
a4f96412
VZ
28 #include "wx/utils.h"
29 #include "wx/app.h"
1f0500b3
VZ
30 #include "wx/intl.h"
31 #include "wx/log.h"
743e0a66 32#endif //WX_PRECOMP
2bda0e17 33
2739d4f0 34#include "wx/apptrait.h"
15cdcf6a 35#include "wx/dynload.h"
2739d4f0 36
2dc357ea
VZ
37#include "wx/confbase.h" // for wxExpandEnvVars()
38
b568d04f 39#include "wx/msw/private.h" // includes <windows.h>
fcd0c90f 40#include "wx/msw/missing.h" // CHARSET_HANGUL
b568d04f 41
3c302c07
MB
42#if defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) \
43 || defined(__CYGWIN32__)
c1cb4153
VZ
44 // apparently we need to include winsock.h to get WSADATA and other stuff
45 // used in wxGetFullHostName() with the old mingw32 versions
46 #include <winsock.h>
47#endif
48
2bda0e17
KB
49#include "wx/timer.h"
50
4676948b 51#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
a4f96412 52 #include <direct.h>
ce3ed50d 53
a4f96412
VZ
54 #ifndef __MWERKS__
55 #include <dos.h>
56 #endif
743e0a66 57#endif //GNUWIN32
2bda0e17 58
b39dbf34 59#if defined(__CYGWIN__)
a4f96412
VZ
60 #include <sys/unistd.h>
61 #include <sys/stat.h>
3ffbc733 62 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
743e0a66
VZ
63#endif //GNUWIN32
64
2bda0e17
KB
65#ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
66 // this (3.1 I believe) and how to test for it.
67 // If this works for Borland 4.0 as well, then no worries.
a4f96412 68 #include <dir.h>
2bda0e17
KB
69#endif
70
a4f96412
VZ
71// VZ: there is some code using NetXXX() functions to get the full user name:
72// I don't think it's a good idea because they don't work under Win95 and
73// seem to return the same as wxGetUserId() under NT. If you really want
74// to use them, just #define USE_NET_API
75#undef USE_NET_API
76
77#ifdef USE_NET_API
78 #include <lm.h>
79#endif // USE_NET_API
80
4676948b 81#if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
2e38557f
JS
82 #ifndef __UNIX__
83 #include <io.h>
84 #endif
2bda0e17 85
a4f96412
VZ
86 #ifndef __GNUWIN32__
87 #include <shellapi.h>
88 #endif
2bda0e17
KB
89#endif
90
2bda0e17 91#ifndef __WATCOMC__
3f4a0c5b
VZ
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
93 #include <errno.h>
94 #endif
2bda0e17 95#endif
2bda0e17 96
e0f6b731
JS
97// For wxKillAllChildren
98#include <tlhelp32.h>
99
b568d04f
VZ
100// ----------------------------------------------------------------------------
101// constants
102// ----------------------------------------------------------------------------
103
2bda0e17 104// In the WIN.INI file
e7d9c398 105static const wxChar WX_SECTION[] = wxT("wxWindows");
b568d04f
VZ
106static const wxChar eUSERNAME[] = wxT("UserName");
107
b568d04f
VZ
108// ============================================================================
109// implementation
110// ============================================================================
2bda0e17 111
b568d04f
VZ
112// ----------------------------------------------------------------------------
113// get host name and related
114// ----------------------------------------------------------------------------
2bda0e17 115
1f0500b3 116// Get hostname only (without domain name)
837e5743 117bool wxGetHostName(wxChar *buf, int maxSize)
2bda0e17 118{
4676948b 119#if defined(__WXWINCE__)
7010702f 120 return false;
4676948b 121#elif defined(__WIN32__) && !defined(__WXMICROWIN__)
b568d04f
VZ
122 DWORD nSize = maxSize;
123 if ( !::GetComputerName(buf, &nSize) )
124 {
f6bcfd97 125 wxLogLastError(wxT("GetComputerName"));
b568d04f 126
7010702f 127 return false;
b568d04f
VZ
128 }
129
27d2dbbc 130 return true;
2bda0e17 131#else
b568d04f
VZ
132 wxChar *sysname;
133 const wxChar *default_host = wxT("noname");
134
135 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
136 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
137 } else
138 wxStrncpy(buf, sysname, maxSize - 1);
139 buf[maxSize] = wxT('\0');
27d2dbbc 140 return *buf ? true : false;
2bda0e17
KB
141#endif
142}
143
1f0500b3 144// get full hostname (with domain name if possible)
b568d04f
VZ
145bool wxGetFullHostName(wxChar *buf, int maxSize)
146{
ffcb4ee4 147#if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER
1f0500b3 148 // TODO should use GetComputerNameEx() when available
79180098 149
15cdcf6a 150 // we don't want to always link with Winsock DLL as we might not use it at
7b28e0ed
VZ
151 // all, so load it dynamically here if needed (and don't complain if it is
152 // missing, we handle this)
153 wxLogNull noLog;
154
15cdcf6a
VZ
155 wxDynamicLibrary dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM);
156 if ( dllWinsock.IsLoaded() )
1f0500b3 157 {
15cdcf6a
VZ
158 typedef int (PASCAL *WSAStartup_t)(WORD, WSADATA *);
159 typedef int (PASCAL *gethostname_t)(char *, int);
160 typedef hostent* (PASCAL *gethostbyname_t)(const char *);
161 typedef hostent* (PASCAL *gethostbyaddr_t)(const char *, int , int);
162 typedef int (PASCAL *WSACleanup_t)(void);
1f0500b3 163
15cdcf6a
VZ
164 #define LOAD_WINSOCK_FUNC(func) \
165 func ## _t \
166 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func))
1f0500b3 167
15cdcf6a
VZ
168 LOAD_WINSOCK_FUNC(WSAStartup);
169
170 WSADATA wsa;
171 if ( pfnWSAStartup && pfnWSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
172 {
173 LOAD_WINSOCK_FUNC(gethostname);
174
175 wxString host;
176 if ( pfngethostname )
177 {
178 char bufA[256];
179 if ( pfngethostname(bufA, WXSIZEOF(bufA)) == 0 )
1f0500b3 180 {
15cdcf6a
VZ
181 // gethostname() won't usually include the DNS domain name,
182 // for this we need to work a bit more
183 if ( !strchr(bufA, '.') )
184 {
185 LOAD_WINSOCK_FUNC(gethostbyname);
186
187 struct hostent *pHostEnt = pfngethostbyname
188 ? pfngethostbyname(bufA)
189 : NULL;
190
191 if ( pHostEnt )
192 {
193 // Windows will use DNS internally now
194 LOAD_WINSOCK_FUNC(gethostbyaddr);
195
196 pHostEnt = pfngethostbyaddr
197 ? pfngethostbyaddr(pHostEnt->h_addr,
198 4, AF_INET)
199 : NULL;
200 }
201
202 if ( pHostEnt )
203 {
204 host = wxString::FromAscii(pHostEnt->h_name);
205 }
206 }
1f0500b3
VZ
207 }
208 }
1f0500b3 209
15cdcf6a
VZ
210 LOAD_WINSOCK_FUNC(WSACleanup);
211 if ( pfnWSACleanup )
212 pfnWSACleanup();
1f0500b3 213
1f0500b3 214
15cdcf6a
VZ
215 if ( !host.empty() )
216 {
217 wxStrncpy(buf, host, maxSize);
218
27d2dbbc 219 return true;
15cdcf6a 220 }
1f0500b3
VZ
221 }
222 }
15cdcf6a 223#endif // !__WXMICROWIN__
1f0500b3 224
b568d04f
VZ
225 return wxGetHostName(buf, maxSize);
226}
227
2bda0e17 228// Get user ID e.g. jacs
837e5743 229bool wxGetUserId(wxChar *buf, int maxSize)
2bda0e17 230{
4676948b 231#if defined(__WXWINCE__)
7010702f 232 return false;
3a5bcc4d 233#elif defined(__WIN32__) && !defined(__WXMICROWIN__)
0a144271
VZ
234 DWORD nSize = maxSize;
235 if ( ::GetUserName(buf, &nSize) == 0 )
236 {
a4f96412 237 // actually, it does happen on Win9x if the user didn't log on
223d09f6 238 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
a4f96412
VZ
239 if ( res == 0 )
240 {
241 // not found
27d2dbbc 242 return false;
a4f96412 243 }
0a144271
VZ
244 }
245
27d2dbbc 246 return true;
3a5bcc4d 247#else // __WXMICROWIN__
b568d04f
VZ
248 wxChar *user;
249 const wxChar *default_id = wxT("anonymous");
2bda0e17 250
b568d04f
VZ
251 // Can't assume we have NIS (PC-NFS) or some other ID daemon
252 // So we ...
253 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
254 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
255 {
77ffb593 256 // Use wxWidgets configuration data (comming soon)
b568d04f
VZ
257 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
258 }
259 else
260 {
261 wxStrncpy(buf, user, maxSize - 1);
262 }
a4f96412 263
27d2dbbc 264 return *buf ? true : false;
2bda0e17
KB
265#endif
266}
267
268// Get user name e.g. Julian Smart
837e5743 269bool wxGetUserName(wxChar *buf, int maxSize)
2bda0e17 270{
4676948b 271#if defined(__WXWINCE__)
7010702f 272 return false;
4676948b 273#elif defined(USE_NET_API)
3e3be693
VZ
274 CHAR szUserName[256];
275 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
7010702f 276 return false;
a4f96412 277
3e3be693
VZ
278 // TODO how to get the domain name?
279 CHAR *szDomain = "";
a4f96412 280
3e3be693
VZ
281 // the code is based on the MSDN example (also see KB article Q119670)
282 WCHAR wszUserName[256]; // Unicode user name
283 WCHAR wszDomain[256];
284 LPBYTE ComputerName;
a4f96412 285
3e3be693 286 USER_INFO_2 *ui2; // User structure
a4f96412 287
3e3be693
VZ
288 // Convert ANSI user name and domain to Unicode
289 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
290 wszUserName, WXSIZEOF(wszUserName) );
291 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
292 wszDomain, WXSIZEOF(wszDomain) );
a4f96412 293
3e3be693
VZ
294 // Get the computer name of a DC for the domain.
295 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
296 {
297 wxLogError(wxT("Can not find domain controller"));
a4f96412 298
3e3be693
VZ
299 goto error;
300 }
a4f96412 301
3e3be693
VZ
302 // Look up the user on the DC
303 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
304 (LPWSTR)&wszUserName,
305 2, // level - we want USER_INFO_2
306 (LPBYTE *) &ui2 );
307 switch ( status )
308 {
309 case NERR_Success:
310 // ok
311 break;
a4f96412 312
3e3be693
VZ
313 case NERR_InvalidComputer:
314 wxLogError(wxT("Invalid domain controller name."));
a4f96412 315
3e3be693 316 goto error;
a4f96412 317
3e3be693
VZ
318 case NERR_UserNotFound:
319 wxLogError(wxT("Invalid user name '%s'."), szUserName);
a4f96412 320
3e3be693 321 goto error;
a4f96412 322
3e3be693
VZ
323 default:
324 wxLogSysError(wxT("Can't get information about user"));
a4f96412 325
3e3be693
VZ
326 goto error;
327 }
a4f96412 328
3e3be693
VZ
329 // Convert the Unicode full name to ANSI
330 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
331 buf, maxSize, NULL, NULL );
a4f96412 332
27d2dbbc 333 return true;
a4f96412
VZ
334
335error:
3e3be693 336 wxLogError(wxT("Couldn't look up full user name."));
a4f96412 337
27d2dbbc 338 return false;
a4f96412 339#else // !USE_NET_API
3e3be693 340 // Could use NIS, MS-Mail or other site specific programs
77ffb593 341 // Use wxWidgets configuration data
fda7962d 342 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0;
3e3be693
VZ
343 if ( !ok )
344 {
345 ok = wxGetUserId(buf, maxSize);
346 }
0a144271 347
3e3be693
VZ
348 if ( !ok )
349 {
350 wxStrncpy(buf, wxT("Unknown User"), maxSize);
b568d04f 351 }
3e3be693 352#endif // Win32/16
0a144271 353
27d2dbbc 354 return true;
2bda0e17
KB
355}
356
b568d04f 357const wxChar* wxGetHomeDir(wxString *pstr)
2bda0e17 358{
2dc357ea 359 wxString& strDir = *pstr;
2bda0e17 360
2dc357ea 361 // first branch is for Cygwin
4676948b 362#if defined(__UNIX__)
b568d04f
VZ
363 const wxChar *szHome = wxGetenv("HOME");
364 if ( szHome == NULL ) {
365 // we're homeless...
366 wxLogWarning(_("can't find user's HOME, using current directory."));
367 strDir = wxT(".");
368 }
369 else
370 strDir = szHome;
2bda0e17 371
b568d04f
VZ
372 // add a trailing slash if needed
373 if ( strDir.Last() != wxT('/') )
374 strDir << wxT('/');
3ffbc733 375
e02e8816 376 #ifdef __CYGWIN__
2dc357ea
VZ
377 // Cygwin returns unix type path but that does not work well
378 static wxChar windowsPath[MAX_PATH];
379 cygwin_conv_to_full_win32_path(strDir, windowsPath);
380 strDir = windowsPath;
3ffbc733 381 #endif
4676948b
JS
382#elif defined(__WXWINCE__)
383 // Nothing
384#else
2dc357ea 385 strDir.clear();
96c21216 386
2dc357ea
VZ
387 // If we have a valid HOME directory, as is used on many machines that
388 // have unix utilities on them, we should use that.
389 const wxChar *szHome = wxGetenv(wxT("HOME"));
96c21216 390
2dc357ea
VZ
391 if ( szHome != NULL )
392 {
96c21216 393 strDir = szHome;
2dc357ea
VZ
394 }
395 else // no HOME, try HOMEDRIVE/PATH
396 {
397 szHome = wxGetenv(wxT("HOMEDRIVE"));
398 if ( szHome != NULL )
96c21216 399 strDir << szHome;
2dc357ea 400 szHome = wxGetenv(wxT("HOMEPATH"));
96c21216 401
2dc357ea
VZ
402 if ( szHome != NULL )
403 {
96c21216
VZ
404 strDir << szHome;
405
406 // the idea is that under NT these variables have default values
407 // of "%systemdrive%:" and "\\". As we don't want to create our
408 // config files in the root directory of the system drive, we will
409 // create it in our program's dir. However, if the user took care
410 // to set HOMEPATH to something other than "\\", we suppose that he
411 // knows what he is doing and use the supplied value.
412 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
2dc357ea
VZ
413 strDir.clear();
414 }
415 }
96c21216 416
2dc357ea
VZ
417 if ( strDir.empty() )
418 {
419 // If we have a valid USERPROFILE directory, as is the case in
420 // Windows NT, 2000 and XP, we should use that as our home directory.
421 szHome = wxGetenv(wxT("USERPROFILE"));
2bda0e17 422
2dc357ea 423 if ( szHome != NULL )
96c21216 424 strDir = szHome;
2dc357ea 425 }
2bda0e17 426
2dc357ea
VZ
427 if ( !strDir.empty() )
428 {
429 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
430 // value once again, it shouldn't hurt anyhow
431 strDir = wxExpandEnvVars(strDir);
432 }
433 else // fall back to the program directory
434 {
77d8d6cd
VZ
435 // extract the directory component of the program file name
436 wxSplitPath(wxGetFullModuleName(), &strDir, NULL, NULL);
2dc357ea 437 }
4676948b 438#endif // UNIX/Win
b568d04f 439
2dc357ea 440 return strDir.c_str();
afb74891
VZ
441}
442
33ac7e6f 443wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
2bda0e17 444{
b568d04f
VZ
445 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
446 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
447 // static buffer and sometimes I don't even know what.
448 static wxString s_home;
2bda0e17 449
b568d04f 450 return (wxChar *)wxGetHomeDir(&s_home);
2bda0e17
KB
451}
452
b568d04f 453bool wxDirExists(const wxString& dir)
2bda0e17 454{
04ef50df
JS
455#ifdef __WXMICROWIN__
456 return wxPathExist(dir);
457#elif defined(__WIN32__)
cf1eeea3 458 DWORD attribs = GetFileAttributes(dir);
3897b707 459 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
3a5bcc4d 460#endif // Win32/__WXMICROWIN__
b568d04f 461}
2bda0e17 462
eadd7bd2
VZ
463bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
464{
4676948b 465#ifdef __WXWINCE__
7010702f 466 return false;
4676948b 467#else
eadd7bd2 468 if ( path.empty() )
7010702f 469 return false;
eadd7bd2 470
ee88cb34
MB
471// old w32api don't have ULARGE_INTEGER
472#if defined(__WIN32__) && \
473 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
eadd7bd2
VZ
474 // GetDiskFreeSpaceEx() is not available under original Win95, check for
475 // it
9ee966ec
VZ
476 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
477 PULARGE_INTEGER,
478 PULARGE_INTEGER,
479 PULARGE_INTEGER);
eadd7bd2
VZ
480
481 GetDiskFreeSpaceEx_t
bb0e27ee 482 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
eadd7bd2
VZ
483 (
484 ::GetModuleHandle(_T("kernel32.dll")),
485#if wxUSE_UNICODE
486 "GetDiskFreeSpaceExW"
487#else
488 "GetDiskFreeSpaceExA"
489#endif
490 );
491
492 if ( pGetDiskFreeSpaceEx )
493 {
494 ULARGE_INTEGER bytesFree, bytesTotal;
495
496 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
497 if ( !pGetDiskFreeSpaceEx(path,
498 &bytesFree,
499 &bytesTotal,
500 NULL) )
501 {
502 wxLogLastError(_T("GetDiskFreeSpaceEx"));
503
27d2dbbc 504 return false;
eadd7bd2
VZ
505 }
506
221e1181
VZ
507 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
508 // two 32 bit fields which may be or may be not named - try to make it
509 // compile in all cases
510#if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
511 #define UL(ul) ul.u
512#else // anon union
513 #define UL(ul) ul
514#endif
eadd7bd2
VZ
515 if ( pTotal )
516 {
221e1181 517 *pTotal = wxLongLong(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
eadd7bd2
VZ
518 }
519
520 if ( pFree )
521 {
221e1181 522 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
eadd7bd2
VZ
523 }
524 }
525 else
526#endif // Win32
527 {
bb0e27ee
VZ
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
eadd7bd2
VZ
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,
540 &lSectorsPerCluster,
541 &lBytesPerSector,
542 &lNumberOfFreeClusters,
543 &lTotalNumberOfClusters) )
544 {
545 wxLogLastError(_T("GetDiskFreeSpace"));
546
27d2dbbc 547 return false;
eadd7bd2
VZ
548 }
549
eadd7bd2
VZ
550 wxLongLong lBytesPerCluster = 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
27d2dbbc 566 return true;
4676948b
JS
567#endif
568 // __WXWINCE__
eadd7bd2
VZ
569}
570
308978f6
VZ
571// ----------------------------------------------------------------------------
572// env vars
573// ----------------------------------------------------------------------------
574
575bool wxGetEnv(const wxString& var, wxString *value)
576{
4676948b 577#ifdef __WXWINCE__
27d2dbbc 578 return false;
e622dd68 579#else // Win32
308978f6
VZ
580 // first get the size of the buffer
581 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
582 if ( !dwRet )
583 {
584 // this means that there is no such variable
27d2dbbc 585 return false;
308978f6
VZ
586 }
587
588 if ( value )
589 {
de564874
MB
590 (void)::GetEnvironmentVariable(var, wxStringBuffer(*value, dwRet),
591 dwRet);
308978f6
VZ
592 }
593
27d2dbbc 594 return true;
3a5bcc4d 595#endif // WinCE/32
308978f6
VZ
596}
597
1fb45475
VZ
598bool wxSetEnv(const wxString& var, const wxChar *value)
599{
600 // some compilers have putenv() or _putenv() or _wputenv() but it's better
601 // to always use Win32 function directly instead of dealing with them
4676948b 602#if defined(__WIN32__) && !defined(__WXWINCE__)
1fb45475
VZ
603 if ( !::SetEnvironmentVariable(var, value) )
604 {
605 wxLogLastError(_T("SetEnvironmentVariable"));
606
27d2dbbc 607 return false;
1fb45475
VZ
608 }
609
27d2dbbc 610 return true;
1fb45475 611#else // no way to set env vars
27d2dbbc 612 return false;
1fb45475
VZ
613#endif
614}
615
b568d04f
VZ
616// ----------------------------------------------------------------------------
617// process management
618// ----------------------------------------------------------------------------
619
50567b69
VZ
620// structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
621struct wxFindByPidParams
b568d04f 622{
50567b69
VZ
623 wxFindByPidParams() { hwnd = 0; pid = 0; }
624
625 // the HWND used to return the result
626 HWND hwnd;
627
628 // the PID we're looking from
629 DWORD pid;
22f3361e
VZ
630
631 DECLARE_NO_COPY_CLASS(wxFindByPidParams)
50567b69
VZ
632};
633
634// wxKill helper: EnumWindows() callback which is used to find the first (top
635// level) window belonging to the given process
636BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
637{
638 DWORD pid;
639 (void)::GetWindowThreadProcessId(hwnd, &pid);
640
641 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
642 if ( pid == params->pid )
643 {
644 // remember the window we found
645 params->hwnd = hwnd;
646
647 // return FALSE to stop the enumeration
648 return FALSE;
649 }
650
651 // continue enumeration
652 return TRUE;
653}
e949bf13 654
e0f6b731
JS
655int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc);
656
657int wxKill(long pid, wxSignal sig, wxKillError *krc, int flags)
50567b69 658{
e0f6b731
JS
659 if (flags & wxKILL_CHILDREN)
660 wxKillAllChildren(pid, sig, krc);
9d8aca48 661
50567b69
VZ
662 // get the process handle to operate on
663 HANDLE hProcess = ::OpenProcess(SYNCHRONIZE |
664 PROCESS_TERMINATE |
665 PROCESS_QUERY_INFORMATION,
666 FALSE, // not inheritable
667 (DWORD)pid);
668 if ( hProcess == NULL )
e949bf13 669 {
50567b69 670 if ( krc )
e949bf13 671 {
50567b69 672 if ( ::GetLastError() == ERROR_ACCESS_DENIED )
e949bf13 673 {
50567b69
VZ
674 *krc = wxKILL_ACCESS_DENIED;
675 }
676 else
677 {
678 *krc = wxKILL_NO_PROCESS;
679 }
680 }
681
682 return -1;
683 }
684
27d2dbbc 685 bool ok = true;
50567b69
VZ
686 switch ( sig )
687 {
688 case wxSIGKILL:
689 // kill the process forcefully returning -1 as error code
690 if ( !::TerminateProcess(hProcess, (UINT)-1) )
691 {
692 wxLogSysError(_("Failed to kill process %d"), pid);
693
694 if ( krc )
e949bf13 695 {
50567b69
VZ
696 // this is not supposed to happen if we could open the
697 // process
698 *krc = wxKILL_ERROR;
e949bf13 699 }
50567b69 700
27d2dbbc 701 ok = false;
e949bf13 702 }
50567b69
VZ
703 break;
704
705 case wxSIGNONE:
706 // do nothing, we just want to test for process existence
707 break;
708
709 default:
710 // any other signal means "terminate"
711 {
712 wxFindByPidParams params;
713 params.pid = (DWORD)pid;
714
715 // EnumWindows() has nice semantics: it returns 0 if it found
716 // something or if an error occured and non zero if it
717 // enumerated all the window
718 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
719 {
720 // did we find any window?
721 if ( params.hwnd )
722 {
723 // tell the app to close
724 //
725 // NB: this is the harshest way, the app won't have
726 // opportunity to save any files, for example, but
727 // this is probably what we want here. If not we
728 // can also use SendMesageTimeout(WM_CLOSE)
729 if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
730 {
731 wxLogLastError(_T("PostMessage(WM_QUIT)"));
732 }
733 }
734 else // it was an error then
735 {
736 wxLogLastError(_T("EnumWindows"));
737
27d2dbbc 738 ok = false;
50567b69
VZ
739 }
740 }
741 else // no windows for this PID
742 {
743 if ( krc )
744 {
745 *krc = wxKILL_ERROR;
746 }
747
27d2dbbc 748 ok = false;
50567b69
VZ
749 }
750 }
751 }
752
753 // the return code
754 DWORD rc;
755
756 if ( ok )
757 {
758 // as we wait for a short time, we can use just WaitForSingleObject()
759 // and not MsgWaitForMultipleObjects()
760 switch ( ::WaitForSingleObject(hProcess, 500 /* msec */) )
761 {
762 case WAIT_OBJECT_0:
763 // process terminated
764 if ( !::GetExitCodeProcess(hProcess, &rc) )
765 {
766 wxLogLastError(_T("GetExitCodeProcess"));
767 }
768 break;
769
770 default:
771 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
772 // fall through
773
774 case WAIT_FAILED:
775 wxLogLastError(_T("WaitForSingleObject"));
776 // fall through
777
778 case WAIT_TIMEOUT:
779 if ( krc )
780 {
781 *krc = wxKILL_ERROR;
782 }
783
784 rc = STILL_ACTIVE;
785 break;
e949bf13
JS
786 }
787 }
50567b69
VZ
788 else // !ok
789 {
790 // just to suppress the warnings about uninitialized variable
791 rc = 0;
792 }
e949bf13 793
50567b69 794 ::CloseHandle(hProcess);
b568d04f 795
50567b69
VZ
796 // the return code is the same as from Unix kill(): 0 if killed
797 // successfully or -1 on error
b1a28eef
VZ
798 //
799 // be careful to interpret rc correctly: for wxSIGNONE we return success if
800 // the process exists, for all the other sig values -- if it doesn't
801 if ( ok &&
802 ((sig == wxSIGNONE) == (rc == STILL_ACTIVE)) )
e949bf13 803 {
b1a28eef 804 if ( krc )
50567b69 805 {
b1a28eef 806 *krc = wxKILL_OK;
50567b69 807 }
b1a28eef
VZ
808
809 return 0;
e949bf13 810 }
50567b69
VZ
811
812 // error
813 return -1;
2bda0e17
KB
814}
815
e0f6b731
JS
816HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
817BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
818BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
9d8aca48 819
e0f6b731
JS
820static void InitToolHelp32()
821{
822 static bool s_initToolHelpDone = false;
9d8aca48 823
e0f6b731
JS
824 if (s_initToolHelpDone)
825 return;
9d8aca48 826
e0f6b731
JS
827 s_initToolHelpDone = true;
828
829 lpfCreateToolhelp32Snapshot = NULL;
830 lpfProcess32First = NULL;
831 lpfProcess32Next = NULL;
9d8aca48 832
ade0e73d 833 HINSTANCE hInstLib = LoadLibrary( wxT("Kernel32.DLL") ) ;
e0f6b731
JS
834 if( hInstLib == NULL )
835 return ;
9d8aca48 836
e0f6b731
JS
837 // Get procedure addresses.
838 // We are linking to these functions of Kernel32
839 // explicitly, because otherwise a module using
840 // this code would fail to load under Windows NT,
841 // which does not have the Toolhelp32
842 // functions in the Kernel 32.
843 lpfCreateToolhelp32Snapshot=
844 (HANDLE(WINAPI *)(DWORD,DWORD))
845 GetProcAddress( hInstLib,
885b88a2
JS
846#ifdef __WXWINCE__
847 wxT("CreateToolhelp32Snapshot")
848#else
849 "CreateToolhelp32Snapshot"
850#endif
851 ) ;
9d8aca48 852
e0f6b731
JS
853 lpfProcess32First=
854 (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
885b88a2
JS
855 GetProcAddress( hInstLib,
856#ifdef __WXWINCE__
857 wxT("Process32First")
858#else
859 "Process32First"
860#endif
861 ) ;
e0f6b731
JS
862
863 lpfProcess32Next=
864 (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
885b88a2
JS
865 GetProcAddress( hInstLib,
866#ifdef __WXWINCE__
867 wxT("Process32Next")
868#else
869 "Process32Next"
870#endif
871 ) ;
e0f6b731
JS
872
873 FreeLibrary( hInstLib ) ;
874}
875
876// By John Skiff
877int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc)
878{
879 InitToolHelp32();
9d8aca48 880
e0f6b731
JS
881 if (krc)
882 *krc = wxKILL_OK;
9d8aca48 883
e0f6b731
JS
884 // If not implemented for this platform (e.g. NT 4.0), silently ignore
885 if (!lpfCreateToolhelp32Snapshot || !lpfProcess32First || !lpfProcess32Next)
886 return 0;
9d8aca48 887
e0f6b731
JS
888 // Take a snapshot of all processes in the system.
889 HANDLE hProcessSnap = lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
890 if (hProcessSnap == INVALID_HANDLE_VALUE) {
891 if (krc)
892 *krc = wxKILL_ERROR;
893 return -1;
894 }
9d8aca48 895
e0f6b731
JS
896 //Fill in the size of the structure before using it.
897 PROCESSENTRY32 pe = {0};
898 pe.dwSize = sizeof(PROCESSENTRY32);
9d8aca48 899
e0f6b731
JS
900 // Walk the snapshot of the processes, and for each process,
901 // kill it if its parent is pid.
902 if (!lpfProcess32First(hProcessSnap, &pe)) {
903 // Can't get first process.
904 if (krc)
905 *krc = wxKILL_ERROR;
906 CloseHandle (hProcessSnap);
907 return -1;
908 }
9d8aca48 909
e0f6b731
JS
910 do {
911 if (pe.th32ParentProcessID == (DWORD) pid) {
912 if (wxKill(pe.th32ProcessID, sig, krc))
913 return -1;
914 }
915 } while (lpfProcess32Next (hProcessSnap, &pe));
9d8aca48
WS
916
917
e0f6b731
JS
918 return 0;
919}
920
b568d04f
VZ
921// Execute a program in an Interactive Shell
922bool wxShell(const wxString& command)
2bda0e17 923{
7010702f
WS
924 wxString cmd;
925
4676948b 926#ifdef __WXWINCE__
7010702f 927 cmd = command;
4676948b 928#else
b568d04f
VZ
929 wxChar *shell = wxGetenv(wxT("COMSPEC"));
930 if ( !shell )
ba14d986 931 shell = (wxChar*) wxT("\\COMMAND.COM");
b568d04f 932
b568d04f
VZ
933 if ( !command )
934 {
935 // just the shell
936 cmd = shell;
937 }
938 else
939 {
940 // pass the command to execute to the command processor
941 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
942 }
7010702f 943#endif
b568d04f 944
011a524e 945 return wxExecute(cmd, wxEXEC_SYNC) == 0;
2bda0e17
KB
946}
947
d8c65cf4 948// Shutdown or reboot the PC
f6ba47d9
VZ
949bool wxShutdown(wxShutdownFlags wFlags)
950{
4676948b 951#ifdef __WXWINCE__
27d2dbbc 952 return false;
4676948b 953#elif defined(__WIN32__)
27d2dbbc 954 bool bOK = true;
f6ba47d9
VZ
955
956 if ( wxGetOsVersion(NULL, NULL) == wxWINDOWS_NT ) // if is NT or 2K
957 {
d8c65cf4
RD
958 // Get a token for this process.
959 HANDLE hToken;
f6ba47d9
VZ
960 bOK = ::OpenProcessToken(GetCurrentProcess(),
961 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
962 &hToken) != 0;
963 if ( bOK )
964 {
d8c65cf4 965 TOKEN_PRIVILEGES tkp;
f6ba47d9 966
d8c65cf4 967 // Get the LUID for the shutdown privilege.
f6ba47d9 968 ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
d8c65cf4 969 &tkp.Privileges[0].Luid);
f6ba47d9 970
d8c65cf4
RD
971 tkp.PrivilegeCount = 1; // one privilege to set
972 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
f6ba47d9 973
d8c65cf4 974 // Get the shutdown privilege for this process.
f6ba47d9 975 ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
d8c65cf4 976 (PTOKEN_PRIVILEGES)NULL, 0);
f6ba47d9 977
d8c65cf4 978 // Cannot test the return value of AdjustTokenPrivileges.
f6ba47d9
VZ
979 bOK = ::GetLastError() == ERROR_SUCCESS;
980 }
981 }
982
983 if ( bOK )
984 {
985 UINT flags = EWX_SHUTDOWN | EWX_FORCE;
986 switch ( wFlags )
987 {
988 case wxSHUTDOWN_POWEROFF:
989 flags |= EWX_POWEROFF;
990 break;
991
992 case wxSHUTDOWN_REBOOT:
993 flags |= EWX_REBOOT;
994 break;
995
996 default:
997 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
27d2dbbc 998 return false;
f6ba47d9
VZ
999 }
1000
999836aa 1001 bOK = ::ExitWindowsEx(flags, 0) != 0;
f6ba47d9
VZ
1002 }
1003
1004 return bOK;
f6ba47d9
VZ
1005#endif // Win32/16
1006}
1007
b568d04f
VZ
1008// ----------------------------------------------------------------------------
1009// misc
1010// ----------------------------------------------------------------------------
1011
1012// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
9d8aca48 1013wxMemorySize wxGetFreeMemory()
2bda0e17 1014{
9d8aca48
WS
1015#if defined(__WIN64__)
1016 MEMORYSTATUSEX memStatex;
1017 statex.dwLength = sizeof (statex);
1018 GlobalMemoryStatusEx (&statex);
1019 return (wxMemorySize)memStatus.ullAvailPhys;
1020#elif defined(__WIN32__) && !defined(__BORLANDC__)
b568d04f
VZ
1021 MEMORYSTATUS memStatus;
1022 memStatus.dwLength = sizeof(MEMORYSTATUS);
1023 GlobalMemoryStatus(&memStatus);
9d8aca48 1024 return (wxMemorySize)memStatus.dwAvailPhys;
b568d04f 1025#else
9d8aca48 1026 return (wxMemorySize)GetFreeSpace(0);
b568d04f 1027#endif
2bda0e17
KB
1028}
1029
c1cb4153
VZ
1030unsigned long wxGetProcessId()
1031{
c1cb4153 1032 return ::GetCurrentProcessId();
c1cb4153
VZ
1033}
1034
2bda0e17 1035// Emit a beeeeeep
634903fd 1036void wxBell()
2bda0e17 1037{
b568d04f 1038 ::MessageBeep((UINT)-1); // default sound
2bda0e17
KB
1039}
1040
bdc72a22 1041wxString wxGetOsDescription()
2bda0e17 1042{
bdc72a22
VZ
1043 wxString str;
1044
1045 OSVERSIONINFO info;
1046 wxZeroMemory(info);
1047
1048 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1049 if ( ::GetVersionEx(&info) )
1050 {
1051 switch ( info.dwPlatformId )
1052 {
1053 case VER_PLATFORM_WIN32s:
1054 str = _("Win32s on Windows 3.1");
1055 break;
1056
1057 case VER_PLATFORM_WIN32_WINDOWS:
db1d0193
VZ
1058 switch (info.dwMinorVersion)
1059 {
1060 case 0:
1061 if ( info.szCSDVersion[1] == 'B' ||
1062 info.szCSDVersion[1] == 'C' )
1063 {
1064 str = _("Windows 95 OSR2");
1065 }
1066 else
1067 {
1068 str = _("Windows 95");
1069 }
1070 break;
1071 case 10:
1072 if ( info.szCSDVersion[1] == 'B' ||
1073 info.szCSDVersion[1] == 'C' )
1074 {
1075 str = _("Windows 98 SE");
1076 }
1077 else
1078 {
1079 str = _("Windows 98");
1080 }
1081 break;
1082 case 90:
1083 str = _("Windows ME");
1084 break;
1085 default:
1086 str.Printf(_("Windows 9x (%d.%d)"),
1087 info.dwMajorVersion,
1088 info.dwMinorVersion);
1089 break;
1090 }
bdc72a22
VZ
1091 if ( !wxIsEmpty(info.szCSDVersion) )
1092 {
1093 str << _T(" (") << info.szCSDVersion << _T(')');
1094 }
1095 break;
1096
1097 case VER_PLATFORM_WIN32_NT:
db1d0193
VZ
1098 if ( info.dwMajorVersion == 5 )
1099 {
1100 switch ( info.dwMinorVersion )
1101 {
1102 case 0:
1103 str.Printf(_("Windows 2000 (build %lu"),
1104 info.dwBuildNumber);
1105 break;
1106 case 1:
1107 str.Printf(_("Windows XP (build %lu"),
1108 info.dwBuildNumber);
1109 break;
1110 case 2:
1111 str.Printf(_("Windows Server 2003 (build %lu"),
1112 info.dwBuildNumber);
1113 break;
1114 }
1115 }
1116 if ( wxIsEmpty(str) )
1117 {
1118 str.Printf(_("Windows NT %lu.%lu (build %lu"),
bdc72a22
VZ
1119 info.dwMajorVersion,
1120 info.dwMinorVersion,
1121 info.dwBuildNumber);
db1d0193 1122 }
bdc72a22
VZ
1123 if ( !wxIsEmpty(info.szCSDVersion) )
1124 {
1125 str << _T(", ") << info.szCSDVersion;
1126 }
1127 str << _T(')');
1128 break;
1129 }
1130 }
1131 else
1132 {
1133 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1134 }
1135
1136 return str;
bdc72a22 1137}
6f65e337 1138
324899f6 1139wxToolkitInfo& wxAppTraits::GetToolkitInfo()
bdc72a22 1140{
2739d4f0
VZ
1141 // cache the version info, it's not going to change
1142 //
1143 // NB: this is MT-safe, we may use these static vars from different threads
1144 // but as they always have the same value it doesn't matter
1145 static int s_ver = -1,
1146 s_major = -1,
1147 s_minor = -1;
96c21216 1148
2739d4f0 1149 if ( s_ver == -1 )
bdc72a22 1150 {
6af638ed
VS
1151 OSVERSIONINFO info;
1152 wxZeroMemory(info);
ec5d7799 1153
2739d4f0 1154 s_ver = wxWINDOWS;
6af638ed
VS
1155 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1156 if ( ::GetVersionEx(&info) )
bdc72a22 1157 {
2739d4f0
VZ
1158 s_major = info.dwMajorVersion;
1159 s_minor = info.dwMinorVersion;
bdc72a22 1160
6af638ed
VS
1161 switch ( info.dwPlatformId )
1162 {
1163 case VER_PLATFORM_WIN32s:
2739d4f0 1164 s_ver = wxWIN32S;
6af638ed 1165 break;
bdc72a22 1166
6af638ed 1167 case VER_PLATFORM_WIN32_WINDOWS:
2739d4f0 1168 s_ver = wxWIN95;
6af638ed
VS
1169 break;
1170
1171 case VER_PLATFORM_WIN32_NT:
2739d4f0 1172 s_ver = wxWINDOWS_NT;
6af638ed 1173 break;
471085e4 1174#ifdef __WXWINCE__
f07dc2e2
JS
1175 case VER_PLATFORM_WIN32_CE:
1176 s_ver = wxWINDOWS_CE;
1177 break;
eccd1992 1178#endif
6af638ed 1179 }
bdc72a22
VZ
1180 }
1181 }
1182
eccd1992 1183 static wxToolkitInfo info;
a8eaaeb2
VS
1184 info.versionMajor = s_major;
1185 info.versionMinor = s_minor;
1186 info.os = s_ver;
1187 info.name = _T("wxBase");
324899f6 1188 return info;
2bda0e17
KB
1189}
1190
b568d04f
VZ
1191// ----------------------------------------------------------------------------
1192// sleep functions
1193// ----------------------------------------------------------------------------
1194
08873d36 1195void wxMilliSleep(unsigned long milliseconds)
b568d04f
VZ
1196{
1197 ::Sleep(milliseconds);
1198}
1199
08873d36
VZ
1200void wxMicroSleep(unsigned long microseconds)
1201{
1202 wxMilliSleep(microseconds/1000);
1203}
1204
b568d04f
VZ
1205void wxSleep(int nSecs)
1206{
08873d36 1207 wxMilliSleep(1000*nSecs);
b568d04f
VZ
1208}
1209
b568d04f 1210// ----------------------------------------------------------------------------
e2478fde 1211// font encoding <-> Win32 codepage conversion functions
b568d04f
VZ
1212// ----------------------------------------------------------------------------
1213
bddd7a8d 1214extern WXDLLIMPEXP_BASE long wxEncodingToCharset(wxFontEncoding encoding)
b568d04f 1215{
e2478fde 1216 switch ( encoding )
b568d04f 1217 {
e2478fde
VZ
1218 // although this function is supposed to return an exact match, do do
1219 // some mappings here for the most common case of "standard" encoding
1220 case wxFONTENCODING_SYSTEM:
1221 return DEFAULT_CHARSET;
2bda0e17 1222
e2478fde
VZ
1223 case wxFONTENCODING_ISO8859_1:
1224 case wxFONTENCODING_ISO8859_15:
1225 case wxFONTENCODING_CP1252:
1226 return ANSI_CHARSET;
2bda0e17 1227
e2478fde
VZ
1228#if !defined(__WXMICROWIN__)
1229 // The following four fonts are multi-byte charsets
1230 case wxFONTENCODING_CP932:
1231 return SHIFTJIS_CHARSET;
2bda0e17 1232
e2478fde
VZ
1233 case wxFONTENCODING_CP936:
1234 return GB2312_CHARSET;
2bda0e17 1235
e2478fde
VZ
1236 case wxFONTENCODING_CP949:
1237 return HANGUL_CHARSET;
634903fd 1238
e2478fde
VZ
1239 case wxFONTENCODING_CP950:
1240 return CHINESEBIG5_CHARSET;
2bda0e17 1241
e2478fde
VZ
1242 // The rest are single byte encodings
1243 case wxFONTENCODING_CP1250:
1244 return EASTEUROPE_CHARSET;
bfbd6dc1 1245
e2478fde
VZ
1246 case wxFONTENCODING_CP1251:
1247 return RUSSIAN_CHARSET;
2bda0e17 1248
e2478fde
VZ
1249 case wxFONTENCODING_CP1253:
1250 return GREEK_CHARSET;
b07135ba 1251
e2478fde
VZ
1252 case wxFONTENCODING_CP1254:
1253 return TURKISH_CHARSET;
2bda0e17 1254
e2478fde
VZ
1255 case wxFONTENCODING_CP1255:
1256 return HEBREW_CHARSET;
2bda0e17 1257
e2478fde
VZ
1258 case wxFONTENCODING_CP1256:
1259 return ARABIC_CHARSET;
b568d04f 1260
e2478fde
VZ
1261 case wxFONTENCODING_CP1257:
1262 return BALTIC_CHARSET;
634903fd 1263
e2478fde
VZ
1264 case wxFONTENCODING_CP874:
1265 return THAI_CHARSET;
5acc0d5f 1266#endif // !__WXMICROWIN__
cc2b7472 1267
e2478fde
VZ
1268 case wxFONTENCODING_CP437:
1269 return OEM_CHARSET;
ea28b885
VZ
1270
1271 default:
1272 // no way to translate this encoding into a Windows charset
69557827 1273 return -1;
e2478fde 1274 }
373658eb 1275}
7f555861 1276
e2478fde
VZ
1277// we have 2 versions of wxCharsetToCodepage(): the old one which directly
1278// looks up the vlaues in the registry and the new one which is more
1279// politically correct and has more chances to work on other Windows versions
1280// as well but the old version is still needed for !wxUSE_FONTMAP case
1281#if wxUSE_FONTMAP
c030b70f 1282
373658eb 1283#include "wx/fontmap.h"
c030b70f 1284
bddd7a8d 1285extern WXDLLIMPEXP_BASE long wxEncodingToCodepage(wxFontEncoding encoding)
c030b70f 1286{
373658eb 1287 // translate encoding into the Windows CHARSET
e2478fde
VZ
1288 long charset = wxEncodingToCharset(encoding);
1289 if ( charset == -1 )
373658eb
VZ
1290 return -1;
1291
1292 // translate CHARSET to code page
1293 CHARSETINFO csetInfo;
e2478fde 1294 if ( !::TranslateCharsetInfo((DWORD *)(DWORD)charset,
373658eb
VZ
1295 &csetInfo,
1296 TCI_SRCCHARSET) )
1297 {
1298 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1299
1300 return -1;
1301 }
1302
1303 return csetInfo.ciACP;
c030b70f 1304}
373658eb 1305
373658eb 1306extern long wxCharsetToCodepage(const wxChar *name)
c030b70f 1307{
373658eb
VZ
1308 // first get the font encoding for this charset
1309 if ( !name )
1310 return -1;
1311
27d2dbbc 1312 wxFontEncoding enc = wxFontMapper::Get()->CharsetToEncoding(name, false);
373658eb
VZ
1313 if ( enc == wxFONTENCODING_SYSTEM )
1314 return -1;
1315
1316 // the use the helper function
1317 return wxEncodingToCodepage(enc);
c030b70f 1318}
c030b70f 1319
e2478fde 1320#else // !wxUSE_FONTMAP
373658eb
VZ
1321
1322#include "wx/msw/registry.h"
1323
1324// this should work if Internet Exploiter is installed
1325extern long wxCharsetToCodepage(const wxChar *name)
04ef50df 1326{
373658eb
VZ
1327 if (!name)
1328 return GetACP();
1329
e2478fde 1330 long CP = -1;
373658eb 1331
e2478fde 1332 wxString path(wxT("MIME\\Database\\Charset\\"));
373658eb 1333 wxString cn(name);
373658eb 1334
e2478fde
VZ
1335 // follow the alias loop
1336 for ( ;; )
1337 {
1338 wxRegKey key(wxRegKey::HKCR, path + cn);
1339
1340 if (!key.Exists())
1341 break;
373658eb
VZ
1342
1343 // two cases: either there's an AliasForCharset string,
1344 // or there are Codepage and InternetEncoding dwords.
1345 // The InternetEncoding gives us the actual encoding,
1346 // the Codepage just says which Windows character set to
1347 // use when displaying the data.
1348 if (key.HasValue(wxT("InternetEncoding")) &&
e2478fde
VZ
1349 key.QueryValue(wxT("InternetEncoding"), &CP))
1350 break;
373658eb
VZ
1351
1352 // no encoding, see if it's an alias
1353 if (!key.HasValue(wxT("AliasForCharset")) ||
e2478fde
VZ
1354 !key.QueryValue(wxT("AliasForCharset"), cn))
1355 break;
1356 }
373658eb
VZ
1357
1358 return CP;
04ef50df 1359}
373658eb 1360
e2478fde 1361#endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
c030b70f 1362
eccd1992
VZ
1363/*
1364 Creates a hidden window with supplied window proc registering the class for
1365 it if necesssary (i.e. the first time only). Caller is responsible for
1366 destroying the window and unregistering the class (note that this must be
77ffb593 1367 done because wxWidgets may be used as a DLL and so may be loaded/unloaded
eccd1992
VZ
1368 multiple times into/from the same process so we cna't rely on automatic
1369 Windows class unregistration).
1370
1371 pclassname is a pointer to a caller stored classname, which must initially be
1372 NULL. classname is the desired wndclass classname. If function succesfully
1373 registers the class, pclassname will be set to classname.
1374 */
487f2d58 1375extern "C" WXDLLIMPEXP_BASE HWND
eccd1992
VZ
1376wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc)
1377{
1378 wxCHECK_MSG( classname && pclassname && wndproc, NULL,
1379 _T("NULL parameter in wxCreateHiddenWindow") );
1380
1381 // register the class fi we need to first
1382 if ( *pclassname == NULL )
1383 {
1384 WNDCLASS wndclass;
1385 wxZeroMemory(wndclass);
1386
1387 wndclass.lpfnWndProc = wndproc;
1388 wndclass.hInstance = wxGetInstance();
1389 wndclass.lpszClassName = classname;
1390
1391 if ( !::RegisterClass(&wndclass) )
1392 {
1393 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1394
1395 return NULL;
1396 }
1397
1398 *pclassname = classname;
1399 }
1400
1401 // next create the window
1402 HWND hwnd = ::CreateWindow
1403 (
1404 *pclassname,
1405 NULL,
1406 0, 0, 0, 0,
1407 0,
1408 (HWND) NULL,
1409 (HMENU)NULL,
1410 wxGetInstance(),
1411 (LPVOID) NULL
1412 );
1413
1414 if ( !hwnd )
1415 {
1416 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));
1417 }
1418
1419 return hwnd;
1420}
1421