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