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 "extensions/browser/api/usb/usb_guid_map.h"
9 #include "base/lazy_instance.h"
10 #include "device/core/device_client.h"
11 #include "device/usb/usb_device.h"
12 #include "device/usb/usb_service.h"
14 namespace extensions
{
18 base::LazyInstance
<BrowserContextKeyedAPIFactory
<UsbGuidMap
>>::Leaky
19 g_usb_guid_map_factory
= LAZY_INSTANCE_INITIALIZER
;
24 UsbGuidMap
* UsbGuidMap::Get(content::BrowserContext
* browser_context
) {
25 return BrowserContextKeyedAPIFactory
<UsbGuidMap
>::Get(browser_context
);
29 BrowserContextKeyedAPIFactory
<UsbGuidMap
>* UsbGuidMap::GetFactoryInstance() {
30 return g_usb_guid_map_factory
.Pointer();
33 int UsbGuidMap::GetIdFromGuid(const std::string
& guid
) {
34 auto iter
= guid_to_id_map_
.find(guid
);
35 if (iter
== guid_to_id_map_
.end()) {
36 auto result
= guid_to_id_map_
.insert(std::make_pair(guid
, next_id_
++));
37 DCHECK(result
.second
);
39 id_to_guid_map_
.insert(std::make_pair(iter
->second
, guid
));
44 bool UsbGuidMap::GetGuidFromId(int id
, std::string
* guid
) {
45 auto iter
= id_to_guid_map_
.find(id
);
46 if (iter
== id_to_guid_map_
.end())
52 UsbGuidMap::UsbGuidMap(content::BrowserContext
* browser_context
)
53 : browser_context_(browser_context
), observer_(this) {
54 device::UsbService
* service
= device::DeviceClient::Get()->GetUsbService();
56 observer_
.Add(service
);
59 UsbGuidMap::~UsbGuidMap() {
62 void UsbGuidMap::OnDeviceRemovedCleanup(
63 scoped_refptr
<device::UsbDevice
> device
) {
64 auto iter
= guid_to_id_map_
.find(device
->guid());
65 if (iter
!= guid_to_id_map_
.end()) {
66 int id
= iter
->second
;
67 guid_to_id_map_
.erase(iter
);
68 id_to_guid_map_
.erase(id
);
72 } // namespace extensions