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