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