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