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