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