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"
37 #include "wx/cursor.h"
41 // In some mingws there is a missing extern "C" int the winsock header,
42 // so we put it here just to be safe. Note that this must appear _before_
43 // #include "wx/msw/private.h" which itself includes <windows.h>, as this
44 // one in turn includes <winsock.h> unless we define WIN32_LEAN_AND_MEAN.
46 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
48 #include <winsock.h> // we use socket functions in wxGetFullHostName()
52 #include "wx/msw/private.h" // includes <windows.h>
56 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
64 #if defined(__CYGWIN__) && !defined(__TWIN32__)
65 #include <sys/unistd.h>
67 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
70 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
71 // this (3.1 I believe) and how to test for it.
72 // If this works for Borland 4.0 as well, then no worries.
76 // VZ: there is some code using NetXXX() functions to get the full user name:
77 // I don't think it's a good idea because they don't work under Win95 and
78 // seem to return the same as wxGetUserId() under NT. If you really want
79 // to use them, just #define USE_NET_API
86 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
95 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
100 //// BEGIN for console support: VC++ only
103 #include "wx/msw/msvcrt.h"
107 #include "wx/ioswrap.h"
109 /* Need to undef new if including crtdbg.h */
118 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
119 # define new new(__TFILE__,__LINE__)
124 /// END for console support
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 // In the WIN.INI file
131 static const wxChar WX_SECTION
[] = wxT("wxWindows");
132 static const wxChar eUSERNAME
[] = wxT("UserName");
134 // these are only used under Win16
135 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
136 static const wxChar eHOSTNAME
[] = wxT("HostName");
137 static const wxChar eUSERID
[] = wxT("UserId");
140 #ifndef __WXMICROWIN__
142 // ============================================================================
144 // ============================================================================
146 // ----------------------------------------------------------------------------
147 // get host name and related
148 // ----------------------------------------------------------------------------
150 // Get hostname only (without domain name)
151 bool wxGetHostName(wxChar
*buf
, int maxSize
)
153 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
154 DWORD nSize
= maxSize
;
155 if ( !::GetComputerName(buf
, &nSize
) )
157 wxLogLastError(wxT("GetComputerName"));
165 const wxChar
*default_host
= wxT("noname");
167 if ((sysname
= wxGetenv(wxT("SYSTEM_NAME"))) == NULL
) {
168 GetProfileString(WX_SECTION
, eHOSTNAME
, default_host
, buf
, maxSize
- 1);
170 wxStrncpy(buf
, sysname
, maxSize
- 1);
171 buf
[maxSize
] = wxT('\0');
172 return *buf
? TRUE
: FALSE
;
176 // get full hostname (with domain name if possible)
177 bool wxGetFullHostName(wxChar
*buf
, int maxSize
)
179 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
180 // TODO should use GetComputerNameEx() when available
182 // the idea is that if someone had set wxUSE_SOCKETS to 0 the code
183 // shouldn't use winsock.dll (a.k.a. ws2_32.dll) at all so only use this
184 // code if we link with it anyhow
187 if ( WSAStartup(MAKEWORD(1, 1), &wsa
) == 0 )
191 if ( gethostname(bufA
, WXSIZEOF(bufA
)) == 0 )
193 // gethostname() won't usually include the DNS domain name, for
194 // this we need to work a bit more
195 if ( !strchr(bufA
, '.') )
197 struct hostent
*pHostEnt
= gethostbyname(bufA
);
201 // Windows will use DNS internally now
202 pHostEnt
= gethostbyaddr(pHostEnt
->h_addr
, 4, PF_INET
);
207 host
= pHostEnt
->h_name
;
216 wxStrncpy(buf
, host
, maxSize
);
221 #endif // wxUSE_SOCKETS
225 return wxGetHostName(buf
, maxSize
);
228 // Get user ID e.g. jacs
229 bool wxGetUserId(wxChar
*buf
, int maxSize
)
231 #if defined(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
232 DWORD nSize
= maxSize
;
233 if ( ::GetUserName(buf
, &nSize
) == 0 )
235 // actually, it does happen on Win9x if the user didn't log on
236 DWORD res
= ::GetEnvironmentVariable(wxT("username"), buf
, maxSize
);
245 #else // Win16 or Win32s
247 const wxChar
*default_id
= wxT("anonymous");
249 // Can't assume we have NIS (PC-NFS) or some other ID daemon
251 if ( (user
= wxGetenv(wxT("USER"))) == NULL
&&
252 (user
= wxGetenv(wxT("LOGNAME"))) == NULL
)
254 // Use wxWindows configuration data (comming soon)
255 GetProfileString(WX_SECTION
, eUSERID
, default_id
, buf
, maxSize
- 1);
259 wxStrncpy(buf
, user
, maxSize
- 1);
262 return *buf
? TRUE
: FALSE
;
266 // Get user name e.g. Julian Smart
267 bool wxGetUserName(wxChar
*buf
, int maxSize
)
269 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
270 extern HANDLE g_hPenWin
; // PenWindows Running?
273 // PenWindows Does have a user concept!
274 // Get the current owner of the recognizer
275 GetPrivateProfileString("Current", "User", default_name
, wxBuffer
, maxSize
- 1, "PENWIN.INI");
276 strncpy(buf
, wxBuffer
, maxSize
- 1);
282 CHAR szUserName
[256];
283 if ( !wxGetUserId(szUserName
, WXSIZEOF(szUserName
)) )
286 // TODO how to get the domain name?
289 // the code is based on the MSDN example (also see KB article Q119670)
290 WCHAR wszUserName
[256]; // Unicode user name
291 WCHAR wszDomain
[256];
294 USER_INFO_2
*ui2
; // User structure
296 // Convert ANSI user name and domain to Unicode
297 MultiByteToWideChar( CP_ACP
, 0, szUserName
, strlen(szUserName
)+1,
298 wszUserName
, WXSIZEOF(wszUserName
) );
299 MultiByteToWideChar( CP_ACP
, 0, szDomain
, strlen(szDomain
)+1,
300 wszDomain
, WXSIZEOF(wszDomain
) );
302 // Get the computer name of a DC for the domain.
303 if ( NetGetDCName( NULL
, wszDomain
, &ComputerName
) != NERR_Success
)
305 wxLogError(wxT("Can not find domain controller"));
310 // Look up the user on the DC
311 NET_API_STATUS status
= NetUserGetInfo( (LPWSTR
)ComputerName
,
312 (LPWSTR
)&wszUserName
,
313 2, // level - we want USER_INFO_2
321 case NERR_InvalidComputer
:
322 wxLogError(wxT("Invalid domain controller name."));
326 case NERR_UserNotFound
:
327 wxLogError(wxT("Invalid user name '%s'."), szUserName
);
332 wxLogSysError(wxT("Can't get information about user"));
337 // Convert the Unicode full name to ANSI
338 WideCharToMultiByte( CP_ACP
, 0, ui2
->usri2_full_name
, -1,
339 buf
, maxSize
, NULL
, NULL
);
344 wxLogError(wxT("Couldn't look up full user name."));
347 #else // !USE_NET_API
348 // Could use NIS, MS-Mail or other site specific programs
349 // Use wxWindows configuration data
350 bool ok
= GetProfileString(WX_SECTION
, eUSERNAME
, wxT(""), buf
, maxSize
- 1) != 0;
353 ok
= wxGetUserId(buf
, maxSize
);
358 wxStrncpy(buf
, wxT("Unknown User"), maxSize
);
366 const wxChar
* wxGetHomeDir(wxString
*pstr
)
368 wxString
& strDir
= *pstr
;
370 #if defined(__UNIX__) && !defined(__TWIN32__)
371 const wxChar
*szHome
= wxGetenv("HOME");
372 if ( szHome
== NULL
) {
374 wxLogWarning(_("can't find user's HOME, using current directory."));
380 // add a trailing slash if needed
381 if ( strDir
.Last() != wxT('/') )
385 // Cygwin returns unix type path but that does not work well
386 static wxChar windowsPath
[MAX_PATH
];
387 cygwin_conv_to_full_win32_path(strDir
, windowsPath
);
388 strDir
= windowsPath
;
394 // If we have a valid HOME directory, as is used on many machines that
395 // have unix utilities on them, we should use that.
396 const wxChar
*szHome
= wxGetenv(wxT("HOME"));
398 if ( szHome
!= NULL
)
402 else // no HOME, try HOMEDRIVE/PATH
404 szHome
= wxGetenv(wxT("HOMEDRIVE"));
405 if ( szHome
!= NULL
)
407 szHome
= wxGetenv(wxT("HOMEPATH"));
409 if ( szHome
!= NULL
)
413 // the idea is that under NT these variables have default values
414 // of "%systemdrive%:" and "\\". As we don't want to create our
415 // config files in the root directory of the system drive, we will
416 // create it in our program's dir. However, if the user took care
417 // to set HOMEPATH to something other than "\\", we suppose that he
418 // knows what he is doing and use the supplied value.
419 if ( wxStrcmp(szHome
, wxT("\\")) == 0 )
424 if ( strDir
.empty() )
426 // If we have a valid USERPROFILE directory, as is the case in
427 // Windows NT, 2000 and XP, we should use that as our home directory.
428 szHome
= wxGetenv(wxT("USERPROFILE"));
430 if ( szHome
!= NULL
)
434 if ( !strDir
.empty() )
436 return strDir
.c_str();
438 //else: fall back to the prograrm directory
440 // Win16 has no idea about home, so use the executable directory instead
443 // 260 was taken from windef.h
449 ::GetModuleFileName(::GetModuleHandle(NULL
),
450 strPath
.GetWriteBuf(MAX_PATH
), MAX_PATH
);
451 strPath
.UngetWriteBuf();
453 // extract the dir name
454 wxSplitPath(strPath
, &strDir
, NULL
, NULL
);
458 return strDir
.c_str();
461 wxChar
*wxGetUserHome(const wxString
& WXUNUSED(user
))
463 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
464 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
465 // static buffer and sometimes I don't even know what.
466 static wxString s_home
;
468 return (wxChar
*)wxGetHomeDir(&s_home
);
471 bool wxDirExists(const wxString
& dir
)
473 #ifdef __WXMICROWIN__
474 return wxPathExist(dir
);
475 #elif defined(__WIN32__)
476 DWORD attribs
= GetFileAttributes(dir
);
477 return ((attribs
!= (DWORD
)-1) && (attribs
& FILE_ATTRIBUTE_DIRECTORY
));
480 struct ffblk fileInfo
;
482 struct find_t fileInfo
;
484 // In Borland findfirst has a different argument
485 // ordering from _dos_findfirst. But _dos_findfirst
486 // _should_ be ok in both MS and Borland... why not?
488 return (findfirst(dir
, &fileInfo
, _A_SUBDIR
) == 0 &&
489 (fileInfo
.ff_attrib
& _A_SUBDIR
) != 0);
491 return (_dos_findfirst(dir
, _A_SUBDIR
, &fileInfo
) == 0) &&
492 ((fileInfo
.attrib
& _A_SUBDIR
) != 0);
497 bool wxGetDiskSpace(const wxString
& path
, wxLongLong
*pTotal
, wxLongLong
*pFree
)
502 // old w32api don't have ULARGE_INTEGER
503 #if defined(__WIN32__) && \
504 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
505 // GetDiskFreeSpaceEx() is not available under original Win95, check for
507 typedef BOOL (WINAPI
*GetDiskFreeSpaceEx_t
)(LPCTSTR
,
513 pGetDiskFreeSpaceEx
= (GetDiskFreeSpaceEx_t
)::GetProcAddress
515 ::GetModuleHandle(_T("kernel32.dll")),
517 "GetDiskFreeSpaceExW"
519 "GetDiskFreeSpaceExA"
523 if ( pGetDiskFreeSpaceEx
)
525 ULARGE_INTEGER bytesFree
, bytesTotal
;
527 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
528 if ( !pGetDiskFreeSpaceEx(path
,
533 wxLogLastError(_T("GetDiskFreeSpaceEx"));
538 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
539 // two 32 bit fields which may be or may be not named - try to make it
540 // compile in all cases
541 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
548 *pTotal
= wxLongLong(UL(bytesTotal
).HighPart
, UL(bytesTotal
).LowPart
);
553 *pFree
= wxLongLong(UL(bytesFree
).HighPart
, UL(bytesFree
).LowPart
);
559 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
560 // should be used instead - but if it's not available, fall back on
561 // GetDiskFreeSpace() nevertheless...
563 DWORD lSectorsPerCluster
,
565 lNumberOfFreeClusters
,
566 lTotalNumberOfClusters
;
568 // FIXME: this is wrong, we should extract the root drive from path
569 // instead, but this is the job for wxFileName...
570 if ( !::GetDiskFreeSpace(path
,
573 &lNumberOfFreeClusters
,
574 &lTotalNumberOfClusters
) )
576 wxLogLastError(_T("GetDiskFreeSpace"));
581 wxLongLong lBytesPerCluster
= lSectorsPerCluster
;
582 lBytesPerCluster
*= lBytesPerSector
;
586 *pTotal
= lBytesPerCluster
;
587 *pTotal
*= lTotalNumberOfClusters
;
592 *pFree
= lBytesPerCluster
;
593 *pFree
*= lNumberOfFreeClusters
;
600 // ----------------------------------------------------------------------------
602 // ----------------------------------------------------------------------------
604 bool wxGetEnv(const wxString
& var
, wxString
*value
)
607 const wxChar
* ret
= wxGetenv(var
);
616 // first get the size of the buffer
617 DWORD dwRet
= ::GetEnvironmentVariable(var
, NULL
, 0);
620 // this means that there is no such variable
626 (void)::GetEnvironmentVariable(var
, value
->GetWriteBuf(dwRet
), dwRet
);
627 value
->UngetWriteBuf();
634 bool wxSetEnv(const wxString
& var
, const wxChar
*value
)
636 // some compilers have putenv() or _putenv() or _wputenv() but it's better
637 // to always use Win32 function directly instead of dealing with them
638 #if defined(__WIN32__)
639 if ( !::SetEnvironmentVariable(var
, value
) )
641 wxLogLastError(_T("SetEnvironmentVariable"));
647 #else // no way to set env vars
652 // ----------------------------------------------------------------------------
653 // process management
654 // ----------------------------------------------------------------------------
658 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
659 struct wxFindByPidParams
661 wxFindByPidParams() { hwnd
= 0; pid
= 0; }
663 // the HWND used to return the result
666 // the PID we're looking from
670 // wxKill helper: EnumWindows() callback which is used to find the first (top
671 // level) window belonging to the given process
672 BOOL CALLBACK
wxEnumFindByPidProc(HWND hwnd
, LPARAM lParam
)
675 (void)::GetWindowThreadProcessId(hwnd
, &pid
);
677 wxFindByPidParams
*params
= (wxFindByPidParams
*)lParam
;
678 if ( pid
== params
->pid
)
680 // remember the window we found
683 // return FALSE to stop the enumeration
687 // continue enumeration
693 int wxKill(long pid
, wxSignal sig
, wxKillError
*krc
)
696 // get the process handle to operate on
697 HANDLE hProcess
= ::OpenProcess(SYNCHRONIZE
|
699 PROCESS_QUERY_INFORMATION
,
700 FALSE
, // not inheritable
702 if ( hProcess
== NULL
)
706 if ( ::GetLastError() == ERROR_ACCESS_DENIED
)
708 *krc
= wxKILL_ACCESS_DENIED
;
712 *krc
= wxKILL_NO_PROCESS
;
723 // kill the process forcefully returning -1 as error code
724 if ( !::TerminateProcess(hProcess
, (UINT
)-1) )
726 wxLogSysError(_("Failed to kill process %d"), pid
);
730 // this is not supposed to happen if we could open the
740 // do nothing, we just want to test for process existence
744 // any other signal means "terminate"
746 wxFindByPidParams params
;
747 params
.pid
= (DWORD
)pid
;
749 // EnumWindows() has nice semantics: it returns 0 if it found
750 // something or if an error occured and non zero if it
751 // enumerated all the window
752 if ( !::EnumWindows(wxEnumFindByPidProc
, (LPARAM
)¶ms
) )
754 // did we find any window?
757 // tell the app to close
759 // NB: this is the harshest way, the app won't have
760 // opportunity to save any files, for example, but
761 // this is probably what we want here. If not we
762 // can also use SendMesageTimeout(WM_CLOSE)
763 if ( !::PostMessage(params
.hwnd
, WM_QUIT
, 0, 0) )
765 wxLogLastError(_T("PostMessage(WM_QUIT)"));
768 else // it was an error then
770 wxLogLastError(_T("EnumWindows"));
775 else // no windows for this PID
792 // as we wait for a short time, we can use just WaitForSingleObject()
793 // and not MsgWaitForMultipleObjects()
794 switch ( ::WaitForSingleObject(hProcess
, 500 /* msec */) )
797 // process terminated
798 if ( !::GetExitCodeProcess(hProcess
, &rc
) )
800 wxLogLastError(_T("GetExitCodeProcess"));
805 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
809 wxLogLastError(_T("WaitForSingleObject"));
824 // just to suppress the warnings about uninitialized variable
828 ::CloseHandle(hProcess
);
830 // the return code is the same as from Unix kill(): 0 if killed
831 // successfully or -1 on error
832 if ( sig
== wxSIGNONE
)
834 if ( ok
&& rc
== STILL_ACTIVE
)
836 // there is such process => success
842 if ( ok
&& rc
!= STILL_ACTIVE
)
849 wxFAIL_MSG( _T("not implemented") );
850 #endif // Win32/Win16
856 // Execute a program in an Interactive Shell
857 bool wxShell(const wxString
& command
)
859 wxChar
*shell
= wxGetenv(wxT("COMSPEC"));
861 shell
= wxT("\\COMMAND.COM");
871 // pass the command to execute to the command processor
872 cmd
.Printf(wxT("%s /c %s"), shell
, command
.c_str());
875 return wxExecute(cmd
, TRUE
/* sync */) != 0;
878 // Shutdown or reboot the PC
879 bool wxShutdown(wxShutdownFlags wFlags
)
884 if ( wxGetOsVersion(NULL
, NULL
) == wxWINDOWS_NT
) // if is NT or 2K
886 // Get a token for this process.
888 bOK
= ::OpenProcessToken(GetCurrentProcess(),
889 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
893 TOKEN_PRIVILEGES tkp
;
895 // Get the LUID for the shutdown privilege.
896 ::LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
,
897 &tkp
.Privileges
[0].Luid
);
899 tkp
.PrivilegeCount
= 1; // one privilege to set
900 tkp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
902 // Get the shutdown privilege for this process.
903 ::AdjustTokenPrivileges(hToken
, FALSE
, &tkp
, 0,
904 (PTOKEN_PRIVILEGES
)NULL
, 0);
906 // Cannot test the return value of AdjustTokenPrivileges.
907 bOK
= ::GetLastError() == ERROR_SUCCESS
;
913 UINT flags
= EWX_SHUTDOWN
| EWX_FORCE
;
916 case wxSHUTDOWN_POWEROFF
:
917 flags
|= EWX_POWEROFF
;
920 case wxSHUTDOWN_REBOOT
:
925 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
929 bOK
= ::ExitWindowsEx(EWX_SHUTDOWN
| EWX_FORCE
| EWX_REBOOT
, 0) != 0;
938 // ----------------------------------------------------------------------------
940 // ----------------------------------------------------------------------------
942 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
943 long wxGetFreeMemory()
945 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
946 MEMORYSTATUS memStatus
;
947 memStatus
.dwLength
= sizeof(MEMORYSTATUS
);
948 GlobalMemoryStatus(&memStatus
);
949 return memStatus
.dwAvailPhys
;
951 return (long)GetFreeSpace(0);
958 ::MessageBeep((UINT
)-1); // default sound
961 wxString
wxGetOsDescription()
969 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
970 if ( ::GetVersionEx(&info
) )
972 switch ( info
.dwPlatformId
)
974 case VER_PLATFORM_WIN32s
:
975 str
= _("Win32s on Windows 3.1");
978 case VER_PLATFORM_WIN32_WINDOWS
:
979 str
.Printf(_("Windows 9%c"),
980 info
.dwMinorVersion
== 0 ? _T('5') : _T('8'));
981 if ( !wxIsEmpty(info
.szCSDVersion
) )
983 str
<< _T(" (") << info
.szCSDVersion
<< _T(')');
987 case VER_PLATFORM_WIN32_NT
:
988 str
.Printf(_T("Windows NT %lu.%lu (build %lu"),
992 if ( !wxIsEmpty(info
.szCSDVersion
) )
994 str
<< _T(", ") << info
.szCSDVersion
;
1002 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1007 return _("Windows 3.1");
1011 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1013 #if defined(__WIN32__) && !defined(__SC__)
1014 static int ver
= -1, major
= -1, minor
= -1;
1022 info
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1023 if ( ::GetVersionEx(&info
) )
1025 major
= info
.dwMajorVersion
;
1026 minor
= info
.dwMinorVersion
;
1028 switch ( info
.dwPlatformId
)
1030 case VER_PLATFORM_WIN32s
:
1034 case VER_PLATFORM_WIN32_WINDOWS
:
1038 case VER_PLATFORM_WIN32_NT
:
1045 if (majorVsn
&& major
!= -1)
1047 if (minorVsn
&& minor
!= -1)
1052 int retValue
= wxWINDOWS
;
1053 #ifdef __WINDOWS_386__
1054 retValue
= wxWIN386
;
1056 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
1057 extern HANDLE g_hPenWin
;
1058 retValue
= g_hPenWin
? wxPENWINDOWS
: wxWINDOWS
;
1071 // ----------------------------------------------------------------------------
1073 // ----------------------------------------------------------------------------
1079 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1080 static bool gs_inTimer
= FALSE
;
1082 class wxSleepTimer
: public wxTimer
1085 virtual void Notify()
1092 static wxTimer
*wxTheSleepTimer
= NULL
;
1094 void wxUsleep(unsigned long milliseconds
)
1097 ::Sleep(milliseconds
);
1102 wxTheSleepTimer
= new wxSleepTimer
;
1104 wxTheSleepTimer
->Start(milliseconds
);
1107 if (wxTheApp
->Pending())
1108 wxTheApp
->Dispatch();
1110 delete wxTheSleepTimer
;
1111 wxTheSleepTimer
= NULL
;
1112 #endif // Win32/!Win32
1115 void wxSleep(int nSecs
)
1120 wxTheSleepTimer
= new wxSleepTimer
;
1122 wxTheSleepTimer
->Start(nSecs
*1000);
1125 if (wxTheApp
->Pending())
1126 wxTheApp
->Dispatch();
1128 delete wxTheSleepTimer
;
1129 wxTheSleepTimer
= NULL
;
1132 // Consume all events until no more left
1133 void wxFlushEvents()
1138 #endif // wxUSE_TIMER
1140 #elif defined(__WIN32__) // wxUSE_GUI
1142 void wxUsleep(unsigned long milliseconds
)
1144 ::Sleep(milliseconds
);
1147 void wxSleep(int nSecs
)
1149 wxUsleep(1000*nSecs
);
1152 #endif // wxUSE_GUI/!wxUSE_GUI
1153 #endif // __WXMICROWIN__
1155 // ----------------------------------------------------------------------------
1156 // deprecated (in favour of wxLog) log functions
1157 // ----------------------------------------------------------------------------
1159 #if WXWIN_COMPATIBILITY_2_2
1161 // Output a debug mess., in a system dependent fashion.
1162 #ifndef __WXMICROWIN__
1163 void wxDebugMsg(const wxChar
*fmt
...)
1166 static wxChar buffer
[512];
1168 if (!wxTheApp
->GetWantDebugOutput())
1173 wvsprintf(buffer
,fmt
,ap
);
1174 OutputDebugString((LPCTSTR
)buffer
);
1179 // Non-fatal error: pop up message box and (possibly) continue
1180 void wxError(const wxString
& msg
, const wxString
& title
)
1182 wxSprintf(wxBuffer
, wxT("%s\nContinue?"), WXSTRINGCAST msg
);
1183 if (MessageBox(NULL
, (LPCTSTR
)wxBuffer
, (LPCTSTR
)WXSTRINGCAST title
,
1184 MB_ICONSTOP
| MB_YESNO
) == IDNO
)
1188 // Fatal error: pop up message box and abort
1189 void wxFatalError(const wxString
& msg
, const wxString
& title
)
1191 wxSprintf(wxBuffer
, wxT("%s: %s"), WXSTRINGCAST title
, WXSTRINGCAST msg
);
1192 FatalAppExit(0, (LPCTSTR
)wxBuffer
);
1194 #endif // __WXMICROWIN__
1196 #endif // WXWIN_COMPATIBILITY_2_2
1200 // ----------------------------------------------------------------------------
1201 // functions to work with .INI files
1202 // ----------------------------------------------------------------------------
1204 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1206 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, const wxString
& value
, const wxString
& file
)
1208 if (file
!= wxT(""))
1209 // Don't know what the correct cast should be, but it doesn't
1210 // compile in BC++/16-bit without this cast.
1211 #if !defined(__WIN32__)
1212 return (WritePrivateProfileString((const char*) section
, (const char*) entry
, (const char*) value
, (const char*) file
) != 0);
1214 return (WritePrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)value
, (LPCTSTR
)WXSTRINGCAST file
) != 0);
1217 return (WriteProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)WXSTRINGCAST value
) != 0);
1220 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, float value
, const wxString
& file
)
1223 buf
.Printf(wxT("%.4f"), value
);
1225 return wxWriteResource(section
, entry
, buf
, file
);
1228 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, long value
, const wxString
& file
)
1231 buf
.Printf(wxT("%ld"), value
);
1233 return wxWriteResource(section
, entry
, buf
, file
);
1236 bool wxWriteResource(const wxString
& section
, const wxString
& entry
, int value
, const wxString
& file
)
1239 buf
.Printf(wxT("%d"), value
);
1241 return wxWriteResource(section
, entry
, buf
, file
);
1244 bool wxGetResource(const wxString
& section
, const wxString
& entry
, wxChar
**value
, const wxString
& file
)
1246 static const wxChar defunkt
[] = wxT("$$default");
1247 if (file
!= wxT(""))
1249 int n
= GetPrivateProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1250 (LPTSTR
)wxBuffer
, 1000, (LPCTSTR
)WXSTRINGCAST file
);
1251 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1256 int n
= GetProfileString((LPCTSTR
)WXSTRINGCAST section
, (LPCTSTR
)WXSTRINGCAST entry
, (LPCTSTR
)defunkt
,
1257 (LPTSTR
)wxBuffer
, 1000);
1258 if (n
== 0 || wxStrcmp(wxBuffer
, defunkt
) == 0)
1261 if (*value
) delete[] (*value
);
1262 *value
= copystring(wxBuffer
);
1266 bool wxGetResource(const wxString
& section
, const wxString
& entry
, float *value
, const wxString
& file
)
1269 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1272 *value
= (float)wxStrtod(s
, NULL
);
1279 bool wxGetResource(const wxString
& section
, const wxString
& entry
, long *value
, const wxString
& file
)
1282 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1285 *value
= wxStrtol(s
, NULL
, 10);
1292 bool wxGetResource(const wxString
& section
, const wxString
& entry
, int *value
, const wxString
& file
)
1295 bool succ
= wxGetResource(section
, entry
, (wxChar
**)&s
, file
);
1298 *value
= (int)wxStrtol(s
, NULL
, 10);
1304 #endif // wxUSE_RESOURCES
1306 // ---------------------------------------------------------------------------
1307 // helper functions for showing a "busy" cursor
1308 // ---------------------------------------------------------------------------
1310 static HCURSOR gs_wxBusyCursor
= 0; // new, busy cursor
1311 static HCURSOR gs_wxBusyCursorOld
= 0; // old cursor
1312 static int gs_wxBusyCursorCount
= 0;
1314 extern HCURSOR
wxGetCurrentBusyCursor()
1316 return gs_wxBusyCursor
;
1319 // Set the cursor to the busy cursor for all windows
1320 void wxBeginBusyCursor(wxCursor
*cursor
)
1322 if ( gs_wxBusyCursorCount
++ == 0 )
1324 gs_wxBusyCursor
= (HCURSOR
)cursor
->GetHCURSOR();
1325 #ifndef __WXMICROWIN__
1326 gs_wxBusyCursorOld
= ::SetCursor(gs_wxBusyCursor
);
1329 //else: nothing to do, already set
1332 // Restore cursor to normal
1333 void wxEndBusyCursor()
1335 wxCHECK_RET( gs_wxBusyCursorCount
> 0,
1336 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1338 if ( --gs_wxBusyCursorCount
== 0 )
1340 #ifndef __WXMICROWIN__
1341 ::SetCursor(gs_wxBusyCursorOld
);
1343 gs_wxBusyCursorOld
= 0;
1347 // TRUE if we're between the above two calls
1350 return gs_wxBusyCursorCount
> 0;
1353 // Check whether this window wants to process messages, e.g. Stop button
1354 // in long calculations.
1355 bool wxCheckForInterrupt(wxWindow
*wnd
)
1357 wxCHECK( wnd
, FALSE
);
1360 while ( ::PeekMessage(&msg
, GetHwndOf(wnd
), 0, 0, PM_REMOVE
) )
1362 ::TranslateMessage(&msg
);
1363 ::DispatchMessage(&msg
);
1369 // MSW only: get user-defined resource from the .res file.
1370 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1372 #ifndef __WXMICROWIN__
1373 wxChar
*wxLoadUserResource(const wxString
& resourceName
, const wxString
& resourceType
)
1375 HRSRC hResource
= ::FindResource(wxGetInstance(), resourceName
, resourceType
);
1376 if ( hResource
== 0 )
1379 HGLOBAL hData
= ::LoadResource(wxGetInstance(), hResource
);
1383 wxChar
*theText
= (wxChar
*)::LockResource(hData
);
1387 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1388 // so we need to find the length of the resource.
1389 int len
= ::SizeofResource(wxGetInstance(), hResource
);
1390 wxChar
*s
= new wxChar
[len
+1];
1391 wxStrncpy(s
,theText
,len
);
1394 // wxChar *s = copystring(theText);
1396 // Obsolete in WIN32
1398 UnlockResource(hData
);
1402 // GlobalFree(hData);
1406 #endif // __WXMICROWIN__
1408 // ----------------------------------------------------------------------------
1410 // ----------------------------------------------------------------------------
1412 // See also the wxGetMousePosition in window.cpp
1413 // Deprecated: use wxPoint wxGetMousePosition() instead
1414 void wxGetMousePosition( int* x
, int* y
)
1417 GetCursorPos( & pt
);
1422 // Return TRUE if we have a colour display
1423 bool wxColourDisplay()
1425 #ifdef __WXMICROWIN__
1429 // this function is called from wxDC ctor so it is called a *lot* of times
1430 // hence we optimize it a bit but doign the check only once
1432 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1434 static int s_isColour
= -1;
1436 if ( s_isColour
== -1 )
1439 int noCols
= ::GetDeviceCaps(dc
, NUMCOLORS
);
1441 s_isColour
= (noCols
== -1) || (noCols
> 2);
1444 return s_isColour
!= 0;
1448 // Returns depth of screen
1449 int wxDisplayDepth()
1452 return GetDeviceCaps(dc
, PLANES
) * GetDeviceCaps(dc
, BITSPIXEL
);
1455 // Get size of display
1456 void wxDisplaySize(int *width
, int *height
)
1458 #ifdef __WXMICROWIN__
1460 HWND hWnd
= GetDesktopWindow();
1461 ::GetWindowRect(hWnd
, & rect
);
1464 *width
= rect
.right
- rect
.left
;
1466 *height
= rect
.bottom
- rect
.top
;
1467 #else // !__WXMICROWIN__
1471 *width
= ::GetDeviceCaps(dc
, HORZRES
);
1473 *height
= ::GetDeviceCaps(dc
, VERTRES
);
1474 #endif // __WXMICROWIN__/!__WXMICROWIN__
1477 void wxDisplaySizeMM(int *width
, int *height
)
1479 #ifdef __WXMICROWIN__
1489 *width
= ::GetDeviceCaps(dc
, HORZSIZE
);
1491 *height
= ::GetDeviceCaps(dc
, VERTSIZE
);
1495 void wxClientDisplayRect(int *x
, int *y
, int *width
, int *height
)
1497 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1499 wxDisplaySize(width
, height
);
1501 // Determine the desktop dimensions minus the taskbar and any other
1502 // special decorations...
1505 SystemParametersInfo(SPI_GETWORKAREA
, 0, &r
, 0);
1508 if (width
) *width
= r
.right
- r
.left
;
1509 if (height
) *height
= r
.bottom
- r
.top
;
1513 // ---------------------------------------------------------------------------
1514 // window information functions
1515 // ---------------------------------------------------------------------------
1517 wxString WXDLLEXPORT
wxGetWindowText(WXHWND hWnd
)
1523 int len
= GetWindowTextLength((HWND
)hWnd
) + 1;
1524 ::GetWindowText((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1525 str
.UngetWriteBuf();
1531 wxString WXDLLEXPORT
wxGetWindowClass(WXHWND hWnd
)
1536 #ifndef __WXMICROWIN__
1539 int len
= 256; // some starting value
1543 int count
= ::GetClassName((HWND
)hWnd
, str
.GetWriteBuf(len
), len
);
1545 str
.UngetWriteBuf();
1548 // the class name might have been truncated, retry with larger
1558 #endif // !__WXMICROWIN__
1563 WXWORD WXDLLEXPORT
wxGetWindowId(WXHWND hWnd
)
1566 return (WXWORD
)GetWindowWord((HWND
)hWnd
, GWW_ID
);
1568 return (WXWORD
)GetWindowLong((HWND
)hWnd
, GWL_ID
);
1572 // ----------------------------------------------------------------------------
1574 // ----------------------------------------------------------------------------
1576 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
1580 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1581 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1582 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1583 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1585 *x
*= (iWidthMM
* 100);
1587 *y
*= (iHeightMM
* 100);
1591 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
1595 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
1596 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
1597 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
1598 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
1601 *x
/= (iWidthMM
* 100);
1603 *y
/= (iHeightMM
* 100);
1608 #ifdef __WXMICROWIN__
1609 int wxGetOsVersion(int *majorVsn
, int *minorVsn
)
1612 if (majorVsn
) *majorVsn
= 0;
1613 if (minorVsn
) *minorVsn
= 0;
1616 #endif // __WXMICROWIN__
1618 // ----------------------------------------------------------------------------
1619 // Win32 codepage conversion functions
1620 // ----------------------------------------------------------------------------
1622 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1624 // wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1625 #if wxUSE_GUI && !defined(__WXUNIVERSAL__)
1627 #include "wx/fontmap.h"
1629 // VZ: the new version of wxCharsetToCodepage() is more politically correct
1630 // and should work on other Windows versions as well but the old version is
1631 // still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
1633 extern long wxEncodingToCodepage(wxFontEncoding encoding
)
1635 // translate encoding into the Windows CHARSET
1636 wxNativeEncodingInfo natveEncInfo
;
1637 if ( !wxGetNativeFontEncoding(encoding
, &natveEncInfo
) )
1640 // translate CHARSET to code page
1641 CHARSETINFO csetInfo
;
1642 if ( !::TranslateCharsetInfo((DWORD
*)(DWORD
)natveEncInfo
.charset
,
1646 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1651 return csetInfo
.ciACP
;
1656 extern long wxCharsetToCodepage(const wxChar
*name
)
1658 // first get the font encoding for this charset
1662 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(name
, FALSE
);
1663 if ( enc
== wxFONTENCODING_SYSTEM
)
1666 // the use the helper function
1667 return wxEncodingToCodepage(enc
);
1670 #endif // wxUSE_FONTMAP
1674 // include old wxCharsetToCodepage() by OK if needed
1675 #if !wxUSE_GUI || !wxUSE_FONTMAP
1677 #include "wx/msw/registry.h"
1679 // this should work if Internet Exploiter is installed
1680 extern long wxCharsetToCodepage(const wxChar
*name
)
1689 wxString
path(wxT("MIME\\Database\\Charset\\"));
1691 wxRegKey
key(wxRegKey::HKCR
, path
);
1693 if (!key
.Exists()) break;
1695 // two cases: either there's an AliasForCharset string,
1696 // or there are Codepage and InternetEncoding dwords.
1697 // The InternetEncoding gives us the actual encoding,
1698 // the Codepage just says which Windows character set to
1699 // use when displaying the data.
1700 if (key
.HasValue(wxT("InternetEncoding")) &&
1701 key
.QueryValue(wxT("InternetEncoding"), &CP
)) break;
1703 // no encoding, see if it's an alias
1704 if (!key
.HasValue(wxT("AliasForCharset")) ||
1705 !key
.QueryValue(wxT("AliasForCharset"), cn
)) break;
1711 #endif // !wxUSE_GUI || !wxUSE_FONTMAP