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