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