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