]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/msw/utils.cpp
Added wxYieldIfNeeded
[wxWidgets.git] / src / msw / utils.cpp
... / ...
CommitLineData
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__))
45extern "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
142static const wxChar WX_SECTION[] = wxT("wxWindows");
143static const wxChar eUSERNAME[] = wxT("UserName");
144
145// these are only used under Win16
146#ifndef __WIN32__
147static const wxChar eHOSTNAME[] = wxT("HostName");
148static 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)
160bool 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)
186bool 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
231bool 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
269bool 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
345error:
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
368const 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
426wxChar *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
436bool wxDirExists(const wxString& dir)
437{
438#if defined(__WIN32__)
439 WIN32_FIND_DATA fileInfo;
440#else // Win16
441 #ifdef __BORLANDC__
442 struct ffblk fileInfo;
443 #else
444 struct find_t fileInfo;
445 #endif
446#endif // Win32/16
447
448#if defined(__WIN32__)
449 HANDLE h = ::FindFirstFile(dir, &fileInfo);
450
451 if ( h == INVALID_HANDLE_VALUE )
452 {
453 wxLogLastError(wxT("FindFirstFile"));
454
455 return FALSE;
456 }
457
458 ::FindClose(h);
459
460 return (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
461#else // Win16
462 // In Borland findfirst has a different argument
463 // ordering from _dos_findfirst. But _dos_findfirst
464 // _should_ be ok in both MS and Borland... why not?
465 #ifdef __BORLANDC__
466 return (findfirst(dir, &fileInfo, _A_SUBDIR) == 0 &&
467 (fileInfo.ff_attrib & _A_SUBDIR) != 0);
468 #else
469 return (_dos_findfirst(dir, _A_SUBDIR, &fileInfo) == 0) &&
470 ((fileInfo.attrib & _A_SUBDIR) != 0);
471 #endif
472#endif // Win32/16
473}
474
475// ----------------------------------------------------------------------------
476// env vars
477// ----------------------------------------------------------------------------
478
479bool wxGetEnv(const wxString& var, wxString *value)
480{
481 // first get the size of the buffer
482 DWORD dwRet = ::GetEnvironmentVariable(var, NULL, 0);
483 if ( !dwRet )
484 {
485 // this means that there is no such variable
486 return FALSE;
487 }
488
489 if ( value )
490 {
491 (void)::GetEnvironmentVariable(var, value->GetWriteBuf(dwRet), dwRet);
492 value->UngetWriteBuf();
493 }
494
495 return TRUE;
496}
497
498bool wxSetEnv(const wxString& var, const wxChar *value)
499{
500 // some compilers have putenv() or _putenv() or _wputenv() but it's better
501 // to always use Win32 function directly instead of dealing with them
502#if defined(__WIN32__)
503 if ( !::SetEnvironmentVariable(var, value) )
504 {
505 wxLogLastError(_T("SetEnvironmentVariable"));
506
507 return FALSE;
508 }
509
510 return TRUE;
511#else // no way to set env vars
512 return FALSE;
513#endif
514}
515
516// ----------------------------------------------------------------------------
517// process management
518// ----------------------------------------------------------------------------
519
520int wxKill(long pid, int sig)
521{
522 // TODO use SendMessage(WM_QUIT) and TerminateProcess() if needed
523
524 return 0;
525}
526
527// Execute a program in an Interactive Shell
528bool wxShell(const wxString& command)
529{
530 wxChar *shell = wxGetenv(wxT("COMSPEC"));
531 if ( !shell )
532 shell = wxT("\\COMMAND.COM");
533
534 wxString cmd;
535 if ( !command )
536 {
537 // just the shell
538 cmd = shell;
539 }
540 else
541 {
542 // pass the command to execute to the command processor
543 cmd.Printf(wxT("%s /c %s"), shell, command.c_str());
544 }
545
546 return wxExecute(cmd, TRUE /* sync */) != 0;
547}
548
549// ----------------------------------------------------------------------------
550// misc
551// ----------------------------------------------------------------------------
552
553// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
554long wxGetFreeMemory()
555{
556#if defined(__WIN32__) && !defined(__BORLANDC__) && !defined(__TWIN32__)
557 MEMORYSTATUS memStatus;
558 memStatus.dwLength = sizeof(MEMORYSTATUS);
559 GlobalMemoryStatus(&memStatus);
560 return memStatus.dwAvailPhys;
561#else
562 return (long)GetFreeSpace(0);
563#endif
564}
565
566// Emit a beeeeeep
567void wxBell()
568{
569 ::MessageBeep((UINT)-1); // default sound
570}
571
572wxString wxGetOsDescription()
573{
574#ifdef __WIN32__
575 wxString str;
576
577 OSVERSIONINFO info;
578 wxZeroMemory(info);
579
580 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
581 if ( ::GetVersionEx(&info) )
582 {
583 switch ( info.dwPlatformId )
584 {
585 case VER_PLATFORM_WIN32s:
586 str = _("Win32s on Windows 3.1");
587 break;
588
589 case VER_PLATFORM_WIN32_WINDOWS:
590 str.Printf(_("Windows 9%c"),
591 info.dwMinorVersion == 0 ? _T('5') : _T('8'));
592 if ( !wxIsEmpty(info.szCSDVersion) )
593 {
594 str << _T(" (") << info.szCSDVersion << _T(')');
595 }
596 break;
597
598 case VER_PLATFORM_WIN32_NT:
599 str.Printf(_T("Windows NT %lu.%lu (build %lu"),
600 info.dwMajorVersion,
601 info.dwMinorVersion,
602 info.dwBuildNumber);
603 if ( !wxIsEmpty(info.szCSDVersion) )
604 {
605 str << _T(", ") << info.szCSDVersion;
606 }
607 str << _T(')');
608 break;
609 }
610 }
611 else
612 {
613 wxFAIL_MSG( _T("GetVersionEx() failed") ); // should never happen
614 }
615
616 return str;
617#else // Win16
618 return _("Windows 3.1");
619#endif // Win32/16
620}
621
622int wxGetOsVersion(int *majorVsn, int *minorVsn)
623{
624#if defined(__WIN32__) && !defined(__SC__)
625 OSVERSIONINFO info;
626 wxZeroMemory(info);
627
628 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
629 if ( ::GetVersionEx(&info) )
630 {
631 if (majorVsn)
632 *majorVsn = info.dwMajorVersion;
633 if (minorVsn)
634 *minorVsn = info.dwMinorVersion;
635
636 switch ( info.dwPlatformId )
637 {
638 case VER_PLATFORM_WIN32s:
639 return wxWIN32S;
640
641 case VER_PLATFORM_WIN32_WINDOWS:
642 return wxWIN95;
643
644 case VER_PLATFORM_WIN32_NT:
645 return wxWINDOWS_NT;
646 }
647 }
648
649 return wxWINDOWS; // error if we get here, return generic value
650#else // Win16
651 int retValue = wxWINDOWS;
652 #ifdef __WINDOWS_386__
653 retValue = wxWIN386;
654 #else
655 #if !defined(__WATCOMC__) && !defined(GNUWIN32) && wxUSE_PENWINDOWS
656 extern HANDLE g_hPenWin;
657 retValue = g_hPenWin ? wxPENWINDOWS : wxWINDOWS;
658 #endif
659 #endif
660
661 if (majorVsn)
662 *majorVsn = 3;
663 if (minorVsn)
664 *minorVsn = 1;
665
666 return retValue;
667#endif
668}
669
670// ----------------------------------------------------------------------------
671// sleep functions
672// ----------------------------------------------------------------------------
673
674#if wxUSE_GUI
675
676// Sleep for nSecs seconds. Attempt a Windows implementation using timers.
677static bool gs_inTimer = FALSE;
678
679class wxSleepTimer: public wxTimer
680{
681public:
682 virtual void Notify()
683 {
684 gs_inTimer = FALSE;
685 Stop();
686 }
687};
688
689static wxTimer *wxTheSleepTimer = NULL;
690
691void wxUsleep(unsigned long milliseconds)
692{
693#ifdef __WIN32__
694 ::Sleep(milliseconds);
695#else
696 if (gs_inTimer)
697 return;
698
699 wxTheSleepTimer = new wxSleepTimer;
700 gs_inTimer = TRUE;
701 wxTheSleepTimer->Start(milliseconds);
702 while (gs_inTimer)
703 {
704 if (wxTheApp->Pending())
705 wxTheApp->Dispatch();
706 }
707 delete wxTheSleepTimer;
708 wxTheSleepTimer = NULL;
709#endif
710}
711
712void wxSleep(int nSecs)
713{
714 if (gs_inTimer)
715 return;
716
717 wxTheSleepTimer = new wxSleepTimer;
718 gs_inTimer = TRUE;
719 wxTheSleepTimer->Start(nSecs*1000);
720 while (gs_inTimer)
721 {
722 if (wxTheApp->Pending())
723 wxTheApp->Dispatch();
724 }
725 delete wxTheSleepTimer;
726 wxTheSleepTimer = NULL;
727}
728
729// Consume all events until no more left
730void wxFlushEvents()
731{
732// wxYield();
733}
734
735#elif defined(__WIN32__) // wxUSE_GUI
736
737void wxUsleep(unsigned long milliseconds)
738{
739 ::Sleep(milliseconds);
740}
741
742void wxSleep(int nSecs)
743{
744 wxUsleep(1000*nSecs);
745}
746
747#endif // wxUSE_GUI/!wxUSE_GUI
748
749// ----------------------------------------------------------------------------
750// deprecated (in favour of wxLog) log functions
751// ----------------------------------------------------------------------------
752
753#if wxUSE_GUI
754
755// Output a debug mess., in a system dependent fashion.
756void wxDebugMsg(const wxChar *fmt ...)
757{
758 va_list ap;
759 static wxChar buffer[512];
760
761 if (!wxTheApp->GetWantDebugOutput())
762 return ;
763
764 va_start(ap, fmt);
765
766 wvsprintf(buffer,fmt,ap) ;
767 OutputDebugString((LPCTSTR)buffer) ;
768
769 va_end(ap);
770}
771
772// Non-fatal error: pop up message box and (possibly) continue
773void wxError(const wxString& msg, const wxString& title)
774{
775 wxSprintf(wxBuffer, wxT("%s\nContinue?"), WXSTRINGCAST msg);
776 if (MessageBox(NULL, (LPCTSTR)wxBuffer, (LPCTSTR)WXSTRINGCAST title,
777 MB_ICONSTOP | MB_YESNO) == IDNO)
778 wxExit();
779}
780
781// Fatal error: pop up message box and abort
782void wxFatalError(const wxString& msg, const wxString& title)
783{
784 wxSprintf(wxBuffer, wxT("%s: %s"), WXSTRINGCAST title, WXSTRINGCAST msg);
785 FatalAppExit(0, (LPCTSTR)wxBuffer);
786}
787
788// ----------------------------------------------------------------------------
789// functions to work with .INI files
790// ----------------------------------------------------------------------------
791
792// Reading and writing resources (eg WIN.INI, .Xdefaults)
793#if wxUSE_RESOURCES
794bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
795{
796 if (file != wxT(""))
797// Don't know what the correct cast should be, but it doesn't
798// compile in BC++/16-bit without this cast.
799#if !defined(__WIN32__)
800 return (WritePrivateProfileString((const char*) section, (const char*) entry, (const char*) value, (const char*) file) != 0);
801#else
802 return (WritePrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)value, (LPCTSTR)WXSTRINGCAST file) != 0);
803#endif
804 else
805 return (WriteProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)WXSTRINGCAST value) != 0);
806}
807
808bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
809{
810 wxString buf;
811 buf.Printf(wxT("%.4f"), value);
812
813 return wxWriteResource(section, entry, buf, file);
814}
815
816bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
817{
818 wxString buf;
819 buf.Printf(wxT("%ld"), value);
820
821 return wxWriteResource(section, entry, buf, file);
822}
823
824bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
825{
826 wxString buf;
827 buf.Printf(wxT("%d"), value);
828
829 return wxWriteResource(section, entry, buf, file);
830}
831
832bool wxGetResource(const wxString& section, const wxString& entry, wxChar **value, const wxString& file)
833{
834 static const wxChar defunkt[] = wxT("$$default");
835 if (file != wxT(""))
836 {
837 int n = GetPrivateProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
838 (LPTSTR)wxBuffer, 1000, (LPCTSTR)WXSTRINGCAST file);
839 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
840 return FALSE;
841 }
842 else
843 {
844 int n = GetProfileString((LPCTSTR)WXSTRINGCAST section, (LPCTSTR)WXSTRINGCAST entry, (LPCTSTR)defunkt,
845 (LPTSTR)wxBuffer, 1000);
846 if (n == 0 || wxStrcmp(wxBuffer, defunkt) == 0)
847 return FALSE;
848 }
849 if (*value) delete[] (*value);
850 *value = copystring(wxBuffer);
851 return TRUE;
852}
853
854bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
855{
856 wxChar *s = NULL;
857 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
858 if (succ)
859 {
860 *value = (float)wxStrtod(s, NULL);
861 delete[] s;
862 return TRUE;
863 }
864 else return FALSE;
865}
866
867bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
868{
869 wxChar *s = NULL;
870 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
871 if (succ)
872 {
873 *value = wxStrtol(s, NULL, 10);
874 delete[] s;
875 return TRUE;
876 }
877 else return FALSE;
878}
879
880bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
881{
882 wxChar *s = NULL;
883 bool succ = wxGetResource(section, entry, (wxChar **)&s, file);
884 if (succ)
885 {
886 *value = (int)wxStrtol(s, NULL, 10);
887 delete[] s;
888 return TRUE;
889 }
890 else return FALSE;
891}
892#endif // wxUSE_RESOURCES
893
894// ---------------------------------------------------------------------------
895// helper functions for showing a "busy" cursor
896// ---------------------------------------------------------------------------
897
898static HCURSOR gs_wxBusyCursor = 0; // new, busy cursor
899static HCURSOR gs_wxBusyCursorOld = 0; // old cursor
900static int gs_wxBusyCursorCount = 0;
901
902extern HCURSOR wxGetCurrentBusyCursor()
903{
904 return gs_wxBusyCursor;
905}
906
907// Set the cursor to the busy cursor for all windows
908void wxBeginBusyCursor(wxCursor *cursor)
909{
910 if ( gs_wxBusyCursorCount++ == 0 )
911 {
912 gs_wxBusyCursor = (HCURSOR)cursor->GetHCURSOR();
913 gs_wxBusyCursorOld = ::SetCursor(gs_wxBusyCursor);
914 }
915 //else: nothing to do, already set
916}
917
918// Restore cursor to normal
919void wxEndBusyCursor()
920{
921 wxCHECK_RET( gs_wxBusyCursorCount > 0,
922 wxT("no matching wxBeginBusyCursor() for wxEndBusyCursor()") );
923
924 if ( --gs_wxBusyCursorCount == 0 )
925 {
926 ::SetCursor(gs_wxBusyCursorOld);
927
928 gs_wxBusyCursorOld = 0;
929 }
930}
931
932// TRUE if we're between the above two calls
933bool wxIsBusy()
934{
935 return (gs_wxBusyCursorCount > 0);
936}
937
938// Check whether this window wants to process messages, e.g. Stop button
939// in long calculations.
940bool wxCheckForInterrupt(wxWindow *wnd)
941{
942 wxCHECK( wnd, FALSE );
943
944 MSG msg;
945 while ( ::PeekMessage(&msg, GetHwndOf(wnd), 0, 0, PM_REMOVE) )
946 {
947 ::TranslateMessage(&msg);
948 ::DispatchMessage(&msg);
949 }
950
951 return TRUE;
952}
953
954// MSW only: get user-defined resource from the .res file.
955// Returns NULL or newly-allocated memory, so use delete[] to clean up.
956
957wxChar *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
958{
959 HRSRC hResource = ::FindResource(wxGetInstance(), resourceName, resourceType);
960 if ( hResource == 0 )
961 return NULL;
962
963 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
964 if ( hData == 0 )
965 return NULL;
966
967 wxChar *theText = (wxChar *)::LockResource(hData);
968 if ( !theText )
969 return NULL;
970
971 // Not all compilers put a zero at the end of the resource (e.g. BC++ doesn't).
972 // so we need to find the length of the resource.
973 int len = ::SizeofResource(wxGetInstance(), hResource);
974 wxChar *s = new wxChar[len+1];
975 wxStrncpy(s,theText,len);
976 s[len]=0;
977
978 // wxChar *s = copystring(theText);
979
980 // Obsolete in WIN32
981#ifndef __WIN32__
982 UnlockResource(hData);
983#endif
984
985 // No need??
986 // GlobalFree(hData);
987
988 return s;
989}
990
991// ----------------------------------------------------------------------------
992// get display info
993// ----------------------------------------------------------------------------
994
995// See also the wxGetMousePosition in window.cpp
996// Deprecated: use wxPoint wxGetMousePosition() instead
997void wxGetMousePosition( int* x, int* y )
998{
999 POINT pt;
1000 GetCursorPos( & pt );
1001 if ( x ) *x = pt.x;
1002 if ( y ) *y = pt.y;
1003};
1004
1005// Return TRUE if we have a colour display
1006bool wxColourDisplay()
1007{
1008 ScreenHDC dc;
1009 int noCols = GetDeviceCaps(dc, NUMCOLORS);
1010
1011 return (noCols == -1) || (noCols > 2);
1012}
1013
1014// Returns depth of screen
1015int wxDisplayDepth()
1016{
1017 ScreenHDC dc;
1018 return GetDeviceCaps(dc, PLANES) * GetDeviceCaps(dc, BITSPIXEL);
1019}
1020
1021// Get size of display
1022void wxDisplaySize(int *width, int *height)
1023{
1024 ScreenHDC dc;
1025
1026 if ( width ) *width = GetDeviceCaps(dc, HORZRES);
1027 if ( height ) *height = GetDeviceCaps(dc, VERTRES);
1028}
1029
1030void wxDisplaySizeMM(int *width, int *height)
1031{
1032 ScreenHDC dc;
1033
1034 if ( width ) *width = GetDeviceCaps(dc, HORZSIZE);
1035 if ( height ) *height = GetDeviceCaps(dc, VERTSIZE);
1036}
1037
1038
1039// ---------------------------------------------------------------------------
1040// window information functions
1041// ---------------------------------------------------------------------------
1042
1043wxString WXDLLEXPORT wxGetWindowText(WXHWND hWnd)
1044{
1045 wxString str;
1046 int len = GetWindowTextLength((HWND)hWnd) + 1;
1047 GetWindowText((HWND)hWnd, str.GetWriteBuf(len), len);
1048 str.UngetWriteBuf();
1049
1050 return str;
1051}
1052
1053wxString WXDLLEXPORT wxGetWindowClass(WXHWND hWnd)
1054{
1055 wxString str;
1056
1057 int len = 256; // some starting value
1058
1059 for ( ;; )
1060 {
1061 // as we've #undefined GetClassName we must now manually choose the
1062 // right function to call
1063 int count =
1064
1065 #ifndef __WIN32__
1066 GetClassName
1067 #else // Win32
1068 #ifdef UNICODE
1069 GetClassNameW
1070 #else // !Unicode
1071 #ifdef __TWIN32__
1072 GetClassName
1073 #else // !Twin32
1074 GetClassNameA
1075 #endif // Twin32/!Twin32
1076 #endif // Unicode/ANSI
1077 #endif // Win16/32
1078 ((HWND)hWnd, str.GetWriteBuf(len), len);
1079
1080 str.UngetWriteBuf();
1081 if ( count == len )
1082 {
1083 // the class name might have been truncated, retry with larger
1084 // buffer
1085 len *= 2;
1086 }
1087 else
1088 {
1089 break;
1090 }
1091 }
1092
1093 return str;
1094}
1095
1096WXWORD WXDLLEXPORT wxGetWindowId(WXHWND hWnd)
1097{
1098#ifndef __WIN32__
1099 return GetWindowWord((HWND)hWnd, GWW_ID);
1100#else // Win32
1101 return GetWindowLong((HWND)hWnd, GWL_ID);
1102#endif // Win16/32
1103}
1104
1105#endif // wxUSE_GUI
1106
1107#if 0
1108//------------------------------------------------------------------------
1109// wild character routines
1110//------------------------------------------------------------------------
1111
1112bool wxIsWild( const wxString& pattern )
1113{
1114 wxString tmp = pattern;
1115 char *pat = WXSTRINGCAST(tmp);
1116 while (*pat) {
1117 switch (*pat++) {
1118 case '?': case '*': case '[': case '{':
1119 return TRUE;
1120 case '\\':
1121 if (!*pat++)
1122 return FALSE;
1123 }
1124 }
1125 return FALSE;
1126};
1127
1128
1129bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1130{
1131 wxString tmp1 = pat;
1132 char *pattern = WXSTRINGCAST(tmp1);
1133 wxString tmp2 = text;
1134 char *str = WXSTRINGCAST(tmp2);
1135 char c;
1136 char *cp;
1137 bool done = FALSE, ret_code, ok;
1138 // Below is for vi fans
1139 const char OB = '{', CB = '}';
1140
1141 // dot_special means '.' only matches '.'
1142 if (dot_special && *str == '.' && *pattern != *str)
1143 return FALSE;
1144
1145 while ((*pattern != '\0') && (!done)
1146 && (((*str=='\0')&&((*pattern==OB)||(*pattern=='*')))||(*str!='\0'))) {
1147 switch (*pattern) {
1148 case '\\':
1149 pattern++;
1150 if (*pattern != '\0')
1151 pattern++;
1152 break;
1153 case '*':
1154 pattern++;
1155 ret_code = FALSE;
1156 while ((*str!='\0')
1157 && (!(ret_code=wxMatchWild(pattern, str++, FALSE))))
1158 /*loop*/;
1159 if (ret_code) {
1160 while (*str != '\0')
1161 str++;
1162 while (*pattern != '\0')
1163 pattern++;
1164 }
1165 break;
1166 case '[':
1167 pattern++;
1168 repeat:
1169 if ((*pattern == '\0') || (*pattern == ']')) {
1170 done = TRUE;
1171 break;
1172 }
1173 if (*pattern == '\\') {
1174 pattern++;
1175 if (*pattern == '\0') {
1176 done = TRUE;
1177 break;
1178 }
1179 }
1180 if (*(pattern + 1) == '-') {
1181 c = *pattern;
1182 pattern += 2;
1183 if (*pattern == ']') {
1184 done = TRUE;
1185 break;
1186 }
1187 if (*pattern == '\\') {
1188 pattern++;
1189 if (*pattern == '\0') {
1190 done = TRUE;
1191 break;
1192 }
1193 }
1194 if ((*str < c) || (*str > *pattern)) {
1195 pattern++;
1196 goto repeat;
1197 }
1198 } else if (*pattern != *str) {
1199 pattern++;
1200 goto repeat;
1201 }
1202 pattern++;
1203 while ((*pattern != ']') && (*pattern != '\0')) {
1204 if ((*pattern == '\\') && (*(pattern + 1) != '\0'))
1205 pattern++;
1206 pattern++;
1207 }
1208 if (*pattern != '\0') {
1209 pattern++, str++;
1210 }
1211 break;
1212 case '?':
1213 pattern++;
1214 str++;
1215 break;
1216 case OB:
1217 pattern++;
1218 while ((*pattern != CB) && (*pattern != '\0')) {
1219 cp = str;
1220 ok = TRUE;
1221 while (ok && (*cp != '\0') && (*pattern != '\0')
1222 && (*pattern != ',') && (*pattern != CB)) {
1223 if (*pattern == '\\')
1224 pattern++;
1225 ok = (*pattern++ == *cp++);
1226 }
1227 if (*pattern == '\0') {
1228 ok = FALSE;
1229 done = TRUE;
1230 break;
1231 } else if (ok) {
1232 str = cp;
1233 while ((*pattern != CB) && (*pattern != '\0')) {
1234 if (*++pattern == '\\') {
1235 if (*++pattern == CB)
1236 pattern++;
1237 }
1238 }
1239 } else {
1240 while (*pattern!=CB && *pattern!=',' && *pattern!='\0') {
1241 if (*++pattern == '\\') {
1242 if (*++pattern == CB || *pattern == ',')
1243 pattern++;
1244 }
1245 }
1246 }
1247 if (*pattern != '\0')
1248 pattern++;
1249 }
1250 break;
1251 default:
1252 if (*str == *pattern) {
1253 str++, pattern++;
1254 } else {
1255 done = TRUE;
1256 }
1257 }
1258 }
1259 while (*pattern == '*')
1260 pattern++;
1261 return ((*str == '\0') && (*pattern == '\0'));
1262};
1263
1264#endif // 0
1265
1266#if 0
1267
1268// maximum mumber of lines the output console should have
1269static const WORD MAX_CONSOLE_LINES = 500;
1270
1271BOOL WINAPI MyConsoleHandler( DWORD dwCtrlType ) { // control signal type
1272 FreeConsole();
1273 return TRUE;
1274}
1275
1276void wxRedirectIOToConsole()
1277{
1278 int hConHandle;
1279 long lStdHandle;
1280 CONSOLE_SCREEN_BUFFER_INFO coninfo;
1281 FILE *fp;
1282
1283 // allocate a console for this app
1284 AllocConsole();
1285
1286 // set the screen buffer to be big enough to let us scroll text
1287 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
1288 &coninfo);
1289 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
1290 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
1291 coninfo.dwSize);
1292
1293 // redirect unbuffered STDOUT to the console
1294 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
1295 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1296 if(hConHandle <= 0) return;
1297 fp = _fdopen( hConHandle, "w" );
1298 *stdout = *fp;
1299 setvbuf( stdout, NULL, _IONBF, 0 );
1300
1301 // redirect unbuffered STDIN to the console
1302 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
1303 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1304 if(hConHandle <= 0) return;
1305 fp = _fdopen( hConHandle, "r" );
1306 *stdin = *fp;
1307 setvbuf( stdin, NULL, _IONBF, 0 );
1308
1309 // redirect unbuffered STDERR to the console
1310 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
1311 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
1312 if(hConHandle <= 0) return;
1313 fp = _fdopen( hConHandle, "w" );
1314 *stderr = *fp;
1315 setvbuf( stderr, NULL, _IONBF, 0 );
1316
1317 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
1318 // point to console as well
1319 ios::sync_with_stdio();
1320
1321 SetConsoleCtrlHandler(MyConsoleHandler, TRUE);
1322}
1323#else
1324// Not supported
1325void wxRedirectIOToConsole()
1326{
1327}
1328#endif
1329
1330