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