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