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