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