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