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