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