Fix typo in wxGUIEventLoop::ScheduleExit() in wxMotif.
[wxWidgets.git] / src / motif / evtloop.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/motif/evtloop.cpp
3 // Purpose: implements wxEventLoop for Motif
4 // Author: Mattia Barbon
5 // Modified by:
6 // Created: 01.11.02
7 // RCS-ID: $Id$
8 // Copyright: (c) 2002 Mattia Barbon
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 #ifndef WX_PRECOMP
24 #include "wx/event.h"
25 #include "wx/app.h"
26 #include "wx/window.h"
27 #include "wx/module.h"
28 #endif //WX_PRECOMP
29
30 #include "wx/evtloop.h"
31 #include "wx/thread.h"
32
33 #ifdef __VMS__
34 #pragma message disable nosimpint
35 #endif
36 #include <Xm/Xm.h>
37 #include <X11/Xlib.h>
38 #ifdef __VMS__
39 #pragma message enable nosimpint
40 #endif
41
42 #include "wx/unix/private.h"
43 #include "wx/motif/private.h"
44
45 #ifdef HAVE_SYS_SELECT_H
46 # include <sys/select.h>
47 #endif
48
49 static bool CheckForKeyUp(XEvent* event);
50 static bool CheckForKeyDown(XEvent* event);
51 static bool CheckForAccelerator(XEvent* event);
52 static void ProcessXEvent(XEvent* event);
53 static void wxBreakDispatch();
54
55 // ----------------------------------------------------------------------------
56 // wxEventLoopImpl
57 // ----------------------------------------------------------------------------
58
59 class WXDLLEXPORT wxEventLoopImpl
60 {
61 public:
62 // ctor
63 wxEventLoopImpl() { SetExitCode(0); }
64
65 // set/get the exit code
66 void SetExitCode(int exitcode) { m_exitcode = exitcode; }
67 int GetExitCode() const { return m_exitcode; }
68
69 bool SendIdleMessage();
70 bool GetKeepGoing() const { return m_keepGoing; }
71 void SetKeepGoing(bool keepGoing) { m_keepGoing = keepGoing; }
72 private:
73 // the exit code of the event loop
74 int m_exitcode;
75 bool m_keepGoing;
76 };
77
78 // ----------------------------------------------------------------------------
79 // wxEventLoopImpl idle event processing
80 // ----------------------------------------------------------------------------
81
82 static bool SendIdleMessage()
83 {
84 return wxTheApp->ProcessIdle();
85 }
86
87 bool wxEventLoopImpl::SendIdleMessage()
88 {
89 return ::SendIdleMessage();
90 }
91
92 // ============================================================================
93 // wxEventLoop implementation
94 // ============================================================================
95
96 // ----------------------------------------------------------------------------
97 // wxEventLoop running and exiting
98 // ----------------------------------------------------------------------------
99
100 wxGUIEventLoop::~wxGUIEventLoop()
101 {
102 wxASSERT_MSG( !m_impl, wxT("should have been deleted in Run()") );
103 }
104
105 int wxGUIEventLoop::DoRun()
106 {
107 m_impl = new wxEventLoopImpl;
108 m_impl->SetKeepGoing( true );
109
110 for( ;; )
111 {
112 if( !wxDoEventLoopIteration( *this ) )
113 break;
114 }
115
116 OnExit();
117
118 int exitcode = m_impl->GetExitCode();
119 wxDELETE(m_impl);
120
121 return exitcode;
122 }
123
124 void wxGUIEventLoop::ScheduleExit(int rc)
125 {
126 wxCHECK_RET( IsInsideRun(), wxT("can't call ScheduleExit() if not started") );
127
128 m_impl->SetExitCode(rc);
129 m_impl->SetKeepGoing( false );
130
131 ::wxBreakDispatch();
132 }
133
134 bool wxGUIEventLoop::YieldFor(long eventsToProcess)
135 {
136 m_isInsideYield = true;
137 m_eventsToProcessInsideYield = eventsToProcess;
138
139 while (wxTheApp && wxTheApp->Pending())
140 // TODO: implement event filtering using the eventsToProcess mask
141 wxTheApp->Dispatch();
142
143 m_isInsideYield = false;
144
145 return true;
146 }
147
148 // ----------------------------------------------------------------------------
149 // wxEventLoop message processing dispatching
150 // ----------------------------------------------------------------------------
151
152 bool wxGUIEventLoop::Pending() const
153 {
154 return XtAppPending( (XtAppContext)wxTheApp->GetAppContext() ) != 0;
155 }
156
157 bool wxGUIEventLoop::Dispatch()
158 {
159 XEvent event;
160 XtAppContext context = (XtAppContext)wxTheApp->GetAppContext();
161
162 if( XtAppPeekEvent( context, &event ) != 0 )
163 {
164 XtAppNextEvent( context, &event );
165 ProcessXEvent( &event );
166 }
167 else
168 {
169 XtAppProcessEvent( context, XtIMTimer | XtIMAlternateInput
170 #ifdef XtIMSignal
171 | XtIMSignal
172 #endif
173 );
174 }
175
176 return m_impl ? m_impl->GetKeepGoing() : true;
177 }
178
179 // ----------------------------------------------------------------------------
180 // Static functions (originally in app.cpp)
181 // ----------------------------------------------------------------------------
182
183 void ProcessXEvent(XEvent* event)
184 {
185 if (event->type == KeyPress)
186 {
187 if (CheckForAccelerator(event))
188 {
189 // Do nothing! We intercepted and processed the event as an
190 // accelerator.
191 return;
192 }
193 // It seemed before that this hack was redundant and
194 // key down events were being generated by wxCanvasInputEvent.
195 // But no longer - why ???
196 //
197 else if (CheckForKeyDown(event))
198 {
199 // We intercepted and processed the key down event
200 return;
201 }
202 else
203 {
204 XtDispatchEvent(event);
205 return;
206 }
207 }
208 else if (event->type == KeyRelease)
209 {
210 // TODO: work out why we still need this ! -michael
211 //
212 if (::CheckForKeyUp(event))
213 {
214 // We intercepted and processed the key up event
215 return;
216 }
217 else
218 {
219 XtDispatchEvent(event);
220 return;
221 }
222 }
223 else if (event->type == PropertyNotify)
224 {
225 wxTheApp->HandlePropertyChange(event);
226 return;
227 }
228 else if (event->type == ResizeRequest)
229 {
230 /* Terry Gitnick <terryg@scientech.com> - 1/21/98
231 * If resize event, don't resize until the last resize event for this
232 * window is recieved. Prevents flicker as windows are resized.
233 */
234
235 Display *disp = event->xany.display;
236 Window win = event->xany.window;
237 XEvent report;
238
239 // to avoid flicker
240 report = * event;
241 while( XCheckTypedWindowEvent (disp, win, ResizeRequest, &report));
242
243 // TODO: when implementing refresh optimization, we can use
244 // XtAddExposureToRegion to expand the window's paint region.
245
246 XtDispatchEvent(event);
247 }
248 else
249 {
250 XtDispatchEvent(event);
251 }
252 }
253
254 // Returns true if an accelerator has been processed
255 bool CheckForAccelerator(XEvent* event)
256 {
257 if (event->xany.type == KeyPress)
258 {
259 // Find a wxWindow for this window
260 // TODO: should get display for the window, not the current display
261 Widget widget = XtWindowToWidget(event->xany.display,
262 event->xany.window);
263 wxWindow* win = NULL;
264
265 // Find the first wxWindow that corresponds to this event window
266 while (widget && ((win = wxGetWindowFromTable(widget))!=NULL))
267 widget = XtParent(widget);
268
269 if (!widget || !win)
270 return false;
271
272 wxKeyEvent keyEvent(wxEVT_CHAR);
273 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, event);
274
275 // Now we have a wxKeyEvent and we have a wxWindow.
276 // Go up the hierarchy until we find a matching accelerator,
277 // or we get to the top.
278 while (win)
279 {
280 if (win->ProcessAccelerator(keyEvent))
281 return true;
282 win = win->GetParent();
283 }
284 return false;
285 }
286 return false;
287 }
288
289 // bool wxApp::CheckForKeyDown(WXEvent* event) { wxFAIL; return false; }
290
291 bool CheckForKeyDown(XEvent* event)
292 {
293 if (event->xany.type == KeyPress)
294 {
295 Widget widget = XtWindowToWidget(event->xany.display,
296 event->xany.window);
297 wxWindow* win = NULL;
298
299 // Find the first wxWindow that corresponds to this event window
300 while (widget && ((win = wxGetWindowFromTable(widget))!=NULL))
301 widget = XtParent(widget);
302
303 if (!widget || !win)
304 return false;
305
306 wxKeyEvent keyEvent(wxEVT_KEY_DOWN);
307 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, event);
308
309 return win->HandleWindowEvent( keyEvent );
310 }
311
312 return false;
313 }
314
315 // bool wxApp::CheckForKeyUp(WXEvent* event) { wxFAIL; return false; }
316
317 bool CheckForKeyUp(XEvent* event)
318 {
319 if (event->xany.type == KeyRelease)
320 {
321 Widget widget = XtWindowToWidget(event->xany.display,
322 event->xany.window);
323 wxWindow* win = NULL;
324
325 // Find the first wxWindow that corresponds to this event window
326 while (widget && ((win = wxGetWindowFromTable(widget))!=NULL))
327 widget = XtParent(widget);
328
329 if (!widget || !win)
330 return false;
331
332 wxKeyEvent keyEvent(wxEVT_KEY_UP);
333 wxTranslateKeyEvent(keyEvent, win, (Widget) 0, event);
334
335 return win->HandleWindowEvent( keyEvent );
336 }
337
338 return false;
339 }
340
341 // ----------------------------------------------------------------------------
342 // executes one main loop iteration (declared in include/wx/motif/private.h)
343 // ----------------------------------------------------------------------------
344
345 bool wxDoEventLoopIteration( wxGUIEventLoop& evtLoop )
346 {
347 bool moreRequested, pendingEvents;
348
349 for(;;)
350 {
351 pendingEvents = evtLoop.Pending();
352 if( pendingEvents ) break;
353 moreRequested = ::SendIdleMessage();
354 if( !moreRequested ) break;
355 }
356
357 #if wxUSE_THREADS
358 if( !pendingEvents && !moreRequested )
359 {
360 // leave the main loop to give other threads a chance to
361 // perform their GUI work
362 wxMutexGuiLeave();
363 wxMilliSleep(20);
364 wxMutexGuiEnter();
365 }
366 #endif
367
368 if( !evtLoop.Dispatch() )
369 return false;
370
371 return true;
372 }
373
374 // ----------------------------------------------------------------------------
375 // ::wxWakeUpIdle implementation
376 // ----------------------------------------------------------------------------
377
378 // As per Vadim's suggestion, we open a pipe, and XtAppAddInputSource it;
379 // writing a single byte to the pipe will cause wxEventLoop::Pending
380 // to return true, and wxEventLoop::Dispatch to dispatch an input handler
381 // that simply removes the byte(s), and to return, which will cause
382 // an idle event to be sent
383
384 // also wxEventLoop::Exit is implemented that way, so that exiting an
385 // event loop won't require an event being in the queue
386
387 #include <sys/types.h>
388 #include <sys/time.h>
389 #include <unistd.h>
390
391 static int idleFds[2] = { -1, -1 };
392
393 class wxIdlePipeModule : public wxModule
394 {
395 public:
396 wxIdlePipeModule() {};
397
398 virtual bool OnInit()
399 {
400 // Must be done before modules are initialized
401 #if 0
402 if( pipe(idleFds) != 0 )
403 return false;
404 #endif
405 return true;
406 }
407
408 virtual void OnExit()
409 {
410 close( idleFds[0] );
411 close( idleFds[1] );
412 }
413 private:
414 DECLARE_DYNAMIC_CLASS(wxIdlePipeModule)
415 };
416
417 IMPLEMENT_DYNAMIC_CLASS(wxIdlePipeModule, wxModule)
418
419 static void wxInputCallback( XtPointer, int* fd, XtInputId* )
420 {
421 char buffer[128];
422
423 // wxWakeUpIdle may have been called more than once
424 for(;;)
425 {
426 fd_set in;
427 struct timeval timeout;
428
429 timeout.tv_sec = 0;
430 timeout.tv_usec = 0;
431
432 wxFD_ZERO( &in );
433 wxFD_SET( *fd, &in );
434
435 if( select( *fd + 1, &in, NULL, NULL, &timeout ) <= 0 )
436 break;
437 if( read( *fd, buffer, sizeof(buffer) - 1 ) != sizeof(buffer) - 1 )
438 break;
439 }
440 }
441
442 static void wxBreakDispatch()
443 {
444 char dummy = 0; // for valgrind
445
446 // check if wxWakeUpIdle has already been called
447 fd_set in;
448 struct timeval timeout;
449
450 timeout.tv_sec = 0;
451 timeout.tv_usec = 0;
452
453 wxFD_ZERO( &in );
454 wxFD_SET( idleFds[0], &in );
455
456 if( select( idleFds[0] + 1, &in, NULL, NULL, &timeout ) > 0 )
457 return;
458
459 // write a single byte
460 write( idleFds[1], &dummy, 1 );
461 }
462
463 void wxApp::WakeUpIdle()
464 {
465 ::wxBreakDispatch();
466 }
467
468 bool wxInitIdleFds()
469 {
470 if( pipe(idleFds) != 0 )
471 return false;
472 return true;
473 }
474
475 bool wxAddIdleCallback()
476 {
477 if (!wxInitIdleFds())
478 return false;
479
480 // install input handler for wxWakeUpIdle
481 XtAppAddInput((XtAppContext) wxTheApp->GetAppContext(),
482 idleFds[0],
483 (XtPointer)XtInputReadMask,
484 wxInputCallback,
485 NULL);
486
487 return true;
488 }