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