1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
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"
37 #include "wx/cursor.h"
41 #include "wx/msw/private.h" // includes <windows.h>
43 #ifdef __GNUWIN32_OLD__
44 // apparently we need to include winsock.h to get WSADATA and other stuff
45 // used in wxGetFullHostName() with the old mingw32 versions
51 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
59 #if defined(__CYGWIN__) && !defined(__TWIN32__)
60 #include <sys/unistd.h>
62 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
65 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
66 // this (3.1 I believe) and how to test for it.
67 // If this works for Borland 4.0 as well, then no worries.
71 // VZ: there is some code using NetXXX() functions to get the full user name:
72 // I don't think it's a good idea because they don't work under Win95 and
73 // seem to return the same as wxGetUserId() under NT. If you really want
74 // to use them, just #define USE_NET_API
81 #if defined(__WIN32__) && !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 /* Need to undef new if including crtdbg.h */
115 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
116 # define new new(__TFILE__,__LINE__)
121 /// END for console support
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 // In the WIN.INI file
128 static const wxChar WX_SECTION
[] = wxT("wxWindows");
129 static const wxChar eUSERNAME
[] = wxT("UserName");
131 // these are only used under Win16
132 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
133 static const wxChar eHOSTNAME
[] = wxT("HostName");
134 static const wxChar eUSERID
[] = wxT("UserId");
137 #ifndef __WXMICROWIN__
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__) && !defined(__WXMICROWIN__)
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(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
177 // TODO should use GetComputerNameEx() when available
179 // the idea is that if someone had set wxUSE_SOCKETS to 0 the code
180 // shouldn't use winsock.dll (a.k.a. ws2_32.dll) at all so only use this
181 // code if we link with it anyhow
184 if ( WSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
188 if ( gethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
190 // gethostname() won't usually include the DNS domain name, for
191 // this we need to work a bit more
192 if ( !strchr(bufA
, '.') )
194 struct hostent
*pHostEnt
= gethostbyname(bufA
);
198 // Windows will use DNS internally now
199 pHostEnt
= gethostbyaddr(pHostEnt
->h_addr
, 4, AF_INET
);
204 host
= wxString::FromAscii(pHostEnt
->h_name
);
213 wxStrncpy(buf
, host
, maxSize
);
218 #endif // wxUSE_SOCKETS
222 return wxGetHostName(buf
, maxSize
);
225 // Get user ID e.g. jacs
226 bool wxGetUserId(wxChar
*buf
, int maxSize
)
228 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
229 DWORD nSize
= maxSize
;
230 if ( ::GetUserName(buf
, &nSize
) == 0 )
232 // actually, it does happen on Win9x if the user didn't log on
233 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
242 #else // Win16 or Win32s
244 const wxChar
*default_id
= wxT("anonymous");
246 // Can't assume we have NIS (PC-NFS) or some other ID daemon
248 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
249 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
251 // Use wxWindows configuration data (comming soon)
252 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
256 wxStrncpy(buf
, user
, maxSize
- 1);
259 return *buf
? TRUE
: FALSE
;
263 // Get user name e.g. Julian Smart
264 bool wxGetUserName(wxChar
*buf
, int maxSize
)
266 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
267 extern HANDLE g_hPenWin
; // PenWindows Running?
270 // PenWindows Does have a user concept!
271 // Get the current owner of the recognizer
272 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
273 strncpy(buf
, wxBuffer
, maxSize
- 1);
279 CHAR szUserName
[256];
280 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
283 // TODO how to get the domain name?
286 // the code is based on the MSDN example (also see KB article Q119670)
287 WCHAR wszUserName
[256]; // Unicode user name
288 WCHAR wszDomain
[256];
291 USER_INFO_2
*ui2
; // User structure
293 // Convert ANSI user name and domain to Unicode
294 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
295 wszUserName
, WXSIZEOF(wszUserName
) );
296 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
297 wszDomain
, WXSIZEOF(wszDomain
) );
299 // Get the computer name of a DC for the domain.
300 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
302 wxLogError(wxT("Can not find domain controller"));
307 // Look up the user on the DC
308 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
309 (LPWSTR
)&wszUserName
,
310 2, // level - we want USER_INFO_2
318 case NERR_InvalidComputer
:
319 wxLogError(wxT("Invalid domain controller name."));
323 case NERR_UserNotFound
:
324 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
329 wxLogSysError(wxT("Can't get information about user"));
334 // Convert the Unicode full name to ANSI
335 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
336 buf
, maxSize
, NULL
, NULL
);
341 wxLogError(wxT("Couldn't look up full user name."));
344 #else // !USE_NET_API
345 // Could use NIS, MS-Mail or other site specific programs
346 // Use wxWindows configuration data
347 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
350 ok
= wxGetUserId(buf
, maxSize
);
355 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
363 const wxChar
* wxGetHomeDir(wxString
*pstr
)
365 wxString
& strDir
= *pstr
;
367 #if defined(__UNIX__) && !defined(__TWIN32__)
368 const wxChar
*szHome
= wxGetenv("HOME");
369 if ( szHome
== NULL
) {
371 wxLogWarning(_("can't find user's HOME, using current directory."));
377 // add a trailing slash if needed
378 if ( strDir
.Last() != wxT('/') )
382 // Cygwin returns unix type path but that does not work well
383 static wxChar windowsPath
[MAX_PATH
];
384 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
385 strDir
= windowsPath
;
391 // If we have a valid HOME directory, as is used on many machines that
392 // have unix utilities on them, we should use that.
393 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
395 if ( szHome
!= NULL
)
399 else // no HOME, try HOMEDRIVE/PATH
401 szHome
= wxGetenv(wxT("HOMEDRIVE"));
402 if ( szHome
!= NULL
)
404 szHome
= wxGetenv(wxT("HOMEPATH"));
406 if ( szHome
!= NULL
)
410 // the idea is that under NT these variables have default values
411 // of "%systemdrive%:" and "\\". As we don't want to create our
412 // config files in the root directory of the system drive, we will
413 // create it in our program's dir. However, if the user took care
414 // to set HOMEPATH to something other than "\\", we suppose that he
415 // knows what he is doing and use the supplied value.
416 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
421 if ( strDir
.empty() )
423 // If we have a valid USERPROFILE directory, as is the case in
424 // Windows NT, 2000 and XP, we should use that as our home directory.
425 szHome
= wxGetenv(wxT("USERPROFILE"));
427 if ( szHome
!= NULL
)
431 if ( !strDir
.empty() )
433 return strDir
.c_str();
435 //else: fall back to the prograrm directory
437 // Win16 has no idea about home, so use the executable directory instead
440 // 260 was taken from windef.h
446 ::GetModuleFileName(::GetModuleHandle(NULL
),
447 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
448 strPath
.UngetWriteBuf();
450 // extract the dir name
451 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
455 return strDir
.c_str();
458 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
460 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
461 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
462 // static buffer and sometimes I don't even know what.
463 static wxString s_home
;
465 return (wxChar
*)wxGetHomeDir(&s_home
);
468 bool wxDirExists(const wxString
& dir
)
470 #ifdef __WXMICROWIN__
471 return wxPathExist(dir
);
472 #elif defined(__WIN32__)
473 DWORD attribs
= GetFileAttributes(dir
);
474 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
477 struct ffblk fileInfo
;
479 struct find_t fileInfo
;
481 // In Borland findfirst has a different argument
482 // ordering from _dos_findfirst. But _dos_findfirst
483 // _should_ be ok in both MS and Borland... why not?
485 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
486 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
488 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
489 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
494 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
499 // old w32api don't have ULARGE_INTEGER
500 #if defined(__WIN32__) && \
501 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
502 // GetDiskFreeSpaceEx() is not available under original Win95, check for
504 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
510 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
512 ::GetModuleHandle(_T("kernel32.dll")),
514 "GetDiskFreeSpaceExW"
516 "GetDiskFreeSpaceExA"
520 if ( pGetDiskFreeSpaceEx
)
522 ULARGE_INTEGER bytesFree
, bytesTotal
;
524 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
525 if ( !pGetDiskFreeSpaceEx(path
,
530 wxLogLastError(_T("GetDiskFreeSpaceEx"));
535 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
536 // two 32 bit fields which may be or may be not named - try to make it
537 // compile in all cases
538 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
545 *pTotal
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
550 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
556 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
557 // should be used instead - but if it's not available, fall back on
558 // GetDiskFreeSpace() nevertheless...
560 DWORD lSectorsPerCluster
,
562 lNumberOfFreeClusters
,
563 lTotalNumberOfClusters
;
565 // FIXME: this is wrong, we should extract the root drive from path
566 // instead, but this is the job for wxFileName...
567 if ( !::GetDiskFreeSpace(path
,
570 &lNumberOfFreeClusters
,
571 &lTotalNumberOfClusters
) )
573 wxLogLastError(_T("GetDiskFreeSpace"));
578 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
579 lBytesPerCluster
*= lBytesPerSector
;
583 *pTotal
= lBytesPerCluster
;
584 *pTotal
*= lTotalNumberOfClusters
;
589 *pFree
= lBytesPerCluster
;
590 *pFree
*= lNumberOfFreeClusters
;
597 // ----------------------------------------------------------------------------
599 // ----------------------------------------------------------------------------
601 bool wxGetEnv(const wxString
& var
, wxString
*value
)
604 const wxChar
* ret
= wxGetenv(var
);
615 // first get the size of the buffer
616 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
619 // this means that there is no such variable
625 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
626 value
->UngetWriteBuf();
633 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
635 // some compilers have putenv() or _putenv() or _wputenv() but it's better
636 // to always use Win32 function directly instead of dealing with them
637 #if defined(__WIN32__)
638 if ( !::SetEnvironmentVariable(var
, value
) )
640 wxLogLastError(_T("SetEnvironmentVariable"));
646 #else // no way to set env vars
651 // ----------------------------------------------------------------------------
652 // process management
653 // ----------------------------------------------------------------------------
657 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
658 struct wxFindByPidParams
660 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
662 // the HWND used to return the result
665 // the PID we're looking from
668 DECLARE_NO_COPY_CLASS(wxFindByPidParams
)
671 // wxKill helper: EnumWindows() callback which is used to find the first (top
672 // level) window belonging to the given process
673 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
676 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
678 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
679 if ( pid
== params
->pid
)
681 // remember the window we found
684 // return FALSE to stop the enumeration
688 // continue enumeration
694 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
697 // get the process handle to operate on
698 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
700 PROCESS_QUERY_INFORMATION
,
701 FALSE
, // not inheritable
703 if ( hProcess
== NULL
)
707 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
709 *krc
= wxKILL_ACCESS_DENIED
;
713 *krc
= wxKILL_NO_PROCESS
;
724 // kill the process forcefully returning -1 as error code
725 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
727 wxLogSysError(_("Failed to kill process %d"), pid
);
731 // this is not supposed to happen if we could open the
741 // do nothing, we just want to test for process existence
745 // any other signal means "terminate"
747 wxFindByPidParams params
;
748 params
.pid
= (DWORD
)pid
;
750 // EnumWindows() has nice semantics: it returns 0 if it found
751 // something or if an error occured and non zero if it
752 // enumerated all the window
753 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
755 // did we find any window?
758 // tell the app to close
760 // NB: this is the harshest way, the app won't have
761 // opportunity to save any files, for example, but
762 // this is probably what we want here. If not we
763 // can also use SendMesageTimeout(WM_CLOSE)
764 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
766 wxLogLastError(_T("PostMessage(WM_QUIT)"));
769 else // it was an error then
771 wxLogLastError(_T("EnumWindows"));
776 else // no windows for this PID
793 // as we wait for a short time, we can use just WaitForSingleObject()
794 // and not MsgWaitForMultipleObjects()
795 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
798 // process terminated
799 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
801 wxLogLastError(_T("GetExitCodeProcess"));
806 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
810 wxLogLastError(_T("WaitForSingleObject"));
825 // just to suppress the warnings about uninitialized variable
829 ::CloseHandle(hProcess
);
831 // the return code is the same as from Unix kill(): 0 if killed
832 // successfully or -1 on error
833 if ( sig
== wxSIGNONE
)
835 if ( ok
&& rc
== STILL_ACTIVE
)
837 // there is such process => success
843 if ( ok
&& rc
!= STILL_ACTIVE
)
850 wxFAIL_MSG( _T("not implemented") );
851 #endif // Win32/Win16
857 // Execute a program in an Interactive Shell
858 bool wxShell(const wxString
& command
)
860 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
862 shell
= (wxChar
*) wxT("\\COMMAND.COM");
872 // pass the command to execute to the command processor
873 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
876 return wxExecute(cmd
, wxEXEC_SYNC
) == 0;
879 // Shutdown or reboot the PC
880 bool wxShutdown(wxShutdownFlags wFlags
)
885 if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_NT
) // if is NT or 2K
887 // Get a token for this process.
889 bOK
= ::OpenProcessToken(GetCurrentProcess(),
890 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
894 TOKEN_PRIVILEGES tkp
;
896 // Get the LUID for the shutdown privilege.
897 ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
898 &tkp
.Privileges
[0].Luid
);
900 tkp
.PrivilegeCount
= 1; // one privilege to set
901 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
903 // Get the shutdown privilege for this process.
904 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
905 (PTOKEN_PRIVILEGES
)NULL
, 0);
907 // Cannot test the return value of AdjustTokenPrivileges.
908 bOK
= ::GetLastError() == ERROR_SUCCESS
;
914 UINT flags
= EWX_SHUTDOWN
| EWX_FORCE
;
917 case wxSHUTDOWN_POWEROFF
:
918 flags
|= EWX_POWEROFF
;
921 case wxSHUTDOWN_REBOOT
:
926 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
930 bOK
= ::ExitWindowsEx(EWX_SHUTDOWN
| EWX_FORCE
| EWX_REBOOT
, 0) != 0;
939 // ----------------------------------------------------------------------------
941 // ----------------------------------------------------------------------------
943 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
944 long wxGetFreeMemory()
946 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
947 MEMORYSTATUS memStatus
;
948 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
949 GlobalMemoryStatus(&memStatus
);
950 return memStatus
.dwAvailPhys
;
952 return (long)GetFreeSpace(0);
956 unsigned long wxGetProcessId()
959 return ::GetCurrentProcessId();
968 ::MessageBeep((UINT
)-1); // default sound
971 wxString
wxGetOsDescription()
979 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
980 if ( ::GetVersionEx(&info
) )
982 switch ( info
.dwPlatformId
)
984 case VER_PLATFORM_WIN32s
:
985 str
= _("Win32s on Windows 3.1");
988 case VER_PLATFORM_WIN32_WINDOWS
:
989 str
.Printf(_("Windows 9%c"),
990 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
991 if ( !wxIsEmpty(info
.szCSDVersion
) )
993 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
997 case VER_PLATFORM_WIN32_NT
:
998 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
1000 info
.dwMinorVersion
,
1001 info
.dwBuildNumber
);
1002 if ( !wxIsEmpty(info
.szCSDVersion
) )
1004 str
<< _T(", ") << info
.szCSDVersion
;
1012 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1017 return _("Windows 3.1");
1021 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1023 #if defined(__WIN32__) && !defined(__SC__)
1024 static int ver
= -1, major
= -1, minor
= -1;
1032 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1033 if ( ::GetVersionEx(&info
) )
1035 major
= info
.dwMajorVersion
;
1036 minor
= info
.dwMinorVersion
;
1038 switch ( info
.dwPlatformId
)
1040 case VER_PLATFORM_WIN32s
:
1044 case VER_PLATFORM_WIN32_WINDOWS
:
1048 case VER_PLATFORM_WIN32_NT
:
1055 if (majorVsn
&& major
!= -1)
1057 if (minorVsn
&& minor
!= -1)
1062 int retValue
= wxWINDOWS
;
1063 #ifdef __WINDOWS_386__
1064 retValue
= wxWIN386
;
1066 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
1067 extern HANDLE g_hPenWin
;
1068 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
1081 // ----------------------------------------------------------------------------
1083 // ----------------------------------------------------------------------------
1089 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1090 static bool gs_inTimer
= FALSE
;
1092 class wxSleepTimer
: public wxTimer
1095 virtual void Notify()
1102 static wxTimer
*wxTheSleepTimer
= NULL
;
1104 void wxUsleep(unsigned long milliseconds
)
1107 ::Sleep(milliseconds
);
1111 if (miliseconds
<= 0)
1114 wxTheSleepTimer
= new wxSleepTimer
;
1116 wxTheSleepTimer
->Start(milliseconds
);
1119 if (wxTheApp
->Pending())
1120 wxTheApp
->Dispatch();
1122 delete wxTheSleepTimer
;
1123 wxTheSleepTimer
= NULL
;
1124 #endif // Win32/!Win32
1127 void wxSleep(int nSecs
)
1134 wxTheSleepTimer
= new wxSleepTimer
;
1136 wxTheSleepTimer
->Start(nSecs
*1000);
1139 if (wxTheApp
->Pending())
1140 wxTheApp
->Dispatch();
1142 delete wxTheSleepTimer
;
1143 wxTheSleepTimer
= NULL
;
1146 // Consume all events until no more left
1147 void wxFlushEvents()
1152 #endif // wxUSE_TIMER
1154 #elif defined(__WIN32__) // wxUSE_GUI
1156 void wxUsleep(unsigned long milliseconds
)
1158 ::Sleep(milliseconds
);
1161 void wxSleep(int nSecs
)
1163 wxUsleep(1000*nSecs
);
1166 #endif // wxUSE_GUI/!wxUSE_GUI
1167 #endif // __WXMICROWIN__
1169 // ----------------------------------------------------------------------------
1170 // deprecated (in favour of wxLog) log functions
1171 // ----------------------------------------------------------------------------
1173 #if WXWIN_COMPATIBILITY_2_2
1175 // Output a debug mess., in a system dependent fashion.
1176 #ifndef __WXMICROWIN__
1177 void wxDebugMsg(const wxChar
*fmt
...)
1180 static wxChar buffer
[512];
1182 if (!wxTheApp
->GetWantDebugOutput())
1187 wvsprintf(buffer
,fmt
,ap
);
1188 OutputDebugString((LPCTSTR
)buffer
);
1193 // Non-fatal error: pop up message box and (possibly) continue
1194 void wxError(const wxString
& msg
, const wxString
& title
)
1196 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
1197 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
1198 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
1202 // Fatal error: pop up message box and abort
1203 void wxFatalError(const wxString
& msg
, const wxString
& title
)
1205 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
1206 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
1208 #endif // __WXMICROWIN__
1210 #endif // WXWIN_COMPATIBILITY_2_2
1214 // ----------------------------------------------------------------------------
1215 // functions to work with .INI files
1216 // ----------------------------------------------------------------------------
1218 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1220 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
1222 if (file
!= wxT(""))
1223 // Don't know what the correct cast should be, but it doesn't
1224 // compile in BC++/16-bit without this cast.
1225 #if !defined(__WIN32__)
1226 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
1228 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
1231 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
1234 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
1237 buf
.Printf(wxT("%.4f"), value
);
1239 return wxWriteResource(section
, entry
, buf
, file
);
1242 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1245 buf
.Printf(wxT("%ld"), value
);
1247 return wxWriteResource(section
, entry
, buf
, file
);
1250 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1253 buf
.Printf(wxT("%d"), value
);
1255 return wxWriteResource(section
, entry
, buf
, file
);
1258 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1260 static const wxChar defunkt
[] = wxT("$$default");
1261 if (file
!= wxT(""))
1263 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1264 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1265 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1270 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1271 (LPTSTR
)wxBuffer
, 1000);
1272 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1275 if (*value
) delete[] (*value
);
1276 *value
= copystring(wxBuffer
);
1280 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1283 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1286 *value
= (float)wxStrtod(s
, NULL
);
1293 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1296 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1299 *value
= wxStrtol(s
, NULL
, 10);
1306 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1309 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1312 *value
= (int)wxStrtol(s
, NULL
, 10);
1318 #endif // wxUSE_RESOURCES
1320 // ---------------------------------------------------------------------------
1321 // helper functions for showing a "busy" cursor
1322 // ---------------------------------------------------------------------------
1324 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1325 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1326 static int gs_wxBusyCursorCount
= 0;
1328 extern HCURSOR
wxGetCurrentBusyCursor()
1330 return gs_wxBusyCursor
;
1333 // Set the cursor to the busy cursor for all windows
1334 void wxBeginBusyCursor(wxCursor
*cursor
)
1336 if ( gs_wxBusyCursorCount
++ == 0 )
1338 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1339 #ifndef __WXMICROWIN__
1340 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1343 //else: nothing to do, already set
1346 // Restore cursor to normal
1347 void wxEndBusyCursor()
1349 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1350 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1352 if ( --gs_wxBusyCursorCount
== 0 )
1354 #ifndef __WXMICROWIN__
1355 ::SetCursor(gs_wxBusyCursorOld
);
1357 gs_wxBusyCursorOld
= 0;
1361 // TRUE if we're between the above two calls
1364 return gs_wxBusyCursorCount
> 0;
1367 // Check whether this window wants to process messages, e.g. Stop button
1368 // in long calculations.
1369 bool wxCheckForInterrupt(wxWindow
*wnd
)
1371 wxCHECK( wnd
, FALSE
);
1374 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1376 ::TranslateMessage(&msg
);
1377 ::DispatchMessage(&msg
);
1383 // MSW only: get user-defined resource from the .res file.
1384 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1386 #ifndef __WXMICROWIN__
1387 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1389 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1390 if ( hResource
== 0 )
1393 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1397 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1401 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1402 // so we need to find the length of the resource.
1403 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1404 wxChar
*s
= new wxChar
[len
+1];
1405 wxStrncpy(s
,theText
,len
);
1408 // wxChar *s = copystring(theText);
1410 // Obsolete in WIN32
1412 UnlockResource(hData
);
1416 // GlobalFree(hData);
1420 #endif // __WXMICROWIN__
1422 // ----------------------------------------------------------------------------
1424 // ----------------------------------------------------------------------------
1426 // See also the wxGetMousePosition in window.cpp
1427 // Deprecated: use wxPoint wxGetMousePosition() instead
1428 void wxGetMousePosition( int* x
, int* y
)
1431 GetCursorPos( & pt
);
1436 // Return TRUE if we have a colour display
1437 bool wxColourDisplay()
1439 #ifdef __WXMICROWIN__
1443 // this function is called from wxDC ctor so it is called a *lot* of times
1444 // hence we optimize it a bit but doign the check only once
1446 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1448 static int s_isColour
= -1;
1450 if ( s_isColour
== -1 )
1453 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1455 s_isColour
= (noCols
== -1) || (noCols
> 2);
1458 return s_isColour
!= 0;
1462 // Returns depth of screen
1463 int wxDisplayDepth()
1466 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1469 // Get size of display
1470 void wxDisplaySize(int *width
, int *height
)
1472 #ifdef __WXMICROWIN__
1474 HWND hWnd
= GetDesktopWindow();
1475 ::GetWindowRect(hWnd
, & rect
);
1478 *width
= rect
.right
- rect
.left
;
1480 *height
= rect
.bottom
- rect
.top
;
1481 #else // !__WXMICROWIN__
1485 *width
= ::GetDeviceCaps(dc
, HORZRES
);
1487 *height
= ::GetDeviceCaps(dc
, VERTRES
);
1488 #endif // __WXMICROWIN__/!__WXMICROWIN__
1491 void wxDisplaySizeMM(int *width
, int *height
)
1493 #ifdef __WXMICROWIN__
1503 *width
= ::GetDeviceCaps(dc
, HORZSIZE
);
1505 *height
= ::GetDeviceCaps(dc
, VERTSIZE
);
1509 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1511 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1513 wxDisplaySize(width
, height
);
1515 // Determine the desktop dimensions minus the taskbar and any other
1516 // special decorations...
1519 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1522 if (width
) *width
= r
.right
- r
.left
;
1523 if (height
) *height
= r
.bottom
- r
.top
;
1527 // ---------------------------------------------------------------------------
1528 // window information functions
1529 // ---------------------------------------------------------------------------
1531 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1537 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1538 ::GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1539 str
.UngetWriteBuf();
1545 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1550 #ifndef __WXMICROWIN__
1553 int len
= 256; // some starting value
1557 int count
= ::GetClassName((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1559 str
.UngetWriteBuf();
1562 // the class name might have been truncated, retry with larger
1572 #endif // !__WXMICROWIN__
1577 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1580 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1582 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1586 // ----------------------------------------------------------------------------
1588 // ----------------------------------------------------------------------------
1590 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1594 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1595 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1596 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1597 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1599 *x
*= (iWidthMM
* 100);
1601 *y
*= (iHeightMM
* 100);
1605 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1609 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1610 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1611 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1612 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1615 *x
/= (iWidthMM
* 100);
1617 *y
/= (iHeightMM
* 100);
1622 #ifdef __WXMICROWIN__
1623 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1626 if (majorVsn
) *majorVsn
= 0;
1627 if (minorVsn
) *minorVsn
= 0;
1630 #endif // __WXMICROWIN__
1632 // ----------------------------------------------------------------------------
1633 // Win32 codepage conversion functions
1634 // ----------------------------------------------------------------------------
1636 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1638 // wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1639 #if wxUSE_GUI && !defined(__WXUNIVERSAL__)
1641 #include "wx/fontmap.h"
1643 // VZ: the new version of wxCharsetToCodepage() is more politically correct
1644 // and should work on other Windows versions as well but the old version is
1645 // still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
1647 extern long wxEncodingToCodepage(wxFontEncoding encoding
)
1649 // translate encoding into the Windows CHARSET
1650 wxNativeEncodingInfo natveEncInfo
;
1651 if ( !wxGetNativeFontEncoding(encoding
, &natveEncInfo
) )
1654 // translate CHARSET to code page
1655 CHARSETINFO csetInfo
;
1656 if ( !::TranslateCharsetInfo((DWORD
*)(DWORD
)natveEncInfo
.charset
,
1660 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1665 return csetInfo
.ciACP
;
1670 extern long wxCharsetToCodepage(const wxChar
*name
)
1672 // first get the font encoding for this charset
1676 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(name
, FALSE
);
1677 if ( enc
== wxFONTENCODING_SYSTEM
)
1680 // the use the helper function
1681 return wxEncodingToCodepage(enc
);
1684 #endif // wxUSE_FONTMAP
1688 // include old wxCharsetToCodepage() by OK if needed
1689 #if !wxUSE_GUI || !wxUSE_FONTMAP
1691 #include "wx/msw/registry.h"
1693 // this should work if Internet Exploiter is installed
1694 extern long wxCharsetToCodepage(const wxChar
*name
)
1703 wxString
path(wxT("MIME\\Database\\Charset\\"));
1705 wxRegKey
key(wxRegKey::HKCR
, path
);
1707 if (!key
.Exists()) break;
1709 // two cases: either there's an AliasForCharset string,
1710 // or there are Codepage and InternetEncoding dwords.
1711 // The InternetEncoding gives us the actual encoding,
1712 // the Codepage just says which Windows character set to
1713 // use when displaying the data.
1714 if (key
.HasValue(wxT("InternetEncoding")) &&
1715 key
.QueryValue(wxT("InternetEncoding"), &CP
)) break;
1717 // no encoding, see if it's an alias
1718 if (!key
.HasValue(wxT("AliasForCharset")) ||
1719 !key
.QueryValue(wxT("AliasForCharset"), cn
)) break;
1725 #endif // !wxUSE_GUI || !wxUSE_FONTMAP