1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/message_pump_glib.h"
12 #include "base/eintr_wrapper.h"
13 #include "base/logging.h"
14 #include "base/threading/platform_thread.h"
18 // Return a timeout suitable for the glib loop, -1 to block forever,
19 // 0 to return right away, or a timeout in milliseconds from now.
20 int GetTimeIntervalMilliseconds(const base::TimeTicks
& from
) {
24 // Be careful here. TimeDelta has a precision of microseconds, but we want a
25 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
26 // 6? It should be 6 to avoid executing delayed work too early.
27 int delay
= static_cast<int>(
28 ceil((from
- base::TimeTicks::Now()).InMillisecondsF()));
30 // If this value is negative, then we need to run delayed work soon.
31 return delay
< 0 ? 0 : delay
;
34 // A brief refresher on GLib:
35 // GLib sources have four callbacks: Prepare, Check, Dispatch and Finalize.
36 // On each iteration of the GLib pump, it calls each source's Prepare function.
37 // This function should return TRUE if it wants GLib to call its Dispatch, and
38 // FALSE otherwise. It can also set a timeout in this case for the next time
39 // Prepare should be called again (it may be called sooner).
40 // After the Prepare calls, GLib does a poll to check for events from the
41 // system. File descriptors can be attached to the sources. The poll may block
42 // if none of the Prepare calls returned TRUE. It will block indefinitely, or
43 // by the minimum time returned by a source in Prepare.
44 // After the poll, GLib calls Check for each source that returned FALSE
45 // from Prepare. The return value of Check has the same meaning as for Prepare,
46 // making Check a second chance to tell GLib we are ready for Dispatch.
47 // Finally, GLib calls Dispatch for each source that is ready. If Dispatch
48 // returns FALSE, GLib will destroy the source. Dispatch calls may be recursive
49 // (i.e., you can call Run from them), but Prepare and Check cannot.
50 // Finalize is called when the source is destroyed.
51 // NOTE: It is common for subsytems to want to process pending events while
52 // doing intensive work, for example the flash plugin. They usually use the
53 // following pattern (recommended by the GTK docs):
54 // while (gtk_events_pending()) {
55 // gtk_main_iteration();
58 // gtk_events_pending just calls g_main_context_pending, which does the
60 // - Call prepare on all the sources.
61 // - Do the poll with a timeout of 0 (not blocking).
62 // - Call check on all the sources.
63 // - *Does not* call dispatch on the sources.
64 // - Return true if any of prepare() or check() returned true.
66 // gtk_main_iteration just calls g_main_context_iteration, which does the whole
67 // thing, respecting the timeout for the poll (and block, although it is
68 // expected not to if gtk_events_pending returned true), and call dispatch.
70 // Thus it is important to only return true from prepare or check if we
71 // actually have events or work to do. We also need to make sure we keep
72 // internal state consistent so that if prepare/check return true when called
73 // from gtk_events_pending, they will still return true when called right
74 // after, from gtk_main_iteration.
76 // For the GLib pump we try to follow the Windows UI pump model:
77 // - Whenever we receive a wakeup event or the timer for delayed work expires,
78 // we run DoWork and/or DoDelayedWork. That part will also run in the other
80 // - We also run DoWork, DoDelayedWork, and possibly DoIdleWork in the main
81 // loop, around event handling.
83 struct WorkSource
: public GSource
{
84 base::MessagePumpGlib
* pump
;
87 gboolean
WorkSourcePrepare(GSource
* source
,
89 *timeout_ms
= static_cast<WorkSource
*>(source
)->pump
->HandlePrepare();
90 // We always return FALSE, so that our timeout is honored. If we were
91 // to return TRUE, the timeout would be considered to be 0 and the poll
92 // would never block. Once the poll is finished, Check will be called.
96 gboolean
WorkSourceCheck(GSource
* source
) {
97 // Only return TRUE if Dispatch should be called.
98 return static_cast<WorkSource
*>(source
)->pump
->HandleCheck();
101 gboolean
WorkSourceDispatch(GSource
* source
,
102 GSourceFunc unused_func
,
103 gpointer unused_data
) {
105 static_cast<WorkSource
*>(source
)->pump
->HandleDispatch();
106 // Always return TRUE so our source stays registered.
110 // I wish these could be const, but g_source_new wants non-const.
111 GSourceFuncs WorkSourceFuncs
= {
123 struct MessagePumpGlib::RunState
{
125 MessagePumpDispatcher
* dispatcher
;
127 // Used to flag that the current Run() invocation should return ASAP.
130 // Used to count how many Run() invocations are on the stack.
133 // This keeps the state of whether the pump got signaled that there was new
134 // work to be done. Since we eat the message on the wake up pipe as soon as
135 // we get it, we keep that state here to stay consistent.
139 MessagePumpGlib::MessagePumpGlib()
141 context_(g_main_context_default()),
142 wakeup_gpollfd_(new GPollFD
) {
143 // Create our wakeup pipe, which is used to flag when work was scheduled.
147 (void)ret
; // Prevent warning in release mode.
149 wakeup_pipe_read_
= fds
[0];
150 wakeup_pipe_write_
= fds
[1];
151 wakeup_gpollfd_
->fd
= wakeup_pipe_read_
;
152 wakeup_gpollfd_
->events
= G_IO_IN
;
154 work_source_
= g_source_new(&WorkSourceFuncs
, sizeof(WorkSource
));
155 static_cast<WorkSource
*>(work_source_
)->pump
= this;
156 g_source_add_poll(work_source_
, wakeup_gpollfd_
.get());
157 // Use a low priority so that we let other events in the queue go first.
158 g_source_set_priority(work_source_
, G_PRIORITY_DEFAULT_IDLE
);
159 // This is needed to allow Run calls inside Dispatch.
160 g_source_set_can_recurse(work_source_
, TRUE
);
161 g_source_attach(work_source_
, context_
);
164 MessagePumpGlib::~MessagePumpGlib() {
165 g_source_destroy(work_source_
);
166 g_source_unref(work_source_
);
167 close(wakeup_pipe_read_
);
168 close(wakeup_pipe_write_
);
171 void MessagePumpGlib::RunWithDispatcher(Delegate
* delegate
,
172 MessagePumpDispatcher
* dispatcher
) {
174 // Make sure we only run this on one thread. X/GTK only has one message pump
175 // so we can only have one UI loop per process.
176 static base::PlatformThreadId thread_id
= base::PlatformThread::CurrentId();
177 DCHECK(thread_id
== base::PlatformThread::CurrentId()) <<
178 "Running MessagePumpGlib on two different threads; "
179 "this is unsupported by GLib!";
183 state
.delegate
= delegate
;
184 state
.dispatcher
= dispatcher
;
185 state
.should_quit
= false;
186 state
.run_depth
= state_
? state_
->run_depth
+ 1 : 1;
187 state
.has_work
= false;
189 RunState
* previous_state
= state_
;
192 // We really only do a single task for each iteration of the loop. If we
193 // have done something, assume there is likely something more to do. This
194 // will mean that we don't block on the message pump until there was nothing
195 // more to do. We also set this to true to make sure not to block on the
196 // first iteration of the loop, so RunAllPending() works correctly.
197 bool more_work_is_plausible
= true;
199 // We run our own loop instead of using g_main_loop_quit in one of the
200 // callbacks. This is so we only quit our own loops, and we don't quit
201 // nested loops run by others. TODO(deanm): Is this what we want?
203 // Don't block if we think we have more work to do.
204 bool block
= !more_work_is_plausible
;
206 more_work_is_plausible
= g_main_context_iteration(context_
, block
);
207 if (state_
->should_quit
)
210 more_work_is_plausible
|= state_
->delegate
->DoWork();
211 if (state_
->should_quit
)
214 more_work_is_plausible
|=
215 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
216 if (state_
->should_quit
)
219 if (more_work_is_plausible
)
222 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
223 if (state_
->should_quit
)
227 state_
= previous_state
;
230 // Return the timeout we want passed to poll.
231 int MessagePumpGlib::HandlePrepare() {
232 // We know we have work, but we haven't called HandleDispatch yet. Don't let
233 // the pump block so that we can do some processing.
234 if (state_
&& // state_ may be null during tests.
238 // We don't think we have work to do, but make sure not to block
239 // longer than the next time we need to run delayed work.
240 return GetTimeIntervalMilliseconds(delayed_work_time_
);
243 bool MessagePumpGlib::HandleCheck() {
244 if (!state_
) // state_ may be null during tests.
247 // We should only ever have a single message on the wakeup pipe, since we
248 // are only signaled when the queue went from empty to non-empty. The glib
249 // poll will tell us whether there was data, so this read shouldn't block.
250 if (wakeup_gpollfd_
->revents
& G_IO_IN
) {
252 if (HANDLE_EINTR(read(wakeup_pipe_read_
, &msg
, 1)) != 1 || msg
!= '!') {
253 NOTREACHED() << "Error reading from the wakeup pipe.";
255 // Since we ate the message, we need to record that we have more work,
256 // because HandleCheck() may be called without HandleDispatch being called
258 state_
->has_work
= true;
261 if (state_
->has_work
)
264 if (GetTimeIntervalMilliseconds(delayed_work_time_
) == 0) {
265 // The timer has expired. That condition will stay true until we process
266 // that delayed work, so we don't need to record this differently.
273 void MessagePumpGlib::HandleDispatch() {
274 state_
->has_work
= false;
275 if (state_
->delegate
->DoWork()) {
276 // NOTE: on Windows at this point we would call ScheduleWork (see
277 // MessagePumpGlib::HandleWorkMessage in message_pump_win.cc). But here,
278 // instead of posting a message on the wakeup pipe, we can avoid the
279 // syscalls and just signal that we have more work.
280 state_
->has_work
= true;
283 if (state_
->should_quit
)
286 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
289 void MessagePumpGlib::AddObserver(MessagePumpObserver
* observer
) {
290 observers_
.AddObserver(observer
);
293 void MessagePumpGlib::RemoveObserver(MessagePumpObserver
* observer
) {
294 observers_
.RemoveObserver(observer
);
297 void MessagePumpGlib::Run(Delegate
* delegate
) {
298 RunWithDispatcher(delegate
, NULL
);
301 void MessagePumpGlib::Quit() {
303 state_
->should_quit
= true;
305 NOTREACHED() << "Quit called outside Run!";
309 void MessagePumpGlib::ScheduleWork() {
310 // This can be called on any thread, so we don't want to touch any state
311 // variables as we would then need locks all over. This ensures that if
312 // we are sleeping in a poll that we will wake up.
314 if (HANDLE_EINTR(write(wakeup_pipe_write_
, &msg
, 1)) != 1) {
315 NOTREACHED() << "Could not write to the UI message loop wakeup pipe!";
319 void MessagePumpGlib::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
320 // We need to wake up the loop in case the poll timeout needs to be
321 // adjusted. This will cause us to try to do work, but that's ok.
322 delayed_work_time_
= delayed_work_time
;
326 MessagePumpDispatcher
* MessagePumpGlib::GetDispatcher() {
327 return state_
? state_
->dispatcher
: NULL
;