]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utils.cpp
0c647be3b590e45b615e08e03110a8739844517a
[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/cursor.h"
35 #include "wx/intl.h"
36 #include "wx/log.h"
37 #endif //WX_PRECOMP
38
39 // In some mingws there is a missing extern "C" int the winsock header,
40 // so we put it here just to be safe. Note that this must appear _before_
41 // #include "wx/msw/private.h" which itself includes <windows.h>, as this
42 // one in turn includes <winsock.h> unless we define WIN32_LEAN_AND_MEAN.
43 //
44 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
45 extern "C" {
46 #include <winsock.h> // we use socket functions in wxGetFullHostName()
47 }
48 #endif
49
50 #include "wx/msw/private.h" // includes <windows.h>
51
52 #include "wx/timer.h"
53
54 #include <ctype.h>
55
56 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
57 #include <direct.h>
58
59 #ifndef __MWERKS__
60 #include <dos.h>
61 #endif
62 #endif //GNUWIN32
63
64 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
65 #include <sys/unistd.h>
66 #include <sys/stat.h>
67 #endif //GNUWIN32
68
69 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
70 // this (3.1 I believe) and how to test for it.
71 // If this works for Borland 4.0 as well, then no worries.
72 #include <dir.h>
73 #endif
74
75 // VZ: there is some code using NetXXX() functions to get the full user name:
76 // I don't think it's a good idea because they don't work under Win95 and
77 // seem to return the same as wxGetUserId() under NT. If you really want
78 // to use them, just #define USE_NET_API
79 #undef USE_NET_API
80
81 #ifdef USE_NET_API
82 #include <lm.h>
83 #endif // USE_NET_API
84
85 #if defined(__WIN32__) && !defined(__WXWINE__)
86 #include <io.h>
87
88 #ifndef __GNUWIN32__
89 #include <shellapi.h>
90 #endif
91 #endif
92
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #ifndef __WATCOMC__
97 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
98 #include <errno.h>
99 #endif
100 #endif
101 #include <stdarg.h>
102
103 //// BEGIN for console support: VC++ only
104 #ifdef __VISUALC__
105
106 #include "wx/msw/msvcrt.h"
107
108 #include <fcntl.h>
109
110 #include "wx/ioswrap.h"
111
112 #if wxUSE_IOSTREAMH
113 // N.B. BC++ doesn't have istream.h, ostream.h
114 # include <io.h>
115 # include <fstream.h>
116 #else
117 # include <fstream>
118 #endif
119
120 /* Need to undef new if including crtdbg.h */
121 # ifdef new
122 # undef new
123 # endif
124
125 #ifndef __WIN16__
126 # include <crtdbg.h>
127 #endif
128
129 # if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS && wxUSE_DEBUG_NEW_ALWAYS
130 # define new new(__TFILE__,__LINE__)
131 # endif
132
133 #endif
134 // __VISUALC__
135 /// END for console support
136
137 // ----------------------------------------------------------------------------
138 // constants
139 // ----------------------------------------------------------------------------
140
141 // In the WIN.INI file
142 static const wxChar WX_SECTION[] = wxT("wxWindows");
143 static const wxChar eUSERNAME[] = wxT("UserName");
144
145 // these are only used under Win16
146 #ifndef __WIN32__
147 static const wxChar eHOSTNAME[] = wxT("HostName");
148 static const wxChar eUSERID[] = wxT("UserId");
149 #endif // !Win32
150
151 // ============================================================================
152 // implementation
153 // ============================================================================
154
155 // ----------------------------------------------------------------------------
156 // get host name and related
157 // ----------------------------------------------------------------------------
158
159 // Get hostname only (without domain name)
160 bool wxGetHostName(wxChar *buf, int maxSize)
161 {
162 #if defined(__WIN32__) && !defined(__TWIN32__)
163 DWORD nSize = maxSize;
164 if ( !::GetComputerName(buf, &nSize) )
165 {
166 wxLogLastError(wxT("GetComputerName"));
167
168 return FALSE;
169 }
170
171 return TRUE;
172 #else
173 wxChar *sysname;
174 const wxChar *default_host = wxT("noname");
175
176 if ((sysname = wxGetenv(wxT("SYSTEM_NAME"))) == NULL) {
177 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
178 } else
179 wxStrncpy(buf, sysname, maxSize - 1);
180 buf[maxSize] = wxT('\0');
181 return *buf ? TRUE : FALSE;
182 #endif
183 }
184
185 // get full hostname (with domain name if possible)
186 bool wxGetFullHostName(wxChar *buf, int maxSize)
187 {
188 #if defined(__WIN32__) && !defined(__TWIN32__) && ! (defined(__GNUWIN32__) && !defined(__MINGW32__))
189 // TODO should use GetComputerNameEx() when available
190 WSADATA wsa;
191 if ( WSAStartup(MAKEWORD(1, 1), &wsa) == 0 )
192 {
193 wxString host;
194 char bufA[256];
195 if ( gethostname(bufA, WXSIZEOF(bufA)) == 0 )
196 {
197 // gethostname() won't usually include the DNS domain name, for
198 // this we need to work a bit more
199 if ( !strchr(bufA, '.') )
200 {
201 struct hostent *pHostEnt = gethostbyname(bufA);
202
203 if ( pHostEnt )
204 {
205 // Windows will use DNS internally now
206 pHostEnt = gethostbyaddr(pHostEnt->h_addr, 4, PF_INET);
207 }
208
209 if ( pHostEnt )
210 {
211 host = pHostEnt->h_name;
212 }
213 }
214 }
215
216 WSACleanup();
217
218 if ( !!host )
219 {
220 wxStrncpy(buf, host, maxSize);
221
222 return TRUE;
223 }
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__)
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 #else // Windows
386 #ifdef __WIN32__
387 const wxChar *szHome = wxGetenv(wxT("HOMEDRIVE"));
388 if ( szHome != NULL )
389 strDir << szHome;
390 szHome = wxGetenv(wxT("HOMEPATH"));
391 if ( szHome != NULL ) {
392 strDir << szHome;
393
394 // the idea is that under NT these variables have default values
395 // of "%systemdrive%:" and "\\". As we don't want to create our
396 // config files in the root directory of the system drive, we will
397 // create it in our program's dir. However, if the user took care
398 // to set HOMEPATH to something other than "\\", we suppose that he
399 // knows what he is doing and use the supplied value.
400 if ( wxStrcmp(szHome, wxT("\\")) != 0 )
401 return strDir.c_str();
402 }
403
404 #else // Win16
405 // Win16 has no idea about home, so use the working directory instead
406 #endif // WIN16/32
407
408 // 260 was taken from windef.h
409 #ifndef MAX_PATH
410 #define MAX_PATH 260
411 #endif
412
413 wxString strPath;
414 ::GetModuleFileName(::GetModuleHandle(NULL),
415 strPath.GetWriteBuf(MAX_PATH), MAX_PATH);
416 strPath.UngetWriteBuf();
417
418 // extract the dir name
419 wxSplitPath(strPath, &strDir, NULL, NULL);
420
421 #endif // UNIX/Win
422
423 return strDir.c_str();
424 }
425
426 wxChar *wxGetUserHome(const wxString& user)
427 {
428 // VZ: the old code here never worked for user != "" anyhow! Moreover, it
429 // returned sometimes a malloc()'d pointer, sometimes a pointer to a
430 // static buffer and sometimes I don't even know what.
431 static wxString s_home;
432
433 return (wxChar *)wxGetHomeDir(&s_home);
434 }
435
436 bool wxDirExists(const wxString& dir)
437 {
438 #if defined(__WIN32__)
439 DWORD attribs = GetFileAttributes(dir);
440 return ((attribs != -1) && (attribs & FILE_ATTRIBUTE_DIRECTORY));
441 #else // Win16
442 #ifdef __BORLANDC__
443 struct ffblk fileInfo;
444 #else
445 struct find_t fileInfo;
446 #endif
447 // In Borland findfirst has a different argument
448 // ordering from _dos_findfirst. But _dos_findfirst
449 // _should_ be ok in both MS and Borland... why not?
450 #ifdef __BORLANDC__
451 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
452 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
453 #else
454 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
455 ((fileInfo.attrib & _A_SUBDIR) != 0);
456 #endif
457 #endif // Win32/16
458 }
459
460 bool wxSetEnv(const wxString& var, const wxChar *value)
461 {
462 // some compilers have putenv() or _putenv() or _wputenv() but it's better
463 // to always use Win32 function directly instead of dealing with them
464 #if defined(__WIN32__)
465 if ( !::SetEnvironmentVariable(var, value) )
466 {
467 wxLogLastError(_T("SetEnvironmentVariable"));
468
469 return FALSE;
470 }
471
472 return TRUE;
473 #else // no way to set env vars
474 return FALSE;
475 #endif
476 }
477
478 // ----------------------------------------------------------------------------
479 // process management
480 // ----------------------------------------------------------------------------
481
482 int wxKill(long pid, int sig)
483 {
484 // TODO use SendMessage(WM_QUIT) and TerminateProcess() if needed
485
486 return 0;
487 }
488
489 // Execute a program in an Interactive Shell
490 bool wxShell(const wxString& command)
491 {
492 wxChar *shell = wxGetenv(wxT("COMSPEC"));
493 if ( !shell )
494 shell = wxT("\\COMMAND.COM");
495
496 wxString cmd;
497 if ( !command )
498 {
499 // just the shell
500 cmd = shell;
501 }
502 else
503 {
504 // pass the command to execute to the command processor
505 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
506 }
507
508 return wxExecute(cmd, TRUE /* sync */) != 0;
509 }
510
511 // ----------------------------------------------------------------------------
512 // misc
513 // ----------------------------------------------------------------------------
514
515 // Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
516 long wxGetFreeMemory()
517 {
518 #if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
519 MEMORYSTATUS memStatus;
520 memStatus.dwLength = sizeof(MEMORYSTATUS);
521 GlobalMemoryStatus(&memStatus);
522 return memStatus.dwAvailPhys;
523 #else
524 return (long)GetFreeSpace(0);
525 #endif
526 }
527
528 // Emit a beeeeeep
529 void wxBell()
530 {
531 ::MessageBeep((UINT)-1); // default sound
532 }
533
534 wxString wxGetOsDescription()
535 {
536 #ifdef __WIN32__
537 wxString str;
538
539 OSVERSIONINFO info;
540 wxZeroMemory(info);
541
542 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
543 if ( ::GetVersionEx(&info) )
544 {
545 switch ( info.dwPlatformId )
546 {
547 case VER_PLATFORM_WIN32s:
548 str = _("Win32s on Windows 3.1");
549 break;
550
551 case VER_PLATFORM_WIN32_WINDOWS:
552 str.Printf(_("Windows 9%c"),
553 info.dwMinorVersion == 0 ? _T('5') : _T('9'));
554 if ( !wxIsEmpty(info.szCSDVersion) )
555 {
556 str << _T(" (") << info.szCSDVersion << _T(')');
557 }
558 break;
559
560 case VER_PLATFORM_WIN32_NT:
561 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
562 info.dwMajorVersion,
563 info.dwMinorVersion,
564 info.dwBuildNumber);
565 if ( !wxIsEmpty(info.szCSDVersion) )
566 {
567 str << _T(", ") << info.szCSDVersion;
568 }
569 str << _T(')');
570 break;
571 }
572 }
573 else
574 {
575 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
576 }
577
578 return str;
579 #else // Win16
580 return _("Windows 3.1");
581 #endif // Win32/16
582 }
583
584 int wxGetOsVersion(int *majorVsn, int *minorVsn)
585 {
586 #if defined(__WIN32__) && !defined(__SC__)
587 OSVERSIONINFO info;
588 wxZeroMemory(info);
589
590 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
591 if ( ::GetVersionEx(&info) )
592 {
593 if (majorVsn)
594 *majorVsn = info.dwMajorVersion;
595 if (minorVsn)
596 *minorVsn = info.dwMinorVersion;
597
598 switch ( info.dwPlatformId )
599 {
600 case VER_PLATFORM_WIN32s:
601 return wxWIN32S;
602
603 case VER_PLATFORM_WIN32_WINDOWS:
604 return wxWIN95;
605
606 case VER_PLATFORM_WIN32_NT:
607 return wxWINDOWS_NT;
608 }
609 }
610
611 return wxWINDOWS; // error if we get here, return generic value
612 #else // Win16
613 int retValue = wxWINDOWS;
614 #ifdef __WINDOWS_386__
615 retValue = wxWIN386;
616 #else
617 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
618 extern HANDLE g_hPenWin;
619 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
620 #endif
621 #endif
622
623 if (majorVsn)
624 *majorVsn = 3;
625 if (minorVsn)
626 *minorVsn = 1;
627
628 return retValue;
629 #endif
630 }
631
632 // ----------------------------------------------------------------------------
633 // sleep functions
634 // ----------------------------------------------------------------------------
635
636 #if wxUSE_GUI
637
638 // Sleep for nSecs seconds. Attempt a Windows implementation using timers.
639 static bool gs_inTimer = FALSE;
640
641 class wxSleepTimer: public wxTimer
642 {
643 public:
644 virtual void Notify()
645 {
646 gs_inTimer = FALSE;
647 Stop();
648 }
649 };
650
651 static wxTimer *wxTheSleepTimer = NULL;
652
653 void wxUsleep(unsigned long milliseconds)
654 {
655 #ifdef __WIN32__
656 ::Sleep(milliseconds);
657 #else
658 if (gs_inTimer)
659 return;
660
661 wxTheSleepTimer = new wxSleepTimer;
662 gs_inTimer = TRUE;
663 wxTheSleepTimer->Start(milliseconds);
664 while (gs_inTimer)
665 {
666 if (wxTheApp->Pending())
667 wxTheApp->Dispatch();
668 }
669 delete wxTheSleepTimer;
670 wxTheSleepTimer = NULL;
671 #endif
672 }
673
674 void wxSleep(int nSecs)
675 {
676 if (gs_inTimer)
677 return;
678
679 wxTheSleepTimer = new wxSleepTimer;
680 gs_inTimer = TRUE;
681 wxTheSleepTimer->Start(nSecs*1000);
682 while (gs_inTimer)
683 {
684 if (wxTheApp->Pending())
685 wxTheApp->Dispatch();
686 }
687 delete wxTheSleepTimer;
688 wxTheSleepTimer = NULL;
689 }
690
691 // Consume all events until no more left
692 void wxFlushEvents()
693 {
694 // wxYield();
695 }
696
697 #elif defined(__WIN32__) // wxUSE_GUI
698
699 void wxUsleep(unsigned long milliseconds)
700 {
701 ::Sleep(milliseconds);
702 }
703
704 void wxSleep(int nSecs)
705 {
706 wxUsleep(1000*nSecs);
707 }
708
709 #endif // wxUSE_GUI/!wxUSE_GUI
710
711 // ----------------------------------------------------------------------------
712 // deprecated (in favour of wxLog) log functions
713 // ----------------------------------------------------------------------------
714
715 #if wxUSE_GUI
716
717 // Output a debug mess., in a system dependent fashion.
718 void wxDebugMsg(const wxChar *fmt ...)
719 {
720 va_list ap;
721 static wxChar buffer[512];
722
723 if (!wxTheApp->GetWantDebugOutput())
724 return ;
725
726 va_start(ap, fmt);
727
728 wvsprintf(buffer,fmt,ap) ;
729 OutputDebugString((LPCTSTR)buffer) ;
730
731 va_end(ap);
732 }
733
734 // Non-fatal error: pop up message box and (possibly) continue
735 void wxError(const wxString& msg, const wxString& title)
736 {
737 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
738 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
739 MB_ICONSTOP | MB_YESNO) == IDNO)
740 wxExit();
741 }
742
743 // Fatal error: pop up message box and abort
744 void wxFatalError(const wxString& msg, const wxString& title)
745 {
746 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
747 FatalAppExit(0, (LPCTSTR)wxBuffer);
748 }
749
750 // ----------------------------------------------------------------------------
751 // functions to work with .INI files
752 // ----------------------------------------------------------------------------
753
754 // Reading and writing resources (eg WIN.INI, .Xdefaults)
755 #if wxUSE_RESOURCES
756 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
757 {
758 if (file != wxT(""))
759 // Don't know what the correct cast should be, but it doesn't
760 // compile in BC++/16-bit without this cast.
761 #if !defined(__WIN32__)
762 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
763 #else
764 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
765 #endif
766 else
767 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
768 }
769
770 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
771 {
772 wxString buf;
773 buf.Printf(wxT("%.4f"), value);
774
775 return wxWriteResource(section, entry, buf, file);
776 }
777
778 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
779 {
780 wxString buf;
781 buf.Printf(wxT("%ld"), value);
782
783 return wxWriteResource(section, entry, buf, file);
784 }
785
786 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
787 {
788 wxString buf;
789 buf.Printf(wxT("%d"), value);
790
791 return wxWriteResource(section, entry, buf, file);
792 }
793
794 bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
795 {
796 static const wxChar defunkt[] = wxT("$$default");
797 if (file != wxT(""))
798 {
799 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
800 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
801 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
802 return FALSE;
803 }
804 else
805 {
806 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
807 (LPTSTR)wxBuffer, 1000);
808 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
809 return FALSE;
810 }
811 if (*value) delete[] (*value);
812 *value = copystring(wxBuffer);
813 return TRUE;
814 }
815
816 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
817 {
818 wxChar *s = NULL;
819 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
820 if (succ)
821 {
822 *value = (float)wxStrtod(s, NULL);
823 delete[] s;
824 return TRUE;
825 }
826 else return FALSE;
827 }
828
829 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
830 {
831 wxChar *s = NULL;
832 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
833 if (succ)
834 {
835 *value = wxStrtol(s, NULL, 10);
836 delete[] s;
837 return TRUE;
838 }
839 else return FALSE;
840 }
841
842 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
843 {
844 wxChar *s = NULL;
845 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
846 if (succ)
847 {
848 *value = (int)wxStrtol(s, NULL, 10);
849 delete[] s;
850 return TRUE;
851 }
852 else return FALSE;
853 }
854 #endif // wxUSE_RESOURCES
855
856 // ---------------------------------------------------------------------------
857 // helper functions for showing a "busy" cursor
858 // ---------------------------------------------------------------------------
859
860 static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
861 static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
862 static int gs_wxBusyCursorCount = 0;
863
864 extern HCURSOR wxGetCurrentBusyCursor()
865 {
866 return gs_wxBusyCursor;
867 }
868
869 // Set the cursor to the busy cursor for all windows
870 void wxBeginBusyCursor(wxCursor *cursor)
871 {
872 if ( gs_wxBusyCursorCount++ == 0 )
873 {
874 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
875 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
876 }
877 //else: nothing to do, already set
878 }
879
880 // Restore cursor to normal
881 void wxEndBusyCursor()
882 {
883 wxCHECK_RET( gs_wxBusyCursorCount > 0,
884 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
885
886 if ( --gs_wxBusyCursorCount == 0 )
887 {
888 ::SetCursor(gs_wxBusyCursorOld);
889
890 gs_wxBusyCursorOld = 0;
891 }
892 }
893
894 // TRUE if we're between the above two calls
895 bool wxIsBusy()
896 {
897 return (gs_wxBusyCursorCount > 0);
898 }
899
900 // Check whether this window wants to process messages, e.g. Stop button
901 // in long calculations.
902 bool wxCheckForInterrupt(wxWindow *wnd)
903 {
904 wxCHECK( wnd, FALSE );
905
906 MSG msg;
907 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
908 {
909 ::TranslateMessage(&msg);
910 ::DispatchMessage(&msg);
911 }
912
913 return TRUE;
914 }
915
916 // MSW only: get user-defined resource from the .res file.
917 // Returns NULL or newly-allocated memory, so use delete[] to clean up.
918
919 wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
920 {
921 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
922 if ( hResource == 0 )
923 return NULL;
924
925 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
926 if ( hData == 0 )
927 return NULL;
928
929 wxChar *theText = (wxChar *)::LockResource(hData);
930 if ( !theText )
931 return NULL;
932
933 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
934 // so we need to find the length of the resource.
935 int len = ::SizeofResource(wxGetInstance(), hResource);
936 wxChar *s = new wxChar[len+1];
937 wxStrncpy(s,theText,len);
938 s[len]=0;
939
940 // wxChar *s = copystring(theText);
941
942 // Obsolete in WIN32
943 #ifndef __WIN32__
944 UnlockResource(hData);
945 #endif
946
947 // No need??
948 // GlobalFree(hData);
949
950 return s;
951 }
952
953 // ----------------------------------------------------------------------------
954 // get display info
955 // ----------------------------------------------------------------------------
956
957 // See also the wxGetMousePosition in window.cpp
958 // Deprecated: use wxPoint wxGetMousePosition() instead
959 void wxGetMousePosition( int* x, int* y )
960 {
961 POINT pt;
962 GetCursorPos( & pt );
963 if ( x ) *x = pt.x;
964 if ( y ) *y = pt.y;
965 };
966
967 // Return TRUE if we have a colour display
968 bool wxColourDisplay()
969 {
970 ScreenHDC dc;
971 int noCols = GetDeviceCaps(dc, NUMCOLORS);
972
973 return (noCols == -1) || (noCols > 2);
974 }
975
976 // Returns depth of screen
977 int wxDisplayDepth()
978 {
979 ScreenHDC dc;
980 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
981 }
982
983 // Get size of display
984 void wxDisplaySize(int *width, int *height)
985 {
986 ScreenHDC dc;
987
988 if ( width ) *width = GetDeviceCaps(dc, HORZRES);
989 if ( height ) *height = GetDeviceCaps(dc, VERTRES);
990 }
991
992 void wxDisplaySizeMM(int *width, int *height)
993 {
994 ScreenHDC dc;
995
996 if ( width ) *width = GetDeviceCaps(dc, HORZSIZE);
997 if ( height ) *height = GetDeviceCaps(dc, VERTSIZE);
998 }
999
1000
1001 // ---------------------------------------------------------------------------
1002 // window information functions
1003 // ---------------------------------------------------------------------------
1004
1005 wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1006 {
1007 wxString str;
1008 int len = GetWindowTextLength((HWND)hWnd) + 1;
1009 GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1010 str.UngetWriteBuf();
1011
1012 return str;
1013 }
1014
1015 wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1016 {
1017 wxString str;
1018
1019 int len = 256; // some starting value
1020
1021 for ( ;; )
1022 {
1023 // as we've #undefined GetClassName we must now manually choose the
1024 // right function to call
1025 int count =
1026
1027 #ifndef __WIN32__
1028 GetClassName
1029 #else // Win32
1030 #ifdef UNICODE
1031 GetClassNameW
1032 #else // !Unicode
1033 #ifdef __TWIN32__
1034 GetClassName
1035 #else // !Twin32
1036 GetClassNameA
1037 #endif // Twin32/!Twin32
1038 #endif // Unicode/ANSI
1039 #endif // Win16/32
1040 ((HWND)hWnd, str.GetWriteBuf(len), len);
1041
1042 str.UngetWriteBuf();
1043 if ( count == len )
1044 {
1045 // the class name might have been truncated, retry with larger
1046 // buffer
1047 len *= 2;
1048 }
1049 else
1050 {
1051 break;
1052 }
1053 }
1054
1055 return str;
1056 }
1057
1058 WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
1059 {
1060 #ifndef __WIN32__
1061 return GetWindowWord((HWND)hWnd, GWW_ID);
1062 #else // Win32
1063 return GetWindowLong((HWND)hWnd, GWL_ID);
1064 #endif // Win16/32
1065 }
1066
1067 #endif // wxUSE_GUI
1068
1069 #if 0
1070 //------------------------------------------------------------------------
1071 // wild character routines
1072 //------------------------------------------------------------------------
1073
1074 bool wxIsWild( const wxString& pattern )
1075 {
1076 wxString tmp = pattern;
1077 char *pat = WXSTRINGCAST(tmp);
1078 while (*pat) {
1079 switch (*pat++) {
1080 case '?': case '*': case '[': case '{':
1081 return TRUE;
1082 case '\\':
1083 if (!*pat++)
1084 return FALSE;
1085 }
1086 }
1087 return FALSE;
1088 };
1089
1090
1091 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1092 {
1093 wxString tmp1 = pat;
1094 char *pattern = WXSTRINGCAST(tmp1);
1095 wxString tmp2 = text;
1096 char *str = WXSTRINGCAST(tmp2);
1097 char c;
1098 char *cp;
1099 bool done = FALSE, ret_code, ok;
1100 // Below is for vi fans
1101 const char OB = '{', CB = '}';
1102
1103 // dot_special means '.' only matches '.'
1104 if (dot_special && *str == '.' && *pattern != *str)
1105 return FALSE;
1106
1107 while ((*pattern != '\0') && (!done)
1108 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
1109 switch (*pattern) {
1110 case '\\':
1111 pattern++;
1112 if (*pattern != '\0')
1113 pattern++;
1114 break;
1115 case '*':
1116 pattern++;
1117 ret_code = FALSE;
1118 while ((*str!='\0')
1119 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1120 /*loop*/;
1121 if (ret_code) {
1122 while (*str != '\0')
1123 str++;
1124 while (*pattern != '\0')
1125 pattern++;
1126 }
1127 break;
1128 case '[':
1129 pattern++;
1130 repeat:
1131 if ((*pattern == '\0') || (*pattern == ']')) {
1132 done = TRUE;
1133 break;
1134 }
1135 if (*pattern == '\\') {
1136 pattern++;
1137 if (*pattern == '\0') {
1138 done = TRUE;
1139 break;
1140 }
1141 }
1142 if (*(pattern + 1) == '-') {
1143 c = *pattern;
1144 pattern += 2;
1145 if (*pattern == ']') {
1146 done = TRUE;
1147 break;
1148 }
1149 if (*pattern == '\\') {
1150 pattern++;
1151 if (*pattern == '\0') {
1152 done = TRUE;
1153 break;
1154 }
1155 }
1156 if ((*str < c) || (*str > *pattern)) {
1157 pattern++;
1158 goto repeat;
1159 }
1160 } else if (*pattern != *str) {
1161 pattern++;
1162 goto repeat;
1163 }
1164 pattern++;
1165 while ((*pattern != ']') && (*pattern != '\0')) {
1166 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1167 pattern++;
1168 pattern++;
1169 }
1170 if (*pattern != '\0') {
1171 pattern++, str++;
1172 }
1173 break;
1174 case '?':
1175 pattern++;
1176 str++;
1177 break;
1178 case OB:
1179 pattern++;
1180 while ((*pattern != CB) && (*pattern != '\0')) {
1181 cp = str;
1182 ok = TRUE;
1183 while (ok && (*cp != '\0') && (*pattern != '\0')
1184 && (*pattern != ',') && (*pattern != CB)) {
1185 if (*pattern == '\\')
1186 pattern++;
1187 ok = (*pattern++ == *cp++);
1188 }
1189 if (*pattern == '\0') {
1190 ok = FALSE;
1191 done = TRUE;
1192 break;
1193 } else if (ok) {
1194 str = cp;
1195 while ((*pattern != CB) && (*pattern != '\0')) {
1196 if (*++pattern == '\\') {
1197 if (*++pattern == CB)
1198 pattern++;
1199 }
1200 }
1201 } else {
1202 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1203 if (*++pattern == '\\') {
1204 if (*++pattern == CB || *pattern == ',')
1205 pattern++;
1206 }
1207 }
1208 }
1209 if (*pattern != '\0')
1210 pattern++;
1211 }
1212 break;
1213 default:
1214 if (*str == *pattern) {
1215 str++, pattern++;
1216 } else {
1217 done = TRUE;
1218 }
1219 }
1220 }
1221 while (*pattern == '*')
1222 pattern++;
1223 return ((*str == '\0') && (*pattern == '\0'));
1224 };
1225
1226 #endif // 0
1227
1228 #if 0
1229
1230 // maximum mumber of lines the output console should have
1231 static const WORD MAX_CONSOLE_LINES = 500;
1232
1233 BOOL WINAPI MyConsoleHandler( DWORD dwCtrlType ) { // control signal type
1234 FreeConsole();
1235 return TRUE;
1236 }
1237
1238 void wxRedirectIOToConsole()
1239 {
1240 int hConHandle;
1241 long lStdHandle;
1242 CONSOLE_SCREEN_BUFFER_INFO coninfo;
1243 FILE *fp;
1244
1245 // allocate a console for this app
1246 AllocConsole();
1247
1248 // set the screen buffer to be big enough to let us scroll text
1249 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
1250 &coninfo);
1251 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
1252 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
1253 coninfo.dwSize);
1254
1255 // redirect unbuffered STDOUT to the console
1256 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
1257 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1258 if(hConHandle <= 0) return;
1259 fp = _fdopen( hConHandle, "w" );
1260 *stdout = *fp;
1261 setvbuf( stdout, NULL, _IONBF, 0 );
1262
1263 // redirect unbuffered STDIN to the console
1264 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
1265 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1266 if(hConHandle <= 0) return;
1267 fp = _fdopen( hConHandle, "r" );
1268 *stdin = *fp;
1269 setvbuf( stdin, NULL, _IONBF, 0 );
1270
1271 // redirect unbuffered STDERR to the console
1272 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
1273 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1274 if(hConHandle <= 0) return;
1275 fp = _fdopen( hConHandle, "w" );
1276 *stderr = *fp;
1277 setvbuf( stderr, NULL, _IONBF, 0 );
1278
1279 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1280 // point to console as well
1281 ios::sync_with_stdio();
1282
1283 SetConsoleCtrlHandler(MyConsoleHandler, TRUE);
1284 }
1285 #else
1286 // Not supported
1287 void wxRedirectIOToConsole()
1288 {
1289 }
1290 #endif
1291
1292