Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / extensions / browser / api / usb / usb_guid_map.cc
blob0cb3ce857800befb7d25706b195949d1ecf9e4ea
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"
7 #include <utility>
9 #include "base/lazy_instance.h"
10 #include "base/strings/utf_string_conversions.h"
11 #include "device/core/device_client.h"
12 #include "device/usb/usb_device.h"
13 #include "device/usb/usb_service.h"
14 #include "extensions/common/api/usb.h"
16 namespace extensions {
18 namespace {
20 base::LazyInstance<BrowserContextKeyedAPIFactory<UsbGuidMap>>::Leaky
21 g_usb_guid_map_factory = LAZY_INSTANCE_INITIALIZER;
23 } // namespace
25 // static
26 UsbGuidMap* UsbGuidMap::Get(content::BrowserContext* browser_context) {
27 return BrowserContextKeyedAPIFactory<UsbGuidMap>::Get(browser_context);
30 // static
31 BrowserContextKeyedAPIFactory<UsbGuidMap>* UsbGuidMap::GetFactoryInstance() {
32 return g_usb_guid_map_factory.Pointer();
35 int UsbGuidMap::GetIdFromGuid(const std::string& guid) {
36 auto iter = guid_to_id_map_.find(guid);
37 if (iter == guid_to_id_map_.end()) {
38 auto result = guid_to_id_map_.insert(std::make_pair(guid, next_id_++));
39 DCHECK(result.second);
40 iter = result.first;
41 id_to_guid_map_.insert(std::make_pair(iter->second, guid));
43 return iter->second;
46 bool UsbGuidMap::GetGuidFromId(int id, std::string* guid) {
47 auto iter = id_to_guid_map_.find(id);
48 if (iter == id_to_guid_map_.end())
49 return false;
50 *guid = iter->second;
51 return true;
54 void UsbGuidMap::GetApiDevice(scoped_refptr<const device::UsbDevice> device_in,
55 extensions::api::usb::Device* device_out) {
56 device_out->device = GetIdFromGuid(device_in->guid());
57 device_out->vendor_id = device_in->vendor_id();
58 device_out->product_id = device_in->product_id();
59 device_out->product_name = base::UTF16ToUTF8(device_in->product_string());
60 device_out->manufacturer_name =
61 base::UTF16ToUTF8(device_in->manufacturer_string());
62 device_out->serial_number = base::UTF16ToUTF8(device_in->serial_number());
65 UsbGuidMap::UsbGuidMap(content::BrowserContext* browser_context)
66 : browser_context_(browser_context), observer_(this) {
67 device::UsbService* service = device::DeviceClient::Get()->GetUsbService();
68 DCHECK(service);
69 observer_.Add(service);
72 UsbGuidMap::~UsbGuidMap() {
75 void UsbGuidMap::OnDeviceRemovedCleanup(
76 scoped_refptr<device::UsbDevice> device) {
77 auto iter = guid_to_id_map_.find(device->guid());
78 if (iter != guid_to_id_map_.end()) {
79 int id = iter->second;
80 guid_to_id_map_.erase(iter);
81 id_to_guid_map_.erase(id);
85 } // namespace extensions