]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utils.cpp
Correct making the newly inserted menu item owner drawn in some cases.
[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
6c9a19aa 7// Copyright: (c) Julian Smart
65571936 8// Licence: wxWindows licence
2bda0e17
KB
9/////////////////////////////////////////////////////////////////////////////
10
b568d04f
VZ
11// ============================================================================
12// declarations
13// ============================================================================
14
15// ----------------------------------------------------------------------------
16// headers
17// ----------------------------------------------------------------------------
18
2bda0e17
KB
19// For compilers that support precompilation, includes "wx.h".
20#include "wx/wxprec.h"
21
22#ifdef __BORLANDC__
a4f96412 23 #pragma hdrstop
2bda0e17
KB
24#endif
25
26#ifndef WX_PRECOMP
a4f96412
VZ
27 #include "wx/utils.h"
28 #include "wx/app.h"
1f0500b3
VZ
29 #include "wx/intl.h"
30 #include "wx/log.h"
743e0a66 31#endif //WX_PRECOMP
2bda0e17 32
66d84d11 33#include "wx/msw/registry.h"
2739d4f0 34#include "wx/apptrait.h"
23ee4b48 35#include "wx/dynlib.h"
15cdcf6a 36#include "wx/dynload.h"
a45fb5b4 37#include "wx/scopeguard.h"
b815db22 38#include "wx/filename.h"
2739d4f0 39
2dc357ea
VZ
40#include "wx/confbase.h" // for wxExpandEnvVars()
41
b568d04f 42#include "wx/msw/private.h" // includes <windows.h>
b481194f 43#include "wx/msw/private/hiddenwin.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
2415cf67 62 #include <dos.h>
743e0a66 63#endif //GNUWIN32
2bda0e17 64
b39dbf34 65#if defined(__CYGWIN__)
a4f96412
VZ
66 #include <sys/unistd.h>
67 #include <sys/stat.h>
715e4f7e
VZ
68 #include <sys/cygwin.h> // for cygwin_conv_path()
69 // and cygwin_conv_to_full_win32_path()
70 #include <cygwin/version.h>
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
017dc06b 143 wxStrlcpy(buf, hostName.t_str(), maxSize);
32cdc453 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 {
4c51a665 304 wxLogError(wxT("Cannot 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__)
715e4f7e 370 const wxChar *szHome = wxGetenv(wxT("HOME"));
b568d04f
VZ
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];
715e4f7e
VZ
386 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
387 cygwin_conv_path(CCP_POSIX_TO_WIN_W, strDir, windowsPath, MAX_PATH);
388 #else
389 cygwin_conv_to_full_win32_path(strDir, windowsPath);
390 #endif
2dc357ea 391 strDir = windowsPath;
3ffbc733 392 #endif
4676948b 393#elif defined(__WXWINCE__)
0367d339 394 strDir = wxT("\\");
4676948b 395#else
2dc357ea 396 strDir.clear();
96c21216 397
2dc357ea
VZ
398 // If we have a valid HOME directory, as is used on many machines that
399 // have unix utilities on them, we should use that.
400 const wxChar *szHome = wxGetenv(wxT("HOME"));
96c21216 401
2dc357ea
VZ
402 if ( szHome != NULL )
403 {
96c21216 404 strDir = szHome;
2dc357ea
VZ
405 }
406 else // no HOME, try HOMEDRIVE/PATH
407 {
408 szHome = wxGetenv(wxT("HOMEDRIVE"));
409 if ( szHome != NULL )
96c21216 410 strDir << szHome;
2dc357ea 411 szHome = wxGetenv(wxT("HOMEPATH"));
96c21216 412
2dc357ea
VZ
413 if ( szHome != NULL )
414 {
96c21216
VZ
415 strDir << szHome;
416
417 // the idea is that under NT these variables have default values
418 // of "%systemdrive%:" and "\\". As we don't want to create our
419 // config files in the root directory of the system drive, we will
420 // create it in our program's dir. However, if the user took care
421 // to set HOMEPATH to something other than "\\", we suppose that he
422 // knows what he is doing and use the supplied value.
423 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
2dc357ea
VZ
424 strDir.clear();
425 }
426 }
96c21216 427
2dc357ea
VZ
428 if ( strDir.empty() )
429 {
430 // If we have a valid USERPROFILE directory, as is the case in
431 // Windows NT, 2000 and XP, we should use that as our home directory.
432 szHome = wxGetenv(wxT("USERPROFILE"));
2bda0e17 433
2dc357ea 434 if ( szHome != NULL )
96c21216 435 strDir = szHome;
2dc357ea 436 }
2bda0e17 437
2dc357ea
VZ
438 if ( !strDir.empty() )
439 {
440 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
441 // value once again, it shouldn't hurt anyhow
442 strDir = wxExpandEnvVars(strDir);
443 }
444 else // fall back to the program directory
445 {
77d8d6cd 446 // extract the directory component of the program file name
bd365871 447 wxFileName::SplitPath(wxGetFullModuleName(), &strDir, NULL, NULL);
2dc357ea 448 }
4676948b 449#endif // UNIX/Win
b568d04f 450
2dc357ea 451 return strDir.c_str();
afb74891
VZ
452}
453
14d63513 454wxString wxGetUserHome(const wxString& user)
2bda0e17 455{
14d63513 456 wxString home;
2bda0e17 457
14d63513
VZ
458 if ( user.empty() || user == wxGetUserId() )
459 wxGetHomeDir(&home);
460
461 return home;
2bda0e17
KB
462}
463
7bea7b91 464bool wxGetDiskSpace(const wxString& WXUNUSED_IN_WINCE(path),
7ba7c4e6
VZ
465 wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pTotal),
466 wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pFree))
eadd7bd2 467{
4676948b 468#ifdef __WXWINCE__
040e5f77 469 // TODO-CE
7010702f 470 return false;
4676948b 471#else
eadd7bd2 472 if ( path.empty() )
7010702f 473 return false;
eadd7bd2 474
ee88cb34
MB
475// old w32api don't have ULARGE_INTEGER
476#if defined(__WIN32__) && \
477 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
eadd7bd2
VZ
478 // GetDiskFreeSpaceEx() is not available under original Win95, check for
479 // it
9ee966ec
VZ
480 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
481 PULARGE_INTEGER,
482 PULARGE_INTEGER,
483 PULARGE_INTEGER);
eadd7bd2
VZ
484
485 GetDiskFreeSpaceEx_t
bb0e27ee 486 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
eadd7bd2 487 (
9a83f860 488 ::GetModuleHandle(wxT("kernel32.dll")),
eadd7bd2
VZ
489#if wxUSE_UNICODE
490 "GetDiskFreeSpaceExW"
491#else
492 "GetDiskFreeSpaceExA"
493#endif
494 );
495
496 if ( pGetDiskFreeSpaceEx )
497 {
498 ULARGE_INTEGER bytesFree, bytesTotal;
499
500 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
715e4f7e 501 if ( !pGetDiskFreeSpaceEx(path.t_str(),
eadd7bd2
VZ
502 &bytesFree,
503 &bytesTotal,
504 NULL) )
505 {
9a83f860 506 wxLogLastError(wxT("GetDiskFreeSpaceEx"));
eadd7bd2 507
27d2dbbc 508 return false;
eadd7bd2
VZ
509 }
510
221e1181
VZ
511 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
512 // two 32 bit fields which may be or may be not named - try to make it
513 // compile in all cases
514#if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
515 #define UL(ul) ul.u
516#else // anon union
517 #define UL(ul) ul
518#endif
eadd7bd2
VZ
519 if ( pTotal )
520 {
7ba7c4e6
VZ
521#if wxUSE_LONGLONG
522 *pTotal = wxDiskspaceSize_t(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
523#else
524 *pTotal = wxDiskspaceSize_t(UL(bytesTotal).LowPart);
525#endif
eadd7bd2
VZ
526 }
527
528 if ( pFree )
529 {
7ba7c4e6 530#if wxUSE_LONGLONG
221e1181 531 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
7ba7c4e6
VZ
532#else
533 *pFree = wxDiskspaceSize_t(UL(bytesFree).LowPart);
534#endif
eadd7bd2
VZ
535 }
536 }
537 else
538#endif // Win32
539 {
bb0e27ee
VZ
540 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
541 // should be used instead - but if it's not available, fall back on
542 // GetDiskFreeSpace() nevertheless...
543
eadd7bd2
VZ
544 DWORD lSectorsPerCluster,
545 lBytesPerSector,
546 lNumberOfFreeClusters,
547 lTotalNumberOfClusters;
548
549 // FIXME: this is wrong, we should extract the root drive from path
550 // instead, but this is the job for wxFileName...
715e4f7e 551 if ( !::GetDiskFreeSpace(path.t_str(),
eadd7bd2
VZ
552 &lSectorsPerCluster,
553 &lBytesPerSector,
554 &lNumberOfFreeClusters,
555 &lTotalNumberOfClusters) )
556 {
9a83f860 557 wxLogLastError(wxT("GetDiskFreeSpace"));
eadd7bd2 558
27d2dbbc 559 return false;
eadd7bd2
VZ
560 }
561
7ba7c4e6 562 wxDiskspaceSize_t lBytesPerCluster = (wxDiskspaceSize_t) lSectorsPerCluster;
eadd7bd2
VZ
563 lBytesPerCluster *= lBytesPerSector;
564
565 if ( pTotal )
566 {
567 *pTotal = lBytesPerCluster;
568 *pTotal *= lTotalNumberOfClusters;
569 }
570
571 if ( pFree )
572 {
573 *pFree = lBytesPerCluster;
574 *pFree *= lNumberOfFreeClusters;
575 }
576 }
577
27d2dbbc 578 return true;
4676948b
JS
579#endif
580 // __WXWINCE__
eadd7bd2
VZ
581}
582
308978f6
VZ
583// ----------------------------------------------------------------------------
584// env vars
585// ----------------------------------------------------------------------------
586
7bea7b91
WS
587bool wxGetEnv(const wxString& WXUNUSED_IN_WINCE(var),
588 wxString *WXUNUSED_IN_WINCE(value))
308978f6 589{
4676948b 590#ifdef __WXWINCE__
040e5f77 591 // no environment variables under CE
27d2dbbc 592 return false;
e622dd68 593#else // Win32
308978f6 594 // first get the size of the buffer
dc874fb4 595 DWORD dwRet = ::GetEnvironmentVariable(var.t_str(), NULL, 0);
308978f6
VZ
596 if ( !dwRet )
597 {
598 // this means that there is no such variable
27d2dbbc 599 return false;
308978f6
VZ
600 }
601
602 if ( value )
603 {
dc874fb4 604 (void)::GetEnvironmentVariable(var.t_str(),
e0a050e3 605 wxStringBuffer(*value, dwRet),
de564874 606 dwRet);
308978f6
VZ
607 }
608
27d2dbbc 609 return true;
3a5bcc4d 610#endif // WinCE/32
308978f6
VZ
611}
612
787de19a 613bool wxDoSetEnv(const wxString& var, const wxChar *value)
1fb45475 614{
7bea7b91
WS
615#ifdef __WXWINCE__
616 // no environment variables under CE
787de19a
VZ
617 wxUnusedVar(var);
618 wxUnusedVar(value);
7bea7b91 619 return false;
787de19a
VZ
620#else // !__WXWINCE__
621 // update the CRT environment if possible as people expect getenv() to also
622 // work and it is not affected by Win32 SetEnvironmentVariable() call (OTOH
623 // the CRT does use Win32 call to update the process environment block so
624 // there is no need to call it)
625 //
626 // TODO: add checks for the other compilers (and update wxSetEnv()
627 // documentation in interface/wx/utils.h accordingly)
1b2f7b6d 628#if defined(__VISUALC__) || defined(__MINGW32__)
787de19a
VZ
629 // notice that Microsoft _putenv() has different semantics from POSIX
630 // function with almost the same name: in particular it makes a copy of the
631 // string instead of using it as part of environment so we can safely call
632 // it here without going through all the troubles with wxSetEnvModule as in
633 // src/unix/utilsunx.cpp
634 wxString envstr = var;
635 envstr += '=';
636 if ( value )
637 envstr += value;
d993c262 638 if ( _tputenv(envstr.t_str()) != 0 )
daa35097 639 return false;
787de19a 640#else // other compiler
dc874fb4 641 if ( !::SetEnvironmentVariable(var.t_str(), value) )
1fb45475 642 {
9a83f860 643 wxLogLastError(wxT("SetEnvironmentVariable"));
1fb45475 644
27d2dbbc 645 return false;
1fb45475 646 }
787de19a 647#endif // compiler
1fb45475 648
27d2dbbc 649 return true;
787de19a 650#endif // __WXWINCE__/!__WXWINCE__
1fb45475
VZ
651}
652
90a77e64
VS
653bool wxSetEnv(const wxString& variable, const wxString& value)
654{
dc874fb4 655 return wxDoSetEnv(variable, value.t_str());
90a77e64
VS
656}
657
658bool wxUnsetEnv(const wxString& variable)
659{
660 return wxDoSetEnv(variable, NULL);
661}
662
b568d04f
VZ
663// ----------------------------------------------------------------------------
664// process management
665// ----------------------------------------------------------------------------
666
50567b69
VZ
667// structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
668struct wxFindByPidParams
b568d04f 669{
50567b69
VZ
670 wxFindByPidParams() { hwnd = 0; pid = 0; }
671
672 // the HWND used to return the result
673 HWND hwnd;
674
675 // the PID we're looking from
676 DWORD pid;
22f3361e 677
c0c133e1 678 wxDECLARE_NO_COPY_CLASS(wxFindByPidParams);
50567b69
VZ
679};
680
681// wxKill helper: EnumWindows() callback which is used to find the first (top
682// level) window belonging to the given process
683BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
684{
685 DWORD pid;
686 (void)::GetWindowThreadProcessId(hwnd, &pid);
687
688 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
689 if ( pid == params->pid )
690 {
691 // remember the window we found
692 params->hwnd = hwnd;
693
694 // return FALSE to stop the enumeration
695 return FALSE;
696 }
697
698 // continue enumeration
699 return TRUE;
700}
e949bf13 701
e0f6b731
JS
702int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc);
703
704int wxKill(long pid, wxSignal sig, wxKillError *krc, int flags)
50567b69 705{
e0f6b731
JS
706 if (flags & wxKILL_CHILDREN)
707 wxKillAllChildren(pid, sig, krc);
9d8aca48 708
50567b69 709 // get the process handle to operate on
e19dbcf7
VZ
710 DWORD dwAccess = PROCESS_QUERY_INFORMATION | SYNCHRONIZE;
711 if ( sig == wxSIGKILL )
712 dwAccess |= PROCESS_TERMINATE;
713
714 HANDLE hProcess = ::OpenProcess(dwAccess, FALSE, (DWORD)pid);
50567b69 715 if ( hProcess == NULL )
e949bf13 716 {
50567b69 717 if ( krc )
e949bf13 718 {
a45fb5b4
VZ
719 // recognize wxKILL_ACCESS_DENIED as special because this doesn't
720 // mean that the process doesn't exist and this is important for
721 // wxProcess::Exists()
722 *krc = ::GetLastError() == ERROR_ACCESS_DENIED
723 ? wxKILL_ACCESS_DENIED
724 : wxKILL_NO_PROCESS;
50567b69
VZ
725 }
726
727 return -1;
728 }
729
a45fb5b4
VZ
730 wxON_BLOCK_EXIT1(::CloseHandle, hProcess);
731
e436c454
VZ
732 // Default timeout for waiting for the process termination after killing
733 // it. It should be long enough to allow the process to terminate even on a
734 // busy system but short enough to avoid blocking the main thread for too
735 // long.
736 DWORD waitTimeout = 500; // ms
737
27d2dbbc 738 bool ok = true;
50567b69
VZ
739 switch ( sig )
740 {
741 case wxSIGKILL:
742 // kill the process forcefully returning -1 as error code
743 if ( !::TerminateProcess(hProcess, (UINT)-1) )
744 {
745 wxLogSysError(_("Failed to kill process %d"), pid);
746
747 if ( krc )
e949bf13 748 {
50567b69
VZ
749 // this is not supposed to happen if we could open the
750 // process
751 *krc = wxKILL_ERROR;
e949bf13 752 }
50567b69 753
27d2dbbc 754 ok = false;
e949bf13 755 }
50567b69
VZ
756 break;
757
758 case wxSIGNONE:
e436c454
VZ
759 // Opening the process handle may succeed for a process even if it
760 // doesn't run any more (typically because open handles to it still
761 // exist elsewhere, possibly in this process itself if we're
762 // killing a child process) so we still need check if it hasn't
763 // terminated yet but, unlike when killing it, we don't need to
764 // wait for any time at all.
765 waitTimeout = 0;
766 break;
50567b69
VZ
767
768 default:
769 // any other signal means "terminate"
770 {
771 wxFindByPidParams params;
772 params.pid = (DWORD)pid;
773
774 // EnumWindows() has nice semantics: it returns 0 if it found
3103e8a9 775 // something or if an error occurred and non zero if it
50567b69
VZ
776 // enumerated all the window
777 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
778 {
779 // did we find any window?
780 if ( params.hwnd )
781 {
782 // tell the app to close
783 //
3103e8a9 784 // NB: this is the harshest way, the app won't have an
50567b69
VZ
785 // opportunity to save any files, for example, but
786 // this is probably what we want here. If not we
787 // can also use SendMesageTimeout(WM_CLOSE)
788 if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
789 {
9a83f860 790 wxLogLastError(wxT("PostMessage(WM_QUIT)"));
50567b69
VZ
791 }
792 }
793 else // it was an error then
794 {
9a83f860 795 wxLogLastError(wxT("EnumWindows"));
50567b69 796
27d2dbbc 797 ok = false;
50567b69
VZ
798 }
799 }
800 else // no windows for this PID
801 {
802 if ( krc )
50567b69 803 *krc = wxKILL_ERROR;
50567b69 804
27d2dbbc 805 ok = false;
50567b69
VZ
806 }
807 }
808 }
809
810 // the return code
50567b69
VZ
811 if ( ok )
812 {
813 // as we wait for a short time, we can use just WaitForSingleObject()
814 // and not MsgWaitForMultipleObjects()
e436c454 815 switch ( ::WaitForSingleObject(hProcess, waitTimeout) )
50567b69
VZ
816 {
817 case WAIT_OBJECT_0:
e436c454
VZ
818 // Process terminated: normally this indicates that we
819 // successfully killed it but when testing for the process
820 // existence, this means failure.
821 if ( sig == wxSIGNONE )
50567b69 822 {
e436c454
VZ
823 if ( krc )
824 *krc = wxKILL_NO_PROCESS;
825
826 ok = false;
50567b69
VZ
827 }
828 break;
829
830 default:
9a83f860 831 wxFAIL_MSG( wxT("unexpected WaitForSingleObject() return") );
50567b69
VZ
832 // fall through
833
834 case WAIT_FAILED:
9a83f860 835 wxLogLastError(wxT("WaitForSingleObject"));
50567b69
VZ
836 // fall through
837
838 case WAIT_TIMEOUT:
e436c454
VZ
839 // Process didn't terminate: normally this is a failure but not
840 // when we're just testing for its existence.
841 if ( sig != wxSIGNONE )
842 {
843 if ( krc )
844 *krc = wxKILL_ERROR;
50567b69 845
e436c454
VZ
846 ok = false;
847 }
50567b69 848 break;
e949bf13
JS
849 }
850 }
851
b568d04f 852
50567b69
VZ
853 // the return code is the same as from Unix kill(): 0 if killed
854 // successfully or -1 on error
e436c454 855 if ( !ok )
a45fb5b4 856 return -1;
b1a28eef 857
a45fb5b4
VZ
858 if ( krc )
859 *krc = wxKILL_OK;
50567b69 860
a45fb5b4 861 return 0;
2bda0e17
KB
862}
863
78a054f6
WS
864typedef HANDLE (WINAPI *CreateToolhelp32Snapshot_t)(DWORD,DWORD);
865typedef BOOL (WINAPI *Process32_t)(HANDLE,LPPROCESSENTRY32);
866
867CreateToolhelp32Snapshot_t lpfCreateToolhelp32Snapshot;
868Process32_t lpfProcess32First, lpfProcess32Next;
9d8aca48 869
e0f6b731
JS
870static void InitToolHelp32()
871{
872 static bool s_initToolHelpDone = false;
9d8aca48 873
e0f6b731
JS
874 if (s_initToolHelpDone)
875 return;
9d8aca48 876
e0f6b731
JS
877 s_initToolHelpDone = true;
878
879 lpfCreateToolhelp32Snapshot = NULL;
880 lpfProcess32First = NULL;
881 lpfProcess32Next = NULL;
9d8aca48 882
32c0c61c
WS
883#if wxUSE_DYNLIB_CLASS
884
9a83f860 885 wxDynamicLibrary dllKernel(wxT("kernel32.dll"), wxDL_VERBATIM);
9d8aca48 886
e0f6b731
JS
887 // Get procedure addresses.
888 // We are linking to these functions of Kernel32
889 // explicitly, because otherwise a module using
890 // this code would fail to load under Windows NT,
891 // which does not have the Toolhelp32
892 // functions in the Kernel 32.
78a054f6 893 lpfCreateToolhelp32Snapshot =
9a83f860 894 (CreateToolhelp32Snapshot_t)dllKernel.RawGetSymbol(wxT("CreateToolhelp32Snapshot"));
9d8aca48 895
78a054f6 896 lpfProcess32First =
9a83f860 897 (Process32_t)dllKernel.RawGetSymbol(wxT("Process32First"));
e0f6b731 898
78a054f6 899 lpfProcess32Next =
9a83f860 900 (Process32_t)dllKernel.RawGetSymbol(wxT("Process32Next"));
32c0c61c
WS
901
902#endif // wxUSE_DYNLIB_CLASS
e0f6b731
JS
903}
904
905// By John Skiff
906int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc)
907{
908 InitToolHelp32();
9d8aca48 909
e0f6b731
JS
910 if (krc)
911 *krc = wxKILL_OK;
9d8aca48 912
e0f6b731
JS
913 // If not implemented for this platform (e.g. NT 4.0), silently ignore
914 if (!lpfCreateToolhelp32Snapshot || !lpfProcess32First || !lpfProcess32Next)
915 return 0;
9d8aca48 916
e0f6b731
JS
917 // Take a snapshot of all processes in the system.
918 HANDLE hProcessSnap = lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
919 if (hProcessSnap == INVALID_HANDLE_VALUE) {
920 if (krc)
921 *krc = wxKILL_ERROR;
922 return -1;
923 }
9d8aca48 924
e0f6b731 925 //Fill in the size of the structure before using it.
04a18b0d
WS
926 PROCESSENTRY32 pe;
927 wxZeroMemory(pe);
e0f6b731 928 pe.dwSize = sizeof(PROCESSENTRY32);
9d8aca48 929
e0f6b731
JS
930 // Walk the snapshot of the processes, and for each process,
931 // kill it if its parent is pid.
932 if (!lpfProcess32First(hProcessSnap, &pe)) {
933 // Can't get first process.
934 if (krc)
935 *krc = wxKILL_ERROR;
936 CloseHandle (hProcessSnap);
937 return -1;
938 }
9d8aca48 939
e0f6b731
JS
940 do {
941 if (pe.th32ParentProcessID == (DWORD) pid) {
942 if (wxKill(pe.th32ProcessID, sig, krc))
943 return -1;
944 }
945 } while (lpfProcess32Next (hProcessSnap, &pe));
9d8aca48
WS
946
947
e0f6b731
JS
948 return 0;
949}
950
b568d04f
VZ
951// Execute a program in an Interactive Shell
952bool wxShell(const wxString& command)
2bda0e17 953{
7010702f
WS
954 wxString cmd;
955
4676948b 956#ifdef __WXWINCE__
7010702f 957 cmd = command;
4676948b 958#else
b568d04f
VZ
959 wxChar *shell = wxGetenv(wxT("COMSPEC"));
960 if ( !shell )
ba14d986 961 shell = (wxChar*) wxT("\\COMMAND.COM");
b568d04f 962
b568d04f
VZ
963 if ( !command )
964 {
965 // just the shell
966 cmd = shell;
967 }
968 else
969 {
970 // pass the command to execute to the command processor
971 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
972 }
7010702f 973#endif
b568d04f 974
011a524e 975 return wxExecute(cmd, wxEXEC_SYNC) == 0;
2bda0e17
KB
976}
977
d8c65cf4 978// Shutdown or reboot the PC
118a41d9 979bool wxShutdown(int WXUNUSED_IN_WINCE(flags))
f6ba47d9 980{
4676948b 981#ifdef __WXWINCE__
040e5f77 982 // TODO-CE
27d2dbbc 983 return false;
4676948b 984#elif defined(__WIN32__)
27d2dbbc 985 bool bOK = true;
f6ba47d9 986
406d283a 987 if ( wxGetOsVersion(NULL, NULL) == wxOS_WINDOWS_NT ) // if is NT or 2K
f6ba47d9 988 {
d8c65cf4
RD
989 // Get a token for this process.
990 HANDLE hToken;
f6ba47d9
VZ
991 bOK = ::OpenProcessToken(GetCurrentProcess(),
992 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
993 &hToken) != 0;
994 if ( bOK )
995 {
d8c65cf4 996 TOKEN_PRIVILEGES tkp;
f6ba47d9 997
d8c65cf4 998 // Get the LUID for the shutdown privilege.
a2e50fc2
VZ
999 bOK = ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
1000 &tkp.Privileges[0].Luid) != 0;
f6ba47d9 1001
a2e50fc2
VZ
1002 if ( bOK )
1003 {
1004 tkp.PrivilegeCount = 1; // one privilege to set
1005 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1006
1007 // Get the shutdown privilege for this process.
1008 ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
1009 (PTOKEN_PRIVILEGES)NULL, 0);
f6ba47d9 1010
a2e50fc2
VZ
1011 // Cannot test the return value of AdjustTokenPrivileges.
1012 bOK = ::GetLastError() == ERROR_SUCCESS;
1013 }
f6ba47d9 1014
a2e50fc2 1015 ::CloseHandle(hToken);
f6ba47d9
VZ
1016 }
1017 }
1018
1019 if ( bOK )
1020 {
118a41d9
VZ
1021 UINT wFlags = 0;
1022 if ( flags & wxSHUTDOWN_FORCE )
1023 {
1024 wFlags = EWX_FORCE;
1025 flags &= ~wxSHUTDOWN_FORCE;
1026 }
1027
1028 switch ( flags )
f6ba47d9
VZ
1029 {
1030 case wxSHUTDOWN_POWEROFF:
118a41d9 1031 wFlags |= EWX_POWEROFF;
f6ba47d9
VZ
1032 break;
1033
1034 case wxSHUTDOWN_REBOOT:
118a41d9
VZ
1035 wFlags |= EWX_REBOOT;
1036 break;
1037
1038 case wxSHUTDOWN_LOGOFF:
1039 wFlags |= EWX_LOGOFF;
f6ba47d9
VZ
1040 break;
1041
1042 default:
9a83f860 1043 wxFAIL_MSG( wxT("unknown wxShutdown() flag") );
27d2dbbc 1044 return false;
f6ba47d9
VZ
1045 }
1046
118a41d9 1047 bOK = ::ExitWindowsEx(wFlags, 0) != 0;
f6ba47d9
VZ
1048 }
1049
1050 return bOK;
118a41d9 1051#endif // WinCE/!WinCE
f6ba47d9
VZ
1052}
1053
b568d04f
VZ
1054// ----------------------------------------------------------------------------
1055// misc
1056// ----------------------------------------------------------------------------
1057
1058// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
9d8aca48 1059wxMemorySize wxGetFreeMemory()
2bda0e17 1060{
9d8aca48
WS
1061#if defined(__WIN64__)
1062 MEMORYSTATUSEX memStatex;
106d80ad
JS
1063 memStatex.dwLength = sizeof (memStatex);
1064 ::GlobalMemoryStatusEx (&memStatex);
1065 return (wxMemorySize)memStatex.ullAvailPhys;
2b7295c9 1066#else /* if defined(__WIN32__) */
b568d04f
VZ
1067 MEMORYSTATUS memStatus;
1068 memStatus.dwLength = sizeof(MEMORYSTATUS);
2b7295c9 1069 ::GlobalMemoryStatus(&memStatus);
9d8aca48 1070 return (wxMemorySize)memStatus.dwAvailPhys;
b568d04f 1071#endif
2bda0e17
KB
1072}
1073
c1cb4153
VZ
1074unsigned long wxGetProcessId()
1075{
c1cb4153 1076 return ::GetCurrentProcessId();
c1cb4153
VZ
1077}
1078
c50a4038
VZ
1079bool wxIsDebuggerRunning()
1080{
532d575b 1081#if wxUSE_DYNLIB_CLASS
c50a4038 1082 // IsDebuggerPresent() is not available under Win95, so load it dynamically
9a83f860 1083 wxDynamicLibrary dll(wxT("kernel32.dll"), wxDL_VERBATIM);
c50a4038
VZ
1084
1085 typedef BOOL (WINAPI *IsDebuggerPresent_t)();
9a83f860 1086 if ( !dll.HasSymbol(wxT("IsDebuggerPresent")) )
c50a4038
VZ
1087 {
1088 // no way to know, assume no
1089 return false;
1090 }
1091
9a83f860 1092 return (*(IsDebuggerPresent_t)dll.GetSymbol(wxT("IsDebuggerPresent")))() != 0;
532d575b
WS
1093#else
1094 return false;
1095#endif
c50a4038
VZ
1096}
1097
c5ba4851
VZ
1098// ----------------------------------------------------------------------------
1099// working with MSW resources
1100// ----------------------------------------------------------------------------
1101
1102bool
1103wxLoadUserResource(const void **outData,
1104 size_t *outLen,
1105 const wxString& resourceName,
e23fd60f 1106 const wxChar* resourceType,
18923e36 1107 WXHINSTANCE instance)
c5ba4851
VZ
1108{
1109 wxCHECK_MSG( outData && outLen, false, "output pointers can't be NULL" );
1110
18923e36 1111 HRSRC hResource = ::FindResource(instance,
b2b6da49 1112 resourceName.t_str(),
e23fd60f 1113 resourceType);
c5ba4851
VZ
1114 if ( !hResource )
1115 return false;
1116
18923e36 1117 HGLOBAL hData = ::LoadResource(instance, hResource);
c5ba4851
VZ
1118 if ( !hData )
1119 {
1120 wxLogSysError(_("Failed to load resource \"%s\"."), resourceName);
1121 return false;
1122 }
1123
1124 *outData = ::LockResource(hData);
1125 if ( !*outData )
1126 {
1127 wxLogSysError(_("Failed to lock resource \"%s\"."), resourceName);
1128 return false;
1129 }
1130
18923e36 1131 *outLen = ::SizeofResource(instance, hResource);
c5ba4851
VZ
1132
1133 // Notice that we do not need to call neither UnlockResource() (which is
1134 // obsolete in Win32) nor GlobalFree() (resources are freed on process
1135 // termination only)
1136
1137 return true;
1138}
1139
1140char *
1141wxLoadUserResource(const wxString& resourceName,
e23fd60f 1142 const wxChar* resourceType,
18923e36
VS
1143 int* pLen,
1144 WXHINSTANCE instance)
c5ba4851
VZ
1145{
1146 const void *data;
1147 size_t len;
18923e36 1148 if ( !wxLoadUserResource(&data, &len, resourceName, resourceType, instance) )
c5ba4851
VZ
1149 return NULL;
1150
1151 char *s = new char[len + 1];
1152 memcpy(s, data, len);
1153 s[len] = '\0'; // NUL-terminate in case the resource itself wasn't
1154
1155 if (pLen)
1156 *pLen = len;
1157
1158 return s;
1159}
1160
c50a4038
VZ
1161// ----------------------------------------------------------------------------
1162// OS version
1163// ----------------------------------------------------------------------------
1164
66930b35
VZ
1165// check if we're running under a server or workstation Windows system: it
1166// returns true or false with obvious meaning as well as -1 if the system type
1167// couldn't be determined
1168//
1169// this function is currently private but we may want to expose it later if
1170// it's really useful
1171namespace
1172{
1173
1174int wxIsWindowsServer()
1175{
1176#ifdef VER_NT_WORKSTATION
1177 OSVERSIONINFOEX info;
1178 wxZeroMemory(info);
1179
1180 info.dwOSVersionInfoSize = sizeof(info);
5c33522f 1181 if ( ::GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&info)) )
66930b35
VZ
1182 {
1183 switch ( info.wProductType )
1184 {
1185 case VER_NT_WORKSTATION:
1186 return false;
1187
1188 case VER_NT_SERVER:
1189 case VER_NT_DOMAIN_CONTROLLER:
1190 return true;
1191 }
1192 }
1193#endif // VER_NT_WORKSTATION
1194
1195 return -1;
1196}
1197
1198} // anonymous namespace
1199
bdc72a22 1200wxString wxGetOsDescription()
2bda0e17 1201{
bdc72a22
VZ
1202 wxString str;
1203
1204 OSVERSIONINFO info;
1205 wxZeroMemory(info);
1206
1207 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1208 if ( ::GetVersionEx(&info) )
1209 {
1210 switch ( info.dwPlatformId )
1211 {
84dc0006
WS
1212#ifdef VER_PLATFORM_WIN32_CE
1213 case VER_PLATFORM_WIN32_CE:
1214 str.Printf(_("Windows CE (%d.%d)"),
1215 info.dwMajorVersion,
1216 info.dwMinorVersion);
1217 break;
1218#endif
bdc72a22
VZ
1219 case VER_PLATFORM_WIN32s:
1220 str = _("Win32s on Windows 3.1");
1221 break;
1222
1223 case VER_PLATFORM_WIN32_WINDOWS:
db1d0193
VZ
1224 switch (info.dwMinorVersion)
1225 {
1226 case 0:
1227 if ( info.szCSDVersion[1] == 'B' ||
1228 info.szCSDVersion[1] == 'C' )
1229 {
1230 str = _("Windows 95 OSR2");
1231 }
1232 else
1233 {
1234 str = _("Windows 95");
1235 }
1236 break;
1237 case 10:
1238 if ( info.szCSDVersion[1] == 'B' ||
1239 info.szCSDVersion[1] == 'C' )
1240 {
1241 str = _("Windows 98 SE");
1242 }
1243 else
1244 {
1245 str = _("Windows 98");
1246 }
1247 break;
1248 case 90:
1249 str = _("Windows ME");
1250 break;
1251 default:
1252 str.Printf(_("Windows 9x (%d.%d)"),
1253 info.dwMajorVersion,
1254 info.dwMinorVersion);
1255 break;
1256 }
bdc72a22
VZ
1257 if ( !wxIsEmpty(info.szCSDVersion) )
1258 {
9a83f860 1259 str << wxT(" (") << info.szCSDVersion << wxT(')');
bdc72a22
VZ
1260 }
1261 break;
1262
1263 case VER_PLATFORM_WIN32_NT:
a284cce8 1264 switch ( info.dwMajorVersion )
db1d0193 1265 {
a284cce8
VZ
1266 case 5:
1267 switch ( info.dwMinorVersion )
1268 {
1269 case 0:
5f081e28 1270 str = _("Windows 2000");
a284cce8
VZ
1271 break;
1272
66930b35
VZ
1273 case 2:
1274 // we can't distinguish between XP 64 and 2003
1275 // as they both are 5.2, so examine the product
1276 // type to resolve this ambiguity
575cabba 1277 if ( wxIsWindowsServer() == 1 )
66930b35 1278 {
5f081e28 1279 str = _("Windows Server 2003");
66930b35
VZ
1280 break;
1281 }
1282 //else: must be XP, fall through
1283
a284cce8 1284 case 1:
5f081e28 1285 str = _("Windows XP");
a284cce8 1286 break;
a284cce8
VZ
1287 }
1288 break;
1289
1290 case 6:
7c7eed56 1291 switch ( info.dwMinorVersion )
a284cce8 1292 {
7c7eed56 1293 case 0:
5f081e28
VZ
1294 str = wxIsWindowsServer() == 1
1295 ? _("Windows Server 2008")
1296 : _("Windows Vista");
7c7eed56
VZ
1297 break;
1298
1299 case 1:
5f081e28
VZ
1300 str = wxIsWindowsServer() == 1
1301 ? _("Windows Server 2008 R2")
1302 : _("Windows 7");
7c7eed56 1303 break;
a284cce8
VZ
1304 }
1305 break;
db1d0193 1306 }
a284cce8 1307
84dc0006 1308 if ( str.empty() )
db1d0193 1309 {
5f081e28
VZ
1310 str.Printf(_("Windows NT %lu.%lu"),
1311 info.dwMajorVersion,
1312 info.dwMinorVersion);
db1d0193 1313 }
a284cce8 1314
5f081e28
VZ
1315 str << wxT(" (")
1316 << wxString::Format(_("build %lu"), info.dwBuildNumber);
bdc72a22
VZ
1317 if ( !wxIsEmpty(info.szCSDVersion) )
1318 {
9a83f860 1319 str << wxT(", ") << info.szCSDVersion;
bdc72a22 1320 }
9a83f860 1321 str << wxT(')');
d4885e10
VZ
1322
1323 if ( wxIsPlatform64Bit() )
1324 str << _(", 64-bit edition");
bdc72a22
VZ
1325 break;
1326 }
1327 }
1328 else
1329 {
9a83f860 1330 wxFAIL_MSG( wxT("GetVersionEx() failed") ); // should never happen
bdc72a22
VZ
1331 }
1332
1333 return str;
bdc72a22 1334}
6f65e337 1335
8bb6b2c0 1336bool wxIsPlatform64Bit()
bdc72a22 1337{
8bb6b2c0
VZ
1338#if defined(_WIN64)
1339 return true; // 64-bit programs run only on Win64
a8ff046b 1340#elif wxUSE_DYNLIB_CLASS // Win32
6deb397d
VZ
1341 // 32-bit programs run on both 32-bit and 64-bit Windows so check
1342 typedef BOOL (WINAPI *IsWow64Process_t)(HANDLE, BOOL *);
1343
9a83f860 1344 wxDynamicLibrary dllKernel32(wxT("kernel32.dll"));
b9d4a1b7 1345 IsWow64Process_t pfnIsWow64Process =
9a83f860 1346 (IsWow64Process_t)dllKernel32.RawGetSymbol(wxT("IsWow64Process"));
6deb397d
VZ
1347
1348 BOOL wow64 = FALSE;
1349 if ( pfnIsWow64Process )
1350 {
b9d4a1b7 1351 pfnIsWow64Process(::GetCurrentProcess(), &wow64);
6deb397d
VZ
1352 }
1353 //else: running under a system without Win64 support
1354
1355 return wow64 != FALSE;
a8ff046b
VZ
1356#else
1357 return false;
6deb397d 1358#endif // Win64/Win32
8bb6b2c0 1359}
ec5d7799 1360
8bb6b2c0
VZ
1361wxOperatingSystemId wxGetOsVersion(int *verMaj, int *verMin)
1362{
5bc3ef05
VZ
1363 static struct
1364 {
1365 // this may be false, true or -1 if we tried to initialize but failed
1366 int initialized;
bdc72a22 1367
5bc3ef05
VZ
1368 wxOperatingSystemId os;
1369
1370 int verMaj,
1371 verMin;
1372 } s_version;
1373
1374 // query the OS info only once as it's not supposed to change
1375 if ( !s_version.initialized )
8bb6b2c0 1376 {
5bc3ef05
VZ
1377 OSVERSIONINFO info;
1378 wxZeroMemory(info);
1379 info.dwOSVersionInfoSize = sizeof(info);
1380 if ( ::GetVersionEx(&info) )
1381 {
1382 s_version.initialized = true;
1383
1384#if defined(__WXWINCE__)
1385 s_version.os = wxOS_WINDOWS_CE;
1386#elif defined(__WXMICROWIN__)
1387 s_version.os = wxOS_WINDOWS_MICRO;
1388#else // "normal" desktop Windows system, use run-time detection
1389 switch ( info.dwPlatformId )
1390 {
1391 case VER_PLATFORM_WIN32_NT:
1392 s_version.os = wxOS_WINDOWS_NT;
1393 break;
1394
1395 case VER_PLATFORM_WIN32_WINDOWS:
1396 s_version.os = wxOS_WINDOWS_9X;
1397 break;
1398 }
1399#endif // Windows versions
1400
1401 s_version.verMaj = info.dwMajorVersion;
1402 s_version.verMin = info.dwMinorVersion;
1403 }
1404 else // GetVersionEx() failed
1405 {
1406 s_version.initialized = -1;
1407 }
8bb6b2c0 1408 }
bdc72a22 1409
5bc3ef05 1410 if ( s_version.initialized == 1 )
8bb6b2c0 1411 {
5bc3ef05
VZ
1412 if ( verMaj )
1413 *verMaj = s_version.verMaj;
1414 if ( verMin )
1415 *verMin = s_version.verMin;
bdc72a22
VZ
1416 }
1417
5bc3ef05
VZ
1418 // this works even if we were not initialized successfully as the initial
1419 // values of this field is 0 which is wxOS_UNKNOWN and exactly what we need
1420 return s_version.os;
2bda0e17
KB
1421}
1422
4c5da5e4
VZ
1423wxWinVersion wxGetWinVersion()
1424{
1425 int verMaj,
1426 verMin;
1427 switch ( wxGetOsVersion(&verMaj, &verMin) )
1428 {
406d283a 1429 case wxOS_WINDOWS_9X:
4c5da5e4
VZ
1430 if ( verMaj == 4 )
1431 {
1432 switch ( verMin )
1433 {
1434 case 0:
1435 return wxWinVersion_95;
1436
1437 case 10:
1438 return wxWinVersion_98;
1439
1440 case 90:
1441 return wxWinVersion_ME;
1442 }
1443 }
1444 break;
1445
406d283a 1446 case wxOS_WINDOWS_NT:
4c5da5e4
VZ
1447 switch ( verMaj )
1448 {
1449 case 3:
1450 return wxWinVersion_NT3;
1451
1452 case 4:
1453 return wxWinVersion_NT4;
1454
1455 case 5:
1456 switch ( verMin )
1457 {
1458 case 0:
1459 return wxWinVersion_2000;
1460
1461 case 1:
1462 return wxWinVersion_XP;
1463
1464 case 2:
1465 return wxWinVersion_2003;
1466 }
1467 break;
1468
1469 case 6:
1470 return wxWinVersion_NT6;
1471 }
1472 break;
1473
449210a4
WS
1474 default:
1475 // Do nothing just to silence GCC warning
1476 break;
4c5da5e4
VZ
1477 }
1478
1479 return wxWinVersion_Unknown;
1480}
1481
b568d04f
VZ
1482// ----------------------------------------------------------------------------
1483// sleep functions
1484// ----------------------------------------------------------------------------
1485
08873d36 1486void wxMilliSleep(unsigned long milliseconds)
b568d04f
VZ
1487{
1488 ::Sleep(milliseconds);
1489}
1490
08873d36
VZ
1491void wxMicroSleep(unsigned long microseconds)
1492{
1493 wxMilliSleep(microseconds/1000);
1494}
1495
b568d04f
VZ
1496void wxSleep(int nSecs)
1497{
08873d36 1498 wxMilliSleep(1000*nSecs);
b568d04f
VZ
1499}
1500
b568d04f 1501// ----------------------------------------------------------------------------
e2478fde 1502// font encoding <-> Win32 codepage conversion functions
b568d04f
VZ
1503// ----------------------------------------------------------------------------
1504
bddd7a8d 1505extern WXDLLIMPEXP_BASE long wxEncodingToCharset(wxFontEncoding encoding)
b568d04f 1506{
e2478fde 1507 switch ( encoding )
b568d04f 1508 {
e2478fde
VZ
1509 // although this function is supposed to return an exact match, do do
1510 // some mappings here for the most common case of "standard" encoding
1511 case wxFONTENCODING_SYSTEM:
1512 return DEFAULT_CHARSET;
2bda0e17 1513
e2478fde
VZ
1514 case wxFONTENCODING_ISO8859_1:
1515 case wxFONTENCODING_ISO8859_15:
1516 case wxFONTENCODING_CP1252:
1517 return ANSI_CHARSET;
2bda0e17 1518
e2478fde
VZ
1519#if !defined(__WXMICROWIN__)
1520 // The following four fonts are multi-byte charsets
1521 case wxFONTENCODING_CP932:
1522 return SHIFTJIS_CHARSET;
2bda0e17 1523
e2478fde
VZ
1524 case wxFONTENCODING_CP936:
1525 return GB2312_CHARSET;
2bda0e17 1526
90805c24 1527#ifndef __WXWINCE__
e2478fde
VZ
1528 case wxFONTENCODING_CP949:
1529 return HANGUL_CHARSET;
90805c24 1530#endif
634903fd 1531
e2478fde
VZ
1532 case wxFONTENCODING_CP950:
1533 return CHINESEBIG5_CHARSET;
2bda0e17 1534
e2478fde
VZ
1535 // The rest are single byte encodings
1536 case wxFONTENCODING_CP1250:
1537 return EASTEUROPE_CHARSET;
bfbd6dc1 1538
e2478fde
VZ
1539 case wxFONTENCODING_CP1251:
1540 return RUSSIAN_CHARSET;
2bda0e17 1541
e2478fde
VZ
1542 case wxFONTENCODING_CP1253:
1543 return GREEK_CHARSET;
b07135ba 1544
e2478fde
VZ
1545 case wxFONTENCODING_CP1254:
1546 return TURKISH_CHARSET;
2bda0e17 1547
e2478fde
VZ
1548 case wxFONTENCODING_CP1255:
1549 return HEBREW_CHARSET;
2bda0e17 1550
e2478fde
VZ
1551 case wxFONTENCODING_CP1256:
1552 return ARABIC_CHARSET;
b568d04f 1553
e2478fde
VZ
1554 case wxFONTENCODING_CP1257:
1555 return BALTIC_CHARSET;
634903fd 1556
e2478fde
VZ
1557 case wxFONTENCODING_CP874:
1558 return THAI_CHARSET;
5acc0d5f 1559#endif // !__WXMICROWIN__
cc2b7472 1560
e2478fde
VZ
1561 case wxFONTENCODING_CP437:
1562 return OEM_CHARSET;
ea28b885
VZ
1563
1564 default:
1565 // no way to translate this encoding into a Windows charset
69557827 1566 return -1;
e2478fde 1567 }
373658eb 1568}
7f555861 1569
e2478fde
VZ
1570// we have 2 versions of wxCharsetToCodepage(): the old one which directly
1571// looks up the vlaues in the registry and the new one which is more
1572// politically correct and has more chances to work on other Windows versions
1573// as well but the old version is still needed for !wxUSE_FONTMAP case
1574#if wxUSE_FONTMAP
c030b70f 1575
373658eb 1576#include "wx/fontmap.h"
c030b70f 1577
bddd7a8d 1578extern WXDLLIMPEXP_BASE long wxEncodingToCodepage(wxFontEncoding encoding)
c030b70f 1579{
b169661f
RR
1580 // There don't seem to be symbolic names for
1581 // these under Windows so I just copied the
1582 // values from MSDN.
04a18b0d 1583
fa78de82 1584 unsigned int ret;
04a18b0d 1585
b169661f 1586 switch (encoding)
373658eb 1587 {
fa78de82
RR
1588 case wxFONTENCODING_ISO8859_1: ret = 28591; break;
1589 case wxFONTENCODING_ISO8859_2: ret = 28592; break;
1590 case wxFONTENCODING_ISO8859_3: ret = 28593; break;
1591 case wxFONTENCODING_ISO8859_4: ret = 28594; break;
1592 case wxFONTENCODING_ISO8859_5: ret = 28595; break;
1593 case wxFONTENCODING_ISO8859_6: ret = 28596; break;
1594 case wxFONTENCODING_ISO8859_7: ret = 28597; break;
1595 case wxFONTENCODING_ISO8859_8: ret = 28598; break;
1596 case wxFONTENCODING_ISO8859_9: ret = 28599; break;
1597 case wxFONTENCODING_ISO8859_10: ret = 28600; break;
5df3dbf9 1598 case wxFONTENCODING_ISO8859_11: ret = 874; break;
b169661f 1599 // case wxFONTENCODING_ISO8859_12, // doesn't exist currently, but put it
04a18b0d 1600 case wxFONTENCODING_ISO8859_13: ret = 28603; break;
5fdf0363 1601 // case wxFONTENCODING_ISO8859_14: ret = 28604; break; // no correspondence on Windows
fa78de82 1602 case wxFONTENCODING_ISO8859_15: ret = 28605; break;
bd5c3968 1603
fa78de82
RR
1604 case wxFONTENCODING_KOI8: ret = 20866; break;
1605 case wxFONTENCODING_KOI8_U: ret = 21866; break;
bd5c3968 1606
fa78de82
RR
1607 case wxFONTENCODING_CP437: ret = 437; break;
1608 case wxFONTENCODING_CP850: ret = 850; break;
1609 case wxFONTENCODING_CP852: ret = 852; break;
1610 case wxFONTENCODING_CP855: ret = 855; break;
1611 case wxFONTENCODING_CP866: ret = 866; break;
1612 case wxFONTENCODING_CP874: ret = 874; break;
1613 case wxFONTENCODING_CP932: ret = 932; break;
1614 case wxFONTENCODING_CP936: ret = 936; break;
1615 case wxFONTENCODING_CP949: ret = 949; break;
1616 case wxFONTENCODING_CP950: ret = 950; break;
1617 case wxFONTENCODING_CP1250: ret = 1250; break;
1618 case wxFONTENCODING_CP1251: ret = 1251; break;
1619 case wxFONTENCODING_CP1252: ret = 1252; break;
1620 case wxFONTENCODING_CP1253: ret = 1253; break;
1621 case wxFONTENCODING_CP1254: ret = 1254; break;
1622 case wxFONTENCODING_CP1255: ret = 1255; break;
1623 case wxFONTENCODING_CP1256: ret = 1256; break;
1624 case wxFONTENCODING_CP1257: ret = 1257; break;
bd5c3968 1625
a50ca843 1626 case wxFONTENCODING_EUC_JP: ret = 20932; break;
bd5c3968 1627
fa78de82
RR
1628 case wxFONTENCODING_MACROMAN: ret = 10000; break;
1629 case wxFONTENCODING_MACJAPANESE: ret = 10001; break;
1630 case wxFONTENCODING_MACCHINESETRAD: ret = 10002; break;
1631 case wxFONTENCODING_MACKOREAN: ret = 10003; break;
1632 case wxFONTENCODING_MACARABIC: ret = 10004; break;
1633 case wxFONTENCODING_MACHEBREW: ret = 10005; break;
1634 case wxFONTENCODING_MACGREEK: ret = 10006; break;
1635 case wxFONTENCODING_MACCYRILLIC: ret = 10007; break;
1636 case wxFONTENCODING_MACTHAI: ret = 10021; break;
1637 case wxFONTENCODING_MACCHINESESIMP: ret = 10008; break;
1638 case wxFONTENCODING_MACCENTRALEUR: ret = 10029; break;
1639 case wxFONTENCODING_MACCROATIAN: ret = 10082; break;
1640 case wxFONTENCODING_MACICELANDIC: ret = 10079; break;
1641 case wxFONTENCODING_MACROMANIAN: ret = 10009; break;
bd5c3968
VZ
1642
1643 case wxFONTENCODING_ISO2022_JP: ret = 50222; break;
1644
fa78de82
RR
1645 case wxFONTENCODING_UTF7: ret = 65000; break;
1646 case wxFONTENCODING_UTF8: ret = 65001; break;
bd5c3968 1647
fa78de82 1648 default: return -1;
373658eb 1649 }
04a18b0d 1650
fa78de82
RR
1651 if (::IsValidCodePage(ret) == 0)
1652 return -1;
04a18b0d 1653
fa78de82
RR
1654 CPINFO info;
1655 if (::GetCPInfo(ret, &info) == 0)
1656 return -1;
373658eb 1657
fa78de82 1658 return (long) ret;
c030b70f 1659}
373658eb 1660
86501081 1661extern long wxCharsetToCodepage(const char *name)
c030b70f 1662{
373658eb
VZ
1663 // first get the font encoding for this charset
1664 if ( !name )
1665 return -1;
1666
267e11c5 1667 wxFontEncoding enc = wxFontMapperBase::Get()->CharsetToEncoding(name, false);
373658eb
VZ
1668 if ( enc == wxFONTENCODING_SYSTEM )
1669 return -1;
1670
1671 // the use the helper function
1672 return wxEncodingToCodepage(enc);
c030b70f 1673}
c030b70f 1674
e2478fde 1675#else // !wxUSE_FONTMAP
373658eb
VZ
1676
1677#include "wx/msw/registry.h"
1678
1679// this should work if Internet Exploiter is installed
86501081 1680extern long wxCharsetToCodepage(const char *name)
04ef50df 1681{
373658eb
VZ
1682 if (!name)
1683 return GetACP();
1684
e2478fde 1685 long CP = -1;
373658eb 1686
f77c0fe3 1687#if wxUSE_REGKEY
e2478fde 1688 wxString path(wxT("MIME\\Database\\Charset\\"));
373658eb 1689 wxString cn(name);
373658eb 1690
e2478fde
VZ
1691 // follow the alias loop
1692 for ( ;; )
1693 {
1694 wxRegKey key(wxRegKey::HKCR, path + cn);
1695
1696 if (!key.Exists())
1697 break;
373658eb
VZ
1698
1699 // two cases: either there's an AliasForCharset string,
1700 // or there are Codepage and InternetEncoding dwords.
1701 // The InternetEncoding gives us the actual encoding,
1702 // the Codepage just says which Windows character set to
1703 // use when displaying the data.
1704 if (key.HasValue(wxT("InternetEncoding")) &&
e2478fde
VZ
1705 key.QueryValue(wxT("InternetEncoding"), &CP))
1706 break;
373658eb
VZ
1707
1708 // no encoding, see if it's an alias
1709 if (!key.HasValue(wxT("AliasForCharset")) ||
e2478fde
VZ
1710 !key.QueryValue(wxT("AliasForCharset"), cn))
1711 break;
1712 }
f77c0fe3 1713#endif // wxUSE_REGKEY
373658eb
VZ
1714
1715 return CP;
04ef50df 1716}
373658eb 1717
e2478fde 1718#endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
c030b70f 1719
487f2d58 1720extern "C" WXDLLIMPEXP_BASE HWND
eccd1992
VZ
1721wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc)
1722{
1723 wxCHECK_MSG( classname && pclassname && wndproc, NULL,
9a83f860 1724 wxT("NULL parameter in wxCreateHiddenWindow") );
eccd1992
VZ
1725
1726 // register the class fi we need to first
1727 if ( *pclassname == NULL )
1728 {
1729 WNDCLASS wndclass;
1730 wxZeroMemory(wndclass);
1731
1732 wndclass.lpfnWndProc = wndproc;
1733 wndclass.hInstance = wxGetInstance();
1734 wndclass.lpszClassName = classname;
1735
1736 if ( !::RegisterClass(&wndclass) )
1737 {
1738 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1739
1740 return NULL;
1741 }
1742
1743 *pclassname = classname;
1744 }
1745
1746 // next create the window
1747 HWND hwnd = ::CreateWindow
1748 (
1749 *pclassname,
1750 NULL,
1751 0, 0, 0, 0,
1752 0,
1753 (HWND) NULL,
1754 (HMENU)NULL,
1755 wxGetInstance(),
1756 (LPVOID) NULL
1757 );
1758
1759 if ( !hwnd )
1760 {
1761 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));
1762 }
1763
1764 return hwnd;
1765}