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