game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
shortcut_manager.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// shortcut_manager.cpp
4// ==============================================================================
5// Centralized keyboard shortcut management
6// ==============================================================================
7
8#include "shortcut_manager.h"
9
10#include <QFile>
11#include <QJsonArray>
12#include <QJsonDocument>
13#include <QJsonObject>
14#include <QSettings>
15#include <algorithm>
16
17// ==============================================================================
18// Singleton Instance
19// ==============================================================================
20
26
28ShortcutManager::~ShortcutManager() = default;
29
30// ==============================================================================
31// Initialization
32// ==============================================================================
33
34void ShortcutManager::initialize(QWidget* mainWidget)
35{
36 mainWidget_ = mainWidget;
37
38 // Load saved customizations
40
41 // Create QShortcut objects for all registered actions
42 for (const auto& [id, action] : actions_)
43 {
44 createQShortcut(id);
45 }
46}
47
48// ==============================================================================
49// Registration
50// ==============================================================================
51
53{
54 if (action.id.isEmpty())
55 return false;
56
57 // Check for duplicate ID
58 if (actions_.count(action.id) > 0)
59 return false;
60
61 // Check for shortcut conflict
62 QString conflict = checkConflict(action.currentShortcut, action.id);
63 if (!conflict.isEmpty())
64 {
65 // Conflict exists - we still register but clear the shortcut
66 ShortcutAction modifiedAction = action;
67 modifiedAction.currentShortcut = QKeySequence();
68 actions_[action.id] = modifiedAction;
69 }
70 else
71 {
72 actions_[action.id] = action;
73 }
74
75 // Create QShortcut if manager is initialized
76 if (mainWidget_)
77 {
78 createQShortcut(action.id);
79 }
80
81 return true;
82}
83
84void ShortcutManager::unregisterAction(const QString& actionId)
85{
86 removeQShortcut(actionId);
87 actions_.erase(actionId);
88}
89
90bool ShortcutManager::hasAction(const QString& actionId) const
91{
92 return actions_.count(actionId) > 0;
93}
94
95const ShortcutAction* ShortcutManager::getAction(const QString& actionId) const
96{
97 auto it = actions_.find(actionId);
98 if (it != actions_.end())
99 return &it->second;
100 return nullptr;
101}
102
103std::vector<ShortcutAction> ShortcutManager::getAllActions() const
104{
105 std::vector<ShortcutAction> result;
106 result.reserve(actions_.size());
107 for (const auto& [id, action] : actions_)
108 {
109 result.push_back(action);
110 }
111 return result;
112}
113
114std::vector<ShortcutAction> ShortcutManager::getActionsByCategory(const QString& category) const
115{
116 std::vector<ShortcutAction> result;
117 for (const auto& [id, action] : actions_)
118 {
119 if (action.category == category)
120 result.push_back(action);
121 }
122 return result;
123}
124
126{
127 QStringList categories;
128 for (const auto& [id, action] : actions_)
129 {
130 if (!categories.contains(action.category))
131 categories.append(action.category);
132 }
133 categories.sort();
134 return categories;
135}
136
137// ==============================================================================
138// Customization
139// ==============================================================================
140
141bool ShortcutManager::setShortcut(const QString& actionId, const QKeySequence& shortcut)
142{
143 auto it = actions_.find(actionId);
144 if (it == actions_.end())
145 return false;
146
147 // Check for conflicts (excluding this action)
148 if (!shortcut.isEmpty())
149 {
150 QString conflict = checkConflict(shortcut, actionId);
151 if (!conflict.isEmpty())
152 return false;
153 }
154
155 it->second.currentShortcut = shortcut;
156 updateQShortcut(actionId);
157
158 emit shortcutChanged(actionId, shortcut);
159 return true;
160}
161
162void ShortcutManager::resetToDefault(const QString& actionId)
163{
164 auto it = actions_.find(actionId);
165 if (it == actions_.end())
166 return;
167
168 it->second.resetToDefault();
169 updateQShortcut(actionId);
170
171 emit shortcutChanged(actionId, it->second.currentShortcut);
172}
173
175{
176 for (auto& [id, action] : actions_)
177 {
178 action.resetToDefault();
179 updateQShortcut(id);
180 }
181
182 emit shortcutsReloaded();
183}
184
185QString ShortcutManager::checkConflict(const QKeySequence& shortcut,
186 const QString& excludeActionId) const
187{
188 if (shortcut.isEmpty())
189 return QString();
190
191 for (const auto& [id, action] : actions_)
192 {
193 if (id == excludeActionId)
194 continue;
195
196 if (action.currentShortcut == shortcut)
197 return id;
198 }
199
200 return QString();
201}
202
203// ==============================================================================
204// Enable/Disable
205// ==============================================================================
206
207void ShortcutManager::setActionEnabled(const QString& actionId, bool enabled)
208{
209 auto it = actions_.find(actionId);
210 if (it == actions_.end())
211 return;
212
213 it->second.isEnabled = enabled;
214
215 auto shortcutIt = shortcuts_.find(actionId);
216 if (shortcutIt != shortcuts_.end())
217 {
218 shortcutIt->second->setEnabled(enabled && allEnabled_);
219 }
220}
221
222void ShortcutManager::setCategoryEnabled(const QString& category, bool enabled)
223{
224 for (auto& [id, action] : actions_)
225 {
226 if (action.category == category)
227 {
228 action.isEnabled = enabled;
229
230 auto shortcutIt = shortcuts_.find(id);
231 if (shortcutIt != shortcuts_.end())
232 {
233 shortcutIt->second->setEnabled(enabled && allEnabled_);
234 }
235 }
236 }
237}
238
240{
241 allEnabled_ = enabled;
242
243 for (auto& [id, shortcut] : shortcuts_)
244 {
245 auto it = actions_.find(id);
246 if (it != actions_.end())
247 {
248 shortcut->setEnabled(enabled && it->second.isEnabled);
249 }
250 }
251}
252
253// ==============================================================================
254// Persistence
255// ==============================================================================
256
258{
259 QSettings settings;
260 settings.beginGroup("Shortcuts");
261
262 for (const auto& [id, action] : actions_)
263 {
264 if (action.isCustomized())
265 {
266 settings.setValue(id, action.currentShortcut.toString());
267 }
268 else
269 {
270 settings.remove(id); // Remove if reset to default
271 }
272 }
273
274 settings.endGroup();
275}
276
278{
279 QSettings settings;
280 settings.beginGroup("Shortcuts");
281
282 for (auto& [id, action] : actions_)
283 {
284 if (settings.contains(id))
285 {
286 QString seqStr = settings.value(id).toString();
287 QKeySequence seq(seqStr);
288 if (!seq.isEmpty())
289 {
290 action.currentShortcut = seq;
291 }
292 }
293 }
294
295 settings.endGroup();
296}
297
298bool ShortcutManager::exportToFile(const QString& filePath) const
299{
300 QJsonObject root;
301 QJsonArray actionsArray;
302
303 for (const auto& [id, action] : actions_)
304 {
305 QJsonObject obj;
306 obj["id"] = action.id;
307 obj["label"] = action.label;
308 obj["category"] = action.category;
309 obj["defaultShortcut"] = action.defaultShortcut.toString();
310 obj["currentShortcut"] = action.currentShortcut.toString();
311 obj["isCustomized"] = action.isCustomized();
312 actionsArray.append(obj);
313 }
314
315 root["shortcuts"] = actionsArray;
316 root["version"] = 1;
317
318 QFile file(filePath);
319 if (!file.open(QIODevice::WriteOnly))
320 return false;
321
322 file.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
323 return true;
324}
325
326int ShortcutManager::importFromFile(const QString& filePath)
327{
328 QFile file(filePath);
329 if (!file.open(QIODevice::ReadOnly))
330 return 0;
331
332 QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
333 if (!doc.isObject())
334 return 0;
335
336 QJsonObject root = doc.object();
337 QJsonArray actionsArray = root["shortcuts"].toArray();
338
339 int imported = 0;
340 // QJsonArray's iterator yields QJsonValueRef, not QJsonValue, so the
341 // explicit `const QJsonValue&` form forced an implicit conversion per
342 // iteration (performance-implicit-conversion-in-loop). `auto` keeps
343 // the deduced reference type.
344 for (const auto& val : actionsArray)
345 {
346 QJsonObject obj = val.toObject();
347 QString id = obj["id"].toString();
348 QString shortcutStr = obj["currentShortcut"].toString();
349
350 if (!id.isEmpty() && hasAction(id))
351 {
352 QKeySequence seq(shortcutStr);
353 if (setShortcut(id, seq))
354 {
355 imported++;
356 }
357 }
358 }
359
360 if (imported > 0)
361 {
362 emit shortcutsReloaded();
363 }
364
365 return imported;
366}
367
368// ==============================================================================
369// Utility
370// ==============================================================================
371
372QString ShortcutManager::keySequenceToString(const QKeySequence& seq)
373{
374 if (seq.isEmpty())
375 return QString();
376
377 return seq.toString(QKeySequence::NativeText);
378}
379
380bool ShortcutManager::triggerAction(const QString& actionId)
381{
382 auto it = actions_.find(actionId);
383 if (it == actions_.end())
384 return false;
385
386 const ShortcutAction& action = it->second;
387
388 if (!action.isEnabled || !allEnabled_)
389 return false;
390
391 if (action.canExecute && !action.canExecute())
392 return false;
393
394 if (action.action)
395 {
396 action.action();
397 return true;
398 }
399
400 return false;
401}
402
403// ==============================================================================
404// QShortcut Management
405// ==============================================================================
406
407void ShortcutManager::createQShortcut(const QString& actionId)
408{
409 if (!mainWidget_)
410 return;
411
412 auto it = actions_.find(actionId);
413 if (it == actions_.end())
414 return;
415
416 const ShortcutAction& action = it->second;
417
418 if (action.currentShortcut.isEmpty())
419 return;
420
421 auto shortcut =
422 std::make_unique<QShortcut>(action.currentShortcut, mainWidget_,
423 nullptr, // member function
424 nullptr, // ambiguous member
425 action.isGlobal ? Qt::ApplicationShortcut : Qt::WindowShortcut);
426
427 shortcut->setEnabled(action.isEnabled && allEnabled_);
428
429 // Connect to trigger the action
430 connect(shortcut.get(), &QShortcut::activated, this,
431 [this, actionId]() { triggerAction(actionId); });
432
433 shortcuts_[actionId] = std::move(shortcut);
434}
435
436void ShortcutManager::updateQShortcut(const QString& actionId)
437{
438 auto it = actions_.find(actionId);
439 if (it == actions_.end())
440 return;
441
442 const ShortcutAction& action = it->second;
443
444 // Remove existing shortcut
445 removeQShortcut(actionId);
446
447 // Create new one if shortcut is not empty
448 if (!action.currentShortcut.isEmpty())
449 {
450 createQShortcut(actionId);
451 }
452}
453
454void ShortcutManager::removeQShortcut(const QString& actionId)
455{
456 shortcuts_.erase(actionId);
457}
bool triggerAction(const QString &actionId)
Trigger an action by ID.
void saveCustomizations()
Save custom shortcuts to settings.
QString checkConflict(const QKeySequence &shortcut, const QString &excludeActionId=QString()) const
Check if a shortcut conflicts with existing ones.
bool registerAction(const ShortcutAction &action)
Register a new shortcut action.
bool setShortcut(const QString &actionId, const QKeySequence &shortcut)
Set a custom shortcut for an action.
ShortcutManager(const ShortcutManager &)=delete
std::vector< ShortcutAction > getAllActions() const
Get all registered actions.
void resetAllToDefaults()
Reset all shortcuts to defaults.
void shortcutsReloaded()
Emitted when shortcuts are reloaded.
const ShortcutAction * getAction(const QString &actionId) const
Get an action by ID.
void setCategoryEnabled(const QString &category, bool enabled)
Enable or disable all actions in a category.
static ShortcutManager & instance()
Get singleton instance.
static QString keySequenceToString(const QKeySequence &seq)
Get display string for a key sequence.
void setAllEnabled(bool enabled)
Enable or disable all shortcuts (useful when dialogs are open).
void resetToDefault(const QString &actionId)
Reset an action to its default shortcut.
QStringList getCategories() const
Get all categories.
bool hasAction(const QString &actionId) const
Check if an action is registered.
std::vector< ShortcutAction > getActionsByCategory(const QString &category) const
Get actions by category.
void setActionEnabled(const QString &actionId, bool enabled)
Enable or disable an action.
void loadCustomizations()
Load custom shortcuts from settings.
void unregisterAction(const QString &actionId)
Unregister a shortcut action.
void initialize(QWidget *mainWidget)
Initialize manager with main widget for shortcut context.
int importFromFile(const QString &filePath)
Import shortcuts from JSON file.
bool exportToFile(const QString &filePath) const
Export shortcuts to JSON file.
void shortcutChanged(const QString &actionId, const QKeySequence &newShortcut)
Emitted when a shortcut is changed.
Represents a single keyboard shortcut action.
QKeySequence currentShortcut
Current (possibly customized) key sequence.
bool isGlobal
Whether this is a global (application-wide) shortcut.
QString id
Unique identifier (e.g., "game.launch").
std::function< bool()> canExecute
Optional: returns false to disable temporarily.
bool isEnabled
Whether this shortcut is currently enabled.
std::function< void()> action
Action to execute.