Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / content / browser / gamepad / gamepad_platform_data_fetcher_linux.cc
1 // Copyright (c) 2012 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.
4
5 #include "content/browser/gamepad/gamepad_platform_data_fetcher_linux.h"
6
7 #include <fcntl.h>
8 #include <libudev.h>
9 #include <linux/joystick.h>
10 #include <string.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14
15 #include "base/debug/trace_event.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/posix/eintr_wrapper.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "content/browser/udev_linux.h"
23 #include "device/udev_linux/scoped_udev.h"
24
25 namespace {
26
27 const char kInputSubsystem[] = "input";
28 const char kUsbSubsystem[] = "usb";
29 const char kUsbDeviceType[] = "usb_device";
30 const float kMaxLinuxAxisValue = 32767.0;
31
32 void CloseFileDescriptorIfValid(int fd) {
33   if (fd >= 0)
34     close(fd);
35 }
36
37 bool IsGamepad(udev_device* dev, int* index, std::string* path) {
38   if (!udev_device_get_property_value(dev, "ID_INPUT_JOYSTICK"))
39     return false;
40
41   const char* node_path = udev_device_get_devnode(dev);
42   if (!node_path)
43     return false;
44
45   static const char kJoystickRoot[] = "/dev/input/js";
46   bool is_gamepad = StartsWithASCII(node_path, kJoystickRoot, true);
47   if (!is_gamepad)
48     return false;
49
50   int tmp_idx = -1;
51   const int base_len = sizeof(kJoystickRoot) - 1;
52   base::StringPiece str(&node_path[base_len], strlen(node_path) - base_len);
53   if (!base::StringToInt(str, &tmp_idx))
54     return false;
55   if (tmp_idx < 0 ||
56       tmp_idx >= static_cast<int>(blink::WebGamepads::itemsLengthCap)) {
57     return false;
58   }
59   *index = tmp_idx;
60   *path = node_path;
61   return true;
62 }
63
64 }  // namespace
65
66 namespace content {
67
68 using blink::WebGamepad;
69 using blink::WebGamepads;
70
71 GamepadPlatformDataFetcherLinux::GamepadPlatformDataFetcherLinux() {
72   for (size_t i = 0; i < arraysize(device_fds_); ++i)
73     device_fds_[i] = -1;
74   memset(mappers_, 0, sizeof(mappers_));
75
76   std::vector<UdevLinux::UdevMonitorFilter> filters;
77   filters.push_back(UdevLinux::UdevMonitorFilter(kInputSubsystem, NULL));
78   udev_.reset(
79       new UdevLinux(filters,
80                     base::Bind(&GamepadPlatformDataFetcherLinux::RefreshDevice,
81                                base::Unretained(this))));
82
83   EnumerateDevices();
84 }
85
86 GamepadPlatformDataFetcherLinux::~GamepadPlatformDataFetcherLinux() {
87   for (size_t i = 0; i < WebGamepads::itemsLengthCap; ++i)
88     CloseFileDescriptorIfValid(device_fds_[i]);
89 }
90
91 void GamepadPlatformDataFetcherLinux::GetGamepadData(WebGamepads* pads, bool) {
92   TRACE_EVENT0("GAMEPAD", "GetGamepadData");
93
94   data_.length = WebGamepads::itemsLengthCap;
95
96   // Update our internal state.
97   for (size_t i = 0; i < WebGamepads::itemsLengthCap; ++i) {
98     if (device_fds_[i] >= 0) {
99       ReadDeviceData(i);
100     }
101   }
102
103   // Copy to the current state to the output buffer, using the mapping
104   // function, if there is one available.
105   pads->length = data_.length;
106   for (size_t i = 0; i < WebGamepads::itemsLengthCap; ++i) {
107     if (mappers_[i])
108       mappers_[i](data_.items[i], &pads->items[i]);
109     else
110       pads->items[i] = data_.items[i];
111   }
112 }
113
114 // Used during enumeration, and monitor notifications.
115 void GamepadPlatformDataFetcherLinux::RefreshDevice(udev_device* dev) {
116   int index;
117   std::string node_path;
118   if (IsGamepad(dev, &index, &node_path)) {
119     int& device_fd = device_fds_[index];
120     WebGamepad& pad = data_.items[index];
121     GamepadStandardMappingFunction& mapper = mappers_[index];
122
123     CloseFileDescriptorIfValid(device_fd);
124
125     // The device pointed to by dev contains information about the logical
126     // joystick device. In order to get the information about the physical
127     // hardware, get the parent device that is also in the "input" subsystem.
128     // This function should just walk up the tree one level.
129     dev = udev_device_get_parent_with_subsystem_devtype(
130         dev, kInputSubsystem, NULL);
131     if (!dev) {
132       // Unable to get device information, don't use this device.
133       device_fd = -1;
134       pad.connected = false;
135       return;
136     }
137
138     device_fd = HANDLE_EINTR(open(node_path.c_str(), O_RDONLY | O_NONBLOCK));
139     if (device_fd < 0) {
140       // Unable to open device, don't use.
141       pad.connected = false;
142       return;
143     }
144
145     const char* vendor_id = udev_device_get_sysattr_value(dev, "id/vendor");
146     const char* product_id = udev_device_get_sysattr_value(dev, "id/product");
147     mapper = GetGamepadStandardMappingFunction(vendor_id, product_id);
148
149     // Driver returns utf-8 strings here, so combine in utf-8 first and
150     // convert to WebUChar later once we've picked an id string.
151     const char* name = udev_device_get_sysattr_value(dev, "name");
152     std::string name_string = base::StringPrintf("%s", name);
153
154     // In many cases the information the input subsystem contains isn't
155     // as good as the information that the device bus has, walk up further
156     // to the subsystem/device type "usb"/"usb_device" and if this device
157     // has the same vendor/product id, prefer the description from that.
158     struct udev_device* usb_dev = udev_device_get_parent_with_subsystem_devtype(
159         dev, kUsbSubsystem, kUsbDeviceType);
160     if (usb_dev) {
161       const char* usb_vendor_id =
162           udev_device_get_sysattr_value(usb_dev, "idVendor");
163       const char* usb_product_id =
164           udev_device_get_sysattr_value(usb_dev, "idProduct");
165
166       if (strcmp(vendor_id, usb_vendor_id) == 0 &&
167           strcmp(product_id, usb_product_id) == 0) {
168         const char* manufacturer =
169             udev_device_get_sysattr_value(usb_dev, "manufacturer");
170         const char* product = udev_device_get_sysattr_value(usb_dev, "product");
171
172         // Replace the previous name string with one containing the better
173         // information, again driver returns utf-8 strings here so combine
174         // in utf-8 for conversion to WebUChar below.
175         name_string = base::StringPrintf("%s %s", manufacturer, product);
176       }
177     }
178
179     // Append the vendor and product information then convert the utf-8
180     // id string to WebUChar.
181     std::string id =
182         name_string + base::StringPrintf(" (%sVendor: %s Product: %s)",
183                                          mapper ? "STANDARD GAMEPAD " : "",
184                                          vendor_id,
185                                          product_id);
186     base::TruncateUTF8ToByteSize(id, WebGamepad::idLengthCap - 1, &id);
187     base::string16 tmp16 = base::UTF8ToUTF16(id);
188     memset(pad.id, 0, sizeof(pad.id));
189     tmp16.copy(pad.id, arraysize(pad.id) - 1);
190
191     if (mapper) {
192       std::string mapping = "standard";
193       base::TruncateUTF8ToByteSize(
194           mapping, WebGamepad::mappingLengthCap - 1, &mapping);
195       tmp16 = base::UTF8ToUTF16(mapping);
196       memset(pad.mapping, 0, sizeof(pad.mapping));
197       tmp16.copy(pad.mapping, arraysize(pad.mapping) - 1);
198     } else {
199       pad.mapping[0] = 0;
200     }
201
202     pad.connected = true;
203   }
204 }
205
206 void GamepadPlatformDataFetcherLinux::EnumerateDevices() {
207   device::ScopedUdevEnumeratePtr enumerate(
208       udev_enumerate_new(udev_->udev_handle()));
209   if (!enumerate)
210     return;
211   int ret =
212       udev_enumerate_add_match_subsystem(enumerate.get(), kInputSubsystem);
213   if (ret != 0)
214     return;
215   ret = udev_enumerate_scan_devices(enumerate.get());
216   if (ret != 0)
217     return;
218
219   udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate.get());
220   for (udev_list_entry* dev_list_entry = devices; dev_list_entry != NULL;
221        dev_list_entry = udev_list_entry_get_next(dev_list_entry)) {
222     // Get the filename of the /sys entry for the device and create a
223     // udev_device object (dev) representing it
224     const char* path = udev_list_entry_get_name(dev_list_entry);
225     device::ScopedUdevDevicePtr dev(
226         udev_device_new_from_syspath(udev_->udev_handle(), path));
227     if (!dev)
228       continue;
229     RefreshDevice(dev.get());
230   }
231 }
232
233 void GamepadPlatformDataFetcherLinux::ReadDeviceData(size_t index) {
234   // Linker does not like CHECK_LT(index, WebGamepads::itemsLengthCap). =/
235   if (index >= WebGamepads::itemsLengthCap) {
236     CHECK(false);
237     return;
238   }
239
240   const int& fd = device_fds_[index];
241   WebGamepad& pad = data_.items[index];
242   DCHECK_GE(fd, 0);
243
244   js_event event;
245   while (HANDLE_EINTR(read(fd, &event, sizeof(struct js_event))) > 0) {
246     size_t item = event.number;
247     if (event.type & JS_EVENT_AXIS) {
248       if (item >= WebGamepad::axesLengthCap)
249         continue;
250       pad.axes[item] = event.value / kMaxLinuxAxisValue;
251       if (item >= pad.axesLength)
252         pad.axesLength = item + 1;
253     } else if (event.type & JS_EVENT_BUTTON) {
254       if (item >= WebGamepad::buttonsLengthCap)
255         continue;
256       pad.buttons[item].pressed = event.value;
257       pad.buttons[item].value = event.value ? 1.0 : 0.0;
258       if (item >= pad.buttonsLength)
259         pad.buttonsLength = item + 1;
260     }
261     pad.timestamp = event.time;
262   }
263 }
264
265 }  // namespace content