SILICON
Loading...
Searching...
No Matches
windowActionsSettings.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
19
20#include <cstdint>
21
22#include <QAction>
23#include <QApplication>
24#include <QByteArray>
25#include <QJsonArray>
26#include <QJsonDocument>
27#include <QKeySequence>
28#include <QMainWindow>
29
30#ifdef __EMSCRIPTEN__
31 #include <emscripten/emscripten.h>
32#endif
33
34#include <core/simulator.hpp>
36#include <ui/shell/theme.hpp>
37
38namespace SILICON::ui {
39
40namespace {
41 ShortcutSetting shortcut(const QString& key, const QString& label, QAction* action,
42 const QKeySequence& defaultShortcut)
43 {
44 return {
45 .setting =
46 {
47 .name = key,
48 .defaultValue = QVariant::fromValue(defaultShortcut),
49 },
50 .label = label,
51 .action = action,
52 };
53 }
54
55} // namespace
56
57#ifdef __EMSCRIPTEN__
59{
60 // clang-format off
61 id = EM_ASM_INT({
62 globalThis.__siliconShortcutCaptures = globalThis.__siliconShortcutCaptures || new Map();
63 const id = globalThis.__siliconNextShortcutCaptureId ?? 0;
64 globalThis.__siliconNextShortcutCaptureId = id + 1;
65 globalThis.__siliconShortcutCaptures.set(id, {});
66 return id;
67 });
68 // clang-format on
69}
70
72 // clang-format off
73EM_ASM(
74 {
75 const captures = globalThis.__siliconShortcutCaptures;
76 const capture = captures.get($0);
77 for (const [type, handler] of capture.listeners || [])
78 document.removeEventListener(type, handler, true);
79 if (capture.frame)
80 cancelAnimationFrame(capture.frame);
81 captures.delete($0);
82 }, id);
83 // clang-format on
84}
85
86void BrowserShortcutCapture::update(const QByteArray& shortcutsJson)
87{
88 // clang-format off
89EM_ASM(
90 {
91 const captures = globalThis.__siliconShortcutCaptures;
92 const capture = captures.get($0);
93 const shortcuts = JSON.parse(UTF8ToString($1));
94 capture.sequences =
95 shortcuts.map(sequence => sequence.trim()
96 .split('+')
97 .map(part => part.trim().toLowerCase())
98 .filter(Boolean));
99
100 const isEditableTarget = target => target instanceof HTMLInputElement || target
101 instanceof HTMLTextAreaElement || target
102 instanceof HTMLSelectElement || target?.isContentEditable;
103
104 const normalizedKeyToken = token => ({
105 esc : 'escape',
106 del : 'delete',
107 ins : 'insert',
108 return : 'enter',
109 enter : 'enter',
110 backtab : 'tab',
111 space : ' ',
112 pgup : 'pageup',
113 pgdown : 'pagedown',
114 plus : '+',
115 comma : ','
116 })[token]
117 ?? token;
118
119 const eventMatchesShortcut = (event, shortcut) =>
120 {
121 if (shortcut.length === 0)
122 return false;
123
124 const target = event.composedPath()[0];
125 const key = event.key.toLowerCase();
126 const keyToken = normalizedKeyToken(shortcut[shortcut.length - 1]);
127 const wantsCtrl = shortcut.includes('ctrl') || shortcut.includes('control');
128 const wantsMeta = shortcut.includes('meta');
129 const wantsAlt = shortcut.includes('alt');
130 const wantsShift = shortcut.includes('shift');
131 const usesCommandModifier = wantsCtrl || wantsMeta || wantsAlt;
132
133 if (!usesCommandModifier && isEditableTarget(target))
134 return false;
135
136 if (wantsCtrl || wantsMeta) {
137 if (wantsCtrl && !(event.ctrlKey || event.metaKey))
138 return false;
139 if (wantsMeta && !event.metaKey)
140 return false;
141 } else if (event.ctrlKey || event.metaKey) {
142 return false;
143 }
144 if (wantsAlt !== event.altKey)
145 return false;
146 if (wantsShift !== event.shiftKey)
147 return false;
148
149 return key === keyToken || event.code.toLowerCase() === keyToken;
150 };
151
152 if (capture.listeners)
153 return;
154
155 // Qt 6.11 requestActivateWindow() can leave DOM focus unset when an
156 // input context exists. Keep this compatibility workaround here, alongside
157 // browser shortcut capture; never change a valid DOM/text-input focus.
158 const qtHost = event => event.composedPath().find(
159 node => node.id === 'qt-shadow-container' && node.shadowRoot);
160 const rememberQt = event => {
161 const host = qtHost(event);
162 if (!host)
163 return false;
164 capture.host = host;
165 capture.window = event.composedPath().find(
166 node => node.classList?.contains('qt-window'));
167 return true;
168 };
169 const scheduleFocus = () => {
170 if (capture.frame || !capture.owned)
171 return;
172 // One frame after Qt and browser default handling, without a timeout or
173 // a polling loop. Pointer/focus transitions outside Qt revoke ownership.
174 capture.frame = requestAnimationFrame(() => {
175 capture.frame = 0;
176 if (!capture.owned || !document.hasFocus()
177 || document.activeElement !== document.body)
178 return;
179 const root = capture.host?.shadowRoot;
180 if (!capture.host?.isConnected || !root || root.activeElement)
181 return;
182 const visible = element => element.getClientRects().length > 0;
183 // Prefer the helper for the window that received the event. If a Qt
184 // popup just disappeared, use a remaining visible window's helper.
185 // Both selectors are Qt internals, isolated here for version updates.
186 const selector = '.qt-window-focus-helper, .hidden-visually-read-by-screen-reader';
187 const local = capture.window?.querySelectorAll(selector) || [];
188 const target = Array.from(local).find(visible)
189 || Array.from(root.querySelectorAll(selector)).find(visible);
190 target?.focus({preventScroll: true});
191 });
192 };
193 const onFocusIn = event => {
194 capture.owned = rememberQt(event);
195 };
196 const onPointerDown = event => {
197 capture.owned = rememberQt(event);
198 scheduleFocus();
199 };
200 const onFocusOut = event => {
201 if (capture.owned && qtHost(event))
202 scheduleFocus();
203 };
204 const onKeyDown = event => {
205 if (!rememberQt(event))
206 return;
207 // Tab is an intentional focus transition, including out of the app.
208 capture.owned = event.key !== 'Tab';
209 if (!capture.owned || event.isComposing)
210 return;
211 scheduleFocus();
212 if (capture.sequences.some(
213 shortcut => eventMatchesShortcut(event, shortcut)))
214 event.preventDefault();
215 };
216 capture.listeners = ([
217 ['keydown', onKeyDown], ['focusin', onFocusIn],
218 ['focusout', onFocusOut], ['pointerdown', onPointerDown]
219 ]);
220 for (const [type, handler] of capture.listeners)
221 document.addEventListener(type, handler, true);
222 },
223 id,
224 shortcutsJson.constData());
225 // clang-format on
226}
227
228#endif
229
231
233{
234#ifdef __EMSCRIPTEN__
235 const QVector<ShortcutSetting> shortcuts = shortcutSettings();
236 QJsonArray shortcutSequences;
237 for (const ShortcutSetting& shortcut : shortcuts) {
238 if (!shortcut.action)
239 continue;
240
241 for (const QKeySequence& sequence : shortcut.action->shortcuts()) {
242 if (sequence.isEmpty())
243 continue;
244
245 for (int index = 0; index < sequence.count(); ++index)
246 shortcutSequences.append(
247 QKeySequence(sequence[index]).toString(QKeySequence::PortableText));
248 }
249 }
250
251 const QByteArray shortcutsJson =
252 QJsonDocument(shortcutSequences).toJson(QJsonDocument::Compact);
253
254 if (!browserShortcuts)
255 browserShortcuts = std::make_unique<BrowserShortcutCapture>();
256 browserShortcuts->update(shortcutsJson);
257#endif
258}
259
260QVector<ShortcutSetting> WindowActions::shortcutSettings() const
261{
262 return {
263 shortcut(QStringLiteral("keybindings/new"), tr("New"), project.newProject,
264 QKeySequence(QKeySequence::New)),
265 shortcut(QStringLiteral("keybindings/open"), tr("Open"), project.open,
266 QKeySequence(QKeySequence::Open)),
267 shortcut(QStringLiteral("keybindings/save"), tr("Save"), project.save,
268 QKeySequence(QKeySequence::Save)),
269 shortcut(QStringLiteral("keybindings/exportImage"), tr("Export"),
270 project.exportImage, QKeySequence(QKeySequence::Print)),
271 shortcut(QStringLiteral("keybindings/exit"), tr("Exit"), project.exit,
272 QKeySequence(QKeySequence::Quit)),
273 shortcut(QStringLiteral("keybindings/undo"), tr("Undo"), edit.undo,
274 QKeySequence(QKeySequence::Undo)),
275 shortcut(QStringLiteral("keybindings/redo"), tr("Redo"), edit.redo,
276 QKeySequence(QKeySequence::Redo)),
277 shortcut(QStringLiteral("keybindings/cut"), tr("Cut"), edit.cut,
278 QKeySequence(QKeySequence::Cut)),
279 shortcut(QStringLiteral("keybindings/copy"), tr("Copy"), edit.copy,
280 QKeySequence(QKeySequence::Copy)),
281 shortcut(QStringLiteral("keybindings/paste"), tr("Paste"), edit.paste,
282 QKeySequence(QKeySequence::Paste)),
283 shortcut(QStringLiteral("keybindings/selectAll"), tr("Select All"),
284 circuit.selectAll, QKeySequence(Qt::ControlModifier | Qt::Key_A)),
285 shortcut(QStringLiteral("keybindings/rotate"), tr("Rotate"), circuit.rotate,
286 QKeySequence(Qt::AltModifier | Qt::Key_R)),
287 shortcut(QStringLiteral("keybindings/autoPlace"), tr("Auto place"),
288 circuit.autoPlace, QKeySequence(Qt::AltModifier | Qt::Key_L)),
289 shortcut(QStringLiteral("keybindings/centerView"), tr("Center view"),
290 circuit.centerView, QKeySequence(Qt::AltModifier | Qt::Key_C)),
291 shortcut(QStringLiteral("keybindings/delete"), tr("Delete"), edit.remove,
292 QKeySequence(QKeySequence::Delete)),
293 shortcut(QStringLiteral("keybindings/normalMode"), tr("Normal mode"),
294 circuit.setNormalMode, QKeySequence()),
295 shortcut(QStringLiteral("keybindings/panMode"), tr("Pan mode"), circuit.setPanMode,
296 QKeySequence()),
297 shortcut(QStringLiteral("keybindings/wireCreationMode"), tr("Wire creation mode"),
298 circuit.setWireCreationMode, QKeySequence(Qt::AltModifier | Qt::Key_W)),
299 shortcut(QStringLiteral("keybindings/simulationMode"), tr("Simulation mode"),
300 circuit.setSimulationMode,
301 QKeySequence(Qt::AltModifier | Qt::ControlModifier | Qt::Key_S)),
302 shortcut(QStringLiteral("keybindings/componentPlacingMode"),
303 tr("Component placing mode"), circuit.setComponentPlacingMode,
304 QKeySequence(Qt::AltModifier | Qt::Key_A)),
305 shortcut(QStringLiteral("keybindings/cancelInteraction"),
306 tr("Cancel current interaction"), circuit.cancelInteraction,
307 QKeySequence(Qt::Key_Escape)),
308 shortcut(QStringLiteral("keybindings/toggleTrace"), tr("Waveform trace"),
309 waveform.toggleTrace, QKeySequence()),
310 shortcut(QStringLiteral("keybindings/settings"), tr("Settings"), project.settings,
311 QKeySequence()),
312 };
313}
314
316{
317 SiliconSettings settings("SILICON", this);
319
321 static_cast<uint64_t>(values.maxSimulationSteps));
324
326
327 const auto shortcuts = shortcutSettings();
328 for (const ShortcutSetting& shortcut : shortcuts) {
329 shortcut.action->setShortcut(
330 SILICON::ui::settings::value(settings, shortcut.setting).value<QKeySequence>());
331#ifdef __EMSCRIPTEN__
332 shortcut.action->setShortcutContext(Qt::ApplicationShortcut);
333 if (!window.actions().contains(shortcut.action))
334 window.addAction(shortcut.action);
335#endif
336 }
337
339}
340
342{
343 const auto shortcuts = shortcutSettings();
344#ifdef __EMSCRIPTEN__
345 // WASM cannot run the nested event loop used by QDialog::exec().
346 auto* settingsWindow = new SettingsWindow("SILICON", shortcuts, &window);
347 settingsWindow->setAttribute(Qt::WA_DeleteOnClose);
348 connect(settingsWindow, &QDialog::finished, this,
349 [this] { syncWasmShortcutCapture(); });
350 settingsWindow->open();
351#else
352 SettingsWindow settingsWindow("SILICON", shortcuts, &window);
353 settingsWindow.exec();
355#endif
356}
357
358} // namespace SILICON::ui
static void setMaxSimulationSteps(uint64_t value)
static void setMaxTransitionsPerDeltaCycle(int value)
void update(const QByteArray &shortcutsJson)
Dialog for editing persisted application settings and shortcuts.
QSettings wrapper configured to read and write SILICON TOML settings files.
static void apply(QApplication &app, theme::Mode mode)
Definition theme.cpp:169
WaveformActions waveform
Commands owned by the waveform viewer.
CircuitActions circuit
Commands owned by the circuit editor.
ProjectActions project
Commands owned by the project and application shell.
EditActions edit
Commands owned by the active editor, whatever its kind.
QVector< ShortcutSetting > shortcutSettings() const
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
SILICON::ui::theme::Mode themeModeFromText(const QString &value)
Converts a persisted theme string into a theme engine mode.
CommonSettingsValues readCommonSettings(const QSettings &settings)
Reads the common UI and simulation settings into a typed snapshot.
Snapshot of the common application settings used at runtime.
Shortcut row shown in the settings dialog.