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