]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utils.cpp
Added first stab at GetBoundingRect for generic tree control
[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"
34 #include "wx/cursor.h"
1f0500b3
VZ
35 #include "wx/intl.h"
36 #include "wx/log.h"
743e0a66 37#endif //WX_PRECOMP
2bda0e17 38
26993c4f
GRG
39// In some mingws there is a missing extern "C" int the winsock header,
40// so we put it here just to be safe. Note that this must appear _before_
41// #include "wx/msw/private.h" which itself includes <windows.h>, as this
42// one in turn includes <winsock.h> unless we define WIN32_LEAN_AND_MEAN.
43//
f8f3e763 44#if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
26993c4f
GRG
45extern "C" {
46 #include <winsock.h> // we use socket functions in wxGetFullHostName()
47}
48#endif
49
b568d04f
VZ
50#include "wx/msw/private.h" // includes <windows.h>
51
2bda0e17
KB
52#include "wx/timer.h"
53
54#include <ctype.h>
55
5ea105e0 56#if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
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
5ea105e0 85#if defined(__WIN32__) && !defined(__WXWINE__)
a4f96412 86 #include <io.h>
2bda0e17 87
a4f96412
VZ
88 #ifndef __GNUWIN32__
89 #include <shellapi.h>
90 #endif
2bda0e17
KB
91#endif
92
93#include <stdio.h>
94#include <stdlib.h>
95#include <string.h>
96#ifndef __WATCOMC__
3f4a0c5b
VZ
97 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
98 #include <errno.h>
99 #endif
2bda0e17
KB
100#endif
101#include <stdarg.h>
102
c030b70f 103//// BEGIN for console support: VC++ only
631f1bfe 104#ifdef __VISUALC__
c030b70f 105
3f4a0c5b 106#include "wx/msw/msvcrt.h"
c030b70f 107
3f4a0c5b 108#include <fcntl.h>
c030b70f 109
3f4a0c5b 110#include "wx/ioswrap.h"
c030b70f
JS
111
112#if wxUSE_IOSTREAMH
113// N.B. BC++ doesn't have istream.h, ostream.h
c030b70f
JS
114# include <io.h>
115# include <fstream.h>
c030b70f 116#else
c030b70f 117# include <fstream>
c030b70f
JS
118#endif
119
120/* Need to undef new if including crtdbg.h */
121# ifdef new
122# undef new
123# endif
124
1e6d9499 125#ifndef __WIN16__
c030b70f 126# include <crtdbg.h>
1e6d9499 127#endif
c030b70f
JS
128
129# if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
f6bcfd97 130# define new new(__TFILE__,__LINE__)
c030b70f
JS
131# endif
132
631f1bfe
JS
133#endif
134 // __VISUALC__
c030b70f
JS
135/// END for console support
136
b568d04f
VZ
137// ----------------------------------------------------------------------------
138// constants
139// ----------------------------------------------------------------------------
140
2bda0e17 141// In the WIN.INI file
223d09f6 142static const wxChar WX_SECTION[] = wxT("wxWindows");
b568d04f
VZ
143static const wxChar eUSERNAME[] = wxT("UserName");
144
145// these are only used under Win16
146#ifndef __WIN32__
223d09f6
KB
147static const wxChar eHOSTNAME[] = wxT("HostName");
148static const wxChar eUSERID[] = wxT("UserId");
b568d04f
VZ
149#endif // !Win32
150
151// ============================================================================
152// implementation
153// ============================================================================
2bda0e17 154
b568d04f
VZ
155// ----------------------------------------------------------------------------
156// get host name and related
157// ----------------------------------------------------------------------------
2bda0e17 158
1f0500b3 159// Get hostname only (without domain name)
837e5743 160bool wxGetHostName(wxChar *buf, int maxSize)
2bda0e17 161{
57c208c5 162#if defined(__WIN32__) && !defined(__TWIN32__)
b568d04f
VZ
163 DWORD nSize = maxSize;
164 if ( !::GetComputerName(buf, &nSize) )
165 {
f6bcfd97 166 wxLogLastError(wxT("GetComputerName"));
b568d04f
VZ
167
168 return FALSE;
169 }
170
171 return TRUE;
2bda0e17 172#else
b568d04f
VZ
173 wxChar *sysname;
174 const wxChar *default_host = wxT("noname");
175
176 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
177 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
178 } else
179 wxStrncpy(buf, sysname, maxSize - 1);
180 buf[maxSize] = wxT('\0');
181 return *buf ? TRUE : FALSE;
2bda0e17
KB
182#endif
183}
184
1f0500b3 185// get full hostname (with domain name if possible)
b568d04f
VZ
186bool wxGetFullHostName(wxChar *buf, int maxSize)
187{
f8f3e763 188#if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
1f0500b3
VZ
189 // TODO should use GetComputerNameEx() when available
190 WSADATA wsa;
191 if ( WSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
192 {
193 wxString host;
194 char bufA[256];
195 if ( gethostname(bufA, WXSIZEOF(bufA)) == 0 )
196 {
197 // gethostname() won't usually include the DNS domain name, for
198 // this we need to work a bit more
199 if ( !strchr(bufA, '.') )
200 {
201 struct hostent *pHostEnt = gethostbyname(bufA);
202
203 if ( pHostEnt )
204 {
205 // Windows will use DNS internally now
206 pHostEnt = gethostbyaddr(pHostEnt->h_addr, 4, PF_INET);
207 }
208
209 if ( pHostEnt )
210 {
211 host = pHostEnt->h_name;
212 }
213 }
214 }
215
216 WSACleanup();
217
218 if ( !!host )
219 {
220 wxStrncpy(buf, host, maxSize);
221
222 return TRUE;
223 }
224 }
225#endif // Win32
226
b568d04f
VZ
227 return wxGetHostName(buf, maxSize);
228}
229
2bda0e17 230// Get user ID e.g. jacs
837e5743 231bool wxGetUserId(wxChar *buf, int maxSize)
2bda0e17 232{
57c208c5 233#if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__)
0a144271
VZ
234 DWORD nSize = maxSize;
235 if ( ::GetUserName(buf, &nSize) == 0 )
236 {
a4f96412 237 // actually, it does happen on Win9x if the user didn't log on
223d09f6 238 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
a4f96412
VZ
239 if ( res == 0 )
240 {
241 // not found
242 return FALSE;
243 }
0a144271
VZ
244 }
245
246 return TRUE;
0a144271 247#else // Win16 or Win32s
b568d04f
VZ
248 wxChar *user;
249 const wxChar *default_id = wxT("anonymous");
2bda0e17 250
b568d04f
VZ
251 // Can't assume we have NIS (PC-NFS) or some other ID daemon
252 // So we ...
253 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
254 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
255 {
256 // Use wxWindows configuration data (comming soon)
257 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
258 }
259 else
260 {
261 wxStrncpy(buf, user, maxSize - 1);
262 }
a4f96412 263
b568d04f 264 return *buf ? TRUE : FALSE;
2bda0e17
KB
265#endif
266}
267
268// Get user name e.g. Julian Smart
837e5743 269bool wxGetUserName(wxChar *buf, int maxSize)
2bda0e17 270{
0a144271 271#if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
b568d04f
VZ
272 extern HANDLE g_hPenWin; // PenWindows Running?
273 if (g_hPenWin)
274 {
275 // PenWindows Does have a user concept!
276 // Get the current owner of the recognizer
277 GetPrivateProfileString("Current", "User", default_name, wxBuffer, maxSize - 1, "PENWIN.INI");
278 strncpy(buf, wxBuffer, maxSize - 1);
279 }
280 else
2bda0e17 281#endif
b568d04f 282 {
a4f96412 283#ifdef USE_NET_API
b568d04f
VZ
284 CHAR szUserName[256];
285 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
286 return FALSE;
a4f96412 287
b568d04f
VZ
288 // TODO how to get the domain name?
289 CHAR *szDomain = "";
a4f96412 290
b568d04f
VZ
291 // the code is based on the MSDN example (also see KB article Q119670)
292 WCHAR wszUserName[256]; // Unicode user name
293 WCHAR wszDomain[256];
294 LPBYTE ComputerName;
a4f96412 295
b568d04f 296 USER_INFO_2 *ui2; // User structure
a4f96412 297
b568d04f
VZ
298 // Convert ANSI user name and domain to Unicode
299 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
300 wszUserName, WXSIZEOF(wszUserName) );
301 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
302 wszDomain, WXSIZEOF(wszDomain) );
a4f96412 303
b568d04f
VZ
304 // Get the computer name of a DC for the domain.
305 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
306 {
307 wxLogError(wxT("Can not find domain controller"));
a4f96412 308
b568d04f
VZ
309 goto error;
310 }
a4f96412 311
b568d04f
VZ
312 // Look up the user on the DC
313 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
314 (LPWSTR)&wszUserName,
315 2, // level - we want USER_INFO_2
316 (LPBYTE *) &ui2 );
317 switch ( status )
318 {
319 case NERR_Success:
320 // ok
321 break;
a4f96412 322
b568d04f
VZ
323 case NERR_InvalidComputer:
324 wxLogError(wxT("Invalid domain controller name."));
a4f96412 325
b568d04f 326 goto error;
a4f96412 327
b568d04f
VZ
328 case NERR_UserNotFound:
329 wxLogError(wxT("Invalid user name '%s'."), szUserName);
a4f96412 330
b568d04f 331 goto error;
a4f96412 332
b568d04f
VZ
333 default:
334 wxLogSysError(wxT("Can't get information about user"));
a4f96412 335
b568d04f
VZ
336 goto error;
337 }
a4f96412 338
b568d04f
VZ
339 // Convert the Unicode full name to ANSI
340 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
341 buf, maxSize, NULL, NULL );
a4f96412 342
b568d04f 343 return TRUE;
a4f96412
VZ
344
345error:
b568d04f 346 wxLogError(wxT("Couldn't look up full user name."));
a4f96412 347
b568d04f 348 return FALSE;
a4f96412 349#else // !USE_NET_API
b568d04f
VZ
350 // Could use NIS, MS-Mail or other site specific programs
351 // Use wxWindows configuration data
352 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxT(""), buf, maxSize - 1) != 0;
353 if ( !ok )
354 {
355 ok = wxGetUserId(buf, maxSize);
356 }
0a144271 357
b568d04f
VZ
358 if ( !ok )
359 {
360 wxStrncpy(buf, wxT("Unknown User"), maxSize);
361 }
a4f96412 362#endif // Win32/16
b568d04f 363 }
0a144271 364
b568d04f 365 return TRUE;
2bda0e17
KB
366}
367
b568d04f 368const wxChar* wxGetHomeDir(wxString *pstr)
2bda0e17 369{
b568d04f 370 wxString& strDir = *pstr;
2bda0e17 371
b568d04f
VZ
372 #if defined(__UNIX__) && !defined(__TWIN32__)
373 const wxChar *szHome = wxGetenv("HOME");
374 if ( szHome == NULL ) {
375 // we're homeless...
376 wxLogWarning(_("can't find user's HOME, using current directory."));
377 strDir = wxT(".");
378 }
379 else
380 strDir = szHome;
2bda0e17 381
b568d04f
VZ
382 // add a trailing slash if needed
383 if ( strDir.Last() != wxT('/') )
384 strDir << wxT('/');
385 #else // Windows
386 #ifdef __WIN32__
387 const wxChar *szHome = wxGetenv(wxT("HOMEDRIVE"));
388 if ( szHome != NULL )
389 strDir << szHome;
390 szHome = wxGetenv(wxT("HOMEPATH"));
391 if ( szHome != NULL ) {
392 strDir << szHome;
2bda0e17 393
b568d04f
VZ
394 // the idea is that under NT these variables have default values
395 // of "%systemdrive%:" and "\\". As we don't want to create our
396 // config files in the root directory of the system drive, we will
397 // create it in our program's dir. However, if the user took care
398 // to set HOMEPATH to something other than "\\", we suppose that he
399 // knows what he is doing and use the supplied value.
400 if ( wxStrcmp(szHome, wxT("\\")) != 0 )
401 return strDir.c_str();
402 }
2bda0e17 403
b568d04f
VZ
404 #else // Win16
405 // Win16 has no idea about home, so use the working directory instead
406 #endif // WIN16/32
2bda0e17 407
b568d04f
VZ
408 // 260 was taken from windef.h
409 #ifndef MAX_PATH
410 #define MAX_PATH 260
411 #endif
2bda0e17 412
b568d04f
VZ
413 wxString strPath;
414 ::GetModuleFileName(::GetModuleHandle(NULL),
415 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
416 strPath.UngetWriteBuf();
2bda0e17 417
b568d04f
VZ
418 // extract the dir name
419 wxSplitPath(strPath, &strDir, NULL, NULL);
58a33cb4 420
b568d04f
VZ
421 #endif // UNIX/Win
422
423 return strDir.c_str();
afb74891
VZ
424}
425
b568d04f 426wxChar *wxGetUserHome(const wxString& user)
2bda0e17 427{
b568d04f
VZ
428 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
429 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
430 // static buffer and sometimes I don't even know what.
431 static wxString s_home;
2bda0e17 432
b568d04f 433 return (wxChar *)wxGetHomeDir(&s_home);
2bda0e17
KB
434}
435
b568d04f 436bool wxDirExists(const wxString& dir)
2bda0e17 437{
b568d04f
VZ
438#if defined(__WIN32__)
439 WIN32_FIND_DATA fileInfo;
440#else // Win16
441 #ifdef __BORLANDC__
442 struct ffblk fileInfo;
443 #else
444 struct find_t fileInfo;
445 #endif
446#endif // Win32/16
2bda0e17 447
b568d04f
VZ
448#if defined(__WIN32__)
449 HANDLE h = ::FindFirstFile(dir, &fileInfo);
2bda0e17 450
b568d04f
VZ
451 if ( h == INVALID_HANDLE_VALUE )
452 {
f6bcfd97 453 wxLogLastError(wxT("FindFirstFile"));
2bda0e17 454
b568d04f
VZ
455 return FALSE;
456 }
2bda0e17 457
b568d04f
VZ
458 ::FindClose(h);
459
460 return (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
461#else // Win16
462 // In Borland findfirst has a different argument
463 // ordering from _dos_findfirst. But _dos_findfirst
464 // _should_ be ok in both MS and Borland... why not?
465 #ifdef __BORLANDC__
466 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
467 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
468 #else
469 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
470 ((fileInfo.attrib & _A_SUBDIR) != 0);
471 #endif
472#endif // Win32/16
473}
2bda0e17 474
b568d04f
VZ
475// ----------------------------------------------------------------------------
476// process management
477// ----------------------------------------------------------------------------
478
479int wxKill(long pid, int sig)
480{
481 // TODO use SendMessage(WM_QUIT) and TerminateProcess() if needed
482
483 return 0;
2bda0e17
KB
484}
485
b568d04f
VZ
486// Execute a program in an Interactive Shell
487bool wxShell(const wxString& command)
2bda0e17 488{
b568d04f
VZ
489 wxChar *shell = wxGetenv(wxT("COMSPEC"));
490 if ( !shell )
491 shell = wxT("\\COMMAND.COM");
492
493 wxString cmd;
494 if ( !command )
495 {
496 // just the shell
497 cmd = shell;
498 }
499 else
500 {
501 // pass the command to execute to the command processor
502 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
503 }
504
0d7ea902 505 return wxExecute(cmd, TRUE /* sync */) != 0;
2bda0e17
KB
506}
507
b568d04f
VZ
508// ----------------------------------------------------------------------------
509// misc
510// ----------------------------------------------------------------------------
511
512// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
513long wxGetFreeMemory()
2bda0e17 514{
b568d04f
VZ
515#if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
516 MEMORYSTATUS memStatus;
517 memStatus.dwLength = sizeof(MEMORYSTATUS);
518 GlobalMemoryStatus(&memStatus);
519 return memStatus.dwAvailPhys;
520#else
521 return (long)GetFreeSpace(0);
522#endif
2bda0e17
KB
523}
524
525// Emit a beeeeeep
634903fd 526void wxBell()
2bda0e17 527{
b568d04f 528 ::MessageBeep((UINT)-1); // default sound
2bda0e17
KB
529}
530
bdc72a22 531wxString wxGetOsDescription()
2bda0e17 532{
bdc72a22
VZ
533#ifdef __WIN32__
534 wxString str;
535
536 OSVERSIONINFO info;
537 wxZeroMemory(info);
538
539 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
540 if ( ::GetVersionEx(&info) )
541 {
542 switch ( info.dwPlatformId )
543 {
544 case VER_PLATFORM_WIN32s:
545 str = _("Win32s on Windows 3.1");
546 break;
547
548 case VER_PLATFORM_WIN32_WINDOWS:
549 str.Printf(_("Windows 9%c"),
550 info.dwMinorVersion == 0 ? _T('5') : _T('9'));
551 if ( !wxIsEmpty(info.szCSDVersion) )
552 {
553 str << _T(" (") << info.szCSDVersion << _T(')');
554 }
555 break;
556
557 case VER_PLATFORM_WIN32_NT:
558 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
559 info.dwMajorVersion,
560 info.dwMinorVersion,
561 info.dwBuildNumber);
562 if ( !wxIsEmpty(info.szCSDVersion) )
563 {
564 str << _T(", ") << info.szCSDVersion;
565 }
566 str << _T(')');
567 break;
568 }
569 }
570 else
571 {
572 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
573 }
574
575 return str;
576#else // Win16
577 return _("Windows 3.1");
578#endif // Win32/16
579}
6f65e337 580
bdc72a22
VZ
581int wxGetOsVersion(int *majorVsn, int *minorVsn)
582{
2432b92d 583#if defined(__WIN32__) && !defined(__SC__)
bdc72a22
VZ
584 OSVERSIONINFO info;
585 wxZeroMemory(info);
586
587 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
588 if ( ::GetVersionEx(&info) )
589 {
590 if (majorVsn)
591 *majorVsn = info.dwMajorVersion;
592 if (minorVsn)
593 *minorVsn = info.dwMinorVersion;
90cfeaab 594
bdc72a22
VZ
595 switch ( info.dwPlatformId )
596 {
597 case VER_PLATFORM_WIN32s:
598 return wxWIN32S;
599
600 case VER_PLATFORM_WIN32_WINDOWS:
601 return wxWIN95;
602
603 case VER_PLATFORM_WIN32_NT:
604 return wxWINDOWS_NT;
605 }
606 }
607
608 return wxWINDOWS; // error if we get here, return generic value
609#else // Win16
610 int retValue = wxWINDOWS;
611 #ifdef __WINDOWS_386__
612 retValue = wxWIN386;
613 #else
614 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
615 extern HANDLE g_hPenWin;
616 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
617 #endif
618 #endif
619
620 if (majorVsn)
621 *majorVsn = 3;
622 if (minorVsn)
623 *minorVsn = 1;
624
625 return retValue;
6f65e337 626#endif
2bda0e17
KB
627}
628
b568d04f
VZ
629// ----------------------------------------------------------------------------
630// sleep functions
631// ----------------------------------------------------------------------------
632
633#if wxUSE_GUI
634
635// Sleep for nSecs seconds. Attempt a Windows implementation using timers.
636static bool gs_inTimer = FALSE;
637
638class wxSleepTimer: public wxTimer
639{
640public:
641 virtual void Notify()
642 {
643 gs_inTimer = FALSE;
644 Stop();
645 }
646};
647
648static wxTimer *wxTheSleepTimer = NULL;
649
650void wxUsleep(unsigned long milliseconds)
651{
652#ifdef __WIN32__
653 ::Sleep(milliseconds);
654#else
655 if (gs_inTimer)
656 return;
657
658 wxTheSleepTimer = new wxSleepTimer;
659 gs_inTimer = TRUE;
660 wxTheSleepTimer->Start(milliseconds);
661 while (gs_inTimer)
662 {
663 if (wxTheApp->Pending())
664 wxTheApp->Dispatch();
665 }
666 delete wxTheSleepTimer;
667 wxTheSleepTimer = NULL;
668#endif
669}
670
671void wxSleep(int nSecs)
672{
673 if (gs_inTimer)
674 return;
675
676 wxTheSleepTimer = new wxSleepTimer;
677 gs_inTimer = TRUE;
678 wxTheSleepTimer->Start(nSecs*1000);
679 while (gs_inTimer)
680 {
681 if (wxTheApp->Pending())
682 wxTheApp->Dispatch();
683 }
684 delete wxTheSleepTimer;
685 wxTheSleepTimer = NULL;
686}
687
688// Consume all events until no more left
689void wxFlushEvents()
690{
691// wxYield();
692}
693
694#elif defined(__WIN32__) // wxUSE_GUI
695
696void wxUsleep(unsigned long milliseconds)
697{
698 ::Sleep(milliseconds);
699}
700
701void wxSleep(int nSecs)
702{
703 wxUsleep(1000*nSecs);
704}
705
706#endif // wxUSE_GUI/!wxUSE_GUI
707
708// ----------------------------------------------------------------------------
709// deprecated (in favour of wxLog) log functions
710// ----------------------------------------------------------------------------
711
712#if wxUSE_GUI
713
714// Output a debug mess., in a system dependent fashion.
715void wxDebugMsg(const wxChar *fmt ...)
716{
717 va_list ap;
718 static wxChar buffer[512];
719
720 if (!wxTheApp->GetWantDebugOutput())
721 return ;
722
723 va_start(ap, fmt);
724
725 wvsprintf(buffer,fmt,ap) ;
726 OutputDebugString((LPCTSTR)buffer) ;
727
728 va_end(ap);
729}
730
731// Non-fatal error: pop up message box and (possibly) continue
732void wxError(const wxString& msg, const wxString& title)
733{
734 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
735 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
736 MB_ICONSTOP | MB_YESNO) == IDNO)
737 wxExit();
738}
739
740// Fatal error: pop up message box and abort
741void wxFatalError(const wxString& msg, const wxString& title)
742{
743 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
744 FatalAppExit(0, (LPCTSTR)wxBuffer);
745}
746
747// ----------------------------------------------------------------------------
748// functions to work with .INI files
749// ----------------------------------------------------------------------------
750
2bda0e17 751// Reading and writing resources (eg WIN.INI, .Xdefaults)
47d67540 752#if wxUSE_RESOURCES
2bda0e17
KB
753bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
754{
223d09f6 755 if (file != wxT(""))
8fb3a512
JS
756// Don't know what the correct cast should be, but it doesn't
757// compile in BC++/16-bit without this cast.
758#if !defined(__WIN32__)
759 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
760#else
837e5743 761 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
8fb3a512 762#endif
2bda0e17 763 else
837e5743 764 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
2bda0e17
KB
765}
766
767bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
768{
b568d04f
VZ
769 wxString buf;
770 buf.Printf(wxT("%.4f"), value);
771
772 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
773}
774
775bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
776{
b568d04f
VZ
777 wxString buf;
778 buf.Printf(wxT("%ld"), value);
779
780 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
781}
782
783bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
784{
b568d04f
VZ
785 wxString buf;
786 buf.Printf(wxT("%d"), value);
787
788 return wxWriteResource(section, entry, buf, file);
2bda0e17
KB
789}
790
837e5743 791bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
2bda0e17 792{
b568d04f
VZ
793 static const wxChar defunkt[] = wxT("$$default");
794 if (file != wxT(""))
795 {
796 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
797 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
798 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
799 return FALSE;
800 }
801 else
802 {
803 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
804 (LPTSTR)wxBuffer, 1000);
805 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
806 return FALSE;
2bda0e17 807 }
b568d04f
VZ
808 if (*value) delete[] (*value);
809 *value = copystring(wxBuffer);
810 return TRUE;
811}
2bda0e17
KB
812
813bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
814{
b568d04f
VZ
815 wxChar *s = NULL;
816 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
817 if (succ)
818 {
819 *value = (float)wxStrtod(s, NULL);
820 delete[] s;
821 return TRUE;
822 }
823 else return FALSE;
2bda0e17
KB
824}
825
826bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
827{
b568d04f
VZ
828 wxChar *s = NULL;
829 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
830 if (succ)
831 {
832 *value = wxStrtol(s, NULL, 10);
833 delete[] s;
834 return TRUE;
835 }
836 else return FALSE;
2bda0e17
KB
837}
838
839bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
840{
b568d04f
VZ
841 wxChar *s = NULL;
842 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
843 if (succ)
844 {
845 *value = (int)wxStrtol(s, NULL, 10);
846 delete[] s;
847 return TRUE;
848 }
849 else return FALSE;
2bda0e17 850}
47d67540 851#endif // wxUSE_RESOURCES
2bda0e17 852
634903fd 853// ---------------------------------------------------------------------------
25889d3c 854// helper functions for showing a "busy" cursor
634903fd
VZ
855// ---------------------------------------------------------------------------
856
bfbd6dc1
VZ
857static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
858static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
634903fd 859static int gs_wxBusyCursorCount = 0;
2bda0e17 860
bfbd6dc1
VZ
861extern HCURSOR wxGetCurrentBusyCursor()
862{
863 return gs_wxBusyCursor;
864}
865
2bda0e17
KB
866// Set the cursor to the busy cursor for all windows
867void wxBeginBusyCursor(wxCursor *cursor)
868{
634903fd
VZ
869 if ( gs_wxBusyCursorCount++ == 0 )
870 {
871 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
872 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
873 }
874 //else: nothing to do, already set
2bda0e17
KB
875}
876
877// Restore cursor to normal
634903fd 878void wxEndBusyCursor()
2bda0e17 879{
634903fd 880 wxCHECK_RET( gs_wxBusyCursorCount > 0,
223d09f6 881 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
b07135ba 882
634903fd
VZ
883 if ( --gs_wxBusyCursorCount == 0 )
884 {
885 ::SetCursor(gs_wxBusyCursorOld);
886
887 gs_wxBusyCursorOld = 0;
888 }
2bda0e17
KB
889}
890
891// TRUE if we're between the above two calls
634903fd 892bool wxIsBusy()
2bda0e17 893{
634903fd 894 return (gs_wxBusyCursorCount > 0);
b07135ba 895}
2bda0e17 896
2bda0e17
KB
897// Check whether this window wants to process messages, e.g. Stop button
898// in long calculations.
899bool wxCheckForInterrupt(wxWindow *wnd)
900{
b568d04f
VZ
901 wxCHECK( wnd, FALSE );
902
743e0a66 903 MSG msg;
b568d04f
VZ
904 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
905 {
906 ::TranslateMessage(&msg);
907 ::DispatchMessage(&msg);
743e0a66 908 }
634903fd 909
b568d04f 910 return TRUE;
2bda0e17
KB
911}
912
913// MSW only: get user-defined resource from the .res file.
914// Returns NULL or newly-allocated memory, so use delete[] to clean up.
915
837e5743 916wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
2bda0e17 917{
b568d04f
VZ
918 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
919 if ( hResource == 0 )
920 return NULL;
921
922 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
923 if ( hData == 0 )
924 return NULL;
2bda0e17 925
b568d04f
VZ
926 wxChar *theText = (wxChar *)::LockResource(hData);
927 if ( !theText )
928 return NULL;
b07135ba 929
8caa4ed1
JS
930 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
931 // so we need to find the length of the resource.
932 int len = ::SizeofResource(wxGetInstance(), hResource);
933 wxChar *s = new wxChar[len+1];
934 wxStrncpy(s,theText,len);
935 s[len]=0;
936
937 // wxChar *s = copystring(theText);
2bda0e17 938
b568d04f 939 // Obsolete in WIN32
2bda0e17 940#ifndef __WIN32__
b568d04f 941 UnlockResource(hData);
2bda0e17
KB
942#endif
943
b568d04f
VZ
944 // No need??
945 // GlobalFree(hData);
2bda0e17 946
b568d04f 947 return s;
2bda0e17 948}
b568d04f
VZ
949
950// ----------------------------------------------------------------------------
951// get display info
952// ----------------------------------------------------------------------------
2bda0e17
KB
953
954void wxGetMousePosition( int* x, int* y )
955{
b568d04f
VZ
956 POINT pt;
957 GetCursorPos( & pt );
958 if ( x ) *x = pt.x;
959 if ( y ) *y = pt.y;
2bda0e17
KB
960};
961
962// Return TRUE if we have a colour display
634903fd 963bool wxColourDisplay()
2bda0e17 964{
b568d04f
VZ
965 ScreenHDC dc;
966 int noCols = GetDeviceCaps(dc, NUMCOLORS);
967
968 return (noCols == -1) || (noCols > 2);
2bda0e17
KB
969}
970
971// Returns depth of screen
634903fd 972int wxDisplayDepth()
2bda0e17 973{
b568d04f
VZ
974 ScreenHDC dc;
975 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
2bda0e17
KB
976}
977
978// Get size of display
979void wxDisplaySize(int *width, int *height)
980{
b568d04f 981 ScreenHDC dc;
3f4a0c5b 982
b568d04f
VZ
983 if ( width ) *width = GetDeviceCaps(dc, HORZRES);
984 if ( height ) *height = GetDeviceCaps(dc, VERTRES);
7f555861
JS
985}
986
cc2b7472
VZ
987// ---------------------------------------------------------------------------
988// window information functions
989// ---------------------------------------------------------------------------
990
1c4a764c
VZ
991wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
992{
993 wxString str;
994 int len = GetWindowTextLength((HWND)hWnd) + 1;
995 GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
996 str.UngetWriteBuf();
997
998 return str;
999}
1000
cc2b7472
VZ
1001wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1002{
1003 wxString str;
1004
1005 int len = 256; // some starting value
1006
1007 for ( ;; )
1008 {
1009 // as we've #undefined GetClassName we must now manually choose the
1010 // right function to call
1011 int count =
1012
1013 #ifndef __WIN32__
1014 GetClassName
1015 #else // Win32
1016 #ifdef UNICODE
1017 GetClassNameW
1018 #else // !Unicode
1019 #ifdef __TWIN32__
1020 GetClassName
1021 #else // !Twin32
1022 GetClassNameA
1023 #endif // Twin32/!Twin32
1024 #endif // Unicode/ANSI
1025 #endif // Win16/32
1026 ((HWND)hWnd, str.GetWriteBuf(len), len);
1027
1028 str.UngetWriteBuf();
1029 if ( count == len )
1030 {
1031 // the class name might have been truncated, retry with larger
1032 // buffer
1033 len *= 2;
1034 }
1035 else
1036 {
1037 break;
1038 }
1039 }
1040
1041 return str;
1042}
1043
42e69d6b 1044WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
cc2b7472
VZ
1045{
1046#ifndef __WIN32__
42e69d6b 1047 return GetWindowWord((HWND)hWnd, GWW_ID);
cc2b7472 1048#else // Win32
42e69d6b 1049 return GetWindowLong((HWND)hWnd, GWL_ID);
cc2b7472
VZ
1050#endif // Win16/32
1051}
1052
f6bcfd97
BP
1053#endif // wxUSE_GUI
1054
7f555861
JS
1055#if 0
1056//------------------------------------------------------------------------
1057// wild character routines
1058//------------------------------------------------------------------------
1059
1060bool wxIsWild( const wxString& pattern )
1061{
1062 wxString tmp = pattern;
1063 char *pat = WXSTRINGCAST(tmp);
1064 while (*pat) {
3f4a0c5b
VZ
1065 switch (*pat++) {
1066 case '?': case '*': case '[': case '{':
1067 return TRUE;
1068 case '\\':
1069 if (!*pat++)
1070 return FALSE;
1071 }
7f555861
JS
1072 }
1073 return FALSE;
1074};
1075
1076
1077bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1078{
1079 wxString tmp1 = pat;
1080 char *pattern = WXSTRINGCAST(tmp1);
1081 wxString tmp2 = text;
1082 char *str = WXSTRINGCAST(tmp2);
1083 char c;
1084 char *cp;
1085 bool done = FALSE, ret_code, ok;
1086 // Below is for vi fans
1087 const char OB = '{', CB = '}';
1088
1089 // dot_special means '.' only matches '.'
1090 if (dot_special && *str == '.' && *pattern != *str)
3f4a0c5b 1091 return FALSE;
7f555861
JS
1092
1093 while ((*pattern != '\0') && (!done)
1094 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
3f4a0c5b
VZ
1095 switch (*pattern) {
1096 case '\\':
1097 pattern++;
1098 if (*pattern != '\0')
1099 pattern++;
1100 break;
1101 case '*':
1102 pattern++;
1103 ret_code = FALSE;
1104 while ((*str!='\0')
1105 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1106 /*loop*/;
1107 if (ret_code) {
1108 while (*str != '\0')
1109 str++;
1110 while (*pattern != '\0')
1111 pattern++;
1112 }
1113 break;
1114 case '[':
1115 pattern++;
1116 repeat:
1117 if ((*pattern == '\0') || (*pattern == ']')) {
1118 done = TRUE;
1119 break;
1120 }
1121 if (*pattern == '\\') {
1122 pattern++;
1123 if (*pattern == '\0') {
1124 done = TRUE;
1125 break;
1126 }
1127 }
1128 if (*(pattern + 1) == '-') {
1129 c = *pattern;
1130 pattern += 2;
1131 if (*pattern == ']') {
1132 done = TRUE;
1133 break;
1134 }
1135 if (*pattern == '\\') {
1136 pattern++;
1137 if (*pattern == '\0') {
1138 done = TRUE;
1139 break;
1140 }
1141 }
1142 if ((*str < c) || (*str > *pattern)) {
1143 pattern++;
1144 goto repeat;
1145 }
1146 } else if (*pattern != *str) {
1147 pattern++;
1148 goto repeat;
1149 }
1150 pattern++;
1151 while ((*pattern != ']') && (*pattern != '\0')) {
1152 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1153 pattern++;
1154 pattern++;
1155 }
1156 if (*pattern != '\0') {
1157 pattern++, str++;
1158 }
1159 break;
1160 case '?':
1161 pattern++;
1162 str++;
1163 break;
1164 case OB:
1165 pattern++;
1166 while ((*pattern != CB) && (*pattern != '\0')) {
1167 cp = str;
1168 ok = TRUE;
1169 while (ok && (*cp != '\0') && (*pattern != '\0')
1170 && (*pattern != ',') && (*pattern != CB)) {
1171 if (*pattern == '\\')
1172 pattern++;
1173 ok = (*pattern++ == *cp++);
1174 }
1175 if (*pattern == '\0') {
1176 ok = FALSE;
1177 done = TRUE;
1178 break;
1179 } else if (ok) {
1180 str = cp;
1181 while ((*pattern != CB) && (*pattern != '\0')) {
1182 if (*++pattern == '\\') {
1183 if (*++pattern == CB)
1184 pattern++;
1185 }
1186 }
1187 } else {
1188 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1189 if (*++pattern == '\\') {
7f555861 1190 if (*++pattern == CB || *pattern == ',')
3f4a0c5b
VZ
1191 pattern++;
1192 }
1193 }
1194 }
1195 if (*pattern != '\0')
1196 pattern++;
1197 }
1198 break;
1199 default:
1200 if (*str == *pattern) {
1201 str++, pattern++;
1202 } else {
1203 done = TRUE;
1204 }
1205 }
7f555861
JS
1206 }
1207 while (*pattern == '*')
3f4a0c5b 1208 pattern++;
7f555861
JS
1209 return ((*str == '\0') && (*pattern == '\0'));
1210};
1211
f6bcfd97 1212#endif // 0
7f555861 1213
cf45d1f4 1214#if 0
c030b70f
JS
1215
1216// maximum mumber of lines the output console should have
1217static const WORD MAX_CONSOLE_LINES = 500;
1218
1219BOOL WINAPI MyConsoleHandler( DWORD dwCtrlType ) { // control signal type
3f4a0c5b
VZ
1220 FreeConsole();
1221 return TRUE;
c030b70f
JS
1222}
1223
1224void wxRedirectIOToConsole()
1225{
1226 int hConHandle;
1227 long lStdHandle;
1228 CONSOLE_SCREEN_BUFFER_INFO coninfo;
1229 FILE *fp;
1230
1231 // allocate a console for this app
1232 AllocConsole();
1233
1234 // set the screen buffer to be big enough to let us scroll text
3f4a0c5b 1235 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
c030b70f
JS
1236 &coninfo);
1237 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
3f4a0c5b 1238 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
c030b70f
JS
1239 coninfo.dwSize);
1240
1241 // redirect unbuffered STDOUT to the console
1242 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
1243 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1244 if(hConHandle <= 0) return;
1245 fp = _fdopen( hConHandle, "w" );
1246 *stdout = *fp;
1247 setvbuf( stdout, NULL, _IONBF, 0 );
1248
1249 // redirect unbuffered STDIN to the console
1250 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
1251 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1252 if(hConHandle <= 0) return;
1253 fp = _fdopen( hConHandle, "r" );
1254 *stdin = *fp;
1255 setvbuf( stdin, NULL, _IONBF, 0 );
1256
1257 // redirect unbuffered STDERR to the console
1258 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
1259 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1260 if(hConHandle <= 0) return;
1261 fp = _fdopen( hConHandle, "w" );
1262 *stderr = *fp;
1263 setvbuf( stderr, NULL, _IONBF, 0 );
3f4a0c5b
VZ
1264
1265 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
c030b70f
JS
1266 // point to console as well
1267 ios::sync_with_stdio();
1268
3f4a0c5b 1269 SetConsoleCtrlHandler(MyConsoleHandler, TRUE);
c030b70f
JS
1270}
1271#else
1272// Not supported
1273void wxRedirectIOToConsole()
1274{
1275}
1276#endif
1277
1278