michael@0: // Copyright (c) 2008 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/message_pump_glib.h" michael@0: michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: michael@0: #include "base/eintr_wrapper.h" michael@0: #include "base/logging.h" michael@0: #include "base/platform_thread.h" michael@0: michael@0: namespace { michael@0: michael@0: // We send a byte across a pipe to wakeup the event loop. michael@0: const char kWorkScheduled = '\0'; michael@0: michael@0: // Return a timeout suitable for the glib loop, -1 to block forever, michael@0: // 0 to return right away, or a timeout in milliseconds from now. michael@0: int GetTimeIntervalMilliseconds(const base::TimeTicks& from) { michael@0: if (from.is_null()) michael@0: return -1; michael@0: michael@0: // Be careful here. TimeDelta has a precision of microseconds, but we want a michael@0: // value in milliseconds. If there are 5.5ms left, should the delay be 5 or michael@0: // 6? It should be 6 to avoid executing delayed work too early. michael@0: int delay = static_cast( michael@0: ceil((from - base::TimeTicks::Now()).InMillisecondsF())); michael@0: michael@0: // If this value is negative, then we need to run delayed work soon. michael@0: return delay < 0 ? 0 : delay; michael@0: } michael@0: michael@0: // A brief refresher on GLib: michael@0: // GLib sources have four callbacks: Prepare, Check, Dispatch and Finalize. michael@0: // On each iteration of the GLib pump, it calls each source's Prepare function. michael@0: // This function should return TRUE if it wants GLib to call its Dispatch, and michael@0: // FALSE otherwise. It can also set a timeout in this case for the next time michael@0: // Prepare should be called again (it may be called sooner). michael@0: // After the Prepare calls, GLib does a poll to check for events from the michael@0: // system. File descriptors can be attached to the sources. The poll may block michael@0: // if none of the Prepare calls returned TRUE. It will block indefinitely, or michael@0: // by the minimum time returned by a source in Prepare. michael@0: // After the poll, GLib calls Check for each source that returned FALSE michael@0: // from Prepare. The return value of Check has the same meaning as for Prepare, michael@0: // making Check a second chance to tell GLib we are ready for Dispatch. michael@0: // Finally, GLib calls Dispatch for each source that is ready. If Dispatch michael@0: // returns FALSE, GLib will destroy the source. Dispatch calls may be recursive michael@0: // (i.e., you can call Run from them), but Prepare and Check cannot. michael@0: // Finalize is called when the source is destroyed. michael@0: // NOTE: It is common for subsytems to want to process pending events while michael@0: // doing intensive work, for example the flash plugin. They usually use the michael@0: // following pattern (recommended by the GTK docs): michael@0: // while (gtk_events_pending()) { michael@0: // gtk_main_iteration(); michael@0: // } michael@0: // michael@0: // gtk_events_pending just calls g_main_context_pending, which does the michael@0: // following: michael@0: // - Call prepare on all the sources. michael@0: // - Do the poll with a timeout of 0 (not blocking). michael@0: // - Call check on all the sources. michael@0: // - *Does not* call dispatch on the sources. michael@0: // - Return true if any of prepare() or check() returned true. michael@0: // michael@0: // gtk_main_iteration just calls g_main_context_iteration, which does the whole michael@0: // thing, respecting the timeout for the poll (and block, although it is michael@0: // expected not to if gtk_events_pending returned true), and call dispatch. michael@0: // michael@0: // Thus it is important to only return true from prepare or check if we michael@0: // actually have events or work to do. We also need to make sure we keep michael@0: // internal state consistent so that if prepare/check return true when called michael@0: // from gtk_events_pending, they will still return true when called right michael@0: // after, from gtk_main_iteration. michael@0: // michael@0: // For the GLib pump we try to follow the Windows UI pump model: michael@0: // - Whenever we receive a wakeup event or the timer for delayed work expires, michael@0: // we run DoWork and/or DoDelayedWork. That part will also run in the other michael@0: // event pumps. michael@0: // - We also run DoWork, DoDelayedWork, and possibly DoIdleWork in the main michael@0: // loop, around event handling. michael@0: michael@0: struct WorkSource : public GSource { michael@0: base::MessagePumpForUI* pump; michael@0: }; michael@0: michael@0: gboolean WorkSourcePrepare(GSource* source, michael@0: gint* timeout_ms) { michael@0: *timeout_ms = static_cast(source)->pump->HandlePrepare(); michael@0: // We always return FALSE, so that our timeout is honored. If we were michael@0: // to return TRUE, the timeout would be considered to be 0 and the poll michael@0: // would never block. Once the poll is finished, Check will be called. michael@0: return FALSE; michael@0: } michael@0: michael@0: gboolean WorkSourceCheck(GSource* source) { michael@0: // Only return TRUE if Dispatch should be called. michael@0: return static_cast(source)->pump->HandleCheck(); michael@0: } michael@0: michael@0: gboolean WorkSourceDispatch(GSource* source, michael@0: GSourceFunc unused_func, michael@0: gpointer unused_data) { michael@0: michael@0: static_cast(source)->pump->HandleDispatch(); michael@0: // Always return TRUE so our source stays registered. michael@0: return TRUE; michael@0: } michael@0: michael@0: // I wish these could be const, but g_source_new wants non-const. michael@0: GSourceFuncs WorkSourceFuncs = { michael@0: WorkSourcePrepare, michael@0: WorkSourceCheck, michael@0: WorkSourceDispatch, michael@0: NULL michael@0: }; michael@0: michael@0: } // namespace michael@0: michael@0: michael@0: namespace base { michael@0: michael@0: MessagePumpForUI::MessagePumpForUI() michael@0: : state_(NULL), michael@0: context_(g_main_context_default()), michael@0: wakeup_gpollfd_(new GPollFD) { michael@0: // Create our wakeup pipe, which is used to flag when work was scheduled. michael@0: int fds[2]; michael@0: CHECK(pipe(fds) == 0); michael@0: wakeup_pipe_read_ = fds[0]; michael@0: wakeup_pipe_write_ = fds[1]; michael@0: wakeup_gpollfd_->fd = wakeup_pipe_read_; michael@0: wakeup_gpollfd_->events = G_IO_IN; michael@0: michael@0: work_source_ = g_source_new(&WorkSourceFuncs, sizeof(WorkSource)); michael@0: static_cast(work_source_)->pump = this; michael@0: g_source_add_poll(work_source_, wakeup_gpollfd_.get()); michael@0: // Use a low priority so that we let other events in the queue go first. michael@0: g_source_set_priority(work_source_, G_PRIORITY_DEFAULT_IDLE); michael@0: // This is needed to allow Run calls inside Dispatch. michael@0: g_source_set_can_recurse(work_source_, TRUE); michael@0: g_source_attach(work_source_, context_); michael@0: gdk_event_handler_set(&EventDispatcher, this, NULL); michael@0: } michael@0: michael@0: MessagePumpForUI::~MessagePumpForUI() { michael@0: gdk_event_handler_set(reinterpret_cast(gtk_main_do_event), michael@0: this, NULL); michael@0: g_source_destroy(work_source_); michael@0: g_source_unref(work_source_); michael@0: close(wakeup_pipe_read_); michael@0: close(wakeup_pipe_write_); michael@0: } michael@0: michael@0: void MessagePumpForUI::RunWithDispatcher(Delegate* delegate, michael@0: Dispatcher* dispatcher) { michael@0: #ifndef NDEBUG michael@0: // Make sure we only run this on one thread. GTK only has one message pump michael@0: // so we can only have one UI loop per process. michael@0: static PlatformThreadId thread_id = PlatformThread::CurrentId(); michael@0: DCHECK(thread_id == PlatformThread::CurrentId()) << michael@0: "Running MessagePumpForUI on two different threads; " michael@0: "this is unsupported by GLib!"; michael@0: #endif michael@0: michael@0: RunState state; michael@0: state.delegate = delegate; michael@0: state.dispatcher = dispatcher; michael@0: state.should_quit = false; michael@0: state.run_depth = state_ ? state_->run_depth + 1 : 1; michael@0: state.has_work = false; michael@0: michael@0: RunState* previous_state = state_; michael@0: state_ = &state; michael@0: michael@0: // We really only do a single task for each iteration of the loop. If we michael@0: // have done something, assume there is likely something more to do. This michael@0: // will mean that we don't block on the message pump until there was nothing michael@0: // more to do. We also set this to true to make sure not to block on the michael@0: // first iteration of the loop, so RunAllPending() works correctly. michael@0: bool more_work_is_plausible = true; michael@0: michael@0: // We run our own loop instead of using g_main_loop_quit in one of the michael@0: // callbacks. This is so we only quit our own loops, and we don't quit michael@0: // nested loops run by others. TODO(deanm): Is this what we want? michael@0: for (;;) { michael@0: // Don't block if we think we have more work to do. michael@0: bool block = !more_work_is_plausible; michael@0: michael@0: // g_main_context_iteration returns true if events have been dispatched. michael@0: more_work_is_plausible = g_main_context_iteration(context_, block); michael@0: if (state_->should_quit) michael@0: break; michael@0: michael@0: more_work_is_plausible |= state_->delegate->DoWork(); michael@0: if (state_->should_quit) michael@0: break; michael@0: michael@0: more_work_is_plausible |= michael@0: state_->delegate->DoDelayedWork(&delayed_work_time_); michael@0: if (state_->should_quit) michael@0: break; michael@0: michael@0: if (more_work_is_plausible) michael@0: continue; michael@0: michael@0: more_work_is_plausible = state_->delegate->DoIdleWork(); michael@0: if (state_->should_quit) michael@0: break; michael@0: } michael@0: michael@0: state_ = previous_state; michael@0: } michael@0: michael@0: // Return the timeout we want passed to poll. michael@0: int MessagePumpForUI::HandlePrepare() { michael@0: // We know we have work, but we haven't called HandleDispatch yet. Don't let michael@0: // the pump block so that we can do some processing. michael@0: if (state_ && // state_ may be null during tests. michael@0: state_->has_work) michael@0: return 0; michael@0: michael@0: // We don't think we have work to do, but make sure not to block michael@0: // longer than the next time we need to run delayed work. michael@0: return GetTimeIntervalMilliseconds(delayed_work_time_); michael@0: } michael@0: michael@0: bool MessagePumpForUI::HandleCheck() { michael@0: if (!state_) // state_ may be null during tests. michael@0: return false; michael@0: michael@0: // We should only ever have a single message on the wakeup pipe, since we michael@0: // are only signaled when the queue went from empty to non-empty. The glib michael@0: // poll will tell us whether there was data, so this read shouldn't block. michael@0: if (wakeup_gpollfd_->revents & G_IO_IN) { michael@0: char msg; michael@0: if (HANDLE_EINTR(read(wakeup_pipe_read_, &msg, 1)) != 1 || msg != '!') { michael@0: NOTREACHED() << "Error reading from the wakeup pipe."; michael@0: } michael@0: // Since we ate the message, we need to record that we have more work, michael@0: // because HandleCheck() may be called without HandleDispatch being called michael@0: // afterwards. michael@0: state_->has_work = true; michael@0: } michael@0: michael@0: if (state_->has_work) michael@0: return true; michael@0: michael@0: if (GetTimeIntervalMilliseconds(delayed_work_time_) == 0) { michael@0: // The timer has expired. That condition will stay true until we process michael@0: // that delayed work, so we don't need to record this differently. michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: void MessagePumpForUI::HandleDispatch() { michael@0: state_->has_work = false; michael@0: if (state_->delegate->DoWork()) { michael@0: // NOTE: on Windows at this point we would call ScheduleWork (see michael@0: // MessagePumpForUI::HandleWorkMessage in message_pump_win.cc). But here, michael@0: // instead of posting a message on the wakeup pipe, we can avoid the michael@0: // syscalls and just signal that we have more work. michael@0: state_->has_work = true; michael@0: } michael@0: michael@0: if (state_->should_quit) michael@0: return; michael@0: michael@0: state_->delegate->DoDelayedWork(&delayed_work_time_); michael@0: } michael@0: michael@0: void MessagePumpForUI::AddObserver(Observer* observer) { michael@0: observers_.AddObserver(observer); michael@0: } michael@0: michael@0: void MessagePumpForUI::RemoveObserver(Observer* observer) { michael@0: observers_.RemoveObserver(observer); michael@0: } michael@0: michael@0: void MessagePumpForUI::WillProcessEvent(GdkEvent* event) { michael@0: FOR_EACH_OBSERVER(Observer, observers_, WillProcessEvent(event)); michael@0: } michael@0: michael@0: void MessagePumpForUI::DidProcessEvent(GdkEvent* event) { michael@0: FOR_EACH_OBSERVER(Observer, observers_, DidProcessEvent(event)); michael@0: } michael@0: michael@0: void MessagePumpForUI::Quit() { michael@0: if (state_) { michael@0: state_->should_quit = true; michael@0: } else { michael@0: NOTREACHED() << "Quit called outside Run!"; michael@0: } michael@0: } michael@0: michael@0: void MessagePumpForUI::ScheduleWork() { michael@0: // This can be called on any thread, so we don't want to touch any state michael@0: // variables as we would then need locks all over. This ensures that if michael@0: // we are sleeping in a poll that we will wake up. michael@0: char msg = '!'; michael@0: if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) { michael@0: NOTREACHED() << "Could not write to the UI message loop wakeup pipe!"; michael@0: } michael@0: } michael@0: michael@0: void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { michael@0: // We need to wake up the loop in case the poll timeout needs to be michael@0: // adjusted. This will cause us to try to do work, but that's ok. michael@0: delayed_work_time_ = delayed_work_time; michael@0: ScheduleWork(); michael@0: } michael@0: michael@0: // static michael@0: void MessagePumpForUI::EventDispatcher(GdkEvent* event, gpointer data) { michael@0: MessagePumpForUI* message_pump = reinterpret_cast(data); michael@0: michael@0: message_pump->WillProcessEvent(event); michael@0: if (message_pump->state_ && // state_ may be null during tests. michael@0: message_pump->state_->dispatcher) { michael@0: if (!message_pump->state_->dispatcher->Dispatch(event)) michael@0: message_pump->state_->should_quit = true; michael@0: } else { michael@0: gtk_main_do_event(event); michael@0: } michael@0: message_pump->DidProcessEvent(event); michael@0: } michael@0: michael@0: } // namespace base