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