]> git.saurik.com Git - wxWidgets.git/blob - src/msw/app.cpp
fixed xpm colour parsing bug due to case sensitive colour name comparison
[wxWidgets.git] / src / msw / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
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 "app.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #if defined(__BORLANDC__)
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/frame.h"
33 #include "wx/app.h"
34 #include "wx/utils.h"
35 #include "wx/gdicmn.h"
36 #include "wx/pen.h"
37 #include "wx/brush.h"
38 #include "wx/cursor.h"
39 #include "wx/icon.h"
40 #include "wx/palette.h"
41 #include "wx/dc.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
44 #include "wx/intl.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
47 #include "wx/icon.h"
48 #endif
49
50 #include "wx/log.h"
51 #include "wx/module.h"
52
53 #include "wx/msw/private.h"
54
55 #if wxUSE_THREADS
56 #include "wx/thread.h"
57
58 // define the array of MSG strutures
59 WX_DECLARE_OBJARRAY(MSG, wxMsgArray);
60
61 #include "wx/arrimpl.cpp"
62
63 WX_DEFINE_OBJARRAY(wxMsgArray);
64 #endif // wxUSE_THREADS
65
66 #if wxUSE_WX_RESOURCES
67 #include "wx/resource.h"
68 #endif
69
70 #if wxUSE_TOOLTIPS
71 #include "wx/tooltip.h"
72 #endif // wxUSE_TOOLTIPS
73
74 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
75 // compilers don't support it (missing headers, libs, ...)
76 #if defined(__GNUWIN32_OLD__) || defined(__SC__) || defined(__SALFORDC__)
77 #undef wxUSE_OLE
78
79 #define wxUSE_OLE 0
80 #endif // broken compilers
81
82 #if wxUSE_OLE
83 #include <ole2.h>
84 #endif
85
86 #include <string.h>
87 #include <ctype.h>
88
89 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__TWIN32__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
90 #include <commctrl.h>
91 #endif
92
93 #ifndef __WXMICROWIN__
94 #include "wx/msw/msvcrt.h"
95 #endif
96
97 // ----------------------------------------------------------------------------
98 // conditional compilation
99 // ----------------------------------------------------------------------------
100
101 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
102 // defined before) and shows us what common control features are available
103 // during the compile time (it doesn't mean that they will be available during
104 // the run-time, use GetComCtl32Version() to test for them!). The possible
105 // values are:
106 //
107 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
108 // 0x0300 4.70 IE 3.x
109 // 0x0400 4.71 IE 4.0
110 // 0x0401 4.72 IE 4.01 and Win98
111 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
112
113 #ifndef _WIN32_IE
114 // minimal set of features by default
115 #define _WIN32_IE 0x0200
116 #endif
117
118 #if _WIN32_IE >= 0x0300
119 #include <shlwapi.h>
120 #endif
121
122 // ---------------------------------------------------------------------------
123 // global variables
124 // ---------------------------------------------------------------------------
125
126 extern wxChar *wxBuffer;
127 extern wxList *wxWinHandleList;
128 extern wxList WXDLLEXPORT wxPendingDelete;
129 #ifndef __WXMICROWIN__
130 extern void wxSetKeyboardHook(bool doIt);
131 #endif
132
133 MSG s_currentMsg;
134 wxApp *wxTheApp = NULL;
135
136 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
137 // with NR suffix - wxWindow::MSWCreate() supposes this
138 const wxChar *wxFrameClassName = wxT("wxFrameClass");
139 const wxChar *wxFrameClassNameNoRedraw = wxT("wxFrameClassNR");
140 const wxChar *wxMDIFrameClassName = wxT("wxMDIFrameClass");
141 const wxChar *wxMDIFrameClassNameNoRedraw = wxT("wxMDIFrameClassNR");
142 const wxChar *wxMDIChildFrameClassName = wxT("wxMDIChildFrameClass");
143 const wxChar *wxMDIChildFrameClassNameNoRedraw = wxT("wxMDIChildFrameClassNR");
144 const wxChar *wxPanelClassName = wxT("wxPanelClass");
145 const wxChar *wxPanelClassNameNR = wxT("wxPanelClassNR");
146 const wxChar *wxCanvasClassName = wxT("wxCanvasClass");
147 const wxChar *wxCanvasClassNameNR = wxT("wxCanvasClassNR");
148
149 HICON wxSTD_FRAME_ICON = (HICON) NULL;
150 HICON wxSTD_MDICHILDFRAME_ICON = (HICON) NULL;
151 HICON wxSTD_MDIPARENTFRAME_ICON = (HICON) NULL;
152
153 HICON wxDEFAULT_FRAME_ICON = (HICON) NULL;
154 HICON wxDEFAULT_MDICHILDFRAME_ICON = (HICON) NULL;
155 HICON wxDEFAULT_MDIPARENTFRAME_ICON = (HICON) NULL;
156
157 HBRUSH wxDisableButtonBrush = (HBRUSH) 0;
158
159 LRESULT WXDLLEXPORT APIENTRY wxWndProc(HWND, UINT, WPARAM, LPARAM);
160
161 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
162 // needs compiler support for Win32 SEH. Others (especially Borland)
163 // probably have it too, but I'm not sure about how it works
164 // JACS: get 'Cannot use __try in functions that require unwinding
165 // in Unicode mode, so disabling.
166 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
167 #undef wxUSE_ON_FATAL_EXCEPTION
168 #define wxUSE_ON_FATAL_EXCEPTION 0
169 #endif // VC++
170
171 #if wxUSE_ON_FATAL_EXCEPTION
172 static bool gs_handleExceptions = FALSE;
173 #endif
174
175 // ===========================================================================
176 // implementation
177 // ===========================================================================
178
179 // ---------------------------------------------------------------------------
180 // wxApp
181 // ---------------------------------------------------------------------------
182
183 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
184
185 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
186 EVT_IDLE(wxApp::OnIdle)
187 EVT_END_SESSION(wxApp::OnEndSession)
188 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
189 END_EVENT_TABLE()
190
191 //// Initialize
192 bool wxApp::Initialize()
193 {
194 // the first thing to do is to check if we're trying to run an Unicode
195 // program under Win9x - if so, abort right now as it has no chance to
196 // work
197 #if wxUSE_UNICODE
198 if ( wxGetOsVersion() != wxWINDOWS_NT )
199 {
200 // note that we can use MessageBoxW() as it's implemented even under
201 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
202 // used by wxLocale are not
203 ::MessageBox
204 (
205 NULL,
206 _T("This program uses Unicode and requires Windows NT/2000.\nProgram aborted."),
207 _T("wxWindows Fatal Error"),
208 MB_ICONERROR | MB_OK
209 );
210
211 return FALSE;
212 }
213 #endif // wxUSE_UNICODE
214
215 // Some people may wish to use this, but
216 // probably it shouldn't be here by default.
217 #ifdef __WXDEBUG__
218 // wxRedirectIOToConsole();
219 #endif
220
221 wxBuffer = new wxChar[1500]; // FIXME
222
223 wxClassInfo::InitializeClasses();
224
225 #if wxUSE_THREADS
226 wxPendingEventsLocker = new wxCriticalSection;
227 #endif
228
229 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
230 wxTheColourDatabase->Initialize();
231
232 wxInitializeStockLists();
233 wxInitializeStockObjects();
234
235 #if wxUSE_WX_RESOURCES
236 wxInitializeResourceSystem();
237 #endif
238
239 wxBitmap::InitStandardHandlers();
240
241 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
242 InitCommonControls();
243 #endif // __WIN95__
244
245 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP || wxUSE_DATAOBJ
246
247 #ifdef __WIN16__
248 // for OLE, enlarge message queue to be as large as possible
249 int iMsg = 96;
250 while (!SetMessageQueue(iMsg) && (iMsg -= 8))
251 ;
252 #endif // Win16
253 // we need to initialize OLE library
254 if ( FAILED(::OleInitialize(NULL)) )
255 wxLogError(_("Cannot initialize OLE"));
256
257 #endif // wxUSE_OLE
258
259 #if wxUSE_CTL3D
260 if (!Ctl3dRegister(wxhInstance))
261 wxLogError(wxT("Cannot register CTL3D"));
262
263 Ctl3dAutoSubclass(wxhInstance);
264 #endif // wxUSE_CTL3D
265
266 // VZ: these icons are not in wx.rc anyhow (but should they?)!
267 #if 0
268 wxSTD_FRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_FRAME"));
269 wxSTD_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_MDIPARENTFRAME"));
270 wxSTD_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_MDICHILDFRAME"));
271
272 wxDEFAULT_FRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_FRAME"));
273 wxDEFAULT_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_MDIPARENTFRAME"));
274 wxDEFAULT_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_MDICHILDFRAME"));
275 #endif // 0
276
277 RegisterWindowClasses();
278
279 #ifndef __WXMICROWIN__
280 // Create the brush for disabling bitmap buttons
281
282 LOGBRUSH lb;
283 lb.lbStyle = BS_PATTERN;
284 lb.lbHatch = (int)LoadBitmap( wxhInstance, wxT("wxDISABLE_BUTTON_BITMAP") );
285 if ( lb.lbHatch )
286 {
287 wxDisableButtonBrush = ::CreateBrushIndirect( & lb );
288 ::DeleteObject( (HGDIOBJ)lb.lbHatch );
289 }
290 //else: wxWindows resources are probably not linked in
291 #endif
292
293 #if wxUSE_PENWINDOWS
294 wxRegisterPenWin();
295 #endif
296
297 wxWinHandleList = new wxList(wxKEY_INTEGER);
298
299 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
300 // PLEASE DO NOT ALTER THIS.
301 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
302 extern char wxDummyChar;
303 if (wxDummyChar) wxDummyChar++;
304 #endif
305
306 #ifndef __WXMICROWIN__
307 wxSetKeyboardHook(TRUE);
308 #endif
309
310 wxModule::RegisterModules();
311 if (!wxModule::InitializeModules())
312 return FALSE;
313 return TRUE;
314 }
315
316 // ---------------------------------------------------------------------------
317 // RegisterWindowClasses
318 // ---------------------------------------------------------------------------
319
320 // TODO we should only register classes really used by the app. For this it
321 // would be enough to just delay the class registration until an attempt
322 // to create a window of this class is made.
323 bool wxApp::RegisterWindowClasses()
324 {
325 WNDCLASS wndclass;
326
327 // for each class we register one with CS_(V|H)REDRAW style and one
328 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
329 static const long styleNormal = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
330 static const long styleNoRedraw = CS_DBLCLKS;
331
332 // the fields which are common to all classes
333 wndclass.lpfnWndProc = (WNDPROC)wxWndProc;
334 wndclass.cbClsExtra = 0;
335 wndclass.cbWndExtra = sizeof( DWORD ); // VZ: what is this DWORD used for?
336 wndclass.hInstance = wxhInstance;
337 wndclass.hIcon = (HICON) NULL;
338 wndclass.hCursor = ::LoadCursor((HINSTANCE)NULL, IDC_ARROW);
339 wndclass.lpszMenuName = NULL;
340
341 // Register the frame window class.
342 wndclass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE + 1);
343 wndclass.lpszClassName = wxFrameClassName;
344 wndclass.style = styleNormal;
345
346 if ( !RegisterClass(&wndclass) )
347 {
348 wxLogLastError(wxT("RegisterClass(frame)"));
349
350 return FALSE;
351 }
352
353 // "no redraw" frame
354 wndclass.lpszClassName = wxFrameClassNameNoRedraw;
355 wndclass.style = styleNoRedraw;
356
357 if ( !RegisterClass(&wndclass) )
358 {
359 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
360
361 return FALSE;
362 }
363
364 // Register the MDI frame window class.
365 wndclass.hbrBackground = (HBRUSH)NULL; // paint MDI frame ourselves
366 wndclass.lpszClassName = wxMDIFrameClassName;
367 wndclass.style = styleNormal;
368
369 if ( !RegisterClass(&wndclass) )
370 {
371 wxLogLastError(wxT("RegisterClass(MDI parent)"));
372
373 return FALSE;
374 }
375
376 // "no redraw" MDI frame
377 wndclass.lpszClassName = wxMDIFrameClassNameNoRedraw;
378 wndclass.style = styleNoRedraw;
379
380 if ( !RegisterClass(&wndclass) )
381 {
382 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
383
384 return FALSE;
385 }
386
387 // Register the MDI child frame window class.
388 wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
389 wndclass.lpszClassName = wxMDIChildFrameClassName;
390 wndclass.style = styleNormal;
391
392 if ( !RegisterClass(&wndclass) )
393 {
394 wxLogLastError(wxT("RegisterClass(MDI child)"));
395
396 return FALSE;
397 }
398
399 // "no redraw" MDI child frame
400 wndclass.lpszClassName = wxMDIChildFrameClassNameNoRedraw;
401 wndclass.style = styleNoRedraw;
402
403 if ( !RegisterClass(&wndclass) )
404 {
405 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
406
407 return FALSE;
408 }
409
410 // Register the panel window class.
411 wndclass.hbrBackground = (HBRUSH) GetStockObject( LTGRAY_BRUSH );
412 wndclass.lpszClassName = wxPanelClassName;
413 wndclass.style = styleNormal;
414
415 if ( !RegisterClass(&wndclass) )
416 {
417 wxLogLastError(wxT("RegisterClass(panel)"));
418
419 return FALSE;
420 }
421
422 // Register the no redraw panel window class.
423 wndclass.lpszClassName = wxPanelClassNameNR;
424 wndclass.style = styleNoRedraw;
425
426 if ( !RegisterClass(&wndclass) )
427 {
428 wxLogLastError(wxT("RegisterClass(no redraw panel)"));
429
430 return FALSE;
431 }
432
433 // Register the canvas and textsubwindow class name
434 wndclass.hbrBackground = (HBRUSH)NULL;
435 wndclass.lpszClassName = wxCanvasClassName;
436
437 if ( !RegisterClass(&wndclass) )
438 {
439 wxLogLastError(wxT("RegisterClass(canvas)"));
440
441 return FALSE;
442 }
443
444 wndclass.lpszClassName = wxCanvasClassNameNR;
445 wndclass.style = styleNoRedraw;
446 if ( !RegisterClass(&wndclass) )
447 {
448 wxLogLastError(wxT("RegisterClass(no redraw canvas)"));
449
450 return FALSE;
451 }
452
453 return TRUE;
454 }
455
456 // ---------------------------------------------------------------------------
457 // Convert Windows to argc, argv style
458 // ---------------------------------------------------------------------------
459
460 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine)
461 {
462 wxStringList args;
463
464 wxString cmdLine(lpCmdLine);
465 int count = 0;
466
467 // Get application name
468 wxChar name[260]; // 260 is MAX_PATH value from windef.h
469 ::GetModuleFileName(wxhInstance, name, WXSIZEOF(name));
470
471 args.Add(name);
472 count++;
473
474 wxStrcpy(name, wxFileNameFromPath(name));
475 wxStripExtension(name);
476 wxTheApp->SetAppName(name);
477
478 // Break up string
479 // Treat strings enclosed in double-quotes as single arguments
480 int i = 0;
481 int len = cmdLine.Length();
482 while (i < len)
483 {
484 // Skip whitespace
485 while ((i < len) && wxIsspace(cmdLine.GetChar(i)))
486 i ++;
487
488 if (i < len)
489 {
490 if (cmdLine.GetChar(i) == wxT('"')) // We found the start of a string
491 {
492 i ++;
493 int first = i;
494 while ((i < len) && (cmdLine.GetChar(i) != wxT('"')))
495 i ++;
496
497 wxString arg(cmdLine.Mid(first, (i - first)));
498
499 args.Add(arg);
500 count ++;
501
502 if (i < len)
503 i ++; // Skip past 2nd quote
504 }
505 else // Unquoted argument
506 {
507 int first = i;
508 while ((i < len) && !wxIsspace(cmdLine.GetChar(i)))
509 i ++;
510
511 wxString arg(cmdLine.Mid(first, (i - first)));
512
513 args.Add(arg);
514 count ++;
515 }
516 }
517 }
518
519 wxTheApp->argv = new wxChar*[count + 1];
520 for (i = 0; i < count; i++)
521 {
522 wxString arg(args[i]);
523 wxTheApp->argv[i] = copystring((const wxChar*)arg);
524 }
525 wxTheApp->argv[count] = NULL; // argv[] is a NULL-terminated list
526 wxTheApp->argc = count;
527 }
528
529 //// Cleans up any wxWindows internal structures left lying around
530
531 void wxApp::CleanUp()
532 {
533 //// COMMON CLEANUP
534
535 #if wxUSE_LOG
536 // flush the logged messages if any and install a 'safer' log target: the
537 // default one (wxLogGui) can't be used after the resources are freed just
538 // below and the user suppliedo ne might be even more unsafe (using any
539 // wxWindows GUI function is unsafe starting from now)
540 wxLog::DontCreateOnDemand();
541
542 // this will flush the old messages if any
543 delete wxLog::SetActiveTarget(new wxLogStderr);
544 #endif // wxUSE_LOG
545
546 // One last chance for pending objects to be cleaned up
547 wxTheApp->DeletePendingObjects();
548
549 wxModule::CleanUpModules();
550
551 #if wxUSE_WX_RESOURCES
552 wxCleanUpResourceSystem();
553
554 // wxDefaultResourceTable->ClearTable();
555 #endif
556
557 wxDeleteStockObjects();
558
559 // Destroy all GDI lists, etc.
560 wxDeleteStockLists();
561
562 delete wxTheColourDatabase;
563 wxTheColourDatabase = NULL;
564
565 wxBitmap::CleanUpHandlers();
566
567 delete[] wxBuffer;
568 wxBuffer = NULL;
569
570 //// WINDOWS-SPECIFIC CLEANUP
571
572 #ifndef __WXMICROWIN__
573 wxSetKeyboardHook(FALSE);
574 #endif
575
576 #if wxUSE_PENWINDOWS
577 wxCleanUpPenWin();
578 #endif
579
580 if (wxSTD_FRAME_ICON)
581 DestroyIcon(wxSTD_FRAME_ICON);
582 if (wxSTD_MDICHILDFRAME_ICON)
583 DestroyIcon(wxSTD_MDICHILDFRAME_ICON);
584 if (wxSTD_MDIPARENTFRAME_ICON)
585 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON);
586
587 if (wxDEFAULT_FRAME_ICON)
588 DestroyIcon(wxDEFAULT_FRAME_ICON);
589 if (wxDEFAULT_MDICHILDFRAME_ICON)
590 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON);
591 if (wxDEFAULT_MDIPARENTFRAME_ICON)
592 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON);
593
594 if ( wxDisableButtonBrush )
595 ::DeleteObject( wxDisableButtonBrush );
596
597 #if wxUSE_OLE
598 ::OleUninitialize();
599 #endif
600
601 #if wxUSE_CTL3D
602 Ctl3dUnregister(wxhInstance);
603 #endif
604
605 if (wxWinHandleList)
606 delete wxWinHandleList;
607
608 // GL: I'm annoyed ... I don't know where to put this and I don't want to
609 // create a module for that as it's part of the core.
610 delete wxPendingEvents;
611
612 #if wxUSE_THREADS
613 delete wxPendingEventsLocker;
614 // If we don't do the following, we get an apparent memory leak
615 #if wxUSE_VALIDATORS
616 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
617 #endif // wxUSE_VALIDATORS
618 #endif // wxUSE_THREADS
619
620 wxClassInfo::CleanUpClasses();
621
622 delete wxTheApp;
623 wxTheApp = NULL;
624
625 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
626 // At this point we want to check if there are any memory
627 // blocks that aren't part of the wxDebugContext itself,
628 // as a special case. Then when dumping we need to ignore
629 // wxDebugContext, too.
630 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
631 {
632 wxLogMessage(wxT("There were memory leaks."));
633 wxDebugContext::Dump();
634 wxDebugContext::PrintStatistics();
635 }
636 // wxDebugContext::SetStream(NULL, NULL);
637 #endif
638
639 #if wxUSE_LOG
640 // do it as the very last thing because everything else can log messages
641 delete wxLog::SetActiveTarget(NULL);
642 #endif // wxUSE_LOG
643 }
644
645 //----------------------------------------------------------------------
646 // Entry point helpers, used by wxPython
647 //----------------------------------------------------------------------
648
649 int WXDLLEXPORT wxEntryStart( int WXUNUSED(argc), char** WXUNUSED(argv) )
650 {
651 return wxApp::Initialize();
652 }
653
654 int WXDLLEXPORT wxEntryInitGui()
655 {
656 return wxTheApp->OnInitGui();
657 }
658
659 void WXDLLEXPORT wxEntryCleanup()
660 {
661 wxApp::CleanUp();
662 }
663
664
665 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
666
667 // temporarily disable this warning which would be generated in release builds
668 // because of __try
669 #ifdef __VISUALC__
670 #pragma warning(disable: 4715) // not all control paths return a value
671 #endif // Visual C++
672
673 //----------------------------------------------------------------------
674 // Main wxWindows entry point
675 //----------------------------------------------------------------------
676 int wxEntry(WXHINSTANCE hInstance,
677 WXHINSTANCE WXUNUSED(hPrevInstance),
678 char *lpCmdLine,
679 int nCmdShow,
680 bool enterLoop)
681 {
682 // do check for memory leaks on program exit
683 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
684 // deallocated memory which may be used to simulate low-memory condition)
685 #ifndef __WXMICROWIN__
686 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
687 #endif
688
689 #ifdef __MWERKS__
690 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
691 // This seems to be necessary since there are 'rogue'
692 // objects present at this point (perhaps global objects?)
693 // Setting a checkpoint will ignore them as far as the
694 // memory checking facility is concerned.
695 // Of course you may argue that memory allocated in globals should be
696 // checked, but this is a reasonable compromise.
697 wxDebugContext::SetCheckpoint();
698 #endif
699 #endif
700
701 // take everything into a try-except block to be able to call
702 // OnFatalException() if necessary
703 #if wxUSE_ON_FATAL_EXCEPTION
704 __try {
705 #endif
706 wxhInstance = (HINSTANCE) hInstance;
707
708 if (!wxEntryStart(0,0))
709 return 0;
710
711 // create the application object or ensure that one already exists
712 if (!wxTheApp)
713 {
714 // The app may have declared a global application object, but we recommend
715 // the IMPLEMENT_APP macro is used instead, which sets an initializer
716 // function for delayed, dynamic app object construction.
717 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
718 wxT("No initializer - use IMPLEMENT_APP macro.") );
719
720 wxTheApp = (*wxApp::GetInitializerFunction()) ();
721 }
722
723 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
724
725 // save the WinMain() parameters
726 wxTheApp->ConvertToStandardCommandArgs(lpCmdLine);
727 wxTheApp->m_nCmdShow = nCmdShow;
728
729 // We really don't want timestamps by default, because it means
730 // we can't simply double-click on the error message and get to that
731 // line in the source. So VC++ at least, let's have a sensible default.
732 #ifdef __VISUALC__
733 wxLog::SetTimestamp(NULL);
734 #endif
735
736 int retValue = 0;
737
738 // it is common to create a modal dialog in OnInit() (to ask/notify the
739 // user about something) but it wouldn't work if we don't change the
740 // "exit on delete last frame" flag here as when this dialog is
741 // deleted, the app would terminate (it was the last top level window
742 // as the main frame wasn't created yet!), so disable this behaviour
743 // temproarily
744 bool exitOnLastFrameDelete = wxTheApp->GetExitOnFrameDelete();
745 wxTheApp->SetExitOnFrameDelete(FALSE);
746
747 // init the app
748 retValue = wxEntryInitGui() && wxTheApp->OnInit() ? 0 : -1;
749
750 // restore the old flag value
751 wxTheApp->SetExitOnFrameDelete(exitOnLastFrameDelete);
752
753 if ( retValue == 0 )
754 {
755 if ( enterLoop )
756 {
757 // run the main loop
758 retValue = wxTheApp->OnRun();
759 }
760 else
761 {
762 // we want to initialize, but not run or exit immediately.
763 return 1;
764 }
765 }
766 //else: app initialization failed, so we skipped OnRun()
767
768 wxWindow *topWindow = wxTheApp->GetTopWindow();
769 if ( topWindow )
770 {
771 // Forcibly delete the window.
772 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
773 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
774 {
775 topWindow->Close(TRUE);
776 wxTheApp->DeletePendingObjects();
777 }
778 else
779 {
780 delete topWindow;
781 wxTheApp->SetTopWindow(NULL);
782 }
783 }
784
785 wxTheApp->OnExit();
786
787 wxEntryCleanup();
788
789 return retValue;
790
791 #if wxUSE_ON_FATAL_EXCEPTION
792 }
793 __except ( gs_handleExceptions ? EXCEPTION_EXECUTE_HANDLER
794 : EXCEPTION_CONTINUE_SEARCH ) {
795 if ( wxTheApp )
796 {
797 // give the user a chance to do something special about this
798 wxTheApp->OnFatalException();
799 }
800
801 ::ExitProcess(3); // the same exit code as abort()
802
803 // NOTREACHED
804 }
805 #endif // wxUSE_ON_FATAL_EXCEPTION
806 }
807
808 // restore warning state
809 #ifdef __VISUALC__
810 #pragma warning(default: 4715) // not all control paths return a value
811 #endif // Visual C++
812
813 #else /* _WINDLL */
814
815 //----------------------------------------------------------------------
816 // Entry point for wxWindows + the App in a DLL
817 //----------------------------------------------------------------------
818
819 int wxEntry(WXHINSTANCE hInstance)
820 {
821 wxhInstance = (HINSTANCE) hInstance;
822 wxEntryStart(0, 0);
823
824 // The app may have declared a global application object, but we recommend
825 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
826 // for delayed, dynamic app object construction.
827 if (!wxTheApp)
828 {
829 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
830 "No initializer - use IMPLEMENT_APP macro." );
831
832 wxTheApp = (* wxApp::GetInitializerFunction()) ();
833 }
834
835 wxCHECK_MSG( wxTheApp, 0, "You have to define an instance of wxApp!" );
836
837 wxTheApp->argc = 0;
838 wxTheApp->argv = NULL;
839
840 wxEntryInitGui();
841
842 wxTheApp->OnInit();
843
844 wxWindow *topWindow = wxTheApp->GetTopWindow();
845 if ( topWindow && topWindow->GetHWND())
846 {
847 topWindow->Show(TRUE);
848 }
849
850 return 1;
851 }
852 #endif // _WINDLL
853
854 //// Static member initialization
855
856 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
857
858 wxApp::wxApp()
859 {
860 argc = 0;
861 argv = NULL;
862 m_printMode = wxPRINT_WINDOWS;
863 m_auto3D = TRUE;
864 }
865
866 wxApp::~wxApp()
867 {
868 // Delete command-line args
869 int i;
870 for (i = 0; i < argc; i++)
871 {
872 delete[] argv[i];
873 }
874 delete[] argv;
875 }
876
877 bool wxApp::Initialized()
878 {
879 #ifndef _WINDLL
880 if (GetTopWindow())
881 return TRUE;
882 else
883 return FALSE;
884 #else // Assume initialized if DLL (no way of telling)
885 return TRUE;
886 #endif
887 }
888
889 /*
890 * Get and process a message, returning FALSE if WM_QUIT
891 * received (and also set the flag telling the app to exit the main loop)
892 *
893 */
894 bool wxApp::DoMessage()
895 {
896 BOOL rc = ::GetMessage(&s_currentMsg, (HWND) NULL, 0, 0);
897 if ( rc == 0 )
898 {
899 // got WM_QUIT
900 m_keepGoing = FALSE;
901
902 return FALSE;
903 }
904 else if ( rc == -1 )
905 {
906 // should never happen, but let's test for it nevertheless
907 wxLogLastError(wxT("GetMessage"));
908 }
909 else
910 {
911 #if wxUSE_THREADS
912 wxASSERT_MSG( wxThread::IsMain(),
913 wxT("only the main thread can process Windows messages") );
914
915 static bool s_hadGuiLock = TRUE;
916 static wxMsgArray s_aSavedMessages;
917
918 // if a secondary thread owns is doing GUI calls, save all messages for
919 // later processing - we can't process them right now because it will
920 // lead to recursive library calls (and we're not reentrant)
921 if ( !wxGuiOwnedByMainThread() )
922 {
923 s_hadGuiLock = FALSE;
924
925 // leave out WM_COMMAND messages: too dangerous, sometimes
926 // the message will be processed twice
927 if ( !wxIsWaitingForThread() ||
928 s_currentMsg.message != WM_COMMAND )
929 {
930 s_aSavedMessages.Add(s_currentMsg);
931 }
932
933 return TRUE;
934 }
935 else
936 {
937 // have we just regained the GUI lock? if so, post all of the saved
938 // messages
939 //
940 // FIXME of course, it's not _exactly_ the same as processing the
941 // messages normally - expect some things to break...
942 if ( !s_hadGuiLock )
943 {
944 s_hadGuiLock = TRUE;
945
946 size_t count = s_aSavedMessages.Count();
947 for ( size_t n = 0; n < count; n++ )
948 {
949 MSG& msg = s_aSavedMessages[n];
950
951 if ( !ProcessMessage((WXMSG *)&msg) )
952 {
953 ::TranslateMessage(&msg);
954 ::DispatchMessage(&msg);
955 }
956 }
957
958 s_aSavedMessages.Empty();
959 }
960 }
961 #endif // wxUSE_THREADS
962
963 // Process the message
964 DoMessage((WXMSG *)&s_currentMsg);
965 }
966
967 return TRUE;
968 }
969
970 void wxApp::DoMessage(WXMSG *pMsg)
971 {
972 if ( !ProcessMessage(pMsg) )
973 {
974 ::TranslateMessage((MSG *)pMsg);
975 ::DispatchMessage((MSG *)pMsg);
976 }
977 }
978
979 /*
980 * Keep trying to process messages until WM_QUIT
981 * received.
982 *
983 * If there are messages to be processed, they will all be
984 * processed and OnIdle will not be called.
985 * When there are no more messages, OnIdle is called.
986 * If OnIdle requests more time,
987 * it will be repeatedly called so long as there are no pending messages.
988 * A 'feature' of this is that once OnIdle has decided that no more processing
989 * is required, then it won't get processing time until further messages
990 * are processed (it'll sit in DoMessage).
991 */
992
993 int wxApp::MainLoop()
994 {
995 m_keepGoing = TRUE;
996
997 while ( m_keepGoing )
998 {
999 #if wxUSE_THREADS
1000 wxMutexGuiLeaveOrEnter();
1001 #endif // wxUSE_THREADS
1002
1003 while ( !Pending() && ProcessIdle() )
1004 ;
1005
1006 // a message came or no more idle processing to do
1007 DoMessage();
1008 }
1009
1010 return s_currentMsg.wParam;
1011 }
1012
1013 // Returns TRUE if more time is needed.
1014 bool wxApp::ProcessIdle()
1015 {
1016 wxIdleEvent event;
1017 event.SetEventObject(this);
1018 ProcessEvent(event);
1019
1020 return event.MoreRequested();
1021 }
1022
1023 void wxApp::ExitMainLoop()
1024 {
1025 // VZ: why not ::PostQuitMessage()?
1026 m_keepGoing = FALSE;
1027 }
1028
1029 bool wxApp::Pending()
1030 {
1031 return ::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) != 0;
1032 }
1033
1034 void wxApp::Dispatch()
1035 {
1036 DoMessage();
1037 }
1038
1039 /*
1040 * Give all windows a chance to preprocess
1041 * the message. Some may have accelerator tables, or have
1042 * MDI complications.
1043 */
1044
1045 bool wxApp::ProcessMessage(WXMSG *wxmsg)
1046 {
1047 MSG *msg = (MSG *)wxmsg;
1048 HWND hWnd = msg->hwnd;
1049 wxWindow *wndThis = wxGetWindowFromHWND((WXHWND)hWnd);
1050
1051 #if wxUSE_TOOLTIPS
1052 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1053 // popup the tooltip bubbles
1054 if ( wndThis && (msg->message == WM_MOUSEMOVE) )
1055 {
1056 wxToolTip *tt = wndThis->GetToolTip();
1057 if ( tt )
1058 {
1059 tt->RelayEvent(wxmsg);
1060 }
1061 }
1062 #endif // wxUSE_TOOLTIPS
1063
1064 // Try translations first; find the youngest window with
1065 // a translation table.
1066 wxWindow *wnd;
1067
1068 bool pastTopLevelWindow = FALSE;
1069 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
1070 {
1071 if ( !pastTopLevelWindow && wnd->MSWTranslateMessage(wxmsg))
1072 return TRUE;
1073 if ( wnd->MSWProcessMessage(wxmsg) )
1074 return TRUE;
1075
1076 // stop at first top level window, i.e. don't try to process the key
1077 // strokes originating in a dialog using the accelerators of the parent
1078 // frame - this doesn't make much sense
1079 if ( wnd->IsTopLevel() )
1080 pastTopLevelWindow = TRUE;
1081 }
1082
1083 return FALSE;
1084 }
1085
1086 void wxApp::OnIdle(wxIdleEvent& event)
1087 {
1088 static bool s_inOnIdle = FALSE;
1089
1090 // Avoid recursion (via ProcessEvent default case)
1091 if ( s_inOnIdle )
1092 return;
1093
1094 s_inOnIdle = TRUE;
1095
1096 // If there are pending events, we must process them: pending events
1097 // are either events to the threads other than main or events posted
1098 // with wxPostEvent() functions
1099 // GRG: I have moved this here so that all pending events are processed
1100 // before starting to delete any objects. This behaves better (in
1101 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1102 // behaviour. Changed Feb/2000 before 2.1.14
1103 ProcessPendingEvents();
1104
1105 // 'Garbage' collection of windows deleted with Close().
1106 DeletePendingObjects();
1107
1108 #if wxUSE_LOG
1109 // flush the logged messages if any
1110 wxLog::FlushActive();
1111 #endif // wxUSE_LOG
1112
1113 // Send OnIdle events to all windows
1114 if ( SendIdleEvents() )
1115 {
1116 // SendIdleEvents() returns TRUE if at least one window requested more
1117 // idle events
1118 event.RequestMore(TRUE);
1119 }
1120
1121 s_inOnIdle = FALSE;
1122 }
1123
1124 // Send idle event to all top-level windows
1125 bool wxApp::SendIdleEvents()
1126 {
1127 bool needMore = FALSE;
1128
1129 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
1130 while (node)
1131 {
1132 wxWindow* win = node->GetData();
1133 if (SendIdleEvents(win))
1134 needMore = TRUE;
1135 node = node->GetNext();
1136 }
1137
1138 return needMore;
1139 }
1140
1141 // Send idle event to window and all subwindows
1142 bool wxApp::SendIdleEvents(wxWindow* win)
1143 {
1144 bool needMore = FALSE;
1145
1146 wxIdleEvent event;
1147 event.SetEventObject(win);
1148 win->GetEventHandler()->ProcessEvent(event);
1149
1150 if (event.MoreRequested())
1151 needMore = TRUE;
1152
1153 wxNode* node = win->GetChildren().First();
1154 while (node)
1155 {
1156 wxWindow* win = (wxWindow*) node->Data();
1157 if (SendIdleEvents(win))
1158 needMore = TRUE;
1159
1160 node = node->Next();
1161 }
1162 return needMore;
1163 }
1164
1165 void wxApp::DeletePendingObjects()
1166 {
1167 wxNode *node = wxPendingDelete.First();
1168 while (node)
1169 {
1170 wxObject *obj = (wxObject *)node->Data();
1171
1172 delete obj;
1173
1174 if (wxPendingDelete.Member(obj))
1175 delete node;
1176
1177 // Deleting one object may have deleted other pending
1178 // objects, so start from beginning of list again.
1179 node = wxPendingDelete.First();
1180 }
1181 }
1182
1183 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1184 {
1185 if (GetTopWindow())
1186 GetTopWindow()->Close(TRUE);
1187 }
1188
1189 // Default behaviour: close the application with prompts. The
1190 // user can veto the close, and therefore the end session.
1191 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1192 {
1193 if (GetTopWindow())
1194 {
1195 if (!GetTopWindow()->Close(!event.CanVeto()))
1196 event.Veto(TRUE);
1197 }
1198 }
1199
1200 /* static */
1201 int wxApp::GetComCtl32Version()
1202 {
1203 #ifdef __WXMICROWIN__
1204 return 0;
1205 #else
1206 // cache the result
1207 static int s_verComCtl32 = -1;
1208
1209 wxCRIT_SECT_DECLARE(csComCtl32);
1210 wxCRIT_SECT_LOCKER(lock, csComCtl32);
1211
1212 if ( s_verComCtl32 == -1 )
1213 {
1214 // initally assume no comctl32.dll at all
1215 s_verComCtl32 = 0;
1216
1217 // do we have it?
1218 HMODULE hModuleComCtl32 = ::GetModuleHandle(wxT("COMCTL32"));
1219
1220 // if so, then we can check for the version
1221 if ( hModuleComCtl32 )
1222 {
1223 // try to use DllGetVersion() if available in _headers_
1224 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1225 DLLGETVERSIONPROC pfnDllGetVersion = (DLLGETVERSIONPROC)
1226 ::GetProcAddress(hModuleComCtl32, "DllGetVersion");
1227 if ( pfnDllGetVersion )
1228 {
1229 DLLVERSIONINFO dvi;
1230 dvi.cbSize = sizeof(dvi);
1231
1232 HRESULT hr = (*pfnDllGetVersion)(&dvi);
1233 if ( FAILED(hr) )
1234 {
1235 wxLogApiError(_T("DllGetVersion"), hr);
1236 }
1237 else
1238 {
1239 // this is incompatible with _WIN32_IE values, but
1240 // compatible with the other values returned by
1241 // GetComCtl32Version()
1242 s_verComCtl32 = 100*dvi.dwMajorVersion +
1243 dvi.dwMinorVersion;
1244 }
1245 }
1246 #endif
1247 // DllGetVersion() unavailable either during compile or
1248 // run-time, try to guess the version otherwise
1249 if ( !s_verComCtl32 )
1250 {
1251 // InitCommonControlsEx is unique to 4.70 and later
1252 FARPROC theProc = ::GetProcAddress
1253 (
1254 hModuleComCtl32,
1255 "InitCommonControlsEx"
1256 );
1257
1258 if ( !theProc )
1259 {
1260 // not found, must be 4.00
1261 s_verComCtl32 = 400;
1262 }
1263 else
1264 {
1265 // many symbols appeared in comctl32 4.71, could use
1266 // any of them except may be DllInstall
1267 theProc = ::GetProcAddress
1268 (
1269 hModuleComCtl32,
1270 "InitializeFlatSB"
1271 );
1272 if ( !theProc )
1273 {
1274 // not found, must be 4.70
1275 s_verComCtl32 = 470;
1276 }
1277 else
1278 {
1279 // found, must be 4.71
1280 s_verComCtl32 = 471;
1281 }
1282 }
1283 }
1284 }
1285 }
1286
1287 return s_verComCtl32;
1288 #endif
1289 }
1290
1291 void wxExit()
1292 {
1293 wxLogError(_("Fatal error: exiting"));
1294
1295 wxApp::CleanUp();
1296 exit(0);
1297 }
1298
1299 // Yield to incoming messages
1300
1301 static bool gs_inYield = FALSE;
1302
1303 bool wxYield()
1304 {
1305 // disable log flushing from here because a call to wxYield() shouldn't
1306 // normally result in message boxes popping up &c
1307 wxLog::Suspend();
1308
1309 #ifdef __WXDEBUG__
1310 if (gs_inYield)
1311 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1312 #endif
1313
1314 gs_inYield = TRUE;
1315
1316 // we don't want to process WM_QUIT from here - it should be processed in
1317 // the main event loop in order to stop it
1318 MSG msg;
1319 while ( PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE) &&
1320 msg.message != WM_QUIT )
1321 {
1322 #if wxUSE_THREADS
1323 wxMutexGuiLeaveOrEnter();
1324 #endif // wxUSE_THREADS
1325
1326 if ( !wxTheApp->DoMessage() )
1327 break;
1328 }
1329
1330 // If they are pending events, we must process them.
1331 if (wxTheApp)
1332 wxTheApp->ProcessPendingEvents();
1333
1334 // let the logs be flashed again
1335 wxLog::Resume();
1336
1337 gs_inYield = FALSE;
1338
1339 return TRUE;
1340 }
1341
1342 // Yield to incoming messages; but fail silently if recursion is detected.
1343 bool wxYieldIfNeeded()
1344 {
1345 if (gs_inYield)
1346 return FALSE;
1347
1348 return wxYield();
1349 }
1350
1351 bool wxHandleFatalExceptions(bool doit)
1352 {
1353 #if wxUSE_ON_FATAL_EXCEPTION
1354 // assume this can only be called from the main thread
1355 gs_handleExceptions = doit;
1356
1357 return TRUE;
1358 #else
1359 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to sue this function"));
1360
1361 (void)doit;
1362 return FALSE;
1363 #endif
1364 }
1365
1366 //-----------------------------------------------------------------------------
1367 // wxWakeUpIdle
1368 //-----------------------------------------------------------------------------
1369
1370 void wxWakeUpIdle()
1371 {
1372 // Send the top window a dummy message so idle handler processing will
1373 // start up again. Doing it this way ensures that the idle handler
1374 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1375 // the same for the main app thread only)
1376 wxWindow *topWindow = wxTheApp->GetTopWindow();
1377 if ( topWindow )
1378 {
1379 if ( !::PostMessage(GetHwndOf(topWindow), WM_NULL, 0, 0) )
1380 {
1381 // should never happen
1382 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1383 }
1384 }
1385 }
1386
1387 //-----------------------------------------------------------------------------
1388
1389 wxIcon
1390 wxApp::GetStdIcon(int which) const
1391 {
1392 switch(which)
1393 {
1394 case wxICON_INFORMATION:
1395 return wxIcon("wxICON_INFO");
1396
1397 case wxICON_QUESTION:
1398 return wxIcon("wxICON_QUESTION");
1399
1400 case wxICON_EXCLAMATION:
1401 return wxIcon("wxICON_WARNING");
1402
1403 default:
1404 wxFAIL_MSG(wxT("requested non existent standard icon"));
1405 // still fall through
1406
1407 case wxICON_HAND:
1408 return wxIcon("wxICON_ERROR");
1409 }
1410 }
1411
1412 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1413 // if in a separate file. So include it here to ensure it's linked.
1414 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))
1415 #include "main.cpp"
1416 #endif