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