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