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