1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ===========================================================================
14 // ===========================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
21 #pragma implementation "app.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
27 #if defined(__BORLANDC__)
35 #include "wx/gdicmn.h"
38 #include "wx/cursor.h"
40 #include "wx/palette.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
51 #include "wx/module.h"
53 #include "wx/msw/private.h"
56 #include "wx/thread.h"
58 // define the array of MSG strutures
59 WX_DECLARE_OBJARRAY(MSG
, wxMsgArray
);
61 #include "wx/arrimpl.cpp"
63 WX_DEFINE_OBJARRAY(wxMsgArray
);
64 #endif // wxUSE_THREADS
66 #if wxUSE_WX_RESOURCES
67 #include "wx/resource.h"
71 #include "wx/tooltip.h"
72 #endif // wxUSE_TOOLTIPS
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__)
80 #endif // broken compilers
89 #if defined(__WIN95__) && !(defined(__GNUWIN32_OLD__) || defined(__TWIN32__))
93 #include "wx/msw/msvcrt.h"
95 // ----------------------------------------------------------------------------
96 // conditional compilation
97 // ----------------------------------------------------------------------------
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
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)
112 // minimal set of features by default
113 #define _WIN32_IE 0x0200
116 #if _WIN32_IE >= 0x0300
120 // ---------------------------------------------------------------------------
122 // ---------------------------------------------------------------------------
124 extern wxChar
*wxBuffer
;
125 extern wxChar
*wxOsVersion
;
126 extern wxList
*wxWinHandleList
;
127 extern wxList WXDLLEXPORT wxPendingDelete
;
128 extern void wxSetKeyboardHook(bool doIt
);
131 wxApp
*wxTheApp
= NULL
;
133 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
134 // with NR suffix - wxWindow::MSWCreate() supposes this
135 const wxChar
*wxFrameClassName
= wxT("wxFrameClass");
136 const wxChar
*wxFrameClassNameNoRedraw
= wxT("wxFrameClassNR");
137 const wxChar
*wxMDIFrameClassName
= wxT("wxMDIFrameClass");
138 const wxChar
*wxMDIFrameClassNameNoRedraw
= wxT("wxMDIFrameClassNR");
139 const wxChar
*wxMDIChildFrameClassName
= wxT("wxMDIChildFrameClass");
140 const wxChar
*wxMDIChildFrameClassNameNoRedraw
= wxT("wxMDIChildFrameClassNR");
141 const wxChar
*wxPanelClassName
= wxT("wxPanelClass");
142 const wxChar
*wxPanelClassNameNR
= wxT("wxPanelClassNR");
143 const wxChar
*wxCanvasClassName
= wxT("wxCanvasClass");
144 const wxChar
*wxCanvasClassNameNR
= wxT("wxCanvasClassNR");
146 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
147 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
148 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
150 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
151 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
152 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
154 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
156 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
158 #if wxUSE_ON_FATAL_EXCEPTION
159 static bool gs_handleExceptions
= FALSE
;
162 // ===========================================================================
164 // ===========================================================================
166 // ---------------------------------------------------------------------------
168 // ---------------------------------------------------------------------------
170 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
172 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
173 EVT_IDLE(wxApp::OnIdle
)
174 EVT_END_SESSION(wxApp::OnEndSession
)
175 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
179 bool wxApp::Initialize()
181 // Some people may wish to use this, but
182 // probably it shouldn't be here by default.
184 // wxRedirectIOToConsole();
187 wxBuffer
= new wxChar
[1500]; // FIXME
189 wxClassInfo::InitializeClasses();
192 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion
);
196 wxPendingEventsLocker
= new wxCriticalSection
;
199 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
200 wxTheColourDatabase
->Initialize();
202 wxInitializeStockLists();
203 wxInitializeStockObjects();
205 #if wxUSE_WX_RESOURCES
206 wxInitializeResourceSystem();
209 wxBitmap::InitStandardHandlers();
211 #if defined(__WIN95__)
212 InitCommonControls();
219 // for OLE, enlarge message queue to be as large as possible
221 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
224 // we need to initialize OLE library
225 if ( FAILED(::OleInitialize(NULL
)) )
226 wxLogError(_("Cannot initialize OLE"));
230 if (!Ctl3dRegister(wxhInstance
))
231 wxLogError(wxT("Cannot register CTL3D"));
233 Ctl3dAutoSubclass(wxhInstance
);
236 // VZ: these icons are not in wx.rc anyhow (but should they?)!
238 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
239 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
240 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
242 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
243 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
244 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
247 RegisterWindowClasses();
249 // Create the brush for disabling bitmap buttons
252 lb
.lbStyle
= BS_PATTERN
;
253 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
256 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
257 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
259 //else: wxWindows resources are probably not linked in
265 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
267 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
268 // PLEASE DO NOT ALTER THIS.
269 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
270 extern char wxDummyChar
;
271 if (wxDummyChar
) wxDummyChar
++;
274 wxSetKeyboardHook(TRUE
);
276 wxModule::RegisterModules();
277 if (!wxModule::InitializeModules())
282 // ---------------------------------------------------------------------------
283 // RegisterWindowClasses
284 // ---------------------------------------------------------------------------
286 // TODO we should only register classes really used by the app. For this it
287 // would be enough to just delay the class registration until an attempt
288 // to create a window of this class is made.
289 bool wxApp::RegisterWindowClasses()
293 // for each class we register one with CS_(V|H)REDRAW style and one
294 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
295 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
296 static const long styleNoRedraw
= CS_DBLCLKS
;
298 // the fields which are common to all classes
299 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
300 wndclass
.cbClsExtra
= 0;
301 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
302 wndclass
.hInstance
= wxhInstance
;
303 wndclass
.hIcon
= (HICON
) NULL
;
304 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
305 wndclass
.lpszMenuName
= NULL
;
307 // Register the frame window class.
308 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
309 wndclass
.lpszClassName
= wxFrameClassName
;
310 wndclass
.style
= styleNormal
;
312 if ( !RegisterClass(&wndclass
) )
314 wxLogLastError("RegisterClass(frame)");
320 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
321 wndclass
.style
= styleNoRedraw
;
323 if ( !RegisterClass(&wndclass
) )
325 wxLogLastError("RegisterClass(no redraw frame)");
330 // Register the MDI frame window class.
331 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
332 wndclass
.lpszClassName
= wxMDIFrameClassName
;
333 wndclass
.style
= styleNormal
;
335 if ( !RegisterClass(&wndclass
) )
337 wxLogLastError("RegisterClass(MDI parent)");
342 // "no redraw" MDI frame
343 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
344 wndclass
.style
= styleNoRedraw
;
346 if ( !RegisterClass(&wndclass
) )
348 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
353 // Register the MDI child frame window class.
354 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
355 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
356 wndclass
.style
= styleNormal
;
358 if ( !RegisterClass(&wndclass
) )
360 wxLogLastError("RegisterClass(MDI child)");
365 // "no redraw" MDI child frame
366 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
367 wndclass
.style
= styleNoRedraw
;
369 if ( !RegisterClass(&wndclass
) )
371 wxLogLastError("RegisterClass(no redraw MDI child)");
376 // Register the panel window class.
377 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
378 wndclass
.lpszClassName
= wxPanelClassName
;
379 wndclass
.style
= styleNormal
;
381 if ( !RegisterClass(&wndclass
) )
383 wxLogLastError("RegisterClass(panel)");
388 // Register the no redraw panel window class.
389 wndclass
.lpszClassName
= wxPanelClassNameNR
;
390 wndclass
.style
= styleNoRedraw
;
392 if ( !RegisterClass(&wndclass
) )
394 wxLogLastError("RegisterClass(no redraw panel)");
399 // Register the canvas and textsubwindow class name
400 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
401 wndclass
.lpszClassName
= wxCanvasClassName
;
403 if ( !RegisterClass(&wndclass
) )
405 wxLogLastError("RegisterClass(canvas)");
410 wndclass
.lpszClassName
= wxCanvasClassNameNR
;
411 wndclass
.style
= styleNoRedraw
;
412 if ( !RegisterClass(&wndclass
) )
414 wxLogLastError("RegisterClass(no redraw canvas)");
422 // ---------------------------------------------------------------------------
423 // Convert Windows to argc, argv style
424 // ---------------------------------------------------------------------------
426 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
430 wxString
cmdLine(lpCmdLine
);
433 // Get application name
434 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
435 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
440 wxStrcpy(name
, wxFileNameFromPath(name
));
441 wxStripExtension(name
);
442 wxTheApp
->SetAppName(name
);
445 // Treat strings enclosed in double-quotes as single arguments
447 int len
= cmdLine
.Length();
451 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
456 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
460 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
463 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
469 i
++; // Skip past 2nd quote
471 else // Unquoted argument
474 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
477 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
485 wxTheApp
->argv
= new wxChar
*[count
+ 1];
486 for (i
= 0; i
< count
; i
++)
488 wxString
arg(args
[i
]);
489 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
491 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
492 wxTheApp
->argc
= count
;
495 //// Cleans up any wxWindows internal structures left lying around
497 void wxApp::CleanUp()
502 // flush the logged messages if any and install a 'safer' log target: the
503 // default one (wxLogGui) can't be used after the resources are freed just
504 // below and the user suppliedo ne might be even more unsafe (using any
505 // wxWindows GUI function is unsafe starting from now)
506 wxLog::DontCreateOnDemand();
508 // this will flush the old messages if any
509 delete wxLog::SetActiveTarget(new wxLogStderr
);
512 // One last chance for pending objects to be cleaned up
513 wxTheApp
->DeletePendingObjects();
515 wxModule::CleanUpModules();
517 #if wxUSE_WX_RESOURCES
518 wxCleanUpResourceSystem();
520 // wxDefaultResourceTable->ClearTable();
523 wxDeleteStockObjects();
525 // Destroy all GDI lists, etc.
526 wxDeleteStockLists();
528 delete wxTheColourDatabase
;
529 wxTheColourDatabase
= NULL
;
531 wxBitmap::CleanUpHandlers();
536 //// WINDOWS-SPECIFIC CLEANUP
538 wxSetKeyboardHook(FALSE
);
544 if (wxSTD_FRAME_ICON
)
545 DestroyIcon(wxSTD_FRAME_ICON
);
546 if (wxSTD_MDICHILDFRAME_ICON
)
547 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
548 if (wxSTD_MDIPARENTFRAME_ICON
)
549 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
551 if (wxDEFAULT_FRAME_ICON
)
552 DestroyIcon(wxDEFAULT_FRAME_ICON
);
553 if (wxDEFAULT_MDICHILDFRAME_ICON
)
554 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
555 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
556 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
558 if ( wxDisableButtonBrush
)
559 ::DeleteObject( wxDisableButtonBrush
);
566 Ctl3dUnregister(wxhInstance
);
570 delete wxWinHandleList
;
572 // GL: I'm annoyed ... I don't know where to put this and I don't want to
573 // create a module for that as it's part of the core.
574 delete wxPendingEvents
;
576 delete wxPendingEventsLocker
;
577 // If we don't do the following, we get an apparent memory leak.
578 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
581 wxClassInfo::CleanUpClasses();
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)
593 wxLogMessage(wxT("There were memory leaks."));
594 wxDebugContext::Dump();
595 wxDebugContext::PrintStatistics();
597 // wxDebugContext::SetStream(NULL, NULL);
601 // do it as the very last thing because everything else can log messages
602 delete wxLog::SetActiveTarget(NULL
);
606 //----------------------------------------------------------------------
607 // Entry point helpers, used by wxPython
608 //----------------------------------------------------------------------
610 int WXDLLEXPORT
wxEntryStart( int WXUNUSED(argc
), char** WXUNUSED(argv
) )
612 return wxApp::Initialize();
615 int WXDLLEXPORT
wxEntryInitGui()
617 wxTheApp
->OnInitGui();
621 void WXDLLEXPORT
wxEntryCleanup()
627 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
629 // temporarily disable this warning which would be generated in release builds
632 #pragma warning(disable: 4715) // not all control paths return a value
635 //----------------------------------------------------------------------
636 // Main wxWindows entry point
637 //----------------------------------------------------------------------
638 int wxEntry(WXHINSTANCE hInstance
,
639 WXHINSTANCE
WXUNUSED(hPrevInstance
),
644 // do check for memory leaks on program exit
645 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
646 // deallocated memory which may be used to simulate low-memory condition)
647 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
649 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
650 // This seems to be necessary since there are 'rogue'
651 // objects present at this point (perhaps global objects?)
652 // Setting a checkpoint will ignore them as far as the
653 // memory checking facility is concerned.
654 // Of course you may argue that memory allocated in globals should be
655 // checked, but this is a reasonable compromise.
656 wxDebugContext::SetCheckpoint();
660 // take everything into a try-except block to be able to call
661 // OnFatalException() if necessary
663 // FIXME other compilers must support Win32 SEH (structured exception
664 // handling) too, just find the appropriate keyword in their docs!
665 // Please note that it's _not_ the same as C++ exceptions!
667 #undef wxUSE_ON_FATAL_EXCEPTION
668 #define wxUSE_ON_FATAL_EXCEPTION 0
671 #if wxUSE_ON_FATAL_EXCEPTION
674 wxhInstance
= (HINSTANCE
) hInstance
;
676 if (!wxEntryStart(0,0))
679 // create the application object or ensure that one already exists
682 // The app may have declared a global application object, but we recommend
683 // the IMPLEMENT_APP macro is used instead, which sets an initializer
684 // function for delayed, dynamic app object construction.
685 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
686 wxT("No initializer - use IMPLEMENT_APP macro.") );
688 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
691 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
693 // save the WinMain() parameters
694 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
695 wxTheApp
->m_nCmdShow
= nCmdShow
;
697 // GUI-specific initialisation. In fact on Windows we don't have any,
698 // but this call is provided for compatibility across platforms.
701 // We really don't want timestamps by default, because it means
702 // we can't simply double-click on the error message and get to that
703 // line in the source. So VC++ at least, let's have a sensible default.
705 wxLog::SetTimestamp(NULL
);
710 if ( wxTheApp
->OnInit() )
714 retValue
= wxTheApp
->OnRun();
717 // We want to initialize, but not run or exit immediately.
720 //else: app initialization failed, so we skipped OnRun()
722 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
725 // Forcibly delete the window.
726 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
727 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
729 topWindow
->Close(TRUE
);
730 wxTheApp
->DeletePendingObjects();
735 wxTheApp
->SetTopWindow(NULL
);
745 #if wxUSE_ON_FATAL_EXCEPTION
747 __except ( gs_handleExceptions
? EXCEPTION_EXECUTE_HANDLER
748 : EXCEPTION_CONTINUE_SEARCH
) {
750 wxTheApp
->OnFatalException();
752 // using wxLog would be unsafe here
754 _("Unrecoverable program error detected: "
755 " the application will terminate."),
757 MB_APPLMODAL
| MB_ICONSTOP
| MB_OK
);
759 ::ExitProcess(3); // the same exit code as abort()
763 #endif // wxUSE_ON_FATAL_EXCEPTION
766 // restore warning state
768 #pragma warning(default: 4715) // not all control paths return a value
773 //----------------------------------------------------------------------
774 // Entry point for wxWindows + the App in a DLL
775 //----------------------------------------------------------------------
777 int wxEntry(WXHINSTANCE hInstance
)
779 wxhInstance
= (HINSTANCE
) hInstance
;
782 // The app may have declared a global application object, but we recommend
783 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
784 // for delayed, dynamic app object construction.
787 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
788 "No initializer - use IMPLEMENT_APP macro." );
790 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
793 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
796 wxTheApp
->argv
= NULL
;
802 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
803 if ( topWindow
&& topWindow
->GetHWND())
805 topWindow
->Show(TRUE
);
812 //// Static member initialization
814 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
820 m_wantDebugOutput
= TRUE
;
824 m_printMode
= wxPRINT_WINDOWS
;
825 m_exitOnFrameDelete
= TRUE
;
831 // Delete command-line args
833 for (i
= 0; i
< argc
; i
++)
840 bool wxApp::Initialized()
847 #else // Assume initialized if DLL (no way of telling)
853 * Get and process a message, returning FALSE if WM_QUIT
854 * received (and also set the flag telling the app to exit the main loop)
857 bool wxApp::DoMessage()
859 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
869 // should never happen, but let's test for it nevertheless
870 wxLogLastError("GetMessage");
875 wxASSERT_MSG( wxThread::IsMain(),
876 wxT("only the main thread can process Windows messages") );
878 static bool s_hadGuiLock
= TRUE
;
879 static wxMsgArray s_aSavedMessages
;
881 // if a secondary thread owns is doing GUI calls, save all messages for
882 // later processing - we can't process them right now because it will
883 // lead to recursive library calls (and we're not reentrant)
884 if ( !wxGuiOwnedByMainThread() )
886 s_hadGuiLock
= FALSE
;
888 // leave out WM_COMMAND messages: too dangerous, sometimes
889 // the message will be processed twice
890 if ( !wxIsWaitingForThread() ||
891 s_currentMsg
.message
!= WM_COMMAND
)
893 s_aSavedMessages
.Add(s_currentMsg
);
900 // have we just regained the GUI lock? if so, post all of the saved
903 // FIXME of course, it's not _exactly_ the same as processing the
904 // messages normally - expect some things to break...
909 size_t count
= s_aSavedMessages
.Count();
910 for ( size_t n
= 0; n
< count
; n
++ )
912 MSG
& msg
= s_aSavedMessages
[n
];
914 if ( !ProcessMessage((WXMSG
*)&msg
) )
916 ::TranslateMessage(&msg
);
917 ::DispatchMessage(&msg
);
921 s_aSavedMessages
.Empty();
924 #endif // wxUSE_THREADS
926 // Process the message
927 if ( !ProcessMessage((WXMSG
*)&s_currentMsg
) )
929 ::TranslateMessage(&s_currentMsg
);
930 ::DispatchMessage(&s_currentMsg
);
938 * Keep trying to process messages until WM_QUIT
941 * If there are messages to be processed, they will all be
942 * processed and OnIdle will not be called.
943 * When there are no more messages, OnIdle is called.
944 * If OnIdle requests more time,
945 * it will be repeatedly called so long as there are no pending messages.
946 * A 'feature' of this is that once OnIdle has decided that no more processing
947 * is required, then it won't get processing time until further messages
948 * are processed (it'll sit in DoMessage).
951 int wxApp::MainLoop()
955 while ( m_keepGoing
)
958 wxMutexGuiLeaveOrEnter();
959 #endif // wxUSE_THREADS
961 while ( !Pending() && ProcessIdle() )
964 // a message came or no more idle processing to do
968 return s_currentMsg
.wParam
;
971 // Returns TRUE if more time is needed.
972 bool wxApp::ProcessIdle()
975 event
.SetEventObject(this);
978 return event
.MoreRequested();
981 void wxApp::ExitMainLoop()
983 // VZ: why not ::PostQuitMessage()?
987 bool wxApp::Pending()
989 return ::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0;
992 void wxApp::Dispatch()
998 * Give all windows a chance to preprocess
999 * the message. Some may have accelerator tables, or have
1000 * MDI complications.
1003 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
1005 MSG
*msg
= (MSG
*)wxmsg
;
1006 HWND hWnd
= msg
->hwnd
;
1007 wxWindow
*wndThis
= wxGetWindowFromHWND((WXHWND
)hWnd
);
1010 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1011 // popup the tooltip bubbles
1012 if ( wndThis
&& (msg
->message
== WM_MOUSEMOVE
) )
1014 wxToolTip
*tt
= wndThis
->GetToolTip();
1017 tt
->RelayEvent(wxmsg
);
1020 #endif // wxUSE_TOOLTIPS
1022 // Try translations first; find the youngest window with
1023 // a translation table.
1025 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1027 if ( wnd
->MSWTranslateMessage(wxmsg
) )
1031 // Anyone for a non-translation message? Try youngest descendants first.
1032 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
1034 if ( wnd
->MSWProcessMessage(wxmsg
) )
1041 void wxApp::OnIdle(wxIdleEvent
& event
)
1043 static bool s_inOnIdle
= FALSE
;
1045 // Avoid recursion (via ProcessEvent default case)
1051 // If there are pending events, we must process them: pending events
1052 // are either events to the threads other than main or events posted
1053 // with wxPostEvent() functions
1054 // GRG: I have moved this here so that all pending events are processed
1055 // before starting to delete any objects. This behaves better (in
1056 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1057 // behaviour. Changed Feb/2000 before 2.1.14
1058 ProcessPendingEvents();
1060 // 'Garbage' collection of windows deleted with Close().
1061 DeletePendingObjects();
1064 // flush the logged messages if any
1065 wxLog::FlushActive();
1068 // Send OnIdle events to all windows
1069 if ( SendIdleEvents() )
1071 // SendIdleEvents() returns TRUE if at least one window requested more
1073 event
.RequestMore(TRUE
);
1079 // Send idle event to all top-level windows
1080 bool wxApp::SendIdleEvents()
1082 bool needMore
= FALSE
;
1084 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1087 wxWindow
* win
= node
->GetData();
1088 if (SendIdleEvents(win
))
1090 node
= node
->GetNext();
1096 // Send idle event to window and all subwindows
1097 bool wxApp::SendIdleEvents(wxWindow
* win
)
1099 bool needMore
= FALSE
;
1102 event
.SetEventObject(win
);
1103 win
->GetEventHandler()->ProcessEvent(event
);
1105 if (event
.MoreRequested())
1108 wxNode
* node
= win
->GetChildren().First();
1111 wxWindow
* win
= (wxWindow
*) node
->Data();
1112 if (SendIdleEvents(win
))
1115 node
= node
->Next();
1120 void wxApp::DeletePendingObjects()
1122 wxNode
*node
= wxPendingDelete
.First();
1125 wxObject
*obj
= (wxObject
*)node
->Data();
1129 if (wxPendingDelete
.Member(obj
))
1132 // Deleting one object may have deleted other pending
1133 // objects, so start from beginning of list again.
1134 node
= wxPendingDelete
.First();
1138 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1141 GetTopWindow()->Close(TRUE
);
1144 // Default behaviour: close the application with prompts. The
1145 // user can veto the close, and therefore the end session.
1146 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1150 if (!GetTopWindow()->Close(!event
.CanVeto()))
1156 int wxApp::GetComCtl32Version()
1159 static int s_verComCtl32
= -1;
1161 wxCRIT_SECT_DECLARE(csComCtl32
);
1162 wxCRIT_SECT_LOCKER(lock
, csComCtl32
);
1164 if ( s_verComCtl32
== -1 )
1166 // initally assume no comctl32.dll at all
1170 HMODULE hModuleComCtl32
= ::GetModuleHandle(wxT("COMCTL32"));
1172 // if so, then we can check for the version
1173 if ( hModuleComCtl32
)
1175 // try to use DllGetVersion() if available in _headers_
1176 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1177 DLLGETVERSIONPROC pfnDllGetVersion
= (DLLGETVERSIONPROC
)
1178 ::GetProcAddress(hModuleComCtl32
, _T("DllGetVersion"));
1179 if ( pfnDllGetVersion
)
1182 dvi
.cbSize
= sizeof(dvi
);
1184 HRESULT hr
= (*pfnDllGetVersion
)(&dvi
);
1187 wxLogApiError(_T("DllGetVersion"), hr
);
1191 // this is incompatible with _WIN32_IE values, but
1192 // compatible with the other values returned by
1193 // GetComCtl32Version()
1194 s_verComCtl32
= 100*dvi
.dwMajorVersion
+
1199 // DllGetVersion() unavailable either during compile or
1200 // run-time, try to guess the version otherwise
1201 if ( !s_verComCtl32
)
1203 // InitCommonControlsEx is unique to 4.70 and later
1204 FARPROC theProc
= ::GetProcAddress
1207 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
1208 "InitCommonControlsEx"
1210 _T("InitCommonControlsEx")
1216 // not found, must be 4.00
1217 s_verComCtl32
= 400;
1221 // many symbols appeared in comctl32 4.71, could use
1222 // any of them except may be DllInstall
1223 theProc
= ::GetProcAddress
1226 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
1229 _T("InitializeFlatSB")
1234 // not found, must be 4.70
1235 s_verComCtl32
= 470;
1239 // found, must be 4.71
1240 s_verComCtl32
= 471;
1247 return s_verComCtl32
;
1252 wxLogError(_("Fatal error: exiting"));
1258 // Yield to incoming messages
1261 // disable log flushing from here because a call to wxYield() shouldn't
1262 // normally result in message boxes popping up &c
1265 // we don't want to process WM_QUIT from here - it should be processed in
1266 // the main event loop in order to stop it
1268 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1269 msg
.message
!= WM_QUIT
)
1272 wxMutexGuiLeaveOrEnter();
1273 #endif // wxUSE_THREADS
1275 if ( !wxTheApp
->DoMessage() )
1279 // If they are pending events, we must process them.
1281 wxTheApp
->ProcessPendingEvents();
1283 // let the logs be flashed again
1289 bool wxHandleFatalExceptions(bool doit
)
1291 #if wxUSE_ON_FATAL_EXCEPTION
1292 // assume this can only be called from the main thread
1293 gs_handleExceptions
= doit
;
1297 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to sue this function"));
1303 //-----------------------------------------------------------------------------
1305 //-----------------------------------------------------------------------------
1309 // Send the top window a dummy message so idle handler processing will
1310 // start up again. Doing it this way ensures that the idle handler
1311 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1312 // the same for the main app thread only)
1313 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1316 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1318 // should never happen
1319 wxLogLastError("PostMessage(WM_NULL)");
1324 //-----------------------------------------------------------------------------
1327 wxApp::GetStdIcon(int which
) const
1331 case wxICON_INFORMATION
:
1332 return wxIcon("wxICON_INFO");
1334 case wxICON_QUESTION
:
1335 return wxIcon("wxICON_QUESTION");
1337 case wxICON_EXCLAMATION
:
1338 return wxIcon("wxICON_WARNING");
1341 wxFAIL_MSG(wxT("requested non existent standard icon"));
1342 // still fall through
1345 return wxIcon("wxICON_ERROR");
1349 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1350 // if in a separate file. So include it here to ensure it's linked.
1351 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))