]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utils.cpp
corrected eventual endless loop
[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 // first get the size of the buffer
467 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
468 if ( !dwRet )
469 {
470 // this means that there is no such variable
471 return FALSE;
472 }
473
474 if ( value )
475 {
476 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
477 value->UngetWriteBuf();
478 }
479
480 return TRUE;
481 }
482
483 bool wxSetEnv(const wxString& var, const wxChar *value)
484 {
485 // some compilers have putenv() or _putenv() or _wputenv() but it's better
486 // to always use Win32 function directly instead of dealing with them
487 #if defined(__WIN32__)
488 if ( !::SetEnvironmentVariable(var, value) )
489 {
490 wxLogLastError(_T("SetEnvironmentVariable"));
491
492 return FALSE;
493 }
494
495 return TRUE;
496 #else // no way to set env vars
497 return FALSE;
498 #endif
499 }
500
501 // ----------------------------------------------------------------------------
502 // process management
503 // ----------------------------------------------------------------------------
504
505 int wxKill(long WXUNUSED(pid), int WXUNUSED(sig))
506 {
507 // TODO use SendMessage(WM_QUIT) and TerminateProcess() if needed
508
509 return 0;
510 }
511
512 // Execute a program in an Interactive Shell
513 bool wxShell(const wxString& command)
514 {
515 wxChar *shell = wxGetenv(wxT("COMSPEC"));
516 if ( !shell )
517 shell = wxT("\\COMMAND.COM");
518
519 wxString cmd;
520 if ( !command )
521 {
522 // just the shell
523 cmd = shell;
524 }
525 else
526 {
527 // pass the command to execute to the command processor
528 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
529 }
530
531 return wxExecute(cmd, TRUE /* sync */) != 0;
532 }
533
534 // ----------------------------------------------------------------------------
535 // misc
536 // ----------------------------------------------------------------------------
537
538 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
539 long wxGetFreeMemory()
540 {
541 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
542 MEMORYSTATUS memStatus;
543 memStatus.dwLength = sizeof(MEMORYSTATUS);
544 GlobalMemoryStatus(&memStatus);
545 return memStatus.dwAvailPhys;
546 #else
547 return (long)GetFreeSpace(0);
548 #endif
549 }
550
551 // Emit a beeeeeep
552 void wxBell()
553 {
554 ::MessageBeep((UINT)-1); // default sound
555 }
556
557 wxString wxGetOsDescription()
558 {
559 #ifdef __WIN32__
560 wxString str;
561
562 OSVERSIONINFO info;
563 wxZeroMemory(info);
564
565 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
566 if ( ::GetVersionEx(&info) )
567 {
568 switch ( info.dwPlatformId )
569 {
570 case VER_PLATFORM_WIN32s:
571 str = _("Win32s on Windows 3.1");
572 break;
573
574 case VER_PLATFORM_WIN32_WINDOWS:
575 str.Printf(_("Windows 9%c"),
576 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
577 if ( !wxIsEmpty(info.szCSDVersion) )
578 {
579 str << _T(" (") << info.szCSDVersion << _T(')');
580 }
581 break;
582
583 case VER_PLATFORM_WIN32_NT:
584 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
585 info.dwMajorVersion,
586 info.dwMinorVersion,
587 info.dwBuildNumber);
588 if ( !wxIsEmpty(info.szCSDVersion) )
589 {
590 str << _T(", ") << info.szCSDVersion;
591 }
592 str << _T(')');
593 break;
594 }
595 }
596 else
597 {
598 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
599 }
600
601 return str;
602 #else // Win16
603 return _("Windows 3.1");
604 #endif // Win32/16
605 }
606
607 int wxGetOsVersion(int *majorVsn, int *minorVsn)
608 {
609 #if defined(__WIN32__) && !defined(__SC__)
610 OSVERSIONINFO info;
611 wxZeroMemory(info);
612
613 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
614 if ( ::GetVersionEx(&info) )
615 {
616 if (majorVsn)
617 *majorVsn = info.dwMajorVersion;
618 if (minorVsn)
619 *minorVsn = info.dwMinorVersion;
620
621 switch ( info.dwPlatformId )
622 {
623 case VER_PLATFORM_WIN32s:
624 return wxWIN32S;
625
626 case VER_PLATFORM_WIN32_WINDOWS:
627 return wxWIN95;
628
629 case VER_PLATFORM_WIN32_NT:
630 return wxWINDOWS_NT;
631 }
632 }
633
634 return wxWINDOWS; // error if we get here, return generic value
635 #else // Win16
636 int retValue = wxWINDOWS;
637 #ifdef __WINDOWS_386__
638 retValue = wxWIN386;
639 #else
640 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
641 extern HANDLE g_hPenWin;
642 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
643 #endif
644 #endif
645
646 if (majorVsn)
647 *majorVsn = 3;
648 if (minorVsn)
649 *minorVsn = 1;
650
651 return retValue;
652 #endif
653 }
654
655 // ----------------------------------------------------------------------------
656 // sleep functions
657 // ----------------------------------------------------------------------------
658
659 #if wxUSE_GUI
660
661 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
662 static bool gs_inTimer = FALSE;
663
664 class wxSleepTimer: public wxTimer
665 {
666 public:
667 virtual void Notify()
668 {
669 gs_inTimer = FALSE;
670 Stop();
671 }
672 };
673
674 static wxTimer *wxTheSleepTimer = NULL;
675
676 void wxUsleep(unsigned long milliseconds)
677 {
678 #ifdef __WIN32__
679 ::Sleep(milliseconds);
680 #else
681 if (gs_inTimer)
682 return;
683
684 wxTheSleepTimer = new wxSleepTimer;
685 gs_inTimer = TRUE;
686 wxTheSleepTimer->Start(milliseconds);
687 while (gs_inTimer)
688 {
689 if (wxTheApp->Pending())
690 wxTheApp->Dispatch();
691 }
692 delete wxTheSleepTimer;
693 wxTheSleepTimer = NULL;
694 #endif
695 }
696
697 void wxSleep(int nSecs)
698 {
699 if (gs_inTimer)
700 return;
701
702 wxTheSleepTimer = new wxSleepTimer;
703 gs_inTimer = TRUE;
704 wxTheSleepTimer->Start(nSecs*1000);
705 while (gs_inTimer)
706 {
707 if (wxTheApp->Pending())
708 wxTheApp->Dispatch();
709 }
710 delete wxTheSleepTimer;
711 wxTheSleepTimer = NULL;
712 }
713
714 // Consume all events until no more left
715 void wxFlushEvents()
716 {
717 // wxYield();
718 }
719
720 #elif defined(__WIN32__) // wxUSE_GUI
721
722 void wxUsleep(unsigned long milliseconds)
723 {
724 ::Sleep(milliseconds);
725 }
726
727 void wxSleep(int nSecs)
728 {
729 wxUsleep(1000*nSecs);
730 }
731
732 #endif // wxUSE_GUI/!wxUSE_GUI
733
734 // ----------------------------------------------------------------------------
735 // deprecated (in favour of wxLog) log functions
736 // ----------------------------------------------------------------------------
737
738 #if wxUSE_GUI
739
740 // Output a debug mess., in a system dependent fashion.
741 void wxDebugMsg(const wxChar *fmt ...)
742 {
743 va_list ap;
744 static wxChar buffer[512];
745
746 if (!wxTheApp->GetWantDebugOutput())
747 return ;
748
749 va_start(ap, fmt);
750
751 wvsprintf(buffer,fmt,ap) ;
752 OutputDebugString((LPCTSTR)buffer) ;
753
754 va_end(ap);
755 }
756
757 // Non-fatal error: pop up message box and (possibly) continue
758 void wxError(const wxString& msg, const wxString& title)
759 {
760 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
761 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
762 MB_ICONSTOP | MB_YESNO) == IDNO)
763 wxExit();
764 }
765
766 // Fatal error: pop up message box and abort
767 void wxFatalError(const wxString& msg, const wxString& title)
768 {
769 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
770 FatalAppExit(0, (LPCTSTR)wxBuffer);
771 }
772
773 // ----------------------------------------------------------------------------
774 // functions to work with .INI files
775 // ----------------------------------------------------------------------------
776
777 // Reading and writing resources (eg WIN.INI, .Xdefaults)
778 #if wxUSE_RESOURCES
779 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
780 {
781 if (file != wxT(""))
782 // Don't know what the correct cast should be, but it doesn't
783 // compile in BC++/16-bit without this cast.
784 #if !defined(__WIN32__)
785 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
786 #else
787 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
788 #endif
789 else
790 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
791 }
792
793 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
794 {
795 wxString buf;
796 buf.Printf(wxT("%.4f"), value);
797
798 return wxWriteResource(section, entry, buf, file);
799 }
800
801 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
802 {
803 wxString buf;
804 buf.Printf(wxT("%ld"), value);
805
806 return wxWriteResource(section, entry, buf, file);
807 }
808
809 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
810 {
811 wxString buf;
812 buf.Printf(wxT("%d"), value);
813
814 return wxWriteResource(section, entry, buf, file);
815 }
816
817 bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
818 {
819 static const wxChar defunkt[] = wxT("$$default");
820 if (file != wxT(""))
821 {
822 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
823 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
824 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
825 return FALSE;
826 }
827 else
828 {
829 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
830 (LPTSTR)wxBuffer, 1000);
831 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
832 return FALSE;
833 }
834 if (*value) delete[] (*value);
835 *value = copystring(wxBuffer);
836 return TRUE;
837 }
838
839 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
840 {
841 wxChar *s = NULL;
842 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
843 if (succ)
844 {
845 *value = (float)wxStrtod(s, NULL);
846 delete[] s;
847 return TRUE;
848 }
849 else return FALSE;
850 }
851
852 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
853 {
854 wxChar *s = NULL;
855 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
856 if (succ)
857 {
858 *value = wxStrtol(s, NULL, 10);
859 delete[] s;
860 return TRUE;
861 }
862 else return FALSE;
863 }
864
865 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
866 {
867 wxChar *s = NULL;
868 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
869 if (succ)
870 {
871 *value = (int)wxStrtol(s, NULL, 10);
872 delete[] s;
873 return TRUE;
874 }
875 else return FALSE;
876 }
877 #endif // wxUSE_RESOURCES
878
879 // ---------------------------------------------------------------------------
880 // helper functions for showing a "busy" cursor
881 // ---------------------------------------------------------------------------
882
883 static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
884 static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
885 static int gs_wxBusyCursorCount = 0;
886
887 extern HCURSOR wxGetCurrentBusyCursor()
888 {
889 return gs_wxBusyCursor;
890 }
891
892 // Set the cursor to the busy cursor for all windows
893 void wxBeginBusyCursor(wxCursor *cursor)
894 {
895 if ( gs_wxBusyCursorCount++ == 0 )
896 {
897 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
898 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
899 }
900 //else: nothing to do, already set
901 }
902
903 // Restore cursor to normal
904 void wxEndBusyCursor()
905 {
906 wxCHECK_RET( gs_wxBusyCursorCount > 0,
907 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
908
909 if ( --gs_wxBusyCursorCount == 0 )
910 {
911 ::SetCursor(gs_wxBusyCursorOld);
912
913 gs_wxBusyCursorOld = 0;
914 }
915 }
916
917 // TRUE if we're between the above two calls
918 bool wxIsBusy()
919 {
920 return (gs_wxBusyCursorCount > 0);
921 }
922
923 // Check whether this window wants to process messages, e.g. Stop button
924 // in long calculations.
925 bool wxCheckForInterrupt(wxWindow *wnd)
926 {
927 wxCHECK( wnd, FALSE );
928
929 MSG msg;
930 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
931 {
932 ::TranslateMessage(&msg);
933 ::DispatchMessage(&msg);
934 }
935
936 return TRUE;
937 }
938
939 // MSW only: get user-defined resource from the .res file.
940 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
941
942 wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
943 {
944 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
945 if ( hResource == 0 )
946 return NULL;
947
948 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
949 if ( hData == 0 )
950 return NULL;
951
952 wxChar *theText = (wxChar *)::LockResource(hData);
953 if ( !theText )
954 return NULL;
955
956 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
957 // so we need to find the length of the resource.
958 int len = ::SizeofResource(wxGetInstance(), hResource);
959 wxChar *s = new wxChar[len+1];
960 wxStrncpy(s,theText,len);
961 s[len]=0;
962
963 // wxChar *s = copystring(theText);
964
965 // Obsolete in WIN32
966 #ifndef __WIN32__
967 UnlockResource(hData);
968 #endif
969
970 // No need??
971 // GlobalFree(hData);
972
973 return s;
974 }
975
976 // ----------------------------------------------------------------------------
977 // get display info
978 // ----------------------------------------------------------------------------
979
980 // See also the wxGetMousePosition in window.cpp
981 // Deprecated: use wxPoint wxGetMousePosition() instead
982 void wxGetMousePosition( int* x, int* y )
983 {
984 POINT pt;
985 GetCursorPos( & pt );
986 if ( x ) *x = pt.x;
987 if ( y ) *y = pt.y;
988 };
989
990 // Return TRUE if we have a colour display
991 bool wxColourDisplay()
992 {
993 // this function is called from wxDC ctor so it is called a *lot* of times
994 // hence we optimize it a bit but doign the check only once
995 //
996 // this should be MT safe as only the GUI thread (holding the GUI mutex)
997 // can call us
998 static int s_isColour = -1;
999
1000 if ( s_isColour == -1 )
1001 {
1002 ScreenHDC dc;
1003 int noCols = ::GetDeviceCaps(dc, NUMCOLORS);
1004
1005 s_isColour = (noCols == -1) || (noCols > 2);
1006 }
1007
1008 return s_isColour != 0;
1009 }
1010
1011 // Returns depth of screen
1012 int wxDisplayDepth()
1013 {
1014 ScreenHDC dc;
1015 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
1016 }
1017
1018 // Get size of display
1019 void wxDisplaySize(int *width, int *height)
1020 {
1021 ScreenHDC dc;
1022
1023 if ( width ) *width = GetDeviceCaps(dc, HORZRES);
1024 if ( height ) *height = GetDeviceCaps(dc, VERTRES);
1025 }
1026
1027 void wxDisplaySizeMM(int *width, int *height)
1028 {
1029 ScreenHDC dc;
1030
1031 if ( width ) *width = GetDeviceCaps(dc, HORZSIZE);
1032 if ( height ) *height = GetDeviceCaps(dc, VERTSIZE);
1033 }
1034
1035 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
1036 {
1037 // Determine the desktop dimensions minus the taskbar and any other
1038 // special decorations...
1039 RECT r;
1040 SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
1041 if (x) *x = r.left;
1042 if (y) *y = r.top;
1043 if (width) *width = r.right - r.left;
1044 if (height) *height = r.bottom - r.top;
1045 }
1046
1047
1048 // ---------------------------------------------------------------------------
1049 // window information functions
1050 // ---------------------------------------------------------------------------
1051
1052 wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1053 {
1054 wxString str;
1055 int len = GetWindowTextLength((HWND)hWnd) + 1;
1056 GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1057 str.UngetWriteBuf();
1058
1059 return str;
1060 }
1061
1062 wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1063 {
1064 wxString str;
1065
1066 int len = 256; // some starting value
1067
1068 for ( ;; )
1069 {
1070 // as we've #undefined GetClassName we must now manually choose the
1071 // right function to call
1072 int count =
1073
1074 #ifndef __WIN32__
1075 GetClassName
1076 #else // Win32
1077 #ifdef UNICODE
1078 GetClassNameW
1079 #else // !Unicode
1080 #ifdef __TWIN32__
1081 GetClassName
1082 #else // !Twin32
1083 GetClassNameA
1084 #endif // Twin32/!Twin32
1085 #endif // Unicode/ANSI
1086 #endif // Win16/32
1087 ((HWND)hWnd, str.GetWriteBuf(len), len);
1088
1089 str.UngetWriteBuf();
1090 if ( count == len )
1091 {
1092 // the class name might have been truncated, retry with larger
1093 // buffer
1094 len *= 2;
1095 }
1096 else
1097 {
1098 break;
1099 }
1100 }
1101
1102 return str;
1103 }
1104
1105 WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
1106 {
1107 #ifndef __WIN32__
1108 return (WXWORD)GetWindowWord((HWND)hWnd, GWW_ID);
1109 #else // Win32
1110 return (WXWORD)GetWindowLong((HWND)hWnd, GWL_ID);
1111 #endif // Win16/32
1112 }
1113
1114 #endif // wxUSE_GUI
1115
1116 #if 0
1117 //------------------------------------------------------------------------
1118 // wild character routines
1119 //------------------------------------------------------------------------
1120
1121 bool wxIsWild( const wxString& pattern )
1122 {
1123 wxString tmp = pattern;
1124 char *pat = WXSTRINGCAST(tmp);
1125 while (*pat) {
1126 switch (*pat++) {
1127 case '?': case '*': case '[': case '{':
1128 return TRUE;
1129 case '\\':
1130 if (!*pat++)
1131 return FALSE;
1132 }
1133 }
1134 return FALSE;
1135 };
1136
1137
1138 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1139 {
1140 wxString tmp1 = pat;
1141 char *pattern = WXSTRINGCAST(tmp1);
1142 wxString tmp2 = text;
1143 char *str = WXSTRINGCAST(tmp2);
1144 char c;
1145 char *cp;
1146 bool done = FALSE, ret_code, ok;
1147 // Below is for vi fans
1148 const char OB = '{', CB = '}';
1149
1150 // dot_special means '.' only matches '.'
1151 if (dot_special && *str == '.' && *pattern != *str)
1152 return FALSE;
1153
1154 while ((*pattern != '\0') && (!done)
1155 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
1156 switch (*pattern) {
1157 case '\\':
1158 pattern++;
1159 if (*pattern != '\0')
1160 pattern++;
1161 break;
1162 case '*':
1163 pattern++;
1164 ret_code = FALSE;
1165 while ((*str!='\0')
1166 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1167 /*loop*/;
1168 if (ret_code) {
1169 while (*str != '\0')
1170 str++;
1171 while (*pattern != '\0')
1172 pattern++;
1173 }
1174 break;
1175 case '[':
1176 pattern++;
1177 repeat:
1178 if ((*pattern == '\0') || (*pattern == ']')) {
1179 done = TRUE;
1180 break;
1181 }
1182 if (*pattern == '\\') {
1183 pattern++;
1184 if (*pattern == '\0') {
1185 done = TRUE;
1186 break;
1187 }
1188 }
1189 if (*(pattern + 1) == '-') {
1190 c = *pattern;
1191 pattern += 2;
1192 if (*pattern == ']') {
1193 done = TRUE;
1194 break;
1195 }
1196 if (*pattern == '\\') {
1197 pattern++;
1198 if (*pattern == '\0') {
1199 done = TRUE;
1200 break;
1201 }
1202 }
1203 if ((*str < c) || (*str > *pattern)) {
1204 pattern++;
1205 goto repeat;
1206 }
1207 } else if (*pattern != *str) {
1208 pattern++;
1209 goto repeat;
1210 }
1211 pattern++;
1212 while ((*pattern != ']') && (*pattern != '\0')) {
1213 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1214 pattern++;
1215 pattern++;
1216 }
1217 if (*pattern != '\0') {
1218 pattern++, str++;
1219 }
1220 break;
1221 case '?':
1222 pattern++;
1223 str++;
1224 break;
1225 case OB:
1226 pattern++;
1227 while ((*pattern != CB) && (*pattern != '\0')) {
1228 cp = str;
1229 ok = TRUE;
1230 while (ok && (*cp != '\0') && (*pattern != '\0')
1231 && (*pattern != ',') && (*pattern != CB)) {
1232 if (*pattern == '\\')
1233 pattern++;
1234 ok = (*pattern++ == *cp++);
1235 }
1236 if (*pattern == '\0') {
1237 ok = FALSE;
1238 done = TRUE;
1239 break;
1240 } else if (ok) {
1241 str = cp;
1242 while ((*pattern != CB) && (*pattern != '\0')) {
1243 if (*++pattern == '\\') {
1244 if (*++pattern == CB)
1245 pattern++;
1246 }
1247 }
1248 } else {
1249 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1250 if (*++pattern == '\\') {
1251 if (*++pattern == CB || *pattern == ',')
1252 pattern++;
1253 }
1254 }
1255 }
1256 if (*pattern != '\0')
1257 pattern++;
1258 }
1259 break;
1260 default:
1261 if (*str == *pattern) {
1262 str++, pattern++;
1263 } else {
1264 done = TRUE;
1265 }
1266 }
1267 }
1268 while (*pattern == '*')
1269 pattern++;
1270 return ((*str == '\0') && (*pattern == '\0'));
1271 };
1272
1273 #endif // 0
1274
1275 #if 0
1276
1277 // maximum mumber of lines the output console should have
1278 static const WORD MAX_CONSOLE_LINES = 500;
1279
1280 BOOL WINAPI MyConsoleHandler( DWORD dwCtrlType ) { // control signal type
1281 FreeConsole();
1282 return TRUE;
1283 }
1284
1285 void wxRedirectIOToConsole()
1286 {
1287 int hConHandle;
1288 long lStdHandle;
1289 CONSOLE_SCREEN_BUFFER_INFO coninfo;
1290 FILE *fp;
1291
1292 // allocate a console for this app
1293 AllocConsole();
1294
1295 // set the screen buffer to be big enough to let us scroll text
1296 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
1297 &coninfo);
1298 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
1299 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
1300 coninfo.dwSize);
1301
1302 // redirect unbuffered STDOUT to the console
1303 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
1304 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1305 if(hConHandle <= 0) return;
1306 fp = _fdopen( hConHandle, "w" );
1307 *stdout = *fp;
1308 setvbuf( stdout, NULL, _IONBF, 0 );
1309
1310 // redirect unbuffered STDIN to the console
1311 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
1312 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1313 if(hConHandle <= 0) return;
1314 fp = _fdopen( hConHandle, "r" );
1315 *stdin = *fp;
1316 setvbuf( stdin, NULL, _IONBF, 0 );
1317
1318 // redirect unbuffered STDERR to the console
1319 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
1320 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1321 if(hConHandle <= 0) return;
1322 fp = _fdopen( hConHandle, "w" );
1323 *stderr = *fp;
1324 setvbuf( stderr, NULL, _IONBF, 0 );
1325
1326 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1327 // point to console as well
1328 ios::sync_with_stdio();
1329
1330 SetConsoleCtrlHandler(MyConsoleHandler, TRUE);
1331 }
1332 #else
1333 // Not supported
1334 void wxRedirectIOToConsole()
1335 {
1336 }
1337 #endif
1338
1339