summaryrefslogtreecommitdiff
path: root/chromium/ui/events/devices/x11/touch_factory_x11.cc
blob: c667095966428fcb67bebf4b26a26d7fb1b58c5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/events/devices/x11/touch_factory_x11.h"

#include <stddef.h>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/system/sys_info.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/devices/x11/device_data_manager_x11.h"
#include "ui/events/devices/x11/device_list_cache_x11.h"
#include "ui/events/devices/x11/xinput_util.h"
#include "ui/events/event_switches.h"
#include "ui/gfx/x/connection.h"
#include "ui/gfx/x/future.h"

namespace ui {
namespace {

void AddPointerDevicesFromString(
    const std::string& pointer_devices,
    EventPointerType type,
    std::vector<std::pair<int, EventPointerType>>* devices) {
  for (const base::StringPiece& dev : base::SplitStringPiece(
           pointer_devices, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
    int devid;
    if (base::StringToInt(dev, &devid))
      devices->push_back({devid, type});
    else
      DLOG(WARNING) << "Invalid device id: " << dev.as_string();
  }
}

}  // namespace

TouchFactory::TouchFactory()
    : pointer_device_lookup_(),
      touch_device_list_(),
      id_generator_(0),
      touch_screens_enabled_(true) {
  // Ensure device data manager is properly initialized.
  DeviceDataManagerX11::CreateInstance();

  if (!DeviceDataManagerX11::GetInstance()->IsXInput2Available())
    return;

  UpdateDeviceList(x11::Connection::Get());
}

TouchFactory::~TouchFactory() = default;

// static
TouchFactory* TouchFactory::GetInstance() {
  return base::Singleton<TouchFactory>::get();
}

// static
void TouchFactory::SetTouchDeviceListFromCommandLine() {
  // Get a list of pointer-devices that should be treated as touch-devices.
  // This is primarily used for testing/debugging touch-event processing when a
  // touch-device isn't available.
  std::vector<std::pair<int, EventPointerType>> devices;
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  AddPointerDevicesFromString(
      command_line->GetSwitchValueASCII(switches::kTouchDevices),
      EventPointerType::kTouch, &devices);
  AddPointerDevicesFromString(
      command_line->GetSwitchValueASCII(switches::kPenDevices),
      EventPointerType::kPen, &devices);
  if (!devices.empty())
    ui::TouchFactory::GetInstance()->SetTouchDeviceList(devices);
}

void TouchFactory::UpdateDeviceList(x11::Connection* connection) {
  // Detect touch devices.
  touch_device_lookup_.reset();
  touch_device_list_.clear();
  touchscreen_ids_.clear();

  if (!DeviceDataManagerX11::GetInstance()->IsXInput2Available())
    return;

  // Instead of asking X for the list of devices all the time, let's maintain a
  // list of pointer devices we care about.
  // It should not be necessary to select for slave devices. XInput2 provides
  // enough information to the event callback to decide which slave device
  // triggered the event, thus decide whether the 'pointer event' is a
  // 'mouse event' or a 'touch event'.
  // However, on some desktops, some events from a master pointer are
  // not delivered to the client. So we select for slave devices instead.
  // If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
  // is possible), then the device is detected as a floating device, and a
  // floating device is not connected to a master device. So it is necessary to
  // also select on the floating devices.
  pointer_device_lookup_.reset();
  const XIDeviceList& xi_dev_list =
      DeviceListCacheX11::GetInstance()->GetXI2DeviceList(connection);
  for (const auto& devinfo : xi_dev_list) {
    if (devinfo.type == x11::Input::DeviceType::FloatingSlave ||
        devinfo.type == x11::Input::DeviceType::MasterPointer ||
        devinfo.type == x11::Input::DeviceType::SlavePointer) {
      for (const auto& xiclassinfo : devinfo.classes) {
        if (!xiclassinfo.touch.has_value())
          continue;

        auto& tci = *xiclassinfo.touch;
        // Only care direct touch device (such as touch screen) right now
        if (tci.mode != x11::Input::TouchMode::Direct)
          continue;

        auto master_id = devinfo.type == x11::Input::DeviceType::SlavePointer
                             ? devinfo.attachment
                             : devinfo.deviceid;

        if (!IsValidDevice(static_cast<uint16_t>(master_id)))
          continue;

        touch_device_lookup_[static_cast<uint16_t>(master_id)] = true;
        touch_device_list_[master_id] = {true, EventPointerType::kTouch};

        if (devinfo.type != x11::Input::DeviceType::MasterPointer)
          CacheTouchscreenIds(devinfo.deviceid);

        if (devinfo.type == x11::Input::DeviceType::MasterPointer) {
          device_master_id_list_[devinfo.deviceid] = master_id;
          touch_device_lookup_[static_cast<uint16_t>(devinfo.deviceid)] = true;
          touch_device_list_[devinfo.deviceid] = {false,
                                                  EventPointerType::kTouch};
        }
      }
      pointer_device_lookup_[static_cast<uint16_t>(devinfo.deviceid)] =
          (devinfo.type != x11::Input::DeviceType::SlavePointer);
    } else if (devinfo.type == x11::Input::DeviceType::MasterKeyboard) {
      virtual_core_keyboard_device_ = devinfo.deviceid;
    }
  }
}

bool TouchFactory::ShouldProcessDeviceEvent(
    const x11::Input::DeviceEvent& xiev) {
  const bool is_touch_disabled = !touch_screens_enabled_;

  if (xiev.opcode == x11::Input::DeviceEvent::TouchBegin ||
      xiev.opcode == x11::Input::DeviceEvent::TouchUpdate ||
      xiev.opcode == x11::Input::DeviceEvent::TouchEnd) {
    // Since SetupXI2ForXWindow() selects events from all devices, for a
    // touchscreen attached to a master pointer device, X11 sends two
    // events for each touch: one from the slave (deviceid == the id of
    // the touchscreen device), and one from the master (deviceid == the
    // id of the master pointer device). Instead of processing both
    // events, discard the event that comes from the slave, and only
    // allow processing the event coming from the master.
    // For a 'floating' touchscreen device, X11 sends only one event for
    // each touch, with both deviceid and sourceid set to the id of the
    // touchscreen device.
    bool is_from_master_or_float = touch_device_list_[xiev.deviceid].is_master;
    bool is_from_slave_device =
        !is_from_master_or_float && xiev.sourceid == xiev.deviceid;
    return !is_touch_disabled && IsTouchDevice(xiev.deviceid) &&
           !is_from_slave_device;
  }

  // Make sure only key-events from the virtual core keyboard are processed.
  if (xiev.opcode == x11::Input::DeviceEvent::KeyPress ||
      xiev.opcode == x11::Input::DeviceEvent::KeyRelease) {
    return !virtual_core_keyboard_device_.has_value() ||
           *virtual_core_keyboard_device_ == xiev.deviceid;
  }

  return ShouldProcessEventForDevice(xiev.deviceid);
}

bool TouchFactory::ShouldProcessCrossingEvent(
    const x11::Input::CrossingEvent& xiev) {
  // Don't automatically accept x11::Input::CrossingEvent::Enter or
  // x11::Input::CrossingEvent::Leave. They should be checked against the
  // pointer_device_lookup_ to prevent handling for slave devices. This happens
  // for unknown reasons when using xtest. https://crbug.com/683434.
  if (xiev.opcode != x11::Input::CrossingEvent::Enter &&
      xiev.opcode != x11::Input::CrossingEvent::Leave) {
    return true;
  }

  return ShouldProcessEventForDevice(xiev.deviceid);
}

void TouchFactory::SetupXI2ForXWindow(x11::Window window) {
  // Setup mask for mouse events. It is possible that a device is loaded/plugged
  // in after we have setup XInput2 on a window. In such cases, we need to
  // either resetup XInput2 for the window, so that we get events from the new
  // device, or we need to listen to events from all devices, and then filter
  // the events from uninteresting devices. We do the latter because that's
  // simpler.

  auto* connection = x11::Connection::Get();

  x11::Input::EventMask mask{};
  mask.mask.push_back({});
  auto* mask_data = mask.mask.data();

  SetXinputMask(mask_data, x11::Input::CrossingEvent::Enter);
  SetXinputMask(mask_data, x11::Input::CrossingEvent::Leave);
  SetXinputMask(mask_data, x11::Input::CrossingEvent::FocusIn);
  SetXinputMask(mask_data, x11::Input::CrossingEvent::FocusOut);

  SetXinputMask(mask_data, x11::Input::DeviceEvent::TouchBegin);
  SetXinputMask(mask_data, x11::Input::DeviceEvent::TouchUpdate);
  SetXinputMask(mask_data, x11::Input::DeviceEvent::TouchEnd);

  SetXinputMask(mask_data, x11::Input::DeviceEvent::ButtonPress);
  SetXinputMask(mask_data, x11::Input::DeviceEvent::ButtonRelease);
  SetXinputMask(mask_data, x11::Input::DeviceEvent::Motion);
  // HierarchyChanged and DeviceChanged allow X11EventSource to still pick up
  // these events.
  SetXinputMask(mask_data, x11::Input::HierarchyEvent::opcode);
  SetXinputMask(mask_data, x11::Input::DeviceChangedEvent::opcode);
#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (base::SysInfo::IsRunningOnChromeOS()) {
    SetXinputMask(mask_data, x11::Input::DeviceEvent::KeyPress);
    SetXinputMask(mask_data, x11::Input::DeviceEvent::KeyRelease);
  }
#endif

  connection->xinput().XISelectEvents({window, {mask}});
  connection->Flush();
}

void TouchFactory::SetTouchDeviceList(
    const std::vector<std::pair<int, EventPointerType>>& devices) {
  touch_device_lookup_.reset();
  touch_device_list_.clear();
  for (auto& device : devices) {
    int device_int = device.first;
    auto device_id = static_cast<x11::Input::DeviceId>(device_int);
    EventPointerType type = device.second;
    DCHECK(IsValidDevice(device_int));
    touch_device_lookup_[device_int] = true;
    touch_device_list_[device_id] = {false, type};
    if (device_master_id_list_.find(device_id) !=
        device_master_id_list_.end()) {
      // When we set the device through the "--touch-devices" flag to slave
      // touch device, we also set its master device to be touch device.
      touch_device_lookup_[static_cast<uint16_t>(
          device_master_id_list_[device_id])] = true;
      touch_device_list_[device_master_id_list_[device_id]] = {false, type};
    }
  }
}

bool TouchFactory::IsValidDevice(int deviceid) const {
  return deviceid >= 0 &&
         static_cast<size_t>(deviceid) < touch_device_lookup_.size();
}

bool TouchFactory::IsTouchDevice(x11::Input::DeviceId deviceid) const {
  return IsValidDevice(static_cast<uint16_t>(deviceid)) &&
         touch_device_lookup_[static_cast<uint16_t>(deviceid)];
}

bool TouchFactory::IsMultiTouchDevice(x11::Input::DeviceId deviceid) const {
  return IsValidDevice(static_cast<uint16_t>(deviceid)) &&
         touch_device_lookup_[static_cast<uint16_t>(deviceid)] &&
         touch_device_list_.find(deviceid)->second.is_master;
}

EventPointerType TouchFactory::GetTouchDevicePointerType(
    x11::Input::DeviceId deviceid) const {
  DCHECK(IsTouchDevice(deviceid));
  return touch_device_list_.find(deviceid)->second.pointer_type;
}

bool TouchFactory::QuerySlotForTrackingID(uint32_t tracking_id, int* slot) {
  if (!id_generator_.HasGeneratedIDFor(tracking_id))
    return false;
  *slot = GetSlotForTrackingID(tracking_id);
  return true;
}

int TouchFactory::GetSlotForTrackingID(uint32_t tracking_id) {
  return id_generator_.GetGeneratedID(tracking_id);
}

void TouchFactory::ReleaseSlot(int slot) {
  id_generator_.ReleaseID(slot);
}

bool TouchFactory::IsTouchDevicePresent() {
  return touch_screens_enabled_ && touch_device_lookup_.any();
}

void TouchFactory::ResetForTest() {
  pointer_device_lookup_.reset();
  touch_device_lookup_.reset();
  touch_device_list_.clear();
  touchscreen_ids_.clear();
  id_generator_.ResetForTest();
  SetTouchscreensEnabled(true);
}

void TouchFactory::SetTouchDeviceForTest(const std::vector<int>& devices) {
  touch_device_lookup_.reset();
  touch_device_list_.clear();
  for (int device_id : devices) {
    auto device = static_cast<x11::Input::DeviceId>(device_id);
    DCHECK(IsValidDevice(device_id));
    touch_device_lookup_[device_id] = true;
    touch_device_list_[device] = {true, EventPointerType::kTouch};
  }
  SetTouchscreensEnabled(true);
}

void TouchFactory::SetPointerDeviceForTest(const std::vector<int>& devices) {
  pointer_device_lookup_.reset();
  for (int device : devices)
    pointer_device_lookup_[device] = true;
}

void TouchFactory::SetTouchscreensEnabled(bool enabled) {
  touch_screens_enabled_ = enabled;
  DeviceDataManager::GetInstance()->SetTouchscreensEnabled(enabled);
}

void TouchFactory::CacheTouchscreenIds(x11::Input::DeviceId device_id) {
  if (!DeviceDataManager::HasInstance())
    return;
  std::vector<TouchscreenDevice> touchscreens =
      DeviceDataManager::GetInstance()->GetTouchscreenDevices();
  const auto it =
      std::find_if(touchscreens.begin(), touchscreens.end(),
                   [device_id](const TouchscreenDevice& touchscreen) {
                     return touchscreen.id == static_cast<int>(device_id);
                   });
  // Internal displays will have a vid and pid of 0. Ignore them.
  if (it != touchscreens.end() && it->vendor_id && it->product_id)
    touchscreen_ids_.emplace(it->vendor_id, it->product_id);
}

bool TouchFactory::ShouldProcessEventForDevice(
    x11::Input::DeviceId device_id) const {
  if (!pointer_device_lookup_[static_cast<uint16_t>(device_id)])
    return false;

  return IsTouchDevice(device_id) ? touch_screens_enabled_ : true;
}

}  // namespace ui