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