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