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