Skip to content

AI-native design editor. Open-source Figma alternative.

fix(desktop): leave unmodified shortcuts to the WebView on Linux (#1640)

Valery Komarov58d284d2c164
diff --git a/changes/1640/fixed.md b/changes/1640/fixed.md
new file mode 100644
index 000000000..bc6fbb231
--- /dev/null
+++ b/changes/1640/fixed.md
@@ -0,0 +1 @@
+- On Linux, Backspace and keys such as `[`, `]` and `N` type into comments and other text fields again instead of running menu commands, so Backspace no longer deletes the selected layer while you type.
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index e21f69a5a..98cce1e6c 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -11,6 +11,7 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j
- The Software Update window is a second webview labelled `updater` that loads `updater.html` (`src/updater.ts`), never the editor's `index.html`; its own capability, `desktop/capabilities/updater.json`, grants only checking, installing, restarting, closing, and opening links. It owns no documents, so before a restart or a Windows install it asks the editor window over `updater:restart-request` to run the Quit approval (`src/app/shell/updater/approvals.ts`, `tests/app/shell/updater/session.test.ts`).
- Never click Install in a `tauri dev` build: the updater unpacks the release next to the running binary, which there is `desktop/target/debug`.
- `desktop/generated/menu.json` is produced by `bun run generate:tauri-menu` from `src/app/shell/menu/schema.ts`; do not edit or import it directly.
+- On Linux a menu item registers its accelerator natively only when it holds Ctrl, Alt, or Super and is not copy, cut, or paste: GTK runs window accelerators before the WebView sees the key, so plain and Shift-only keys stay with the frontend's shortcuts, which skip text fields (`menu::tests` in `desktop/src/menu/mod.rs`).
- A menu or menu entry with a `feature` in the schema is built only while the frontend names that feature through `set_native_menu_features` (`src/app/shell/menu/features.ts`); `document` hides what needs an open document on Home and a New file tab. Every rebuild keeps the check states the menu had (`desktop/src/menu/mod.rs`).
- Command items are greyed out while their editor command is unavailable: the frontend sends their ids through `set_native_menu_disabled`, which updates the items in place instead of rebuilding (`src/app/shell/menu/editor.ts`).
- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.
diff --git a/desktop/src/menu/mod.rs b/desktop/src/menu/mod.rs
index ffe2fe7f8..391c96811 100644
--- a/desktop/src/menu/mod.rs
+++ b/desktop/src/menu/mod.rs
@@ -77,6 +77,33 @@ fn app_menu_file() -> tauri::Result<AppMenuFile> {
))?)
}
+/// Whether `accelerator` holds a modifier other than Shift: Ctrl, Alt, Super, or Cmd.
+fn has_command_modifier(accelerator: &str) -> bool {
+ let parts: Vec<&str> = accelerator.split('+').collect();
+ // The last part is the key itself, which may be `+` as in `CmdOrCtrl++`.
+ parts[..parts.len().saturating_sub(1)]
+ .iter()
+ .any(|part| !part.trim().is_empty() && !part.trim().eq_ignore_ascii_case("shift"))
+}
+
+/// The accelerator an item registers natively, if any.
+///
+/// GTK activates a window's accelerators before the focused widget sees the key, so on Linux a
+/// menu accelerator without Ctrl, Alt, or Super takes typed characters, Backspace, and paging
+/// keys away from text fields in the WebView. Those, and copy, cut, and paste, whose native
+/// commands need X11 automation that Wayland lacks, are left to the frontend's shortcuts, which
+/// skip text fields (`src/app/shell/keyboard/registry.ts`).
+fn native_accelerator(entry: &MenuEntry) -> Option<&str> {
+ let accelerator = entry.accelerator.as_deref()?;
+ if cfg!(target_os = "linux") {
+ let clipboard = matches!(entry.id.as_deref(), Some("copy" | "cut" | "paste"));
+ if clipboard || !has_command_modifier(accelerator) {
+ return None;
+ }
+ }
+ Some(accelerator)
+}
+
fn is_separator(entry: &MenuEntry) -> bool {
entry.r#type.as_deref() == Some("separator")
}
@@ -169,7 +196,7 @@ fn build_submenu<R: tauri::Runtime>(
if let Some(id) = &entry.id {
item = item.id(id);
}
- if let Some(accelerator) = &entry.accelerator {
+ if let Some(accelerator) = native_accelerator(entry) {
item = item.accelerator(accelerator);
}
builder = builder.item(&item.build(app)?);
@@ -181,15 +208,8 @@ fn build_submenu<R: tauri::Runtime>(
if let Some(id) = &entry.id {
item = item.id(id);
}
- // On Linux, muda's predefined edit commands depend on optional X11
- // automation and do not work on Wayland. Leave these accelerators to the
- // WebView instead, which preserves native input and canvas paste events.
- let webview_handles_accelerator = cfg!(target_os = "linux")
- && matches!(entry.id.as_deref(), Some("copy" | "cut" | "paste"));
- if !webview_handles_accelerator {
- if let Some(accelerator) = &entry.accelerator {
- item = item.accelerator(accelerator);
- }
+ if let Some(accelerator) = native_accelerator(entry) {
+ item = item.accelerator(accelerator);
}
builder = builder.item(&item.build(app)?);
}
@@ -540,4 +560,53 @@ mod tests {
assert!(!shown(&file, &[]).contains(&"save".to_string()));
assert!(shown(&file, &["document".to_string()]).contains(&"save".to_string()));
}
+
+ fn entry(id: &str, accelerator: &str) -> MenuEntry {
+ MenuEntry {
+ r#type: None,
+ id: Some(id.to_owned()),
+ label: Some(id.to_owned()),
+ accelerator: Some(accelerator.to_owned()),
+ checkbox: false,
+ feature: None,
+ sub: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn counts_every_modifier_but_shift_as_a_command_modifier() {
+ for accelerator in ["CmdOrCtrl+Z", "Ctrl+Tab", "Alt+W", "Super+K", "CmdOrCtrl++"] {
+ assert!(has_command_modifier(accelerator), "{accelerator}");
+ }
+ for accelerator in ["N", "[", "Backspace", "PageUp", "Shift+1", "Shift+'", "+"] {
+ assert!(!has_command_modifier(accelerator), "{accelerator}");
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn leaves_keys_that_text_fields_type_to_the_frontend_on_linux() {
+ for (id, accelerator) in [
+ ("selection.delete", "Backspace"),
+ ("selection.sendToBack", "["),
+ ("view.zoomNextFrame", "N"),
+ ("view.zoomFit", "Shift+1"),
+ ("copy", "CmdOrCtrl+C"),
+ ] {
+ assert_eq!(native_accelerator(&entry(id, accelerator)), None, "{id}");
+ }
+ assert_eq!(
+ native_accelerator(&entry("edit.undo", "CmdOrCtrl+Z")),
+ Some("CmdOrCtrl+Z")
+ );
+ }
+
+ #[cfg(not(target_os = "linux"))]
+ #[test]
+ fn registers_every_accelerator_off_linux() {
+ assert_eq!(
+ native_accelerator(&entry("view.zoomNextFrame", "N")),
+ Some("N")
+ );
+ }
}
diff --git a/src/app/settings/preferences/native-menu.ts b/src/app/settings/preferences/native-menu.ts
index 45de1fcdd..4a64d4207 100644
--- a/src/app/settings/preferences/native-menu.ts
+++ b/src/app/settings/preferences/native-menu.ts
@@ -1,4 +1,5 @@
import { invoke } from '@tauri-apps/api/core'
+import { watch, type Ref } from 'vue'
import type { SnappingPreferences } from '@open-pencil/core'
@@ -6,6 +7,8 @@ import { isTauri } from '@/app/tauri/env'
export const DESIGN_ISSUES_MENU_ID = 'view-design-issues'
export const COMMENTS_MENU_ID = 'view-comments'
+export const RULERS_MENU_ID = 'view-rulers'
+export const PIXEL_GRID_MENU_ID = 'view-pixel-grid'
const SNAPPING_MENU_IDS = {
geometry: 'snap-geometry',
@@ -30,6 +33,50 @@ export async function syncNativeDesignIssuesMenu(showOnCanvas: boolean): Promise
await invoke('set_native_menu_checked', { id: DESIGN_ISSUES_MENU_ID, checked: showOnCanvas })
}
+/**
+ * View → Rulers and View → Pixel Grid, which their keys and the zoom menu also toggle; on Linux
+ * those keys never reach the native menu (`desktop/src/menu/mod.rs`), so it learns of them here.
+ */
+export async function syncNativeCanvasViewMenu(view: {
+ rulers: boolean
+ pixelGrid: boolean
+}): Promise<void> {
+ if (!isTauri()) return
+ await Promise.all([
+ invoke('set_native_menu_checked', { id: RULERS_MENU_ID, checked: view.rulers }),
+ invoke('set_native_menu_checked', { id: PIXEL_GRID_MENU_ID, checked: view.pixelGrid })
+ ])
+}
+
+/** What {@link followNativeCanvasViewMenu} reads of a document. */
+interface CanvasViewSource {
+ state: { showRulers: boolean; showPixelGrid?: boolean }
+}
+
+/**
+ * Keeps View → Rulers and View → Pixel Grid checked as the active document shows them, whatever
+ * toggled them and when another document becomes active. Each sync waits for the one before it,
+ * so the menu ends on the latest state however its calls are answered.
+ */
+export function followNativeCanvasViewMenu(store: Ref<CanvasViewSource | undefined>): () => void {
+ let pending: Promise<void> = Promise.resolve()
+ return watch(
+ () => {
+ const state = store.value?.state
+ return state ? { rulers: state.showRulers, pixelGrid: state.showPixelGrid !== false } : null
+ },
+ (view) => {
+ if (!view) return
+ pending = pending
+ .then(() => syncNativeCanvasViewMenu(view))
+ .catch((error: unknown) => {
+ console.error('[Menu] Failed to synchronize the native rulers and pixel grid:', error)
+ })
+ },
+ { immediate: true, deep: true }
+ )
+}
+
/** View → Comments, which Shift+C and the comment menus also toggle. */
export async function syncNativeCommentsMenu(shown: boolean): Promise<void> {
if (!isTauri()) return
diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.ts
index 8fe989584..3ed8f412d 100644
--- a/src/app/shell/menu/shell.ts
+++ b/src/app/shell/menu/shell.ts
@@ -2,9 +2,11 @@ import { useI18n } from '@open-pencil/vue/i18n'
import { openTour } from '@/app/demo/document'
import { requestAppExit } from '@/app/document/close/exit'
+import { useActiveEditorStoreRef } from '@/app/editor/active-store'
import { openSettingsDialog } from '@/app/settings/dialog'
import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'
import {
+ followNativeCanvasViewMenu,
syncNativeCommentsMenu,
syncNativeDesignIssuesMenu,
syncNativeSnappingMenu
@@ -49,6 +51,8 @@ export function useShellMenu() {
}
)
+ followNativeCanvasViewMenu(useActiveEditorStoreRef())
+
const { setTheme } = useAppTheme()
const { updates } = useI18n()
const actions: Partial<Record<string, () => void>> = {
diff --git a/tests/app/settings/preferences/native-menu.test.ts b/tests/app/settings/preferences/native-menu.test.ts
new file mode 100644
index 000000000..8de0a3ba3
--- /dev/null
+++ b/tests/app/settings/preferences/native-menu.test.ts
@@ -0,0 +1,76 @@
+import { afterEach, expect, test } from 'bun:test'
+
+import { nextTick, shallowReactive, shallowRef } from 'vue'
+
+import { followNativeCanvasViewMenu } from '@/app/settings/preferences/native-menu'
+
+import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'
+
+afterEach(clearTauriMocks)
+
+/** Lets a change reach the watcher and its chained native calls finish. */
+async function settle() {
+ await nextTick()
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0)
+ })
+}
+
+function documentShowing(showRulers: boolean, showPixelGrid?: boolean) {
+ return { state: shallowReactive({ showRulers, showPixelGrid }) }
+}
+
+test('the native Rulers and Pixel Grid items follow the active document', async () => {
+ const checked = new Map<string, boolean>()
+ await mockTauriIPC((command, args) => {
+ expect(command).toBe('set_native_menu_checked')
+ const { id, checked: value } = args as { id: string; checked: boolean }
+ checked.set(id, value)
+ })
+ const first = documentShowing(true)
+ const active = shallowRef<ReturnType<typeof documentShowing> | undefined>(first)
+ const stop = followNativeCanvasViewMenu(active)
+ await settle()
+ expect(Object.fromEntries(checked)).toEqual({ 'view-rulers': true, 'view-pixel-grid': true })
+
+ // A key or the zoom menu toggles the document's state, not the native item.
+ first.state.showRulers = false
+ first.state.showPixelGrid = false
+ await settle()
+ expect(Object.fromEntries(checked)).toEqual({ 'view-rulers': false, 'view-pixel-grid': false })
+
+ active.value = documentShowing(true, true)
+ await settle()
+ expect(Object.fromEntries(checked)).toEqual({ 'view-rulers': true, 'view-pixel-grid': true })
+ stop()
+})
+
+test('the native items end on the latest state however their calls are answered', async () => {
+ const checked = new Map<string, boolean>()
+ const answers: (() => void)[] = []
+ await mockTauriIPC((_command, args) => {
+ const { id, checked: value } = args as { id: string; checked: boolean }
+ // Every call waits until the test answers it, so the first sync is still running below.
+ return new Promise<void>((resolve) => {
+ answers.push(() => {
+ checked.set(id, value)
+ resolve()
+ })
+ })
+ })
+ const shown = documentShowing(true, true)
+ const stop = followNativeCanvasViewMenu(shallowRef(shown))
+ await nextTick()
+ shown.state.showRulers = false
+ await nextTick()
+ // The second sync waits for the first, so only the first pair has been sent.
+ expect(answers).toHaveLength(2)
+
+ // Answering the calls in reverse order still cannot leave the earlier value behind.
+ while (answers.length > 0) {
+ answers.pop()?.()
+ await settle()
+ }
+ expect(Object.fromEntries(checked)).toEqual({ 'view-rulers': false, 'view-pixel-grid': true })
+ stop()
+})