game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
shortcut_manager.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// shortcut_manager.h
4// ==============================================================================
5// Centralized keyboard shortcut management with customization support
6// ==============================================================================
7// Provides a unified system for registering, managing, and customizing
8// keyboard shortcuts across the application.
9// ==============================================================================
10
11#pragma once
12
13#include <QKeySequence>
14#include <QObject>
15#include <QShortcut>
16#include <QWidget>
17#include <functional>
18#include <map>
19#include <memory>
20#include <vector>
21
22// ==============================================================================
23// ShortcutAction Structure
24// ==============================================================================
25
26/**
27 * @struct ShortcutAction
28 * @brief Represents a single keyboard shortcut action
29 */
31{
32 QString id; ///< Unique identifier (e.g., "game.launch")
33 QString label; ///< Display name (e.g., "Launch Game")
34 QString category; ///< Category for grouping (e.g., "Game Actions")
35 QKeySequence defaultShortcut; ///< Default key sequence
36 QKeySequence currentShortcut; ///< Current (possibly customized) key sequence
37 QString description; ///< Optional description
38 bool isEnabled = true; ///< Whether this shortcut is currently enabled
39 bool isGlobal = false; ///< Whether this is a global (application-wide) shortcut
40
41 std::function<void()> action; ///< Action to execute
42 std::function<bool()> canExecute; ///< Optional: returns false to disable temporarily
43
44 /**
45 * @brief Check if shortcut has been customized
46 */
47 bool isCustomized() const
48 {
50 }
51
52 /**
53 * @brief Reset to default shortcut
54 */
59};
60
61// ==============================================================================
62// ShortcutCategory
63// ==============================================================================
64
65/**
66 * @brief Predefined shortcut categories
67 *
68 * Plain `const char*` constants — QString construction at namespace scope
69 * is technically a throwing static initialiser (clang-tidy
70 * bugprone-throwing-static-initialization), and an exception during
71 * static init can't be caught and would call std::terminate. const char*
72 * literals don't allocate. Callers using `.category(ShortcutCategory::X)`
73 * implicitly construct a QString at the call site, which is reachable
74 * code where any exception is recoverable.
75 */
77{
78inline constexpr const char* Global = "Global";
79inline constexpr const char* GameActions = "Game Actions";
80inline constexpr const char* View = "View";
81inline constexpr const char* Navigation = "Navigation";
82inline constexpr const char* Panels = "Panels";
83inline constexpr const char* Tools = "Tools";
84} // namespace ShortcutCategory
85
86// ==============================================================================
87// ShortcutManager Class
88// ==============================================================================
89
90/**
91 * @class ShortcutManager
92 * @brief Singleton manager for all keyboard shortcuts
93 *
94 * Features:
95 * - Centralized shortcut registration
96 * - Conflict detection
97 * - Persistence of customizations
98 * - Enable/disable shortcuts by context
99 * - Export/import shortcut configurations
100 */
101class ShortcutManager : public QObject
102{
103 Q_OBJECT
104
105 public:
106 /**
107 * @brief Get singleton instance
108 */
109 static ShortcutManager& instance();
110
111 /**
112 * @brief Initialize manager with main widget for shortcut context
113 * @param mainWidget The main window widget
114 */
115 void initialize(QWidget* mainWidget);
116
117 /**
118 * @brief Check if manager is initialized
119 */
120 bool isInitialized() const
121 {
122 return mainWidget_ != nullptr;
123 }
124
125 // =========================================================================
126 // Shortcut Registration
127 // =========================================================================
128
129 /**
130 * @brief Register a new shortcut action
131 * @param action The action to register
132 * @return True if registered successfully
133 */
134 bool registerAction(const ShortcutAction& action);
135
136 /**
137 * @brief Unregister a shortcut action
138 * @param actionId Action ID to remove
139 */
140 void unregisterAction(const QString& actionId);
141
142 /**
143 * @brief Check if an action is registered
144 * @param actionId Action ID to check
145 */
146 bool hasAction(const QString& actionId) const;
147
148 /**
149 * @brief Get an action by ID
150 * @param actionId Action ID
151 * @return Pointer to action or nullptr
152 */
153 const ShortcutAction* getAction(const QString& actionId) const;
154
155 /**
156 * @brief Get all registered actions
157 */
158 std::vector<ShortcutAction> getAllActions() const;
159
160 /**
161 * @brief Get actions by category
162 * @param category Category name
163 */
164 std::vector<ShortcutAction> getActionsByCategory(const QString& category) const;
165
166 /**
167 * @brief Get all categories
168 */
169 QStringList getCategories() const;
170
171 // =========================================================================
172 // Shortcut Customization
173 // =========================================================================
174
175 /**
176 * @brief Set a custom shortcut for an action
177 * @param actionId Action ID
178 * @param shortcut New key sequence
179 * @return True if set successfully (no conflicts)
180 */
181 bool setShortcut(const QString& actionId, const QKeySequence& shortcut);
182
183 /**
184 * @brief Reset an action to its default shortcut
185 * @param actionId Action ID
186 */
187 void resetToDefault(const QString& actionId);
188
189 /**
190 * @brief Reset all shortcuts to defaults
191 */
192 void resetAllToDefaults();
193
194 /**
195 * @brief Check if a shortcut conflicts with existing ones
196 * @param shortcut Key sequence to check
197 * @param excludeActionId Optional action ID to exclude from check
198 * @return Conflicting action ID, or empty if no conflict
199 */
200 QString checkConflict(const QKeySequence& shortcut,
201 const QString& excludeActionId = QString()) const;
202
203 // =========================================================================
204 // Enable/Disable
205 // =========================================================================
206
207 /**
208 * @brief Enable or disable an action
209 * @param actionId Action ID
210 * @param enabled Whether to enable
211 */
212 void setActionEnabled(const QString& actionId, bool enabled);
213
214 /**
215 * @brief Enable or disable all actions in a category
216 * @param category Category name
217 * @param enabled Whether to enable
218 */
219 void setCategoryEnabled(const QString& category, bool enabled);
220
221 /**
222 * @brief Enable or disable all shortcuts (useful when dialogs are open)
223 * @param enabled Whether to enable
224 */
225 void setAllEnabled(bool enabled);
226
227 // =========================================================================
228 // Persistence
229 // =========================================================================
230
231 /**
232 * @brief Save custom shortcuts to settings
233 */
234 void saveCustomizations();
235
236 /**
237 * @brief Load custom shortcuts from settings
238 */
239 void loadCustomizations();
240
241 /**
242 * @brief Export shortcuts to JSON file
243 * @param filePath Output file path
244 * @return True if export succeeded
245 */
246 bool exportToFile(const QString& filePath) const;
247
248 /**
249 * @brief Import shortcuts from JSON file
250 * @param filePath Input file path
251 * @return Number of shortcuts imported
252 */
253 int importFromFile(const QString& filePath);
254
255 // =========================================================================
256 // Utility
257 // =========================================================================
258
259 /**
260 * @brief Get display string for a key sequence
261 */
262 static QString keySequenceToString(const QKeySequence& seq);
263
264 /**
265 * @brief Trigger an action by ID
266 * @param actionId Action ID to trigger
267 * @return True if action was triggered
268 */
269 bool triggerAction(const QString& actionId);
270
271 signals:
272 /**
273 * @brief Emitted when a shortcut is changed
274 */
275 void shortcutChanged(const QString& actionId, const QKeySequence& newShortcut);
276
277 /**
278 * @brief Emitted when shortcuts are reloaded
279 */
281
282 public:
283 // Deleted copy operations: kept public so a call-site copy attempt
284 // produces a clear "deleted function" diagnostic instead of the more
285 // confusing "private member" one. Explicit `public:` ends the
286 // preceding `signals:` section so moc doesn't mistake these for
287 // signals. Singleton: instances only via ShortcutManager::instance().
290
291 private:
293 ~ShortcutManager() override;
294
295 void createQShortcut(const QString& actionId);
296 void updateQShortcut(const QString& actionId);
297 void removeQShortcut(const QString& actionId);
298
299 QWidget* mainWidget_ = nullptr;
300 std::map<QString, ShortcutAction> actions_;
301 std::map<QString, std::unique_ptr<QShortcut>> shortcuts_;
302 bool allEnabled_ = true;
303};
304
305// ==============================================================================
306// ShortcutBuilder Helper
307// ==============================================================================
308
309/**
310 * @class ShortcutBuilder
311 * @brief Fluent builder for creating ShortcutAction objects
312 */
314{
315 public:
316 explicit ShortcutBuilder(const QString& id)
317 {
318 action_.id = id;
319 }
320
321 ShortcutBuilder& label(const QString& label)
322 {
323 action_.label = label;
324 return *this;
325 }
326 ShortcutBuilder& category(const QString& cat)
327 {
328 action_.category = cat;
329 return *this;
330 }
331 ShortcutBuilder& shortcut(const QKeySequence& seq)
332 {
333 action_.defaultShortcut = seq;
334 action_.currentShortcut = seq;
335 return *this;
336 }
337 ShortcutBuilder& shortcut(const QString& seq)
338 {
339 return shortcut(QKeySequence(seq));
340 }
341 ShortcutBuilder& description(const QString& desc)
342 {
343 action_.description = desc;
344 return *this;
345 }
346 ShortcutBuilder& global(bool g = true)
347 {
348 action_.isGlobal = g;
349 return *this;
350 }
351 ShortcutBuilder& action(std::function<void()> fn)
352 {
353 action_.action = std::move(fn);
354 return *this;
355 }
356 ShortcutBuilder& canExecute(std::function<bool()> fn)
357 {
358 action_.canExecute = std::move(fn);
359 return *this;
360 }
361
363 {
364 return action_;
365 }
366
367 /**
368 * @brief Build and register with the ShortcutManager
369 */
370 bool registerWith(ShortcutManager& manager) const
371 {
372 return manager.registerAction(action_);
373 }
374
375 private:
376 ShortcutAction action_;
377};
ShortcutBuilder & label(const QString &label)
ShortcutBuilder & description(const QString &desc)
ShortcutAction build() const
bool registerWith(ShortcutManager &manager) const
Build and register with the ShortcutManager.
ShortcutBuilder & category(const QString &cat)
ShortcutBuilder & action(std::function< void()> fn)
ShortcutBuilder & shortcut(const QKeySequence &seq)
ShortcutBuilder & global(bool g=true)
ShortcutBuilder(const QString &id)
ShortcutBuilder & canExecute(std::function< bool()> fn)
ShortcutBuilder & shortcut(const QString &seq)
Singleton manager for all keyboard shortcuts.
bool triggerAction(const QString &actionId)
Trigger an action by ID.
bool isInitialized() const
Check if manager is initialized.
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.
ShortcutManager & operator=(const ShortcutManager &)=delete
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.
Predefined shortcut categories.
constexpr const char * View
constexpr const char * Tools
constexpr const char * Global
constexpr const char * Navigation
constexpr const char * GameActions
constexpr const char * Panels
Represents a single keyboard shortcut action.
QKeySequence currentShortcut
Current (possibly customized) key sequence.
QString category
Category for grouping (e.g., "Game Actions").
bool isCustomized() const
Check if shortcut has been customized.
bool isGlobal
Whether this is a global (application-wide) shortcut.
QString label
Display name (e.g., "Launch Game").
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.
QKeySequence defaultShortcut
Default key sequence.
void resetToDefault()
Reset to default shortcut.
QString description
Optional description.