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