1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 // Copyright (c) 2008 The Chromium Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
6 
7 #include "base/message_pump_glib.h"
8 
9 #include <fcntl.h>
10 #include <math.h>
11 
12 #include <gtk/gtk.h>
13 #include <glib.h>
14 
15 #include "base/eintr_wrapper.h"
16 #include "base/logging.h"
17 #include "base/platform_thread.h"
18 
19 namespace {
20 
21 // Return a timeout suitable for the glib loop, -1 to block forever,
22 // 0 to return right away, or a timeout in milliseconds from now.
GetTimeIntervalMilliseconds(const base::TimeTicks & from)23 int GetTimeIntervalMilliseconds(const base::TimeTicks& from) {
24   if (from.is_null()) return -1;
25 
26   // Be careful here.  TimeDelta has a precision of microseconds, but we want a
27   // value in milliseconds.  If there are 5.5ms left, should the delay be 5 or
28   // 6?  It should be 6 to avoid executing delayed work too early.
29   int delay =
30       static_cast<int>(ceil((from - base::TimeTicks::Now()).InMillisecondsF()));
31 
32   // If this value is negative, then we need to run delayed work soon.
33   return delay < 0 ? 0 : delay;
34 }
35 
36 // A brief refresher on GLib:
37 //     GLib sources have four callbacks: Prepare, Check, Dispatch and Finalize.
38 // On each iteration of the GLib pump, it calls each source's Prepare function.
39 // This function should return TRUE if it wants GLib to call its Dispatch, and
40 // FALSE otherwise.  It can also set a timeout in this case for the next time
41 // Prepare should be called again (it may be called sooner).
42 //     After the Prepare calls, GLib does a poll to check for events from the
43 // system.  File descriptors can be attached to the sources.  The poll may block
44 // if none of the Prepare calls returned TRUE.  It will block indefinitely, or
45 // by the minimum time returned by a source in Prepare.
46 //     After the poll, GLib calls Check for each source that returned FALSE
47 // from Prepare.  The return value of Check has the same meaning as for Prepare,
48 // making Check a second chance to tell GLib we are ready for Dispatch.
49 //     Finally, GLib calls Dispatch for each source that is ready.  If Dispatch
50 // returns FALSE, GLib will destroy the source.  Dispatch calls may be recursive
51 // (i.e., you can call Run from them), but Prepare and Check cannot.
52 //     Finalize is called when the source is destroyed.
53 // NOTE: It is common for subsytems to want to process pending events while
54 // doing intensive work, for example the flash plugin. They usually use the
55 // following pattern (recommended by the GTK docs):
56 // while (gtk_events_pending()) {
57 //   gtk_main_iteration();
58 // }
59 //
60 // gtk_events_pending just calls g_main_context_pending, which does the
61 // following:
62 // - Call prepare on all the sources.
63 // - Do the poll with a timeout of 0 (not blocking).
64 // - Call check on all the sources.
65 // - *Does not* call dispatch on the sources.
66 // - Return true if any of prepare() or check() returned true.
67 //
68 // gtk_main_iteration just calls g_main_context_iteration, which does the whole
69 // thing, respecting the timeout for the poll (and block, although it is
70 // expected not to if gtk_events_pending returned true), and call dispatch.
71 //
72 // Thus it is important to only return true from prepare or check if we
73 // actually have events or work to do. We also need to make sure we keep
74 // internal state consistent so that if prepare/check return true when called
75 // from gtk_events_pending, they will still return true when called right
76 // after, from gtk_main_iteration.
77 //
78 // For the GLib pump we try to follow the Windows UI pump model:
79 // - Whenever we receive a wakeup event or the timer for delayed work expires,
80 // we run DoWork and/or DoDelayedWork. That part will also run in the other
81 // event pumps.
82 // - We also run DoWork, DoDelayedWork, and possibly DoIdleWork in the main
83 // loop, around event handling.
84 
85 struct WorkSource : public GSource {
86   base::MessagePumpForUI* pump;
87 };
88 
WorkSourcePrepare(GSource * source,gint * timeout_ms)89 gboolean WorkSourcePrepare(GSource* source, gint* timeout_ms) {
90   *timeout_ms = static_cast<WorkSource*>(source)->pump->HandlePrepare();
91   // We always return FALSE, so that our timeout is honored.  If we were
92   // to return TRUE, the timeout would be considered to be 0 and the poll
93   // would never block.  Once the poll is finished, Check will be called.
94   return FALSE;
95 }
96 
WorkSourceCheck(GSource * source)97 gboolean WorkSourceCheck(GSource* source) {
98   // Only return TRUE if Dispatch should be called.
99   return static_cast<WorkSource*>(source)->pump->HandleCheck();
100 }
101 
WorkSourceDispatch(GSource * source,GSourceFunc unused_func,gpointer unused_data)102 gboolean WorkSourceDispatch(GSource* source, GSourceFunc unused_func,
103                             gpointer unused_data) {
104   static_cast<WorkSource*>(source)->pump->HandleDispatch();
105   // Always return TRUE so our source stays registered.
106   return TRUE;
107 }
108 
109 // I wish these could be const, but g_source_new wants non-const.
110 GSourceFuncs WorkSourceFuncs = {WorkSourcePrepare, WorkSourceCheck,
111                                 WorkSourceDispatch, NULL};
112 
113 }  // namespace
114 
115 namespace base {
116 
MessagePumpForUI()117 MessagePumpForUI::MessagePumpForUI()
118     : state_(NULL),
119       context_(g_main_context_default()),
120       wakeup_gpollfd_(new GPollFD),
121       pipe_full_(false) {
122   // Create our wakeup pipe, which is used to flag when work was scheduled.
123   int fds[2];
124   CHECK(pipe(fds) == 0);
125   wakeup_pipe_read_ = fds[0];
126   wakeup_pipe_write_ = fds[1];
127   wakeup_gpollfd_->fd = wakeup_pipe_read_;
128   wakeup_gpollfd_->events = G_IO_IN;
129 
130   work_source_ = g_source_new(&WorkSourceFuncs, sizeof(WorkSource));
131   static_cast<WorkSource*>(work_source_)->pump = this;
132   g_source_add_poll(work_source_, wakeup_gpollfd_.get());
133   // Use a low priority so that we let other events in the queue go first.
134   g_source_set_priority(work_source_, G_PRIORITY_DEFAULT_IDLE);
135   // This is needed to allow Run calls inside Dispatch.
136   g_source_set_can_recurse(work_source_, TRUE);
137   g_source_attach(work_source_, context_);
138   gdk_event_handler_set(&EventDispatcher, this, NULL);
139 }
140 
~MessagePumpForUI()141 MessagePumpForUI::~MessagePumpForUI() {
142   gdk_event_handler_set(reinterpret_cast<GdkEventFunc>(gtk_main_do_event), this,
143                         NULL);
144   g_source_destroy(work_source_);
145   g_source_unref(work_source_);
146   close(wakeup_pipe_read_);
147   close(wakeup_pipe_write_);
148 }
149 
RunWithDispatcher(Delegate * delegate,Dispatcher * dispatcher)150 void MessagePumpForUI::RunWithDispatcher(Delegate* delegate,
151                                          Dispatcher* dispatcher) {
152 #ifndef NDEBUG
153   // Make sure we only run this on one thread.  GTK only has one message pump
154   // so we can only have one UI loop per process.
155   static PlatformThreadId thread_id = PlatformThread::CurrentId();
156   DCHECK(thread_id == PlatformThread::CurrentId())
157       << "Running MessagePumpForUI on two different threads; "
158          "this is unsupported by GLib!";
159 #endif
160 
161   RunState state;
162   state.delegate = delegate;
163   state.dispatcher = dispatcher;
164   state.should_quit = false;
165   state.run_depth = state_ ? state_->run_depth + 1 : 1;
166   state.has_work = false;
167 
168   RunState* previous_state = state_;
169   state_ = &state;
170 
171   // We really only do a single task for each iteration of the loop.  If we
172   // have done something, assume there is likely something more to do.  This
173   // will mean that we don't block on the message pump until there was nothing
174   // more to do.  We also set this to true to make sure not to block on the
175   // first iteration of the loop, so RunAllPending() works correctly.
176   bool more_work_is_plausible = true;
177 
178   // We run our own loop instead of using g_main_loop_quit in one of the
179   // callbacks.  This is so we only quit our own loops, and we don't quit
180   // nested loops run by others.  TODO(deanm): Is this what we want?
181   for (;;) {
182     // Don't block if we think we have more work to do.
183     bool block = !more_work_is_plausible;
184 
185     // g_main_context_iteration returns true if events have been dispatched.
186     more_work_is_plausible = g_main_context_iteration(context_, block);
187     if (state_->should_quit) break;
188 
189     more_work_is_plausible |= state_->delegate->DoWork();
190     if (state_->should_quit) break;
191 
192     more_work_is_plausible |=
193         state_->delegate->DoDelayedWork(&delayed_work_time_);
194     if (state_->should_quit) break;
195 
196     if (more_work_is_plausible) continue;
197 
198     more_work_is_plausible = state_->delegate->DoIdleWork();
199     if (state_->should_quit) break;
200   }
201 
202   state_ = previous_state;
203 }
204 
205 // Return the timeout we want passed to poll.
HandlePrepare()206 int MessagePumpForUI::HandlePrepare() {
207   // We know we have work, but we haven't called HandleDispatch yet. Don't let
208   // the pump block so that we can do some processing.
209   if (state_ &&  // state_ may be null during tests.
210       state_->has_work)
211     return 0;
212 
213   // We don't think we have work to do, but make sure not to block
214   // longer than the next time we need to run delayed work.
215   return GetTimeIntervalMilliseconds(delayed_work_time_);
216 }
217 
HandleCheck()218 bool MessagePumpForUI::HandleCheck() {
219   if (!state_)  // state_ may be null during tests.
220     return false;
221 
222   // We should only ever have a single message on the wakeup pipe since we only
223   // write to the pipe when pipe_full_ is false. The glib poll will tell us
224   // whether there was data, so this read shouldn't block.
225   if (wakeup_gpollfd_->revents & G_IO_IN) {
226     pipe_full_ = false;
227 
228     char msg;
229     if (HANDLE_EINTR(read(wakeup_pipe_read_, &msg, 1)) != 1 || msg != '!') {
230       NOTREACHED() << "Error reading from the wakeup pipe.";
231     }
232     // Since we ate the message, we need to record that we have more work,
233     // because HandleCheck() may be called without HandleDispatch being called
234     // afterwards.
235     state_->has_work = true;
236   }
237 
238   if (state_->has_work) return true;
239 
240   if (GetTimeIntervalMilliseconds(delayed_work_time_) == 0) {
241     // The timer has expired. That condition will stay true until we process
242     // that delayed work, so we don't need to record this differently.
243     return true;
244   }
245 
246   return false;
247 }
248 
HandleDispatch()249 void MessagePumpForUI::HandleDispatch() {
250   state_->has_work = false;
251   if (state_->delegate->DoWork()) {
252     // NOTE: on Windows at this point we would call ScheduleWork (see
253     // MessagePumpForUI::HandleWorkMessage in message_pump_win.cc). But here,
254     // instead of posting a message on the wakeup pipe, we can avoid the
255     // syscalls and just signal that we have more work.
256     state_->has_work = true;
257   }
258 
259   if (state_->should_quit) return;
260 
261   state_->delegate->DoDelayedWork(&delayed_work_time_);
262 }
263 
AddObserver(Observer * observer)264 void MessagePumpForUI::AddObserver(Observer* observer) {
265   observers_.AddObserver(observer);
266 }
267 
RemoveObserver(Observer * observer)268 void MessagePumpForUI::RemoveObserver(Observer* observer) {
269   observers_.RemoveObserver(observer);
270 }
271 
WillProcessEvent(GdkEvent * event)272 void MessagePumpForUI::WillProcessEvent(GdkEvent* event) {
273   FOR_EACH_OBSERVER(Observer, observers_, WillProcessEvent(event));
274 }
275 
DidProcessEvent(GdkEvent * event)276 void MessagePumpForUI::DidProcessEvent(GdkEvent* event) {
277   FOR_EACH_OBSERVER(Observer, observers_, DidProcessEvent(event));
278 }
279 
Quit()280 void MessagePumpForUI::Quit() {
281   if (state_) {
282     state_->should_quit = true;
283   } else {
284     NOTREACHED() << "Quit called outside Run!";
285   }
286 }
287 
ScheduleWork()288 void MessagePumpForUI::ScheduleWork() {
289   bool was_full = pipe_full_.exchange(true);
290   if (was_full) {
291     return;
292   }
293 
294   // This can be called on any thread, so we don't want to touch any state
295   // variables as we would then need locks all over.  This ensures that if
296   // we are sleeping in a poll that we will wake up.
297   char msg = '!';
298   if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) {
299     NOTREACHED() << "Could not write to the UI message loop wakeup pipe!";
300   }
301 }
302 
ScheduleDelayedWork(const TimeTicks & delayed_work_time)303 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
304   // We need to wake up the loop in case the poll timeout needs to be
305   // adjusted.  This will cause us to try to do work, but that's ok.
306   delayed_work_time_ = delayed_work_time;
307   ScheduleWork();
308 }
309 
310 // static
EventDispatcher(GdkEvent * event,gpointer data)311 void MessagePumpForUI::EventDispatcher(GdkEvent* event, gpointer data) {
312   MessagePumpForUI* message_pump = reinterpret_cast<MessagePumpForUI*>(data);
313 
314   message_pump->WillProcessEvent(event);
315   if (message_pump->state_ &&  // state_ may be null during tests.
316       message_pump->state_->dispatcher) {
317     if (!message_pump->state_->dispatcher->Dispatch(event))
318       message_pump->state_->should_quit = true;
319   } else {
320     gtk_main_do_event(event);
321   }
322   message_pump->DidProcessEvent(event);
323 }
324 
325 }  // namespace base
326