don't use wx/scopeguard.h for OpenWatcom compatibility (grr...)
[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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "evtloop.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/window.h"
33 #include "wx/app.h"
34 #endif //WX_PRECOMP
35
36 #include "wx/evtloop.h"
37
38 #include "wx/tooltip.h"
39 #include "wx/except.h"
40 #include "wx/ptr_scpd.h"
41
42 #include "wx/msw/private.h"
43
44 #if wxUSE_THREADS
45 #include "wx/thread.h"
46
47 // define the array of MSG strutures
48 WX_DECLARE_OBJARRAY(MSG, wxMsgArray);
49
50 #include "wx/arrimpl.cpp"
51
52 WX_DEFINE_OBJARRAY(wxMsgArray);
53 #endif // wxUSE_THREADS
54
55 // ----------------------------------------------------------------------------
56 // wxEventLoopImpl
57 // ----------------------------------------------------------------------------
58
59 class WXDLLEXPORT wxEventLoopImpl
60 {
61 public:
62 // ctor
63 wxEventLoopImpl() { SetExitCode(0); }
64
65 // process a message
66 void ProcessMessage(MSG *msg);
67
68 // generate an idle message, return TRUE if more idle time requested
69 bool SendIdleMessage();
70
71 // set/get the exit code
72 void SetExitCode(int exitcode) { m_exitcode = exitcode; }
73 int GetExitCode() const { return m_exitcode; }
74
75 private:
76 // preprocess a message, return TRUE if processed (i.e. no further
77 // dispatching required)
78 bool PreProcessMessage(MSG *msg);
79
80 // the exit code of the event loop
81 int m_exitcode;
82 };
83
84 // ----------------------------------------------------------------------------
85 // helper class
86 // ----------------------------------------------------------------------------
87
88 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoopImpl);
89
90 // this object sets the wxEventLoop given to the ctor as the currently active
91 // one and unsets it in its dtor
92 class wxEventLoopActivator
93 {
94 public:
95 wxEventLoopActivator(wxEventLoop **pActive,
96 wxEventLoop *evtLoop)
97 {
98 m_pActive = pActive;
99 m_evtLoopOld = *pActive;
100 *pActive = evtLoop;
101 }
102
103 ~wxEventLoopActivator()
104 {
105 // restore the previously active event loop
106 *m_pActive = m_evtLoopOld;
107 }
108
109 private:
110 wxEventLoop *m_evtLoopOld;
111 wxEventLoop **m_pActive;
112 };
113
114 // ============================================================================
115 // wxEventLoopImpl implementation
116 // ============================================================================
117
118 // ----------------------------------------------------------------------------
119 // wxEventLoopImpl message processing
120 // ----------------------------------------------------------------------------
121
122 void wxEventLoopImpl::ProcessMessage(MSG *msg)
123 {
124 // give us the chance to preprocess the message first
125 if ( !PreProcessMessage(msg) )
126 {
127 // if it wasn't done, dispatch it to the corresponding window
128 ::TranslateMessage(msg);
129 ::DispatchMessage(msg);
130 }
131 }
132
133 bool wxEventLoopImpl::PreProcessMessage(MSG *msg)
134 {
135 HWND hwnd = msg->hwnd;
136 wxWindow *wndThis = wxGetWindowFromHWND((WXHWND)hwnd);
137
138 // this may happen if the event occured in a standard modeless dialog (the
139 // only example of which I know of is the find/replace dialog) - then call
140 // IsDialogMessage() to make TAB navigation in it work
141 if ( !wndThis )
142 {
143 // we need to find the dialog containing this control as
144 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
145 // them) if we call it for the control itself
146 while ( hwnd && ::GetWindowLong(hwnd, GWL_STYLE) & WS_CHILD )
147 {
148 hwnd = ::GetParent(hwnd);
149 }
150
151 return hwnd && ::IsDialogMessage(hwnd, msg) != 0;
152 }
153
154 #if wxUSE_TOOLTIPS
155 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
156 // popup the tooltip bubbles
157 if ( msg->message == WM_MOUSEMOVE )
158 {
159 wxToolTip *tt = wndThis->GetToolTip();
160 if ( tt )
161 {
162 tt->RelayEvent((WXMSG *)msg);
163 }
164 }
165 #endif // wxUSE_TOOLTIPS
166
167 // allow the window to prevent certain messages from being
168 // translated/processed (this is currently used by wxTextCtrl to always
169 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
170 if ( !wndThis->MSWShouldPreProcessMessage((WXMSG *)msg) )
171 {
172 return FALSE;
173 }
174
175 // try translations first: the accelerators override everything
176 wxWindow *wnd;
177
178 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
179 {
180 if ( wnd->MSWTranslateMessage((WXMSG *)msg))
181 return TRUE;
182
183 // stop at first top level window, i.e. don't try to process the key
184 // strokes originating in a dialog using the accelerators of the parent
185 // frame - this doesn't make much sense
186 if ( wnd->IsTopLevel() )
187 break;
188 }
189
190 // now try the other hooks (kbd navigation is handled here): we start from
191 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
192 // called above
193 for ( wnd = wndThis->GetParent(); wnd; wnd = wnd->GetParent() )
194 {
195 if ( wnd->MSWProcessMessage((WXMSG *)msg) )
196 return TRUE;
197 }
198
199 // no special preprocessing for this message, dispatch it normally
200 return FALSE;
201 }
202
203 // ----------------------------------------------------------------------------
204 // wxEventLoopImpl idle event processing
205 // ----------------------------------------------------------------------------
206
207 bool wxEventLoopImpl::SendIdleMessage()
208 {
209 return wxTheApp->ProcessIdle();
210 }
211
212 // ============================================================================
213 // wxEventLoop implementation
214 // ============================================================================
215
216 wxEventLoop *wxEventLoop::ms_activeLoop = NULL;
217
218 // ----------------------------------------------------------------------------
219 // wxEventLoop running and exiting
220 // ----------------------------------------------------------------------------
221
222 wxEventLoop::~wxEventLoop()
223 {
224 wxASSERT_MSG( !m_impl, _T("should have been deleted in Run()") );
225 }
226
227 bool wxEventLoop::IsRunning() const
228 {
229 return m_impl != NULL;
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 // SendIdleMessage() 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 wxEventLoopImplTiedPtr impl(&m_impl, new wxEventLoopImpl);
242
243 class CallEventLoopMethod
244 {
245 public:
246 typedef void (wxEventLoop::*FuncType)();
247
248 CallEventLoopMethod(wxEventLoop *evtLoop, FuncType fn)
249 : m_evtLoop(evtLoop), m_fn(fn) { }
250 ~CallEventLoopMethod() { (m_evtLoop->*m_fn)(); }
251
252 private:
253 wxEventLoop *m_evtLoop;
254 FuncType m_fn;
255 } callOnExit(this, wxEventLoop::OnExit);
256
257 for ( ;; )
258 {
259 #if wxUSE_THREADS
260 wxMutexGuiLeaveOrEnter();
261 #endif // wxUSE_THREADS
262
263 // generate and process idle events for as long as we don't have
264 // anything else to do
265 while ( !Pending() && m_impl->SendIdleMessage() )
266 ;
267
268 // a message came or no more idle processing to do, sit in
269 // Dispatch() waiting for the next message
270 if ( !Dispatch() )
271 {
272 // we got WM_QUIT
273 break;
274 }
275 }
276
277 return m_impl->GetExitCode();
278 }
279
280 void wxEventLoop::Exit(int rc)
281 {
282 wxCHECK_RET( IsRunning(), _T("can't call Exit() if not running") );
283
284 m_impl->SetExitCode(rc);
285
286 ::PostQuitMessage(rc);
287 }
288
289 // ----------------------------------------------------------------------------
290 // wxEventLoop message processing dispatching
291 // ----------------------------------------------------------------------------
292
293 bool wxEventLoop::Pending() const
294 {
295 MSG msg;
296 return ::PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE) != 0;
297 }
298
299 bool wxEventLoop::Dispatch()
300 {
301 wxCHECK_MSG( IsRunning(), FALSE, _T("can't call Dispatch() if not running") );
302
303 MSG msg;
304 BOOL rc = ::GetMessage(&msg, (HWND) NULL, 0, 0);
305
306 if ( rc == 0 )
307 {
308 // got WM_QUIT
309 return FALSE;
310 }
311
312 if ( rc == -1 )
313 {
314 // should never happen, but let's test for it nevertheless
315 wxLogLastError(wxT("GetMessage"));
316
317 // still break from the loop
318 return FALSE;
319 }
320
321 #if wxUSE_THREADS
322 wxASSERT_MSG( wxThread::IsMain(),
323 wxT("only the main thread can process Windows messages") );
324
325 static bool s_hadGuiLock = TRUE;
326 static wxMsgArray s_aSavedMessages;
327
328 // if a secondary thread owning the mutex is doing GUI calls, save all
329 // messages for later processing - we can't process them right now because
330 // it will lead to recursive library calls (and we're not reentrant)
331 if ( !wxGuiOwnedByMainThread() )
332 {
333 s_hadGuiLock = FALSE;
334
335 // leave out WM_COMMAND messages: too dangerous, sometimes
336 // the message will be processed twice
337 if ( !wxIsWaitingForThread() || msg.message != WM_COMMAND )
338 {
339 s_aSavedMessages.Add(msg);
340 }
341
342 return TRUE;
343 }
344 else
345 {
346 // have we just regained the GUI lock? if so, post all of the saved
347 // messages
348 //
349 // FIXME of course, it's not _exactly_ the same as processing the
350 // messages normally - expect some things to break...
351 if ( !s_hadGuiLock )
352 {
353 s_hadGuiLock = TRUE;
354
355 size_t count = s_aSavedMessages.Count();
356 for ( size_t n = 0; n < count; n++ )
357 {
358 MSG& msg = s_aSavedMessages[n];
359 m_impl->ProcessMessage(&msg);
360 }
361
362 s_aSavedMessages.Empty();
363 }
364 }
365 #endif // wxUSE_THREADS
366
367 m_impl->ProcessMessage(&msg);
368
369 return TRUE;
370 }
371