]> git.saurik.com Git - wxWidgets.git/blob - src/msw/app.cpp
wxButton::GetDefaultSize() fix
[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 #if defined(__GNUWIN32__) || defined(__SC__) || defined(__SALFORDC__)
73 #undef wxUSE_OLE
74
75 #define wxUSE_OLE 0
76 #endif // broken compilers
77
78 #if wxUSE_OLE
79 #include <ole2.h>
80 #endif
81
82 #include <string.h>
83 #include <ctype.h>
84
85 #if (defined(__WIN95__) && !defined(__GNUWIN32__)) || defined(__TWIN32__) || defined(wxUSE_NORLANDER_HEADERS)
86 #include <commctrl.h>
87 #endif
88
89 #include "wx/msw/msvcrt.h"
90
91 // ---------------------------------------------------------------------------
92 // global variables
93 // ---------------------------------------------------------------------------
94
95 extern wxChar *wxBuffer;
96 extern wxChar *wxOsVersion;
97 extern wxList *wxWinHandleList;
98 extern wxList WXDLLEXPORT wxPendingDelete;
99 #if wxUSE_THREADS
100 extern wxList *wxPendingEvents;
101 extern wxCriticalSection *wxPendingEventsLocker;
102 #endif
103 extern void wxSetKeyboardHook(bool doIt);
104 extern wxCursor *g_globalCursor;
105
106 HINSTANCE wxhInstance = 0;
107 MSG s_currentMsg;
108 wxApp *wxTheApp = NULL;
109
110 // FIXME why not const? and not static?
111
112 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
113 // with NR suffix - wxWindow::MSWCreate() supposes this
114 wxChar wxFrameClassName[] = _T("wxFrameClass");
115 wxChar wxFrameClassNameNoRedraw[] = _T("wxFrameClassNR");
116 wxChar wxMDIFrameClassName[] = _T("wxMDIFrameClass");
117 wxChar wxMDIFrameClassNameNoRedraw[] = _T("wxMDIFrameClassNR");
118 wxChar wxMDIChildFrameClassName[] = _T("wxMDIChildFrameClass");
119 wxChar wxMDIChildFrameClassNameNoRedraw[] = _T("wxMDIChildFrameClassNR");
120 wxChar wxPanelClassName[] = _T("wxPanelClass");
121 wxChar wxCanvasClassName[] = _T("wxCanvasClass");
122
123 HICON wxSTD_FRAME_ICON = (HICON) NULL;
124 HICON wxSTD_MDICHILDFRAME_ICON = (HICON) NULL;
125 HICON wxSTD_MDIPARENTFRAME_ICON = (HICON) NULL;
126
127 HICON wxDEFAULT_FRAME_ICON = (HICON) NULL;
128 HICON wxDEFAULT_MDICHILDFRAME_ICON = (HICON) NULL;
129 HICON wxDEFAULT_MDIPARENTFRAME_ICON = (HICON) NULL;
130
131 HBRUSH wxDisableButtonBrush = (HBRUSH) 0;
132
133 LRESULT APIENTRY wxWndProc(HWND, UINT, WPARAM, LPARAM);
134
135 #if defined(__WIN95__) && !defined(__TWIN32__)
136 #define wxUSE_RICHEDIT 1
137 #else
138 #define wxUSE_RICHEDIT 0
139 #endif
140
141 #if wxUSE_RICHEDIT
142 static HINSTANCE gs_hRichEdit = (HINSTANCE) NULL;
143 #endif
144
145 // ===========================================================================
146 // implementation
147 // ===========================================================================
148
149 // ---------------------------------------------------------------------------
150 // wxApp
151 // ---------------------------------------------------------------------------
152
153 #if !USE_SHARED_LIBRARY
154 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
155
156 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
157 EVT_IDLE(wxApp::OnIdle)
158 EVT_END_SESSION(wxApp::OnEndSession)
159 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
160 END_EVENT_TABLE()
161 #endif
162
163 //// Initialize
164 bool wxApp::Initialize()
165 {
166 // Some people may wish to use this, but
167 // probably it shouldn't be here by default.
168 #ifdef __WXDEBUG__
169 // wxRedirectIOToConsole();
170 #endif
171
172 wxBuffer = new wxChar[1500]; // FIXME
173
174 wxClassInfo::InitializeClasses();
175
176 #if wxUSE_RESOURCES
177 wxGetResource(_T("wxWindows"), _T("OsVersion"), &wxOsVersion);
178 #endif
179
180 // I'm annoyed ... I don't know where to put this and I don't want to
181 // create a module for that as it's part of the core.
182 #if wxUSE_THREADS
183 wxPendingEvents = new wxList();
184 wxPendingEventsLocker = new wxCriticalSection();
185 #endif
186
187 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
188 wxTheColourDatabase->Initialize();
189
190 wxInitializeStockLists();
191 wxInitializeStockObjects();
192
193 #if wxUSE_WX_RESOURCES
194 wxInitializeResourceSystem();
195 #endif
196
197 wxBitmap::InitStandardHandlers();
198
199 #if defined(__WIN95__)
200 InitCommonControls();
201
202 #if wxUSE_RICHEDIT
203 gs_hRichEdit = LoadLibrary(_T("RICHED32.DLL"));
204
205 if (gs_hRichEdit == (HINSTANCE) NULL)
206 {
207 wxLogError(_("Could not initialise Rich Edit DLL"));
208 }
209 #endif // wxUSE_RICHEDIT
210
211 #endif // __WIN95__
212
213 #if wxUSE_OLE
214
215 #ifdef __WIN16__
216 // for OLE, enlarge message queue to be as large as possible
217 int iMsg = 96;
218 while (!SetMessageQueue(iMsg) && (iMsg -= 8))
219 ;
220 #endif // Win16
221
222 // we need to initialize OLE library
223 if ( FAILED(::OleInitialize(NULL)) )
224 wxLogError(_("Cannot initialize OLE"));
225 #endif // wxUSE_OLE
226
227 #if wxUSE_CTL3D
228 if (!Ctl3dRegister(wxhInstance))
229 wxLogError(_T("Cannot register CTL3D"));
230
231 Ctl3dAutoSubclass(wxhInstance);
232 #endif
233
234 g_globalCursor = new wxCursor;
235
236 wxSTD_FRAME_ICON = LoadIcon(wxhInstance, _T("wxSTD_FRAME"));
237 wxSTD_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, _T("wxSTD_MDIPARENTFRAME"));
238 wxSTD_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, _T("wxSTD_MDICHILDFRAME"));
239
240 wxDEFAULT_FRAME_ICON = LoadIcon(wxhInstance, _T("wxDEFAULT_FRAME"));
241 wxDEFAULT_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, _T("wxDEFAULT_MDIPARENTFRAME"));
242 wxDEFAULT_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, _T("wxDEFAULT_MDICHILDFRAME"));
243
244 RegisterWindowClasses();
245
246 // Create the brush for disabling bitmap buttons
247
248 LOGBRUSH lb;
249 lb.lbStyle = BS_PATTERN;
250 lb.lbHatch = (int)LoadBitmap( wxhInstance, _T("wxDISABLE_BUTTON_BITMAP") );
251 if ( lb.lbHatch )
252 {
253 wxDisableButtonBrush = ::CreateBrushIndirect( & lb );
254 ::DeleteObject( (HGDIOBJ)lb.lbHatch );
255 }
256 //else: wxWindows resources are probably not linked in
257
258 #if wxUSE_PENWINDOWS
259 wxRegisterPenWin();
260 #endif
261
262 wxWinHandleList = new wxList(wxKEY_INTEGER);
263
264 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
265 // PLEASE DO NOT ALTER THIS.
266 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
267 extern char wxDummyChar;
268 if (wxDummyChar) wxDummyChar++;
269 #endif
270
271 wxSetKeyboardHook(TRUE);
272
273 wxModule::RegisterModules();
274 if (!wxModule::InitializeModules())
275 return FALSE;
276 return TRUE;
277 }
278
279 // ---------------------------------------------------------------------------
280 // RegisterWindowClasses
281 // ---------------------------------------------------------------------------
282
283 bool wxApp::RegisterWindowClasses()
284 {
285 WNDCLASS wndclass;
286
287 // for each class we register one with CS_(V|H)REDRAW style and one
288 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
289 static const long styleNormal = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
290 static const long styleNoRedraw = CS_DBLCLKS;
291
292 // the fields which are common to all classes
293 wndclass.lpfnWndProc = (WNDPROC)wxWndProc;
294 wndclass.cbClsExtra = 0;
295 wndclass.cbWndExtra = sizeof( DWORD ); // VZ: what is this DWORD used for?
296 wndclass.hInstance = wxhInstance;
297 wndclass.hIcon = (HICON) NULL;
298 wndclass.hCursor = ::LoadCursor((HINSTANCE)NULL, IDC_ARROW);
299 wndclass.lpszMenuName = NULL;
300
301 // Register the frame window class.
302 wndclass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE + 1);
303 wndclass.style = styleNormal;
304 wndclass.lpszClassName = wxFrameClassName;
305
306 if ( !RegisterClass(&wndclass) )
307 {
308 wxLogLastError("RegisterClass(frame)");
309
310 return FALSE;
311 }
312
313 // "no redraw" frame
314 wndclass.lpszClassName = wxFrameClassNameNoRedraw;
315 wndclass.style = styleNoRedraw;
316
317 if ( !RegisterClass(&wndclass) )
318 {
319 wxLogLastError("RegisterClass(no redraw frame)");
320
321 return FALSE;
322 }
323
324 // Register the MDI frame window class.
325 wndclass.hbrBackground = (HBRUSH)NULL; // paint MDI frame ourselves
326 wndclass.lpszClassName = wxMDIFrameClassNameNoRedraw;
327
328 if ( !RegisterClass(&wndclass) )
329 {
330 wxLogLastError("RegisterClass(MDI parent)");
331
332 return FALSE;
333 }
334
335 // "no redraw" MDI frame
336 wndclass.lpszClassName = wxMDIFrameClassName;
337 wndclass.style = styleNoRedraw;
338
339 if ( !RegisterClass(&wndclass) )
340 {
341 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
342
343 return FALSE;
344 }
345
346 // Register the MDI child frame window class.
347 wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
348 wndclass.lpszClassName = wxMDIChildFrameClassName;
349
350 if ( !RegisterClass(&wndclass) )
351 {
352 wxLogLastError("RegisterClass(MDI child)");
353
354 return FALSE;
355 }
356
357 // "no redraw" MDI child frame
358 wndclass.lpszClassName = wxMDIChildFrameClassNameNoRedraw;
359 wndclass.style = styleNoRedraw;
360
361 if ( !RegisterClass(&wndclass) )
362 {
363 wxLogLastError("RegisterClass(no redraw MDI child)");
364
365 return FALSE;
366 }
367
368 // Register the panel window class.
369 wndclass.hbrBackground = (HBRUSH) GetStockObject( LTGRAY_BRUSH );
370 wndclass.lpszClassName = wxPanelClassName;
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) == _T('"')) // We found the start of a string
428 {
429 i ++;
430 int first = i;
431 while ((i < len) && (cmdLine.GetChar(i) != _T('"')))
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 #if wxUSE_THREADS
562 delete wxPendingEvents;
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(_T("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 _T("No initializer - use IMPLEMENT_APP macro.") );
638
639 wxTheApp = (*wxApp::GetInitializerFunction()) ();
640 }
641
642 wxCHECK_MSG( wxTheApp, 0, _T("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 _T("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 #if wxUSE_THREADS
928 void wxApp::ProcessPendingEvents()
929 {
930 wxNode *node = wxPendingEvents->First();
931 wxCriticalSectionLocker locker(*wxPendingEventsLocker);
932
933 while (node)
934 {
935 wxEvtHandler *handler = (wxEvtHandler *)node->Data();
936
937 handler->ProcessPendingEvents();
938
939 delete node;
940 node = wxPendingEvents->First();
941 }
942 }
943 #endif
944
945
946 void wxApp::ExitMainLoop()
947 {
948 m_keepGoing = FALSE;
949 }
950
951 bool wxApp::Pending()
952 {
953 return (::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) != 0);
954 }
955
956 void wxApp::Dispatch()
957 {
958 DoMessage();
959 }
960
961 /*
962 * Give all windows a chance to preprocess
963 * the message. Some may have accelerator tables, or have
964 * MDI complications.
965 */
966
967 bool wxApp::ProcessMessage(WXMSG *wxmsg)
968 {
969 MSG *msg = (MSG *)wxmsg;
970 HWND hWnd = msg->hwnd;
971 wxWindow *wndThis = wxFindWinFromHandle((WXHWND)hWnd), *wnd;
972
973 // for some composite controls (like a combobox), wndThis might be NULL
974 // because the subcontrol is not a wxWindow, but only the control itself
975 // is - try to catch this case
976 while ( hWnd && !wndThis )
977 {
978 hWnd = ::GetParent(hWnd);
979 wndThis = wxFindWinFromHandle((WXHWND)hWnd);
980 }
981
982 // Try translations first; find the youngest window with
983 // a translation table.
984 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
985 {
986 if ( wnd->MSWTranslateMessage(wxmsg) )
987 return TRUE;
988 }
989
990 // Anyone for a non-translation message? Try youngest descendants first.
991 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
992 {
993 if ( wnd->MSWProcessMessage(wxmsg) )
994 return TRUE;
995 }
996
997 return FALSE;
998 }
999
1000 void wxApp::OnIdle(wxIdleEvent& event)
1001 {
1002 static bool s_inOnIdle = FALSE;
1003
1004 // Avoid recursion (via ProcessEvent default case)
1005 if ( s_inOnIdle )
1006 return;
1007
1008 s_inOnIdle = TRUE;
1009
1010 // 'Garbage' collection of windows deleted with Close().
1011 DeletePendingObjects();
1012
1013 #if wxUSE_LOG
1014 // flush the logged messages if any
1015 wxLog *pLog = wxLog::GetActiveTarget();
1016 if ( pLog != NULL && pLog->HasPendingMessages() )
1017 pLog->Flush();
1018 #endif // wxUSE_LOG
1019
1020 // Send OnIdle events to all windows
1021 if ( SendIdleEvents() )
1022 {
1023 // SendIdleEvents() returns TRUE if at least one window requested more
1024 // idle events
1025 event.RequestMore(TRUE);
1026 }
1027
1028 // If they are pending events, we must process them.
1029 #if wxUSE_THREADS
1030 ProcessPendingEvents();
1031 #endif
1032 s_inOnIdle = FALSE;
1033 }
1034
1035 // Send idle event to all top-level windows
1036 bool wxApp::SendIdleEvents()
1037 {
1038 bool needMore = FALSE;
1039
1040 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
1041 while (node)
1042 {
1043 wxWindow* win = node->GetData();
1044 if (SendIdleEvents(win))
1045 needMore = TRUE;
1046 node = node->GetNext();
1047 }
1048
1049 return needMore;
1050 }
1051
1052 // Send idle event to window and all subwindows
1053 bool wxApp::SendIdleEvents(wxWindow* win)
1054 {
1055 bool needMore = FALSE;
1056
1057 wxIdleEvent event;
1058 event.SetEventObject(win);
1059 win->GetEventHandler()->ProcessEvent(event);
1060
1061 if (event.MoreRequested())
1062 needMore = TRUE;
1063
1064 wxNode* node = win->GetChildren().First();
1065 while (node)
1066 {
1067 wxWindow* win = (wxWindow*) node->Data();
1068 if (SendIdleEvents(win))
1069 needMore = TRUE;
1070
1071 node = node->Next();
1072 }
1073 return needMore;
1074 }
1075
1076 void wxApp::DeletePendingObjects()
1077 {
1078 wxNode *node = wxPendingDelete.First();
1079 while (node)
1080 {
1081 wxObject *obj = (wxObject *)node->Data();
1082
1083 delete obj;
1084
1085 if (wxPendingDelete.Member(obj))
1086 delete node;
1087
1088 // Deleting one object may have deleted other pending
1089 // objects, so start from beginning of list again.
1090 node = wxPendingDelete.First();
1091 }
1092 }
1093
1094 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1095 {
1096 if (GetTopWindow())
1097 GetTopWindow()->Close(TRUE);
1098 }
1099
1100 // Default behaviour: close the application with prompts. The
1101 // user can veto the close, and therefore the end session.
1102 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1103 {
1104 if (GetTopWindow())
1105 {
1106 if (!GetTopWindow()->Close(!event.CanVeto()))
1107 event.Veto(TRUE);
1108 }
1109 }
1110
1111 int wxApp::GetComCtl32Version() const
1112 {
1113 // have we loaded COMCTL32 yet?
1114 HMODULE theModule = ::GetModuleHandle(_T("COMCTL32"));
1115 int version = 0;
1116
1117 // if so, then we can check for the version
1118 if (theModule)
1119 {
1120 // InitCommonControlsEx is unique to 4.7 and later
1121 FARPROC theProc = ::GetProcAddress(theModule, "InitCommonControlsEx");
1122
1123 if (! theProc)
1124 { // not found, must be 4.00
1125 version = 400;
1126 }
1127 else
1128 {
1129 // The following symbol are unique to 4.71
1130 // DllInstall
1131 // FlatSB_EnableScrollBar FlatSB_GetScrollInfo FlatSB_GetScrollPos
1132 // FlatSB_GetScrollProp FlatSB_GetScrollRange FlatSB_SetScrollInfo
1133 // FlatSB_SetScrollPos FlatSB_SetScrollProp FlatSB_SetScrollRange
1134 // FlatSB_ShowScrollBar
1135 // _DrawIndirectImageList _DuplicateImageList
1136 // InitializeFlatSB
1137 // UninitializeFlatSB
1138 // we could check for any of these - I chose DllInstall
1139 FARPROC theProc = ::GetProcAddress(theModule, "DllInstall");
1140 if (! theProc)
1141 {
1142 // not found, must be 4.70
1143 version = 470;
1144 }
1145 else
1146 { // found, must be 4.71
1147 version = 471;
1148 }
1149 }
1150 }
1151 return version;
1152 }
1153
1154 void wxExit()
1155 {
1156 wxLogError(_("Fatal error: exiting"));
1157
1158 wxApp::CleanUp();
1159 }
1160
1161 // Yield to incoming messages
1162 bool wxYield()
1163 {
1164 MSG msg;
1165 // We want to go back to the main message loop
1166 // if we see a WM_QUIT. (?)
1167 #ifdef __WXWINE__
1168 while (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_NOREMOVE) && msg.message != WM_QUIT)
1169 #else
1170 while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) && msg.message != WM_QUIT)
1171 #endif
1172 {
1173 if ( !wxTheApp->DoMessage() )
1174 break;
1175 }
1176 // If they are pending events, we must process them.
1177 #if wxUSE_THREADS
1178 wxTheApp->ProcessPendingEvents();
1179 #endif
1180
1181 return TRUE;
1182 }
1183
1184 wxIcon
1185 wxApp::GetStdIcon(int which) const
1186 {
1187 switch(which)
1188 {
1189 case wxICON_INFORMATION:
1190 return wxIcon("wxICON_INFO");
1191
1192 case wxICON_QUESTION:
1193 return wxIcon("wxICON_QUESTION");
1194
1195 case wxICON_EXCLAMATION:
1196 return wxIcon("wxICON_WARNING");
1197
1198 default:
1199 wxFAIL_MSG(_T("requested non existent standard icon"));
1200 // still fall through
1201
1202 case wxICON_HAND:
1203 return wxIcon("wxICON_ERROR");
1204 }
1205 }
1206
1207
1208 HINSTANCE wxGetInstance()
1209 {
1210 return wxhInstance;
1211 }
1212
1213 void wxSetInstance(HINSTANCE hInst)
1214 {
1215 wxhInstance = hInst;
1216 }
1217
1218 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1219 // if in a separate file. So include it here to ensure it's linked.
1220 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))
1221 #include "main.cpp"
1222 #endif