blob: 3034802aa70504c12b623c0595a24e77629c68dc [file] [log] [blame]
Eric Caruso246e1412019-01-24 16:44:02 -08001// Copyright 2019 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
5// A simple event bridge to allow glib programs to operate on a libchrome
6// message loop.
7
8#ifndef GLIB_BRIDGE_GLIB_BRIDGE_H_
9#define GLIB_BRIDGE_GLIB_BRIDGE_H_
10
11#include <glib.h>
12
13#include <map>
14#include <memory>
15#include <vector>
16
17#include <base/bind.h>
18#include <base/cancelable_callback.h>
Eric Carusobcc58bb2019-11-07 14:10:35 -080019#include <base/files/file_descriptor_watcher_posix.h>
Eric Caruso246e1412019-01-24 16:44:02 -080020
Eric Caruso353af302020-10-12 11:44:25 -070021#include "glib-bridge/glib_bridge_export.h"
22
Eric Caruso246e1412019-01-24 16:44:02 -080023namespace glib_bridge {
24
Eric Caruso353af302020-10-12 11:44:25 -070025struct GLIB_BRIDGE_EXPORT GlibBridge {
Eric Caruso246e1412019-01-24 16:44:02 -080026 public:
Eric Carusobcc58bb2019-11-07 14:10:35 -080027 GlibBridge();
28 virtual ~GlibBridge();
Eric Caruso246e1412019-01-24 16:44:02 -080029
30 private:
31 enum class State {
32 kPreparingIteration,
33 kWaitingForEvents,
34 kReadyForDispatch,
35 };
36
Eric Carusobcc58bb2019-11-07 14:10:35 -080037 struct Watcher {
38 std::unique_ptr<base::FileDescriptorWatcher::Controller> reader;
39 std::unique_ptr<base::FileDescriptorWatcher::Controller> writer;
40 };
41
Eric Caruso246e1412019-01-24 16:44:02 -080042 void PrepareIteration();
Eric Carusobcc58bb2019-11-07 14:10:35 -080043 void Timeout();
Eric Caruso246e1412019-01-24 16:44:02 -080044 void Dispatch();
45
46 void OnEvent(int fd, int flag);
47
48 // If we ever need to support multiple GMainContexts instead of just the
49 // default one then we can wrap a different context here. This is a weak
50 // pointer.
51 GMainContext* glib_context_;
52
53 // glib event and source bits.
54 int max_priority_ = -1;
55 std::vector<GPollFD> poll_fds_;
56 std::map<int, std::vector<GPollFD*>> fd_map_;
57
58 // libchrome message loop bits.
Eric Carusobcc58bb2019-11-07 14:10:35 -080059 std::map<int, Watcher> watchers_;
Eric Caruso246e1412019-01-24 16:44:02 -080060 base::CancelableClosure timeout_closure_;
61
62 State state_;
63
64 base::WeakPtrFactory<GlibBridge> weak_ptr_factory_;
65};
66
67} // namespace glib_bridge
68
69#endif // GLIB_BRIDGE_GLIB_BRIDGE_H_