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