ipc/chromium/src/base/message_pump_glib.cc

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

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

mercurial