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