]> git.saurik.com Git - wxWidgets.git/blob - src/msw/app.cpp
31ce0f4bb419ea49dc368297a395a5d7aac32be0
[wxWidgets.git] / src / msw / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/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
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ===========================================================================
13 // declarations
14 // ===========================================================================
15
16 // ---------------------------------------------------------------------------
17 // headers
18 // ---------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #if defined(__BORLANDC__)
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/msw/wrapcctl.h"
29 #include "wx/dynarray.h"
30 #include "wx/frame.h"
31 #include "wx/app.h"
32 #include "wx/utils.h"
33 #include "wx/gdicmn.h"
34 #include "wx/pen.h"
35 #include "wx/brush.h"
36 #include "wx/cursor.h"
37 #include "wx/icon.h"
38 #include "wx/palette.h"
39 #include "wx/dc.h"
40 #include "wx/dialog.h"
41 #include "wx/msgdlg.h"
42 #include "wx/intl.h"
43 #include "wx/crt.h"
44 #include "wx/log.h"
45 #include "wx/module.h"
46 #endif
47
48 #include "wx/apptrait.h"
49 #include "wx/filename.h"
50 #include "wx/dynlib.h"
51 #include "wx/evtloop.h"
52 #include "wx/thread.h"
53
54 #include "wx/msw/private.h"
55 #include "wx/msw/dc.h"
56 #include "wx/msw/ole/oleutils.h"
57 #include "wx/msw/private/timer.h"
58
59 #if wxUSE_TOOLTIPS
60 #include "wx/tooltip.h"
61 #endif // wxUSE_TOOLTIPS
62
63 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
64 // compilers don't support it (missing headers, libs, ...)
65 #if defined(__GNUWIN32_OLD__) || defined(__SYMANTEC__)
66 #undef wxUSE_OLE
67
68 #define wxUSE_OLE 0
69 #endif // broken compilers
70
71 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
72 #include <ole2.h>
73 #include <aygshell.h>
74 #endif
75
76 #if wxUSE_OLE
77 #include <ole2.h>
78 #endif
79
80 #include <string.h>
81 #include <ctype.h>
82
83 #include "wx/msw/missing.h"
84
85 // instead of including <shlwapi.h> which is not part of the core SDK and not
86 // shipped at all with other compilers, we always define the parts of it we
87 // need here ourselves
88 //
89 // NB: DLLVER_PLATFORM_WINDOWS will be defined if shlwapi.h had been somehow
90 // included already
91 #ifndef DLLVER_PLATFORM_WINDOWS
92 // hopefully we don't need to change packing as DWORDs should be already
93 // correctly aligned
94 struct DLLVERSIONINFO
95 {
96 DWORD cbSize;
97 DWORD dwMajorVersion; // Major version
98 DWORD dwMinorVersion; // Minor version
99 DWORD dwBuildNumber; // Build number
100 DWORD dwPlatformID; // DLLVER_PLATFORM_*
101 };
102
103 typedef HRESULT (CALLBACK* DLLGETVERSIONPROC)(DLLVERSIONINFO *);
104 #endif // defined(DLLVERSIONINFO)
105
106
107 // ---------------------------------------------------------------------------
108 // global variables
109 // ---------------------------------------------------------------------------
110
111 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
112 extern void wxSetKeyboardHook(bool doIt);
113 #endif
114
115 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
116 // with NR suffix - wxWindow::MSWCreate() supposes this
117 #ifdef __WXWINCE__
118 WXDLLIMPEXP_CORE wxChar *wxCanvasClassName;
119 WXDLLIMPEXP_CORE wxChar *wxCanvasClassNameNR;
120 #else
121 WXDLLIMPEXP_CORE const wxChar *wxCanvasClassName = NULL;
122 WXDLLIMPEXP_CORE const wxChar *wxCanvasClassNameNR = NULL;
123 #endif
124 WXDLLIMPEXP_CORE const wxChar *wxMDIFrameClassName = NULL;
125 WXDLLIMPEXP_CORE const wxChar *wxMDIFrameClassNameNoRedraw = NULL;
126 WXDLLIMPEXP_CORE const wxChar *wxMDIChildFrameClassName = NULL;
127 WXDLLIMPEXP_CORE const wxChar *wxMDIChildFrameClassNameNoRedraw = NULL;
128
129 // ----------------------------------------------------------------------------
130 // private functions
131 // ----------------------------------------------------------------------------
132
133 LRESULT WXDLLEXPORT APIENTRY wxWndProc(HWND, UINT, WPARAM, LPARAM);
134
135 // ===========================================================================
136 // wxGUIAppTraits implementation
137 // ===========================================================================
138
139 // private class which we use to pass parameters from BeforeChildWaitLoop() to
140 // AfterChildWaitLoop()
141 struct ChildWaitLoopData
142 {
143 ChildWaitLoopData(wxWindowDisabler *wd_, wxWindow *winActive_)
144 {
145 wd = wd_;
146 winActive = winActive_;
147 }
148
149 wxWindowDisabler *wd;
150 wxWindow *winActive;
151 };
152
153 void *wxGUIAppTraits::BeforeChildWaitLoop()
154 {
155 /*
156 We use a dirty hack here to disable all application windows (which we
157 must do because otherwise the calls to wxYield() could lead to some very
158 unexpected reentrancies in the users code) but to avoid losing
159 focus/activation entirely when the child process terminates which would
160 happen if we simply disabled everything using wxWindowDisabler. Indeed,
161 remember that Windows will never activate a disabled window and when the
162 last childs window is closed and Windows looks for a window to activate
163 all our windows are still disabled. There is no way to enable them in
164 time because we don't know when the childs windows are going to be
165 closed, so the solution we use here is to keep one special tiny frame
166 enabled all the time. Then when the child terminates it will get
167 activated and when we close it below -- after reenabling all the other
168 windows! -- the previously active window becomes activated again and
169 everything is ok.
170 */
171 wxBeginBusyCursor();
172
173 // first disable all existing windows
174 wxWindowDisabler *wd = new wxWindowDisabler;
175
176 // then create an "invisible" frame: it has minimal size, is positioned
177 // (hopefully) outside the screen and doesn't appear on the taskbar
178 wxWindow *winActive = new wxFrame
179 (
180 wxTheApp->GetTopWindow(),
181 wxID_ANY,
182 wxEmptyString,
183 wxPoint(32600, 32600),
184 wxSize(1, 1),
185 wxDEFAULT_FRAME_STYLE | wxFRAME_NO_TASKBAR
186 );
187 winActive->Show();
188
189 return new ChildWaitLoopData(wd, winActive);
190 }
191
192 void wxGUIAppTraits::AlwaysYield()
193 {
194 wxYield();
195 }
196
197 void wxGUIAppTraits::AfterChildWaitLoop(void *dataOrig)
198 {
199 wxEndBusyCursor();
200
201 ChildWaitLoopData * const data = (ChildWaitLoopData *)dataOrig;
202
203 delete data->wd;
204
205 // finally delete the dummy frame and, as wd has been already destroyed and
206 // the other windows reenabled, the activation is going to return to the
207 // window which had had it before
208 data->winActive->Destroy();
209
210 // also delete the temporary data object itself
211 delete data;
212 }
213
214 bool wxGUIAppTraits::DoMessageFromThreadWait()
215 {
216 // we should return false only if the app should exit, i.e. only if
217 // Dispatch() determines that the main event loop should terminate
218 wxEventLoopBase * const evtLoop = wxEventLoop::GetActive();
219 if ( !evtLoop || !evtLoop->Pending() )
220 {
221 // no events means no quit event
222 return true;
223 }
224
225 return evtLoop->Dispatch();
226 }
227
228 DWORD wxGUIAppTraits::WaitForThread(WXHANDLE hThread)
229 {
230 // if we don't have a running event loop, we shouldn't wait for the
231 // messages as we never remove them from the message queue and so we enter
232 // an infinite loop as MsgWaitForMultipleObjects() keeps returning
233 // WAIT_OBJECT_0 + 1
234 if ( !wxEventLoop::GetActive() )
235 return DoSimpleWaitForThread(hThread);
236
237 return ::MsgWaitForMultipleObjects
238 (
239 1, // number of objects to wait for
240 (HANDLE *)&hThread, // the objects
241 false, // wait for any objects, not all
242 INFINITE, // no timeout
243 QS_ALLINPUT | // return as soon as there are any events
244 QS_ALLPOSTMESSAGE
245 );
246 }
247
248 wxPortId wxGUIAppTraits::GetToolkitVersion(int *majVer, int *minVer) const
249 {
250 OSVERSIONINFO info;
251 wxZeroMemory(info);
252
253 // on Windows, the toolkit version is the same of the OS version
254 // as Windows integrates the OS kernel with the GUI toolkit.
255 info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
256 if ( ::GetVersionEx(&info) )
257 {
258 if ( majVer )
259 *majVer = info.dwMajorVersion;
260 if ( minVer )
261 *minVer = info.dwMinorVersion;
262 }
263
264 #if defined(__WXHANDHELD__) || defined(__WXWINCE__)
265 return wxPORT_WINCE;
266 #else
267 return wxPORT_MSW;
268 #endif
269 }
270
271 #if wxUSE_TIMER
272
273 wxTimerImpl *wxGUIAppTraits::CreateTimerImpl(wxTimer *timer)
274 {
275 return new wxMSWTimerImpl(timer);
276 }
277
278 #endif // wxUSE_TIMER
279
280 wxEventLoopBase* wxGUIAppTraits::CreateEventLoop()
281 {
282 return new wxEventLoop;
283 }
284
285 // ---------------------------------------------------------------------------
286 // Stuff for using console from the GUI applications
287 // ---------------------------------------------------------------------------
288
289 #ifndef __WXWINCE__
290
291 #include <wx/dynlib.h>
292
293 namespace
294 {
295
296 /*
297 Helper class to manipulate console from a GUI app.
298
299 Notice that console output is available in the GUI app only if:
300 - AttachConsole() returns TRUE (which means it never works under pre-XP)
301 - we have a valid STD_ERROR_HANDLE
302 - command history hasn't been changed since our startup
303
304 To check if all these conditions are verified, you need to simple call
305 IsOkToUse(). It will check the first two conditions above the first time it
306 is called (and if this fails, the subsequent calls will return immediately)
307 and also recheck the last one every time it is called.
308 */
309 class wxConsoleStderr
310 {
311 public:
312 // default ctor does nothing, call Init() before using this class
313 wxConsoleStderr()
314 {
315 m_hStderr = INVALID_HANDLE_VALUE;
316 m_historyLen =
317 m_dataLen =
318 m_dataLine = 0;
319
320 m_ok = -1;
321 }
322
323 ~wxConsoleStderr()
324 {
325 if ( m_hStderr != INVALID_HANDLE_VALUE )
326 {
327 if ( !::FreeConsole() )
328 {
329 wxLogLastError(_T("FreeConsole"));
330 }
331 }
332 }
333
334 // return true if we were successfully initialized and there had been no
335 // console activity which would interfere with our output since then
336 bool IsOkToUse() const
337 {
338 if ( m_ok == -1 )
339 {
340 wxConsoleStderr * const self = wx_const_cast(wxConsoleStderr *, this);
341 self->m_ok = self->DoInit();
342
343 // no need to call IsHistoryUnchanged() as we just initialized
344 // m_history anyhow
345 return m_ok == 1;
346 }
347
348 return m_ok && IsHistoryUnchanged();
349 }
350
351
352 // output the provided text on the console, return true if ok
353 bool Write(const wxString& text);
354
355 private:
356 // called by Init() once only to do the real initialization
357 bool DoInit();
358
359 // retrieve the command line history into the provided buffer and return
360 // its length
361 int GetCommandHistory(wxWxCharBuffer& buf) const;
362
363 // check if the console history has changed
364 bool IsHistoryUnchanged() const;
365
366 int m_ok; // initially -1, set to true or false by Init()
367
368 wxDynamicLibrary m_dllKernel32;
369
370 HANDLE m_hStderr; // console handle, if it's valid we must call
371 // FreeConsole() (even if m_ok != 1)
372
373 wxWxCharBuffer m_history; // command history on startup
374 int m_historyLen; // length command history buffer
375
376 wxCharBuffer m_data; // data between empty line and cursor position
377 int m_dataLen; // length data buffer
378 int m_dataLine; // line offset
379
380 typedef DWORD (WINAPI *GetConsoleCommandHistory_t)(LPTSTR sCommands,
381 DWORD nBufferLength,
382 LPCTSTR sExeName);
383 typedef DWORD (WINAPI *GetConsoleCommandHistoryLength_t)(LPCTSTR sExeName);
384
385 GetConsoleCommandHistory_t m_pfnGetConsoleCommandHistory;
386 GetConsoleCommandHistoryLength_t m_pfnGetConsoleCommandHistoryLength;
387
388 DECLARE_NO_COPY_CLASS(wxConsoleStderr)
389 };
390
391 bool wxConsoleStderr::DoInit()
392 {
393 HANDLE hStderr = ::GetStdHandle(STD_ERROR_HANDLE);
394
395 if ( hStderr == INVALID_HANDLE_VALUE || !hStderr )
396 return false;
397
398 if ( !m_dllKernel32.Load(_T("kernel32.dll")) )
399 return false;
400
401 typedef BOOL (WINAPI *AttachConsole_t)(DWORD dwProcessId);
402 AttachConsole_t wxDL_INIT_FUNC(pfn, AttachConsole, m_dllKernel32);
403
404 if ( !pfnAttachConsole || !pfnAttachConsole(ATTACH_PARENT_PROCESS) )
405 return false;
406
407 // console attached, set m_hStderr now to ensure that we free it in the
408 // dtor
409 m_hStderr = hStderr;
410
411 wxDL_INIT_FUNC_AW(m_pfn, GetConsoleCommandHistory, m_dllKernel32);
412 if ( !m_pfnGetConsoleCommandHistory )
413 return false;
414
415 wxDL_INIT_FUNC_AW(m_pfn, GetConsoleCommandHistoryLength, m_dllKernel32);
416 if ( !m_pfnGetConsoleCommandHistoryLength )
417 return false;
418
419 // remember the current command history to be able to compare with it later
420 // in IsHistoryUnchanged()
421 m_historyLen = GetCommandHistory(m_history);
422 if ( !m_history )
423 return false;
424
425
426 // now find the first blank line above the current position
427 CONSOLE_SCREEN_BUFFER_INFO csbi;
428
429 if ( !::GetConsoleScreenBufferInfo(m_hStderr, &csbi) )
430 {
431 wxLogLastError(_T("GetConsoleScreenBufferInfo"));
432 return false;
433 }
434
435 COORD pos;
436 pos.X = 0;
437 pos.Y = csbi.dwCursorPosition.Y + 1;
438
439 // we decide that a line is empty if first 4 characters are spaces
440 DWORD ret;
441 char buf[4];
442 do
443 {
444 pos.Y--;
445 if ( !::ReadConsoleOutputCharacterA(m_hStderr, buf, WXSIZEOF(buf),
446 pos, &ret) )
447 {
448 wxLogLastError(_T("ReadConsoleOutputCharacterA"));
449 return false;
450 }
451 } while ( wxStrncmp(" ", buf, WXSIZEOF(buf)) != 0 );
452
453 // calculate line offset and length of data
454 m_dataLine = csbi.dwCursorPosition.Y - pos.Y;
455 m_dataLen = m_dataLine*csbi.dwMaximumWindowSize.X + csbi.dwCursorPosition.X;
456
457 if ( m_dataLen > 0 )
458 {
459 m_data.extend(m_dataLen);
460 if ( !::ReadConsoleOutputCharacterA(m_hStderr, m_data.data(), m_dataLen,
461 pos, &ret) )
462 {
463 wxLogLastError(_T("ReadConsoleOutputCharacterA"));
464 return false;
465 }
466 }
467
468 return true;
469 }
470
471 int wxConsoleStderr::GetCommandHistory(wxWxCharBuffer& buf) const
472 {
473 // these functions are internal and may only be called by cmd.exe
474 static const wxChar *CMD_EXE = _T("cmd.exe");
475
476 const int len = m_pfnGetConsoleCommandHistoryLength(CMD_EXE);
477 if ( len )
478 {
479 buf.extend(len);
480 const int len2 = m_pfnGetConsoleCommandHistory(buf.data(), len, CMD_EXE);
481 if ( len2 != len )
482 {
483 wxFAIL_MSG( _T("failed getting history?") );
484 }
485 }
486
487 return len;
488 }
489
490 bool wxConsoleStderr::IsHistoryUnchanged() const
491 {
492 wxASSERT_MSG( m_ok == 1, _T("shouldn't be called if not initialized") );
493
494 // get (possibly changed) command history
495 wxWxCharBuffer history;
496 const int historyLen = GetCommandHistory(history);
497
498 // and compare it with the original one
499 return historyLen == m_historyLen && history &&
500 memcmp(m_history, history, historyLen) == 0;
501 }
502
503 bool wxConsoleStderr::Write(const wxString& text)
504 {
505 wxASSERT_MSG( m_hStderr != INVALID_HANDLE_VALUE,
506 _T("should only be called if Init() returned true") );
507
508 // get current position
509 CONSOLE_SCREEN_BUFFER_INFO csbi;
510 if ( !::GetConsoleScreenBufferInfo(m_hStderr, &csbi) )
511 {
512 wxLogLastError(_T("GetConsoleScreenBufferInfo"));
513 return false;
514 }
515
516 // and calculate new position (where is empty line)
517 csbi.dwCursorPosition.X = 0;
518 csbi.dwCursorPosition.Y -= m_dataLine;
519
520 if ( !::SetConsoleCursorPosition(m_hStderr, csbi.dwCursorPosition) )
521 {
522 wxLogLastError(_T("SetConsoleCursorPosition"));
523 return false;
524 }
525
526 DWORD ret;
527 if ( !::FillConsoleOutputCharacter(m_hStderr, _T(' '), m_dataLen,
528 csbi.dwCursorPosition, &ret) )
529 {
530 wxLogLastError(_T("FillConsoleOutputCharacter"));
531 return false;
532 }
533
534 if ( !::WriteConsole(m_hStderr, text.wx_str(), text.length(), &ret, NULL) )
535 {
536 wxLogLastError(_T("WriteConsole"));
537 return false;
538 }
539
540 WriteConsoleA(m_hStderr, m_data, m_dataLen, &ret, 0);
541
542 return true;
543 }
544
545 wxConsoleStderr s_consoleStderr;
546
547 } // anonymous namespace
548
549 bool wxGUIAppTraits::CanUseStderr()
550 {
551 return s_consoleStderr.IsOkToUse();
552 }
553
554 bool wxGUIAppTraits::WriteToStderr(const wxString& text)
555 {
556 return s_consoleStderr.IsOkToUse() && s_consoleStderr.Write(text);
557 }
558
559 #endif // !__WXWINCE__
560
561 // ===========================================================================
562 // wxApp implementation
563 // ===========================================================================
564
565 int wxApp::m_nCmdShow = SW_SHOWNORMAL;
566
567 // ---------------------------------------------------------------------------
568 // wxWin macros
569 // ---------------------------------------------------------------------------
570
571 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
572
573 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
574 EVT_IDLE(wxApp::OnIdle)
575 EVT_END_SESSION(wxApp::OnEndSession)
576 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
577 END_EVENT_TABLE()
578
579 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
580 // fails
581 class wxCallBaseCleanup
582 {
583 public:
584 wxCallBaseCleanup(wxApp *app) : m_app(app) { }
585 ~wxCallBaseCleanup() { if ( m_app ) m_app->wxAppBase::CleanUp(); }
586
587 void Dismiss() { m_app = NULL; }
588
589 private:
590 wxApp *m_app;
591 };
592
593 //// Initialize
594 bool wxApp::Initialize(int& argc, wxChar **argv)
595 {
596 if ( !wxAppBase::Initialize(argc, argv) )
597 return false;
598
599 // ensure that base cleanup is done if we return too early
600 wxCallBaseCleanup callBaseCleanup(this);
601
602 #ifdef __WXWINCE__
603 wxString tmp = GetAppName();
604 tmp += wxT("ClassName");
605 wxCanvasClassName = wxStrdup( tmp.wc_str() );
606 tmp += wxT("NR");
607 wxCanvasClassNameNR = wxStrdup( tmp.wc_str() );
608 HWND hWnd = FindWindow( wxCanvasClassNameNR, NULL );
609 if (hWnd)
610 {
611 SetForegroundWindow( (HWND)(((DWORD)hWnd)|0x01) );
612 return false;
613 }
614 #endif
615
616 #if !defined(__WXMICROWIN__)
617 InitCommonControls();
618 #endif // !defined(__WXMICROWIN__)
619
620 #if defined(__SMARTPHONE__) || defined(__POCKETPC__)
621 SHInitExtraControls();
622 #endif
623
624 #ifndef __WXWINCE__
625 // Don't show a message box if a function such as SHGetFileInfo
626 // fails to find a device.
627 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
628 #endif
629
630 wxOleInitialize();
631
632 RegisterWindowClasses();
633
634 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
635 wxSetKeyboardHook(true);
636 #endif
637
638 callBaseCleanup.Dismiss();
639
640 return true;
641 }
642
643 // ---------------------------------------------------------------------------
644 // RegisterWindowClasses
645 // ---------------------------------------------------------------------------
646
647 // This function registers the given class name and stores a pointer to a
648 // heap-allocated copy of it at the specified location, it must be deleted
649 // later.
650 static void RegisterAndStoreClassName(const wxString& uniqueClassName,
651 const wxChar **className,
652 WNDCLASS *lpWndClass)
653 {
654 const size_t length = uniqueClassName.length() + 1; // for trailing NUL
655 wxChar *newChars = new wxChar[length];
656 wxStrncpy(newChars, uniqueClassName, length);
657 *className = newChars;
658 lpWndClass->lpszClassName = *className;
659
660 if ( !::RegisterClass(lpWndClass) )
661 {
662 wxLogLastError(wxString::Format(wxT("RegisterClass(%s)"), newChars));
663 }
664 }
665
666 // This function registers the class defined by the provided WNDCLASS struct
667 // contents using a unique name constructed from the specified base name and
668 // and a suffix unique to this library instance. It also stores the generated
669 // unique names for normal and "no redraw" versions of the class in the
670 // provided variables, caller must delete their contents later.
671 static void RegisterClassWithUniqueNames(const wxString& baseName,
672 const wxChar **className,
673 const wxChar **classNameNR,
674 WNDCLASS *lpWndClass)
675 {
676 // for each class we register one with CS_(V|H)REDRAW style and one
677 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
678 static const long styleNormal = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
679 static const long styleNoRedraw = CS_DBLCLKS;
680
681 const wxString uniqueSuffix(wxString::Format(wxT("@%p"), className));
682
683 wxString uniqueClassName(baseName + uniqueSuffix);
684 lpWndClass->style = styleNormal;
685 RegisterAndStoreClassName(uniqueClassName, className, lpWndClass);
686
687 // NB: remember that code elsewhere supposes that no redraw class names
688 // use the same names as normal classes with "NR" suffix so we must put
689 // "NR" at the end instead of using more natural baseName+"NR"+suffix
690 wxString uniqueClassNameNR(uniqueClassName + wxT("NR"));
691 lpWndClass->style = styleNoRedraw;
692 RegisterAndStoreClassName(uniqueClassNameNR, classNameNR, lpWndClass);
693 }
694
695 // TODO we should only register classes really used by the app. For this it
696 // would be enough to just delay the class registration until an attempt
697 // to create a window of this class is made.
698 bool wxApp::RegisterWindowClasses()
699 {
700 WNDCLASS wndclass;
701 wxZeroMemory(wndclass);
702
703 // the fields which are common to all classes
704 wndclass.lpfnWndProc = (WNDPROC)wxWndProc;
705 wndclass.hInstance = wxhInstance;
706 wndclass.hCursor = ::LoadCursor((HINSTANCE)NULL, IDC_ARROW);
707
708 // register the class for all normal windows and "no redraw" frames
709 wndclass.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
710 RegisterClassWithUniqueNames(wxT("wxWindowClass"),
711 &wxCanvasClassName,
712 &wxCanvasClassNameNR,
713 &wndclass);
714
715 // Register the MDI frame window class and "no redraw" MDI frame
716 wndclass.hbrBackground = (HBRUSH)NULL; // paint MDI frame ourselves
717 RegisterClassWithUniqueNames(wxT("wxMDIFrameClass"),
718 &wxMDIFrameClassName,
719 &wxMDIFrameClassNameNoRedraw,
720 &wndclass);
721
722 // Register the MDI child frame window class and "no redraw" MDI child frame
723 wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
724 RegisterClassWithUniqueNames(wxT("wxMDIChildFrameClass"),
725 &wxMDIChildFrameClassName,
726 &wxMDIChildFrameClassNameNoRedraw,
727 &wndclass);
728
729 return true;
730 }
731
732 // ---------------------------------------------------------------------------
733 // UnregisterWindowClasses
734 // ---------------------------------------------------------------------------
735
736 // This function unregisters the class with the given name and frees memory
737 // allocated for it by RegisterAndStoreClassName().
738 static bool UnregisterAndFreeClassName(const wxChar **ppClassName)
739 {
740 bool retval = true;
741
742 if ( !::UnregisterClass(*ppClassName, wxhInstance) )
743 {
744 wxLogLastError(
745 wxString::Format(wxT("UnregisterClass(%s)"), *ppClassName));
746
747 retval = false;
748 }
749
750 delete [] (wxChar*) *ppClassName;
751 *ppClassName = NULL;
752
753 return retval;
754 }
755
756 bool wxApp::UnregisterWindowClasses()
757 {
758 bool retval = true;
759
760 #ifndef __WXMICROWIN__
761 if ( !UnregisterAndFreeClassName(&wxMDIFrameClassName) )
762 retval = false;
763
764 if ( !UnregisterAndFreeClassName(&wxMDIFrameClassNameNoRedraw) )
765 retval = false;
766
767 if ( !UnregisterAndFreeClassName(&wxMDIChildFrameClassName) )
768 retval = false;
769
770 if ( !UnregisterAndFreeClassName(&wxMDIChildFrameClassNameNoRedraw) )
771 retval = false;
772
773 if ( !UnregisterAndFreeClassName(&wxCanvasClassName) )
774 retval = false;
775
776 if ( !UnregisterAndFreeClassName(&wxCanvasClassNameNR) )
777 retval = false;
778 #endif // __WXMICROWIN__
779
780 return retval;
781 }
782
783 void wxApp::CleanUp()
784 {
785 // all objects pending for deletion must be deleted first, otherwise
786 // UnregisterWindowClasses() call wouldn't succeed (because windows
787 // using the classes being unregistered still exist), so call the base
788 // class method first and only then do our clean up
789 wxAppBase::CleanUp();
790
791 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
792 wxSetKeyboardHook(false);
793 #endif
794
795 wxOleUninitialize();
796
797 // for an EXE the classes are unregistered when it terminates but DLL may
798 // be loaded several times (load/unload/load) into the same process in
799 // which case the registration will fail after the first time if we don't
800 // unregister the classes now
801 UnregisterWindowClasses();
802
803 #ifdef __WXWINCE__
804 free( wxCanvasClassName );
805 free( wxCanvasClassNameNR );
806 #endif
807 }
808
809 // ----------------------------------------------------------------------------
810 // wxApp ctor/dtor
811 // ----------------------------------------------------------------------------
812
813 wxApp::wxApp()
814 {
815 m_printMode = wxPRINT_WINDOWS;
816 }
817
818 wxApp::~wxApp()
819 {
820 }
821
822 // ----------------------------------------------------------------------------
823 // wxApp idle handling
824 // ----------------------------------------------------------------------------
825
826 void wxApp::OnIdle(wxIdleEvent& WXUNUSED(event))
827 {
828 #if wxUSE_DC_CACHEING
829 // automated DC cache management: clear the cached DCs and bitmap
830 // if it's likely that the app has finished with them, that is, we
831 // get an idle event and we're not dragging anything.
832 if (!::GetKeyState(MK_LBUTTON) && !::GetKeyState(MK_MBUTTON) && !::GetKeyState(MK_RBUTTON))
833 wxMSWDCImpl::ClearCache();
834 #endif // wxUSE_DC_CACHEING
835 }
836
837 void wxApp::WakeUpIdle()
838 {
839 // Send the top window a dummy message so idle handler processing will
840 // start up again. Doing it this way ensures that the idle handler
841 // wakes up in the right thread (see also wxWakeUpMainThread() which does
842 // the same for the main app thread only)
843 wxWindow * const topWindow = wxTheApp->GetTopWindow();
844 if ( topWindow )
845 {
846 HWND hwndTop = GetHwndOf(topWindow);
847
848 // Do not post WM_NULL if there's already a pending WM_NULL to avoid
849 // overflowing the message queue.
850 //
851 // Notice that due to a limitation of PeekMessage() API (which handles
852 // 0,0 range specially), we have to check the range from 0-1 instead.
853 // This still makes it possible to overflow the queue with WM_NULLs by
854 // interspersing the calles to WakeUpIdle() with windows creation but
855 // it should be rather hard to do it accidentally.
856 MSG msg;
857 if ( !::PeekMessage(&msg, hwndTop, 0, 1, PM_NOREMOVE) ||
858 ::PeekMessage(&msg, hwndTop, 1, 1, PM_NOREMOVE) )
859 {
860 if ( !::PostMessage(hwndTop, WM_NULL, 0, 0) )
861 {
862 // should never happen
863 wxLogLastError(wxT("PostMessage(WM_NULL)"));
864 }
865 }
866 }
867 }
868
869 // ----------------------------------------------------------------------------
870 // other wxApp event hanlders
871 // ----------------------------------------------------------------------------
872
873 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
874 {
875 // Windows will terminate the process soon after we return from
876 // WM_ENDSESSION handler or when we delete our last window, so make sure we
877 // at least execute our cleanup code before
878
879 // prevent the window from being destroyed when the corresponding wxTLW is
880 // destroyed: this will result in a leak of a HWND, of course, but who
881 // cares when the process is being killed anyhow
882 if ( !wxTopLevelWindows.empty() )
883 wxTopLevelWindows[0]->SetHWND(0);
884
885 const int rc = OnExit();
886
887 wxEntryCleanup();
888
889 // calling exit() instead of ExitProcess() or not doing anything at all and
890 // being killed by Windows has the advantage of executing the dtors of
891 // global objects
892 exit(rc);
893 }
894
895 // Default behaviour: close the application with prompts. The
896 // user can veto the close, and therefore the end session.
897 void wxApp::OnQueryEndSession(wxCloseEvent& event)
898 {
899 if (GetTopWindow())
900 {
901 if (!GetTopWindow()->Close(!event.CanVeto()))
902 event.Veto(true);
903 }
904 }
905
906 // ----------------------------------------------------------------------------
907 // system DLL versions
908 // ----------------------------------------------------------------------------
909
910 // these functions have trivial inline implementations for CE
911 #ifndef __WXWINCE__
912
913 #if wxUSE_DYNLIB_CLASS
914
915 namespace
916 {
917
918 // helper function: retrieve the DLL version by using DllGetVersion(), returns
919 // 0 if the DLL doesn't export such function
920 int CallDllGetVersion(wxDynamicLibrary& dll)
921 {
922 // now check if the function is available during run-time
923 wxDYNLIB_FUNCTION( DLLGETVERSIONPROC, DllGetVersion, dll );
924 if ( !pfnDllGetVersion )
925 return 0;
926
927 DLLVERSIONINFO dvi;
928 dvi.cbSize = sizeof(dvi);
929
930 HRESULT hr = (*pfnDllGetVersion)(&dvi);
931 if ( FAILED(hr) )
932 {
933 wxLogApiError(_T("DllGetVersion"), hr);
934
935 return 0;
936 }
937
938 return 100*dvi.dwMajorVersion + dvi.dwMinorVersion;
939 }
940
941 } // anonymous namespace
942
943 /* static */
944 int wxApp::GetComCtl32Version()
945 {
946 // cache the result
947 //
948 // NB: this is MT-ok as in the worst case we'd compute s_verComCtl32 twice,
949 // but as its value should be the same both times it doesn't matter
950 static int s_verComCtl32 = -1;
951
952 if ( s_verComCtl32 == -1 )
953 {
954 // we're prepared to handle the errors
955 wxLogNull noLog;
956
957 // the DLL should really be available
958 wxDynamicLibrary dllComCtl32(_T("comctl32.dll"), wxDL_VERBATIM);
959 if ( !dllComCtl32.IsLoaded() )
960 {
961 s_verComCtl32 = 0;
962 return 0;
963 }
964
965 // try DllGetVersion() for recent DLLs
966 s_verComCtl32 = CallDllGetVersion(dllComCtl32);
967
968 // if DllGetVersion() is unavailable either during compile or
969 // run-time, try to guess the version otherwise
970 if ( !s_verComCtl32 )
971 {
972 // InitCommonControlsEx is unique to 4.70 and later
973 void *pfn = dllComCtl32.GetSymbol(_T("InitCommonControlsEx"));
974 if ( !pfn )
975 {
976 // not found, must be 4.00
977 s_verComCtl32 = 400;
978 }
979 else // 4.70+
980 {
981 // many symbols appeared in comctl32 4.71, could use any of
982 // them except may be DllInstall()
983 pfn = dllComCtl32.GetSymbol(_T("InitializeFlatSB"));
984 if ( !pfn )
985 {
986 // not found, must be 4.70
987 s_verComCtl32 = 470;
988 }
989 else
990 {
991 // found, must be 4.71 or later
992 s_verComCtl32 = 471;
993 }
994 }
995 }
996 }
997
998 return s_verComCtl32;
999 }
1000
1001 /* static */
1002 int wxApp::GetShell32Version()
1003 {
1004 static int s_verShell32 = -1;
1005 if ( s_verShell32 == -1 )
1006 {
1007 // we're prepared to handle the errors
1008 wxLogNull noLog;
1009
1010 wxDynamicLibrary dllShell32(_T("shell32.dll"), wxDL_VERBATIM);
1011 if ( dllShell32.IsLoaded() )
1012 {
1013 s_verShell32 = CallDllGetVersion(dllShell32);
1014
1015 if ( !s_verShell32 )
1016 {
1017 // there doesn't seem to be any way to distinguish between 4.00
1018 // and 4.70 (starting from 4.71 we have DllGetVersion()) so
1019 // just assume it is 4.0
1020 s_verShell32 = 400;
1021 }
1022 }
1023 else // failed load the DLL?
1024 {
1025 s_verShell32 = 0;
1026 }
1027 }
1028
1029 return s_verShell32;
1030 }
1031
1032 #else // !wxUSE_DYNLIB_CLASS
1033
1034 /* static */
1035 int wxApp::GetComCtl32Version()
1036 {
1037 return 0;
1038 }
1039
1040 /* static */
1041 int wxApp::GetShell32Version()
1042 {
1043 return 0;
1044 }
1045
1046 #endif // wxUSE_DYNLIB_CLASS/!wxUSE_DYNLIB_CLASS
1047
1048 #endif // !__WXWINCE__
1049
1050 // ----------------------------------------------------------------------------
1051 // Yield to incoming messages
1052 // ----------------------------------------------------------------------------
1053
1054 bool wxApp::Yield(bool onlyIfNeeded)
1055 {
1056 // MT-FIXME
1057 static bool s_inYield = false;
1058
1059 #if wxUSE_LOG
1060 // disable log flushing from here because a call to wxYield() shouldn't
1061 // normally result in message boxes popping up &c
1062 wxLog::Suspend();
1063 #endif // wxUSE_LOG
1064
1065 if ( s_inYield )
1066 {
1067 if ( !onlyIfNeeded )
1068 {
1069 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1070 }
1071
1072 return false;
1073 }
1074
1075 s_inYield = true;
1076
1077 // we don't want to process WM_QUIT from here - it should be processed in
1078 // the main event loop in order to stop it
1079 wxEventLoopGuarantor dummyLoopIfNeeded;
1080 MSG msg;
1081 while ( PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE) &&
1082 msg.message != WM_QUIT )
1083 {
1084 #if wxUSE_THREADS
1085 wxMutexGuiLeaveOrEnter();
1086 #endif // wxUSE_THREADS
1087
1088 if ( !wxTheApp->Dispatch() )
1089 break;
1090 }
1091
1092 // if there are pending events, we must process them.
1093 ProcessPendingEvents();
1094
1095 #if wxUSE_LOG
1096 // let the logs be flashed again
1097 wxLog::Resume();
1098 #endif // wxUSE_LOG
1099
1100 s_inYield = false;
1101
1102 return true;
1103 }
1104
1105 #if wxUSE_EXCEPTIONS
1106
1107 // ----------------------------------------------------------------------------
1108 // exception handling
1109 // ----------------------------------------------------------------------------
1110
1111 bool wxApp::OnExceptionInMainLoop()
1112 {
1113 // ask the user about what to do: use the Win32 API function here as it
1114 // could be dangerous to use any wxWidgets code in this state
1115 switch (
1116 ::MessageBox
1117 (
1118 NULL,
1119 _T("An unhandled exception occurred. Press \"Abort\" to \
1120 terminate the program,\r\n\
1121 \"Retry\" to exit the program normally and \"Ignore\" to try to continue."),
1122 _T("Unhandled exception"),
1123 MB_ABORTRETRYIGNORE |
1124 MB_ICONERROR|
1125 MB_TASKMODAL
1126 )
1127 )
1128 {
1129 case IDABORT:
1130 throw;
1131
1132 default:
1133 wxFAIL_MSG( _T("unexpected MessageBox() return code") );
1134 // fall through
1135
1136 case IDRETRY:
1137 return false;
1138
1139 case IDIGNORE:
1140 return true;
1141 }
1142 }
1143
1144 #endif // wxUSE_EXCEPTIONS