1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 // #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
34 #include "wx/cursor.h"
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.
44 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
46 #include <winsock.h> // we use socket functions in wxGetFullHostName()
50 #include "wx/msw/private.h" // includes <windows.h>
54 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
62 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
63 #include <sys/unistd.h>
67 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
68 // this (3.1 I believe) and how to test for it.
69 // If this works for Borland 4.0 as well, then no worries.
73 // VZ: there is some code using NetXXX() functions to get the full user name:
74 // I don't think it's a good idea because they don't work under Win95 and
75 // seem to return the same as wxGetUserId() under NT. If you really want
76 // to use them, just #define USE_NET_API
83 #if defined(__WIN32__) && !defined(__WXWINE__)
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
97 //// BEGIN for console support: VC++ only
100 #include "wx/msw/msvcrt.h"
104 #include "wx/ioswrap.h"
106 #include "wx/ioswrap.h"
108 /* Need to undef new if including crtdbg.h */
117 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
118 # define new new(__TFILE__,__LINE__)
123 /// END for console support
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 // In the WIN.INI file
130 static const wxChar WX_SECTION
[] = wxT("wxWindows");
131 static const wxChar eUSERNAME
[] = wxT("UserName");
133 // these are only used under Win16
135 static const wxChar eHOSTNAME
[] = wxT("HostName");
136 static const wxChar eUSERID
[] = wxT("UserId");
139 // ============================================================================
141 // ============================================================================
143 // ----------------------------------------------------------------------------
144 // get host name and related
145 // ----------------------------------------------------------------------------
147 // Get hostname only (without domain name)
148 bool wxGetHostName(wxChar
*buf
, int maxSize
)
150 #if defined(__WIN32__) && !defined(__TWIN32__)
151 DWORD nSize
= maxSize
;
152 if ( !::GetComputerName(buf
, &nSize
) )
154 wxLogLastError(wxT("GetComputerName"));
162 const wxChar
*default_host
= wxT("noname");
164 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
165 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
167 wxStrncpy(buf
, sysname
, maxSize
- 1);
168 buf
[maxSize
] = wxT('\0');
169 return *buf
? TRUE
: FALSE
;
173 // get full hostname (with domain name if possible)
174 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
176 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
177 // TODO should use GetComputerNameEx() when available
179 if ( WSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
183 if ( gethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
185 // gethostname() won't usually include the DNS domain name, for
186 // this we need to work a bit more
187 if ( !strchr(bufA
, '.') )
189 struct hostent
*pHostEnt
= gethostbyname(bufA
);
193 // Windows will use DNS internally now
194 pHostEnt
= gethostbyaddr(pHostEnt
->h_addr
, 4, PF_INET
);
199 host
= pHostEnt
->h_name
;
208 wxStrncpy(buf
, host
, maxSize
);
215 return wxGetHostName(buf
, maxSize
);
218 // Get user ID e.g. jacs
219 bool wxGetUserId(wxChar
*buf
, int maxSize
)
221 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__)
222 DWORD nSize
= maxSize
;
223 if ( ::GetUserName(buf
, &nSize
) == 0 )
225 // actually, it does happen on Win9x if the user didn't log on
226 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
235 #else // Win16 or Win32s
237 const wxChar
*default_id
= wxT("anonymous");
239 // Can't assume we have NIS (PC-NFS) or some other ID daemon
241 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
242 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
244 // Use wxWindows configuration data (comming soon)
245 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
249 wxStrncpy(buf
, user
, maxSize
- 1);
252 return *buf
? TRUE
: FALSE
;
256 // Get user name e.g. Julian Smart
257 bool wxGetUserName(wxChar
*buf
, int maxSize
)
259 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
260 extern HANDLE g_hPenWin
; // PenWindows Running?
263 // PenWindows Does have a user concept!
264 // Get the current owner of the recognizer
265 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
266 strncpy(buf
, wxBuffer
, maxSize
- 1);
272 CHAR szUserName
[256];
273 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
276 // TODO how to get the domain name?
279 // the code is based on the MSDN example (also see KB article Q119670)
280 WCHAR wszUserName
[256]; // Unicode user name
281 WCHAR wszDomain
[256];
284 USER_INFO_2
*ui2
; // User structure
286 // Convert ANSI user name and domain to Unicode
287 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
288 wszUserName
, WXSIZEOF(wszUserName
) );
289 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
290 wszDomain
, WXSIZEOF(wszDomain
) );
292 // Get the computer name of a DC for the domain.
293 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
295 wxLogError(wxT("Can not find domain controller"));
300 // Look up the user on the DC
301 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
302 (LPWSTR
)&wszUserName
,
303 2, // level - we want USER_INFO_2
311 case NERR_InvalidComputer
:
312 wxLogError(wxT("Invalid domain controller name."));
316 case NERR_UserNotFound
:
317 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
322 wxLogSysError(wxT("Can't get information about user"));
327 // Convert the Unicode full name to ANSI
328 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
329 buf
, maxSize
, NULL
, NULL
);
334 wxLogError(wxT("Couldn't look up full user name."));
337 #else // !USE_NET_API
338 // Could use NIS, MS-Mail or other site specific programs
339 // Use wxWindows configuration data
340 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
343 ok
= wxGetUserId(buf
, maxSize
);
348 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
356 const wxChar
* wxGetHomeDir(wxString
*pstr
)
358 wxString
& strDir
= *pstr
;
360 #if defined(__UNIX__) && !defined(__TWIN32__)
361 const wxChar
*szHome
= wxGetenv("HOME");
362 if ( szHome
== NULL
) {
364 wxLogWarning(_("can't find user's HOME, using current directory."));
370 // add a trailing slash if needed
371 if ( strDir
.Last() != wxT('/') )
375 const wxChar
*szHome
= wxGetenv(wxT("HOMEDRIVE"));
376 if ( szHome
!= NULL
)
378 szHome
= wxGetenv(wxT("HOMEPATH"));
379 if ( szHome
!= NULL
) {
382 // the idea is that under NT these variables have default values
383 // of "%systemdrive%:" and "\\". As we don't want to create our
384 // config files in the root directory of the system drive, we will
385 // create it in our program's dir. However, if the user took care
386 // to set HOMEPATH to something other than "\\", we suppose that he
387 // knows what he is doing and use the supplied value.
388 if ( wxStrcmp(szHome
, wxT("\\")) != 0 )
389 return strDir
.c_str();
393 // Win16 has no idea about home, so use the working directory instead
396 // 260 was taken from windef.h
402 ::GetModuleFileName(::GetModuleHandle(NULL
),
403 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
404 strPath
.UngetWriteBuf();
406 // extract the dir name
407 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
411 return strDir
.c_str();
414 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
416 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
417 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
418 // static buffer and sometimes I don't even know what.
419 static wxString s_home
;
421 return (wxChar
*)wxGetHomeDir(&s_home
);
424 bool wxDirExists(const wxString
& dir
)
426 #if defined(__WIN32__)
427 DWORD attribs
= GetFileAttributes(dir
);
428 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
431 struct ffblk fileInfo
;
433 struct find_t fileInfo
;
435 // In Borland findfirst has a different argument
436 // ordering from _dos_findfirst. But _dos_findfirst
437 // _should_ be ok in both MS and Borland... why not?
439 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
440 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
442 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
443 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
448 // ----------------------------------------------------------------------------
450 // ----------------------------------------------------------------------------
452 bool wxGetEnv(const wxString
& var
, wxString
*value
)
455 const wxChar
* ret
= wxGetenv(var
);
464 // first get the size of the buffer
465 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
468 // this means that there is no such variable
474 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
475 value
->UngetWriteBuf();
482 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
484 // some compilers have putenv() or _putenv() or _wputenv() but it's better
485 // to always use Win32 function directly instead of dealing with them
486 #if defined(__WIN32__)
487 if ( !::SetEnvironmentVariable(var
, value
) )
489 wxLogLastError(_T("SetEnvironmentVariable"));
495 #else // no way to set env vars
500 // ----------------------------------------------------------------------------
501 // process management
502 // ----------------------------------------------------------------------------
506 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
507 struct wxFindByPidParams
509 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
511 // the HWND used to return the result
514 // the PID we're looking from
518 // wxKill helper: EnumWindows() callback which is used to find the first (top
519 // level) window belonging to the given process
520 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
523 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
525 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
526 if ( pid
== params
->pid
)
528 // remember the window we found
531 // return FALSE to stop the enumeration
535 // continue enumeration
541 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
544 // get the process handle to operate on
545 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
547 PROCESS_QUERY_INFORMATION
,
548 FALSE
, // not inheritable
550 if ( hProcess
== NULL
)
554 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
556 *krc
= wxKILL_ACCESS_DENIED
;
560 *krc
= wxKILL_NO_PROCESS
;
571 // kill the process forcefully returning -1 as error code
572 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
574 wxLogSysError(_("Failed to kill process %d"), pid
);
578 // this is not supposed to happen if we could open the
588 // do nothing, we just want to test for process existence
592 // any other signal means "terminate"
594 wxFindByPidParams params
;
595 params
.pid
= (DWORD
)pid
;
597 // EnumWindows() has nice semantics: it returns 0 if it found
598 // something or if an error occured and non zero if it
599 // enumerated all the window
600 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
602 // did we find any window?
605 // tell the app to close
607 // NB: this is the harshest way, the app won't have
608 // opportunity to save any files, for example, but
609 // this is probably what we want here. If not we
610 // can also use SendMesageTimeout(WM_CLOSE)
611 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
613 wxLogLastError(_T("PostMessage(WM_QUIT)"));
616 else // it was an error then
618 wxLogLastError(_T("EnumWindows"));
623 else // no windows for this PID
640 // as we wait for a short time, we can use just WaitForSingleObject()
641 // and not MsgWaitForMultipleObjects()
642 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
645 // process terminated
646 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
648 wxLogLastError(_T("GetExitCodeProcess"));
653 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
657 wxLogLastError(_T("WaitForSingleObject"));
672 // just to suppress the warnings about uninitialized variable
676 ::CloseHandle(hProcess
);
678 // the return code is the same as from Unix kill(): 0 if killed
679 // successfully or -1 on error
680 if ( sig
== wxSIGNONE
)
682 if ( ok
&& rc
== STILL_ACTIVE
)
684 // there is such process => success
690 if ( ok
&& rc
!= STILL_ACTIVE
)
697 wxFAIL_MSG( _T("not implemented") );
698 #endif // Win32/Win16
704 // Execute a program in an Interactive Shell
705 bool wxShell(const wxString
& command
)
707 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
709 shell
= wxT("\\COMMAND.COM");
719 // pass the command to execute to the command processor
720 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
723 return wxExecute(cmd
, TRUE
/* sync */) != 0;
726 // ----------------------------------------------------------------------------
728 // ----------------------------------------------------------------------------
730 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
731 long wxGetFreeMemory()
733 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
734 MEMORYSTATUS memStatus
;
735 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
736 GlobalMemoryStatus(&memStatus
);
737 return memStatus
.dwAvailPhys
;
739 return (long)GetFreeSpace(0);
746 ::MessageBeep((UINT
)-1); // default sound
749 wxString
wxGetOsDescription()
757 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
758 if ( ::GetVersionEx(&info
) )
760 switch ( info
.dwPlatformId
)
762 case VER_PLATFORM_WIN32s
:
763 str
= _("Win32s on Windows 3.1");
766 case VER_PLATFORM_WIN32_WINDOWS
:
767 str
.Printf(_("Windows 9%c"),
768 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
769 if ( !wxIsEmpty(info
.szCSDVersion
) )
771 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
775 case VER_PLATFORM_WIN32_NT
:
776 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
780 if ( !wxIsEmpty(info
.szCSDVersion
) )
782 str
<< _T(", ") << info
.szCSDVersion
;
790 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
795 return _("Windows 3.1");
799 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
801 #if defined(__WIN32__) && !defined(__SC__)
805 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
806 if ( ::GetVersionEx(&info
) )
809 *majorVsn
= info
.dwMajorVersion
;
811 *minorVsn
= info
.dwMinorVersion
;
813 switch ( info
.dwPlatformId
)
815 case VER_PLATFORM_WIN32s
:
818 case VER_PLATFORM_WIN32_WINDOWS
:
821 case VER_PLATFORM_WIN32_NT
:
826 return wxWINDOWS
; // error if we get here, return generic value
828 int retValue
= wxWINDOWS
;
829 #ifdef __WINDOWS_386__
832 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
833 extern HANDLE g_hPenWin
;
834 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
847 // ----------------------------------------------------------------------------
849 // ----------------------------------------------------------------------------
855 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
856 static bool gs_inTimer
= FALSE
;
858 class wxSleepTimer
: public wxTimer
861 virtual void Notify()
868 static wxTimer
*wxTheSleepTimer
= NULL
;
870 void wxUsleep(unsigned long milliseconds
)
873 ::Sleep(milliseconds
);
878 wxTheSleepTimer
= new wxSleepTimer
;
880 wxTheSleepTimer
->Start(milliseconds
);
883 if (wxTheApp
->Pending())
884 wxTheApp
->Dispatch();
886 delete wxTheSleepTimer
;
887 wxTheSleepTimer
= NULL
;
888 #endif // Win32/!Win32
891 void wxSleep(int nSecs
)
896 wxTheSleepTimer
= new wxSleepTimer
;
898 wxTheSleepTimer
->Start(nSecs
*1000);
901 if (wxTheApp
->Pending())
902 wxTheApp
->Dispatch();
904 delete wxTheSleepTimer
;
905 wxTheSleepTimer
= NULL
;
908 // Consume all events until no more left
914 #endif // wxUSE_TIMER
916 #elif defined(__WIN32__) // wxUSE_GUI
918 void wxUsleep(unsigned long milliseconds
)
920 ::Sleep(milliseconds
);
923 void wxSleep(int nSecs
)
925 wxUsleep(1000*nSecs
);
928 #endif // wxUSE_GUI/!wxUSE_GUI
930 // ----------------------------------------------------------------------------
931 // deprecated (in favour of wxLog) log functions
932 // ----------------------------------------------------------------------------
936 // Output a debug mess., in a system dependent fashion.
937 void wxDebugMsg(const wxChar
*fmt
...)
940 static wxChar buffer
[512];
942 if (!wxTheApp
->GetWantDebugOutput())
947 wvsprintf(buffer
,fmt
,ap
) ;
948 OutputDebugString((LPCTSTR
)buffer
) ;
953 // Non-fatal error: pop up message box and (possibly) continue
954 void wxError(const wxString
& msg
, const wxString
& title
)
956 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
957 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
958 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
962 // Fatal error: pop up message box and abort
963 void wxFatalError(const wxString
& msg
, const wxString
& title
)
965 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
966 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
969 // ----------------------------------------------------------------------------
970 // functions to work with .INI files
971 // ----------------------------------------------------------------------------
973 // Reading and writing resources (eg WIN.INI, .Xdefaults)
975 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
978 // Don't know what the correct cast should be, but it doesn't
979 // compile in BC++/16-bit without this cast.
980 #if !defined(__WIN32__)
981 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
983 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
986 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
989 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
992 buf
.Printf(wxT("%.4f"), value
);
994 return wxWriteResource(section
, entry
, buf
, file
);
997 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1000 buf
.Printf(wxT("%ld"), value
);
1002 return wxWriteResource(section
, entry
, buf
, file
);
1005 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1008 buf
.Printf(wxT("%d"), value
);
1010 return wxWriteResource(section
, entry
, buf
, file
);
1013 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1015 static const wxChar defunkt
[] = wxT("$$default");
1016 if (file
!= wxT(""))
1018 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1019 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1020 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1025 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1026 (LPTSTR
)wxBuffer
, 1000);
1027 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1030 if (*value
) delete[] (*value
);
1031 *value
= copystring(wxBuffer
);
1035 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1038 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1041 *value
= (float)wxStrtod(s
, NULL
);
1048 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1051 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1054 *value
= wxStrtol(s
, NULL
, 10);
1061 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1064 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1067 *value
= (int)wxStrtol(s
, NULL
, 10);
1073 #endif // wxUSE_RESOURCES
1075 // ---------------------------------------------------------------------------
1076 // helper functions for showing a "busy" cursor
1077 // ---------------------------------------------------------------------------
1079 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1080 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1081 static int gs_wxBusyCursorCount
= 0;
1083 extern HCURSOR
wxGetCurrentBusyCursor()
1085 return gs_wxBusyCursor
;
1088 // Set the cursor to the busy cursor for all windows
1089 void wxBeginBusyCursor(wxCursor
*cursor
)
1091 if ( gs_wxBusyCursorCount
++ == 0 )
1093 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1094 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1096 //else: nothing to do, already set
1099 // Restore cursor to normal
1100 void wxEndBusyCursor()
1102 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1103 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1105 if ( --gs_wxBusyCursorCount
== 0 )
1107 ::SetCursor(gs_wxBusyCursorOld
);
1109 gs_wxBusyCursorOld
= 0;
1113 // TRUE if we're between the above two calls
1116 return (gs_wxBusyCursorCount
> 0);
1119 // Check whether this window wants to process messages, e.g. Stop button
1120 // in long calculations.
1121 bool wxCheckForInterrupt(wxWindow
*wnd
)
1123 wxCHECK( wnd
, FALSE
);
1126 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1128 ::TranslateMessage(&msg
);
1129 ::DispatchMessage(&msg
);
1135 // MSW only: get user-defined resource from the .res file.
1136 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1138 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1140 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1141 if ( hResource
== 0 )
1144 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1148 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1152 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1153 // so we need to find the length of the resource.
1154 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1155 wxChar
*s
= new wxChar
[len
+1];
1156 wxStrncpy(s
,theText
,len
);
1159 // wxChar *s = copystring(theText);
1161 // Obsolete in WIN32
1163 UnlockResource(hData
);
1167 // GlobalFree(hData);
1172 // ----------------------------------------------------------------------------
1174 // ----------------------------------------------------------------------------
1176 // See also the wxGetMousePosition in window.cpp
1177 // Deprecated: use wxPoint wxGetMousePosition() instead
1178 void wxGetMousePosition( int* x
, int* y
)
1181 GetCursorPos( & pt
);
1186 // Return TRUE if we have a colour display
1187 bool wxColourDisplay()
1189 // this function is called from wxDC ctor so it is called a *lot* of times
1190 // hence we optimize it a bit but doign the check only once
1192 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1194 static int s_isColour
= -1;
1196 if ( s_isColour
== -1 )
1199 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1201 s_isColour
= (noCols
== -1) || (noCols
> 2);
1204 return s_isColour
!= 0;
1207 // Returns depth of screen
1208 int wxDisplayDepth()
1211 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1214 // Get size of display
1215 void wxDisplaySize(int *width
, int *height
)
1219 if ( width
) *width
= GetDeviceCaps(dc
, HORZRES
);
1220 if ( height
) *height
= GetDeviceCaps(dc
, VERTRES
);
1223 void wxDisplaySizeMM(int *width
, int *height
)
1227 if ( width
) *width
= GetDeviceCaps(dc
, HORZSIZE
);
1228 if ( height
) *height
= GetDeviceCaps(dc
, VERTSIZE
);
1231 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1235 wxDisplaySize(width
, height
);
1237 // Determine the desktop dimensions minus the taskbar and any other
1238 // special decorations...
1241 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1244 if (width
) *width
= r
.right
- r
.left
;
1245 if (height
) *height
= r
.bottom
- r
.top
;
1250 // ---------------------------------------------------------------------------
1251 // window information functions
1252 // ---------------------------------------------------------------------------
1254 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1257 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1258 GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1259 str
.UngetWriteBuf();
1264 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1268 int len
= 256; // some starting value
1272 // as we've #undefined GetClassName we must now manually choose the
1273 // right function to call
1286 #endif // Twin32/!Twin32
1287 #endif // Unicode/ANSI
1289 ((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1291 str
.UngetWriteBuf();
1294 // the class name might have been truncated, retry with larger
1307 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1310 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1312 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1320 // ----------------------------------------------------------------------------
1322 // ----------------------------------------------------------------------------
1324 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1328 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1329 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1330 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1331 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1333 *x
*= (iWidthMM
* 100);
1335 *y
*= (iHeightMM
* 100);
1339 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1343 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1344 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1345 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1346 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1349 *x
/= (iWidthMM
* 100);
1351 *y
/= (iHeightMM
* 100);
1357 //------------------------------------------------------------------------
1358 // wild character routines
1359 //------------------------------------------------------------------------
1361 bool wxIsWild( const wxString
& pattern
)
1363 wxString tmp
= pattern
;
1364 char *pat
= WXSTRINGCAST(tmp
);
1367 case '?': case '*': case '[': case '{':
1378 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1380 wxString tmp1
= pat
;
1381 char *pattern
= WXSTRINGCAST(tmp1
);
1382 wxString tmp2
= text
;
1383 char *str
= WXSTRINGCAST(tmp2
);
1386 bool done
= FALSE
, ret_code
, ok
;
1387 // Below is for vi fans
1388 const char OB
= '{', CB
= '}';
1390 // dot_special means '.' only matches '.'
1391 if (dot_special
&& *str
== '.' && *pattern
!= *str
)
1394 while ((*pattern
!= '\0') && (!done
)
1395 && (((*str
=='\0')&&((*pattern
==OB
)||(*pattern
=='*')))||(*str
!='\0'))) {
1399 if (*pattern
!= '\0')
1406 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1409 while (*str
!= '\0')
1411 while (*pattern
!= '\0')
1418 if ((*pattern
== '\0') || (*pattern
== ']')) {
1422 if (*pattern
== '\\') {
1424 if (*pattern
== '\0') {
1429 if (*(pattern
+ 1) == '-') {
1432 if (*pattern
== ']') {
1436 if (*pattern
== '\\') {
1438 if (*pattern
== '\0') {
1443 if ((*str
< c
) || (*str
> *pattern
)) {
1447 } else if (*pattern
!= *str
) {
1452 while ((*pattern
!= ']') && (*pattern
!= '\0')) {
1453 if ((*pattern
== '\\') && (*(pattern
+ 1) != '\0'))
1457 if (*pattern
!= '\0') {
1467 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
1470 while (ok
&& (*cp
!= '\0') && (*pattern
!= '\0')
1471 && (*pattern
!= ',') && (*pattern
!= CB
)) {
1472 if (*pattern
== '\\')
1474 ok
= (*pattern
++ == *cp
++);
1476 if (*pattern
== '\0') {
1482 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
1483 if (*++pattern
== '\\') {
1484 if (*++pattern
== CB
)
1489 while (*pattern
!=CB
&& *pattern
!=',' && *pattern
!='\0') {
1490 if (*++pattern
== '\\') {
1491 if (*++pattern
== CB
|| *pattern
== ',')
1496 if (*pattern
!= '\0')
1501 if (*str
== *pattern
) {
1508 while (*pattern
== '*')
1510 return ((*str
== '\0') && (*pattern
== '\0'));
1517 // maximum mumber of lines the output console should have
1518 static const WORD MAX_CONSOLE_LINES
= 500;
1520 BOOL WINAPI
MyConsoleHandler( DWORD dwCtrlType
) { // control signal type
1525 void wxRedirectIOToConsole()
1529 CONSOLE_SCREEN_BUFFER_INFO coninfo
;
1532 // allocate a console for this app
1535 // set the screen buffer to be big enough to let us scroll text
1536 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
),
1538 coninfo
.dwSize
.Y
= MAX_CONSOLE_LINES
;
1539 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE
),
1542 // redirect unbuffered STDOUT to the console
1543 lStdHandle
= (long)GetStdHandle(STD_OUTPUT_HANDLE
);
1544 hConHandle
= _open_osfhandle(lStdHandle
, _O_TEXT
);
1545 if(hConHandle
<= 0) return;
1546 fp
= _fdopen( hConHandle
, "w" );
1548 setvbuf( stdout
, NULL
, _IONBF
, 0 );
1550 // redirect unbuffered STDIN to the console
1551 lStdHandle
= (long)GetStdHandle(STD_INPUT_HANDLE
);
1552 hConHandle
= _open_osfhandle(lStdHandle
, _O_TEXT
);
1553 if(hConHandle
<= 0) return;
1554 fp
= _fdopen( hConHandle
, "r" );
1556 setvbuf( stdin
, NULL
, _IONBF
, 0 );
1558 // redirect unbuffered STDERR to the console
1559 lStdHandle
= (long)GetStdHandle(STD_ERROR_HANDLE
);
1560 hConHandle
= _open_osfhandle(lStdHandle
, _O_TEXT
);
1561 if(hConHandle
<= 0) return;
1562 fp
= _fdopen( hConHandle
, "w" );
1564 setvbuf( stderr
, NULL
, _IONBF
, 0 );
1566 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1567 // point to console as well
1568 ios::sync_with_stdio();
1570 SetConsoleCtrlHandler(MyConsoleHandler
, TRUE
);
1574 void wxRedirectIOToConsole()