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 "ui/base/touch/touch_factory_x11.h"
6
7#include <X11/cursorfont.h>
8#include <X11/extensions/XInput.h>
9#include <X11/extensions/XInput2.h>
10#include <X11/extensions/XIproto.h>
11
12#include "base/basictypes.h"
13#include "base/command_line.h"
14#include "base/compiler_specific.h"
15#include "base/logging.h"
16#include "base/memory/singleton.h"
17#include "base/message_loop/message_loop.h"
18#include "base/strings/string_number_conversions.h"
19#include "base/strings/string_split.h"
20#include "ui/base/ui_base_switches.h"
21#include "ui/base/x/device_list_cache_x.h"
22#include "ui/base/x/x11_util.h"
23
24namespace ui {
25
26TouchFactory::TouchFactory()
27    : pointer_device_lookup_(),
28      touch_device_available_(false),
29      touch_events_disabled_(false),
30      touch_device_list_(),
31#if defined(USE_XI2_MT)
32      min_available_slot_(0),
33#endif
34      slots_used_() {
35#if defined(USE_AURA)
36  if (!base::MessagePumpForUI::HasXInput2())
37    return;
38#endif
39
40  Display* display = GetXDisplay();
41  UpdateDeviceList(display);
42
43  CommandLine* cmdline = CommandLine::ForCurrentProcess();
44  touch_events_disabled_ = cmdline->HasSwitch(switches::kTouchEvents) &&
45      cmdline->GetSwitchValueASCII(switches::kTouchEvents) ==
46          switches::kTouchEventsDisabled;
47}
48
49TouchFactory::~TouchFactory() {
50}
51
52// static
53TouchFactory* TouchFactory::GetInstance() {
54  return Singleton<TouchFactory>::get();
55}
56
57// static
58void TouchFactory::SetTouchDeviceListFromCommandLine() {
59#if defined(TOOLKIT_VIEWS)
60  // Get a list of pointer-devices that should be treated as touch-devices.
61  // This is primarily used for testing/debugging touch-event processing when a
62  // touch-device isn't available.
63  std::string touch_devices =
64      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
65          switches::kTouchDevices);
66
67  if (!touch_devices.empty()) {
68    std::vector<std::string> devs;
69    std::vector<unsigned int> device_ids;
70    unsigned int devid;
71    base::SplitString(touch_devices, ',', &devs);
72    for (std::vector<std::string>::iterator iter = devs.begin();
73        iter != devs.end(); ++iter) {
74      if (base::StringToInt(*iter, reinterpret_cast<int*>(&devid)))
75        device_ids.push_back(devid);
76      else
77        DLOG(WARNING) << "Invalid touch-device id: " << *iter;
78    }
79    ui::TouchFactory::GetInstance()->SetTouchDeviceList(device_ids);
80  }
81#endif
82}
83
84void TouchFactory::UpdateDeviceList(Display* display) {
85  // Detect touch devices.
86  touch_device_available_ = false;
87  touch_device_lookup_.reset();
88  touch_device_list_.clear();
89
90#if !defined(USE_XI2_MT)
91  // NOTE: The new API for retrieving the list of devices (XIQueryDevice) does
92  // not provide enough information to detect a touch device. As a result, the
93  // old version of query function (XListInputDevices) is used instead.
94  // If XInput2 is not supported, this will return null (with count of -1) so
95  // we assume there cannot be any touch devices.
96  // With XI2.1 or older, we allow only single touch devices.
97  XDeviceList dev_list =
98      DeviceListCacheX::GetInstance()->GetXDeviceList(display);
99  for (int i = 0; i < dev_list.count; i++) {
100    if (dev_list[i].type) {
101      XScopedString devtype(XGetAtomName(display, dev_list[i].type));
102      if (devtype.string() && !strcmp(devtype.string(), XI_TOUCHSCREEN)) {
103        touch_device_lookup_[dev_list[i].id] = true;
104        touch_device_list_[dev_list[i].id] = false;
105        touch_device_available_ = true;
106      }
107    }
108  }
109#endif
110
111  // Instead of asking X for the list of devices all the time, let's maintain a
112  // list of pointer devices we care about.
113  // It should not be necessary to select for slave devices. XInput2 provides
114  // enough information to the event callback to decide which slave device
115  // triggered the event, thus decide whether the 'pointer event' is a
116  // 'mouse event' or a 'touch event'.
117  // However, on some desktops, some events from a master pointer are
118  // not delivered to the client. So we select for slave devices instead.
119  // If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
120  // is possible), then the device is detected as a floating device, and a
121  // floating device is not connected to a master device. So it is necessary to
122  // also select on the floating devices.
123  pointer_device_lookup_.reset();
124  XIDeviceList xi_dev_list =
125      DeviceListCacheX::GetInstance()->GetXI2DeviceList(display);
126  for (int i = 0; i < xi_dev_list.count; i++) {
127    XIDeviceInfo* devinfo = xi_dev_list.devices + i;
128    if (devinfo->use == XIFloatingSlave || devinfo->use == XIMasterPointer) {
129#if defined(USE_XI2_MT)
130      for (int k = 0; k < devinfo->num_classes; ++k) {
131        XIAnyClassInfo* xiclassinfo = devinfo->classes[k];
132        if (xiclassinfo->type == XITouchClass) {
133          XITouchClassInfo* tci =
134              reinterpret_cast<XITouchClassInfo *>(xiclassinfo);
135          // Only care direct touch device (such as touch screen) right now
136          if (tci->mode == XIDirectTouch) {
137            touch_device_lookup_[devinfo->deviceid] = true;
138            touch_device_list_[devinfo->deviceid] = true;
139            touch_device_available_ = true;
140          }
141        }
142      }
143#endif
144      pointer_device_lookup_[devinfo->deviceid] = true;
145    }
146  }
147}
148
149bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) {
150  DCHECK_EQ(GenericEvent, xev->type);
151  XIEvent* event = static_cast<XIEvent*>(xev->xcookie.data);
152  XIDeviceEvent* xiev = reinterpret_cast<XIDeviceEvent*>(event);
153
154#if defined(USE_XI2_MT)
155  if (event->evtype == XI_TouchBegin ||
156      event->evtype == XI_TouchUpdate ||
157      event->evtype == XI_TouchEnd) {
158    return !touch_events_disabled_ && IsTouchDevice(xiev->deviceid);
159  }
160#endif
161  if (event->evtype != XI_ButtonPress &&
162      event->evtype != XI_ButtonRelease &&
163      event->evtype != XI_Motion)
164    return true;
165
166  if (!pointer_device_lookup_[xiev->deviceid])
167    return false;
168
169  return IsTouchDevice(xiev->deviceid) ? !touch_events_disabled_ : true;
170}
171
172void TouchFactory::SetupXI2ForXWindow(Window window) {
173  // Setup mask for mouse events. It is possible that a device is loaded/plugged
174  // in after we have setup XInput2 on a window. In such cases, we need to
175  // either resetup XInput2 for the window, so that we get events from the new
176  // device, or we need to listen to events from all devices, and then filter
177  // the events from uninteresting devices. We do the latter because that's
178  // simpler.
179
180  Display* display = ui::GetXDisplay();
181
182  unsigned char mask[XIMaskLen(XI_LASTEVENT)];
183  memset(mask, 0, sizeof(mask));
184
185#if defined(USE_XI2_MT)
186  XISetMask(mask, XI_TouchBegin);
187  XISetMask(mask, XI_TouchUpdate);
188  XISetMask(mask, XI_TouchEnd);
189#endif
190  XISetMask(mask, XI_ButtonPress);
191  XISetMask(mask, XI_ButtonRelease);
192  XISetMask(mask, XI_Motion);
193
194  XIEventMask evmask;
195  evmask.deviceid = XIAllDevices;
196  evmask.mask_len = sizeof(mask);
197  evmask.mask = mask;
198  XISelectEvents(display, window, &evmask, 1);
199  XFlush(display);
200}
201
202void TouchFactory::SetTouchDeviceList(
203    const std::vector<unsigned int>& devices) {
204  touch_device_lookup_.reset();
205  touch_device_list_.clear();
206  for (std::vector<unsigned int>::const_iterator iter = devices.begin();
207       iter != devices.end(); ++iter) {
208    DCHECK(*iter < touch_device_lookup_.size());
209    touch_device_lookup_[*iter] = true;
210    touch_device_list_[*iter] = false;
211  }
212}
213
214bool TouchFactory::IsTouchDevice(unsigned deviceid) const {
215  return deviceid < touch_device_lookup_.size() ?
216      touch_device_lookup_[deviceid] : false;
217}
218
219bool TouchFactory::IsMultiTouchDevice(unsigned int deviceid) const {
220  return (deviceid < touch_device_lookup_.size() &&
221          touch_device_lookup_[deviceid]) ?
222          touch_device_list_.find(deviceid)->second :
223          false;
224}
225
226#if defined(USE_XI2_MT)
227bool TouchFactory::QuerySlotForTrackingID(uint32 tracking_id, int* slot) {
228  TrackingIdMap::iterator itr = tracking_id_map_.find(tracking_id);
229  if (itr != tracking_id_map_.end()) {
230    *slot = itr->second;
231    return true;
232  }
233  return false;
234}
235
236int TouchFactory::GetSlotForTrackingID(uint32 tracking_id) {
237  TrackingIdMap::iterator itr = tracking_id_map_.find(tracking_id);
238  if (itr != tracking_id_map_.end())
239    return itr->second;
240
241  int slot = min_available_slot_;
242  if (slot == kMaxTouchPoints) {
243    LOG(ERROR) << "Could not find available slot for touch point";
244    return 0;
245  }
246  SetSlotUsed(slot, true);
247  tracking_id_map_.insert(std::make_pair(tracking_id, slot));
248
249  // Updates the minium available slot ID
250  while (++min_available_slot_ < kMaxTouchPoints &&
251         IsSlotUsed(min_available_slot_))
252    continue;
253
254  return slot;
255}
256
257void TouchFactory::ReleaseSlotForTrackingID(uint32 tracking_id) {
258  TrackingIdMap::iterator itr = tracking_id_map_.find(tracking_id);
259  if (itr != tracking_id_map_.end()) {
260    int slot = itr->second;
261    SetSlotUsed(slot, false);
262    tracking_id_map_.erase(itr);
263    if (slot < min_available_slot_)
264      min_available_slot_ = slot;
265  } else {
266    NOTREACHED() << "Cannot find slot mapping to tracking ID " << tracking_id;
267  }
268}
269#endif
270
271bool TouchFactory::IsSlotUsed(int slot) const {
272  CHECK_LT(slot, kMaxTouchPoints);
273  return slots_used_[slot];
274}
275
276void TouchFactory::SetSlotUsed(int slot, bool used) {
277  CHECK_LT(slot, kMaxTouchPoints);
278  slots_used_[slot] = used;
279}
280
281bool TouchFactory::IsTouchDevicePresent() {
282  return !touch_events_disabled_ && touch_device_available_;
283}
284
285void TouchFactory::SetTouchDeviceForTest(
286    const std::vector<unsigned int>& devices) {
287  touch_device_lookup_.reset();
288  touch_device_list_.clear();
289  for (std::vector<unsigned int>::const_iterator iter = devices.begin();
290       iter != devices.end(); ++iter) {
291    DCHECK(*iter < touch_device_lookup_.size());
292    touch_device_lookup_[*iter] = true;
293    touch_device_list_[*iter] = true;
294  }
295  touch_device_available_ = true;
296  touch_events_disabled_ = false;
297}
298
299}  // namespace ui
300