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