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