]> git.saurik.com Git - wxWidgets.git/blob - src/msw/app.cpp
bitmap and image updates
[wxWidgets.git] / src / msw / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ===========================================================================
13 // declarations
14 // ===========================================================================
15
16 // ---------------------------------------------------------------------------
17 // headers
18 // ---------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "app.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #if defined(__BORLANDC__)
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/frame.h"
33 #include "wx/app.h"
34 #include "wx/utils.h"
35 #include "wx/gdicmn.h"
36 #include "wx/pen.h"
37 #include "wx/brush.h"
38 #include "wx/cursor.h"
39 #include "wx/icon.h"
40 #include "wx/palette.h"
41 #include "wx/dc.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
44 #include "wx/intl.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
47 #include "wx/icon.h"
48 #endif
49
50 #include "wx/log.h"
51 #include "wx/module.h"
52
53 #include "wx/msw/private.h"
54
55 #if wxUSE_THREADS
56 #include "wx/thread.h"
57
58 // define the array of MSG strutures
59 WX_DECLARE_OBJARRAY(MSG, wxMsgArray);
60
61 #include "wx/arrimpl.cpp"
62
63 WX_DEFINE_OBJARRAY(wxMsgArray);
64 #endif // wxUSE_THREADS
65
66 #if wxUSE_WX_RESOURCES
67 #include "wx/resource.h"
68 #endif
69
70 // OLE is used for drag-and-drop, clipboard, OLE Automation...
71 #ifndef wxUSE_NORLANDER_HEADERS
72 #if defined(__GNUWIN32__) || defined(__SC__) || defined(__SALFORDC__)
73 #undef wxUSE_OLE
74
75 #define wxUSE_OLE 0
76 #endif // broken compilers
77 #endif
78
79 #if wxUSE_OLE
80 #include <ole2.h>
81 #endif
82
83 #include <string.h>
84 #include <ctype.h>
85
86 #if (defined(__WIN95__) && !defined(__GNUWIN32__)) || defined(__TWIN32__) || defined(wxUSE_NORLANDER_HEADERS)
87 #include <commctrl.h>
88 #include <shlwapi.h>
89 #endif
90
91 #include "wx/msw/msvcrt.h"
92
93 // ----------------------------------------------------------------------------
94 // conditional compilation
95 // ----------------------------------------------------------------------------
96
97 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
98 // defined before) and shows us what common control features are available
99 // during the compile time (it doesn't mean that they will be available during
100 // the run-time, use GetComCtl32Version() to test for them!). The possible
101 // values are:
102 //
103 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
104 // 0x0300 4.70 IE 3.x
105 // 0x0400 4.71 IE 4.0
106 // 0x0401 4.72 IE 4.01 and Win98
107 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
108
109 #ifndef _WIN32_IE
110 // minimal set of features by default
111 #define _WIN32_IE 0x0200
112 #endif
113
114 // ---------------------------------------------------------------------------
115 // global variables
116 // ---------------------------------------------------------------------------
117
118 extern wxChar *wxBuffer;
119 extern wxChar *wxOsVersion;
120 extern wxList *wxWinHandleList;
121 extern wxList WXDLLEXPORT wxPendingDelete;
122 extern void wxSetKeyboardHook(bool doIt);
123 extern wxCursor *g_globalCursor;
124
125 MSG s_currentMsg;
126 wxApp *wxTheApp = NULL;
127
128 // FIXME why not const? and not static?
129
130 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
131 // with NR suffix - wxWindow::MSWCreate() supposes this
132 wxChar wxFrameClassName[] = wxT("wxFrameClass");
133 wxChar wxFrameClassNameNoRedraw[] = wxT("wxFrameClassNR");
134 wxChar wxMDIFrameClassName[] = wxT("wxMDIFrameClass");
135 wxChar wxMDIFrameClassNameNoRedraw[] = wxT("wxMDIFrameClassNR");
136 wxChar wxMDIChildFrameClassName[] = wxT("wxMDIChildFrameClass");
137 wxChar wxMDIChildFrameClassNameNoRedraw[] = wxT("wxMDIChildFrameClassNR");
138 wxChar wxPanelClassName[] = wxT("wxPanelClass");
139 wxChar wxCanvasClassName[] = wxT("wxCanvasClass");
140
141 HICON wxSTD_FRAME_ICON = (HICON) NULL;
142 HICON wxSTD_MDICHILDFRAME_ICON = (HICON) NULL;
143 HICON wxSTD_MDIPARENTFRAME_ICON = (HICON) NULL;
144
145 HICON wxDEFAULT_FRAME_ICON = (HICON) NULL;
146 HICON wxDEFAULT_MDICHILDFRAME_ICON = (HICON) NULL;
147 HICON wxDEFAULT_MDIPARENTFRAME_ICON = (HICON) NULL;
148
149 HBRUSH wxDisableButtonBrush = (HBRUSH) 0;
150
151 LRESULT WXDLLEXPORT APIENTRY wxWndProc(HWND, UINT, WPARAM, LPARAM);
152
153 #if wxUSE_RICHEDIT
154 // the handle to richedit DLL and the version of the DLL loaded
155 static HINSTANCE gs_hRichEdit = (HINSTANCE)NULL;
156 static int gs_verRichEdit = -1;
157 #endif
158
159 // ===========================================================================
160 // implementation
161 // ===========================================================================
162
163 // ---------------------------------------------------------------------------
164 // wxApp
165 // ---------------------------------------------------------------------------
166
167 #if !USE_SHARED_LIBRARY
168 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
169
170 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
171 EVT_IDLE(wxApp::OnIdle)
172 EVT_END_SESSION(wxApp::OnEndSession)
173 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
174 END_EVENT_TABLE()
175 #endif
176
177 //// Initialize
178 bool wxApp::Initialize()
179 {
180 // Some people may wish to use this, but
181 // probably it shouldn't be here by default.
182 #ifdef __WXDEBUG__
183 // wxRedirectIOToConsole();
184 #endif
185
186 wxBuffer = new wxChar[1500]; // FIXME
187
188 wxClassInfo::InitializeClasses();
189
190 #if wxUSE_RESOURCES
191 wxGetResource(wxT("wxWindows"), wxT("OsVersion"), &wxOsVersion);
192 #endif
193
194 #if wxUSE_THREADS
195 wxPendingEventsLocker = new wxCriticalSection;
196 #endif
197
198 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
199 wxTheColourDatabase->Initialize();
200
201 wxInitializeStockLists();
202 wxInitializeStockObjects();
203
204 #if wxUSE_WX_RESOURCES
205 wxInitializeResourceSystem();
206 #endif
207
208 wxBitmap::InitStandardHandlers();
209
210 #if defined(__WIN95__)
211 InitCommonControls();
212
213 #endif // __WIN95__
214
215 #if wxUSE_OLE
216
217 #ifdef __WIN16__
218 // for OLE, enlarge message queue to be as large as possible
219 int iMsg = 96;
220 while (!SetMessageQueue(iMsg) && (iMsg -= 8))
221 ;
222 #endif // Win16
223 // we need to initialize OLE library
224 if ( FAILED(::OleInitialize(NULL)) )
225 wxLogError(_("Cannot initialize OLE"));
226 #endif // wxUSE_OLE
227
228 #if wxUSE_CTL3D
229 if (!Ctl3dRegister(wxhInstance))
230 wxLogError(wxT("Cannot register CTL3D"));
231
232 Ctl3dAutoSubclass(wxhInstance);
233 #endif
234
235 g_globalCursor = new wxCursor;
236
237 // VZ: these icons are not in wx.rc anyhow (but should they?)!
238 #if 0
239 wxSTD_FRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_FRAME"));
240 wxSTD_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_MDIPARENTFRAME"));
241 wxSTD_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_MDICHILDFRAME"));
242
243 wxDEFAULT_FRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_FRAME"));
244 wxDEFAULT_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_MDIPARENTFRAME"));
245 wxDEFAULT_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_MDICHILDFRAME"));
246 #endif // 0
247
248 RegisterWindowClasses();
249
250 // Create the brush for disabling bitmap buttons
251
252 LOGBRUSH lb;
253 lb.lbStyle = BS_PATTERN;
254 lb.lbHatch = (int)LoadBitmap( wxhInstance, wxT("wxDISABLE_BUTTON_BITMAP") );
255 if ( lb.lbHatch )
256 {
257 wxDisableButtonBrush = ::CreateBrushIndirect( & lb );
258 ::DeleteObject( (HGDIOBJ)lb.lbHatch );
259 }
260 //else: wxWindows resources are probably not linked in
261
262 #if wxUSE_PENWINDOWS
263 wxRegisterPenWin();
264 #endif
265
266 wxWinHandleList = new wxList(wxKEY_INTEGER);
267
268 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
269 // PLEASE DO NOT ALTER THIS.
270 #if defined(__VISUALC__) && !defined(WXMAKINGDLL)
271 extern char wxDummyChar;
272 if (wxDummyChar) wxDummyChar++;
273 #endif
274
275 wxSetKeyboardHook(TRUE);
276
277 wxModule::RegisterModules();
278 if (!wxModule::InitializeModules())
279 return FALSE;
280 return TRUE;
281 }
282
283 // ---------------------------------------------------------------------------
284 // RegisterWindowClasses
285 // ---------------------------------------------------------------------------
286
287 // TODO we should only register classes really used by the app. For this it
288 // would be enough to just delay the class registration until an attempt
289 // to create a window of this class is made.
290 bool wxApp::RegisterWindowClasses()
291 {
292 WNDCLASS wndclass;
293
294 // for each class we register one with CS_(V|H)REDRAW style and one
295 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
296 static const long styleNormal = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
297 static const long styleNoRedraw = CS_DBLCLKS;
298
299 // the fields which are common to all classes
300 wndclass.lpfnWndProc = (WNDPROC)wxWndProc;
301 wndclass.cbClsExtra = 0;
302 wndclass.cbWndExtra = sizeof( DWORD ); // VZ: what is this DWORD used for?
303 wndclass.hInstance = wxhInstance;
304 wndclass.hIcon = (HICON) NULL;
305 wndclass.hCursor = ::LoadCursor((HINSTANCE)NULL, IDC_ARROW);
306 wndclass.lpszMenuName = NULL;
307
308 // Register the frame window class.
309 wndclass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE + 1);
310 wndclass.lpszClassName = wxFrameClassName;
311 wndclass.style = styleNormal;
312
313 if ( !RegisterClass(&wndclass) )
314 {
315 wxLogLastError("RegisterClass(frame)");
316
317 return FALSE;
318 }
319
320 // "no redraw" frame
321 wndclass.lpszClassName = wxFrameClassNameNoRedraw;
322 wndclass.style = styleNoRedraw;
323
324 if ( !RegisterClass(&wndclass) )
325 {
326 wxLogLastError("RegisterClass(no redraw frame)");
327
328 return FALSE;
329 }
330
331 // Register the MDI frame window class.
332 wndclass.hbrBackground = (HBRUSH)NULL; // paint MDI frame ourselves
333 wndclass.lpszClassName = wxMDIFrameClassName;
334 wndclass.style = styleNormal;
335
336 if ( !RegisterClass(&wndclass) )
337 {
338 wxLogLastError("RegisterClass(MDI parent)");
339
340 return FALSE;
341 }
342
343 // "no redraw" MDI frame
344 wndclass.lpszClassName = wxMDIFrameClassNameNoRedraw;
345 wndclass.style = styleNoRedraw;
346
347 if ( !RegisterClass(&wndclass) )
348 {
349 wxLogLastError("RegisterClass(no redraw MDI parent frame)");
350
351 return FALSE;
352 }
353
354 // Register the MDI child frame window class.
355 wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
356 wndclass.lpszClassName = wxMDIChildFrameClassName;
357 wndclass.style = styleNormal;
358
359 if ( !RegisterClass(&wndclass) )
360 {
361 wxLogLastError("RegisterClass(MDI child)");
362
363 return FALSE;
364 }
365
366 // "no redraw" MDI child frame
367 wndclass.lpszClassName = wxMDIChildFrameClassNameNoRedraw;
368 wndclass.style = styleNoRedraw;
369
370 if ( !RegisterClass(&wndclass) )
371 {
372 wxLogLastError("RegisterClass(no redraw MDI child)");
373
374 return FALSE;
375 }
376
377 // Register the panel window class.
378 wndclass.hbrBackground = (HBRUSH) GetStockObject( LTGRAY_BRUSH );
379 wndclass.lpszClassName = wxPanelClassName;
380 wndclass.style = styleNormal;
381
382 if ( !RegisterClass(&wndclass) )
383 {
384 wxLogLastError("RegisterClass(panel)");
385
386 return FALSE;
387 }
388
389 // Register the canvas and textsubwindow class name
390 wndclass.hbrBackground = (HBRUSH)NULL;
391 wndclass.lpszClassName = wxCanvasClassName;
392
393 if ( !RegisterClass(&wndclass) )
394 {
395 wxLogLastError("RegisterClass(canvas)");
396
397 return FALSE;
398 }
399
400 return TRUE;
401 }
402
403 // ---------------------------------------------------------------------------
404 // Convert Windows to argc, argv style
405 // ---------------------------------------------------------------------------
406
407 void wxApp::ConvertToStandardCommandArgs(char* lpCmdLine)
408 {
409 wxStringList args;
410
411 wxString cmdLine(lpCmdLine);
412 int count = 0;
413
414 // Get application name
415 wxChar name[260]; // 260 is MAX_PATH value from windef.h
416 ::GetModuleFileName(wxhInstance, name, WXSIZEOF(name));
417
418 args.Add(name);
419 count++;
420
421 wxStrcpy(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) && wxIsspace(cmdLine.GetChar(i)))
433 i ++;
434
435 if (i < len)
436 {
437 if (cmdLine.GetChar(i) == wxT('"')) // We found the start of a string
438 {
439 i ++;
440 int first = i;
441 while ((i < len) && (cmdLine.GetChar(i) != wxT('"')))
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) && !wxIsspace(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 wxChar*[count + 1];
467 for (i = 0; i < count; i++)
468 {
469 wxString arg(args[i]);
470 wxTheApp->argv[i] = copystring((const wxChar*)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
478 void wxApp::CleanUp()
479 {
480 //// COMMON CLEANUP
481
482 #if wxUSE_LOG
483 // flush the logged messages if any and install a 'safer' log target: the
484 // default one (wxLogGui) can't be used after the resources are freed just
485 // below and the user suppliedo ne might be even more unsafe (using any
486 // wxWindows GUI function is unsafe starting from now)
487 wxLog::DontCreateOnDemand();
488
489 // this will flush the old messages if any
490 delete wxLog::SetActiveTarget(new wxLogStderr);
491 #endif // wxUSE_LOG
492
493 // One last chance for pending objects to be cleaned up
494 wxTheApp->DeletePendingObjects();
495
496 wxModule::CleanUpModules();
497
498 #if wxUSE_WX_RESOURCES
499 wxCleanUpResourceSystem();
500
501 // wxDefaultResourceTable->ClearTable();
502 #endif
503
504 // Indicate that the cursor can be freed, so that cursor won't be deleted
505 // by deleting the bitmap list before g_globalCursor goes out of scope
506 // (double deletion of the cursor).
507 wxSetCursor(wxNullCursor);
508 delete g_globalCursor;
509 g_globalCursor = NULL;
510
511 wxDeleteStockObjects();
512
513 // Destroy all GDI lists, etc.
514 wxDeleteStockLists();
515
516 delete wxTheColourDatabase;
517 wxTheColourDatabase = NULL;
518
519 wxBitmap::CleanUpHandlers();
520
521 delete[] wxBuffer;
522 wxBuffer = NULL;
523
524 //// WINDOWS-SPECIFIC CLEANUP
525
526 wxSetKeyboardHook(FALSE);
527
528 #if wxUSE_RICHEDIT
529 if (gs_hRichEdit != (HINSTANCE) NULL)
530 FreeLibrary(gs_hRichEdit);
531 #endif
532
533 #if wxUSE_PENWINDOWS
534 wxCleanUpPenWin();
535 #endif
536
537 if (wxSTD_FRAME_ICON)
538 DestroyIcon(wxSTD_FRAME_ICON);
539 if (wxSTD_MDICHILDFRAME_ICON)
540 DestroyIcon(wxSTD_MDICHILDFRAME_ICON);
541 if (wxSTD_MDIPARENTFRAME_ICON)
542 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON);
543
544 if (wxDEFAULT_FRAME_ICON)
545 DestroyIcon(wxDEFAULT_FRAME_ICON);
546 if (wxDEFAULT_MDICHILDFRAME_ICON)
547 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON);
548 if (wxDEFAULT_MDIPARENTFRAME_ICON)
549 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON);
550
551 if ( wxDisableButtonBrush )
552 ::DeleteObject( wxDisableButtonBrush );
553
554 #if wxUSE_OLE
555 ::OleUninitialize();
556 #endif
557
558 #if wxUSE_CTL3D
559 Ctl3dUnregister(wxhInstance);
560 #endif
561
562 if (wxWinHandleList)
563 delete wxWinHandleList;
564
565 // GL: I'm annoyed ... I don't know where to put this and I don't want to
566 // create a module for that as it's part of the core.
567 delete wxPendingEvents;
568 #if wxUSE_THREADS
569 delete wxPendingEventsLocker;
570 // If we don't do the following, we get an apparent memory leak.
571 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
572 #endif
573
574 wxClassInfo::CleanUpClasses();
575
576 delete wxTheApp;
577 wxTheApp = NULL;
578
579 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
580 // At this point we want to check if there are any memory
581 // blocks that aren't part of the wxDebugContext itself,
582 // as a special case. Then when dumping we need to ignore
583 // wxDebugContext, too.
584 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
585 {
586 wxLogDebug(wxT("There were memory leaks."));
587 wxDebugContext::Dump();
588 wxDebugContext::PrintStatistics();
589 }
590 // wxDebugContext::SetStream(NULL, NULL);
591 #endif
592
593 #if wxUSE_LOG
594 // do it as the very last thing because everything else can log messages
595 delete wxLog::SetActiveTarget(NULL);
596 #endif // wxUSE_LOG
597 }
598
599 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
600
601 // temporarily disable this warning which would be generated in release builds
602 // because of __try
603 #ifdef __VISUALC__
604 #pragma warning(disable: 4715) // not all control paths return a value
605 #endif // Visual C++
606
607 //// Main wxWindows entry point
608 int wxEntry(WXHINSTANCE hInstance,
609 WXHINSTANCE WXUNUSED(hPrevInstance),
610 char *lpCmdLine,
611 int nCmdShow,
612 bool enterLoop)
613 {
614 // do check for memory leaks on program exit
615 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
616 // deallocated memory which may be used to simulate low-memory condition)
617 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
618 #ifdef __MWERKS__
619 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
620 // This seems to be necessary since there are 'rogue'
621 // objects present at this point (perhaps global objects?)
622 // Setting a checkpoint will ignore them as far as the
623 // memory checking facility is concerned.
624 // Of course you may argue that memory allocated in globals should be
625 // checked, but this is a reasonable compromise.
626 wxDebugContext::SetCheckpoint();
627 #endif
628 #endif
629 // take everything into a try-except block in release build
630 // FIXME other compilers must support Win32 SEH (structured exception
631 // handling) too, just find the appropriate keyword in their docs!
632 // Please note that it's _not_ the same as C++ exceptions!
633 #if !defined(__WXDEBUG__) && defined(__VISUALC__)
634 #define CATCH_PROGRAM_EXCEPTIONS
635
636 __try {
637 #else
638 #undef CATCH_PROGRAM_EXCEPTIONS
639 #endif
640 wxhInstance = (HINSTANCE) hInstance;
641
642 if (!wxApp::Initialize())
643 return 0;
644
645 // create the application object or ensure that one already exists
646 if (!wxTheApp)
647 {
648 // The app may have declared a global application object, but we recommend
649 // the IMPLEMENT_APP macro is used instead, which sets an initializer
650 // function for delayed, dynamic app object construction.
651 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
652 wxT("No initializer - use IMPLEMENT_APP macro.") );
653
654 wxTheApp = (*wxApp::GetInitializerFunction()) ();
655 }
656
657 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
658
659 // save the WinMain() parameters
660 wxTheApp->ConvertToStandardCommandArgs(lpCmdLine);
661 wxTheApp->m_nCmdShow = nCmdShow;
662
663 // GUI-specific initialisation. In fact on Windows we don't have any,
664 // but this call is provided for compatibility across platforms.
665 wxTheApp->OnInitGui();
666
667 // We really don't want timestamps by default, because it means
668 // we can't simply double-click on the error message and get to that
669 // line in the source. So VC++ at least, let's have a sensible default.
670 #ifdef __VISUALC__
671 wxLog::SetTimestamp(NULL);
672 #endif
673
674 int retValue = 0;
675
676 if ( wxTheApp->OnInit() )
677 {
678 if ( enterLoop )
679 {
680 retValue = wxTheApp->OnRun();
681 }
682 else
683 // We want to initialize, but not run or exit immediately.
684 return 1;
685 }
686 //else: app initialization failed, so we skipped OnRun()
687
688 wxWindow *topWindow = wxTheApp->GetTopWindow();
689 if ( topWindow )
690 {
691 // Forcibly delete the window.
692 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
693 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
694 {
695 topWindow->Close(TRUE);
696 wxTheApp->DeletePendingObjects();
697 }
698 else
699 {
700 delete topWindow;
701 wxTheApp->SetTopWindow(NULL);
702 }
703 }
704
705 wxTheApp->OnExit();
706
707 wxApp::CleanUp();
708
709 return retValue;
710
711 #ifdef CATCH_PROGRAM_EXCEPTIONS
712 }
713 __except ( EXCEPTION_EXECUTE_HANDLER ) {
714 /*
715 if ( wxTheApp )
716 wxTheApp->OnFatalException();
717 */
718
719 // using wxLog would be unsafe here
720 ::MessageBox(NULL,
721 _("Unrecoverable program error detected: "
722 " the application will terminate."),
723 _("Fatal Error"),
724 MB_APPLMODAL | MB_ICONSTOP | MB_OK);
725
726 ::ExitProcess(3); // the same exit code as abort()
727
728 // NOTREACHED
729 }
730 #endif // CATCH_PROGRAM_EXCEPTIONS
731 }
732
733 // restore warning state
734 #ifdef __VISUALC__
735 #pragma warning(default: 4715) // not all control paths return a value
736 #endif // Visual C++
737
738 #else /* _WINDLL */
739
740 //// Entry point for DLLs
741
742 int wxEntry(WXHINSTANCE hInstance)
743 {
744 wxhInstance = (HINSTANCE) hInstance;
745 wxApp::Initialize();
746
747 // The app may have declared a global application object, but we recommend
748 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
749 // for delayed, dynamic app object construction.
750 if (!wxTheApp)
751 {
752 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
753 "No initializer - use IMPLEMENT_APP macro." );
754
755 wxTheApp = (* wxApp::GetInitializerFunction()) ();
756 }
757
758 wxCHECK_MSG( wxTheApp, 0, "You have to define an instance of wxApp!" );
759
760 wxTheApp->argc = 0;
761 wxTheApp->argv = NULL;
762
763 wxTheApp->OnInitGui();
764
765 wxTheApp->OnInit();
766
767 wxWindow *topWindow = wxTheApp->GetTopWindow();
768 if ( topWindow && topWindow->GetHWND())
769 {
770 topWindow->Show(TRUE);
771 }
772
773 return 1;
774 }
775 #endif // _WINDLL
776
777 //// Static member initialization
778
779 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
780
781 wxApp::wxApp()
782 {
783 m_topWindow = NULL;
784 wxTheApp = this;
785 m_wantDebugOutput = TRUE;
786
787 argc = 0;
788 argv = NULL;
789 m_printMode = wxPRINT_WINDOWS;
790 m_exitOnFrameDelete = TRUE;
791 m_auto3D = TRUE;
792 }
793
794 wxApp::~wxApp()
795 {
796 // Delete command-line args
797 int i;
798 for (i = 0; i < argc; i++)
799 {
800 delete[] argv[i];
801 }
802 delete[] argv;
803 }
804
805 bool wxApp::Initialized()
806 {
807 #ifndef _WINDLL
808 if (GetTopWindow())
809 return TRUE;
810 else
811 return FALSE;
812 #endif
813 #ifdef _WINDLL // Assume initialized if DLL (no way of telling)
814 return TRUE;
815 #endif
816 }
817
818 /*
819 * Get and process a message, returning FALSE if WM_QUIT
820 * received (and also set the flag telling the app to exit the main loop)
821 *
822 */
823 bool wxApp::DoMessage()
824 {
825 BOOL rc = ::GetMessage(&s_currentMsg, (HWND) NULL, 0, 0);
826 if ( rc == 0 )
827 {
828 // got WM_QUIT
829 m_keepGoing = FALSE;
830
831 return FALSE;
832 }
833 else if ( rc == -1 )
834 {
835 // should never happen, but let's test for it nevertheless
836 wxLogLastError("GetMessage");
837 }
838 else
839 {
840 #if wxUSE_THREADS
841 wxASSERT_MSG( wxThread::IsMain(),
842 wxT("only the main thread can process Windows messages") );
843
844 static bool s_hadGuiLock = TRUE;
845 static wxMsgArray s_aSavedMessages;
846
847 // if a secondary thread owns is doing GUI calls, save all messages for
848 // later processing - we can't process them right now because it will
849 // lead to recursive library calls (and we're not reentrant)
850 if ( !wxGuiOwnedByMainThread() )
851 {
852 s_hadGuiLock = FALSE;
853
854 // leave out WM_COMMAND messages: too dangerous, sometimes
855 // the message will be processed twice
856 if ( !wxIsWaitingForThread() ||
857 s_currentMsg.message != WM_COMMAND )
858 {
859 s_aSavedMessages.Add(s_currentMsg);
860 }
861
862 return TRUE;
863 }
864 else
865 {
866 // have we just regained the GUI lock? if so, post all of the saved
867 // messages
868 //
869 // FIXME of course, it's not _exactly_ the same as processing the
870 // messages normally - expect some things to break...
871 if ( !s_hadGuiLock )
872 {
873 s_hadGuiLock = TRUE;
874
875 size_t count = s_aSavedMessages.Count();
876 for ( size_t n = 0; n < count; n++ )
877 {
878 MSG& msg = s_aSavedMessages[n];
879
880 if ( !ProcessMessage((WXMSG *)&msg) )
881 {
882 ::TranslateMessage(&msg);
883 ::DispatchMessage(&msg);
884 }
885 }
886
887 s_aSavedMessages.Empty();
888 }
889 }
890 #endif // wxUSE_THREADS
891
892 // Process the message
893 if ( !ProcessMessage((WXMSG *)&s_currentMsg) )
894 {
895 ::TranslateMessage(&s_currentMsg);
896 ::DispatchMessage(&s_currentMsg);
897 }
898 }
899
900 return TRUE;
901 }
902
903 /*
904 * Keep trying to process messages until WM_QUIT
905 * received.
906 *
907 * If there are messages to be processed, they will all be
908 * processed and OnIdle will not be called.
909 * When there are no more messages, OnIdle is called.
910 * If OnIdle requests more time,
911 * it will be repeatedly called so long as there are no pending messages.
912 * A 'feature' of this is that once OnIdle has decided that no more processing
913 * is required, then it won't get processing time until further messages
914 * are processed (it'll sit in DoMessage).
915 */
916
917 int wxApp::MainLoop()
918 {
919 m_keepGoing = TRUE;
920
921 while ( m_keepGoing )
922 {
923 #if wxUSE_THREADS
924 wxMutexGuiLeaveOrEnter();
925 #endif // wxUSE_THREADS
926
927 while ( !::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) &&
928 ProcessIdle() )
929 {
930 }
931
932
933 DoMessage();
934 }
935
936 return s_currentMsg.wParam;
937 }
938
939 // Returns TRUE if more time is needed.
940 bool wxApp::ProcessIdle()
941 {
942 wxIdleEvent event;
943 event.SetEventObject(this);
944 ProcessEvent(event);
945
946 return event.MoreRequested();
947 }
948
949 void wxApp::ExitMainLoop()
950 {
951 m_keepGoing = FALSE;
952 }
953
954 bool wxApp::Pending()
955 {
956 return (::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) != 0);
957 }
958
959 void wxApp::Dispatch()
960 {
961 DoMessage();
962 }
963
964 /*
965 * Give all windows a chance to preprocess
966 * the message. Some may have accelerator tables, or have
967 * MDI complications.
968 */
969
970 bool wxApp::ProcessMessage(WXMSG *wxmsg)
971 {
972 MSG *msg = (MSG *)wxmsg;
973 HWND hWnd = msg->hwnd;
974 wxWindow *wndThis = wxFindWinFromHandle((WXHWND)hWnd), *wnd;
975
976 // for some composite controls (like a combobox), wndThis might be NULL
977 // because the subcontrol is not a wxWindow, but only the control itself
978 // is - try to catch this case
979 while ( hWnd && !wndThis )
980 {
981 hWnd = ::GetParent(hWnd);
982 wndThis = wxFindWinFromHandle((WXHWND)hWnd);
983 }
984
985 // Try translations first; find the youngest window with
986 // a translation table.
987 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
988 {
989 if ( wnd->MSWTranslateMessage(wxmsg) )
990 return TRUE;
991 }
992
993 // Anyone for a non-translation message? Try youngest descendants first.
994 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
995 {
996 if ( wnd->MSWProcessMessage(wxmsg) )
997 return TRUE;
998 }
999
1000 return FALSE;
1001 }
1002
1003 void wxApp::OnIdle(wxIdleEvent& event)
1004 {
1005 static bool s_inOnIdle = FALSE;
1006
1007 // Avoid recursion (via ProcessEvent default case)
1008 if ( s_inOnIdle )
1009 return;
1010
1011 s_inOnIdle = TRUE;
1012
1013 // 'Garbage' collection of windows deleted with Close().
1014 DeletePendingObjects();
1015
1016 #if wxUSE_LOG
1017 // flush the logged messages if any
1018 wxLog *pLog = wxLog::GetActiveTarget();
1019 if ( pLog != NULL && pLog->HasPendingMessages() )
1020 pLog->Flush();
1021 #endif // wxUSE_LOG
1022
1023 // Send OnIdle events to all windows
1024 if ( SendIdleEvents() )
1025 {
1026 // SendIdleEvents() returns TRUE if at least one window requested more
1027 // idle events
1028 event.RequestMore(TRUE);
1029 }
1030
1031 // If they are pending events, we must process them: pending events are
1032 // either events to the threads other than main or events posted with
1033 // wxPostEvent() functions
1034 ProcessPendingEvents();
1035
1036 s_inOnIdle = FALSE;
1037 }
1038
1039 // Send idle event to all top-level windows
1040 bool wxApp::SendIdleEvents()
1041 {
1042 bool needMore = FALSE;
1043
1044 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
1045 while (node)
1046 {
1047 wxWindow* win = node->GetData();
1048 if (SendIdleEvents(win))
1049 needMore = TRUE;
1050 node = node->GetNext();
1051 }
1052
1053 return needMore;
1054 }
1055
1056 // Send idle event to window and all subwindows
1057 bool wxApp::SendIdleEvents(wxWindow* win)
1058 {
1059 bool needMore = FALSE;
1060
1061 wxIdleEvent event;
1062 event.SetEventObject(win);
1063 win->GetEventHandler()->ProcessEvent(event);
1064
1065 if (event.MoreRequested())
1066 needMore = TRUE;
1067
1068 wxNode* node = win->GetChildren().First();
1069 while (node)
1070 {
1071 wxWindow* win = (wxWindow*) node->Data();
1072 if (SendIdleEvents(win))
1073 needMore = TRUE;
1074
1075 node = node->Next();
1076 }
1077 return needMore;
1078 }
1079
1080 void wxApp::DeletePendingObjects()
1081 {
1082 wxNode *node = wxPendingDelete.First();
1083 while (node)
1084 {
1085 wxObject *obj = (wxObject *)node->Data();
1086
1087 delete obj;
1088
1089 if (wxPendingDelete.Member(obj))
1090 delete node;
1091
1092 // Deleting one object may have deleted other pending
1093 // objects, so start from beginning of list again.
1094 node = wxPendingDelete.First();
1095 }
1096 }
1097
1098 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1099 {
1100 if (GetTopWindow())
1101 GetTopWindow()->Close(TRUE);
1102 }
1103
1104 // Default behaviour: close the application with prompts. The
1105 // user can veto the close, and therefore the end session.
1106 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1107 {
1108 if (GetTopWindow())
1109 {
1110 if (!GetTopWindow()->Close(!event.CanVeto()))
1111 event.Veto(TRUE);
1112 }
1113 }
1114
1115 #if wxUSE_RICHEDIT
1116
1117 /* static */
1118 bool wxApp::InitRichEdit(int version)
1119 {
1120 wxCHECK_MSG( version >= 1 && version <= 3, FALSE,
1121 _T("incorrect richedit control version requested") );
1122
1123 if ( version <= gs_verRichEdit )
1124 {
1125 // we've already got this or better
1126 return TRUE;
1127 }
1128
1129 if ( gs_hRichEdit )
1130 {
1131 ::FreeLibrary(gs_hRichEdit);
1132 }
1133
1134 // always try load riched20.dll first - like this we won't have to reload
1135 // it later if we're first asked for RE 1 and then for RE 2 or 3
1136 wxString dllname = _T("riched20.dll");
1137 gs_hRichEdit = ::LoadLibrary(dllname);
1138 if ( !gs_hRichEdit && (version == 1) )
1139 {
1140 // fall back to RE 1
1141 dllname = _T("riched32.dll");
1142 gs_hRichEdit = ::LoadLibrary(dllname);
1143 }
1144
1145 if ( !gs_hRichEdit )
1146 {
1147 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname.c_str());
1148
1149 gs_verRichEdit = -1;
1150
1151 return FALSE;
1152 }
1153
1154 gs_verRichEdit = version;
1155
1156 return TRUE;
1157 }
1158
1159 #endif // wxUSE_RICHEDIT
1160
1161 /* static */
1162 int wxApp::GetComCtl32Version()
1163 {
1164 // cache the result
1165 static int s_verComCtl32 = -1;
1166
1167 wxCRIT_SECT_DECLARE(csComCtl32);
1168 wxCRIT_SECT_LOCKER(lock, csComCtl32);
1169
1170 if ( s_verComCtl32 == -1 )
1171 {
1172 // initally assume no comctl32.dll at all
1173 s_verComCtl32 = 0;
1174
1175 // do we have it?
1176 HMODULE hModuleComCtl32 = ::GetModuleHandle(wxT("COMCTL32"));
1177
1178 // if so, then we can check for the version
1179 if ( hModuleComCtl32 )
1180 {
1181 // try to use DllGetVersion() if available in _headers_
1182 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1183 DLLGETVERSIONPROC pfnDllGetVersion = (DLLGETVERSIONPROC)
1184 ::GetProcAddress(hModuleComCtl32, _T("DllGetVersion"));
1185 if ( pfnDllGetVersion )
1186 {
1187 DLLVERSIONINFO dvi;
1188 dvi.cbSize = sizeof(dvi);
1189
1190 HRESULT hr = (*pfnDllGetVersion)(&dvi);
1191 if ( FAILED(hr) )
1192 {
1193 wxLogApiError(_T("DllGetVersion"), hr);
1194 }
1195 else
1196 {
1197 // this is incompatible with _WIN32_IE values, but
1198 // compatible with the other values returned by
1199 // GetComCtl32Version()
1200 s_verComCtl32 = 100*dvi.dwMajorVersion +
1201 dvi.dwMinorVersion;
1202 }
1203 }
1204 #endif
1205 // DllGetVersion() unavailable either during compile or
1206 // run-time, try to guess the version otherwise
1207 if ( !s_verComCtl32 )
1208 {
1209 // InitCommonControlsEx is unique to 4.70 and later
1210 FARPROC theProc = ::GetProcAddress
1211 (
1212 hModuleComCtl32,
1213 _T("InitCommonControlsEx")
1214 );
1215
1216 if ( !theProc )
1217 {
1218 // not found, must be 4.00
1219 s_verComCtl32 = 400;
1220 }
1221 else
1222 {
1223 // many symbols appeared in comctl32 4.71, could use
1224 // any of them except may be DllInstall
1225 theProc = ::GetProcAddress
1226 (
1227 hModuleComCtl32,
1228 _T("InitializeFlatSB")
1229 );
1230 if ( !theProc )
1231 {
1232 // not found, must be 4.70
1233 s_verComCtl32 = 470;
1234 }
1235 else
1236 {
1237 // found, must be 4.71
1238 s_verComCtl32 = 471;
1239 }
1240 }
1241 }
1242 }
1243 }
1244
1245 return s_verComCtl32;
1246 }
1247
1248 void wxExit()
1249 {
1250 wxLogError(_("Fatal error: exiting"));
1251
1252 wxApp::CleanUp();
1253 }
1254
1255 // Yield to incoming messages
1256 bool wxYield()
1257 {
1258 // we don't want to process WM_QUIT from here - it should be processed in
1259 // the main event loop in order to stop it
1260
1261 MSG msg;
1262 while ( PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE) &&
1263 msg.message != WM_QUIT )
1264 {
1265 if ( !wxTheApp->DoMessage() )
1266 break;
1267 }
1268
1269 // If they are pending events, we must process them.
1270 wxTheApp->ProcessPendingEvents();
1271
1272 return TRUE;
1273 }
1274
1275 //-----------------------------------------------------------------------------
1276 // wxWakeUpIdle
1277 //-----------------------------------------------------------------------------
1278
1279 void wxWakeUpIdle()
1280 {
1281 // Send the top window a dummy message so idle handler processing will
1282 // start up again. Doing it this way ensures that the idle handler
1283 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1284 // the same for the main app thread only)
1285 wxWindow *topWindow = wxTheApp->GetTopWindow();
1286 if ( topWindow )
1287 {
1288 if ( !::PostMessage(GetHwndOf(topWindow), WM_NULL, 0, 0) )
1289 {
1290 // should never happen
1291 wxLogLastError("PostMessage(WM_NULL)");
1292 }
1293 }
1294 }
1295
1296 //-----------------------------------------------------------------------------
1297
1298 wxIcon
1299 wxApp::GetStdIcon(int which) const
1300 {
1301 switch(which)
1302 {
1303 case wxICON_INFORMATION:
1304 return wxIcon("wxICON_INFO");
1305
1306 case wxICON_QUESTION:
1307 return wxIcon("wxICON_QUESTION");
1308
1309 case wxICON_EXCLAMATION:
1310 return wxIcon("wxICON_WARNING");
1311
1312 default:
1313 wxFAIL_MSG(wxT("requested non existent standard icon"));
1314 // still fall through
1315
1316 case wxICON_HAND:
1317 return wxIcon("wxICON_ERROR");
1318 }
1319 }
1320
1321 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1322 // if in a separate file. So include it here to ensure it's linked.
1323 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__))
1324 #include "main.cpp"
1325 #endif