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