]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/msw/app.cpp
* Fixed Apple IEEE conversion
[wxWidgets.git] / src / msw / app.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: app.cpp
3// Purpose: wxApp
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
8// Copyright: (c) Julian Smart and Markus Holzem
9// Licence: wxWindows license
10/////////////////////////////////////////////////////////////////////////////
11
12// ===========================================================================
13// declarations
14// ===========================================================================
15
16// ---------------------------------------------------------------------------
17// headers
18// ---------------------------------------------------------------------------
19
20#ifdef __GNUG__
21 #pragma implementation "app.h"
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#if defined(__BORLANDC__)
28 #pragma hdrstop
29#endif
30
31#ifndef WX_PRECOMP
32 #include "wx/frame.h"
33 #include "wx/app.h"
34 #include "wx/utils.h"
35 #include "wx/gdicmn.h"
36 #include "wx/pen.h"
37 #include "wx/brush.h"
38 #include "wx/cursor.h"
39 #include "wx/icon.h"
40 #include "wx/palette.h"
41 #include "wx/dc.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
44 #include "wx/intl.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
47#endif
48
49#include "wx/log.h"
50#include "wx/module.h"
51
52#include "wx/msw/private.h"
53
54#if wxUSE_THREADS
55 #include "wx/thread.h"
56
57 // define the array of MSG strutures
58 WX_DECLARE_OBJARRAY(MSG, wxMsgArray);
59
60 #include "wx/arrimpl.cpp"
61
62 WX_DEFINE_OBJARRAY(wxMsgArray);
63#endif // wxUSE_THREADS
64
65#if wxUSE_WX_RESOURCES
66 #include "wx/resource.h"
67#endif
68
69// OLE is used for drag-and-drop, clipboard, OLE Automation...
70#if defined(__GNUWIN32__) || defined(__SC__) || defined(__SALFORDC__)
71 #undef wxUSE_OLE
72
73 #define wxUSE_OLE 0
74#endif // broken compilers
75
76#if wxUSE_OLE
77 #include <ole2.h>
78#endif
79
80#include <string.h>
81#include <ctype.h>
82
83#if (defined(__WIN95__) && !defined(__GNUWIN32__)) || defined(__TWIN32__)
84 #include <commctrl.h>
85#endif
86
87#include "wx/msw/msvcrt.h"
88
89// ---------------------------------------------------------------------------
90// global variables
91// ---------------------------------------------------------------------------
92
93extern wxChar *wxBuffer;
94extern wxChar *wxOsVersion;
95extern wxList *wxWinHandleList;
96extern wxList WXDLLEXPORT wxPendingDelete;
97#if wxUSE_THREADS
98extern wxList *wxPendingEvents;
99extern wxCriticalSection *wxPendingEventsLocker;
100#endif
101extern void wxSetKeyboardHook(bool doIt);
102extern wxCursor *g_globalCursor;
103
104HINSTANCE wxhInstance = 0;
105MSG s_currentMsg;
106wxApp *wxTheApp = NULL;
107
108// FIXME why not const? and not static?
109wxChar wxFrameClassName[] = _T("wxFrameClass");
110wxChar wxMDIFrameClassName[] = _T("wxMDIFrameClass");
111wxChar wxMDIChildFrameClassName[] = _T("wxMDIChildFrameClass");
112wxChar wxPanelClassName[] = _T("wxPanelClass");
113wxChar wxCanvasClassName[] = _T("wxCanvasClass");
114
115HICON wxSTD_FRAME_ICON = (HICON) NULL;
116HICON wxSTD_MDICHILDFRAME_ICON = (HICON) NULL;
117HICON wxSTD_MDIPARENTFRAME_ICON = (HICON) NULL;
118
119HICON wxDEFAULT_FRAME_ICON = (HICON) NULL;
120HICON wxDEFAULT_MDICHILDFRAME_ICON = (HICON) NULL;
121HICON wxDEFAULT_MDIPARENTFRAME_ICON = (HICON) NULL;
122
123HBRUSH wxDisableButtonBrush = (HBRUSH) 0;
124
125LRESULT APIENTRY wxWndProc(HWND, UINT, WPARAM, LPARAM);
126
127#if defined(__WIN95__) && !defined(__TWIN32__)
128 #define wxUSE_RICHEDIT 1
129#else
130 #define wxUSE_RICHEDIT 0
131#endif
132
133#if wxUSE_RICHEDIT
134 static HINSTANCE gs_hRichEdit = (HINSTANCE) NULL;
135#endif
136
137// ===========================================================================
138// implementation
139// ===========================================================================
140
141// ---------------------------------------------------------------------------
142// wxApp
143// ---------------------------------------------------------------------------
144
145#if !USE_SHARED_LIBRARY
146 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
147
148 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
149 EVT_IDLE(wxApp::OnIdle)
150 EVT_END_SESSION(wxApp::OnEndSession)
151 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
152 END_EVENT_TABLE()
153#endif
154
155//// Initialize
156bool wxApp::Initialize()
157{
158 // Some people may wish to use this, but
159 // probably it shouldn't be here by default.
160#ifdef __WXDEBUG__
161 // wxRedirectIOToConsole();
162#endif
163
164 wxBuffer = new wxChar[1500]; // FIXME
165
166 wxClassInfo::InitializeClasses();
167
168#if wxUSE_RESOURCES
169 wxGetResource(_T("wxWindows"), _T("OsVersion"), &wxOsVersion);
170#endif
171
172 // I'm annoyed ... I don't know where to put this and I don't want to
173 // create a module for that as it's part of the core.
174#if wxUSE_THREADS
175 wxPendingEvents = new wxList();
176 wxPendingEventsLocker = new wxCriticalSection();
177#endif
178
179 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
180 wxTheColourDatabase->Initialize();
181
182 wxInitializeStockLists();
183 wxInitializeStockObjects();
184
185#if wxUSE_WX_RESOURCES
186 wxInitializeResourceSystem();
187#endif
188
189 wxBitmap::InitStandardHandlers();
190
191#if defined(__WIN95__)
192 InitCommonControls();
193
194#if wxUSE_RICHEDIT
195 gs_hRichEdit = LoadLibrary(_T("RICHED32.DLL"));
196
197 if (gs_hRichEdit == (HINSTANCE) NULL)
198 {
199 wxLogError(_("Could not initialise Rich Edit DLL"));
200 }
201#endif // wxUSE_RICHEDIT
202
203#endif // __WIN95__
204
205 // for OLE, enlarge message queue to be as large as possible
206 int iMsg = 96;
207 while (!SetMessageQueue(iMsg) && (iMsg -= 8));
208
209#if wxUSE_OLE
210 // we need to initialize OLE library
211 if ( FAILED(::OleInitialize(NULL)) )
212 wxLogError(_("Cannot initialize OLE"));
213#endif
214
215#if wxUSE_CTL3D
216 if (!Ctl3dRegister(wxhInstance))
217 wxLogError(_T("Cannot register CTL3D"));
218
219 Ctl3dAutoSubclass(wxhInstance);
220#endif
221
222 g_globalCursor = new wxCursor;
223
224 wxSTD_FRAME_ICON = LoadIcon(wxhInstance, _T("wxSTD_FRAME"));
225 wxSTD_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, _T("wxSTD_MDIPARENTFRAME"));
226 wxSTD_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, _T("wxSTD_MDICHILDFRAME"));
227
228 wxDEFAULT_FRAME_ICON = LoadIcon(wxhInstance, _T("wxDEFAULT_FRAME"));
229 wxDEFAULT_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, _T("wxDEFAULT_MDIPARENTFRAME"));
230 wxDEFAULT_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, _T("wxDEFAULT_MDICHILDFRAME"));
231
232 RegisterWindowClasses();
233
234 // Create the brush for disabling bitmap buttons
235
236 LOGBRUSH lb;
237 lb.lbStyle = BS_PATTERN;
238 lb.lbHatch = (int)LoadBitmap( wxhInstance, _T("wxDISABLE_BUTTON_BITMAP") );
239 if ( lb.lbHatch )
240 {
241 wxDisableButtonBrush = ::CreateBrushIndirect( & lb );
242 ::DeleteObject( (HGDIOBJ)lb.lbHatch );
243 }
244 //else: wxWindows resources are probably not linked in
245
246#if wxUSE_PENWINDOWS
247 wxRegisterPenWin();
248#endif
249
250 wxWinHandleList = new wxList(wxKEY_INTEGER);
251
252 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
253 // PLEASE DO NOT ALTER THIS.
254#if defined(__VISUALC__) && !defined(WXMAKINGDLL)
255 extern char wxDummyChar;
256 if (wxDummyChar) wxDummyChar++;
257#endif
258
259 wxSetKeyboardHook(TRUE);
260
261 wxModule::RegisterModules();
262 if (!wxModule::InitializeModules())
263 return FALSE;
264 return TRUE;
265}
266
267// ---------------------------------------------------------------------------
268// RegisterWindowClasses
269// ---------------------------------------------------------------------------
270
271bool wxApp::RegisterWindowClasses()
272{
273 WNDCLASS wndclass;
274
275 // the fields which are common to all classes
276 wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
277 wndclass.lpfnWndProc = (WNDPROC)wxWndProc;
278 wndclass.cbClsExtra = 0;
279 wndclass.cbWndExtra = sizeof( DWORD ); // what is this DWORD used for?
280 wndclass.hInstance = wxhInstance;
281 wndclass.hIcon = (HICON) NULL;
282 wndclass.hCursor = ::LoadCursor((HINSTANCE)NULL, IDC_ARROW);
283 wndclass.lpszMenuName = NULL;
284
285 // Register the frame window class.
286 wndclass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE + 1);
287#ifdef _MULTIPLE_INSTANCES
288 sprintf( wxFrameClassName,"wxFrameClass%d", wxhInstance );
289#endif
290 wndclass.lpszClassName = wxFrameClassName;
291
292 if ( !RegisterClass(&wndclass) )
293 {
294 wxLogLastError("RegisterClass(frame)");
295
296 return FALSE;
297 }
298
299 // Register the MDI frame window class.
300 wndclass.hbrBackground = (HBRUSH)NULL; // paint MDI frame ourselves
301 wndclass.lpszClassName = wxMDIFrameClassName;
302
303 if ( !RegisterClass(&wndclass) )
304 {
305 wxLogLastError("RegisterClass(MDI parent)");
306
307 return FALSE;
308 }
309
310 // Register the MDI child frame window class.
311 wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
312 wndclass.lpszClassName = wxMDIChildFrameClassName;
313
314 if ( !RegisterClass(&wndclass) )
315 {
316 wxLogLastError("RegisterClass(MDI child)");
317
318 return FALSE;
319 }
320
321 // Register the panel window class.
322 wndclass.hbrBackground = (HBRUSH) GetStockObject( LTGRAY_BRUSH );
323 wndclass.lpszClassName = wxPanelClassName;
324
325 if ( !RegisterClass(&wndclass) )
326 {
327 wxLogLastError("RegisterClass(panel)");
328
329 return FALSE;
330 }
331
332 // Register the canvas and textsubwindow class name
333 wndclass.hbrBackground = (HBRUSH)NULL;
334 wndclass.lpszClassName = wxCanvasClassName;
335
336 if ( !RegisterClass(&wndclass) )
337 {
338 wxLogLastError("RegisterClass(canvas)");
339
340 return FALSE;
341 }
342
343 return TRUE;
344}
345
346// ---------------------------------------------------------------------------
347// Convert Windows to argc, argv style
348// ---------------------------------------------------------------------------
349
350void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine)
351{
352 wxStringList args;
353
354 wxString cmdLine(lpCmdLine);
355 int count = 0;
356
357 // Get application name
358 wxChar name[260]; // 260 is MAX_PATH value from windef.h
359 ::GetModuleFileName(wxhInstance, name, WXSIZEOF(name));
360
361 args.Add(name);
362 count++;
363
364 wxStrcpy(name, wxFileNameFromPath(name));
365 wxStripExtension(name);
366 wxTheApp->SetAppName(name);
367
368 // Break up string
369 // Treat strings enclosed in double-quotes as single arguments
370 int i = 0;
371 int len = cmdLine.Length();
372 while (i < len)
373 {
374 // Skip whitespace
375 while ((i < len) && wxIsspace(cmdLine.GetChar(i)))
376 i ++;
377
378 if (i < len)
379 {
380 if (cmdLine.GetChar(i) == _T('"')) // We found the start of a string
381 {
382 i ++;
383 int first = i;
384 while ((i < len) && (cmdLine.GetChar(i) != _T('"')))
385 i ++;
386
387 wxString arg(cmdLine.Mid(first, (i - first)));
388
389 args.Add(arg);
390 count ++;
391
392 if (i < len)
393 i ++; // Skip past 2nd quote
394 }
395 else // Unquoted argument
396 {
397 int first = i;
398 while ((i < len) && !wxIsspace(cmdLine.GetChar(i)))
399 i ++;
400
401 wxString arg(cmdLine.Mid(first, (i - first)));
402
403 args.Add(arg);
404 count ++;
405 }
406 }
407 }
408
409 wxTheApp->argv = new wxChar*[count + 1];
410 for (i = 0; i < count; i++)
411 {
412 wxString arg(args[i]);
413 wxTheApp->argv[i] = copystring((const wxChar*)arg);
414 }
415 wxTheApp->argv[count] = NULL; // argv[] is a NULL-terminated list
416 wxTheApp->argc = count;
417}
418
419//// Cleans up any wxWindows internal structures left lying around
420
421void wxApp::CleanUp()
422{
423 //// COMMON CLEANUP
424
425#if wxUSE_LOG
426 // flush the logged messages if any and install a 'safer' log target: the
427 // default one (wxLogGui) can't be used after the resources are freed just
428 // below and the user suppliedo ne might be even more unsafe (using any
429 // wxWindows GUI function is unsafe starting from now)
430 wxLog::DontCreateOnDemand();
431
432 // this will flush the old messages if any
433 delete wxLog::SetActiveTarget(new wxLogStderr);
434#endif // wxUSE_LOG
435
436 // One last chance for pending objects to be cleaned up
437 wxTheApp->DeletePendingObjects();
438
439 wxModule::CleanUpModules();
440
441#if wxUSE_WX_RESOURCES
442 wxCleanUpResourceSystem();
443
444 // wxDefaultResourceTable->ClearTable();
445#endif
446
447 // Indicate that the cursor can be freed, so that cursor won't be deleted
448 // by deleting the bitmap list before g_globalCursor goes out of scope
449 // (double deletion of the cursor).
450 wxSetCursor(wxNullCursor);
451 delete g_globalCursor;
452 g_globalCursor = NULL;
453
454 wxDeleteStockObjects();
455
456 // Destroy all GDI lists, etc.
457 wxDeleteStockLists();
458
459 delete wxTheColourDatabase;
460 wxTheColourDatabase = NULL;
461
462 wxBitmap::CleanUpHandlers();
463
464 delete[] wxBuffer;
465 wxBuffer = NULL;
466
467 //// WINDOWS-SPECIFIC CLEANUP
468
469 wxSetKeyboardHook(FALSE);
470
471#ifdef __WIN95__
472
473#if wxUSE_RICHEDIT
474 if (gs_hRichEdit != (HINSTANCE) NULL)
475 FreeLibrary(gs_hRichEdit);
476#endif
477
478#endif
479
480#if wxUSE_PENWINDOWS
481 wxCleanUpPenWin();
482#endif
483
484 if (wxSTD_FRAME_ICON)
485 DestroyIcon(wxSTD_FRAME_ICON);
486 if (wxSTD_MDICHILDFRAME_ICON)
487 DestroyIcon(wxSTD_MDICHILDFRAME_ICON);
488 if (wxSTD_MDIPARENTFRAME_ICON)
489 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON);
490
491 if (wxDEFAULT_FRAME_ICON)
492 DestroyIcon(wxDEFAULT_FRAME_ICON);
493 if (wxDEFAULT_MDICHILDFRAME_ICON)
494 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON);
495 if (wxDEFAULT_MDIPARENTFRAME_ICON)
496 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON);
497
498 if ( wxDisableButtonBrush )
499 ::DeleteObject( wxDisableButtonBrush );
500
501#if wxUSE_OLE
502 ::OleUninitialize();
503#endif
504
505#if wxUSE_CTL3D
506 Ctl3dUnregister(wxhInstance);
507#endif
508
509 if (wxWinHandleList)
510 delete wxWinHandleList;
511
512 // GL: I'm annoyed ... I don't know where to put this and I don't want to
513 // create a module for that as it's part of the core.
514#if wxUSE_THREADS
515 delete wxPendingEvents;
516 delete wxPendingEventsLocker;
517 // If we don't do the following, we get an apparent memory leak.
518 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
519#endif
520
521 wxClassInfo::CleanUpClasses();
522
523 delete wxTheApp;
524 wxTheApp = NULL;
525
526#if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
527 // At this point we want to check if there are any memory
528 // blocks that aren't part of the wxDebugContext itself,
529 // as a special case. Then when dumping we need to ignore
530 // wxDebugContext, too.
531 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
532 {
533 wxLogDebug(_T("There were memory leaks."));
534 wxDebugContext::Dump();
535 wxDebugContext::PrintStatistics();
536 }
537 // wxDebugContext::SetStream(NULL, NULL);
538#endif
539
540#if wxUSE_LOG
541 // do it as the very last thing because everything else can log messages
542 delete wxLog::SetActiveTarget(NULL);
543#endif // wxUSE_LOG
544}
545
546#if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
547
548// temporarily disable this warning which would be generated in release builds
549// because of __try
550#ifdef __VISUALC__
551 #pragma warning(disable: 4715) // not all control paths return a value
552#endif // Visual C++
553
554//// Main wxWindows entry point
555int wxEntry(WXHINSTANCE hInstance,
556 WXHINSTANCE WXUNUSED(hPrevInstance),
557 char *lpCmdLine,
558 int nCmdShow,
559 bool enterLoop)
560{
561 // do check for memory leaks on program exit
562 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
563 // deallocated memory which may be used to simulate low-memory condition)
564 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
565
566 // take everything into a try-except block in release build
567 // FIXME other compilers must support Win32 SEH (structured exception
568 // handling) too, just find the appropriate keyword in their docs!
569 // Please note that it's _not_ the same as C++ exceptions!
570#if !defined(__WXDEBUG__) && defined(__VISUALC__)
571 #define CATCH_PROGRAM_EXCEPTIONS
572
573 __try {
574#else
575 #undef CATCH_PROGRAM_EXCEPTIONS
576#endif
577
578 wxhInstance = (HINSTANCE) hInstance;
579
580 if (!wxApp::Initialize())
581 return 0;
582
583 // create the application object or ensure that one already exists
584 if (!wxTheApp)
585 {
586 // The app may have declared a global application object, but we recommend
587 // the IMPLEMENT_APP macro is used instead, which sets an initializer
588 // function for delayed, dynamic app object construction.
589 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
590 _T("No initializer - use IMPLEMENT_APP macro.") );
591
592 wxTheApp = (*wxApp::GetInitializerFunction()) ();
593 }
594
595 wxCHECK_MSG( wxTheApp, 0, _T("You have to define an instance of wxApp!") );
596
597 // save the WinMain() parameters
598 wxTheApp->ConvertToStandardCommandArgs(lpCmdLine);
599 wxTheApp->m_nCmdShow = nCmdShow;
600
601 // GUI-specific initialisation. In fact on Windows we don't have any,
602 // but this call is provided for compatibility across platforms.
603 wxTheApp->OnInitGui();
604
605 int retValue = 0;
606
607 if ( wxTheApp->OnInit() )
608 {
609 if ( enterLoop )
610 {
611 retValue = wxTheApp->OnRun();
612 }
613 else
614 // We want to initialize, but not run or exit immediately.
615 return 1;
616 }
617 //else: app initialization failed, so we skipped OnRun()
618
619 wxWindow *topWindow = wxTheApp->GetTopWindow();
620 if ( topWindow )
621 {
622 // Forcibly delete the window.
623 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
624 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
625 {
626 topWindow->Close(TRUE);
627 wxTheApp->DeletePendingObjects();
628 }
629 else
630 {
631 delete topWindow;
632 wxTheApp->SetTopWindow(NULL);
633 }
634 }
635
636 wxTheApp->OnExit();
637
638 wxApp::CleanUp();
639
640 return retValue;
641
642#ifdef CATCH_PROGRAM_EXCEPTIONS
643 }
644 __except ( EXCEPTION_EXECUTE_HANDLER ) {
645 /*
646 if ( wxTheApp )
647 wxTheApp->OnFatalException();
648 */
649
650 // using wxLog would be unsafe here
651 ::MessageBox(NULL,
652 _("Unrecoverable program error detected: "
653 " the application will terminate."),
654 _("Fatal Error"),
655 MB_APPLMODAL | MB_ICONSTOP | MB_OK);
656
657 ::ExitProcess(3); // the same exit code as abort()
658
659 // NOTREACHED
660 }
661#endif // CATCH_PROGRAM_EXCEPTIONS
662}
663
664// restore warning state
665#ifdef __VISUALC__
666 #pragma warning(default: 4715) // not all control paths return a value
667#endif // Visual C++
668
669#else /* _WINDLL */
670
671//// Entry point for DLLs
672
673int wxEntry(WXHINSTANCE hInstance)
674{
675 wxhInstance = (HINSTANCE) hInstance;
676 wxApp::Initialize();
677
678 // The app may have declared a global application object, but we recommend
679 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
680 // for delayed, dynamic app object construction.
681 if (!wxTheApp)
682 {
683 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
684 "No initializer - use IMPLEMENT_APP macro." );
685
686 wxTheApp = (* wxApp::GetInitializerFunction()) ();
687 }
688
689 wxCHECK_MSG( wxTheApp, 0, "You have to define an instance of wxApp!" );
690
691 wxTheApp->argc = 0;
692 wxTheApp->argv = NULL;
693
694 wxTheApp->OnInitGui();
695
696 wxTheApp->OnInit();
697
698 wxWindow *topWindow = wxTheApp->GetTopWindow();
699 if ( topWindow && topWindow->GetHWND())
700 {
701 topWindow->Show(TRUE);
702 }
703
704 return 1;
705}
706#endif // _WINDLL
707
708//// Static member initialization
709
710wxAppInitializerFunction wxApp::m_appInitFn = (wxAppInitializerFunction) NULL;
711
712wxApp::wxApp()
713{
714 m_topWindow = NULL;
715 wxTheApp = this;
716 m_wantDebugOutput = TRUE;
717
718 argc = 0;
719 argv = NULL;
720 m_printMode = wxPRINT_WINDOWS;
721 m_exitOnFrameDelete = TRUE;
722 m_auto3D = TRUE;
723}
724
725wxApp::~wxApp()
726{
727 // Delete command-line args
728 int i;
729 for (i = 0; i < argc; i++)
730 {
731 delete[] argv[i];
732 }
733 delete[] argv;
734}
735
736bool wxApp::Initialized()
737{
738#ifndef _WINDLL
739 if (GetTopWindow())
740 return TRUE;
741 else
742 return FALSE;
743#endif
744#ifdef _WINDLL // Assume initialized if DLL (no way of telling)
745 return TRUE;
746#endif
747}
748
749/*
750 * Get and process a message, returning FALSE if WM_QUIT
751 * received (and also set the flag telling the app to exit the main loop)
752 *
753 */
754bool wxApp::DoMessage()
755{
756 BOOL rc = ::GetMessage(&s_currentMsg, (HWND) NULL, 0, 0);
757 if ( rc == 0 )
758 {
759 // got WM_QUIT
760 m_keepGoing = FALSE;
761
762 return FALSE;
763 }
764 else if ( rc == -1 )
765 {
766 // should never happen, but let's test for it nevertheless
767 wxLogLastError("GetMessage");
768 }
769 else
770 {
771#if wxUSE_THREADS
772 wxASSERT_MSG( wxThread::IsMain(),
773 _T("only the main thread can process Windows messages") );
774
775 static bool s_hadGuiLock = TRUE;
776 static wxMsgArray s_aSavedMessages;
777
778 // if a secondary thread owns is doing GUI calls, save all messages for
779 // later processing - we can't process them right now because it will
780 // lead to recursive library calls (and we're not reentrant)
781 if ( !wxGuiOwnedByMainThread() )
782 {
783 s_hadGuiLock = FALSE;
784
785 // leave out WM_COMMAND messages: too dangerous, sometimes
786 // the message will be processed twice
787 if ( !wxIsWaitingForThread() ||
788 s_currentMsg.message != WM_COMMAND )
789 {
790 s_aSavedMessages.Add(s_currentMsg);
791 }
792
793 return TRUE;
794 }
795 else
796 {
797 // have we just regained the GUI lock? if so, post all of the saved
798 // messages
799 //
800 // FIXME of course, it's not _exactly_ the same as processing the
801 // messages normally - expect some things to break...
802 if ( !s_hadGuiLock )
803 {
804 s_hadGuiLock = TRUE;
805
806 size_t count = s_aSavedMessages.Count();
807 for ( size_t n = 0; n < count; n++ )
808 {
809 MSG& msg = s_aSavedMessages[n];
810
811 if ( !ProcessMessage((WXMSG *)&msg) )
812 {
813 ::TranslateMessage(&msg);
814 ::DispatchMessage(&msg);
815 }
816 }
817
818 s_aSavedMessages.Empty();
819 }
820 }
821#endif // wxUSE_THREADS
822
823 // Process the message
824 if ( !ProcessMessage((WXMSG *)&s_currentMsg) )
825 {
826 ::TranslateMessage(&s_currentMsg);
827 ::DispatchMessage(&s_currentMsg);
828 }
829 }
830
831 return TRUE;
832}
833
834/*
835 * Keep trying to process messages until WM_QUIT
836 * received.
837 *
838 * If there are messages to be processed, they will all be
839 * processed and OnIdle will not be called.
840 * When there are no more messages, OnIdle is called.
841 * If OnIdle requests more time,
842 * it will be repeatedly called so long as there are no pending messages.
843 * A 'feature' of this is that once OnIdle has decided that no more processing
844 * is required, then it won't get processing time until further messages
845 * are processed (it'll sit in DoMessage).
846 */
847
848int wxApp::MainLoop()
849{
850 m_keepGoing = TRUE;
851
852 while ( m_keepGoing )
853 {
854#if wxUSE_THREADS
855 wxMutexGuiLeaveOrEnter();
856#endif // wxUSE_THREADS
857
858 while ( !::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) &&
859 ProcessIdle() )
860 {
861 }
862
863
864 DoMessage();
865 }
866
867 return s_currentMsg.wParam;
868}
869
870// Returns TRUE if more time is needed.
871bool wxApp::ProcessIdle()
872{
873 wxIdleEvent event;
874 event.SetEventObject(this);
875 ProcessEvent(event);
876
877 return event.MoreRequested();
878}
879
880#if wxUSE_THREADS
881void wxApp::ProcessPendingEvents()
882{
883 wxNode *node = wxPendingEvents->First();
884 wxCriticalSectionLocker locker(*wxPendingEventsLocker);
885
886 while (node)
887 {
888 wxEvtHandler *handler = (wxEvtHandler *)node->Data();
889
890 handler->ProcessPendingEvents();
891
892 delete node;
893 node = wxPendingEvents->First();
894 }
895}
896#endif
897
898
899void wxApp::ExitMainLoop()
900{
901 m_keepGoing = FALSE;
902}
903
904bool wxApp::Pending()
905{
906 return (::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) != 0);
907}
908
909void wxApp::Dispatch()
910{
911 DoMessage();
912}
913
914/*
915 * Give all windows a chance to preprocess
916 * the message. Some may have accelerator tables, or have
917 * MDI complications.
918 */
919
920bool wxApp::ProcessMessage(WXMSG *wxmsg)
921{
922 MSG *msg = (MSG *)wxmsg;
923 HWND hWnd = msg->hwnd;
924 wxWindow *wndThis = wxFindWinFromHandle((WXHWND)hWnd), *wnd;
925
926 // for some composite controls (like a combobox), wndThis might be NULL
927 // because the subcontrol is not a wxWindow, but only the control itself
928 // is - try to catch this case
929 while ( hWnd && !wndThis )
930 {
931 hWnd = ::GetParent(hWnd);
932 wndThis = wxFindWinFromHandle((WXHWND)hWnd);
933 }
934
935 // Try translations first; find the youngest window with
936 // a translation table.
937 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
938 {
939 if ( wnd->MSWTranslateMessage(wxmsg) )
940 return TRUE;
941 }
942
943 // Anyone for a non-translation message? Try youngest descendants first.
944 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
945 {
946 if ( wnd->MSWProcessMessage(wxmsg) )
947 return TRUE;
948 }
949
950 return FALSE;
951}
952
953void wxApp::OnIdle(wxIdleEvent& event)
954{
955 static bool s_inOnIdle = FALSE;
956
957 // Avoid recursion (via ProcessEvent default case)
958 if ( s_inOnIdle )
959 return;
960
961 s_inOnIdle = TRUE;
962
963 // 'Garbage' collection of windows deleted with Close().
964 DeletePendingObjects();
965
966#if wxUSE_LOG
967 // flush the logged messages if any
968 wxLog *pLog = wxLog::GetActiveTarget();
969 if ( pLog != NULL && pLog->HasPendingMessages() )
970 pLog->Flush();
971#endif // wxUSE_LOG
972
973 // Send OnIdle events to all windows
974 if ( SendIdleEvents() )
975 {
976 // SendIdleEvents() returns TRUE if at least one window requested more
977 // idle events
978 event.RequestMore(TRUE);
979 }
980
981 // If they are pending events, we must process them.
982#if wxUSE_THREADS
983 ProcessPendingEvents();
984#endif
985 s_inOnIdle = FALSE;
986}
987
988// Send idle event to all top-level windows
989bool wxApp::SendIdleEvents()
990{
991 bool needMore = FALSE;
992
993 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
994 while (node)
995 {
996 wxWindow* win = node->GetData();
997 if (SendIdleEvents(win))
998 needMore = TRUE;
999 node = node->GetNext();
1000 }
1001
1002 return needMore;
1003}
1004
1005// Send idle event to window and all subwindows
1006bool wxApp::SendIdleEvents(wxWindow* win)
1007{
1008 bool needMore = FALSE;
1009
1010 wxIdleEvent event;
1011 event.SetEventObject(win);
1012 win->GetEventHandler()->ProcessEvent(event);
1013
1014 if (event.MoreRequested())
1015 needMore = TRUE;
1016
1017 wxNode* node = win->GetChildren().First();
1018 while (node)
1019 {
1020 wxWindow* win = (wxWindow*) node->Data();
1021 if (SendIdleEvents(win))
1022 needMore = TRUE;
1023
1024 node = node->Next();
1025 }
1026 return needMore;
1027}
1028
1029void wxApp::DeletePendingObjects()
1030{
1031 wxNode *node = wxPendingDelete.First();
1032 while (node)
1033 {
1034 wxObject *obj = (wxObject *)node->Data();
1035
1036 delete obj;
1037
1038 if (wxPendingDelete.Member(obj))
1039 delete node;
1040
1041 // Deleting one object may have deleted other pending
1042 // objects, so start from beginning of list again.
1043 node = wxPendingDelete.First();
1044 }
1045}
1046
1047void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1048{
1049 if (GetTopWindow())
1050 GetTopWindow()->Close(TRUE);
1051}
1052
1053// Default behaviour: close the application with prompts. The
1054// user can veto the close, and therefore the end session.
1055void wxApp::OnQueryEndSession(wxCloseEvent& event)
1056{
1057 if (GetTopWindow())
1058 {
1059 if (!GetTopWindow()->Close(!event.CanVeto()))
1060 event.Veto(TRUE);
1061 }
1062}
1063
1064wxLog* wxApp::CreateLogTarget()
1065{
1066 return new wxLogGui;
1067}
1068
1069wxWindow* wxApp::GetTopWindow() const
1070{
1071 if (m_topWindow)
1072 return m_topWindow;
1073 else if (wxTopLevelWindows.GetCount() > 0)
1074 return wxTopLevelWindows.GetFirst()->GetData();
1075 else
1076 return NULL;
1077}
1078
1079int wxApp::GetComCtl32Version() const
1080{
1081 // have we loaded COMCTL32 yet?
1082 HMODULE theModule = ::GetModuleHandle(_T("COMCTL32"));
1083 int version = 0;
1084
1085 // if so, then we can check for the version
1086 if (theModule)
1087 {
1088 // InitCommonControlsEx is unique to 4.7 and later
1089 FARPROC theProc = ::GetProcAddress(theModule, "InitCommonControlsEx");
1090
1091 if (! theProc)
1092 { // not found, must be 4.00
1093 version = 400;
1094 }
1095 else
1096 {
1097 // The following symbol are unique to 4.71
1098 // DllInstall
1099 // FlatSB_EnableScrollBar FlatSB_GetScrollInfo FlatSB_GetScrollPos
1100 // FlatSB_GetScrollProp FlatSB_GetScrollRange FlatSB_SetScrollInfo
1101 // FlatSB_SetScrollPos FlatSB_SetScrollProp FlatSB_SetScrollRange
1102 // FlatSB_ShowScrollBar
1103 // _DrawIndirectImageList _DuplicateImageList
1104 // InitializeFlatSB
1105 // UninitializeFlatSB
1106 // we could check for any of these - I chose DllInstall
1107 FARPROC theProc = ::GetProcAddress(theModule, "DllInstall");
1108 if (! theProc)
1109 {
1110 // not found, must be 4.70
1111 version = 470;
1112 }
1113 else
1114 { // found, must be 4.71
1115 version = 471;
1116 }
1117 }
1118 }
1119 return version;
1120}
1121
1122void wxExit()
1123{
1124 wxLogError(_("Fatal error: exiting"));
1125
1126 wxApp::CleanUp();
1127}
1128
1129// Yield to incoming messages
1130bool wxYield()
1131{
1132 MSG msg;
1133 // We want to go back to the main message loop
1134 // if we see a WM_QUIT. (?)
1135#ifdef __WXWINE__
1136 while (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_NOREMOVE) && msg.message != WM_QUIT)
1137#else
1138 while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) && msg.message != WM_QUIT)
1139#endif
1140 {
1141 if ( !wxTheApp->DoMessage() )
1142 break;
1143 }
1144 // If they are pending events, we must process them.
1145#if wxUSE_THREADS
1146 wxTheApp->ProcessPendingEvents();
1147#endif
1148
1149 return TRUE;
1150}
1151
1152HINSTANCE wxGetInstance()
1153{
1154 return wxhInstance;
1155}
1156
1157void wxSetInstance(HINSTANCE hInst)
1158{
1159 wxhInstance = hInst;
1160}
1161
1162// For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1163// if in a separate file. So include it here to ensure it's linked.
1164#if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))
1165#include "main.cpp"
1166#endif