blob: fb318b771ed54b281bfbd36b9ab8b4eb88653913 [file] [log] [blame]
simon.hong81@gmail.come2d43142012-02-24 06:56:22 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
dsh@google.com119a2522008-10-04 01:52:59 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/message_pump_glib.h"
6
7#include <fcntl.h>
8#include <math.h>
9
mattm@chromium.orgf30aae52009-12-05 05:45:54 +090010#include <glib.h>
11
agl@chromium.orgd263ad72009-05-02 06:37:31 +090012#include "base/eintr_wrapper.h"
dsh@google.com119a2522008-10-04 01:52:59 +090013#include "base/logging.h"
brettw@chromium.org61391822011-01-01 05:02:16 +090014#include "base/threading/platform_thread.h"
dsh@google.com119a2522008-10-04 01:52:59 +090015
deanm@chromium.orga65cf922008-11-13 04:39:42 +090016namespace {
dsh@google.com119a2522008-10-04 01:52:59 +090017
deanm@chromium.orga65cf922008-11-13 04:39:42 +090018// 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.
jar@chromium.org9b0fb062010-11-07 07:23:29 +090020int GetTimeIntervalMilliseconds(const base::TimeTicks& from) {
dsh@google.com119a2522008-10-04 01:52:59 +090021 if (from.is_null())
22 return -1;
23
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.
deanm@chromium.orga65cf922008-11-13 04:39:42 +090027 int delay = static_cast<int>(
jar@chromium.org9b0fb062010-11-07 07:23:29 +090028 ceil((from - base::TimeTicks::Now()).InMillisecondsF()));
dsh@google.com119a2522008-10-04 01:52:59 +090029
30 // If this value is negative, then we need to run delayed work soon.
deanm@chromium.orga65cf922008-11-13 04:39:42 +090031 return delay < 0 ? 0 : delay;
dsh@google.com119a2522008-10-04 01:52:59 +090032}
33
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.
evan@chromium.org85e4a3e2009-06-02 07:01:53 +090051// 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();
56// }
57//
58// gtk_events_pending just calls g_main_context_pending, which does the
59// following:
deanm@chromium.orgbec47f42009-06-15 19:30:44 +090060// - 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.
evan@chromium.org85e4a3e2009-06-02 07:01:53 +090065//
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.
69//
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.
75//
76// For the GLib pump we try to follow the Windows UI pump model:
deanm@chromium.orgbec47f42009-06-15 19:30:44 +090077// - Whenever we receive a wakeup event or the timer for delayed work expires,
evan@chromium.org85e4a3e2009-06-02 07:01:53 +090078// we run DoWork and/or DoDelayedWork. That part will also run in the other
deanm@chromium.orgbec47f42009-06-15 19:30:44 +090079// event pumps.
80// - We also run DoWork, DoDelayedWork, and possibly DoIdleWork in the main
evan@chromium.org85e4a3e2009-06-02 07:01:53 +090081// loop, around event handling.
dsh@google.com119a2522008-10-04 01:52:59 +090082
deanm@chromium.orga65cf922008-11-13 04:39:42 +090083struct WorkSource : public GSource {
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +090084 base::MessagePumpGlib* pump;
deanm@chromium.orga65cf922008-11-13 04:39:42 +090085};
dsh@google.com119a2522008-10-04 01:52:59 +090086
deanm@chromium.orga65cf922008-11-13 04:39:42 +090087gboolean WorkSourcePrepare(GSource* source,
88 gint* timeout_ms) {
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +090089 *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.
dsh@google.com119a2522008-10-04 01:52:59 +090093 return FALSE;
94}
95
deanm@chromium.orga65cf922008-11-13 04:39:42 +090096gboolean WorkSourceCheck(GSource* source) {
evan@chromium.org85e4a3e2009-06-02 07:01:53 +090097 // Only return TRUE if Dispatch should be called.
98 return static_cast<WorkSource*>(source)->pump->HandleCheck();
dsh@google.com119a2522008-10-04 01:52:59 +090099}
100
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900101gboolean WorkSourceDispatch(GSource* source,
102 GSourceFunc unused_func,
103 gpointer unused_data) {
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900104
105 static_cast<WorkSource*>(source)->pump->HandleDispatch();
106 // Always return TRUE so our source stays registered.
dsh@google.com119a2522008-10-04 01:52:59 +0900107 return TRUE;
108}
109
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900110// I wish these could be const, but g_source_new wants non-const.
111GSourceFuncs WorkSourceFuncs = {
112 WorkSourcePrepare,
113 WorkSourceCheck,
114 WorkSourceDispatch,
115 NULL
116};
117
118} // namespace
119
120
121namespace base {
122
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900123struct MessagePumpGlib::RunState {
thestig@chromium.orge7ca2cf2010-08-06 07:36:04 +0900124 Delegate* delegate;
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900125 MessagePumpDispatcher* dispatcher;
thestig@chromium.orge7ca2cf2010-08-06 07:36:04 +0900126
127 // Used to flag that the current Run() invocation should return ASAP.
128 bool should_quit;
129
130 // Used to count how many Run() invocations are on the stack.
131 int run_depth;
132
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.
136 bool has_work;
137};
138
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900139MessagePumpGlib::MessagePumpGlib()
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900140 : state_(NULL),
mattm@chromium.orgf30aae52009-12-05 05:45:54 +0900141 context_(g_main_context_default()),
142 wakeup_gpollfd_(new GPollFD) {
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900143 // Create our wakeup pipe, which is used to flag when work was scheduled.
144 int fds[2];
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900145 int ret = pipe(fds);
146 DCHECK_EQ(ret, 0);
147 (void)ret; // Prevent warning in release mode.
148
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900149 wakeup_pipe_read_ = fds[0];
150 wakeup_pipe_write_ = fds[1];
mattm@chromium.orgf30aae52009-12-05 05:45:54 +0900151 wakeup_gpollfd_->fd = wakeup_pipe_read_;
152 wakeup_gpollfd_->events = G_IO_IN;
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +0900153
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900154 work_source_ = g_source_new(&WorkSourceFuncs, sizeof(WorkSource));
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900155 static_cast<WorkSource*>(work_source_)->pump = this;
mattm@chromium.orgf30aae52009-12-05 05:45:54 +0900156 g_source_add_poll(work_source_, wakeup_gpollfd_.get());
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900157 // 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);
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900159 // This is needed to allow Run calls inside Dispatch.
160 g_source_set_can_recurse(work_source_, TRUE);
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900161 g_source_attach(work_source_, context_);
dsh@google.com119a2522008-10-04 01:52:59 +0900162}
163
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900164void MessagePumpGlib::RunWithDispatcher(Delegate* delegate,
165 MessagePumpDispatcher* dispatcher) {
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900166#ifndef NDEBUG
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900167 // Make sure we only run this on one thread. X/GTK only has one message pump
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900168 // so we can only have one UI loop per process.
brettw@chromium.org61391822011-01-01 05:02:16 +0900169 static base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
170 DCHECK(thread_id == base::PlatformThread::CurrentId()) <<
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900171 "Running MessagePumpGlib on two different threads; "
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900172 "this is unsupported by GLib!";
173#endif
dsh@google.com119a2522008-10-04 01:52:59 +0900174
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900175 RunState state;
176 state.delegate = delegate;
jcampan@chromium.org05423582009-08-01 07:53:37 +0900177 state.dispatcher = dispatcher;
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900178 state.should_quit = false;
179 state.run_depth = state_ ? state_->run_depth + 1 : 1;
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900180 state.has_work = false;
181
182 RunState* previous_state = state_;
183 state_ = &state;
184
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900185 // We really only do a single task for each iteration of the loop. If we
186 // have done something, assume there is likely something more to do. This
187 // will mean that we don't block on the message pump until there was nothing
188 // more to do. We also set this to true to make sure not to block on the
189 // first iteration of the loop, so RunAllPending() works correctly.
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900190 bool more_work_is_plausible = true;
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900191
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900192 // We run our own loop instead of using g_main_loop_quit in one of the
193 // callbacks. This is so we only quit our own loops, and we don't quit
194 // nested loops run by others. TODO(deanm): Is this what we want?
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900195 for (;;) {
196 // Don't block if we think we have more work to do.
197 bool block = !more_work_is_plausible;
198
piman@chromium.orgbfd272d2011-12-15 01:34:31 +0900199 more_work_is_plausible = g_main_context_iteration(context_, block);
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900200 if (state_->should_quit)
201 break;
202
203 more_work_is_plausible |= state_->delegate->DoWork();
204 if (state_->should_quit)
205 break;
206
207 more_work_is_plausible |=
208 state_->delegate->DoDelayedWork(&delayed_work_time_);
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900209 if (state_->should_quit)
210 break;
211
212 if (more_work_is_plausible)
213 continue;
214
215 more_work_is_plausible = state_->delegate->DoIdleWork();
216 if (state_->should_quit)
217 break;
218 }
dsh@google.com119a2522008-10-04 01:52:59 +0900219
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900220 state_ = previous_state;
dsh@google.com119a2522008-10-04 01:52:59 +0900221}
222
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900223// Return the timeout we want passed to poll.
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900224int MessagePumpGlib::HandlePrepare() {
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900225 // We know we have work, but we haven't called HandleDispatch yet. Don't let
226 // the pump block so that we can do some processing.
sky@chromium.orgd9b59ec2010-01-30 09:47:28 +0900227 if (state_ && // state_ may be null during tests.
228 state_->has_work)
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900229 return 0;
230
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900231 // We don't think we have work to do, but make sure not to block
232 // longer than the next time we need to run delayed work.
233 return GetTimeIntervalMilliseconds(delayed_work_time_);
234}
235
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900236bool MessagePumpGlib::HandleCheck() {
sky@chromium.orgd9b59ec2010-01-30 09:47:28 +0900237 if (!state_) // state_ may be null during tests.
238 return false;
239
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900240 // We should only ever have a single message on the wakeup pipe, since we
241 // are only signaled when the queue went from empty to non-empty. The glib
242 // poll will tell us whether there was data, so this read shouldn't block.
mattm@chromium.orgf30aae52009-12-05 05:45:54 +0900243 if (wakeup_gpollfd_->revents & G_IO_IN) {
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900244 char msg;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900245 if (HANDLE_EINTR(read(wakeup_pipe_read_, &msg, 1)) != 1 || msg != '!') {
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900246 NOTREACHED() << "Error reading from the wakeup pipe.";
247 }
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900248 // Since we ate the message, we need to record that we have more work,
249 // because HandleCheck() may be called without HandleDispatch being called
250 // afterwards.
251 state_->has_work = true;
252 }
253
254 if (state_->has_work)
255 return true;
256
257 if (GetTimeIntervalMilliseconds(delayed_work_time_) == 0) {
258 // The timer has expired. That condition will stay true until we process
259 // that delayed work, so we don't need to record this differently.
260 return true;
261 }
262
263 return false;
264}
265
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900266void MessagePumpGlib::HandleDispatch() {
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900267 state_->has_work = false;
268 if (state_->delegate->DoWork()) {
deanm@chromium.orgbec47f42009-06-15 19:30:44 +0900269 // NOTE: on Windows at this point we would call ScheduleWork (see
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900270 // MessagePumpGlib::HandleWorkMessage in message_pump_win.cc). But here,
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900271 // instead of posting a message on the wakeup pipe, we can avoid the
272 // syscalls and just signal that we have more work.
273 state_->has_work = true;
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900274 }
275
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900276 if (state_->should_quit)
277 return;
278
evan@chromium.org85e4a3e2009-06-02 07:01:53 +0900279 state_->delegate->DoDelayedWork(&delayed_work_time_);
deanm@chromium.orgabb3a2b2008-11-13 09:25:51 +0900280}
281
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900282void MessagePumpGlib::AddObserver(MessagePumpObserver* observer) {
sky@chromium.org20b30c22009-05-16 07:40:05 +0900283 observers_.AddObserver(observer);
284}
285
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900286void MessagePumpGlib::RemoveObserver(MessagePumpObserver* observer) {
sky@chromium.org20b30c22009-05-16 07:40:05 +0900287 observers_.RemoveObserver(observer);
288}
289
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900290void MessagePumpGlib::Run(Delegate* delegate) {
erg@google.com190e7b02010-12-10 03:25:03 +0900291 RunWithDispatcher(delegate, NULL);
292}
293
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900294void MessagePumpGlib::Quit() {
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900295 if (state_) {
296 state_->should_quit = true;
297 } else {
298 NOTREACHED() << "Quit called outside Run!";
299 }
300}
dsh@google.com119a2522008-10-04 01:52:59 +0900301
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900302void MessagePumpGlib::ScheduleWork() {
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900303 // This can be called on any thread, so we don't want to touch any state
304 // variables as we would then need locks all over. This ensures that if
deanm@chromium.org3f05f762008-11-13 06:34:03 +0900305 // we are sleeping in a poll that we will wake up.
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900306 char msg = '!';
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900307 if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) {
deanm@chromium.org1ab155c2008-11-18 10:30:42 +0900308 NOTREACHED() << "Could not write to the UI message loop wakeup pipe!";
309 }
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900310}
dsh@google.com119a2522008-10-04 01:52:59 +0900311
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900312void MessagePumpGlib::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
deanm@chromium.orga65cf922008-11-13 04:39:42 +0900313 // We need to wake up the loop in case the poll timeout needs to be
314 // adjusted. This will cause us to try to do work, but that's ok.
315 delayed_work_time_ = delayed_work_time;
316 ScheduleWork();
dsh@google.com119a2522008-10-04 01:52:59 +0900317}
318
rsleevi@chromium.orgd2163992012-05-19 03:00:22 +0900319MessagePumpGlib::~MessagePumpGlib() {
320 g_source_destroy(work_source_);
321 g_source_unref(work_source_);
322 close(wakeup_pipe_read_);
323 close(wakeup_pipe_write_);
324}
325
sadrul@chromium.orgf7f3b262011-06-25 05:10:25 +0900326MessagePumpDispatcher* MessagePumpGlib::GetDispatcher() {
erg@google.com37c078e2011-01-11 09:50:59 +0900327 return state_ ? state_->dispatcher : NULL;
328}
329
dsh@google.com119a2522008-10-04 01:52:59 +0900330} // namespace base