blob: 69fbb951b0cdef4db0784e0bedb44f69ca3b1e06 [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]b44d5cc2009-06-15 10:30:442// 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
[email protected]23d35392009-06-15 19:53:087#include <math.h>
8
[email protected]b44d5cc2009-06-15 10:30:449#include <algorithm>
10#include <vector>
[email protected]23d35392009-06-15 19:53:0811
[email protected]3b63f8f42011-03-28 01:54:1512#include "base/memory/ref_counted.h"
[email protected]b44d5cc2009-06-15 10:30:4413#include "base/message_loop.h"
[email protected]34b99632011-01-01 01:01:0614#include "base/threading/thread.h"
[email protected]b44d5cc2009-06-15 10:30:4415#include "testing/gtest/include/gtest/gtest.h"
16
[email protected]258dca42011-09-21 00:17:1917#if defined(TOOLKIT_USES_GTK)
18#include <gtk/gtk.h>
19#endif
20
[email protected]b44d5cc2009-06-15 10:30:4421namespace {
22
23// This class injects dummy "events" into the GLib loop. When "handled" these
24// events can run tasks. This is intended to mock gtk events (the corresponding
25// GLib source runs at the same priority).
26class EventInjector {
27 public:
28 EventInjector() : processed_events_(0) {
29 source_ = static_cast<Source*>(g_source_new(&SourceFuncs, sizeof(Source)));
30 source_->injector = this;
31 g_source_attach(source_, NULL);
32 g_source_set_can_recurse(source_, TRUE);
33 }
34
35 ~EventInjector() {
36 g_source_destroy(source_);
37 g_source_unref(source_);
38 }
39
40 int HandlePrepare() {
41 // If the queue is empty, block.
42 if (events_.empty())
43 return -1;
44 base::TimeDelta delta = events_[0].time - base::Time::NowFromSystemTime();
45 return std::max(0, static_cast<int>(ceil(delta.InMillisecondsF())));
46 }
47
48 bool HandleCheck() {
49 if (events_.empty())
50 return false;
[email protected]b44d5cc2009-06-15 10:30:4451 return events_[0].time <= base::Time::NowFromSystemTime();
52 }
53
54 void HandleDispatch() {
55 if (events_.empty())
56 return;
57 Event event = events_[0];
58 events_.erase(events_.begin());
59 ++processed_events_;
60 if (event.task) {
61 event.task->Run();
62 delete event.task;
63 }
64 }
65
66 // Adds an event to the queue. When "handled", executes |task|.
67 // delay_ms is relative to the last event if any, or to Now() otherwise.
68 void AddEvent(int delay_ms, Task* task) {
69 base::Time last_time;
70 if (!events_.empty()) {
71 last_time = (events_.end()-1)->time;
72 } else {
73 last_time = base::Time::NowFromSystemTime();
74 }
75 base::Time future = last_time + base::TimeDelta::FromMilliseconds(delay_ms);
76 EventInjector::Event event = { future, task };
77 events_.push_back(event);
78 }
79
80 void Reset() {
81 processed_events_ = 0;
82 events_.clear();
83 }
84
85 int processed_events() const { return processed_events_; }
86
87 private:
88 struct Event {
89 base::Time time;
90 Task* task;
91 };
92
93 struct Source : public GSource {
94 EventInjector* injector;
95 };
96
97 static gboolean Prepare(GSource* source, gint* timeout_ms) {
98 *timeout_ms = static_cast<Source*>(source)->injector->HandlePrepare();
99 return FALSE;
100 }
101
102 static gboolean Check(GSource* source) {
103 return static_cast<Source*>(source)->injector->HandleCheck();
104 }
105
106 static gboolean Dispatch(GSource* source,
107 GSourceFunc unused_func,
108 gpointer unused_data) {
109 static_cast<Source*>(source)->injector->HandleDispatch();
110 return TRUE;
111 }
112
113 Source* source_;
114 std::vector<Event> events_;
115 int processed_events_;
116 static GSourceFuncs SourceFuncs;
117 DISALLOW_COPY_AND_ASSIGN(EventInjector);
118};
119
120GSourceFuncs EventInjector::SourceFuncs = {
121 EventInjector::Prepare,
122 EventInjector::Check,
123 EventInjector::Dispatch,
124 NULL
125};
126
127// Does nothing. This function can be called from a task.
128void DoNothing() {
129}
130
131void IncrementInt(int *value) {
132 ++*value;
133}
134
135// Checks how many events have been processed by the injector.
136void ExpectProcessedEvents(EventInjector* injector, int count) {
137 EXPECT_EQ(injector->processed_events(), count);
138}
139
140// Quits the current message loop.
141void QuitMessageLoop() {
142 MessageLoop::current()->Quit();
143}
144
145// Returns a new task that quits the main loop.
146Task* NewQuitTask() {
147 return NewRunnableFunction(QuitMessageLoop);
148}
149
150// Posts a task on the current message loop.
151void PostMessageLoopTask(const tracked_objects::Location& from_here,
152 Task* task) {
153 MessageLoop::current()->PostTask(from_here, task);
154}
155
156// Test fixture.
157class MessagePumpGLibTest : public testing::Test {
158 public:
159 MessagePumpGLibTest() : loop_(NULL), injector_(NULL) { }
160
161 virtual void SetUp() {
162 loop_ = new MessageLoop(MessageLoop::TYPE_UI);
163 injector_ = new EventInjector();
164 }
165
166 virtual void TearDown() {
167 delete injector_;
168 injector_ = NULL;
169 delete loop_;
170 loop_ = NULL;
171 }
172
173 MessageLoop* loop() const { return loop_; }
174 EventInjector* injector() const { return injector_; }
175
176 private:
177 MessageLoop* loop_;
178 EventInjector* injector_;
179 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest);
180};
181
182} // namespace
183
184// EventInjector is expected to always live longer than the runnable methods.
[email protected]c56428f22010-06-16 02:17:23185DISABLE_RUNNABLE_METHOD_REFCOUNT(EventInjector);
[email protected]b44d5cc2009-06-15 10:30:44186
187TEST_F(MessagePumpGLibTest, TestQuit) {
188 // Checks that Quit works and that the basic infrastructure is working.
189
190 // Quit from a task
191 loop()->PostTask(FROM_HERE, NewQuitTask());
192 loop()->Run();
193 EXPECT_EQ(0, injector()->processed_events());
194
195 injector()->Reset();
196 // Quit from an event
197 injector()->AddEvent(0, NewQuitTask());
198 loop()->Run();
199 EXPECT_EQ(1, injector()->processed_events());
200}
201
202TEST_F(MessagePumpGLibTest, TestEventTaskInterleave) {
203 // Checks that tasks posted by events are executed before the next event if
204 // the posted task queue is empty.
205 // MessageLoop doesn't make strong guarantees that it is the case, but the
206 // current implementation ensures it and the tests below rely on it.
207 // If changes cause this test to fail, it is reasonable to change it, but
208 // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
209 // changed accordingly, otherwise they can become flaky.
210 injector()->AddEvent(0, NewRunnableFunction(DoNothing));
211 Task* check_task = NewRunnableFunction(ExpectProcessedEvents, injector(), 2);
212 Task* posted_task = NewRunnableFunction(PostMessageLoopTask,
213 FROM_HERE, check_task);
214 injector()->AddEvent(0, posted_task);
215 injector()->AddEvent(0, NewRunnableFunction(DoNothing));
216 injector()->AddEvent(0, NewQuitTask());
217 loop()->Run();
218 EXPECT_EQ(4, injector()->processed_events());
219
220 injector()->Reset();
221 injector()->AddEvent(0, NewRunnableFunction(DoNothing));
222 check_task = NewRunnableFunction(ExpectProcessedEvents, injector(), 2);
223 posted_task = NewRunnableFunction(PostMessageLoopTask, FROM_HERE, check_task);
224 injector()->AddEvent(0, posted_task);
225 injector()->AddEvent(10, NewRunnableFunction(DoNothing));
226 injector()->AddEvent(0, NewQuitTask());
227 loop()->Run();
228 EXPECT_EQ(4, injector()->processed_events());
229}
230
231TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
232 int task_count = 0;
233 // Tests that we process tasks while waiting for new events.
234 // The event queue is empty at first.
235 for (int i = 0; i < 10; ++i) {
236 loop()->PostTask(FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
237 }
238 // After all the previous tasks have executed, enqueue an event that will
239 // quit.
240 loop()->PostTask(
241 FROM_HERE, NewRunnableMethod(injector(), &EventInjector::AddEvent,
242 0, NewQuitTask()));
243 loop()->Run();
244 ASSERT_EQ(10, task_count);
245 EXPECT_EQ(1, injector()->processed_events());
246
247 // Tests that we process delayed tasks while waiting for new events.
248 injector()->Reset();
249 task_count = 0;
250 for (int i = 0; i < 10; ++i) {
251 loop()->PostDelayedTask(
252 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count), 10*i);
253 }
254 // After all the previous tasks have executed, enqueue an event that will
255 // quit.
256 // This relies on the fact that delayed tasks are executed in delay order.
257 // That is verified in message_loop_unittest.cc.
258 loop()->PostDelayedTask(
259 FROM_HERE, NewRunnableMethod(injector(), &EventInjector::AddEvent,
260 10, NewQuitTask()), 150);
261 loop()->Run();
262 ASSERT_EQ(10, task_count);
263 EXPECT_EQ(1, injector()->processed_events());
264}
265
266TEST_F(MessagePumpGLibTest, TestEventsWhileWaitingForWork) {
267 // Tests that we process events while waiting for work.
268 // The event queue is empty at first.
269 for (int i = 0; i < 10; ++i) {
270 injector()->AddEvent(0, NULL);
271 }
272 // After all the events have been processed, post a task that will check that
273 // the events have been processed (note: the task executes after the event
274 // that posted it has been handled, so we expect 11 at that point).
275 Task* check_task = NewRunnableFunction(ExpectProcessedEvents, injector(), 11);
276 Task* posted_task = NewRunnableFunction(PostMessageLoopTask,
277 FROM_HERE, check_task);
278 injector()->AddEvent(10, posted_task);
279
280 // And then quit (relies on the condition tested by TestEventTaskInterleave).
281 injector()->AddEvent(10, NewQuitTask());
282 loop()->Run();
283
284 EXPECT_EQ(12, injector()->processed_events());
285}
286
287namespace {
288
289// This class is a helper for the concurrent events / posted tasks test below.
290// It will quit the main loop once enough tasks and events have been processed,
291// while making sure there is always work to do and events in the queue.
292class ConcurrentHelper : public base::RefCounted<ConcurrentHelper> {
293 public:
[email protected]2fdc86a2010-01-26 23:08:02294 explicit ConcurrentHelper(EventInjector* injector)
[email protected]b44d5cc2009-06-15 10:30:44295 : injector_(injector),
296 event_count_(kStartingEventCount),
297 task_count_(kStartingTaskCount) {
298 }
299
300 void FromTask() {
301 if (task_count_ > 0) {
302 --task_count_;
303 }
304 if (task_count_ == 0 && event_count_ == 0) {
305 MessageLoop::current()->Quit();
306 } else {
307 MessageLoop::current()->PostTask(
308 FROM_HERE, NewRunnableMethod(this, &ConcurrentHelper::FromTask));
309 }
310 }
311
312 void FromEvent() {
313 if (event_count_ > 0) {
314 --event_count_;
315 }
316 if (task_count_ == 0 && event_count_ == 0) {
317 MessageLoop::current()->Quit();
318 } else {
319 injector_->AddEvent(
320 0, NewRunnableMethod(this, &ConcurrentHelper::FromEvent));
321 }
322 }
323
324 int event_count() const { return event_count_; }
325 int task_count() const { return task_count_; }
326
327 private:
[email protected]877d55d2009-11-05 21:53:08328 friend class base::RefCounted<ConcurrentHelper>;
329
330 ~ConcurrentHelper() {}
331
[email protected]b44d5cc2009-06-15 10:30:44332 static const int kStartingEventCount = 20;
333 static const int kStartingTaskCount = 20;
334
335 EventInjector* injector_;
336 int event_count_;
337 int task_count_;
338};
339
340} // namespace
341
342TEST_F(MessagePumpGLibTest, TestConcurrentEventPostedTask) {
343 // Tests that posted tasks don't starve events, nor the opposite.
344 // We use the helper class above. We keep both event and posted task queues
345 // full, the helper verifies that both tasks and events get processed.
346 // If that is not the case, either event_count_ or task_count_ will not get
347 // to 0, and MessageLoop::Quit() will never be called.
348 scoped_refptr<ConcurrentHelper> helper = new ConcurrentHelper(injector());
349
350 // Add 2 events to the queue to make sure it is always full (when we remove
351 // the event before processing it).
352 injector()->AddEvent(
353 0, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromEvent));
354 injector()->AddEvent(
355 0, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromEvent));
356
357 // Similarly post 2 tasks.
358 loop()->PostTask(
359 FROM_HERE, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromTask));
360 loop()->PostTask(
361 FROM_HERE, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromTask));
362
363 loop()->Run();
364 EXPECT_EQ(0, helper->event_count());
365 EXPECT_EQ(0, helper->task_count());
366}
367
368namespace {
369
370void AddEventsAndDrainGLib(EventInjector* injector) {
371 // Add a couple of dummy events
372 injector->AddEvent(0, NULL);
373 injector->AddEvent(0, NULL);
374 // Then add an event that will quit the main loop.
375 injector->AddEvent(0, NewQuitTask());
376
377 // Post a couple of dummy tasks
378 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
379 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
380
381 // Drain the events
382 while (g_main_context_pending(NULL)) {
383 g_main_context_iteration(NULL, FALSE);
384 }
385}
386
387} // namespace
388
389TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
390 // Tests that draining events using GLib works.
391 loop()->PostTask(
392 FROM_HERE, NewRunnableFunction(AddEventsAndDrainGLib, injector()));
393 loop()->Run();
394
395 EXPECT_EQ(3, injector()->processed_events());
396}
397
398
399namespace {
400
[email protected]258dca42011-09-21 00:17:19401#if defined(TOOLKIT_USES_GTK)
[email protected]b44d5cc2009-06-15 10:30:44402void AddEventsAndDrainGtk(EventInjector* injector) {
403 // Add a couple of dummy events
404 injector->AddEvent(0, NULL);
405 injector->AddEvent(0, NULL);
406 // Then add an event that will quit the main loop.
407 injector->AddEvent(0, NewQuitTask());
408
409 // Post a couple of dummy tasks
410 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
411 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
412
413 // Drain the events
414 while (gtk_events_pending()) {
415 gtk_main_iteration();
416 }
417}
[email protected]258dca42011-09-21 00:17:19418#endif
[email protected]b44d5cc2009-06-15 10:30:44419
420} // namespace
421
[email protected]258dca42011-09-21 00:17:19422#if defined(TOOLKIT_USES_GTK)
[email protected]b44d5cc2009-06-15 10:30:44423TEST_F(MessagePumpGLibTest, TestDrainingGtk) {
424 // Tests that draining events using Gtk works.
425 loop()->PostTask(
426 FROM_HERE, NewRunnableFunction(AddEventsAndDrainGtk, injector()));
427 loop()->Run();
428
429 EXPECT_EQ(3, injector()->processed_events());
430}
[email protected]258dca42011-09-21 00:17:19431#endif
[email protected]b44d5cc2009-06-15 10:30:44432
433namespace {
434
435// Helper class that lets us run the GLib message loop.
436class GLibLoopRunner : public base::RefCounted<GLibLoopRunner> {
437 public:
438 GLibLoopRunner() : quit_(false) { }
439
440 void RunGLib() {
441 while (!quit_) {
442 g_main_context_iteration(NULL, TRUE);
443 }
444 }
445
[email protected]258dca42011-09-21 00:17:19446 void RunLoop() {
447#if defined(TOOLKIT_USES_GTK)
[email protected]b44d5cc2009-06-15 10:30:44448 while (!quit_) {
449 gtk_main_iteration();
450 }
[email protected]258dca42011-09-21 00:17:19451#else
452 while (!quit_) {
453 g_main_context_iteration(NULL, TRUE);
454 }
455#endif
[email protected]b44d5cc2009-06-15 10:30:44456 }
457
458 void Quit() {
459 quit_ = true;
460 }
461
462 void Reset() {
463 quit_ = false;
464 }
465
466 private:
[email protected]877d55d2009-11-05 21:53:08467 friend class base::RefCounted<GLibLoopRunner>;
468
469 ~GLibLoopRunner() {}
470
[email protected]b44d5cc2009-06-15 10:30:44471 bool quit_;
472};
473
474void TestGLibLoopInternal(EventInjector* injector) {
475 // Allow tasks to be processed from 'native' event loops.
476 MessageLoop::current()->SetNestableTasksAllowed(true);
477 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
478
479 int task_count = 0;
480 // Add a couple of dummy events
481 injector->AddEvent(0, NULL);
482 injector->AddEvent(0, NULL);
483 // Post a couple of dummy tasks
484 MessageLoop::current()->PostTask(
485 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
486 MessageLoop::current()->PostTask(
487 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
488 // Delayed events
489 injector->AddEvent(10, NULL);
490 injector->AddEvent(10, NULL);
491 // Delayed work
492 MessageLoop::current()->PostDelayedTask(
493 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count), 30);
494 MessageLoop::current()->PostDelayedTask(
495 FROM_HERE, NewRunnableMethod(runner.get(), &GLibLoopRunner::Quit), 40);
496
497 // Run a nested, straight GLib message loop.
498 runner->RunGLib();
499
500 ASSERT_EQ(3, task_count);
501 EXPECT_EQ(4, injector->processed_events());
502 MessageLoop::current()->Quit();
503}
504
505void TestGtkLoopInternal(EventInjector* injector) {
506 // Allow tasks to be processed from 'native' event loops.
507 MessageLoop::current()->SetNestableTasksAllowed(true);
508 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
509
510 int task_count = 0;
511 // Add a couple of dummy events
512 injector->AddEvent(0, NULL);
513 injector->AddEvent(0, NULL);
514 // Post a couple of dummy tasks
515 MessageLoop::current()->PostTask(
516 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
517 MessageLoop::current()->PostTask(
518 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
519 // Delayed events
520 injector->AddEvent(10, NULL);
521 injector->AddEvent(10, NULL);
522 // Delayed work
523 MessageLoop::current()->PostDelayedTask(
524 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count), 30);
525 MessageLoop::current()->PostDelayedTask(
526 FROM_HERE, NewRunnableMethod(runner.get(), &GLibLoopRunner::Quit), 40);
527
528 // Run a nested, straight Gtk message loop.
[email protected]258dca42011-09-21 00:17:19529 runner->RunLoop();
[email protected]b44d5cc2009-06-15 10:30:44530
531 ASSERT_EQ(3, task_count);
532 EXPECT_EQ(4, injector->processed_events());
533 MessageLoop::current()->Quit();
534}
535
536} // namespace
537
538TEST_F(MessagePumpGLibTest, TestGLibLoop) {
539 // Tests that events and posted tasks are correctly exectuted if the message
540 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
541 // Note that in this case we don't make strong guarantees about niceness
542 // between events and posted tasks.
543 loop()->PostTask(FROM_HERE,
544 NewRunnableFunction(TestGLibLoopInternal, injector()));
545 loop()->Run();
546}
547
548TEST_F(MessagePumpGLibTest, TestGtkLoop) {
549 // Tests that events and posted tasks are correctly exectuted if the message
550 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
551 // Note that in this case we don't make strong guarantees about niceness
552 // between events and posted tasks.
553 loop()->PostTask(FROM_HERE,
554 NewRunnableFunction(TestGtkLoopInternal, injector()));
555 loop()->Run();
556}