Refactor wxEventLoopSource-related code.
[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() { }
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
79 // ----------------------------------------------------------------------------
80 // initialization
81 // ----------------------------------------------------------------------------
82
83 bool PipeIOHandler::Create()
84 {
85 if ( !m_pipe.Create() )
86 {
87 wxLogError(_("Failed to create wake up pipe used by event loop."));
88 return false;
89 }
90
91 const int fdRead = GetReadFd();
92
93 int flags = fcntl(fdRead, F_GETFL, 0);
94 if ( flags == -1 || fcntl(fdRead, F_SETFL, flags | O_NONBLOCK) == -1 )
95 {
96 wxLogSysError(_("Failed to switch wake up pipe to non-blocking mode"));
97 return false;
98 }
99
100 wxLogTrace(TRACE_EVENTS, wxT("Wake up pipe (%d, %d) created"),
101 fdRead, m_pipe[wxPipe::Write]);
102
103 return true;
104 }
105
106 // ----------------------------------------------------------------------------
107 // wakeup handling
108 // ----------------------------------------------------------------------------
109
110 void PipeIOHandler::WakeUp()
111 {
112 if ( write(m_pipe[wxPipe::Write], "s", 1) != 1 )
113 {
114 // don't use wxLog here, we can be in another thread and this could
115 // result in dead locks
116 perror("write(wake up pipe)");
117 }
118 }
119
120 void PipeIOHandler::OnReadWaiting()
121 {
122 // got wakeup from child thread: read all data available in pipe just to
123 // make it empty (even though we write one byte at a time from WakeUp(),
124 // it could have been called several times)
125 char buf[4];
126 for ( ;; )
127 {
128 const int size = read(GetReadFd(), buf, WXSIZEOF(buf));
129
130 if ( size == 0 || (size == -1 && (errno == EAGAIN || errno == EINTR)) )
131 {
132 // nothing left in the pipe (EAGAIN is expected for an FD with
133 // O_NONBLOCK)
134 break;
135 }
136
137 if ( size == -1 )
138 {
139 wxLogSysError(_("Failed to read from wake-up pipe"));
140
141 break;
142 }
143 }
144
145 // writing to the wake up pipe will make wxConsoleEventLoop return from
146 // wxFDIODispatcher::Dispatch() it might be currently blocking in, nothing
147 // else needs to be done
148 }
149
150 } // namespace wxPrivate
151
152 // ===========================================================================
153 // wxEventLoop implementation
154 // ===========================================================================
155
156 //-----------------------------------------------------------------------------
157 // initialization
158 //-----------------------------------------------------------------------------
159
160 wxConsoleEventLoop::wxConsoleEventLoop()
161 {
162 m_wakeupPipe = new wxPrivate::PipeIOHandler();
163 if ( !m_wakeupPipe->Create() )
164 {
165 wxDELETE(m_wakeupPipe);
166 m_dispatcher = NULL;
167 return;
168 }
169
170 m_dispatcher = wxFDIODispatcher::Get();
171 if ( !m_dispatcher )
172 return;
173
174 m_dispatcher->RegisterFD
175 (
176 m_wakeupPipe->GetReadFd(),
177 m_wakeupPipe,
178 wxFDIO_INPUT
179 );
180 }
181
182 wxConsoleEventLoop::~wxConsoleEventLoop()
183 {
184 if ( m_wakeupPipe )
185 {
186 if ( m_dispatcher )
187 {
188 m_dispatcher->UnregisterFD(m_wakeupPipe->GetReadFd());
189 }
190
191 delete m_wakeupPipe;
192 }
193 }
194
195 //-----------------------------------------------------------------------------
196 // adding & removing sources
197 //-----------------------------------------------------------------------------
198
199 #if wxUSE_EVENTLOOP_SOURCE
200
201 // This class is a temporary bridge between event loop sources and
202 // FDIODispatcher. It is going to be removed soon, when all subject interfaces
203 // are modified
204 class wxFDIOEventLoopSourceHandler : public wxFDIOHandler
205 {
206 public:
207 wxFDIOEventLoopSourceHandler(wxEventLoopSourceHandler* handler) :
208 m_impl(handler) { }
209
210 virtual void OnReadWaiting()
211 {
212 m_impl->OnReadWaiting();
213 }
214 virtual void OnWriteWaiting()
215 {
216 m_impl->OnWriteWaiting();
217 }
218
219 virtual void OnExceptionWaiting()
220 {
221 m_impl->OnExceptionWaiting();
222 }
223
224 protected:
225 wxEventLoopSourceHandler* m_impl;
226 };
227
228 wxEventLoopSource *
229 wxConsoleEventLoop::AddSourceForFD(int fd,
230 wxEventLoopSourceHandler *handler,
231 int flags)
232 {
233 wxCHECK_MSG( fd != -1, NULL, "can't monitor invalid fd" );
234
235 wxLogTrace(wxTRACE_EVT_SOURCE,
236 "Adding event loop source for fd=%d", fd);
237
238 // we need a bridge to wxFDIODispatcher
239 //
240 // TODO: refactor the code so that only wxEventLoopSourceHandler is used
241 wxScopedPtr<wxFDIOHandler>
242 fdioHandler(new wxFDIOEventLoopSourceHandler(handler));
243
244 if ( !m_dispatcher->RegisterFD(fd, fdioHandler.get(), flags) )
245 return NULL;
246
247 return new wxUnixEventLoopSource(m_dispatcher, fdioHandler.release(),
248 fd, handler, flags);
249 }
250
251 wxUnixEventLoopSource::~wxUnixEventLoopSource()
252 {
253 wxLogTrace(wxTRACE_EVT_SOURCE,
254 "Removing event loop source for fd=%d", m_fd);
255
256 m_dispatcher->UnregisterFD(m_fd);
257
258 delete m_fdioHandler;
259 }
260
261 #endif // wxUSE_EVENTLOOP_SOURCE
262
263 //-----------------------------------------------------------------------------
264 // events dispatch and loop handling
265 //-----------------------------------------------------------------------------
266
267 bool wxConsoleEventLoop::Pending() const
268 {
269 if ( m_dispatcher->HasPending() )
270 return true;
271
272 #if wxUSE_TIMER
273 wxUsecClock_t nextTimer;
274 if ( wxTimerScheduler::Get().GetNext(&nextTimer) &&
275 !wxMilliClockToLong(nextTimer) )
276 return true;
277 #endif // wxUSE_TIMER
278
279 return false;
280 }
281
282 bool wxConsoleEventLoop::Dispatch()
283 {
284 DispatchTimeout(static_cast<unsigned long>(
285 wxFDIODispatcher::TIMEOUT_INFINITE));
286
287 return true;
288 }
289
290 int wxConsoleEventLoop::DispatchTimeout(unsigned long timeout)
291 {
292 #if wxUSE_TIMER
293 // check if we need to decrease the timeout to account for a timer
294 wxUsecClock_t nextTimer;
295 if ( wxTimerScheduler::Get().GetNext(&nextTimer) )
296 {
297 unsigned long timeUntilNextTimer = wxMilliClockToLong(nextTimer / 1000);
298 if ( timeUntilNextTimer < timeout )
299 timeout = timeUntilNextTimer;
300 }
301 #endif // wxUSE_TIMER
302
303 bool hadEvent = m_dispatcher->Dispatch(timeout) > 0;
304
305 #if wxUSE_TIMER
306 if ( wxTimerScheduler::Get().NotifyExpired() )
307 hadEvent = true;
308 #endif // wxUSE_TIMER
309
310 return hadEvent ? 1 : -1;
311 }
312
313 void wxConsoleEventLoop::WakeUp()
314 {
315 m_wakeupPipe->WakeUp();
316 }
317
318 void wxConsoleEventLoop::OnNextIteration()
319 {
320 // call the signal handlers for any signals we caught recently
321 wxTheApp->CheckSignal();
322 }
323
324
325 wxEventLoopBase *wxConsoleAppTraits::CreateEventLoop()
326 {
327 return new wxEventLoop();
328 }
329
330 #endif // wxUSE_CONSOLE_EVENTLOOP