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(__WXMICROWIN__) && ! (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__) && !defined(__WXMICROWIN__)
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__) && !defined(__WXMICROWIN__)
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
134 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
135 static const wxChar eHOSTNAME
[] = wxT("HostName");
136 static const wxChar eUSERID
[] = wxT("UserId");
139 #ifndef __WXMICROWIN__
141 // ============================================================================
143 // ============================================================================
145 // ----------------------------------------------------------------------------
146 // get host name and related
147 // ----------------------------------------------------------------------------
149 // Get hostname only (without domain name)
150 bool wxGetHostName(wxChar
*buf
, int maxSize
)
152 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
153 DWORD nSize
= maxSize
;
154 if ( !::GetComputerName(buf
, &nSize
) )
156 wxLogLastError(wxT("GetComputerName"));
164 const wxChar
*default_host
= wxT("noname");
166 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
167 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
169 wxStrncpy(buf
, sysname
, maxSize
- 1);
170 buf
[maxSize
] = wxT('\0');
171 return *buf
? TRUE
: FALSE
;
175 // get full hostname (with domain name if possible)
176 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
178 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
179 // TODO should use GetComputerNameEx() when available
181 if ( WSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
185 if ( gethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
187 // gethostname() won't usually include the DNS domain name, for
188 // this we need to work a bit more
189 if ( !strchr(bufA
, '.') )
191 struct hostent
*pHostEnt
= gethostbyname(bufA
);
195 // Windows will use DNS internally now
196 pHostEnt
= gethostbyaddr(pHostEnt
->h_addr
, 4, PF_INET
);
201 host
= pHostEnt
->h_name
;
210 wxStrncpy(buf
, host
, maxSize
);
217 return wxGetHostName(buf
, maxSize
);
220 // Get user ID e.g. jacs
221 bool wxGetUserId(wxChar
*buf
, int maxSize
)
223 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
224 DWORD nSize
= maxSize
;
225 if ( ::GetUserName(buf
, &nSize
) == 0 )
227 // actually, it does happen on Win9x if the user didn't log on
228 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
237 #else // Win16 or Win32s
239 const wxChar
*default_id
= wxT("anonymous");
241 // Can't assume we have NIS (PC-NFS) or some other ID daemon
243 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
244 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
246 // Use wxWindows configuration data (comming soon)
247 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
251 wxStrncpy(buf
, user
, maxSize
- 1);
254 return *buf
? TRUE
: FALSE
;
258 // Get user name e.g. Julian Smart
259 bool wxGetUserName(wxChar
*buf
, int maxSize
)
261 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
262 extern HANDLE g_hPenWin
; // PenWindows Running?
265 // PenWindows Does have a user concept!
266 // Get the current owner of the recognizer
267 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
268 strncpy(buf
, wxBuffer
, maxSize
- 1);
274 CHAR szUserName
[256];
275 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
278 // TODO how to get the domain name?
281 // the code is based on the MSDN example (also see KB article Q119670)
282 WCHAR wszUserName
[256]; // Unicode user name
283 WCHAR wszDomain
[256];
286 USER_INFO_2
*ui2
; // User structure
288 // Convert ANSI user name and domain to Unicode
289 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
290 wszUserName
, WXSIZEOF(wszUserName
) );
291 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
292 wszDomain
, WXSIZEOF(wszDomain
) );
294 // Get the computer name of a DC for the domain.
295 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
297 wxLogError(wxT("Can not find domain controller"));
302 // Look up the user on the DC
303 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
304 (LPWSTR
)&wszUserName
,
305 2, // level - we want USER_INFO_2
313 case NERR_InvalidComputer
:
314 wxLogError(wxT("Invalid domain controller name."));
318 case NERR_UserNotFound
:
319 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
324 wxLogSysError(wxT("Can't get information about user"));
329 // Convert the Unicode full name to ANSI
330 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
331 buf
, maxSize
, NULL
, NULL
);
336 wxLogError(wxT("Couldn't look up full user name."));
339 #else // !USE_NET_API
340 // Could use NIS, MS-Mail or other site specific programs
341 // Use wxWindows configuration data
342 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
345 ok
= wxGetUserId(buf
, maxSize
);
350 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
358 const wxChar
* wxGetHomeDir(wxString
*pstr
)
360 wxString
& strDir
= *pstr
;
362 #if defined(__UNIX__) && !defined(__TWIN32__)
363 const wxChar
*szHome
= wxGetenv("HOME");
364 if ( szHome
== NULL
) {
366 wxLogWarning(_("can't find user's HOME, using current directory."));
372 // add a trailing slash if needed
373 if ( strDir
.Last() != wxT('/') )
377 const wxChar
*szHome
= wxGetenv(wxT("HOMEDRIVE"));
378 if ( szHome
!= NULL
)
380 szHome
= wxGetenv(wxT("HOMEPATH"));
381 if ( szHome
!= NULL
) {
384 // the idea is that under NT these variables have default values
385 // of "%systemdrive%:" and "\\". As we don't want to create our
386 // config files in the root directory of the system drive, we will
387 // create it in our program's dir. However, if the user took care
388 // to set HOMEPATH to something other than "\\", we suppose that he
389 // knows what he is doing and use the supplied value.
390 if ( wxStrcmp(szHome
, wxT("\\")) != 0 )
391 return strDir
.c_str();
395 // Win16 has no idea about home, so use the working directory instead
398 // 260 was taken from windef.h
404 ::GetModuleFileName(::GetModuleHandle(NULL
),
405 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
406 strPath
.UngetWriteBuf();
408 // extract the dir name
409 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
413 return strDir
.c_str();
416 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
418 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
419 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
420 // static buffer and sometimes I don't even know what.
421 static wxString s_home
;
423 return (wxChar
*)wxGetHomeDir(&s_home
);
426 bool wxDirExists(const wxString
& dir
)
428 #ifdef __WXMICROWIN__
429 return wxPathExist(dir
);
430 #elif defined(__WIN32__)
431 DWORD attribs
= GetFileAttributes(dir
);
432 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
435 struct ffblk fileInfo
;
437 struct find_t fileInfo
;
439 // In Borland findfirst has a different argument
440 // ordering from _dos_findfirst. But _dos_findfirst
441 // _should_ be ok in both MS and Borland... why not?
443 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
444 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
446 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
447 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
452 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
458 // GetDiskFreeSpaceEx() is not available under original Win95, check for
460 typedef BOOL (*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
466 pGetDiskFreeSpaceEx
= ::GetProcAddress
468 ::GetModuleHandle(_T("kernel32.dll")),
470 "GetDiskFreeSpaceExW"
472 "GetDiskFreeSpaceExA"
476 if ( pGetDiskFreeSpaceEx
)
478 ULARGE_INTEGER bytesFree
, bytesTotal
;
480 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
481 if ( !pGetDiskFreeSpaceEx(path
,
486 wxLogLastError(_T("GetDiskFreeSpaceEx"));
493 *pTotal
= wxLongLong(bytesTotal
.HighPart
, bytesTotal
.LowPart
);
498 *pFree
= wxLongLong(bytesFree
.HighPart
, bytesFree
.LowPart
);
504 DWORD lSectorsPerCluster
,
506 lNumberOfFreeClusters
,
507 lTotalNumberOfClusters
;
509 // FIXME: this is wrong, we should extract the root drive from path
510 // instead, but this is the job for wxFileName...
511 if ( !::GetDiskFreeSpace(path
,
514 &lNumberOfFreeClusters
,
515 &lTotalNumberOfClusters
) )
517 wxLogLastError(_T("GetDiskFreeSpace"));
522 // there's a problem with drives larger than 2GB on non Win32!!
523 // let's calculate it, nevertheless....
524 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
525 lBytesPerCluster
*= lBytesPerSector
;
529 *pTotal
= lBytesPerCluster
;
530 *pTotal
*= lTotalNumberOfClusters
;
535 *pFree
= lBytesPerCluster
;
536 *pFree
*= lNumberOfFreeClusters
;
543 // ----------------------------------------------------------------------------
545 // ----------------------------------------------------------------------------
547 bool wxGetEnv(const wxString
& var
, wxString
*value
)
550 const wxChar
* ret
= wxGetenv(var
);
559 // first get the size of the buffer
560 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
563 // this means that there is no such variable
569 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
570 value
->UngetWriteBuf();
577 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
579 // some compilers have putenv() or _putenv() or _wputenv() but it's better
580 // to always use Win32 function directly instead of dealing with them
581 #if defined(__WIN32__)
582 if ( !::SetEnvironmentVariable(var
, value
) )
584 wxLogLastError(_T("SetEnvironmentVariable"));
590 #else // no way to set env vars
595 // ----------------------------------------------------------------------------
596 // process management
597 // ----------------------------------------------------------------------------
601 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
602 struct wxFindByPidParams
604 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
606 // the HWND used to return the result
609 // the PID we're looking from
613 // wxKill helper: EnumWindows() callback which is used to find the first (top
614 // level) window belonging to the given process
615 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
618 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
620 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
621 if ( pid
== params
->pid
)
623 // remember the window we found
626 // return FALSE to stop the enumeration
630 // continue enumeration
636 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
639 // get the process handle to operate on
640 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
642 PROCESS_QUERY_INFORMATION
,
643 FALSE
, // not inheritable
645 if ( hProcess
== NULL
)
649 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
651 *krc
= wxKILL_ACCESS_DENIED
;
655 *krc
= wxKILL_NO_PROCESS
;
666 // kill the process forcefully returning -1 as error code
667 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
669 wxLogSysError(_("Failed to kill process %d"), pid
);
673 // this is not supposed to happen if we could open the
683 // do nothing, we just want to test for process existence
687 // any other signal means "terminate"
689 wxFindByPidParams params
;
690 params
.pid
= (DWORD
)pid
;
692 // EnumWindows() has nice semantics: it returns 0 if it found
693 // something or if an error occured and non zero if it
694 // enumerated all the window
695 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
697 // did we find any window?
700 // tell the app to close
702 // NB: this is the harshest way, the app won't have
703 // opportunity to save any files, for example, but
704 // this is probably what we want here. If not we
705 // can also use SendMesageTimeout(WM_CLOSE)
706 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
708 wxLogLastError(_T("PostMessage(WM_QUIT)"));
711 else // it was an error then
713 wxLogLastError(_T("EnumWindows"));
718 else // no windows for this PID
735 // as we wait for a short time, we can use just WaitForSingleObject()
736 // and not MsgWaitForMultipleObjects()
737 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
740 // process terminated
741 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
743 wxLogLastError(_T("GetExitCodeProcess"));
748 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
752 wxLogLastError(_T("WaitForSingleObject"));
767 // just to suppress the warnings about uninitialized variable
771 ::CloseHandle(hProcess
);
773 // the return code is the same as from Unix kill(): 0 if killed
774 // successfully or -1 on error
775 if ( sig
== wxSIGNONE
)
777 if ( ok
&& rc
== STILL_ACTIVE
)
779 // there is such process => success
785 if ( ok
&& rc
!= STILL_ACTIVE
)
792 wxFAIL_MSG( _T("not implemented") );
793 #endif // Win32/Win16
799 // Execute a program in an Interactive Shell
800 bool wxShell(const wxString
& command
)
802 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
804 shell
= wxT("\\COMMAND.COM");
814 // pass the command to execute to the command processor
815 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
818 return wxExecute(cmd
, TRUE
/* sync */) != 0;
821 // ----------------------------------------------------------------------------
823 // ----------------------------------------------------------------------------
825 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
826 long wxGetFreeMemory()
828 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
829 MEMORYSTATUS memStatus
;
830 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
831 GlobalMemoryStatus(&memStatus
);
832 return memStatus
.dwAvailPhys
;
834 return (long)GetFreeSpace(0);
841 ::MessageBeep((UINT
)-1); // default sound
844 wxString
wxGetOsDescription()
852 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
853 if ( ::GetVersionEx(&info
) )
855 switch ( info
.dwPlatformId
)
857 case VER_PLATFORM_WIN32s
:
858 str
= _("Win32s on Windows 3.1");
861 case VER_PLATFORM_WIN32_WINDOWS
:
862 str
.Printf(_("Windows 9%c"),
863 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
864 if ( !wxIsEmpty(info
.szCSDVersion
) )
866 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
870 case VER_PLATFORM_WIN32_NT
:
871 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
875 if ( !wxIsEmpty(info
.szCSDVersion
) )
877 str
<< _T(", ") << info
.szCSDVersion
;
885 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
890 return _("Windows 3.1");
894 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
896 #if defined(__WIN32__) && !defined(__SC__)
900 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
901 if ( ::GetVersionEx(&info
) )
904 *majorVsn
= info
.dwMajorVersion
;
906 *minorVsn
= info
.dwMinorVersion
;
908 switch ( info
.dwPlatformId
)
910 case VER_PLATFORM_WIN32s
:
913 case VER_PLATFORM_WIN32_WINDOWS
:
916 case VER_PLATFORM_WIN32_NT
:
921 return wxWINDOWS
; // error if we get here, return generic value
923 int retValue
= wxWINDOWS
;
924 #ifdef __WINDOWS_386__
927 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
928 extern HANDLE g_hPenWin
;
929 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
942 // ----------------------------------------------------------------------------
944 // ----------------------------------------------------------------------------
950 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
951 static bool gs_inTimer
= FALSE
;
953 class wxSleepTimer
: public wxTimer
956 virtual void Notify()
963 static wxTimer
*wxTheSleepTimer
= NULL
;
965 void wxUsleep(unsigned long milliseconds
)
968 ::Sleep(milliseconds
);
973 wxTheSleepTimer
= new wxSleepTimer
;
975 wxTheSleepTimer
->Start(milliseconds
);
978 if (wxTheApp
->Pending())
979 wxTheApp
->Dispatch();
981 delete wxTheSleepTimer
;
982 wxTheSleepTimer
= NULL
;
983 #endif // Win32/!Win32
986 void wxSleep(int nSecs
)
991 wxTheSleepTimer
= new wxSleepTimer
;
993 wxTheSleepTimer
->Start(nSecs
*1000);
996 if (wxTheApp
->Pending())
997 wxTheApp
->Dispatch();
999 delete wxTheSleepTimer
;
1000 wxTheSleepTimer
= NULL
;
1003 // Consume all events until no more left
1004 void wxFlushEvents()
1009 #endif // wxUSE_TIMER
1011 #elif defined(__WIN32__) // wxUSE_GUI
1013 void wxUsleep(unsigned long milliseconds
)
1015 ::Sleep(milliseconds
);
1018 void wxSleep(int nSecs
)
1020 wxUsleep(1000*nSecs
);
1023 #endif // wxUSE_GUI/!wxUSE_GUI
1027 // ----------------------------------------------------------------------------
1028 // deprecated (in favour of wxLog) log functions
1029 // ----------------------------------------------------------------------------
1033 // Output a debug mess., in a system dependent fashion.
1034 #ifndef __WXMICROWIN__
1035 void wxDebugMsg(const wxChar
*fmt
...)
1038 static wxChar buffer
[512];
1040 if (!wxTheApp
->GetWantDebugOutput())
1045 wvsprintf(buffer
,fmt
,ap
) ;
1046 OutputDebugString((LPCTSTR
)buffer
) ;
1051 // Non-fatal error: pop up message box and (possibly) continue
1052 void wxError(const wxString
& msg
, const wxString
& title
)
1054 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
1055 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
1056 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
1060 // Fatal error: pop up message box and abort
1061 void wxFatalError(const wxString
& msg
, const wxString
& title
)
1063 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
1064 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
1066 #endif // __WXMICROWIN__
1068 // ----------------------------------------------------------------------------
1069 // functions to work with .INI files
1070 // ----------------------------------------------------------------------------
1072 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1074 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
1076 if (file
!= wxT(""))
1077 // Don't know what the correct cast should be, but it doesn't
1078 // compile in BC++/16-bit without this cast.
1079 #if !defined(__WIN32__)
1080 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
1082 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
1085 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
1088 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
1091 buf
.Printf(wxT("%.4f"), value
);
1093 return wxWriteResource(section
, entry
, buf
, file
);
1096 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1099 buf
.Printf(wxT("%ld"), value
);
1101 return wxWriteResource(section
, entry
, buf
, file
);
1104 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1107 buf
.Printf(wxT("%d"), value
);
1109 return wxWriteResource(section
, entry
, buf
, file
);
1112 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1114 static const wxChar defunkt
[] = wxT("$$default");
1115 if (file
!= wxT(""))
1117 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1118 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1119 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1124 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1125 (LPTSTR
)wxBuffer
, 1000);
1126 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1129 if (*value
) delete[] (*value
);
1130 *value
= copystring(wxBuffer
);
1134 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1137 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1140 *value
= (float)wxStrtod(s
, NULL
);
1147 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1150 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1153 *value
= wxStrtol(s
, NULL
, 10);
1160 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1163 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1166 *value
= (int)wxStrtol(s
, NULL
, 10);
1172 #endif // wxUSE_RESOURCES
1174 // ---------------------------------------------------------------------------
1175 // helper functions for showing a "busy" cursor
1176 // ---------------------------------------------------------------------------
1178 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1179 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1180 static int gs_wxBusyCursorCount
= 0;
1182 extern HCURSOR
wxGetCurrentBusyCursor()
1184 return gs_wxBusyCursor
;
1187 // Set the cursor to the busy cursor for all windows
1188 void wxBeginBusyCursor(wxCursor
*cursor
)
1190 if ( gs_wxBusyCursorCount
++ == 0 )
1192 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1193 #ifndef __WXMICROWIN__
1194 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1197 //else: nothing to do, already set
1200 // Restore cursor to normal
1201 void wxEndBusyCursor()
1203 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1204 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1206 if ( --gs_wxBusyCursorCount
== 0 )
1208 #ifndef __WXMICROWIN__
1209 ::SetCursor(gs_wxBusyCursorOld
);
1211 gs_wxBusyCursorOld
= 0;
1215 // TRUE if we're between the above two calls
1218 return (gs_wxBusyCursorCount
> 0);
1221 // Check whether this window wants to process messages, e.g. Stop button
1222 // in long calculations.
1223 bool wxCheckForInterrupt(wxWindow
*wnd
)
1225 wxCHECK( wnd
, FALSE
);
1228 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1230 ::TranslateMessage(&msg
);
1231 ::DispatchMessage(&msg
);
1237 // MSW only: get user-defined resource from the .res file.
1238 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1240 #ifndef __WXMICROWIN__
1241 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1243 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1244 if ( hResource
== 0 )
1247 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1251 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1255 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1256 // so we need to find the length of the resource.
1257 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1258 wxChar
*s
= new wxChar
[len
+1];
1259 wxStrncpy(s
,theText
,len
);
1262 // wxChar *s = copystring(theText);
1264 // Obsolete in WIN32
1266 UnlockResource(hData
);
1270 // GlobalFree(hData);
1276 // ----------------------------------------------------------------------------
1278 // ----------------------------------------------------------------------------
1280 // See also the wxGetMousePosition in window.cpp
1281 // Deprecated: use wxPoint wxGetMousePosition() instead
1282 void wxGetMousePosition( int* x
, int* y
)
1285 GetCursorPos( & pt
);
1290 // Return TRUE if we have a colour display
1291 bool wxColourDisplay()
1293 #ifdef __WXMICROWIN__
1297 // this function is called from wxDC ctor so it is called a *lot* of times
1298 // hence we optimize it a bit but doign the check only once
1300 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1302 static int s_isColour
= -1;
1304 if ( s_isColour
== -1 )
1307 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1309 s_isColour
= (noCols
== -1) || (noCols
> 2);
1312 return s_isColour
!= 0;
1316 // Returns depth of screen
1317 int wxDisplayDepth()
1320 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1323 // Get size of display
1324 void wxDisplaySize(int *width
, int *height
)
1326 #ifdef __WXMICROWIN__
1328 HWND hWnd
= GetDesktopWindow();
1329 ::GetWindowRect(hWnd
, & rect
);
1331 *width
= rect
.right
- rect
.left
;
1332 *height
= rect
.bottom
- rect
.top
;
1336 if ( width
) *width
= GetDeviceCaps(dc
, HORZRES
);
1337 if ( height
) *height
= GetDeviceCaps(dc
, VERTRES
);
1341 void wxDisplaySizeMM(int *width
, int *height
)
1343 #ifdef __WXMICROWIN__
1345 *width
= 0; * height
= 0;
1349 if ( width
) *width
= GetDeviceCaps(dc
, HORZSIZE
);
1350 if ( height
) *height
= GetDeviceCaps(dc
, VERTSIZE
);
1354 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1356 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1358 wxDisplaySize(width
, height
);
1360 // Determine the desktop dimensions minus the taskbar and any other
1361 // special decorations...
1364 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1367 if (width
) *width
= r
.right
- r
.left
;
1368 if (height
) *height
= r
.bottom
- r
.top
;
1373 // ---------------------------------------------------------------------------
1374 // window information functions
1375 // ---------------------------------------------------------------------------
1377 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1380 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1381 GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1382 str
.UngetWriteBuf();
1387 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1389 #ifdef __WXMICROWIN__
1391 return wxEmptyString
;
1395 int len
= 256; // some starting value
1399 // as we've #undefined GetClassName we must now manually choose the
1400 // right function to call
1413 #endif // Twin32/!Twin32
1414 #endif // Unicode/ANSI
1416 ((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1418 str
.UngetWriteBuf();
1421 // the class name might have been truncated, retry with larger
1435 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1438 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1440 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1448 // ----------------------------------------------------------------------------
1450 // ----------------------------------------------------------------------------
1452 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1456 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1457 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1458 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1459 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1461 *x
*= (iWidthMM
* 100);
1463 *y
*= (iHeightMM
* 100);
1467 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1471 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1472 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1473 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1474 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1477 *x
/= (iWidthMM
* 100);
1479 *y
/= (iHeightMM
* 100);
1485 //------------------------------------------------------------------------
1486 // wild character routines
1487 //------------------------------------------------------------------------
1489 bool wxIsWild( const wxString
& pattern
)
1491 wxString tmp
= pattern
;
1492 char *pat
= WXSTRINGCAST(tmp
);
1495 case '?': case '*': case '[': case '{':
1506 bool wxMatchWild( const wxString
& pat
, const wxString
& text
, bool dot_special
)
1508 wxString tmp1
= pat
;
1509 char *pattern
= WXSTRINGCAST(tmp1
);
1510 wxString tmp2
= text
;
1511 char *str
= WXSTRINGCAST(tmp2
);
1514 bool done
= FALSE
, ret_code
, ok
;
1515 // Below is for vi fans
1516 const char OB
= '{', CB
= '}';
1518 // dot_special means '.' only matches '.'
1519 if (dot_special
&& *str
== '.' && *pattern
!= *str
)
1522 while ((*pattern
!= '\0') && (!done
)
1523 && (((*str
=='\0')&&((*pattern
==OB
)||(*pattern
=='*')))||(*str
!='\0'))) {
1527 if (*pattern
!= '\0')
1534 && (!(ret_code
=wxMatchWild(pattern
, str
++, FALSE
))))
1537 while (*str
!= '\0')
1539 while (*pattern
!= '\0')
1546 if ((*pattern
== '\0') || (*pattern
== ']')) {
1550 if (*pattern
== '\\') {
1552 if (*pattern
== '\0') {
1557 if (*(pattern
+ 1) == '-') {
1560 if (*pattern
== ']') {
1564 if (*pattern
== '\\') {
1566 if (*pattern
== '\0') {
1571 if ((*str
< c
) || (*str
> *pattern
)) {
1575 } else if (*pattern
!= *str
) {
1580 while ((*pattern
!= ']') && (*pattern
!= '\0')) {
1581 if ((*pattern
== '\\') && (*(pattern
+ 1) != '\0'))
1585 if (*pattern
!= '\0') {
1595 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
1598 while (ok
&& (*cp
!= '\0') && (*pattern
!= '\0')
1599 && (*pattern
!= ',') && (*pattern
!= CB
)) {
1600 if (*pattern
== '\\')
1602 ok
= (*pattern
++ == *cp
++);
1604 if (*pattern
== '\0') {
1610 while ((*pattern
!= CB
) && (*pattern
!= '\0')) {
1611 if (*++pattern
== '\\') {
1612 if (*++pattern
== CB
)
1617 while (*pattern
!=CB
&& *pattern
!=',' && *pattern
!='\0') {
1618 if (*++pattern
== '\\') {
1619 if (*++pattern
== CB
|| *pattern
== ',')
1624 if (*pattern
!= '\0')
1629 if (*str
== *pattern
) {
1636 while (*pattern
== '*')
1638 return ((*str
== '\0') && (*pattern
== '\0'));
1645 // maximum mumber of lines the output console should have
1646 static const WORD MAX_CONSOLE_LINES
= 500;
1648 BOOL WINAPI
MyConsoleHandler( DWORD dwCtrlType
) { // control signal type
1653 void wxRedirectIOToConsole()
1657 CONSOLE_SCREEN_BUFFER_INFO coninfo
;
1660 // allocate a console for this app
1663 // set the screen buffer to be big enough to let us scroll text
1664 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
),
1666 coninfo
.dwSize
.Y
= MAX_CONSOLE_LINES
;
1667 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE
),
1670 // redirect unbuffered STDOUT to the console
1671 lStdHandle
= (long)GetStdHandle(STD_OUTPUT_HANDLE
);
1672 hConHandle
= _open_osfhandle(lStdHandle
, _O_TEXT
);
1673 if(hConHandle
<= 0) return;
1674 fp
= _fdopen( hConHandle
, "w" );
1676 setvbuf( stdout
, NULL
, _IONBF
, 0 );
1678 // redirect unbuffered STDIN to the console
1679 lStdHandle
= (long)GetStdHandle(STD_INPUT_HANDLE
);
1680 hConHandle
= _open_osfhandle(lStdHandle
, _O_TEXT
);
1681 if(hConHandle
<= 0) return;
1682 fp
= _fdopen( hConHandle
, "r" );
1684 setvbuf( stdin
, NULL
, _IONBF
, 0 );
1686 // redirect unbuffered STDERR to the console
1687 lStdHandle
= (long)GetStdHandle(STD_ERROR_HANDLE
);
1688 hConHandle
= _open_osfhandle(lStdHandle
, _O_TEXT
);
1689 if(hConHandle
<= 0) return;
1690 fp
= _fdopen( hConHandle
, "w" );
1692 setvbuf( stderr
, NULL
, _IONBF
, 0 );
1694 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1695 // point to console as well
1696 ios::sync_with_stdio();
1698 SetConsoleCtrlHandler(MyConsoleHandler
, TRUE
);
1702 void wxRedirectIOToConsole()
1707 #ifdef __WXMICROWIN__
1708 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1711 if (majorVsn
) *majorVsn
= 0;
1712 if (minorVsn
) *minorVsn
= 0;