~tatokis/unity/gcc-72-errors

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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/*
 * Copyright (C) 2014 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Marco Trevisan <marco.trevisan@canonical.com>
 */

#include "InputMonitor.h"
#include "SigcSlotHash.h"

#include <Nux/Nux.h>
#include <NuxCore/Logger.h>
#include <X11/extensions/XInput2.h>
#include <UnityCore/GLibSource.h>
#include <unordered_set>
#include <gdk/gdkx.h>
#include <glib.h>

namespace unity
{
namespace input
{
namespace
{
DECLARE_LOGGER(logger, "unity.input.monitor");

Monitor* instance_ = nullptr;

const unsigned XINPUT_MAJOR_VERSION = 2;
const unsigned XINPUT_MINOR_VERSION = 3;

bool operator&(Events l, Events r)
{
  typedef std::underlying_type<Events>::type ut;
  return static_cast<ut>(static_cast<ut>(l) & static_cast<ut>(r));
}

Events& operator|=(Events& l, Events r)
{
  typedef std::underlying_type<Events>::type ut;
  return l = static_cast<Events>(static_cast<ut>(l) | static_cast<ut>(r));
}

template <typename EVENT>
void initialize_event_common(EVENT* ev, XIDeviceEvent* xiev)
{
  ev->serial = xiev->serial;
  ev->send_event = xiev->send_event;
  ev->display = xiev->display;
  ev->window = xiev->event;
  ev->root = xiev->root;
  ev->subwindow = xiev->child;
  ev->time = xiev->time;
  ev->x = std::round(xiev->event_x);
  ev->y = std::round(xiev->event_y);
  ev->x_root = std::round(xiev->root_x);
  ev->y_root = std::round(xiev->root_y);
  ev->state = xiev->mods.effective;
  ev->same_screen = True;
}

template <typename EVENT_TYPE, typename NATIVE_TYPE>
void initialize_event(XEvent* ev, NATIVE_TYPE* xiev);

template <>
void initialize_event<XButtonEvent>(XEvent* ev, XIDeviceEvent* xiev)
{
  XButtonEvent* bev = &ev->xbutton;
  ev->type = (xiev->evtype == XI_ButtonPress) ? ButtonPress : ButtonRelease;
  initialize_event_common(bev, xiev);
  bev->button = xiev->detail;
}

template <>
void initialize_event<XKeyEvent>(XEvent* ev, XIDeviceEvent* xiev)
{
  XKeyEvent* kev = &ev->xkey;
  ev->type = (xiev->evtype == XI_KeyPress) ? KeyPress : KeyRelease;
  initialize_event_common(kev, xiev);
  kev->keycode = xiev->detail;
}

template <>
void initialize_event<XMotionEvent>(XEvent* ev, XIDeviceEvent* xiev)
{
  XMotionEvent* mev = &ev->xmotion;
  ev->type = MotionNotify;
  initialize_event_common(mev, xiev);
  mev->is_hint = NotifyNormal;

  for (int i = 0; i < xiev->buttons.mask_len * 8; ++i)
  {
    if (XIMaskIsSet(xiev->buttons.mask, i))
    {
      mev->is_hint = NotifyHint;
      break;
    }
  }
}

template <>
void initialize_event<XGenericEventCookie>(XEvent* ev, XIBarrierEvent* xiev)
{
  XGenericEventCookie* cev = &ev->xcookie;
  cev->type = GenericEvent;
  cev->serial = xiev->serial;
  cev->send_event = xiev->send_event;
  cev->display = xiev->display;
  cev->evtype = xiev->evtype;
  cev->data = xiev;
}
}

struct Monitor::Impl
{
#if __GNUC__ < 6
  using EventCallbackSet = std::unordered_set<EventCallback>;
#else
  using EventCallbackSet = std::unordered_set<EventCallback, std::hash<sigc::slot_base>>;
#endif

  Impl()
    : xi_opcode_(0)
    , event_filter_set_(false)
    , invoking_callbacks_(false)
  {
    Display *dpy = gdk_x11_get_default_xdisplay();
    int event_base, error_base;

    if (XQueryExtension(dpy, "XInputExtension", &xi_opcode_, &event_base, &error_base))
    {
      int maj = XINPUT_MAJOR_VERSION;
      int min = XINPUT_MINOR_VERSION;

      if (XIQueryVersion(dpy, &maj, &min) == BadRequest)
      {
        LOG_ERROR(logger) << "Need XInput version "<< maj << "." << min << ", "
                          << "impossible, to setup an InputMonitor";
      }
    }
    else
    {
      LOG_ERROR(logger) << "Missing XInput, impossible to setup an InputMonitor";
    }
  }

  ~Impl()
  {
    if (event_filter_set_)
    {
      pointer_callbacks_.clear();
      key_callbacks_.clear();
      barrier_callbacks_.clear();
      UpdateEventMonitor();
    }
  }

  bool RegisterClient(Events type, EventCallback const& cb)
  {
    bool added = false;

    if (type & Events::POINTER)
      added = pointer_callbacks_.insert(cb).second || added;

    if (type & Events::KEYS)
      added = key_callbacks_.insert(cb).second || added;

    if (type & Events::BARRIER)
      added = barrier_callbacks_.insert(cb).second || added;

    if (added)
      UpdateEventMonitor();

    return added;
  }

  bool UnregisterClient(EventCallback const& cb)
  {
    if (invoking_callbacks_)
    {
      // Delay the event removal if we're currently invoking a callback
      // not to break the callbacks loop
      removal_queue_.insert(cb);
      return false;
    }

    bool removed = false;
    removed = pointer_callbacks_.erase(cb) > 0 || removed;
    removed = key_callbacks_.erase(cb) > 0 || removed;
    removed = barrier_callbacks_.erase(cb) > 0 || removed;

    if (removed)
      UpdateEventMonitor();

    return removed;
  }

  Events RegisteredEvents(EventCallback const& cb) const
  {
    Events events = Events::NONE;

    if (pointer_callbacks_.find(cb) != end(pointer_callbacks_))
      events |= Events::POINTER;

    if (key_callbacks_.find(cb) != end(key_callbacks_))
      events |= Events::KEYS;

    if (barrier_callbacks_.find(cb) != end(barrier_callbacks_))
      events |= Events::BARRIER;

    return events;
  }

  void UpdateEventMonitor()
  {
    auto* nux_dpy = nux::GetGraphicsDisplay();
    auto* dpy = nux_dpy ? nux_dpy->GetX11Display() : gdk_x11_get_default_xdisplay();
    Window root = DefaultRootWindow(dpy);

    unsigned char master_dev_bits[XIMaskLen(XI_LASTEVENT)] = { 0 };
    XIEventMask master_dev = { XIAllMasterDevices, sizeof(master_dev_bits), master_dev_bits };

    if (!barrier_callbacks_.empty())
    {
      XISetMask(master_dev.mask, XI_BarrierHit);
      XISetMask(master_dev.mask, XI_BarrierLeave);
    }

    unsigned char all_devs_bits[XIMaskLen(XI_LASTEVENT)] = { 0 };
    XIEventMask all_devs = { XIAllDevices, sizeof(all_devs_bits), all_devs_bits };

    if (!pointer_callbacks_.empty())
    {
      XISetMask(all_devs.mask, XI_Motion);
      XISetMask(all_devs.mask, XI_ButtonPress);
      XISetMask(all_devs.mask, XI_ButtonRelease);
    }

    if (!key_callbacks_.empty())
    {
      XISetMask(all_devs.mask, XI_KeyPress);
      XISetMask(all_devs.mask, XI_KeyRelease);
    }

    XIEventMask selected[] = {master_dev, all_devs};
    XISelectEvents(dpy, root, selected, G_N_ELEMENTS(selected));
    XSync(dpy, False);

    LOG_DEBUG(logger) << "Pointer clients: " << pointer_callbacks_.size() << ", "
                      << "Key clients: " << key_callbacks_.size() << ", "
                      << "Barrier clients: " << barrier_callbacks_.size();

    if (!pointer_callbacks_.empty() || !key_callbacks_.empty() || !barrier_callbacks_.empty())
    {
      if (!event_filter_set_ && nux_dpy)
      {
        nux_dpy->AddEventFilter({[] (XEvent event, void* data) {
          return static_cast<Impl*>(data)->HandleEvent(event);
        }, this});

        event_filter_set_ = true;
        LOG_DEBUG(logger) << "Event filter enabled";
      }
    }
    else if (event_filter_set_)
    {
      if (nux_dpy)
        nux_dpy->RemoveEventFilter(this);

      event_filter_set_ = false;
      LOG_DEBUG(logger) << "Event filter disabled";
    }
  }

  bool HandleEvent(XEvent& event)
  {
    bool handled = false;

    if (event.type != GenericEvent || event.xcookie.extension != xi_opcode_)
      return handled;

    switch (event.xcookie.evtype)
    {
      case XI_ButtonPress:
      case XI_ButtonRelease:
        handled = InvokeCallbacks<XButtonEvent>(pointer_callbacks_, event);
        break;
      case XI_Motion:
        handled = InvokeCallbacks<XMotionEvent>(pointer_callbacks_, event);
        break;
      case XI_KeyPress:
      case XI_KeyRelease:
        handled = InvokeCallbacks<XKeyEvent>(key_callbacks_, event);
        break;
      case XI_BarrierHit:
      case XI_BarrierLeave:
        handled = InvokeCallbacks<XGenericEventCookie, XIBarrierEvent>(barrier_callbacks_, event);
        break;
    }

    return handled;
  }

  template <typename EVENT_TYPE, typename NATIVE_TYPE = XIDeviceEvent>
  bool InvokeCallbacks(EventCallbackSet& callbacks, XEvent& xiev)
  {
    XGenericEventCookie *cookie = &xiev.xcookie;

    if (!XGetEventData(xiev.xany.display, cookie))
      return false;

    XEvent event;
    initialize_event<EVENT_TYPE>(&event, reinterpret_cast<NATIVE_TYPE*>(cookie->data));
    invoking_callbacks_ = true;

    for (auto it = callbacks.begin(); it != callbacks.end();)
    {
      if (it->empty())
      {
        it = callbacks.erase(it);
        continue;
      }

      (*it)(event);
      ++it;
    }

    XFreeEventData(xiev.xany.display, cookie);
    invoking_callbacks_ = false;

    // A callback might unregister itself on the event callback, causing the
    // above callbacks loop to crash, so in this case we save the event in the
    // removal queue and eventually we unregistered these callbacks.
    bool update_event_monitor = false;
    for (auto it = removal_queue_.begin(); it != removal_queue_.end(); it = removal_queue_.erase(it))
    {
      auto const& cb = *it;
      pointer_callbacks_.erase(cb);
      key_callbacks_.erase(cb);
      barrier_callbacks_.erase(cb);
      update_event_monitor = true;
    }

    if (callbacks.empty() || update_event_monitor)
    {
      idle_removal_.reset(new glib::Idle([this] {
        UpdateEventMonitor();
        return false;
      }));

      return false;
    }

    return true;
  }

  int xi_opcode_;
  bool event_filter_set_;
  bool invoking_callbacks_;
  glib::Source::UniquePtr idle_removal_;
  EventCallbackSet pointer_callbacks_;
  EventCallbackSet key_callbacks_;
  EventCallbackSet barrier_callbacks_;
  EventCallbackSet removal_queue_;
};

Monitor::Monitor()
{
  if (instance_)
  {
    LOG_WARN(logger) << "More than one input::Monitor created.";
    return;
  }

  instance_ = this;
  impl_.reset(new Impl());
}

Monitor::~Monitor()
{
  if (this == instance_)
    instance_ = nullptr;
}

Monitor& Monitor::Get()
{
  if (!instance_)
  {
    LOG_ERROR(logger) << "No input::Monitor created yet.";
  }

  return *instance_;
}

bool Monitor::RegisterClient(Events events, EventCallback const& cb)
{
  return impl_->RegisterClient(events, cb);
}

bool Monitor::UnregisterClient(EventCallback const& cb)
{
  return impl_->UnregisterClient(cb);
}

Events Monitor::RegisteredEvents(EventCallback const& cb) const
{
  return impl_->RegisteredEvents(cb);
}

} // input namespace
} // unity namespace