Fix wxWakeUpIdle() in Unix console application broken by r71089.
[wxWidgets.git] / src / unix / evtloopunix.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/evtloopunix.cpp
3 // Purpose: wxEventLoop implementation
4 // Author: Lukasz Michalski (lm@zork.pl)
5 // Created: 2007-05-07
6 // RCS-ID: $Id$
7 // Copyright: (c) 2006 Zork Lukasz Michalski
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // ===========================================================================
12 // declarations
13 // ===========================================================================
14
15 // ---------------------------------------------------------------------------
16 // headers
17 // ---------------------------------------------------------------------------
18
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21
22 #if wxUSE_CONSOLE_EVENTLOOP
23
24 #include "wx/evtloop.h"
25
26 #ifndef WX_PRECOMP
27 #include "wx/app.h"
28 #include "wx/log.h"
29 #endif
30
31 #include <errno.h>
32 #include "wx/apptrait.h"
33 #include "wx/scopedptr.h"
34 #include "wx/thread.h"
35 #include "wx/module.h"
36 #include "wx/unix/pipe.h"
37 #include "wx/unix/private/timer.h"
38 #include "wx/unix/private/epolldispatcher.h"
39 #include "wx/private/selectdispatcher.h"
40
41 #if wxUSE_EVENTLOOP_SOURCE
42 #include "wx/evtloopsrc.h"
43 #endif // wxUSE_EVENTLOOP_SOURCE
44
45 #define TRACE_EVENTS wxT("events")
46
47 // ===========================================================================
48 // wxEventLoop::PipeIOHandler implementation
49 // ===========================================================================
50
51 namespace wxPrivate
52 {
53
54 // pipe used for wake up messages: when a child thread wants to wake up
55 // the event loop in the main thread it writes to this pipe
56 class PipeIOHandler : public wxFDIOHandler
57 {
58 public:
59 // default ctor does nothing, call Create() to really initialize the
60 // object
61 PipeIOHandler() : m_pipeIsEmpty(true) { }
62
63 bool Create();
64
65 // this method can be, and normally is, called from another thread
66 void WakeUp();
67
68 int GetReadFd() { return m_pipe[wxPipe::Read]; }
69
70 // implement wxFDIOHandler pure virtual methods
71 virtual void OnReadWaiting();
72 virtual void OnWriteWaiting() { }
73 virtual void OnExceptionWaiting() { }
74
75 private:
76 wxPipe m_pipe;
77
78 // Protects access to m_pipeIsEmpty.
79 wxCriticalSection m_pipeLock;
80
81 // This flag is set to true after writing to the pipe and reset to false
82 // after reading from it in the main thread. Having it allows us to avoid
83 // overflowing the pipe with too many writes if the main thread can't keep
84 // up with reading from it.
85 bool m_pipeIsEmpty;
86 };
87
88 // ----------------------------------------------------------------------------
89 // initialization
90 // ----------------------------------------------------------------------------
91
92 bool PipeIOHandler::Create()
93 {
94 if ( !m_pipe.Create() )
95 {
96 wxLogError(_("Failed to create wake up pipe used by event loop."));
97 return false;
98 }
99
100
101 if ( !m_pipe.MakeNonBlocking(wxPipe::Read) )
102 {
103 wxLogSysError(_("Failed to switch wake up pipe to non-blocking mode"));
104 return false;
105 }
106
107 wxLogTrace(TRACE_EVENTS, wxT("Wake up pipe (%d, %d) created"),
108 m_pipe[wxPipe::Read], m_pipe[wxPipe::Write]);
109
110 return true;
111 }
112
113 // ----------------------------------------------------------------------------
114 // wakeup handling
115 // ----------------------------------------------------------------------------
116
117 void PipeIOHandler::WakeUp()
118 {
119 wxCriticalSectionLocker lock(m_pipeLock);
120
121 // No need to do anything if the pipe already contains something.
122 if ( !m_pipeIsEmpty )
123 return;
124
125 if ( write(m_pipe[wxPipe::Write], "s", 1) != 1 )
126 {
127 // don't use wxLog here, we can be in another thread and this could
128 // result in dead locks
129 perror("write(wake up pipe)");
130 }
131 else
132 {
133 // We just wrote to it, so it's not empty any more.
134 m_pipeIsEmpty = false;
135 }
136 }
137
138 void PipeIOHandler::OnReadWaiting()
139 {
140 // got wakeup from child thread, remove the data that provoked it from the
141 // pipe
142
143 wxCriticalSectionLocker lock(m_pipeLock);
144
145 char buf[4];
146 for ( ;; )
147 {
148 const int size = read(GetReadFd(), buf, WXSIZEOF(buf));
149
150 if ( size > 0 )
151 {
152 wxASSERT_MSG( size == 1, "Too many writes to wake-up pipe?" );
153
154 break;
155 }
156
157 if ( size == 0 || (size == -1 && errno == EAGAIN) )
158 {
159 // No data available, not an error (but still surprising,
160 // spurious wakeup?)
161 break;
162 }
163
164 if ( errno == EINTR )
165 {
166 // We were interrupted, try again.
167 continue;
168 }
169
170 wxLogSysError(_("Failed to read from wake-up pipe"));
171
172 return;
173 }
174
175 // The pipe is empty now, so future calls to WakeUp() would need to write
176 // to it again.
177 m_pipeIsEmpty = true;
178
179 // writing to the wake up pipe will make wxConsoleEventLoop return from
180 // wxFDIODispatcher::Dispatch() it might be currently blocking in, nothing
181 // else needs to be done
182 }
183
184 } // namespace wxPrivate
185
186 // ===========================================================================
187 // wxEventLoop implementation
188 // ===========================================================================
189
190 //-----------------------------------------------------------------------------
191 // initialization
192 //-----------------------------------------------------------------------------
193
194 wxConsoleEventLoop::wxConsoleEventLoop()
195 {
196 m_wakeupPipe = new wxPrivate::PipeIOHandler();
197 if ( !m_wakeupPipe->Create() )
198 {
199 wxDELETE(m_wakeupPipe);
200 m_dispatcher = NULL;
201 return;
202 }
203
204 m_dispatcher = wxFDIODispatcher::Get();
205 if ( !m_dispatcher )
206 return;
207
208 m_dispatcher->RegisterFD
209 (
210 m_wakeupPipe->GetReadFd(),
211 m_wakeupPipe,
212 wxFDIO_INPUT
213 );
214 }
215
216 wxConsoleEventLoop::~wxConsoleEventLoop()
217 {
218 if ( m_wakeupPipe )
219 {
220 if ( m_dispatcher )
221 {
222 m_dispatcher->UnregisterFD(m_wakeupPipe->GetReadFd());
223 }
224
225 delete m_wakeupPipe;
226 }
227 }
228
229 //-----------------------------------------------------------------------------
230 // adding & removing sources
231 //-----------------------------------------------------------------------------
232
233 #if wxUSE_EVENTLOOP_SOURCE
234
235 // This class is a temporary bridge between event loop sources and
236 // FDIODispatcher. It is going to be removed soon, when all subject interfaces
237 // are modified
238 class wxFDIOEventLoopSourceHandler : public wxFDIOHandler
239 {
240 public:
241 wxFDIOEventLoopSourceHandler(wxEventLoopSourceHandler* handler) :
242 m_impl(handler) { }
243
244 virtual void OnReadWaiting()
245 {
246 m_impl->OnReadWaiting();
247 }
248 virtual void OnWriteWaiting()
249 {
250 m_impl->OnWriteWaiting();
251 }
252
253 virtual void OnExceptionWaiting()
254 {
255 m_impl->OnExceptionWaiting();
256 }
257
258 protected:
259 wxEventLoopSourceHandler* m_impl;
260 };
261
262 wxEventLoopSource *
263 wxConsoleEventLoop::AddSourceForFD(int fd,
264 wxEventLoopSourceHandler *handler,
265 int flags)
266 {
267 wxCHECK_MSG( fd != -1, NULL, "can't monitor invalid fd" );
268
269 wxLogTrace(wxTRACE_EVT_SOURCE,
270 "Adding event loop source for fd=%d", fd);
271
272 // we need a bridge to wxFDIODispatcher
273 //
274 // TODO: refactor the code so that only wxEventLoopSourceHandler is used
275 wxScopedPtr<wxFDIOHandler>
276 fdioHandler(new wxFDIOEventLoopSourceHandler(handler));
277
278 if ( !m_dispatcher->RegisterFD(fd, fdioHandler.get(), flags) )
279 return NULL;
280
281 return new wxUnixEventLoopSource(m_dispatcher, fdioHandler.release(),
282 fd, handler, flags);
283 }
284
285 wxUnixEventLoopSource::~wxUnixEventLoopSource()
286 {
287 wxLogTrace(wxTRACE_EVT_SOURCE,
288 "Removing event loop source for fd=%d", m_fd);
289
290 m_dispatcher->UnregisterFD(m_fd);
291
292 delete m_fdioHandler;
293 }
294
295 #endif // wxUSE_EVENTLOOP_SOURCE
296
297 //-----------------------------------------------------------------------------
298 // events dispatch and loop handling
299 //-----------------------------------------------------------------------------
300
301 bool wxConsoleEventLoop::Pending() const
302 {
303 if ( m_dispatcher->HasPending() )
304 return true;
305
306 #if wxUSE_TIMER
307 wxUsecClock_t nextTimer;
308 if ( wxTimerScheduler::Get().GetNext(&nextTimer) &&
309 !wxMilliClockToLong(nextTimer) )
310 return true;
311 #endif // wxUSE_TIMER
312
313 return false;
314 }
315
316 bool wxConsoleEventLoop::Dispatch()
317 {
318 DispatchTimeout(static_cast<unsigned long>(
319 wxFDIODispatcher::TIMEOUT_INFINITE));
320
321 return true;
322 }
323
324 int wxConsoleEventLoop::DispatchTimeout(unsigned long timeout)
325 {
326 #if wxUSE_TIMER
327 // check if we need to decrease the timeout to account for a timer
328 wxUsecClock_t nextTimer;
329 if ( wxTimerScheduler::Get().GetNext(&nextTimer) )
330 {
331 unsigned long timeUntilNextTimer = wxMilliClockToLong(nextTimer / 1000);
332 if ( timeUntilNextTimer < timeout )
333 timeout = timeUntilNextTimer;
334 }
335 #endif // wxUSE_TIMER
336
337 bool hadEvent = m_dispatcher->Dispatch(timeout) > 0;
338
339 #if wxUSE_TIMER
340 if ( wxTimerScheduler::Get().NotifyExpired() )
341 hadEvent = true;
342 #endif // wxUSE_TIMER
343
344 return hadEvent ? 1 : -1;
345 }
346
347 void wxConsoleEventLoop::WakeUp()
348 {
349 m_wakeupPipe->WakeUp();
350 }
351
352 void wxConsoleEventLoop::OnNextIteration()
353 {
354 // call the signal handlers for any signals we caught recently
355 wxTheApp->CheckSignal();
356 }
357
358
359 wxEventLoopBase *wxConsoleAppTraits::CreateEventLoop()
360 {
361 return new wxEventLoop();
362 }
363
364 #endif // wxUSE_CONSOLE_EVENTLOOP