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