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