diff --git a/docs/settings.md b/docs/settings.md index f090c8cc..467779a7 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -20,6 +20,6 @@ On the same page, **Style** builds the whole app another way, on this device: Li - **Clean cache** (a host's): what its enowX folder takes, and what can go of it, each kind with its size, what cleaning it does and a box. It only removes what a look just listed, under folders named in `core/cacheclean`. It asks first and reports what was freed and, item by item, what wasn't. Old app backups and worktrees are picked one by one, with their date and state. Team sync's copies are shown but not offered, as merges need them. `enowx-app cache` and `enowx-app cache clean` do the same. **Logs** keep the current ones and each one's most recent rotated copy ([diagnostics.md](diagnostics.md)). - **Discord**: Rich Presence, under the user's name in Discord: the selected session's project, branch and agent (in GOD of Agents mode, "Working using GOA" and the agent it runs on instead), how many sessions are open and how long it has run, with a *Get enowX* button to enowx.ai; *In enowX* with no session. On by default; a switch keeps the project's and branch's names out. It goes to the Discord app on this device only, over its local socket, and updates no more often than Discord allows. It needs the build's Discord application (`ENOWX_DISCORD_APP_ID` replaces it). - **Cloud**: the connected host's sign-in to enowX's cloud, https://cloud.enowx.ai ([cloud.md](cloud.md)), also at the rail's foot (**Sign in**, then the account's menu): signing in with GitHub (the browser opens on a code to approve), nothing reaching the cloud before; then two tabs: **Teams**, the account's teams as cards, each opening a dialog of its members and of an invite link made for one as member, viewer or admin, with **New team** and **Join with an invite** in dialogs of their own; and **Devices**, to sign one out or approve a code another shows. Signing out, removing a member and leaving a team ask first. The account's menu at the rail's foot also picks the space Notes and Canvas show: Personal, or a team's. Each host signs in as a device of its own; this computer's is the app. -- **App**: the editor files open in, desktop notifications, keeping enowX in the menu bar or notification area when its window closes ([tray.md](tray.md)), looking for updates by itself, the version, and the keyboard shortcuts. +- **App**: the editor files open in, desktop notifications, keeping enowX in the menu bar or notification area when its window closes ([tray.md](tray.md)), looking for updates by itself, the version, and customizable keyboard shortcuts (with modifier key requirements, conflict refusal, and terminal key protection). - **Floating control**: the round panel over any app and its shortcut ([floating-control.md](floating-control.md)), whether clicking another app folds it away, whether it opens at the pointer or in the middle of the display, and hiding the Sessions panel. Its own accent color, tinted segments, compact size and reduced animation can be set here without changing the app theme. - **Diagnostics**: the host's daemon (version, pid, since when, its build), the end of its log (`daemon.log`), and **Restart the daemon** (`daemon.restart`): it stops as an update stops it, and connecting again starts it, its sessions continued. diff --git a/ui/app.go b/ui/app.go index 07bfff97..2a25e5f8 100644 --- a/ui/app.go +++ b/ui/app.go @@ -242,9 +242,10 @@ type App struct { // portOffers are ports sessions just opened, offered to open. portOffers []portOffer // conflicts are the conflict radar's last look, by project path. - conflicts map[string][]proto.Conflict - budget *budgetForm // setting a session's budget - agentLimit *agentsForm // setting the host's limit of agents at once + conflicts map[string][]proto.Conflict + budget *budgetForm // setting a session's budget + agentLimit *agentsForm // setting the host's limit of agents at once + shortcutsForm *shortcutDialogState usage usageview.Meter usageShown bool // the Resource usage page was shown last frame tok tokensState // token usage: the Tokens tab, sessions' badges (tokens.go) diff --git a/ui/palette.go b/ui/palette.go index 7dbccb62..269aff0b 100644 --- a/ui/palette.go +++ b/ui/palette.go @@ -44,7 +44,7 @@ func (a *App) commands() []command { var out []command p, hasProject := a.currentProject() if hasProject { - out = append(out, command{"new", "New session", modKey + "N", icon.Plus, func() { a.openNewSession(p) }}) + out = append(out, command{"new", "New session", a.shortcutLabel(ShortcutNewSession), icon.Plus, func() { a.openNewSession(p) }}) } out = append(out, command{"sessions", "Sessions", "Page", icon.Terminal, func() { if a.goaOn() { @@ -79,14 +79,14 @@ func (a *App) commands() []command { } out = append(out, command{"add-host", "Add host", "A VPS or another device", icon.Server, a.openAddHost}, - command{"open", "Open folder", modKey + "O", icon.FolderPlus, a.openFolder}, + command{"open", "Open folder", a.shortcutLabel(ShortcutOpenFolder), icon.FolderPlus, a.openFolder}, command{"clone", "Clone from Git", "", icon.Git, a.openClone}, - command{"goto-file", "Go to file…", modKey + "P", icon.File, a.openQuickOpen}, + command{"goto-file", "Go to file…", a.shortcutLabel(ShortcutQuickOpen), icon.File, a.openQuickOpen}, ) if hasProject && a.client != nil { out = append(out, command{"history", "Past conversations", p.Name, icon.Chat, func() { a.openHistory(p) }}) } - out = append(out, command{"rail", "Expand or collapse sidebar", modKey + "B", icon.Sidebar, func() { a.state.RailWide = !a.state.RailWide }}) + out = append(out, command{"rail", "Expand or collapse sidebar", a.shortcutLabel(ShortcutSidebar), icon.Sidebar, func() { a.state.RailWide = !a.state.RailWide }}) out = append(out, a.sessionCommands()...) out = append(out, a.runPaletteCommands()...) if hasProject && a.client != nil { @@ -105,7 +105,7 @@ func (a *App) commands() []command { command{"quit-stop", "Quit and stop all agents", "On this device", icon.Stop, a.quitAndStopAgents}, command{"diagnostics", "Save diagnostics for a bug report", "This device's logs and " + a.host.Name + "'s, as a zip", icon.Download, a.saveDiagnostics}, command{"updates", "Check for updates", "enowX " + version.String, icon.ArrowUp, func() { a.checkForUpdates(true) }}, - command{"sessions-panel", "Show or hide the sidebar", modKey + "⇧S", icon.Sidebar, a.toggleSessionsPanel}, + command{"sessions-panel", "Show or hide the sidebar", a.shortcutLabel(ShortcutSessionsPanel), icon.Sidebar, a.toggleSessionsPanel}, command{"floating", "Floating control", floatingKey + " · Over any app", icon.Floating, a.toggleFloating}, ) for _, h := range a.allHosts() { @@ -135,9 +135,9 @@ func (a *App) sessionCommands() []command { label = "Show one session at a time" } out = append(out, - command{"split", label, modKey + "⇧L", icon.Split, func() { a.setSplit(!a.splitOn()) }}, - command{"next", "Next session", modKey + "⇧]", icon.ChevronRight, func() { a.stepSession(1) }}, - command{"previous", "Previous session", modKey + "⇧[", icon.ChevronRight, func() { a.stepSession(-1) }}, + command{"split", label, a.shortcutLabel(ShortcutSplitView), icon.Split, func() { a.setSplit(!a.splitOn()) }}, + command{"next", "Next session", a.shortcutLabel(ShortcutNextSession), icon.ChevronRight, func() { a.stepSession(1) }}, + command{"previous", "Previous session", a.shortcutLabel(ShortcutPrevSession), icon.ChevronRight, func() { a.stepSession(-1) }}, ) } s, ok := a.selectedSession() @@ -160,7 +160,11 @@ func (a *App) sessionCommands() []command { if a.panelShows(panelChanges) { label = "Hide changes" } - out = append(out, command{"changes", label, name + " · " + modKey + "⇧D", icon.Git, func() { a.toggleTool(panelChanges) }}) + sub := name + if lbl := a.shortcutLabel(ShortcutSidePanel); lbl != "" { + sub += " · " + lbl + } + out = append(out, command{"changes", label, sub, icon.Git, func() { a.toggleTool(panelChanges) }}) } for _, t := range panelTools[1:] { label := "Show " + strings.ToLower(t.name) @@ -173,7 +177,11 @@ func (a *App) sessionCommands() []command { if a.maximized != "" { maximize = "Restore session" } - out = append(out, command{"maximize", maximize, name + " · " + modKey + "⇧↩", icon.Maximize, func() { a.toggleMaximized(s.ID) }}) + maxSub := name + if lbl := a.shortcutLabel(ShortcutMaximize); lbl != "" { + maxSub += " · " + lbl + } + out = append(out, command{"maximize", maximize, maxSub, icon.Maximize, func() { a.toggleMaximized(s.ID) }}) if a.canReview(s) { for _, r := range []struct { action, label string diff --git a/ui/settings_sections.go b/ui/settings_sections.go index 4401fa96..b89cd956 100644 --- a/ui/settings_sections.go +++ b/ui/settings_sections.go @@ -546,16 +546,58 @@ func (a *App) appSection(c *ui.Context) { a.commandLineCard(c) }) widget.GridCard(c.Key("keys")).Grow(7).Basis(0).Children(func() { - list := shortcutList() widget.CardTitle(c, nil, "Keyboard shortcuts", func() { - ui.Text(c, strconv.Itoa(len(list))).FontSize(theme.TextLabel).TextColor(theme.TextSoft) + if a.hasCustomShortcuts() { + if widget.GhostButton(c.Key("reset-shortcuts-top"), "Reset").Clicked() { + a.confirm("Reset all shortcuts to defaults?", "All custom shortcut key combinations will be restored to their factory defaults.", "Reset all", func() { + a.resetAllShortcuts() + }) + } + } + if widget.GhostButton(c.Key("customize-shortcuts"), "Customize…").Clicked() { + a.openShortcutSheet() + } }) + masterOn := !a.state.ShortcutsOff + if switchRowKey(c, "app-master-shortcuts", &masterOn, "Enable keyboard shortcuts", "Turn off to disable all application shortcuts") { + a.state.ShortcutsOff = !masterOn + a.saveState() + } ui.Column(c).FillWidth().MinWidth(0).Children(func() { - for _, s := range list { + for _, def := range GlobalShortcuts { + cfg := a.shortcutConfig(def.ID) + mods, key, disabled := a.effectiveShortcut(def.ID) + globallyOff := a.state.ShortcutsOff + keyStr := FormatKey(mods, key) + if keyStr == "" || disabled || globallyOff { + keyStr = "Off" + } + + ui.Box(c).Height(theme.Rule).FillWidth().Shrink(0).Background(theme.Border) + defID := def.ID + row := ui.Row(c.Key(string(defID))).FillWidth().Height(28).Shrink(0).Gap(theme.S3).Cursor(ui.CursorPointer) + if row.Clicked() { + a.openShortcutSheet(defID) + } + row.Children(func() { + ui.Row(c).Grow(1).MinWidth(0).Gap(theme.S2).AlignItems(ui.Center).Children(func() { + widget.Running(c, def.Name, widget.RunStyle{}) + if cfg.Custom { + widget.Chip(c, "Custom", ui.Color{}) + } + }) + ui.Text(c, keyStr).FontSize(theme.TextLabel).TextColor(theme.TextSoft).SingleLine().Shrink(0) + }) + } + + for _, info := range [][2]string{ + {floatingKey, "Floating control, over any app"}, + {modKey + "-click", "Open a path or a local page printed in a terminal"}, + } { ui.Box(c).Height(theme.Rule).FillWidth().Shrink(0).Background(theme.Border) - ui.Row(c.Key(s[0])).FillWidth().Height(28).Shrink(0).Gap(theme.S3).Children(func() { - ui.Row(c).Grow(1).MinWidth(0).Children(func() { widget.Running(c, s[1], widget.RunStyle{}) }) - ui.Text(c, s[0]).FontSize(theme.TextLabel).TextColor(theme.TextSoft).SingleLine().Shrink(0) + ui.Row(c.Key(info[0])).FillWidth().Height(28).Shrink(0).Gap(theme.S3).Children(func() { + ui.Row(c).Grow(1).MinWidth(0).Children(func() { widget.Running(c, info[1], widget.RunStyle{}) }) + ui.Text(c, info[0]).FontSize(theme.TextLabel).TextColor(theme.TextSoft).SingleLine().Shrink(0) }) } }) diff --git a/ui/shortcuts.go b/ui/shortcuts.go new file mode 100644 index 00000000..2e25c93e --- /dev/null +++ b/ui/shortcuts.go @@ -0,0 +1,458 @@ +package ui + +import ( + "errors" + "fmt" + "runtime" + "strconv" + "strings" + "unicode" + + "github.com/egoist/mygo/ui" +) + +// ShortcutID identifies a customizable application shortcut. +type ShortcutID string + +const ( + ShortcutPalette ShortcutID = "palette" + ShortcutQuickOpen ShortcutID = "quick_open" + ShortcutNewSession ShortcutID = "new_session" + ShortcutOpenFolder ShortcutID = "open_folder" + ShortcutSidebar ShortcutID = "sidebar" + ShortcutSidePanel ShortcutID = "side_panel" + ShortcutSessionsPanel ShortcutID = "sessions_panel" + ShortcutBrowserTool ShortcutID = "browser_tool" + ShortcutSplitView ShortcutID = "split_view" + ShortcutNextSession ShortcutID = "next_session" + ShortcutPrevSession ShortcutID = "prev_session" + ShortcutMaximize ShortcutID = "maximize" + ShortcutHibernate ShortcutID = "hibernate" +) + +// ShortcutDef describes a registered global application shortcut. +type ShortcutDef struct { + ID ShortcutID + Name string + Description string + DefaultMods ui.Modifiers + DefaultKey ui.Key +} + +// ShortcutConfig holds user overrides and disable state for a shortcut. +type ShortcutConfig struct { + Disabled bool `json:"disabled,omitempty"` + Mods ui.Modifiers `json:"mods,omitempty"` + Key ui.Key `json:"key,omitempty"` + Custom bool `json:"custom,omitempty"` + Text string `json:"text,omitempty"` +} + +// GlobalShortcuts lists all configurable global shortcuts in presentation order. +var GlobalShortcuts = []ShortcutDef{ + {ID: ShortcutPalette, Name: "Command palette", Description: "Find and run commands", DefaultMods: ui.Cmd, DefaultKey: ui.KeyK}, + {ID: ShortcutQuickOpen, Name: "Go to file", Description: "Quick open a file of the session", DefaultMods: ui.Cmd, DefaultKey: ui.KeyP}, + {ID: ShortcutNewSession, Name: "New session", Description: "Start a new agent session", DefaultMods: ui.Cmd, DefaultKey: ui.KeyN}, + {ID: ShortcutOpenFolder, Name: "Open folder", Description: "Open a folder or project", DefaultMods: ui.Cmd, DefaultKey: ui.KeyO}, + {ID: ShortcutSidebar, Name: "Expand or collapse sidebar", Description: "Toggle wide / narrow rail", DefaultMods: ui.Cmd, DefaultKey: ui.KeyB}, + {ID: ShortcutSidePanel, Name: "Show or hide side panel", Description: "Toggle side panel tools", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyD}, + {ID: ShortcutSessionsPanel, Name: "Show or hide Sessions panel", Description: "Toggle sessions list panel", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyS}, + {ID: ShortcutBrowserTool, Name: "Browser tool", Description: "Open the built-in browser", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyP}, + {ID: ShortcutSplitView, Name: "Sessions side by side", Description: "Toggle split view for sessions", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyL}, + {ID: ShortcutNextSession, Name: "Next session", Description: "Switch to next session in project", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyBracketRight}, + {ID: ShortcutPrevSession, Name: "Previous session", Description: "Switch to previous session in project", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyBracketLeft}, + {ID: ShortcutMaximize, Name: "Maximize session", Description: "Expand session to full workspace", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyEnter}, + {ID: ShortcutHibernate, Name: "Hibernate session", Description: "Hibernate selected idle session", DefaultMods: ui.Cmd | ui.Shift, DefaultKey: ui.KeyH}, +} + +// LookupShortcut finds a shortcut definition by its ID. +func LookupShortcut(id ShortcutID) (ShortcutDef, bool) { + for _, def := range GlobalShortcuts { + if def.ID == id { + return def, true + } + } + return ShortcutDef{}, false +} + +// FormatKey formats modifiers and a key into a human-readable display string. +func FormatKey(mods ui.Modifiers, key ui.Key) string { + keyName := formatSingleKey(key) + if keyName == "" { + return "" + } + + if runtime.GOOS == "darwin" { + var b strings.Builder + if mods&ui.Ctrl != 0 { + b.WriteString("^") + } + if mods&ui.Alt != 0 { + b.WriteString("⌥") + } + if mods&ui.Shift != 0 { + b.WriteString("⇧") + } + if mods&(ui.Super|ui.Cmd) != 0 { + b.WriteString("⌘") + } + b.WriteString(keyName) + return b.String() + } + + var parts []string + if mods&ui.Ctrl != 0 || (mods&ui.Cmd != 0 && ui.Cmd == ui.Ctrl) { + parts = append(parts, "Ctrl") + } + if mods&ui.Alt != 0 { + parts = append(parts, "Alt") + } + if mods&ui.Shift != 0 { + parts = append(parts, "Shift") + } + if mods&ui.Super != 0 && ui.Cmd != ui.Super { + parts = append(parts, "Win") + } + parts = append(parts, keyName) + return strings.Join(parts, "+") +} + +func formatSingleKey(key ui.Key) string { + switch { + case key >= ui.KeyA && key <= ui.KeyZ: + return string(rune('A' + int(key-ui.KeyA))) + case key >= ui.Key0 && key <= ui.Key9: + return string(rune('0' + int(key-ui.Key0))) + case key >= ui.KeyF1 && key <= ui.KeyF12: + return fmt.Sprintf("F%d", int(key-ui.KeyF1)+1) + } + + switch key { + case ui.KeyEnter: + if runtime.GOOS == "darwin" { + return "↩" + } + return "Enter" + case ui.KeyEscape: + return "Esc" + case ui.KeyTab: + return "Tab" + case ui.KeySpace: + return "Space" + case ui.KeyBackspace: + return "Backspace" + case ui.KeyDelete: + return "Delete" + case ui.KeyBracketLeft: + return "[" + case ui.KeyBracketRight: + return "]" + case ui.KeySlash: + return "/" + case ui.KeyBackslash: + return "\\" + case ui.KeyMinus: + return "-" + case ui.KeyEqual: + return "=" + case ui.KeyComma: + return "," + case ui.KeyPeriod: + return "." + case ui.KeySemicolon: + return ";" + case ui.KeyQuote: + return "'" + case ui.KeyBackquote: + return "`" + case ui.KeyUp: + return "Up" + case ui.KeyDown: + return "Down" + case ui.KeyLeft: + return "Left" + case ui.KeyRight: + return "Right" + case ui.KeyHome: + return "Home" + case ui.KeyEnd: + return "End" + case ui.KeyPageUp: + return "PageUp" + case ui.KeyPageDown: + return "PageDown" + default: + return "" + } +} + +// ParseKey parses a key combination string like "Ctrl+Shift+K" or "⌘K" +// into ui.Modifiers and ui.Key. A modifier key is strictly required. +func ParseKey(s string) (ui.Modifiers, ui.Key, error) { + s = strings.TrimSpace(s) + if s == "" { + return 0, ui.KeyUnknown, errors.New("shortcut cannot be empty") + } + + // Normalize Mac glyphs into standard token representation + s = strings.ReplaceAll(s, "⌘", "+cmd+") + s = strings.ReplaceAll(s, "⇧", "+shift+") + s = strings.ReplaceAll(s, "⌥", "+alt+") + s = strings.ReplaceAll(s, "^", "+ctrl+") + s = strings.ReplaceAll(s, "↩", "+enter+") + + rawTokens := strings.FieldsFunc(s, func(r rune) bool { + return r == '+' || r == '-' || unicode.IsSpace(r) + }) + + var mods ui.Modifiers + var foundKey ui.Key = ui.KeyUnknown + + for _, raw := range rawTokens { + token := strings.TrimSpace(strings.ToLower(raw)) + if token == "" { + continue + } + + switch token { + case "ctrl", "control": + mods |= ui.Ctrl + case "alt", "opt", "option": + mods |= ui.Alt + case "shift": + mods |= ui.Shift + case "cmd", "command": + mods |= ui.Cmd + case "super", "win", "windows": + mods |= ui.Super + default: + // Parse key + k, err := parseSingleKey(token) + if err != nil { + return 0, ui.KeyUnknown, err + } + if foundKey != ui.KeyUnknown { + return 0, ui.KeyUnknown, fmt.Errorf("multiple keys specified (%s and %s)", formatSingleKey(foundKey), raw) + } + foundKey = k + } + } + + if foundKey == ui.KeyUnknown { + return 0, ui.KeyUnknown, errors.New("a key (e.g. K, Enter, or F1) is required") + } + + if mods == 0 { + return 0, ui.KeyUnknown, errors.New("a modifier key (Ctrl, Alt, Shift, or Cmd) is required") + } + + return mods, foundKey, nil +} + +func parseSingleKey(s string) (ui.Key, error) { + upper := strings.ToUpper(s) + + if len(upper) == 1 { + r := rune(upper[0]) + if r >= 'A' && r <= 'Z' { + return ui.Key(int(ui.KeyA) + int(r-'A')), nil + } + if r >= '0' && r <= '9' { + return ui.Key(int(ui.Key0) + int(r-'0')), nil + } + } + + if strings.HasPrefix(upper, "F") && len(upper) >= 2 && len(upper) <= 3 { + if n, err := strconv.Atoi(upper[1:]); err == nil && n >= 1 && n <= 12 { + return ui.Key(int(ui.KeyF1) + (n - 1)), nil + } + } + + switch upper { + case "ENTER", "RETURN": + return ui.KeyEnter, nil + case "ESC", "ESCAPE": + return ui.KeyEscape, nil + case "TAB": + return ui.KeyTab, nil + case "SPACE": + return ui.KeySpace, nil + case "BACKSPACE": + return ui.KeyBackspace, nil + case "DEL", "DELETE": + return ui.KeyDelete, nil + case "[", "BRACKETLEFT": + return ui.KeyBracketLeft, nil + case "]", "BRACKETRIGHT": + return ui.KeyBracketRight, nil + case "/", "SLASH": + return ui.KeySlash, nil + case "\\", "BACKSLASH": + return ui.KeyBackslash, nil + case "-", "MINUS": + return ui.KeyMinus, nil + case "=", "EQUAL": + return ui.KeyEqual, nil + case ",", "COMMA": + return ui.KeyComma, nil + case ".", "PERIOD": + return ui.KeyPeriod, nil + case ";", "SEMICOLON": + return ui.KeySemicolon, nil + case "'", "QUOTE": + return ui.KeyQuote, nil + case "`", "BACKQUOTE": + return ui.KeyBackquote, nil + case "UP": + return ui.KeyUp, nil + case "DOWN": + return ui.KeyDown, nil + case "LEFT": + return ui.KeyLeft, nil + case "RIGHT": + return ui.KeyRight, nil + case "HOME": + return ui.KeyHome, nil + case "END": + return ui.KeyEnd, nil + case "PAGEUP": + return ui.KeyPageUp, nil + case "PAGEDOWN": + return ui.KeyPageDown, nil + default: + return ui.KeyUnknown, fmt.Errorf("unknown key %q", s) + } +} + +// shortcutConfig returns the user's config for id, or an empty config if unset. +func (a *App) shortcutConfig(id ShortcutID) ShortcutConfig { + if a.state.Shortcuts != nil { + if cfg, ok := a.state.Shortcuts[string(id)]; ok { + return cfg + } + } + return ShortcutConfig{} +} + +// effectiveShortcut returns the active modifiers, key, and whether the shortcut is disabled. +func (a *App) effectiveShortcut(id ShortcutID) (mods ui.Modifiers, key ui.Key, disabled bool) { + def, ok := LookupShortcut(id) + if !ok { + return 0, ui.KeyUnknown, true + } + cfg := a.shortcutConfig(id) + if cfg.Disabled { + return 0, ui.KeyUnknown, true + } + if cfg.Custom && cfg.Key != ui.KeyUnknown { + return cfg.Mods, cfg.Key, false + } + return def.DefaultMods, def.DefaultKey, false +} + +// isShortcutTriggered reports whether the shortcut for id fired in context c. +func (a *App) isShortcutTriggered(id ShortcutID, c *ui.Context) bool { + if a.state.ShortcutsOff { + return false + } + mods, key, disabled := a.effectiveShortcut(id) + if disabled || key == ui.KeyUnknown { + return false + } + return c.Shortcut(mods, key) +} + +// shortcutLabel returns the formatted label for the shortcut, or "" if disabled or turned off. +func (a *App) shortcutLabel(id ShortcutID) string { + if a.state.ShortcutsOff { + return "" + } + mods, key, disabled := a.effectiveShortcut(id) + if disabled || key == ui.KeyUnknown { + return "" + } + return FormatKey(mods, key) +} + +// setShortcutDisabled enables or disables a single shortcut. +func (a *App) setShortcutDisabled(id ShortcutID, disabled bool) { + if a.state.Shortcuts == nil { + a.state.Shortcuts = make(map[string]ShortcutConfig) + } + cfg := a.state.Shortcuts[string(id)] + cfg.Disabled = disabled + a.state.Shortcuts[string(id)] = cfg + a.saveState() +} + +// isTerminalKey reports whether mods and key conflict with essential terminal keys. +func isTerminalKey(mods ui.Modifiers, key ui.Key) bool { + // Ctrl+C is essential for terminal interrupt (SIGINT) on Windows and Linux + if (mods&ui.Ctrl != 0 || (runtime.GOOS != "darwin" && mods&ui.Cmd != 0)) && key == ui.KeyC { + return true + } + return false +} + +// setShortcutKey changes the key combination of a shortcut. +// Rejects combinations without modifiers, terminal-reserved keys, and conflicts. +func (a *App) setShortcutKey(id ShortcutID, text string) error { + mods, key, err := ParseKey(text) + if err != nil { + return err + } + if isTerminalKey(mods, key) { + return fmt.Errorf("%s is reserved for the terminal", FormatKey(mods, key)) + } + if conflict, found := a.findShortcutConflict(id, mods, key); found { + return fmt.Errorf("%s conflicts with %s", FormatKey(mods, key), conflict.Name) + } + if a.state.Shortcuts == nil { + a.state.Shortcuts = make(map[string]ShortcutConfig) + } + cfg := a.state.Shortcuts[string(id)] + cfg.Custom = true + cfg.Mods = mods + cfg.Key = key + cfg.Text = FormatKey(mods, key) + a.state.Shortcuts[string(id)] = cfg + a.saveState() + return nil +} + +// resetShortcut restores a shortcut to its factory default. +func (a *App) resetShortcut(id ShortcutID) { + if a.state.Shortcuts != nil { + delete(a.state.Shortcuts, string(id)) + a.saveState() + } +} + +// resetAllShortcuts enables all shortcuts and restores their default bindings. +func (a *App) resetAllShortcuts() { + a.state.ShortcutsOff = false + a.state.Shortcuts = nil + a.saveState() +} + +// hasCustomShortcuts reports whether any shortcut is disabled, custom, or master switch is off. +func (a *App) hasCustomShortcuts() bool { + if a.state.ShortcutsOff { + return true + } + return len(a.state.Shortcuts) > 0 +} + +// findShortcutConflict checks if mods and key are already used by another active shortcut. +func (a *App) findShortcutConflict(id ShortcutID, mods ui.Modifiers, key ui.Key) (ShortcutDef, bool) { + for _, def := range GlobalShortcuts { + if def.ID == id { + continue + } + otherMods, otherKey, disabled := a.effectiveShortcut(def.ID) + if !disabled && otherMods == mods && otherKey == key { + return def, true + } + } + return ShortcutDef{}, false +} diff --git a/ui/shortcuts_dialog.go b/ui/shortcuts_dialog.go new file mode 100644 index 00000000..e4d35b91 --- /dev/null +++ b/ui/shortcuts_dialog.go @@ -0,0 +1,186 @@ +package ui + +import ( + "github.com/egoist/mygo/ui" + + "github.com/enowx/enowx/ui/icon" + "github.com/enowx/enowx/ui/theme" + "github.com/enowx/enowx/ui/widget" +) + +type shortcutDialogState struct { + open bool + editingID ShortcutID + editText string + editErr string +} + +// openShortcutSheet opens the keyboard shortcuts customization dialog. +func (a *App) openShortcutSheet(initialID ...ShortcutID) { + f := &shortcutDialogState{open: true} + if len(initialID) > 0 { + id := initialID[0] + f.editingID = id + mods, key, _ := a.effectiveShortcut(id) + f.editText = FormatKey(mods, key) + } + a.shortcutsForm = f +} + +// shortcutDialog draws the customizable shortcut form sheet. +func (a *App) shortcutDialog(c *ui.Context) { + f := a.shortcutsForm + if f == nil { + return + } + if !f.open { + a.shortcutsForm = nil + return + } + + widget.FormSheet(c, &f.open, 600, "Keyboard shortcuts", + "Customize keyboard shortcuts or disable the ones you don't need.", + func() { + // Master toggle + masterOn := !a.state.ShortcutsOff + if switchRowKey(c, "shortcuts-master", &masterOn, "Enable keyboard shortcuts", + "When turned off, no application keyboard shortcuts will trigger.") { + a.state.ShortcutsOff = !masterOn + a.saveState() + } + + ui.Box(c).Height(theme.Rule).FillWidth().Shrink(0).Background(theme.Border).MarginY(theme.S3) + + ui.Column(c.Key("shortcuts-list")).FillWidth().Gap(theme.S2).Children(func() { + for _, def := range GlobalShortcuts { + a.shortcutDialogRow(c, f, def) + } + }) + }, + func() { + if a.hasCustomShortcuts() { + if widget.GhostButton(c.Key("reset-all-shortcuts"), "Reset all to defaults").Clicked() { + a.confirm("Reset all shortcuts to defaults?", "All custom shortcut key combinations will be restored to their factory defaults.", "Reset all", func() { + a.resetAllShortcuts() + f.editingID = "" + f.editErr = "" + }) + } + } + ui.Spacer(c) + if widget.Button(c.Key("done-shortcuts"), widget.Secondary, nil, "Done", "").Clicked() { + f.open = false + } + }, + ) +} + +func (a *App) shortcutDialogRow(c *ui.Context, f *shortcutDialogState, def ShortcutDef) { + cfg := a.shortcutConfig(def.ID) + mods, key, disabled := a.effectiveShortcut(def.ID) + globallyOff := a.state.ShortcutsOff + + ui.Column(c.Key(string(def.ID))).FillWidth().Padding(theme.S2, theme.S3). + Radius(theme.RadiusSmall).Background(theme.Fade(theme.Border, 0.4)).Gap(theme.S2).Children(func() { + ui.Row(c.Key("header")).FillWidth().Gap(theme.S3).AlignItems(ui.Center).Children(func() { + // Individual shortcut switch + on := !cfg.Disabled && !globallyOff + sw := on + if globallyOff { + // Master switch is off, so individual switch cannot be enabled + widget.Switch(c.Key("switch-"+string(def.ID)), &sw, def.Name) + } else { + if widget.Switch(c.Key("switch-"+string(def.ID)), &sw, def.Name) { + a.setShortcutDisabled(def.ID, !sw) + } + } + + // Name and Description + ui.Column(c).Grow(1).MinWidth(0).Children(func() { + ui.Row(c).Gap(theme.S2).AlignItems(ui.Center).Children(func() { + ui.Text(c, def.Name).FontSize(theme.TextUI).FontWeight(500) + if cfg.Custom { + widget.Chip(c, "Custom", ui.Color{}) + } + if disabled || globallyOff { + widget.Chip(c, "Off", ui.Color{}) + } + }) + ui.Text(c, def.Description).FontSize(theme.TextLabel).TextColor(theme.TextSoft) + }) + + // Actions: Current shortcut pill and edit/reset buttons + if f.editingID != def.ID { + keyStr := FormatKey(mods, key) + if keyStr == "" || disabled || globallyOff { + keyStr = "None" + } + ui.Text(c, keyStr).FontSize(theme.TextLabel).TextColor(theme.TextSoft). + Padding(2, 6).Radius(theme.RadiusSmall).Background(theme.Border) + + if !globallyOff { + if widget.GhostButton(c.Key("btn-edit-"+string(def.ID)), "Change").Clicked() { + f.editingID = def.ID + f.editText = FormatKey(mods, key) + f.editErr = "" + } + if cfg.Custom || cfg.Disabled { + if widget.GhostButton(c.Key("btn-reset-"+string(def.ID)), "Reset").Clicked() { + a.resetShortcut(def.ID) + f.editErr = "" + } + } + } + } + }) + + // Inline editing panel + if f.editingID == def.ID && !globallyOff { + ui.Column(c.Key("edit-panel")).FillWidth().Gap(theme.S2).PaddingY(theme.S2).Children(func() { + ui.Row(c).FillWidth().Gap(theme.S2).AlignItems(ui.Center).Children(func() { + ui.Row(c).Grow(1).MinWidth(0).Children(func() { + widget.Input(c.Key("key-input"), &f.editText, "e.g. Ctrl+Shift+K") + }) + if widget.Button(c.Key("apply-key"), widget.Primary, nil, "Apply", "").Clicked() { + if err := a.setShortcutKey(def.ID, f.editText); err != nil { + f.editErr = err.Error() + } else { + f.editingID = "" + f.editErr = "" + } + } + if widget.GhostButton(c.Key("cancel-key"), "Cancel").Clicked() { + f.editingID = "" + f.editErr = "" + } + }) + + // Check potential conflict + if f.editText != "" { + if testMods, testKey, err := ParseKey(f.editText); err == nil { + if isTerminalKey(testMods, testKey) { + ui.Row(c).Gap(theme.S1).AlignItems(ui.Center).Children(func() { + ui.Icon(c, icon.Alert).FontSize(12).TextColor(theme.Error) + ui.Text(c, "Reserved for terminal control"). + FontSize(theme.TextLabel).TextColor(theme.Error) + }) + } else if conflict, found := a.findShortcutConflict(def.ID, testMods, testKey); found { + ui.Row(c).Gap(theme.S1).AlignItems(ui.Center).Children(func() { + ui.Icon(c, icon.Alert).FontSize(12).TextColor(theme.Error) + ui.Text(c, "Conflicts with "+conflict.Name). + FontSize(theme.TextLabel).TextColor(theme.Error) + }) + } + } + } + + if f.editErr != "" { + ui.Row(c).Gap(theme.S1).AlignItems(ui.Center).Children(func() { + ui.Icon(c, icon.Alert).FontSize(12).TextColor(theme.Error) + ui.Text(c, f.editErr).FontSize(theme.TextLabel).TextColor(theme.Error) + }) + } + }) + } + }) +} diff --git a/ui/shortcuts_test.go b/ui/shortcuts_test.go new file mode 100644 index 00000000..ad28a193 --- /dev/null +++ b/ui/shortcuts_test.go @@ -0,0 +1,232 @@ +package ui + +import ( + "encoding/json" + "testing" + + "github.com/egoist/mygo/ui" +) + +func TestParseAndFormatKey(t *testing.T) { + tests := []struct { + input string + wantKey ui.Key + wantMods ui.Modifiers + expectError bool + }{ + {"Ctrl+K", ui.KeyK, ui.Ctrl, false}, + {"Ctrl+Shift+D", ui.KeyD, ui.Ctrl | ui.Shift, false}, + {"Alt+P", ui.KeyP, ui.Alt, false}, + {"Shift+Enter", ui.KeyEnter, ui.Shift, false}, + {"Ctrl+F12", ui.KeyF12, ui.Ctrl, false}, + {"Ctrl+[", ui.KeyBracketLeft, ui.Ctrl, false}, + {"Ctrl+]", ui.KeyBracketRight, ui.Ctrl, false}, + {"⌘K", ui.KeyK, ui.Cmd, false}, + {"⌘⇧D", ui.KeyD, ui.Cmd | ui.Shift, false}, + {"", 0, 0, true}, + {"K", 0, 0, true}, // Bare letter without modifier must error + {"Enter", 0, 0, true}, // Bare key without modifier must error + {"Ctrl", 0, 0, true}, + {"Ctrl+Shift", 0, 0, true}, + {"UnknownKey123", 0, 0, true}, + {"Ctrl+Shift+Alt+Unknown", 0, 0, true}, + } + + for _, tc := range tests { + mods, key, err := ParseKey(tc.input) + if tc.expectError { + if err == nil { + t.Errorf("ParseKey(%q): expected error, got nil", tc.input) + } + continue + } + if err != nil { + t.Errorf("ParseKey(%q): unexpected error: %v", tc.input, err) + continue + } + if key != tc.wantKey { + t.Errorf("ParseKey(%q): key = %v, want %v", tc.input, key, tc.wantKey) + } + if mods&tc.wantMods != tc.wantMods { + t.Errorf("ParseKey(%q): mods = %v, want %v", tc.input, mods, tc.wantMods) + } + + formatted := FormatKey(mods, key) + if formatted == "" { + t.Errorf("FormatKey(%v, %v) returned empty string", mods, key) + } + } +} + +func TestAppShortcutsConfigAndState(t *testing.T) { + app := New(Options{}) + + // 1. Initial defaults + mods, key, disabled := app.effectiveShortcut(ShortcutPalette) + if disabled { + t.Fatal("expected ShortcutPalette to be enabled by default") + } + if key != ui.KeyK { + t.Fatalf("expected ShortcutPalette default key to be ui.KeyK, got %v", key) + } + if mods&ui.Cmd == 0 { + t.Fatalf("expected ShortcutPalette default mods to include ui.Cmd, got %v", mods) + } + if app.shortcutLabel(ShortcutPalette) == "" { + t.Fatal("expected non-empty shortcut label for ShortcutPalette") + } + if app.hasCustomShortcuts() { + t.Fatal("expected no custom shortcuts initially") + } + + // 2. Disable individual shortcut + app.setShortcutDisabled(ShortcutPalette, true) + if !app.hasCustomShortcuts() { + t.Fatal("expected hasCustomShortcuts to be true after disabling one") + } + _, _, disabled = app.effectiveShortcut(ShortcutPalette) + if !disabled { + t.Fatal("expected ShortcutPalette to be disabled") + } + if app.shortcutLabel(ShortcutPalette) != "" { + t.Fatalf("expected empty label for disabled shortcut, got %q", app.shortcutLabel(ShortcutPalette)) + } + + // 3. Re-enable and customize key + app.setShortcutDisabled(ShortcutPalette, false) + if err := app.setShortcutKey(ShortcutPalette, "Ctrl+Shift+K"); err != nil { + t.Fatalf("unexpected error setting shortcut key: %v", err) + } + mods, key, disabled = app.effectiveShortcut(ShortcutPalette) + if disabled { + t.Fatal("expected shortcut to remain enabled after key change") + } + if key != ui.KeyK || mods&(ui.Ctrl|ui.Shift) != (ui.Ctrl|ui.Shift) { + t.Fatalf("expected custom mods and key, got mods=%v key=%v", mods, key) + } + + // 4. Refuse conflict with another existing shortcut + if err := app.setShortcutKey(ShortcutQuickOpen, "Ctrl+Shift+K"); err == nil { + t.Fatal("expected setShortcutKey to refuse conflicting shortcut Ctrl+Shift+K") + } + + // 5. Refuse reserved terminal key (Ctrl+C) + if err := app.setShortcutKey(ShortcutQuickOpen, "Ctrl+C"); err == nil { + t.Fatal("expected setShortcutKey to refuse reserved terminal key Ctrl+C") + } + + // 6. Master switch disables all + app.state.ShortcutsOff = true + if app.shortcutLabel(ShortcutPalette) != "" { + t.Fatal("expected empty label when master switch is off") + } + if app.shortcutLabel(ShortcutNewSession) != "" { + t.Fatal("expected empty label for all shortcuts when master switch is off") + } + + // 7. Reset all shortcuts + app.resetAllShortcuts() + if app.state.ShortcutsOff { + t.Fatal("expected ShortcutsOff to be false after reset") + } + if app.hasCustomShortcuts() { + t.Fatal("expected hasCustomShortcuts to be false after reset") + } + _, key, disabled = app.effectiveShortcut(ShortcutPalette) + if disabled || key != ui.KeyK { + t.Fatalf("expected reset to restore default ui.KeyK, got %v (disabled: %v)", key, disabled) + } +} + +func TestShortcutStateJSONPersistence(t *testing.T) { + st := appState{ + ShortcutsOff: true, + Shortcuts: map[string]ShortcutConfig{ + string(ShortcutPalette): { + Disabled: true, + }, + string(ShortcutNewSession): { + Custom: true, + Mods: ui.Ctrl | ui.Shift, + Key: ui.KeyT, + Text: "Ctrl+Shift+T", + }, + }, + } + + data, err := json.Marshal(st) + if err != nil { + t.Fatalf("json.Marshal failed: %v", err) + } + + var restored appState + if err := json.Unmarshal(data, &restored); err != nil { + t.Fatalf("json.Unmarshal failed: %v", err) + } + + if !restored.ShortcutsOff { + t.Fatal("expected restored ShortcutsOff to be true") + } + if len(restored.Shortcuts) != 2 { + t.Fatalf("expected 2 restored shortcuts, got %d", len(restored.Shortcuts)) + } + palCfg := restored.Shortcuts[string(ShortcutPalette)] + if !palCfg.Disabled { + t.Fatal("expected restored ShortcutPalette to be disabled") + } + newCfg := restored.Shortcuts[string(ShortcutNewSession)] + if !newCfg.Custom || newCfg.Key != ui.KeyT || newCfg.Text != "Ctrl+Shift+T" { + t.Fatalf("restored ShortcutNewSession mismatch: %+v", newCfg) + } +} + +func TestShortcutDialogUI(t *testing.T) { + app := New(Options{}) + + // Open dialog + app.openShortcutSheet(ShortcutPalette) + if app.shortcutsForm == nil || !app.shortcutsForm.open { + t.Fatal("expected shortcut dialog to be open") + } + if app.shortcutsForm.editingID != ShortcutPalette { + t.Fatalf("expected editingID to be %s, got %s", ShortcutPalette, app.shortcutsForm.editingID) + } + + tt := ui.NewTester(func(c *ui.Context) { + ui.Column(c).Width(700).Height(800).Children(func() { + app.shortcutDialog(c) + }) + }, 700, 800) + tt.Frame() + + if !tt.HasText("Keyboard shortcuts") { + t.Fatalf("expected dialog title in %q", tt.Texts()) + } + if !tt.HasText("Enable keyboard shortcuts") { + t.Fatalf("expected master switch in %q", tt.Texts()) + } + if !tt.HasText("Command palette") { + t.Fatalf("expected Command palette row in %q", tt.Texts()) + } + + // Change key to Ctrl+Shift+K + app.shortcutsForm.editText = "Ctrl+Shift+K" + if err := tt.Click("Apply"); err != nil { + t.Fatalf("clicking Apply failed: %v", err) + } + tt.Frame() + + cfg := app.shortcutConfig(ShortcutPalette) + if !cfg.Custom || cfg.Key != ui.KeyK { + t.Fatalf("expected custom key to be applied, got %+v", cfg) + } + + // Click Done to close + if err := tt.Click("Done"); err != nil { + t.Fatalf("clicking Done failed: %v", err) + } + tt.Frame() + if app.shortcutsForm != nil { + t.Fatal("expected dialog to be closed after clicking Done") + } +} diff --git a/ui/state.go b/ui/state.go index 0ed6a7d9..7621b2cc 100644 --- a/ui/state.go +++ b/ui/state.go @@ -100,6 +100,10 @@ type appState struct { HideSessions bool `json:"hideSessions,omitempty"` // GOA shows GOD of Agents mode (goa.go). GOA bool `json:"goa,omitempty"` + // ShortcutsOff disables all application shortcuts when true. + ShortcutsOff bool `json:"shortcutsOff,omitempty"` + // Shortcuts holds per-shortcut custom key combinations and disable states. + Shortcuts map[string]ShortcutConfig `json:"shortcuts,omitempty"` } // palette is the palette the user picked, with their accent. diff --git a/ui/view.go b/ui/view.go index a0a0a321..47f833cb 100644 --- a/ui/view.go +++ b/ui/view.go @@ -121,28 +121,29 @@ func (a *App) view(c *ui.Context) { a.cloneDialog(c) a.noteImportDialog(c) a.noteExportDialog(c) + a.shortcutDialog(c) a.confirmDialog(c) // last: what a dialog asks shows over it a.saveState() } func (a *App) shortcuts(c *ui.Context) { - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyH) && a.page == "" { + if a.isShortcutTriggered(ShortcutHibernate, c) && a.page == "" { if s, ok := a.sessionByID(a.selected); ok && canHibernate(s) { a.hibernate(a.hibernateTargets(s)) } } - if c.Shortcut(ui.Cmd, ui.KeyN) { + if a.isShortcutTriggered(ShortcutNewSession, c) { if p, ok := a.currentProject(); ok { a.openNewSession(p) } } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyEnter) { + if a.isShortcutTriggered(ShortcutMaximize, c) { a.toggleMaximized(a.selected) } - if c.Shortcut(ui.Cmd, ui.KeyO) { + if a.isShortcutTriggered(ShortcutOpenFolder, c) { a.openFolder() } - if c.Shortcut(ui.Cmd, ui.KeyK) { + if a.isShortcutTriggered(ShortcutPalette, c) { switch { case a.page == pageNotes && !a.palette.open && a.notes.OpenJump(): // On a page of notes, it jumps to a section of it. @@ -152,32 +153,32 @@ func (a *App) shortcuts(c *ui.Context) { a.openPalette() } } - if c.Shortcut(ui.Cmd, ui.KeyP) { + if a.isShortcutTriggered(ShortcutQuickOpen, c) { if a.quick.open { a.quick.open = false } else { a.openQuickOpen() } } - if c.Shortcut(ui.Cmd, ui.KeyB) { + if a.isShortcutTriggered(ShortcutSidebar, c) { a.state.RailWide = !a.state.RailWide } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyBracketRight) { + if a.isShortcutTriggered(ShortcutNextSession, c) { a.stepSession(1) } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyBracketLeft) { + if a.isShortcutTriggered(ShortcutPrevSession, c) { a.stepSession(-1) } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyL) { + if a.isShortcutTriggered(ShortcutSplitView, c) { a.setSplit(!a.splitOn()) } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyD) { + if a.isShortcutTriggered(ShortcutSidePanel, c) { a.togglePanel() } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyP) { + if a.isShortcutTriggered(ShortcutBrowserTool, c) { a.toggleTool(panelBrowser) } - if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyS) { + if a.isShortcutTriggered(ShortcutSessionsPanel, c) { a.toggleSessionsPanel() } }