blob: bc2940b2d3fdcda3c32eede6d0d516084f9b30b7 [file] [log] [blame]
Alex Deymo53556ec2014-03-17 10:05:57 -07001// Copyright (c) 2014 The Chromium OS 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
Alex Deymo63784a52014-05-28 10:46:14 -07005#include "update_engine/update_manager/event_loop.h"
Alex Deymo53556ec2014-03-17 10:05:57 -07006
7#include <cmath>
8
9using base::Closure;
10
11namespace {
12
13// Called by the GLib's main loop when is time to call the callback scheduled
14// with RunFromMainLopp() and similar functions. The pointer to the callback
15// passed when scheduling it is passed to this functions as a gpointer on
16// |user_data|.
17gboolean OnRanFromMainLoop(gpointer user_data) {
18 Closure* callback_p = reinterpret_cast<Closure*>(user_data);
19 callback_p->Run();
Alex Deymo53556ec2014-03-17 10:05:57 -070020 return FALSE; // Removes the source since a callback can only be called once.
21}
22
Alex Deymo3273d032014-05-28 19:29:52 -070023void DestroyClosure(gpointer user_data) {
24 delete reinterpret_cast<Closure*>(user_data);
25}
26
Alex Deymo53556ec2014-03-17 10:05:57 -070027} // namespace
28
Alex Deymo63784a52014-05-28 10:46:14 -070029namespace chromeos_update_manager {
Alex Deymo53556ec2014-03-17 10:05:57 -070030
31EventId RunFromMainLoop(const Closure& callback) {
32 Closure* callback_p = new Closure(callback);
33 return g_idle_add_full(G_PRIORITY_DEFAULT,
34 OnRanFromMainLoop,
35 reinterpret_cast<gpointer>(callback_p),
Alex Deymo3273d032014-05-28 19:29:52 -070036 DestroyClosure);
Alex Deymo53556ec2014-03-17 10:05:57 -070037}
38
39EventId RunFromMainLoopAfterTimeout(
40 const Closure& callback,
41 base::TimeDelta timeout) {
42 Closure* callback_p = new Closure(callback);
Alex Deymo3273d032014-05-28 19:29:52 -070043 return g_timeout_add_seconds_full(
44 G_PRIORITY_DEFAULT,
45 static_cast<guint>(ceil(timeout.InSecondsF())),
46 OnRanFromMainLoop,
47 reinterpret_cast<gpointer>(callback_p),
48 DestroyClosure);
Alex Deymo53556ec2014-03-17 10:05:57 -070049}
50
51bool CancelMainLoopEvent(EventId event) {
52 if (event != kEventIdNull)
53 return g_source_remove(event);
54 return false;
55}
56
Alex Deymo63784a52014-05-28 10:46:14 -070057} // namespace chromeos_update_manager