Alex Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 1 | // 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 Deymo | 63784a5 | 2014-05-28 10:46:14 -0700 | [diff] [blame] | 5 | #include "update_engine/update_manager/event_loop.h" |
Alex Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 6 | |
| 7 | #include <cmath> |
| 8 | |
| 9 | using base::Closure; |
| 10 | |
| 11 | namespace { |
| 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|. |
| 17 | gboolean OnRanFromMainLoop(gpointer user_data) { |
| 18 | Closure* callback_p = reinterpret_cast<Closure*>(user_data); |
| 19 | callback_p->Run(); |
Alex Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 20 | return FALSE; // Removes the source since a callback can only be called once. |
| 21 | } |
| 22 | |
Alex Deymo | 3273d03 | 2014-05-28 19:29:52 -0700 | [diff] [blame^] | 23 | void DestroyClosure(gpointer user_data) { |
| 24 | delete reinterpret_cast<Closure*>(user_data); |
| 25 | } |
| 26 | |
Alex Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 27 | } // namespace |
| 28 | |
Alex Deymo | 63784a5 | 2014-05-28 10:46:14 -0700 | [diff] [blame] | 29 | namespace chromeos_update_manager { |
Alex Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 30 | |
| 31 | EventId 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 Deymo | 3273d03 | 2014-05-28 19:29:52 -0700 | [diff] [blame^] | 36 | DestroyClosure); |
Alex Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 37 | } |
| 38 | |
| 39 | EventId RunFromMainLoopAfterTimeout( |
| 40 | const Closure& callback, |
| 41 | base::TimeDelta timeout) { |
| 42 | Closure* callback_p = new Closure(callback); |
Alex Deymo | 3273d03 | 2014-05-28 19:29:52 -0700 | [diff] [blame^] | 43 | 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 Deymo | 53556ec | 2014-03-17 10:05:57 -0700 | [diff] [blame] | 49 | } |
| 50 | |
| 51 | bool CancelMainLoopEvent(EventId event) { |
| 52 | if (event != kEventIdNull) |
| 53 | return g_source_remove(event); |
| 54 | return false; |
| 55 | } |
| 56 | |
Alex Deymo | 63784a5 | 2014-05-28 10:46:14 -0700 | [diff] [blame] | 57 | } // namespace chromeos_update_manager |