]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utils.cpp
Added missing files to listing
[wxWidgets.git] / src / msw / utils.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utils.cpp
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
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 // #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/cursor.h"
35 #include "wx/intl.h"
36 #include "wx/log.h"
37 #endif //WX_PRECOMP
38
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 //
44 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
45 extern "C" {
46 #include <winsock.h> // we use socket functions in wxGetFullHostName()
47 }
48 #endif
49
50 #include "wx/msw/private.h" // includes <windows.h>
51
52 #include "wx/timer.h"
53
54 #include <ctype.h>
55
56 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
57 #include <direct.h>
58
59 #ifndef __MWERKS__
60 #include <dos.h>
61 #endif
62 #endif //GNUWIN32
63
64 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
65 #include <sys/unistd.h>
66 #include <sys/stat.h>
67 #endif //GNUWIN32
68
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.
72 #include <dir.h>
73 #endif
74
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
85 #if defined(__WIN32__) && !defined(__WXWINE__)
86 #include <io.h>
87
88 #ifndef __GNUWIN32__
89 #include <shellapi.h>
90 #endif
91 #endif
92
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #ifndef __WATCOMC__
97 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
98 #include <errno.h>
99 #endif
100 #endif
101 #include <stdarg.h>
102
103 //// BEGIN for console support: VC++ only
104 #ifdef __VISUALC__
105
106 #include "wx/msw/msvcrt.h"
107
108 #include <fcntl.h>
109
110 #include "wx/ioswrap.h"
111
112 #if wxUSE_IOSTREAMH
113 // N.B. BC++ doesn't have istream.h, ostream.h
114 # include <io.h>
115 # include <fstream.h>
116 #else
117 # include <fstream>
118 #endif
119
120 /* Need to undef new if including crtdbg.h */
121 # ifdef new
122 # undef new
123 # endif
124
125 #ifndef __WIN16__
126 # include <crtdbg.h>
127 #endif
128
129 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
130 # define new new(__TFILE__,__LINE__)
131 # endif
132
133 #endif
134 // __VISUALC__
135 /// END for console support
136
137 // ----------------------------------------------------------------------------
138 // constants
139 // ----------------------------------------------------------------------------
140
141 // In the WIN.INI file
142 static const wxChar WX_SECTION[] = wxT("wxWindows");
143 static const wxChar eUSERNAME[] = wxT("UserName");
144
145 // these are only used under Win16
146 #ifndef __WIN32__
147 static const wxChar eHOSTNAME[] = wxT("HostName");
148 static const wxChar eUSERID[] = wxT("UserId");
149 #endif // !Win32
150
151 // ============================================================================
152 // implementation
153 // ============================================================================
154
155 // ----------------------------------------------------------------------------
156 // get host name and related
157 // ----------------------------------------------------------------------------
158
159 // Get hostname only (without domain name)
160 bool wxGetHostName(wxChar *buf, int maxSize)
161 {
162 #if defined(__WIN32__) && !defined(__TWIN32__)
163 DWORD nSize = maxSize;
164 if ( !::GetComputerName(buf, &nSize) )
165 {
166 wxLogLastError(wxT("GetComputerName"));
167
168 return FALSE;
169 }
170
171 return TRUE;
172 #else
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;
182 #endif
183 }
184
185 // get full hostname (with domain name if possible)
186 bool wxGetFullHostName(wxChar *buf, int maxSize)
187 {
188 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
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
227 return wxGetHostName(buf, maxSize);
228 }
229
230 // Get user ID e.g. jacs
231 bool wxGetUserId(wxChar *buf, int maxSize)
232 {
233 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__)
234 DWORD nSize = maxSize;
235 if ( ::GetUserName(buf, &nSize) == 0 )
236 {
237 // actually, it does happen on Win9x if the user didn't log on
238 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
239 if ( res == 0 )
240 {
241 // not found
242 return FALSE;
243 }
244 }
245
246 return TRUE;
247 #else // Win16 or Win32s
248 wxChar *user;
249 const wxChar *default_id = wxT("anonymous");
250
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 }
263
264 return *buf ? TRUE : FALSE;
265 #endif
266 }
267
268 // Get user name e.g. Julian Smart
269 bool wxGetUserName(wxChar *buf, int maxSize)
270 {
271 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
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
281 #endif
282 {
283 #ifdef USE_NET_API
284 CHAR szUserName[256];
285 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
286 return FALSE;
287
288 // TODO how to get the domain name?
289 CHAR *szDomain = "";
290
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;
295
296 USER_INFO_2 *ui2; // User structure
297
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) );
303
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"));
308
309 goto error;
310 }
311
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;
322
323 case NERR_InvalidComputer:
324 wxLogError(wxT("Invalid domain controller name."));
325
326 goto error;
327
328 case NERR_UserNotFound:
329 wxLogError(wxT("Invalid user name '%s'."), szUserName);
330
331 goto error;
332
333 default:
334 wxLogSysError(wxT("Can't get information about user"));
335
336 goto error;
337 }
338
339 // Convert the Unicode full name to ANSI
340 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
341 buf, maxSize, NULL, NULL );
342
343 return TRUE;
344
345 error:
346 wxLogError(wxT("Couldn't look up full user name."));
347
348 return FALSE;
349 #else // !USE_NET_API
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 }
357
358 if ( !ok )
359 {
360 wxStrncpy(buf, wxT("Unknown User"), maxSize);
361 }
362 #endif // Win32/16
363 }
364
365 return TRUE;
366 }
367
368 const wxChar* wxGetHomeDir(wxString *pstr)
369 {
370 wxString& strDir = *pstr;
371
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;
381
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;
393
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 }
403
404 #else // Win16
405 // Win16 has no idea about home, so use the working directory instead
406 #endif // WIN16/32
407
408 // 260 was taken from windef.h
409 #ifndef MAX_PATH
410 #define MAX_PATH 260
411 #endif
412
413 wxString strPath;
414 ::GetModuleFileName(::GetModuleHandle(NULL),
415 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
416 strPath.UngetWriteBuf();
417
418 // extract the dir name
419 wxSplitPath(strPath, &strDir, NULL, NULL);
420
421 #endif // UNIX/Win
422
423 return strDir.c_str();
424 }
425
426 wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
427 {
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;
432
433 return (wxChar *)wxGetHomeDir(&s_home);
434 }
435
436 bool wxDirExists(const wxString& dir)
437 {
438 #if defined(__WIN32__)
439 DWORD attribs = GetFileAttributes(dir);
440 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
441 #else // Win16
442 #ifdef __BORLANDC__
443 struct ffblk fileInfo;
444 #else
445 struct find_t fileInfo;
446 #endif
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 }
459
460 // ----------------------------------------------------------------------------
461 // env vars
462 // ----------------------------------------------------------------------------
463
464 bool wxGetEnv(const wxString& var, wxString *value)
465 {
466 #ifdef __WIN16__
467 const wxChar* ret = wxGetenv(var);
468 if (ret)
469 {
470 *value = ret;
471 return TRUE;
472 }
473 else
474 return FALSE;
475 #else
476 // first get the size of the buffer
477 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
478 if ( !dwRet )
479 {
480 // this means that there is no such variable
481 return FALSE;
482 }
483
484 if ( value )
485 {
486 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
487 value->UngetWriteBuf();
488 }
489
490 return TRUE;
491 #endif
492 }
493
494 bool wxSetEnv(const wxString& var, const wxChar *value)
495 {
496 // some compilers have putenv() or _putenv() or _wputenv() but it's better
497 // to always use Win32 function directly instead of dealing with them
498 #if defined(__WIN32__)
499 if ( !::SetEnvironmentVariable(var, value) )
500 {
501 wxLogLastError(_T("SetEnvironmentVariable"));
502
503 return FALSE;
504 }
505
506 return TRUE;
507 #else // no way to set env vars
508 return FALSE;
509 #endif
510 }
511
512 // ----------------------------------------------------------------------------
513 // process management
514 // ----------------------------------------------------------------------------
515
516 int wxKill(long WXUNUSED(pid), int WXUNUSED(sig))
517 {
518 // TODO use SendMessage(WM_QUIT) and TerminateProcess() if needed
519
520 return 0;
521 }
522
523 // Execute a program in an Interactive Shell
524 bool wxShell(const wxString& command)
525 {
526 wxChar *shell = wxGetenv(wxT("COMSPEC"));
527 if ( !shell )
528 shell = wxT("\\COMMAND.COM");
529
530 wxString cmd;
531 if ( !command )
532 {
533 // just the shell
534 cmd = shell;
535 }
536 else
537 {
538 // pass the command to execute to the command processor
539 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
540 }
541
542 return wxExecute(cmd, TRUE /* sync */) != 0;
543 }
544
545 // ----------------------------------------------------------------------------
546 // misc
547 // ----------------------------------------------------------------------------
548
549 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
550 long wxGetFreeMemory()
551 {
552 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
553 MEMORYSTATUS memStatus;
554 memStatus.dwLength = sizeof(MEMORYSTATUS);
555 GlobalMemoryStatus(&memStatus);
556 return memStatus.dwAvailPhys;
557 #else
558 return (long)GetFreeSpace(0);
559 #endif
560 }
561
562 // Emit a beeeeeep
563 void wxBell()
564 {
565 ::MessageBeep((UINT)-1); // default sound
566 }
567
568 wxString wxGetOsDescription()
569 {
570 #ifdef __WIN32__
571 wxString str;
572
573 OSVERSIONINFO info;
574 wxZeroMemory(info);
575
576 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
577 if ( ::GetVersionEx(&info) )
578 {
579 switch ( info.dwPlatformId )
580 {
581 case VER_PLATFORM_WIN32s:
582 str = _("Win32s on Windows 3.1");
583 break;
584
585 case VER_PLATFORM_WIN32_WINDOWS:
586 str.Printf(_("Windows 9%c"),
587 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
588 if ( !wxIsEmpty(info.szCSDVersion) )
589 {
590 str << _T(" (") << info.szCSDVersion << _T(')');
591 }
592 break;
593
594 case VER_PLATFORM_WIN32_NT:
595 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
596 info.dwMajorVersion,
597 info.dwMinorVersion,
598 info.dwBuildNumber);
599 if ( !wxIsEmpty(info.szCSDVersion) )
600 {
601 str << _T(", ") << info.szCSDVersion;
602 }
603 str << _T(')');
604 break;
605 }
606 }
607 else
608 {
609 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
610 }
611
612 return str;
613 #else // Win16
614 return _("Windows 3.1");
615 #endif // Win32/16
616 }
617
618 int wxGetOsVersion(int *majorVsn, int *minorVsn)
619 {
620 #if defined(__WIN32__) && !defined(__SC__)
621 OSVERSIONINFO info;
622 wxZeroMemory(info);
623
624 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
625 if ( ::GetVersionEx(&info) )
626 {
627 if (majorVsn)
628 *majorVsn = info.dwMajorVersion;
629 if (minorVsn)
630 *minorVsn = info.dwMinorVersion;
631
632 switch ( info.dwPlatformId )
633 {
634 case VER_PLATFORM_WIN32s:
635 return wxWIN32S;
636
637 case VER_PLATFORM_WIN32_WINDOWS:
638 return wxWIN95;
639
640 case VER_PLATFORM_WIN32_NT:
641 return wxWINDOWS_NT;
642 }
643 }
644
645 return wxWINDOWS; // error if we get here, return generic value
646 #else // Win16
647 int retValue = wxWINDOWS;
648 #ifdef __WINDOWS_386__
649 retValue = wxWIN386;
650 #else
651 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
652 extern HANDLE g_hPenWin;
653 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
654 #endif
655 #endif
656
657 if (majorVsn)
658 *majorVsn = 3;
659 if (minorVsn)
660 *minorVsn = 1;
661
662 return retValue;
663 #endif
664 }
665
666 // ----------------------------------------------------------------------------
667 // sleep functions
668 // ----------------------------------------------------------------------------
669
670 #if wxUSE_GUI
671
672 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
673 static bool gs_inTimer = FALSE;
674
675 class wxSleepTimer: public wxTimer
676 {
677 public:
678 virtual void Notify()
679 {
680 gs_inTimer = FALSE;
681 Stop();
682 }
683 };
684
685 static wxTimer *wxTheSleepTimer = NULL;
686
687 void wxUsleep(unsigned long milliseconds)
688 {
689 #ifdef __WIN32__
690 ::Sleep(milliseconds);
691 #else
692 if (gs_inTimer)
693 return;
694
695 wxTheSleepTimer = new wxSleepTimer;
696 gs_inTimer = TRUE;
697 wxTheSleepTimer->Start(milliseconds);
698 while (gs_inTimer)
699 {
700 if (wxTheApp->Pending())
701 wxTheApp->Dispatch();
702 }
703 delete wxTheSleepTimer;
704 wxTheSleepTimer = NULL;
705 #endif
706 }
707
708 void wxSleep(int nSecs)
709 {
710 if (gs_inTimer)
711 return;
712
713 wxTheSleepTimer = new wxSleepTimer;
714 gs_inTimer = TRUE;
715 wxTheSleepTimer->Start(nSecs*1000);
716 while (gs_inTimer)
717 {
718 if (wxTheApp->Pending())
719 wxTheApp->Dispatch();
720 }
721 delete wxTheSleepTimer;
722 wxTheSleepTimer = NULL;
723 }
724
725 // Consume all events until no more left
726 void wxFlushEvents()
727 {
728 // wxYield();
729 }
730
731 #elif defined(__WIN32__) // wxUSE_GUI
732
733 void wxUsleep(unsigned long milliseconds)
734 {
735 ::Sleep(milliseconds);
736 }
737
738 void wxSleep(int nSecs)
739 {
740 wxUsleep(1000*nSecs);
741 }
742
743 #endif // wxUSE_GUI/!wxUSE_GUI
744
745 // ----------------------------------------------------------------------------
746 // deprecated (in favour of wxLog) log functions
747 // ----------------------------------------------------------------------------
748
749 #if wxUSE_GUI
750
751 // Output a debug mess., in a system dependent fashion.
752 void wxDebugMsg(const wxChar *fmt ...)
753 {
754 va_list ap;
755 static wxChar buffer[512];
756
757 if (!wxTheApp->GetWantDebugOutput())
758 return ;
759
760 va_start(ap, fmt);
761
762 wvsprintf(buffer,fmt,ap) ;
763 OutputDebugString((LPCTSTR)buffer) ;
764
765 va_end(ap);
766 }
767
768 // Non-fatal error: pop up message box and (possibly) continue
769 void wxError(const wxString& msg, const wxString& title)
770 {
771 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
772 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
773 MB_ICONSTOP | MB_YESNO) == IDNO)
774 wxExit();
775 }
776
777 // Fatal error: pop up message box and abort
778 void wxFatalError(const wxString& msg, const wxString& title)
779 {
780 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
781 FatalAppExit(0, (LPCTSTR)wxBuffer);
782 }
783
784 // ----------------------------------------------------------------------------
785 // functions to work with .INI files
786 // ----------------------------------------------------------------------------
787
788 // Reading and writing resources (eg WIN.INI, .Xdefaults)
789 #if wxUSE_RESOURCES
790 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
791 {
792 if (file != wxT(""))
793 // Don't know what the correct cast should be, but it doesn't
794 // compile in BC++/16-bit without this cast.
795 #if !defined(__WIN32__)
796 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
797 #else
798 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
799 #endif
800 else
801 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
802 }
803
804 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
805 {
806 wxString buf;
807 buf.Printf(wxT("%.4f"), value);
808
809 return wxWriteResource(section, entry, buf, file);
810 }
811
812 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
813 {
814 wxString buf;
815 buf.Printf(wxT("%ld"), value);
816
817 return wxWriteResource(section, entry, buf, file);
818 }
819
820 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
821 {
822 wxString buf;
823 buf.Printf(wxT("%d"), value);
824
825 return wxWriteResource(section, entry, buf, file);
826 }
827
828 bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
829 {
830 static const wxChar defunkt[] = wxT("$$default");
831 if (file != wxT(""))
832 {
833 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
834 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
835 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
836 return FALSE;
837 }
838 else
839 {
840 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
841 (LPTSTR)wxBuffer, 1000);
842 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
843 return FALSE;
844 }
845 if (*value) delete[] (*value);
846 *value = copystring(wxBuffer);
847 return TRUE;
848 }
849
850 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
851 {
852 wxChar *s = NULL;
853 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
854 if (succ)
855 {
856 *value = (float)wxStrtod(s, NULL);
857 delete[] s;
858 return TRUE;
859 }
860 else return FALSE;
861 }
862
863 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
864 {
865 wxChar *s = NULL;
866 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
867 if (succ)
868 {
869 *value = wxStrtol(s, NULL, 10);
870 delete[] s;
871 return TRUE;
872 }
873 else return FALSE;
874 }
875
876 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
877 {
878 wxChar *s = NULL;
879 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
880 if (succ)
881 {
882 *value = (int)wxStrtol(s, NULL, 10);
883 delete[] s;
884 return TRUE;
885 }
886 else return FALSE;
887 }
888 #endif // wxUSE_RESOURCES
889
890 // ---------------------------------------------------------------------------
891 // helper functions for showing a "busy" cursor
892 // ---------------------------------------------------------------------------
893
894 static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
895 static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
896 static int gs_wxBusyCursorCount = 0;
897
898 extern HCURSOR wxGetCurrentBusyCursor()
899 {
900 return gs_wxBusyCursor;
901 }
902
903 // Set the cursor to the busy cursor for all windows
904 void wxBeginBusyCursor(wxCursor *cursor)
905 {
906 if ( gs_wxBusyCursorCount++ == 0 )
907 {
908 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
909 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
910 }
911 //else: nothing to do, already set
912 }
913
914 // Restore cursor to normal
915 void wxEndBusyCursor()
916 {
917 wxCHECK_RET( gs_wxBusyCursorCount > 0,
918 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
919
920 if ( --gs_wxBusyCursorCount == 0 )
921 {
922 ::SetCursor(gs_wxBusyCursorOld);
923
924 gs_wxBusyCursorOld = 0;
925 }
926 }
927
928 // TRUE if we're between the above two calls
929 bool wxIsBusy()
930 {
931 return (gs_wxBusyCursorCount > 0);
932 }
933
934 // Check whether this window wants to process messages, e.g. Stop button
935 // in long calculations.
936 bool wxCheckForInterrupt(wxWindow *wnd)
937 {
938 wxCHECK( wnd, FALSE );
939
940 MSG msg;
941 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
942 {
943 ::TranslateMessage(&msg);
944 ::DispatchMessage(&msg);
945 }
946
947 return TRUE;
948 }
949
950 // MSW only: get user-defined resource from the .res file.
951 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
952
953 wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
954 {
955 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
956 if ( hResource == 0 )
957 return NULL;
958
959 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
960 if ( hData == 0 )
961 return NULL;
962
963 wxChar *theText = (wxChar *)::LockResource(hData);
964 if ( !theText )
965 return NULL;
966
967 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
968 // so we need to find the length of the resource.
969 int len = ::SizeofResource(wxGetInstance(), hResource);
970 wxChar *s = new wxChar[len+1];
971 wxStrncpy(s,theText,len);
972 s[len]=0;
973
974 // wxChar *s = copystring(theText);
975
976 // Obsolete in WIN32
977 #ifndef __WIN32__
978 UnlockResource(hData);
979 #endif
980
981 // No need??
982 // GlobalFree(hData);
983
984 return s;
985 }
986
987 // ----------------------------------------------------------------------------
988 // get display info
989 // ----------------------------------------------------------------------------
990
991 // See also the wxGetMousePosition in window.cpp
992 // Deprecated: use wxPoint wxGetMousePosition() instead
993 void wxGetMousePosition( int* x, int* y )
994 {
995 POINT pt;
996 GetCursorPos( & pt );
997 if ( x ) *x = pt.x;
998 if ( y ) *y = pt.y;
999 };
1000
1001 // Return TRUE if we have a colour display
1002 bool wxColourDisplay()
1003 {
1004 // this function is called from wxDC ctor so it is called a *lot* of times
1005 // hence we optimize it a bit but doign the check only once
1006 //
1007 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1008 // can call us
1009 static int s_isColour = -1;
1010
1011 if ( s_isColour == -1 )
1012 {
1013 ScreenHDC dc;
1014 int noCols = ::GetDeviceCaps(dc, NUMCOLORS);
1015
1016 s_isColour = (noCols == -1) || (noCols > 2);
1017 }
1018
1019 return s_isColour != 0;
1020 }
1021
1022 // Returns depth of screen
1023 int wxDisplayDepth()
1024 {
1025 ScreenHDC dc;
1026 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
1027 }
1028
1029 // Get size of display
1030 void wxDisplaySize(int *width, int *height)
1031 {
1032 ScreenHDC dc;
1033
1034 if ( width ) *width = GetDeviceCaps(dc, HORZRES);
1035 if ( height ) *height = GetDeviceCaps(dc, VERTRES);
1036 }
1037
1038 void wxDisplaySizeMM(int *width, int *height)
1039 {
1040 ScreenHDC dc;
1041
1042 if ( width ) *width = GetDeviceCaps(dc, HORZSIZE);
1043 if ( height ) *height = GetDeviceCaps(dc, VERTSIZE);
1044 }
1045
1046 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
1047 {
1048 #ifdef __WIN16__
1049 *x = 0; *y = 0;
1050 wxDisplaySize(width, height);
1051 #else
1052 // Determine the desktop dimensions minus the taskbar and any other
1053 // special decorations...
1054 RECT r;
1055
1056 SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
1057 if (x) *x = r.left;
1058 if (y) *y = r.top;
1059 if (width) *width = r.right - r.left;
1060 if (height) *height = r.bottom - r.top;
1061 #endif
1062 }
1063
1064
1065 // ---------------------------------------------------------------------------
1066 // window information functions
1067 // ---------------------------------------------------------------------------
1068
1069 wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1070 {
1071 wxString str;
1072 int len = GetWindowTextLength((HWND)hWnd) + 1;
1073 GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1074 str.UngetWriteBuf();
1075
1076 return str;
1077 }
1078
1079 wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1080 {
1081 wxString str;
1082
1083 int len = 256; // some starting value
1084
1085 for ( ;; )
1086 {
1087 // as we've #undefined GetClassName we must now manually choose the
1088 // right function to call
1089 int count =
1090
1091 #ifndef __WIN32__
1092 GetClassName
1093 #else // Win32
1094 #ifdef UNICODE
1095 GetClassNameW
1096 #else // !Unicode
1097 #ifdef __TWIN32__
1098 GetClassName
1099 #else // !Twin32
1100 GetClassNameA
1101 #endif // Twin32/!Twin32
1102 #endif // Unicode/ANSI
1103 #endif // Win16/32
1104 ((HWND)hWnd, str.GetWriteBuf(len), len);
1105
1106 str.UngetWriteBuf();
1107 if ( count == len )
1108 {
1109 // the class name might have been truncated, retry with larger
1110 // buffer
1111 len *= 2;
1112 }
1113 else
1114 {
1115 break;
1116 }
1117 }
1118
1119 return str;
1120 }
1121
1122 WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
1123 {
1124 #ifndef __WIN32__
1125 return (WXWORD)GetWindowWord((HWND)hWnd, GWW_ID);
1126 #else // Win32
1127 return (WXWORD)GetWindowLong((HWND)hWnd, GWL_ID);
1128 #endif // Win16/32
1129 }
1130
1131 #endif // wxUSE_GUI
1132
1133 #if 0
1134 //------------------------------------------------------------------------
1135 // wild character routines
1136 //------------------------------------------------------------------------
1137
1138 bool wxIsWild( const wxString& pattern )
1139 {
1140 wxString tmp = pattern;
1141 char *pat = WXSTRINGCAST(tmp);
1142 while (*pat) {
1143 switch (*pat++) {
1144 case '?': case '*': case '[': case '{':
1145 return TRUE;
1146 case '\\':
1147 if (!*pat++)
1148 return FALSE;
1149 }
1150 }
1151 return FALSE;
1152 };
1153
1154
1155 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1156 {
1157 wxString tmp1 = pat;
1158 char *pattern = WXSTRINGCAST(tmp1);
1159 wxString tmp2 = text;
1160 char *str = WXSTRINGCAST(tmp2);
1161 char c;
1162 char *cp;
1163 bool done = FALSE, ret_code, ok;
1164 // Below is for vi fans
1165 const char OB = '{', CB = '}';
1166
1167 // dot_special means '.' only matches '.'
1168 if (dot_special && *str == '.' && *pattern != *str)
1169 return FALSE;
1170
1171 while ((*pattern != '\0') && (!done)
1172 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
1173 switch (*pattern) {
1174 case '\\':
1175 pattern++;
1176 if (*pattern != '\0')
1177 pattern++;
1178 break;
1179 case '*':
1180 pattern++;
1181 ret_code = FALSE;
1182 while ((*str!='\0')
1183 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1184 /*loop*/;
1185 if (ret_code) {
1186 while (*str != '\0')
1187 str++;
1188 while (*pattern != '\0')
1189 pattern++;
1190 }
1191 break;
1192 case '[':
1193 pattern++;
1194 repeat:
1195 if ((*pattern == '\0') || (*pattern == ']')) {
1196 done = TRUE;
1197 break;
1198 }
1199 if (*pattern == '\\') {
1200 pattern++;
1201 if (*pattern == '\0') {
1202 done = TRUE;
1203 break;
1204 }
1205 }
1206 if (*(pattern + 1) == '-') {
1207 c = *pattern;
1208 pattern += 2;
1209 if (*pattern == ']') {
1210 done = TRUE;
1211 break;
1212 }
1213 if (*pattern == '\\') {
1214 pattern++;
1215 if (*pattern == '\0') {
1216 done = TRUE;
1217 break;
1218 }
1219 }
1220 if ((*str < c) || (*str > *pattern)) {
1221 pattern++;
1222 goto repeat;
1223 }
1224 } else if (*pattern != *str) {
1225 pattern++;
1226 goto repeat;
1227 }
1228 pattern++;
1229 while ((*pattern != ']') && (*pattern != '\0')) {
1230 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1231 pattern++;
1232 pattern++;
1233 }
1234 if (*pattern != '\0') {
1235 pattern++, str++;
1236 }
1237 break;
1238 case '?':
1239 pattern++;
1240 str++;
1241 break;
1242 case OB:
1243 pattern++;
1244 while ((*pattern != CB) && (*pattern != '\0')) {
1245 cp = str;
1246 ok = TRUE;
1247 while (ok && (*cp != '\0') && (*pattern != '\0')
1248 && (*pattern != ',') && (*pattern != CB)) {
1249 if (*pattern == '\\')
1250 pattern++;
1251 ok = (*pattern++ == *cp++);
1252 }
1253 if (*pattern == '\0') {
1254 ok = FALSE;
1255 done = TRUE;
1256 break;
1257 } else if (ok) {
1258 str = cp;
1259 while ((*pattern != CB) && (*pattern != '\0')) {
1260 if (*++pattern == '\\') {
1261 if (*++pattern == CB)
1262 pattern++;
1263 }
1264 }
1265 } else {
1266 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1267 if (*++pattern == '\\') {
1268 if (*++pattern == CB || *pattern == ',')
1269 pattern++;
1270 }
1271 }
1272 }
1273 if (*pattern != '\0')
1274 pattern++;
1275 }
1276 break;
1277 default:
1278 if (*str == *pattern) {
1279 str++, pattern++;
1280 } else {
1281 done = TRUE;
1282 }
1283 }
1284 }
1285 while (*pattern == '*')
1286 pattern++;
1287 return ((*str == '\0') && (*pattern == '\0'));
1288 };
1289
1290 #endif // 0
1291
1292 #if 0
1293
1294 // maximum mumber of lines the output console should have
1295 static const WORD MAX_CONSOLE_LINES = 500;
1296
1297 BOOL WINAPI MyConsoleHandler( DWORD dwCtrlType ) { // control signal type
1298 FreeConsole();
1299 return TRUE;
1300 }
1301
1302 void wxRedirectIOToConsole()
1303 {
1304 int hConHandle;
1305 long lStdHandle;
1306 CONSOLE_SCREEN_BUFFER_INFO coninfo;
1307 FILE *fp;
1308
1309 // allocate a console for this app
1310 AllocConsole();
1311
1312 // set the screen buffer to be big enough to let us scroll text
1313 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
1314 &coninfo);
1315 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
1316 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
1317 coninfo.dwSize);
1318
1319 // redirect unbuffered STDOUT to the console
1320 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
1321 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1322 if(hConHandle <= 0) return;
1323 fp = _fdopen( hConHandle, "w" );
1324 *stdout = *fp;
1325 setvbuf( stdout, NULL, _IONBF, 0 );
1326
1327 // redirect unbuffered STDIN to the console
1328 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
1329 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1330 if(hConHandle <= 0) return;
1331 fp = _fdopen( hConHandle, "r" );
1332 *stdin = *fp;
1333 setvbuf( stdin, NULL, _IONBF, 0 );
1334
1335 // redirect unbuffered STDERR to the console
1336 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
1337 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1338 if(hConHandle <= 0) return;
1339 fp = _fdopen( hConHandle, "w" );
1340 *stderr = *fp;
1341 setvbuf( stderr, NULL, _IONBF, 0 );
1342
1343 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1344 // point to console as well
1345 ios::sync_with_stdio();
1346
1347 SetConsoleCtrlHandler(MyConsoleHandler, TRUE);
1348 }
1349 #else
1350 // Not supported
1351 void wxRedirectIOToConsole()
1352 {
1353 }
1354 #endif
1355
1356