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