~azzar1/unity/fix-crash-acc-controller

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
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/*
 * Copyright (C) 2013-2015 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: William Hua <william.hua@canonical.com>
 *              Marco Trevisan <marco.trevisan@canonical.com>
 */

#include "GnomeKeyGrabberImpl.h"

#include <NuxCore/Logger.h>

namespace unity
{
namespace key
{
DECLARE_LOGGER(logger, "unity.key.gnome.grabber");

// Private implementation
namespace shell
{
std::string const DBUS_NAME = "org.gnome.Shell";
std::string const DBUS_INTERFACE = "org.gnome.Shell";
std::string const DBUS_OBJECT_PATH = "/org/gnome/Shell";
std::string const INTROSPECTION_XML =
R"(<node>
  <interface name='org.gnome.Shell'>
    <method name='GrabAccelerators'>
      <arg type='a(su)' direction='in' name='accelerators'/>
      <arg type='au' direction='out' name='actions'/>
    </method>
    <method name='GrabAccelerator'>
      <arg type='s' direction='in' name='accelerator'/>
      <arg type='u' direction='in' name='flags'/>
      <arg type='u' direction='out' name='action'/>
    </method>
    <method name='UngrabAccelerator'>
      <arg type='u' direction='in' name='action'/>
      <arg type='b' direction='out' name='success'/>
    </method>
    <signal name='AcceleratorActivated'>
      <arg type='u' name='action'/>
      <arg type='u' name='device'/>
      <arg type='u' name='timestamp'/>
    </signal>
  </interface>
</node>)";
}

namespace
{
const std::string SETTINGS_NAME = "com.canonical.Unity";
const std::string WHITELIST_KEY = "whitelist-repeated-keys";
}

namespace testing
{
std::string const DBUS_NAME = "com.canonical.Unity.Test.GnomeKeyGrabber";
}

GnomeGrabber::Impl::Impl(Grabber* parent, bool test_mode)
  : parent_(parent)
  , screen_(screen)
  , shell_server_(test_mode ? testing::DBUS_NAME : shell::DBUS_NAME)
  , settings_(g_settings_new(SETTINGS_NAME.c_str()))
  , current_action_id_(0)
{
  shell_server_.AddObjects(shell::INTROSPECTION_XML, shell::DBUS_OBJECT_PATH);
  shell_object_ = shell_server_.GetObject(shell::DBUS_INTERFACE);
  shell_object_->SetMethodsCallsHandlerFull(sigc::mem_fun(this, &Impl::OnShellMethodCall));

  whitelist_changed_signal_.Connect(settings_, "changed::" + WHITELIST_KEY, [this] (GSettings*, gchar*) {
    UpdateWhitelist();
  });

  UpdateWhitelist();
}

GnomeGrabber::Impl::~Impl()
{
  for (auto& action : actions_)
    screen_->removeAction(&action);
}

uint32_t GnomeGrabber::Impl::NextActionID()
{
  return ++current_action_id_;
}

bool GnomeGrabber::Impl::AddAction(CompAction const& action, uint32_t& action_id)
{
  LOG_DEBUG(logger) << "AddAction (\"" << action.keyToString() << "\") = " << action_id;

  if (action.key().toString().empty())
  {
    LOG_WARN(logger) << "Trying to grab a disabled action, we skip it";
    return false;
  }

  auto it = std::find(actions_.begin(), actions_.end(), action);
  if (it != actions_.end())
  {
    auto action_index = it - actions_.begin();
    action_id = actions_ids_[action_index];
    ++actions_customers_[action_index];
    LOG_DEBUG(logger) << "Key binding \"" << action.keyToString() << "\" is already grabbed, reusing id " << action_id;
    return true;
  }

  if (screen_->addAction(const_cast<CompAction*>(&action)))
  {
    actions_ids_.push_back(action_id);
    actions_.push_back(action);
    actions_customers_.push_back(1);
    parent_->action_added.emit(action);
    return true;
  }

  LOG_ERROR(logger) << "Impossible to grab action \"" << action.keyToString() << "\"";
  return false;
}

uint32_t GnomeGrabber::Impl::AddAction(CompAction const& action)
{
  auto action_id = NextActionID();
  return AddAction(action, action_id) ? action_id : 0;
}

bool GnomeGrabber::Impl::RemoveAction(CompAction const& action)
{
  auto it = std::find(actions_.begin(), actions_.end(), action);

  if (it != actions_.end())
    return RemoveActionByIndex(it - actions_.begin());

  return false;
}

bool GnomeGrabber::Impl::RemoveActionByID(uint32_t action_id)
{
  if (!action_id)
    return false;

  auto it = std::find(actions_ids_.begin(), actions_ids_.end(), action_id);

  if (it != actions_ids_.end())
    return RemoveActionByIndex(it - actions_ids_.begin());

  return false;
}

bool GnomeGrabber::Impl::RemoveActionByIndex(size_t index)
{
  if (!index || index >= actions_.size())
    return false;

  if (actions_customers_[index] > 1)
  {
    LOG_DEBUG(logger) << "Not removing action " << actions_[index].keyToString()
                      << " as it is used by multiple customers ("
                      << actions_customers_[index] << ")";

    --actions_customers_[index];
    return false;
  }

  CompAction* action = &(actions_[index]);
  LOG_DEBUG(logger) << "RemoveAction (\"" << action->keyToString() << "\")";

  screen_->removeAction(action);
  parent_->action_removed.emit(*action);
  actions_.erase(actions_.begin() + index);
  actions_ids_.erase(actions_ids_.begin() + index);
  actions_customers_.erase(actions_customers_.begin() + index);

  return true;
}

GVariant* GnomeGrabber::Impl::OnShellMethodCall(std::string const& method, GVariant* parameters, std::string const& sender, std::string const&)
{
  LOG_DEBUG(logger) << "Called method '" << method << "'";

  if (method == "GrabAccelerators")
  {
    GVariant* variant;
    GVariantBuilder builder;
    GVariantIter* iterator;
    gchar const* accelerator;
    guint flags;

    g_variant_builder_init(&builder, G_VARIANT_TYPE("au"));
    g_variant_get(parameters, "(a(su))", &iterator);

    while (g_variant_iter_next(iterator, "(&su)", &accelerator, &flags))
      g_variant_builder_add(&builder, "u", GrabDBusAccelerator(sender, accelerator, flags));

    g_variant_iter_free(iterator);
    variant = g_variant_builder_end(&builder);
    return g_variant_new_tuple(&variant, 1);
  }
  else if (method == "GrabAccelerator")
  {
    gchar const* accelerator;
    guint flags;
    g_variant_get(parameters, "(&su)", &accelerator, &flags);

    if (uint32_t action_id = GrabDBusAccelerator(sender, accelerator, flags))
      return g_variant_new("(u)", action_id);
  }
  else if (method == "UngrabAccelerator")
  {
    uint32_t action_id;
    g_variant_get(parameters, "(u)", &action_id);
    return g_variant_new("(b)", UnGrabDBusAccelerator(sender, action_id));
  }

  return nullptr;
}

uint32_t GnomeGrabber::Impl::GrabDBusAccelerator(std::string const& owner, std::string const& accelerator, uint32_t flags)
{
  CompAction action;
  action.keyFromString(accelerator);
  uint32_t action_id = NextActionID();

  LOG_DEBUG(logger) << "GrabDBusAccelerator \"" << accelerator << "\"";

  if (action.key().toString().empty())
  {
    auto prefixed = "XF86" + accelerator;
    LOG_DEBUG(logger) << "Can't grab \"" << accelerator << "\", trying \"" << prefixed << "\"";
    action.keyFromString(prefixed);
  }

  if (!IsActionPostponed(action))
  {
    action.setState(CompAction::StateInitKey);
    action.setInitiate([this, action_id](CompAction* action, CompAction::State state, CompOption::Vector& options) {
      bool is_whitelisted = std::find(whitelist_.begin(), whitelist_.end(), action->keyToString()) != whitelist_.end();
      if (is_whitelisted || !CompOption::getBoolOptionNamed(options, "is_repeated"))
      {
        LOG_DEBUG(logger) << "pressed \"" << action->keyToString() << "\"";
        ActivateDBusAction(*action, action_id, 0, CompOption::getIntOptionNamed(options, "time"));
      }
      return true;
    });
  }
  else
  {
    action.setState(CompAction::StateInitKey | CompAction::StateTermKey);
    action.setTerminate([this, action_id](CompAction* action, CompAction::State state, CompOption::Vector& options) {
      auto key = action->keyToString();
      LOG_DEBUG(logger) << "released \"" << key << "\"";

      if (state & CompAction::StateTermTapped)
      {
        LOG_DEBUG(logger) << "tapped \"" << key << "\"";
        ActivateDBusAction(*action, action_id, 0, CompOption::getIntOptionNamed(options, "time"));
        return true;
      }

      return false;
    });
  }

  if (AddAction(action, action_id))
  {
    auto& owner_actions = actions_by_owner_[owner];
    bool first_insertion = owner_actions.actions.empty();
    owner_actions.actions.insert(action_id);

    if (first_insertion)
    {
      LOG_DEBUG(logger) << "Initialize dbus watcher for owner '" << owner << "'";
      owner_actions.watcher = std::make_shared<glib::DBusNameWatcher>(owner);
      owner_actions.watcher->vanished.connect([this] (std::string const& name) {
        LOG_DEBUG(logger) << "Signal destination vanished '" << name << "', removing related actions";
        auto it = actions_by_owner_.find(name);
        if (it != actions_by_owner_.end())
        {
          for (auto action_id : it->second.actions)
            RemoveActionByID(action_id);

          actions_by_owner_.erase(it);
        }
      });
    }

    return action_id;
  }

  return 0;
}

bool GnomeGrabber::Impl::UnGrabDBusAccelerator(std::string const& owner, uint32_t action_id)
{
  LOG_DEBUG(logger) << "UnGrabDBusAccelerator \"" << action_id << "\"";

  auto it = actions_by_owner_.find(owner);
  if (it != actions_by_owner_.end())
  {
    auto& actions = it->second.actions;
    actions.erase(action_id);

    if (actions.empty())
      actions_by_owner_.erase(it);

    return RemoveActionByID(action_id);
  }

  LOG_WARN(logger) << "Action " << action_id << " was not registered by " << owner << ". "
                   << "Unregistration denied";
  return false;
}

void GnomeGrabber::Impl::ActivateDBusAction(CompAction const& action, uint32_t action_id, uint32_t device, uint32_t timestamp) const
{
  LOG_DEBUG(logger) << "ActivateAction (" << action_id << " \"" << action.keyToString() << "\")";

  for (auto const& pair : actions_by_owner_)
  {
    if (pair.second.actions.find(action_id) != pair.second.actions.end())
      shell_object_->EmitSignal("AcceleratorActivated", g_variant_new("(uuu)", action_id, device, timestamp), pair.first);
  }
}

bool GnomeGrabber::Impl::IsActionPostponed(CompAction const& action) const
{
  int keycode = action.key().keycode();
  return keycode == 0 || modHandler->keycodeToModifiers(keycode) != 0;
}

void GnomeGrabber::Impl::UpdateWhitelist()
{
  std::shared_ptr<gchar*> whitelist(g_settings_get_strv(settings_, WHITELIST_KEY.c_str()), g_strfreev);
  auto whitelist_raw = whitelist.get();

  whitelist_.clear();
  for (int i = 0; whitelist_raw[i]; ++i)
    whitelist_.push_back(whitelist_raw[i]);
}

// Public implementation

GnomeGrabber::GnomeGrabber()
  : impl_(new Impl(this))
{}

GnomeGrabber::GnomeGrabber(TestMode const& dummy)
  : impl_(new Impl(this, true))
{}

GnomeGrabber::~GnomeGrabber()
{}

CompAction::Vector& GnomeGrabber::GetActions()
{
  return impl_->actions_;
}

uint32_t GnomeGrabber::AddAction(CompAction const& action)
{
  return impl_->AddAction(action);
}

bool GnomeGrabber::RemoveAction(CompAction const& action)
{
  return impl_->RemoveAction(action);
}

bool GnomeGrabber::RemoveAction(uint32_t action_id)
{
  return impl_->RemoveActionByID(action_id);
}

} // namespace key
} // namespace unity