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