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"
70 // OLE is used for drag-and-drop, clipboard, OLE Automation...
71 #ifndef wxUSE_NORLANDER_HEADERS
72 #if defined(__GNUWIN32__) || defined(__SC__) || defined(__SALFORDC__)
76 #endif // broken compilers
86 #if (defined(__WIN95__) && !defined(__GNUWIN32__)) || defined(__TWIN32__) || defined(wxUSE_NORLANDER_HEADERS)
90 #include "wx/msw/msvcrt.h"
92 // ---------------------------------------------------------------------------
94 // ---------------------------------------------------------------------------
96 extern wxChar
*wxBuffer
;
97 extern wxChar
*wxOsVersion
;
98 extern wxList
*wxWinHandleList
;
99 extern wxList WXDLLEXPORT wxPendingDelete
;
100 extern void wxSetKeyboardHook(bool doIt
);
101 extern wxCursor
*g_globalCursor
;
104 wxApp
*wxTheApp
= NULL
;
106 // FIXME why not const? and not static?
108 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
109 // with NR suffix - wxWindow::MSWCreate() supposes this
110 wxChar wxFrameClassName
[] = wxT("wxFrameClass");
111 wxChar wxFrameClassNameNoRedraw
[] = wxT("wxFrameClassNR");
112 wxChar wxMDIFrameClassName
[] = wxT("wxMDIFrameClass");
113 wxChar wxMDIFrameClassNameNoRedraw
[] = wxT("wxMDIFrameClassNR");
114 wxChar wxMDIChildFrameClassName
[] = wxT("wxMDIChildFrameClass");
115 wxChar wxMDIChildFrameClassNameNoRedraw
[] = wxT("wxMDIChildFrameClassNR");
116 wxChar wxPanelClassName
[] = wxT("wxPanelClass");
117 wxChar wxCanvasClassName
[] = wxT("wxCanvasClass");
119 HICON wxSTD_FRAME_ICON
= (HICON
) NULL
;
120 HICON wxSTD_MDICHILDFRAME_ICON
= (HICON
) NULL
;
121 HICON wxSTD_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
123 HICON wxDEFAULT_FRAME_ICON
= (HICON
) NULL
;
124 HICON wxDEFAULT_MDICHILDFRAME_ICON
= (HICON
) NULL
;
125 HICON wxDEFAULT_MDIPARENTFRAME_ICON
= (HICON
) NULL
;
127 HBRUSH wxDisableButtonBrush
= (HBRUSH
) 0;
129 LRESULT WXDLLEXPORT APIENTRY
wxWndProc(HWND
, UINT
, WPARAM
, LPARAM
);
132 // the handle to richedit DLL and the version of the DLL loaded
133 static HINSTANCE gs_hRichEdit
= (HINSTANCE
)NULL
;
134 static int gs_verRichEdit
= -1;
137 // ===========================================================================
139 // ===========================================================================
141 // ---------------------------------------------------------------------------
143 // ---------------------------------------------------------------------------
145 #if !USE_SHARED_LIBRARY
146 IMPLEMENT_DYNAMIC_CLASS(wxApp
, wxEvtHandler
)
148 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
149 EVT_IDLE(wxApp::OnIdle
)
150 EVT_END_SESSION(wxApp::OnEndSession
)
151 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession
)
156 bool wxApp::Initialize()
158 // Some people may wish to use this, but
159 // probably it shouldn't be here by default.
161 // wxRedirectIOToConsole();
164 wxBuffer
= new wxChar
[1500]; // FIXME
166 wxClassInfo::InitializeClasses();
169 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion
);
173 wxPendingEventsLocker
= new wxCriticalSection
;
176 wxTheColourDatabase
= new wxColourDatabase(wxKEY_STRING
);
177 wxTheColourDatabase
->Initialize();
179 wxInitializeStockLists();
180 wxInitializeStockObjects();
182 #if wxUSE_WX_RESOURCES
183 wxInitializeResourceSystem();
186 wxBitmap::InitStandardHandlers();
188 #if defined(__WIN95__)
189 InitCommonControls();
196 // for OLE, enlarge message queue to be as large as possible
198 while (!SetMessageQueue(iMsg
) && (iMsg
-= 8))
201 // we need to initialize OLE library
202 if ( FAILED(::OleInitialize(NULL
)) )
203 wxLogError(_("Cannot initialize OLE"));
207 if (!Ctl3dRegister(wxhInstance
))
208 wxLogError(wxT("Cannot register CTL3D"));
210 Ctl3dAutoSubclass(wxhInstance
);
213 g_globalCursor
= new wxCursor
;
215 // VZ: these icons are not in wx.rc anyhow (but should they?)!
217 wxSTD_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_FRAME"));
218 wxSTD_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDIPARENTFRAME"));
219 wxSTD_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxSTD_MDICHILDFRAME"));
221 wxDEFAULT_FRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_FRAME"));
222 wxDEFAULT_MDIPARENTFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDIPARENTFRAME"));
223 wxDEFAULT_MDICHILDFRAME_ICON
= LoadIcon(wxhInstance
, wxT("wxDEFAULT_MDICHILDFRAME"));
226 RegisterWindowClasses();
228 // Create the brush for disabling bitmap buttons
231 lb
.lbStyle
= BS_PATTERN
;
232 lb
.lbHatch
= (int)LoadBitmap( wxhInstance
, wxT("wxDISABLE_BUTTON_BITMAP") );
235 wxDisableButtonBrush
= ::CreateBrushIndirect( & lb
);
236 ::DeleteObject( (HGDIOBJ
)lb
.lbHatch
);
238 //else: wxWindows resources are probably not linked in
244 wxWinHandleList
= new wxList(wxKEY_INTEGER
);
246 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
247 // PLEASE DO NOT ALTER THIS.
248 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
249 extern char wxDummyChar
;
250 if (wxDummyChar
) wxDummyChar
++;
253 wxSetKeyboardHook(TRUE
);
255 wxModule::RegisterModules();
256 if (!wxModule::InitializeModules())
261 // ---------------------------------------------------------------------------
262 // RegisterWindowClasses
263 // ---------------------------------------------------------------------------
265 // TODO we should only register classes really used by the app. For this it
266 // would be enough to just delay the class registration until an attempt
267 // to create a window of this class is made.
268 bool wxApp::RegisterWindowClasses()
272 // for each class we register one with CS_(V|H)REDRAW style and one
273 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
274 static const long styleNormal
= CS_HREDRAW
| CS_VREDRAW
| CS_DBLCLKS
;
275 static const long styleNoRedraw
= CS_DBLCLKS
;
277 // the fields which are common to all classes
278 wndclass
.lpfnWndProc
= (WNDPROC
)wxWndProc
;
279 wndclass
.cbClsExtra
= 0;
280 wndclass
.cbWndExtra
= sizeof( DWORD
); // VZ: what is this DWORD used for?
281 wndclass
.hInstance
= wxhInstance
;
282 wndclass
.hIcon
= (HICON
) NULL
;
283 wndclass
.hCursor
= ::LoadCursor((HINSTANCE
)NULL
, IDC_ARROW
);
284 wndclass
.lpszMenuName
= NULL
;
286 // Register the frame window class.
287 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_APPWORKSPACE
+ 1);
288 wndclass
.lpszClassName
= wxFrameClassName
;
289 wndclass
.style
= styleNormal
;
291 if ( !RegisterClass(&wndclass
) )
293 wxLogLastError("RegisterClass(frame)");
299 wndclass
.lpszClassName
= wxFrameClassNameNoRedraw
;
300 wndclass
.style
= styleNoRedraw
;
302 if ( !RegisterClass(&wndclass
) )
304 wxLogLastError("RegisterClass(no redraw frame)");
309 // Register the MDI frame window class.
310 wndclass
.hbrBackground
= (HBRUSH
)NULL
; // paint MDI frame ourselves
311 wndclass
.lpszClassName
= wxMDIFrameClassName
;
312 wndclass
.style
= styleNormal
;
314 if ( !RegisterClass(&wndclass
) )
316 wxLogLastError("RegisterClass(MDI parent)");
321 // "no redraw" MDI frame
322 wndclass
.lpszClassName
= wxMDIFrameClassNameNoRedraw
;
323 wndclass
.style
= styleNoRedraw
;
325 if ( !RegisterClass(&wndclass
) )
327 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
332 // Register the MDI child frame window class.
333 wndclass
.hbrBackground
= (HBRUSH
)(COLOR_WINDOW
+ 1);
334 wndclass
.lpszClassName
= wxMDIChildFrameClassName
;
335 wndclass
.style
= styleNormal
;
337 if ( !RegisterClass(&wndclass
) )
339 wxLogLastError("RegisterClass(MDI child)");
344 // "no redraw" MDI child frame
345 wndclass
.lpszClassName
= wxMDIChildFrameClassNameNoRedraw
;
346 wndclass
.style
= styleNoRedraw
;
348 if ( !RegisterClass(&wndclass
) )
350 wxLogLastError("RegisterClass(no redraw MDI child)");
355 // Register the panel window class.
356 wndclass
.hbrBackground
= (HBRUSH
) GetStockObject( LTGRAY_BRUSH
);
357 wndclass
.lpszClassName
= wxPanelClassName
;
358 wndclass
.style
= styleNormal
;
360 if ( !RegisterClass(&wndclass
) )
362 wxLogLastError("RegisterClass(panel)");
367 // Register the canvas and textsubwindow class name
368 wndclass
.hbrBackground
= (HBRUSH
)NULL
;
369 wndclass
.lpszClassName
= wxCanvasClassName
;
371 if ( !RegisterClass(&wndclass
) )
373 wxLogLastError("RegisterClass(canvas)");
381 // ---------------------------------------------------------------------------
382 // Convert Windows to argc, argv style
383 // ---------------------------------------------------------------------------
385 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine
)
389 wxString
cmdLine(lpCmdLine
);
392 // Get application name
393 wxChar name
[260]; // 260 is MAX_PATH value from windef.h
394 ::GetModuleFileName(wxhInstance
, name
, WXSIZEOF(name
));
399 wxStrcpy(name
, wxFileNameFromPath(name
));
400 wxStripExtension(name
);
401 wxTheApp
->SetAppName(name
);
404 // Treat strings enclosed in double-quotes as single arguments
406 int len
= cmdLine
.Length();
410 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
415 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
419 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
422 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
428 i
++; // Skip past 2nd quote
430 else // Unquoted argument
433 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
436 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
444 wxTheApp
->argv
= new wxChar
*[count
+ 1];
445 for (i
= 0; i
< count
; i
++)
447 wxString
arg(args
[i
]);
448 wxTheApp
->argv
[i
] = copystring((const wxChar
*)arg
);
450 wxTheApp
->argv
[count
] = NULL
; // argv[] is a NULL-terminated list
451 wxTheApp
->argc
= count
;
454 //// Cleans up any wxWindows internal structures left lying around
456 void wxApp::CleanUp()
461 // flush the logged messages if any and install a 'safer' log target: the
462 // default one (wxLogGui) can't be used after the resources are freed just
463 // below and the user suppliedo ne might be even more unsafe (using any
464 // wxWindows GUI function is unsafe starting from now)
465 wxLog::DontCreateOnDemand();
467 // this will flush the old messages if any
468 delete wxLog::SetActiveTarget(new wxLogStderr
);
471 // One last chance for pending objects to be cleaned up
472 wxTheApp
->DeletePendingObjects();
474 wxModule::CleanUpModules();
476 #if wxUSE_WX_RESOURCES
477 wxCleanUpResourceSystem();
479 // wxDefaultResourceTable->ClearTable();
482 // Indicate that the cursor can be freed, so that cursor won't be deleted
483 // by deleting the bitmap list before g_globalCursor goes out of scope
484 // (double deletion of the cursor).
485 wxSetCursor(wxNullCursor
);
486 delete g_globalCursor
;
487 g_globalCursor
= NULL
;
489 wxDeleteStockObjects();
491 // Destroy all GDI lists, etc.
492 wxDeleteStockLists();
494 delete wxTheColourDatabase
;
495 wxTheColourDatabase
= NULL
;
497 wxBitmap::CleanUpHandlers();
502 //// WINDOWS-SPECIFIC CLEANUP
504 wxSetKeyboardHook(FALSE
);
507 if (gs_hRichEdit
!= (HINSTANCE
) NULL
)
508 FreeLibrary(gs_hRichEdit
);
515 if (wxSTD_FRAME_ICON
)
516 DestroyIcon(wxSTD_FRAME_ICON
);
517 if (wxSTD_MDICHILDFRAME_ICON
)
518 DestroyIcon(wxSTD_MDICHILDFRAME_ICON
);
519 if (wxSTD_MDIPARENTFRAME_ICON
)
520 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON
);
522 if (wxDEFAULT_FRAME_ICON
)
523 DestroyIcon(wxDEFAULT_FRAME_ICON
);
524 if (wxDEFAULT_MDICHILDFRAME_ICON
)
525 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON
);
526 if (wxDEFAULT_MDIPARENTFRAME_ICON
)
527 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON
);
529 if ( wxDisableButtonBrush
)
530 ::DeleteObject( wxDisableButtonBrush
);
537 Ctl3dUnregister(wxhInstance
);
541 delete wxWinHandleList
;
543 // GL: I'm annoyed ... I don't know where to put this and I don't want to
544 // create a module for that as it's part of the core.
545 delete wxPendingEvents
;
547 delete wxPendingEventsLocker
;
548 // If we don't do the following, we get an apparent memory leak.
549 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
552 wxClassInfo::CleanUpClasses();
557 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
558 // At this point we want to check if there are any memory
559 // blocks that aren't part of the wxDebugContext itself,
560 // as a special case. Then when dumping we need to ignore
561 // wxDebugContext, too.
562 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
564 wxLogDebug(wxT("There were memory leaks."));
565 wxDebugContext::Dump();
566 wxDebugContext::PrintStatistics();
568 // wxDebugContext::SetStream(NULL, NULL);
572 // do it as the very last thing because everything else can log messages
573 delete wxLog::SetActiveTarget(NULL
);
577 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
579 // temporarily disable this warning which would be generated in release builds
582 #pragma warning(disable: 4715) // not all control paths return a value
585 //// Main wxWindows entry point
586 int wxEntry(WXHINSTANCE hInstance
,
587 WXHINSTANCE
WXUNUSED(hPrevInstance
),
592 // do check for memory leaks on program exit
593 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
594 // deallocated memory which may be used to simulate low-memory condition)
595 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
597 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
598 // This seems to be necessary since there are 'rogue'
599 // objects present at this point (perhaps global objects?)
600 // Setting a checkpoint will ignore them as far as the
601 // memory checking facility is concerned.
602 // Of course you may argue that memory allocated in globals should be
603 // checked, but this is a reasonable compromise.
604 wxDebugContext::SetCheckpoint();
607 // take everything into a try-except block in release build
608 // FIXME other compilers must support Win32 SEH (structured exception
609 // handling) too, just find the appropriate keyword in their docs!
610 // Please note that it's _not_ the same as C++ exceptions!
611 #if !defined(__WXDEBUG__) && defined(__VISUALC__)
612 #define CATCH_PROGRAM_EXCEPTIONS
616 #undef CATCH_PROGRAM_EXCEPTIONS
618 wxhInstance
= (HINSTANCE
) hInstance
;
620 if (!wxApp::Initialize())
623 // create the application object or ensure that one already exists
626 // The app may have declared a global application object, but we recommend
627 // the IMPLEMENT_APP macro is used instead, which sets an initializer
628 // function for delayed, dynamic app object construction.
629 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
630 wxT("No initializer - use IMPLEMENT_APP macro.") );
632 wxTheApp
= (*wxApp::GetInitializerFunction()) ();
635 wxCHECK_MSG( wxTheApp
, 0, wxT("You have to define an instance of wxApp!") );
637 // save the WinMain() parameters
638 wxTheApp
->ConvertToStandardCommandArgs(lpCmdLine
);
639 wxTheApp
->m_nCmdShow
= nCmdShow
;
641 // GUI-specific initialisation. In fact on Windows we don't have any,
642 // but this call is provided for compatibility across platforms.
643 wxTheApp
->OnInitGui();
645 // We really don't want timestamps by default, because it means
646 // we can't simply double-click on the error message and get to that
647 // line in the source. So VC++ at least, let's have a sensible default.
649 wxLog::SetTimestamp(NULL
);
654 if ( wxTheApp
->OnInit() )
658 retValue
= wxTheApp
->OnRun();
661 // We want to initialize, but not run or exit immediately.
664 //else: app initialization failed, so we skipped OnRun()
666 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
669 // Forcibly delete the window.
670 if ( topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
671 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
673 topWindow
->Close(TRUE
);
674 wxTheApp
->DeletePendingObjects();
679 wxTheApp
->SetTopWindow(NULL
);
689 #ifdef CATCH_PROGRAM_EXCEPTIONS
691 __except ( EXCEPTION_EXECUTE_HANDLER
) {
694 wxTheApp->OnFatalException();
697 // using wxLog would be unsafe here
699 _("Unrecoverable program error detected: "
700 " the application will terminate."),
702 MB_APPLMODAL
| MB_ICONSTOP
| MB_OK
);
704 ::ExitProcess(3); // the same exit code as abort()
708 #endif // CATCH_PROGRAM_EXCEPTIONS
711 // restore warning state
713 #pragma warning(default: 4715) // not all control paths return a value
718 //// Entry point for DLLs
720 int wxEntry(WXHINSTANCE hInstance
)
722 wxhInstance
= (HINSTANCE
) hInstance
;
725 // The app may have declared a global application object, but we recommend
726 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
727 // for delayed, dynamic app object construction.
730 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
731 "No initializer - use IMPLEMENT_APP macro." );
733 wxTheApp
= (* wxApp::GetInitializerFunction()) ();
736 wxCHECK_MSG( wxTheApp
, 0, "You have to define an instance of wxApp!" );
739 wxTheApp
->argv
= NULL
;
741 wxTheApp
->OnInitGui();
745 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
746 if ( topWindow
&& topWindow
->GetHWND())
748 topWindow
->Show(TRUE
);
755 //// Static member initialization
757 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
763 m_wantDebugOutput
= TRUE
;
767 m_printMode
= wxPRINT_WINDOWS
;
768 m_exitOnFrameDelete
= TRUE
;
774 // Delete command-line args
776 for (i
= 0; i
< argc
; i
++)
783 bool wxApp::Initialized()
791 #ifdef _WINDLL // Assume initialized if DLL (no way of telling)
797 * Get and process a message, returning FALSE if WM_QUIT
798 * received (and also set the flag telling the app to exit the main loop)
801 bool wxApp::DoMessage()
803 BOOL rc
= ::GetMessage(&s_currentMsg
, (HWND
) NULL
, 0, 0);
813 // should never happen, but let's test for it nevertheless
814 wxLogLastError("GetMessage");
819 wxASSERT_MSG( wxThread::IsMain(),
820 wxT("only the main thread can process Windows messages") );
822 static bool s_hadGuiLock
= TRUE
;
823 static wxMsgArray s_aSavedMessages
;
825 // if a secondary thread owns is doing GUI calls, save all messages for
826 // later processing - we can't process them right now because it will
827 // lead to recursive library calls (and we're not reentrant)
828 if ( !wxGuiOwnedByMainThread() )
830 s_hadGuiLock
= FALSE
;
832 // leave out WM_COMMAND messages: too dangerous, sometimes
833 // the message will be processed twice
834 if ( !wxIsWaitingForThread() ||
835 s_currentMsg
.message
!= WM_COMMAND
)
837 s_aSavedMessages
.Add(s_currentMsg
);
844 // have we just regained the GUI lock? if so, post all of the saved
847 // FIXME of course, it's not _exactly_ the same as processing the
848 // messages normally - expect some things to break...
853 size_t count
= s_aSavedMessages
.Count();
854 for ( size_t n
= 0; n
< count
; n
++ )
856 MSG
& msg
= s_aSavedMessages
[n
];
858 if ( !ProcessMessage((WXMSG
*)&msg
) )
860 ::TranslateMessage(&msg
);
861 ::DispatchMessage(&msg
);
865 s_aSavedMessages
.Empty();
868 #endif // wxUSE_THREADS
870 // Process the message
871 if ( !ProcessMessage((WXMSG
*)&s_currentMsg
) )
873 ::TranslateMessage(&s_currentMsg
);
874 ::DispatchMessage(&s_currentMsg
);
882 * Keep trying to process messages until WM_QUIT
885 * If there are messages to be processed, they will all be
886 * processed and OnIdle will not be called.
887 * When there are no more messages, OnIdle is called.
888 * If OnIdle requests more time,
889 * it will be repeatedly called so long as there are no pending messages.
890 * A 'feature' of this is that once OnIdle has decided that no more processing
891 * is required, then it won't get processing time until further messages
892 * are processed (it'll sit in DoMessage).
895 int wxApp::MainLoop()
899 while ( m_keepGoing
)
902 wxMutexGuiLeaveOrEnter();
903 #endif // wxUSE_THREADS
905 while ( !::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) &&
914 return s_currentMsg
.wParam
;
917 // Returns TRUE if more time is needed.
918 bool wxApp::ProcessIdle()
921 event
.SetEventObject(this);
924 return event
.MoreRequested();
927 void wxApp::ExitMainLoop()
932 bool wxApp::Pending()
934 return (::PeekMessage(&s_currentMsg
, 0, 0, 0, PM_NOREMOVE
) != 0);
937 void wxApp::Dispatch()
943 * Give all windows a chance to preprocess
944 * the message. Some may have accelerator tables, or have
948 bool wxApp::ProcessMessage(WXMSG
*wxmsg
)
950 MSG
*msg
= (MSG
*)wxmsg
;
951 HWND hWnd
= msg
->hwnd
;
952 wxWindow
*wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
), *wnd
;
954 // for some composite controls (like a combobox), wndThis might be NULL
955 // because the subcontrol is not a wxWindow, but only the control itself
956 // is - try to catch this case
957 while ( hWnd
&& !wndThis
)
959 hWnd
= ::GetParent(hWnd
);
960 wndThis
= wxFindWinFromHandle((WXHWND
)hWnd
);
963 // Try translations first; find the youngest window with
964 // a translation table.
965 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
967 if ( wnd
->MSWTranslateMessage(wxmsg
) )
971 // Anyone for a non-translation message? Try youngest descendants first.
972 for ( wnd
= wndThis
; wnd
; wnd
= wnd
->GetParent() )
974 if ( wnd
->MSWProcessMessage(wxmsg
) )
981 void wxApp::OnIdle(wxIdleEvent
& event
)
983 static bool s_inOnIdle
= FALSE
;
985 // Avoid recursion (via ProcessEvent default case)
991 // 'Garbage' collection of windows deleted with Close().
992 DeletePendingObjects();
995 // flush the logged messages if any
996 wxLog
*pLog
= wxLog::GetActiveTarget();
997 if ( pLog
!= NULL
&& pLog
->HasPendingMessages() )
1001 // Send OnIdle events to all windows
1002 if ( SendIdleEvents() )
1004 // SendIdleEvents() returns TRUE if at least one window requested more
1006 event
.RequestMore(TRUE
);
1009 // If they are pending events, we must process them: pending events are
1010 // either events to the threads other than main or events posted with
1011 // wxPostEvent() functions
1012 ProcessPendingEvents();
1017 // Send idle event to all top-level windows
1018 bool wxApp::SendIdleEvents()
1020 bool needMore
= FALSE
;
1022 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
1025 wxWindow
* win
= node
->GetData();
1026 if (SendIdleEvents(win
))
1028 node
= node
->GetNext();
1034 // Send idle event to window and all subwindows
1035 bool wxApp::SendIdleEvents(wxWindow
* win
)
1037 bool needMore
= FALSE
;
1040 event
.SetEventObject(win
);
1041 win
->GetEventHandler()->ProcessEvent(event
);
1043 if (event
.MoreRequested())
1046 wxNode
* node
= win
->GetChildren().First();
1049 wxWindow
* win
= (wxWindow
*) node
->Data();
1050 if (SendIdleEvents(win
))
1053 node
= node
->Next();
1058 void wxApp::DeletePendingObjects()
1060 wxNode
*node
= wxPendingDelete
.First();
1063 wxObject
*obj
= (wxObject
*)node
->Data();
1067 if (wxPendingDelete
.Member(obj
))
1070 // Deleting one object may have deleted other pending
1071 // objects, so start from beginning of list again.
1072 node
= wxPendingDelete
.First();
1076 void wxApp::OnEndSession(wxCloseEvent
& WXUNUSED(event
))
1079 GetTopWindow()->Close(TRUE
);
1082 // Default behaviour: close the application with prompts. The
1083 // user can veto the close, and therefore the end session.
1084 void wxApp::OnQueryEndSession(wxCloseEvent
& event
)
1088 if (!GetTopWindow()->Close(!event
.CanVeto()))
1096 bool wxApp::InitRichEdit(int version
)
1098 wxCHECK_MSG( version
>= 1 && version
<= 3, FALSE
,
1099 _T("incorrect richedit control version requested") );
1101 if ( version
<= gs_verRichEdit
)
1103 // we've already got this or better
1109 ::FreeLibrary(gs_hRichEdit
);
1112 // always try load riched20.dll first - like this we won't have to reload
1113 // it later if we're first asked for RE 1 and then for RE 2 or 3
1114 wxString dllname
= _T("riched20.dll");
1115 gs_hRichEdit
= ::LoadLibrary(dllname
);
1116 if ( !gs_hRichEdit
&& (version
== 1) )
1118 // fall back to RE 1
1119 dllname
= _T("riched32.dll");
1120 gs_hRichEdit
= ::LoadLibrary(dllname
);
1123 if ( !gs_hRichEdit
)
1125 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname
.c_str());
1127 gs_verRichEdit
= -1;
1132 gs_verRichEdit
= version
;
1137 #endif // wxUSE_RICHEDIT
1140 int wxApp::GetComCtl32Version()
1142 // TODO should use DllGetVersion() instead of this hack
1145 static int s_verComCtl32
= -1; // MT-FIXME
1147 if ( s_verComCtl32
== -1 )
1151 // have we loaded COMCTL32 yet?
1152 HMODULE theModule
= ::GetModuleHandle(wxT("COMCTL32"));
1154 // if so, then we can check for the version
1157 // InitCommonControlsEx is unique to 4.7 and later
1158 FARPROC theProc
= ::GetProcAddress(theModule
,
1159 _T("InitCommonControlsEx"));
1162 { // not found, must be 4.00
1163 s_verComCtl32
= 400;
1167 // The following symbol are unique to 4.71
1169 // FlatSB_EnableScrollBar FlatSB_GetScrollInfo FlatSB_GetScrollPos
1170 // FlatSB_GetScrollProp FlatSB_GetScrollRange FlatSB_SetScrollInfo
1171 // FlatSB_SetScrollPos FlatSB_SetScrollProp FlatSB_SetScrollRange
1172 // FlatSB_ShowScrollBar
1173 // _DrawIndirectImageList _DuplicateImageList
1175 // UninitializeFlatSB
1176 // we could check for any of these - I chose DllInstall
1177 FARPROC theProc
= ::GetProcAddress(theModule
, _T("DllInstall"));
1180 // not found, must be 4.70
1181 s_verComCtl32
= 470;
1184 { // found, must be 4.71
1185 s_verComCtl32
= 471;
1191 return s_verComCtl32
;
1196 wxLogError(_("Fatal error: exiting"));
1201 // Yield to incoming messages
1204 // we don't want to process WM_QUIT from here - it should be processed in
1205 // the main event loop in order to stop it
1208 while ( PeekMessage(&msg
, (HWND
)0, 0, 0, PM_NOREMOVE
) &&
1209 msg
.message
!= WM_QUIT
)
1211 if ( !wxTheApp
->DoMessage() )
1215 // If they are pending events, we must process them.
1216 wxTheApp
->ProcessPendingEvents();
1221 //-----------------------------------------------------------------------------
1223 //-----------------------------------------------------------------------------
1227 // Send the top window a dummy message so idle handler processing will
1228 // start up again. Doing it this way ensures that the idle handler
1229 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1230 // the same for the main app thread only)
1231 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
1234 if ( !::PostMessage(GetHwndOf(topWindow
), WM_NULL
, 0, 0) )
1236 // should never happen
1237 wxLogLastError("PostMessage(WM_NULL)");
1242 //-----------------------------------------------------------------------------
1245 wxApp::GetStdIcon(int which
) const
1249 case wxICON_INFORMATION
:
1250 return wxIcon("wxICON_INFO");
1252 case wxICON_QUESTION
:
1253 return wxIcon("wxICON_QUESTION");
1255 case wxICON_EXCLAMATION
:
1256 return wxIcon("wxICON_WARNING");
1259 wxFAIL_MSG(wxT("requested non existent standard icon"));
1260 // still fall through
1263 return wxIcon("wxICON_ERROR");
1267 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1268 // if in a separate file. So include it here to ensure it's linked.
1269 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))