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