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