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