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