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