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