]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/msw/utils.cpp
showing a bevel button for a multiline label (is not multline on the OS level, but...
[wxWidgets.git] / src / msw / utils.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: msw/utils.cpp
3// Purpose: Various utilities
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
8// Copyright: (c) Julian Smart
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
24 #pragma hdrstop
25#endif
26
27#ifndef WX_PRECOMP
28 #include "wx/utils.h"
29 #include "wx/app.h"
30 #include "wx/intl.h"
31 #include "wx/log.h"
32#endif //WX_PRECOMP
33
34#include "wx/apptrait.h"
35#include "wx/dynload.h"
36
37#include "wx/confbase.h" // for wxExpandEnvVars()
38
39#include "wx/msw/private.h" // includes <windows.h>
40#include "wx/msw/missing.h" // CHARSET_HANGUL
41
42#if defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) \
43 || defined(__CYGWIN32__)
44 // apparently we need to include winsock.h to get WSADATA and other stuff
45 // used in wxGetFullHostName() with the old mingw32 versions
46 #include <winsock.h>
47#endif
48
49#include "wx/timer.h"
50
51#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
52 #include <direct.h>
53
54 #ifndef __MWERKS__
55 #include <dos.h>
56 #endif
57#endif //GNUWIN32
58
59#if defined(__CYGWIN__)
60 #include <sys/unistd.h>
61 #include <sys/stat.h>
62 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
63#endif //GNUWIN32
64
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.
68 #include <dir.h>
69#endif
70
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
75#undef USE_NET_API
76
77#ifdef USE_NET_API
78 #include <lm.h>
79#endif // USE_NET_API
80
81#if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
82 #ifndef __UNIX__
83 #include <io.h>
84 #endif
85
86 #ifndef __GNUWIN32__
87 #include <shellapi.h>
88 #endif
89#endif
90
91#ifndef __WATCOMC__
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
93 #include <errno.h>
94 #endif
95#endif
96
97// 260 was taken from windef.h
98#ifndef MAX_PATH
99 #define MAX_PATH 260
100#endif
101
102// ----------------------------------------------------------------------------
103// constants
104// ----------------------------------------------------------------------------
105
106// In the WIN.INI file
107static const wxChar WX_SECTION[] = wxT("wxWindows");
108static const wxChar eUSERNAME[] = wxT("UserName");
109
110// these are only used under Win16
111#if !defined(__WIN32__) && !defined(__WXMICROWIN__)
112static const wxChar eHOSTNAME[] = wxT("HostName");
113static const wxChar eUSERID[] = wxT("UserId");
114#endif // !Win32
115
116// ============================================================================
117// implementation
118// ============================================================================
119
120// ----------------------------------------------------------------------------
121// get host name and related
122// ----------------------------------------------------------------------------
123
124// Get hostname only (without domain name)
125bool wxGetHostName(wxChar *buf, int maxSize)
126{
127#if defined(__WXWINCE__)
128 return FALSE;
129#elif defined(__WIN32__) && !defined(__WXMICROWIN__)
130 DWORD nSize = maxSize;
131 if ( !::GetComputerName(buf, &nSize) )
132 {
133 wxLogLastError(wxT("GetComputerName"));
134
135 return FALSE;
136 }
137
138 return TRUE;
139#else
140 wxChar *sysname;
141 const wxChar *default_host = wxT("noname");
142
143 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
144 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
145 } else
146 wxStrncpy(buf, sysname, maxSize - 1);
147 buf[maxSize] = wxT('\0');
148 return *buf ? TRUE : FALSE;
149#endif
150}
151
152// get full hostname (with domain name if possible)
153bool wxGetFullHostName(wxChar *buf, int maxSize)
154{
155#if !defined( __WXMICROWIN__) && wxUSE_DYNAMIC_LOADER
156 // TODO should use GetComputerNameEx() when available
157
158 // we don't want to always link with Winsock DLL as we might not use it at
159 // all, so load it dynamically here if needed (and don't complain if it is
160 // missing, we handle this)
161 wxLogNull noLog;
162
163 wxDynamicLibrary dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM);
164 if ( dllWinsock.IsLoaded() )
165 {
166 typedef int (PASCAL *WSAStartup_t)(WORD, WSADATA *);
167 typedef int (PASCAL *gethostname_t)(char *, int);
168 typedef hostent* (PASCAL *gethostbyname_t)(const char *);
169 typedef hostent* (PASCAL *gethostbyaddr_t)(const char *, int , int);
170 typedef int (PASCAL *WSACleanup_t)(void);
171
172 #define LOAD_WINSOCK_FUNC(func) \
173 func ## _t \
174 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func))
175
176 LOAD_WINSOCK_FUNC(WSAStartup);
177
178 WSADATA wsa;
179 if ( pfnWSAStartup && pfnWSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
180 {
181 LOAD_WINSOCK_FUNC(gethostname);
182
183 wxString host;
184 if ( pfngethostname )
185 {
186 char bufA[256];
187 if ( pfngethostname(bufA, WXSIZEOF(bufA)) == 0 )
188 {
189 // gethostname() won't usually include the DNS domain name,
190 // for this we need to work a bit more
191 if ( !strchr(bufA, '.') )
192 {
193 LOAD_WINSOCK_FUNC(gethostbyname);
194
195 struct hostent *pHostEnt = pfngethostbyname
196 ? pfngethostbyname(bufA)
197 : NULL;
198
199 if ( pHostEnt )
200 {
201 // Windows will use DNS internally now
202 LOAD_WINSOCK_FUNC(gethostbyaddr);
203
204 pHostEnt = pfngethostbyaddr
205 ? pfngethostbyaddr(pHostEnt->h_addr,
206 4, AF_INET)
207 : NULL;
208 }
209
210 if ( pHostEnt )
211 {
212 host = wxString::FromAscii(pHostEnt->h_name);
213 }
214 }
215 }
216 }
217
218 LOAD_WINSOCK_FUNC(WSACleanup);
219 if ( pfnWSACleanup )
220 pfnWSACleanup();
221
222
223 if ( !host.empty() )
224 {
225 wxStrncpy(buf, host, maxSize);
226
227 return TRUE;
228 }
229 }
230 }
231#endif // !__WXMICROWIN__
232
233 return wxGetHostName(buf, maxSize);
234}
235
236// Get user ID e.g. jacs
237bool wxGetUserId(wxChar *buf, int maxSize)
238{
239#if defined(__WXWINCE__)
240 return FALSE;
241#elif defined(__WIN32__) && !defined(__win32s__) && !defined(__WXMICROWIN__)
242 DWORD nSize = maxSize;
243 if ( ::GetUserName(buf, &nSize) == 0 )
244 {
245 // actually, it does happen on Win9x if the user didn't log on
246 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
247 if ( res == 0 )
248 {
249 // not found
250 return FALSE;
251 }
252 }
253
254 return TRUE;
255#else // Win16 or Win32s
256 wxChar *user;
257 const wxChar *default_id = wxT("anonymous");
258
259 // Can't assume we have NIS (PC-NFS) or some other ID daemon
260 // So we ...
261 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
262 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
263 {
264 // Use wxWindows configuration data (comming soon)
265 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
266 }
267 else
268 {
269 wxStrncpy(buf, user, maxSize - 1);
270 }
271
272 return *buf ? TRUE : FALSE;
273#endif
274}
275
276// Get user name e.g. Julian Smart
277bool wxGetUserName(wxChar *buf, int maxSize)
278{
279#if defined(__WXWINCE__)
280 return FALSE;
281#elif defined(USE_NET_API)
282 CHAR szUserName[256];
283 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
284 return FALSE;
285
286 // TODO how to get the domain name?
287 CHAR *szDomain = "";
288
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];
292 LPBYTE ComputerName;
293
294 USER_INFO_2 *ui2; // User structure
295
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) );
301
302 // Get the computer name of a DC for the domain.
303 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
304 {
305 wxLogError(wxT("Can not find domain controller"));
306
307 goto error;
308 }
309
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
314 (LPBYTE *) &ui2 );
315 switch ( status )
316 {
317 case NERR_Success:
318 // ok
319 break;
320
321 case NERR_InvalidComputer:
322 wxLogError(wxT("Invalid domain controller name."));
323
324 goto error;
325
326 case NERR_UserNotFound:
327 wxLogError(wxT("Invalid user name '%s'."), szUserName);
328
329 goto error;
330
331 default:
332 wxLogSysError(wxT("Can't get information about user"));
333
334 goto error;
335 }
336
337 // Convert the Unicode full name to ANSI
338 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
339 buf, maxSize, NULL, NULL );
340
341 return TRUE;
342
343error:
344 wxLogError(wxT("Couldn't look up full user name."));
345
346 return FALSE;
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, wxEmptyString, buf, maxSize - 1) != 0;
351 if ( !ok )
352 {
353 ok = wxGetUserId(buf, maxSize);
354 }
355
356 if ( !ok )
357 {
358 wxStrncpy(buf, wxT("Unknown User"), maxSize);
359 }
360#endif // Win32/16
361
362 return TRUE;
363}
364
365const wxChar* wxGetHomeDir(wxString *pstr)
366{
367 wxString& strDir = *pstr;
368
369 // first branch is for Cygwin
370#if defined(__UNIX__)
371 const wxChar *szHome = wxGetenv("HOME");
372 if ( szHome == NULL ) {
373 // we're homeless...
374 wxLogWarning(_("can't find user's HOME, using current directory."));
375 strDir = wxT(".");
376 }
377 else
378 strDir = szHome;
379
380 // add a trailing slash if needed
381 if ( strDir.Last() != wxT('/') )
382 strDir << wxT('/');
383
384 #ifdef __CYGWIN__
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;
389 #endif
390#elif defined(__WXWINCE__)
391 // Nothing
392#else
393 strDir.clear();
394
395 // If we have a valid HOME directory, as is used on many machines that
396 // have unix utilities on them, we should use that.
397 const wxChar *szHome = wxGetenv(wxT("HOME"));
398
399 if ( szHome != NULL )
400 {
401 strDir = szHome;
402 }
403 else // no HOME, try HOMEDRIVE/PATH
404 {
405 szHome = wxGetenv(wxT("HOMEDRIVE"));
406 if ( szHome != NULL )
407 strDir << szHome;
408 szHome = wxGetenv(wxT("HOMEPATH"));
409
410 if ( szHome != NULL )
411 {
412 strDir << szHome;
413
414 // the idea is that under NT these variables have default values
415 // of "%systemdrive%:" and "\\". As we don't want to create our
416 // config files in the root directory of the system drive, we will
417 // create it in our program's dir. However, if the user took care
418 // to set HOMEPATH to something other than "\\", we suppose that he
419 // knows what he is doing and use the supplied value.
420 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
421 strDir.clear();
422 }
423 }
424
425 if ( strDir.empty() )
426 {
427 // If we have a valid USERPROFILE directory, as is the case in
428 // Windows NT, 2000 and XP, we should use that as our home directory.
429 szHome = wxGetenv(wxT("USERPROFILE"));
430
431 if ( szHome != NULL )
432 strDir = szHome;
433 }
434
435 if ( !strDir.empty() )
436 {
437 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
438 // value once again, it shouldn't hurt anyhow
439 strDir = wxExpandEnvVars(strDir);
440 }
441 else // fall back to the program directory
442 {
443 wxString strPath;
444 ::GetModuleFileName(::GetModuleHandle(NULL),
445 wxStringBuffer(strPath, MAX_PATH), MAX_PATH);
446
447 // extract the dir name
448 wxSplitPath(strPath, &strDir, NULL, NULL);
449 }
450#endif // UNIX/Win
451
452 return strDir.c_str();
453}
454
455wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
456{
457 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
458 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
459 // static buffer and sometimes I don't even know what.
460 static wxString s_home;
461
462 return (wxChar *)wxGetHomeDir(&s_home);
463}
464
465bool wxDirExists(const wxString& dir)
466{
467#ifdef __WXMICROWIN__
468 return wxPathExist(dir);
469#elif defined(__WIN32__)
470 DWORD attribs = GetFileAttributes(dir);
471 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
472#else // Win16
473 #ifdef __BORLANDC__
474 struct ffblk fileInfo;
475 #else
476 struct find_t fileInfo;
477 #endif
478 // In Borland findfirst has a different argument
479 // ordering from _dos_findfirst. But _dos_findfirst
480 // _should_ be ok in both MS and Borland... why not?
481 #ifdef __BORLANDC__
482 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
483 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
484 #else
485 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
486 ((fileInfo.attrib & _A_SUBDIR) != 0);
487 #endif
488#endif // Win32/16
489}
490
491bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
492{
493#ifdef __WXWINCE__
494 return FALSE;
495#else
496 if ( path.empty() )
497 return FALSE;
498
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
503 // it
504 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
505 PULARGE_INTEGER,
506 PULARGE_INTEGER,
507 PULARGE_INTEGER);
508
509 GetDiskFreeSpaceEx_t
510 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
511 (
512 ::GetModuleHandle(_T("kernel32.dll")),
513#if wxUSE_UNICODE
514 "GetDiskFreeSpaceExW"
515#else
516 "GetDiskFreeSpaceExA"
517#endif
518 );
519
520 if ( pGetDiskFreeSpaceEx )
521 {
522 ULARGE_INTEGER bytesFree, bytesTotal;
523
524 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
525 if ( !pGetDiskFreeSpaceEx(path,
526 &bytesFree,
527 &bytesTotal,
528 NULL) )
529 {
530 wxLogLastError(_T("GetDiskFreeSpaceEx"));
531
532 return FALSE;
533 }
534
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)
539 #define UL(ul) ul.u
540#else // anon union
541 #define UL(ul) ul
542#endif
543 if ( pTotal )
544 {
545 *pTotal = wxLongLong(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
546 }
547
548 if ( pFree )
549 {
550 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
551 }
552 }
553 else
554#endif // Win32
555 {
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...
559
560 DWORD lSectorsPerCluster,
561 lBytesPerSector,
562 lNumberOfFreeClusters,
563 lTotalNumberOfClusters;
564
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,
568 &lSectorsPerCluster,
569 &lBytesPerSector,
570 &lNumberOfFreeClusters,
571 &lTotalNumberOfClusters) )
572 {
573 wxLogLastError(_T("GetDiskFreeSpace"));
574
575 return FALSE;
576 }
577
578 wxLongLong lBytesPerCluster = lSectorsPerCluster;
579 lBytesPerCluster *= lBytesPerSector;
580
581 if ( pTotal )
582 {
583 *pTotal = lBytesPerCluster;
584 *pTotal *= lTotalNumberOfClusters;
585 }
586
587 if ( pFree )
588 {
589 *pFree = lBytesPerCluster;
590 *pFree *= lNumberOfFreeClusters;
591 }
592 }
593
594 return TRUE;
595#endif
596 // __WXWINCE__
597}
598
599// ----------------------------------------------------------------------------
600// env vars
601// ----------------------------------------------------------------------------
602
603bool wxGetEnv(const wxString& var, wxString *value)
604{
605#ifdef __WXWINCE__
606 return FALSE;
607#elif defined(__WIN16__)
608 const wxChar* ret = wxGetenv(var);
609 if ( !ret )
610 return FALSE;
611
612 if ( value )
613 {
614 *value = ret;
615 }
616
617 return TRUE;
618#else // Win32
619 // first get the size of the buffer
620 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
621 if ( !dwRet )
622 {
623 // this means that there is no such variable
624 return FALSE;
625 }
626
627 if ( value )
628 {
629 (void)::GetEnvironmentVariable(var, wxStringBuffer(*value, dwRet),
630 dwRet);
631 }
632
633 return TRUE;
634#endif // Win16/32
635}
636
637bool wxSetEnv(const wxString& var, const wxChar *value)
638{
639 // some compilers have putenv() or _putenv() or _wputenv() but it's better
640 // to always use Win32 function directly instead of dealing with them
641#if defined(__WIN32__) && !defined(__WXWINCE__)
642 if ( !::SetEnvironmentVariable(var, value) )
643 {
644 wxLogLastError(_T("SetEnvironmentVariable"));
645
646 return FALSE;
647 }
648
649 return TRUE;
650#else // no way to set env vars
651 return FALSE;
652#endif
653}
654
655// ----------------------------------------------------------------------------
656// process management
657// ----------------------------------------------------------------------------
658
659// structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
660struct wxFindByPidParams
661{
662 wxFindByPidParams() { hwnd = 0; pid = 0; }
663
664 // the HWND used to return the result
665 HWND hwnd;
666
667 // the PID we're looking from
668 DWORD pid;
669
670 DECLARE_NO_COPY_CLASS(wxFindByPidParams)
671};
672
673// wxKill helper: EnumWindows() callback which is used to find the first (top
674// level) window belonging to the given process
675BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
676{
677 DWORD pid;
678 (void)::GetWindowThreadProcessId(hwnd, &pid);
679
680 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
681 if ( pid == params->pid )
682 {
683 // remember the window we found
684 params->hwnd = hwnd;
685
686 // return FALSE to stop the enumeration
687 return FALSE;
688 }
689
690 // continue enumeration
691 return TRUE;
692}
693
694int wxKill(long pid, wxSignal sig, wxKillError *krc)
695{
696 // get the process handle to operate on
697 HANDLE hProcess = ::OpenProcess(SYNCHRONIZE |
698 PROCESS_TERMINATE |
699 PROCESS_QUERY_INFORMATION,
700 FALSE, // not inheritable
701 (DWORD)pid);
702 if ( hProcess == NULL )
703 {
704 if ( krc )
705 {
706 if ( ::GetLastError() == ERROR_ACCESS_DENIED )
707 {
708 *krc = wxKILL_ACCESS_DENIED;
709 }
710 else
711 {
712 *krc = wxKILL_NO_PROCESS;
713 }
714 }
715
716 return -1;
717 }
718
719 bool ok = TRUE;
720 switch ( sig )
721 {
722 case wxSIGKILL:
723 // kill the process forcefully returning -1 as error code
724 if ( !::TerminateProcess(hProcess, (UINT)-1) )
725 {
726 wxLogSysError(_("Failed to kill process %d"), pid);
727
728 if ( krc )
729 {
730 // this is not supposed to happen if we could open the
731 // process
732 *krc = wxKILL_ERROR;
733 }
734
735 ok = FALSE;
736 }
737 break;
738
739 case wxSIGNONE:
740 // do nothing, we just want to test for process existence
741 break;
742
743 default:
744 // any other signal means "terminate"
745 {
746 wxFindByPidParams params;
747 params.pid = (DWORD)pid;
748
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)&params) )
753 {
754 // did we find any window?
755 if ( params.hwnd )
756 {
757 // tell the app to close
758 //
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) )
764 {
765 wxLogLastError(_T("PostMessage(WM_QUIT)"));
766 }
767 }
768 else // it was an error then
769 {
770 wxLogLastError(_T("EnumWindows"));
771
772 ok = FALSE;
773 }
774 }
775 else // no windows for this PID
776 {
777 if ( krc )
778 {
779 *krc = wxKILL_ERROR;
780 }
781
782 ok = FALSE;
783 }
784 }
785 }
786
787 // the return code
788 DWORD rc;
789
790 if ( ok )
791 {
792 // as we wait for a short time, we can use just WaitForSingleObject()
793 // and not MsgWaitForMultipleObjects()
794 switch ( ::WaitForSingleObject(hProcess, 500 /* msec */) )
795 {
796 case WAIT_OBJECT_0:
797 // process terminated
798 if ( !::GetExitCodeProcess(hProcess, &rc) )
799 {
800 wxLogLastError(_T("GetExitCodeProcess"));
801 }
802 break;
803
804 default:
805 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
806 // fall through
807
808 case WAIT_FAILED:
809 wxLogLastError(_T("WaitForSingleObject"));
810 // fall through
811
812 case WAIT_TIMEOUT:
813 if ( krc )
814 {
815 *krc = wxKILL_ERROR;
816 }
817
818 rc = STILL_ACTIVE;
819 break;
820 }
821 }
822 else // !ok
823 {
824 // just to suppress the warnings about uninitialized variable
825 rc = 0;
826 }
827
828 ::CloseHandle(hProcess);
829
830 // the return code is the same as from Unix kill(): 0 if killed
831 // successfully or -1 on error
832 //
833 // be careful to interpret rc correctly: for wxSIGNONE we return success if
834 // the process exists, for all the other sig values -- if it doesn't
835 if ( ok &&
836 ((sig == wxSIGNONE) == (rc == STILL_ACTIVE)) )
837 {
838 if ( krc )
839 {
840 *krc = wxKILL_OK;
841 }
842
843 return 0;
844 }
845
846 // error
847 return -1;
848}
849
850// Execute a program in an Interactive Shell
851bool wxShell(const wxString& command)
852{
853#ifdef __WXWINCE__
854 return FALSE;
855#else
856 wxChar *shell = wxGetenv(wxT("COMSPEC"));
857 if ( !shell )
858 shell = (wxChar*) wxT("\\COMMAND.COM");
859
860 wxString cmd;
861 if ( !command )
862 {
863 // just the shell
864 cmd = shell;
865 }
866 else
867 {
868 // pass the command to execute to the command processor
869 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
870 }
871
872 return wxExecute(cmd, wxEXEC_SYNC) == 0;
873#endif
874}
875
876// Shutdown or reboot the PC
877bool wxShutdown(wxShutdownFlags wFlags)
878{
879#ifdef __WXWINCE__
880 return FALSE;
881#elif defined(__WIN32__)
882 bool bOK = TRUE;
883
884 if ( wxGetOsVersion(NULL, NULL) == wxWINDOWS_NT ) // if is NT or 2K
885 {
886 // Get a token for this process.
887 HANDLE hToken;
888 bOK = ::OpenProcessToken(GetCurrentProcess(),
889 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
890 &hToken) != 0;
891 if ( bOK )
892 {
893 TOKEN_PRIVILEGES tkp;
894
895 // Get the LUID for the shutdown privilege.
896 ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
897 &tkp.Privileges[0].Luid);
898
899 tkp.PrivilegeCount = 1; // one privilege to set
900 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
901
902 // Get the shutdown privilege for this process.
903 ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
904 (PTOKEN_PRIVILEGES)NULL, 0);
905
906 // Cannot test the return value of AdjustTokenPrivileges.
907 bOK = ::GetLastError() == ERROR_SUCCESS;
908 }
909 }
910
911 if ( bOK )
912 {
913 UINT flags = EWX_SHUTDOWN | EWX_FORCE;
914 switch ( wFlags )
915 {
916 case wxSHUTDOWN_POWEROFF:
917 flags |= EWX_POWEROFF;
918 break;
919
920 case wxSHUTDOWN_REBOOT:
921 flags |= EWX_REBOOT;
922 break;
923
924 default:
925 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
926 return FALSE;
927 }
928
929 bOK = ::ExitWindowsEx(flags, 0) != 0;
930 }
931
932 return bOK;
933#else // Win16
934 return FALSE;
935#endif // Win32/16
936}
937
938// ----------------------------------------------------------------------------
939// misc
940// ----------------------------------------------------------------------------
941
942// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
943long wxGetFreeMemory()
944{
945#if defined(__WIN32__) && !defined(__BORLANDC__)
946 MEMORYSTATUS memStatus;
947 memStatus.dwLength = sizeof(MEMORYSTATUS);
948 GlobalMemoryStatus(&memStatus);
949 return memStatus.dwAvailPhys;
950#else
951 return (long)GetFreeSpace(0);
952#endif
953}
954
955unsigned long wxGetProcessId()
956{
957#ifdef __WIN32__
958 return ::GetCurrentProcessId();
959#else
960 return 0;
961#endif
962}
963
964// Emit a beeeeeep
965void wxBell()
966{
967 ::MessageBeep((UINT)-1); // default sound
968}
969
970wxString wxGetOsDescription()
971{
972#ifdef __WIN32__
973 wxString str;
974
975 OSVERSIONINFO info;
976 wxZeroMemory(info);
977
978 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
979 if ( ::GetVersionEx(&info) )
980 {
981 switch ( info.dwPlatformId )
982 {
983 case VER_PLATFORM_WIN32s:
984 str = _("Win32s on Windows 3.1");
985 break;
986
987 case VER_PLATFORM_WIN32_WINDOWS:
988 str.Printf(_("Windows 9%c"),
989 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
990 if ( !wxIsEmpty(info.szCSDVersion) )
991 {
992 str << _T(" (") << info.szCSDVersion << _T(')');
993 }
994 break;
995
996 case VER_PLATFORM_WIN32_NT:
997 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
998 info.dwMajorVersion,
999 info.dwMinorVersion,
1000 info.dwBuildNumber);
1001 if ( !wxIsEmpty(info.szCSDVersion) )
1002 {
1003 str << _T(", ") << info.szCSDVersion;
1004 }
1005 str << _T(')');
1006 break;
1007 }
1008 }
1009 else
1010 {
1011 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1012 }
1013
1014 return str;
1015#else // Win16
1016 return _("Windows 3.1");
1017#endif // Win32/16
1018}
1019
1020wxToolkitInfo& wxAppTraits::GetToolkitInfo()
1021{
1022 // cache the version info, it's not going to change
1023 //
1024 // NB: this is MT-safe, we may use these static vars from different threads
1025 // but as they always have the same value it doesn't matter
1026 static int s_ver = -1,
1027 s_major = -1,
1028 s_minor = -1;
1029
1030 if ( s_ver == -1 )
1031 {
1032 OSVERSIONINFO info;
1033 wxZeroMemory(info);
1034
1035 s_ver = wxWINDOWS;
1036 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1037 if ( ::GetVersionEx(&info) )
1038 {
1039 s_major = info.dwMajorVersion;
1040 s_minor = info.dwMinorVersion;
1041
1042 switch ( info.dwPlatformId )
1043 {
1044 case VER_PLATFORM_WIN32s:
1045 s_ver = wxWIN32S;
1046 break;
1047
1048 case VER_PLATFORM_WIN32_WINDOWS:
1049 s_ver = wxWIN95;
1050 break;
1051
1052 case VER_PLATFORM_WIN32_NT:
1053 s_ver = wxWINDOWS_NT;
1054 break;
1055#ifdef __WXWINCE__
1056 case VER_PLATFORM_WIN32_CE:
1057 s_ver = wxWINDOWS_CE;
1058 break;
1059#endif
1060 }
1061 }
1062 }
1063
1064 static wxToolkitInfo info;
1065 info.versionMajor = s_major;
1066 info.versionMinor = s_minor;
1067 info.os = s_ver;
1068 info.name = _T("wxBase");
1069 return info;
1070}
1071
1072// ----------------------------------------------------------------------------
1073// sleep functions
1074// ----------------------------------------------------------------------------
1075
1076void wxUsleep(unsigned long milliseconds)
1077{
1078 ::Sleep(milliseconds);
1079}
1080
1081void wxSleep(int nSecs)
1082{
1083 wxUsleep(1000*nSecs);
1084}
1085
1086// ----------------------------------------------------------------------------
1087// font encoding <-> Win32 codepage conversion functions
1088// ----------------------------------------------------------------------------
1089
1090extern WXDLLIMPEXP_BASE long wxEncodingToCharset(wxFontEncoding encoding)
1091{
1092 switch ( encoding )
1093 {
1094 // although this function is supposed to return an exact match, do do
1095 // some mappings here for the most common case of "standard" encoding
1096 case wxFONTENCODING_SYSTEM:
1097 return DEFAULT_CHARSET;
1098
1099 case wxFONTENCODING_ISO8859_1:
1100 case wxFONTENCODING_ISO8859_15:
1101 case wxFONTENCODING_CP1252:
1102 return ANSI_CHARSET;
1103
1104#if !defined(__WXMICROWIN__)
1105 // The following four fonts are multi-byte charsets
1106 case wxFONTENCODING_CP932:
1107 return SHIFTJIS_CHARSET;
1108
1109 case wxFONTENCODING_CP936:
1110 return GB2312_CHARSET;
1111
1112 case wxFONTENCODING_CP949:
1113 return HANGUL_CHARSET;
1114
1115 case wxFONTENCODING_CP950:
1116 return CHINESEBIG5_CHARSET;
1117
1118 // The rest are single byte encodings
1119 case wxFONTENCODING_CP1250:
1120 return EASTEUROPE_CHARSET;
1121
1122 case wxFONTENCODING_CP1251:
1123 return RUSSIAN_CHARSET;
1124
1125 case wxFONTENCODING_CP1253:
1126 return GREEK_CHARSET;
1127
1128 case wxFONTENCODING_CP1254:
1129 return TURKISH_CHARSET;
1130
1131 case wxFONTENCODING_CP1255:
1132 return HEBREW_CHARSET;
1133
1134 case wxFONTENCODING_CP1256:
1135 return ARABIC_CHARSET;
1136
1137 case wxFONTENCODING_CP1257:
1138 return BALTIC_CHARSET;
1139
1140 case wxFONTENCODING_CP874:
1141 return THAI_CHARSET;
1142#endif // !__WXMICROWIN__
1143
1144 case wxFONTENCODING_CP437:
1145 return OEM_CHARSET;
1146
1147 default:
1148 // no way to translate this encoding into a Windows charset
1149 return -1;
1150 }
1151}
1152
1153// we have 2 versions of wxCharsetToCodepage(): the old one which directly
1154// looks up the vlaues in the registry and the new one which is more
1155// politically correct and has more chances to work on other Windows versions
1156// as well but the old version is still needed for !wxUSE_FONTMAP case
1157#if wxUSE_FONTMAP
1158
1159#include "wx/fontmap.h"
1160
1161extern WXDLLIMPEXP_BASE long wxEncodingToCodepage(wxFontEncoding encoding)
1162{
1163 // translate encoding into the Windows CHARSET
1164 long charset = wxEncodingToCharset(encoding);
1165 if ( charset == -1 )
1166 return -1;
1167
1168 // translate CHARSET to code page
1169 CHARSETINFO csetInfo;
1170 if ( !::TranslateCharsetInfo((DWORD *)(DWORD)charset,
1171 &csetInfo,
1172 TCI_SRCCHARSET) )
1173 {
1174 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1175
1176 return -1;
1177 }
1178
1179 return csetInfo.ciACP;
1180}
1181
1182extern long wxCharsetToCodepage(const wxChar *name)
1183{
1184 // first get the font encoding for this charset
1185 if ( !name )
1186 return -1;
1187
1188 wxFontEncoding enc = wxFontMapper::Get()->CharsetToEncoding(name, FALSE);
1189 if ( enc == wxFONTENCODING_SYSTEM )
1190 return -1;
1191
1192 // the use the helper function
1193 return wxEncodingToCodepage(enc);
1194}
1195
1196#else // !wxUSE_FONTMAP
1197
1198#include "wx/msw/registry.h"
1199
1200// this should work if Internet Exploiter is installed
1201extern long wxCharsetToCodepage(const wxChar *name)
1202{
1203 if (!name)
1204 return GetACP();
1205
1206 long CP = -1;
1207
1208 wxString path(wxT("MIME\\Database\\Charset\\"));
1209 wxString cn(name);
1210
1211 // follow the alias loop
1212 for ( ;; )
1213 {
1214 wxRegKey key(wxRegKey::HKCR, path + cn);
1215
1216 if (!key.Exists())
1217 break;
1218
1219 // two cases: either there's an AliasForCharset string,
1220 // or there are Codepage and InternetEncoding dwords.
1221 // The InternetEncoding gives us the actual encoding,
1222 // the Codepage just says which Windows character set to
1223 // use when displaying the data.
1224 if (key.HasValue(wxT("InternetEncoding")) &&
1225 key.QueryValue(wxT("InternetEncoding"), &CP))
1226 break;
1227
1228 // no encoding, see if it's an alias
1229 if (!key.HasValue(wxT("AliasForCharset")) ||
1230 !key.QueryValue(wxT("AliasForCharset"), cn))
1231 break;
1232 }
1233
1234 return CP;
1235}
1236
1237#endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1238
1239/*
1240 Creates a hidden window with supplied window proc registering the class for
1241 it if necesssary (i.e. the first time only). Caller is responsible for
1242 destroying the window and unregistering the class (note that this must be
1243 done because wxWindows may be used as a DLL and so may be loaded/unloaded
1244 multiple times into/from the same process so we cna't rely on automatic
1245 Windows class unregistration).
1246
1247 pclassname is a pointer to a caller stored classname, which must initially be
1248 NULL. classname is the desired wndclass classname. If function succesfully
1249 registers the class, pclassname will be set to classname.
1250 */
1251extern "C" WXDLLIMPEXP_BASE HWND
1252wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc)
1253{
1254 wxCHECK_MSG( classname && pclassname && wndproc, NULL,
1255 _T("NULL parameter in wxCreateHiddenWindow") );
1256
1257 // register the class fi we need to first
1258 if ( *pclassname == NULL )
1259 {
1260 WNDCLASS wndclass;
1261 wxZeroMemory(wndclass);
1262
1263 wndclass.lpfnWndProc = wndproc;
1264 wndclass.hInstance = wxGetInstance();
1265 wndclass.lpszClassName = classname;
1266
1267 if ( !::RegisterClass(&wndclass) )
1268 {
1269 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1270
1271 return NULL;
1272 }
1273
1274 *pclassname = classname;
1275 }
1276
1277 // next create the window
1278 HWND hwnd = ::CreateWindow
1279 (
1280 *pclassname,
1281 NULL,
1282 0, 0, 0, 0,
1283 0,
1284 (HWND) NULL,
1285 (HMENU)NULL,
1286 wxGetInstance(),
1287 (LPVOID) NULL
1288 );
1289
1290 if ( !hwnd )
1291 {
1292 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));
1293 }
1294
1295 return hwnd;
1296}
1297