]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utils.cpp
create the DIBs in correct (and not down up) line order
[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
1f0500b3
VZ
183 WSADATA wsa;
184 if ( WSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
185 {
186 wxString host;
187 char bufA[256];
188 if ( gethostname(bufA, WXSIZEOF(bufA)) == 0 )
189 {
190 // gethostname() won't usually include the DNS domain name, for
191 // this we need to work a bit more
192 if ( !strchr(bufA, '.') )
193 {
194 struct hostent *pHostEnt = gethostbyname(bufA);
195
196 if ( pHostEnt )
197 {
198 // Windows will use DNS internally now
d5b18b50 199 pHostEnt = gethostbyaddr(pHostEnt->h_addr, 4, AF_INET);
1f0500b3
VZ
200 }
201
202 if ( pHostEnt )
203 {
2b5f62a0 204 host = wxString::FromAscii(pHostEnt->h_name);
1f0500b3
VZ
205 }
206 }
207 }
208
209 WSACleanup();
210
79180098 211 if ( !host.empty() )
1f0500b3
VZ
212 {
213 wxStrncpy(buf, host, maxSize);
214
215 return TRUE;
216 }
217 }
79180098
VZ
218#endif // wxUSE_SOCKETS
219
1f0500b3
VZ
220#endif // Win32
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{
04ef50df 228#if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
0a144271
VZ
229 DWORD nSize = maxSize;
230 if ( ::GetUserName(buf, &nSize) == 0 )
231 {
a4f96412 232 // actually, it does happen on Win9x if the user didn't log on
223d09f6 233 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
a4f96412
VZ
234 if ( res == 0 )
235 {
236 // not found
237 return FALSE;
238 }
0a144271
VZ
239 }
240
241 return TRUE;
0a144271 242#else // Win16 or Win32s
b568d04f
VZ
243 wxChar *user;
244 const wxChar *default_id = wxT("anonymous");
2bda0e17 245
b568d04f
VZ
246 // Can't assume we have NIS (PC-NFS) or some other ID daemon
247 // So we ...
248 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
249 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
250 {
251 // Use wxWindows configuration data (comming soon)
252 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
253 }
254 else
255 {
256 wxStrncpy(buf, user, maxSize - 1);
257 }
a4f96412 258
b568d04f 259 return *buf ? TRUE : FALSE;
2bda0e17
KB
260#endif
261}
262
263// Get user name e.g. Julian Smart
837e5743 264bool wxGetUserName(wxChar *buf, int maxSize)
2bda0e17 265{
0a144271 266#if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
b568d04f
VZ
267 extern HANDLE g_hPenWin; // PenWindows Running?
268 if (g_hPenWin)
269 {
270 // PenWindows Does have a user concept!
271 // Get the current owner of the recognizer
272 GetPrivateProfileString("Current", "User", default_name, wxBuffer, maxSize - 1, "PENWIN.INI");
273 strncpy(buf, wxBuffer, maxSize - 1);
274 }
275 else
2bda0e17 276#endif
b568d04f 277 {
a4f96412 278#ifdef USE_NET_API
b568d04f
VZ
279 CHAR szUserName[256];
280 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
281 return FALSE;
a4f96412 282
b568d04f
VZ
283 // TODO how to get the domain name?
284 CHAR *szDomain = "";
a4f96412 285
b568d04f
VZ
286 // the code is based on the MSDN example (also see KB article Q119670)
287 WCHAR wszUserName[256]; // Unicode user name
288 WCHAR wszDomain[256];
289 LPBYTE ComputerName;
a4f96412 290
b568d04f 291 USER_INFO_2 *ui2; // User structure
a4f96412 292
b568d04f
VZ
293 // Convert ANSI user name and domain to Unicode
294 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
295 wszUserName, WXSIZEOF(wszUserName) );
296 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
297 wszDomain, WXSIZEOF(wszDomain) );
a4f96412 298
b568d04f
VZ
299 // Get the computer name of a DC for the domain.
300 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
301 {
302 wxLogError(wxT("Can not find domain controller"));
a4f96412 303
b568d04f
VZ
304 goto error;
305 }
a4f96412 306
b568d04f
VZ
307 // Look up the user on the DC
308 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
309 (LPWSTR)&wszUserName,
310 2, // level - we want USER_INFO_2
311 (LPBYTE *) &ui2 );
312 switch ( status )
313 {
314 case NERR_Success:
315 // ok
316 break;
a4f96412 317
b568d04f
VZ
318 case NERR_InvalidComputer:
319 wxLogError(wxT("Invalid domain controller name."));
a4f96412 320
b568d04f 321 goto error;
a4f96412 322
b568d04f
VZ
323 case NERR_UserNotFound:
324 wxLogError(wxT("Invalid user name '%s'."), szUserName);
a4f96412 325
b568d04f 326 goto error;
a4f96412 327
b568d04f
VZ
328 default:
329 wxLogSysError(wxT("Can't get information about user"));
a4f96412 330
b568d04f
VZ
331 goto error;
332 }
a4f96412 333
b568d04f
VZ
334 // Convert the Unicode full name to ANSI
335 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
336 buf, maxSize, NULL, NULL );
a4f96412 337
b568d04f 338 return TRUE;
a4f96412
VZ
339
340error:
b568d04f 341 wxLogError(wxT("Couldn't look up full user name."));
a4f96412 342
b568d04f 343 return FALSE;
a4f96412 344#else // !USE_NET_API
b568d04f
VZ
345 // Could use NIS, MS-Mail or other site specific programs
346 // Use wxWindows configuration data
347 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxT(""), buf, maxSize - 1) != 0;
348 if ( !ok )
349 {
350 ok = wxGetUserId(buf, maxSize);
351 }
0a144271 352
b568d04f
VZ
353 if ( !ok )
354 {
355 wxStrncpy(buf, wxT("Unknown User"), maxSize);
356 }
a4f96412 357#endif // Win32/16
b568d04f 358 }
0a144271 359
b568d04f 360 return TRUE;
2bda0e17
KB
361}
362
b568d04f 363const wxChar* wxGetHomeDir(wxString *pstr)
2bda0e17 364{
b568d04f 365 wxString& strDir = *pstr;
2bda0e17 366
b568d04f
VZ
367 #if defined(__UNIX__) && !defined(__TWIN32__)
368 const wxChar *szHome = wxGetenv("HOME");
369 if ( szHome == NULL ) {
370 // we're homeless...
371 wxLogWarning(_("can't find user's HOME, using current directory."));
372 strDir = wxT(".");
373 }
374 else
375 strDir = szHome;
2bda0e17 376
b568d04f
VZ
377 // add a trailing slash if needed
378 if ( strDir.Last() != wxT('/') )
379 strDir << wxT('/');
3ffbc733 380
e02e8816 381 #ifdef __CYGWIN__
3ffbc733
VZ
382 // Cygwin returns unix type path but that does not work well
383 static wxChar windowsPath[MAX_PATH];
384 cygwin_conv_to_full_win32_path(strDir, windowsPath);
385 strDir = windowsPath;
386 #endif
b568d04f
VZ
387 #else // Windows
388 #ifdef __WIN32__
96c21216
VZ
389 strDir.clear();
390
391 // If we have a valid HOME directory, as is used on many machines that
392 // have unix utilities on them, we should use that.
393 const wxChar *szHome = wxGetenv(wxT("HOME"));
394
b568d04f 395 if ( szHome != NULL )
96c21216
VZ
396 {
397 strDir = szHome;
b568d04f 398 }
96c21216
VZ
399 else // no HOME, try HOMEDRIVE/PATH
400 {
401 szHome = wxGetenv(wxT("HOMEDRIVE"));
402 if ( szHome != NULL )
403 strDir << szHome;
404 szHome = wxGetenv(wxT("HOMEPATH"));
405
406 if ( szHome != NULL )
407 {
408 strDir << szHome;
409
410 // the idea is that under NT these variables have default values
411 // of "%systemdrive%:" and "\\". As we don't want to create our
412 // config files in the root directory of the system drive, we will
413 // create it in our program's dir. However, if the user took care
414 // to set HOMEPATH to something other than "\\", we suppose that he
415 // knows what he is doing and use the supplied value.
416 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
417 strDir.clear();
418 }
419 }
420
421 if ( strDir.empty() )
422 {
423 // If we have a valid USERPROFILE directory, as is the case in
424 // Windows NT, 2000 and XP, we should use that as our home directory.
425 szHome = wxGetenv(wxT("USERPROFILE"));
2bda0e17 426
96c21216
VZ
427 if ( szHome != NULL )
428 strDir = szHome;
429 }
430
431 if ( !strDir.empty() )
432 {
433 return strDir.c_str();
434 }
435 //else: fall back to the prograrm directory
b568d04f 436 #else // Win16
96c21216 437 // Win16 has no idea about home, so use the executable directory instead
b568d04f 438 #endif // WIN16/32
2bda0e17 439
b568d04f
VZ
440 // 260 was taken from windef.h
441 #ifndef MAX_PATH
442 #define MAX_PATH 260
443 #endif
2bda0e17 444
b568d04f
VZ
445 wxString strPath;
446 ::GetModuleFileName(::GetModuleHandle(NULL),
447 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
448 strPath.UngetWriteBuf();
2bda0e17 449
b568d04f
VZ
450 // extract the dir name
451 wxSplitPath(strPath, &strDir, NULL, NULL);
58a33cb4 452
b568d04f
VZ
453 #endif // UNIX/Win
454
455 return strDir.c_str();
afb74891
VZ
456}
457
33ac7e6f 458wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
2bda0e17 459{
b568d04f
VZ
460 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
461 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
462 // static buffer and sometimes I don't even know what.
463 static wxString s_home;
2bda0e17 464
b568d04f 465 return (wxChar *)wxGetHomeDir(&s_home);
2bda0e17
KB
466}
467
b568d04f 468bool wxDirExists(const wxString& dir)
2bda0e17 469{
04ef50df
JS
470#ifdef __WXMICROWIN__
471 return wxPathExist(dir);
472#elif defined(__WIN32__)
cf1eeea3 473 DWORD attribs = GetFileAttributes(dir);
3897b707 474 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
b568d04f
VZ
475#else // Win16
476 #ifdef __BORLANDC__
477 struct ffblk fileInfo;
478 #else
479 struct find_t fileInfo;
480 #endif
b568d04f
VZ
481 // In Borland findfirst has a different argument
482 // ordering from _dos_findfirst. But _dos_findfirst
483 // _should_ be ok in both MS and Borland... why not?
484 #ifdef __BORLANDC__
485 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
486 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
487 #else
488 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
489 ((fileInfo.attrib & _A_SUBDIR) != 0);
490 #endif
491#endif // Win32/16
492}
2bda0e17 493
eadd7bd2
VZ
494bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
495{
496 if ( path.empty() )
497 return FALSE;
498
ee88cb34
MB
499// old w32api don't have ULARGE_INTEGER
500#if defined(__WIN32__) && \
501 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
eadd7bd2
VZ
502 // GetDiskFreeSpaceEx() is not available under original Win95, check for
503 // it
9ee966ec
VZ
504 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
505 PULARGE_INTEGER,
506 PULARGE_INTEGER,
507 PULARGE_INTEGER);
eadd7bd2
VZ
508
509 GetDiskFreeSpaceEx_t
bb0e27ee 510 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
eadd7bd2
VZ
511 (
512 ::GetModuleHandle(_T("kernel32.dll")),
513#if wxUSE_UNICODE
514 "GetDiskFreeSpaceExW"
515#else
516 "GetDiskFreeSpaceExA"
517#endif
518 );
519
520 if ( pGetDiskFreeSpaceEx )
521 {
522 ULARGE_INTEGER bytesFree, bytesTotal;
523
524 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
525 if ( !pGetDiskFreeSpaceEx(path,
526 &bytesFree,
527 &bytesTotal,
528 NULL) )
529 {
530 wxLogLastError(_T("GetDiskFreeSpaceEx"));
531
532 return FALSE;
533 }
534
221e1181
VZ
535 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
536 // two 32 bit fields which may be or may be not named - try to make it
537 // compile in all cases
538#if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
539 #define UL(ul) ul.u
540#else // anon union
541 #define UL(ul) ul
542#endif
eadd7bd2
VZ
543 if ( pTotal )
544 {
221e1181 545 *pTotal = wxLongLong(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
eadd7bd2
VZ
546 }
547
548 if ( pFree )
549 {
221e1181 550 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
eadd7bd2
VZ
551 }
552 }
553 else
554#endif // Win32
555 {
bb0e27ee
VZ
556 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
557 // should be used instead - but if it's not available, fall back on
558 // GetDiskFreeSpace() nevertheless...
559
eadd7bd2
VZ
560 DWORD lSectorsPerCluster,
561 lBytesPerSector,
562 lNumberOfFreeClusters,
563 lTotalNumberOfClusters;
564
565 // FIXME: this is wrong, we should extract the root drive from path
566 // instead, but this is the job for wxFileName...
567 if ( !::GetDiskFreeSpace(path,
568 &lSectorsPerCluster,
569 &lBytesPerSector,
570 &lNumberOfFreeClusters,
571 &lTotalNumberOfClusters) )
572 {
573 wxLogLastError(_T("GetDiskFreeSpace"));
574
575 return FALSE;
576 }
577
eadd7bd2
VZ
578 wxLongLong lBytesPerCluster = lSectorsPerCluster;
579 lBytesPerCluster *= lBytesPerSector;
580
581 if ( pTotal )
582 {
583 *pTotal = lBytesPerCluster;
584 *pTotal *= lTotalNumberOfClusters;
585 }
586
587 if ( pFree )
588 {
589 *pFree = lBytesPerCluster;
590 *pFree *= lNumberOfFreeClusters;
591 }
592 }
593
594 return TRUE;
595}
596
308978f6
VZ
597// ----------------------------------------------------------------------------
598// env vars
599// ----------------------------------------------------------------------------
600
601bool wxGetEnv(const wxString& var, wxString *value)
602{
788722ac
JS
603#ifdef __WIN16__
604 const wxChar* ret = wxGetenv(var);
e622dd68
VZ
605 if ( !ret )
606 return FALSE;
607
608 if ( value )
788722ac
JS
609 {
610 *value = ret;
788722ac 611 }
e622dd68
VZ
612
613 return TRUE;
614#else // Win32
308978f6
VZ
615 // first get the size of the buffer
616 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
617 if ( !dwRet )
618 {
619 // this means that there is no such variable
620 return FALSE;
621 }
622
623 if ( value )
624 {
625 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
626 value->UngetWriteBuf();
627 }
628
629 return TRUE;
e622dd68 630#endif // Win16/32
308978f6
VZ
631}
632
1fb45475
VZ
633bool wxSetEnv(const wxString& var, const wxChar *value)
634{
635 // some compilers have putenv() or _putenv() or _wputenv() but it's better
636 // to always use Win32 function directly instead of dealing with them
637#if defined(__WIN32__)
638 if ( !::SetEnvironmentVariable(var, value) )
639 {
640 wxLogLastError(_T("SetEnvironmentVariable"));
641
642 return FALSE;
643 }
644
645 return TRUE;
646#else // no way to set env vars
647 return FALSE;
648#endif
649}
650
b568d04f
VZ
651// ----------------------------------------------------------------------------
652// process management
653// ----------------------------------------------------------------------------
654
50567b69
VZ
655#ifdef __WIN32__
656
657// structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
658struct wxFindByPidParams
b568d04f 659{
50567b69
VZ
660 wxFindByPidParams() { hwnd = 0; pid = 0; }
661
662 // the HWND used to return the result
663 HWND hwnd;
664
665 // the PID we're looking from
666 DWORD pid;
22f3361e
VZ
667
668 DECLARE_NO_COPY_CLASS(wxFindByPidParams)
50567b69
VZ
669};
670
671// wxKill helper: EnumWindows() callback which is used to find the first (top
672// level) window belonging to the given process
673BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
674{
675 DWORD pid;
676 (void)::GetWindowThreadProcessId(hwnd, &pid);
677
678 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
679 if ( pid == params->pid )
680 {
681 // remember the window we found
682 params->hwnd = hwnd;
683
684 // return FALSE to stop the enumeration
685 return FALSE;
686 }
687
688 // continue enumeration
689 return TRUE;
690}
e949bf13 691
50567b69
VZ
692#endif // __WIN32__
693
694int wxKill(long pid, wxSignal sig, wxKillError *krc)
695{
696#ifdef __WIN32__
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
833 if ( sig == wxSIGNONE )
e949bf13 834 {
50567b69
VZ
835 if ( ok && rc == STILL_ACTIVE )
836 {
837 // there is such process => success
e949bf13 838 return 0;
50567b69 839 }
e949bf13 840 }
50567b69 841 else // not SIGNONE
e949bf13 842 {
50567b69
VZ
843 if ( ok && rc != STILL_ACTIVE )
844 {
845 // killed => success
e949bf13 846 return 0;
50567b69 847 }
e949bf13 848 }
f6ba47d9 849#else // Win16
50567b69
VZ
850 wxFAIL_MSG( _T("not implemented") );
851#endif // Win32/Win16
852
853 // error
854 return -1;
2bda0e17
KB
855}
856
b568d04f
VZ
857// Execute a program in an Interactive Shell
858bool wxShell(const wxString& command)
2bda0e17 859{
b568d04f
VZ
860 wxChar *shell = wxGetenv(wxT("COMSPEC"));
861 if ( !shell )
ba14d986 862 shell = (wxChar*) wxT("\\COMMAND.COM");
b568d04f
VZ
863
864 wxString cmd;
865 if ( !command )
866 {
867 // just the shell
868 cmd = shell;
869 }
870 else
871 {
872 // pass the command to execute to the command processor
873 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
874 }
875
011a524e 876 return wxExecute(cmd, wxEXEC_SYNC) == 0;
2bda0e17
KB
877}
878
d8c65cf4 879// Shutdown or reboot the PC
f6ba47d9
VZ
880bool wxShutdown(wxShutdownFlags wFlags)
881{
882#ifdef __WIN32__
883 bool bOK = TRUE;
884
885 if ( wxGetOsVersion(NULL, NULL) == wxWINDOWS_NT ) // if is NT or 2K
886 {
d8c65cf4
RD
887 // Get a token for this process.
888 HANDLE hToken;
f6ba47d9
VZ
889 bOK = ::OpenProcessToken(GetCurrentProcess(),
890 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
891 &hToken) != 0;
892 if ( bOK )
893 {
d8c65cf4 894 TOKEN_PRIVILEGES tkp;
f6ba47d9 895
d8c65cf4 896 // Get the LUID for the shutdown privilege.
f6ba47d9 897 ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
d8c65cf4 898 &tkp.Privileges[0].Luid);
f6ba47d9 899
d8c65cf4
RD
900 tkp.PrivilegeCount = 1; // one privilege to set
901 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
f6ba47d9 902
d8c65cf4 903 // Get the shutdown privilege for this process.
f6ba47d9 904 ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
d8c65cf4 905 (PTOKEN_PRIVILEGES)NULL, 0);
f6ba47d9 906
d8c65cf4 907 // Cannot test the return value of AdjustTokenPrivileges.
f6ba47d9
VZ
908 bOK = ::GetLastError() == ERROR_SUCCESS;
909 }
910 }
911
912 if ( bOK )
913 {
914 UINT flags = EWX_SHUTDOWN | EWX_FORCE;
915 switch ( wFlags )
916 {
917 case wxSHUTDOWN_POWEROFF:
918 flags |= EWX_POWEROFF;
919 break;
920
921 case wxSHUTDOWN_REBOOT:
922 flags |= EWX_REBOOT;
923 break;
924
925 default:
926 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
927 return FALSE;
928 }
929
d8c65cf4 930 bOK = ::ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE | EWX_REBOOT, 0) != 0;
f6ba47d9
VZ
931 }
932
933 return bOK;
934#else // Win16
935 return FALSE;
936#endif // Win32/16
937}
938
b568d04f
VZ
939// ----------------------------------------------------------------------------
940// misc
941// ----------------------------------------------------------------------------
942
943// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
944long wxGetFreeMemory()
2bda0e17 945{
b568d04f
VZ
946#if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
947 MEMORYSTATUS memStatus;
948 memStatus.dwLength = sizeof(MEMORYSTATUS);
949 GlobalMemoryStatus(&memStatus);
950 return memStatus.dwAvailPhys;
951#else
952 return (long)GetFreeSpace(0);
953#endif
2bda0e17
KB
954}
955
c1cb4153
VZ
956unsigned long wxGetProcessId()
957{
958#ifdef __WIN32__
959 return ::GetCurrentProcessId();
960#else
961 return 0;
962#endif
963}
964
2bda0e17 965// Emit a beeeeeep
634903fd 966void wxBell()
2bda0e17 967{
b568d04f 968 ::MessageBeep((UINT)-1); // default sound
2bda0e17
KB
969}
970
bdc72a22 971wxString wxGetOsDescription()
2bda0e17 972{
bdc72a22
VZ
973#ifdef __WIN32__
974 wxString str;
975
976 OSVERSIONINFO info;
977 wxZeroMemory(info);
978
979 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
980 if ( ::GetVersionEx(&info) )
981 {
982 switch ( info.dwPlatformId )
983 {
984 case VER_PLATFORM_WIN32s:
985 str = _("Win32s on Windows 3.1");
986 break;
987
988 case VER_PLATFORM_WIN32_WINDOWS:
989 str.Printf(_("Windows 9%c"),
a46a73a6 990 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
bdc72a22
VZ
991 if ( !wxIsEmpty(info.szCSDVersion) )
992 {
993 str << _T(" (") << info.szCSDVersion << _T(')');
994 }
995 break;
996
997 case VER_PLATFORM_WIN32_NT:
998 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
999 info.dwMajorVersion,
1000 info.dwMinorVersion,
1001 info.dwBuildNumber);
1002 if ( !wxIsEmpty(info.szCSDVersion) )
1003 {
1004 str << _T(", ") << info.szCSDVersion;
1005 }
1006 str << _T(')');
1007 break;
1008 }
1009 }
1010 else
1011 {
1012 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1013 }
1014
1015 return str;
1016#else // Win16
1017 return _("Windows 3.1");
1018#endif // Win32/16
1019}
6f65e337 1020
bdc72a22
VZ
1021int wxGetOsVersion(int *majorVsn, int *minorVsn)
1022{
2432b92d 1023#if defined(__WIN32__) && !defined(__SC__)
6af638ed 1024 static int ver = -1, major = -1, minor = -1;
96c21216 1025
6af638ed 1026 if ( ver == -1 )
bdc72a22 1027 {
6af638ed
VS
1028 OSVERSIONINFO info;
1029 wxZeroMemory(info);
ec5d7799 1030
6af638ed
VS
1031 ver = wxWINDOWS;
1032 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1033 if ( ::GetVersionEx(&info) )
bdc72a22 1034 {
6af638ed
VS
1035 major = info.dwMajorVersion;
1036 minor = info.dwMinorVersion;
bdc72a22 1037
6af638ed
VS
1038 switch ( info.dwPlatformId )
1039 {
1040 case VER_PLATFORM_WIN32s:
1041 ver = wxWIN32S;
1042 break;
bdc72a22 1043
6af638ed
VS
1044 case VER_PLATFORM_WIN32_WINDOWS:
1045 ver = wxWIN95;
1046 break;
1047
1048 case VER_PLATFORM_WIN32_NT:
1049 ver = wxWINDOWS_NT;
1050 break;
1051 }
bdc72a22
VZ
1052 }
1053 }
1054
6af638ed
VS
1055 if (majorVsn && major != -1)
1056 *majorVsn = major;
1057 if (minorVsn && minor != -1)
1058 *minorVsn = minor;
96c21216 1059
6af638ed 1060 return ver;
bdc72a22
VZ
1061#else // Win16
1062 int retValue = wxWINDOWS;
1063 #ifdef __WINDOWS_386__
1064 retValue = wxWIN386;
1065 #else
1066 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
1067 extern HANDLE g_hPenWin;
1068 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
1069 #endif
1070 #endif
1071
1072 if (majorVsn)
1073 *majorVsn = 3;
1074 if (minorVsn)
1075 *minorVsn = 1;
1076
1077 return retValue;
6f65e337 1078#endif
2bda0e17
KB
1079}
1080
b568d04f
VZ
1081// ----------------------------------------------------------------------------
1082// sleep functions
1083// ----------------------------------------------------------------------------
1084
1085#if wxUSE_GUI
1086
1e6feb95
VZ
1087#if wxUSE_TIMER
1088
b568d04f
VZ
1089// Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1090static bool gs_inTimer = FALSE;
1091
1e6feb95 1092class wxSleepTimer : public wxTimer
b568d04f
VZ
1093{
1094public:
1095 virtual void Notify()
1096 {
1097 gs_inTimer = FALSE;
1098 Stop();
1099 }
1100};
1101
1102static wxTimer *wxTheSleepTimer = NULL;
1103
1104void wxUsleep(unsigned long milliseconds)
1105{
1106#ifdef __WIN32__
1107 ::Sleep(milliseconds);
1e6feb95 1108#else // !Win32
b568d04f
VZ
1109 if (gs_inTimer)
1110 return;
d8c65cf4
RD
1111 if (miliseconds <= 0)
1112 return;
b568d04f
VZ
1113
1114 wxTheSleepTimer = new wxSleepTimer;
1115 gs_inTimer = TRUE;
1116 wxTheSleepTimer->Start(milliseconds);
1117 while (gs_inTimer)
1118 {
1119 if (wxTheApp->Pending())
1120 wxTheApp->Dispatch();
1121 }
1122 delete wxTheSleepTimer;
1123 wxTheSleepTimer = NULL;
1e6feb95 1124#endif // Win32/!Win32
b568d04f
VZ
1125}
1126
1127void wxSleep(int nSecs)
1128{
1129 if (gs_inTimer)
1130 return;
d8c65cf4
RD
1131 if (nSecs <= 0)
1132 return;
b568d04f
VZ
1133
1134 wxTheSleepTimer = new wxSleepTimer;
1135 gs_inTimer = TRUE;
1136 wxTheSleepTimer->Start(nSecs*1000);
1137 while (gs_inTimer)
1138 {
1139 if (wxTheApp->Pending())
1140 wxTheApp->Dispatch();
1141 }
1142 delete wxTheSleepTimer;
1143 wxTheSleepTimer = NULL;
1144}
1145
1146// Consume all events until no more left
1147void wxFlushEvents()
1148{
1149// wxYield();
1150}
1151
1e6feb95
VZ
1152#endif // wxUSE_TIMER
1153
b568d04f
VZ
1154#elif defined(__WIN32__) // wxUSE_GUI
1155
1156void wxUsleep(unsigned long milliseconds)
1157{
1158 ::Sleep(milliseconds);
1159}
1160
1161void wxSleep(int nSecs)
1162{
1163 wxUsleep(1000*nSecs);
1164}
1165
1166#endif // wxUSE_GUI/!wxUSE_GUI
373658eb 1167#endif // __WXMICROWIN__
b568d04f
VZ
1168
1169// ----------------------------------------------------------------------------
1170// deprecated (in favour of wxLog) log functions
1171// ----------------------------------------------------------------------------
1172
73deed44 1173#if WXWIN_COMPATIBILITY_2_2
b568d04f
VZ
1174
1175// Output a debug mess., in a system dependent fashion.
04ef50df 1176#ifndef __WXMICROWIN__
b568d04f
VZ
1177void wxDebugMsg(const wxChar *fmt ...)
1178{
1179 va_list ap;
1180 static wxChar buffer[512];
1181
1182 if (!wxTheApp->GetWantDebugOutput())
f6ba47d9 1183 return;
b568d04f
VZ
1184
1185 va_start(ap, fmt);
1186
f6ba47d9
VZ
1187 wvsprintf(buffer,fmt,ap);
1188 OutputDebugString((LPCTSTR)buffer);
b568d04f
VZ
1189
1190 va_end(ap);
1191}
1192
1193// Non-fatal error: pop up message box and (possibly) continue
1194void wxError(const wxString& msg, const wxString& title)
1195{
1196 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
1197 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
1198 MB_ICONSTOP | MB_YESNO) == IDNO)
1199 wxExit();
1200}
1201
1202// Fatal error: pop up message box and abort
1203void wxFatalError(const wxString& msg, const wxString& title)
1204{
1205 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
1206 FatalAppExit(0, (LPCTSTR)wxBuffer);
1207}
04ef50df 1208#endif // __WXMICROWIN__
b568d04f 1209
73deed44
VZ
1210#endif // WXWIN_COMPATIBILITY_2_2
1211
1212#if wxUSE_GUI
1213
b568d04f
VZ
1214// ----------------------------------------------------------------------------
1215// functions to work with .INI files
1216// ----------------------------------------------------------------------------
1217
2bda0e17 1218// Reading and writing resources (eg WIN.INI, .Xdefaults)
47d67540 1219#if wxUSE_RESOURCES
2bda0e17
KB
1220bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
1221{
223d09f6 1222 if (file != wxT(""))
8fb3a512
JS
1223// Don't know what the correct cast should be, but it doesn't
1224// compile in BC++/16-bit without this cast.
1225#if !defined(__WIN32__)
1226 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
1227#else
837e5743 1228 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
8fb3a512 1229#endif
2bda0e17 1230 else
837e5743 1231 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
2bda0e17
KB
1232}
1233
1234bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
1235{
b568d04f
VZ
1236 wxString buf;
1237 buf.Printf(wxT("%.4f"), value);
1238
1239 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
1240}
1241
1242bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
1243{
b568d04f
VZ
1244 wxString buf;
1245 buf.Printf(wxT("%ld"), value);
1246
1247 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
1248}
1249
1250bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
1251{
b568d04f
VZ
1252 wxString buf;
1253 buf.Printf(wxT("%d"), value);
1254
1255 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
1256}
1257
837e5743 1258bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
2bda0e17 1259{
b568d04f
VZ
1260 static const wxChar defunkt[] = wxT("$$default");
1261 if (file != wxT(""))
1262 {
1263 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1264 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
1265 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1266 return FALSE;
1267 }
1268 else
1269 {
1270 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1271 (LPTSTR)wxBuffer, 1000);
1272 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1273 return FALSE;
2bda0e17 1274 }
b568d04f
VZ
1275 if (*value) delete[] (*value);
1276 *value = copystring(wxBuffer);
1277 return TRUE;
1278}
2bda0e17
KB
1279
1280bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
1281{
b568d04f
VZ
1282 wxChar *s = NULL;
1283 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1284 if (succ)
1285 {
1286 *value = (float)wxStrtod(s, NULL);
1287 delete[] s;
1288 return TRUE;
1289 }
1290 else return FALSE;
2bda0e17
KB
1291}
1292
1293bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
1294{
b568d04f
VZ
1295 wxChar *s = NULL;
1296 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1297 if (succ)
1298 {
1299 *value = wxStrtol(s, NULL, 10);
1300 delete[] s;
1301 return TRUE;
1302 }
1303 else return FALSE;
2bda0e17
KB
1304}
1305
1306bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
1307{
b568d04f
VZ
1308 wxChar *s = NULL;
1309 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1310 if (succ)
1311 {
1312 *value = (int)wxStrtol(s, NULL, 10);
1313 delete[] s;
1314 return TRUE;
1315 }
1316 else return FALSE;
2bda0e17 1317}
47d67540 1318#endif // wxUSE_RESOURCES
2bda0e17 1319
634903fd 1320// ---------------------------------------------------------------------------
25889d3c 1321// helper functions for showing a "busy" cursor
634903fd
VZ
1322// ---------------------------------------------------------------------------
1323
bfbd6dc1
VZ
1324static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
1325static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
634903fd 1326static int gs_wxBusyCursorCount = 0;
2bda0e17 1327
bfbd6dc1
VZ
1328extern HCURSOR wxGetCurrentBusyCursor()
1329{
1330 return gs_wxBusyCursor;
1331}
1332
2bda0e17
KB
1333// Set the cursor to the busy cursor for all windows
1334void wxBeginBusyCursor(wxCursor *cursor)
1335{
634903fd
VZ
1336 if ( gs_wxBusyCursorCount++ == 0 )
1337 {
1338 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
04ef50df 1339#ifndef __WXMICROWIN__
634903fd 1340 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
04ef50df 1341#endif
634903fd
VZ
1342 }
1343 //else: nothing to do, already set
2bda0e17
KB
1344}
1345
1346// Restore cursor to normal
634903fd 1347void wxEndBusyCursor()
2bda0e17 1348{
634903fd 1349 wxCHECK_RET( gs_wxBusyCursorCount > 0,
223d09f6 1350 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
b07135ba 1351
634903fd
VZ
1352 if ( --gs_wxBusyCursorCount == 0 )
1353 {
04ef50df 1354#ifndef __WXMICROWIN__
634903fd 1355 ::SetCursor(gs_wxBusyCursorOld);
04ef50df 1356#endif
634903fd
VZ
1357 gs_wxBusyCursorOld = 0;
1358 }
2bda0e17
KB
1359}
1360
1361// TRUE if we're between the above two calls
634903fd 1362bool wxIsBusy()
2bda0e17 1363{
373658eb 1364 return gs_wxBusyCursorCount > 0;
b07135ba 1365}
2bda0e17 1366
2bda0e17
KB
1367// Check whether this window wants to process messages, e.g. Stop button
1368// in long calculations.
1369bool wxCheckForInterrupt(wxWindow *wnd)
1370{
b568d04f
VZ
1371 wxCHECK( wnd, FALSE );
1372
743e0a66 1373 MSG msg;
b568d04f
VZ
1374 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
1375 {
1376 ::TranslateMessage(&msg);
1377 ::DispatchMessage(&msg);
743e0a66 1378 }
634903fd 1379
b568d04f 1380 return TRUE;
2bda0e17
KB
1381}
1382
1383// MSW only: get user-defined resource from the .res file.
1384// Returns NULL or newly-allocated memory, so use delete[] to clean up.
1385
04ef50df 1386#ifndef __WXMICROWIN__
837e5743 1387wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
2bda0e17 1388{
b568d04f
VZ
1389 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
1390 if ( hResource == 0 )
1391 return NULL;
1392
1393 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
1394 if ( hData == 0 )
1395 return NULL;
2bda0e17 1396
b568d04f
VZ
1397 wxChar *theText = (wxChar *)::LockResource(hData);
1398 if ( !theText )
1399 return NULL;
b07135ba 1400
8caa4ed1
JS
1401 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1402 // so we need to find the length of the resource.
1403 int len = ::SizeofResource(wxGetInstance(), hResource);
1404 wxChar *s = new wxChar[len+1];
1405 wxStrncpy(s,theText,len);
1406 s[len]=0;
1407
1408 // wxChar *s = copystring(theText);
2bda0e17 1409
b568d04f 1410 // Obsolete in WIN32
2bda0e17 1411#ifndef __WIN32__
b568d04f 1412 UnlockResource(hData);
2bda0e17
KB
1413#endif
1414
b568d04f
VZ
1415 // No need??
1416 // GlobalFree(hData);
2bda0e17 1417
b568d04f 1418 return s;
2bda0e17 1419}
373658eb 1420#endif // __WXMICROWIN__
b568d04f
VZ
1421
1422// ----------------------------------------------------------------------------
1423// get display info
1424// ----------------------------------------------------------------------------
2bda0e17 1425
d3db92b2
JS
1426// See also the wxGetMousePosition in window.cpp
1427// Deprecated: use wxPoint wxGetMousePosition() instead
2bda0e17
KB
1428void wxGetMousePosition( int* x, int* y )
1429{
b568d04f
VZ
1430 POINT pt;
1431 GetCursorPos( & pt );
1432 if ( x ) *x = pt.x;
1433 if ( y ) *y = pt.y;
2bda0e17
KB
1434};
1435
1436// Return TRUE if we have a colour display
634903fd 1437bool wxColourDisplay()
2bda0e17 1438{
04ef50df
JS
1439#ifdef __WXMICROWIN__
1440 // MICROWIN_TODO
1441 return TRUE;
1442#else
807a903e
VZ
1443 // this function is called from wxDC ctor so it is called a *lot* of times
1444 // hence we optimize it a bit but doign the check only once
1445 //
1446 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1447 // can call us
1448 static int s_isColour = -1;
1449
1450 if ( s_isColour == -1 )
1451 {
1452 ScreenHDC dc;
1453 int noCols = ::GetDeviceCaps(dc, NUMCOLORS);
1454
1455 s_isColour = (noCols == -1) || (noCols > 2);
1456 }
b568d04f 1457
807a903e 1458 return s_isColour != 0;
04ef50df 1459#endif
2bda0e17
KB
1460}
1461
1462// Returns depth of screen
634903fd 1463int wxDisplayDepth()
2bda0e17 1464{
b568d04f
VZ
1465 ScreenHDC dc;
1466 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
2bda0e17
KB
1467}
1468
1469// Get size of display
1470void wxDisplaySize(int *width, int *height)
1471{
04ef50df 1472#ifdef __WXMICROWIN__
54800df8
JS
1473 RECT rect;
1474 HWND hWnd = GetDesktopWindow();
1475 ::GetWindowRect(hWnd, & rect);
1476
373658eb
VZ
1477 if ( width )
1478 *width = rect.right - rect.left;
1479 if ( height )
1480 *height = rect.bottom - rect.top;
1481#else // !__WXMICROWIN__
b568d04f 1482 ScreenHDC dc;
3f4a0c5b 1483
373658eb
VZ
1484 if ( width )
1485 *width = ::GetDeviceCaps(dc, HORZRES);
1486 if ( height )
1487 *height = ::GetDeviceCaps(dc, VERTRES);
1488#endif // __WXMICROWIN__/!__WXMICROWIN__
7f555861
JS
1489}
1490
904a68b6
RL
1491void wxDisplaySizeMM(int *width, int *height)
1492{
04ef50df
JS
1493#ifdef __WXMICROWIN__
1494 // MICROWIN_TODO
373658eb
VZ
1495 if ( width )
1496 *width = 0;
1497 if ( height )
1498 *height = 0;
04ef50df 1499#else
904a68b6
RL
1500 ScreenHDC dc;
1501
373658eb
VZ
1502 if ( width )
1503 *width = ::GetDeviceCaps(dc, HORZSIZE);
1504 if ( height )
1505 *height = ::GetDeviceCaps(dc, VERTSIZE);
04ef50df 1506#endif
904a68b6
RL
1507}
1508
ec5d7799
RD
1509void wxClientDisplayRect(int *x, int *y, int *width, int *height)
1510{
04ef50df 1511#if defined(__WIN16__) || defined(__WXMICROWIN__)
788722ac
JS
1512 *x = 0; *y = 0;
1513 wxDisplaySize(width, height);
1514#else
ec5d7799
RD
1515 // Determine the desktop dimensions minus the taskbar and any other
1516 // special decorations...
1517 RECT r;
788722ac 1518
ec5d7799
RD
1519 SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
1520 if (x) *x = r.left;
1521 if (y) *y = r.top;
1522 if (width) *width = r.right - r.left;
1523 if (height) *height = r.bottom - r.top;
788722ac 1524#endif
ec5d7799
RD
1525}
1526
cc2b7472
VZ
1527// ---------------------------------------------------------------------------
1528// window information functions
1529// ---------------------------------------------------------------------------
1530
1c4a764c
VZ
1531wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1532{
1533 wxString str;
5acc0d5f
VZ
1534
1535 if ( hWnd )
1536 {
1537 int len = GetWindowTextLength((HWND)hWnd) + 1;
1538 ::GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1539 str.UngetWriteBuf();
1540 }
1c4a764c
VZ
1541
1542 return str;
1543}
1544
cc2b7472
VZ
1545wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1546{
1547 wxString str;
1548
5acc0d5f
VZ
1549 // MICROWIN_TODO
1550#ifndef __WXMICROWIN__
1551 if ( hWnd )
cc2b7472 1552 {
5acc0d5f 1553 int len = 256; // some starting value
cc2b7472 1554
5acc0d5f 1555 for ( ;; )
cc2b7472 1556 {
5acc0d5f
VZ
1557 int count = ::GetClassName((HWND)hWnd, str.GetWriteBuf(len), len);
1558
1559 str.UngetWriteBuf();
1560 if ( count == len )
1561 {
1562 // the class name might have been truncated, retry with larger
1563 // buffer
1564 len *= 2;
1565 }
1566 else
1567 {
1568 break;
1569 }
cc2b7472
VZ
1570 }
1571 }
5acc0d5f 1572#endif // !__WXMICROWIN__
cc2b7472
VZ
1573
1574 return str;
1575}
1576
42e69d6b 1577WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
cc2b7472
VZ
1578{
1579#ifndef __WIN32__
33ac7e6f 1580 return (WXWORD)GetWindowWord((HWND)hWnd, GWW_ID);
cc2b7472 1581#else // Win32
33ac7e6f 1582 return (WXWORD)GetWindowLong((HWND)hWnd, GWL_ID);
cc2b7472
VZ
1583#endif // Win16/32
1584}
1585
b0c89ddf
JS
1586// ----------------------------------------------------------------------------
1587// Metafile helpers
1588// ----------------------------------------------------------------------------
1589
1590extern void PixelToHIMETRIC(LONG *x, LONG *y)
1591{
1592 ScreenHDC hdcRef;
1593
1594 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1595 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1596 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1597 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1598
1599 *x *= (iWidthMM * 100);
1600 *x /= iWidthPels;
1601 *y *= (iHeightMM * 100);
1602 *y /= iHeightPels;
1603}
1604
1605extern void HIMETRICToPixel(LONG *x, LONG *y)
1606{
1607 ScreenHDC hdcRef;
1608
1609 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1610 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1611 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1612 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1613
1614 *x *= iWidthPels;
1615 *x /= (iWidthMM * 100);
1616 *y *= iHeightPels;
1617 *y /= (iHeightMM * 100);
1618}
1619
1620#endif // wxUSE_GUI
1621
373658eb
VZ
1622#ifdef __WXMICROWIN__
1623int wxGetOsVersion(int *majorVsn, int *minorVsn)
7f555861 1624{
373658eb
VZ
1625 // MICROWIN_TODO
1626 if (majorVsn) *majorVsn = 0;
1627 if (minorVsn) *minorVsn = 0;
1628 return wxUNIX;
1629}
1630#endif // __WXMICROWIN__
7f555861 1631
373658eb
VZ
1632// ----------------------------------------------------------------------------
1633// Win32 codepage conversion functions
1634// ----------------------------------------------------------------------------
7f555861 1635
373658eb 1636#if defined(__WIN32__) && !defined(__WXMICROWIN__)
7f555861 1637
1f86850d
VZ
1638// wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1639#if wxUSE_GUI && !defined(__WXUNIVERSAL__)
c030b70f 1640
373658eb 1641#include "wx/fontmap.h"
c030b70f 1642
373658eb
VZ
1643// VZ: the new version of wxCharsetToCodepage() is more politically correct
1644// and should work on other Windows versions as well but the old version is
1645// still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
c030b70f 1646
373658eb 1647extern long wxEncodingToCodepage(wxFontEncoding encoding)
c030b70f 1648{
373658eb
VZ
1649 // translate encoding into the Windows CHARSET
1650 wxNativeEncodingInfo natveEncInfo;
1651 if ( !wxGetNativeFontEncoding(encoding, &natveEncInfo) )
1652 return -1;
1653
1654 // translate CHARSET to code page
1655 CHARSETINFO csetInfo;
1656 if ( !::TranslateCharsetInfo((DWORD *)(DWORD)natveEncInfo.charset,
1657 &csetInfo,
1658 TCI_SRCCHARSET) )
1659 {
1660 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1661
1662 return -1;
1663 }
1664
1665 return csetInfo.ciACP;
c030b70f 1666}
373658eb
VZ
1667
1668#if wxUSE_FONTMAP
1669
1670extern long wxCharsetToCodepage(const wxChar *name)
c030b70f 1671{
373658eb
VZ
1672 // first get the font encoding for this charset
1673 if ( !name )
1674 return -1;
1675
142b3bc2 1676 wxFontEncoding enc = wxFontMapper::Get()->CharsetToEncoding(name, FALSE);
373658eb
VZ
1677 if ( enc == wxFONTENCODING_SYSTEM )
1678 return -1;
1679
1680 // the use the helper function
1681 return wxEncodingToCodepage(enc);
c030b70f 1682}
c030b70f 1683
373658eb
VZ
1684#endif // wxUSE_FONTMAP
1685
1686#endif // wxUSE_GUI
1687
1688// include old wxCharsetToCodepage() by OK if needed
1689#if !wxUSE_GUI || !wxUSE_FONTMAP
1690
1691#include "wx/msw/registry.h"
1692
1693// this should work if Internet Exploiter is installed
1694extern long wxCharsetToCodepage(const wxChar *name)
04ef50df 1695{
373658eb
VZ
1696 if (!name)
1697 return GetACP();
1698
1699 long CP=-1;
1700
1701 wxString cn(name);
1702 do {
1703 wxString path(wxT("MIME\\Database\\Charset\\"));
1704 path += cn;
1705 wxRegKey key(wxRegKey::HKCR, path);
1706
1707 if (!key.Exists()) break;
1708
1709 // two cases: either there's an AliasForCharset string,
1710 // or there are Codepage and InternetEncoding dwords.
1711 // The InternetEncoding gives us the actual encoding,
1712 // the Codepage just says which Windows character set to
1713 // use when displaying the data.
1714 if (key.HasValue(wxT("InternetEncoding")) &&
1715 key.QueryValue(wxT("InternetEncoding"), &CP)) break;
1716
1717 // no encoding, see if it's an alias
1718 if (!key.HasValue(wxT("AliasForCharset")) ||
1719 !key.QueryValue(wxT("AliasForCharset"), cn)) break;
1720 } while (1);
1721
1722 return CP;
04ef50df 1723}
373658eb
VZ
1724
1725#endif // !wxUSE_GUI || !wxUSE_FONTMAP
1726
1727#endif // Win32
c030b70f 1728