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