]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utils.cpp
Cured DC/GDI object leak; listbox window proc restored from debugging
[wxWidgets.git] / src / msw / utils.cpp
CommitLineData
2bda0e17
KB
1/////////////////////////////////////////////////////////////////////////////
2// Name: 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#ifdef __GNUG__
13#pragma implementation
14#pragma implementation "utils.h"
15#endif
16
17// For compilers that support precompilation, includes "wx.h".
18#include "wx/wxprec.h"
19
20#ifdef __BORLANDC__
21#pragma hdrstop
22#endif
23
24#ifndef WX_PRECOMP
25#include "wx/setup.h"
26#include "wx/utils.h"
27#include "wx/app.h"
28#include "wx/cursor.h"
29#endif
30
31#include "wx/msw/private.h"
32#include "wx/timer.h"
33
34#include <ctype.h>
35
36#ifndef __GNUWIN32__
37#include <direct.h>
38#include <dos.h>
39#endif
40
41#ifdef __GNUWIN32__
42#include <sys/unistd.h>
43#include <sys/stat.h>
44#ifndef __MINGW32__
45#include <std.h>
46#endif
47
48#define stricmp strcasecmp
49#endif
50
51#ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
52 // this (3.1 I believe) and how to test for it.
53 // If this works for Borland 4.0 as well, then no worries.
54#include <dir.h>
55#endif
56
57#ifdef __WIN32__
58#include <io.h>
59
60#ifndef __GNUWIN32__
61#include <shellapi.h>
62#endif
63#endif
64
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#ifndef __WATCOMC__
69#if !(defined(_MSC_VER) && (_MSC_VER > 800))
70#include <errno.h>
71#endif
72#endif
73#include <stdarg.h>
74
75// In the WIN.INI file
76static const char WX_SECTION[] = "wxWindows";
77static const char eHOSTNAME[] = "HostName";
78static const char eUSERID[] = "UserId";
79static const char eUSERNAME[] = "UserName";
80
2bda0e17
KB
81// For the following functions we SHOULD fill in support
82// for Windows-NT (which I don't know) as I assume it begin
83// a POSIX Unix (so claims MS) that it has some special
84// functions beyond those provided by WinSock
85
86// Get full hostname (eg. DoDo.BSn-Germany.crg.de)
87bool wxGetHostName(char *buf, int maxSize)
88{
89#ifdef __WIN32__
90 DWORD nSize = maxSize;
91 return (::GetComputerName(buf, &nSize) != 0);
92#else
93 char *sysname;
94 const char *default_host = "noname";
95
96 if ((sysname = getenv("SYSTEM_NAME")) == NULL) {
97 GetProfileString(WX_SECTION, eHOSTNAME, default_host, buf, maxSize - 1);
98 } else
99 strncpy(buf, sysname, maxSize - 1);
100 buf[maxSize] = '\0';
101 return *buf ? TRUE : FALSE;
102#endif
103}
104
105// Get user ID e.g. jacs
106bool wxGetUserId(char *buf, int maxSize)
107{
108#if defined(__WIN32__) && !defined(__win32s__) && 0
109 // Gets the current user's full name according to the MS article PSS ID
110 // Number: Q119670
111 // Seems to be the same as the login name for me?
112 char *UserName = new char[256];
113 char *Domain = new char[256];
114 DWORD maxCharacters = 255;
115 GetUserName( UserName, &maxCharacters );
116 GetComputerName( Domain, &maxCharacters );
117
118 WCHAR wszUserName[256]; // Unicode user name
119 WCHAR wszDomain[256];
120 LPBYTE ComputerName;
121
122 struct _SERVER_INFO_100 *si100; // Server structure
123 struct _USER_INFO_2 *ui; // User structure
124
125 // Convert ASCII user name and domain to Unicode.
126
127 MultiByteToWideChar( CP_ACP, 0, UserName,
128 strlen(UserName)+1, wszUserName, sizeof(wszUserName) );
129 MultiByteToWideChar( CP_ACP, 0, Domain,
130 strlen(Domain)+1, wszDomain, sizeof(wszDomain) );
131
132 // Get the computer name of a DC for the specified domain.
133 // >If you get a link error on this, include netapi32.lib<
134
135 NetGetDCName( NULL, wszDomain, &ComputerName );
136
137 // Look up the user on the DC.
138
139 if(NetUserGetInfo( (LPWSTR) ComputerName,
140 (LPWSTR) &wszUserName, 2, (LPBYTE *) &ui))
141 {
142 printf( "Error getting user information.\n" );
143 return( FALSE );
144 }
145
146 // Convert the Unicode full name to ASCII.
147
148 WideCharToMultiByte( CP_ACP, 0, ui->usri2_full_name,
149 -1, buf, 256, NULL, NULL );
150 }
151 return( TRUE );
152/*
153 DWORD nSize = maxSize;
154 return ::GetUserName(buf, &nSize);
155*/
156#else
157 char *user;
158 const char *default_id = "anonymous";
159
160 // Can't assume we have NIS (PC-NFS) or some other ID daemon
161 // So we ...
162 if ( (user = getenv("USER")) == NULL &&
163 (user = getenv("LOGNAME")) == NULL ) {
164 // Use wxWindows configuration data (comming soon)
165 GetProfileString(WX_SECTION, eUSERID, default_id, buf, maxSize - 1);
166 } else
167 strncpy(buf, user, maxSize - 1);
168 return *buf ? TRUE : FALSE;
169#endif
170}
171
172// Get user name e.g. Julian Smart
173bool wxGetUserName(char *buf, int maxSize)
174{
175 const char *default_name = "Unknown User";
176#if defined(__WIN32__)
177/*
178 DWORD nSize = maxSize;
179 In VC++ 4.0, results in unresolved symbol __imp__GetUserNameA
180 if (GetUserName(buf, &nSize))
181 return TRUE;
182 else
183*/
184 // Could use NIS, MS-Mail or other site specific programs
185 // Use wxWindows configuration data
186 GetProfileString(WX_SECTION, eUSERNAME, default_name, buf, maxSize - 1);
187 return *buf ? TRUE : FALSE;
188// }
189#else
190#if !defined(__WATCOMC__) && !defined(__GNUWIN32__) && USE_PENWINDOWS
191 extern HANDLE hPenWin; // PenWindows Running?
192 if (hPenWin)
193 {
194 // PenWindows Does have a user concept!
195 // Get the current owner of the recognizer
196 GetPrivateProfileString("Current", "User", default_name, wxBuffer, maxSize - 1, "PENWIN.INI");
197 strncpy(buf, wxBuffer, maxSize - 1);
198 }
199 else
200#endif
201 {
202 // Could use NIS, MS-Mail or other site specific programs
203 // Use wxWindows configuration data
204 GetProfileString(WX_SECTION, eUSERNAME, default_name, buf, maxSize - 1);
205 }
206 return *buf ? TRUE : FALSE;
207#endif
208}
209
210// Execute a command (e.g. another program) in a
211// system-independent manner.
212
213long wxExecute(char **argv, bool sync)
214{
215 if (*argv == NULL)
216 return 0;
217
218 char command[1024];
219 command[0] = '\0';
220
221 int argc;
222 for (argc = 0; argv[argc]; argc++)
223 {
224 if (argc)
225 strcat(command, " ");
226 strcat(command, argv[argc]);
227 }
228
229 return wxExecute((char *)command, sync);
230}
231
232long wxExecute(const wxString& command, bool sync)
233{
234 if (command == "")
235 return 0;
236
237#ifdef __WIN32__
238 char * cl;
239 char * argp;
240 int clen;
241 HINSTANCE result;
242 DWORD dresult;
243
244 // copy the command line
245 clen = command.Length();
246 if (!clen) return -1;
247 cl = (char *) calloc( 1, 256);
248 if (!cl) return -1;
249 strcpy( cl, WXSTRINGCAST command);
250
251 // isolate command and arguments
252 argp = strchr( cl, ' ');
253 if (argp)
254 *argp++ = '\0';
255
256 // execute the command
257#ifdef __GNUWIN32__
258 result = ShellExecute( (HWND) (wxTheApp->GetTopWindow() ? (HWND) wxTheApp->GetTopWindow()->GetHWND() : NULL),
259 (const wchar_t) "open", (const wchar_t) cl, (const wchar_t) argp, (const wchar_t) NULL, SW_SHOWNORMAL);
260#else
261 result = ShellExecute( (HWND) (wxTheApp->GetTopWindow() ? wxTheApp->GetTopWindow()->GetHWND() : NULL),
262 "open", cl, argp, NULL, SW_SHOWNORMAL);
263#endif
264
265 if (((long)result) <= 32) {
266 free(cl);
267 return 0;
268 }
269
270 if (!sync)
271 {
272 free(cl);
273 return dresult;
274 }
275
276 // waiting until command executed
277 do {
278 wxYield();
279 dresult = GetModuleFileName( result, cl, 256);
280 } while( dresult);
281
282 /* long lastError = GetLastError(); */
283
284 free(cl);
285 return 0;
286#else
287 long instanceID = WinExec((LPCSTR) WXSTRINGCAST command, SW_SHOW);
288 if (instanceID < 32) return(0);
289
290 if (sync) {
291 int running;
292 do {
293 wxYield();
294 running = GetModuleUsage((HANDLE)instanceID);
295 } while (running);
296 }
297 return(instanceID);
298#endif
299}
300
301int wxKill(long pid, int sig)
302{
303 return 0;
304}
305
306//
307// Execute a program in an Interactive Shell
308//
309bool
310wxShell(const wxString& command)
311{
312 char *shell;
313 if ((shell = getenv("COMSPEC")) == NULL)
314 shell = "\\COMMAND.COM";
315
316 char tmp[255];
317 if (command != "")
318 sprintf(tmp, "%s /c %s", shell, WXSTRINGCAST command);
319 else
320 strcpy(tmp, shell);
321
322 return (wxExecute((char *)tmp, FALSE) != 0);
323}
324
325// Get free memory in bytes, or -1 if cannot determine amount (e.g. on UNIX)
326long wxGetFreeMemory(void)
327{
328#if defined(__WIN32__) && !defined(__BORLANDC__)
329 MEMORYSTATUS memStatus;
330 memStatus.dwLength = sizeof(MEMORYSTATUS);
331 GlobalMemoryStatus(&memStatus);
332 return memStatus.dwAvailPhys;
333#else
334 return (long)GetFreeSpace(0);
335#endif
336}
337
338// Sleep for nSecs seconds. Attempt a Windows implementation using timers.
339static bool inTimer = FALSE;
340class wxSleepTimer: public wxTimer
341{
342 public:
343 inline void Notify(void)
344 {
345 inTimer = FALSE;
346 Stop();
347 }
348};
349
350static wxTimer *wxTheSleepTimer = NULL;
351
352void wxSleep(int nSecs)
353{
354#if 0 // WIN32 hangs app
355 Sleep( 1000*nSecs );
356#else
357 if (inTimer)
358 return;
359
360 wxTheSleepTimer = new wxSleepTimer;
361 inTimer = TRUE;
362 wxTheSleepTimer->Start(nSecs*1000);
363 while (inTimer)
364 {
365 if (wxTheApp->Pending())
366 wxTheApp->Dispatch();
367 }
368 delete wxTheSleepTimer;
369 wxTheSleepTimer = NULL;
370#endif
371}
372
373// Consume all events until no more left
374void wxFlushEvents(void)
375{
376// wxYield();
377}
378
379// Output a debug mess., in a system dependent fashion.
380void wxDebugMsg(const char *fmt ...)
381{
382 va_list ap;
383 static char buffer[512];
384
385 if (!wxTheApp->GetWantDebugOutput())
386 return ;
387
388 va_start(ap, fmt);
389
390 wvsprintf(buffer,fmt,ap) ;
391 OutputDebugString((LPCSTR)buffer) ;
392
393 va_end(ap);
394}
395
396// Non-fatal error: pop up message box and (possibly) continue
397void wxError(const wxString& msg, const wxString& title)
398{
399 sprintf(wxBuffer, "%s\nContinue?", WXSTRINGCAST msg);
400 if (MessageBox(NULL, (LPCSTR)wxBuffer, (LPCSTR)WXSTRINGCAST title,
401 MB_ICONSTOP | MB_YESNO) == IDNO)
402 wxExit();
403}
404
405// Fatal error: pop up message box and abort
406void wxFatalError(const wxString& msg, const wxString& title)
407{
408 sprintf(wxBuffer, "%s: %s", WXSTRINGCAST title, WXSTRINGCAST msg);
409 FatalAppExit(0, (LPCSTR)wxBuffer);
410}
411
412// Emit a beeeeeep
413void wxBell(void)
414{
415#ifdef __WIN32__
416 Beep(1000,1000) ; // 1kHz during 1 sec.
417#else
418 MessageBeep(-1) ;
419#endif
420}
421
6f65e337
JS
422// Chris Breeze 27/5/98: revised WIN32 code to
423// detect WindowsNT correctly
2bda0e17
KB
424int wxGetOsVersion(int *majorVsn, int *minorVsn)
425{
426 extern char *wxOsVersion;
6f65e337
JS
427 if (majorVsn) *majorVsn = 0;
428 if (minorVsn) *minorVsn = 0;
429
430#ifdef WIN32
431 OSVERSIONINFO info;
432 memset(&info, 0, sizeof(OSVERSIONINFO));
433 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
434 if (GetVersionEx(&info))
435 {
436 if (majorVsn) *majorVsn = info.dwMajorVersion;
437 if (minorVsn) *minorVsn = info.dwMinorVersion;
438 switch (info.dwPlatformId)
439 {
440 case VER_PLATFORM_WIN32s:
441 return wxWIN32S;
442 break;
443 case VER_PLATFORM_WIN32_WINDOWS:
444 return wxWIN95;
445 break;
446 case VER_PLATFORM_WIN32_NT:
447 return wxWINDOWS_NT;
448 break;
449 }
450 }
451 return wxWINDOWS; // error if we get here, return generic value
452#else
453 // Win16 code...
2bda0e17 454 int retValue ;
6f65e337 455# ifdef __WINDOWS_386__
2bda0e17 456 retValue = wxWIN386;
6f65e337
JS
457# else
458# if !defined(__WATCOMC__) && !defined(GNUWIN32)
2bda0e17
KB
459 extern HANDLE hPenWin;
460 retValue = hPenWin ? wxPENWINDOWS : wxWINDOWS ;
6f65e337
JS
461# endif
462# endif
2bda0e17
KB
463 // @@@@ To be completed. I don't have the manual here...
464 if (majorVsn) *majorVsn = 3 ;
465 if (minorVsn) *minorVsn = 1 ;
466 return retValue ;
6f65e337 467#endif
2bda0e17
KB
468}
469
470// Reading and writing resources (eg WIN.INI, .Xdefaults)
471#if USE_RESOURCES
472bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
473{
474 if (file != "")
475 return (WritePrivateProfileString((LPCSTR)WXSTRINGCAST section, (LPCSTR)WXSTRINGCAST entry, (LPCSTR)value, (LPCSTR)WXSTRINGCAST file) != 0);
476 else
477 return (WriteProfileString((LPCSTR)WXSTRINGCAST section, (LPCSTR)WXSTRINGCAST entry, (LPCSTR)WXSTRINGCAST value) != 0);
478}
479
480bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
481{
482 char buf[50];
483 sprintf(buf, "%.4f", value);
484 return wxWriteResource(section, entry, buf, file);
485}
486
487bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
488{
489 char buf[50];
490 sprintf(buf, "%ld", value);
491 return wxWriteResource(section, entry, buf, file);
492}
493
494bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
495{
496 char buf[50];
497 sprintf(buf, "%d", value);
498 return wxWriteResource(section, entry, buf, file);
499}
500
501bool wxGetResource(const wxString& section, const wxString& entry, char **value, const wxString& file)
502{
503 static const char defunkt[] = "$$default";
504 if (file != "")
505 {
506 int n = GetPrivateProfileString((LPCSTR)WXSTRINGCAST section, (LPCSTR)WXSTRINGCAST entry, (LPCSTR)defunkt,
507 (LPSTR)wxBuffer, 1000, (LPCSTR)WXSTRINGCAST file);
508 if (n == 0 || strcmp(wxBuffer, defunkt) == 0)
509 return FALSE;
510 }
511 else
512 {
513 int n = GetProfileString((LPCSTR)WXSTRINGCAST section, (LPCSTR)WXSTRINGCAST entry, (LPCSTR)defunkt,
514 (LPSTR)wxBuffer, 1000);
515 if (n == 0 || strcmp(wxBuffer, defunkt) == 0)
516 return FALSE;
517 }
518 if (*value) delete[] (*value);
519 *value = copystring(wxBuffer);
520 return TRUE;
521 }
522
523bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
524{
525 char *s = NULL;
526 bool succ = wxGetResource(section, entry, (char **)&s, file);
527 if (succ)
528 {
529 *value = (float)strtod(s, NULL);
530 delete[] s;
531 return TRUE;
532 }
533 else return FALSE;
534}
535
536bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
537{
538 char *s = NULL;
539 bool succ = wxGetResource(section, entry, (char **)&s, file);
540 if (succ)
541 {
542 *value = strtol(s, NULL, 10);
543 delete[] s;
544 return TRUE;
545 }
546 else return FALSE;
547}
548
549bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
550{
551 char *s = NULL;
552 bool succ = wxGetResource(section, entry, (char **)&s, file);
553 if (succ)
554 {
555 *value = (int)strtol(s, NULL, 10);
556 delete[] s;
557 return TRUE;
558 }
559 else return FALSE;
560}
561#endif // USE_RESOURCES
562
563// Old cursor
564static HCURSOR wxBusyCursorOld = 0;
565static int wxBusyCursorCount = 0;
566
567// Set the cursor to the busy cursor for all windows
568void wxBeginBusyCursor(wxCursor *cursor)
569{
570 wxBusyCursorCount ++;
571 if (wxBusyCursorCount == 1)
572 {
573 wxBusyCursorOld = ::SetCursor((HCURSOR) cursor->GetHCURSOR());
574 }
575 else
576 {
577 (void)::SetCursor((HCURSOR) cursor->GetHCURSOR());
578 }
579}
580
581// Restore cursor to normal
582void wxEndBusyCursor(void)
583{
584 if (wxBusyCursorCount == 0)
585 return;
586
587 wxBusyCursorCount --;
588 if (wxBusyCursorCount == 0)
589 {
590 ::SetCursor(wxBusyCursorOld);
591 wxBusyCursorOld = 0;
592 }
593}
594
595// TRUE if we're between the above two calls
596bool wxIsBusy(void)
597{
598 return (wxBusyCursorCount > 0);
599}
600
601// Hack for MS-DOS
602char *wxGetUserHome (const wxString& user)
603{
604 char *home;
605 wxString user1(user);
606
607 if (user1 != "") {
608 char tmp[64];
609 if (wxGetUserId(tmp, sizeof(tmp)/sizeof(char))) {
610 // Guests belong in the temp dir
611 if (stricmp(tmp, "annonymous") == 0) {
612 if ((home = getenv("TMP")) != NULL ||
613 (home = getenv("TMPDIR")) != NULL ||
614 (home = getenv("TEMP")) != NULL)
615 return *home ? home : "\\";
616 }
617 if (stricmp(tmp, WXSTRINGCAST user1) == 0)
618 user1 = "";
619 }
620 }
621 if (user1 == "")
622 if ((home = getenv("HOME")) != NULL)
623 {
624 strcpy(wxBuffer, home);
625 Unix2DosFilename(wxBuffer);
626 return wxBuffer;
627 }
628 return NULL; // No home known!
629}
630
631// Check whether this window wants to process messages, e.g. Stop button
632// in long calculations.
633bool wxCheckForInterrupt(wxWindow *wnd)
634{
635 if(wnd){
636 MSG msg;
637 HWND win= (HWND) wnd->GetHWND();
638 while(PeekMessage(&msg,win,0,0,PM_REMOVE)){
639 TranslateMessage(&msg);
640 DispatchMessage(&msg);
641 }
642 return TRUE;//*** temporary?
643 }
644 else{
645 wxError("wnd==NULL !!!");
646 return FALSE;//*** temporary?
647 }
648}
649
650// MSW only: get user-defined resource from the .res file.
651// Returns NULL or newly-allocated memory, so use delete[] to clean up.
652
653#ifdef __WINDOWS__
654char *wxLoadUserResource(const wxString& resourceName, const wxString& resourceType)
655{
656 char *s = NULL;
657#ifndef __WIN32__
658 HRSRC hResource = ::FindResource(wxGetInstance(), WXSTRINGCAST resourceName, WXSTRINGCAST resourceType);
659#else
660#ifdef UNICODE
661 HRSRC hResource = ::FindResourceW(wxGetInstance(), WXSTRINGCAST resourceName, WXSTRINGCAST resourceType);
662#else
663 HRSRC hResource = ::FindResourceA(wxGetInstance(), WXSTRINGCAST resourceName, WXSTRINGCAST resourceType);
664#endif
665#endif
666
667 if (hResource == 0)
668 return NULL;
669 HGLOBAL hData = ::LoadResource(wxGetInstance(), hResource);
670 if (hData == 0)
671 return NULL;
672 char *theText = (char *)LockResource(hData);
673 if (!theText)
674 return NULL;
675
676 s = copystring(theText);
677
678 // Obsolete in WIN32
679#ifndef __WIN32__
680 UnlockResource(hData);
681#endif
682
683 // No need??
684// GlobalFree(hData);
685
686 return s;
687}
688#endif
689
690void wxGetMousePosition( int* x, int* y )
691{
692 POINT pt;
693 GetCursorPos( & pt );
694 *x = pt.x;
695 *y = pt.y;
696};
697
698// Return TRUE if we have a colour display
699bool wxColourDisplay(void)
700{
701 HDC dc = ::GetDC(NULL);
702 bool flag;
703 int noCols = GetDeviceCaps(dc, NUMCOLORS);
704 if ((noCols == -1) || (noCols > 2))
705 flag = TRUE;
706 else
707 flag = FALSE;
708 ReleaseDC(NULL, dc);
709 return flag;
710}
711
712// Returns depth of screen
713int wxDisplayDepth(void)
714{
715 HDC dc = ::GetDC(NULL);
716 int planes = GetDeviceCaps(dc, PLANES);
717 int bitsPerPixel = GetDeviceCaps(dc, BITSPIXEL);
718 int depth = planes*bitsPerPixel;
719 ReleaseDC(NULL, dc);
720 return depth;
721}
722
723// Get size of display
724void wxDisplaySize(int *width, int *height)
725{
726 HDC dc = ::GetDC(NULL);
727 *width = GetDeviceCaps(dc, HORZRES); *height = GetDeviceCaps(dc, VERTRES);
728 ReleaseDC(NULL, dc);
729}
730