]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utils.cpp
Updated documentation according to recent array changes.
[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 and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 // #pragma implementation "utils.h" // Note: this is done in utilscmn.cpp now.
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/intl.h"
35 #include "wx/log.h"
36 #if wxUSE_GUI
37 #include "wx/cursor.h"
38 #endif
39 #endif //WX_PRECOMP
40
41 // In some mingws there is a missing extern "C" int the winsock header,
42 // so we put it here just to be safe. Note that this must appear _before_
43 // #include "wx/msw/private.h" which itself includes <windows.h>, as this
44 // one in turn includes <winsock.h> unless we define WIN32_LEAN_AND_MEAN.
45 //
46 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
47 extern "C" {
48 #include <winsock.h> // we use socket functions in wxGetFullHostName()
49 }
50 #endif
51
52 #include "wx/msw/private.h" // includes <windows.h>
53
54 #include "wx/timer.h"
55
56 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
57 #include <direct.h>
58
59 #ifndef __MWERKS__
60 #include <dos.h>
61 #endif
62 #endif //GNUWIN32
63
64 #if defined(__CYGWIN__) && !defined(__TWIN32__)
65 #include <sys/unistd.h>
66 #include <sys/stat.h>
67 #include <sys/cygwin.h> // for cygwin_conv_to_full_win32_path()
68 #endif //GNUWIN32
69
70 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
71 // this (3.1 I believe) and how to test for it.
72 // If this works for Borland 4.0 as well, then no worries.
73 #include <dir.h>
74 #endif
75
76 // VZ: there is some code using NetXXX() functions to get the full user name:
77 // I don't think it's a good idea because they don't work under Win95 and
78 // seem to return the same as wxGetUserId() under NT. If you really want
79 // to use them, just #define USE_NET_API
80 #undef USE_NET_API
81
82 #ifdef USE_NET_API
83 #include <lm.h>
84 #endif // USE_NET_API
85
86 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
87 #include <io.h>
88
89 #ifndef __GNUWIN32__
90 #include <shellapi.h>
91 #endif
92 #endif
93
94 #ifndef __WATCOMC__
95 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
96 #include <errno.h>
97 #endif
98 #endif
99
100 //// BEGIN for console support: VC++ only
101 #ifdef __VISUALC__
102
103 #include "wx/msw/msvcrt.h"
104
105 #include <fcntl.h>
106
107 #include "wx/ioswrap.h"
108
109 /* Need to undef new if including crtdbg.h */
110 # ifdef new
111 # undef new
112 # endif
113
114 #ifndef __WIN16__
115 # include <crtdbg.h>
116 #endif
117
118 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
119 # define new new(__TFILE__,__LINE__)
120 # endif
121
122 #endif
123 // __VISUALC__
124 /// END for console support
125
126 // ----------------------------------------------------------------------------
127 // constants
128 // ----------------------------------------------------------------------------
129
130 // In the WIN.INI file
131 static const wxChar WX_SECTION[] = wxT("wxWindows");
132 static const wxChar eUSERNAME[] = wxT("UserName");
133
134 // these are only used under Win16
135 #if !defined(__WIN32__) && !defined(__WXMICROWIN__)
136 static const wxChar eHOSTNAME[] = wxT("HostName");
137 static const wxChar eUSERID[] = wxT("UserId");
138 #endif // !Win32
139
140 #ifndef __WXMICROWIN__
141
142 // ============================================================================
143 // implementation
144 // ============================================================================
145
146 // ----------------------------------------------------------------------------
147 // get host name and related
148 // ----------------------------------------------------------------------------
149
150 // Get hostname only (without domain name)
151 bool wxGetHostName(wxChar *buf, int maxSize)
152 {
153 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
154 DWORD nSize = maxSize;
155 if ( !::GetComputerName(buf, &nSize) )
156 {
157 wxLogLastError(wxT("GetComputerName"));
158
159 return FALSE;
160 }
161
162 return TRUE;
163 #else
164 wxChar *sysname;
165 const wxChar *default_host = wxT("noname");
166
167 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
168 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
169 } else
170 wxStrncpy(buf, sysname, maxSize - 1);
171 buf[maxSize] = wxT('\0');
172 return *buf ? TRUE : FALSE;
173 #endif
174 }
175
176 // get full hostname (with domain name if possible)
177 bool wxGetFullHostName(wxChar *buf, int maxSize)
178 {
179 #if defined(__WIN32__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
180 // TODO should use GetComputerNameEx() when available
181
182 // the idea is that if someone had set wxUSE_SOCKETS to 0 the code
183 // shouldn't use winsock.dll (a.k.a. ws2_32.dll) at all so only use this
184 // code if we link with it anyhow
185 #if wxUSE_SOCKETS
186 WSADATA wsa;
187 if ( WSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
188 {
189 wxString host;
190 char bufA[256];
191 if ( gethostname(bufA, WXSIZEOF(bufA)) == 0 )
192 {
193 // gethostname() won't usually include the DNS domain name, for
194 // this we need to work a bit more
195 if ( !strchr(bufA, '.') )
196 {
197 struct hostent *pHostEnt = gethostbyname(bufA);
198
199 if ( pHostEnt )
200 {
201 // Windows will use DNS internally now
202 pHostEnt = gethostbyaddr(pHostEnt->h_addr, 4, PF_INET);
203 }
204
205 if ( pHostEnt )
206 {
207 host = pHostEnt->h_name;
208 }
209 }
210 }
211
212 WSACleanup();
213
214 if ( !host.empty() )
215 {
216 wxStrncpy(buf, host, maxSize);
217
218 return TRUE;
219 }
220 }
221 #endif // wxUSE_SOCKETS
222
223 #endif // Win32
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(__WIN32__) && !defined(__win32s__) && !defined(__TWIN32__) && !defined(__WXMICROWIN__)
232 DWORD nSize = maxSize;
233 if ( ::GetUserName(buf, &nSize) == 0 )
234 {
235 // actually, it does happen on Win9x if the user didn't log on
236 DWORD res = ::GetEnvironmentVariable(wxT("username"), buf, maxSize);
237 if ( res == 0 )
238 {
239 // not found
240 return FALSE;
241 }
242 }
243
244 return TRUE;
245 #else // Win16 or Win32s
246 wxChar *user;
247 const wxChar *default_id = wxT("anonymous");
248
249 // Can't assume we have NIS (PC-NFS) or some other ID daemon
250 // So we ...
251 if ( (user = wxGetenv(wxT("USER"))) == NULL &&
252 (user = wxGetenv(wxT("LOGNAME"))) == NULL )
253 {
254 // Use wxWindows configuration data (comming soon)
255 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
256 }
257 else
258 {
259 wxStrncpy(buf, user, maxSize - 1);
260 }
261
262 return *buf ? TRUE : FALSE;
263 #endif
264 }
265
266 // Get user name e.g. Julian Smart
267 bool wxGetUserName(wxChar *buf, int maxSize)
268 {
269 #if wxUSE_PENWINDOWS && !defined(__WATCOMC__) && !defined(__GNUWIN32__)
270 extern HANDLE g_hPenWin; // PenWindows Running?
271 if (g_hPenWin)
272 {
273 // PenWindows Does have a user concept!
274 // Get the current owner of the recognizer
275 GetPrivateProfileString("Current", "User", default_name, wxBuffer, maxSize - 1, "PENWIN.INI");
276 strncpy(buf, wxBuffer, maxSize - 1);
277 }
278 else
279 #endif
280 {
281 #ifdef USE_NET_API
282 CHAR szUserName[256];
283 if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
284 return FALSE;
285
286 // TODO how to get the domain name?
287 CHAR *szDomain = "";
288
289 // the code is based on the MSDN example (also see KB article Q119670)
290 WCHAR wszUserName[256]; // Unicode user name
291 WCHAR wszDomain[256];
292 LPBYTE ComputerName;
293
294 USER_INFO_2 *ui2; // User structure
295
296 // Convert ANSI user name and domain to Unicode
297 MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
298 wszUserName, WXSIZEOF(wszUserName) );
299 MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
300 wszDomain, WXSIZEOF(wszDomain) );
301
302 // Get the computer name of a DC for the domain.
303 if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
304 {
305 wxLogError(wxT("Can not find domain controller"));
306
307 goto error;
308 }
309
310 // Look up the user on the DC
311 NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
312 (LPWSTR)&wszUserName,
313 2, // level - we want USER_INFO_2
314 (LPBYTE *) &ui2 );
315 switch ( status )
316 {
317 case NERR_Success:
318 // ok
319 break;
320
321 case NERR_InvalidComputer:
322 wxLogError(wxT("Invalid domain controller name."));
323
324 goto error;
325
326 case NERR_UserNotFound:
327 wxLogError(wxT("Invalid user name '%s'."), szUserName);
328
329 goto error;
330
331 default:
332 wxLogSysError(wxT("Can't get information about user"));
333
334 goto error;
335 }
336
337 // Convert the Unicode full name to ANSI
338 WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
339 buf, maxSize, NULL, NULL );
340
341 return TRUE;
342
343 error:
344 wxLogError(wxT("Couldn't look up full user name."));
345
346 return FALSE;
347 #else // !USE_NET_API
348 // Could use NIS, MS-Mail or other site specific programs
349 // Use wxWindows configuration data
350 bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxT(""), buf, maxSize - 1) != 0;
351 if ( !ok )
352 {
353 ok = wxGetUserId(buf, maxSize);
354 }
355
356 if ( !ok )
357 {
358 wxStrncpy(buf, wxT("Unknown User"), maxSize);
359 }
360 #endif // Win32/16
361 }
362
363 return TRUE;
364 }
365
366 const wxChar* wxGetHomeDir(wxString *pstr)
367 {
368 wxString& strDir = *pstr;
369
370 #if defined(__UNIX__) && !defined(__TWIN32__)
371 const wxChar *szHome = wxGetenv("HOME");
372 if ( szHome == NULL ) {
373 // we're homeless...
374 wxLogWarning(_("can't find user's HOME, using current directory."));
375 strDir = wxT(".");
376 }
377 else
378 strDir = szHome;
379
380 // add a trailing slash if needed
381 if ( strDir.Last() != wxT('/') )
382 strDir << wxT('/');
383
384 #ifdef __CYGWIN__
385 // Cygwin returns unix type path but that does not work well
386 static wxChar windowsPath[MAX_PATH];
387 cygwin_conv_to_full_win32_path(strDir, windowsPath);
388 strDir = windowsPath;
389 #endif
390 #else // Windows
391 #ifdef __WIN32__
392 strDir.clear();
393
394 // If we have a valid HOME directory, as is used on many machines that
395 // have unix utilities on them, we should use that.
396 const wxChar *szHome = wxGetenv(wxT("HOME"));
397
398 if ( szHome != NULL )
399 {
400 strDir = szHome;
401 }
402 else // no HOME, try HOMEDRIVE/PATH
403 {
404 szHome = wxGetenv(wxT("HOMEDRIVE"));
405 if ( szHome != NULL )
406 strDir << szHome;
407 szHome = wxGetenv(wxT("HOMEPATH"));
408
409 if ( szHome != NULL )
410 {
411 strDir << szHome;
412
413 // the idea is that under NT these variables have default values
414 // of "%systemdrive%:" and "\\". As we don't want to create our
415 // config files in the root directory of the system drive, we will
416 // create it in our program's dir. However, if the user took care
417 // to set HOMEPATH to something other than "\\", we suppose that he
418 // knows what he is doing and use the supplied value.
419 if ( wxStrcmp(szHome, wxT("\\")) == 0 )
420 strDir.clear();
421 }
422 }
423
424 if ( strDir.empty() )
425 {
426 // If we have a valid USERPROFILE directory, as is the case in
427 // Windows NT, 2000 and XP, we should use that as our home directory.
428 szHome = wxGetenv(wxT("USERPROFILE"));
429
430 if ( szHome != NULL )
431 strDir = szHome;
432 }
433
434 if ( !strDir.empty() )
435 {
436 return strDir.c_str();
437 }
438 //else: fall back to the prograrm directory
439 #else // Win16
440 // Win16 has no idea about home, so use the executable directory instead
441 #endif // WIN16/32
442
443 // 260 was taken from windef.h
444 #ifndef MAX_PATH
445 #define MAX_PATH 260
446 #endif
447
448 wxString strPath;
449 ::GetModuleFileName(::GetModuleHandle(NULL),
450 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
451 strPath.UngetWriteBuf();
452
453 // extract the dir name
454 wxSplitPath(strPath, &strDir, NULL, NULL);
455
456 #endif // UNIX/Win
457
458 return strDir.c_str();
459 }
460
461 wxChar *wxGetUserHome(const wxString& WXUNUSED(user))
462 {
463 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
464 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
465 // static buffer and sometimes I don't even know what.
466 static wxString s_home;
467
468 return (wxChar *)wxGetHomeDir(&s_home);
469 }
470
471 bool wxDirExists(const wxString& dir)
472 {
473 #ifdef __WXMICROWIN__
474 return wxPathExist(dir);
475 #elif defined(__WIN32__)
476 DWORD attribs = GetFileAttributes(dir);
477 return ((attribs != (DWORD)-1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
478 #else // Win16
479 #ifdef __BORLANDC__
480 struct ffblk fileInfo;
481 #else
482 struct find_t fileInfo;
483 #endif
484 // In Borland findfirst has a different argument
485 // ordering from _dos_findfirst. But _dos_findfirst
486 // _should_ be ok in both MS and Borland... why not?
487 #ifdef __BORLANDC__
488 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
489 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
490 #else
491 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
492 ((fileInfo.attrib & _A_SUBDIR) != 0);
493 #endif
494 #endif // Win32/16
495 }
496
497 bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
498 {
499 if ( path.empty() )
500 return FALSE;
501
502 // old w32api don't have ULARGE_INTEGER
503 #if defined(__WIN32__) && \
504 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
505 // GetDiskFreeSpaceEx() is not available under original Win95, check for
506 // it
507 typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
508 PULARGE_INTEGER,
509 PULARGE_INTEGER,
510 PULARGE_INTEGER);
511
512 GetDiskFreeSpaceEx_t
513 pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
514 (
515 ::GetModuleHandle(_T("kernel32.dll")),
516 #if wxUSE_UNICODE
517 "GetDiskFreeSpaceExW"
518 #else
519 "GetDiskFreeSpaceExA"
520 #endif
521 );
522
523 if ( pGetDiskFreeSpaceEx )
524 {
525 ULARGE_INTEGER bytesFree, bytesTotal;
526
527 // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
528 if ( !pGetDiskFreeSpaceEx(path,
529 &bytesFree,
530 &bytesTotal,
531 NULL) )
532 {
533 wxLogLastError(_T("GetDiskFreeSpaceEx"));
534
535 return FALSE;
536 }
537
538 // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
539 // two 32 bit fields which may be or may be not named - try to make it
540 // compile in all cases
541 #if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
542 #define UL(ul) ul.u
543 #else // anon union
544 #define UL(ul) ul
545 #endif
546 if ( pTotal )
547 {
548 *pTotal = wxLongLong(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
549 }
550
551 if ( pFree )
552 {
553 *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
554 }
555 }
556 else
557 #endif // Win32
558 {
559 // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
560 // should be used instead - but if it's not available, fall back on
561 // GetDiskFreeSpace() nevertheless...
562
563 DWORD lSectorsPerCluster,
564 lBytesPerSector,
565 lNumberOfFreeClusters,
566 lTotalNumberOfClusters;
567
568 // FIXME: this is wrong, we should extract the root drive from path
569 // instead, but this is the job for wxFileName...
570 if ( !::GetDiskFreeSpace(path,
571 &lSectorsPerCluster,
572 &lBytesPerSector,
573 &lNumberOfFreeClusters,
574 &lTotalNumberOfClusters) )
575 {
576 wxLogLastError(_T("GetDiskFreeSpace"));
577
578 return FALSE;
579 }
580
581 wxLongLong lBytesPerCluster = lSectorsPerCluster;
582 lBytesPerCluster *= lBytesPerSector;
583
584 if ( pTotal )
585 {
586 *pTotal = lBytesPerCluster;
587 *pTotal *= lTotalNumberOfClusters;
588 }
589
590 if ( pFree )
591 {
592 *pFree = lBytesPerCluster;
593 *pFree *= lNumberOfFreeClusters;
594 }
595 }
596
597 return TRUE;
598 }
599
600 // ----------------------------------------------------------------------------
601 // env vars
602 // ----------------------------------------------------------------------------
603
604 bool wxGetEnv(const wxString& var, wxString *value)
605 {
606 #ifdef __WIN16__
607 const wxChar* ret = wxGetenv(var);
608 if (ret)
609 {
610 *value = ret;
611 return TRUE;
612 }
613 else
614 return FALSE;
615 #else
616 // first get the size of the buffer
617 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
618 if ( !dwRet )
619 {
620 // this means that there is no such variable
621 return FALSE;
622 }
623
624 if ( value )
625 {
626 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
627 value->UngetWriteBuf();
628 }
629
630 return TRUE;
631 #endif
632 }
633
634 bool wxSetEnv(const wxString& var, const wxChar *value)
635 {
636 // some compilers have putenv() or _putenv() or _wputenv() but it's better
637 // to always use Win32 function directly instead of dealing with them
638 #if defined(__WIN32__)
639 if ( !::SetEnvironmentVariable(var, value) )
640 {
641 wxLogLastError(_T("SetEnvironmentVariable"));
642
643 return FALSE;
644 }
645
646 return TRUE;
647 #else // no way to set env vars
648 return FALSE;
649 #endif
650 }
651
652 // ----------------------------------------------------------------------------
653 // process management
654 // ----------------------------------------------------------------------------
655
656 #ifdef __WIN32__
657
658 // structure used to pass parameters from wxKill() to wxEnumFindByPidProc()
659 struct wxFindByPidParams
660 {
661 wxFindByPidParams() { hwnd = 0; pid = 0; }
662
663 // the HWND used to return the result
664 HWND hwnd;
665
666 // the PID we're looking from
667 DWORD pid;
668 };
669
670 // wxKill helper: EnumWindows() callback which is used to find the first (top
671 // level) window belonging to the given process
672 BOOL CALLBACK wxEnumFindByPidProc(HWND hwnd, LPARAM lParam)
673 {
674 DWORD pid;
675 (void)::GetWindowThreadProcessId(hwnd, &pid);
676
677 wxFindByPidParams *params = (wxFindByPidParams *)lParam;
678 if ( pid == params->pid )
679 {
680 // remember the window we found
681 params->hwnd = hwnd;
682
683 // return FALSE to stop the enumeration
684 return FALSE;
685 }
686
687 // continue enumeration
688 return TRUE;
689 }
690
691 #endif // __WIN32__
692
693 int wxKill(long pid, wxSignal sig, wxKillError *krc)
694 {
695 #ifdef __WIN32__
696 // get the process handle to operate on
697 HANDLE hProcess = ::OpenProcess(SYNCHRONIZE |
698 PROCESS_TERMINATE |
699 PROCESS_QUERY_INFORMATION,
700 FALSE, // not inheritable
701 (DWORD)pid);
702 if ( hProcess == NULL )
703 {
704 if ( krc )
705 {
706 if ( ::GetLastError() == ERROR_ACCESS_DENIED )
707 {
708 *krc = wxKILL_ACCESS_DENIED;
709 }
710 else
711 {
712 *krc = wxKILL_NO_PROCESS;
713 }
714 }
715
716 return -1;
717 }
718
719 bool ok = TRUE;
720 switch ( sig )
721 {
722 case wxSIGKILL:
723 // kill the process forcefully returning -1 as error code
724 if ( !::TerminateProcess(hProcess, (UINT)-1) )
725 {
726 wxLogSysError(_("Failed to kill process %d"), pid);
727
728 if ( krc )
729 {
730 // this is not supposed to happen if we could open the
731 // process
732 *krc = wxKILL_ERROR;
733 }
734
735 ok = FALSE;
736 }
737 break;
738
739 case wxSIGNONE:
740 // do nothing, we just want to test for process existence
741 break;
742
743 default:
744 // any other signal means "terminate"
745 {
746 wxFindByPidParams params;
747 params.pid = (DWORD)pid;
748
749 // EnumWindows() has nice semantics: it returns 0 if it found
750 // something or if an error occured and non zero if it
751 // enumerated all the window
752 if ( !::EnumWindows(wxEnumFindByPidProc, (LPARAM)&params) )
753 {
754 // did we find any window?
755 if ( params.hwnd )
756 {
757 // tell the app to close
758 //
759 // NB: this is the harshest way, the app won't have
760 // opportunity to save any files, for example, but
761 // this is probably what we want here. If not we
762 // can also use SendMesageTimeout(WM_CLOSE)
763 if ( !::PostMessage(params.hwnd, WM_QUIT, 0, 0) )
764 {
765 wxLogLastError(_T("PostMessage(WM_QUIT)"));
766 }
767 }
768 else // it was an error then
769 {
770 wxLogLastError(_T("EnumWindows"));
771
772 ok = FALSE;
773 }
774 }
775 else // no windows for this PID
776 {
777 if ( krc )
778 {
779 *krc = wxKILL_ERROR;
780 }
781
782 ok = FALSE;
783 }
784 }
785 }
786
787 // the return code
788 DWORD rc;
789
790 if ( ok )
791 {
792 // as we wait for a short time, we can use just WaitForSingleObject()
793 // and not MsgWaitForMultipleObjects()
794 switch ( ::WaitForSingleObject(hProcess, 500 /* msec */) )
795 {
796 case WAIT_OBJECT_0:
797 // process terminated
798 if ( !::GetExitCodeProcess(hProcess, &rc) )
799 {
800 wxLogLastError(_T("GetExitCodeProcess"));
801 }
802 break;
803
804 default:
805 wxFAIL_MSG( _T("unexpected WaitForSingleObject() return") );
806 // fall through
807
808 case WAIT_FAILED:
809 wxLogLastError(_T("WaitForSingleObject"));
810 // fall through
811
812 case WAIT_TIMEOUT:
813 if ( krc )
814 {
815 *krc = wxKILL_ERROR;
816 }
817
818 rc = STILL_ACTIVE;
819 break;
820 }
821 }
822 else // !ok
823 {
824 // just to suppress the warnings about uninitialized variable
825 rc = 0;
826 }
827
828 ::CloseHandle(hProcess);
829
830 // the return code is the same as from Unix kill(): 0 if killed
831 // successfully or -1 on error
832 if ( sig == wxSIGNONE )
833 {
834 if ( ok && rc == STILL_ACTIVE )
835 {
836 // there is such process => success
837 return 0;
838 }
839 }
840 else // not SIGNONE
841 {
842 if ( ok && rc != STILL_ACTIVE )
843 {
844 // killed => success
845 return 0;
846 }
847 }
848 #else // Win15
849 wxFAIL_MSG( _T("not implemented") );
850 #endif // Win32/Win16
851
852 // error
853 return -1;
854 }
855
856 // Execute a program in an Interactive Shell
857 bool wxShell(const wxString& command)
858 {
859 wxChar *shell = wxGetenv(wxT("COMSPEC"));
860 if ( !shell )
861 shell = wxT("\\COMMAND.COM");
862
863 wxString cmd;
864 if ( !command )
865 {
866 // just the shell
867 cmd = shell;
868 }
869 else
870 {
871 // pass the command to execute to the command processor
872 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
873 }
874
875 return wxExecute(cmd, TRUE /* sync */) != 0;
876 }
877
878 // ----------------------------------------------------------------------------
879 // misc
880 // ----------------------------------------------------------------------------
881
882 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
883 long wxGetFreeMemory()
884 {
885 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
886 MEMORYSTATUS memStatus;
887 memStatus.dwLength = sizeof(MEMORYSTATUS);
888 GlobalMemoryStatus(&memStatus);
889 return memStatus.dwAvailPhys;
890 #else
891 return (long)GetFreeSpace(0);
892 #endif
893 }
894
895 // Emit a beeeeeep
896 void wxBell()
897 {
898 ::MessageBeep((UINT)-1); // default sound
899 }
900
901 wxString wxGetOsDescription()
902 {
903 #ifdef __WIN32__
904 wxString str;
905
906 OSVERSIONINFO info;
907 wxZeroMemory(info);
908
909 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
910 if ( ::GetVersionEx(&info) )
911 {
912 switch ( info.dwPlatformId )
913 {
914 case VER_PLATFORM_WIN32s:
915 str = _("Win32s on Windows 3.1");
916 break;
917
918 case VER_PLATFORM_WIN32_WINDOWS:
919 str.Printf(_("Windows 9%c"),
920 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
921 if ( !wxIsEmpty(info.szCSDVersion) )
922 {
923 str << _T(" (") << info.szCSDVersion << _T(')');
924 }
925 break;
926
927 case VER_PLATFORM_WIN32_NT:
928 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
929 info.dwMajorVersion,
930 info.dwMinorVersion,
931 info.dwBuildNumber);
932 if ( !wxIsEmpty(info.szCSDVersion) )
933 {
934 str << _T(", ") << info.szCSDVersion;
935 }
936 str << _T(')');
937 break;
938 }
939 }
940 else
941 {
942 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
943 }
944
945 return str;
946 #else // Win16
947 return _("Windows 3.1");
948 #endif // Win32/16
949 }
950
951 int wxGetOsVersion(int *majorVsn, int *minorVsn)
952 {
953 #if defined(__WIN32__) && !defined(__SC__)
954 static int ver = -1, major = -1, minor = -1;
955
956 if ( ver == -1 )
957 {
958 OSVERSIONINFO info;
959 wxZeroMemory(info);
960
961 ver = wxWINDOWS;
962 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
963 if ( ::GetVersionEx(&info) )
964 {
965 major = info.dwMajorVersion;
966 minor = info.dwMinorVersion;
967
968 switch ( info.dwPlatformId )
969 {
970 case VER_PLATFORM_WIN32s:
971 ver = wxWIN32S;
972 break;
973
974 case VER_PLATFORM_WIN32_WINDOWS:
975 ver = wxWIN95;
976 break;
977
978 case VER_PLATFORM_WIN32_NT:
979 ver = wxWINDOWS_NT;
980 break;
981 }
982 }
983 }
984
985 if (majorVsn && major != -1)
986 *majorVsn = major;
987 if (minorVsn && minor != -1)
988 *minorVsn = minor;
989
990 return ver;
991 #else // Win16
992 int retValue = wxWINDOWS;
993 #ifdef __WINDOWS_386__
994 retValue = wxWIN386;
995 #else
996 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
997 extern HANDLE g_hPenWin;
998 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
999 #endif
1000 #endif
1001
1002 if (majorVsn)
1003 *majorVsn = 3;
1004 if (minorVsn)
1005 *minorVsn = 1;
1006
1007 return retValue;
1008 #endif
1009 }
1010
1011 // ----------------------------------------------------------------------------
1012 // sleep functions
1013 // ----------------------------------------------------------------------------
1014
1015 #if wxUSE_GUI
1016
1017 #if wxUSE_TIMER
1018
1019 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
1020 static bool gs_inTimer = FALSE;
1021
1022 class wxSleepTimer : public wxTimer
1023 {
1024 public:
1025 virtual void Notify()
1026 {
1027 gs_inTimer = FALSE;
1028 Stop();
1029 }
1030 };
1031
1032 static wxTimer *wxTheSleepTimer = NULL;
1033
1034 void wxUsleep(unsigned long milliseconds)
1035 {
1036 #ifdef __WIN32__
1037 ::Sleep(milliseconds);
1038 #else // !Win32
1039 if (gs_inTimer)
1040 return;
1041
1042 wxTheSleepTimer = new wxSleepTimer;
1043 gs_inTimer = TRUE;
1044 wxTheSleepTimer->Start(milliseconds);
1045 while (gs_inTimer)
1046 {
1047 if (wxTheApp->Pending())
1048 wxTheApp->Dispatch();
1049 }
1050 delete wxTheSleepTimer;
1051 wxTheSleepTimer = NULL;
1052 #endif // Win32/!Win32
1053 }
1054
1055 void wxSleep(int nSecs)
1056 {
1057 if (gs_inTimer)
1058 return;
1059
1060 wxTheSleepTimer = new wxSleepTimer;
1061 gs_inTimer = TRUE;
1062 wxTheSleepTimer->Start(nSecs*1000);
1063 while (gs_inTimer)
1064 {
1065 if (wxTheApp->Pending())
1066 wxTheApp->Dispatch();
1067 }
1068 delete wxTheSleepTimer;
1069 wxTheSleepTimer = NULL;
1070 }
1071
1072 // Consume all events until no more left
1073 void wxFlushEvents()
1074 {
1075 // wxYield();
1076 }
1077
1078 #endif // wxUSE_TIMER
1079
1080 #elif defined(__WIN32__) // wxUSE_GUI
1081
1082 void wxUsleep(unsigned long milliseconds)
1083 {
1084 ::Sleep(milliseconds);
1085 }
1086
1087 void wxSleep(int nSecs)
1088 {
1089 wxUsleep(1000*nSecs);
1090 }
1091
1092 #endif // wxUSE_GUI/!wxUSE_GUI
1093 #endif // __WXMICROWIN__
1094
1095 // ----------------------------------------------------------------------------
1096 // deprecated (in favour of wxLog) log functions
1097 // ----------------------------------------------------------------------------
1098
1099 #if WXWIN_COMPATIBILITY_2_2
1100
1101 // Output a debug mess., in a system dependent fashion.
1102 #ifndef __WXMICROWIN__
1103 void wxDebugMsg(const wxChar *fmt ...)
1104 {
1105 va_list ap;
1106 static wxChar buffer[512];
1107
1108 if (!wxTheApp->GetWantDebugOutput())
1109 return ;
1110
1111 va_start(ap, fmt);
1112
1113 wvsprintf(buffer,fmt,ap) ;
1114 OutputDebugString((LPCTSTR)buffer) ;
1115
1116 va_end(ap);
1117 }
1118
1119 // Non-fatal error: pop up message box and (possibly) continue
1120 void wxError(const wxString& msg, const wxString& title)
1121 {
1122 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
1123 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
1124 MB_ICONSTOP | MB_YESNO) == IDNO)
1125 wxExit();
1126 }
1127
1128 // Fatal error: pop up message box and abort
1129 void wxFatalError(const wxString& msg, const wxString& title)
1130 {
1131 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
1132 FatalAppExit(0, (LPCTSTR)wxBuffer);
1133 }
1134 #endif // __WXMICROWIN__
1135
1136 #endif // WXWIN_COMPATIBILITY_2_2
1137
1138 #if wxUSE_GUI
1139
1140 // ----------------------------------------------------------------------------
1141 // functions to work with .INI files
1142 // ----------------------------------------------------------------------------
1143
1144 // Reading and writing resources (eg WIN.INI, .Xdefaults)
1145 #if wxUSE_RESOURCES
1146 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
1147 {
1148 if (file != wxT(""))
1149 // Don't know what the correct cast should be, but it doesn't
1150 // compile in BC++/16-bit without this cast.
1151 #if !defined(__WIN32__)
1152 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
1153 #else
1154 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
1155 #endif
1156 else
1157 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
1158 }
1159
1160 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
1161 {
1162 wxString buf;
1163 buf.Printf(wxT("%.4f"), value);
1164
1165 return wxWriteResource(section, entry, buf, file);
1166 }
1167
1168 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
1169 {
1170 wxString buf;
1171 buf.Printf(wxT("%ld"), value);
1172
1173 return wxWriteResource(section, entry, buf, file);
1174 }
1175
1176 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
1177 {
1178 wxString buf;
1179 buf.Printf(wxT("%d"), value);
1180
1181 return wxWriteResource(section, entry, buf, file);
1182 }
1183
1184 bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
1185 {
1186 static const wxChar defunkt[] = wxT("$$default");
1187 if (file != wxT(""))
1188 {
1189 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1190 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
1191 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1192 return FALSE;
1193 }
1194 else
1195 {
1196 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
1197 (LPTSTR)wxBuffer, 1000);
1198 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
1199 return FALSE;
1200 }
1201 if (*value) delete[] (*value);
1202 *value = copystring(wxBuffer);
1203 return TRUE;
1204 }
1205
1206 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
1207 {
1208 wxChar *s = NULL;
1209 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1210 if (succ)
1211 {
1212 *value = (float)wxStrtod(s, NULL);
1213 delete[] s;
1214 return TRUE;
1215 }
1216 else return FALSE;
1217 }
1218
1219 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
1220 {
1221 wxChar *s = NULL;
1222 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1223 if (succ)
1224 {
1225 *value = wxStrtol(s, NULL, 10);
1226 delete[] s;
1227 return TRUE;
1228 }
1229 else return FALSE;
1230 }
1231
1232 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
1233 {
1234 wxChar *s = NULL;
1235 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
1236 if (succ)
1237 {
1238 *value = (int)wxStrtol(s, NULL, 10);
1239 delete[] s;
1240 return TRUE;
1241 }
1242 else return FALSE;
1243 }
1244 #endif // wxUSE_RESOURCES
1245
1246 // ---------------------------------------------------------------------------
1247 // helper functions for showing a "busy" cursor
1248 // ---------------------------------------------------------------------------
1249
1250 static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
1251 static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
1252 static int gs_wxBusyCursorCount = 0;
1253
1254 extern HCURSOR wxGetCurrentBusyCursor()
1255 {
1256 return gs_wxBusyCursor;
1257 }
1258
1259 // Set the cursor to the busy cursor for all windows
1260 void wxBeginBusyCursor(wxCursor *cursor)
1261 {
1262 if ( gs_wxBusyCursorCount++ == 0 )
1263 {
1264 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
1265 #ifndef __WXMICROWIN__
1266 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
1267 #endif
1268 }
1269 //else: nothing to do, already set
1270 }
1271
1272 // Restore cursor to normal
1273 void wxEndBusyCursor()
1274 {
1275 wxCHECK_RET( gs_wxBusyCursorCount > 0,
1276 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
1277
1278 if ( --gs_wxBusyCursorCount == 0 )
1279 {
1280 #ifndef __WXMICROWIN__
1281 ::SetCursor(gs_wxBusyCursorOld);
1282 #endif
1283 gs_wxBusyCursorOld = 0;
1284 }
1285 }
1286
1287 // TRUE if we're between the above two calls
1288 bool wxIsBusy()
1289 {
1290 return gs_wxBusyCursorCount > 0;
1291 }
1292
1293 // Check whether this window wants to process messages, e.g. Stop button
1294 // in long calculations.
1295 bool wxCheckForInterrupt(wxWindow *wnd)
1296 {
1297 wxCHECK( wnd, FALSE );
1298
1299 MSG msg;
1300 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
1301 {
1302 ::TranslateMessage(&msg);
1303 ::DispatchMessage(&msg);
1304 }
1305
1306 return TRUE;
1307 }
1308
1309 // MSW only: get user-defined resource from the .res file.
1310 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
1311
1312 #ifndef __WXMICROWIN__
1313 wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
1314 {
1315 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
1316 if ( hResource == 0 )
1317 return NULL;
1318
1319 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
1320 if ( hData == 0 )
1321 return NULL;
1322
1323 wxChar *theText = (wxChar *)::LockResource(hData);
1324 if ( !theText )
1325 return NULL;
1326
1327 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
1328 // so we need to find the length of the resource.
1329 int len = ::SizeofResource(wxGetInstance(), hResource);
1330 wxChar *s = new wxChar[len+1];
1331 wxStrncpy(s,theText,len);
1332 s[len]=0;
1333
1334 // wxChar *s = copystring(theText);
1335
1336 // Obsolete in WIN32
1337 #ifndef __WIN32__
1338 UnlockResource(hData);
1339 #endif
1340
1341 // No need??
1342 // GlobalFree(hData);
1343
1344 return s;
1345 }
1346 #endif // __WXMICROWIN__
1347
1348 // ----------------------------------------------------------------------------
1349 // get display info
1350 // ----------------------------------------------------------------------------
1351
1352 // See also the wxGetMousePosition in window.cpp
1353 // Deprecated: use wxPoint wxGetMousePosition() instead
1354 void wxGetMousePosition( int* x, int* y )
1355 {
1356 POINT pt;
1357 GetCursorPos( & pt );
1358 if ( x ) *x = pt.x;
1359 if ( y ) *y = pt.y;
1360 };
1361
1362 // Return TRUE if we have a colour display
1363 bool wxColourDisplay()
1364 {
1365 #ifdef __WXMICROWIN__
1366 // MICROWIN_TODO
1367 return TRUE;
1368 #else
1369 // this function is called from wxDC ctor so it is called a *lot* of times
1370 // hence we optimize it a bit but doign the check only once
1371 //
1372 // this should be MT safe as only the GUI thread (holding the GUI mutex)
1373 // can call us
1374 static int s_isColour = -1;
1375
1376 if ( s_isColour == -1 )
1377 {
1378 ScreenHDC dc;
1379 int noCols = ::GetDeviceCaps(dc, NUMCOLORS);
1380
1381 s_isColour = (noCols == -1) || (noCols > 2);
1382 }
1383
1384 return s_isColour != 0;
1385 #endif
1386 }
1387
1388 // Returns depth of screen
1389 int wxDisplayDepth()
1390 {
1391 ScreenHDC dc;
1392 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
1393 }
1394
1395 // Get size of display
1396 void wxDisplaySize(int *width, int *height)
1397 {
1398 #ifdef __WXMICROWIN__
1399 RECT rect;
1400 HWND hWnd = GetDesktopWindow();
1401 ::GetWindowRect(hWnd, & rect);
1402
1403 if ( width )
1404 *width = rect.right - rect.left;
1405 if ( height )
1406 *height = rect.bottom - rect.top;
1407 #else // !__WXMICROWIN__
1408 ScreenHDC dc;
1409
1410 if ( width )
1411 *width = ::GetDeviceCaps(dc, HORZRES);
1412 if ( height )
1413 *height = ::GetDeviceCaps(dc, VERTRES);
1414 #endif // __WXMICROWIN__/!__WXMICROWIN__
1415 }
1416
1417 void wxDisplaySizeMM(int *width, int *height)
1418 {
1419 #ifdef __WXMICROWIN__
1420 // MICROWIN_TODO
1421 if ( width )
1422 *width = 0;
1423 if ( height )
1424 *height = 0;
1425 #else
1426 ScreenHDC dc;
1427
1428 if ( width )
1429 *width = ::GetDeviceCaps(dc, HORZSIZE);
1430 if ( height )
1431 *height = ::GetDeviceCaps(dc, VERTSIZE);
1432 #endif
1433 }
1434
1435 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
1436 {
1437 #if defined(__WIN16__) || defined(__WXMICROWIN__)
1438 *x = 0; *y = 0;
1439 wxDisplaySize(width, height);
1440 #else
1441 // Determine the desktop dimensions minus the taskbar and any other
1442 // special decorations...
1443 RECT r;
1444
1445 SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
1446 if (x) *x = r.left;
1447 if (y) *y = r.top;
1448 if (width) *width = r.right - r.left;
1449 if (height) *height = r.bottom - r.top;
1450 #endif
1451 }
1452
1453 // ---------------------------------------------------------------------------
1454 // window information functions
1455 // ---------------------------------------------------------------------------
1456
1457 wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1458 {
1459 wxString str;
1460
1461 if ( hWnd )
1462 {
1463 int len = GetWindowTextLength((HWND)hWnd) + 1;
1464 ::GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1465 str.UngetWriteBuf();
1466 }
1467
1468 return str;
1469 }
1470
1471 wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1472 {
1473 wxString str;
1474
1475 // MICROWIN_TODO
1476 #ifndef __WXMICROWIN__
1477 if ( hWnd )
1478 {
1479 int len = 256; // some starting value
1480
1481 for ( ;; )
1482 {
1483 int count = ::GetClassName((HWND)hWnd, str.GetWriteBuf(len), len);
1484
1485 str.UngetWriteBuf();
1486 if ( count == len )
1487 {
1488 // the class name might have been truncated, retry with larger
1489 // buffer
1490 len *= 2;
1491 }
1492 else
1493 {
1494 break;
1495 }
1496 }
1497 }
1498 #endif // !__WXMICROWIN__
1499
1500 return str;
1501 }
1502
1503 WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
1504 {
1505 #ifndef __WIN32__
1506 return (WXWORD)GetWindowWord((HWND)hWnd, GWW_ID);
1507 #else // Win32
1508 return (WXWORD)GetWindowLong((HWND)hWnd, GWL_ID);
1509 #endif // Win16/32
1510 }
1511
1512 // ----------------------------------------------------------------------------
1513 // Metafile helpers
1514 // ----------------------------------------------------------------------------
1515
1516 extern void PixelToHIMETRIC(LONG *x, LONG *y)
1517 {
1518 ScreenHDC hdcRef;
1519
1520 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1521 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1522 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1523 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1524
1525 *x *= (iWidthMM * 100);
1526 *x /= iWidthPels;
1527 *y *= (iHeightMM * 100);
1528 *y /= iHeightPels;
1529 }
1530
1531 extern void HIMETRICToPixel(LONG *x, LONG *y)
1532 {
1533 ScreenHDC hdcRef;
1534
1535 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
1536 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
1537 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
1538 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
1539
1540 *x *= iWidthPels;
1541 *x /= (iWidthMM * 100);
1542 *y *= iHeightPels;
1543 *y /= (iHeightMM * 100);
1544 }
1545
1546 #endif // wxUSE_GUI
1547
1548 #ifdef __WXMICROWIN__
1549 int wxGetOsVersion(int *majorVsn, int *minorVsn)
1550 {
1551 // MICROWIN_TODO
1552 if (majorVsn) *majorVsn = 0;
1553 if (minorVsn) *minorVsn = 0;
1554 return wxUNIX;
1555 }
1556 #endif // __WXMICROWIN__
1557
1558 // ----------------------------------------------------------------------------
1559 // Win32 codepage conversion functions
1560 // ----------------------------------------------------------------------------
1561
1562 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1563
1564 // wxGetNativeFontEncoding() doesn't exist neither in wxBase nor in wxUniv
1565 #if wxUSE_GUI && !defined(__WXUNIVERSAL__)
1566
1567 #include "wx/fontmap.h"
1568
1569 // VZ: the new version of wxCharsetToCodepage() is more politically correct
1570 // and should work on other Windows versions as well but the old version is
1571 // still needed for !wxUSE_FONTMAP || !wxUSE_GUI case
1572
1573 extern long wxEncodingToCodepage(wxFontEncoding encoding)
1574 {
1575 // translate encoding into the Windows CHARSET
1576 wxNativeEncodingInfo natveEncInfo;
1577 if ( !wxGetNativeFontEncoding(encoding, &natveEncInfo) )
1578 return -1;
1579
1580 // translate CHARSET to code page
1581 CHARSETINFO csetInfo;
1582 if ( !::TranslateCharsetInfo((DWORD *)(DWORD)natveEncInfo.charset,
1583 &csetInfo,
1584 TCI_SRCCHARSET) )
1585 {
1586 wxLogLastError(_T("TranslateCharsetInfo(TCI_SRCCHARSET)"));
1587
1588 return -1;
1589 }
1590
1591 return csetInfo.ciACP;
1592 }
1593
1594 #if wxUSE_FONTMAP
1595
1596 extern long wxCharsetToCodepage(const wxChar *name)
1597 {
1598 // first get the font encoding for this charset
1599 if ( !name )
1600 return -1;
1601
1602 wxFontEncoding enc = wxFontMapper::Get()->CharsetToEncoding(name, FALSE);
1603 if ( enc == wxFONTENCODING_SYSTEM )
1604 return -1;
1605
1606 // the use the helper function
1607 return wxEncodingToCodepage(enc);
1608 }
1609
1610 #endif // wxUSE_FONTMAP
1611
1612 #endif // wxUSE_GUI
1613
1614 // include old wxCharsetToCodepage() by OK if needed
1615 #if !wxUSE_GUI || !wxUSE_FONTMAP
1616
1617 #include "wx/msw/registry.h"
1618
1619 // this should work if Internet Exploiter is installed
1620 extern long wxCharsetToCodepage(const wxChar *name)
1621 {
1622 if (!name)
1623 return GetACP();
1624
1625 long CP=-1;
1626
1627 wxString cn(name);
1628 do {
1629 wxString path(wxT("MIME\\Database\\Charset\\"));
1630 path += cn;
1631 wxRegKey key(wxRegKey::HKCR, path);
1632
1633 if (!key.Exists()) break;
1634
1635 // two cases: either there's an AliasForCharset string,
1636 // or there are Codepage and InternetEncoding dwords.
1637 // The InternetEncoding gives us the actual encoding,
1638 // the Codepage just says which Windows character set to
1639 // use when displaying the data.
1640 if (key.HasValue(wxT("InternetEncoding")) &&
1641 key.QueryValue(wxT("InternetEncoding"), &CP)) break;
1642
1643 // no encoding, see if it's an alias
1644 if (!key.HasValue(wxT("AliasForCharset")) ||
1645 !key.QueryValue(wxT("AliasForCharset"), cn)) break;
1646 } while (1);
1647
1648 return CP;
1649 }
1650
1651 #endif // !wxUSE_GUI || !wxUSE_FONTMAP
1652
1653 #endif // Win32
1654