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