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