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