]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utils.cpp
f4fd4ce3c3f31d75d5db28a0aeb8a63a505fb577
[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/confbase.h" // for wxExpandEnvVars()
38
39 #include "wx/msw/private.h" // includes <windows.h>
40 #include "wx/msw/missing.h" // CHARSET_HANGUL
41
42 #if defined(__GNUWIN32_OLD__) || defined(__WXWINCE__) \
43 || defined(__CYGWIN32__)
44 // apparently we need to include winsock.h to get WSADATA and other stuff
45 // used in wxGetFullHostName() with the old mingw32 versions
46 #include <winsock.h>
47 #endif
48
49 #include "wx/timer.h"
50
51 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
52 #include <direct.h>
53
54 #ifndef __MWERKS__
55 #include <dos.h>
56 #endif
57 #endif //GNUWIN32
58
59 #if defined(__CYGWIN__)
60 #include <sys/unistd.h>
61 #include <sys/stat.h>
62 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
63 #endif //GNUWIN32
64
65 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
66 // this (3.1 I believe) and how to test for it.
67 // If this works for Borland 4.0 as well, then no worries.
68 #include <dir.h>
69 #endif
70
71 // VZ: there is some code using NetXXX() functions to get the full user name:
72 // I don't think it's a good idea because they don't work under Win95 and
73 // seem to return the same as wxGetUserId() under NT. If you really want
74 // to use them, just #define USE_NET_API
75 #undef USE_NET_API
76
77 #ifdef USE_NET_API
78 #include <lm.h>
79 #endif // USE_NET_API
80
81 #if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
82 #ifndef __UNIX__
83 #include <io.h>
84 #endif
85
86 #ifndef __GNUWIN32__
87 #include <shellapi.h>
88 #endif
89 #endif
90
91 #ifndef __WATCOMC__
92 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
93 #include <errno.h>
94 #endif
95 #endif
96
97 // For wxKillAllChildren
98 #include <tlhelp32.h>
99
100 // ----------------------------------------------------------------------------
101 // constants
102 // ----------------------------------------------------------------------------
103
104 // In the WIN.INI file
105 static const wxChar WX_SECTION[] = wxT("wxWindows");
106 static const wxChar eUSERNAME[] = wxT("UserName");
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 (and don't complain if it is
152 // missing, we handle this)
153 wxLogNull noLog;
154
155 wxDynamicLibrary dllWinsock(_T("ws2_32.dll"), wxDL_VERBATIM);
156 if ( dllWinsock.IsLoaded() )
157 {
158 typedef int (PASCAL *WSAStartup_t)(WORD, WSADATA *);
159 typedef int (PASCAL *gethostname_t)(char *, int);
160 typedef hostent* (PASCAL *gethostbyname_t)(const char *);
161 typedef hostent* (PASCAL *gethostbyaddr_t)(const char *, int , int);
162 typedef int (PASCAL *WSACleanup_t)(void);
163
164 #define LOAD_WINSOCK_FUNC(func) \
165 func ## _t \
166 pfn ## func = (func ## _t)dllWinsock.GetSymbol(_T(#func))
167
168 LOAD_WINSOCK_FUNC(WSAStartup);
169
170 WSADATA wsa;
171 if ( pfnWSAStartup && pfnWSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
172 {
173 LOAD_WINSOCK_FUNC(gethostname);
174
175 wxString host;
176 if ( pfngethostname )
177 {
178 char bufA[256];
179 if ( pfngethostname(bufA, WXSIZEOF(bufA)) == 0 )
180 {
181 // gethostname() won't usually include the DNS domain name,
182 // for this we need to work a bit more
183 if ( !strchr(bufA, '.') )
184 {
185 LOAD_WINSOCK_FUNC(gethostbyname);
186
187 struct hostent *pHostEnt = pfngethostbyname
188 ? pfngethostbyname(bufA)
189 : NULL;
190
191 if ( pHostEnt )
192 {
193 // Windows will use DNS internally now
194 LOAD_WINSOCK_FUNC(gethostbyaddr);
195
196 pHostEnt = pfngethostbyaddr
197 ? pfngethostbyaddr(pHostEnt->h_addr,
198 4, AF_INET)
199 : NULL;
200 }
201
202 if ( pHostEnt )
203 {
204 host = wxString::FromAscii(pHostEnt->h_name);
205 }
206 }
207 }
208 }
209
210 LOAD_WINSOCK_FUNC(WSACleanup);
211 if ( pfnWSACleanup )
212 pfnWSACleanup();
213
214
215 if ( !host.empty() )
216 {
217 wxStrncpy(buf, host, maxSize);
218
219 return true;
220 }
221 }
222 }
223 #endif // !__WXMICROWIN__
224
225 return wxGetHostName(buf, maxSize);
226 }
227
228 // Get user ID e.g. jacs
229 bool wxGetUserId(wxChar *buf, int maxSize)
230 {
231 #if defined(__WXWINCE__)
232 return false;
233 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
234 DWORD nSize = maxSize;
235 if ( ::GetUserName(buf, &nSize) == 0 )
236 {
237 // actually, it does happen on Win9x if the user didn't log on
238 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
239 if ( res == 0 )
240 {
241 // not found
242 return false;
243 }
244 }
245
246 return true;
247 #else // __WXMICROWIN__
248 wxChar *user;
249 const wxChar *default_id = wxT("anonymous");
250
251 // Can't assume we have NIS (PC-NFS) or some other ID daemon
252 // So we ...
253 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
254 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
255 {
256 // Use wxWidgets configuration data (comming soon)
257 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
258 }
259 else
260 {
261 wxStrncpy(buf, user, maxSize - 1);
262 }
263
264 return *buf ? true : false;
265 #endif
266 }
267
268 // Get user name e.g. Julian Smart
269 bool wxGetUserName(wxChar *buf, int maxSize)
270 {
271 #if defined(__WXWINCE__)
272 return false;
273 #elif defined(USE_NET_API)
274 CHAR szUserName[256];
275 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
276 return false;
277
278 // TODO how to get the domain name?
279 CHAR *szDomain = "";
280
281 // the code is based on the MSDN example (also see KB article Q119670)
282 WCHAR wszUserName[256]; // Unicode user name
283 WCHAR wszDomain[256];
284 LPBYTE ComputerName;
285
286 USER_INFO_2 *ui2; // User structure
287
288 // Convert ANSI user name and domain to Unicode
289 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
290 wszUserName, WXSIZEOF(wszUserName) );
291 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
292 wszDomain, WXSIZEOF(wszDomain) );
293
294 // Get the computer name of a DC for the domain.
295 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
296 {
297 wxLogError(wxT("Can not find domain controller"));
298
299 goto error;
300 }
301
302 // Look up the user on the DC
303 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
304 (LPWSTR)&wszUserName,
305 2, // level - we want USER_INFO_2
306 (LPBYTE *) &ui2 );
307 switch ( status )
308 {
309 case NERR_Success:
310 // ok
311 break;
312
313 case NERR_InvalidComputer:
314 wxLogError(wxT("Invalid domain controller name."));
315
316 goto error;
317
318 case NERR_UserNotFound:
319 wxLogError(wxT("Invalid user name '%s'."), szUserName);
320
321 goto error;
322
323 default:
324 wxLogSysError(wxT("Can't get information about user"));
325
326 goto error;
327 }
328
329 // Convert the Unicode full name to ANSI
330 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
331 buf, maxSize, NULL, NULL );
332
333 return true;
334
335 error:
336 wxLogError(wxT("Couldn't look up full user name."));
337
338 return false;
339 #else // !USE_NET_API
340 // Could use NIS, MS-Mail or other site specific programs
341 // Use wxWidgets configuration data
342 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0;
343 if ( !ok )
344 {
345 ok = wxGetUserId(buf, maxSize);
346 }
347
348 if ( !ok )
349 {
350 wxStrncpy(buf, wxT("Unknown User"), maxSize);
351 }
352 #endif // Win32/16
353
354 return true;
355 }
356
357 const wxChar* wxGetHomeDir(wxString *pstr)
358 {
359 wxString& strDir = *pstr;
360
361 // first branch is for Cygwin
362 #if defined(__UNIX__)
363 const wxChar *szHome = wxGetenv("HOME");
364 if ( szHome == NULL ) {
365 // we're homeless...
366 wxLogWarning(_("can't find user's HOME, using current directory."));
367 strDir = wxT(".");
368 }
369 else
370 strDir = szHome;
371
372 // add a trailing slash if needed
373 if ( strDir.Last() != wxT('/') )
374 strDir << wxT('/');
375
376 #ifdef __CYGWIN__
377 // Cygwin returns unix type path but that does not work well
378 static wxChar windowsPath[MAX_PATH];
379 cygwin_conv_to_full_win32_path(strDir, windowsPath);
380 strDir = windowsPath;
381 #endif
382 #elif defined(__WXWINCE__)
383 // Nothing
384 #else
385 strDir.clear();
386
387 // If we have a valid HOME directory, as is used on many machines that
388 // have unix utilities on them, we should use that.
389 const wxChar *szHome = wxGetenv(wxT("HOME"));
390
391 if ( szHome != NULL )
392 {
393 strDir = szHome;
394 }
395 else // no HOME, try HOMEDRIVE/PATH
396 {
397 szHome = wxGetenv(wxT("HOMEDRIVE"));
398 if ( szHome != NULL )
399 strDir << szHome;
400 szHome = wxGetenv(wxT("HOMEPATH"));
401
402 if ( szHome != NULL )
403 {
404 strDir << szHome;
405
406 // the idea is that under NT these variables have default values
407 // of "%systemdrive%:" and "\\". As we don't want to create our
408 // config files in the root directory of the system drive, we will
409 // create it in our program's dir. However, if the user took care
410 // to set HOMEPATH to something other than "\\", we suppose that he
411 // knows what he is doing and use the supplied value.
412 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
413 strDir.clear();
414 }
415 }
416
417 if ( strDir.empty() )
418 {
419 // If we have a valid USERPROFILE directory, as is the case in
420 // Windows NT, 2000 and XP, we should use that as our home directory.
421 szHome = wxGetenv(wxT("USERPROFILE"));
422
423 if ( szHome != NULL )
424 strDir = szHome;
425 }
426
427 if ( !strDir.empty() )
428 {
429 // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
430 // value once again, it shouldn't hurt anyhow
431 strDir = wxExpandEnvVars(strDir);
432 }
433 else // fall back to the program directory
434 {
435 // extract the directory component of the program file name
436 wxSplitPath(wxGetFullModuleName(), &strDir, NULL, NULL);
437 }
438 #endif // UNIX/Win
439
440 return strDir.c_str();
441 }
442
443 wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
444 {
445 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
446 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
447 // static buffer and sometimes I don't even know what.
448 static wxString s_home;
449
450 return (wxChar *)wxGetHomeDir(&s_home);
451 }
452
453 bool wxDirExists(const wxString& dir)
454 {
455 #ifdef __WXMICROWIN__
456 return wxPathExist(dir);
457 #elif defined(__WIN32__)
458 DWORD attribs = GetFileAttributes(dir);
459 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
460 #endif // Win32/__WXMICROWIN__
461 }
462
463 bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
464 {
465 #ifdef __WXWINCE__
466 return false;
467 #else
468 if ( path.empty() )
469 return false;
470
471 // old w32api don't have ULARGE_INTEGER
472 #if defined(__WIN32__) && \
473 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
474 // GetDiskFreeSpaceEx() is not available under original Win95, check for
475 // it
476 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
477 PULARGE_INTEGER,
478 PULARGE_INTEGER,
479 PULARGE_INTEGER);
480
481 GetDiskFreeSpaceEx_t
482 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
483 (
484 ::GetModuleHandle(_T("kernel32.dll")),
485 #if wxUSE_UNICODE
486 "GetDiskFreeSpaceExW"
487 #else
488 "GetDiskFreeSpaceExA"
489 #endif
490 );
491
492 if ( pGetDiskFreeSpaceEx )
493 {
494 ULARGE_INTEGER bytesFree, bytesTotal;
495
496 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
497 if ( !pGetDiskFreeSpaceEx(path,
498 &bytesFree,
499 &bytesTotal,
500 NULL) )
501 {
502 wxLogLastError(_T("GetDiskFreeSpaceEx"));
503
504 return false;
505 }
506
507 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
508 // two 32 bit fields which may be or may be not named - try to make it
509 // compile in all cases
510 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
511 #define UL(ul) ul.u
512 #else // anon union
513 #define UL(ul) ul
514 #endif
515 if ( pTotal )
516 {
517 *pTotal = wxLongLong(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
518 }
519
520 if ( pFree )
521 {
522 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
523 }
524 }
525 else
526 #endif // Win32
527 {
528 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
529 // should be used instead - but if it's not available, fall back on
530 // GetDiskFreeSpace() nevertheless...
531
532 DWORD lSectorsPerCluster,
533 lBytesPerSector,
534 lNumberOfFreeClusters,
535 lTotalNumberOfClusters;
536
537 // FIXME: this is wrong, we should extract the root drive from path
538 // instead, but this is the job for wxFileName...
539 if ( !::GetDiskFreeSpace(path,
540 &lSectorsPerCluster,
541 &lBytesPerSector,
542 &lNumberOfFreeClusters,
543 &lTotalNumberOfClusters) )
544 {
545 wxLogLastError(_T("GetDiskFreeSpace"));
546
547 return false;
548 }
549
550 wxLongLong lBytesPerCluster = lSectorsPerCluster;
551 lBytesPerCluster *= lBytesPerSector;
552
553 if ( pTotal )
554 {
555 *pTotal = lBytesPerCluster;
556 *pTotal *= lTotalNumberOfClusters;
557 }
558
559 if ( pFree )
560 {
561 *pFree = lBytesPerCluster;
562 *pFree *= lNumberOfFreeClusters;
563 }
564 }
565
566 return true;
567 #endif
568 // __WXWINCE__
569 }
570
571 // ----------------------------------------------------------------------------
572 // env vars
573 // ----------------------------------------------------------------------------
574
575 bool wxGetEnv(const wxString& var, wxString *value)
576 {
577 #ifdef __WXWINCE__
578 return false;
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, wxStringBuffer(*value, dwRet),
591 dwRet);
592 }
593
594 return true;
595 #endif // WinCE/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__) && !defined(__WXWINCE__)
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 wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc);
656
657 int wxKill(long pid, wxSignal sig, wxKillError *krc, int flags)
658 {
659 if (flags & wxKILL_CHILDREN)
660 wxKillAllChildren(pid, sig, krc);
661
662 // get the process handle to operate on
663 HANDLE hProcess = ::OpenProcess(SYNCHRONIZE |
664 PROCESS_TERMINATE |
665 PROCESS_QUERY_INFORMATION,
666 FALSE, // not inheritable
667 (DWORD)pid);
668 if ( hProcess == NULL )
669 {
670 if ( krc )
671 {
672 if ( ::GetLastError() == ERROR_ACCESS_DENIED )
673 {
674 *krc = wxKILL_ACCESS_DENIED;
675 }
676 else
677 {
678 *krc = wxKILL_NO_PROCESS;
679 }
680 }
681
682 return -1;
683 }
684
685 bool ok = true;
686 switch ( sig )
687 {
688 case wxSIGKILL:
689 // kill the process forcefully returning -1 as error code
690 if ( !::TerminateProcess(hProcess, (UINT)-1) )
691 {
692 wxLogSysError(_("Failed to kill process %d"), pid);
693
694 if ( krc )
695 {
696 // this is not supposed to happen if we could open the
697 // process
698 *krc = wxKILL_ERROR;
699 }
700
701 ok = false;
702 }
703 break;
704
705 case wxSIGNONE:
706 // do nothing, we just want to test for process existence
707 break;
708
709 default:
710 // any other signal means "terminate"
711 {
712 wxFindByPidParams params;
713 params.pid = (DWORD)pid;
714
715 // EnumWindows() has nice semantics: it returns 0 if it found
716 // something or if an error occured and non zero if it
717 // enumerated all the window
718 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
719 {
720 // did we find any window?
721 if ( params.hwnd )
722 {
723 // tell the app to close
724 //
725 // NB: this is the harshest way, the app won't have
726 // opportunity to save any files, for example, but
727 // this is probably what we want here. If not we
728 // can also use SendMesageTimeout(WM_CLOSE)
729 if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
730 {
731 wxLogLastError(_T("PostMessage(WM_QUIT)"));
732 }
733 }
734 else // it was an error then
735 {
736 wxLogLastError(_T("EnumWindows"));
737
738 ok = false;
739 }
740 }
741 else // no windows for this PID
742 {
743 if ( krc )
744 {
745 *krc = wxKILL_ERROR;
746 }
747
748 ok = false;
749 }
750 }
751 }
752
753 // the return code
754 DWORD rc;
755
756 if ( ok )
757 {
758 // as we wait for a short time, we can use just WaitForSingleObject()
759 // and not MsgWaitForMultipleObjects()
760 switch ( ::WaitForSingleObject(hProcess, 500 /* msec */) )
761 {
762 case WAIT_OBJECT_0:
763 // process terminated
764 if ( !::GetExitCodeProcess(hProcess, &rc) )
765 {
766 wxLogLastError(_T("GetExitCodeProcess"));
767 }
768 break;
769
770 default:
771 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
772 // fall through
773
774 case WAIT_FAILED:
775 wxLogLastError(_T("WaitForSingleObject"));
776 // fall through
777
778 case WAIT_TIMEOUT:
779 if ( krc )
780 {
781 *krc = wxKILL_ERROR;
782 }
783
784 rc = STILL_ACTIVE;
785 break;
786 }
787 }
788 else // !ok
789 {
790 // just to suppress the warnings about uninitialized variable
791 rc = 0;
792 }
793
794 ::CloseHandle(hProcess);
795
796 // the return code is the same as from Unix kill(): 0 if killed
797 // successfully or -1 on error
798 //
799 // be careful to interpret rc correctly: for wxSIGNONE we return success if
800 // the process exists, for all the other sig values -- if it doesn't
801 if ( ok &&
802 ((sig == wxSIGNONE) == (rc == STILL_ACTIVE)) )
803 {
804 if ( krc )
805 {
806 *krc = wxKILL_OK;
807 }
808
809 return 0;
810 }
811
812 // error
813 return -1;
814 }
815
816 HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
817 BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
818 BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
819
820 static void InitToolHelp32()
821 {
822 static bool s_initToolHelpDone = false;
823
824 if (s_initToolHelpDone)
825 return;
826
827 s_initToolHelpDone = true;
828
829 lpfCreateToolhelp32Snapshot = NULL;
830 lpfProcess32First = NULL;
831 lpfProcess32Next = NULL;
832
833 #ifdef __WXWINCE__
834 HINSTANCE hInstLib = LoadLibrary( wxT("Kernel32.DLL") ) ;
835 #else
836 HINSTANCE hInstLib = LoadLibraryA( "Kernel32.DLL" ) ;
837 #endif
838 if( hInstLib == NULL )
839 return ;
840
841 // Get procedure addresses.
842 // We are linking to these functions of Kernel32
843 // explicitly, because otherwise a module using
844 // this code would fail to load under Windows NT,
845 // which does not have the Toolhelp32
846 // functions in the Kernel 32.
847 lpfCreateToolhelp32Snapshot=
848 (HANDLE(WINAPI *)(DWORD,DWORD))
849 GetProcAddress( hInstLib,
850 #ifdef __WXWINCE__
851 wxT("CreateToolhelp32Snapshot")
852 #else
853 "CreateToolhelp32Snapshot"
854 #endif
855 ) ;
856
857 lpfProcess32First=
858 (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
859 GetProcAddress( hInstLib,
860 #ifdef __WXWINCE__
861 wxT("Process32First")
862 #else
863 "Process32First"
864 #endif
865 ) ;
866
867 lpfProcess32Next=
868 (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
869 GetProcAddress( hInstLib,
870 #ifdef __WXWINCE__
871 wxT("Process32Next")
872 #else
873 "Process32Next"
874 #endif
875 ) ;
876
877 FreeLibrary( hInstLib ) ;
878 }
879
880 // By John Skiff
881 int wxKillAllChildren(long pid, wxSignal sig, wxKillError *krc)
882 {
883 InitToolHelp32();
884
885 if (krc)
886 *krc = wxKILL_OK;
887
888 // If not implemented for this platform (e.g. NT 4.0), silently ignore
889 if (!lpfCreateToolhelp32Snapshot || !lpfProcess32First || !lpfProcess32Next)
890 return 0;
891
892 // Take a snapshot of all processes in the system.
893 HANDLE hProcessSnap = lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
894 if (hProcessSnap == INVALID_HANDLE_VALUE) {
895 if (krc)
896 *krc = wxKILL_ERROR;
897 return -1;
898 }
899
900 //Fill in the size of the structure before using it.
901 PROCESSENTRY32 pe = {0};
902 pe.dwSize = sizeof(PROCESSENTRY32);
903
904 // Walk the snapshot of the processes, and for each process,
905 // kill it if its parent is pid.
906 if (!lpfProcess32First(hProcessSnap, &pe)) {
907 // Can't get first process.
908 if (krc)
909 *krc = wxKILL_ERROR;
910 CloseHandle (hProcessSnap);
911 return -1;
912 }
913
914 do {
915 if (pe.th32ParentProcessID == (DWORD) pid) {
916 if (wxKill(pe.th32ProcessID, sig, krc))
917 return -1;
918 }
919 } while (lpfProcess32Next (hProcessSnap, &pe));
920
921
922 return 0;
923 }
924
925 // Execute a program in an Interactive Shell
926 bool wxShell(const wxString& command)
927 {
928 wxString cmd;
929
930 #ifdef __WXWINCE__
931 cmd = command;
932 #else
933 wxChar *shell = wxGetenv(wxT("COMSPEC"));
934 if ( !shell )
935 shell = (wxChar*) wxT("\\COMMAND.COM");
936
937 if ( !command )
938 {
939 // just the shell
940 cmd = shell;
941 }
942 else
943 {
944 // pass the command to execute to the command processor
945 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
946 }
947 #endif
948
949 return wxExecute(cmd, wxEXEC_SYNC) == 0;
950 }
951
952 // Shutdown or reboot the PC
953 bool wxShutdown(wxShutdownFlags wFlags)
954 {
955 #ifdef __WXWINCE__
956 return false;
957 #elif defined(__WIN32__)
958 bool bOK = true;
959
960 if ( wxGetOsVersion(NULL, NULL) == wxWINDOWS_NT ) // if is NT or 2K
961 {
962 // Get a token for this process.
963 HANDLE hToken;
964 bOK = ::OpenProcessToken(GetCurrentProcess(),
965 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
966 &hToken) != 0;
967 if ( bOK )
968 {
969 TOKEN_PRIVILEGES tkp;
970
971 // Get the LUID for the shutdown privilege.
972 ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
973 &tkp.Privileges[0].Luid);
974
975 tkp.PrivilegeCount = 1; // one privilege to set
976 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
977
978 // Get the shutdown privilege for this process.
979 ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
980 (PTOKEN_PRIVILEGES)NULL, 0);
981
982 // Cannot test the return value of AdjustTokenPrivileges.
983 bOK = ::GetLastError() == ERROR_SUCCESS;
984 }
985 }
986
987 if ( bOK )
988 {
989 UINT flags = EWX_SHUTDOWN | EWX_FORCE;
990 switch ( wFlags )
991 {
992 case wxSHUTDOWN_POWEROFF:
993 flags |= EWX_POWEROFF;
994 break;
995
996 case wxSHUTDOWN_REBOOT:
997 flags |= EWX_REBOOT;
998 break;
999
1000 default:
1001 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
1002 return false;
1003 }
1004
1005 bOK = ::ExitWindowsEx(flags, 0) != 0;
1006 }
1007
1008 return bOK;
1009 #endif // Win32/16
1010 }
1011
1012 // ----------------------------------------------------------------------------
1013 // misc
1014 // ----------------------------------------------------------------------------
1015
1016 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
1017 long wxGetFreeMemory()
1018 {
1019 #if defined(__WIN32__) && !defined(__BORLANDC__)
1020 MEMORYSTATUS memStatus;
1021 memStatus.dwLength = sizeof(MEMORYSTATUS);
1022 GlobalMemoryStatus(&memStatus);
1023 return memStatus.dwAvailPhys;
1024 #else
1025 return (long)GetFreeSpace(0);
1026 #endif
1027 }
1028
1029 unsigned long wxGetProcessId()
1030 {
1031 return ::GetCurrentProcessId();
1032 }
1033
1034 // Emit a beeeeeep
1035 void wxBell()
1036 {
1037 ::MessageBeep((UINT)-1); // default sound
1038 }
1039
1040 wxString wxGetOsDescription()
1041 {
1042 wxString str;
1043
1044 OSVERSIONINFO info;
1045 wxZeroMemory(info);
1046
1047 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1048 if ( ::GetVersionEx(&info) )
1049 {
1050 switch ( info.dwPlatformId )
1051 {
1052 case VER_PLATFORM_WIN32s:
1053 str = _("Win32s on Windows 3.1");
1054 break;
1055
1056 case VER_PLATFORM_WIN32_WINDOWS:
1057 switch (info.dwMinorVersion)
1058 {
1059 case 0:
1060 if ( info.szCSDVersion[1] == 'B' ||
1061 info.szCSDVersion[1] == 'C' )
1062 {
1063 str = _("Windows 95 OSR2");
1064 }
1065 else
1066 {
1067 str = _("Windows 95");
1068 }
1069 break;
1070 case 10:
1071 if ( info.szCSDVersion[1] == 'B' ||
1072 info.szCSDVersion[1] == 'C' )
1073 {
1074 str = _("Windows 98 SE");
1075 }
1076 else
1077 {
1078 str = _("Windows 98");
1079 }
1080 break;
1081 case 90:
1082 str = _("Windows ME");
1083 break;
1084 default:
1085 str.Printf(_("Windows 9x (%d.%d)"),
1086 info.dwMajorVersion,
1087 info.dwMinorVersion);
1088 break;
1089 }
1090 if ( !wxIsEmpty(info.szCSDVersion) )
1091 {
1092 str << _T(" (") << info.szCSDVersion << _T(')');
1093 }
1094 break;
1095
1096 case VER_PLATFORM_WIN32_NT:
1097 if ( info.dwMajorVersion == 5 )
1098 {
1099 switch ( info.dwMinorVersion )
1100 {
1101 case 0:
1102 str.Printf(_("Windows 2000 (build %lu"),
1103 info.dwBuildNumber);
1104 break;
1105 case 1:
1106 str.Printf(_("Windows XP (build %lu"),
1107 info.dwBuildNumber);
1108 break;
1109 case 2:
1110 str.Printf(_("Windows Server 2003 (build %lu"),
1111 info.dwBuildNumber);
1112 break;
1113 }
1114 }
1115 if ( wxIsEmpty(str) )
1116 {
1117 str.Printf(_("Windows NT %lu.%lu (build %lu"),
1118 info.dwMajorVersion,
1119 info.dwMinorVersion,
1120 info.dwBuildNumber);
1121 }
1122 if ( !wxIsEmpty(info.szCSDVersion) )
1123 {
1124 str << _T(", ") << info.szCSDVersion;
1125 }
1126 str << _T(')');
1127 break;
1128 }
1129 }
1130 else
1131 {
1132 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
1133 }
1134
1135 return str;
1136 }
1137
1138 wxToolkitInfo& wxAppTraits::GetToolkitInfo()
1139 {
1140 // cache the version info, it's not going to change
1141 //
1142 // NB: this is MT-safe, we may use these static vars from different threads
1143 // but as they always have the same value it doesn't matter
1144 static int s_ver = -1,
1145 s_major = -1,
1146 s_minor = -1;
1147
1148 if ( s_ver == -1 )
1149 {
1150 OSVERSIONINFO info;
1151 wxZeroMemory(info);
1152
1153 s_ver = wxWINDOWS;
1154 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1155 if ( ::GetVersionEx(&info) )
1156 {
1157 s_major = info.dwMajorVersion;
1158 s_minor = info.dwMinorVersion;
1159
1160 switch ( info.dwPlatformId )
1161 {
1162 case VER_PLATFORM_WIN32s:
1163 s_ver = wxWIN32S;
1164 break;
1165
1166 case VER_PLATFORM_WIN32_WINDOWS:
1167 s_ver = wxWIN95;
1168 break;
1169
1170 case VER_PLATFORM_WIN32_NT:
1171 s_ver = wxWINDOWS_NT;
1172 break;
1173 #ifdef __WXWINCE__
1174 case VER_PLATFORM_WIN32_CE:
1175 s_ver = wxWINDOWS_CE;
1176 break;
1177 #endif
1178 }
1179 }
1180 }
1181
1182 static wxToolkitInfo info;
1183 info.versionMajor = s_major;
1184 info.versionMinor = s_minor;
1185 info.os = s_ver;
1186 info.name = _T("wxBase");
1187 return info;
1188 }
1189
1190 // ----------------------------------------------------------------------------
1191 // sleep functions
1192 // ----------------------------------------------------------------------------
1193
1194 void wxMilliSleep(unsigned long milliseconds)
1195 {
1196 ::Sleep(milliseconds);
1197 }
1198
1199 void wxMicroSleep(unsigned long microseconds)
1200 {
1201 wxMilliSleep(microseconds/1000);
1202 }
1203
1204 void wxSleep(int nSecs)
1205 {
1206 wxMilliSleep(1000*nSecs);
1207 }
1208
1209 // ----------------------------------------------------------------------------
1210 // font encoding <-> Win32 codepage conversion functions
1211 // ----------------------------------------------------------------------------
1212
1213 extern WXDLLIMPEXP_BASE long wxEncodingToCharset(wxFontEncoding encoding)
1214 {
1215 switch ( encoding )
1216 {
1217 // although this function is supposed to return an exact match, do do
1218 // some mappings here for the most common case of "standard" encoding
1219 case wxFONTENCODING_SYSTEM:
1220 return DEFAULT_CHARSET;
1221
1222 case wxFONTENCODING_ISO8859_1:
1223 case wxFONTENCODING_ISO8859_15:
1224 case wxFONTENCODING_CP1252:
1225 return ANSI_CHARSET;
1226
1227 #if !defined(__WXMICROWIN__)
1228 // The following four fonts are multi-byte charsets
1229 case wxFONTENCODING_CP932:
1230 return SHIFTJIS_CHARSET;
1231
1232 case wxFONTENCODING_CP936:
1233 return GB2312_CHARSET;
1234
1235 case wxFONTENCODING_CP949:
1236 return HANGUL_CHARSET;
1237
1238 case wxFONTENCODING_CP950:
1239 return CHINESEBIG5_CHARSET;
1240
1241 // The rest are single byte encodings
1242 case wxFONTENCODING_CP1250:
1243 return EASTEUROPE_CHARSET;
1244
1245 case wxFONTENCODING_CP1251:
1246 return RUSSIAN_CHARSET;
1247
1248 case wxFONTENCODING_CP1253:
1249 return GREEK_CHARSET;
1250
1251 case wxFONTENCODING_CP1254:
1252 return TURKISH_CHARSET;
1253
1254 case wxFONTENCODING_CP1255:
1255 return HEBREW_CHARSET;
1256
1257 case wxFONTENCODING_CP1256:
1258 return ARABIC_CHARSET;
1259
1260 case wxFONTENCODING_CP1257:
1261 return BALTIC_CHARSET;
1262
1263 case wxFONTENCODING_CP874:
1264 return THAI_CHARSET;
1265 #endif // !__WXMICROWIN__
1266
1267 case wxFONTENCODING_CP437:
1268 return OEM_CHARSET;
1269
1270 default:
1271 // no way to translate this encoding into a Windows charset
1272 return -1;
1273 }
1274 }
1275
1276 // we have 2 versions of wxCharsetToCodepage(): the old one which directly
1277 // looks up the vlaues in the registry and the new one which is more
1278 // politically correct and has more chances to work on other Windows versions
1279 // as well but the old version is still needed for !wxUSE_FONTMAP case
1280 #if wxUSE_FONTMAP
1281
1282 #include "wx/fontmap.h"
1283
1284 extern WXDLLIMPEXP_BASE long wxEncodingToCodepage(wxFontEncoding encoding)
1285 {
1286 // translate encoding into the Windows CHARSET
1287 long charset = wxEncodingToCharset(encoding);
1288 if ( charset == -1 )
1289 return -1;
1290
1291 // translate CHARSET to code page
1292 CHARSETINFO csetInfo;
1293 if ( !::TranslateCharsetInfo((DWORD *)(DWORD)charset,
1294 &csetInfo,
1295 TCI_SRCCHARSET) )
1296 {
1297 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1298
1299 return -1;
1300 }
1301
1302 return csetInfo.ciACP;
1303 }
1304
1305 extern long wxCharsetToCodepage(const wxChar *name)
1306 {
1307 // first get the font encoding for this charset
1308 if ( !name )
1309 return -1;
1310
1311 wxFontEncoding enc = wxFontMapper::Get()->CharsetToEncoding(name, false);
1312 if ( enc == wxFONTENCODING_SYSTEM )
1313 return -1;
1314
1315 // the use the helper function
1316 return wxEncodingToCodepage(enc);
1317 }
1318
1319 #else // !wxUSE_FONTMAP
1320
1321 #include "wx/msw/registry.h"
1322
1323 // this should work if Internet Exploiter is installed
1324 extern long wxCharsetToCodepage(const wxChar *name)
1325 {
1326 if (!name)
1327 return GetACP();
1328
1329 long CP = -1;
1330
1331 wxString path(wxT("MIME\\Database\\Charset\\"));
1332 wxString cn(name);
1333
1334 // follow the alias loop
1335 for ( ;; )
1336 {
1337 wxRegKey key(wxRegKey::HKCR, path + cn);
1338
1339 if (!key.Exists())
1340 break;
1341
1342 // two cases: either there's an AliasForCharset string,
1343 // or there are Codepage and InternetEncoding dwords.
1344 // The InternetEncoding gives us the actual encoding,
1345 // the Codepage just says which Windows character set to
1346 // use when displaying the data.
1347 if (key.HasValue(wxT("InternetEncoding")) &&
1348 key.QueryValue(wxT("InternetEncoding"), &CP))
1349 break;
1350
1351 // no encoding, see if it's an alias
1352 if (!key.HasValue(wxT("AliasForCharset")) ||
1353 !key.QueryValue(wxT("AliasForCharset"), cn))
1354 break;
1355 }
1356
1357 return CP;
1358 }
1359
1360 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1361
1362 /*
1363 Creates a hidden window with supplied window proc registering the class for
1364 it if necesssary (i.e. the first time only). Caller is responsible for
1365 destroying the window and unregistering the class (note that this must be
1366 done because wxWidgets may be used as a DLL and so may be loaded/unloaded
1367 multiple times into/from the same process so we cna't rely on automatic
1368 Windows class unregistration).
1369
1370 pclassname is a pointer to a caller stored classname, which must initially be
1371 NULL. classname is the desired wndclass classname. If function succesfully
1372 registers the class, pclassname will be set to classname.
1373 */
1374 extern "C" WXDLLIMPEXP_BASE HWND
1375 wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc)
1376 {
1377 wxCHECK_MSG( classname && pclassname && wndproc, NULL,
1378 _T("NULL parameter in wxCreateHiddenWindow") );
1379
1380 // register the class fi we need to first
1381 if ( *pclassname == NULL )
1382 {
1383 WNDCLASS wndclass;
1384 wxZeroMemory(wndclass);
1385
1386 wndclass.lpfnWndProc = wndproc;
1387 wndclass.hInstance = wxGetInstance();
1388 wndclass.lpszClassName = classname;
1389
1390 if ( !::RegisterClass(&wndclass) )
1391 {
1392 wxLogLastError(wxT("RegisterClass() in wxCreateHiddenWindow"));
1393
1394 return NULL;
1395 }
1396
1397 *pclassname = classname;
1398 }
1399
1400 // next create the window
1401 HWND hwnd = ::CreateWindow
1402 (
1403 *pclassname,
1404 NULL,
1405 0, 0, 0, 0,
1406 0,
1407 (HWND) NULL,
1408 (HMENU)NULL,
1409 wxGetInstance(),
1410 (LPVOID) NULL
1411 );
1412
1413 if ( !hwnd )
1414 {
1415 wxLogLastError(wxT("CreateWindow() in wxCreateHiddenWindow"));
1416 }
1417
1418 return hwnd;
1419 }
1420