1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 // #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
27 #include "wx/cursor.h"
30 #include "wx/msw/private.h"
41 #include <sys/unistd.h>
51 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
52 // this (3.1 I believe) and how to test for it.
53 // If this works for Borland 4.0 as well, then no worries.
69 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
75 // In the WIN.INI file
76 static const char WX_SECTION
[] = "wxWindows";
77 static const char eHOSTNAME
[] = "HostName";
78 static const char eUSERID
[] = "UserId";
79 static const char eUSERNAME
[] = "UserName";
81 // For the following functions we SHOULD fill in support
82 // for Windows-NT (which I don't know) as I assume it begin
83 // a POSIX Unix (so claims MS) that it has some special
84 // functions beyond those provided by WinSock
86 // Get full hostname (eg. DoDo.BSn-Germany.crg.de)
87 bool wxGetHostName(char *buf
, int maxSize
)
90 DWORD nSize
= maxSize
;
91 return (::GetComputerName(buf
, &nSize
) != 0);
94 const char *default_host
= "noname";
96 if ((sysname
= getenv("SYSTEM_NAME")) == NULL
) {
97 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
99 strncpy(buf
, sysname
, maxSize
- 1);
101 return *buf
? TRUE
: FALSE
;
105 // Get user ID e.g. jacs
106 bool wxGetUserId(char *buf
, int maxSize
)
108 #if defined(__WIN32__) && !defined(__win32s__) && 0
109 // Gets the current user's full name according to the MS article PSS ID
111 // Seems to be the same as the login name for me?
112 char *UserName
= new char[256];
113 char *Domain
= new char[256];
114 DWORD maxCharacters
= 255;
115 GetUserName( UserName
, &maxCharacters
);
116 GetComputerName( Domain
, &maxCharacters
);
118 WCHAR wszUserName
[256]; // Unicode user name
119 WCHAR wszDomain
[256];
122 struct _SERVER_INFO_100
*si100
; // Server structure
123 struct _USER_INFO_2
*ui
; // User structure
125 // Convert ASCII user name and domain to Unicode.
127 MultiByteToWideChar( CP_ACP
, 0, UserName
,
128 strlen(UserName
)+1, wszUserName
, sizeof(wszUserName
) );
129 MultiByteToWideChar( CP_ACP
, 0, Domain
,
130 strlen(Domain
)+1, wszDomain
, sizeof(wszDomain
) );
132 // Get the computer name of a DC for the specified domain.
133 // >If you get a link error on this, include netapi32.lib<
135 NetGetDCName( NULL
, wszDomain
, &ComputerName
);
137 // Look up the user on the DC.
139 if(NetUserGetInfo( (LPWSTR
) ComputerName
,
140 (LPWSTR
) &wszUserName
, 2, (LPBYTE
*) &ui
))
142 printf( "Error getting user information.\n" );
146 // Convert the Unicode full name to ASCII.
148 WideCharToMultiByte( CP_ACP
, 0, ui
->usri2_full_name
,
149 -1, buf
, 256, NULL
, NULL
);
153 DWORD nSize = maxSize;
154 return ::GetUserName(buf, &nSize);
158 const char *default_id
= "anonymous";
160 // Can't assume we have NIS (PC-NFS) or some other ID daemon
162 if ( (user
= getenv("USER")) == NULL
&&
163 (user
= getenv("LOGNAME")) == NULL
) {
164 // Use wxWindows configuration data (comming soon)
165 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
167 strncpy(buf
, user
, maxSize
- 1);
168 return *buf
? TRUE
: FALSE
;
172 // Get user name e.g. Julian Smart
173 bool wxGetUserName(char *buf
, int maxSize
)
175 const char *default_name
= "Unknown User";
176 #if defined(__WIN32__)
178 DWORD nSize = maxSize;
179 In VC++ 4.0, results in unresolved symbol __imp__GetUserNameA
180 if (GetUserName(buf, &nSize))
184 // Could use NIS, MS-Mail or other site specific programs
185 // Use wxWindows configuration data
186 GetProfileString(WX_SECTION
, eUSERNAME
, default_name
, buf
, maxSize
- 1);
187 return *buf
? TRUE
: FALSE
;
190 #if !defined(__WATCOMC__) && !defined(__GNUWIN32__) && wxUSE_PENWINDOWS
191 extern HANDLE g_hPenWin
; // PenWindows Running?
194 // PenWindows Does have a user concept!
195 // Get the current owner of the recognizer
196 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
197 strncpy(buf
, wxBuffer
, maxSize
- 1);
202 // Could use NIS, MS-Mail or other site specific programs
203 // Use wxWindows configuration data
204 GetProfileString(WX_SECTION
, eUSERNAME
, default_name
, buf
, maxSize
- 1);
206 return *buf
? TRUE
: FALSE
;
210 int wxKill(long pid
, int sig
)
216 // Execute a program in an Interactive Shell
219 wxShell(const wxString
& command
)
222 if ((shell
= getenv("COMSPEC")) == NULL
)
223 shell
= "\\COMMAND.COM";
227 sprintf(tmp
, "%s /c %s", shell
, WXSTRINGCAST command
);
231 return (wxExecute((char *)tmp
, FALSE
) != 0);
234 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
235 long wxGetFreeMemory(void)
237 #if defined(__WIN32__) && !defined(__BORLANDC__)
238 MEMORYSTATUS memStatus
;
239 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
240 GlobalMemoryStatus(&memStatus
);
241 return memStatus
.dwAvailPhys
;
243 return (long)GetFreeSpace(0);
247 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
248 static bool inTimer
= FALSE
;
249 class wxSleepTimer
: public wxTimer
252 inline void Notify(void)
259 static wxTimer
*wxTheSleepTimer
= NULL
;
261 void wxSleep(int nSecs
)
263 #if 0 // WIN32 hangs app
269 wxTheSleepTimer
= new wxSleepTimer
;
271 wxTheSleepTimer
->Start(nSecs
*1000);
274 if (wxTheApp
->Pending())
275 wxTheApp
->Dispatch();
277 delete wxTheSleepTimer
;
278 wxTheSleepTimer
= NULL
;
282 // Consume all events until no more left
283 void wxFlushEvents(void)
288 // Output a debug mess., in a system dependent fashion.
289 void wxDebugMsg(const char *fmt
...)
292 static char buffer
[512];
294 if (!wxTheApp
->GetWantDebugOutput())
299 wvsprintf(buffer
,fmt
,ap
) ;
300 OutputDebugString((LPCSTR
)buffer
) ;
305 // Non-fatal error: pop up message box and (possibly) continue
306 void wxError(const wxString
& msg
, const wxString
& title
)
308 sprintf(wxBuffer
, "%s\nContinue?", WXSTRINGCAST msg
);
309 if (MessageBox(NULL
, (LPCSTR
)wxBuffer
, (LPCSTR
)WXSTRINGCAST title
,
310 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
314 // Fatal error: pop up message box and abort
315 void wxFatalError(const wxString
& msg
, const wxString
& title
)
317 sprintf(wxBuffer
, "%s: %s", WXSTRINGCAST title
, WXSTRINGCAST msg
);
318 FatalAppExit(0, (LPCSTR
)wxBuffer
);
325 Beep(1000,1000) ; // 1kHz during 1 sec.
331 // Chris Breeze 27/5/98: revised WIN32 code to
332 // detect WindowsNT correctly
333 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
335 extern char *wxOsVersion
;
336 if (majorVsn
) *majorVsn
= 0;
337 if (minorVsn
) *minorVsn
= 0;
341 memset(&info
, 0, sizeof(OSVERSIONINFO
));
342 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
343 if (GetVersionEx(&info
))
345 if (majorVsn
) *majorVsn
= info
.dwMajorVersion
;
346 if (minorVsn
) *minorVsn
= info
.dwMinorVersion
;
347 switch (info
.dwPlatformId
)
349 case VER_PLATFORM_WIN32s
:
352 case VER_PLATFORM_WIN32_WINDOWS
:
355 case VER_PLATFORM_WIN32_NT
:
360 return wxWINDOWS
; // error if we get here, return generic value
364 # ifdef __WINDOWS_386__
367 # if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
368 extern HANDLE g_hPenWin
;
369 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
372 // @@@@ To be completed. I don't have the manual here...
373 if (majorVsn
) *majorVsn
= 3 ;
374 if (minorVsn
) *minorVsn
= 1 ;
379 // Reading and writing resources (eg WIN.INI, .Xdefaults)
381 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
384 return (WritePrivateProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)value
, (LPCSTR
)WXSTRINGCAST file
) != 0);
386 return (WriteProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)WXSTRINGCAST value
) != 0);
389 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
392 sprintf(buf
, "%.4f", value
);
393 return wxWriteResource(section
, entry
, buf
, file
);
396 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
399 sprintf(buf
, "%ld", value
);
400 return wxWriteResource(section
, entry
, buf
, file
);
403 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
406 sprintf(buf
, "%d", value
);
407 return wxWriteResource(section
, entry
, buf
, file
);
410 bool wxGetResource(const wxString
& section
, const wxString
& entry
, char **value
, const wxString
& file
)
412 static const char defunkt
[] = "$$default";
415 int n
= GetPrivateProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)defunkt
,
416 (LPSTR
)wxBuffer
, 1000, (LPCSTR
)WXSTRINGCAST file
);
417 if (n
== 0 || strcmp(wxBuffer
, defunkt
) == 0)
422 int n
= GetProfileString((LPCSTR
)WXSTRINGCAST section
, (LPCSTR
)WXSTRINGCAST entry
, (LPCSTR
)defunkt
,
423 (LPSTR
)wxBuffer
, 1000);
424 if (n
== 0 || strcmp(wxBuffer
, defunkt
) == 0)
427 if (*value
) delete[] (*value
);
428 *value
= copystring(wxBuffer
);
432 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
435 bool succ
= wxGetResource(section
, entry
, (char **)&s
, file
);
438 *value
= (float)strtod(s
, NULL
);
445 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
448 bool succ
= wxGetResource(section
, entry
, (char **)&s
, file
);
451 *value
= strtol(s
, NULL
, 10);
458 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
461 bool succ
= wxGetResource(section
, entry
, (char **)&s
, file
);
464 *value
= (int)strtol(s
, NULL
, 10);
470 #endif // wxUSE_RESOURCES
473 static HCURSOR wxBusyCursorOld
= 0;
474 static int wxBusyCursorCount
= 0;
476 // Set the cursor to the busy cursor for all windows
477 void wxBeginBusyCursor(wxCursor
*cursor
)
479 wxBusyCursorCount
++;
480 if (wxBusyCursorCount
== 1)
482 wxBusyCursorOld
= ::SetCursor((HCURSOR
) cursor
->GetHCURSOR());
486 (void)::SetCursor((HCURSOR
) cursor
->GetHCURSOR());
490 // Restore cursor to normal
491 void wxEndBusyCursor(void)
493 if (wxBusyCursorCount
== 0)
496 wxBusyCursorCount
--;
497 if (wxBusyCursorCount
== 0)
499 ::SetCursor(wxBusyCursorOld
);
504 // TRUE if we're between the above two calls
507 return (wxBusyCursorCount
> 0);
510 const char* WXDLLEXPORT
wxGetHomeDir(wxString
*pstr
)
512 wxString
& strDir
= *pstr
;
515 const char *szHome
= getenv("HOME");
516 if ( szHome
== NULL
) {
518 wxLogWarning(_("can't find user's HOME, using current directory."));
524 // add a trailing slash if needed
525 if ( strDir
.Last() != '/' )
529 const char *szHome
= getenv("HOMEDRIVE");
530 if ( szHome
!= NULL
)
532 szHome
= getenv("HOMEPATH");
533 if ( szHome
!= NULL
) {
536 // the idea is that under NT these variables have default values
537 // of "%systemdrive%:" and "\\". As we don't want to create our
538 // config files in the root directory of the system drive, we will
539 // create it in our program's dir. However, if the user took care
540 // to set HOMEPATH to something other than "\\", we suppose that he
541 // knows what he is doing and use the supplied value.
542 if ( strcmp(szHome
, "\\") != 0 )
543 return strDir
.c_str();
547 // Win16 has no idea about home, so use the working directory instead
550 // 260 was taken from windef.h
556 ::GetModuleFileName(::GetModuleHandle(NULL
),
557 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
558 strPath
.UngetWriteBuf();
560 // extract the dir name
561 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
565 return strDir
.c_str();
569 char *wxGetUserHome (const wxString
& user
)
572 wxString
user1(user
);
576 if (wxGetUserId(tmp
, sizeof(tmp
)/sizeof(char))) {
577 // Guests belong in the temp dir
578 if (Stricmp(tmp
, "annonymous") == 0) {
579 if ((home
= getenv("TMP")) != NULL
||
580 (home
= getenv("TMPDIR")) != NULL
||
581 (home
= getenv("TEMP")) != NULL
)
582 return *home
? home
: "\\";
584 if (Stricmp(tmp
, WXSTRINGCAST user1
) == 0)
589 if ((home
= getenv("HOME")) != NULL
)
591 strcpy(wxBuffer
, home
);
592 Unix2DosFilename(wxBuffer
);
595 return NULL
; // No home known!
598 // Check whether this window wants to process messages, e.g. Stop button
599 // in long calculations.
600 bool wxCheckForInterrupt(wxWindow
*wnd
)
604 HWND win
= (HWND
) wnd
->GetHWND();
605 while(PeekMessage(&msg
,win
,0,0,PM_REMOVE
)){
606 TranslateMessage(&msg
);
607 DispatchMessage(&msg
);
609 return TRUE
;//*** temporary?
612 wxError("wnd==NULL !!!");
613 return FALSE
;//*** temporary?
617 // MSW only: get user-defined resource from the .res file.
618 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
621 char *wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
625 HRSRC hResource
= ::FindResource(wxGetInstance(), WXSTRINGCAST resourceName
, WXSTRINGCAST resourceType
);
628 HRSRC hResource
= ::FindResourceW(wxGetInstance(), WXSTRINGCAST resourceName
, WXSTRINGCAST resourceType
);
630 HRSRC hResource
= ::FindResourceA(wxGetInstance(), WXSTRINGCAST resourceName
, WXSTRINGCAST resourceType
);
636 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
639 char *theText
= (char *)LockResource(hData
);
643 s
= copystring(theText
);
647 UnlockResource(hData
);
651 // GlobalFree(hData);
657 void wxGetMousePosition( int* x
, int* y
)
660 GetCursorPos( & pt
);
665 // Return TRUE if we have a colour display
666 bool wxColourDisplay(void)
668 HDC dc
= ::GetDC(NULL
);
670 int noCols
= GetDeviceCaps(dc
, NUMCOLORS
);
671 if ((noCols
== -1) || (noCols
> 2))
679 // Returns depth of screen
680 int wxDisplayDepth(void)
682 HDC dc
= ::GetDC(NULL
);
683 int planes
= GetDeviceCaps(dc
, PLANES
);
684 int bitsPerPixel
= GetDeviceCaps(dc
, BITSPIXEL
);
685 int depth
= planes
*bitsPerPixel
;
690 // Get size of display
691 void wxDisplaySize(int *width
, int *height
)
693 HDC dc
= ::GetDC(NULL
);
694 *width
= GetDeviceCaps(dc
, HORZRES
); *height
= GetDeviceCaps(dc
, VERTRES
);
698 bool wxDirExists(const wxString
& dir
)
700 /* MATTHEW: [6] Always use same code for Win32, call FindClose */
701 #if defined(__WIN32__)
702 WIN32_FIND_DATA fileInfo
;
705 struct ffblk fileInfo
;
707 struct find_t fileInfo
;
711 #if defined(__WIN32__)
712 HANDLE h
= FindFirstFile((LPTSTR
) WXSTRINGCAST dir
,(LPWIN32_FIND_DATA
)&fileInfo
);
714 if (h
==INVALID_HANDLE_VALUE
)
718 return ((fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) == FILE_ATTRIBUTE_DIRECTORY
);
721 // In Borland findfirst has a different argument
722 // ordering from _dos_findfirst. But _dos_findfirst
723 // _should_ be ok in both MS and Borland... why not?
725 return ((findfirst(WXSTRINGCAST dir
, &fileInfo
, _A_SUBDIR
) == 0 && (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0));
727 return (((_dos_findfirst(WXSTRINGCAST dir
, _A_SUBDIR
, &fileInfo
) == 0) && (fileInfo
.attrib
& _A_SUBDIR
)) != 0);
732 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
735 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
736 GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
743 //------------------------------------------------------------------------
744 // wild character routines
745 //------------------------------------------------------------------------
747 bool wxIsWild( const wxString
& pattern
)
749 wxString tmp
= pattern
;
750 char *pat
= WXSTRINGCAST(tmp
);
753 case '?': case '*': case '[': case '{':
764 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
767 char *pattern
= WXSTRINGCAST(tmp1
);
768 wxString tmp2
= text
;
769 char *str
= WXSTRINGCAST(tmp2
);
772 bool done
= FALSE
, ret_code
, ok
;
773 // Below is for vi fans
774 const char OB
= '{', CB
= '}';
776 // dot_special means '.' only matches '.'
777 if (dot_special
&& *str
== '.' && *pattern
!= *str
)
780 while ((*pattern
!= '\0') && (!done
)
781 && (((*str
=='\0')&&((*pattern
==OB
)||(*pattern
=='*')))||(*str
!='\0'))) {
785 if (*pattern
!= '\0')
792 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
797 while (*pattern
!= '\0')
804 if ((*pattern
== '\0') || (*pattern
== ']')) {
808 if (*pattern
== '\\') {
810 if (*pattern
== '\0') {
815 if (*(pattern
+ 1) == '-') {
818 if (*pattern
== ']') {
822 if (*pattern
== '\\') {
824 if (*pattern
== '\0') {
829 if ((*str
< c
) || (*str
> *pattern
)) {
833 } else if (*pattern
!= *str
) {
838 while ((*pattern
!= ']') && (*pattern
!= '\0')) {
839 if ((*pattern
== '\\') && (*(pattern
+ 1) != '\0'))
843 if (*pattern
!= '\0') {
853 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
856 while (ok
&& (*cp
!= '\0') && (*pattern
!= '\0')
857 && (*pattern
!= ',') && (*pattern
!= CB
)) {
858 if (*pattern
== '\\')
860 ok
= (*pattern
++ == *cp
++);
862 if (*pattern
== '\0') {
868 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
869 if (*++pattern
== '\\') {
870 if (*++pattern
== CB
)
875 while (*pattern
!=CB
&& *pattern
!=',' && *pattern
!='\0') {
876 if (*++pattern
== '\\') {
877 if (*++pattern
== CB
|| *pattern
== ',')
882 if (*pattern
!= '\0')
887 if (*str
== *pattern
) {
894 while (*pattern
== '*')
896 return ((*str
== '\0') && (*pattern
== '\0'));