OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #include "base/message_loop/message_pump_glib.h" | |
6 | |
7 #include <fcntl.h> | |
8 #include <math.h> | |
9 | |
10 #include <glib.h> | |
11 | |
12 #include "base/logging.h" | |
13 #include "base/posix/eintr_wrapper.h" | |
14 #include "base/threading/platform_thread.h" | |
15 | |
16 namespace base { | |
17 | |
18 namespace { | |
19 | |
20 // Return a timeout suitable for the glib loop, -1 to block forever, | |
21 // 0 to return right away, or a timeout in milliseconds from now. | |
22 int GetTimeIntervalMilliseconds(const TimeTicks& from) { | |
23 if (from.is_null()) | |
24 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 = static_cast<int>( | |
30 ceil((from - 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 MessagePumpGlib* pump; | |
87 }; | |
88 | |
89 gboolean WorkSourcePrepare(GSource* source, | |
90 gint* timeout_ms) { | |
91 *timeout_ms = static_cast<WorkSource*>(source)->pump->HandlePrepare(); | |
92 // We always return FALSE, so that our timeout is honored. If we were | |
93 // to return TRUE, the timeout would be considered to be 0 and the poll | |
94 // would never block. Once the poll is finished, Check will be called. | |
95 return FALSE; | |
96 } | |
97 | |
98 gboolean WorkSourceCheck(GSource* source) { | |
99 // Only return TRUE if Dispatch should be called. | |
100 return static_cast<WorkSource*>(source)->pump->HandleCheck(); | |
101 } | |
102 | |
103 gboolean WorkSourceDispatch(GSource* source, | |
104 GSourceFunc unused_func, | |
105 gpointer unused_data) { | |
106 | |
107 static_cast<WorkSource*>(source)->pump->HandleDispatch(); | |
108 // Always return TRUE so our source stays registered. | |
109 return TRUE; | |
110 } | |
111 | |
112 // I wish these could be const, but g_source_new wants non-const. | |
113 GSourceFuncs WorkSourceFuncs = { | |
114 WorkSourcePrepare, | |
115 WorkSourceCheck, | |
116 WorkSourceDispatch, | |
117 NULL | |
118 }; | |
119 | |
120 } // namespace | |
121 | |
122 struct MessagePumpGlib::RunState { | |
123 Delegate* delegate; | |
124 MessagePumpDispatcher* dispatcher; | |
125 | |
126 // Used to flag that the current Run() invocation should return ASAP. | |
127 bool should_quit; | |
128 | |
129 // Used to count how many Run() invocations are on the stack. | |
130 int run_depth; | |
131 | |
132 // This keeps the state of whether the pump got signaled that there was new | |
133 // work to be done. Since we eat the message on the wake up pipe as soon as | |
134 // we get it, we keep that state here to stay consistent. | |
135 bool has_work; | |
136 }; | |
137 | |
138 MessagePumpGlib::MessagePumpGlib() | |
139 : state_(NULL), | |
140 context_(g_main_context_default()), | |
141 wakeup_gpollfd_(new GPollFD) { | |
142 // Create our wakeup pipe, which is used to flag when work was scheduled. | |
143 int fds[2]; | |
144 int ret = pipe(fds); | |
145 DCHECK_EQ(ret, 0); | |
146 (void)ret; // Prevent warning in release mode. | |
147 | |
148 wakeup_pipe_read_ = fds[0]; | |
149 wakeup_pipe_write_ = fds[1]; | |
150 wakeup_gpollfd_->fd = wakeup_pipe_read_; | |
151 wakeup_gpollfd_->events = G_IO_IN; | |
152 | |
153 work_source_ = g_source_new(&WorkSourceFuncs, sizeof(WorkSource)); | |
154 static_cast<WorkSource*>(work_source_)->pump = this; | |
155 g_source_add_poll(work_source_, wakeup_gpollfd_.get()); | |
156 // Use a low priority so that we let other events in the queue go first. | |
157 g_source_set_priority(work_source_, G_PRIORITY_DEFAULT_IDLE); | |
158 // This is needed to allow Run calls inside Dispatch. | |
159 g_source_set_can_recurse(work_source_, TRUE); | |
160 g_source_attach(work_source_, context_); | |
161 } | |
162 | |
163 void MessagePumpGlib::RunWithDispatcher(Delegate* delegate, | |
164 MessagePumpDispatcher* dispatcher) { | |
165 #ifndef NDEBUG | |
166 // Make sure we only run this on one thread. X/GTK only has one message pump | |
167 // so we can only have one UI loop per process. | |
168 static PlatformThreadId thread_id = PlatformThread::CurrentId(); | |
169 DCHECK(thread_id == PlatformThread::CurrentId()) << | |
170 "Running MessagePumpGlib on two different threads; " | |
171 "this is unsupported by GLib!"; | |
172 #endif | |
173 | |
174 RunState state; | |
175 state.delegate = delegate; | |
176 state.dispatcher = dispatcher; | |
177 state.should_quit = false; | |
178 state.run_depth = state_ ? state_->run_depth + 1 : 1; | |
179 state.has_work = false; | |
180 | |
181 RunState* previous_state = state_; | |
182 state_ = &state; | |
183 | |
184 // We really only do a single task for each iteration of the loop. If we | |
185 // have done something, assume there is likely something more to do. This | |
186 // will mean that we don't block on the message pump until there was nothing | |
187 // more to do. We also set this to true to make sure not to block on the | |
188 // first iteration of the loop, so RunUntilIdle() works correctly. | |
189 bool more_work_is_plausible = true; | |
190 | |
191 // We run our own loop instead of using g_main_loop_quit in one of the | |
192 // callbacks. This is so we only quit our own loops, and we don't quit | |
193 // nested loops run by others. TODO(deanm): Is this what we want? | |
194 for (;;) { | |
195 // Don't block if we think we have more work to do. | |
196 bool block = !more_work_is_plausible; | |
197 | |
198 more_work_is_plausible = g_main_context_iteration(context_, block); | |
199 if (state_->should_quit) | |
200 break; | |
201 | |
202 more_work_is_plausible |= state_->delegate->DoWork(); | |
203 if (state_->should_quit) | |
204 break; | |
205 | |
206 more_work_is_plausible |= | |
207 state_->delegate->DoDelayedWork(&delayed_work_time_); | |
208 if (state_->should_quit) | |
209 break; | |
210 | |
211 if (more_work_is_plausible) | |
212 continue; | |
213 | |
214 more_work_is_plausible = state_->delegate->DoIdleWork(); | |
215 if (state_->should_quit) | |
216 break; | |
217 } | |
218 | |
219 state_ = previous_state; | |
220 } | |
221 | |
222 // Return the timeout we want passed to poll. | |
223 int MessagePumpGlib::HandlePrepare() { | |
224 // We know we have work, but we haven't called HandleDispatch yet. Don't let | |
225 // the pump block so that we can do some processing. | |
226 if (state_ && // state_ may be null during tests. | |
227 state_->has_work) | |
228 return 0; | |
229 | |
230 // We don't think we have work to do, but make sure not to block | |
231 // longer than the next time we need to run delayed work. | |
232 return GetTimeIntervalMilliseconds(delayed_work_time_); | |
233 } | |
234 | |
235 bool MessagePumpGlib::HandleCheck() { | |
236 if (!state_) // state_ may be null during tests. | |
237 return false; | |
238 | |
239 // We usually have a single message on the wakeup pipe, since we are only | |
240 // signaled when the queue went from empty to non-empty, but there can be | |
241 // two messages if a task posted a task, hence we read at most two bytes. | |
242 // The glib poll will tell us whether there was data, so this read | |
243 // shouldn't block. | |
244 if (wakeup_gpollfd_->revents & G_IO_IN) { | |
245 char msg[2]; | |
246 const int num_bytes = HANDLE_EINTR(read(wakeup_pipe_read_, msg, 2)); | |
247 if (num_bytes < 1) { | |
248 NOTREACHED() << "Error reading from the wakeup pipe."; | |
249 } | |
250 DCHECK((num_bytes == 1 && msg[0] == '!') || | |
251 (num_bytes == 2 && msg[0] == '!' && msg[1] == '!')); | |
252 // Since we ate the message, we need to record that we have more work, | |
253 // because HandleCheck() may be called without HandleDispatch being called | |
254 // afterwards. | |
255 state_->has_work = true; | |
256 } | |
257 | |
258 if (state_->has_work) | |
259 return true; | |
260 | |
261 if (GetTimeIntervalMilliseconds(delayed_work_time_) == 0) { | |
262 // The timer has expired. That condition will stay true until we process | |
263 // that delayed work, so we don't need to record this differently. | |
264 return true; | |
265 } | |
266 | |
267 return false; | |
268 } | |
269 | |
270 void MessagePumpGlib::HandleDispatch() { | |
271 state_->has_work = false; | |
272 if (state_->delegate->DoWork()) { | |
273 // NOTE: on Windows at this point we would call ScheduleWork (see | |
274 // MessagePumpGlib::HandleWorkMessage in message_pump_win.cc). But here, | |
275 // instead of posting a message on the wakeup pipe, we can avoid the | |
276 // syscalls and just signal that we have more work. | |
277 state_->has_work = true; | |
278 } | |
279 | |
280 if (state_->should_quit) | |
281 return; | |
282 | |
283 state_->delegate->DoDelayedWork(&delayed_work_time_); | |
284 } | |
285 | |
286 void MessagePumpGlib::AddObserver(MessagePumpObserver* observer) { | |
287 observers_.AddObserver(observer); | |
288 } | |
289 | |
290 void MessagePumpGlib::RemoveObserver(MessagePumpObserver* observer) { | |
291 observers_.RemoveObserver(observer); | |
292 } | |
293 | |
294 void MessagePumpGlib::Run(Delegate* delegate) { | |
295 RunWithDispatcher(delegate, NULL); | |
296 } | |
297 | |
298 void MessagePumpGlib::Quit() { | |
299 if (state_) { | |
300 state_->should_quit = true; | |
301 } else { | |
302 NOTREACHED() << "Quit called outside Run!"; | |
303 } | |
304 } | |
305 | |
306 void MessagePumpGlib::ScheduleWork() { | |
307 // This can be called on any thread, so we don't want to touch any state | |
308 // variables as we would then need locks all over. This ensures that if | |
309 // we are sleeping in a poll that we will wake up. | |
310 char msg = '!'; | |
311 if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) { | |
312 NOTREACHED() << "Could not write to the UI message loop wakeup pipe!"; | |
313 } | |
314 } | |
315 | |
316 void MessagePumpGlib::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { | |
317 // We need to wake up the loop in case the poll timeout needs to be | |
318 // adjusted. This will cause us to try to do work, but that's ok. | |
319 delayed_work_time_ = delayed_work_time; | |
320 ScheduleWork(); | |
321 } | |
322 | |
323 MessagePumpGlib::~MessagePumpGlib() { | |
324 g_source_destroy(work_source_); | |
325 g_source_unref(work_source_); | |
326 close(wakeup_pipe_read_); | |
327 close(wakeup_pipe_write_); | |
328 } | |
329 | |
330 MessagePumpDispatcher* MessagePumpGlib::GetDispatcher() { | |
331 return state_ ? state_->dispatcher : NULL; | |
332 } | |
333 | |
334 } // namespace base | |
OLD | NEW |