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