1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 // Note: this is done in utilscmn.cpp now.
14 // #pragma implementation
15 // #pragma implementation "utils.h"
18 // For compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
29 #include "wx/cursor.h"
32 #include "wx/msw/private.h"
43 #include <sys/unistd.h>
53 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
54 // this (3.1 I believe) and how to test for it.
55 // If this works for Borland 4.0 as well, then no worries.
71 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
77 // In the WIN.INI file
78 static const char WX_SECTION
[] = "wxWindows";
79 static const char eHOSTNAME
[] = "HostName";
80 static const char eUSERID
[] = "UserId";
81 static const char eUSERNAME
[] = "UserName";
83 // For the following functions we SHOULD fill in support
84 // for Windows-NT (which I don't know) as I assume it begin
85 // a POSIX Unix (so claims MS) that it has some special
86 // functions beyond those provided by WinSock
88 // Get full hostname (eg. DoDo.BSn-Germany.crg.de)
89 bool wxGetHostName(char *buf
, int maxSize
)
92 DWORD nSize
= maxSize
;
93 return (::GetComputerName(buf
, &nSize
) != 0);
96 const char *default_host
= "noname";
98 if ((sysname
= getenv("SYSTEM_NAME")) == NULL
) {
99 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
101 strncpy(buf
, sysname
, maxSize
- 1);
103 return *buf
? TRUE
: FALSE
;
107 // Get user ID e.g. jacs
108 bool wxGetUserId(char *buf
, int maxSize
)
110 #if defined(__WIN32__) && !defined(__win32s__) && 0
111 // Gets the current user's full name according to the MS article PSS ID
113 // Seems to be the same as the login name for me?
114 char *UserName
= new char[256];
115 char *Domain
= new char[256];
116 DWORD maxCharacters
= 255;
117 GetUserName( UserName
, &maxCharacters
);
118 GetComputerName( Domain
, &maxCharacters
);
120 WCHAR wszUserName
[256]; // Unicode user name
121 WCHAR wszDomain
[256];
124 struct _SERVER_INFO_100
*si100
; // Server structure
125 struct _USER_INFO_2
*ui
; // User structure
127 // Convert ASCII user name and domain to Unicode.
129 MultiByteToWideChar( CP_ACP
, 0, UserName
,
130 strlen(UserName
)+1, wszUserName
, sizeof(wszUserName
) );
131 MultiByteToWideChar( CP_ACP
, 0, Domain
,
132 strlen(Domain
)+1, wszDomain
, sizeof(wszDomain
) );
134 // Get the computer name of a DC for the specified domain.
135 // >If you get a link error on this, include netapi32.lib<
137 NetGetDCName( NULL
, wszDomain
, &ComputerName
);
139 // Look up the user on the DC.
141 if(NetUserGetInfo( (LPWSTR
) ComputerName
,
142 (LPWSTR
) &wszUserName
, 2, (LPBYTE
*) &ui
))
144 printf( "Error getting user information.\n" );
148 // Convert the Unicode full name to ASCII.
150 WideCharToMultiByte( CP_ACP
, 0, ui
->usri2_full_name
,
151 -1, buf
, 256, NULL
, NULL
);
155 DWORD nSize = maxSize;
156 return ::GetUserName(buf, &nSize);
160 const char *default_id
= "anonymous";
162 // Can't assume we have NIS (PC-NFS) or some other ID daemon
164 if ( (user
= getenv("USER")) == NULL
&&
165 (user
= getenv("LOGNAME")) == NULL
) {
166 // Use wxWindows configuration data (comming soon)
167 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
169 strncpy(buf
, user
, maxSize
- 1);
170 return *buf
? TRUE
: FALSE
;
174 // Get user name e.g. Julian Smart
175 bool wxGetUserName(char *buf
, int maxSize
)
177 const char *default_name
= "Unknown User";
178 #if defined(__WIN32__)
180 DWORD nSize = maxSize;
181 In VC++ 4.0, results in unresolved symbol __imp__GetUserNameA
182 if (GetUserName(buf, &nSize))
186 // Could use NIS, MS-Mail or other site specific programs
187 // Use wxWindows configuration data
188 GetProfileString(WX_SECTION
, eUSERNAME
, default_name
, buf
, maxSize
- 1);
189 return *buf
? TRUE
: FALSE
;
192 #if !defined(__WATCOMC__) && !defined(__GNUWIN32__) && wxUSE_PENWINDOWS
193 extern HANDLE g_hPenWin
; // PenWindows Running?
196 // PenWindows Does have a user concept!
197 // Get the current owner of the recognizer
198 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
199 strncpy(buf
, wxBuffer
, maxSize
- 1);
204 // Could use NIS, MS-Mail or other site specific programs
205 // Use wxWindows configuration data
206 GetProfileString(WX_SECTION
, eUSERNAME
, default_name
, buf
, maxSize
- 1);
208 return *buf
? TRUE
: FALSE
;
212 int wxKill(long pid
, int sig
)
218 // Execute a program in an Interactive Shell
221 wxShell(const wxString
& command
)
224 if ((shell
= getenv("COMSPEC")) == NULL
)
225 shell
= "\\COMMAND.COM";
229 sprintf(tmp
, "%s /c %s", shell
, WXSTRINGCAST command
);
233 return (wxExecute((char *)tmp
, FALSE
) != 0);
236 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
237 long wxGetFreeMemory(void)
239 #if defined(__WIN32__) && !defined(__BORLANDC__)
240 MEMORYSTATUS memStatus
;
241 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
242 GlobalMemoryStatus(&memStatus
);
243 return memStatus
.dwAvailPhys
;
245 return (long)GetFreeSpace(0);
249 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
250 static bool inTimer
= FALSE
;
251 class wxSleepTimer
: public wxTimer
254 inline void Notify(void)
261 static wxTimer
*wxTheSleepTimer
= NULL
;
263 void wxSleep(int nSecs
)
265 #if 0 // WIN32 hangs app
271 wxTheSleepTimer
= new wxSleepTimer
;
273 wxTheSleepTimer
->Start(nSecs
*1000);
276 if (wxTheApp
->Pending())
277 wxTheApp
->Dispatch();
279 delete wxTheSleepTimer
;
280 wxTheSleepTimer
= NULL
;
284 // Consume all events until no more left
285 void wxFlushEvents(void)
290 // Output a debug mess., in a system dependent fashion.
291 void wxDebugMsg(const char *fmt
...)
294 static char buffer
[512];
296 if (!wxTheApp
->GetWantDebugOutput())
301 wvsprintf(buffer
,fmt
,ap
) ;
302 OutputDebugString((LPCSTR
)buffer
) ;
307 // Non-fatal error: pop up message box and (possibly) continue
308 void wxError(const wxString
& msg
, const wxString
& title
)
310 sprintf(wxBuffer
, "%s\nContinue?", WXSTRINGCAST msg
);
311 if (MessageBox(NULL
, (LPCSTR
)wxBuffer
, (LPCSTR
)WXSTRINGCAST title
,
312 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
316 // Fatal error: pop up message box and abort
317 void wxFatalError(const wxString
& msg
, const wxString
& title
)
319 sprintf(wxBuffer
, "%s: %s", WXSTRINGCAST title
, WXSTRINGCAST msg
);
320 FatalAppExit(0, (LPCSTR
)wxBuffer
);
327 Beep(1000,1000) ; // 1kHz during 1 sec.
333 // Chris Breeze 27/5/98: revised WIN32 code to
334 // detect WindowsNT correctly
335 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
337 extern char *wxOsVersion
;
338 if (majorVsn
) *majorVsn
= 0;
339 if (minorVsn
) *minorVsn
= 0;
343 memset(&info
, 0, sizeof(OSVERSIONINFO
));
344 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
345 if (GetVersionEx(&info
))
347 if (majorVsn
) *majorVsn
= info
.dwMajorVersion
;
348 if (minorVsn
) *minorVsn
= info
.dwMinorVersion
;
349 switch (info
.dwPlatformId
)
351 case VER_PLATFORM_WIN32s
:
354 case VER_PLATFORM_WIN32_WINDOWS
:
357 case VER_PLATFORM_WIN32_NT
:
362 return wxWINDOWS
; // error if we get here, return generic value
366 # ifdef __WINDOWS_386__
369 # if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
370 extern HANDLE g_hPenWin
;
371 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
374 // @@@@ To be completed. I don't have the manual here...
375 if (majorVsn
) *majorVsn
= 3 ;
376 if (minorVsn
) *minorVsn
= 1 ;
381 // Reading and writing resources (eg WIN.INI, .Xdefaults)
383 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
386 return (WritePrivateProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)value
, (LPCSTR
)WXSTRINGCAST file
) != 0);
388 return (WriteProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)WXSTRINGCAST value
) != 0);
391 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
394 sprintf(buf
, "%.4f", value
);
395 return wxWriteResource(section
, entry
, buf
, file
);
398 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
401 sprintf(buf
, "%ld", value
);
402 return wxWriteResource(section
, entry
, buf
, file
);
405 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
408 sprintf(buf
, "%d", value
);
409 return wxWriteResource(section
, entry
, buf
, file
);
412 bool wxGetResource(const wxString
& section
, const wxString
& entry
, char **value
, const wxString
& file
)
414 static const char defunkt
[] = "$$default";
417 int n
= GetPrivateProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)defunkt
,
418 (LPSTR
)wxBuffer
, 1000, (LPCSTR
)WXSTRINGCAST file
);
419 if (n
== 0 || strcmp(wxBuffer
, defunkt
) == 0)
424 int n
= GetProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)defunkt
,
425 (LPSTR
)wxBuffer
, 1000);
426 if (n
== 0 || strcmp(wxBuffer
, defunkt
) == 0)
429 if (*value
) delete[] (*value
);
430 *value
= copystring(wxBuffer
);
434 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
437 bool succ
= wxGetResource(section
, entry
, (char **)&s
, file
);
440 *value
= (float)strtod(s
, NULL
);
447 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
450 bool succ
= wxGetResource(section
, entry
, (char **)&s
, file
);
453 *value
= strtol(s
, NULL
, 10);
460 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
463 bool succ
= wxGetResource(section
, entry
, (char **)&s
, file
);
466 *value
= (int)strtol(s
, NULL
, 10);
472 #endif // wxUSE_RESOURCES
475 static HCURSOR wxBusyCursorOld
= 0;
476 static int wxBusyCursorCount
= 0;
478 // Set the cursor to the busy cursor for all windows
479 void wxBeginBusyCursor(wxCursor
*cursor
)
481 wxBusyCursorCount
++;
482 if (wxBusyCursorCount
== 1)
484 wxBusyCursorOld
= ::SetCursor((HCURSOR
) cursor
->GetHCURSOR());
488 (void)::SetCursor((HCURSOR
) cursor
->GetHCURSOR());
492 // Restore cursor to normal
493 void wxEndBusyCursor(void)
495 if (wxBusyCursorCount
== 0)
498 wxBusyCursorCount
--;
499 if (wxBusyCursorCount
== 0)
501 ::SetCursor(wxBusyCursorOld
);
506 // TRUE if we're between the above two calls
509 return (wxBusyCursorCount
> 0);
512 const char* WXDLLEXPORT
wxGetHomeDir(wxString
*pstr
)
514 wxString
& strDir
= *pstr
;
517 const char *szHome
= getenv("HOME");
518 if ( szHome
== NULL
) {
520 wxLogWarning(_("can't find user's HOME, using current directory."));
526 // add a trailing slash if needed
527 if ( strDir
.Last() != '/' )
531 const char *szHome
= getenv("HOMEDRIVE");
532 if ( szHome
!= NULL
)
534 szHome
= getenv("HOMEPATH");
535 if ( szHome
!= NULL
) {
538 // the idea is that under NT these variables have default values
539 // of "%systemdrive%:" and "\\". As we don't want to create our
540 // config files in the root directory of the system drive, we will
541 // create it in our program's dir. However, if the user took care
542 // to set HOMEPATH to something other than "\\", we suppose that he
543 // knows what he is doing and use the supplied value.
544 if ( strcmp(szHome
, "\\") != 0 )
545 return strDir
.c_str();
549 // Win16 has no idea about home, so use the working directory instead
552 // 260 was taken from windef.h
558 ::GetModuleFileName(::GetModuleHandle(NULL
),
559 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
560 strPath
.UngetWriteBuf();
562 // extract the dir name
563 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
567 return strDir
.c_str();
571 char *wxGetUserHome (const wxString
& user
)
574 wxString
user1(user
);
578 if (wxGetUserId(tmp
, sizeof(tmp
)/sizeof(char))) {
579 // Guests belong in the temp dir
580 if (Stricmp(tmp
, "annonymous") == 0) {
581 if ((home
= getenv("TMP")) != NULL
||
582 (home
= getenv("TMPDIR")) != NULL
||
583 (home
= getenv("TEMP")) != NULL
)
584 return *home
? home
: "\\";
586 if (Stricmp(tmp
, WXSTRINGCAST user1
) == 0)
591 if ((home
= getenv("HOME")) != NULL
)
593 strcpy(wxBuffer
, home
);
594 Unix2DosFilename(wxBuffer
);
597 return NULL
; // No home known!
600 // Check whether this window wants to process messages, e.g. Stop button
601 // in long calculations.
602 bool wxCheckForInterrupt(wxWindow
*wnd
)
606 HWND win
= (HWND
) wnd
->GetHWND();
607 while(PeekMessage(&msg
,win
,0,0,PM_REMOVE
)){
608 TranslateMessage(&msg
);
609 DispatchMessage(&msg
);
611 return TRUE
;//*** temporary?
614 wxError("wnd==NULL !!!");
615 return FALSE
;//*** temporary?
619 // MSW only: get user-defined resource from the .res file.
620 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
623 char *wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
627 HRSRC hResource
= ::FindResource(wxGetInstance(), WXSTRINGCAST resourceName
, WXSTRINGCAST resourceType
);
630 HRSRC hResource
= ::FindResourceW(wxGetInstance(), WXSTRINGCAST resourceName
, WXSTRINGCAST resourceType
);
632 HRSRC hResource
= ::FindResourceA(wxGetInstance(), WXSTRINGCAST resourceName
, WXSTRINGCAST resourceType
);
638 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
641 char *theText
= (char *)LockResource(hData
);
645 s
= copystring(theText
);
649 UnlockResource(hData
);
653 // GlobalFree(hData);
659 void wxGetMousePosition( int* x
, int* y
)
662 GetCursorPos( & pt
);
667 // Return TRUE if we have a colour display
668 bool wxColourDisplay(void)
670 HDC dc
= ::GetDC(NULL
);
672 int noCols
= GetDeviceCaps(dc
, NUMCOLORS
);
673 if ((noCols
== -1) || (noCols
> 2))
681 // Returns depth of screen
682 int wxDisplayDepth(void)
684 HDC dc
= ::GetDC(NULL
);
685 int planes
= GetDeviceCaps(dc
, PLANES
);
686 int bitsPerPixel
= GetDeviceCaps(dc
, BITSPIXEL
);
687 int depth
= planes
*bitsPerPixel
;
692 // Get size of display
693 void wxDisplaySize(int *width
, int *height
)
695 HDC dc
= ::GetDC(NULL
);
696 *width
= GetDeviceCaps(dc
, HORZRES
); *height
= GetDeviceCaps(dc
, VERTRES
);
700 bool wxDirExists(const wxString
& dir
)
702 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
703 #if defined(__WIN32__)
704 WIN32_FIND_DATA fileInfo
;
707 struct ffblk fileInfo
;
709 struct find_t fileInfo
;
713 #if defined(__WIN32__)
714 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
716 if (h
==INVALID_HANDLE_VALUE
)
720 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
723 // In Borland findfirst has a different argument
724 // ordering from _dos_findfirst. But _dos_findfirst
725 // _should_ be ok in both MS and Borland... why not?
727 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
729 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
734 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
737 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
738 GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
745 //------------------------------------------------------------------------
746 // wild character routines
747 //------------------------------------------------------------------------
749 bool wxIsWild( const wxString
& pattern
)
751 wxString tmp
= pattern
;
752 char *pat
= WXSTRINGCAST(tmp
);
755 case '?': case '*': case '[': case '{':
766 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
769 char *pattern
= WXSTRINGCAST(tmp1
);
770 wxString tmp2
= text
;
771 char *str
= WXSTRINGCAST(tmp2
);
774 bool done
= FALSE
, ret_code
, ok
;
775 // Below is for vi fans
776 const char OB
= '{', CB
= '}';
778 // dot_special means '.' only matches '.'
779 if (dot_special
&& *str
== '.' && *pattern
!= *str
)
782 while ((*pattern
!= '\0') && (!done
)
783 && (((*str
=='\0')&&((*pattern
==OB
)||(*pattern
=='*')))||(*str
!='\0'))) {
787 if (*pattern
!= '\0')
794 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
799 while (*pattern
!= '\0')
806 if ((*pattern
== '\0') || (*pattern
== ']')) {
810 if (*pattern
== '\\') {
812 if (*pattern
== '\0') {
817 if (*(pattern
+ 1) == '-') {
820 if (*pattern
== ']') {
824 if (*pattern
== '\\') {
826 if (*pattern
== '\0') {
831 if ((*str
< c
) || (*str
> *pattern
)) {
835 } else if (*pattern
!= *str
) {
840 while ((*pattern
!= ']') && (*pattern
!= '\0')) {
841 if ((*pattern
== '\\') && (*(pattern
+ 1) != '\0'))
845 if (*pattern
!= '\0') {
855 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
858 while (ok
&& (*cp
!= '\0') && (*pattern
!= '\0')
859 && (*pattern
!= ',') && (*pattern
!= CB
)) {
860 if (*pattern
== '\\')
862 ok
= (*pattern
++ == *cp
++);
864 if (*pattern
== '\0') {
870 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
871 if (*++pattern
== '\\') {
872 if (*++pattern
== CB
)
877 while (*pattern
!=CB
&& *pattern
!=',' && *pattern
!='\0') {
878 if (*++pattern
== '\\') {
879 if (*++pattern
== CB
|| *pattern
== ',')
884 if (*pattern
!= '\0')
889 if (*str
== *pattern
) {
896 while (*pattern
== '*')
898 return ((*str
== '\0') && (*pattern
== '\0'));