Allow wx parents a chance to handle events fired by non-wx children. (i.e. wxActiveX...
[wxWidgets.git] / src / msw / evtloop.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: msw/evtloop.cpp
3 // Purpose: implements wxEventLoop for MSW
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 01.06.01
7 // RCS-ID: $Id$
8 // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // License: 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 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/window.h"
29 #include "wx/app.h"
30 #endif //WX_PRECOMP
31
32 #include "wx/evtloop.h"
33
34 #include "wx/tooltip.h"
35 #include "wx/except.h"
36 #include "wx/ptr_scpd.h"
37
38 #include "wx/msw/private.h"
39
40 #if wxUSE_THREADS
41 #include "wx/thread.h"
42
43 // define the list of MSG strutures
44 WX_DECLARE_LIST(MSG, wxMsgList);
45
46 #include "wx/listimpl.cpp"
47
48 WX_DEFINE_LIST(wxMsgList)
49 #endif // wxUSE_THREADS
50
51 // ----------------------------------------------------------------------------
52 // helper class
53 // ----------------------------------------------------------------------------
54
55 // this object sets the wxEventLoop given to the ctor as the currently active
56 // one and unsets it in its dtor
57 class wxEventLoopActivator
58 {
59 public:
60 wxEventLoopActivator(wxEventLoop **pActive,
61 wxEventLoop *evtLoop)
62 {
63 m_pActive = pActive;
64 m_evtLoopOld = *pActive;
65 *pActive = evtLoop;
66 }
67
68 ~wxEventLoopActivator()
69 {
70 // restore the previously active event loop
71 *m_pActive = m_evtLoopOld;
72 }
73
74 private:
75 wxEventLoop *m_evtLoopOld;
76 wxEventLoop **m_pActive;
77 };
78
79 // ============================================================================
80 // wxEventLoop implementation
81 // ============================================================================
82
83 wxEventLoop *wxEventLoopBase::ms_activeLoop = NULL;
84 wxWindowMSW *wxEventLoop::ms_winCritical = NULL;
85
86 // ----------------------------------------------------------------------------
87 // ctor/dtor
88 // ----------------------------------------------------------------------------
89
90 wxEventLoop::wxEventLoop()
91 {
92 m_shouldExit = false;
93 m_exitcode = 0;
94 }
95
96 // ----------------------------------------------------------------------------
97 // wxEventLoop message processing
98 // ----------------------------------------------------------------------------
99
100 void wxEventLoop::ProcessMessage(WXMSG *msg)
101 {
102 // give us the chance to preprocess the message first
103 if ( !PreProcessMessage(msg) )
104 {
105 // if it wasn't done, dispatch it to the corresponding window
106 ::TranslateMessage(msg);
107 ::DispatchMessage(msg);
108 }
109 }
110
111 bool wxEventLoop::IsChildOfCriticalWindow(wxWindowMSW *win)
112 {
113 while ( win )
114 {
115 if ( win == ms_winCritical )
116 return true;
117
118 win = win->GetParent();
119 }
120
121 return false;
122 }
123
124 bool wxEventLoop::PreProcessMessage(WXMSG *msg)
125 {
126 HWND hwnd = msg->hwnd;
127 wxWindow *wndThis = wxGetWindowFromHWND((WXHWND)hwnd);
128 wxWindow *wnd;
129
130 wxWindow* parent = NULL;
131
132 // this might happen if we're in a modeless dialog, or if a wx control has
133 // children which themselves were not created by wx (i.e. wxActiveX control children)
134 if ( !wndThis )
135 {
136 while ( hwnd && ::GetWindowLong(hwnd, GWL_STYLE) & WS_CHILD )
137 {
138 hwnd = ::GetParent(hwnd);
139
140 // If the control has a wx parent, break and give the parent a chance
141 // to process the window message
142 wndThis = wxGetWindowFromHWND((WXHWND)hwnd);
143 if (wndThis != NULL)
144 break;
145 }
146
147 if ( !wndThis ){
148 // this may happen if the event occurred in a standard modeless dialog (the
149 // only example of which I know of is the find/replace dialog) - then call
150 // IsDialogMessage() to make TAB navigation in it work
151
152 // NOTE: IsDialogMessage() just eats all the messages (i.e. returns true for
153 // them) if we call it for the control itself
154 return hwnd && ::IsDialogMessage(hwnd, msg) != 0;
155 }
156 }
157
158 if ( !AllowProcessing(wndThis) )
159 {
160 // not a child of critical window, so we eat the event but take care to
161 // stop an endless stream of WM_PAINTs which would have resulted if we
162 // didn't validate the invalidated part of the window
163 if ( msg->message == WM_PAINT )
164 ::ValidateRect(hwnd, NULL);
165
166 return true;
167 }
168
169 #if wxUSE_TOOLTIPS
170 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
171 // popup the tooltip bubbles
172 if ( msg->message == WM_MOUSEMOVE )
173 {
174 wxToolTip *tt = wndThis->GetToolTip();
175 if ( tt )
176 {
177 tt->RelayEvent((WXMSG *)msg);
178 }
179 }
180 #endif // wxUSE_TOOLTIPS
181
182 // allow the window to prevent certain messages from being
183 // translated/processed (this is currently used by wxTextCtrl to always
184 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
185 if ( !wndThis->MSWShouldPreProcessMessage((WXMSG *)msg) )
186 {
187 return false;
188 }
189
190 // try translations first: the accelerators override everything
191 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
192 {
193 if ( wnd->MSWTranslateMessage((WXMSG *)msg))
194 return true;
195
196 // stop at first top level window, i.e. don't try to process the key
197 // strokes originating in a dialog using the accelerators of the parent
198 // frame - this doesn't make much sense
199 if ( wnd->IsTopLevel() )
200 break;
201 }
202
203 // now try the other hooks (kbd navigation is handled here)
204 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
205 {
206 if (wnd != wndThis) // Skip the first since wndThis->MSWProcessMessage() was called above
207 {
208 if ( wnd->MSWProcessMessage((WXMSG *)msg) )
209 return true;
210 }
211
212 // Stop at first top level window (as per comment above).
213 // If we don't do this, pressing ESC on a modal dialog shown as child of a modal
214 // dialog with wxID_CANCEL will cause the parent dialog to be closed, for example
215 if (wnd->IsTopLevel())
216 break;
217 }
218
219 // no special preprocessing for this message, dispatch it normally
220 return false;
221 }
222
223 // ----------------------------------------------------------------------------
224 // wxEventLoop running and exiting
225 // ----------------------------------------------------------------------------
226
227 bool wxEventLoop::IsRunning() const
228 {
229 return ms_activeLoop == this;
230 }
231
232 int wxEventLoop::Run()
233 {
234 // event loops are not recursive, you need to create another loop!
235 wxCHECK_MSG( !IsRunning(), -1, _T("can't reenter a message loop") );
236
237 // ProcessIdle() and Dispatch() below may throw so the code here should
238 // be exception-safe, hence we must use local objects for all actions we
239 // should undo
240 wxEventLoopActivator activate(&ms_activeLoop, this);
241
242 // we must ensure that OnExit() is called even if an exception is thrown
243 // from inside Dispatch() but we must call it from Exit() in normal
244 // situations because it is supposed to be called synchronously,
245 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
246 // something similar here)
247 #if wxUSE_EXCEPTIONS
248 for ( ;; )
249 {
250 try
251 {
252 #endif // wxUSE_EXCEPTIONS
253
254 // this is the event loop itself
255 for ( ;; )
256 {
257 #if wxUSE_THREADS
258 wxMutexGuiLeaveOrEnter();
259 #endif // wxUSE_THREADS
260
261 // generate and process idle events for as long as we don't
262 // have anything else to do
263 while ( !Pending() && (wxTheApp && wxTheApp->ProcessIdle()) )
264 ;
265
266 // if the "should exit" flag is set, the loop should terminate
267 // but not before processing any remaining messages so while
268 // Pending() returns true, do process them
269 if ( m_shouldExit )
270 {
271 while ( Pending() )
272 Dispatch();
273
274 break;
275 }
276
277 // a message came or no more idle processing to do, sit in
278 // Dispatch() waiting for the next message
279 if ( !Dispatch() )
280 {
281 // we got WM_QUIT
282 break;
283 }
284 }
285
286 #if wxUSE_EXCEPTIONS
287 // exit the outer loop as well
288 break;
289 }
290 catch ( ... )
291 {
292 try
293 {
294 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
295 {
296 OnExit();
297 break;
298 }
299 //else: continue running the event loop
300 }
301 catch ( ... )
302 {
303 // OnException() throwed, possibly rethrowing the same
304 // exception again: very good, but we still need OnExit() to
305 // be called
306 OnExit();
307 throw;
308 }
309 }
310 }
311 #endif // wxUSE_EXCEPTIONS
312
313 return m_exitcode;
314 }
315
316 void wxEventLoop::Exit(int rc)
317 {
318 wxCHECK_RET( IsRunning(), _T("can't call Exit() if not running") );
319
320 m_exitcode = rc;
321 m_shouldExit = true;
322
323 OnExit();
324
325 // all we have to do to exit from the loop is to (maybe) wake it up so that
326 // it can notice that Exit() had been called
327 //
328 // in particular, we do *not* use PostQuitMessage() here because we're not
329 // sure that WM_QUIT is going to be processed by the correct event loop: it
330 // is possible that another one is started before this one has a chance to
331 // process WM_QUIT
332 ::PostMessage(NULL, WM_NULL, 0, 0);
333 }
334
335 // ----------------------------------------------------------------------------
336 // wxEventLoop message processing dispatching
337 // ----------------------------------------------------------------------------
338
339 bool wxEventLoop::Pending() const
340 {
341 MSG msg;
342 return ::PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE) != 0;
343 }
344
345 bool wxEventLoop::Dispatch()
346 {
347 wxCHECK_MSG( IsRunning(), false, _T("can't call Dispatch() if not running") );
348
349 MSG msg;
350 BOOL rc = ::GetMessage(&msg, (HWND) NULL, 0, 0);
351
352 if ( rc == 0 )
353 {
354 // got WM_QUIT
355 return false;
356 }
357
358 if ( rc == -1 )
359 {
360 // should never happen, but let's test for it nevertheless
361 wxLogLastError(wxT("GetMessage"));
362
363 // still break from the loop
364 return false;
365 }
366
367 #if wxUSE_THREADS
368 wxASSERT_MSG( wxThread::IsMain(),
369 wxT("only the main thread can process Windows messages") );
370
371 static bool s_hadGuiLock = true;
372 static wxMsgList s_aSavedMessages;
373
374 // if a secondary thread owning the mutex is doing GUI calls, save all
375 // messages for later processing - we can't process them right now because
376 // it will lead to recursive library calls (and we're not reentrant)
377 if ( !wxGuiOwnedByMainThread() )
378 {
379 s_hadGuiLock = false;
380
381 // leave out WM_COMMAND messages: too dangerous, sometimes
382 // the message will be processed twice
383 if ( !wxIsWaitingForThread() || msg.message != WM_COMMAND )
384 {
385 MSG* pMsg = new MSG(msg);
386 s_aSavedMessages.Append(pMsg);
387 }
388
389 return true;
390 }
391 else
392 {
393 // have we just regained the GUI lock? if so, post all of the saved
394 // messages
395 //
396 // FIXME of course, it's not _exactly_ the same as processing the
397 // messages normally - expect some things to break...
398 if ( !s_hadGuiLock )
399 {
400 s_hadGuiLock = true;
401
402 wxMsgList::compatibility_iterator node = s_aSavedMessages.GetFirst();
403 while (node)
404 {
405 MSG* pMsg = node->GetData();
406 s_aSavedMessages.Erase(node);
407
408 ProcessMessage(pMsg);
409 delete pMsg;
410
411 node = s_aSavedMessages.GetFirst();
412 }
413 }
414 }
415 #endif // wxUSE_THREADS
416
417 ProcessMessage(&msg);
418
419 return true;
420 }
421