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