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