summaryrefslogtreecommitdiffstats
path: root/device/hid/device_monitor_linux.h
blob: d05e31ba1b7c6f5600e81dde45e570f2728b6dad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef DEVICE_HID_DEVICE_MONITOR_LINUX_H_
#define DEVICE_HID_DEVICE_MONITOR_LINUX_H_

#include <string>

#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_pump_libevent.h"
#include "base/observer_list.h"
#include "base/threading/thread_checker.h"
#include "device/udev_linux/scoped_udev.h"

struct udev_device;

namespace device {

// This class listends for notifications from libudev about
// connected/disconnected devices. This class is *NOT* thread-safe and
// all methods must be accessed from the FILE thread.
class DeviceMonitorLinux : public base::MessageLoop::DestructionObserver,
                           public base::MessagePumpLibevent::Watcher {
 public:
  typedef base::Callback<void(udev_device* device)> EnumerateCallback;

  class Observer {
   public:
    virtual ~Observer() {}
    virtual void OnDeviceAdded(udev_device* device) = 0;
    virtual void OnDeviceRemoved(udev_device* device) = 0;
  };

  DeviceMonitorLinux();

  static DeviceMonitorLinux* GetInstance();
  static bool HasInstance();

  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  ScopedUdevDevicePtr GetDeviceFromPath(const std::string& path);
  void Enumerate(const EnumerateCallback& callback);

  // Implements base::MessageLoop::DestructionObserver
  void WillDestroyCurrentMessageLoop() override;

  // Implements base::MessagePumpLibevent::Watcher
  void OnFileCanReadWithoutBlocking(int fd) override;
  void OnFileCanWriteWithoutBlocking(int fd) override;

 private:
  friend struct base::DefaultDeleter<DeviceMonitorLinux>;

  ~DeviceMonitorLinux() override;

  ScopedUdevPtr udev_;
  ScopedUdevMonitorPtr monitor_;
  int monitor_fd_;
  base::MessagePumpLibevent::FileDescriptorWatcher monitor_watcher_;

  base::ObserverList<Observer> observers_;

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(DeviceMonitorLinux);
};

}  // namespace device

#endif  // DEVICE_HID_DEVICE_MONITOR_LINUX_H_