]> git.saurik.com Git - wxWidgets.git/blob - src/msw/app.cpp
a564b6033fd2a3c048bbed94a1d25fd72cd2fbd7
[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 #ifndef __VISUALC__
667 #undef wxUSE_ON_FATAL_EXCEPTION
668 #define wxUSE_ON_FATAL_EXCEPTION 0
669 #endif // VC++
670
671 #if wxUSE_ON_FATAL_EXCEPTION
672 __try {
673 #endif
674 wxhInstance = (HINSTANCE) hInstance;
675
676 if (!wxEntryStart(0,0))
677 return 0;
678
679 // create the application object or ensure that one already exists
680 if (!wxTheApp)
681 {
682 // The app may have declared a global application object, but we recommend
683 // the IMPLEMENT_APP macro is used instead, which sets an initializer
684 // function for delayed, dynamic app object construction.
685 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
686 wxT("No initializer - use IMPLEMENT_APP macro.") );
687
688 wxTheApp = (*wxApp::GetInitializerFunction()) ();
689 }
690
691 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
692
693 // save the WinMain() parameters
694 wxTheApp->ConvertToStandardCommandArgs(lpCmdLine);
695 wxTheApp->m_nCmdShow = nCmdShow;
696
697 // GUI-specific initialisation. In fact on Windows we don't have any,
698 // but this call is provided for compatibility across platforms.
699 wxEntryInitGui();
700
701 // We really don't want timestamps by default, because it means
702 // we can't simply double-click on the error message and get to that
703 // line in the source. So VC++ at least, let's have a sensible default.
704 #ifdef __VISUALC__
705 wxLog::SetTimestamp(NULL);
706 #endif
707
708 int retValue = 0;
709
710 if ( wxTheApp->OnInit() )
711 {
712 if ( enterLoop )
713 {
714 retValue = wxTheApp->OnRun();
715 }
716 else
717 // We want to initialize, but not run or exit immediately.
718 return 1;
719 }
720 //else: app initialization failed, so we skipped OnRun()
721
722 wxWindow *topWindow = wxTheApp->GetTopWindow();
723 if ( topWindow )
724 {
725 // Forcibly delete the window.
726 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
727 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
728 {
729 topWindow->Close(TRUE);
730 wxTheApp->DeletePendingObjects();
731 }
732 else
733 {
734 delete topWindow;
735 wxTheApp->SetTopWindow(NULL);
736 }
737 }
738
739 wxTheApp->OnExit();
740
741 wxEntryCleanup();
742
743 return retValue;
744
745 #if wxUSE_ON_FATAL_EXCEPTION
746 }
747 __except ( gs_handleExceptions ? EXCEPTION_EXECUTE_HANDLER
748 : EXCEPTION_CONTINUE_SEARCH ) {
749 if ( wxTheApp )
750 wxTheApp->OnFatalException();
751
752 // using wxLog would be unsafe here
753 ::MessageBox(NULL,
754 _("Unrecoverable program error detected: "
755 " the application will terminate."),
756 _("Fatal Error"),
757 MB_APPLMODAL | MB_ICONSTOP | MB_OK);
758
759 ::ExitProcess(3); // the same exit code as abort()
760
761 // NOTREACHED
762 }
763 #endif // wxUSE_ON_FATAL_EXCEPTION
764 }
765
766 // restore warning state
767 #ifdef __VISUALC__
768 #pragma warning(default: 4715) // not all control paths return a value
769 #endif // Visual C++
770
771 #else /* _WINDLL */
772
773 //----------------------------------------------------------------------
774 // Entry point for wxWindows + the App in a DLL
775 //----------------------------------------------------------------------
776
777 int wxEntry(WXHINSTANCE hInstance)
778 {
779 wxhInstance = (HINSTANCE) hInstance;
780 wxEntryStart(0, 0);
781
782 // The app may have declared a global application object, but we recommend
783 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
784 // for delayed, dynamic app object construction.
785 if (!wxTheApp)
786 {
787 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
788 "No initializer - use IMPLEMENT_APP macro." );
789
790 wxTheApp = (* wxApp::GetInitializerFunction()) ();
791 }
792
793 wxCHECK_MSG( wxTheApp, 0, "You have to define an instance of wxApp!" );
794
795 wxTheApp->argc = 0;
796 wxTheApp->argv = NULL;
797
798 wxEntryInitGui();
799
800 wxTheApp->OnInit();
801
802 wxWindow *topWindow = wxTheApp->GetTopWindow();
803 if ( topWindow && topWindow->GetHWND())
804 {
805 topWindow->Show(TRUE);
806 }
807
808 return 1;
809 }
810 #endif // _WINDLL
811
812 //// Static member initialization
813
814 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
815
816 wxApp::wxApp()
817 {
818 m_topWindow = NULL;
819 wxTheApp = this;
820 m_wantDebugOutput = TRUE;
821
822 argc = 0;
823 argv = NULL;
824 m_printMode = wxPRINT_WINDOWS;
825 m_exitOnFrameDelete = TRUE;
826 m_auto3D = TRUE;
827 }
828
829 wxApp::~wxApp()
830 {
831 // Delete command-line args
832 int i;
833 for (i = 0; i < argc; i++)
834 {
835 delete[] argv[i];
836 }
837 delete[] argv;
838 }
839
840 bool wxApp::Initialized()
841 {
842 #ifndef _WINDLL
843 if (GetTopWindow())
844 return TRUE;
845 else
846 return FALSE;
847 #else // Assume initialized if DLL (no way of telling)
848 return TRUE;
849 #endif
850 }
851
852 /*
853 * Get and process a message, returning FALSE if WM_QUIT
854 * received (and also set the flag telling the app to exit the main loop)
855 *
856 */
857 bool wxApp::DoMessage()
858 {
859 BOOL rc = ::GetMessage(&s_currentMsg, (HWND) NULL, 0, 0);
860 if ( rc == 0 )
861 {
862 // got WM_QUIT
863 m_keepGoing = FALSE;
864
865 return FALSE;
866 }
867 else if ( rc == -1 )
868 {
869 // should never happen, but let's test for it nevertheless
870 wxLogLastError("GetMessage");
871 }
872 else
873 {
874 #if wxUSE_THREADS
875 wxASSERT_MSG( wxThread::IsMain(),
876 wxT("only the main thread can process Windows messages") );
877
878 static bool s_hadGuiLock = TRUE;
879 static wxMsgArray s_aSavedMessages;
880
881 // if a secondary thread owns is doing GUI calls, save all messages for
882 // later processing - we can't process them right now because it will
883 // lead to recursive library calls (and we're not reentrant)
884 if ( !wxGuiOwnedByMainThread() )
885 {
886 s_hadGuiLock = FALSE;
887
888 // leave out WM_COMMAND messages: too dangerous, sometimes
889 // the message will be processed twice
890 if ( !wxIsWaitingForThread() ||
891 s_currentMsg.message != WM_COMMAND )
892 {
893 s_aSavedMessages.Add(s_currentMsg);
894 }
895
896 return TRUE;
897 }
898 else
899 {
900 // have we just regained the GUI lock? if so, post all of the saved
901 // messages
902 //
903 // FIXME of course, it's not _exactly_ the same as processing the
904 // messages normally - expect some things to break...
905 if ( !s_hadGuiLock )
906 {
907 s_hadGuiLock = TRUE;
908
909 size_t count = s_aSavedMessages.Count();
910 for ( size_t n = 0; n < count; n++ )
911 {
912 MSG& msg = s_aSavedMessages[n];
913
914 if ( !ProcessMessage((WXMSG *)&msg) )
915 {
916 ::TranslateMessage(&msg);
917 ::DispatchMessage(&msg);
918 }
919 }
920
921 s_aSavedMessages.Empty();
922 }
923 }
924 #endif // wxUSE_THREADS
925
926 // Process the message
927 if ( !ProcessMessage((WXMSG *)&s_currentMsg) )
928 {
929 ::TranslateMessage(&s_currentMsg);
930 ::DispatchMessage(&s_currentMsg);
931 }
932 }
933
934 return TRUE;
935 }
936
937 /*
938 * Keep trying to process messages until WM_QUIT
939 * received.
940 *
941 * If there are messages to be processed, they will all be
942 * processed and OnIdle will not be called.
943 * When there are no more messages, OnIdle is called.
944 * If OnIdle requests more time,
945 * it will be repeatedly called so long as there are no pending messages.
946 * A 'feature' of this is that once OnIdle has decided that no more processing
947 * is required, then it won't get processing time until further messages
948 * are processed (it'll sit in DoMessage).
949 */
950
951 int wxApp::MainLoop()
952 {
953 m_keepGoing = TRUE;
954
955 while ( m_keepGoing )
956 {
957 #if wxUSE_THREADS
958 wxMutexGuiLeaveOrEnter();
959 #endif // wxUSE_THREADS
960
961 while ( !Pending() && ProcessIdle() )
962 ;
963
964 // a message came or no more idle processing to do
965 DoMessage();
966 }
967
968 return s_currentMsg.wParam;
969 }
970
971 // Returns TRUE if more time is needed.
972 bool wxApp::ProcessIdle()
973 {
974 wxIdleEvent event;
975 event.SetEventObject(this);
976 ProcessEvent(event);
977
978 return event.MoreRequested();
979 }
980
981 void wxApp::ExitMainLoop()
982 {
983 // VZ: why not ::PostQuitMessage()?
984 m_keepGoing = FALSE;
985 }
986
987 bool wxApp::Pending()
988 {
989 return ::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) != 0;
990 }
991
992 void wxApp::Dispatch()
993 {
994 DoMessage();
995 }
996
997 /*
998 * Give all windows a chance to preprocess
999 * the message. Some may have accelerator tables, or have
1000 * MDI complications.
1001 */
1002
1003 bool wxApp::ProcessMessage(WXMSG *wxmsg)
1004 {
1005 MSG *msg = (MSG *)wxmsg;
1006 HWND hWnd = msg->hwnd;
1007 wxWindow *wndThis = wxGetWindowFromHWND((WXHWND)hWnd);
1008
1009 #if wxUSE_TOOLTIPS
1010 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1011 // popup the tooltip bubbles
1012 if ( wndThis && (msg->message == WM_MOUSEMOVE) )
1013 {
1014 wxToolTip *tt = wndThis->GetToolTip();
1015 if ( tt )
1016 {
1017 tt->RelayEvent(wxmsg);
1018 }
1019 }
1020 #endif // wxUSE_TOOLTIPS
1021
1022 // Try translations first; find the youngest window with
1023 // a translation table.
1024 wxWindow *wnd;
1025 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
1026 {
1027 if ( wnd->MSWTranslateMessage(wxmsg) )
1028 return TRUE;
1029 }
1030
1031 // Anyone for a non-translation message? Try youngest descendants first.
1032 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
1033 {
1034 if ( wnd->MSWProcessMessage(wxmsg) )
1035 return TRUE;
1036 }
1037
1038 return FALSE;
1039 }
1040
1041 void wxApp::OnIdle(wxIdleEvent& event)
1042 {
1043 static bool s_inOnIdle = FALSE;
1044
1045 // Avoid recursion (via ProcessEvent default case)
1046 if ( s_inOnIdle )
1047 return;
1048
1049 s_inOnIdle = TRUE;
1050
1051 // If there are pending events, we must process them: pending events
1052 // are either events to the threads other than main or events posted
1053 // with wxPostEvent() functions
1054 // GRG: I have moved this here so that all pending events are processed
1055 // before starting to delete any objects. This behaves better (in
1056 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1057 // behaviour. Changed Feb/2000 before 2.1.14
1058 ProcessPendingEvents();
1059
1060 // 'Garbage' collection of windows deleted with Close().
1061 DeletePendingObjects();
1062
1063 #if wxUSE_LOG
1064 // flush the logged messages if any
1065 wxLog::FlushActive();
1066 #endif // wxUSE_LOG
1067
1068 // Send OnIdle events to all windows
1069 if ( SendIdleEvents() )
1070 {
1071 // SendIdleEvents() returns TRUE if at least one window requested more
1072 // idle events
1073 event.RequestMore(TRUE);
1074 }
1075
1076 s_inOnIdle = FALSE;
1077 }
1078
1079 // Send idle event to all top-level windows
1080 bool wxApp::SendIdleEvents()
1081 {
1082 bool needMore = FALSE;
1083
1084 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
1085 while (node)
1086 {
1087 wxWindow* win = node->GetData();
1088 if (SendIdleEvents(win))
1089 needMore = TRUE;
1090 node = node->GetNext();
1091 }
1092
1093 return needMore;
1094 }
1095
1096 // Send idle event to window and all subwindows
1097 bool wxApp::SendIdleEvents(wxWindow* win)
1098 {
1099 bool needMore = FALSE;
1100
1101 wxIdleEvent event;
1102 event.SetEventObject(win);
1103 win->GetEventHandler()->ProcessEvent(event);
1104
1105 if (event.MoreRequested())
1106 needMore = TRUE;
1107
1108 wxNode* node = win->GetChildren().First();
1109 while (node)
1110 {
1111 wxWindow* win = (wxWindow*) node->Data();
1112 if (SendIdleEvents(win))
1113 needMore = TRUE;
1114
1115 node = node->Next();
1116 }
1117 return needMore;
1118 }
1119
1120 void wxApp::DeletePendingObjects()
1121 {
1122 wxNode *node = wxPendingDelete.First();
1123 while (node)
1124 {
1125 wxObject *obj = (wxObject *)node->Data();
1126
1127 delete obj;
1128
1129 if (wxPendingDelete.Member(obj))
1130 delete node;
1131
1132 // Deleting one object may have deleted other pending
1133 // objects, so start from beginning of list again.
1134 node = wxPendingDelete.First();
1135 }
1136 }
1137
1138 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1139 {
1140 if (GetTopWindow())
1141 GetTopWindow()->Close(TRUE);
1142 }
1143
1144 // Default behaviour: close the application with prompts. The
1145 // user can veto the close, and therefore the end session.
1146 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1147 {
1148 if (GetTopWindow())
1149 {
1150 if (!GetTopWindow()->Close(!event.CanVeto()))
1151 event.Veto(TRUE);
1152 }
1153 }
1154
1155 /* static */
1156 int wxApp::GetComCtl32Version()
1157 {
1158 // cache the result
1159 static int s_verComCtl32 = -1;
1160
1161 wxCRIT_SECT_DECLARE(csComCtl32);
1162 wxCRIT_SECT_LOCKER(lock, csComCtl32);
1163
1164 if ( s_verComCtl32 == -1 )
1165 {
1166 // initally assume no comctl32.dll at all
1167 s_verComCtl32 = 0;
1168
1169 // do we have it?
1170 HMODULE hModuleComCtl32 = ::GetModuleHandle(wxT("COMCTL32"));
1171
1172 // if so, then we can check for the version
1173 if ( hModuleComCtl32 )
1174 {
1175 // try to use DllGetVersion() if available in _headers_
1176 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1177 DLLGETVERSIONPROC pfnDllGetVersion = (DLLGETVERSIONPROC)
1178 ::GetProcAddress(hModuleComCtl32, _T("DllGetVersion"));
1179 if ( pfnDllGetVersion )
1180 {
1181 DLLVERSIONINFO dvi;
1182 dvi.cbSize = sizeof(dvi);
1183
1184 HRESULT hr = (*pfnDllGetVersion)(&dvi);
1185 if ( FAILED(hr) )
1186 {
1187 wxLogApiError(_T("DllGetVersion"), hr);
1188 }
1189 else
1190 {
1191 // this is incompatible with _WIN32_IE values, but
1192 // compatible with the other values returned by
1193 // GetComCtl32Version()
1194 s_verComCtl32 = 100*dvi.dwMajorVersion +
1195 dvi.dwMinorVersion;
1196 }
1197 }
1198 #endif
1199 // DllGetVersion() unavailable either during compile or
1200 // run-time, try to guess the version otherwise
1201 if ( !s_verComCtl32 )
1202 {
1203 // InitCommonControlsEx is unique to 4.70 and later
1204 FARPROC theProc = ::GetProcAddress
1205 (
1206 hModuleComCtl32,
1207 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
1208 "InitCommonControlsEx"
1209 #else
1210 _T("InitCommonControlsEx")
1211 #endif
1212 );
1213
1214 if ( !theProc )
1215 {
1216 // not found, must be 4.00
1217 s_verComCtl32 = 400;
1218 }
1219 else
1220 {
1221 // many symbols appeared in comctl32 4.71, could use
1222 // any of them except may be DllInstall
1223 theProc = ::GetProcAddress
1224 (
1225 hModuleComCtl32,
1226 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
1227 "InitializeFlatSB"
1228 #else
1229 _T("InitializeFlatSB")
1230 #endif
1231 );
1232 if ( !theProc )
1233 {
1234 // not found, must be 4.70
1235 s_verComCtl32 = 470;
1236 }
1237 else
1238 {
1239 // found, must be 4.71
1240 s_verComCtl32 = 471;
1241 }
1242 }
1243 }
1244 }
1245 }
1246
1247 return s_verComCtl32;
1248 }
1249
1250 void wxExit()
1251 {
1252 wxLogError(_("Fatal error: exiting"));
1253
1254 wxApp::CleanUp();
1255 exit(0);
1256 }
1257
1258 // Yield to incoming messages
1259 bool wxYield()
1260 {
1261 // disable log flushing from here because a call to wxYield() shouldn't
1262 // normally result in message boxes popping up &c
1263 wxLog::Suspend();
1264
1265 // we don't want to process WM_QUIT from here - it should be processed in
1266 // the main event loop in order to stop it
1267 MSG msg;
1268 while ( PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE) &&
1269 msg.message != WM_QUIT )
1270 {
1271 #if wxUSE_THREADS
1272 wxMutexGuiLeaveOrEnter();
1273 #endif // wxUSE_THREADS
1274
1275 if ( !wxTheApp->DoMessage() )
1276 break;
1277 }
1278
1279 // If they are pending events, we must process them.
1280 if (wxTheApp)
1281 wxTheApp->ProcessPendingEvents();
1282
1283 // let the logs be flashed again
1284 wxLog::Resume();
1285
1286 return TRUE;
1287 }
1288
1289 bool wxHandleFatalExceptions(bool doit)
1290 {
1291 #if wxUSE_ON_FATAL_EXCEPTION
1292 // assume this can only be called from the main thread
1293 gs_handleExceptions = doit;
1294
1295 return TRUE;
1296 #else
1297 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to sue this function"));
1298
1299 return FALSE;
1300 #endif
1301 }
1302
1303 //-----------------------------------------------------------------------------
1304 // wxWakeUpIdle
1305 //-----------------------------------------------------------------------------
1306
1307 void wxWakeUpIdle()
1308 {
1309 // Send the top window a dummy message so idle handler processing will
1310 // start up again. Doing it this way ensures that the idle handler
1311 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1312 // the same for the main app thread only)
1313 wxWindow *topWindow = wxTheApp->GetTopWindow();
1314 if ( topWindow )
1315 {
1316 if ( !::PostMessage(GetHwndOf(topWindow), WM_NULL, 0, 0) )
1317 {
1318 // should never happen
1319 wxLogLastError("PostMessage(WM_NULL)");
1320 }
1321 }
1322 }
1323
1324 //-----------------------------------------------------------------------------
1325
1326 wxIcon
1327 wxApp::GetStdIcon(int which) const
1328 {
1329 switch(which)
1330 {
1331 case wxICON_INFORMATION:
1332 return wxIcon("wxICON_INFO");
1333
1334 case wxICON_QUESTION:
1335 return wxIcon("wxICON_QUESTION");
1336
1337 case wxICON_EXCLAMATION:
1338 return wxIcon("wxICON_WARNING");
1339
1340 default:
1341 wxFAIL_MSG(wxT("requested non existent standard icon"));
1342 // still fall through
1343
1344 case wxICON_HAND:
1345 return wxIcon("wxICON_ERROR");
1346 }
1347 }
1348
1349 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1350 // if in a separate file. So include it here to ensure it's linked.
1351 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))
1352 #include "main.cpp"
1353 #endif