1 // Copyright 2015 The Chromium 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.
5 #include "device/usb/usb_service.h"
7 #include "base/message_loop/message_loop.h"
8 #include "device/usb/usb_device.h"
9 #include "device/usb/usb_service_impl.h"
15 UsbService
* g_service
;
19 // This class manages the lifetime of the global UsbService instance so that
20 // it is destroyed when the current message loop is destroyed. A lazy instance
21 // cannot be used because this object does not live on the main thread.
22 class UsbService::Destroyer
: private base::MessageLoop::DestructionObserver
{
24 explicit Destroyer(UsbService
* usb_service
) : usb_service_(usb_service
) {
25 base::MessageLoop::current()->AddDestructionObserver(this);
27 ~Destroyer() override
{}
30 // base::MessageLoop::DestructionObserver implementation.
31 void WillDestroyCurrentMessageLoop() override
{
32 base::MessageLoop::current()->RemoveDestructionObserver(this);
38 UsbService
* usb_service_
;
41 void UsbService::Observer::OnDeviceAdded(scoped_refptr
<UsbDevice
> device
) {
44 void UsbService::Observer::OnDeviceRemoved(scoped_refptr
<UsbDevice
> device
) {
48 UsbService
* UsbService::GetInstance(
49 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner
) {
51 g_service
= UsbServiceImpl::Create(ui_task_runner
);
52 // This object will clean itself up when the message loop is destroyed.
53 new Destroyer(g_service
);
59 void UsbService::SetInstanceForTest(UsbService
* instance
) {
61 new Destroyer(instance
);
64 UsbService::UsbService() {
67 UsbService::~UsbService() {
70 void UsbService::AddObserver(Observer
* observer
) {
71 DCHECK(CalledOnValidThread());
72 observer_list_
.AddObserver(observer
);
75 void UsbService::RemoveObserver(Observer
* observer
) {
76 DCHECK(CalledOnValidThread());
77 observer_list_
.RemoveObserver(observer
);
80 void UsbService::NotifyDeviceAdded(scoped_refptr
<UsbDevice
> device
) {
81 DCHECK(CalledOnValidThread());
82 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnDeviceAdded(device
));
85 void UsbService::NotifyDeviceRemoved(scoped_refptr
<UsbDevice
> device
) {
86 DCHECK(CalledOnValidThread());
87 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnDeviceRemoved(device
));