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