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