]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utils.cpp
Doc corrections
[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 20#ifdef __GNUG__
a3b46648 21// #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
2bda0e17
KB
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
a4f96412 28 #pragma hdrstop
2bda0e17
KB
29#endif
30
31#ifndef WX_PRECOMP
a4f96412
VZ
32 #include "wx/utils.h"
33 #include "wx/app.h"
1f0500b3
VZ
34 #include "wx/intl.h"
35 #include "wx/log.h"
3a922bb4
RL
36#if wxUSE_GUI
37 #include "wx/cursor.h"
38#endif
743e0a66 39#endif //WX_PRECOMP
2bda0e17 40
b568d04f
VZ
41#include "wx/msw/private.h" // includes <windows.h>
42
c1cb4153
VZ
43#ifdef __GNUWIN32_OLD__
44 // apparently we need to include winsock.h to get WSADATA and other stuff
45 // used in wxGetFullHostName() with the old mingw32 versions
46 #include <winsock.h>
47#endif
48
2bda0e17
KB
49#include "wx/timer.h"
50
b4da152e 51#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
a4f96412 52 #include <direct.h>
ce3ed50d 53
a4f96412
VZ
54 #ifndef __MWERKS__
55 #include <dos.h>
56 #endif
743e0a66 57#endif //GNUWIN32
2bda0e17 58
e02e8816 59#if defined(__CYGWIN__) && !defined(__TWIN32__)
a4f96412
VZ
60 #include <sys/unistd.h>
61 #include <sys/stat.h>
3ffbc733 62 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
743e0a66
VZ
63#endif //GNUWIN32
64
2bda0e17
KB
65#ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
66 // this (3.1 I believe) and how to test for it.
67 // If this works for Borland 4.0 as well, then no worries.
a4f96412 68 #include <dir.h>
2bda0e17
KB
69#endif
70
a4f96412
VZ
71// VZ: there is some code using NetXXX() functions to get the full user name:
72// I don't think it's a good idea because they don't work under Win95 and
73// seem to return the same as wxGetUserId() under NT. If you really want
74// to use them, just #define USE_NET_API
75#undef USE_NET_API
76
77#ifdef USE_NET_API
78 #include <lm.h>
79#endif // USE_NET_API
80
b4da152e 81#if defined(__WIN32__) && !defined(__WXMICROWIN__)
2e38557f
JS
82 #ifndef __UNIX__
83 #include <io.h>
84 #endif
2bda0e17 85
a4f96412
VZ
86 #ifndef __GNUWIN32__
87 #include <shellapi.h>
88 #endif
2bda0e17
KB
89#endif
90
2bda0e17 91#ifndef __WATCOMC__
3f4a0c5b
VZ
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
93 #include <errno.h>
94 #endif
2bda0e17 95#endif
2bda0e17 96
c030b70f 97//// BEGIN for console support: VC++ only
631f1bfe 98#ifdef __VISUALC__
c030b70f 99
3f4a0c5b 100#include "wx/msw/msvcrt.h"
c030b70f 101
3f4a0c5b 102#include <fcntl.h>
c030b70f 103
3f4a0c5b 104#include "wx/ioswrap.h"
c030b70f 105
c030b70f
JS
106/* Need to undef new if including crtdbg.h */
107# ifdef new
108# undef new
109# endif
110
1e6d9499 111#ifndef __WIN16__
c030b70f 112# include <crtdbg.h>
1e6d9499 113#endif
c030b70f
JS
114
115# if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
f6bcfd97 116# define new new(__TFILE__,__LINE__)
c030b70f
JS
117# endif
118
631f1bfe
JS
119#endif
120 // __VISUALC__
c030b70f
JS
121/// END for console support
122
b568d04f
VZ
123// ----------------------------------------------------------------------------
124// constants
125// ----------------------------------------------------------------------------
126
2bda0e17 127// In the WIN.INI file
223d09f6 128static const wxChar WX_SECTION[] = wxT("wxWindows");
b568d04f
VZ
129static const wxChar eUSERNAME[] = wxT("UserName");
130
131// these are only used under Win16
04ef50df 132#if !defined(__WIN32__) && !defined(__WXMICROWIN__)
223d09f6
KB
133static const wxChar eHOSTNAME[] = wxT("HostName");
134static const wxChar eUSERID[] = wxT("UserId");
b568d04f
VZ
135#endif // !Win32
136
04ef50df
JS
137#ifndef __WXMICROWIN__
138
b568d04f
VZ
139// ============================================================================
140// implementation
141// ============================================================================
2bda0e17 142
b568d04f
VZ
143// ----------------------------------------------------------------------------
144// get host name and related
145// ----------------------------------------------------------------------------
2bda0e17 146
1f0500b3 147// Get hostname only (without domain name)
837e5743 148bool wxGetHostName(wxChar *buf, int maxSize)
2bda0e17 149{
04ef50df 150#if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
b568d04f
VZ
151 DWORD nSize = maxSize;
152 if ( !::GetComputerName(buf, &nSize) )
153 {
f6bcfd97 154 wxLogLastError(wxT("GetComputerName"));
b568d04f
VZ
155
156 return FALSE;
157 }
158
159 return TRUE;
2bda0e17 160#else
b568d04f
VZ
161 wxChar *sysname;
162 const wxChar *default_host = wxT("noname");
163
164 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
165 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
166 } else
167 wxStrncpy(buf, sysname, maxSize - 1);
168 buf[maxSize] = wxT('\0');
169 return *buf ? TRUE : FALSE;
2bda0e17
KB
170#endif
171}
172
1f0500b3 173// get full hostname (with domain name if possible)
b568d04f
VZ
174bool wxGetFullHostName(wxChar *buf, int maxSize)
175{
04ef50df 176#if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
1f0500b3 177 // TODO should use GetComputerNameEx() when available
79180098
VZ
178
179 // the idea is that if someone had set wxUSE_SOCKETS to 0 the code
180 // shouldn't use winsock.dll (a.k.a. ws2_32.dll) at all so only use this
181 // code if we link with it anyhow
182#if wxUSE_SOCKETS
4ce1efe1
CE
183 //FIXME __DIGITALMARS__ why is using sockets not properly turned off in setup.h ??
184 // find which library should contain sockets for Digital Mars CE April 2003
185#ifndef __DIGITALMARS__
1f0500b3
VZ
186 WSADATA wsa;
187 if ( WSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
188 {
189 wxString host;
190 char bufA[256];
191 if ( gethostname(bufA, WXSIZEOF(bufA)) == 0 )
192 {
193 // gethostname() won't usually include the DNS domain name, for
194 // this we need to work a bit more
195 if ( !strchr(bufA, '.') )
196 {
197 struct hostent *pHostEnt = gethostbyname(bufA);
198
199 if ( pHostEnt )
200 {
201 // Windows will use DNS internally now
d5b18b50 202 pHostEnt = gethostbyaddr(pHostEnt->h_addr, 4, AF_INET);
1f0500b3
VZ
203 }
204
205 if ( pHostEnt )
206 {
2b5f62a0 207 host = wxString::FromAscii(pHostEnt->h_name);
1f0500b3
VZ
208 }
209 }
210 }
211
212 WSACleanup();
213
79180098 214 if ( !host.empty() )
1f0500b3
VZ
215 {
216 wxStrncpy(buf, host, maxSize);
217
218 return TRUE;
219 }
220 }
4ce1efe1
CE
221#endif //__DIGITALMARS__
222
79180098
VZ
223#endif // wxUSE_SOCKETS
224
1f0500b3
VZ
225#endif // Win32
226
b568d04f
VZ
227 return wxGetHostName(buf, maxSize);
228}
229
2bda0e17 230// Get user ID e.g. jacs
837e5743 231bool wxGetUserId(wxChar *buf, int maxSize)
2bda0e17 232{
04ef50df 233#if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
0a144271
VZ
234 DWORD nSize = maxSize;
235 if ( ::GetUserName(buf, &nSize) == 0 )
236 {
a4f96412 237 // actually, it does happen on Win9x if the user didn't log on
223d09f6 238 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
a4f96412
VZ
239 if ( res == 0 )
240 {
241 // not found
242 return FALSE;
243 }
0a144271
VZ
244 }
245
246 return TRUE;
0a144271 247#else // Win16 or Win32s
b568d04f
VZ
248 wxChar *user;
249 const wxChar *default_id = wxT("anonymous");
2bda0e17 250
b568d04f
VZ
251 // Can't assume we have NIS (PC-NFS) or some other ID daemon
252 // So we ...
253 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
254 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
255 {
256 // Use wxWindows configuration data (comming soon)
257 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
258 }
259 else
260 {
261 wxStrncpy(buf, user, maxSize - 1);
262 }
a4f96412 263
b568d04f 264 return *buf ? TRUE : FALSE;
2bda0e17
KB
265#endif
266}
267
268// Get user name e.g. Julian Smart
837e5743 269bool wxGetUserName(wxChar *buf, int maxSize)
2bda0e17 270{
0a144271 271#if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
b568d04f
VZ
272 extern HANDLE g_hPenWin; // PenWindows Running?
273 if (g_hPenWin)
274 {
275 // PenWindows Does have a user concept!
276 // Get the current owner of the recognizer
277 GetPrivateProfileString("Current", "User", default_name, wxBuffer, maxSize - 1, "PENWIN.INI");
278 strncpy(buf, wxBuffer, maxSize - 1);
279 }
280 else
2bda0e17 281#endif
b568d04f 282 {
a4f96412 283#ifdef USE_NET_API
b568d04f
VZ
284 CHAR szUserName[256];
285 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
286 return FALSE;
a4f96412 287
b568d04f
VZ
288 // TODO how to get the domain name?
289 CHAR *szDomain = "";
a4f96412 290
b568d04f
VZ
291 // the code is based on the MSDN example (also see KB article Q119670)
292 WCHAR wszUserName[256]; // Unicode user name
293 WCHAR wszDomain[256];
294 LPBYTE ComputerName;
a4f96412 295
b568d04f 296 USER_INFO_2 *ui2; // User structure
a4f96412 297
b568d04f
VZ
298 // Convert ANSI user name and domain to Unicode
299 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
300 wszUserName, WXSIZEOF(wszUserName) );
301 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
302 wszDomain, WXSIZEOF(wszDomain) );
a4f96412 303
b568d04f
VZ
304 // Get the computer name of a DC for the domain.
305 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
306 {
307 wxLogError(wxT("Can not find domain controller"));
a4f96412 308
b568d04f
VZ
309 goto error;
310 }
a4f96412 311
b568d04f
VZ
312 // Look up the user on the DC
313 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
314 (LPWSTR)&wszUserName,
315 2, // level - we want USER_INFO_2
316 (LPBYTE *) &ui2 );
317 switch ( status )
318 {
319 case NERR_Success:
320 // ok
321 break;
a4f96412 322
b568d04f
VZ
323 case NERR_InvalidComputer:
324 wxLogError(wxT("Invalid domain controller name."));
a4f96412 325
b568d04f 326 goto error;
a4f96412 327
b568d04f
VZ
328 case NERR_UserNotFound:
329 wxLogError(wxT("Invalid user name '%s'."), szUserName);
a4f96412 330
b568d04f 331 goto error;
a4f96412 332
b568d04f
VZ
333 default:
334 wxLogSysError(wxT("Can't get information about user"));
a4f96412 335
b568d04f
VZ
336 goto error;
337 }
a4f96412 338
b568d04f
VZ
339 // Convert the Unicode full name to ANSI
340 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
341 buf, maxSize, NULL, NULL );
a4f96412 342
b568d04f 343 return TRUE;
a4f96412
VZ
344
345error:
b568d04f 346 wxLogError(wxT("Couldn't look up full user name."));
a4f96412 347
b568d04f 348 return FALSE;
a4f96412 349#else // !USE_NET_API
b568d04f
VZ
350 // Could use NIS, MS-Mail or other site specific programs
351 // Use wxWindows configuration data
352 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxT(""), buf, maxSize - 1) != 0;
353 if ( !ok )
354 {
355 ok = wxGetUserId(buf, maxSize);
356 }
0a144271 357
b568d04f
VZ
358 if ( !ok )
359 {
360 wxStrncpy(buf, wxT("Unknown User"), maxSize);
361 }
a4f96412 362#endif // Win32/16
b568d04f 363 }
0a144271 364
b568d04f 365 return TRUE;
2bda0e17
KB
366}
367
b568d04f 368const wxChar* wxGetHomeDir(wxString *pstr)
2bda0e17 369{
b568d04f 370 wxString& strDir = *pstr;
2bda0e17 371
b568d04f
VZ
372 #if defined(__UNIX__) && !defined(__TWIN32__)
373 const wxChar *szHome = wxGetenv("HOME");
374 if ( szHome == NULL ) {
375 // we're homeless...
376 wxLogWarning(_("can't find user's HOME, using current directory."));
377 strDir = wxT(".");
378 }
379 else
380 strDir = szHome;
2bda0e17 381
b568d04f
VZ
382 // add a trailing slash if needed
383 if ( strDir.Last() != wxT('/') )
384 strDir << wxT('/');
3ffbc733 385
e02e8816 386 #ifdef __CYGWIN__
3ffbc733
VZ
387 // Cygwin returns unix type path but that does not work well
388 static wxChar windowsPath[MAX_PATH];
389 cygwin_conv_to_full_win32_path(strDir, windowsPath);
390 strDir = windowsPath;
391 #endif
b568d04f
VZ
392 #else // Windows
393 #ifdef __WIN32__
96c21216
VZ
394 strDir.clear();
395
396 // If we have a valid HOME directory, as is used on many machines that
397 // have unix utilities on them, we should use that.
398 const wxChar *szHome = wxGetenv(wxT("HOME"));
399
b568d04f 400 if ( szHome != NULL )
96c21216
VZ
401 {
402 strDir = szHome;
b568d04f 403 }
96c21216
VZ
404 else // no HOME, try HOMEDRIVE/PATH
405 {
406 szHome = wxGetenv(wxT("HOMEDRIVE"));
407 if ( szHome != NULL )
408 strDir << szHome;
409 szHome = wxGetenv(wxT("HOMEPATH"));
410
411 if ( szHome != NULL )
412 {
413 strDir << szHome;
414
415 // the idea is that under NT these variables have default values
416 // of "%systemdrive%:" and "\\". As we don't want to create our
417 // config files in the root directory of the system drive, we will
418 // create it in our program's dir. However, if the user took care
419 // to set HOMEPATH to something other than "\\", we suppose that he
420 // knows what he is doing and use the supplied value.
421 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
422 strDir.clear();
423 }
424 }
425
426 if ( strDir.empty() )
427 {
428 // If we have a valid USERPROFILE directory, as is the case in
429 // Windows NT, 2000 and XP, we should use that as our home directory.
430 szHome = wxGetenv(wxT("USERPROFILE"));
2bda0e17 431
96c21216
VZ
432 if ( szHome != NULL )
433 strDir = szHome;
434 }
435
436 if ( !strDir.empty() )
437 {
438 return strDir.c_str();
439 }
440 //else: fall back to the prograrm directory
b568d04f 441 #else // Win16
96c21216 442 // Win16 has no idea about home, so use the executable directory instead
b568d04f 443 #endif // WIN16/32
2bda0e17 444
b568d04f
VZ
445 // 260 was taken from windef.h
446 #ifndef MAX_PATH
447 #define MAX_PATH 260
448 #endif
2bda0e17 449
b568d04f
VZ
450 wxString strPath;
451 ::GetModuleFileName(::GetModuleHandle(NULL),
452 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
453 strPath.UngetWriteBuf();
2bda0e17 454
b568d04f
VZ
455 // extract the dir name
456 wxSplitPath(strPath, &strDir, NULL, NULL);
58a33cb4 457
b568d04f
VZ
458 #endif // UNIX/Win
459
460 return strDir.c_str();
afb74891
VZ
461}
462
33ac7e6f 463wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
2bda0e17 464{
b568d04f
VZ
465 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
466 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
467 // static buffer and sometimes I don't even know what.
468 static wxString s_home;
2bda0e17 469
b568d04f 470 return (wxChar *)wxGetHomeDir(&s_home);
2bda0e17
KB
471}
472
b568d04f 473bool wxDirExists(const wxString& dir)
2bda0e17 474{
04ef50df
JS
475#ifdef __WXMICROWIN__
476 return wxPathExist(dir);
477#elif defined(__WIN32__)
cf1eeea3 478 DWORD attribs = GetFileAttributes(dir);
3897b707 479 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
b568d04f
VZ
480#else // Win16
481 #ifdef __BORLANDC__
482 struct ffblk fileInfo;
483 #else
484 struct find_t fileInfo;
485 #endif
b568d04f
VZ
486 // In Borland findfirst has a different argument
487 // ordering from _dos_findfirst. But _dos_findfirst
488 // _should_ be ok in both MS and Borland... why not?
489 #ifdef __BORLANDC__
490 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
491 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
492 #else
493 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
494 ((fileInfo.attrib & _A_SUBDIR) != 0);
495 #endif
496#endif // Win32/16
497}
2bda0e17 498
eadd7bd2
VZ
499bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
500{
501 if ( path.empty() )
502 return FALSE;
503
ee88cb34
MB
504// old w32api don't have ULARGE_INTEGER
505#if defined(__WIN32__) && \
506 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
eadd7bd2
VZ
507 // GetDiskFreeSpaceEx() is not available under original Win95, check for
508 // it
9ee966ec
VZ
509 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
510 PULARGE_INTEGER,
511 PULARGE_INTEGER,
512 PULARGE_INTEGER);
eadd7bd2
VZ
513
514 GetDiskFreeSpaceEx_t
bb0e27ee 515 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
eadd7bd2
VZ
516 (
517 ::GetModuleHandle(_T("kernel32.dll")),
518#if wxUSE_UNICODE
519 "GetDiskFreeSpaceExW"
520#else
521 "GetDiskFreeSpaceExA"
522#endif
523 );
524
525 if ( pGetDiskFreeSpaceEx )
526 {
527 ULARGE_INTEGER bytesFree, bytesTotal;
528
529 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
530 if ( !pGetDiskFreeSpaceEx(path,
531 &bytesFree,
532 &bytesTotal,
533 NULL) )
534 {
535 wxLogLastError(_T("GetDiskFreeSpaceEx"));
536
537 return FALSE;
538 }
539
221e1181
VZ
540 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
541 // two 32 bit fields which may be or may be not named - try to make it
542 // compile in all cases
543#if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
544 #define UL(ul) ul.u
545#else // anon union
546 #define UL(ul) ul
547#endif
eadd7bd2
VZ
548 if ( pTotal )
549 {
221e1181 550 *pTotal = wxLongLong(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
eadd7bd2
VZ
551 }
552
553 if ( pFree )
554 {
221e1181 555 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
eadd7bd2
VZ
556 }
557 }
558 else
559#endif // Win32
560 {
bb0e27ee
VZ
561 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
562 // should be used instead - but if it's not available, fall back on
563 // GetDiskFreeSpace() nevertheless...
564
eadd7bd2
VZ
565 DWORD lSectorsPerCluster,
566 lBytesPerSector,
567 lNumberOfFreeClusters,
568 lTotalNumberOfClusters;
569
570 // FIXME: this is wrong, we should extract the root drive from path
571 // instead, but this is the job for wxFileName...
572 if ( !::GetDiskFreeSpace(path,
573 &lSectorsPerCluster,
574 &lBytesPerSector,
575 &lNumberOfFreeClusters,
576 &lTotalNumberOfClusters) )
577 {
578 wxLogLastError(_T("GetDiskFreeSpace"));
579
580 return FALSE;
581 }
582
eadd7bd2
VZ
583 wxLongLong lBytesPerCluster = lSectorsPerCluster;
584 lBytesPerCluster *= lBytesPerSector;
585
586 if ( pTotal )
587 {
588 *pTotal = lBytesPerCluster;
589 *pTotal *= lTotalNumberOfClusters;
590 }
591
592 if ( pFree )
593 {
594 *pFree = lBytesPerCluster;
595 *pFree *= lNumberOfFreeClusters;
596 }
597 }
598
599 return TRUE;
600}
601
308978f6
VZ
602// ----------------------------------------------------------------------------
603// env vars
604// ----------------------------------------------------------------------------
605
606bool wxGetEnv(const wxString& var, wxString *value)
607{
788722ac
JS
608#ifdef __WIN16__
609 const wxChar* ret = wxGetenv(var);
e622dd68
VZ
610 if ( !ret )
611 return FALSE;
612
613 if ( value )
788722ac
JS
614 {
615 *value = ret;
788722ac 616 }
e622dd68
VZ
617
618 return TRUE;
619#else // Win32
308978f6
VZ
620 // first get the size of the buffer
621 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
622 if ( !dwRet )
623 {
624 // this means that there is no such variable
625 return FALSE;
626 }
627
628 if ( value )
629 {
630 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
631 value->UngetWriteBuf();
632 }
633
634 return TRUE;
e622dd68 635#endif // Win16/32
308978f6
VZ
636}
637
1fb45475
VZ
638bool wxSetEnv(const wxString& var, const wxChar *value)
639{
640 // some compilers have putenv() or _putenv() or _wputenv() but it's better
641 // to always use Win32 function directly instead of dealing with them
642#if defined(__WIN32__)
643 if ( !::SetEnvironmentVariable(var, value) )
644 {
645 wxLogLastError(_T("SetEnvironmentVariable"));
646
647 return FALSE;
648 }
649
650 return TRUE;
651#else // no way to set env vars
652 return FALSE;
653#endif
654}
655
b568d04f
VZ
656// ----------------------------------------------------------------------------
657// process management
658// ----------------------------------------------------------------------------
659
50567b69
VZ
660// structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
661struct wxFindByPidParams
b568d04f 662{
50567b69
VZ
663 wxFindByPidParams() { hwnd = 0; pid = 0; }
664
665 // the HWND used to return the result
666 HWND hwnd;
667
668 // the PID we're looking from
669 DWORD pid;
22f3361e
VZ
670
671 DECLARE_NO_COPY_CLASS(wxFindByPidParams)
50567b69
VZ
672};
673
674// wxKill helper: EnumWindows() callback which is used to find the first (top
675// level) window belonging to the given process
676BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
677{
678 DWORD pid;
679 (void)::GetWindowThreadProcessId(hwnd, &pid);
680
681 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
682 if ( pid == params->pid )
683 {
684 // remember the window we found
685 params->hwnd = hwnd;
686
687 // return FALSE to stop the enumeration
688 return FALSE;
689 }
690
691 // continue enumeration
692 return TRUE;
693}
e949bf13 694
50567b69
VZ
695int wxKill(long pid, wxSignal sig, wxKillError *krc)
696{
50567b69
VZ
697 // get the process handle to operate on
698 HANDLE hProcess = ::OpenProcess(SYNCHRONIZE |
699 PROCESS_TERMINATE |
700 PROCESS_QUERY_INFORMATION,
701 FALSE, // not inheritable
702 (DWORD)pid);
703 if ( hProcess == NULL )
e949bf13 704 {
50567b69 705 if ( krc )
e949bf13 706 {
50567b69 707 if ( ::GetLastError() == ERROR_ACCESS_DENIED )
e949bf13 708 {
50567b69
VZ
709 *krc = wxKILL_ACCESS_DENIED;
710 }
711 else
712 {
713 *krc = wxKILL_NO_PROCESS;
714 }
715 }
716
717 return -1;
718 }
719
720 bool ok = TRUE;
721 switch ( sig )
722 {
723 case wxSIGKILL:
724 // kill the process forcefully returning -1 as error code
725 if ( !::TerminateProcess(hProcess, (UINT)-1) )
726 {
727 wxLogSysError(_("Failed to kill process %d"), pid);
728
729 if ( krc )
e949bf13 730 {
50567b69
VZ
731 // this is not supposed to happen if we could open the
732 // process
733 *krc = wxKILL_ERROR;
e949bf13 734 }
50567b69
VZ
735
736 ok = FALSE;
e949bf13 737 }
50567b69
VZ
738 break;
739
740 case wxSIGNONE:
741 // do nothing, we just want to test for process existence
742 break;
743
744 default:
745 // any other signal means "terminate"
746 {
747 wxFindByPidParams params;
748 params.pid = (DWORD)pid;
749
750 // EnumWindows() has nice semantics: it returns 0 if it found
751 // something or if an error occured and non zero if it
752 // enumerated all the window
753 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
754 {
755 // did we find any window?
756 if ( params.hwnd )
757 {
758 // tell the app to close
759 //
760 // NB: this is the harshest way, the app won't have
761 // opportunity to save any files, for example, but
762 // this is probably what we want here. If not we
763 // can also use SendMesageTimeout(WM_CLOSE)
764 if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
765 {
766 wxLogLastError(_T("PostMessage(WM_QUIT)"));
767 }
768 }
769 else // it was an error then
770 {
771 wxLogLastError(_T("EnumWindows"));
772
773 ok = FALSE;
774 }
775 }
776 else // no windows for this PID
777 {
778 if ( krc )
779 {
780 *krc = wxKILL_ERROR;
781 }
782
783 ok = FALSE;
784 }
785 }
786 }
787
788 // the return code
789 DWORD rc;
790
791 if ( ok )
792 {
793 // as we wait for a short time, we can use just WaitForSingleObject()
794 // and not MsgWaitForMultipleObjects()
795 switch ( ::WaitForSingleObject(hProcess, 500 /* msec */) )
796 {
797 case WAIT_OBJECT_0:
798 // process terminated
799 if ( !::GetExitCodeProcess(hProcess, &rc) )
800 {
801 wxLogLastError(_T("GetExitCodeProcess"));
802 }
803 break;
804
805 default:
806 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
807 // fall through
808
809 case WAIT_FAILED:
810 wxLogLastError(_T("WaitForSingleObject"));
811 // fall through
812
813 case WAIT_TIMEOUT:
814 if ( krc )
815 {
816 *krc = wxKILL_ERROR;
817 }
818
819 rc = STILL_ACTIVE;
820 break;
e949bf13
JS
821 }
822 }
50567b69
VZ
823 else // !ok
824 {
825 // just to suppress the warnings about uninitialized variable
826 rc = 0;
827 }
e949bf13 828
50567b69 829 ::CloseHandle(hProcess);
b568d04f 830
50567b69
VZ
831 // the return code is the same as from Unix kill(): 0 if killed
832 // successfully or -1 on error
b1a28eef
VZ
833 //
834 // be careful to interpret rc correctly: for wxSIGNONE we return success if
835 // the process exists, for all the other sig values -- if it doesn't
836 if ( ok &&
837 ((sig == wxSIGNONE) == (rc == STILL_ACTIVE)) )
e949bf13 838 {
b1a28eef 839 if ( krc )
50567b69 840 {
b1a28eef 841 *krc = wxKILL_OK;
50567b69 842 }
b1a28eef
VZ
843
844 return 0;
e949bf13 845 }
50567b69
VZ
846
847 // error
848 return -1;
2bda0e17
KB
849}
850
b568d04f
VZ
851// Execute a program in an Interactive Shell
852bool wxShell(const wxString& command)
2bda0e17 853{
b568d04f
VZ
854 wxChar *shell = wxGetenv(wxT("COMSPEC"));
855 if ( !shell )
ba14d986 856 shell = (wxChar*) wxT("\\COMMAND.COM");
b568d04f
VZ
857
858 wxString cmd;
859 if ( !command )
860 {
861 // just the shell
862 cmd = shell;
863 }
864 else
865 {
866 // pass the command to execute to the command processor
867 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
868 }
869
011a524e 870 return wxExecute(cmd, wxEXEC_SYNC) == 0;
2bda0e17
KB
871}
872
d8c65cf4 873// Shutdown or reboot the PC
f6ba47d9
VZ
874bool wxShutdown(wxShutdownFlags wFlags)
875{
876#ifdef __WIN32__
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{
b568d04f
VZ
940#if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
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
bdc72a22
VZ
1015int wxGetOsVersion(int *majorVsn, int *minorVsn)
1016{
4ce1efe1 1017#if defined(__WIN32__)
6af638ed 1018 static int ver = -1, major = -1, minor = -1;
96c21216 1019
6af638ed 1020 if ( ver == -1 )
bdc72a22 1021 {
6af638ed
VS
1022 OSVERSIONINFO info;
1023 wxZeroMemory(info);
ec5d7799 1024
6af638ed
VS
1025 ver = wxWINDOWS;
1026 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1027 if ( ::GetVersionEx(&info) )
bdc72a22 1028 {
6af638ed
VS
1029 major = info.dwMajorVersion;
1030 minor = info.dwMinorVersion;
bdc72a22 1031
6af638ed
VS
1032 switch ( info.dwPlatformId )
1033 {
1034 case VER_PLATFORM_WIN32s:
1035 ver = wxWIN32S;
1036 break;
bdc72a22 1037
6af638ed
VS
1038 case VER_PLATFORM_WIN32_WINDOWS:
1039 ver = wxWIN95;
1040 break;
1041
1042 case VER_PLATFORM_WIN32_NT:
1043 ver = wxWINDOWS_NT;
1044 break;
1045 }
bdc72a22
VZ
1046 }
1047 }
1048
6af638ed
VS
1049 if (majorVsn && major != -1)
1050 *majorVsn = major;
1051 if (minorVsn && minor != -1)
1052 *minorVsn = minor;
96c21216 1053
6af638ed 1054 return ver;
bdc72a22
VZ
1055#else // Win16
1056 int retValue = wxWINDOWS;
1057 #ifdef __WINDOWS_386__
1058 retValue = wxWIN386;
1059 #else
1060 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
1061 extern HANDLE g_hPenWin;
1062 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
1063 #endif
1064 #endif
1065
1066 if (majorVsn)
1067 *majorVsn = 3;
1068 if (minorVsn)
1069 *minorVsn = 1;
1070
1071 return retValue;
6f65e337 1072#endif
2bda0e17
KB
1073}
1074
b568d04f
VZ
1075// ----------------------------------------------------------------------------
1076// sleep functions
1077// ----------------------------------------------------------------------------
1078
1079#if wxUSE_GUI
1080
1e6feb95
VZ
1081#if wxUSE_TIMER
1082
b568d04f
VZ
1083// Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1084static bool gs_inTimer = FALSE;
1085
1e6feb95 1086class wxSleepTimer : public wxTimer
b568d04f
VZ
1087{
1088public:
1089 virtual void Notify()
1090 {
1091 gs_inTimer = FALSE;
1092 Stop();
1093 }
1094};
1095
1096static wxTimer *wxTheSleepTimer = NULL;
1097
1098void wxUsleep(unsigned long milliseconds)
1099{
1100#ifdef __WIN32__
1101 ::Sleep(milliseconds);
1e6feb95 1102#else // !Win32
b568d04f
VZ
1103 if (gs_inTimer)
1104 return;
d8c65cf4
RD
1105 if (miliseconds <= 0)
1106 return;
b568d04f
VZ
1107
1108 wxTheSleepTimer = new wxSleepTimer;
1109 gs_inTimer = TRUE;
1110 wxTheSleepTimer->Start(milliseconds);
1111 while (gs_inTimer)
1112 {
1113 if (wxTheApp->Pending())
1114 wxTheApp->Dispatch();
1115 }
1116 delete wxTheSleepTimer;
1117 wxTheSleepTimer = NULL;
1e6feb95 1118#endif // Win32/!Win32
b568d04f
VZ
1119}
1120
1121void wxSleep(int nSecs)
1122{
1123 if (gs_inTimer)
1124 return;
d8c65cf4
RD
1125 if (nSecs <= 0)
1126 return;
b568d04f
VZ
1127
1128 wxTheSleepTimer = new wxSleepTimer;
1129 gs_inTimer = TRUE;
1130 wxTheSleepTimer->Start(nSecs*1000);
1131 while (gs_inTimer)
1132 {
1133 if (wxTheApp->Pending())
1134 wxTheApp->Dispatch();
1135 }
1136 delete wxTheSleepTimer;
1137 wxTheSleepTimer = NULL;
1138}
1139
1140// Consume all events until no more left
1141void wxFlushEvents()
1142{
1143// wxYield();
1144}
1145
1e6feb95
VZ
1146#endif // wxUSE_TIMER
1147
b568d04f
VZ
1148#elif defined(__WIN32__) // wxUSE_GUI
1149
1150void wxUsleep(unsigned long milliseconds)
1151{
1152 ::Sleep(milliseconds);
1153}
1154
1155void wxSleep(int nSecs)
1156{
1157 wxUsleep(1000*nSecs);
1158}
1159
1160#endif // wxUSE_GUI/!wxUSE_GUI
373658eb 1161#endif // __WXMICROWIN__
b568d04f
VZ
1162
1163// ----------------------------------------------------------------------------
1164// deprecated (in favour of wxLog) log functions
1165// ----------------------------------------------------------------------------
1166
73deed44 1167#if WXWIN_COMPATIBILITY_2_2
b568d04f
VZ
1168
1169// Output a debug mess., in a system dependent fashion.
04ef50df 1170#ifndef __WXMICROWIN__
b568d04f
VZ
1171void wxDebugMsg(const wxChar *fmt ...)
1172{
1173 va_list ap;
1174 static wxChar buffer[512];
1175
1176 if (!wxTheApp->GetWantDebugOutput())
f6ba47d9 1177 return;
b568d04f
VZ
1178
1179 va_start(ap, fmt);
1180
f6ba47d9
VZ
1181 wvsprintf(buffer,fmt,ap);
1182 OutputDebugString((LPCTSTR)buffer);
b568d04f
VZ
1183
1184 va_end(ap);
1185}
1186
1187// Non-fatal error: pop up message box and (possibly) continue
1188void wxError(const wxString& msg, const wxString& title)
1189{
1190 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
1191 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
1192 MB_ICONSTOP | MB_YESNO) == IDNO)
1193 wxExit();
1194}
1195
1196// Fatal error: pop up message box and abort
1197void wxFatalError(const wxString& msg, const wxString& title)
1198{
1199 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
1200 FatalAppExit(0, (LPCTSTR)wxBuffer);
1201}
04ef50df 1202#endif // __WXMICROWIN__
b568d04f 1203
73deed44
VZ
1204#endif // WXWIN_COMPATIBILITY_2_2
1205
1206#if wxUSE_GUI
1207
b568d04f
VZ
1208// ----------------------------------------------------------------------------
1209// functions to work with .INI files
1210// ----------------------------------------------------------------------------
1211
2bda0e17 1212// Reading and writing resources (eg WIN.INI, .Xdefaults)
47d67540 1213#if wxUSE_RESOURCES
2bda0e17
KB
1214bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
1215{
223d09f6 1216 if (file != wxT(""))
8fb3a512
JS
1217// Don't know what the correct cast should be, but it doesn't
1218// compile in BC++/16-bit without this cast.
1219#if !defined(__WIN32__)
1220 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
1221#else
837e5743 1222 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
8fb3a512 1223#endif
2bda0e17 1224 else
837e5743 1225 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
2bda0e17
KB
1226}
1227
1228bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
1229{
b568d04f
VZ
1230 wxString buf;
1231 buf.Printf(wxT("%.4f"), value);
1232
1233 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
1234}
1235
1236bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
1237{
b568d04f
VZ
1238 wxString buf;
1239 buf.Printf(wxT("%ld"), value);
1240
1241 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
1242}
1243
1244bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
1245{
b568d04f
VZ
1246 wxString buf;
1247 buf.Printf(wxT("%d"), value);
1248
1249 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
1250}
1251
837e5743 1252bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
2bda0e17 1253{
b568d04f
VZ
1254 static const wxChar defunkt[] = wxT("$$default");
1255 if (file != wxT(""))
1256 {
1257 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1258 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
1259 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1260 return FALSE;
1261 }
1262 else
1263 {
1264 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1265 (LPTSTR)wxBuffer, 1000);
1266 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1267 return FALSE;
2bda0e17 1268 }
b568d04f
VZ
1269 if (*value) delete[] (*value);
1270 *value = copystring(wxBuffer);
1271 return TRUE;
1272}
2bda0e17
KB
1273
1274bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
1275{
b568d04f
VZ
1276 wxChar *s = NULL;
1277 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1278 if (succ)
1279 {
1280 *value = (float)wxStrtod(s, NULL);
1281 delete[] s;
1282 return TRUE;
1283 }
1284 else return FALSE;
2bda0e17
KB
1285}
1286
1287bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
1288{
b568d04f
VZ
1289 wxChar *s = NULL;
1290 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1291 if (succ)
1292 {
1293 *value = wxStrtol(s, NULL, 10);
1294 delete[] s;
1295 return TRUE;
1296 }
1297 else return FALSE;
2bda0e17
KB
1298}
1299
1300bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
1301{
b568d04f
VZ
1302 wxChar *s = NULL;
1303 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1304 if (succ)
1305 {
1306 *value = (int)wxStrtol(s, NULL, 10);
1307 delete[] s;
1308 return TRUE;
1309 }
1310 else return FALSE;
2bda0e17 1311}
47d67540 1312#endif // wxUSE_RESOURCES
2bda0e17 1313
634903fd 1314// ---------------------------------------------------------------------------
25889d3c 1315// helper functions for showing a "busy" cursor
634903fd
VZ
1316// ---------------------------------------------------------------------------
1317
bfbd6dc1
VZ
1318static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
1319static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
634903fd 1320static int gs_wxBusyCursorCount = 0;
2bda0e17 1321
cc972ac6
CE
1322#ifdef __DIGITALMARS__
1323extern "C" HCURSOR wxGetCurrentBusyCursor()
1324#else
bfbd6dc1 1325extern HCURSOR wxGetCurrentBusyCursor()
cc972ac6 1326#endif
bfbd6dc1
VZ
1327{
1328 return gs_wxBusyCursor;
1329}
1330
2bda0e17
KB
1331// Set the cursor to the busy cursor for all windows
1332void wxBeginBusyCursor(wxCursor *cursor)
1333{
634903fd
VZ
1334 if ( gs_wxBusyCursorCount++ == 0 )
1335 {
1336 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
04ef50df 1337#ifndef __WXMICROWIN__
634903fd 1338 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
04ef50df 1339#endif
634903fd
VZ
1340 }
1341 //else: nothing to do, already set
2bda0e17
KB
1342}
1343
1344// Restore cursor to normal
634903fd 1345void wxEndBusyCursor()
2bda0e17 1346{
634903fd 1347 wxCHECK_RET( gs_wxBusyCursorCount > 0,
223d09f6 1348 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
b07135ba 1349
634903fd
VZ
1350 if ( --gs_wxBusyCursorCount == 0 )
1351 {
04ef50df 1352#ifndef __WXMICROWIN__
634903fd 1353 ::SetCursor(gs_wxBusyCursorOld);
04ef50df 1354#endif
634903fd
VZ
1355 gs_wxBusyCursorOld = 0;
1356 }
2bda0e17
KB
1357}
1358
1359// TRUE if we're between the above two calls
634903fd 1360bool wxIsBusy()
2bda0e17 1361{
373658eb 1362 return gs_wxBusyCursorCount > 0;
b07135ba 1363}
2bda0e17 1364
2bda0e17
KB
1365// Check whether this window wants to process messages, e.g. Stop button
1366// in long calculations.
1367bool wxCheckForInterrupt(wxWindow *wnd)
1368{
b568d04f
VZ
1369 wxCHECK( wnd, FALSE );
1370
743e0a66 1371 MSG msg;
b568d04f
VZ
1372 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
1373 {
1374 ::TranslateMessage(&msg);
1375 ::DispatchMessage(&msg);
743e0a66 1376 }
634903fd 1377
b568d04f 1378 return TRUE;
2bda0e17
KB
1379}
1380
1381// MSW only: get user-defined resource from the .res file.
1382// Returns NULL or newly-allocated memory, so use delete[] to clean up.
1383
04ef50df 1384#ifndef __WXMICROWIN__
837e5743 1385wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
2bda0e17 1386{
b568d04f
VZ
1387 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
1388 if ( hResource == 0 )
1389 return NULL;
1390
1391 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
1392 if ( hData == 0 )
1393 return NULL;
2bda0e17 1394
b568d04f
VZ
1395 wxChar *theText = (wxChar *)::LockResource(hData);
1396 if ( !theText )
1397 return NULL;
b07135ba 1398
8caa4ed1
JS
1399 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1400 // so we need to find the length of the resource.
1401 int len = ::SizeofResource(wxGetInstance(), hResource);
1402 wxChar *s = new wxChar[len+1];
1403 wxStrncpy(s,theText,len);
1404 s[len]=0;
1405
1406 // wxChar *s = copystring(theText);
2bda0e17 1407
b568d04f 1408 // Obsolete in WIN32
2bda0e17 1409#ifndef __WIN32__
b568d04f 1410 UnlockResource(hData);
2bda0e17
KB
1411#endif
1412
b568d04f
VZ
1413 // No need??
1414 // GlobalFree(hData);
2bda0e17 1415
b568d04f 1416 return s;
2bda0e17 1417}
373658eb 1418#endif // __WXMICROWIN__
b568d04f
VZ
1419
1420// ----------------------------------------------------------------------------
1421// get display info
1422// ----------------------------------------------------------------------------
2bda0e17 1423
d3db92b2
JS
1424// See also the wxGetMousePosition in window.cpp
1425// Deprecated: use wxPoint wxGetMousePosition() instead
2bda0e17
KB
1426void wxGetMousePosition( int* x, int* y )
1427{
b568d04f
VZ
1428 POINT pt;
1429 GetCursorPos( & pt );
1430 if ( x ) *x = pt.x;
1431 if ( y ) *y = pt.y;
2bda0e17
KB
1432};
1433
1434// Return TRUE if we have a colour display
634903fd 1435bool wxColourDisplay()
2bda0e17 1436{
04ef50df
JS
1437#ifdef __WXMICROWIN__
1438 // MICROWIN_TODO
1439 return TRUE;
1440#else
807a903e
VZ
1441 // this function is called from wxDC ctor so it is called a *lot* of times
1442 // hence we optimize it a bit but doign the check only once
1443 //
1444 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1445 // can call us
1446 static int s_isColour = -1;
1447
1448 if ( s_isColour == -1 )
1449 {
1450 ScreenHDC dc;
1451 int noCols = ::GetDeviceCaps(dc, NUMCOLORS);
1452
1453 s_isColour = (noCols == -1) || (noCols > 2);
1454 }
b568d04f 1455
807a903e 1456 return s_isColour != 0;
04ef50df 1457#endif
2bda0e17
KB
1458}
1459
1460// Returns depth of screen
634903fd 1461int wxDisplayDepth()
2bda0e17 1462{
b568d04f
VZ
1463 ScreenHDC dc;
1464 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
2bda0e17
KB
1465}
1466
1467// Get size of display
1468void wxDisplaySize(int *width, int *height)
1469{
04ef50df 1470#ifdef __WXMICROWIN__
54800df8
JS
1471 RECT rect;
1472 HWND hWnd = GetDesktopWindow();
1473 ::GetWindowRect(hWnd, & rect);
1474
373658eb
VZ
1475 if ( width )
1476 *width = rect.right - rect.left;
1477 if ( height )
1478 *height = rect.bottom - rect.top;
1479#else // !__WXMICROWIN__
b568d04f 1480 ScreenHDC dc;
3f4a0c5b 1481
373658eb
VZ
1482 if ( width )
1483 *width = ::GetDeviceCaps(dc, HORZRES);
1484 if ( height )
1485 *height = ::GetDeviceCaps(dc, VERTRES);
1486#endif // __WXMICROWIN__/!__WXMICROWIN__
7f555861
JS
1487}
1488
904a68b6
RL
1489void wxDisplaySizeMM(int *width, int *height)
1490{
04ef50df
JS
1491#ifdef __WXMICROWIN__
1492 // MICROWIN_TODO
373658eb
VZ
1493 if ( width )
1494 *width = 0;
1495 if ( height )
1496 *height = 0;
04ef50df 1497#else
904a68b6
RL
1498 ScreenHDC dc;
1499
373658eb
VZ
1500 if ( width )
1501 *width = ::GetDeviceCaps(dc, HORZSIZE);
1502 if ( height )
1503 *height = ::GetDeviceCaps(dc, VERTSIZE);
04ef50df 1504#endif
904a68b6
RL
1505}
1506
ec5d7799
RD
1507void wxClientDisplayRect(int *x, int *y, int *width, int *height)
1508{
04ef50df 1509#if defined(__WIN16__) || defined(__WXMICROWIN__)
788722ac
JS
1510 *x = 0; *y = 0;
1511 wxDisplaySize(width, height);
1512#else
ec5d7799
RD
1513 // Determine the desktop dimensions minus the taskbar and any other
1514 // special decorations...
1515 RECT r;
788722ac 1516
ec5d7799
RD
1517 SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
1518 if (x) *x = r.left;
1519 if (y) *y = r.top;
1520 if (width) *width = r.right - r.left;
1521 if (height) *height = r.bottom - r.top;
788722ac 1522#endif
ec5d7799
RD
1523}
1524
cc2b7472
VZ
1525// ---------------------------------------------------------------------------
1526// window information functions
1527// ---------------------------------------------------------------------------
1528
1c4a764c
VZ
1529wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1530{
1531 wxString str;
5acc0d5f
VZ
1532
1533 if ( hWnd )
1534 {
1535 int len = GetWindowTextLength((HWND)hWnd) + 1;
1536 ::GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1537 str.UngetWriteBuf();
1538 }
1c4a764c
VZ
1539
1540 return str;
1541}
1542
cc2b7472
VZ
1543wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1544{
1545 wxString str;
1546
5acc0d5f
VZ
1547 // MICROWIN_TODO
1548#ifndef __WXMICROWIN__
1549 if ( hWnd )
cc2b7472 1550 {
5acc0d5f 1551 int len = 256; // some starting value
cc2b7472 1552
5acc0d5f 1553 for ( ;; )
cc2b7472 1554 {
5acc0d5f
VZ
1555 int count = ::GetClassName((HWND)hWnd, str.GetWriteBuf(len), len);
1556
1557 str.UngetWriteBuf();
1558 if ( count == len )
1559 {
1560 // the class name might have been truncated, retry with larger
1561 // buffer
1562 len *= 2;
1563 }
1564 else
1565 {
1566 break;
1567 }
cc2b7472
VZ
1568 }
1569 }
5acc0d5f 1570#endif // !__WXMICROWIN__
cc2b7472
VZ
1571
1572 return str;
1573}
1574
42e69d6b 1575WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
cc2b7472
VZ
1576{
1577#ifndef __WIN32__
33ac7e6f 1578 return (WXWORD)GetWindowWord((HWND)hWnd, GWW_ID);
cc2b7472 1579#else // Win32
33ac7e6f 1580 return (WXWORD)GetWindowLong((HWND)hWnd, GWL_ID);
cc2b7472
VZ
1581#endif // Win16/32
1582}
1583
b0c89ddf
JS
1584// ----------------------------------------------------------------------------
1585// Metafile helpers
1586// ----------------------------------------------------------------------------
1587
1588extern void PixelToHIMETRIC(LONG *x, LONG *y)
1589{
1590 ScreenHDC hdcRef;
1591
1592 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1593 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1594 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1595 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1596
1597 *x *= (iWidthMM * 100);
1598 *x /= iWidthPels;
1599 *y *= (iHeightMM * 100);
1600 *y /= iHeightPels;
1601}
1602
1603extern void HIMETRICToPixel(LONG *x, LONG *y)
1604{
1605 ScreenHDC hdcRef;
1606
1607 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1608 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1609 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1610 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1611
1612 *x *= iWidthPels;
1613 *x /= (iWidthMM * 100);
1614 *y *= iHeightPels;
1615 *y /= (iHeightMM * 100);
1616}
1617
1618#endif // wxUSE_GUI
1619
373658eb
VZ
1620#ifdef __WXMICROWIN__
1621int wxGetOsVersion(int *majorVsn, int *minorVsn)
7f555861 1622{
373658eb
VZ
1623 // MICROWIN_TODO
1624 if (majorVsn) *majorVsn = 0;
1625 if (minorVsn) *minorVsn = 0;
1626 return wxUNIX;
1627}
1628#endif // __WXMICROWIN__
7f555861 1629
373658eb
VZ
1630// ----------------------------------------------------------------------------
1631// Win32 codepage conversion functions
1632// ----------------------------------------------------------------------------
7f555861 1633
373658eb 1634#if defined(__WIN32__) && !defined(__WXMICROWIN__)
7f555861 1635
1f86850d
VZ
1636// wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1637#if wxUSE_GUI && !defined(__WXUNIVERSAL__)
c030b70f 1638
373658eb 1639#include "wx/fontmap.h"
c030b70f 1640
373658eb
VZ
1641// VZ: the new version of wxCharsetToCodepage() is more politically correct
1642// and should work on other Windows versions as well but the old version is
1643// still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
c030b70f 1644
373658eb 1645extern long wxEncodingToCodepage(wxFontEncoding encoding)
c030b70f 1646{
373658eb
VZ
1647 // translate encoding into the Windows CHARSET
1648 wxNativeEncodingInfo natveEncInfo;
1649 if ( !wxGetNativeFontEncoding(encoding, &natveEncInfo) )
1650 return -1;
1651
1652 // translate CHARSET to code page
1653 CHARSETINFO csetInfo;
1654 if ( !::TranslateCharsetInfo((DWORD *)(DWORD)natveEncInfo.charset,
1655 &csetInfo,
1656 TCI_SRCCHARSET) )
1657 {
1658 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1659
1660 return -1;
1661 }
1662
1663 return csetInfo.ciACP;
c030b70f 1664}
373658eb
VZ
1665
1666#if wxUSE_FONTMAP
1667
1668extern long wxCharsetToCodepage(const wxChar *name)
c030b70f 1669{
373658eb
VZ
1670 // first get the font encoding for this charset
1671 if ( !name )
1672 return -1;
1673
142b3bc2 1674 wxFontEncoding enc = wxFontMapper::Get()->CharsetToEncoding(name, FALSE);
373658eb
VZ
1675 if ( enc == wxFONTENCODING_SYSTEM )
1676 return -1;
1677
1678 // the use the helper function
1679 return wxEncodingToCodepage(enc);
c030b70f 1680}
c030b70f 1681
373658eb
VZ
1682#endif // wxUSE_FONTMAP
1683
1684#endif // wxUSE_GUI
1685
1686// include old wxCharsetToCodepage() by OK if needed
1687#if !wxUSE_GUI || !wxUSE_FONTMAP
1688
1689#include "wx/msw/registry.h"
1690
1691// this should work if Internet Exploiter is installed
1692extern long wxCharsetToCodepage(const wxChar *name)
04ef50df 1693{
373658eb
VZ
1694 if (!name)
1695 return GetACP();
1696
1697 long CP=-1;
1698
1699 wxString cn(name);
1700 do {
1701 wxString path(wxT("MIME\\Database\\Charset\\"));
1702 path += cn;
1703 wxRegKey key(wxRegKey::HKCR, path);
1704
1705 if (!key.Exists()) break;
1706
1707 // two cases: either there's an AliasForCharset string,
1708 // or there are Codepage and InternetEncoding dwords.
1709 // The InternetEncoding gives us the actual encoding,
1710 // the Codepage just says which Windows character set to
1711 // use when displaying the data.
1712 if (key.HasValue(wxT("InternetEncoding")) &&
1713 key.QueryValue(wxT("InternetEncoding"), &CP)) break;
1714
1715 // no encoding, see if it's an alias
1716 if (!key.HasValue(wxT("AliasForCharset")) ||
1717 !key.QueryValue(wxT("AliasForCharset"), cn)) break;
1718 } while (1);
1719
1720 return CP;
04ef50df 1721}
373658eb
VZ
1722
1723#endif // !wxUSE_GUI || !wxUSE_FONTMAP
1724
1725#endif // Win32
c030b70f 1726