diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..990f62db --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,57 @@ +version: "2" + +run: + timeout: 5m + +linters: + default: standard + enable: + - bodyclose + - errorlint + - misspell + settings: + staticcheck: + # Bug (SA) and simplification (S) checks only. ST style checks + # conflict with deliberate complete, capitalized user-facing + # messages, and QF quickfixes are optional rewrites; neither should + # gate contributions. S1005 conflicts with errcheck: receiving an + # error result purely for synchronization is discarded explicitly + # with _ = <-ch rather than silently. + checks: + - all + - -ST* + - -QF* + - -S1005 + errcheck: + exclude-functions: + # CLI usage/status output: there is nothing useful to do if writing + # the message itself fails. + - fmt.Fprint + - fmt.Fprintf + - fmt.Fprintln + exclusions: + rules: + # Close on cleanup paths (pipe ends after spawning helpers, + # connections and files being discarded) is best-effort teardown + # with no actionable recovery. Closes whose errors protect data + # (flushing writers, saved configuration, the debug database) + # are handled explicitly at those call sites and must stay handled. + - text: 'Error return value of `[^`]+\.Close` is not checked' + linters: + - errcheck + # Tests routinely ignore fixture teardown errors, and assert exact + # sentinel identity on errors they constructed unwrapped. + # Production code must still handle errors or discard them + # explicitly with _ =. + - path: _test\.go + linters: + - errcheck + - errorlint + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + +formatters: + enable: + - gofmt diff --git a/AGENTS.md b/AGENTS.md index c75f1904..441d003c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,14 +40,20 @@ libraries for libevdev, X11, libvterm, and ALSA. See `README.md` for runtime dep - `./fenrir -x`: run in an X11 terminal with `DISPLAY` and `WINDOWID` available. - `go test ./...`: run the Go test suite. - `go test ./internal/reader`: run a focused package's tests. +- `go vet ./...`: check common Go errors. +- `golangci-lint run ./...`: run the lint gate in `.golangci.yml` (the same + policy as Cthulhu and common). Build the linter with a Go at least as new as + the project's, or it reports typecheck errors. - `go run ./tools/translations check`: validate extracted messages and catalogs; requires GNU gettext. ## Coding Style & Naming Conventions -Format Go changes with `gofmt` and preserve tab indentation. Follow neighboring -code: camelCase locals, snake_case helpers, and capitalized exported identifiers -where required by Go visibility. Preserve existing license headers. Keep changes -focused and use existing configuration and presentation APIs. +Follow Go conventions: `gofmt -s`, Effective Go, and Go Code Review Comments. +Exported names are PascalCase and unexported names are camelCase, including +functions and methods. Do not use snake_case identifiers. Initialisms keep one +case (`ID`, `URL`). Handle errors or discard them explicitly with `_ =` and a +short reason. Preserve existing license headers. Keep changes focused and use +existing configuration and presentation APIs. Keep interface messages translatable through `internal/i18n`; exclude screen contents and protocol identifiers. After message changes, run diff --git a/README.md b/README.md index 9caf5b62..6387f0d4 100644 --- a/README.md +++ b/README.md @@ -406,6 +406,9 @@ gettext installed, run this read-only check from the checkout root: go run ./tools/translations check ``` +To add a language or update a catalog, see the +[translation guide](https://git.stormux.org/storm/screenreader-common/src/branch/master/TRANSLATIONS.md), shared with Cthulhu. + ## Development Run the Go tests from the checkout root: @@ -483,7 +486,7 @@ The Default choice remains available even when no named profiles are saved. Removing a preset leaves the configured primary voice in place. Application settings do not edit the global preset catalog. -Profiles and their editor are shared through `screenreader-common v0.7.0`, +Profiles and their editor are shared through `screenreader-common v0.8.0`, pinned for standalone builds. A sibling Go workspace can use local shared-module changes during development. diff --git a/cmd/fenrir/daemon_linux.go b/cmd/fenrir/daemon_linux.go index 72778a74..8a0a9f37 100644 --- a/cmd/fenrir/daemon_linux.go +++ b/cmd/fenrir/daemon_linux.go @@ -36,17 +36,17 @@ type daemonStatus struct { // Re-exec rather than forking a running Go runtime. Keep the working directory // and environment so relative configuration paths and audio access still work. -func start_daemon(args []string, stderr io.Writer) int { +func startDaemon(args []string, stderr io.Writer) int { executable, err := os.Executable() if err != nil { fmt.Fprintln(stderr, "fenrir: daemon executable:", err) return 1 } child := exec.Command(executable, append(append([]string{}, args...), "-f")...) - return launch_daemon(child, stderr) + return launchDaemon(child, stderr) } -func launch_daemon(child *exec.Cmd, stderr io.Writer) int { +func launchDaemon(child *exec.Cmd, stderr io.Writer) int { reader, writer, err := os.Pipe() if err != nil { fmt.Fprintln(stderr, "fenrir: daemon startup pipe:", err) @@ -66,25 +66,28 @@ func launch_daemon(child *exec.Cmd, stderr io.Writer) int { var status daemonStatus if err := json.NewDecoder(reader).Decode(&status); err != nil { // A child that cannot report readiness must not keep input grabbed. - child.Process.Kill() - child.Wait() + // Best effort: the startup failure is what gets reported. + _ = child.Process.Kill() + _ = child.Wait() fmt.Fprintln(stderr, "fenrir: daemon startup:", err) return 1 } if status.Code != 0 { - child.Wait() + // The child's reported status is authoritative; Wait only reaps it. + _ = child.Wait() fmt.Fprint(stderr, status.Error) return status.Code } - child.Process.Release() + // The daemon keeps running; releasing the handle cannot change that. + _ = child.Process.Release() return 0 } -func run_daemon_child(args []string, stdout io.Writer, statusFile *os.File) int { +func runDaemonChild(args []string, stdout io.Writer, statusFile *os.File) int { defer statusFile.Close() var diagnostics bytes.Buffer reported := false - code := run_with_ready(args, stdout, &diagnostics, func() error { + code := runWithReady(args, stdout, &diagnostics, func() error { if err := json.NewEncoder(statusFile).Encode(daemonStatus{}); err != nil { return fmt.Errorf("report daemon readiness: %w", err) } @@ -92,7 +95,8 @@ func run_daemon_child(args []string, stdout io.Writer, statusFile *os.File) int return statusFile.Close() }) if !reported { - json.NewEncoder(statusFile).Encode(daemonStatus{Code: code, Error: diagnostics.String()}) + // If the parent cannot read this, it reports its own startup error. + _ = json.NewEncoder(statusFile).Encode(daemonStatus{Code: code, Error: diagnostics.String()}) } return code } diff --git a/cmd/fenrir/daemon_linux_test.go b/cmd/fenrir/daemon_linux_test.go index 31a79d90..2f286115 100644 --- a/cmd/fenrir/daemon_linux_test.go +++ b/cmd/fenrir/daemon_linux_test.go @@ -41,11 +41,11 @@ func TestDaemonProcess(t *testing.T) { recordPath := os.Args[len(os.Args)-1] switch mode { case "failure": - os.Exit(run_daemon_child([]string{"--unknown"}, os.Stdout, statusFile)) + os.Exit(runDaemonChild([]string{"--unknown"}, os.Stdout, statusFile)) case "crash": os.Exit(17) case "ready": - ctx, stop := termination_context() + ctx, stop := terminationContext() defer stop() sessionID, _, err := syscall.Syscall(syscall.SYS_GETSID, 0, 0, 0) if err != 0 || int(sessionID) != os.Getpid() || syscall.Getpgrp() != os.Getpid() { @@ -84,7 +84,7 @@ func TestDaemonDetachesAndReportsReadiness(t *testing.T) { child := exec.Command(os.Args[0], "-test.run=^TestDaemonProcess$", "--", "ready", recordPath) child.Dir = root var stderr bytes.Buffer - if status := launch_daemon(child, &stderr); status != 0 { + if status := launchDaemon(child, &stderr); status != 0 { t.Fatal(status, stderr.String()) } record, err := os.ReadFile(recordPath) @@ -140,7 +140,7 @@ func TestDaemonStartupFailuresReturnToLauncher(t *testing.T) { wantText = "start daemon:" } var stderr bytes.Buffer - if code := launch_daemon(child, &stderr); code != wantCode || !strings.Contains(stderr.String(), wantText) { + if code := launchDaemon(child, &stderr); code != wantCode || !strings.Contains(stderr.String(), wantText) { t.Fatal(code, stderr.String()) } }) diff --git a/cmd/fenrir/main.go b/cmd/fenrir/main.go index b2230816..4d858dac 100644 --- a/cmd/fenrir/main.go +++ b/cmd/fenrir/main.go @@ -19,6 +19,7 @@ package main import ( "context" + "errors" "flag" "fmt" "io" @@ -43,19 +44,19 @@ func main() { i18n.Use(i18n.New(i18n.LocaleDir, i18n.Language())) if os.Getenv(daemonStatusEnv) == "3" { // Do not pass the private startup channel to scripts or synthesizers. - os.Unsetenv(daemonStatusEnv) + _ = os.Unsetenv(daemonStatusEnv) // Fails only for invalid names. syscall.CloseOnExec(3) statusFile := os.NewFile(3, "daemon startup") - os.Exit(run_daemon_child(os.Args[1:], os.Stdout, statusFile)) + os.Exit(runDaemonChild(os.Args[1:], os.Stdout, statusFile)) } os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) } func run(args []string, stdout, stderr io.Writer) int { - return run_with_ready(args, stdout, stderr, nil) + return runWithReady(args, stdout, stderr, nil) } -func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) int { +func runWithReady(args []string, stdout, stderr io.Writer, ready func() error) int { flags := flag.NewFlagSet("fenrir", flag.ContinueOnError) flags.SetOutput(stderr) showVersion := flags.Bool("version", false, "print the version and release channel") @@ -88,7 +89,7 @@ func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) flags.PrintDefaults() } if err := flags.Parse(args); err != nil { - if err == flag.ErrHelp { + if errors.Is(err, flag.ErrHelp) { return 0 } return 2 @@ -101,11 +102,11 @@ func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) fmt.Fprintln(stdout, "fenrir", version.Label()) return 0 } - if err := initialize_home(); err != nil { + if err := initializeHome(); err != nil { fmt.Fprintln(stderr, "fenrir: settings:", err) return 2 } - settings, path, err := load_settings(flags, *configPath, *rate, *module, devices, *keyboardLayout, *driver, *punctuationProfile) + settings, path, err := loadSettings(flags, *configPath, *rate, *module, devices, *keyboardLayout, *driver, *punctuationProfile) if err != nil { fmt.Fprintln(stderr, "fenrir: settings:", path, err) return 2 @@ -122,14 +123,14 @@ func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) fmt.Fprintln(stderr, "fenrir: -x does not use keyboard.devices or --input-device") return 2 } - bindings, bindingPath, err := load_keyboard(settings.Keyboard.Layout) + bindings, bindingPath, err := loadKeyboard(settings.Keyboard.Layout) if err != nil { fmt.Fprintln(stderr, "fenrir: keyboard layout:", bindingPath, err) return 2 } - modifierRouter, modifierErr := input.New_router(bindings) + modifierRouter, modifierErr := input.NewRouter(bindings) if modifierErr == nil { - modifierErr = modifierRouter.Configure_modifiers(settings.Keyboard.FenrirKeys, settings.General.ScriptKeys) + modifierErr = modifierRouter.ConfigureModifiers(settings.Keyboard.FenrirKeys, settings.General.ScriptKeys) } if modifierErr != nil { fmt.Fprintln(stderr, "fenrir: keyboard modifiers:", modifierErr) @@ -154,7 +155,7 @@ func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) logOutput, logLevel = file, slog.LevelDebug } if !*foreground && !*terminalMode && ready == nil { - return start_daemon(args, stderr) + return startDaemon(args, stderr) } if ready != nil && *debugFile == "" { logOutput = io.Discard @@ -172,12 +173,12 @@ func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) }, }))) slog.Info("reader starting", "pid", os.Getpid(), "terminal_mode", *terminalMode, "at", time.Now()) - ctx, stop := termination_context() + ctx, stop := terminationContext() defer stop() if *terminalMode { - err = app.Start_terminal(ctx, settings, path, bindings) + err = app.StartTerminal(ctx, settings, path, bindings) } else { - err = app.Start_with_ready(ctx, settings, path, bindings, ready) + err = app.StartWithReady(ctx, settings, path, bindings, ready) } if err != nil { if *debugFile != "" { @@ -190,7 +191,7 @@ func run_with_ready(args []string, stdout, stderr io.Writer, ready func() error) return 0 } -func termination_context() (context.Context, func()) { +func terminationContext() (context.Context, func()) { ctx, cancel := context.WithCancel(context.Background()) signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTSTP) @@ -211,7 +212,7 @@ func termination_context() (context.Context, func()) { } } -func load_keyboard(layout string) (input.Layout, string, error) { +func loadKeyboard(layout string) (input.Layout, string, error) { home, err := os.UserHomeDir() if err != nil { return input.Layout{}, "", err @@ -221,19 +222,19 @@ func load_keyboard(layout string) (input.Layout, string, error) { return input.Layout{}, "", err } bundledDirectory := filepath.Join(filepath.Dir(executable), "config", "keyboard") - paths, err := input.Layout_paths(layout, home, os.Geteuid(), bundledDirectory) + paths, err := input.LayoutPaths(layout, home, os.Geteuid(), bundledDirectory) if err != nil { return input.Layout{}, "", err } - return input.Load_bindings(paths) + return input.LoadBindings(paths) } -func load_settings(flags *flag.FlagSet, requested string, rate int, module string, devices []string, keyboardLayout string, driver string, punctuationProfile string) (config.Settings, string, error) { +func loadSettings(flags *flag.FlagSet, requested string, rate int, module string, devices []string, keyboardLayout string, driver string, punctuationProfile string) (config.Settings, string, error) { home, err := os.UserHomeDir() if err != nil { return config.Settings{}, "", err } - settings, path, err := config.Load_startup(requested, config.Paths(home, os.Geteuid())) + settings, path, err := config.LoadStartup(requested, config.Paths(home, os.Geteuid())) if err != nil { return config.Settings{}, path, err } @@ -259,7 +260,7 @@ func load_settings(flags *flag.FlagSet, requested string, rate int, module strin // Service managers need not export HOME. Resolve it once before configuration // discovery so all resources and child processes use the effective account's // home, while preserving explicitly supplied environments (including sudo). -func initialize_home() error { +func initializeHome() error { if os.Getenv("HOME") != "" { return nil } diff --git a/cmd/fenrir/main_test.go b/cmd/fenrir/main_test.go index e2d3c532..f05ee5ec 100644 --- a/cmd/fenrir/main_test.go +++ b/cmd/fenrir/main_test.go @@ -35,7 +35,7 @@ func TestStartupUsesAccountSaveDestination(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) flags := flag.NewFlagSet("fenrir", flag.ContinueOnError) - _, path, err := load_settings(flags, "", config.Defaults().Presentation.Speech.Rate, "", nil, "", "speech-dispatcher", "") + _, path, err := loadSettings(flags, "", config.Defaults().Presentation.Speech.Rate, "", nil, "", "speech-dispatcher", "") if expected := config.Paths(home, os.Geteuid())[0]; err != nil || path != expected { t.Fatalf("save destination=%q, want %q: %v", path, expected, err) } diff --git a/go.mod b/go.mod index ded9a85c..4b7128f3 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,9 @@ module git.stormux.org/storm/fenrir go 1.27.2 require ( - git.stormux.org/storm/screenreader-common v0.7.0 + git.stormux.org/storm/screenreader-common v0.8.0 github.com/jfreymuth/pulse v0.1.3 - github.com/leonelquinteros/gotext v1.8.0 github.com/pelletier/go-toml/v2 v2.4.3 ) + +require github.com/leonelquinteros/gotext v1.8.0 // indirect diff --git a/go.sum b/go.sum index 5df529d4..d706e0df 100644 --- a/go.sum +++ b/go.sum @@ -1,19 +1,5 @@ -git.stormux.org/storm/screenreader-common v0.1.1 h1:r/qcWUv4ODZ+XzXw1J+qe4hVnyr7MqH0W7L5tp6XOcE= -git.stormux.org/storm/screenreader-common v0.1.1/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.2.0 h1:PbGwyIi/nT0qwvscje4pvIIsAxDLBYwLV1eTXT36hxk= -git.stormux.org/storm/screenreader-common v0.2.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.3.0 h1:eWuSMf3lM8fB5RyegnsyHmdz1uP0CzPqMfFP8wonV3k= -git.stormux.org/storm/screenreader-common v0.3.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.4.0 h1:iq2BuC/d6EBiMh76WZK09De+sQjGk2TWDNw6p5zGHGE= -git.stormux.org/storm/screenreader-common v0.4.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.5.0 h1:OmplWVqpXWwPCQsi9f6tOxRjj/b5XDnSCch9RPzSh4s= -git.stormux.org/storm/screenreader-common v0.5.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.6.0 h1:iXsUBBjHOQTPu3ROTR9ysrPOi3iIXLMW3DCu6XZRTec= -git.stormux.org/storm/screenreader-common v0.6.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.6.1 h1:IVIVyihIjI38XWsxGlI3hwdSrNNSyGbxa9rPgfan0Ac= -git.stormux.org/storm/screenreader-common v0.6.1/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= -git.stormux.org/storm/screenreader-common v0.7.0 h1:AUrvGrAFwT+7TTZVqq6sgdEeESsHnj7gFt1xPtbARC4= -git.stormux.org/storm/screenreader-common v0.7.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= +git.stormux.org/storm/screenreader-common v0.8.0 h1:vMHgI9c+qT9yOKk1A/MP98GsXZpVpzKa6rrKzRe7D+Y= +git.stormux.org/storm/screenreader-common v0.8.0/go.mod h1:2LW1ooP+4sYH2ewpgutyUIzJPy2IlgfYFxNPS2L3Ul4= github.com/jfreymuth/pulse v0.1.3 h1:bc5TdxiB8E+2INnFjFWWgyfgXtz2IyNNNCX+Wt/ZD14= github.com/jfreymuth/pulse v0.1.3/go.mod h1:cpYspI6YljhkUf1WLXLLDmeaaPFc3CnGLjDZf9dZ4no= github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU= diff --git a/internal/app/app.go b/internal/app/app.go index 24a9e2d6..52227903 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -45,19 +45,19 @@ type Keyboards interface { Events() <-chan error Poll(bool, bool, func(input.Decision)) error Scan() error - Pass_next() + PassNext() Capture(bool) error - Update_modifiers([]string, []string) (bool, error) + UpdateModifiers([]string, []string) (bool, error) Close() error } type Speaker interface { Say(string) - Say_after(string, func(context.Context)) - Say_with_pitch(text string, pitch int) + SayAfter(string, func(context.Context)) + SayWithPitch(text string, pitch int) Configure(speech.Parameters) Interrupt() - Toggle_mute() bool + ToggleMute() bool Errors() <-chan error Close() } @@ -65,12 +65,12 @@ type Speaker interface { type SoundPlayer interface { // Play reports whether the cue was accepted, so unavailable cues use speech. Play(presentation.Cue) bool - Play_wait(context.Context, presentation.Cue) error - Play_progress(float64) bool - Play_indentation(int) bool - Discard_progress() - Clear_progress() - Set_volume(float64) + PlayWait(context.Context, presentation.Cue) error + PlayProgress(float64) bool + PlayIndentation(int) bool + DiscardProgress() + ClearProgress() + SetVolume(float64) Errors() <-chan error } diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 1d46e32e..c3c41389 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -108,9 +108,9 @@ type fakeSounds struct { missing map[presentation.Cue]bool } -func (f *fakeSounds) Set_volume(volume float64) { f.volume = volume } +func (f *fakeSounds) SetVolume(volume float64) { f.volume = volume } -func (f *fakeSounds) Play_wait(_ context.Context, cue presentation.Cue) error { +func (f *fakeSounds) PlayWait(_ context.Context, cue presentation.Cue) error { f.Play(cue) return nil } @@ -122,16 +122,16 @@ func (f *fakeSounds) Play(cue presentation.Cue) bool { f.cues = append(f.cues, cue) return true } -func (f *fakeSounds) Play_progress(value float64) bool { +func (f *fakeSounds) PlayProgress(value float64) bool { f.progress = append(f.progress, value) return true } -func (f *fakeSounds) Play_indentation(level int) bool { +func (f *fakeSounds) PlayIndentation(level int) bool { f.indentation = append(f.indentation, level) return true } -func (f *fakeSounds) Clear_progress() {} -func (f *fakeSounds) Discard_progress() {} +func (f *fakeSounds) ClearProgress() {} +func (f *fakeSounds) DiscardProgress() {} func (f *fakeSounds) Errors() <-chan error { return f.errors } func TestSoundFailureDoesNotStopInputOrSpeech(t *testing.T) { @@ -267,11 +267,11 @@ func TestStartupAndUnmuteUseSoundOrSpeech(t *testing.T) { func TestTemporarySilenceDropsOutputUntilFreshKeypress(t *testing.T) { for _, enabled := range []bool{false, true} { for _, restoreKey := range []uint16{input.KeyShift, input.KeyKP8, 30} { - bindings, _, err := input.Load_bindings([]string{"../../config/keyboard/desktop.toml"}) + bindings, _, err := input.LoadBindings([]string{"../../config/keyboard/desktop.toml"}) if err != nil { t.Fatal(err) } - router, err := input.New_router(bindings) + router, err := input.NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -502,13 +502,13 @@ func (f *fakeKeys) Capture(enabled bool) error { } return f.captureErr } -func (f *fakeKeys) Update_modifiers(reader, script []string) (bool, error) { +func (f *fakeKeys) UpdateModifiers(reader, script []string) (bool, error) { if f.updateModifiers != nil { return f.updateModifiers(reader, script) } return true, nil } -func (f *fakeKeys) Pass_next() { f.passed = true } +func (f *fakeKeys) PassNext() { f.passed = true } func (f *fakeKeys) Close() error { f.closed = true; return nil } type fakeVoice struct { @@ -524,11 +524,11 @@ func (f *fakeVoice) Configure(parameters speech.Parameters) { f.parameters = append(f.parameters, parameters) } -func (f *fakeVoice) Say_with_pitch(text string, pitch int) { +func (f *fakeVoice) SayWithPitch(text string, pitch int) { f.Say(text) } -func (f *fakeVoice) Say_after(text string, before func(context.Context)) { +func (f *fakeVoice) SayAfter(text string, before func(context.Context)) { if !f.muted { before(context.Background()) f.Say(text) @@ -544,7 +544,7 @@ func (f *fakeVoice) Say(text string) { } } func (f *fakeVoice) Interrupt() { f.interrupts++ } -func (f *fakeVoice) Toggle_mute() bool { f.muted = !f.muted; return f.muted } +func (f *fakeVoice) ToggleMute() bool { f.muted = !f.muted; return f.muted } func (f *fakeVoice) Errors() <-chan error { return f.errors } func (f *fakeVoice) Close() {} diff --git a/internal/app/application.go b/internal/app/application.go index 7d6035a4..05e49beb 100644 --- a/internal/app/application.go +++ b/internal/app/application.go @@ -82,7 +82,7 @@ type application struct { overrideTransition, overrideRestoreFailed, overrideDirty bool } -func new_application(ctx context.Context, source Source, keyboards Keyboards, voice Speaker, options RunOptions) (*application, error) { +func newApplication(ctx context.Context, source Source, keyboards Keyboards, voice Speaker, options RunOptions) (*application, error) { prompts, err := prompt.New(options.Settings.Prompt.ExactMatches, options.Settings.Prompt.CustomPatterns) if err != nil { return nil, err @@ -97,28 +97,28 @@ func new_application(ctx context.Context, source Source, keyboards Keyboards, vo speechAvailable: options.Settings.Presentation.Speech.Enabled, }, muted: !options.Settings.Presentation.Speech.Enabled, - quick: new_quick_settings(options.Settings.Presentation.Speech.Driver), saver: &settingsSaver{results: make(chan error, 1)}, + quick: newQuickSettings(options.Settings.Presentation.Speech.Driver), saver: &settingsSaver{results: make(chan error, 1)}, } if options.EffectiveSpeech != nil { - copy_speech_selection(&a.settings.live.Presentation.Speech, *options.EffectiveSpeech) + copySpeechSelection(&a.settings.live.Presentation.Speech, *options.EffectiveSpeech) } a.voice.punctuation, a.voice.punctuationLevel = options.Punctuation, options.Settings.Reading.PunctuationLevel a.voice.settings, a.voice.play = &a.settings.live, a.play - a.ui = new_internal_ui(ctx, keyboards, a.voice) + a.ui = newInternalUi(ctx, keyboards, a.voice) a.ui.gridSettings = func() config.InternalUI { return a.settings.live.InternalUI } - a.ui.previewSpelling = a.preview_spelling - a.ui.previewSpeech, a.ui.restoreSpeech = a.preview_menu_speech, a.restore_speech_preview - a.ui.deferSpeech = a.defer_preview_speech - a.ui.discoverChoices, a.ui.saveSettings = options.SettingsChoices, a.save_menu_settings + a.ui.previewSpelling = a.previewSpelling + a.ui.previewSpeech, a.ui.restoreSpeech = a.previewMenuSpeech, a.restoreSpeechPreview + a.ui.deferSpeech = a.deferPreviewSpeech + a.ui.discoverChoices, a.ui.saveSettings = options.SettingsChoices, a.saveMenuSettings a.speechResults = make(chan speechChangeResult, 1) a.preview.results = make(chan speechPreviewResult, 1) a.overrideLoads = make(chan func(), 1) a.speechChoices = make(chan preferences.Discovery, 1) - a.prepareSpeech = prepare_speech + a.prepareSpeech = prepareSpeech a.quick.selectSpeech = func(target config.Speech, done func(error, bool)) { driverChanged := target.Driver != a.settings.live.Presentation.Speech.Driver session, feedback, uiGeneration := a.spellSession, a.spellFeedback, a.ui.generation - a.change_speech(target, func(err error) { + a.changeSpeech(target, func(err error) { done(err, a.spellSession == session && a.spellFeedback == feedback && a.ui.generation == uiGeneration && !a.quitting) if err == nil && driverChanged && options.SettingsChoices != nil { selected := a.settings.live @@ -146,20 +146,20 @@ func new_application(ctx context.Context, source Source, keyboards Keyboards, vo } }() } - a.configure_reader() - a.clipboards = new_clipboard(options.Settings.Clipboard, a.engine, options.Clipboard, a.present, func() string { return a.voice.last }) + a.configureReader() + a.clipboards = newClipboard(options.Settings.Clipboard, a.engine, options.Clipboard, a.present, func() string { return a.voice.last }) a.ui.readClipboard = a.clipboards.history.Current a.ui.writeClipboard = func(text string) bool { return a.clipboards.add(text, true) } a.clipboards.historyStore = options.ClipboardHistory - a.restore_clipboard() + a.restoreClipboard() a.spellMenu = &spellcheckMenu{ui: a.ui, service: options.Spellcheck, clipboards: a.clipboards} if session, ok := source.(*terminal.Session); ok { - a.clipboards.queuePaste = session.Queue_paste + a.clipboards.queuePaste = session.QueuePaste } return a, nil } -func (a *application) restore_clipboard() { +func (a *application) restoreClipboard() { if a.options.ClipboardHistory == nil { return } diff --git a/internal/app/application_alias.go b/internal/app/application_alias.go index c7f17eb1..766900da 100644 --- a/internal/app/application_alias.go +++ b/internal/app/application_alias.go @@ -9,13 +9,13 @@ import ( "git.stormux.org/storm/fenrir/internal/control" ) -func shell_quote(text string) string { +func shellQuote(text string) string { return "'" + strings.ReplaceAll(text, "'", "'\"'\"'") + "'" } // The last simple command receives the arguments following the alias. Keep the // optional reader request in an OR list so errexit cannot prevent the launch. -func application_alias(id, socketPath string) string { +func applicationAlias(id, socketPath string) string { program := "" switch id { case "networkmanager": @@ -30,6 +30,6 @@ func application_alias(id, socketPath string) string { if socketPath == "" { socketPath = control.MainSocket } - body := "(echo " + shell_quote("command application "+id) + " | socat -T 2 - " + shell_quote("UNIX-CLIENT:"+socketPath) + ") || :; command " + program - return "alias " + program + "=" + shell_quote(body) + body := "(echo " + shellQuote("command application "+id) + " | socat -T 2 - " + shellQuote("UNIX-CLIENT:"+socketPath) + ") || :; command " + program + return "alias " + program + "=" + shellQuote(body) } diff --git a/internal/app/application_alias_test.go b/internal/app/application_alias_test.go index 2b654eaf..4eb190c7 100644 --- a/internal/app/application_alias_test.go +++ b/internal/app/application_alias_test.go @@ -23,7 +23,7 @@ func TestApplicationAliasesShellCheck(t *testing.T) { } for _, id := range []string{"networkmanager", "ninjam", "rogue", "codex"} { process := exec.Command(path, "-s", "bash", "-") - process.Stdin = strings.NewReader(application_alias(id, "") + "\n") + process.Stdin = strings.NewReader(applicationAlias(id, "") + "\n") if output, err := process.CombinedOutput(); err != nil { t.Fatalf("%s: %v: %s", id, err, output) } @@ -50,9 +50,9 @@ func TestApplicationAliasThroughPrivateSocket(t *testing.T) { if err := os.WriteFile(filepath.Join(directory, "cninjam"), []byte("#!/bin/sh\necho application-launched\n"), 0700); err != nil { t.Fatal(err) } - a, _ := persistence_application(t, true) - override_read(t, a, override_screen(1, "[Username@host directory] $")) - process := exec.CommandContext(ctx, "/bin/bash", "--noprofile", "--norc", "-c", "shopt -s expand_aliases\n"+application_alias("ninjam", socketPath)+"\ncninjam\n") + a, _ := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) + process := exec.CommandContext(ctx, "/bin/bash", "--noprofile", "--norc", "-c", "shopt -s expand_aliases\n"+applicationAlias("ninjam", socketPath)+"\ncninjam\n") process.Env = append(os.Environ(), "PATH="+directory) completed := make(chan struct{}) var output []byte @@ -66,7 +66,7 @@ func TestApplicationAliasThroughPrivateSocket(t *testing.T) { if request.Text != "command application ninjam" { t.Fatal(request.Text) } - a.remote_request(request) + a.remoteRequest(request) case <-ctx.Done(): t.Fatal("alias did not send selection request") } @@ -74,7 +74,7 @@ func TestApplicationAliasThroughPrivateSocket(t *testing.T) { if processError != nil || string(output) != "application-launched\n" || a.overrides[1] == nil { t.Fatalf("launch failed: %v, %s", processError, output) } - override_read(t, a, override_screen(1, "ninjam")) + overrideRead(t, a, overrideScreen(1, "ninjam")) if a.overrideCurrent == nil || a.overrideCurrent.id != "ninjam" { t.Fatal("pre-launch selection did not activate when application appeared") } @@ -103,7 +103,7 @@ func TestApplicationAliasLaunchesWithArgumentsDespiteReaderFailure(t *testing.T) } } socketPath := "/tmp/example socket'$(false).sock" - script := "set -euo pipefail\nshopt -s expand_aliases\n" + application_alias("ninjam", socketPath) + "\ncninjam 'argument with spaces' '*.wav'\n" + script := "set -euo pipefail\nshopt -s expand_aliases\n" + applicationAlias("ninjam", socketPath) + "\ncninjam 'argument with spaces' '*.wav'\n" process := exec.Command("/bin/bash", "--noprofile", "--norc", "-c", script) process.Env = append(os.Environ(), "PATH="+directory, "ALIAS_ARGS="+argsPath, "ALIAS_REQUEST="+requestPath) output, err := process.CombinedOutput() @@ -128,9 +128,9 @@ func TestApplicationAliasLaunchesWithArgumentsDespiteReaderFailure(t *testing.T) } func TestApplicationsMenuCopiesAliasWithoutSelecting(t *testing.T) { - a, voice := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) - a.open_applications() + a, voice := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.openApplications() a.ui.handle(interaction.Key{Name: "tab"}) a.ui.handle(interaction.Key{Name: "enter"}) if got := voice.messages[len(voice.messages)-1]; got != "Default has no application alias" { @@ -146,7 +146,7 @@ func TestApplicationsMenuCopiesAliasWithoutSelecting(t *testing.T) { t.Fatal("copy closed menu or selected an override") } text, ok := a.clipboards.history.Current() - if !ok || text != application_alias("ninjam", "") { + if !ok || text != applicationAlias("ninjam", "") { t.Fatal("wrong clipboard contents", text) } a.ui.handle(interaction.Key{Name: "escape"}) diff --git a/internal/app/application_overrides.go b/internal/app/application_overrides.go index 7532fe98..c88ae980 100644 --- a/internal/app/application_overrides.go +++ b/internal/app/application_overrides.go @@ -41,22 +41,22 @@ type applicationOverride struct { initialized, recognized, exitPending bool } -func (a *application) saves_unavailable() bool { +func (a *application) savesUnavailable() bool { return a.overrideTransition || a.overrideRestoreFailed || a.overrideFailed != nil || (a.overrideCurrent != nil && (!a.overrideCurrent.recognized || a.overrideCurrent.path == "")) } -func (a *application) settings_path() string { +func (a *application) settingsPath() string { if a.overrideCurrent != nil { return a.overrideCurrent.path } return a.options.ConfigPath } -func (a *application) start_settings_save(path string, settings config.Settings) bool { +func (a *application) startSettingsSave(path string, settings config.Settings) bool { if selected := a.overrideCurrent; selected != nil { base := selected.base return a.saver.start(a.ctx, settings, func() error { - doc, err := config.Open_application_document(path, base) + doc, err := config.OpenApplicationDocument(path, base) if err != nil { return err } @@ -67,16 +67,16 @@ func (a *application) start_settings_save(path string, settings config.Settings) } // Profile reads are bounded and run off the event loop, like settings writes. -func (a *application) load_application_profile(selected *applicationOverride) { - selected.base = config.Apply_application_settings(a.effective_settings(), a.settings_to_save()) +func (a *application) loadApplicationProfile(selected *applicationOverride) { + selected.base = config.ApplyApplicationSettings(a.effectiveSettings(), a.settingsToSave()) // Inherit the actual working selection, including startup fallback, rather // than unavailable saved voices or selections for a next-launch backend. - copy_speech_selection(&selected.base.Presentation.Speech, a.settings.live.Presentation.Speech) + copySpeechSelection(&selected.base.Presentation.Speech, a.settings.live.Presentation.Speech) selected.adapter.Configure(&selected.base) path, base := selected.path, selected.base a.overrideTransition = true go func() { - doc, err := config.Open_application_document(path, base) + doc, err := config.OpenApplicationDocument(path, base) select { case a.overrideLoads <- func() { a.overrideTransition = false @@ -95,36 +95,36 @@ func (a *application) load_application_profile(selected *applicationOverride) { }() } -func (a *application) capture_override(terminal int) overrideSnapshot { +func (a *application) captureOverride(terminal int) overrideSnapshot { settings := a.settings settings.remoteFields = maps.Clone(settings.remoteFields) - return overrideSnapshot{settings, a.quick.clone(), a.engine.Capture_terminal_session(terminal), a.muted, a.temporarySilence} + return overrideSnapshot{settings, a.quick.clone(), a.engine.CaptureTerminalSession(terminal), a.muted, a.temporarySilence} } -func (a *application) install_override(saved overrideSnapshot, terminal int) { +func (a *application) installOverride(saved overrideSnapshot, terminal int) { live := saved.settings.live live.Presentation.Speech.Enabled = !saved.muted - a.apply_remote_state(live, false) + a.applyRemoteState(live, false) a.settings = saved.settings *a.quick = saved.quick.clone() a.muted, a.temporarySilence = saved.muted, saved.silence - a.configure_reader() - a.engine.Restore_session(saved.runtime, terminal) + a.configureReader() + a.engine.RestoreSession(saved.runtime, terminal) a.spellSession++ - a.reading_regions_changed() + a.readingRegionsChanged() } // A synthesizer selection can require asynchronous restoration. Until it // completes, no new context is installed and all settings mutations are gated. -func (a *application) restore_override(done func()) bool { - return a.restore_override_result(func(err error) { +func (a *application) restoreOverride(done func()) bool { + return a.restoreOverrideResult(func(err error) { if err == nil { done() } }) } -func (a *application) restore_override_result(done func(error)) bool { +func (a *application) restoreOverrideResult(done func(error)) bool { current := a.overrideCurrent if current == nil { current = a.overrideFailed @@ -143,21 +143,21 @@ func (a *application) restore_override_result(done func(error)) bool { return false } if a.overrideCurrent != nil { - current.temporary = a.capture_override(current.terminal) + current.temporary = a.captureOverride(current.terminal) } restore := func() { - a.install_override(current.underlying, current.terminal) + a.installOverride(current.underlying, current.terminal) a.overrideCurrent = nil a.overrideFailed = nil current.adapter.Reset() done(nil) } - if same_speech_selection(a.settings.live.Presentation.Speech, current.underlying.settings.live.Presentation.Speech) { + if sameSpeechSelection(a.settings.live.Presentation.Speech, current.underlying.settings.live.Presentation.Speech) { restore() return true } a.overrideTransition = true - a.change_speech(current.underlying.settings.live.Presentation.Speech, func(err error) { + a.changeSpeech(current.underlying.settings.live.Presentation.Speech, func(err error) { a.overrideTransition = false if err != nil { a.overrideRestoreFailed = true @@ -165,8 +165,8 @@ func (a *application) restore_override_result(done func(error)) bool { // prepared. Keep its actual current selection and retain the save // guard until an explicit Default/selection retries restoration. fallback := current.underlying - copy_speech_selection(&fallback.settings.live.Presentation.Speech, a.settings.live.Presentation.Speech) - a.install_override(fallback, current.terminal) + copySpeechSelection(&fallback.settings.live.Presentation.Speech, a.settings.live.Presentation.Speech) + a.installOverride(fallback, current.terminal) a.overrideCurrent, a.overrideFailed = nil, current current.adapter.Reset() a.voice.Say(i18n.Format("Could not restore application settings: {0}", err.Error())) @@ -178,7 +178,7 @@ func (a *application) restore_override_result(done func(error)) bool { return false } -func (a *application) select_override(id string) { +func (a *application) selectOverride(id string) { if a.saver.busy || a.speechPending || a.overrideTransition { a.voice.Say(i18n.T("Settings are busy")) return @@ -187,13 +187,13 @@ func (a *application) select_override(id string) { if terminal == 0 || !a.lastActive { return } - a.select_override_result(id, func(string) {}) + a.selectOverrideResult(id, func(string) {}) } // Completion means selected, not recognized or profile-loaded: launchers must // be able to select an override before starting the application. Callers check // the ID and busy/terminal gates before entering this path. -func (a *application) select_override_result(id string, done func(string)) { +func (a *application) selectOverrideResult(id string, done func(string)) { terminal := a.lastTerminal a.ui.close() if a.preview.busy { @@ -201,7 +201,7 @@ func (a *application) select_override_result(id string, done func(string)) { return } a.overrideRestoreFailed = false // An explicit selection retries restoration. - a.restore_override_result(func(err error) { + a.restoreOverrideResult(func(err error) { if err != nil { done("Could not restore application settings: " + err.Error()) return @@ -246,7 +246,7 @@ func (a *application) select_override_result(id string, done func(string)) { // Called before reader.Update so exit detection and restored settings affect // the first shell snapshot, rather than interpreting it with the old adapter. -func (a *application) observe_override(next screen.Snapshot) (applicationoverrides.Frame, bool) { +func (a *application) observeOverride(next screen.Snapshot) (applicationoverrides.Frame, bool) { if a.overrideTransition || (a.saver.busy && len(a.overrides) != 0) { return applicationoverrides.Frame{}, false } @@ -255,7 +255,7 @@ func (a *application) observe_override(next screen.Snapshot) (applicationoverrid } selected := a.overrides[next.Terminal] if a.overrideCurrent != nil && (a.overrideCurrent != selected || !next.Active) { - if !a.restore_override(func() {}) { + if !a.restoreOverride(func() {}) { return applicationoverrides.Frame{}, false } } @@ -270,7 +270,7 @@ func (a *application) observe_override(next screen.Snapshot) (applicationoverrid if !frame.Recognized || selected.exitPending { selected.recognized = false if a.overrideCurrent == selected { - if !a.restore_override(func() {}) { + if !a.restoreOverride(func() {}) { return applicationoverrides.Frame{}, false } } @@ -290,28 +290,28 @@ func (a *application) observe_override(next screen.Snapshot) (applicationoverrid return applicationoverrides.Frame{}, false } if !selected.initialized && selected.profile == nil { - a.load_application_profile(selected) + a.loadApplicationProfile(selected) return applicationoverrides.Frame{}, false } - selected.underlying = a.capture_override(next.Terminal) + selected.underlying = a.captureOverride(next.Terminal) if !selected.initialized { - settings := a.effective_settings() + settings := a.effectiveSettings() selected.adapter.Configure(&settings) - settings = selected.profile.Apply_application(settings) + settings = selected.profile.ApplyApplication(settings) activate := func() { - a.apply_remote_state(settings, false) + a.applyRemoteState(settings, false) a.settings.saveDraft, a.settings.resetBase = selected.profile.Settings, selected.profile.Settings a.settings.remoteFields = make(map[string]uint64) a.settings.remoteRevision = 0 - *a.quick = *new_quick_settings(settings.Presentation.Speech.Driver) - a.configure_reader() - a.engine.Clear_session_regions(next.Terminal) + *a.quick = *newQuickSettings(settings.Presentation.Speech.Driver) + a.configureReader() + a.engine.ClearSessionRegions(next.Terminal) selected.initialized, selected.recognized = true, true a.overrideCurrent = selected } - if !same_speech_selection(settings.Presentation.Speech, a.settings.live.Presentation.Speech) { + if !sameSpeechSelection(settings.Presentation.Speech, a.settings.live.Presentation.Speech) { a.overrideTransition = true - a.change_speech(settings.Presentation.Speech, func(err error) { + a.changeSpeech(settings.Presentation.Speech, func(err error) { a.overrideTransition = false if err != nil { selected.adapter.Close() @@ -328,22 +328,22 @@ func (a *application) observe_override(next screen.Snapshot) (applicationoverrid } else { // Numeric/runtime settings are synchronous. Speech selection is // restored separately before resuming a suspended adapter. - if !same_speech_selection(a.settings.live.Presentation.Speech, selected.temporary.settings.live.Presentation.Speech) { + if !sameSpeechSelection(a.settings.live.Presentation.Speech, selected.temporary.settings.live.Presentation.Speech) { a.overrideTransition = true - a.change_speech(selected.temporary.settings.live.Presentation.Speech, func(err error) { + a.changeSpeech(selected.temporary.settings.live.Presentation.Speech, func(err error) { a.overrideTransition = false if err != nil { a.overrideRestoreFailed = true a.voice.Say(i18n.Format("Could not restore application settings: {0}", err.Error())) return } - a.install_override(selected.temporary, next.Terminal) + a.installOverride(selected.temporary, next.Terminal) selected.adapter.Reset() a.overrideCurrent = selected }) return applicationoverrides.Frame{}, false } - a.install_override(selected.temporary, next.Terminal) + a.installOverride(selected.temporary, next.Terminal) } a.overrideCurrent = selected } @@ -351,7 +351,7 @@ func (a *application) observe_override(next screen.Snapshot) (applicationoverrid return frame, true } -func (a *application) open_applications() { +func (a *application) openApplications() { if a.saver.busy || a.speechPending || a.overrideTransition { a.voice.Say(i18n.T("Settings are busy")) return @@ -362,7 +362,7 @@ func (a *application) open_applications() { if selected := a.overrides[a.lastTerminal]; selected != nil { position = slices.Index(ids, selected.id) } - session, err := interaction.New_session(interaction.Form{Type: interaction.TabForm, Title: "Applications", Tabs: []interaction.Tab{{ID: "applications", Label: "Applications", Controls: []interaction.Control{ + session, err := interaction.NewSession(interaction.Form{Type: interaction.TabForm, Title: "Applications", Tabs: []interaction.Tab{{ID: "applications", Label: "Applications", Controls: []interaction.Control{ {ID: "application", Label: "Application", Kind: interaction.List, Items: items, Selected: position, Action: "activate"}, {ID: "copy_alias", Label: "Copy alias to clipboard", Kind: interaction.Button, Action: "copy_alias"}, {ID: "cancel", Label: "Cancel", Kind: interaction.Button, Action: "cancel"}, @@ -385,11 +385,11 @@ func (a *application) open_applications() { if action == "activate" { selected := session.Values()["applications.application"].Selected a.ui.close() - a.select_override(ids[selected]) + a.selectOverride(ids[selected]) } if action == "copy_alias" { selected := session.Values()["applications.application"].Selected - text := application_alias(ids[selected], a.settings.live.Remote.SocketFile) + text := applicationAlias(ids[selected], a.settings.live.Remote.SocketFile) if text == "" { a.voice.Say(i18n.T("Default has no application alias")) return diff --git a/internal/app/application_overrides_test.go b/internal/app/application_overrides_test.go index 010a135e..9c241844 100644 --- a/internal/app/application_overrides_test.go +++ b/internal/app/application_overrides_test.go @@ -22,7 +22,7 @@ import ( "git.stormux.org/storm/fenrir/internal/speech" ) -func override_screen(terminal int, kind string) screen.Snapshot { +func overrideScreen(terminal int, kind string) screen.Snapshot { s := screen.Snapshot{Terminal: terminal, Active: true, Rows: 24, Cols: 100, Y: 23, Cells: make([]rune, 2400), Attributes: make([]screen.Attribute, 2400)} for index := range s.Cells { s.Cells[index] = ' ' @@ -46,44 +46,44 @@ func override_screen(terminal int, kind string) screen.Snapshot { } func TestRogueMenuSelectionNamedReadProfileAndShellExit(t *testing.T) { - a, voice := persistence_application(t, true) - override_read(t, a, override_screen(1, "rogue")) - a.open_applications() + a, voice := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "rogue")) + a.openApplications() a.ui.handle(interaction.Key{Text: "r"}) if got := voice.messages[len(voice.messages)-1]; got != "Rogue" { t.Fatal(got) } a.ui.handle(interaction.Key{Name: "enter"}) - override_read(t, a, override_screen(1, "rogue")) + overrideRead(t, a, overrideScreen(1, "rogue")) if a.overrideCurrent == nil || a.overrideCurrent.id != "rogue" { t.Fatal("Rogue not activated") } - a.handle_command(command.ReadLiveRegion1) + a.handleCommand(command.ReadLiveRegion1) if got := voice.messages[len(voice.messages)-1]; got != "Health: 12 of 12" { t.Fatal(got) } base := a.overrideCurrent.underlying.settings.live.Presentation.Speech.Rate for _, id := range quickToRate { - a.handle_command(id) + a.handleCommand(id) } - a.handle_command(command.NextQuickValue) + a.handleCommand(command.NextQuickValue) rate := a.settings.live.Presentation.Speech.Rate if rate == base { t.Fatal("application rate unchanged") } - a.save_settings() - finish_persistence(t, a, false) + a.saveSettings() + finishPersistence(t, a, false) path := filepath.Join(filepath.Dir(a.options.ConfigPath), "applications", "rogue.toml") - doc, err := config.Open_application_document(path, a.overrideCurrent.base) + doc, err := config.OpenApplicationDocument(path, a.overrideCurrent.base) if err != nil || doc.Settings.Presentation.Speech.Rate != rate { t.Fatal("Rogue profile not saved", err) } - override_read(t, a, override_screen(1, "[Username@host directory] $")) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) if a.overrideCurrent != nil || a.overrides[1] != nil || a.settings.live.Presentation.Speech.Rate != base { t.Fatal("shell did not restore default settings") } - a.select_override("rogue") - override_read(t, a, override_screen(1, "rogue")) + a.selectOverride("rogue") + overrideRead(t, a, overrideScreen(1, "rogue")) if a.overrideCurrent == nil || a.settings.live.Presentation.Speech.Rate != rate { t.Fatal("Rogue profile not reloaded") } @@ -91,64 +91,64 @@ func TestRogueMenuSelectionNamedReadProfileAndShellExit(t *testing.T) { func TestOverrideRestoresSynthesizerAndKeepsSaveBlockedUntilCompletion(t *testing.T) { for _, failed := range []bool{false, true} { - a, voice, _ := selection_application(t, true) + a, voice, _ := selectionApplication(t, true) a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return &preparedVoice{}, nil } - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) baseline := a.settings.saveDraft - if response := request_selection(t, a, "SET speech#voice=Temporary;speech#module=fixture"); response != "" { + if response := requestSelection(t, a, "SET speech#voice=Temporary;speech#module=fixture"); response != "" { t.Fatal(response) } - if a.settings.saveDraft.Presentation.Speech.Voice != "Temporary" || !same_speech_selection(a.overrideCurrent.underlying.settings.saveDraft.Presentation.Speech, baseline.Presentation.Speech) { + if a.settings.saveDraft.Presentation.Speech.Voice != "Temporary" || !sameSpeechSelection(a.overrideCurrent.underlying.settings.saveDraft.Presentation.Speech, baseline.Presentation.Speech) { t.Fatal("application voice did not stay in its own draft") } if failed { a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return nil, errors.New("fixture unavailable") } } - a.select_override("default") - if !a.speechPending || !a.saves_unavailable() { + a.selectOverride("default") + if !a.speechPending || !a.savesUnavailable() { t.Fatal("restoration did not retain save guard") } - a.handle_command(command.NextQuickValue) + a.handleCommand(command.NextQuickValue) if voice.messages[len(voice.messages)-1] != "Settings are busy" { t.Fatal("settings changed during restoration") } - finish_selection(t, a) + finishSelection(t, a) if failed { - if !a.saves_unavailable() || !a.overrideRestoreFailed { + if !a.savesUnavailable() || !a.overrideRestoreFailed { t.Fatal("failed restoration released save guard") } - override_read(t, a, override_screen(1, "shell output remains readable")) + overrideRead(t, a, overrideScreen(1, "shell output remains readable")) if a.overrideCurrent != nil || !strings.Contains(voice.messages[len(voice.messages)-1], "shell output remains readable") { t.Fatal("failed speech restoration suppressed ordinary reading", voice.messages) } a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return &preparedVoice{}, nil } - a.select_override("default") - finish_selection(t, a) + a.selectOverride("default") + finishSelection(t, a) } - if a.saves_unavailable() || !same_speech_selection(a.settings.live.Presentation.Speech, baseline.Presentation.Speech) { + if a.savesUnavailable() || !sameSpeechSelection(a.settings.live.Presentation.Speech, baseline.Presentation.Speech) { t.Fatal("speech selection not restored") } } } func TestExitWaitsForPendingSpeechChangeAndRestoresBeforeShellOutput(t *testing.T) { - a, _, _ := selection_application(t, true) + a, _, _ := selectionApplication(t, true) a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return &preparedVoice{}, nil } - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) - if response := request_selection(t, a, "SET speech#voice=Temporary;speech#module=fixture"); response != "" { + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) + if response := requestSelection(t, a, "SET speech#voice=Temporary;speech#module=fixture"); response != "" { t.Fatal(response) } - override_read(t, a, override_screen(1, "[Username@host directory] $")) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) if !a.speechPending || a.overrides[1] == nil { t.Fatal("exit did not wait for restoration") } - finish_selection(t, a) - override_read(t, a, override_screen(1, "[Username@host directory] $")) - if a.overrides[1] != nil || a.overrideCurrent != nil || a.engine.Tracking_mode() != "cursor" { + finishSelection(t, a) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) + if a.overrides[1] != nil || a.overrideCurrent != nil || a.engine.TrackingMode() != "cursor" { t.Fatal("async exit missed") } } @@ -156,26 +156,26 @@ func TestExitWaitsForPendingSpeechChangeAndRestoresBeforeShellOutput(t *testing. func TestCodexShellExitWithoutBridgeClosure(t *testing.T) { for _, pendingSpeech := range []bool{false, true} { t.Run(fmt.Sprint(pendingSpeech), func(t *testing.T) { - a, voice, _ := selection_application(t, true) + a, voice, _ := selectionApplication(t, true) a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return &preparedVoice{}, nil } - composer := override_screen(1, "› hello") + composer := overrideScreen(1, "› hello") composer.X = 7 - override_read(t, a, composer) - a.select_override("codex") - override_read(t, a, composer) + overrideRead(t, a, composer) + a.selectOverride("codex") + overrideRead(t, a, composer) baseline := a.overrideCurrent.underlying.settings.live if pendingSpeech { - if response := request_selection(t, a, "SET speech#voice=Temporary;speech#module=fixture"); response != "" { + if response := requestSelection(t, a, "SET speech#voice=Temporary;speech#module=fixture"); response != "" { t.Fatal(response) } } - shell := override_screen(1, "[Username@host directory] $") + shell := overrideScreen(1, "[Username@host directory] $") copy(shell.Line(20), []rune("› previous composer")) shell.X = len([]rune(shell.Text(23))) + 1 - override_read(t, a, shell) + overrideRead(t, a, shell) if pendingSpeech { - finish_selection(t, a) - override_read(t, a, shell) + finishSelection(t, a) + overrideRead(t, a, shell) } if a.overrideCurrent != nil || a.overrides[1] != nil || !reflect.DeepEqual(a.settings.live, baseline) { t.Fatal("shell retained Codex settings without a bridge close event") @@ -183,8 +183,8 @@ func TestCodexShellExitWithoutBridgeClosure(t *testing.T) { next := shell next.X-- start := len(voice.messages) - a.engine.Note_input(true, false, false) - override_read(t, a, next) + a.engine.NoteInput(true, false, false) + overrideRead(t, a, next) if len(voice.messages) == start { t.Fatal("shell arrow navigation remained silent") } @@ -192,10 +192,10 @@ func TestCodexShellExitWithoutBridgeClosure(t *testing.T) { } } -func override_read(t *testing.T, a *application, snapshot screen.Snapshot) { +func overrideRead(t *testing.T, a *application, snapshot screen.Snapshot) { t.Helper() a.source.(*fakeSource).snapshot = snapshot - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } // Model the event loop's asynchronous profile-read completion, leaving @@ -207,16 +207,16 @@ func override_read(t *testing.T, a *application, snapshot screen.Snapshot) { case <-time.After(time.Second): t.Fatal("profile load stalled") } - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } } } func TestApplicationsMenuActivatesOnlyOnEnterAndReleasesCapture(t *testing.T) { - a, voice := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) - a.open_applications() + a, voice := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.openApplications() if !a.ui.active || !strings.Contains(voice.messages[len(voice.messages)-1], "Default") { t.Fatal(voice.messages) } @@ -240,18 +240,18 @@ func TestApplicationsMenuActivatesOnlyOnEnterAndReleasesCapture(t *testing.T) { if len(a.overrides) != 0 || a.ui.active { t.Fatal("cancel activated override") } - a.open_applications() + a.openApplications() a.ui.handle(interaction.Key{Name: "down"}) a.ui.handle(interaction.Key{Name: "down"}) a.ui.handle(interaction.Key{Name: "enter"}) if a.ui.active || a.overrides[1] == nil || a.overrides[1].id != "ninjam" { t.Fatal("activation failed") } - override_read(t, a, override_screen(1, "ninjam")) - if a.engine.Tracking_mode() != "highlight" { + overrideRead(t, a, overrideScreen(1, "ninjam")) + if a.engine.TrackingMode() != "highlight" { t.Fatal("settings not applied") } - a.open_applications() + a.openApplications() if a.ui.session.Values()["applications.application"].Selected != 2 { t.Fatal("active item not selected") } @@ -261,20 +261,20 @@ func TestApplicationsMenuActivatesOnlyOnEnterAndReleasesCapture(t *testing.T) { if a.ui.active || a.overrides[1] == nil { t.Fatal("Cancel button changed selection") } - a.open_applications() + a.openApplications() a.ui.handle(interaction.Key{Name: "down"}) // Rogue a.ui.handle(interaction.Key{Name: "down"}) // Codex a.ui.handle(interaction.Key{Name: "down"}) // list wraps to Default a.ui.handle(interaction.Key{Name: "enter"}) - if a.saves_unavailable() || a.engine.Tracking_mode() != "cursor" { + if a.savesUnavailable() || a.engine.TrackingMode() != "cursor" { t.Fatal("default failed") } } func TestApplicationsMenuPrefixSearch(t *testing.T) { - a, voice := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) - a.open_applications() + a, voice := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.openApplications() for _, step := range []struct{ text, want string }{{"n", "NetworkManager"}, {"i", "Ninjam"}} { a.ui.handle(interaction.Key{Text: step.text}) if got := voice.messages[len(voice.messages)-1]; got != step.want { @@ -291,67 +291,67 @@ func TestApplicationsMenuPrefixSearch(t *testing.T) { } func TestOverrideSavesOwnDraftAndRestoresSession(t *testing.T) { - a, voice := persistence_application(t, true) - a.handle_command(command.NextQuickValue) // Preserve a pre-existing unsaved adjustment. - a.handle_command(command.AutoRead) - a.handle_command(command.ToggleAttributes) - override_read(t, a, override_screen(1, "ninjam")) - baseSettings, baseQuick, baseRuntime := a.settings, a.quick.revision, a.engine.Capture_session() + a, voice := persistenceApplication(t, true) + a.handleCommand(command.NextQuickValue) // Preserve a pre-existing unsaved adjustment. + a.handleCommand(command.AutoRead) + a.handleCommand(command.ToggleAttributes) + overrideRead(t, a, overrideScreen(1, "ninjam")) + baseSettings, baseQuick, baseRuntime := a.settings, a.quick.revision, a.engine.CaptureSession() before, err := os.ReadFile(a.options.ConfigPath) if err != nil { t.Fatal(err) } - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) for _, id := range []command.ID{command.NextQuickValue, command.ProgressMonitor, command.ToggleTracking, command.AutoRead, command.ToggleAttributes} { - a.handle_command(id) + a.handleCommand(id) } - if response := a.apply_remote_settings("SET speech#rate=0.77;keyboard#word_echo=True"); response != "" { + if response := a.applyRemoteSettings("SET speech#rate=0.77;keyboard#word_echo=True"); response != "" { t.Fatal(response) } if !reflect.DeepEqual(a.overrideCurrent.underlying.settings, baseSettings) { t.Fatal("ordinary draft changed") } profilePath := filepath.Join(filepath.Dir(a.options.ConfigPath), "applications", "ninjam.toml") - a.save_settings() - finish_persistence(t, a, false) + a.saveSettings() + finishPersistence(t, a, false) if !strings.Contains(voice.messages[len(voice.messages)-1], "Ninjam application settings saved") { t.Fatal(voice.messages) } - doc, err := config.Open_application_document(profilePath, a.overrideCurrent.base) + doc, err := config.OpenApplicationDocument(profilePath, a.overrideCurrent.base) if err != nil || doc.Settings.Presentation.Speech.Rate != a.settings.live.Presentation.Speech.Rate || !doc.Settings.Keyboard.WordEcho { t.Fatal("profile not saved", err) } - reply := persistence_request(a, "SAVE") - finish_persistence(t, a, false) - persistence_reply(t, reply, false) - if got := runtime_request(a, "SETTING SAVEAS "+a.options.ConfigPath); got != "SAVEAS is unavailable in application settings" { + reply := persistenceRequest(a, "SAVE") + finishPersistence(t, a, false) + persistenceReply(t, reply, false) + if got := runtimeRequest(a, "SETTING SAVEAS "+a.options.ConfigPath); got != "SAVEAS is unavailable in application settings" { t.Fatal(got) } - a.open_settings() - receive_ui(t, a.ui) + a.openSettings() + receiveUi(t, a.ui) if !strings.Contains(voice.messages[len(voice.messages)-1], "Ninjam application settings") { t.Fatal(voice.messages) } for range 100 { - if control, ok := a.ui.session.Focused_control(); ok && control.Action == "save" { + if control, ok := a.ui.session.FocusedControl(); ok && control.Action == "save" { break } a.ui.handle(interaction.Key{Name: "tab"}) } a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) + finishPersistence(t, a, false) a.ui.close() - a.select_override("default") - if !reflect.DeepEqual(a.settings, baseSettings) || a.quick.revision != baseQuick || !reflect.DeepEqual(a.engine.Capture_session(), baseRuntime) { + a.selectOverride("default") + if !reflect.DeepEqual(a.settings, baseSettings) || a.quick.revision != baseQuick || !reflect.DeepEqual(a.engine.CaptureSession(), baseRuntime) { t.Fatal("pre-override session was not restored") } after, _ := os.ReadFile(a.options.ConfigPath) if !slices.Equal(before, after) { t.Fatal("configuration changed") } - a.save_settings() - finish_persistence(t, a, false) + a.saveSettings() + finishPersistence(t, a, false) saved, _, err := config.Load(a.options.ConfigPath, nil) if err != nil || saved.Presentation.Speech.Rate != baseSettings.live.Presentation.Speech.Rate || saved.Keyboard.WordEcho { t.Fatal("override leaked after clearing", saved, err) @@ -359,89 +359,89 @@ func TestOverrideSavesOwnDraftAndRestoresSession(t *testing.T) { } func TestOverridesSuspendPerTerminalAndClearOnlyOnFreshShell(t *testing.T) { - a, _ := persistence_application(t, false) - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + a, _ := persistenceApplication(t, false) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) for _, id := range quickToRate { - a.handle_command(id) + a.handleCommand(id) } - a.handle_command(command.NextQuickValue) + a.handleCommand(command.NextQuickValue) appRate := a.settings.live.Presentation.Speech.Rate - override_read(t, a, override_screen(2, "other terminal")) - if a.overrideCurrent != nil || a.engine.Tracking_mode() != "cursor" || a.settings.live.Presentation.Speech.Rate == appRate { + overrideRead(t, a, overrideScreen(2, "other terminal")) + if a.overrideCurrent != nil || a.engine.TrackingMode() != "cursor" || a.settings.live.Presentation.Speech.Rate == appRate { t.Fatal("override leaked across VT") } - override_read(t, a, override_screen(2, "networkmanager")) - a.select_override("networkmanager") - override_read(t, a, override_screen(2, "networkmanager")) + overrideRead(t, a, overrideScreen(2, "networkmanager")) + a.selectOverride("networkmanager") + overrideRead(t, a, overrideScreen(2, "networkmanager")) if a.overrideCurrent == nil || a.overrideCurrent.id != "networkmanager" { t.Fatal("second terminal activation") } - override_read(t, a, override_screen(1, "ninjam")) + overrideRead(t, a, overrideScreen(1, "ninjam")) if a.overrideCurrent == nil || a.overrideCurrent.id != "ninjam" || a.settings.live.Presentation.Speech.Rate != appRate { t.Fatal("resume lost temporary state") } for _, text := range []string{"Password:", "Confirm? [y/n]", "unrecognized screen", " $"} { - override_read(t, a, override_screen(1, text)) - if a.overrides[1] == nil || a.overrideCurrent != nil || a.engine.Tracking_mode() != "cursor" { + overrideRead(t, a, overrideScreen(1, text)) + if a.overrides[1] == nil || a.overrideCurrent != nil || a.engine.TrackingMode() != "cursor" { t.Fatal("bad suspension", text) } } - s := override_screen(1, "[Username@host directory] $") + s := overrideScreen(1, "[Username@host directory] $") s.Generation = 2 // Returning from an alternate buffer must still detect exit. - override_read(t, a, s) + overrideRead(t, a, s) if a.overrides[1] != nil || a.overrides[2] == nil { t.Fatal("exit affected wrong terminal") } - a.select_override("default") + a.selectOverride("default") if a.overrides[2] == nil { t.Fatal("Default cleared another terminal") } } func TestOverrideRestoresUserRegionsAndPreservesRawReview(t *testing.T) { - a, voice := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) + a, voice := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) a.engine.Command(command.CurrentLine) - a.engine.Set_mark() + a.engine.SetMark() a.engine.Command(command.SetLiveRegion) before := a.engine.Command(command.ReadLiveRegion1).Text - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) - a.handle_command(command.ReadLiveRegion1) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.handleCommand(command.ReadLiveRegion1) if voice.messages[len(voice.messages)-1] != "No chat message received" { t.Fatal(voice.messages) } - a.handle_command(command.ReadScreen) + a.handleCommand(command.ReadScreen) if !strings.Contains(voice.messages[len(voice.messages)-1], "[ ]mute") { t.Fatal("raw screen replaced", voice.messages) } - a.select_override("default") + a.selectOverride("default") if after := a.engine.Command(command.ReadLiveRegion1).Text; after != before { t.Fatal("user region lost", before, after) } } func TestApplicationExitInvalidatesSettingsFormAndItsPreviews(t *testing.T) { - a, _ := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) + a, _ := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) baseline := a.settings - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) - a.open_settings() - receive_ui(t, a.ui) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.openSettings() + receiveUi(t, a.ui) generation := a.ui.generation reading := a.settings.live.Reading reading.Spellcheck = !reading.Spellcheck - a.preview_spelling(reading) - override_read(t, a, override_screen(1, "[Username@host directory] $")) + a.previewSpelling(reading) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) if a.ui.active || !reflect.DeepEqual(a.settings, baseline) { t.Fatal("old form or preview survived exit") } a.ui.update(uiUpdate{generation: generation, apply: func() { t.Fatal("stale form callback applied") }}) - a.save_settings() - finish_persistence(t, a, false) + a.saveSettings() + finishPersistence(t, a, false) saved, _, err := config.Load(a.options.ConfigPath, nil) if err != nil || saved.Reading.Mode != baseline.saveDraft.Reading.Mode || saved.Reading.Spellcheck != baseline.saveDraft.Reading.Spellcheck { t.Fatal("old application form contaminated subsequent save", err) @@ -449,79 +449,79 @@ func TestApplicationExitInvalidatesSettingsFormAndItsPreviews(t *testing.T) { } func TestActivationRejectsPendingOperationsAndRestartStartsWithoutOverride(t *testing.T) { - a, _ := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) + a, _ := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) a.saver.busy = true - a.select_override("ninjam") + a.selectOverride("ninjam") if len(a.overrides) != 0 { t.Fatal("activated during save") } a.saver.busy, a.speechPending = false, true - a.select_override("ninjam") + a.selectOverride("ninjam") if len(a.overrides) != 0 { t.Fatal("activated during speech selection") } a.speechPending = false - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) saved, _, err := config.Load(a.options.ConfigPath, nil) if err != nil { t.Fatal(err) } - fresh, err := new_application(a.ctx, &fakeSource{}, &fakeKeys{poll: func(bool, func(input.Decision)) error { return nil }}, &fakeVoice{}, RunOptions{Settings: saved}) - if err != nil || fresh.saves_unavailable() || fresh.engine.Tracking_mode() != "cursor" { + fresh, err := newApplication(a.ctx, &fakeSource{}, &fakeKeys{poll: func(bool, func(input.Decision)) error { return nil }}, &fakeVoice{}, RunOptions{Settings: saved}) + if err != nil || fresh.savesUnavailable() || fresh.engine.TrackingMode() != "cursor" { t.Fatal("restart retained override", err) } } func TestApplicationProfileReloadAndDefaultInheritance(t *testing.T) { for _, terminalMode := range []bool{false, true} { - a, _ := persistence_application(t, terminalMode) - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + a, _ := persistenceApplication(t, terminalMode) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) for _, id := range quickToRate { - a.handle_command(id) + a.handleCommand(id) } - a.handle_command(command.NextQuickValue) + a.handleCommand(command.NextQuickValue) savedRate := a.settings.live.Presentation.Speech.Rate - a.save_settings() + a.saveSettings() // A terminal switch must wait for the admitted application write. - override_read(t, a, override_screen(3, "other terminal")) + overrideRead(t, a, overrideScreen(3, "other terminal")) if a.overrideCurrent == nil { t.Fatal("save ownership lost before completion") } - finish_persistence(t, a, false) - override_read(t, a, override_screen(3, "other terminal")) + finishPersistence(t, a, false) + overrideRead(t, a, overrideScreen(3, "other terminal")) if a.overrideCurrent != nil || a.settings.live.Presentation.Speech.Rate == savedRate { t.Fatal("application leaked across terminal") } // Change an unrelated ordinary setting, then discard/reselect the adapter. - if text := a.apply_remote_settings("SET speech#pitch=0.6"); text != "" { + if text := a.applyRemoteSettings("SET speech#pitch=0.6"); text != "" { t.Fatal(text) } pitch := a.settings.live.Presentation.Speech.Pitch - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("default") - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("default") + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) if a.settings.live.Presentation.Speech.Rate != savedRate || a.settings.live.Presentation.Speech.Pitch != pitch { t.Fatal("saved rate or new inherited pitch missing", a.settings.live.Presentation.Speech) } - if text := a.apply_remote_settings("SET speech#rate=0.1"); text != "" { + if text := a.applyRemoteSettings("SET speech#rate=0.1"); text != "" { t.Fatal(text) } - if text := a.reset_remote_settings(); text != "" { + if text := a.resetRemoteSettings(); text != "" { t.Fatal(text) } if a.settings.live.Presentation.Speech.Rate != savedRate { t.Fatal("RESET did not restore profile") } before := a.settings - if text := a.apply_remote_settings("SET speech#rate=0.2;screen#ignore_screen=1"); text == "" || !reflect.DeepEqual(a.settings, before) { + if text := a.applyRemoteSettings("SET speech#rate=0.2;screen#ignore_screen=1"); text == "" || !reflect.DeepEqual(a.settings, before) { t.Fatal("global remote change was not rejected atomically") } - override_read(t, a, override_screen(1, "[Username@host directory] $")) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) if a.overrideCurrent != nil || a.settings.live.Presentation.Speech.Rate == savedRate { t.Fatal("exit did not restore default") } @@ -530,7 +530,7 @@ func TestApplicationProfileReloadAndDefaultInheritance(t *testing.T) { func TestApplicationProfileVoiceLoadAndFailureLeaveDefaultIntact(t *testing.T) { for _, failure := range []string{"", "invalid", "unavailable"} { - a, _, path := selection_application(t, true) + a, _, path := selectionApplication(t, true) profilePath := filepath.Join(filepath.Dir(path), "applications", "ninjam.toml") if err := os.MkdirAll(filepath.Dir(profilePath), 0700); err != nil { t.Fatal(err) @@ -549,24 +549,24 @@ func TestApplicationProfileVoiceLoadAndFailureLeaveDefaultIntact(t *testing.T) { return &preparedVoice{}, nil } baseline := a.settings - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) if a.speechPending { - finish_selection(t, a) + finishSelection(t, a) } if failure != "" { - if a.overrideCurrent != nil || !reflect.DeepEqual(a.settings, baseline) || a.saves_unavailable() { + if a.overrideCurrent != nil || !reflect.DeepEqual(a.settings, baseline) || a.savesUnavailable() { t.Fatal("failed profile changed ordinary settings") } continue } - override_read(t, a, override_screen(1, "ninjam")) + overrideRead(t, a, overrideScreen(1, "ninjam")) if a.settings.live.Presentation.Speech.Voice != "Application voice" || a.settings.live.Presentation.Speech.Rate != 12 { t.Fatal("profile voice not applied") } - a.select_override("default") - finish_selection(t, a) + a.selectOverride("default") + finishSelection(t, a) if !reflect.DeepEqual(a.settings, baseline) { t.Fatal("default voice not restored") } @@ -574,33 +574,33 @@ func TestApplicationProfileVoiceLoadAndFailureLeaveDefaultIntact(t *testing.T) { } func TestApplicationMenuPreservesSessionTogglesAndLaunchChoices(t *testing.T) { - a, _ := persistence_application(t, true) + a, _ := persistenceApplication(t, true) a.settings.saveDraft.Keyboard.Layout = "laptop" a.settings.saveDraft.Presentation.Speech.Driver = "dectalk" a.settings.saveDraft.Presentation.Speech.Voice = "Next launch voice" - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) - a.handle_command(command.Mute) - a.handle_command(command.AutoRead) - a.open_settings() - receive_ui(t, a.ui) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.handleCommand(command.Mute) + a.handleCommand(command.AutoRead) + a.openSettings() + receiveUi(t, a.ui) for range 100 { - if control, ok := a.ui.session.Focused_control(); ok && control.Action == "save" { + if control, ok := a.ui.session.FocusedControl(); ok && control.Action == "save" { break } a.ui.handle(interaction.Key{Name: "tab"}) } a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) - if !a.muted || a.engine.Automatic_reading() || a.settings.live.Keyboard.Layout != "desktop" || a.settings.live.Presentation.Speech.Driver != "speech-dispatcher" || a.settings.live.Presentation.Speech.Voice != "" { + finishPersistence(t, a, false) + if !a.muted || a.engine.AutomaticReading() || a.settings.live.Keyboard.Layout != "desktop" || a.settings.live.Presentation.Speech.Driver != "speech-dispatcher" || a.settings.live.Presentation.Speech.Voice != "" { t.Fatal("menu changed session toggles or launch-only choices") } data, err := os.ReadFile(a.overrideCurrent.path) if err != nil || strings.Contains(string(data), "enabled") || strings.Contains(string(data), "automatic") || strings.Contains(string(data), "driver") || strings.Contains(string(data), "layout") || strings.Contains(string(data), "voice") { t.Fatal("menu saved inherited/session/launch settings", string(data), err) } - a.select_override("default") + a.selectOverride("default") if a.settings.saveDraft.Keyboard.Layout != "laptop" || a.settings.saveDraft.Presentation.Speech.Driver != "dectalk" { t.Fatal("ordinary next-launch choices lost") } diff --git a/internal/app/attributes_test.go b/internal/app/attributes_test.go index 50afa1af..6eddc163 100644 --- a/internal/app/attributes_test.go +++ b/internal/app/attributes_test.go @@ -28,7 +28,7 @@ func TestQuickAttributesChoicesMenuCancelSaveAndRestart(t *testing.T) { t.Fatal(err) } voice := &fakeVoice{} - quick := new_quick_settings("speech-dispatcher") + quick := newQuickSettings("speech-dispatcher") quick.command(command.NextQuickCategory, &base, voice) for range 2 { quick.command(command.NextQuickEntry, &base, voice) @@ -50,9 +50,9 @@ func TestQuickAttributesChoicesMenuCancelSaveAndRestart(t *testing.T) { if len(voice.parameters) != 0 || base.Reading.Attributes != "both" { t.Fatal(base, voice.parameters) } - ui := new_internal_ui(context.Background(), &fakeKeys{}, voice) - ui.open_settings(base, path, base) - receive_ui(t, ui) + ui := newInternalUi(context.Background(), &fakeKeys{}, voice) + ui.openSettings(base, path, base) + receiveUi(t, ui) control := ui.session.Values()["reading.attributes"] if control.Choices[control.Selected].ID != "both" { t.Fatal("menu lost quick choice", control) diff --git a/internal/app/audio_recovery_test.go b/internal/app/audio_recovery_test.go index 376d3b6b..d8f66ca5 100644 --- a/internal/app/audio_recovery_test.go +++ b/internal/app/audio_recovery_test.go @@ -26,7 +26,7 @@ type unavailableSpeech struct { func (f *unavailableSpeech) Say(string) error { return io.EOF } func (f *unavailableSpeech) Configure(speech.Parameters) error { return nil } -func (f *unavailableSpeech) Set_pitch(int) error { return nil } +func (f *unavailableSpeech) SetPitch(int) error { return nil } func (f *unavailableSpeech) Cancel() error { return nil } func (f *unavailableSpeech) Close() {} func (f *unavailableSpeech) Reopen(ctx context.Context) (speech.Transport, error) { diff --git a/internal/app/capitalization_test.go b/internal/app/capitalization_test.go index 0bb97f52..d9638440 100644 --- a/internal/app/capitalization_test.go +++ b/internal/app/capitalization_test.go @@ -18,7 +18,7 @@ type capitalVoice struct { pitches []int } -func (v *capitalVoice) Say_with_pitch(text string, pitch int) { +func (v *capitalVoice) SayWithPitch(text string, pitch int) { v.pitches = append(v.pitches, pitch) v.Say(text) } @@ -41,7 +41,7 @@ func TestCapitalChoicesAreIndependentAndKeepOriginalEcho(t *testing.T) { return true }} for _, char := range "EÉeé1?" { - echo.say_character(char) + echo.sayCharacter(char) } prefix := "" if settings.Reading.SayCapForCapitals { @@ -66,7 +66,7 @@ func TestCapitalChoicesAreIndependentAndKeepOriginalEcho(t *testing.T) { t.Fatal(cue) } } - echo.say_character('E', " first character in cell Subject") + echo.sayCharacter('E', " first character in cell Subject") if echo.last != "E first character in cell Subject" { t.Fatal("capital indication leaked into clipboard echo", echo.last) } @@ -85,7 +85,7 @@ func TestCapitalPitchFollowsLiveNormalPitch(t *testing.T) { echo := &echoSpeaker{Speaker: voice, settings: &settings} for _, trial := range []struct{ normal, capital int }{{0, 60}, {30, 70}, {90, 100}, {-80, 60}} { settings.Presentation.Speech.Pitch = trial.normal - echo.say_character('A') + echo.sayCharacter('A') if got := voice.pitches[len(voice.pitches)-1]; got != trial.capital { t.Fatal(trial, got) } diff --git a/internal/app/clipboard.go b/internal/app/clipboard.go index 47126fae..d3679afb 100644 --- a/internal/app/clipboard.go +++ b/internal/app/clipboard.go @@ -54,14 +54,14 @@ type echoSpeaker struct { } func (s *echoSpeaker) Say(text string) { - s.Speaker.Say(s.prepare_text(text)) + s.Speaker.Say(s.prepareText(text)) } -func (s *echoSpeaker) Say_after(text string, before func(context.Context)) { - s.Speaker.Say_after(s.prepare_text(text), before) +func (s *echoSpeaker) SayAfter(text string, before func(context.Context)) { + s.Speaker.SayAfter(s.prepareText(text), before) } -func (s *echoSpeaker) prepare_text(text string) string { +func (s *echoSpeaker) prepareText(text string) string { if text != "" { s.last = text } @@ -71,13 +71,13 @@ func (s *echoSpeaker) prepare_text(text string) string { reading := s.settings.Reading options = punctuation.TextOptions{Emoticons: reading.Emoticons, RepeatedSymbols: reading.RepeatedSymbols, RepeatedSymbolsMin: reading.RepeatedSymbolsMin} } - text = s.punctuation.Process_text(text, s.punctuationLevel, options) + text = s.punctuation.ProcessText(text, s.punctuationLevel, options) } return text } // Character feedback bypasses text expansion, including punctuation in names. -func (s *echoSpeaker) say_character(char rune, suffix ...string) { +func (s *echoSpeaker) sayCharacter(char rune, suffix ...string) { text := presentation.Character(char) if s.punctuation != nil { text = s.punctuation.Character(char) @@ -104,7 +104,7 @@ func (s *echoSpeaker) say_character(char rune, suffix ...string) { // Python Fenrir's capital_pitch=0.8 maps to 60 on the SSIP scale. // Keep a rise above a higher normal pitch, up to the backend limit. pitch := min(100, max(60, s.settings.Presentation.Speech.Pitch+40)) - s.Speaker.Say_with_pitch(text, pitch) + s.Speaker.SayWithPitch(text, pitch) return } s.Speaker.Say(text) @@ -128,8 +128,8 @@ type clipboardHost struct { terminal int } -func new_clipboard(settings config.Clipboard, engine *reader.Reader, worker ClipboardTransfers, present func(string, presentation.Cue), lastEcho func() string) *clipboardHost { - return &clipboardHost{history: clipboard.New_history(settings.NumberOfClipboards), settings: settings, engine: engine, worker: worker, present: present, lastEcho: lastEcho} +func newClipboard(settings config.Clipboard, engine *reader.Reader, worker ClipboardTransfers, present func(string, presentation.Cue), lastEcho func() string) *clipboardHost { + return &clipboardHost{history: clipboard.NewHistory(settings.NumberOfClipboards), settings: settings, engine: engine, worker: worker, present: present, lastEcho: lastEcho} } func (c *clipboardHost) configure(settings config.Clipboard) { @@ -179,7 +179,7 @@ func (c *clipboardHost) add(text string, dirty bool) bool { return true } -func (c *clipboardHost) history_update(update clipboard.HistoryUpdate) { +func (c *clipboardHost) historyUpdate(update clipboard.HistoryUpdate) { if update.Sequence != c.historyStore.Sequence() { return // A newer local action has not been acknowledged yet. } @@ -198,7 +198,7 @@ func (c *clipboardHost) history_update(update clipboard.HistoryUpdate) { } } -func (c *clipboardHost) session_changed(terminal int) { +func (c *clipboardHost) sessionChanged(terminal int) { c.terminal = terminal c.revision++ c.feedback++ @@ -208,7 +208,7 @@ func (c *clipboardHost) session_changed(terminal int) { } } -func clipboard_path(path string) string { +func clipboardPath(path string) string { name := os.Getenv("SUDO_USER") if name == "" { if current, err := user.Current(); err == nil { @@ -226,7 +226,7 @@ func (c *clipboardHost) transfer(id command.ID, text string) { c.say("Clipboard import failed") return } - request := clipboard.Request{Command: id, Revision: c.revision, Feedback: c.feedback, Text: text, Path: clipboard_path(c.settings.ExportPath), Display: c.settings.SyncDisplay, Terminal: c.terminal} + request := clipboard.Request{Command: id, Revision: c.revision, Feedback: c.feedback, Text: text, Path: clipboardPath(c.settings.ExportPath), Display: c.settings.SyncDisplay, Terminal: c.terminal} c.next = append(c.next, request) if c.busy { c.worker.Cancel() @@ -265,13 +265,13 @@ func (c *clipboardHost) poll() { func (c *clipboardHost) command(id command.ID) bool { switch id { case command.SetMark: - message := c.engine.Set_mark() + message := c.engine.SetMark() c.present(message.Text, message.Cue) case command.RemoveMarks: - c.engine.Clear_marks() + c.engine.ClearMarks() c.say("Remove marks") case command.MarkedText, command.CopyMarked: - text, ok := c.engine.Marked_text(id == command.CopyMarked) + text, ok := c.engine.MarkedText(id == command.CopyMarked) if !ok { if id == command.CopyMarked { c.say("One or two marks are needed") @@ -282,7 +282,7 @@ func (c *clipboardHost) command(id command.ID) bool { } if id == command.CopyMarked { if c.add(text, true) { - c.engine.Clear_marks() + c.engine.ClearMarks() c.present(text, presentation.CopyToClipboard) } } else if strings.TrimSpace(text) == "" { @@ -327,10 +327,10 @@ func (c *clipboardHost) command(id command.ID) bool { } } if id == command.PreviousClipboard || id == command.NextClipboard { - if c.history.At_first() { + if c.history.AtFirst() { c.say("First clipboard ") } - if c.history.At_last() { + if c.history.AtLast() { c.say("Last clipboard ") } } diff --git a/internal/app/clipboard_test.go b/internal/app/clipboard_test.go index 11bc1f4e..df1964ac 100644 --- a/internal/app/clipboard_test.go +++ b/internal/app/clipboard_test.go @@ -45,20 +45,20 @@ func (f *fakeTransfers) Results() <-chan clipboard.Result { return nil } func (f *fakeTransfers) Cancel() {} func (f *fakeTransfers) Close() {} -func clipboard_fixture() (*clipboardHost, *fakeTransfers, *[]presentation.Message, *string) { +func clipboardFixture() (*clipboardHost, *fakeTransfers, *[]presentation.Message, *string) { settings := config.Defaults().Clipboard settings.Sync = true worker := &fakeTransfers{} messages := []presentation.Message{} echo := "last text" - host := new_clipboard(settings, reader.New(), worker, func(text string, cue presentation.Cue) { + host := newClipboard(settings, reader.New(), worker, func(text string, cue presentation.Cue) { messages = append(messages, presentation.Message{Text: text, Cue: cue}) }, func() string { return echo }) return host, worker, &messages, &echo } func TestClipboardSyncStaleImportRetryAcknowledgementAndNoLoop(t *testing.T) { - host, worker, messages, echo := clipboard_fixture() + host, worker, messages, echo := clipboardFixture() host.poll() stale := worker.requests[0] host.command(command.CopyLastEcho) @@ -83,7 +83,7 @@ func TestClipboardSyncStaleImportRetryAcknowledgementAndNoLoop(t *testing.T) { host.poll() poll := worker.requests[len(worker.requests)-1] host.result(clipboard.Result{Request: poll, Text: *echo}) - if !host.history.At_first() || !host.history.At_last() || len(*messages) != 1 { + if !host.history.AtFirst() || !host.history.AtLast() || len(*messages) != 1 { t.Fatal("own write reimported or sync spoke", *messages) } host.poll() @@ -98,7 +98,7 @@ func TestClipboardSyncStaleImportRetryAcknowledgementAndNoLoop(t *testing.T) { } func TestClipboardManualImportsAndLateFeedback(t *testing.T) { - host, worker, messages, _ := clipboard_fixture() + host, worker, messages, _ := clipboardFixture() host.settings.Sync = false host.poll() if len(worker.requests) != 0 { @@ -127,11 +127,11 @@ func TestClipboardManualImportsAndLateFeedback(t *testing.T) { } func TestClipboardPendingManualTransferRetiresOnTargetChange(t *testing.T) { - host, worker, messages, _ := clipboard_fixture() + host, worker, messages, _ := clipboardFixture() host.poll() stale := worker.requests[0] host.command(command.ImportXClipboard) - host.session_changed(3) + host.sessionChanged(3) host.result(clipboard.Result{Request: stale, Text: "old session"}) if _, ok := host.history.Current(); ok || len(*messages) != 0 || len(worker.requests) != 1 { t.Fatal("stale session changed clipboard", *messages, worker.requests) @@ -139,7 +139,7 @@ func TestClipboardPendingManualTransferRetiresOnTargetChange(t *testing.T) { } func TestManualTransferQueuePreservesEveryExport(t *testing.T) { - host, worker, _, _ := clipboard_fixture() + host, worker, _, _ := clipboardFixture() host.settings.Sync = false host.add("text", true) for range 3 { @@ -158,8 +158,8 @@ func TestManualTransferQueuePreservesEveryExport(t *testing.T) { func TestPersistentClipboardLiveEnableResizeSelectionDisableAndClear(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "clipboard.json") - host, _, _, _ := clipboard_fixture() - host.historyStore = clipboard.New_persistence(path, false) + host, _, _, _ := clipboardFixture() + host.historyStore = clipboard.NewPersistence(path, false) host.settings.Sync = false host.add("old", true) host.add("new", true) @@ -170,7 +170,7 @@ func TestPersistentClipboardLiveEnableResizeSelectionDisableAndClear(t *testing. if err := host.historyStore.Close(); err != nil { t.Fatal(err) } - store := clipboard.New_persistence(path, true) + store := clipboard.NewPersistence(path, true) if store.LoadErr != nil || store.Initial.Selected != 1 || !reflect.DeepEqual(store.Initial.Entries, []string{"new", "old"}) { t.Fatal(store.Initial, store.LoadErr) } @@ -189,7 +189,7 @@ func TestPersistentClipboardLiveEnableResizeSelectionDisableAndClear(t *testing. if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { t.Fatal("disabling kept the saved file", err) } - host.historyStore = clipboard.New_persistence(path, false) + host.historyStore = clipboard.NewPersistence(path, false) settings.Persistent = true host.configure(settings) host.command(command.ClearClipboard) @@ -203,12 +203,12 @@ func TestPersistentClipboardLiveEnableResizeSelectionDisableAndClear(t *testing. func TestPersistentClipboardStartupRestoresClipsAndRetainsSelection(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "tty.json") - store := clipboard.New_persistence(path, false) + store := clipboard.NewPersistence(path, false) store.Enable(clipboard.Snapshot{Version: 1, Entries: []string{"new", "middle", "old"}, Selected: 1}, 200) if err := store.Close(); err != nil { t.Fatal(err) } - store = clipboard.New_persistence(path, true) + store = clipboard.NewPersistence(path, true) settings := config.Defaults() settings.Clipboard.Persistent = true settings.Clipboard.NumberOfClipboards = 2 @@ -228,21 +228,21 @@ func TestPersistentClipboardStartupRestoresClipsAndRetainsSelection(t *testing.T if err := store.Close(); err != nil { t.Fatal(err) } - store = clipboard.New_persistence(path, true) + store = clipboard.NewPersistence(path, true) if store.LoadErr != nil || !reflect.DeepEqual(store.Initial.Entries, []string{"new", "middle"}) || store.Initial.Selected != 1 { t.Fatal("startup limit not applied on disk", store.Initial, store.LoadErr) } store.Close() } -func apply_shared_history(t *testing.T, host *clipboardHost) { +func applySharedHistory(t *testing.T, host *clipboardHost) { t.Helper() deadline := time.NewTimer(3 * time.Second) defer deadline.Stop() for { select { case update := <-host.historyStore.Updates(): - host.history_update(update) + host.historyUpdate(update) if update.Sequence == host.historyStore.Sequence() { return } @@ -256,25 +256,25 @@ func apply_shared_history(t *testing.T, host *clipboardHost) { func TestSharedClipboardHostsKeepSelectionLocalAndRefreshSilently(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "clipboard.json") - first, _, firstMessages, _ := clipboard_fixture() - second, _, secondMessages, _ := clipboard_fixture() + first, _, firstMessages, _ := clipboardFixture() + second, _, secondMessages, _ := clipboardFixture() for _, host := range []*clipboardHost{first, second} { host.settings.Persistent = true host.settings.Sync = false - host.historyStore = clipboard.New_persistence(path, true) + host.historyStore = clipboard.NewPersistence(path, true) t.Cleanup(func() { host.historyStore.Close() }) } first.add("older", true) - apply_shared_history(t, first) - apply_shared_history(t, second) + applySharedHistory(t, first) + applySharedHistory(t, second) first.add("newer", true) - apply_shared_history(t, first) - apply_shared_history(t, second) + applySharedHistory(t, first) + applySharedHistory(t, second) first.command(command.NextClipboard) - apply_shared_history(t, first) + applySharedHistory(t, first) second.add("peer", true) - apply_shared_history(t, second) - apply_shared_history(t, first) + applySharedHistory(t, second) + applySharedHistory(t, first) if got, _ := first.history.Current(); got != "older" { t.Fatal("peer copy changed local selection", got) } @@ -286,8 +286,8 @@ func TestSharedClipboardHostsKeepSelectionLocalAndRefreshSilently(t *testing.T) } beforeFirst, beforeSecond := len(*firstMessages), len(*secondMessages) second.command(command.ClearClipboard) - apply_shared_history(t, second) - apply_shared_history(t, first) + applySharedHistory(t, second) + applySharedHistory(t, first) if _, ok := first.history.Current(); ok { t.Fatal("peer Clear kept local history") } @@ -296,24 +296,24 @@ func TestSharedClipboardHostsKeepSelectionLocalAndRefreshSilently(t *testing.T) } // Pending local copies cannot be overwritten by an earlier refresh. first.add("pending", true) - first.history_update(clipboard.HistoryUpdate{State: clipboard.Snapshot{Version: 1}, Enabled: true}) + first.historyUpdate(clipboard.HistoryUpdate{State: clipboard.Snapshot{Version: 1}, Enabled: true}) if got, _ := first.history.Current(); got != "pending" { t.Fatal("stale refresh replaced pending copy", got) } - apply_shared_history(t, first) + applySharedHistory(t, first) } func TestDisabledClipboardClearDoesNotEnablePersistence(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "clipboard.json") - host, _, _, _ := clipboard_fixture() - host.historyStore = clipboard.New_persistence(path, false) + host, _, _, _ := clipboardFixture() + host.historyStore = clipboard.NewPersistence(path, false) host.command(command.ClearClipboard) if err := host.historyStore.Close(); err != nil { t.Fatal(err) } select { case update := <-host.historyStore.Updates(): - host.history_update(update) + host.historyUpdate(update) default: } if host.settings.Persistent { diff --git a/internal/app/codex_events.go b/internal/app/codex_events.go index 2f6cc161..ab99fc55 100644 --- a/internal/app/codex_events.go +++ b/internal/app/codex_events.go @@ -11,7 +11,7 @@ import ( "git.stormux.org/storm/fenrir/internal/applicationoverrides/codex" ) -func (a *application) codex_event(text string) string { +func (a *application) codexEvent(text string) string { kind, payload, _ := strings.Cut(text, " ") if kind != "CODEX" { return "Unsupported application event" diff --git a/internal/app/codex_events_test.go b/internal/app/codex_events_test.go index 7daa7c0d..0ae14301 100644 --- a/internal/app/codex_events_test.go +++ b/internal/app/codex_events_test.go @@ -18,12 +18,12 @@ import ( func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { t.Setenv("WINDOWID", "42") - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) a.options.TerminalMode = true - snapshot := override_screen(1, "OpenAI Codex") - override_read(t, a, snapshot) - a.select_override("codex") - override_read(t, a, snapshot) + snapshot := overrideScreen(1, "OpenAI Codex") + overrideRead(t, a, snapshot) + a.selectOverride("codex") + overrideRead(t, a, snapshot) base := codex.Event{Version: 1, Epoch: 1, Window: "42", Terminal: 1, Session: "fixture-session", Kind: "status", Status: "working"} send := func(event codex.Event, uid int) string { t.Helper() @@ -32,7 +32,7 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { t.Fatal(err) } reply := make(chan string, 1) - a.remote_request(control.Request{UID: uid, Text: "APPLICATION CODEX " + string(encoded), Reply: reply}) + a.remoteRequest(control.Request{UID: uid, Text: "APPLICATION CODEX " + string(encoded), Reply: reply}) return <-reply } other := base @@ -51,7 +51,7 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { if reply := send(base, os.Geteuid()); reply != "" { t.Fatal(reply) } - a.handle_command(command.ReadLiveRegion10) + a.handleCommand(command.ReadLiveRegion10) if got := voice.messages[len(voice.messages)-1]; got != "Codex working" { t.Fatal(got) } @@ -61,7 +61,7 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { if reply := send(message, os.Geteuid()); reply != "" { t.Fatal(reply) } - override_read(t, a, snapshot) + overrideRead(t, a, snapshot) if len(voice.messages) != start { t.Fatal("partial text spoken", voice.messages[start:]) } @@ -69,7 +69,7 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { if reply := send(message, os.Geteuid()); reply != "" { t.Fatal(reply) } - override_read(t, a, snapshot) + overrideRead(t, a, snapshot) if got := voice.messages[len(voice.messages)-1]; got != "Complete message" { t.Fatal(got) } @@ -78,26 +78,26 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { if reply := send(message, os.Geteuid()); reply != "" { t.Fatal(reply) } - override_read(t, a, override_screen(1, "file output and repeated streaming text")) + overrideRead(t, a, overrideScreen(1, "file output and repeated streaming text")) if len(voice.messages) != start { t.Fatal("duplicate or tool output spoken", voice.messages[start:]) } - a.handle_command(command.Mute) + a.handleCommand(command.Mute) message.ID, message.Text = "muted", "Message while muted" if reply := send(message, os.Geteuid()); reply != "" { t.Fatal(reply) } - override_read(t, a, snapshot) + overrideRead(t, a, snapshot) if len(voice.messages) != start { t.Fatal("mute bypassed") } - a.handle_command(command.Mute) - a.handle_command(command.ReadLiveRegion1) + a.handleCommand(command.Mute) + a.handleCommand(command.ReadLiveRegion1) if got := voice.messages[len(voice.messages)-1]; got != "Message while muted" { t.Fatal(got) } // Stored replies must not replace raw screen review. - a.handle_command(command.CurrentLine) + a.handleCommand(command.CurrentLine) if slices.Contains(voice.messages[len(voice.messages)-1:], "Message while muted") { t.Fatal("history replaced raw review") } @@ -105,7 +105,7 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { if reply := send(base, os.Geteuid()); reply != "" { t.Fatal(reply) } - override_read(t, a, override_screen(1, "[Username@host directory] $")) + overrideRead(t, a, overrideScreen(1, "[Username@host directory] $")) if a.overrideCurrent != nil || a.overrides[1] != nil { t.Fatal("shell did not restore defaults") } @@ -114,28 +114,28 @@ func TestCodexEventRoutingWholeMessagesMuteReviewAndExit(t *testing.T) { func TestCodexWorkingToneUsesExistingSoundGates(t *testing.T) { for _, mode := range []string{"enabled", "sound off", "progress off", "muted", "automatic off", "menu"} { t.Run(mode, func(t *testing.T) { - a, _ := persistence_application(t, true) - snapshot := override_screen(1, "OpenAI Codex") - override_read(t, a, snapshot) - a.select_override("codex") - override_read(t, a, snapshot) + a, _ := persistenceApplication(t, true) + snapshot := overrideScreen(1, "OpenAI Codex") + overrideRead(t, a, snapshot) + a.selectOverride("codex") + overrideRead(t, a, snapshot) sounds := &fakeSounds{} a.cues = sounds a.settings.live.Presentation.Sound.Enabled = mode != "sound off" a.settings.live.Presentation.Progress.Enabled = mode != "progress off" a.settings.live.Reading.Automatic = mode != "automatic off" - a.configure_reader() + a.configureReader() if mode == "muted" { - a.handle_command(command.Mute) + a.handleCommand(command.Mute) } if mode == "menu" { - a.open_applications() + a.openApplications() } adapter := a.overrideCurrent.adapter.(*codex.Adapter) if err := adapter.Accept(codex.Event{Version: 1, Epoch: 1, Session: "fixture-session", Kind: "status", Status: "working"}); err != nil { t.Fatal(err) } - override_read(t, a, snapshot) + overrideRead(t, a, snapshot) want := mode == "enabled" || mode == "muted" || mode == "automatic off" if (len(sounds.progress) > 0) != want { t.Fatal(mode, sounds.progress) @@ -143,8 +143,8 @@ func TestCodexWorkingToneUsesExistingSoundGates(t *testing.T) { if err := adapter.Accept(codex.Event{Version: 1, Epoch: 1, Session: "fixture-session", Kind: "status", Status: "permission"}); err != nil { t.Fatal(err) } - override_read(t, a, snapshot) - if _, ok := a.engine.Next_progress(time.Now().Add(2 * time.Second)); ok { + overrideRead(t, a, snapshot) + if _, ok := a.engine.NextProgress(time.Now().Add(2 * time.Second)); ok { t.Fatal("approval wait retained working beep") } }) diff --git a/internal/app/commands.go b/internal/app/commands.go index 7f5b06d8..e2c70c67 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -24,16 +24,16 @@ import ( "git.stormux.org/storm/fenrir/internal/command" "git.stormux.org/storm/fenrir/internal/config" - "git.stormux.org/storm/fenrir/internal/datetime" "git.stormux.org/storm/fenrir/internal/diagnostic" "git.stormux.org/storm/fenrir/internal/i18n" "git.stormux.org/storm/fenrir/internal/input" "git.stormux.org/storm/fenrir/internal/presentation" "git.stormux.org/storm/fenrir/internal/scripts" "git.stormux.org/storm/fenrir/internal/version" + "git.stormux.org/storm/screenreader-common/datetime" ) -func (a *application) handle_input(decision input.Decision) { +func (a *application) handleInput(decision input.Decision) { started := time.Now() defer func() { diagnostic.Timing("input action", started, "command", decision.Command) }() if a.quitting { @@ -44,20 +44,20 @@ func (a *application) handle_input(decision input.Decision) { "ui_active", a.ui.active) if decision.Interrupt { if decision.Forward && !a.ui.active && a.overrideCurrent != nil { - if observer, ok := a.overrideCurrent.adapter.(interface{ Note_key(uint16) }); ok { - observer.Note_key(decision.Code) + if observer, ok := a.overrideCurrent.adapter.(interface{ NoteKey(uint16) }); ok { + observer.NoteKey(decision.Code) } } a.spellFeedback++ - a.engine.Reset_progress() + a.engine.ResetProgress() if a.cues != nil { - a.cues.Clear_progress() + a.cues.ClearProgress() } a.clipboards.feedback++ a.voice.Interrupt() - a.engine.Note_input(decision.Forward && !a.ui.active, decision.Typing, decision.WordBoundary) + a.engine.NoteInput(decision.Forward && !a.ui.active, decision.Typing, decision.WordBoundary) if decision.Forward && decision.Deletion && !a.ui.active { - a.engine.Note_deletion() + a.engine.NoteDeletion() } } if decision.Keypress && a.temporarySilence { @@ -70,17 +70,17 @@ func (a *application) handle_input(decision input.Decision) { if !decision.Interrupt { a.voice.Interrupt() } - a.ui.handle_tutorial(*decision.Learn) + a.ui.handleTutorial(*decision.Learn) } } else if decision.UI != nil { a.ui.handle(*decision.UI) } return } - a.handle_command(decision.Command) + a.handleCommand(decision.Command) } -func (a *application) handle_command(id command.ID) { +func (a *application) handleCommand(id command.ID) { if a.overrideTransition && id != "" && id != command.Quit && id != command.Mute { a.voice.Say(i18n.T("Settings are busy")) return @@ -94,18 +94,18 @@ func (a *application) handle_command(id command.ID) { switch id { case "": case command.Help: - a.ui.open_tutorial(a.options.Bindings, a.options.Scripts, a.settings.live.General.ScriptKeys) + a.ui.openTutorial(a.options.Bindings, a.options.Scripts, a.settings.live.General.ScriptKeys) case command.LastNotification: - a.last_notification() + a.lastNotification() case command.NotificationHistory: - a.open_notifications() + a.openNotifications() case command.Version: a.present(i18n.Format("Fenrir screen reader version {0}-{1}", version.Version, version.Channel), "") case command.Time: - text, _ := datetime.Format_time(a.settings.live.Presentation.DateTime.TimeFormat, time.Now()) + text, _ := datetime.FormatTime(a.settings.live.Presentation.DateTime.TimeFormat, time.Now()) a.present(text, "") case command.Date: - text, _ := datetime.Format_date(a.settings.live.Presentation.DateTime.DateFormat, time.Now()) + text, _ := datetime.FormatDate(a.settings.live.Presentation.DateTime.DateFormat, time.Now()) a.present(text, "") case command.Quit: if a.saver.busy { @@ -114,20 +114,20 @@ func (a *application) handle_command(id command.ID) { a.quitting = true } case command.EmojiMenu: - a.ui.open_emoji(a.clipboards) + a.ui.openEmoji(a.clipboards) case command.SpellcheckMenu: - a.spellMenu.open(a.engine.Spellcheck_word()) + a.spellMenu.open(a.engine.SpellcheckWord()) case command.FenrirMenu: - a.open_settings() + a.openSettings() case command.ApplicationsMenu: - a.open_applications() + a.openApplications() case command.SaveSettings: - a.save_settings() + a.saveSettings() case command.ProgressMonitor: - a.quick.mark_changed("presentation.progress.enabled") + a.quick.markChanged("presentation.progress.enabled") a.settings.live.Presentation.Progress.Enabled = !a.settings.live.Presentation.Progress.Enabled a.settings.saveDraft.Presentation.Progress = a.settings.live.Presentation.Progress - a.engine.Configure_progress(a.settings.live.Presentation.Progress.Enabled) + a.engine.ConfigureProgress(a.settings.live.Presentation.Progress.Enabled) if a.settings.live.Presentation.Progress.Enabled { a.voice.Say(i18n.T("Progress monitoring enabled")) } else { @@ -136,21 +136,21 @@ func (a *application) handle_command(id command.ID) { case command.Mute: // This toggle lasts only for this session, including when settings // are saved. Speech enablement belongs to the settings menu/file. - a.muted = a.voice.Toggle_mute() - a.present_speech_state() + a.muted = a.voice.ToggleMute() + a.presentSpeechState() case command.TempDisableSpeech: if !a.muted && !a.temporarySilence { a.present(i18n.T("speech temporary disabled"), presentation.SpeechOff) a.temporarySilence = true } case command.PassNext: - a.keyboards.Pass_next() + a.keyboards.PassNext() a.voice.Say(i18n.T("Forward next keypress")) default: - saved := config.Primary_voice(a.settings.resetBase) + saved := config.PrimaryVoice(a.settings.resetBase) a.quick.savedVoice = &saved if a.quick.command(id, &a.settings.live, a.voice) { - a.apply_quick_settings() + a.applyQuickSettings() return } if script, exists := a.options.Scripts[id]; exists { @@ -163,30 +163,30 @@ func (a *application) handle_command(id command.ID) { if a.clipboards.command(id) { return } - a.review_command(id) + a.reviewCommand(id) } } -func (a *application) review_command(id command.ID) { - regionRevision := a.engine.Region_revision() +func (a *application) reviewCommand(id command.ID) { + regionRevision := a.engine.RegionRevision() result := a.engine.Command(id) - if regionRevision != a.engine.Region_revision() { - a.reading_regions_changed() + if regionRevision != a.engine.RegionRevision() { + a.readingRegionsChanged() } if message := result.Attributes; message != nil { - a.present_attributes(*message) + a.presentAttributes(*message) } if message := result.Indentation; message != nil { - a.present_indentation(*message) + a.presentIndentation(*message) } switch id { case command.ToggleTracking: - a.settings.saveDraft.Reading.Mode = a.engine.Tracking_mode() + a.settings.saveDraft.Reading.Mode = a.engine.TrackingMode() } if spelling := result.Spelling; spelling != nil && !a.temporarySilence { - a.voice.say_spelling(*spelling) + a.voice.saySpelling(*spelling) } else if char := result.Character; char != nil && !a.temporarySilence { - a.voice.say_character(*char, strings.TrimPrefix(result.Text, presentation.Character(*char))) + a.voice.sayCharacter(*char, strings.TrimPrefix(result.Text, presentation.Character(*char))) } else { a.present(result.Text, result.Cue) } diff --git a/internal/app/date_time_test.go b/internal/app/date_time_test.go index 13db1cb6..16f85500 100644 --- a/internal/app/date_time_test.go +++ b/internal/app/date_time_test.go @@ -13,10 +13,10 @@ import ( "git.stormux.org/storm/fenrir/internal/command" "git.stormux.org/storm/fenrir/internal/config" - "git.stormux.org/storm/fenrir/internal/datetime" "git.stormux.org/storm/fenrir/internal/input" "git.stormux.org/storm/fenrir/internal/interaction" "git.stormux.org/storm/fenrir/internal/screen" + "git.stormux.org/storm/screenreader-common/datetime" ) func TestTimeDateMenuAppliesOnlyAfterSave(t *testing.T) { @@ -78,9 +78,9 @@ func TestTimeDateMenuAppliesOnlyAfterSave(t *testing.T) { formats.TimeFormat, formats.DateFormat = "24-hour-seconds-words", "full-dm" } for _, id := range []command.ID{command.Time, command.Date} { - format, value := datetime.Format_time, formats.TimeFormat + format, value := datetime.FormatTime, formats.TimeFormat if id == command.Date { - format, value = datetime.Format_date, formats.DateFormat + format, value = datetime.FormatDate, formats.DateFormat } before, _ := format(value, time.Now()) handle(input.Decision{Command: id, Interrupt: true}) diff --git a/internal/app/deletion_test.go b/internal/app/deletion_test.go index 2e7590c2..3ab7d33f 100644 --- a/internal/app/deletion_test.go +++ b/internal/app/deletion_test.go @@ -19,7 +19,7 @@ func TestDeletionThroughSharedRouterWithAutoreadOff(t *testing.T) { for _, key := range []uint16{input.KeyBackspace, input.KeyDelete} { for _, mode := range []string{"enabled", "muted", "temporary silence", "speech disabled"} { t.Run(mode+"/"+map[uint16]string{input.KeyBackspace: "backspace", input.KeyDelete: "delete"}[key], func(t *testing.T) { - router, err := input.New_router(input.Layout{Bindings: []input.Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) + router, err := input.NewRouter(input.Layout{Bindings: []input.Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) if err != nil { t.Fatal(err) } diff --git a/internal/app/emoji_menu.go b/internal/app/emoji_menu.go index e9f8e5d4..4a1cc480 100644 --- a/internal/app/emoji_menu.go +++ b/internal/app/emoji_menu.go @@ -11,8 +11,8 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func (ui *internalUI) open_emoji(clipboards *clipboardHost) { - session, err := emoji.New_session() +func (ui *internalUI) openEmoji(clipboards *clipboardHost) { + session, err := emoji.NewSession() if err != nil { ui.failed("Could not open Emoji Menu: {0}", err) return @@ -21,7 +21,7 @@ func (ui *internalUI) open_emoji(clipboards *clipboardHost) { ui.failed("Could not open Emoji Menu: {0}", err) return } - ui.configure_session(session) + ui.configureSession(session) ui.session = session ui.action = func(action string, session *interaction.Session) { if action != "copy_emoji" { diff --git a/internal/app/emoji_menu_test.go b/internal/app/emoji_menu_test.go index 07e4c773..ecee2e4e 100644 --- a/internal/app/emoji_menu_test.go +++ b/internal/app/emoji_menu_test.go @@ -18,13 +18,13 @@ import ( func TestEmojiMenuCancellationCopyAndStaleClipboardSync(t *testing.T) { for _, query := range []string{"Jack", "Black cat", "United States", "Coffin"} { t.Run(query, func(t *testing.T) { - host, worker, _, _ := clipboard_fixture() + host, worker, _, _ := clipboardFixture() host.add("original", false) host.poll() stale := worker.requests[0] keys, voice := &fakeKeys{}, &fakeVoice{} - ui := new_internal_ui(context.Background(), keys, voice) - ui.open_emoji(host) + ui := newInternalUi(context.Background(), keys, voice) + ui.openEmoji(host) if voice.messages[0] != "Emoji Menu. All tab" { t.Fatal(voice.messages) } @@ -34,7 +34,7 @@ func TestEmojiMenuCancellationCopyAndStaleClipboardSync(t *testing.T) { if got, _ := host.history.Current(); got != "original" || host.revision != stale.Revision { t.Fatal("cancel changed clipboard", got) } - ui.open_emoji(host) + ui.openEmoji(host) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Text: query + "zzzz"}) ui.handle(interaction.Key{Name: "enter"}) @@ -69,10 +69,10 @@ func TestEmojiMenuCancellationCopyAndStaleClipboardSync(t *testing.T) { } func TestEmojiMenuCaptureFailureDoesNotChangeClipboard(t *testing.T) { - host, _, _, _ := clipboard_fixture() + host, _, _, _ := clipboardFixture() keys, voice := &fakeKeys{captureErr: errors.New("capture refused")}, &fakeVoice{} - ui := new_internal_ui(context.Background(), keys, voice) - ui.open_emoji(host) + ui := newInternalUi(context.Background(), keys, voice) + ui.openEmoji(host) if ui.active || host.revision != 0 || len(voice.messages) != 1 { t.Fatal(ui.active, host.revision, voice.messages) } diff --git a/internal/app/event_loop.go b/internal/app/event_loop.go index 8d41529c..3cf8bb0d 100644 --- a/internal/app/event_loop.go +++ b/internal/app/event_loop.go @@ -61,7 +61,7 @@ func run(ctx context.Context, source Source, keyboards Keyboards, voices Speaker if len(options) > 0 { opts = options[0] } - a, err := new_application(ctx, source, keyboards, voices, opts) + a, err := newApplication(ctx, source, keyboards, voices, opts) if err != nil { return err } @@ -111,12 +111,12 @@ func (a *application) loop(ticks <-chan time.Time) error { } clipboardTick := time.NewTicker(500 * time.Millisecond) defer clipboardTick.Stop() - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { return err } scan := time.NewTicker(time.Second) defer scan.Stop() - if err := a.poll_input(true); err != nil { + if err := a.pollInput(true); err != nil { return err } if a.options.Ready != nil { @@ -134,53 +134,53 @@ func (a *application) loop(ticks <-chan time.Time) error { } select { case <-notificationUpdates: - a.refresh_notification_history() + a.refreshNotificationHistory() case discovery := <-a.speechChoices: a.quick.discovery = discovery case loaded := <-a.overrideLoads: loaded() case result := <-a.preview.results: - a.speech_preview_result(result) + a.speechPreviewResult(result) case result := <-a.speechResults: - a.speech_result(result) + a.speechResult(result) if len(a.overrides) != 0 || a.overrideCurrent != nil { a.overrideDirty = true } case result := <-spellResults: - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { return err } - a.spellcheck_result(result) + a.spellcheckResult(result) case err := <-a.saver.results: - a.settings_save_result(err) + a.settingsSaveResult(err) a.overrideDirty = true a.quitting = a.quitAfterSave case result := <-scriptResults: - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { return err } - a.script_result(result) + a.scriptResult(result) case request := <-remoteRequests: - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { return err } - a.remote_request(request) + a.remoteRequest(request) case err := <-historyErrors: slog.Warn("clipboard history update failed", "error", err, "at", time.Now()) a.present(err.Error(), presentation.Error) case update := <-historyUpdates: - a.clipboards.history_update(update) + a.clipboards.historyUpdate(update) a.settings.live.Clipboard.Persistent = a.clipboards.settings.Persistent a.settings.saveDraft.Clipboard.Persistent = a.clipboards.settings.Persistent case result := <-clipboardResults: - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { return err } a.clipboards.result(result) case <-clipboardTick.C: a.clipboards.poll() case update := <-a.ui.updates: - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { return err } a.ui.update(update) @@ -192,14 +192,14 @@ func (a *application) loop(ticks <-chan time.Time) error { slog.Warn("sound disabled", "error", err, "at", time.Now()) soundErrors, a.cues = nil, nil case err := <-a.source.Events(): - if err := a.screen_event(err); err != nil { + if err := a.screenEvent(err); err != nil { return err } case err := <-a.keyboards.Events(): if err != nil { return fmt.Errorf("keyboard watcher failed: %w", err) } - if err := a.poll_input(true); err != nil { + if err := a.pollInput(true); err != nil { return err } case <-scan.C: @@ -207,20 +207,20 @@ func (a *application) loop(ticks <-chan time.Time) error { return err } // Acquire newly discovered idle keyboards before their first key. - if err := a.poll_input(true); err != nil { + if err := a.pollInput(true); err != nil { return err } case <-ticks: if a.overrideDirty { a.overrideDirty = false - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { return err } } - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { return err } - a.play_progress() + a.playProgress() a.spellMenu.poll() } } diff --git a/internal/app/feedback.go b/internal/app/feedback.go index bd41d129..380f7625 100644 --- a/internal/app/feedback.go +++ b/internal/app/feedback.go @@ -38,7 +38,7 @@ func (a *application) present(text string, cue presentation.Cue) { } } -func (a *application) present_speech_state() { +func (a *application) presentSpeechState() { if a.muted { a.play(presentation.SpeechOff) } else { @@ -46,20 +46,20 @@ func (a *application) present_speech_state() { } } -func (a *application) present_indentation(message presentation.Message) { +func (a *application) presentIndentation(message presentation.Message) { if a.temporarySilence || a.muted { return } accepted := false if message.Indentation != nil && a.settings.live.Presentation.Sound.Enabled && a.settings.live.Presentation.Sound.Volume > 0 && a.cues != nil { - accepted = a.cues.Play_indentation(message.Indentation.Level) + accepted = a.cues.PlayIndentation(message.Indentation.Level) } if !accepted || message.Indentation.Speech { a.voice.Say(message.Text) } } -func (a *application) present_attributes(message presentation.Message) { +func (a *application) presentAttributes(message presentation.Message) { if a.temporarySilence || a.muted { return } @@ -69,22 +69,22 @@ func (a *application) present_attributes(message presentation.Message) { } } -func (a *application) play_progress() { +func (a *application) playProgress() { if a.ui.active { - a.engine.Reset_progress() + a.engine.ResetProgress() } if a.cues != nil { if a.ui.active { - a.cues.Clear_progress() - } else if !a.engine.Progress_active() { + a.cues.ClearProgress() + } else if !a.engine.ProgressActive() { // A passive redraw can reset detection halfway through a beep. // Discard stale waiting tones, but let the current one finish. - a.cues.Discard_progress() + a.cues.DiscardProgress() } } if !a.ui.active && a.settings.live.Presentation.Sound.Enabled && a.cues != nil { - if value, ok := a.engine.Next_progress(time.Now()); ok { - if a.cues.Play_progress(value) { + if value, ok := a.engine.NextProgress(time.Now()); ok { + if a.cues.PlayProgress(value) { diagnostic.Record("progress tone", "percentage", value) } } diff --git a/internal/app/fenrir_menu.go b/internal/app/fenrir_menu.go index 387f732a..89bcb078 100644 --- a/internal/app/fenrir_menu.go +++ b/internal/app/fenrir_menu.go @@ -27,15 +27,15 @@ import ( "strings" ) -func (ui *internalUI) open_settings(settings config.Settings, path string, liveQuick ...config.Settings) { - ui.open_settings_context(settings, path, nil, preferences.MenuTitle, "", liveQuick...) +func (ui *internalUI) openSettings(settings config.Settings, path string, liveQuick ...config.Settings) { + ui.openSettingsContext(settings, path, nil, preferences.MenuTitle, "", liveQuick...) } -func (ui *internalUI) open_application_settings(settings config.Settings, path string, base config.Settings, name string) { - ui.open_settings_context(settings, path, &base, i18n.Format("{0} application settings", name), i18n.Format("{0} application settings saved.", name)) +func (ui *internalUI) openApplicationSettings(settings config.Settings, path string, base config.Settings, name string) { + ui.openSettingsContext(settings, path, &base, i18n.Format("{0} application settings", name), i18n.Format("{0} application settings saved.", name)) } -func (ui *internalUI) open_settings_context(settings config.Settings, path string, applicationBase *config.Settings, title string, savedMessage string, liveQuick ...config.Settings) { +func (ui *internalUI) openSettingsContext(settings config.Settings, path string, applicationBase *config.Settings, title string, savedMessage string, liveQuick ...config.Settings) { generation, err := ui.begin(title) if err != nil { ui.failed("Could not open Fenrir Menu: {0}", err) @@ -68,12 +68,12 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin var doc *config.Document var err error if applicationBase != nil { - doc, err = config.Open_application_document(path, *applicationBase) + doc, err = config.OpenApplicationDocument(path, *applicationBase) if err == nil { doc.Settings = settings } } else { - doc, err = config.Open_document(path, settings) + doc, err = config.OpenDocument(path, settings) } if err != nil { ui.post(uiUpdate{generation: generation, close: true, speech: i18n.Format("Could not open Fenrir Menu: {0}", err.Error())}) @@ -83,10 +83,10 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin doc.Settings.Keyboard.FenrirKeys = append([]string(nil), settings.Keyboard.FenrirKeys...) } if len(liveQuick) != 0 { - copy_quick_settings(&doc.Settings, liveQuick[0]) + copyQuickSettings(&doc.Settings, liveQuick[0]) } if speechOverride != nil { - copy_speech_selection(&doc.Settings.Presentation.Speech, *speechOverride) + copySpeechSelection(&doc.Settings.Presentation.Speech, *speechOverride) } var discovery preferences.Discovery if ui.discoverChoices != nil { @@ -94,9 +94,9 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin } var session *interaction.Session if applicationBase != nil { - session, err = preferences.New_application_session(doc.Settings, doc.Order, title, discovery.Choices(doc.Settings)) + session, err = preferences.NewApplicationSession(doc.Settings, doc.Order, title, discovery.Choices(doc.Settings)) } else { - session, err = preferences.New_session(doc.Settings, doc.Order, discovery.Choices(doc.Settings)) + session, err = preferences.NewSession(doc.Settings, doc.Order, discovery.Choices(doc.Settings)) } if err != nil { ui.post(uiUpdate{generation: generation, close: true, speech: i18n.Format("Could not open Fenrir Menu: {0}", err.Error())}) @@ -105,7 +105,7 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin profileDraft := doc.Settings.VoiceProfiles.Clone() baseReadSettings := preferences.Settings if applicationBase != nil { - baseReadSettings = preferences.Application_settings + baseReadSettings = preferences.ApplicationSettings } readSettings := func(s *interaction.Session, base config.Settings) (config.Settings, error) { next, err := baseReadSettings(s, base) @@ -134,16 +134,16 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin if ui.cancelTest != nil { draft, err := readSettings(session, doc.Settings) if err != nil || draft.Presentation.Speech != tested { - ui.stop_test() + ui.stopTest() } } - if !discovery.Refresh_speech(session, &previous) { + if !discovery.RefreshSpeech(session, &previous) { return } driverID := previous.Presentation.Speech.Driver if cached, ok := catalogs[driverID]; ok { discovery = cached - discovery.Refresh_catalog(session, previous) + discovery.RefreshCatalog(session, previous) return } discovery = preferences.Discovery{Driver: driverID} @@ -166,7 +166,7 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin return } discovery = result - discovery.Refresh_catalog(session, previous) + discovery.RefreshCatalog(session, previous) previewSpeech(session) if ui.catalog != nil { ui.catalog(result) @@ -183,21 +183,21 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin return } selectedProfile := session.Values()["voice-profiles.profiles"].Selected - ui.manage_profiles(name, session, draft, discovery, func(next config.Settings) { + ui.manageProfiles(name, session, draft, discovery, func(next config.Settings) { profileDraft = next.VoiceProfiles.Clone() previous = next - restored, err := preferences.New_session(next, doc.Order, discovery.Choices(next)) + restored, err := preferences.NewSession(next, doc.Order, discovery.Choices(next)) if err != nil { ui.failed("Could not open Fenrir Menu: {0}", err) return } - restored.Focus_control("voice-profiles", "profiles") + restored.FocusControl("voice-profiles", "profiles") if len(next.VoiceProfiles.Profiles) > len(draft.VoiceProfiles.Profiles) { selectedProfile = len(next.VoiceProfiles.Profiles) - 1 } restored.Select("voice-profiles", "profiles", min(selectedProfile, len(next.VoiceProfiles.Profiles)-1)) if len(next.VoiceProfiles.Profiles) == 0 { - restored.Focus_control("voice-profiles", "add") + restored.FocusControl("voice-profiles", "add") } if ui.session != nil { ui.session.Close() @@ -214,10 +214,10 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin if name == "test-synthesizer" { draft, err := readSettings(session, doc.Settings) if err != nil { - ui.test_failed(err) + ui.testFailed(err) return } - ui.stop_test() + ui.stopTest() testSequence++ sequence := testSequence testCtx, cancel := context.WithCancel(ui.ctx) @@ -247,7 +247,7 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin } ui.cancelTest = nil if err != nil && !errors.Is(err, context.Canceled) { - ui.test_failed(err) + ui.testFailed(err) } }} select { @@ -265,7 +265,7 @@ func (ui *internalUI) open_settings_context(settings config.Settings, path strin ui.failed("Could not save settings: {0}", err) return } - ui.stop_test() + ui.stopTest() if ui.saveSettings(doc, draft, func(err error) { if err != nil { ui.update(uiUpdate{generation: generation, session: session, action: action, speech: i18n.Format("Could not save settings: {0}", err.Error())}) diff --git a/internal/app/hardware_form_test.go b/internal/app/hardware_form_test.go index 22f764cc..54d8c0e0 100644 --- a/internal/app/hardware_form_test.go +++ b/internal/app/hardware_form_test.go @@ -19,10 +19,10 @@ import ( "git.stormux.org/storm/fenrir/internal/speech" ) -func focus_ui_control(t *testing.T, ui *internalUI, id string) { +func focusUiControl(t *testing.T, ui *internalUI, id string) { t.Helper() for range 100 { - if control, ok := ui.session.Focused_control(); ok && control.ID == id { + if control, ok := ui.session.FocusedControl(); ok && control.ID == id { return } ui.handle(interaction.Key{Name: "tab"}) @@ -30,28 +30,28 @@ func focus_ui_control(t *testing.T, ui *internalUI, id string) { t.Fatal("control not reachable", id) } -func hardware_form_application(t *testing.T) (*application, string, *fakeVoice) { +func hardwareFormApplication(t *testing.T) (*application, string, *fakeVoice) { t.Helper() path := filepath.Join(t.TempDir(), "settings.toml") if err := config.Save(path, config.Defaults()); err != nil { t.Fatal(err) } voice := &fakeVoice{} - a := settings_ui_application(t, &fakeKeys{}, voice, path) - a.ui.open_settings(a.settings.live, path) - receive_ui(t, a.ui) + a := settingsUiApplication(t, &fakeKeys{}, voice, path) + a.ui.openSettings(a.settings.live, path) + receiveUi(t, a.ui) t.Cleanup(func() { a.ui.close(); a.ui.testWorkers.Wait() }) - focus_ui_control(t, a.ui, "speech.driver") + focusUiControl(t, a.ui, "speech.driver") a.ui.handle(interaction.Key{Name: "down"}) - focus_ui_control(t, a.ui, "speech.hardware_device") + focusUiControl(t, a.ui, "speech.hardware_device") a.ui.handle(interaction.Key{Text: "/dev/fixture-synth"}) - focus_ui_control(t, a.ui, "speech.hardware_baud_rate") + focusUiControl(t, a.ui, "speech.hardware_baud_rate") a.ui.handle(interaction.Key{Name: "end"}) return a, path, voice } func TestHardwarePreviewUsesUnsavedDraftAndSaveKeepsActiveDriver(t *testing.T) { - a, path, _ := hardware_form_application(t) + a, path, _ := hardwareFormApplication(t) before, _ := os.ReadFile(path) requested, stopped := make(chan config.Speech, 2), make(chan struct{}, 2) a.ui.testSpeech = func(ctx context.Context, selected, current config.Speech) error { @@ -63,7 +63,7 @@ func TestHardwarePreviewUsesUnsavedDraftAndSaveKeepsActiveDriver(t *testing.T) { stopped <- struct{}{} return ctx.Err() } - focus_ui_control(t, a.ui, "speech.test") + focusUiControl(t, a.ui, "speech.test") a.ui.handle(interaction.Key{Name: "enter"}) select { case selected := <-requested: @@ -79,7 +79,7 @@ func TestHardwarePreviewUsesUnsavedDraftAndSaveKeepsActiveDriver(t *testing.T) { if a.settings.live.Presentation.Speech.Driver != "speech-dispatcher" || !a.ui.active { t.Fatal("test replaced active driver or closed menu") } - focus_ui_control(t, a.ui, "speech.hardware_device") + focusUiControl(t, a.ui, "speech.hardware_device") a.ui.handle(interaction.Key{Ctrl: true, Text: "a"}) a.ui.handle(interaction.Key{Text: "/dev/fixture-updated"}) select { @@ -87,9 +87,9 @@ func TestHardwarePreviewUsesUnsavedDraftAndSaveKeepsActiveDriver(t *testing.T) { case <-time.After(time.Second): t.Fatal("editing did not cancel preview") } - focus_ui_control(t, a.ui, "ok") + focusUiControl(t, a.ui, "ok") a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) + finishPersistence(t, a, false) saved, _, err := config.Load(path, nil) if err != nil || saved.Presentation.Speech.HardwareDevice != "/dev/fixture-updated" || saved.Presentation.Speech.HardwareBaudRate != 115200 { t.Fatal(saved, err) @@ -100,14 +100,14 @@ func TestHardwarePreviewUsesUnsavedDraftAndSaveKeepsActiveDriver(t *testing.T) { } func TestHardwarePreviewFailureAndCloseDoNotWriteOrDeliverStaleFeedback(t *testing.T) { - a, path, voice := hardware_form_application(t) + a, path, voice := hardwareFormApplication(t) before, _ := os.ReadFile(path) a.ui.testSpeech = func(context.Context, config.Speech, config.Speech) error { return errors.New("fixture port unavailable") } - focus_ui_control(t, a.ui, "speech.test") + focusUiControl(t, a.ui, "speech.test") a.ui.handle(interaction.Key{Name: "enter"}) - receive_ui(t, a.ui) + receiveUi(t, a.ui) if got := voice.messages[len(voice.messages)-1]; !strings.Contains(got, "Voice test failed") || !strings.Contains(got, "fixture port unavailable") { t.Fatal(got) } @@ -128,7 +128,7 @@ func TestHardwarePreviewFailureAndCloseDoNotWriteOrDeliverStaleFeedback(t *testi close(release) a.ui.testWorkers.Wait() for len(a.ui.updates) > 0 { - receive_ui(t, a.ui) + receiveUi(t, a.ui) } if strings.Contains(strings.Join(voice.messages, "|"), "stale fixture failure") { t.Fatal("late failure escaped closed menu", voice.messages) @@ -143,18 +143,18 @@ type previewVoice struct { previews chan speech.Parameters } -func (v *previewVoice) Say_with_parameters(_ string, parameters speech.Parameters) { +func (v *previewVoice) SayWithParameters(_ string, parameters speech.Parameters) { v.previews <- parameters } func TestHardwarePreviewReusesOwnedConnectionAndNormalizesDefaultBaud(t *testing.T) { voice := &previewVoice{previews: make(chan speech.Parameters, 1)} - ui := new_internal_ui(context.Background(), &fakeKeys{}, &echoSpeaker{Speaker: voice}) + ui := newInternalUi(context.Background(), &fakeKeys{}, &echoSpeaker{Speaker: voice}) current := config.Defaults().Presentation.Speech current.Driver, current.HardwareDevice = "dectalk", "/dev/fixture-owned" selected := current selected.HardwareBaudRate, selected.Rate = 9600, 20 - if err := ui.test_synthesizer(context.Background(), selected, current); err != nil { + if err := ui.testSynthesizer(context.Background(), selected, current); err != nil { t.Fatal(err) } select { @@ -171,7 +171,7 @@ func TestHardwarePreviewReusesOwnedConnectionAndNormalizesDefaultBaud(t *testing } func TestDriverCatalogArrivesWithoutOverwritingAnotherDriverOrMovingFocus(t *testing.T) { - a, _, _ := hardware_form_application(t) + a, _, _ := hardwareFormApplication(t) queries, releases := make(chan string, 4), make(chan struct{}, 4) a.ui.discoverChoices = func(settings config.Settings) preferences.Discovery { id := settings.Presentation.Speech.Driver @@ -185,10 +185,10 @@ func TestDriverCatalogArrivesWithoutOverwritingAnotherDriverOrMovingFocus(t *tes base := a.settings.live base.Presentation.Speech.Driver, base.Presentation.Speech.HardwareDevice = "dectalk", "/dev/fixture-synth" go func() { releases <- struct{}{} }() - a.ui.open_settings(base, "") - receive_ui(t, a.ui) + a.ui.openSettings(base, "") + receiveUi(t, a.ui) <-queries - focus_ui_control(t, a.ui, "speech.driver") + focusUiControl(t, a.ui, "speech.driver") a.ui.handle(interaction.Key{Name: "home"}) select { case id := <-queries: @@ -200,12 +200,12 @@ func TestDriverCatalogArrivesWithoutOverwritingAnotherDriverOrMovingFocus(t *tes } a.ui.handle(interaction.Key{Name: "down"}) releases <- struct{}{} - receive_ui(t, a.ui) + receiveUi(t, a.ui) if !a.ui.session.Values()["presentation.speech.module"].Hidden { t.Fatal("stale catalog changed driver visibility") } a.ui.handle(interaction.Key{Name: "home"}) - control, _ := a.ui.session.Focused_control() + control, _ := a.ui.session.FocusedControl() if control.ID != "speech.driver" || len(a.ui.session.Values()["presentation.speech.module"].Choices) != 2 { t.Fatal("catalog/focus not restored", control) } diff --git a/internal/app/indentation_test.go b/internal/app/indentation_test.go index eff0b007..21b4b06d 100644 --- a/internal/app/indentation_test.go +++ b/internal/app/indentation_test.go @@ -21,7 +21,7 @@ import ( type unavailableIndentationSounds struct{ fakeSounds } -func (f *unavailableIndentationSounds) Play_indentation(int) bool { return false } +func (f *unavailableIndentationSounds) PlayIndentation(int) bool { return false } func TestReviewIndentationSpeechBeepCombinedFallbackAndSilence(t *testing.T) { for _, mode := range []string{"none", "speech", "beeps", "both"} { @@ -76,7 +76,7 @@ func TestQuickIndentationChoicesMenuCancelSaveAndRestart(t *testing.T) { t.Fatal(err) } voice := &fakeVoice{} - quick := new_quick_settings("speech-dispatcher") + quick := newQuickSettings("speech-dispatcher") quick.command(command.NextQuickCategory, &base, voice) quick.command(command.NextQuickEntry, &base, voice) for _, trial := range []struct { @@ -96,9 +96,9 @@ func TestQuickIndentationChoicesMenuCancelSaveAndRestart(t *testing.T) { if len(voice.parameters) != 0 || base.Reading.Indentation != "both" { t.Fatal(base, voice.parameters) } - ui := new_internal_ui(context.Background(), &fakeKeys{}, voice) - ui.open_settings(base, path, base) - receive_ui(t, ui) + ui := newInternalUi(context.Background(), &fakeKeys{}, voice) + ui.openSettings(base, path, base) + receiveUi(t, ui) control := ui.session.Values()["reading.indentation"] if control.Choices[control.Selected].ID != "both" { t.Fatal("menu lost quick choice", control) diff --git a/internal/app/internal_ui.go b/internal/app/internal_ui.go index 516ab61e..9c839d64 100644 --- a/internal/app/internal_ui.go +++ b/internal/app/internal_ui.go @@ -76,13 +76,13 @@ type uiUpdate struct { close bool } -func new_internal_ui(ctx context.Context, keys Keyboards, voice Speaker) *internalUI { +func newInternalUi(ctx context.Context, keys Keyboards, voice Speaker) *internalUI { ui := &internalUI{ctx: ctx, keys: keys, voice: voice, updates: make(chan uiUpdate, 8)} - ui.testSpeech = ui.test_synthesizer + ui.testSpeech = ui.testSynthesizer return ui } -func (ui *internalUI) stop_test() { +func (ui *internalUI) stopTest() { if ui.cancelTest != nil { ui.cancelTest() ui.cancelTest = nil @@ -93,7 +93,7 @@ func (ui *internalUI) begin(name string) (uint64, error) { if err := ui.keys.Capture(true); err != nil { return 0, err } - ui.stop_test() + ui.stopTest() ui.generation++ if ui.session != nil { ui.session.Close() @@ -109,7 +109,7 @@ func (ui *internalUI) close() { if !ui.active { return } - ui.stop_test() + ui.stopTest() if ui.tutorial != nil { if err := ui.keys.Capture(false); err != nil { slog.Error("release tutorial capture", "error", err, "at", time.Now()) @@ -182,10 +182,10 @@ func (ui *internalUI) update(update uiUpdate) { } } -func (ui *internalUI) configure_session(session *interaction.Session) { +func (ui *internalUI) configureSession(session *interaction.Session) { if ui.gridSettings != nil { settings := ui.gridSettings() - session.Configure_grid(settings.AnnounceGridCoordinates, settings.AnnounceItemPosition) + session.ConfigureGrid(settings.AnnounceGridCoordinates, settings.AnnounceItemPosition) } } @@ -201,7 +201,7 @@ func (ui *internalUI) handle(key interaction.Key) { if ui.session == nil { return } // Loading or saving still owns every key. - ui.configure_session(ui.session) + ui.configureSession(ui.session) result := ui.session.Handle(key) if result.Paste { text, ok := "", false diff --git a/internal/app/internal_ui_clipboard_test.go b/internal/app/internal_ui_clipboard_test.go index a5eada04..4cafeffd 100644 --- a/internal/app/internal_ui_clipboard_test.go +++ b/internal/app/internal_ui_clipboard_test.go @@ -9,8 +9,8 @@ import ( ) func TestInternalUIClipboardCutFailurePasteAndSecretClose(t *testing.T) { - ui := new_internal_ui(context.Background(), &fakeKeys{}, &fakeVoice{}) - s, err := interaction.New_session(interaction.Form{Type: interaction.TabForm, Title: "Edit", Tabs: []interaction.Tab{{ID: "p", Label: "Page", Controls: []interaction.Control{{ID: "e", Label: "Text", Kind: interaction.Entry, Text: "one two"}, {ID: "password", Label: "Password", Kind: interaction.Entry, Secret: true, Text: "private"}}}}}) + ui := newInternalUi(context.Background(), &fakeKeys{}, &fakeVoice{}) + s, err := interaction.NewSession(interaction.Form{Type: interaction.TabForm, Title: "Edit", Tabs: []interaction.Tab{{ID: "p", Label: "Page", Controls: []interaction.Control{{ID: "e", Label: "Text", Kind: interaction.Entry, Text: "one two"}, {ID: "password", Label: "Password", Kind: interaction.Entry, Secret: true, Text: "private"}}}}}) if err != nil { t.Fatal(err) } diff --git a/internal/app/internal_ui_settings_test.go b/internal/app/internal_ui_settings_test.go index 925f021b..11ab8cc5 100644 --- a/internal/app/internal_ui_settings_test.go +++ b/internal/app/internal_ui_settings_test.go @@ -12,10 +12,10 @@ import ( ) func TestInternalUIMenuSaveAndCancel(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) for _, save := range []bool{false, true} { - a.open_settings() - receive_ui(t, a.ui) + a.openSettings() + receiveUi(t, a.ui) for count := 0; a.ui.session.Describe() != "Internal UI tab"; count++ { if count > 20 { t.Fatal("Internal UI tab missing") @@ -28,7 +28,7 @@ func TestInternalUIMenuSaveAndCancel(t *testing.T) { } if save { a.ui.action("save", a.ui.session) - a.settings_save_result(committed_menu_result(t, a)) + a.settingsSaveResult(committedMenuResult(t, a)) } else { a.ui.handle(interaction.Key{Name: "escape"}) } @@ -37,7 +37,7 @@ func TestInternalUIMenuSaveAndCancel(t *testing.T) { if err != nil || loaded.InternalUI != want || a.settings.live.InternalUI != want { t.Fatal("save/cancel diverged", loaded.InternalUI, a.settings.live.InternalUI, err) } - a.ui.open_emoji(a.clipboards) + a.ui.openEmoji(a.clipboards) a.ui.handle(interaction.Key{Name: "tab"}) got := voice.messages[len(voice.messages)-1] if strings.Contains(got, "row 1, column 1") != !save || strings.Contains(got, "1 of ") != !save { diff --git a/internal/app/internal_ui_test.go b/internal/app/internal_ui_test.go index 11b1cd2f..1e0a38c5 100644 --- a/internal/app/internal_ui_test.go +++ b/internal/app/internal_ui_test.go @@ -34,9 +34,9 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func settings_ui_application(t *testing.T, keys *fakeKeys, voice *fakeVoice, path string) *application { +func settingsUiApplication(t *testing.T, keys *fakeKeys, voice *fakeVoice, path string) *application { t.Helper() - a, err := new_application(context.Background(), &fakeSource{}, keys, voice, RunOptions{Settings: config.Defaults(), ConfigPath: path}) + a, err := newApplication(context.Background(), &fakeSource{}, keys, voice, RunOptions{Settings: config.Defaults(), ConfigPath: path}) if err != nil { t.Fatal(err) } @@ -44,7 +44,7 @@ func settings_ui_application(t *testing.T, keys *fakeKeys, voice *fakeVoice, pat return a } -func receive_ui(t *testing.T, ui *internalUI) { +func receiveUi(t *testing.T, ui *internalUI) { t.Helper() select { case update := <-ui.updates: @@ -62,22 +62,22 @@ func TestSettingsMenuCancelSaveAndReopen(t *testing.T) { t.Fatal(err) } keys, voice := &fakeKeys{}, &fakeVoice{} - a := settings_ui_application(t, keys, voice, path) + a := settingsUiApplication(t, keys, voice, path) ui := a.ui - ui.open_settings(config.Defaults(), path) - receive_ui(t, ui) + ui.openSettings(config.Defaults(), path) + receiveUi(t, ui) if !ui.active || voice.messages[len(voice.messages)-1] != "Fenrir Menu. Presentation tab" { t.Fatal(ui.active, voice.messages) } - tab_to_control(t, ui, "speech.rate") + tabToControl(t, ui, "speech.rate") ui.handle(interaction.Key{Name: "up"}) if action == "escape" { ui.handle(interaction.Key{Name: "escape"}) } else { - tab_to_control(t, ui, map[string]string{"save": "ok", "cancel": "cancel"}[action]) + tabToControl(t, ui, map[string]string{"save": "ok", "cancel": "cancel"}[action]) ui.handle(interaction.Key{Name: "enter"}) if action == "save" { - finish_persistence(t, a, false) + finishPersistence(t, a, false) } } if ui.active || !reflect.DeepEqual(keys.captures, []bool{true, false}) { @@ -94,9 +94,9 @@ func TestSettingsMenuCancelSaveAndReopen(t *testing.T) { if err != nil || settings.Presentation.Speech.Rate != want { t.Fatal("wrong persistence", settings, err) } - ui.open_settings(config.Defaults(), path) - receive_ui(t, ui) - tab_to_control(t, ui, "speech.rate") + ui.openSettings(config.Defaults(), path) + receiveUi(t, ui) + tabToControl(t, ui, "speech.rate") if ui.session.Values()["presentation.speech.rate"].Number != float64(want) { t.Fatal("reopen did not reload settings") } @@ -199,10 +199,10 @@ func TestMenuSaveFailureRetainsEditsAndCapture(t *testing.T) { if err := config.Save(path, config.Defaults()); err != nil { t.Fatal(err) } - a := settings_ui_application(t, &fakeKeys{}, &fakeVoice{}, path) + a := settingsUiApplication(t, &fakeKeys{}, &fakeVoice{}, path) ui := a.ui - ui.open_settings(config.Defaults(), path) - receive_ui(t, ui) + ui.openSettings(config.Defaults(), path) + receiveUi(t, ui) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Name: "space"}) // Speech enabled false. other := config.Defaults() @@ -211,7 +211,7 @@ func TestMenuSaveFailureRetainsEditsAndCapture(t *testing.T) { t.Fatal(err) } ui.action("save", ui.session) - finish_persistence(t, a, true) + finishPersistence(t, a, true) if !ui.active || ui.session == nil || ui.session.Values()["presentation.speech.enabled"].Checked { t.Fatal("failed save lost draft or capture") } @@ -229,16 +229,16 @@ func TestMenuSaveFailureRetainsEditsAndCapture(t *testing.T) { func TestMenuRejectsStaleWorkerAndCaptureFailure(t *testing.T) { keys := &fakeKeys{captureErr: errors.New("fixture capture denied")} voice := &fakeVoice{} - ui := new_internal_ui(context.Background(), keys, voice) - ui.open_settings(config.Defaults(), filepath.Join(t.TempDir(), "settings.toml")) + ui := newInternalUi(context.Background(), keys, voice) + ui.openSettings(config.Defaults(), filepath.Join(t.TempDir(), "settings.toml")) if ui.active || !strings.Contains(strings.Join(voice.messages, "|"), "capture denied") { t.Fatal(ui.active, voice.messages) } keys.captureErr = nil - ui.open_settings(config.Defaults(), filepath.Join(t.TempDir(), "settings.toml")) + ui.openSettings(config.Defaults(), filepath.Join(t.TempDir(), "settings.toml")) ui.close() closedCount := len(voice.messages) - receive_ui(t, ui) + receiveUi(t, ui) if ui.active || ui.session != nil || len(voice.messages) != closedCount { t.Fatal("closed UI resurrected") } @@ -247,7 +247,7 @@ func TestMenuRejectsStaleWorkerAndCaptureFailure(t *testing.T) { func TestInternalUICloseUsesTitleWithoutLoadedSessionAndOnlyOnce(t *testing.T) { for _, title := range []string{"Fenrir settings", "Actions"} { keys, voice := &fakeKeys{}, &fakeVoice{} - ui := new_internal_ui(context.Background(), keys, voice) + ui := newInternalUi(context.Background(), keys, voice) if _, err := ui.begin(title); err != nil { t.Fatal(err) } @@ -265,9 +265,9 @@ func TestMenuOpenFailureClosesWithNameAndReportsError(t *testing.T) { t.Fatal(err) } voice := &fakeVoice{} - ui := new_internal_ui(context.Background(), &fakeKeys{}, voice) - ui.open_settings(config.Defaults(), path) - receive_ui(t, ui) + ui := newInternalUi(context.Background(), &fakeKeys{}, voice) + ui.openSettings(config.Defaults(), path) + receiveUi(t, ui) if ui.active || len(voice.messages) != 2 || voice.messages[0] != "Fenrir Menu closed" || !strings.Contains(voice.messages[1], "Could not open Fenrir Menu:") { t.Fatal(ui.active, voice.messages) } @@ -348,11 +348,11 @@ func TestMenuAbortsOnTerminalChange(t *testing.T) { } } -// tab_to_control moves focus with Tab, as a user would, until id is focused. -func tab_to_control(t *testing.T, ui *internalUI, id string) { +// tabToControl moves focus with Tab, as a user would, until id is focused. +func tabToControl(t *testing.T, ui *internalUI, id string) { t.Helper() for range 64 { - if control, ok := ui.session.Focused_control(); ok && control.ID == id { + if control, ok := ui.session.FocusedControl(); ok && control.ID == id { return } ui.handle(interaction.Key{Name: "tab"}) diff --git a/internal/app/live_modifiers_test.go b/internal/app/live_modifiers_test.go index 04cfefff..23cfbd94 100644 --- a/internal/app/live_modifiers_test.go +++ b/internal/app/live_modifiers_test.go @@ -28,7 +28,7 @@ func TestSavedModifiersWaitForMenuCloseAndIdleKeys(t *testing.T) { } return idle, nil }} - a, err := new_application(context.Background(), source, keys, voice, RunOptions{Settings: base}) + a, err := newApplication(context.Background(), source, keys, voice, RunOptions{Settings: base}) if err != nil { t.Fatal(err) } @@ -36,22 +36,22 @@ func TestSavedModifiersWaitForMenuCloseAndIdleKeys(t *testing.T) { saved.Keyboard.FenrirKeys = []string{"KEY_CAPSLOCK"} saved.General.ScriptKeys = []string{"KEY_META"} a.ui.active = true - a.apply_saved_settings(saved, false) - a.apply_pending_modifiers() + a.applySavedSettings(saved, false) + a.applyPendingModifiers() if calls != 0 || a.settings.pendingModifiers == nil { t.Fatal("changed during modal capture") } a.ui.active = false - a.apply_pending_modifiers() + a.applyPendingModifiers() if calls != 1 || !reflect.DeepEqual(a.settings.live.Keyboard.FenrirKeys, base.Keyboard.FenrirKeys) || !reflect.DeepEqual(a.settings.live.General.ScriptKeys, base.General.ScriptKeys) { t.Fatal("changed while held", a.settings.live) } idle = true - a.apply_pending_modifiers() + a.applyPendingModifiers() if calls != 2 || a.settings.pendingModifiers != nil || !reflect.DeepEqual(a.settings.live.Keyboard.FenrirKeys, saved.Keyboard.FenrirKeys) || !reflect.DeepEqual(a.settings.live.General.ScriptKeys, saved.General.ScriptKeys) { t.Fatal("new keys not applied", a.settings.live) } - a.apply_pending_modifiers() + a.applyPendingModifiers() if calls != 2 { t.Fatal("update repeated after success") } @@ -63,14 +63,14 @@ func TestModifierApplyFailureKeepsPreviousRuntimeAndAllowsRetry(t *testing.T) { source := &fakeSource{snapshot: screen.Snapshot{Terminal: 1, Active: true}} voice := &fakeVoice{} keys := &fakeKeys{updateModifiers: func([]string, []string) (bool, error) { return false, errors.New("fixture grab conflict") }} - a, err := new_application(context.Background(), source, keys, voice, RunOptions{Settings: base}) + a, err := newApplication(context.Background(), source, keys, voice, RunOptions{Settings: base}) if err != nil { t.Fatal(err) } saved := base saved.Keyboard.FenrirKeys = []string{"KEY_META"} - a.apply_saved_settings(saved, false) - a.apply_pending_modifiers() + a.applySavedSettings(saved, false) + a.applyPendingModifiers() if a.settings.pendingModifiers != nil || !reflect.DeepEqual(a.settings.live.Keyboard.FenrirKeys, base.Keyboard.FenrirKeys) || !reflect.DeepEqual(a.settings.saveDraft.Keyboard.FenrirKeys, saved.Keyboard.FenrirKeys) { t.Fatal(a.settings) } @@ -78,8 +78,8 @@ func TestModifierApplyFailureKeepsPreviousRuntimeAndAllowsRetry(t *testing.T) { t.Fatal(voice.messages) } keys.updateModifiers = func([]string, []string) (bool, error) { return true, nil } - a.apply_saved_settings(saved, false) - a.apply_pending_modifiers() + a.applySavedSettings(saved, false) + a.applyPendingModifiers() if !reflect.DeepEqual(a.settings.live.Keyboard.FenrirKeys, saved.Keyboard.FenrirKeys) { t.Fatal("retry failed") } diff --git a/internal/app/menu_save_test.go b/internal/app/menu_save_test.go index 90ed23ab..03bcd92f 100644 --- a/internal/app/menu_save_test.go +++ b/internal/app/menu_save_test.go @@ -14,11 +14,11 @@ import ( "git.stormux.org/storm/fenrir/internal/interaction" ) -func admit_menu_save(t *testing.T, a *application) { +func admitMenuSave(t *testing.T, a *application) { t.Helper() - a.open_settings() - receive_ui(t, a.ui) - tab_to_control(t, a.ui, "speech.rate") + a.openSettings() + receiveUi(t, a.ui) + tabToControl(t, a.ui, "speech.rate") a.ui.handle(interaction.Key{Name: "right"}) // Rate 24 -> 25. a.ui.action("save", a.ui.session) if !a.saver.busy || a.ui.session != nil { @@ -26,7 +26,7 @@ func admit_menu_save(t *testing.T, a *application) { } } -func committed_menu_result(t *testing.T, a *application) error { +func committedMenuResult(t *testing.T, a *application) error { t.Helper() select { case err := <-a.saver.results: @@ -41,9 +41,9 @@ func TestMenuCommitSurvivesCloseAndHandoff(t *testing.T) { for _, terminalMode := range []bool{false, true} { for _, closeAction := range []string{"escape", "terminal", "focus", "other menu"} { t.Run(closeAction+map[bool]string{false: "/tty", true: "/x11"}[terminalMode], func(t *testing.T) { - a, voice := persistence_application(t, terminalMode) - admit_menu_save(t, a) - err := committed_menu_result(t, a) // Gate completion after disk commit. + a, voice := persistenceApplication(t, terminalMode) + admitMenuSave(t, a) + err := committedMenuResult(t, a) // Gate completion after disk commit. if err != nil { t.Fatal(err) } @@ -55,7 +55,7 @@ func TestMenuCommitSurvivesCloseAndHandoff(t *testing.T) { } else { source.snapshot.Active = false } - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } default: @@ -68,7 +68,7 @@ func TestMenuCommitSurvivesCloseAndHandoff(t *testing.T) { a.ui.begin("Other menu") } generation, speechCount := a.ui.generation, len(voice.messages) - a.settings_save_result(err) + a.settingsSaveResult(err) saved, _, err := config.Load(a.options.ConfigPath, nil) if err != nil || saved.Presentation.Speech.Rate != 25 || a.settings.live.Presentation.Speech.Rate != 25 || !reflect.DeepEqual(a.settings.saveDraft, saved) || !reflect.DeepEqual(a.settings.resetBase, saved) { t.Fatal("committed menu settings diverged", saved, a.settings, err) @@ -77,15 +77,15 @@ func TestMenuCommitSurvivesCloseAndHandoff(t *testing.T) { t.Fatal("stale save changed modal presentation") } configured := len(voice.parameters) - a.settings_save_result(nil) + a.settingsSaveResult(nil) if len(voice.parameters) != configured { t.Fatal("duplicate result applied twice") } if closeAction == "other menu" { a.ui.close() } - a.open_settings() - receive_ui(t, a.ui) + a.openSettings() + receiveUi(t, a.ui) if a.ui.session.Values()["presentation.speech.rate"].Number != 25 { t.Fatal("reopened form lost the commit") } @@ -96,68 +96,68 @@ func TestMenuCommitSurvivesCloseAndHandoff(t *testing.T) { func TestMenuCommitPreservesNewerOverridesAndCoordinatesSaves(t *testing.T) { for _, terminalMode := range []bool{false, true} { - a, _ := persistence_application(t, terminalMode) - admit_menu_save(t, a) - err := committed_menu_result(t, a) + a, _ := persistenceApplication(t, terminalMode) + admitMenuSave(t, a) + err := committedMenuResult(t, a) if err != nil { t.Fatal(err) } a.ui.close() - a.open_settings() + a.openSettings() if a.ui.active { t.Fatal("settings menu reopened during an admitted save") } - persistence_reply(t, persistence_request(a, "SAVE"), true) - persistence_reply(t, persistence_request(a, "SAVEAS ignored.toml"), true) - persistence_reply(t, persistence_request(a, "RESET"), true) - a.save_settings() // Cannot replace the pending menu snapshot. - persistence_reply(t, persistence_request(a, "SET speech#pitch=0.8;keyboard#word_echo=True"), false) + persistenceReply(t, persistenceRequest(a, "SAVE"), true) + persistenceReply(t, persistenceRequest(a, "SAVEAS ignored.toml"), true) + persistenceReply(t, persistenceRequest(a, "RESET"), true) + a.saveSettings() // Cannot replace the pending menu snapshot. + persistenceReply(t, persistenceRequest(a, "SET speech#pitch=0.8;keyboard#word_echo=True"), false) for _, id := range append(quickToRate, command.NextQuickValue, command.PreviousQuickValue, command.ProgressMonitor, command.Mute, command.AutoRead) { - a.handle_input(input.Decision{Command: id}) + a.handleInput(input.Decision{Command: id}) } // Returning rate to its old value still counts as a later adjustment. - a.settings_save_result(err) - if a.settings.live.Presentation.Speech.Rate != 24 || a.settings.live.Presentation.Speech.Pitch != 60 || !a.settings.live.Keyboard.WordEcho || a.settings.live.Presentation.Progress.Enabled == a.settings.resetBase.Presentation.Progress.Enabled || !a.muted || a.engine.Automatic_reading() || !a.quick.changed { + a.settingsSaveResult(err) + if a.settings.live.Presentation.Speech.Rate != 24 || a.settings.live.Presentation.Speech.Pitch != 60 || !a.settings.live.Keyboard.WordEcho || a.settings.live.Presentation.Progress.Enabled == a.settings.resetBase.Presentation.Progress.Enabled || !a.muted || a.engine.AutomaticReading() || !a.quick.changed { t.Fatal("menu completion overwrote a later/session change", a.settings.live) } if a.settings.saveDraft.Presentation.Speech.Rate != 24 || a.settings.saveDraft.Presentation.Speech.Pitch != 60 || !a.settings.saveDraft.Keyboard.WordEcho || a.settings.resetBase.Presentation.Speech.Rate != 25 { t.Fatal("save draft or reset baseline diverged", a.settings) } - persistence_reply(t, persistence_request(a, "RESET"), false) - if a.settings.live.Presentation.Speech.Rate != 25 || a.settings.live.Presentation.Speech.Pitch != a.settings.resetBase.Presentation.Speech.Pitch || a.settings.live.Keyboard.WordEcho || !a.muted || a.engine.Automatic_reading() { + persistenceReply(t, persistenceRequest(a, "RESET"), false) + if a.settings.live.Presentation.Speech.Rate != 25 || a.settings.live.Presentation.Speech.Pitch != a.settings.resetBase.Presentation.Speech.Pitch || a.settings.live.Keyboard.WordEcho || !a.muted || a.engine.AutomaticReading() { t.Fatal("RESET did not restore committed values and preserve session toggles") } } } func TestMenuFailureAfterCloseIsSilentAndDoesNotCommit(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) base := a.settings.resetBase - a.open_settings() - receive_ui(t, a.ui) + a.openSettings() + receiveUi(t, a.ui) external := base external.Presentation.Speech.Rate = 70 if err := config.Save(a.options.ConfigPath, external); err != nil { t.Fatal(err) } a.ui.action("save", a.ui.session) - err := committed_menu_result(t, a) + err := committedMenuResult(t, a) if err == nil { t.Fatal("external edit was overwritten") } a.ui.close() count := len(voice.messages) - a.settings_save_result(err) + a.settingsSaveResult(err) if a.ui.active || a.saver.busy || len(voice.messages) != count || !reflect.DeepEqual(a.settings.resetBase, base) || !reflect.DeepEqual(a.settings.saveDraft, base) { t.Fatal("closed failure changed state or presented into another session") } } func TestQuitWaitsForMenuCommitAfterClose(t *testing.T) { - a, _ := persistence_application(t, true) - admit_menu_save(t, a) + a, _ := persistenceApplication(t, true) + admitMenuSave(t, a) a.ui.close() - a.handle_input(input.Decision{Command: command.Quit}) + a.handleInput(input.Decision{Command: command.Quit}) if a.quitting || !a.quitAfterSave { t.Fatal("quit did not wait for menu save") } diff --git a/internal/app/notifications.go b/internal/app/notifications.go index ca819b7a..a7e55e7f 100644 --- a/internal/app/notifications.go +++ b/internal/app/notifications.go @@ -13,12 +13,12 @@ import ( "syscall" "time" - "git.stormux.org/storm/fenrir/internal/datetime" "git.stormux.org/storm/fenrir/internal/diagnostic" "git.stormux.org/storm/fenrir/internal/i18n" "git.stormux.org/storm/fenrir/internal/interaction" "git.stormux.org/storm/fenrir/internal/notifications" "git.stormux.org/storm/fenrir/internal/presentation" + "git.stormux.org/storm/screenreader-common/datetime" ) const notificationLimit = notifications.Limit @@ -48,7 +48,7 @@ type notification struct { // Share only the active console account's history with its terminal readers. // On graphical VTs keep the previous account until a text console is active. -func (a *application) share_notification_history(terminal int, active bool) { +func (a *application) shareNotificationHistory(terminal int, active bool) { if !a.options.SharedNotifications { return } @@ -59,28 +59,28 @@ func (a *application) share_notification_history(terminal int, active bool) { } info, err := os.Stat(fmt.Sprintf("/dev/tty%d", terminal)) if err != nil { - a.clear_notification_user() + a.clearNotificationUser() return } stat, ok := info.Sys().(*syscall.Stat_t) if !ok { - a.clear_notification_user() + a.clearNotificationUser() return } uid = int(stat.Uid) } - a.select_notification_user(uid) + a.selectNotificationUser(uid) } -func (a *application) select_notification_user(uid int) { +func (a *application) selectNotificationUser(uid int) { if previous := a.notificationHistory; previous != nil && previous.UID == uid { return } - a.clear_notification_user() + a.clearNotificationUser() a.notificationHistory = notifications.New(a.ctx, uid, a.options.NotificationNamespace) } -func (a *application) clear_notification_user() { +func (a *application) clearNotificationUser() { if previous := a.notificationHistory; previous != nil { a.voice.Interrupt() a.ui.close() @@ -92,7 +92,7 @@ func (a *application) clear_notification_user() { // Snapshot updates are deliberately silent: never call notify, present, or the // sound service while incorporating another reader's history. -func (a *application) refresh_notification_history() { +func (a *application) refreshNotificationHistory() { if a.notificationHistory == nil { return } @@ -110,10 +110,10 @@ func (a *application) notify(text string, received time.Time) { if text == "" { return } - a.share_notification_history(a.lastTerminal, a.lastActive) + a.shareNotificationHistory(a.lastTerminal, a.lastActive) if a.notificationHistory != nil { a.notificationHistory.Publish(text, received) - a.refresh_notification_history() + a.refreshNotificationHistory() } else { if len(a.notifications) == notificationLimit { copy(a.notifications, a.notifications[1:]) @@ -127,40 +127,40 @@ func (a *application) notify(text string, received time.Time) { history := a.notificationHistory if a.temporarySilence || a.muted { if history != nil { - history.Sound(func(ctx context.Context) { play_notification(ctx, cues) }) + history.Sound(func(ctx context.Context) { playNotification(ctx, cues) }) } else if a.notificationSound.allow(time.Now()) { a.play(presentation.Notification) } return } gate := &a.notificationSound - a.voice.Say_after(text, func(ctx context.Context) { + a.voice.SayAfter(text, func(ctx context.Context) { if ctx.Err() != nil { return } if history != nil { - if !history.Claim_sound(ctx) { + if !history.ClaimSound(ctx) { return } } else if !gate.allow(time.Now()) { return } - play_notification(ctx, cues) + playNotification(ctx, cues) }) return } a.present(text, "") } -func play_notification(ctx context.Context, cues SoundPlayer) { - if err := cues.Play_wait(ctx, presentation.Notification); err != nil && ctx.Err() == nil { +func playNotification(ctx context.Context, cues SoundPlayer) { + if err := cues.PlayWait(ctx, presentation.Notification); err != nil && ctx.Err() == nil { slog.Warn("notification sound incomplete", "error", err, "at", time.Now()) } } -func (a *application) last_notification() { - a.share_notification_history(a.lastTerminal, a.lastActive) - a.refresh_notification_history() +func (a *application) lastNotification() { + a.shareNotificationHistory(a.lastTerminal, a.lastActive) + a.refreshNotificationHistory() if len(a.notifications) == 0 { a.present(i18n.T("No notifications"), "") return @@ -168,9 +168,9 @@ func (a *application) last_notification() { a.present(a.notifications[len(a.notifications)-1].text, "") } -func (a *application) open_notifications() { - a.share_notification_history(a.lastTerminal, a.lastActive) - a.refresh_notification_history() +func (a *application) openNotifications() { + a.shareNotificationHistory(a.lastTerminal, a.lastActive) + a.refreshNotificationHistory() if len(a.notifications) == 0 { a.present(i18n.T("No notifications"), "") return @@ -179,10 +179,10 @@ func (a *application) open_notifications() { items := make([]string, 0, len(a.notifications)) for index := len(a.notifications) - 1; index >= 0; index-- { entry := a.notifications[index] - timestamp, _ := datetime.Format_time(a.settings.live.Presentation.DateTime.TimeFormat, entry.received) + timestamp, _ := datetime.FormatTime(a.settings.live.Presentation.DateTime.TimeFormat, entry.received) items = append(items, entry.text+" "+timestamp) } - session, err := interaction.New_session(interaction.Form{Type: interaction.TabForm, Title: "Notifications", Tabs: []interaction.Tab{ + session, err := interaction.NewSession(interaction.Form{Type: interaction.TabForm, Title: "Notifications", Tabs: []interaction.Tab{ {ID: "notifications", Label: "Notifications", Controls: []interaction.Control{ {ID: "history", Label: "Notifications", Kind: interaction.List, Items: items, Action: "repeat_notification"}, {ID: "close", Label: "Close", Kind: interaction.Button, Action: "cancel"}, diff --git a/internal/app/notifications_test.go b/internal/app/notifications_test.go index 3ab0b0be..3fc2a554 100644 --- a/internal/app/notifications_test.go +++ b/internal/app/notifications_test.go @@ -62,7 +62,7 @@ func TestNotificationSoundCooldownBoundaryAndConcurrentAdmission(t *testing.T) { func TestNotificationBurstLimitsCuesWithoutLosingSpeechOrHistory(t *testing.T) { for _, mode := range []string{"enabled", "muted", "silenced"} { t.Run(mode, func(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) voice.messages = nil sounds := &fakeSounds{} a.cues = sounds @@ -108,7 +108,7 @@ type queuedNotificationVoice struct { } } -func (v *queuedNotificationVoice) Say_after(text string, before func(context.Context)) { +func (v *queuedNotificationVoice) SayAfter(text string, before func(context.Context)) { v.requests = append(v.requests, struct { text string before func(context.Context) @@ -116,7 +116,7 @@ func (v *queuedNotificationVoice) Say_after(text string, before func(context.Con } func TestQueuedNotificationsCheckCooldownAtPlaybackAndCancellation(t *testing.T) { - a, _ := persistence_application(t, true) + a, _ := persistenceApplication(t, true) voice := &queuedNotificationVoice{} a.voice.Speaker = voice sounds := &fakeSounds{} @@ -146,7 +146,7 @@ func TestQueuedNotificationsCheckCooldownAtPlaybackAndCancellation(t *testing.T) func TestNotificationCuePrecedesSpeechAndOnlyPlaysForNewNotifications(t *testing.T) { for _, mode := range []string{"enabled", "disabled", "zero volume", "missing cue", "unavailable", "muted", "silenced"} { t.Run(mode, func(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) voice.messages = nil sounds := &fakeSounds{} a.cues = sounds @@ -170,7 +170,7 @@ func TestNotificationCuePrecedesSpeechAndOnlyPlaysForNewNotifications(t *testing t.Fatal("speech arrived before notification cue", sounds.cues) } } - if reply := runtime_request(a, "command notify Incoming message"); reply != "" { + if reply := runtimeRequest(a, "command notify Incoming message"); reply != "" { t.Fatal(reply) } if (len(sounds.cues) == 1) != wantCue || len(a.notifications) != 1 { @@ -179,8 +179,8 @@ func TestNotificationCuePrecedesSpeechAndOnlyPlaysForNewNotifications(t *testing if (len(voice.messages) == 1) != (mode != "muted" && mode != "silenced") { t.Fatal("notification speech policy", voice.messages) } - a.last_notification() - runtime_request(a, "command say Self-voice") + a.lastNotification() + runtimeRequest(a, "command say Self-voice") if (len(sounds.cues) == 1) != wantCue || len(a.notifications) != 1 { t.Fatal("recall or self-voice replayed notification cue", sounds.cues, a.notifications) } @@ -189,7 +189,7 @@ func TestNotificationCuePrecedesSpeechAndOnlyPlaysForNewNotifications(t *testing } func TestNotificationThroughPrivateSocket(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) voice.messages = nil directory := t.TempDir() path := filepath.Join(directory, "reader.sock") @@ -211,7 +211,7 @@ func TestNotificationThroughPrivateSocket(t *testing.T) { } select { case request := <-server.Requests(): - a.remote_request(request) + a.remoteRequest(request) case <-ctx.Done(): t.Fatal("notification did not reach the application") } @@ -223,7 +223,7 @@ func TestNotificationThroughPrivateSocket(t *testing.T) { func TestNotificationRemoteAdmissionAndSpeechPolicy(t *testing.T) { for _, terminalMode := range []bool{false, true} { - a, voice := persistence_application(t, terminalMode) + a, voice := persistenceApplication(t, terminalMode) voice.messages = nil for _, trial := range []struct { text string @@ -237,22 +237,22 @@ func TestNotificationRemoteAdmissionAndSpeechPolicy(t *testing.T) { } { a.settings.live.Remote.EnableCommandRemote = trial.enabled reply := make(chan string, 1) - a.remote_request(control.Request{Text: trial.text, UID: trial.uid, Reply: reply}) + a.remoteRequest(control.Request{Text: trial.text, UID: trial.uid, Reply: reply}) if response := <-reply; response == "" || len(a.notifications) != 0 || len(voice.messages) != 0 { t.Fatal("rejected notification had side effects", response, a.notifications, voice.messages) } } a.settings.live.Remote.EnableCommandRemote = true before := time.Now() - if response := runtime_request(a, "command notify You are transmatting"); response != "" { + if response := runtimeRequest(a, "command notify You are transmatting"); response != "" { t.Fatal(response) } entry := a.notifications[0] if entry.text != "You are transmatting" || entry.received.Before(before) || entry.received.After(time.Now()) || !reflect.DeepEqual(voice.messages, []string{entry.text}) { t.Fatal("notification was not spoken and timestamped", entry, voice.messages) } - runtime_request(a, "COMMAND SAY unrelated self-voice") - a.handle_command(command.LastNotification) + runtimeRequest(a, "COMMAND SAY unrelated self-voice") + a.handleCommand(command.LastNotification) if len(a.notifications) != 1 || voice.messages[len(voice.messages)-1] != entry.text { t.Fatal("self-voice replaced notification", a.notifications, voice.messages) } @@ -261,13 +261,13 @@ func TestNotificationRemoteAdmissionAndSpeechPolicy(t *testing.T) { a.muted, voice.muted = state == "muted", state == "muted" a.settings.live.Reading.Automatic = false voice.messages = nil - runtime_request(a, "COMMAND NOTIFY "+state) + runtimeRequest(a, "COMMAND NOTIFY "+state) if a.notifications[len(a.notifications)-1].text != state || (len(voice.messages) > 0) != (state == "automatic off") { t.Fatal("notification storage or speech policy", state, a.notifications, voice.messages) } } a.temporarySilence, a.muted, voice.muted = false, false, false - a.handle_command(command.LastNotification) + a.handleCommand(command.LastNotification) if voice.messages[len(voice.messages)-1] != "automatic off" { t.Fatal("retained notification could not be recalled", voice.messages) } @@ -275,7 +275,7 @@ func TestNotificationRemoteAdmissionAndSpeechPolicy(t *testing.T) { } func TestNotificationHistoryTimesNavigationAndNewArrivals(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) keys := a.keyboards.(*fakeKeys) a.notify("Hello world", time.Date(2026, 1, 2, 13, 38, 0, 0, time.Local)) a.notify("You are transmatting", time.Date(2026, 1, 2, 22, 50, 0, 0, time.Local)) @@ -285,7 +285,7 @@ func TestNotificationHistoryTimesNavigationAndNewArrivals(t *testing.T) { {"24-hour-seconds", "22:50:00", "13:38:00"}, } { a.settings.live.Presentation.DateTime.TimeFormat = trial.format - a.handle_input(input.Decision{Command: command.NotificationHistory, Interrupt: true, Keypress: true}) + a.handleInput(input.Decision{Command: command.NotificationHistory, Interrupt: true, Keypress: true}) if !a.ui.active || a.ui.session == nil || !strings.HasSuffix(voice.messages[len(voice.messages)-1], "You are transmatting "+trial.first) { t.Fatal("history did not open at newest entry", trial, voice.messages) } @@ -295,12 +295,12 @@ func TestNotificationHistoryTimesNavigationAndNewArrivals(t *testing.T) { t.Fatal("history order, repeat or received time", trial, got) } a.ui.handle(interaction.Key{Name: "tab"}) - control, _ := a.ui.session.Focused_control() + control, _ := a.ui.session.FocusedControl() if control.ID != "close" { t.Fatal("Tab could not reach Close", control) } a.ui.handle(interaction.Key{Name: "tab", Shift: true}) - control, _ = a.ui.session.Focused_control() + control, _ = a.ui.session.FocusedControl() if control.ID != "history" { t.Fatal("Shift+Tab could not return to list", control) } @@ -309,7 +309,7 @@ func TestNotificationHistoryTimesNavigationAndNewArrivals(t *testing.T) { t.Fatal("history did not release capture") } } - a.open_notifications() + a.openNotifications() a.ui.handle(interaction.Key{Name: "down"}) selected := a.ui.session.Values()["notifications.history"] a.notify("New arrival", time.Now()) @@ -317,7 +317,7 @@ func TestNotificationHistoryTimesNavigationAndNewArrivals(t *testing.T) { t.Fatal("arrival moved the selection", got, selected) } a.ui.close() - a.open_notifications() + a.openNotifications() if !strings.Contains(voice.messages[len(voice.messages)-1], "New arrival") { t.Fatal("reopened history missed arrival") } @@ -327,16 +327,16 @@ func TestNotificationHistoryTimesNavigationAndNewArrivals(t *testing.T) { t.Fatal("Close button did not close history") } keys.captureErr = errors.New("capture unavailable") - a.open_notifications() + a.openNotifications() if a.ui.active || !strings.Contains(voice.messages[len(voice.messages)-1], "Could not open Notifications") { t.Fatal("capture failure not reported", voice.messages) } } func TestNotificationHistoryEmptyAndBounded(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) for _, id := range []command.ID{command.LastNotification, command.NotificationHistory} { - a.handle_command(id) + a.handleCommand(id) if a.ui.active || voice.messages[len(voice.messages)-1] != "No notifications" { t.Fatal(id, voice.messages) } diff --git a/internal/app/progress_test.go b/internal/app/progress_test.go index b8488019..25724eb2 100644 --- a/internal/app/progress_test.go +++ b/internal/app/progress_test.go @@ -92,9 +92,9 @@ type progressSounds struct { onProgress func(float64) } -func (f *progressSounds) Play_progress(value float64) bool { +func (f *progressSounds) PlayProgress(value float64) bool { f.onProgress(value) - return f.fakeSounds.Play_progress(value) + return f.fakeSounds.PlayProgress(value) } type progressResetSounds struct { @@ -102,8 +102,8 @@ type progressResetSounds struct { clears, discards int } -func (f *progressResetSounds) Clear_progress() { f.clears++ } -func (f *progressResetSounds) Discard_progress() { f.discards++ } +func (f *progressResetSounds) ClearProgress() { f.clears++ } +func (f *progressResetSounds) DiscardProgress() { f.discards++ } func TestProgressResetDistinguishesPassiveRedrawFromInterruption(t *testing.T) { for _, redraw := range []string{"cursor", "ordinary output", "prompt", "repaint", "input", "menu", "terminal", "inactive", "buffer", "resize"} { @@ -212,7 +212,7 @@ func TestProgressLoopFlushesFinalValueWithoutAnotherScreenEvent(t *testing.T) { } func TestBackspaceThroughSharedRouterDoesNotBeep(t *testing.T) { - router, err := input.New_router(input.Layout{Bindings: []input.Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) + router, err := input.NewRouter(input.Layout{Bindings: []input.Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) if err != nil { t.Fatal(err) } diff --git a/internal/app/prompt_test.go b/internal/app/prompt_test.go index 7e2072c1..218af13f 100644 --- a/internal/app/prompt_test.go +++ b/internal/app/prompt_test.go @@ -18,7 +18,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func prompt_snapshot(lines ...string) screen.Snapshot { +func promptSnapshot(lines ...string) screen.Snapshot { result := screen.Snapshot{Terminal: 1, Active: true, Rows: len(lines), Cols: 80, Y: len(lines) - 1} for _, line := range lines { cells := make([]rune, result.Cols) @@ -39,7 +39,7 @@ func TestPromptRestorationDiscardsBatchAndPreservesModes(t *testing.T) { settings.Presentation.Sound.Enabled = mode != "speech" settings.Reading.Automatic = mode != "automatic off" settings.Prompt.ExactMatches = []string{"CUSTOM READY"} - source := &fakeSource{snapshot: prompt_snapshot("old", "working"), events: make(chan error, 1)} + source := &fakeSource{snapshot: promptSnapshot("old", "working"), events: make(chan error, 1)} keys := &fakeKeys{events: make(chan error, 1)} voice, sounds := &fakeVoice{}, &fakeSounds{} if mode == "missing sound" { @@ -69,20 +69,20 @@ func TestPromptRestorationDiscardsBatchAndPreservesModes(t *testing.T) { } voice.onSay = nil voice.messages, sounds.cues = nil, nil - source.snapshot = prompt_snapshot("discard this backlog", "Worked for 19s • 7:4") + source.snapshot = promptSnapshot("discard this backlog", "Worked for 19s • 7:4") source.events <- nil } handle(input.Decision{Command: command.FenrirMenu}) return nil } voice.messages, sounds.cues = nil, nil - source.snapshot = prompt_snapshot("discard this backlog", "Worked for 19s • 7:4") + source.snapshot = promptSnapshot("discard this backlog", "Worked for 19s • 7:4") source.events <- nil case 2: if len(voice.messages) != 0 || len(sounds.cues) != 0 { t.Fatal("incomplete line restored speech", voice.messages, sounds.cues) } - source.snapshot = prompt_snapshot("also discard this batch", line) + source.snapshot = promptSnapshot("also discard this batch", line) source.events <- nil case 3: var wantSpeech []string diff --git a/internal/app/punctuation_test.go b/internal/app/punctuation_test.go index 9536b1b3..6c96ff60 100644 --- a/internal/app/punctuation_test.go +++ b/internal/app/punctuation_test.go @@ -30,12 +30,12 @@ func TestSharedSpeechPunctuationAndPreparedCharacterFeedback(t *testing.T) { t.Fatal("clipboard echo lost original text", echo.last) } echo.punctuationLevel = "none" - echo.say_character('?') + echo.sayCharacter('?') echo.Say("a/b") echo.punctuationLevel = "all" - echo.say_character('?') + echo.sayCharacter('?') echo.punctuationLevel = "some" - echo.say_character('?', " first character in cell path/to") + echo.sayCharacter('?', " first character in cell path/to") if echo.last != "question? first character in cell path/to" { t.Fatal("clipboard echo lost raw table header", echo.last) } diff --git a/internal/app/quick_settings.go b/internal/app/quick_settings.go index 5474cb8d..ccc7746f 100644 --- a/internal/app/quick_settings.go +++ b/internal/app/quick_settings.go @@ -48,8 +48,8 @@ type quickSettings struct { fields map[string]uint64 } -func new_quick_settings(driverID string) *quickSettings { - driver, _ := speech.Find_driver(driverID) // Startup settings are validated. +func newQuickSettings(driverID string) *quickSettings { + driver, _ := speech.FindDriver(driverID) // Startup settings are validated. var sections []config.Section var visit func([]config.Section) visit = func(groups []config.Section) { @@ -61,7 +61,7 @@ func new_quick_settings(driverID string) *quickSettings { visit(config.Sections()) menu := &quickSettings{definitions: make(map[string]config.Definition)} var categories []quicksettings.Category - for _, section := range config.Ordered_sections(sections, []string{"presentation.speech", "reading", "keyboard"}) { + for _, section := range config.OrderedSections(sections, []string{"presentation.speech", "reading", "keyboard"}) { category := quicksettings.Category{ID: section.ID, Label: section.Label} for _, definition := range section.Settings { if definition.ChoiceSource == "speech-module" && driver.Modules == nil { @@ -78,7 +78,7 @@ func new_quick_settings(driverID string) *quickSettings { case definition.Kind == reflect.Bool: entry.Kind = quicksettings.Toggle case definition.ChoiceSource != "": - entry.Kind, entry.EmptyIsDefault = quicksettings.Choice, speech_choice(definition.ChoiceSource) + entry.Kind, entry.EmptyIsDefault = quicksettings.Choice, speechChoice(definition.ChoiceSource) default: // Python's 0.05 normalized step on the 200-point SSIP scale. entry.Kind, entry.Min, entry.Max, entry.Step = quicksettings.Range, int(definition.Min), int(definition.Max), 10 @@ -114,7 +114,7 @@ type quickHost struct { func (h quickHost) Value(entry quicksettings.Entry) quicksettings.Value { if entry.ID == "voice-profile" { - return quicksettings.Value{Choice: h.quick.voice_profile_choice(*h.settings)} + return quicksettings.Value{Choice: h.quick.voiceProfileChoice(*h.settings)} } switch value := h.quick.definitions[entry.ID].Value(*h.settings).(type) { case bool: @@ -129,16 +129,16 @@ func (h quickHost) Value(entry quicksettings.Entry) quicksettings.Value { func (h quickHost) Options(entry quicksettings.Entry) []quicksettings.Option { if entry.ID == "voice-profile" { - return h.settings.VoiceProfiles.Quick_options(config.Primary_voice(*h.settings), h.quick.savedVoice) + return h.settings.VoiceProfiles.QuickOptions(config.PrimaryVoice(*h.settings), h.quick.savedVoice) } definition := h.quick.definitions[entry.ID] choices := definition.Choices(*h.settings) - if speech_choice(definition.ChoiceSource) { + if speechChoice(definition.ChoiceSource) { choices = h.quick.discovery.Choices(*h.settings)[entry.ID] } options := make([]quicksettings.Option, 0, len(choices)) for _, choice := range choices { - options = append(options, quicksettings.Option{ID: choice.ID, Label: choice.Label, Literal: speech_choice(definition.ChoiceSource) && choice.ID != ""}) + options = append(options, quicksettings.Option{ID: choice.ID, Label: choice.Label, Literal: speechChoice(definition.ChoiceSource) && choice.ID != ""}) } return options } @@ -161,9 +161,9 @@ func (h quickHost) set(entry quicksettings.Entry, value quicksettings.Value, set // Overlay only the curated quick settings, preserving file-only and session // choices such as automatic reading, mute and the attribute feedback override. -func copy_quick_settings(target *config.Settings, source config.Settings) { +func copyQuickSettings(target *config.Settings, source config.Settings) { for _, definition := range config.Definitions() { - if definition.QuickLabel != "" && !speech_choice(definition.ChoiceSource) { + if definition.QuickLabel != "" && !speechChoice(definition.ChoiceSource) { if err := definition.Set(target, definition.Value(source)); err != nil { panic(err) } @@ -171,7 +171,7 @@ func copy_quick_settings(target *config.Settings, source config.Settings) { } } -func speech_parameters(settings config.Settings) speech.Parameters { +func speechParameters(settings config.Settings) speech.Parameters { voice := settings.Presentation.Speech return speech.Parameters{Rate: voice.Rate, Pitch: voice.Pitch, Volume: voice.Volume} } @@ -192,7 +192,7 @@ func (q *quickSettings) command(id command.ID, settings *config.Settings, voice if !ok { return false } - fresh := new_quick_settings(settings.Presentation.Speech.Driver) + fresh := newQuickSettings(settings.Presentation.Speech.Driver) // Always offered so "Default" can restore the saved voice without profiles. for index := range fresh.categories { if fresh.categories[index].ID == "presentation.speech" { @@ -211,12 +211,12 @@ func (q *quickSettings) command(id command.ID, settings *config.Settings, voice return true } if result.Entry.ID == "voice-profile" { - p, ok := settings.VoiceProfiles.Quick_profile(result.Value.Choice, q.savedVoice) + p, ok := settings.VoiceProfiles.QuickProfile(result.Value.Choice, q.savedVoice) if !ok { voice.Say(i18n.T("Choose a saved voice profile")) return true } - candidate, err := config.Apply_primary_voice(*settings, p) + candidate, err := config.ApplyPrimaryVoice(*settings, p) if err != nil { voice.Say(err.Error()) return true @@ -246,11 +246,11 @@ func (q *quickSettings) command(id command.ID, settings *config.Settings, voice enabled := settings.Presentation.Speech.Enabled settings.Presentation.Speech = candidate.Presentation.Speech settings.Presentation.Speech.Enabled = enabled - voice.Configure(speech_parameters(*settings)) + voice.Configure(speechParameters(*settings)) q.changed = true q.selectionChanged = true for _, path := range []string{"presentation.speech.driver", "presentation.speech.hardware_device", "presentation.speech.hardware_baud_rate", "presentation.speech.module", "presentation.speech.language", "presentation.speech.voice", "presentation.speech.rate", "presentation.speech.pitch", "presentation.speech.volume"} { - q.mark_changed(path) + q.markChanged(path) } if present { voice.Say(result.Text) @@ -259,7 +259,7 @@ func (q *quickSettings) command(id command.ID, settings *config.Settings, voice return true } definition := q.definitions[result.Entry.ID] - if speech_choice(definition.ChoiceSource) && q.selectSpeech != nil { + if speechChoice(definition.ChoiceSource) && q.selectSpeech != nil { candidate := *settings host.set(result.Entry, result.Value, &candidate) if definition.ChoiceSource == "speech-module" { @@ -277,11 +277,11 @@ func (q *quickSettings) command(id command.ID, settings *config.Settings, voice } return } - copy_speech_selection(&settings.Presentation.Speech, candidate.Presentation.Speech) + copySpeechSelection(&settings.Presentation.Speech, candidate.Presentation.Speech) q.changed = true q.selectionChanged = true for _, path := range []string{"presentation.speech.module", "presentation.speech.language", "presentation.speech.voice"} { - q.mark_changed(path) + q.markChanged(path) } if present { voice.Say(result.Text) @@ -291,15 +291,15 @@ func (q *quickSettings) command(id command.ID, settings *config.Settings, voice } host.set(result.Entry, result.Value, settings) if result.Entry.Kind == quicksettings.Range { - voice.Configure(speech_parameters(*settings)) + voice.Configure(speechParameters(*settings)) } q.changed = true - q.mark_changed(result.Entry.ID) + q.markChanged(result.Entry.ID) voice.Say(result.Text) return true } -func (q *quickSettings) mark_changed(path string) { +func (q *quickSettings) markChanged(path string) { if q.fields == nil { q.fields = make(map[string]uint64) } @@ -320,7 +320,7 @@ type settingsSaver struct { func (s *settingsSaver) save(ctx context.Context, path string, settings config.Settings) bool { return s.start(ctx, settings, func() error { - doc, err := config.Open_document(path, settings) + doc, err := config.OpenDocument(path, settings) if err != nil { return err } @@ -355,8 +355,8 @@ func (s *settingsSaver) result(err error, voice Speaker) { voice.Say(i18n.T("Settings saved.")) } -// voice_profile_choice names the matching profile, then the saved voice, and +// voiceProfileChoice names the matching profile, then the saved voice, and // otherwise reports a custom session voice. -func (q *quickSettings) voice_profile_choice(settings config.Settings) string { - return settings.VoiceProfiles.Quick_choice(config.Primary_voice(settings), q.savedVoice) +func (q *quickSettings) voiceProfileChoice(settings config.Settings) string { + return settings.VoiceProfiles.QuickChoice(config.PrimaryVoice(settings), q.savedVoice) } diff --git a/internal/app/quick_settings_test.go b/internal/app/quick_settings_test.go index 5964d7fc..3a99234b 100644 --- a/internal/app/quick_settings_test.go +++ b/internal/app/quick_settings_test.go @@ -41,7 +41,7 @@ func TestQuickSpeechNamesBypassTranslation(t *testing.T) { settings.Presentation.Speech.Module = "all" settings.Presentation.Speech.Language = "en" settings.Presentation.Speech.Voice = "default" - menu := new_quick_settings("speech-dispatcher") + menu := newQuickSettings("speech-dispatcher") menu.discovery = preferences.Discovery{Catalog: speech.Catalog{Modules: []string{"all"}, Voices: map[string][]speech.Voice{"all": {{Name: "default", Language: "en"}}}}} menu.menu.Messages.Translate = func(text string) string { return "translated " + text } host := quickHost{quick: menu, settings: &settings} @@ -62,7 +62,7 @@ func TestQuickSpeechSelectionAdjustmentAndBounds(t *testing.T) { settings := config.Defaults() settings.Presentation.Speech.Rate = 80 // Exercise the upper rate bound. voice := &fakeVoice{} - menu := new_quick_settings("speech-dispatcher") + menu := newQuickSettings("speech-dispatcher") for _, testCase := range []struct { id command.ID want string @@ -115,7 +115,7 @@ func TestHardwareQuickSettingsOnlyOfferSupportedControls(t *testing.T) { settings := config.Defaults() settings.Presentation.Speech.Driver = driver settings.Presentation.Speech.HardwareDevice = "/dev/fixture-synth" - menu, voice := new_quick_settings(driver), &fakeVoice{} + menu, voice := newQuickSettings(driver), &fakeVoice{} menu.selectSpeech = func(config.Speech, func(error, bool)) { t.Fatal("hardware numeric adjustment tried reopening the device") } @@ -167,12 +167,12 @@ func TestQuickChangesSurviveMenuCancelAndExplicitSaveThenQuit(t *testing.T) { // Opening the full menu reflects unsaved quick adjustments; cancelling // it leaves the running values and the existing disk file intact. - menu := new_quick_settings("speech-dispatcher") - quick_select_rate(menu, &base, voice) + menu := newQuickSettings("speech-dispatcher") + quickSelectRate(menu, &base, voice) menu.command(command.NextQuickValue, &base, voice) - ui := new_internal_ui(context.Background(), keys, voice) - ui.open_settings(base, path, base) - receive_ui(t, ui) + ui := newInternalUi(context.Background(), keys, voice) + ui.openSettings(base, path, base) + receiveUi(t, ui) if got := ui.session.Values()["presentation.speech.pitch"].Number; got != 0 { t.Fatal(got) } @@ -329,8 +329,8 @@ func TestSaveFailureKeepsRunningQuickSettings(t *testing.T) { } settings := config.Defaults() voice := &fakeVoice{} - menu := new_quick_settings("speech-dispatcher") - quick_select_rate(menu, &settings, voice) + menu := newQuickSettings("speech-dispatcher") + quickSelectRate(menu, &settings, voice) menu.command(command.NextQuickValue, &settings, voice) saver := &settingsSaver{results: make(chan error, 1)} saver.save(context.Background(), filepath.Join(path, "settings.toml"), settings) @@ -351,7 +351,7 @@ func TestSaveFailureKeepsRunningQuickSettings(t *testing.T) { func TestQuickCategoriesRememberSelectionAndWrap(t *testing.T) { settings := config.Defaults() voice := &fakeVoice{} - menu := new_quick_settings("speech-dispatcher") + menu := newQuickSettings("speech-dispatcher") for _, trial := range []struct { id command.ID want string @@ -379,7 +379,7 @@ func TestQuickCategoriesRememberSelectionAndWrap(t *testing.T) { t.Fatalf("%s: got %q, want %q", trial.id, got, trial.want) } } - if menu := new_quick_settings("speech-dispatcher"); !menu.command(command.CurrentQuickEntry, &settings, voice) || voice.messages[len(voice.messages)-1] != "Speech Dispatcher module default" { + if menu := newQuickSettings("speech-dispatcher"); !menu.command(command.CurrentQuickEntry, &settings, voice) || voice.messages[len(voice.messages)-1] != "Speech Dispatcher module default" { t.Fatal("new session did not reset selection", voice.messages) } } @@ -398,7 +398,7 @@ func TestQuickEchoCombinationsAndMenuCancelOrSave(t *testing.T) { } settings := original voice := &fakeVoice{} - menu := new_quick_settings("speech-dispatcher") + menu := newQuickSettings("speech-dispatcher") menu.command(command.NextQuickCategory, &settings, voice) menu.command(command.PreviousQuickValue, &settings, voice) // punctuation none menu.command(command.NextQuickCategory, &settings, voice) @@ -414,17 +414,17 @@ func TestQuickEchoCombinationsAndMenuCancelOrSave(t *testing.T) { if settings.Keyboard.CharacterEcho != (mask&1 != 0) || settings.Keyboard.WordEcho != (mask&2 != 0) || settings.Keyboard.EchoOnCapsLock != (mask&4 != 0) { t.Fatal(mask, settings.Keyboard) } - a := settings_ui_application(t, &fakeKeys{}, voice, path) + a := settingsUiApplication(t, &fakeKeys{}, voice, path) ui := a.ui - ui.open_settings(settings, path, settings) - receive_ui(t, ui) + ui.openSettings(settings, path, settings) + receiveUi(t, ui) values := ui.session.Values() if values["keyboard.character_echo"].Checked != settings.Keyboard.CharacterEcho || values["keyboard.word_echo"].Checked != settings.Keyboard.WordEcho || values["keyboard.echo_on_capslock"].Checked != settings.Keyboard.EchoOnCapsLock || values["reading.punctuation_level"].Choices[values["reading.punctuation_level"].Selected].ID != "none" { t.Fatal("form lost unsaved quick choices", values) } if save { ui.action("save", ui.session) - finish_persistence(t, a, false) + finishPersistence(t, a, false) } else { ui.handle(interaction.Key{Name: "escape"}) } @@ -518,7 +518,7 @@ func TestQuickEchoAppliesLiveWithAutomaticReadingOff(t *testing.T) { // quickToRate reaches rate past the module, language and voice entries. var quickToRate = []command.ID{command.NextQuickEntry, command.NextQuickEntry, command.NextQuickEntry} -func quick_select_rate(menu *quickSettings, settings *config.Settings, voice Speaker) { +func quickSelectRate(menu *quickSettings, settings *config.Settings, voice Speaker) { for _, id := range quickToRate { menu.command(id, settings, voice) } diff --git a/internal/app/reading_regions.go b/internal/app/reading_regions.go index 1a7ef2cb..92f14b43 100644 --- a/internal/app/reading_regions.go +++ b/internal/app/reading_regions.go @@ -8,20 +8,20 @@ import ( "strings" ) -func (a *application) reading_regions_changed() { +func (a *application) readingRegionsChanged() { a.spellFeedback++ if a.cues != nil { - a.cues.Clear_progress() + a.cues.ClearProgress() } // Changing a filter must not make an old, newly exposed prompt restore // speech. Observe it now as a baseline, without presenting the result. - a.prompts.Observe(a.engine.Automatic_snapshot()) + a.prompts.Observe(a.engine.AutomaticSnapshot()) } -// remote_window runs only after the existing section-specific authorization. +// remoteWindow runs only after the existing section-specific authorization. // Python accepts these operations in both COMMAND and SETTING sections. Remote // coordinates are zero-based inclusive cells, unlike spoken row/column reports. -func (a *application) remote_window(text string) (string, bool) { +func (a *application) remoteWindow(text string) (string, bool) { fields := strings.Fields(text) if len(fields) == 0 { return "", false @@ -39,17 +39,17 @@ func (a *application) remote_window(text string) (string, bool) { } coordinates[index] = value } - if err := a.engine.Set_window(coordinates[0], coordinates[1], coordinates[2], coordinates[3]); err != nil { + if err := a.engine.SetWindow(coordinates[0], coordinates[1], coordinates[2], coordinates[3]); err != nil { return err.Error(), true } case "RESETWINDOW": if len(fields) != 1 { return "RESETWINDOW does not accept coordinates", true } - a.engine.Clear_window() + a.engine.ClearWindow() default: return "", false } - a.reading_regions_changed() + a.readingRegionsChanged() return "", true } diff --git a/internal/app/reading_regions_test.go b/internal/app/reading_regions_test.go index 10915a6e..49cf5970 100644 --- a/internal/app/reading_regions_test.go +++ b/internal/app/reading_regions_test.go @@ -18,37 +18,37 @@ import ( func TestLiveRegionCannotRestoreSpeechOrReplayAnOldPromptWhenCleared(t *testing.T) { settings := config.Defaults() settings.Presentation.Sound.Enabled = false - source := &fakeSource{snapshot: prompt_snapshot("compose", "status")} + source := &fakeSource{snapshot: promptSnapshot("compose", "status")} voice := &fakeVoice{} - a, err := new_application(context.Background(), source, &fakeKeys{}, voice, RunOptions{Settings: settings}) + a, err := newApplication(context.Background(), source, &fakeKeys{}, voice, RunOptions{Settings: settings}) if err != nil { t.Fatal(err) } t.Cleanup(a.ui.close) - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } - a.handle_command(command.CurrentLine) - a.handle_command(command.SetMark) - a.handle_command(command.SetLiveRegion) - a.handle_input(input.Decision{Command: command.TempDisableSpeech, Interrupt: true}) + a.handleCommand(command.CurrentLine) + a.handleCommand(command.SetMark) + a.handleCommand(command.SetLiveRegion) + a.handleInput(input.Decision{Command: command.TempDisableSpeech, Interrupt: true}) voice.messages = nil - source.snapshot = prompt_snapshot("compose", "Worked for 19s • 7:46 PM") - if err := a.read_screen(); err != nil { + source.snapshot = promptSnapshot("compose", "Worked for 19s • 7:46 PM") + if err := a.readScreen(); err != nil { t.Fatal(err) } if !a.temporarySilence || len(voice.messages) != 0 { t.Fatal("ignored completion restored speech", a.temporarySilence, voice.messages) } - a.handle_command(command.ClearLiveRegions) - if err := a.read_screen(); err != nil { + a.handleCommand(command.ClearLiveRegions) + if err := a.readScreen(); err != nil { t.Fatal(err) } if !a.temporarySilence || len(voice.messages) != 0 { t.Fatal("clearing replayed excluded completion", a.temporarySilence, voice.messages) } - source.snapshot = prompt_snapshot("compose", "Password:") - if err := a.read_screen(); err != nil { + source.snapshot = promptSnapshot("compose", "Password:") + if err := a.readScreen(); err != nil { t.Fatal(err) } if a.temporarySilence || !strings.Contains(strings.Join(voice.messages, " "), "Speech restored") { @@ -60,32 +60,32 @@ func TestRemoteWindowValidationAuthorizationAndSectionGates(t *testing.T) { for _, section := range []string{"COMMAND", "SETTING"} { t.Run(section, func(t *testing.T) { settings := config.Defaults() - source := &fakeSource{snapshot: prompt_snapshot("outer", "IN allowed OUT")} - a, err := new_application(context.Background(), source, &fakeKeys{}, &fakeVoice{}, RunOptions{Settings: settings, TerminalMode: true}) + source := &fakeSource{snapshot: promptSnapshot("outer", "IN allowed OUT")} + a, err := newApplication(context.Background(), source, &fakeKeys{}, &fakeVoice{}, RunOptions{Settings: settings, TerminalMode: true}) if err != nil { t.Fatal(err) } t.Cleanup(a.ui.close) - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } request := func(uid int, text string) string { t.Helper() reply := make(chan string, 1) - a.remote_request(control.Request{UID: uid, Text: section + " " + text, Reply: reply}) + a.remoteRequest(control.Request{UID: uid, Text: section + " " + text, Reply: reply}) return <-reply } - if reply := request(os.Geteuid(), "WINDOW 9 1 3 1"); reply != "" || a.engine.Automatic_snapshot().Text(1) != " allowed" { - t.Fatal("valid reversed window", reply, a.engine.Automatic_snapshot().Text(1)) + if reply := request(os.Geteuid(), "WINDOW 9 1 3 1"); reply != "" || a.engine.AutomaticSnapshot().Text(1) != " allowed" { + t.Fatal("valid reversed window", reply, a.engine.AutomaticSnapshot().Text(1)) } for _, text := range []string{"WINDOW", "WINDOW 0 0 1", "WINDOW 0 0 1 1 extra", "WINDOW -1 0 1 1", "WINDOW 0 0 9999999999999999999999 1", "WINDOW 0 0 80 1", "WINDOW 0 0 1 2", "WINDOW 0 x 1 1", "RESETWINDOW 1"} { - revision := a.engine.Region_revision() - if reply := request(os.Geteuid(), text); reply == "" || a.engine.Region_revision() != revision { + revision := a.engine.RegionRevision() + if reply := request(os.Geteuid(), text); reply == "" || a.engine.RegionRevision() != revision { t.Fatal("invalid request changed window", text, reply) } } - revision := a.engine.Region_revision() - if reply := request(os.Geteuid()+1, "RESETWINDOW"); reply == "" || a.engine.Region_revision() != revision { + revision := a.engine.RegionRevision() + if reply := request(os.Geteuid()+1, "RESETWINDOW"); reply == "" || a.engine.RegionRevision() != revision { t.Fatal("unauthorized reset", reply) } if section == "COMMAND" { @@ -93,11 +93,11 @@ func TestRemoteWindowValidationAuthorizationAndSectionGates(t *testing.T) { } else { a.settings.live.Remote.EnableSettingsRemote = false } - if reply := request(os.Geteuid(), "RESETWINDOW"); reply == "" || a.engine.Region_revision() != revision { + if reply := request(os.Geteuid(), "RESETWINDOW"); reply == "" || a.engine.RegionRevision() != revision { t.Fatal("disabled remote gate bypassed", reply) } a.settings.live.Remote = settings.Remote - if reply := request(os.Geteuid(), "RESETWINDOW"); reply != "" || a.engine.Automatic_snapshot().Text(1) != "IN allowed OUT" { + if reply := request(os.Geteuid(), "RESETWINDOW"); reply != "" || a.engine.AutomaticSnapshot().Text(1) != "IN allowed OUT" { t.Fatal("window reset", reply) } }) diff --git a/internal/app/remote_application.go b/internal/app/remote_application.go index d6486ac6..899ed2fb 100644 --- a/internal/app/remote_application.go +++ b/internal/app/remote_application.go @@ -10,21 +10,21 @@ import ( ) // Runs after the command authorization and enablement gates. -func (a *application) remote_application(parameter string, request control.Request) { +func (a *application) remoteApplication(parameter string, request control.Request) { id := strings.ToLower(strings.TrimSpace(parameter)) switch id { case "default", "networkmanager", "ninjam", "rogue", "codex": default: - remote_reply(request.Reply, "APPLICATION requires one ID: default, networkmanager, ninjam, rogue, codex") + remoteReply(request.Reply, "APPLICATION requires one ID: default, networkmanager, ninjam, rogue, codex") return } if a.saver.busy || a.speechPending || a.overrideTransition { - remote_reply(request.Reply, "Settings are busy; try again after the current operation") + remoteReply(request.Reply, "Settings are busy; try again after the current operation") return } if a.lastTerminal == 0 || !a.lastActive { - remote_reply(request.Reply, "No active terminal for application selection") + remoteReply(request.Reply, "No active terminal for application selection") return } - a.select_override_result(id, func(response string) { remote_reply(request.Reply, response) }) + a.selectOverrideResult(id, func(response string) { remoteReply(request.Reply, response) }) } diff --git a/internal/app/remote_application_test.go b/internal/app/remote_application_test.go index 258a434e..8265611c 100644 --- a/internal/app/remote_application_test.go +++ b/internal/app/remote_application_test.go @@ -15,10 +15,10 @@ import ( func TestRemoteApplicationSelectionAndDefault(t *testing.T) { for _, terminalMode := range []bool{true, false} { - a, _ := persistence_application(t, terminalMode) - override_read(t, a, override_screen(1, "ninjam")) + a, _ := persistenceApplication(t, terminalMode) + overrideRead(t, a, overrideScreen(1, "ninjam")) for _, id := range []string{"ninjam", "networkmanager", "rogue", "codex", "default"} { - if got := runtime_request(a, "COMMAND APPLICATION "+id); got != "" { + if got := runtimeRequest(a, "COMMAND APPLICATION "+id); got != "" { t.Fatal(id, got) } selected := a.overrides[1] @@ -30,26 +30,26 @@ func TestRemoteApplicationSelectionAndDefault(t *testing.T) { t.Fatal("wrong application selected", id) } } - if got := runtime_request(a, "command application NINJAM"); got != "" { + if got := runtimeRequest(a, "command application NINJAM"); got != "" { t.Fatal(got) } - override_read(t, a, override_screen(1, "ninjam")) - if a.overrideCurrent == nil || a.engine.Tracking_mode() != "highlight" { + overrideRead(t, a, overrideScreen(1, "ninjam")) + if a.overrideCurrent == nil || a.engine.TrackingMode() != "highlight" { t.Fatal("remote selection did not activate Ninjam") } - if got := runtime_request(a, "command application default"); got != "" || a.overrideCurrent != nil { + if got := runtimeRequest(a, "command application default"); got != "" || a.overrideCurrent != nil { t.Fatal("Default did not restore settings", got) } } } func TestRemoteApplicationRejectsInvalidAndUnavailableRequests(t *testing.T) { - a, _ := persistence_application(t, true) - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") + a, _ := persistenceApplication(t, true) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") selected := a.overrides[1] for _, parameter := range []string{"", "unknown", "ninjam extra", "default extra"} { - if got := runtime_request(a, "COMMAND APPLICATION "+parameter); got == "" || a.overrides[1] != selected { + if got := runtimeRequest(a, "COMMAND APPLICATION "+parameter); got == "" || a.overrides[1] != selected { t.Fatal("invalid request changed selection", parameter, got) } } @@ -73,7 +73,7 @@ func TestRemoteApplicationRejectsInvalidAndUnavailableRequests(t *testing.T) { uid++ } reply := make(chan string, 1) - a.remote_request(control.Request{UID: uid, Text: "COMMAND APPLICATION default", Reply: reply}) + a.remoteRequest(control.Request{UID: uid, Text: "COMMAND APPLICATION default", Reply: reply}) if got := <-reply; got == "" || a.overrides[1] != selected { t.Fatal("gated request changed selection", got) } @@ -86,25 +86,25 @@ func TestRemoteApplicationRejectsInvalidAndUnavailableRequests(t *testing.T) { func TestRemoteApplicationWaitsForVoiceRestoration(t *testing.T) { for _, fail := range []bool{false, true} { - a, _, _ := selection_application(t, true) + a, _, _ := selectionApplication(t, true) a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return &preparedVoice{}, nil } - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) - if got := request_selection(t, a, "SET speech#module=fixture;speech#voice=Temporary"); got != "" { + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) + if got := requestSelection(t, a, "SET speech#module=fixture;speech#voice=Temporary"); got != "" { t.Fatal(got) } if fail { a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return nil, errors.New("fixture unavailable") } } reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid(), Text: "COMMAND APPLICATION rogue", Reply: reply}) + a.remoteRequest(control.Request{UID: os.Geteuid(), Text: "COMMAND APPLICATION rogue", Reply: reply}) select { case got := <-reply: t.Fatal("selection replied before restoration", got) default: } - finish_selection(t, a) + finishSelection(t, a) got := <-reply if fail { if got == "" || a.overrides[1].id != "ninjam" { diff --git a/internal/app/remote_authorization_test.go b/internal/app/remote_authorization_test.go index b4baf67c..068bb262 100644 --- a/internal/app/remote_authorization_test.go +++ b/internal/app/remote_authorization_test.go @@ -15,14 +15,14 @@ import ( func TestRemoteRequestRejectsOtherUsersBeforeApplyingCommands(t *testing.T) { for _, terminalMode := range []bool{false, true} { voice := &fakeVoice{} - a, err := new_application(context.Background(), &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: config.Defaults(), TerminalMode: terminalMode}) + a, err := newApplication(context.Background(), &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: config.Defaults(), TerminalMode: terminalMode}) if err != nil { t.Fatal(err) } t.Cleanup(a.ui.close) for _, uid := range []int{os.Geteuid() + 1, os.Geteuid(), 0} { replies := make(chan string, 1) - a.remote_request(control.Request{UID: uid, Text: "COMMAND SAY authorized", Reply: replies}) + a.remoteRequest(control.Request{UID: uid, Text: "COMMAND SAY authorized", Reply: replies}) reply := <-replies if uid == os.Geteuid()+1 { if reply != "Remote control is not permitted for this session" || len(voice.messages) != 0 { diff --git a/internal/app/remote_parameters_test.go b/internal/app/remote_parameters_test.go index 68b2be56..7b6a36cb 100644 --- a/internal/app/remote_parameters_test.go +++ b/internal/app/remote_parameters_test.go @@ -28,27 +28,27 @@ func TestRemoteNormalizedParametersAndAtomicValidation(t *testing.T) { }{ {"0", -100}, {"0.25", -50}, {"0.499", 0}, {"0.5", 0}, {"0.75", 50}, {"1", 100}, } { - updated, err := remote_settings(base, "SET speech#rate="+testCase.value+";speech#pitch="+testCase.value+",speech#volume="+testCase.value) - if err != nil || speech_parameters(updated) != (speech.Parameters{Rate: testCase.want, Pitch: testCase.want, Volume: testCase.want}) { + updated, err := remoteSettings(base, "SET speech#rate="+testCase.value+";speech#pitch="+testCase.value+",speech#volume="+testCase.value) + if err != nil || speechParameters(updated) != (speech.Parameters{Rate: testCase.want, Pitch: testCase.want, Volume: testCase.want}) { t.Fatal(testCase, updated.Presentation.Speech, err) } } for _, path := range []string{"speech#rate", "speech#pitch", "speech#volume", "sound#volume"} { for _, value := range []string{"", "-0.01", "1.01", "80", "NaN", "Inf", "-Inf", "1e999", "invalid"} { - updated, err := remote_settings(base, "SET speech#enabled=False;screen#ignore_screen=7,8;"+path+"="+value) + updated, err := remoteSettings(base, "SET speech#enabled=False;screen#ignore_screen=7,8;"+path+"="+value) if err == nil || !reflect.DeepEqual(updated, base) { t.Fatal("invalid request was not rolled back", path, value, updated, err) } } } for _, level := range punctuation.Levels() { - updated, err := remote_settings(base, "SET general#punctuation_level="+level) + updated, err := remoteSettings(base, "SET general#punctuation_level="+level) if err != nil || updated.Reading.PunctuationLevel != level { t.Fatal(level, updated.Reading, err) } } for _, level := range []string{"", "ALL", "invalid"} { - updated, err := remote_settings(base, "SET speech#rate=0.2;general#punctuation_level="+level) + updated, err := remoteSettings(base, "SET speech#rate=0.2;general#punctuation_level="+level) if err == nil || !reflect.DeepEqual(updated, base) { t.Fatal("invalid punctuation partially applied", level, err) } @@ -68,19 +68,19 @@ func TestRemoteParametersApplyAndSaveWithoutChangingSessionOverrides(t *testing. voice, sounds := &fakeVoice{}, &fakeSounds{} source := &fakeSource{snapshot: screen.Snapshot{Terminal: 1, Active: true, Rows: 1, Cols: 5, Cells: []rune("alpha")}} keys := &fakeKeys{poll: func(bool, func(input.Decision)) error { return nil }} - a, err := new_application(ctx, source, keys, voice, RunOptions{Settings: base, ConfigPath: path, TerminalMode: terminalMode, Sounds: sounds, Punctuation: processor}) + a, err := newApplication(ctx, source, keys, voice, RunOptions{Settings: base, ConfigPath: path, TerminalMode: terminalMode, Sounds: sounds, Punctuation: processor}) if err != nil { t.Fatal(err) } defer a.ui.close() - a.handle_input(input.Decision{Command: command.AutoRead}) - a.handle_input(input.Decision{Command: command.Mute}) + a.handleInput(input.Decision{Command: command.AutoRead}) + a.handleInput(input.Decision{Command: command.Mute}) // Preserve next-launch menu choices across remote updates and quick save. a.settings.saveDraft.Keyboard.Layout = "laptop" a.settings.saveDraft.Presentation.Speech.Module = "saved-module" request := func(uid int, text string) string { replies := make(chan string, 1) - a.remote_request(control.Request{UID: uid, Text: text, Reply: replies}) + a.remoteRequest(control.Request{UID: uid, Text: text, Reply: replies}) return <-replies } assignment := "SETTING SET speech#rate=0.75;speech#pitch=0.25;speech#volume=0.8;sound#volume=0.3;general#punctuation_level=all" @@ -104,24 +104,24 @@ func TestRemoteParametersApplyAndSaveWithoutChangingSessionOverrides(t *testing. if len(voice.parameters) != 1 || voice.parameters[0] != (speech.Parameters{Rate: 50, Pitch: -50, Volume: 60}) || sounds.volume != 0.3 || a.voice.punctuationLevel != "all" { t.Fatal("remote values did not reach shared services", voice.parameters, sounds.volume, a.voice.punctuationLevel) } - if !a.muted || a.engine.Automatic_reading() || !a.settings.saveDraft.Presentation.Speech.Enabled || !a.settings.saveDraft.Reading.Automatic { + if !a.muted || a.engine.AutomaticReading() || !a.settings.saveDraft.Presentation.Speech.Enabled || !a.settings.saveDraft.Reading.Automatic { t.Fatal("unrelated session overrides changed or became saved defaults") } // Repeating an identical request does not reconfigure speech/audio. if reply := request(os.Geteuid(), assignment); reply != "" || len(voice.parameters) != 1 { t.Fatal("identical request reconfigured speech", reply, voice.parameters) } - a.handle_input(input.Decision{Command: command.Mute}) + a.handleInput(input.Decision{Command: command.Mute}) if reply := request(os.Geteuid(), "COMMAND SAY x#y"); reply != "" || voice.messages[len(voice.messages)-1] != "x hash y" { t.Fatal("remote punctuation did not affect subsequent speech", reply, voice.messages) } - a.handle_input(input.Decision{Command: command.SaveSettings}) - a.handle_input(input.Decision{Command: command.Quit}) + a.handleInput(input.Decision{Command: command.SaveSettings}) + a.handleInput(input.Decision{Command: command.Quit}) if err := a.loop(nil); err != nil || ctx.Err() != nil { t.Fatal(err, ctx.Err()) } saved, _, err := config.Load(path, nil) - if err != nil || speech_parameters(saved) != speech_parameters(a.settings.live) || saved.Presentation.Sound.Volume != 0.3 || saved.Reading.PunctuationLevel != "all" || saved.Keyboard.Layout != "laptop" || saved.Presentation.Speech.Module != "saved-module" || !saved.Reading.Automatic { + if err != nil || speechParameters(saved) != speechParameters(a.settings.live) || saved.Presentation.Sound.Volume != 0.3 || saved.Reading.PunctuationLevel != "all" || saved.Keyboard.Layout != "laptop" || saved.Presentation.Speech.Module != "saved-module" || !saved.Reading.Automatic { t.Fatal("remote values or next-launch choices lost on save", saved, err) } } diff --git a/internal/app/remote_persistence.go b/internal/app/remote_persistence.go index c29583aa..cd59145c 100644 --- a/internal/app/remote_persistence.go +++ b/internal/app/remote_persistence.go @@ -15,10 +15,10 @@ import ( // These operations run only after the shared credential and settings gates. // A save keeps its reply pending until the worker reports the actual disk result. -func (a *application) remote_settings_request(text string, request control.Request) (string, bool) { +func (a *application) remoteSettingsRequest(text string, request control.Request) (string, bool) { verb, parameter, _ := strings.Cut(text, " ") verb, parameter = strings.ToUpper(verb), strings.TrimSpace(parameter) - if a.saves_unavailable() && (verb == "SAVE" || verb == "SAVEAS") { + if a.savesUnavailable() && (verb == "SAVE" || verb == "SAVEAS") { return "Save unavailable.", false } if a.overrideTransition { @@ -28,25 +28,25 @@ func (a *application) remote_settings_request(text string, request control.Reque return "Settings are busy; try again after the current operation", false } if verb == "SET" { - if err := a.check_application_remote(text); err != nil { + if err := a.checkApplicationRemote(text); err != nil { return err.Error(), false } - updated, err := remote_settings(a.effective_settings(), text) + updated, err := remoteSettings(a.effectiveSettings(), text) if err != nil { return err.Error(), false } - if !same_speech_selection(updated.Presentation.Speech, a.settings.live.Presentation.Speech) { + if !sameSpeechSelection(updated.Presentation.Speech, a.settings.live.Presentation.Speech) { if a.saver.busy || a.ui.active { return "Settings are busy; try again after the current operation", false } - a.change_speech(updated.Presentation.Speech, func(err error) { + a.changeSpeech(updated.Presentation.Speech, func(err error) { response := "" if err != nil { response = err.Error() } else { - response = a.apply_remote_settings(resolved_remote_selection(text, updated)) + response = a.applyRemoteSettings(resolvedRemoteSelection(text, updated)) } - remote_reply(request.Reply, response) + remoteReply(request.Reply, response) }) return "", true } @@ -57,31 +57,31 @@ func (a *application) remote_settings_request(text string, request control.Reque return "Settings are busy; try again after the current operation", false } default: - return a.apply_remote_settings(text), false + return a.applyRemoteSettings(text), false } if verb != "SAVEAS" && parameter != "" { return verb + " does not accept parameters", false } if verb == "RESET" { - updated, _, err := a.remote_reset_state() + updated, _, err := a.remoteResetState() if err != nil { return err.Error(), false } - if !same_speech_selection(updated.Presentation.Speech, a.settings.live.Presentation.Speech) { - a.change_speech(updated.Presentation.Speech, func(err error) { + if !sameSpeechSelection(updated.Presentation.Speech, a.settings.live.Presentation.Speech) { + a.changeSpeech(updated.Presentation.Speech, func(err error) { response := "" if err != nil { response = err.Error() } else { - response = a.reset_remote_settings() + response = a.resetRemoteSettings() } - remote_reply(request.Reply, response) + remoteReply(request.Reply, response) }) return "", true } - return a.reset_remote_settings(), false + return a.resetRemoteSettings(), false } - path := a.settings_path() + path := a.settingsPath() if verb == "SAVEAS" { if a.overrideCurrent != nil { return "SAVEAS is unavailable in application settings", false @@ -96,7 +96,7 @@ func (a *application) remote_settings_request(text string, request control.Reque if path == "" || strings.ContainsAny(path, "\x00\r\n") { return "A valid settings destination is required", false } - if !a.start_settings_save(path, a.settings_to_save()) { + if !a.startSettingsSave(path, a.settingsToSave()) { return "Settings are busy; try again after the current operation", false } a.saver.revision = a.settings.remoteRevision @@ -104,11 +104,11 @@ func (a *application) remote_settings_request(text string, request control.Reque return "", true } -func (a *application) settings_save_result(err error) { +func (a *application) settingsSaveResult(err error) { if !a.saver.busy { return } - if settings_committed(err) { + if settingsCommitted(err) { a.settings.resetBase = a.saver.snapshot for path, revision := range a.settings.remoteFields { if revision <= a.saver.revision { @@ -125,7 +125,7 @@ func (a *application) settings_save_result(err error) { if err != nil { response = "Could not save settings: " + err.Error() } - remote_reply(reply, response) + remoteReply(reply, response) } else if a.overrideCurrent != nil && err == nil { a.saver.busy = false a.voice.Say(i18n.Format("{0} application settings saved.", i18n.T(a.overrideCurrent.adapter.Name()))) @@ -136,14 +136,14 @@ func (a *application) settings_save_result(err error) { // RESET clears temporary quick/remote overrides, as in Python's // reset_setting_arg_dict. It never reloads a file or installs factory defaults. -func (a *application) remote_reset_state() (config.Settings, config.Settings, error) { - updated, persisted := a.effective_settings(), a.settings.saveDraft +func (a *application) remoteResetState() (config.Settings, config.Settings, error) { + updated, persisted := a.effectiveSettings(), a.settings.saveDraft for _, target := range []*config.Settings{&updated, &persisted} { - copy_quick_settings(target, a.settings.resetBase) + copyQuickSettings(target, a.settings.resetBase) if a.quick.selectionChanged { - copy_speech_selection(&target.Presentation.Speech, a.settings.resetBase.Presentation.Speech) + copySpeechSelection(&target.Presentation.Speech, a.settings.resetBase.Presentation.Speech) } - copy_remote_settings(target, a.settings.resetBase, a.settings.remoteFields) + copyRemoteSettings(target, a.settings.resetBase, a.settings.remoteFields) if err := target.Validate(); err != nil { return updated, persisted, err } @@ -154,14 +154,14 @@ func (a *application) remote_reset_state() (config.Settings, config.Settings, er return updated, persisted, nil } -func (a *application) reset_remote_settings() string { - updated, persisted, err := a.remote_reset_state() +func (a *application) resetRemoteSettings() string { + updated, persisted, err := a.remoteResetState() if err != nil { return err.Error() } a.settings.saveDraft = persisted _, speechOverridden := a.settings.remoteFields["speech#enabled"] - a.apply_remote_state(updated, speechOverridden) + a.applyRemoteState(updated, speechOverridden) clear(a.settings.remoteFields) a.quick.changed = false a.quick.selectionChanged = false @@ -170,7 +170,7 @@ func (a *application) reset_remote_settings() string { // Copy only remotely overridden fields; unrelated session mute/AutoRead, // next-launch menu choices, reading regions and keyboard routing survive. -func copy_remote_settings(target *config.Settings, source config.Settings, fields map[string]uint64) { +func copyRemoteSettings(target *config.Settings, source config.Settings, fields map[string]uint64) { for path := range fields { switch path { case "reading#mode", "focus#cursor", "focus#highlight": @@ -178,7 +178,7 @@ func copy_remote_settings(target *config.Settings, source config.Settings, field case "speech#enabled": target.Presentation.Speech.Enabled = source.Presentation.Speech.Enabled case "speech#module", "speech#language", "speech#voice": - copy_speech_selection(&target.Presentation.Speech, source.Presentation.Speech) + copySpeechSelection(&target.Presentation.Speech, source.Presentation.Speech) case "speech#rate": target.Presentation.Speech.Rate = source.Presentation.Speech.Rate case "speech#pitch": @@ -211,12 +211,12 @@ func copy_remote_settings(target *config.Settings, source config.Settings, field } // Screen routing is global and has no application-profile counterpart. -func (a *application) check_application_remote(text string) error { +func (a *application) checkApplicationRemote(text string) error { if a.overrideCurrent == nil { return nil } _, parameters, _ := strings.Cut(text, " ") - for _, assignment := range remote_assignments(parameters) { + for _, assignment := range remoteAssignments(parameters) { path, _, _ := strings.Cut(assignment, "=") if strings.EqualFold(strings.TrimSpace(path), "screen#ignore_screen") { return fmt.Errorf("screen#ignore_screen is unavailable in application settings") diff --git a/internal/app/remote_persistence_test.go b/internal/app/remote_persistence_test.go index c9e9e4d8..ee9bf515 100644 --- a/internal/app/remote_persistence_test.go +++ b/internal/app/remote_persistence_test.go @@ -20,7 +20,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func persistence_application(t *testing.T, terminalMode bool) (*application, *fakeVoice) { +func persistenceApplication(t *testing.T, terminalMode bool) (*application, *fakeVoice) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) t.Cleanup(cancel) @@ -34,24 +34,24 @@ func persistence_application(t *testing.T, terminalMode bool) (*application, *fa voice := &fakeVoice{} source := &fakeSource{snapshot: screen.Snapshot{Terminal: 1, Active: true, Rows: 1, Cols: 5, Cells: []rune("alpha")}} keys := &fakeKeys{poll: func(bool, func(input.Decision)) error { return nil }} - a, err := new_application(ctx, source, keys, voice, RunOptions{Settings: base, ConfigPath: path, TerminalMode: terminalMode, Sounds: &fakeSounds{}}) + a, err := newApplication(ctx, source, keys, voice, RunOptions{Settings: base, ConfigPath: path, TerminalMode: terminalMode, Sounds: &fakeSounds{}}) if err != nil { t.Fatal(err) } t.Cleanup(a.ui.close) - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } return a, voice } -func persistence_request(a *application, text string) chan string { +func persistenceRequest(a *application, text string) chan string { reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid(), Text: "SETTING " + text, Reply: reply}) + a.remoteRequest(control.Request{UID: os.Geteuid(), Text: "SETTING " + text, Reply: reply}) return reply } -func persistence_reply(t *testing.T, reply chan string, wantError bool) { +func persistenceReply(t *testing.T, reply chan string, wantError bool) { t.Helper() select { case text := <-reply: @@ -63,14 +63,14 @@ func persistence_reply(t *testing.T, reply chan string, wantError bool) { } } -func finish_persistence(t *testing.T, a *application, wantError bool) { +func finishPersistence(t *testing.T, a *application, wantError bool) { t.Helper() select { case err := <-a.saver.results: if (err != nil) != wantError { t.Fatal("unexpected save result", err) } - a.settings_save_result(err) + a.settingsSaveResult(err) case <-time.After(time.Second): t.Fatal("save worker stalled") } @@ -78,35 +78,35 @@ func finish_persistence(t *testing.T, a *application, wantError bool) { func TestRemoteResetRestoresLoadedValuesAndPreservesSessionState(t *testing.T) { for _, terminalMode := range []bool{false, true} { - a, _ := persistence_application(t, terminalMode) + a, _ := persistenceApplication(t, terminalMode) base := a.settings.resetBase windowReply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid(), Text: "COMMAND WINDOW 0 0 4 0", Reply: windowReply}) - persistence_reply(t, windowReply, false) - regionRevision := a.engine.Region_revision() + a.remoteRequest(control.Request{UID: os.Geteuid(), Text: "COMMAND WINDOW 0 0 4 0", Reply: windowReply}) + persistenceReply(t, windowReply, false) + regionRevision := a.engine.RegionRevision() a.settings.saveDraft.Keyboard.Layout = "laptop" for _, id := range []command.ID{command.Mute, command.AutoRead, command.ToggleAttributes} { - a.handle_input(input.Decision{Command: id}) + a.handleInput(input.Decision{Command: id}) } - a.handle_input(input.Decision{Command: command.NextQuickValue}) - persistence_reply(t, persistence_request(a, "SET speech#rate=0.2;sound#volume=0.3;screen#ignore_screen=7,8;general#punctuation_level=all;keyboard#word_echo=True"), false) - persistence_reply(t, persistence_request(a, "RESET"), false) - if !a.muted || a.engine.Automatic_reading() || a.settings.live.Presentation.Speech.Rate != base.Presentation.Speech.Rate || !reflect.DeepEqual(a.settings.live.Screen, base.Screen) || a.settings.live.Keyboard.WordEcho || a.settings.live.Presentation.Sound != base.Presentation.Sound || a.settings.live.Reading.PunctuationLevel != base.Reading.PunctuationLevel || a.settings.saveDraft.Keyboard.Layout != "laptop" { + a.handleInput(input.Decision{Command: command.NextQuickValue}) + persistenceReply(t, persistenceRequest(a, "SET speech#rate=0.2;sound#volume=0.3;screen#ignore_screen=7,8;general#punctuation_level=all;keyboard#word_echo=True"), false) + persistenceReply(t, persistenceRequest(a, "RESET"), false) + if !a.muted || a.engine.AutomaticReading() || a.settings.live.Presentation.Speech.Rate != base.Presentation.Speech.Rate || !reflect.DeepEqual(a.settings.live.Screen, base.Screen) || a.settings.live.Keyboard.WordEcho || a.settings.live.Presentation.Sound != base.Presentation.Sound || a.settings.live.Reading.PunctuationLevel != base.Reading.PunctuationLevel || a.settings.saveDraft.Keyboard.Layout != "laptop" { t.Fatal("reset lost session overrides, loaded values or next-launch choices", a.settings.live, a.settings.saveDraft) } if got := a.engine.Command(command.ToggleAttributes).Text; got != "announcement of attributes disabled" { t.Fatal("unrelated remote update/reset lost the session attribute toggle", got) } - if !a.settings.saveDraft.Presentation.Speech.Enabled || !a.settings.saveDraft.Reading.Automatic || a.quick.changed || len(a.settings.remoteFields) != 0 || a.engine.Region_revision() != regionRevision { + if !a.settings.saveDraft.Presentation.Speech.Enabled || !a.settings.saveDraft.Reading.Automatic || a.quick.changed || len(a.settings.remoteFields) != 0 || a.engine.RegionRevision() != regionRevision { t.Fatal("reset persisted unrelated session state or retained overrides") } // A successful menu save becomes the next reset baseline too. menuSaved := a.settings.saveDraft menuSaved.Presentation.Speech.Rate = 44 - a.apply_saved_settings(menuSaved, false) - persistence_reply(t, persistence_request(a, "SET speech#rate=0.1;speech#enabled=False;reading#automatic=False;sound#enabled=False;sound#progress_monitoring=False;reading#cursor_echo=False;keyboard#char_echo_mode=2;keyboard#echo_on_capslock=True"), false) - persistence_reply(t, persistence_request(a, "RESET"), false) - if a.muted || !a.engine.Automatic_reading() || a.settings.live.Presentation != menuSaved.Presentation || a.settings.live.Keyboard.CharacterEcho != menuSaved.Keyboard.CharacterEcho || a.settings.live.Keyboard.EchoOnCapsLock != menuSaved.Keyboard.EchoOnCapsLock || a.settings.live.Reading.CursorEcho != menuSaved.Reading.CursorEcho { + a.applySavedSettings(menuSaved, false) + persistenceReply(t, persistenceRequest(a, "SET speech#rate=0.1;speech#enabled=False;reading#automatic=False;sound#enabled=False;sound#progress_monitoring=False;reading#cursor_echo=False;keyboard#char_echo_mode=2;keyboard#echo_on_capslock=True"), false) + persistenceReply(t, persistenceRequest(a, "RESET"), false) + if a.muted || !a.engine.AutomaticReading() || a.settings.live.Presentation != menuSaved.Presentation || a.settings.live.Keyboard.CharacterEcho != menuSaved.Keyboard.CharacterEcho || a.settings.live.Keyboard.EchoOnCapsLock != menuSaved.Keyboard.EchoOnCapsLock || a.settings.live.Reading.CursorEcho != menuSaved.Reading.CursorEcho { t.Fatal("reset did not restore explicitly overridden booleans or menu baseline", a.settings.live) } } @@ -114,26 +114,26 @@ func TestRemoteResetRestoresLoadedValuesAndPreservesSessionState(t *testing.T) { func TestRemoteSaveAsRepliesAfterWriteAndRetainsNewerOverrides(t *testing.T) { for _, terminalMode := range []bool{false, true} { - a, _ := persistence_application(t, terminalMode) + a, _ := persistenceApplication(t, terminalMode) defaultPath := a.options.ConfigPath exportPath := filepath.Join(t.TempDir(), "export with spaces.toml") for _, id := range []command.ID{command.Mute, command.AutoRead} { - a.handle_input(input.Decision{Command: id}) + a.handleInput(input.Decision{Command: id}) } - persistence_reply(t, persistence_request(a, "SET speech#rate=0.2;sound#volume=0.3"), false) - reply := persistence_request(a, "SAVEAS "+exportPath) + persistenceReply(t, persistenceRequest(a, "SET speech#rate=0.2;sound#volume=0.3"), false) + reply := persistenceRequest(a, "SAVEAS "+exportPath) select { case response := <-reply: t.Fatal("save acknowledged before result processing", response) default: } - persistence_reply(t, persistence_request(a, "RESET"), true) - persistence_reply(t, persistence_request(a, "SAVE"), true) + persistenceReply(t, persistenceRequest(a, "RESET"), true) + persistenceReply(t, persistenceRequest(a, "SAVE"), true) // Keep input and later SET requests responsive while disk work runs. - a.handle_input(input.Decision{Command: command.CurrentLine}) - persistence_reply(t, persistence_request(a, "SET speech#rate=0.8;keyboard#word_echo=True"), false) - finish_persistence(t, a, false) - persistence_reply(t, reply, false) + a.handleInput(input.Decision{Command: command.CurrentLine}) + persistenceReply(t, persistenceRequest(a, "SET speech#rate=0.8;keyboard#word_echo=True"), false) + finishPersistence(t, a, false) + persistenceReply(t, reply, false) saved, _, err := config.Load(exportPath, nil) if err != nil || saved.Presentation.Speech.Rate != -60 || saved.Presentation.Sound.Volume != 0.3 || !saved.Presentation.Speech.Enabled || !saved.Reading.Automatic || saved.Keyboard.WordEcho { t.Fatal("save did not retain its admitted snapshot", saved, err) @@ -146,18 +146,18 @@ func TestRemoteSaveAsRepliesAfterWriteAndRetainsNewerOverrides(t *testing.T) { if err != nil || original.Presentation.Speech.Rate != 24 || a.options.ConfigPath != defaultPath { t.Fatal("SAVEAS changed the default destination", original, err) } - persistence_reply(t, persistence_request(a, "RESET"), false) - if a.settings.live.Presentation.Speech.Rate != -60 || a.settings.live.Keyboard.WordEcho || !a.muted || a.engine.Automatic_reading() { + persistenceReply(t, persistenceRequest(a, "RESET"), false) + if a.settings.live.Presentation.Speech.Rate != -60 || a.settings.live.Keyboard.WordEcho || !a.muted || a.engine.AutomaticReading() { t.Fatal("save completion lost newer changes or reset session state", a.settings.live) } - persistence_reply(t, persistence_request(a, "SET speech#rate=0.9"), false) - reply = persistence_request(a, "SAVE") + persistenceReply(t, persistenceRequest(a, "SET speech#rate=0.9"), false) + reply = persistenceRequest(a, "SAVE") // The existing normal quit waits for the admitted write and reply. - a.handle_input(input.Decision{Command: command.Quit}) + a.handleInput(input.Decision{Command: command.Quit}) if err := a.loop(nil); err != nil || a.ctx.Err() != nil { t.Fatal("save/quit failed", err, a.ctx.Err()) } - persistence_reply(t, reply, false) + persistenceReply(t, reply, false) current, _, err := config.Load(defaultPath, nil) if err != nil || current.Presentation.Speech.Rate != 80 { t.Fatal("SAVE did not use original configured path", current, err) @@ -170,31 +170,31 @@ func TestRemoteSaveAsRepliesAfterWriteAndRetainsNewerOverrides(t *testing.T) { } func TestRemotePersistenceFailureAndAdmissionPreserveState(t *testing.T) { - a, _ := persistence_application(t, true) + a, _ := persistenceApplication(t, true) base := a.settings.resetBase - persistence_reply(t, persistence_request(a, "SET speech#pitch=0.2;speech#volume=0.6;speech#auto_read_incoming=False"), false) + persistenceReply(t, persistenceRequest(a, "SET speech#pitch=0.2;speech#volume=0.6;speech#auto_read_incoming=False"), false) for _, text := range []string{"SAVEAS", "SAVE unexpected", "RESET unexpected", "SAVEAS bad\x00path", "SAVEAS bad\npath"} { - persistence_reply(t, persistence_request(a, text), true) + persistenceReply(t, persistenceRequest(a, text), true) if a.saver.busy { t.Fatal("malformed operation started a worker", text) } } a.ui.active = true - persistence_reply(t, persistence_request(a, "RESET"), true) - persistence_reply(t, persistence_request(a, "SAVE"), true) + persistenceReply(t, persistenceRequest(a, "RESET"), true) + persistenceReply(t, persistenceRequest(a, "SAVE"), true) a.ui.active = false a.settings.live.Remote.EnableSettingsRemote = false - persistence_reply(t, persistence_request(a, "RESET"), true) - persistence_reply(t, persistence_request(a, "SAVEAS "+filepath.Join(t.TempDir(), "denied.toml")), true) + persistenceReply(t, persistenceRequest(a, "RESET"), true) + persistenceReply(t, persistenceRequest(a, "SAVEAS "+filepath.Join(t.TempDir(), "denied.toml")), true) a.settings.live.Remote.EnableSettingsRemote = true denied := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid() + 1, Text: "SETTING RESET", Reply: denied}) - persistence_reply(t, denied, true) - if response, deferred := a.remote_settings_request("SAVEAS ignored.toml", control.Request{UID: os.Geteuid() + 1}); response != "SAVEAS requires the reader owner or root" || deferred || a.saver.busy { + a.remoteRequest(control.Request{UID: os.Geteuid() + 1, Text: "SETTING RESET", Reply: denied}) + persistenceReply(t, denied, true) + if response, deferred := a.remoteSettingsRequest("SAVEAS ignored.toml", control.Request{UID: os.Geteuid() + 1}); response != "SAVEAS requires the reader owner or root" || deferred || a.saver.busy { t.Fatal("SAVEAS granted arbitrary privileged writes", response, deferred) } - reply := persistence_request(a, "SAVEAS "+t.TempDir()) // A directory cannot be a TOML file. - finish_persistence(t, a, true) + reply := persistenceRequest(a, "SAVEAS "+t.TempDir()) // A directory cannot be a TOML file. + finishPersistence(t, a, true) select { case response := <-reply: if !strings.HasPrefix(response, "Could not save settings:") { @@ -210,11 +210,11 @@ func TestRemotePersistenceFailureAndAdmissionPreserveState(t *testing.T) { if err := syscall.Mkfifo(pipePath, 0600); err != nil { t.Fatal(err) } - reply = persistence_request(a, "SAVEAS "+pipePath) - finish_persistence(t, a, true) - persistence_reply(t, reply, true) - persistence_reply(t, persistence_request(a, "RESET"), false) - if a.settings.live.Presentation.Speech != base.Presentation.Speech || !a.engine.Automatic_reading() { + reply = persistenceRequest(a, "SAVEAS "+pipePath) + finishPersistence(t, a, true) + persistenceReply(t, reply, true) + persistenceReply(t, persistenceRequest(a, "RESET"), false) + if a.settings.live.Presentation.Speech != base.Presentation.Speech || !a.engine.AutomaticReading() { t.Fatal("failed-save overrides were not reset", a.settings.live) } } diff --git a/internal/app/remote_runtime_test.go b/internal/app/remote_runtime_test.go index 7a32f20a..f7a291a7 100644 --- a/internal/app/remote_runtime_test.go +++ b/internal/app/remote_runtime_test.go @@ -14,9 +14,9 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func runtime_request(a *application, text string) string { +func runtimeRequest(a *application, text string) string { reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid(), Text: text, Reply: reply}) + a.remoteRequest(control.Request{UID: os.Geteuid(), Text: text, Reply: reply}) return <-reply } @@ -33,7 +33,7 @@ func TestRemoteTrackingSelectionAndAtomicFlags(t *testing.T) { {"focus#highlight=False,focus#cursor=True", "cursor"}, {"focus#cursor=False;focus#highlight=False", "table"}, } { - updated, err := remote_settings(base, "SET "+trial.text) + updated, err := remoteSettings(base, "SET "+trial.text) if err != nil || updated.Reading.Mode != trial.mode { t.Fatal(baseMode, trial, updated.Reading.Mode, err) } @@ -43,7 +43,7 @@ func TestRemoteTrackingSelectionAndAtomicFlags(t *testing.T) { "focus#cursor=invalid", "focus#cursor=True;focus#highlight=True", "reading#mode=cursor;focus#highlight=False", } { - updated, err := remote_settings(base, "SET speech#enabled=False;"+invalid) + updated, err := remoteSettings(base, "SET speech#enabled=False;"+invalid) if err == nil || !reflect.DeepEqual(updated, base) { t.Fatal("invalid selection partially applied", baseMode, invalid, updated, err) } @@ -53,43 +53,43 @@ func TestRemoteTrackingSelectionAndAtomicFlags(t *testing.T) { func TestRemoteTrackingLiveSaveResetAndGates(t *testing.T) { for _, terminalMode := range []bool{false, true} { - a, _ := persistence_application(t, terminalMode) + a, _ := persistenceApplication(t, terminalMode) // A Python flag update must use the current mode for both live and // saved state, even when a menu draft chose a different startup mode. a.settings.saveDraft.Reading.Mode = "highlight" for _, text := range []string{"SETTING SET focus#cursor=False;focus#highlight=True", "SETTING SET reading#mode=highlight"} { a.settings.live.Remote.EnableSettingsRemote = false - if runtime_request(a, text) == "" || a.engine.Tracking_mode() != "cursor" { + if runtimeRequest(a, text) == "" || a.engine.TrackingMode() != "cursor" { t.Fatal("disabled remote changed mode") } a.settings.live.Remote.EnableSettingsRemote = true reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid() + 1, Text: text, Reply: reply}) - if <-reply == "" || a.engine.Tracking_mode() != "cursor" { + a.remoteRequest(control.Request{UID: os.Geteuid() + 1, Text: text, Reply: reply}) + if <-reply == "" || a.engine.TrackingMode() != "cursor" { t.Fatal("unauthorized caller changed mode") } - if response := runtime_request(a, text); response != "" || a.engine.Tracking_mode() != "highlight" || a.settings.saveDraft.Reading.Mode != "highlight" { + if response := runtimeRequest(a, text); response != "" || a.engine.TrackingMode() != "highlight" || a.settings.saveDraft.Reading.Mode != "highlight" { t.Fatal("tracking not applied to live/draft", response) } - if response := runtime_request(a, "SETTING RESET"); response != "" || a.engine.Tracking_mode() != "cursor" || a.settings.saveDraft.Reading.Mode != "cursor" { + if response := runtimeRequest(a, "SETTING RESET"); response != "" || a.engine.TrackingMode() != "cursor" || a.settings.saveDraft.Reading.Mode != "cursor" { t.Fatal("reset did not restore tracking", response) } } a.settings.saveDraft.Reading.Mode = "highlight" - if response := runtime_request(a, "SETTING SET focus#cursor=False"); response != "" || a.engine.Tracking_mode() != "table" || a.settings.saveDraft.Reading.Mode != "table" { + if response := runtimeRequest(a, "SETTING SET focus#cursor=False"); response != "" || a.engine.TrackingMode() != "table" || a.settings.saveDraft.Reading.Mode != "table" { t.Fatal("partial flag update used a stale saved mode", response) } - reply := persistence_request(a, "SAVE") - finish_persistence(t, a, false) - persistence_reply(t, reply, false) + reply := persistenceRequest(a, "SAVE") + finishPersistence(t, a, false) + persistenceReply(t, reply, false) saved, _, err := config.Load(a.options.ConfigPath, nil) if err != nil || saved.Reading.Mode != "table" { t.Fatal("remote tracking not saved", saved.Reading.Mode, err) } - if response := runtime_request(a, "SETTING SET reading#mode=highlight"); response != "" { + if response := runtimeRequest(a, "SETTING SET reading#mode=highlight"); response != "" { t.Fatal(response) } - if response := runtime_request(a, "SETTING RESET"); response != "" || a.engine.Tracking_mode() != "table" { + if response := runtimeRequest(a, "SETTING RESET"); response != "" || a.engine.TrackingMode() != "table" { t.Fatal("reset lost saved tracking baseline", response) } } @@ -98,7 +98,7 @@ func TestRemoteTrackingLiveSaveResetAndGates(t *testing.T) { func TestRemoteSpeechRestorationFeedbackAndAdmission(t *testing.T) { for _, terminalMode := range []bool{false, true} { for _, soundMode := range []string{"enabled", "disabled", "missing", "unavailable"} { - a, voice := persistence_application(t, terminalMode) + a, voice := persistenceApplication(t, terminalMode) sounds := a.cues.(*fakeSounds) a.settings.live.Presentation.Sound.Enabled = soundMode != "disabled" if soundMode == "missing" { @@ -108,7 +108,7 @@ func TestRemoteSpeechRestorationFeedbackAndAdmission(t *testing.T) { } voice.messages, sounds.cues = nil, nil for _, text := range []string{"SETTING SET speech#enabled=False", "COMMAND SAY discarded", "SETTING SET speech#enabled=True"} { - if response := runtime_request(a, text); response != "" { + if response := runtimeRequest(a, text); response != "" { t.Fatal(response) } } @@ -123,35 +123,35 @@ func TestRemoteSpeechRestorationFeedbackAndAdmission(t *testing.T) { t.Fatal("missing restoration speech fallback", soundMode, voice.messages) } voice.messages, sounds.cues = nil, nil - if response := runtime_request(a, "SETTING SET speech#enabled=True"); response != "" || len(voice.messages)+len(sounds.cues) != 0 { + if response := runtimeRequest(a, "SETTING SET speech#enabled=True"); response != "" || len(voice.messages)+len(sounds.cues) != 0 { t.Fatal("identical enable repeated feedback", response) } - if response := runtime_request(a, "COMMAND TEMPDISABLESPEECH"); response != "" || !a.temporarySilence { + if response := runtimeRequest(a, "COMMAND TEMPDISABLESPEECH"); response != "" || !a.temporarySilence { t.Fatal("remote keypad action did not silence", response) } voice.messages, sounds.cues = nil, nil before := a.settings.saveDraft reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid() + 1, Text: "SETTING SET speech#enabled=True", Reply: reply}) + a.remoteRequest(control.Request{UID: os.Geteuid() + 1, Text: "SETTING SET speech#enabled=True", Reply: reply}) if <-reply == "" || !a.temporarySilence { t.Fatal("unauthorized enable restored temporary silence") } a.settings.live.Remote.EnableSettingsRemote = false - if response := runtime_request(a, "SETTING SET speech#enabled=True"); response == "" || !a.temporarySilence { + if response := runtimeRequest(a, "SETTING SET speech#enabled=True"); response == "" || !a.temporarySilence { t.Fatal("disabled remote enable restored temporary silence", response) } a.settings.live.Remote.EnableSettingsRemote = true for _, text := range []string{"SETTING SET speech#enabled=True;reading#mode=bad", "COMMAND TEMPDISABLESPEECH extra"} { - if response := runtime_request(a, text); response == "" || !a.temporarySilence || !reflect.DeepEqual(a.settings.saveDraft, before) || len(voice.messages)+len(sounds.cues) != 0 { + if response := runtimeRequest(a, text); response == "" || !a.temporarySilence || !reflect.DeepEqual(a.settings.saveDraft, before) || len(voice.messages)+len(sounds.cues) != 0 { t.Fatal("invalid request restored speech or changed state", text, response) } } for _, text := range []string{"COMMAND SAY discarded", "SETTING SET reading#mode=highlight"} { - if response := runtime_request(a, text); response != "" || !a.temporarySilence || len(voice.messages) != 0 { + if response := runtimeRequest(a, text); response != "" || !a.temporarySilence || len(voice.messages) != 0 { t.Fatal("unrelated request cleared temporary silence", text, response) } } - if response := runtime_request(a, "SETTING SET speech#enabled=True"); response != "" || a.temporarySilence || a.muted { + if response := runtimeRequest(a, "SETTING SET speech#enabled=True"); response != "" || a.temporarySilence || a.muted { t.Fatal("explicit enable failed to restore temporary silence", response) } if soundMode == "enabled" { @@ -166,10 +166,10 @@ func TestRemoteSpeechRestorationFeedbackAndAdmission(t *testing.T) { } func TestRemoteNoArgumentCommandsRejectExtraParameters(t *testing.T) { - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) for _, verb := range []string{"INTERRUPT", "TEMPDISABLESPEECH", "QUITAPPLICATION", "EXPORTCLIPBOARD"} { before := voice.interrupts - if response := runtime_request(a, "COMMAND "+verb+" extra"); response == "" || a.quitting || a.temporarySilence || voice.interrupts != before { + if response := runtimeRequest(a, "COMMAND "+verb+" extra"); response == "" || a.quitting || a.temporarySilence || voice.interrupts != before { t.Fatal("malformed command had side effects", verb, response) } } diff --git a/internal/app/remote_settings.go b/internal/app/remote_settings.go index fb46573d..8f70504f 100644 --- a/internal/app/remote_settings.go +++ b/internal/app/remote_settings.go @@ -34,7 +34,7 @@ import ( // Python's section#setting=value wire syntax remains distinct from TOML disk // settings. Apply an entire request to a copy and validate before changing the // reader. Unsupported Python-only features are reported, never silently saved. -func remote_settings(base config.Settings, text string) (config.Settings, error) { +func remoteSettings(base config.Settings, text string) (config.Settings, error) { verb, parameters, _ := strings.Cut(text, " ") if strings.ToUpper(verb) != "SET" { return base, fmt.Errorf("Unsupported remote settings operation: %s", verb) @@ -42,7 +42,7 @@ func remote_settings(base config.Settings, text string) (config.Settings, error) updated := base cursorTracking, highlightTracking := base.Reading.Mode == "cursor", base.Reading.Mode == "highlight" focusChanged, modeChanged := false, false - for _, assignment := range remote_assignments(parameters) { + for _, assignment := range remoteAssignments(parameters) { path, _, _ := strings.Cut(assignment, "=") switch strings.ToLower(strings.TrimSpace(path)) { case "speech#module": @@ -52,7 +52,7 @@ func remote_settings(base config.Settings, text string) (config.Settings, error) updated.Presentation.Speech.Voice = "" } } - for _, assignment := range remote_assignments(parameters) { + for _, assignment := range remoteAssignments(parameters) { path, value, ok := strings.Cut(assignment, "=") if !ok { return base, fmt.Errorf("Invalid remote setting assignment") @@ -162,7 +162,7 @@ func remote_settings(base config.Settings, text string) (config.Settings, error) // Python lists use commas inside a value. Preserve those while retaining the // existing comma-separated assignments when a new path=value begins. -func remote_assignments(parameters string) []string { +func remoteAssignments(parameters string) []string { var assignments []string for _, group := range strings.Split(parameters, ";") { parts := strings.Split(group, ",") @@ -180,10 +180,10 @@ func remote_assignments(parameters string) []string { return assignments } -func (a *application) remote_request(request control.Request) { +func (a *application) remoteRequest(request control.Request) { response := "" deferred := false - if !remote_authorized(request.UID, a.lastTerminal, a.options.TerminalMode) { + if !remoteAuthorized(request.UID, a.lastTerminal, a.options.TerminalMode) { response = "Remote control is not permitted for this session" } else { section, text, _ := strings.Cut(request.Text, " ") @@ -192,14 +192,14 @@ func (a *application) remote_request(request control.Request) { if !a.settings.live.Remote.EnableCommandRemote { response = "Command remote control is disabled" } else { - response = a.codex_event(text) + response = a.codexEvent(text) } case "COMMAND": if !a.settings.live.Remote.EnableCommandRemote { response = "Command remote control is disabled" break } - if reply, handled := a.remote_window(text); handled { + if reply, handled := a.remoteWindow(text); handled { response = reply break } @@ -225,15 +225,15 @@ func (a *application) remote_request(request control.Request) { case "INTERRUPT": a.voice.Interrupt() case "TEMPDISABLESPEECH": - a.handle_input(input.Decision{Command: command.TempDisableSpeech, Interrupt: true}) + a.handleInput(input.Decision{Command: command.TempDisableSpeech, Interrupt: true}) case "QUITAPPLICATION": - a.handle_command(command.Quit) + a.handleCommand(command.Quit) case "CLIPBOARD": a.clipboards.add(parameter, true) case "EXPORTCLIPBOARD": a.clipboards.command(command.ExportClipboard) case "APPLICATION": - a.remote_application(parameter, request) + a.remoteApplication(parameter, request) deferred = true default: response = "Unsupported remote command: " + verb @@ -243,11 +243,11 @@ func (a *application) remote_request(request control.Request) { response = "Settings remote control is disabled" break } - if reply, handled := a.remote_window(text); handled { + if reply, handled := a.remoteWindow(text); handled { response = reply break } - response, deferred = a.remote_settings_request(text, request) + response, deferred = a.remoteSettingsRequest(text, request) default: response = "Unknown command format. Use 'COMMAND ...' or 'SETTING ...'" } @@ -255,10 +255,10 @@ func (a *application) remote_request(request control.Request) { if deferred { return // The save result owns the original reply channel. } - remote_reply(request.Reply, response) + remoteReply(request.Reply, response) } -func remote_reply(reply chan string, response string) { +func remoteReply(reply chan string, response string) { if response != "" { // An opt-in bridge may be attached while its override is unselected, // loading, or on another VT. Its normal retry must not fill the log. @@ -278,11 +278,11 @@ func remote_reply(reply chan string, response string) { // Resolve paired focus flags at admission. A physical tracking command during // asynchronous voice preparation must not make a validated request invalid // after its speaking transport has already been committed. -func resolved_remote_selection(text string, admitted config.Settings) string { +func resolvedRemoteSelection(text string, admitted config.Settings) string { _, parameters, _ := strings.Cut(text, " ") var kept []string focus := false - for _, assignment := range remote_assignments(parameters) { + for _, assignment := range remoteAssignments(parameters) { path, _, _ := strings.Cut(assignment, "=") switch strings.ToLower(strings.TrimSpace(path)) { case "focus#cursor", "focus#highlight": diff --git a/internal/app/review_spelling.go b/internal/app/review_spelling.go index 151f0dbe..63f8d846 100644 --- a/internal/app/review_spelling.go +++ b/internal/app/review_spelling.go @@ -10,13 +10,13 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func (s *echoSpeaker) say_spelling(spelling presentation.Spelling) { +func (s *echoSpeaker) saySpelling(spelling presentation.Spelling) { for _, char := range spelling.Text { if !spelling.Phonetic { - s.say_character(char) + s.sayCharacter(char) continue } - text := presentation.Phonetic_letter(char) + text := presentation.PhoneticLetter(char) if text == "" { text = presentation.Character(char) if s.punctuation != nil { diff --git a/internal/app/review_spelling_test.go b/internal/app/review_spelling_test.go index 6daea5a2..a7c33103 100644 --- a/internal/app/review_spelling_test.go +++ b/internal/app/review_spelling_test.go @@ -33,7 +33,7 @@ func TestSpellingPreservesRunesAndNamesWithoutDoubleProcessing(t *testing.T) { echo := &echoSpeaker{Speaker: voice, settings: &settings, punctuation: processor, punctuationLevel: level, play: func(presentation.Cue) bool { beeps++; return true }} const source = "A book!?É界🙂\t" - echo.say_spelling(presentation.Spelling{Text: source, Phonetic: true}) + echo.saySpelling(presentation.Spelling{Text: source, Phonetic: true}) prefix := "" if settings.Reading.SayCapForCapitals { prefix = "cap " @@ -43,7 +43,7 @@ func TestSpellingPreservesRunesAndNamesWithoutDoubleProcessing(t *testing.T) { t.Fatal(profile, level, choices, got, voice.pitches, beeps) } voice.messages = nil - echo.say_spelling(presentation.Spelling{Text: source}) + echo.saySpelling(presentation.Spelling{Text: source}) want[0], want[2], want[3], want[4], want[5] = prefix+"A", "b", "o", "o", "k" if got := strings.Join(voice.messages, "|"); got != strings.Join(want, "|") { t.Fatal(profile, level, got) diff --git a/internal/app/runtime_settings.go b/internal/app/runtime_settings.go index c23c156c..eae8f5a1 100644 --- a/internal/app/runtime_settings.go +++ b/internal/app/runtime_settings.go @@ -42,29 +42,29 @@ type applicationSettings struct { speechAvailable bool // The startup connection cannot be enabled by a remote setting. } -// configure_reader applies startup settings, including next-launch-only fields. -func (a *application) configure_reader() { - a.configure_screen() +// configureReader applies startup settings, including next-launch-only fields. +func (a *application) configureReader() { + a.configureScreen() a.engine.Configure(a.settings.live.Reading.Automatic, a.settings.live.Reading.CursorEcho) - a.engine.Configure_indentation(a.settings.live.Reading.Indentation) - a.engine.Configure_attributes(a.settings.live.Reading.Attributes, a.settings.live.Reading.AttributeFormat) - a.engine.Configure_progress(a.settings.live.Presentation.Progress.Enabled) - a.engine.Configure_tracking(a.settings.live.Reading.Mode) - a.engine.Configure_review(a.settings.live.Review.LineBreak, a.settings.live.Review.EndOfScreen, a.settings.live.Review.LeaveReviewOnCursorChange, a.settings.live.Review.LeaveReviewOnScreenChange) - a.engine.Configure_echo(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) + a.engine.ConfigureIndentation(a.settings.live.Reading.Indentation) + a.engine.ConfigureAttributes(a.settings.live.Reading.Attributes, a.settings.live.Reading.AttributeFormat) + a.engine.ConfigureProgress(a.settings.live.Presentation.Progress.Enabled) + a.engine.ConfigureTracking(a.settings.live.Reading.Mode) + a.engine.ConfigureReview(a.settings.live.Review.LineBreak, a.settings.live.Review.EndOfScreen, a.settings.live.Review.LeaveReviewOnCursorChange, a.settings.live.Review.LeaveReviewOnScreenChange) + a.engine.ConfigureEcho(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) } -func (a *application) configure_screen() { +func (a *application) configureScreen() { if !a.options.TerminalMode { - if source, ok := a.source.(interface{ Configure_ignored_vts([]int) }); ok { - source.Configure_ignored_vts(a.settings.live.Screen.IgnoredVTs) + if source, ok := a.source.(interface{ ConfigureIgnoredVts([]int) }); ok { + source.ConfigureIgnoredVts(a.settings.live.Screen.IgnoredVTs) } } } -// preview_spelling invalidates queued feedback when menu previews change. +// previewSpelling invalidates queued feedback when menu previews change. // The modal host restores the previous values on cancellation. -func (a *application) preview_spelling(reading config.Reading) { +func (a *application) previewSpelling(reading config.Reading) { if a.settings.live.Reading.Spellcheck != reading.Spellcheck || a.settings.live.Reading.SpellcheckSound != reading.SpellcheckSound || a.settings.live.Reading.SpellcheckReadWord != reading.SpellcheckReadWord || a.settings.live.Reading.SpellcheckSayMisspelled != reading.SpellcheckSayMisspelled { a.spellFeedback++ @@ -75,11 +75,11 @@ func (a *application) preview_spelling(reading config.Reading) { a.settings.live.Reading.SpellcheckSound = reading.SpellcheckSound } -// apply_saved_settings keeps the complete saved draft but applies only fields +// applySavedSettings keeps the complete saved draft but applies only fields // supported live. Device, layout and backend changes wait until the next launch. -func (a *application) apply_saved_settings(saved config.Settings, speechApplied bool) { +func (a *application) applySavedSettings(saved config.Settings, speechApplied bool) { if speechApplied { - copy_speech_selection(&a.settings.live.Presentation.Speech, saved.Presentation.Speech) + copySpeechSelection(&a.settings.live.Presentation.Speech, saved.Presentation.Speech) } if !slices.Equal(saved.Keyboard.FenrirKeys, a.settings.live.Keyboard.FenrirKeys) || !slices.Equal(saved.General.ScriptKeys, a.settings.live.General.ScriptKeys) { a.settings.pendingModifiers = &modifierSettings{fenrirKeys: slices.Clone(saved.Keyboard.FenrirKeys), scriptKeys: slices.Clone(saved.General.ScriptKeys)} @@ -91,8 +91,8 @@ func (a *application) apply_saved_settings(saved config.Settings, speechApplied a.settings.live.VoiceProfiles = saved.VoiceProfiles.Clone() a.settings.live.InternalUI = saved.InternalUI a.settings.live.Screen = saved.Screen - a.configure_screen() - a.preview_spelling(saved.Reading) + a.configureScreen() + a.previewSpelling(saved.Reading) a.settings.live.Presentation.DateTime = saved.Presentation.DateTime a.settings.live.Reading.PunctuationLevel = saved.Reading.PunctuationLevel a.settings.live.Reading.Emoticons = saved.Reading.Emoticons @@ -100,9 +100,9 @@ func (a *application) apply_saved_settings(saved config.Settings, speechApplied a.settings.live.Reading.RepeatedSymbolsMin = saved.Reading.RepeatedSymbolsMin a.settings.live.Reading.Attributes = saved.Reading.Attributes a.settings.live.Reading.AttributeFormat = saved.Reading.AttributeFormat - a.engine.Configure_attributes(saved.Reading.Attributes, saved.Reading.AttributeFormat) + a.engine.ConfigureAttributes(saved.Reading.Attributes, saved.Reading.AttributeFormat) a.settings.live.Reading.Indentation = saved.Reading.Indentation - a.engine.Configure_indentation(saved.Reading.Indentation) + a.engine.ConfigureIndentation(saved.Reading.Indentation) a.settings.live.Reading.RaisePitchForCapitals = saved.Reading.RaisePitchForCapitals a.settings.live.Reading.BeepForCapitals = saved.Reading.BeepForCapitals a.settings.live.Reading.SayCapForCapitals = saved.Reading.SayCapForCapitals @@ -110,34 +110,34 @@ func (a *application) apply_saved_settings(saved config.Settings, speechApplied a.settings.live.Presentation.Speech.Rate = saved.Presentation.Speech.Rate a.settings.live.Presentation.Speech.Pitch = saved.Presentation.Speech.Pitch a.settings.live.Presentation.Speech.Volume = saved.Presentation.Speech.Volume - a.voice.Configure(speech_parameters(a.settings.live)) + a.voice.Configure(speechParameters(a.settings.live)) a.settings.live.Keyboard.CharacterEcho = saved.Keyboard.CharacterEcho a.settings.live.Keyboard.WordEcho = saved.Keyboard.WordEcho a.settings.live.Keyboard.EchoOnCapsLock = saved.Keyboard.EchoOnCapsLock - a.engine.Configure_echo(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) + a.engine.ConfigureEcho(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) a.quick.changed = false a.quick.selectionChanged = false a.settings.live.Presentation.Sound.Volume = saved.Presentation.Sound.Volume if a.cues != nil { - a.cues.Set_volume(saved.Presentation.Sound.Volume) + a.cues.SetVolume(saved.Presentation.Sound.Volume) } a.settings.live.Presentation.Progress = saved.Presentation.Progress - a.engine.Configure_progress(saved.Presentation.Progress.Enabled) + a.engine.ConfigureProgress(saved.Presentation.Progress.Enabled) if a.cues != nil { - a.cues.Clear_progress() + a.cues.ClearProgress() } a.settings.live.Clipboard = saved.Clipboard a.clipboards.configure(saved.Clipboard) } -// apply_pending_modifiers runs on the event loop after menu closure. Native +// applyPendingModifiers runs on the event loop after menu closure. Native // adapters defer while keys are held; failure leaves the prior runtime intact. -func (a *application) apply_pending_modifiers() { +func (a *application) applyPendingModifiers() { pending := a.settings.pendingModifiers if pending == nil || a.ui.active { return } - applied, err := a.keyboards.Update_modifiers(pending.fenrirKeys, pending.scriptKeys) + applied, err := a.keyboards.UpdateModifiers(pending.fenrirKeys, pending.scriptKeys) if err != nil { a.settings.pendingModifiers = nil a.voice.Say(i18n.Format("Settings saved, but key changes could not be applied: {0}. Previous keys remain active.", err.Error())) @@ -153,37 +153,37 @@ func (a *application) apply_pending_modifiers() { // Quick commands have already changed live values and configured speech when // needed. Refresh the reader without copying session overrides into the draft. -func (a *application) apply_quick_settings() { +func (a *application) applyQuickSettings() { a.voice.punctuationLevel = a.settings.live.Reading.PunctuationLevel - a.engine.Configure_echo(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) - a.engine.Configure_indentation(a.settings.live.Reading.Indentation) - a.engine.Configure_attributes(a.settings.live.Reading.Attributes, a.settings.live.Reading.AttributeFormat) + a.engine.ConfigureEcho(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) + a.engine.ConfigureIndentation(a.settings.live.Reading.Indentation) + a.engine.ConfigureAttributes(a.settings.live.Reading.Attributes, a.settings.live.Reading.AttributeFormat) } -func (a *application) open_settings() { +func (a *application) openSettings() { if a.saver.busy || a.speechPending { a.ui.failed("Could not open Fenrir Menu: {0}", fmt.Errorf("settings save in progress")) return } - a.settings.live.Reading.Mode = a.engine.Tracking_mode() + a.settings.live.Reading.Mode = a.engine.TrackingMode() a.ui.speechOverride = nil if a.quick.selectionChanged { selected := a.settings.live.Presentation.Speech a.ui.speechOverride = &selected } if selected := a.overrideCurrent; selected != nil { - a.ui.open_application_settings(a.settings_to_save(), selected.path, selected.base, i18n.T(selected.adapter.Name())) + a.ui.openApplicationSettings(a.settingsToSave(), selected.path, selected.base, i18n.T(selected.adapter.Name())) return } if a.quick.changed { - a.ui.open_settings(a.settings.live, a.options.ConfigPath, a.settings.live) + a.ui.openSettings(a.settings.live, a.options.ConfigPath, a.settings.live) } else { - a.ui.open_settings(a.settings.live, a.options.ConfigPath) + a.ui.openSettings(a.settings.live, a.options.ConfigPath) } } -func (a *application) save_settings() { - if a.saves_unavailable() { +func (a *application) saveSettings() { + if a.savesUnavailable() { a.voice.Say(i18n.T("Save unavailable.")) return } @@ -191,7 +191,7 @@ func (a *application) save_settings() { a.voice.Say(i18n.T("Failed to save settings.")) return } - if a.start_settings_save(a.settings_path(), a.settings_to_save()) { + if a.startSettingsSave(a.settingsPath(), a.settingsToSave()) { a.saver.revision = a.settings.remoteRevision } } @@ -199,8 +199,8 @@ func (a *application) save_settings() { // Menu writes share admission and completion with quick/remote saves. Only // presentation belongs to the modal generation; a committed write belongs to // the application even after Escape or a session handoff closes its form. -func (a *application) save_menu_settings(doc *config.Document, draft config.Settings, done func(error)) bool { - if a.saves_unavailable() { +func (a *application) saveMenuSettings(doc *config.Document, draft config.Settings, done func(error)) bool { + if a.savesUnavailable() { a.voice.Say(i18n.T("Save unavailable.")) return false } @@ -208,8 +208,8 @@ func (a *application) save_menu_settings(doc *config.Document, draft config.Sett a.ui.failed("Could not save settings: {0}", fmt.Errorf("speech selection in progress")) return false } - if a.after_speech_preview(func() { - if !a.save_menu_settings(doc, draft, done) { + if a.afterSpeechPreview(func() { + if !a.saveMenuSettings(doc, draft, done) { done(fmt.Errorf("settings save in progress")) } }) { @@ -218,10 +218,10 @@ func (a *application) save_menu_settings(doc *config.Document, draft config.Sett previousDraft := a.settings.saveDraft liveSpeech, draftSpeech := a.settings.live.Presentation.Speech, draft.Presentation.Speech sameDevice := draftSpeech.Driver == liveSpeech.Driver && draftSpeech.HardwareDevice == liveSpeech.HardwareDevice && draftSpeech.HardwareBaudRate == liveSpeech.HardwareBaudRate - profileSelected := draft.VoiceProfiles.Matching(config.Primary_voice(draft)) != "" - speechApplied := a.settings.speechAvailable && (sameDevice || profileSelected) && !same_speech_selection(draftSpeech, liveSpeech) + profileSelected := draft.VoiceProfiles.Matching(config.PrimaryVoice(draft)) != "" + speechApplied := a.settings.speechAvailable && (sameDevice || profileSelected) && !sameSpeechSelection(draftSpeech, liveSpeech) // The menu preview may already be speaking with this selection. - previewed := a.preview.active && same_speech_selection(a.preview.selection, draftSpeech) + previewed := a.preview.active && sameSpeechSelection(a.preview.selection, draftSpeech) if !a.saver.start(a.ctx, draft, func() error { var prepared speech.Transport if speechApplied && !previewed { @@ -238,7 +238,7 @@ func (a *application) save_menu_settings(doc *config.Document, draft config.Sett return err } if prepared != nil { - if err := a.replace_speech(prepared); err != nil { + if err := a.replaceSpeech(prepared); err != nil { return &savedSpeechError{err: err} } return nil @@ -251,11 +251,11 @@ func (a *application) save_menu_settings(doc *config.Document, draft config.Sett a.saver.revision = a.settings.remoteRevision quickRevision := a.quick.revision a.saver.menuDone = func(err error) { - if settings_committed(err) { + if settingsCommitted(err) { merged := draft - // settings_save_result already removed overrides included in the + // settingsSaveResult already removed overrides included in the // commit. Remaining remote fields were assigned after admission. - copy_remote_settings(&merged, a.settings.saveDraft, a.settings.remoteFields) + copyRemoteSettings(&merged, a.settings.saveDraft, a.settings.remoteFields) newerQuick := false for _, definition := range config.Definitions() { if a.quick.fields[definition.Path] > quickRevision { @@ -270,60 +270,60 @@ func (a *application) save_menu_settings(doc *config.Document, draft config.Sett merged.Presentation.Progress = a.settings.live.Presentation.Progress } if a.overrideCurrent != nil { - live := config.Apply_application_settings(a.effective_settings(), merged) + live := config.ApplyApplicationSettings(a.effectiveSettings(), merged) if merged.Presentation.Speech.Enabled == previousDraft.Presentation.Speech.Enabled { live.Presentation.Speech.Enabled = !a.muted } if merged.Reading.Automatic == previousDraft.Reading.Automatic { - live.Reading.Automatic = a.engine.Automatic_reading() + live.Reading.Automatic = a.engine.AutomaticReading() } if !speechApplied || err != nil { - copy_speech_selection(&live.Presentation.Speech, a.settings.live.Presentation.Speech) + copySpeechSelection(&live.Presentation.Speech, a.settings.live.Presentation.Speech) } - a.apply_remote_state(live, false) - a.configure_reader() + a.applyRemoteState(live, false) + a.configureReader() a.settings.saveDraft = merged a.quick.selectionChanged = false } else { - a.apply_saved_settings(merged, speechApplied && err == nil) + a.applySavedSettings(merged, speechApplied && err == nil) } a.settings.resetBase = draft // RESET reflects disk, not later overrides. a.quick.changed = newerQuick } // A committed save owns the voice now; otherwise the form stays // open with its preview. Either way the live settings decide. - if settings_committed(err) { - a.restore_speech_preview() + if settingsCommitted(err) { + a.restoreSpeechPreview() } done(err) } return true } -func (a *application) settings_to_save() config.Settings { +func (a *application) settingsToSave() config.Settings { saved := a.settings.saveDraft - copy_quick_settings(&saved, a.settings.live) + copyQuickSettings(&saved, a.settings.live) if a.quick.selectionChanged { - copy_speech_selection(&saved.Presentation.Speech, a.settings.live.Presentation.Speech) + copySpeechSelection(&saved.Presentation.Speech, a.settings.live.Presentation.Speech) } return saved } -func (a *application) effective_settings() config.Settings { +func (a *application) effectiveSettings() config.Settings { base := a.settings.live base.Presentation.Speech.Enabled = !a.muted - base.Reading.Automatic = a.engine.Automatic_reading() - base.Reading.Mode = a.engine.Tracking_mode() + base.Reading.Automatic = a.engine.AutomaticReading() + base.Reading.Mode = a.engine.TrackingMode() return base } // Remote assignments are validated against effective session state, then // separately overlaid on the save draft so unrelated next-launch choices survive. -func (a *application) apply_remote_settings(text string) string { - if err := a.check_application_remote(text); err != nil { +func (a *application) applyRemoteSettings(text string) string { + if err := a.checkApplicationRemote(text); err != nil { return err.Error() } - updated, err := remote_settings(a.effective_settings(), text) + updated, err := remoteSettings(a.effectiveSettings(), text) if err != nil { return err.Error() } @@ -334,26 +334,26 @@ func (a *application) apply_remote_settings(text string) string { // draft, retaining unrelated next-launch menu settings. draftBase := a.settings.saveDraft _, parameters, _ := strings.Cut(text, " ") - for _, assignment := range remote_assignments(parameters) { + for _, assignment := range remoteAssignments(parameters) { path, _, _ := strings.Cut(assignment, "=") switch strings.ToLower(strings.TrimSpace(path)) { case "reading#mode", "focus#cursor", "focus#highlight": // Resolve paired flags against the running mode, even if the // next-launch draft started with a different mode. - draftBase.Reading.Mode = a.engine.Tracking_mode() + draftBase.Reading.Mode = a.engine.TrackingMode() } } - persisted, err := remote_settings(draftBase, text) + persisted, err := remoteSettings(draftBase, text) if err != nil { return err.Error() } a.settings.saveDraft = persisted - if !same_speech_selection(updated.Presentation.Speech, a.settings.live.Presentation.Speech) { + if !sameSpeechSelection(updated.Presentation.Speech, a.settings.live.Presentation.Speech) { a.quick.selectionChanged = false } a.settings.remoteRevision++ restoreSpeech := false - for _, assignment := range remote_assignments(parameters) { + for _, assignment := range remoteAssignments(parameters) { path, _, _ := strings.Cut(assignment, "=") path = strings.ToLower(strings.TrimSpace(path)) a.settings.remoteFields[path] = a.settings.remoteRevision @@ -361,44 +361,44 @@ func (a *application) apply_remote_settings(text string) string { restoreSpeech = updated.Presentation.Speech.Enabled } } - a.apply_remote_state(updated, restoreSpeech) + a.applyRemoteState(updated, restoreSpeech) return "" } -func (a *application) apply_remote_state(updated config.Settings, restoreSpeech bool) { - base := a.effective_settings() +func (a *application) applyRemoteState(updated config.Settings, restoreSpeech bool) { + base := a.effectiveSettings() speechChanged := updated.Presentation.Speech.Enabled != !a.muted restored := restoreSpeech && updated.Presentation.Speech.Enabled && a.temporarySilence if restored { a.temporarySilence = false } if speechChanged { - a.muted = a.voice.Toggle_mute() + a.muted = a.voice.ToggleMute() } a.settings.live = updated - a.configure_screen() - if speech_parameters(base) != speech_parameters(updated) { - a.voice.Configure(speech_parameters(updated)) + a.configureScreen() + if speechParameters(base) != speechParameters(updated) { + a.voice.Configure(speechParameters(updated)) } a.voice.punctuationLevel = updated.Reading.PunctuationLevel if base.Presentation.Sound.Volume != updated.Presentation.Sound.Volume && a.cues != nil { - a.cues.Set_volume(updated.Presentation.Sound.Volume) + a.cues.SetVolume(updated.Presentation.Sound.Volume) } a.engine.Configure(a.settings.live.Reading.Automatic, a.settings.live.Reading.CursorEcho) - a.engine.Configure_progress(a.settings.live.Presentation.Progress.Enabled) + a.engine.ConfigureProgress(a.settings.live.Presentation.Progress.Enabled) if !a.settings.live.Presentation.Sound.Enabled && a.cues != nil { - a.cues.Clear_progress() - a.engine.Reset_progress() + a.cues.ClearProgress() + a.engine.ResetProgress() } - a.engine.Configure_echo(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) - a.engine.Configure_tracking(a.settings.live.Reading.Mode) + a.engine.ConfigureEcho(a.settings.live.Keyboard.CharacterEcho, a.settings.live.Keyboard.WordEcho, a.settings.live.Keyboard.EchoOnCapsLock) + a.engine.ConfigureTracking(a.settings.live.Reading.Mode) if base.Reading.Indentation != updated.Reading.Indentation { - a.engine.Configure_indentation(updated.Reading.Indentation) + a.engine.ConfigureIndentation(updated.Reading.Indentation) } if base.Reading.Attributes != updated.Reading.Attributes || base.Reading.AttributeFormat != updated.Reading.AttributeFormat { - a.engine.Configure_attributes(updated.Reading.Attributes, updated.Reading.AttributeFormat) + a.engine.ConfigureAttributes(updated.Reading.Attributes, updated.Reading.AttributeFormat) } if speechChanged || restored { - a.present_speech_state() + a.presentSpeechState() } } diff --git a/internal/app/runtime_settings_test.go b/internal/app/runtime_settings_test.go index 00cbb983..c6526a75 100644 --- a/internal/app/runtime_settings_test.go +++ b/internal/app/runtime_settings_test.go @@ -26,7 +26,7 @@ func TestMenuRemoteAndQuickSavePreserveNextLaunchChoices(t *testing.T) { source := &fakeSource{snapshot: screen.Snapshot{Terminal: 1, Active: true, Rows: 1, Cols: 5, Cells: []rune("alpha")}} voice := &fakeVoice{} keys := &fakeKeys{poll: func(bool, func(input.Decision)) error { return nil }} - a, err := new_application(ctx, source, keys, voice, RunOptions{Settings: base, ConfigPath: path}) + a, err := newApplication(ctx, source, keys, voice, RunOptions{Settings: base, ConfigPath: path}) if err != nil { t.Fatal(err) } @@ -45,7 +45,7 @@ func TestMenuRemoteAndQuickSavePreserveNextLaunchChoices(t *testing.T) { if err := config.Save(path, menuSaved); err != nil { t.Fatal(err) } - a.apply_saved_settings(menuSaved, false) + a.applySavedSettings(menuSaved, false) if a.settings.live.Keyboard.Layout != base.Keyboard.Layout || a.settings.live.Presentation.Speech.Module != base.Presentation.Speech.Module || a.settings.live.Review != base.Review || a.settings.live.Presentation.Sound != base.Presentation.Sound { t.Fatal("next-launch choices changed the running configuration") } @@ -53,7 +53,7 @@ func TestMenuRemoteAndQuickSavePreserveNextLaunchChoices(t *testing.T) { t.Fatal("menu speech adjustment did not apply live", voice.parameters) } for _, id := range []command.ID{command.Mute, command.AutoRead, command.ToggleAttributes} { - a.handle_input(input.Decision{Command: id}) + a.handleInput(input.Decision{Command: id}) } for _, request := range []struct { text string @@ -63,16 +63,16 @@ func TestMenuRemoteAndQuickSavePreserveNextLaunchChoices(t *testing.T) { {"SETTING SET keyboard#word_echo=True", ""}, } { replies := make(chan string, 1) - a.remote_request(control.Request{UID: 0, Text: request.text, Reply: replies}) + a.remoteRequest(control.Request{UID: 0, Text: request.text, Reply: replies}) if reply := <-replies; !strings.HasPrefix(reply, request.want) || request.want == "" && reply != "" { t.Fatal("unexpected remote response", reply) } - if !voice.muted || a.engine.Automatic_reading() { + if !voice.muted || a.engine.AutomaticReading() { t.Fatal("remote assignment changed unrelated session state") } } for _, id := range append(quickToRate, command.NextQuickValue, command.SaveSettings, command.Quit) { - a.handle_input(input.Decision{Command: id}) + a.handleInput(input.Decision{Command: id}) } if err := a.loop(nil); err != nil || ctx.Err() != nil { t.Fatal("save and quit failed", err, ctx.Err()) @@ -91,12 +91,12 @@ func TestMenuRemoteAndQuickSavePreserveNextLaunchChoices(t *testing.T) { t.Fatal("session overrides leaked into the save", saved) } freshVoice := &fakeVoice{} - fresh, err := new_application(ctx, source, &fakeKeys{}, freshVoice, RunOptions{Settings: saved}) + fresh, err := newApplication(ctx, source, &fakeKeys{}, freshVoice, RunOptions{Settings: saved}) if err != nil { t.Fatal(err) } defer fresh.ui.close() - if err := fresh.read_screen(); err != nil || !slices.Contains(freshVoice.messages, "alpha") { + if err := fresh.readScreen(); err != nil || !slices.Contains(freshVoice.messages, "alpha") { t.Fatal("saved defaults did not restore startup reading", err, freshVoice.messages) } } @@ -104,12 +104,12 @@ func TestMenuRemoteAndQuickSavePreserveNextLaunchChoices(t *testing.T) { func TestRemoteCannotEnableSpeechWithoutStartupConnection(t *testing.T) { base := config.Defaults() base.Presentation.Speech.Enabled = false - a, err := new_application(context.Background(), &fakeSource{}, &fakeKeys{}, disabledVoice{}, RunOptions{Settings: base}) + a, err := newApplication(context.Background(), &fakeSource{}, &fakeKeys{}, disabledVoice{}, RunOptions{Settings: base}) if err != nil { t.Fatal(err) } defer a.ui.close() - response := a.apply_remote_settings("SET speech#enabled=True;keyboard#word_echo=True") + response := a.applyRemoteSettings("SET speech#enabled=True;keyboard#word_echo=True") if response != "Speech was disabled at startup; enable it in settings and relaunch" { t.Fatal(response) } diff --git a/internal/app/screen_policy_test.go b/internal/app/screen_policy_test.go index 2973f4bb..b2605965 100644 --- a/internal/app/screen_policy_test.go +++ b/internal/app/screen_policy_test.go @@ -31,15 +31,15 @@ func TestLoginPromptStartupAndDelayedActivation(t *testing.T) { modes = append(modes, active) return nil }} - a, err := new_application(context.Background(), source, keys, voice, RunOptions{Settings: config.Defaults()}) + a, err := newApplication(context.Background(), source, keys, voice, RunOptions{Settings: config.Defaults()}) if err != nil { t.Fatal(err) } t.Cleanup(a.ui.close) - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } - if err := a.poll_input(true); err != nil { + if err := a.pollInput(true); err != nil { t.Fatal(err) } if terminal == 2 { @@ -47,7 +47,7 @@ func TestLoginPromptStartupAndDelayedActivation(t *testing.T) { t.Fatal("unused console was captured or read", a.lastActive, voice.messages) } source.snapshot = prompt - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { t.Fatal(err) } } @@ -67,7 +67,7 @@ type policySource struct { ignoredVTs []int } -func (s *policySource) Configure_ignored_vts(numbers []int) { +func (s *policySource) ConfigureIgnoredVts(numbers []int) { s.ignoredVTs = append([]int(nil), numbers...) } @@ -92,18 +92,18 @@ func TestRemoteIgnoredVTListsAreAtomic(t *testing.T) { "SET screen#ignore_screen=7, 8,10;speech#enabled=False", "SET screen#ignore_screen=7, 8,10,speech#enabled=False", } { - updated, err := remote_settings(base, text) + updated, err := remoteSettings(base, text) if err != nil || !reflect.DeepEqual(updated.Screen.IgnoredVTs, []int{7, 8, 10}) || updated.Presentation.Speech.Enabled { t.Fatal("lost list or following assignment", updated, err) } } for _, value := range []string{"0", "64", "-1", "7,7", "7,", "7,,8", "tty7", "7;unknown#setting=True"} { - failed, err := remote_settings(base, "SET speech#enabled=False;screen#ignore_screen="+value) + failed, err := remoteSettings(base, "SET speech#enabled=False;screen#ignore_screen="+value) if err == nil || !reflect.DeepEqual(failed, base) || !reflect.DeepEqual(base.Screen.IgnoredVTs, []int{2, 3}) { t.Fatal("invalid list partially applied", value, failed, base, err) } } - updated, err := remote_settings(base, "SET screen#ignore_screen=") + updated, err := remoteSettings(base, "SET screen#ignore_screen=") if err != nil || len(updated.Screen.IgnoredVTs) != 0 { t.Fatal("empty list did not clear policy", updated.Screen, err) } @@ -120,15 +120,15 @@ func TestIgnoredVTStartupRemoteReleaseRecoveryAndTerminalIsolation(t *testing.T) modes = append(modes, active) return nil }} - a, err := new_application(context.Background(), source, keys, voice, RunOptions{Settings: settings, TerminalMode: terminalMode}) + a, err := newApplication(context.Background(), source, keys, voice, RunOptions{Settings: settings, TerminalMode: terminalMode}) if err != nil { t.Fatal(err) } t.Cleanup(a.ui.close) - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } - if err := a.poll_input(true); err != nil { + if err := a.pollInput(true); err != nil { t.Fatal(err) } if a.lastActive != terminalMode || (!terminalMode && len(voice.messages) != 0) { @@ -137,7 +137,7 @@ func TestIgnoredVTStartupRemoteReleaseRecoveryAndTerminalIsolation(t *testing.T) request := func(uid int, text string) string { t.Helper() replies := make(chan string, 1) - a.remote_request(control.Request{UID: uid, Text: "SETTING " + text, Reply: replies}) + a.remoteRequest(control.Request{UID: uid, Text: "SETTING " + text, Reply: replies}) return <-replies } if reply := request(os.Geteuid()+1, "SET screen#ignore_screen="); reply == "" || !reflect.DeepEqual(a.settings.live.Screen, settings.Screen) { @@ -146,15 +146,15 @@ func TestIgnoredVTStartupRemoteReleaseRecoveryAndTerminalIsolation(t *testing.T) if reply := request(os.Geteuid(), "SET screen#ignore_screen="); reply != "" { t.Fatal(reply) } - if err := a.poll_input(true); err != nil || !a.lastActive { + if err := a.pollInput(true); err != nil || !a.lastActive { t.Fatal("did not recover after remote clear", err) } - a.ui.open_tutorial(nil, nil, nil) + a.ui.openTutorial(nil, nil, nil) interrupts := voice.interrupts if reply := request(os.Geteuid(), "SET screen#ignore_screen=2,7,8,10"); reply != "" { t.Fatal(reply) } - if err := a.poll_input(false); err != nil { + if err := a.pollInput(false); err != nil { t.Fatal(err) } if !terminalMode && (a.lastActive || a.ui.active || voice.interrupts <= interrupts || !reflect.DeepEqual(keys.captures, []bool{true, false})) { @@ -164,7 +164,7 @@ func TestIgnoredVTStartupRemoteReleaseRecoveryAndTerminalIsolation(t *testing.T) t.Fatal("console policy affected X11 session") } source.snapshot.Terminal = 3 - if err := a.poll_input(false); err != nil || !a.lastActive { + if err := a.pollInput(false); err != nil || !a.lastActive { t.Fatal("allowed VT did not resume", err) } if !terminalMode && !reflect.DeepEqual(modes, []bool{false, true, false, true}) { @@ -173,8 +173,8 @@ func TestIgnoredVTStartupRemoteReleaseRecoveryAndTerminalIsolation(t *testing.T) // Applying a saved draft uses the same policy; quick-save must retain it. saved := settings saved.Screen.IgnoredVTs = []int{3} - a.apply_saved_settings(saved, false) - if err := a.poll_input(false); err != nil || a.lastActive != terminalMode { + a.applySavedSettings(saved, false) + if err := a.pollInput(false); err != nil || a.lastActive != terminalMode { t.Fatal("saved policy was not applied", err, a.lastActive) } if !reflect.DeepEqual(a.settings.saveDraft.Screen.IgnoredVTs, []int{3}) { diff --git a/internal/app/screen_updates.go b/internal/app/screen_updates.go index 4c3e9c1e..94a80a0d 100644 --- a/internal/app/screen_updates.go +++ b/internal/app/screen_updates.go @@ -27,14 +27,14 @@ import ( "git.stormux.org/storm/fenrir/internal/spellcheck" ) -func (a *application) read_screen() error { +func (a *application) readScreen() error { started := time.Now() snapshot, err := a.source.Read() diagnostic.Timing("screen capture", started) if err != nil { return err } - a.share_notification_history(snapshot.Terminal, snapshot.Active) + a.shareNotificationHistory(snapshot.Terminal, snapshot.Active) if a.lastTerminal == 0 { if snapshot.Active { a.present(i18n.T("Start Fenrir"), presentation.Ready) @@ -48,19 +48,19 @@ func (a *application) read_screen() error { } if a.cues != nil && (sessionChanged || a.lastTerminal != 0 && (snapshot.Generation != a.lastGeneration || snapshot.Rows != a.lastRows || snapshot.Cols != a.lastCols)) { - a.cues.Clear_progress() + a.cues.ClearProgress() } if sessionChanged { a.voice.Interrupt() a.ui.close() - a.clipboards.session_changed(snapshot.Terminal) + a.clipboards.sessionChanged(snapshot.Terminal) if a.options.ScriptRunner != nil { a.scriptGeneration = a.options.ScriptRunner.Cancel() } } a.clipboards.terminal = snapshot.Terminal a.lastSnapshot = snapshot - frame, ready := a.observe_override(snapshot) + frame, ready := a.observeOverride(snapshot) if !ready { a.lastTerminal, a.lastActive = snapshot.Terminal, snapshot.Active a.lastGeneration, a.lastRows, a.lastCols = snapshot.Generation, snapshot.Rows, snapshot.Cols @@ -68,18 +68,18 @@ func (a *application) read_screen() error { return nil } updated := time.Now() - output := a.engine.Update_application(snapshot, frame) + output := a.engine.UpdateApplication(snapshot, frame) if a.options.Spellcheck != nil && a.settings.live.Reading.Spellcheck && !a.ui.active && !a.muted && !a.temporarySilence { - for _, word := range a.engine.Completed_words() { + for _, word := range a.engine.CompletedWords() { a.options.Spellcheck.Submit(spellcheck.Request{Operation: spellcheck.Automatic, Word: word, Generation: a.spellSession, Revision: a.spellFeedback}) } } - restoreLine := a.prompts.Observe(a.engine.Automatic_snapshot()) + restoreLine := a.prompts.Observe(a.engine.AutomaticSnapshot()) restored := a.temporarySilence && !a.muted && !a.ui.active && restoreLine != "" if restored { a.temporarySilence = false a.present(i18n.T("Speech restored"), presentation.SpeechOn) - if a.engine.Automatic_reading() { + if a.engine.AutomaticReading() { a.present(restoreLine, "") } } @@ -99,11 +99,11 @@ func (a *application) read_screen() error { if !a.ui.active && !restored { for _, message := range output { if message.Attributes != nil { - a.present_attributes(message) + a.presentAttributes(message) } else if message.Indentation != nil { - a.present_indentation(message) + a.presentIndentation(message) } else if message.Character != nil && !a.temporarySilence { - a.voice.say_character(*message.Character) + a.voice.sayCharacter(*message.Character) } else { a.present(message.Text, message.Cue) } @@ -112,32 +112,32 @@ func (a *application) read_screen() error { a.lastTerminal, a.lastActive = snapshot.Terminal, snapshot.Active a.lastGeneration, a.lastRows, a.lastCols = snapshot.Generation, snapshot.Rows, snapshot.Cols a.lastNumLock = snapshot.NumLock - a.play_progress() + a.playProgress() return nil } -func (a *application) poll_input(inputReady bool) error { +func (a *application) pollInput(inputReady bool) error { tty, active, numLock, err := a.source.State() if err != nil { return err } changed := tty != a.lastTerminal || active != a.lastActive if changed { - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { return err } active, numLock = a.lastActive, a.lastNumLock } if inputReady || changed { - if err := a.keyboards.Poll(active, numLock, a.handle_input); err != nil { + if err := a.keyboards.Poll(active, numLock, a.handleInput); err != nil { return err } } - a.apply_pending_modifiers() + a.applyPendingModifiers() return nil } -func (a *application) screen_event(err error) error { +func (a *application) screenEvent(err error) error { if err != nil { return fmt.Errorf("screen watcher failed: %w", err) } @@ -149,7 +149,7 @@ func (a *application) screen_event(err error) error { if err != nil { return fmt.Errorf("keyboard watcher failed: %w", err) } - if err := a.poll_input(true); err != nil { + if err := a.pollInput(true); err != nil { return err } default: @@ -158,11 +158,11 @@ func (a *application) screen_event(err error) error { return nil } previousTTY, previousText := a.lastTerminal, a.lastActive - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { return err } if previousTTY != a.lastTerminal || previousText != a.lastActive { - if err := a.keyboards.Poll(a.lastActive, a.lastNumLock, a.handle_input); err != nil { + if err := a.keyboards.Poll(a.lastActive, a.lastNumLock, a.handleInput); err != nil { return err } } diff --git a/internal/app/scripts.go b/internal/app/scripts.go index 597c3b90..7ffe62cc 100644 --- a/internal/app/scripts.go +++ b/internal/app/scripts.go @@ -33,10 +33,10 @@ import ( "git.stormux.org/storm/fenrir/internal/scripts" ) -// script_username supplies Python's current-user argument without changing +// scriptUsername supplies Python's current-user argument without changing // process credentials, HOME, cwd or any inherited environment variable. // Session lookup runs in a script worker, never in the input dispatcher. -func script_username(terminalMode bool, terminal int) string { +func scriptUsername(terminalMode bool, terminal int) string { if terminalMode { for _, name := range []string{os.Getenv("LOGNAME"), os.Getenv("USER")} { if name != "" { @@ -74,7 +74,7 @@ func script_username(terminalMode bool, terminal int) string { return "" // Python also leaves this empty when no session was found. } -func remote_authorized(uid, terminal int, terminalMode bool) bool { +func remoteAuthorized(uid, terminal int, terminalMode bool) bool { if uid == 0 || uid == os.Geteuid() { return true } @@ -89,7 +89,7 @@ func remote_authorized(uid, terminal int, terminalMode bool) bool { return ok && int(stat.Uid) == uid } -func (a *application) script_result(result scripts.Result) { +func (a *application) scriptResult(result scripts.Result) { if result.Generation != a.scriptGeneration || result.Terminal != a.lastTerminal || !a.lastActive { return } diff --git a/internal/app/scripts_test.go b/internal/app/scripts_test.go index 6884465b..a95ea7cd 100644 --- a/internal/app/scripts_test.go +++ b/internal/app/scripts_test.go @@ -41,7 +41,7 @@ func TestHungScriptDoesNotBlockReviewOrReaderShutdown(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() - runner := scripts.New_runner(ctx, scripts.Limits{Workers: 1, Queue: 1, OutputBytes: 1024}, nil) + runner := scripts.NewRunner(ctx, scripts.Limits{Workers: 1, Queue: 1, OutputBytes: 1024}, nil) defer runner.Close() script := scripts.Script{ID: "script:hang", Path: path} source := &fakeSource{snapshot: screen.Snapshot{Active: true, Terminal: 1, Rows: 1, Cols: 5, Cells: []rune("alpha")}} @@ -87,7 +87,7 @@ func TestScriptResultsUseMainLoopStderrThenStdout(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - runner := scripts.New_runner(ctx, scripts.Limits{Workers: 1, Queue: 1, OutputBytes: 1024}, nil) + runner := scripts.NewRunner(ctx, scripts.Limits{Workers: 1, Queue: 1, OutputBytes: 1024}, nil) defer runner.Close() script := scripts.Script{ID: "script:result", Path: path} source := &fakeSource{snapshot: screen.Snapshot{Active: true, Terminal: 1, Rows: 1, Cols: 5, Cells: []rune("alpha")}} @@ -118,11 +118,11 @@ func TestScriptResultsUseMainLoopStderrThenStdout(t *testing.T) { func TestRemoteSettingsAreAtomicAndUsePythonNames(t *testing.T) { base := config.Defaults() - updated, err := remote_settings(base, "set speech#enabled=False;speech#auto_read_incoming=False,keyboard#word_echo=True") + updated, err := remoteSettings(base, "set speech#enabled=False;speech#auto_read_incoming=False,keyboard#word_echo=True") if err != nil || updated.Presentation.Speech.Enabled || updated.Reading.Automatic || !updated.Keyboard.WordEcho { t.Fatal(updated, err) } - failed, err := remote_settings(base, "SET speech#enabled=False;unknown#setting=True") + failed, err := remoteSettings(base, "SET speech#enabled=False;unknown#setting=True") if err == nil || !reflect.DeepEqual(failed, base) { t.Fatal("partial settings applied", failed, err) } diff --git a/internal/app/shared_notifications_test.go b/internal/app/shared_notifications_test.go index 0ac0e467..58f6b026 100644 --- a/internal/app/shared_notifications_test.go +++ b/internal/app/shared_notifications_test.go @@ -11,15 +11,15 @@ import ( "time" ) -func shared_notification_application(t *testing.T, namespace string) (*application, *fakeVoice, *fakeSounds) { +func sharedNotificationApplication(t *testing.T, namespace string) (*application, *fakeVoice, *fakeSounds) { t.Helper() - a, voice := persistence_application(t, true) + a, voice := persistenceApplication(t, true) voice.messages = nil sounds := &fakeSounds{} a.cues = sounds a.options.SharedNotifications = true a.options.NotificationNamespace = namespace - a.share_notification_history(1, true) + a.shareNotificationHistory(1, true) t.Cleanup(func() { a.notificationHistory.Close() a.notificationClosers.Wait() @@ -27,12 +27,12 @@ func shared_notification_application(t *testing.T, namespace string) (*applicati return a, voice, sounds } -func wait_shared_notifications(t *testing.T, a *application, count int) { +func waitSharedNotifications(t *testing.T, a *application, count int) { t.Helper() deadline := time.NewTimer(3 * time.Second) defer deadline.Stop() for { - a.refresh_notification_history() + a.refreshNotificationHistory() if len(a.notifications) == count { return } @@ -50,14 +50,14 @@ func TestSharedNotificationHistoryNeverSpeaksOrPlaysOnOtherReaders(t *testing.T) var voices []*fakeVoice var sounds []*fakeSounds for range 4 { - a, voice, cues := shared_notification_application(t, namespace) + a, voice, cues := sharedNotificationApplication(t, namespace) readers, voices, sounds = append(readers, a), append(voices, voice), append(sounds, cues) } - if response := runtime_request(readers[0], "command notify First target"); response != "" { + if response := runtimeRequest(readers[0], "command notify First target"); response != "" { t.Fatal(response) } for index, a := range readers { - wait_shared_notifications(t, a, 1) + waitSharedNotifications(t, a, 1) wantSpeech, wantCues := 0, 0 if index == 0 { wantSpeech, wantCues = 1, 1 @@ -66,9 +66,9 @@ func TestSharedNotificationHistoryNeverSpeaksOrPlaysOnOtherReaders(t *testing.T) t.Fatal("silent history update triggered speech or sound", index, voices[index].messages, sounds[index].cues) } } - runtime_request(readers[1], "command notify Second target") + runtimeRequest(readers[1], "command notify Second target") for index, a := range readers { - wait_shared_notifications(t, a, 2) + waitSharedNotifications(t, a, 2) if !reflect.DeepEqual(a.notifications, readers[0].notifications) { t.Fatal("readers disagree about history", index) } @@ -82,22 +82,22 @@ func TestSharedNotificationHistoryNeverSpeaksOrPlaysOnOtherReaders(t *testing.T) } } // History recall is an explicit user action and still belongs to that reader. - readers[2].last_notification() + readers[2].lastNotification() if !reflect.DeepEqual(voices[2].messages, []string{"Second target"}) || len(sounds[2].cues) != 0 { t.Fatal("history recall was missing or replayed the cue") } readers[2].muted, voices[2].muted = true, true - runtime_request(readers[2], "command notify Muted target") + runtimeRequest(readers[2], "command notify Muted target") readers[3].temporarySilence = true - runtime_request(readers[3], "command notify Silenced target") + runtimeRequest(readers[3], "command notify Silenced target") for index, a := range readers { - wait_shared_notifications(t, a, 4) + waitSharedNotifications(t, a, 4) if index >= 2 && len(sounds[index].cues) != 0 { t.Fatal("muted or silenced target replayed the cue") } } - joining, voice, cues := shared_notification_application(t, namespace) - wait_shared_notifications(t, joining, 4) + joining, voice, cues := sharedNotificationApplication(t, namespace) + waitSharedNotifications(t, joining, 4) if len(voice.messages) != 0 || len(cues.cues) != 0 || !reflect.DeepEqual(joining.notifications, readers[0].notifications) { t.Fatal("joining reader announced existing history or loaded different messages") } @@ -105,22 +105,22 @@ func TestSharedNotificationHistoryNeverSpeaksOrPlaysOnOtherReaders(t *testing.T) func TestNotificationUserSwitchClearsHistoryAndClosesOldDialog(t *testing.T) { namespace := fmt.Sprintf(".app.%d.%d", os.Getpid(), time.Now().UnixNano()) - a, voice, _ := shared_notification_application(t, namespace) - peer, _, _ := shared_notification_application(t, namespace) + a, voice, _ := sharedNotificationApplication(t, namespace) + peer, _, _ := sharedNotificationApplication(t, namespace) a.notify("Original account", time.Now()) - wait_shared_notifications(t, peer, 1) - a.open_notifications() + waitSharedNotifications(t, peer, 1) + a.openNotifications() if !a.ui.active { t.Fatal("notification dialog did not open") } - a.select_notification_user(os.Geteuid() + 1) + a.selectNotificationUser(os.Geteuid() + 1) voice.messages = nil - a.refresh_notification_history() + a.refreshNotificationHistory() if len(a.notifications) != 0 || a.ui.active { t.Fatal("switching accounts exposed the previous history or dialog") } - a.select_notification_user(os.Geteuid()) - wait_shared_notifications(t, a, 1) + a.selectNotificationUser(os.Geteuid()) + waitSharedNotifications(t, a, 1) if len(voice.messages) != 0 { t.Fatal("restoring an account spoke its history", voice.messages) } diff --git a/internal/app/speech_preview.go b/internal/app/speech_preview.go index f873e9f3..d7bd5a3a 100644 --- a/internal/app/speech_preview.go +++ b/internal/app/speech_preview.go @@ -31,14 +31,14 @@ type speechPreviewResult struct { err error } -func previewable_selection(driverID string) bool { - driver, err := speech.Find_driver(driverID) +func previewableSelection(driverID string) bool { + driver, err := speech.FindDriver(driverID) return err == nil && !driver.Hardware && driver.Voices != nil } -// preview_menu_speech applies unsaved menu values to the running voice. +// previewMenuSpeech applies unsaved menu values to the running voice. // Hardware synthesizers keep their explicit voice test instead. -func (a *application) preview_menu_speech(selected config.Speech) { +func (a *application) previewMenuSpeech(selected config.Speech) { live := a.settings.live if !a.settings.speechAvailable || a.speechPending || a.saver.busy || selected.Driver != live.Presentation.Speech.Driver { return @@ -51,31 +51,31 @@ func (a *application) preview_menu_speech(selected config.Speech) { if !preview.active { preview.active = true preview.selection = live.Presentation.Speech - preview.parameters = speech_parameters(live) + preview.parameters = speechParameters(live) } if parameters != preview.parameters { preview.parameters = parameters a.voice.Configure(parameters) } - if previewable_selection(selected.Driver) { - a.preview_selection(selected) + if previewableSelection(selected.Driver) { + a.previewSelection(selected) } } -func (a *application) preview_selection(selected config.Speech) { +func (a *application) previewSelection(selected config.Speech) { preview := &a.preview if preview.busy { preview.queued = &selected return } - if same_speech_selection(selected, preview.selection) { + if sameSpeechSelection(selected, preview.selection) { return } preview.busy = true go func() { prepared, err := a.prepareSpeech(selected) if err == nil { - err = a.replace_speech(prepared) + err = a.replaceSpeech(prepared) } select { case preview.results <- speechPreviewResult{selected: selected, err: err}: @@ -84,7 +84,7 @@ func (a *application) preview_selection(selected config.Speech) { }() } -func (a *application) speech_preview_result(result speechPreviewResult) { +func (a *application) speechPreviewResult(result speechPreviewResult) { preview := &a.preview preview.busy = false if result.err == nil { @@ -94,7 +94,7 @@ func (a *application) speech_preview_result(result speechPreviewResult) { } if queued := preview.queued; queued != nil { preview.queued = nil - a.preview_selection(*queued) + a.previewSelection(*queued) } if preview.busy { return @@ -103,8 +103,8 @@ func (a *application) speech_preview_result(result speechPreviewResult) { preview.announce = "" a.voice.Say(announce) } - if same_speech_selection(preview.selection, a.settings.live.Presentation.Speech) && - preview.parameters == speech_parameters(a.settings.live) { + if sameSpeechSelection(preview.selection, a.settings.live.Presentation.Speech) && + preview.parameters == speechParameters(a.settings.live) { preview.active = false } idle := preview.idle @@ -114,28 +114,28 @@ func (a *application) speech_preview_result(result speechPreviewResult) { } } -// restore_speech_preview returns the running voice to the live settings. -func (a *application) restore_speech_preview() { +// restoreSpeechPreview returns the running voice to the live settings. +func (a *application) restoreSpeechPreview() { preview := &a.preview if !preview.active { return } live := a.settings.live - if parameters := speech_parameters(live); parameters != preview.parameters { + if parameters := speechParameters(live); parameters != preview.parameters { preview.parameters = parameters a.voice.Configure(parameters) } - if previewable_selection(preview.selection.Driver) { - a.preview_selection(live.Presentation.Speech) + if previewableSelection(preview.selection.Driver) { + a.previewSelection(live.Presentation.Speech) } - if !preview.busy && same_speech_selection(preview.selection, live.Presentation.Speech) { + if !preview.busy && sameSpeechSelection(preview.selection, live.Presentation.Speech) { preview.active, preview.queued = false, nil } } -// after_speech_preview runs work once no preview candidate is in flight, so a +// afterSpeechPreview runs work once no preview candidate is in flight, so a // save's own transport replacement cannot be overtaken by an older preview. -func (a *application) after_speech_preview(run func()) bool { +func (a *application) afterSpeechPreview(run func()) bool { if !a.preview.busy { return false } @@ -143,9 +143,9 @@ func (a *application) after_speech_preview(run func()) bool { return true } -// defer_preview_speech keeps only the newest menu announcement until the +// deferPreviewSpeech keeps only the newest menu announcement until the // candidate connection is speaking. -func (a *application) defer_preview_speech(text string) bool { +func (a *application) deferPreviewSpeech(text string) bool { if !a.preview.busy { return false } diff --git a/internal/app/speech_preview_test.go b/internal/app/speech_preview_test.go index 8738dcdd..93c7576e 100644 --- a/internal/app/speech_preview_test.go +++ b/internal/app/speech_preview_test.go @@ -12,9 +12,9 @@ import ( "git.stormux.org/storm/fenrir/internal/speech" ) -func preview_application(t *testing.T) (*application, *selectingVoice, string, chan config.Speech) { +func previewApplication(t *testing.T) (*application, *selectingVoice, string, chan config.Speech) { t.Helper() - a, voice, path := selection_application(t, true) + a, voice, path := selectionApplication(t, true) prepared := make(chan config.Speech, 8) a.prepareSpeech = func(selected config.Speech) (speech.Transport, error) { prepared <- selected @@ -23,20 +23,20 @@ func preview_application(t *testing.T) (*application, *selectingVoice, string, c return a, voice, path, prepared } -func finish_preview(t *testing.T, a *application, voice *selectingVoice) { +func finishPreview(t *testing.T, a *application, voice *selectingVoice) { t.Helper() select { case result := <-a.preview.results: if result.err == nil { (<-voice.replaced).Close() } - a.speech_preview_result(result) + a.speechPreviewResult(result) case <-time.After(time.Second): t.Fatal("speech preview stalled") } } -func last_parameters(t *testing.T, voice *selectingVoice) speech.Parameters { +func lastParameters(t *testing.T, voice *selectingVoice) speech.Parameters { t.Helper() if len(voice.parameters) == 0 { t.Fatal("no speech parameters were configured") @@ -45,12 +45,12 @@ func last_parameters(t *testing.T, voice *selectingVoice) speech.Parameters { } func TestMenuSpeechPreviewAppliesUnsavedVoiceAndRestoresOnClose(t *testing.T) { - a, voice, _, prepared := preview_application(t) + a, voice, _, prepared := previewApplication(t) live := a.settings.live.Presentation.Speech selected := live selected.Module, selected.Rate = "fixture", 40 - a.preview_menu_speech(selected) - if got := last_parameters(t, voice); got.Rate != 40 { + a.previewMenuSpeech(selected) + if got := lastParameters(t, voice); got.Rate != 40 { t.Fatalf("rate preview = %+v", got) } if got := <-prepared; got.Module != "fixture" { @@ -59,52 +59,52 @@ func TestMenuSpeechPreviewAppliesUnsavedVoiceAndRestoresOnClose(t *testing.T) { // A newer form value waits for the candidate in flight. newer := selected newer.Module = "second" - a.preview_menu_speech(newer) - finish_preview(t, a, voice) + a.previewMenuSpeech(newer) + finishPreview(t, a, voice) if got := <-prepared; got.Module != "second" { t.Fatalf("queued module = %q", got.Module) } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if a.preview.selection.Module != "second" || a.settings.live.Presentation.Speech.Module != live.Module { t.Fatal("preview changed live settings", a.preview.selection, a.settings.live.Presentation.Speech) } - a.restore_speech_preview() - if got := last_parameters(t, voice); got != speech_parameters(a.settings.live) { + a.restoreSpeechPreview() + if got := lastParameters(t, voice); got != speechParameters(a.settings.live) { t.Fatalf("restored parameters = %+v", got) } if got := <-prepared; got.Module != live.Module { t.Fatalf("restored module = %q", got.Module) } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if a.preview.active { t.Fatal("preview still active after restore") } } func TestMenuSaveWaitsForPreviewAndKeepsPreviewedVoice(t *testing.T) { - a, voice, path, prepared := preview_application(t) + a, voice, path, prepared := previewApplication(t) selected := a.settings.live.Presentation.Speech selected.Module = "fixture" - a.preview_menu_speech(selected) + a.previewMenuSpeech(selected) <-prepared - doc, err := config.Open_document(path, a.settings.live) + doc, err := config.OpenDocument(path, a.settings.live) if err != nil { t.Fatal(err) } draft := doc.Settings draft.Presentation.Speech.Module = "fixture" var outcome error - if !a.save_menu_settings(doc, draft, func(err error) { outcome = err }) { + if !a.saveMenuSettings(doc, draft, func(err error) { outcome = err }) { t.Fatal("save not admitted") } if a.saver.busy { t.Fatal("save overtook the preview in flight") } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if !a.saver.busy { t.Fatal("deferred save did not start") } - finish_persistence(t, a, false) + finishPersistence(t, a, false) if outcome != nil || a.settings.live.Presentation.Speech.Module != "fixture" || a.preview.active { t.Fatal("save did not commit the previewed voice", outcome, a.settings.live.Presentation.Speech, a.preview) } @@ -116,10 +116,10 @@ func TestMenuSaveWaitsForPreviewAndKeepsPreviewedVoice(t *testing.T) { } func TestHardwareSelectionIsNotPreviewed(t *testing.T) { - a, voice, _, prepared := preview_application(t) + a, voice, _, prepared := previewApplication(t) selected := a.settings.live.Presentation.Speech selected.Driver, selected.Rate = "dectalk", 30 - a.preview_menu_speech(selected) + a.previewMenuSpeech(selected) if len(voice.parameters) != 0 || a.preview.active { t.Fatal("a different driver changed the running voice") } @@ -131,11 +131,11 @@ func TestHardwareSelectionIsNotPreviewed(t *testing.T) { } func TestMenuRateChangeIsHeardAndEscapeRestoresIt(t *testing.T) { - a, voice := persistence_application(t, true) - live := speech_parameters(a.settings.live) - a.open_settings() - receive_ui(t, a.ui) - tab_to_control(t, a.ui, "speech.rate") + a, voice := persistenceApplication(t, true) + live := speechParameters(a.settings.live) + a.openSettings() + receiveUi(t, a.ui) + tabToControl(t, a.ui, "speech.rate") a.ui.handle(interaction.Key{Name: "right"}) if len(voice.parameters) == 0 || voice.parameters[len(voice.parameters)-1].Rate != live.Rate+1 { t.Fatal("menu rate change was not previewed", voice.parameters, live) @@ -147,10 +147,10 @@ func TestMenuRateChangeIsHeardAndEscapeRestoresIt(t *testing.T) { } func TestMenuAnnouncementWaitsForPreviewedVoice(t *testing.T) { - a, voice, _, prepared := preview_application(t) + a, voice, _, prepared := previewApplication(t) selected := a.settings.live.Presentation.Speech selected.Module = "fixture" - a.preview_menu_speech(selected) + a.previewMenuSpeech(selected) <-prepared a.ui.say("old announcement") a.ui.say("Speech Dispatcher module combo box fixture") @@ -159,7 +159,7 @@ func TestMenuAnnouncementWaitsForPreviewedVoice(t *testing.T) { t.Fatal("announcement reached the connection being replaced") } } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if got := voice.messages[len(voice.messages)-1]; got != "Speech Dispatcher module combo box fixture" { t.Fatal("announcement not spoken with the new voice", voice.messages) } @@ -175,15 +175,15 @@ func TestMenuAnnouncementWaitsForPreviewedVoice(t *testing.T) { } func TestSpeechChangeWaitsForClosingPreview(t *testing.T) { - a, voice, _, prepared := preview_application(t) + a, voice, _, prepared := previewApplication(t) selected := a.settings.live.Presentation.Speech selected.Module = "preview" - a.preview_menu_speech(selected) + a.previewMenuSpeech(selected) <-prepared - a.restore_speech_preview() + a.restoreSpeechPreview() next := selected next.Module = "requested" - a.change_speech(next, func(err error) { + a.changeSpeech(next, func(err error) { if err != nil { t.Error(err) } @@ -201,40 +201,40 @@ func TestSpeechChangeWaitsForClosingPreview(t *testing.T) { t.Fatal("selection completed before the closing preview") default: } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if got := <-prepared; got.Module != a.settings.live.Presentation.Speech.Module { t.Fatal("preview did not restore first", got) } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if got := <-prepared; got.Module != "requested" { t.Fatal("requested selection was not last", got) } - finish_selection(t, a) + finishSelection(t, a) } func TestOverrideRestorationWaitsForMenuPreview(t *testing.T) { - a, voice, _, prepared := preview_application(t) - override_read(t, a, override_screen(1, "ninjam")) - a.select_override("ninjam") - override_read(t, a, override_screen(1, "ninjam")) + a, voice, _, prepared := previewApplication(t) + overrideRead(t, a, overrideScreen(1, "ninjam")) + a.selectOverride("ninjam") + overrideRead(t, a, overrideScreen(1, "ninjam")) current := a.overrideCurrent if current == nil { t.Fatal("application override did not activate") } selected := a.settings.live.Presentation.Speech selected.Module = "preview" - a.preview_menu_speech(selected) + a.previewMenuSpeech(selected) <-prepared a.ui.active = true - a.ui.onClosed = a.restore_speech_preview + a.ui.onClosed = a.restoreSpeechPreview completed := false - if a.restore_override(func() { completed = true }) || completed || a.overrideCurrent != current { + if a.restoreOverride(func() { completed = true }) || completed || a.overrideCurrent != current { t.Fatal("application context changed before its preview restored") } - finish_preview(t, a, voice) + finishPreview(t, a, voice) <-prepared - finish_preview(t, a, voice) - if !a.restore_override(func() { completed = true }) || !completed || a.overrideCurrent != nil { + finishPreview(t, a, voice) + if !a.restoreOverride(func() { completed = true }) || !completed || a.overrideCurrent != nil { t.Fatal("application context did not restore after its preview") } } diff --git a/internal/app/speech_selection.go b/internal/app/speech_selection.go index 0f07f8f4..af77a0d1 100644 --- a/internal/app/speech_selection.go +++ b/internal/app/speech_selection.go @@ -19,26 +19,26 @@ type speechChangeResult struct { done func(error) } -func same_speech_selection(a, b config.Speech) bool { +func sameSpeechSelection(a, b config.Speech) bool { return a.Driver == b.Driver && a.HardwareDevice == b.HardwareDevice && a.HardwareBaudRate == b.HardwareBaudRate && a.Module == b.Module && a.Language == b.Language && a.Voice == b.Voice } -func copy_speech_selection(target *config.Speech, source config.Speech) { +func copySpeechSelection(target *config.Speech, source config.Speech) { target.Driver = source.Driver target.HardwareDevice = source.HardwareDevice target.HardwareBaudRate = source.HardwareBaudRate target.Module, target.Language, target.Voice = source.Module, source.Language, source.Voice } -func prepare_speech(selected config.Speech) (speech.Transport, error) { - return speech.Prepare(selected.Driver, speech_options(selected)) +func prepareSpeech(selected config.Speech) (speech.Transport, error) { + return speech.Prepare(selected.Driver, speechOptions(selected)) } -func speech_options(selected config.Speech) speech.Options { +func speechOptions(selected config.Speech) speech.Options { return speech.Options{Rate: selected.Rate, Pitch: &selected.Pitch, Volume: &selected.Volume, Module: selected.Module, Language: selected.Language, Voice: selected.Voice, Hardware: speech.HardwareOptions{Device: selected.HardwareDevice, BaudRate: selected.HardwareBaudRate}} } -func (a *application) replace_speech(prepared speech.Transport) error { +func (a *application) replaceSpeech(prepared speech.Transport) error { if service, ok := a.voice.Speaker.(interface{ Replace(speech.Transport) error }); ok { return service.Replace(prepared) } @@ -48,7 +48,7 @@ func (a *application) replace_speech(prepared speech.Transport) error { // Only the result callback mutates reader state. Preparing a silent candidate // and committing it through the speech worker never blocks the input loop. -func (a *application) change_speech(selected config.Speech, done func(error)) { +func (a *application) changeSpeech(selected config.Speech, done func(error)) { if a.speechPending || a.saver.busy { done(fmt.Errorf("settings are busy")) return @@ -62,7 +62,7 @@ func (a *application) change_speech(selected config.Speech, done func(error)) { go func() { prepared, err := a.prepareSpeech(selected) if err == nil { - err = a.replace_speech(prepared) + err = a.replaceSpeech(prepared) } select { case a.speechResults <- speechChangeResult{err: err, done: done}: @@ -72,20 +72,20 @@ func (a *application) change_speech(selected config.Speech, done func(error)) { } // Closing a menu may still be restoring its old transport. Keep admission // while it drains so that restoration cannot overwrite this selection. - if !a.after_speech_preview(start) { + if !a.afterSpeechPreview(start) { start() } } -func speech_choice(source string) bool { +func speechChoice(source string) bool { return source == "speech-module" || source == "speech-language" || source == "speech-voice" } -func (a *application) speech_result(result speechChangeResult) { +func (a *application) speechResult(result speechChangeResult) { a.speechPending = false result.done(result.err) // Reapply numeric overrides made while the silent candidate was prepared. - a.voice.Configure(speech_parameters(a.settings.live)) + a.voice.Configure(speechParameters(a.settings.live)) } type savedSpeechError struct{ err error } @@ -94,24 +94,24 @@ func (e *savedSpeechError) Error() string { return "settings saved; speech selection was not applied: " + e.err.Error() } func (e *savedSpeechError) Unwrap() error { return e.err } -func settings_committed(err error) bool { +func settingsCommitted(err error) bool { var saved *savedSpeechError return err == nil || errors.As(err, &saved) } -func open_speech(ctx context.Context, selected config.Speech) (speech.Transport, config.Speech, error) { - options := speech_options(selected) +func openSpeech(ctx context.Context, selected config.Speech) (speech.Transport, config.Speech, error) { + options := speechOptions(selected) if selected.Module == "" && selected.Language == "" && selected.Voice == "" { - client, err := speech.Open_driver_context(ctx, selected.Driver, options) + client, err := speech.OpenDriverContext(ctx, selected.Driver, options) return client, selected, err } - client, err := speech.Prepare_context(ctx, selected.Driver, options) + client, err := speech.PrepareContext(ctx, selected.Driver, options) if err == nil { return client, selected, nil } slog.Warn("saved speech selection unavailable; using server default", "error", err, "at", time.Now()) selected.Module, selected.Language, selected.Voice = "", "", "" options.Module, options.Language, options.Voice = "", "", "" - client, err = speech.Open_driver_context(ctx, selected.Driver, options) + client, err = speech.OpenDriverContext(ctx, selected.Driver, options) return client, selected, err } diff --git a/internal/app/speech_selection_test.go b/internal/app/speech_selection_test.go index a0fc4bf4..a672edf5 100644 --- a/internal/app/speech_selection_test.go +++ b/internal/app/speech_selection_test.go @@ -25,7 +25,7 @@ type preparedVoice struct{ closed atomic.Bool } func (p *preparedVoice) Say(string) error { return nil } func (p *preparedVoice) Configure(speech.Parameters) error { return nil } -func (p *preparedVoice) Set_pitch(int) error { return nil } +func (p *preparedVoice) SetPitch(int) error { return nil } func (p *preparedVoice) Cancel() error { return nil } func (p *preparedVoice) Close() { p.closed.Store(true) } @@ -44,7 +44,7 @@ func (s *selectingVoice) Replace(candidate speech.Transport) error { return nil } -func selection_application(t *testing.T, terminal bool) (*application, *selectingVoice, string) { +func selectionApplication(t *testing.T, terminal bool) (*application, *selectingVoice, string) { t.Helper() path := filepath.Join(t.TempDir(), "settings.toml") base := config.Defaults() @@ -54,7 +54,7 @@ func selection_application(t *testing.T, terminal bool) (*application, *selectin voice := &selectingVoice{replaced: make(chan speech.Transport, 8)} ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - a, err := new_application(ctx, &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: base, ConfigPath: path, TerminalMode: terminal}) + a, err := newApplication(ctx, &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: base, ConfigPath: path, TerminalMode: terminal}) if err != nil { t.Fatal(err) } @@ -70,21 +70,21 @@ func selection_application(t *testing.T, terminal bool) (*application, *selectin }) return a, voice, path } -func finish_selection(t *testing.T, a *application) { +func finishSelection(t *testing.T, a *application) { t.Helper() select { case result := <-a.speechResults: - a.speech_result(result) + a.speechResult(result) case <-time.After(time.Second): t.Fatal("selection stalled") } } -func request_selection(t *testing.T, a *application, text string) string { +func requestSelection(t *testing.T, a *application, text string) string { t.Helper() reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid(), Text: "SETTING " + text, Reply: reply}) + a.remoteRequest(control.Request{UID: os.Geteuid(), Text: "SETTING " + text, Reply: reply}) if a.speechPending { - finish_selection(t, a) + finishSelection(t, a) } select { case result := <-reply: @@ -98,19 +98,19 @@ func request_selection(t *testing.T, a *application, text string) string { func TestRemoteVoiceChangesAreAtomicAndResetRestoresTransport(t *testing.T) { for _, terminal := range []bool{false, true} { t.Run(map[bool]string{false: "tty", true: "terminal"}[terminal], func(t *testing.T) { - a, voice, path := selection_application(t, terminal) - base := a.effective_settings() + a, voice, path := selectionApplication(t, terminal) + base := a.effectiveSettings() a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return nil, errors.New("fixture unavailable") } - result := request_selection(t, a, "SET speech#module=fixture;speech#voice=Missing;speech#rate=0.25;speech#enabled=False") - if !strings.Contains(result, "fixture unavailable") || !reflect.DeepEqual(a.effective_settings(), base) || !reflect.DeepEqual(a.settings.saveDraft, base) { - t.Fatal("failed selection partially applied", result, a.effective_settings()) + result := requestSelection(t, a, "SET speech#module=fixture;speech#voice=Missing;speech#rate=0.25;speech#enabled=False") + if !strings.Contains(result, "fixture unavailable") || !reflect.DeepEqual(a.effectiveSettings(), base) || !reflect.DeepEqual(a.settings.saveDraft, base) { + t.Fatal("failed selection partially applied", result, a.effectiveSettings()) } var prepared []config.Speech a.prepareSpeech = func(selected config.Speech) (speech.Transport, error) { prepared = append(prepared, selected) return &preparedVoice{}, nil } - result = request_selection(t, a, "SET speech#voice=Base Voice;speech#language=en-US;speech#module=fixture;speech#rate=0.25") + result = requestSelection(t, a, "SET speech#voice=Base Voice;speech#language=en-US;speech#module=fixture;speech#rate=0.25") if result != "" || a.settings.live.Presentation.Speech.Voice != "Base Voice" || prepared[0].Voice != "Base Voice" || prepared[0].Language != "en-US" || a.settings.live.Presentation.Speech.Rate != -50 { t.Fatal(result, prepared, a.settings.live) } @@ -118,13 +118,13 @@ func TestRemoteVoiceChangesAreAtomicAndResetRestoresTransport(t *testing.T) { if err != nil || saved.Presentation.Speech.Module != "" { t.Fatal("SET wrote the file", saved, err) } - if result = request_selection(t, a, "RESET"); result != "" || len(prepared) != 2 || prepared[1].Module != "" || !same_speech_selection(a.settings.live.Presentation.Speech, base.Presentation.Speech) { + if result = requestSelection(t, a, "RESET"); result != "" || len(prepared) != 2 || prepared[1].Module != "" || !sameSpeechSelection(a.settings.live.Presentation.Speech, base.Presentation.Speech) { t.Fatal("RESET did not replace transport", result, prepared, a.settings.live) } if a.speechPending { t.Fatal("selection admission not released") } - if len(voice.parameters) == 0 || voice.parameters[len(voice.parameters)-1] != speech_parameters(base) { + if len(voice.parameters) == 0 || voice.parameters[len(voice.parameters)-1] != speechParameters(base) { t.Fatal("RESET numeric parameters not restored", voice.parameters) } }) @@ -133,25 +133,25 @@ func TestRemoteVoiceChangesAreAtomicAndResetRestoresTransport(t *testing.T) { func TestHardwareOptionsReachStartupAndRemoteChangesStayAtomic(t *testing.T) { for _, terminal := range []bool{false, true} { - a, _, _ := selection_application(t, terminal) + a, _, _ := selectionApplication(t, terminal) selected := a.settings.live.Presentation.Speech selected.Driver, selected.HardwareDevice, selected.HardwareBaudRate = "dectalk", "/dev/fixture-synth", 19200 - options := speech_options(selected) + options := speechOptions(selected) if options.Hardware.Device != selected.HardwareDevice || options.Hardware.BaudRate != 19200 { t.Fatal(options) } a.settings.live.Presentation.Speech = selected a.settings.saveDraft.Presentation.Speech = selected a.settings.resetBase.Presentation.Speech = selected - before := a.effective_settings() - if result := request_selection(t, a, "SET speech#voice=Unsupported;speech#rate=0.25;speech#enabled=False"); result == "" || !reflect.DeepEqual(a.effective_settings(), before) || !reflect.DeepEqual(a.settings.saveDraft, before) { - t.Fatal("partial hardware assignment", result, a.effective_settings()) + before := a.effectiveSettings() + if result := requestSelection(t, a, "SET speech#voice=Unsupported;speech#rate=0.25;speech#enabled=False"); result == "" || !reflect.DeepEqual(a.effectiveSettings(), before) || !reflect.DeepEqual(a.settings.saveDraft, before) { + t.Fatal("partial hardware assignment", result, a.effectiveSettings()) } - if result := request_selection(t, a, "SET speech#rate=0.5;speech#pitch=0.25;speech#volume=1"); result != "" || speech_parameters(a.effective_settings()) != (speech.Parameters{Rate: 0, Pitch: -50, Volume: 100}) { - t.Fatal(result, a.effective_settings()) + if result := requestSelection(t, a, "SET speech#rate=0.5;speech#pitch=0.25;speech#volume=1"); result != "" || speechParameters(a.effectiveSettings()) != (speech.Parameters{Rate: 0, Pitch: -50, Volume: 100}) { + t.Fatal(result, a.effectiveSettings()) } - if result := request_selection(t, a, "RESET"); result != "" || a.effective_settings().Presentation.Speech != selected { - t.Fatal("hardware RESET", result, a.effective_settings()) + if result := requestSelection(t, a, "RESET"); result != "" || a.effectiveSettings().Presentation.Speech != selected { + t.Fatal("hardware RESET", result, a.effectiveSettings()) } } } @@ -159,12 +159,12 @@ func TestHardwareOptionsReachStartupAndRemoteChangesStayAtomic(t *testing.T) { func TestMenuSelectionFailurePreservesDiskAndCommittedSaveSurvivesClose(t *testing.T) { for _, failed := range []bool{true, false} { t.Run(map[bool]string{true: "failed", false: "success"}[failed], func(t *testing.T) { - a, _, path := selection_application(t, true) + a, _, path := selectionApplication(t, true) before, err := os.ReadFile(path) if err != nil { t.Fatal(err) } - doc, err := config.Open_document(path, a.settings.live) + doc, err := config.OpenDocument(path, a.settings.live) if err != nil { t.Fatal(err) } @@ -182,15 +182,15 @@ func TestMenuSelectionFailurePreservesDiskAndCommittedSaveSurvivesClose(t *testi return &preparedVoice{}, nil } var outcome error - if !a.save_menu_settings(doc, draft, func(err error) { outcome = err }) { + if !a.saveMenuSettings(doc, draft, func(err error) { outcome = err }) { t.Fatal("save not admitted") } <-started a.ui.close() - quick_select_rate(a.quick, &a.settings.live, a.voice) + quickSelectRate(a.quick, &a.settings.live, a.voice) a.quick.command(command.NextQuickValue, &a.settings.live, a.voice) close(release) - finish_persistence(t, a, failed) + finishPersistence(t, a, failed) after, err := os.ReadFile(path) if err != nil { t.Fatal(err) @@ -209,8 +209,8 @@ func TestMenuSelectionFailurePreservesDiskAndCommittedSaveSurvivesClose(t *testi } func TestFailedWriteClosesPreparedClientAndKeepsActiveSelection(t *testing.T) { - a, voice, path := selection_application(t, true) - doc, err := config.Open_document(path, a.settings.live) + a, voice, path := selectionApplication(t, true) + doc, err := config.OpenDocument(path, a.settings.live) if err != nil { t.Fatal(err) } @@ -222,18 +222,18 @@ func TestFailedWriteClosesPreparedClientAndKeepsActiveSelection(t *testing.T) { t.Fatal(err) } var outcome error - if !a.save_menu_settings(doc, draft, func(err error) { outcome = err }) { + if !a.saveMenuSettings(doc, draft, func(err error) { outcome = err }) { t.Fatal("not admitted") } - finish_persistence(t, a, true) + finishPersistence(t, a, true) if outcome == nil || !prepared.closed.Load() || len(voice.replaced) != 0 || a.settings.live.Presentation.Speech.Module != "" { t.Fatal("failed write replaced voice or leaked candidate", outcome) } } func TestSavedFileTruthSurvivesConnectionFailureAtCommit(t *testing.T) { - a, voice, path := selection_application(t, true) - doc, err := config.Open_document(path, a.settings.live) + a, voice, path := selectionApplication(t, true) + doc, err := config.OpenDocument(path, a.settings.live) if err != nil { t.Fatal(err) } @@ -242,18 +242,18 @@ func TestSavedFileTruthSurvivesConnectionFailureAtCommit(t *testing.T) { a.prepareSpeech = func(config.Speech) (speech.Transport, error) { return &preparedVoice{}, nil } voice.replacementError = errors.New("fixture connection lost") var outcome error - if !a.save_menu_settings(doc, draft, func(err error) { outcome = err }) { + if !a.saveMenuSettings(doc, draft, func(err error) { outcome = err }) { t.Fatal("not admitted") } - finish_persistence(t, a, true) + finishPersistence(t, a, true) saved, _, err := config.Load(path, nil) - if err != nil || saved.Presentation.Speech.Module != "fixture" || a.settings.resetBase.Presentation.Speech.Module != "fixture" || a.settings.saveDraft.Presentation.Speech.Module != "fixture" || a.settings.live.Presentation.Speech.Module != "" || !settings_committed(outcome) { + if err != nil || saved.Presentation.Speech.Module != "fixture" || a.settings.resetBase.Presentation.Speech.Module != "fixture" || a.settings.saveDraft.Presentation.Speech.Module != "fixture" || a.settings.live.Presentation.Speech.Module != "" || !settingsCommitted(outcome) { t.Fatal("disk truth lost after committed write", outcome, saved, a.settings) } } func TestQuickVoiceCancelSaveAndStaleFeedback(t *testing.T) { - a, voice, path := selection_application(t, true) + a, voice, path := selectionApplication(t, true) a.quick.discovery = preferences.Discovery{Catalog: speech.Catalog{Modules: []string{"fixture"}, Voices: map[string][]speech.Voice{ "fixture": {{Name: "Base Voice", Language: "en-US"}}, }}} @@ -266,13 +266,13 @@ func TestQuickVoiceCancelSaveAndStaleFeedback(t *testing.T) { a.spellSession++ before := len(voice.messages) close(release) - finish_selection(t, a) + finishSelection(t, a) if a.settings.live.Presentation.Speech.Module != "fixture" || !a.quick.selectionChanged || len(voice.messages) != before { t.Fatal("stale feedback or lost selection", voice.messages) } // Unsaved quick selection appears in the form; Cancel does not undo it. - a.open_settings() - receive_ui(t, a.ui) + a.openSettings() + receiveUi(t, a.ui) if got := a.ui.session.Values()["presentation.speech.module"]; got.Choices[got.Selected].ID != "fixture" { t.Fatal(got) } @@ -281,8 +281,8 @@ func TestQuickVoiceCancelSaveAndStaleFeedback(t *testing.T) { if err != nil || saved.Presentation.Speech.Module != "" { t.Fatal("Cancel saved quick voice", saved, err) } - a.save_settings() - finish_persistence(t, a, false) + a.saveSettings() + finishPersistence(t, a, false) saved, _, err = config.Load(path, nil) if err != nil || saved.Presentation.Speech.Module != "fixture" { t.Fatal("quick save lost module", saved, err) @@ -294,23 +294,23 @@ func TestQuickVoiceCancelSaveAndStaleFeedback(t *testing.T) { effective.Module = "" effective.Language = "" effective.Voice = "" - fresh, err := new_application(a.ctx, &fakeSource{}, &fakeKeys{}, &fakeVoice{}, RunOptions{Settings: original, EffectiveSpeech: &effective}) - if err != nil || fresh.settings.live.Presentation.Speech.Module != "" || fresh.settings_to_save().Presentation.Speech.Module != "missing" || fresh.settings.resetBase.Presentation.Speech.Module != "missing" { + fresh, err := newApplication(a.ctx, &fakeSource{}, &fakeKeys{}, &fakeVoice{}, RunOptions{Settings: original, EffectiveSpeech: &effective}) + if err != nil || fresh.settings.live.Presentation.Speech.Module != "" || fresh.settingsToSave().Presentation.Speech.Module != "missing" || fresh.settings.resetBase.Presentation.Speech.Module != "missing" { t.Fatal("startup recovery erased saved choice", err) } } func TestRemoteSelectionRetainsAdmittedTrackingIntent(t *testing.T) { - a, _, _ := selection_application(t, true) + a, _, _ := selectionApplication(t, true) started, release := make(chan struct{}), make(chan struct{}) a.prepareSpeech = func(config.Speech) (speech.Transport, error) { close(started); <-release; return &preparedVoice{}, nil } reply := make(chan string, 1) - a.remote_request(control.Request{UID: os.Geteuid(), Text: "SETTING SET speech#module=fixture;focus#cursor=True", Reply: reply}) + a.remoteRequest(control.Request{UID: os.Geteuid(), Text: "SETTING SET speech#module=fixture;focus#cursor=True", Reply: reply}) <-started - a.engine.Configure_tracking("highlight") + a.engine.ConfigureTracking("highlight") close(release) - finish_selection(t, a) - if response := <-reply; response != "" || a.engine.Tracking_mode() != "cursor" || a.settings.live.Presentation.Speech.Module != "fixture" { - t.Fatal("admitted selection became invalid during preparation", response, a.effective_settings()) + finishSelection(t, a) + if response := <-reply; response != "" || a.engine.TrackingMode() != "cursor" || a.settings.live.Presentation.Speech.Module != "fixture" { + t.Fatal("admitted selection became invalid during preparation", response, a.effectiveSettings()) } } diff --git a/internal/app/spellcheck.go b/internal/app/spellcheck.go index ca9c70cc..f368de3a 100644 --- a/internal/app/spellcheck.go +++ b/internal/app/spellcheck.go @@ -10,7 +10,7 @@ import ( "git.stormux.org/storm/fenrir/internal/spellcheck" ) -func present_misspelling(word string, settings config.Reading, voice Speaker, play func(presentation.Cue) bool) { +func presentMisspelling(word string, settings config.Reading, voice Speaker, play func(presentation.Cue) bool) { accepted := false if settings.SpellcheckSound { accepted = play(presentation.Misspelled) @@ -23,7 +23,7 @@ func present_misspelling(word string, settings config.Reading, voice Speaker, pl } } -func (a *application) spellcheck_result(result spellcheck.Result) { +func (a *application) spellcheckResult(result spellcheck.Result) { if result.Operation != spellcheck.Automatic { a.spellMenu.result(result) return @@ -31,7 +31,7 @@ func (a *application) spellcheck_result(result spellcheck.Result) { if result.Generation != a.spellSession || result.Revision != a.spellFeedback || !a.lastActive || a.ui.active || a.muted || a.temporarySilence || !a.settings.live.Reading.Spellcheck || !result.Available || result.Err != nil || result.Correct || result.Word == "" { return } - present_misspelling(result.Word, a.settings.live.Reading, a.voice, func(cue presentation.Cue) bool { + presentMisspelling(result.Word, a.settings.live.Reading, a.voice, func(cue presentation.Cue) bool { return a.settings.live.Presentation.Sound.Volume > 0 && a.play(cue) }) } diff --git a/internal/app/spellcheck_loop_test.go b/internal/app/spellcheck_loop_test.go index 8c118956..ec16e722 100644 --- a/internal/app/spellcheck_loop_test.go +++ b/internal/app/spellcheck_loop_test.go @@ -39,7 +39,7 @@ func TestAutomaticSpellcheckDropsResultsAfterInputMuteSilenceAndScreenChanges(t settings.Presentation.Sound.Enabled = false keys := &fakeKeys{events: make(chan error, 2)} gate := make(chan struct{}) - service := spellcheck.New_service(context.Background(), spellcheck.Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return &LoopDictionary{keys.events, gate}, nil }}) + service := spellcheck.NewService(context.Background(), spellcheck.Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return &LoopDictionary{keys.events, gate}, nil }}) defer service.Close() voice := &fakeVoice{} source := &fakeSource{snapshot: screen.Snapshot{Terminal: 2, Active: true, Rows: 1, Cols: 32, X: 6, Cells: []rune("$ helo" + strings.Repeat(" ", 26))}, events: make(chan error, 2)} diff --git a/internal/app/spellcheck_menu.go b/internal/app/spellcheck_menu.go index 915fcffc..59b16e71 100644 --- a/internal/app/spellcheck_menu.go +++ b/internal/app/spellcheck_menu.go @@ -24,7 +24,7 @@ type spellcheckMenu struct { busy bool } -func word_choices(words []string) []interaction.Choice { +func wordChoices(words []string) []interaction.Choice { choices := make([]interaction.Choice, 0, len(words)) for _, word := range words { choices = append(choices, interaction.Choice{ID: word, Label: word, Literal: true}) @@ -41,7 +41,7 @@ func (h *spellcheckMenu) open(word string) { } h.generation, h.source, h.deleted, h.busy = generation, spellcheck.Word(word), "", false h.revision++ - session, err := interaction.New_session(interaction.Form{Type: interaction.TabForm, Title: spellcheckTitle, Tabs: []interaction.Tab{ + session, err := interaction.NewSession(interaction.Form{Type: interaction.TabForm, Title: spellcheckTitle, Tabs: []interaction.Tab{ {ID: "suggestions", Label: "Suggestions", Controls: []interaction.Control{ {ID: "word", Label: "Word", Kind: interaction.Entry, Text: h.source, Action: "check_word"}, {ID: "suggestions", Label: "Suggestions", Kind: interaction.Grid, Columns: 6, Action: "copy_word"}, @@ -58,7 +58,7 @@ func (h *spellcheckMenu) open(word string) { ui.failed("Could not open Spellcheck Menu: {0}", err) return } - ui.configure_session(session) + ui.configureSession(session) ui.session, ui.action = session, h.action ui.changed = func(session *interaction.Session) { source := session.Values()["suggestions.word"].Text @@ -66,7 +66,7 @@ func (h *spellcheckMenu) open(word string) { h.source = source h.revision++ h.due = time.Now().Add(150 * time.Millisecond) - session.Set_choices("suggestions", "suggestions", nil) + session.SetChoices("suggestions", "suggestions", nil) } } ui.voice.Say(session.Open()) @@ -96,7 +96,7 @@ func (h *spellcheckMenu) action(action string, session *interaction.Session) { return } if action == "copy_word" { - control, ok := session.Focused_control() + control, ok := session.FocusedControl() if !ok || control.Selected < 0 || control.Selected >= len(control.Choices) { return } @@ -116,7 +116,7 @@ func (h *spellcheckMenu) action(action string, session *interaction.Session) { case "add_word": word = session.Values()["exceptions.word"].Text case "remove_word": - control, ok := session.Focused_control() + control, ok := session.FocusedControl() if !ok || control.Selected < 0 || control.Selected >= len(control.Choices) { return } @@ -163,15 +163,15 @@ func (h *spellcheckMenu) result(result spellcheck.Result) { } else if strings.EqualFold(h.deleted, result.Word) { h.deleted = "" } - ui.session.Set_choices("exceptions", "exceptions", word_choices(result.Exceptions)) + ui.session.SetChoices("exceptions", "exceptions", wordChoices(result.Exceptions)) // An exception change may alter the source word's status immediately. h.revision++ h.due = time.Now().Add(150 * time.Millisecond) ui.voice.Say(i18n.Format(message, result.Word)) return } - ui.session.Set_choices("exceptions", "exceptions", word_choices(result.Exceptions)) - ui.session.Set_choices("suggestions", "suggestions", word_choices(result.Suggestions)) + ui.session.SetChoices("exceptions", "exceptions", wordChoices(result.Exceptions)) + ui.session.SetChoices("suggestions", "suggestions", wordChoices(result.Suggestions)) if result.Err != nil { ui.failed("Could not check spelling: {0}", result.Err) return diff --git a/internal/app/spellcheck_menu_test.go b/internal/app/spellcheck_menu_test.go index d5836bf2..394a8ed5 100644 --- a/internal/app/spellcheck_menu_test.go +++ b/internal/app/spellcheck_menu_test.go @@ -23,7 +23,7 @@ func (*SpellDictionary) Suggest(string) ([]string, error) { } func (*SpellDictionary) Close() {} -func receive_spelling(t *testing.T, menu *spellcheckMenu) spellcheck.Result { +func receiveSpelling(t *testing.T, menu *spellcheckMenu) spellcheck.Result { t.Helper() select { case result := <-menu.service.Results(): @@ -36,14 +36,14 @@ func receive_spelling(t *testing.T, menu *spellcheckMenu) spellcheck.Result { } func TestSpellcheckMenuSuggestionsFilterCopyCancelAndEditableSource(t *testing.T) { - service := spellcheck.New_service(context.Background(), spellcheck.Options{Language: "en_US", ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return &SpellDictionary{}, nil }}) + service := spellcheck.NewService(context.Background(), spellcheck.Options{Language: "en_US", ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return &SpellDictionary{}, nil }}) defer service.Close() - clipboard, _, _, _ := clipboard_fixture() + clipboard, _, _, _ := clipboardFixture() clipboard.add("original", false) - ui := new_internal_ui(context.Background(), &fakeKeys{}, &fakeVoice{}) + ui := newInternalUi(context.Background(), &fakeKeys{}, &fakeVoice{}) menu := &spellcheckMenu{ui: ui, service: service, clipboards: clipboard} menu.open("helo") - receive_spelling(t, menu) + receiveSpelling(t, menu) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Text: "zz"}) @@ -56,7 +56,7 @@ func TestSpellcheckMenuSuggestionsFilterCopyCancelAndEditableSource(t *testing.T t.Fatal(text) } menu.open("helo") - receive_spelling(t, menu) + receiveSpelling(t, menu) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Text: "hel"}) @@ -66,15 +66,15 @@ func TestSpellcheckMenuSuggestionsFilterCopyCancelAndEditableSource(t *testing.T t.Fatal(text, ui.active) } menu.open("helo") - receive_spelling(t, menu) + receiveSpelling(t, menu) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Text: "a", Ctrl: true}) ui.handle(interaction.Key{Text: "hello"}) ui.handle(interaction.Key{Name: "enter"}) - if result := receive_spelling(t, menu); result.Word != "hello" || !result.Correct { + if result := receiveSpelling(t, menu); result.Word != "hello" || !result.Correct { t.Fatal(result) } - if control, _ := ui.session.Focused_control(); control.ID != "word" || control.Text != "hello" { + if control, _ := ui.session.FocusedControl(); control.ID != "word" || control.Text != "hello" { t.Fatal(control) } ui.close() @@ -87,17 +87,17 @@ func TestSpellcheckMenuSuggestionsFilterCopyCancelAndEditableSource(t *testing.T } func TestSpellcheckExceptionAddDeleteUndoAndCopy(t *testing.T) { - service := spellcheck.New_service(context.Background(), spellcheck.Options{Language: "en_US", ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return &SpellDictionary{}, nil }}) + service := spellcheck.NewService(context.Background(), spellcheck.Options{Language: "en_US", ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return &SpellDictionary{}, nil }}) defer service.Close() - clipboard, _, _, _ := clipboard_fixture() - ui := new_internal_ui(context.Background(), &fakeKeys{}, &fakeVoice{}) + clipboard, _, _, _ := clipboardFixture() + ui := newInternalUi(context.Background(), &fakeKeys{}, &fakeVoice{}) menu := &spellcheckMenu{ui: ui, service: service, clipboards: clipboard} menu.open("Fenrir") - receive_spelling(t, menu) + receiveSpelling(t, menu) ui.handle(interaction.Key{Name: "right"}) ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Name: "enter"}) - if result := receive_spelling(t, menu); result.Err != nil { + if result := receiveSpelling(t, menu); result.Err != nil { t.Fatal(result) } ui.handle(interaction.Key{Name: "tab"}) @@ -108,15 +108,15 @@ func TestSpellcheckExceptionAddDeleteUndoAndCopy(t *testing.T) { t.Fatal("held Delete removed exception") } ui.handle(interaction.Key{Name: "delete"}) - receive_spelling(t, menu) + receiveSpelling(t, menu) if !ui.active || len(ui.session.Values()["exceptions.exceptions"].Choices) != 0 { t.Fatal("remove did not retain empty grid") } ui.handle(interaction.Key{Name: "tab"}) ui.handle(interaction.Key{Name: "enter"}) - receive_spelling(t, menu) + receiveSpelling(t, menu) ui.handle(interaction.Key{Name: "tab", Shift: true}) - control, _ := ui.session.Focused_control() + control, _ := ui.session.FocusedControl() if control.Text != "fen" || len(control.Choices) != 1 { t.Fatal(control) } @@ -127,14 +127,14 @@ func TestSpellcheckExceptionAddDeleteUndoAndCopy(t *testing.T) { } func TestSpellcheckMenuMissingDictionaryAndCaptureFailure(t *testing.T) { - service := spellcheck.New_service(context.Background(), spellcheck.Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return nil, errors.New("missing dictionary") }}) + service := spellcheck.NewService(context.Background(), spellcheck.Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (spellcheck.Dictionary, error) { return nil, errors.New("missing dictionary") }}) defer service.Close() voice := &fakeVoice{} - clipboard, _, _, _ := clipboard_fixture() - ui := new_internal_ui(context.Background(), &fakeKeys{}, voice) + clipboard, _, _, _ := clipboardFixture() + ui := newInternalUi(context.Background(), &fakeKeys{}, voice) menu := &spellcheckMenu{ui: ui, service: service, clipboards: clipboard} menu.open("helo") - receive_spelling(t, menu) + receiveSpelling(t, menu) if !ui.active || !strings.Contains(strings.Join(voice.messages, "|"), "missing dictionary") { t.Fatal(voice.messages) } @@ -154,11 +154,11 @@ func TestSpellcheckReadingPreviewCancelAndSave(t *testing.T) { t.Fatal(err) } voice := &fakeVoice{} - a := settings_ui_application(t, &fakeKeys{}, voice, path) + a := settingsUiApplication(t, &fakeKeys{}, voice, path) ui := a.ui live := &a.settings.live.Reading - ui.open_settings(settings, path) - receive_ui(t, ui) + ui.openSettings(settings, path) + receiveUi(t, ui) for range 8 { if strings.Contains(ui.session.Describe(), "Reading tab") { break @@ -167,7 +167,7 @@ func TestSpellcheckReadingPreviewCancelAndSave(t *testing.T) { } for range 32 { ui.handle(interaction.Key{Name: "tab"}) - if control, ok := ui.session.Focused_control(); ok && control.ID == "spellcheck" { + if control, ok := ui.session.FocusedControl(); ok && control.ID == "spellcheck" { break } } @@ -183,7 +183,7 @@ func TestSpellcheckReadingPreviewCancelAndSave(t *testing.T) { } } ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) + finishPersistence(t, a, false) } else { ui.handle(interaction.Key{Name: "escape"}) } diff --git a/internal/app/spellcheck_test.go b/internal/app/spellcheck_test.go index dc116b33..d468064f 100644 --- a/internal/app/spellcheck_test.go +++ b/internal/app/spellcheck_test.go @@ -19,7 +19,7 @@ func TestMisspellingFeedbackIndependentChoicesAndSoundFallback(t *testing.T) { settings.SpellcheckSound = choices&4 != 0 voice := &fakeVoice{} var cues []presentation.Cue - present_misspelling("helo", settings, voice, func(cue presentation.Cue) bool { cues = append(cues, cue); return soundAvailable }) + presentMisspelling("helo", settings, voice, func(cue presentation.Cue) bool { cues = append(cues, cue); return soundAvailable }) var want []string if settings.SpellcheckReadWord { want = append(want, "helo") diff --git a/internal/app/startup.go b/internal/app/startup.go index 74758ea6..7bc0bcdb 100644 --- a/internal/app/startup.go +++ b/internal/app/startup.go @@ -45,27 +45,27 @@ import ( // disabledVoice allows sound-only operation without opening a speech driver. type disabledVoice struct{} -func (disabledVoice) Say(string) {} -func (disabledVoice) Say_after(string, func(context.Context)) {} -func (disabledVoice) Say_with_pitch(string, int) {} -func (disabledVoice) Configure(speech.Parameters) {} -func (disabledVoice) Interrupt() {} -func (disabledVoice) Toggle_mute() bool { return true } -func (disabledVoice) Errors() <-chan error { return nil } -func (disabledVoice) Close() {} +func (disabledVoice) Say(string) {} +func (disabledVoice) SayAfter(string, func(context.Context)) {} +func (disabledVoice) SayWithPitch(string, int) {} +func (disabledVoice) Configure(speech.Parameters) {} +func (disabledVoice) Interrupt() {} +func (disabledVoice) ToggleMute() bool { return true } +func (disabledVoice) Errors() <-chan error { return nil } +func (disabledVoice) Close() {} func Start(ctx context.Context, settings config.Settings, configPath string, bindings input.Layout) error { - return Start_with_ready(ctx, settings, configPath, bindings, nil) + return StartWithReady(ctx, settings, configPath, bindings, nil) } -// Start_with_ready reports console startup after the first screen and input poll. +// StartWithReady reports console startup after the first screen and input poll. // A failed notification tears down the reader and releases its keyboards. -func Start_with_ready(ctx context.Context, settings config.Settings, configPath string, bindings input.Layout, ready func() error) error { +func StartWithReady(ctx context.Context, settings config.Settings, configPath string, bindings input.Layout, ready func() error) error { return start(ctx, settings, false, configPath, bindings, ready) } -// Start_terminal runs the same reader and command dispatcher in an X11 PTY. -func Start_terminal(ctx context.Context, settings config.Settings, configPath string, bindings input.Layout) error { +// StartTerminal runs the same reader and command dispatcher in an X11 PTY. +func StartTerminal(ctx context.Context, settings config.Settings, configPath string, bindings input.Layout) error { return start(ctx, settings, true, configPath, bindings, nil) } @@ -78,18 +78,18 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con return fmt.Errorf("punctuation profile %s: %w", punctuationPath, err) } // Connect before creating virtual keyboards or acquiring any input grabs. - router, err := input.New_router(bindings) + router, err := input.NewRouter(bindings) if err != nil { return err } - if err := router.Configure_modifiers(settings.Keyboard.FenrirKeys, settings.General.ScriptKeys); err != nil { + if err := router.ConfigureModifiers(settings.Keyboard.FenrirKeys, settings.General.ScriptKeys); err != nil { return err } - settings.Keyboard.FenrirKeys = router.Fenrir_keys() + settings.Keyboard.FenrirKeys = router.FenrirKeys() if err := settings.Validate(); err != nil { return err } - if err := router.Set_multi_press_timeout(time.Duration(settings.Keyboard.MultiPressTimeoutMS) * time.Millisecond); err != nil { + if err := router.SetMultiPressTimeout(time.Duration(settings.Keyboard.MultiPressTimeoutMS) * time.Millisecond); err != nil { return err } home, err := os.UserHomeDir() @@ -100,7 +100,7 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con if err != nil { return err } - spellChecker := spellcheck.New_service(ctx, spellcheck.Options{Language: spellcheck.Language(), ExceptionsPath: spellcheck.Exceptions_path(home)}) + spellChecker := spellcheck.NewService(ctx, spellcheck.Options{Language: spellcheck.Language(), ExceptionsPath: spellcheck.ExceptionsPath(home)}) defer spellChecker.Close() installedScripts, problems := scripts.Discover(scripts.Paths(home, settings.General.ScriptPath, filepath.Join(filepath.Dir(executable), "config", "scripts")), nil) for _, problem := range problems { @@ -112,7 +112,7 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con scriptCommands[script.ID] = script scriptBindings = append(scriptBindings, input.ScriptBinding{ID: script.ID, Keys: script.Keys}) } - if err := router.Configure_scripts(settings.General.ScriptKeys, scriptBindings); err != nil { + if err := router.ConfigureScripts(settings.General.ScriptKeys, scriptBindings); err != nil { return err } var remote *control.Server @@ -123,7 +123,7 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con } defer remote.Close() } - scriptRunner := scripts.New_runner(ctx, scripts.Limits{Workers: settings.Scripts.Workers, Queue: settings.Scripts.QueueLimit, OutputBytes: settings.Scripts.OutputBytes, Timeout: time.Duration(settings.Scripts.TimeoutSeconds) * time.Second}, func(terminal int) string { return script_username(terminalMode, terminal) }) + scriptRunner := scripts.NewRunner(ctx, scripts.Limits{Workers: settings.Scripts.Workers, Queue: settings.Scripts.QueueLimit, OutputBytes: settings.Scripts.OutputBytes, Timeout: time.Duration(settings.Scripts.TimeoutSeconds) * time.Second}, func(terminal int) string { return scriptUsername(terminalMode, terminal) }) defer scriptRunner.Close() var voices Speaker = disabledVoice{} var effectiveSpeech *config.Speech @@ -134,7 +134,7 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con retryContext, cancel := context.WithTimeout(ctx, audio.RecoveryTimeout) err := audio.Retry(retryContext, func(ctx context.Context) error { var err error - client, selected, err = open_speech(ctx, settings.Presentation.Speech) + client, selected, err = openSpeech(ctx, settings.Presentation.Speech) if err != nil && !waitingForSpeech && audio.Temporary(err) { waitingForSpeech = true slog.Warn("speech unavailable; waiting before acquiring keyboards", "error", err, "at", time.Now()) @@ -150,7 +150,7 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con slog.Info("speech connection ready", "at", time.Now()) } voices = speech.New(client) - voices.Configure(speech_parameters(settings)) + voices.Configure(speechParameters(settings)) } defer voices.Close() var cues SoundPlayer @@ -160,13 +160,13 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con if err != nil { return err } - player = sound.Open_recovering(ctx, sound.Theme_paths(home, settings.Presentation.Sound.Theme), sound.Options{Driver: settings.Presentation.Sound.Driver, Device: settings.Presentation.Sound.Device, Volume: settings.Presentation.Sound.Volume}) + player = sound.OpenRecovering(ctx, sound.ThemePaths(home, settings.Presentation.Sound.Theme), sound.Options{Driver: settings.Presentation.Sound.Driver, Device: settings.Presentation.Sound.Device, Volume: settings.Presentation.Sound.Volume}) if player != nil { defer player.Close() cues = player } } - historyStore := clipboard.New_persistence(clipboard.History_path(home, terminalMode), settings.Clipboard.Persistent) + historyStore := clipboard.NewPersistence(clipboard.HistoryPath(home, terminalMode), settings.Clipboard.Persistent) defer func() { result = errors.Join(result, historyStore.Close()) }() var source Source var keyboards Keyboards @@ -184,7 +184,7 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con } defer consoleSource.Close() source = consoleSource - consoleKeys, err := console.Open_keyboards(settings.Keyboard.Devices, router) + consoleKeys, err := console.OpenKeyboards(settings.Keyboard.Devices, router) if err != nil { return err } @@ -194,9 +194,9 @@ func start(ctx context.Context, settings config.Settings, terminalMode bool, con if consoleSource, ok := source.(*console.Source); ok { paste = consoleSource.Paste } - transfers := clipboard.New_worker(ctx, paste) + transfers := clipboard.NewWorker(ctx, paste) defer transfers.Close() - result = Run(ctx, source, keyboards, voices, RunOptions{Ready: ready, Spellcheck: spellChecker, Bindings: bindings.Bindings, Settings: settings, EffectiveSpeech: effectiveSpeech, Punctuation: punctuationProcessor, Sounds: cues, ConfigPath: configPath, Clipboard: transfers, ClipboardHistory: historyStore, SettingsChoices: preferences.Discover_choices, Scripts: scriptCommands, ScriptRunner: scriptRunner, Remote: remote, TerminalMode: terminalMode, SharedNotifications: true}) + result = Run(ctx, source, keyboards, voices, RunOptions{Ready: ready, Spellcheck: spellChecker, Bindings: bindings.Bindings, Settings: settings, EffectiveSpeech: effectiveSpeech, Punctuation: punctuationProcessor, Sounds: cues, ConfigPath: configPath, Clipboard: transfers, ClipboardHistory: historyStore, SettingsChoices: preferences.DiscoverChoices, Scripts: scriptCommands, ScriptRunner: scriptRunner, Remote: remote, TerminalMode: terminalMode, SharedNotifications: true}) if result == nil && player != nil { if err := player.Finish(context.Background()); err != nil { slog.Warn("shutdown sound incomplete", "error", err, "at", time.Now()) diff --git a/internal/app/synthesizer_preview.go b/internal/app/synthesizer_preview.go index c9ddd2bf..694290b3 100644 --- a/internal/app/synthesizer_preview.go +++ b/internal/app/synthesizer_preview.go @@ -16,13 +16,13 @@ import ( // Reuse the current connection only when its driver, device and baud match. // Numeric preview and restoration stay on the normal serialized speech worker. -func (ui *internalUI) test_synthesizer(ctx context.Context, selected, current config.Speech) error { +func (ui *internalUI) testSynthesizer(ctx context.Context, selected, current config.Speech) error { if err := ctx.Err(); err != nil { return err } text := i18n.T("Voice test: The quick brown fox jumps over the lazy dog.") sameConnection := selected.Driver == current.Driver - driver, err := speech.Find_driver(selected.Driver) + driver, err := speech.FindDriver(selected.Driver) if err != nil { return err } @@ -44,18 +44,18 @@ func (ui *internalUI) test_synthesizer(ctx context.Context, selected, current co voice = echo.Speaker } preview, ok := voice.(interface { - Say_with_parameters(string, speech.Parameters) + SayWithParameters(string, speech.Parameters) }) if !ok { return fmt.Errorf("speech service does not support parameter preview") } - preview.Say_with_parameters(text, speech.Parameters{Rate: selected.Rate, Pitch: selected.Pitch, Volume: selected.Volume}) + preview.SayWithParameters(text, speech.Parameters{Rate: selected.Rate, Pitch: selected.Pitch, Volume: selected.Volume}) return nil } - return speech.Test_hardware(ctx, selected.Driver, speech_options(selected), text) + return speech.TestHardware(ctx, selected.Driver, speechOptions(selected), text) } -func (ui *internalUI) test_failed(err error) { +func (ui *internalUI) testFailed(err error) { slog.Warn("hardware speech test failed", "error", err, "at", time.Now()) ui.voice.Say(i18n.T("Voice test failed") + ": " + err.Error()) } diff --git a/internal/app/text_processing_test.go b/internal/app/text_processing_test.go index 99b93aae..08132c94 100644 --- a/internal/app/text_processing_test.go +++ b/internal/app/text_processing_test.go @@ -34,12 +34,12 @@ func TestTextProcessingMenuCommitCancelAndFailedSave(t *testing.T) { text := ":) :) #####" source := &fakeSource{snapshot: screen.Snapshot{Terminal: 1, Active: true, Rows: 1, Cols: len(text), Cells: []rune(text)}} voice := &fakeVoice{} - a, err := new_application(context.Background(), source, &fakeKeys{}, voice, RunOptions{Settings: settings, ConfigPath: path, Punctuation: processor}) + a, err := newApplication(context.Background(), source, &fakeKeys{}, voice, RunOptions{Settings: settings, ConfigPath: path, Punctuation: processor}) if err != nil { t.Fatal(err) } defer a.ui.close() - if err := a.read_screen(); err != nil { + if err := a.readScreen(); err != nil { t.Fatal(err) } if got := strings.Join(strings.Fields(voice.messages[len(voice.messages)-1]), " "); got != "smile smile hash hash hash hash hash" { @@ -48,8 +48,8 @@ func TestTextProcessingMenuCommitCancelAndFailedSave(t *testing.T) { if a.voice.last != text { t.Fatal("automatic reading changed clipboard echo", a.voice.last) } - a.open_settings() - receive_ui(t, a.ui) + a.openSettings() + receiveUi(t, a.ui) focus := func(want string) { t.Helper() for range 40 { @@ -79,7 +79,7 @@ func TestTextProcessingMenuCommitCancelAndFailedSave(t *testing.T) { } focus("OK button") a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, action == "failed save") + finishPersistence(t, a, action == "failed save") if action == "failed save" { if !a.ui.active || !strings.HasPrefix(voice.messages[len(voice.messages)-1], "Could not save settings:") { t.Fatal("failed save lost the draft", voice.messages) @@ -106,26 +106,26 @@ func TestTextProcessingMenuCommitCancelAndFailedSave(t *testing.T) { t.Fatal(saved.Reading, err) } freshVoice := &fakeVoice{} - fresh, err := new_application(context.Background(), source, &fakeKeys{}, freshVoice, RunOptions{Settings: saved, Punctuation: processor}) + fresh, err := newApplication(context.Background(), source, &fakeKeys{}, freshVoice, RunOptions{Settings: saved, Punctuation: processor}) if err != nil { t.Fatal(err) } defer fresh.ui.close() - if err := fresh.read_screen(); err != nil || strings.Join(strings.Fields(freshVoice.messages[len(freshVoice.messages)-1]), " ") != ": : 5 number" { + if err := fresh.readScreen(); err != nil || strings.Join(strings.Fields(freshVoice.messages[len(freshVoice.messages)-1]), " ") != ": : 5 number" { t.Fatal("fresh reader lost saved processing", freshVoice.messages, err) } voice.messages = nil - a.review_command(command.CurrentLine) + a.reviewCommand(command.CurrentLine) if strings.Join(strings.Fields(voice.messages[0]), " ") != ": : 5 number" { t.Fatal("review bypassed processing", voice.messages) } voice.messages = nil - a.voice.say_spelling(presentation.Spelling{Text: "#####"}) + a.voice.saySpelling(presentation.Spelling{Text: "#####"}) if !reflect.DeepEqual(voice.messages, []string{"hash", "hash", "hash", "hash", "hash"}) || a.voice.last != "#####" { t.Fatal("summary changed spelling or raw copy", voice.messages, a.voice.last) } voice.messages = nil - a.voice.say_spelling(presentation.Spelling{Text: ":)", Phonetic: true}) + a.voice.saySpelling(presentation.Spelling{Text: ":)", Phonetic: true}) if !reflect.DeepEqual(voice.messages, []string{"colon", "right paren"}) { t.Fatal("emoticon changed phonetic feedback", voice.messages) } diff --git a/internal/app/tutorial.go b/internal/app/tutorial.go index cd8c0398..0a8f381a 100644 --- a/internal/app/tutorial.go +++ b/internal/app/tutorial.go @@ -32,14 +32,14 @@ type tutorialMode struct { names map[command.ID]string } -func tutorial_key_name(name string) string { +func tutorialKeyName(name string) string { name = strings.ToLower(name) name = strings.ReplaceAll(name, "key_kp", "keypad ") name = strings.TrimPrefix(name, "key_") return i18n.T(name) } -func tutorial_shortcut(keys []string, presses int, scriptKeys []string) string { +func tutorialShortcut(keys []string, presses int, scriptKeys []string) string { keys = slices.Clone(keys) var ordered []string for _, modifier := range []string{"KEY_FENRIR", "KEY_SCRIPT", "KEY_CTRL", "KEY_SHIFT", "KEY_ALT", "KEY_META"} { @@ -54,11 +54,11 @@ func tutorial_shortcut(keys []string, presses int, scriptKeys []string) string { if key == "KEY_SCRIPT" { var physical []string for _, scriptKey := range scriptKeys { - physical = append(physical, tutorial_key_name(scriptKey)) + physical = append(physical, tutorialKeyName(scriptKey)) } names = append(names, strings.Join(physical, " / ")) } else { - names = append(names, tutorial_key_name(key)) + names = append(names, tutorialKeyName(key)) } } prefix := "" @@ -68,7 +68,7 @@ func tutorial_shortcut(keys []string, presses int, scriptKeys []string) string { return prefix + strings.Join(names, ", ") } -func new_tutorial(bindings []input.Binding, installed map[command.ID]scripts.Script, scriptKeys []string) *tutorialMode { +func newTutorial(bindings []input.Binding, installed map[command.ID]scripts.Script, scriptKeys []string) *tutorialMode { mode := &tutorialMode{index: -1, shortcuts: map[command.ID][]string{}, names: map[command.ID]string{}} for _, binding := range bindings { keys := make([]string, len(binding.Keys)) @@ -77,7 +77,7 @@ func new_tutorial(bindings []input.Binding, installed map[command.ID]scripts.Scr } for index, id := range []command.ID{binding.Command, binding.DoubleCommand, binding.TripleCommand} { if id != "" { - mode.shortcuts[id] = append(mode.shortcuts[id], tutorial_shortcut(keys, index+1, scriptKeys)) + mode.shortcuts[id] = append(mode.shortcuts[id], tutorialShortcut(keys, index+1, scriptKeys)) } } } @@ -90,7 +90,7 @@ func new_tutorial(bindings []input.Binding, installed map[command.ID]scripts.Scr } for id, script := range installed { mode.names[id] = strings.ReplaceAll(strings.ToLower(script.Name), "_", " ") - mode.shortcuts[id] = []string{tutorial_shortcut(script.Keys, 1, scriptKeys)} + mode.shortcuts[id] = []string{tutorialShortcut(script.Keys, 1, scriptKeys)} mode.sections[2] = append(mode.sections[2], id) } slices.Sort(mode.sections[2]) @@ -152,7 +152,7 @@ func (mode *tutorialMode) handle(key input.LearnKey) (string, bool) { } var names []string for _, code := range append(slices.Clone(key.Held), key.Code) { - names = append(names, tutorial_key_name(input.Key_name(code))) + names = append(names, tutorialKeyName(input.KeyName(code))) } text := strings.Join(names, ", ") if key.Command != "" && key.Command != command.Unbound { @@ -163,7 +163,7 @@ func (mode *tutorialMode) handle(key input.LearnKey) (string, bool) { return text, false } -func (ui *internalUI) open_tutorial(bindings []input.Binding, installed map[command.ID]scripts.Script, scriptKeys []string) { +func (ui *internalUI) openTutorial(bindings []input.Binding, installed map[command.ID]scripts.Script, scriptKeys []string) { if ui.active { return } @@ -172,11 +172,11 @@ func (ui *internalUI) open_tutorial(bindings []input.Binding, installed map[comm ui.voice.Say(i18n.T(tutorialCaptureFailed)) return } - ui.tutorial = new_tutorial(bindings, installed, scriptKeys) + ui.tutorial = newTutorial(bindings, installed, scriptKeys) ui.voice.Say(i18n.T(tutorialEntry)) } -func (ui *internalUI) handle_tutorial(key input.LearnKey) { +func (ui *internalUI) handleTutorial(key input.LearnKey) { text, close := ui.tutorial.handle(key) if close { ui.close() diff --git a/internal/app/tutorial_test.go b/internal/app/tutorial_test.go index d0b1b6b7..1774e157 100644 --- a/internal/app/tutorial_test.go +++ b/internal/app/tutorial_test.go @@ -24,7 +24,7 @@ import ( func TestTutorialBrowsesCustomUnboundAndPluginActions(t *testing.T) { bindings := []input.Binding{{Keys: []string{"FENRIR", "Z"}, Command: command.Time, DoubleCommand: command.Date, TripleCommand: command.CurrentQuickEntry}} installed := map[command.ID]scripts.Script{"script:example": {Name: "EXAMPLE", Keys: []string{"KEY_SCRIPT", "KEY_SHIFT", "KEY_U"}}} - mode := new_tutorial(bindings, installed, []string{"KEY_COMPOSE", "KEY_META"}) + mode := newTutorial(bindings, installed, []string{"KEY_COMPOSE", "KEY_META"}) if got := mode.describe(command.Date); !strings.Contains(got, "2 times fenrir, z") || !strings.Contains(got, "presents the date") { t.Fatal(got) } @@ -64,7 +64,7 @@ func TestTutorialBrowsesCustomUnboundAndPluginActions(t *testing.T) { if press(input.KeyRight) != "Active actions" || press(input.KeyLeft) != "Plugins" { t.Fatal(mode.current()) } - empty := new_tutorial(nil, nil, nil) + empty := newTutorial(nil, nil, nil) empty.section = 2 if got, _ := empty.handle(input.LearnKey{Code: input.KeyDown, Bare: true}); got != "Plugins" { t.Fatal(got) @@ -81,15 +81,15 @@ func TestTutorialBrowsesCustomUnboundAndPluginActions(t *testing.T) { } func TestTutorialDispatcherBlocksActionsAndRestoresTyping(t *testing.T) { - bindings, _, err := input.Load_bindings([]string{"../../config/keyboard/desktop.toml"}) + bindings, _, err := input.LoadBindings([]string{"../../config/keyboard/desktop.toml"}) if err != nil { t.Fatal(err) } - router, err := input.New_router(bindings) + router, err := input.NewRouter(bindings) if err != nil { t.Fatal(err) } - if err := router.Configure_scripts([]string{"KEY_COMPOSE"}, []input.ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { + if err := router.ConfigureScripts([]string{"KEY_COMPOSE"}, []input.ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { t.Fatal(err) } keys, voice := &fakeKeys{}, &fakeVoice{} @@ -113,7 +113,7 @@ func TestTutorialDispatcherBlocksActionsAndRestoresTyping(t *testing.T) { chord(input.KeyInsert, code) } chord(input.KeyInsert, input.KeyCtrl, 31) // save - compose, _ := input.Key_code("KEY_COMPOSE") + compose, _ := input.KeyCode("KEY_COMPOSE") chord(compose, 22) chord(88) if !router.Captured() { @@ -141,14 +141,14 @@ func TestTutorialDispatcherBlocksActionsAndRestoresTyping(t *testing.T) { func TestTutorialCaptureFailureAndMenuExclusion(t *testing.T) { keys, voice := &fakeKeys{}, &fakeVoice{} - ui := new_internal_ui(context.Background(), keys, voice) + ui := newInternalUi(context.Background(), keys, voice) keys.captureErr = errors.New("capture refused") - ui.open_tutorial(nil, nil, nil) + ui.openTutorial(nil, nil, nil) if ui.active || voice.messages[len(voice.messages)-1] != tutorialCaptureFailed { t.Fatal(ui, voice.messages) } keys.captureErr = nil - ui.open_tutorial(nil, nil, nil) + ui.openTutorial(nil, nil, nil) keys.captureErr = errors.New("release refused") ui.close() if !ui.active || ui.tutorial == nil || voice.messages[len(voice.messages)-1] != tutorialReleaseFailed { @@ -161,7 +161,7 @@ func TestTutorialCaptureFailureAndMenuExclusion(t *testing.T) { } ui.begin("Fenrir Menu") count := len(keys.captures) - ui.open_tutorial(nil, nil, nil) + ui.openTutorial(nil, nil, nil) if ui.tutorial != nil || len(keys.captures) != count { t.Fatal("tutorial replaced menu") } @@ -257,7 +257,7 @@ msgstr "translated-fenrir" } previous := i18n.Use(i18n.New(root, "xx")) t.Cleanup(func() { i18n.Use(previous) }) - mode := new_tutorial([]input.Binding{{Keys: []string{"FENRIR", "Z"}, Command: command.Date, DoubleCommand: command.Time}}, nil, nil) + mode := newTutorial([]input.Binding{{Keys: []string{"FENRIR", "Z"}, Command: command.Date, DoubleCommand: command.Time}}, nil, nil) if got := mode.describe(command.Time); got != "translated-time: 2 repetitions translated-fenrir, z: time" { t.Fatal(got) } diff --git a/internal/app/version_test.go b/internal/app/version_test.go index deecd903..6ae81c4b 100644 --- a/internal/app/version_test.go +++ b/internal/app/version_test.go @@ -16,12 +16,12 @@ import ( func TestVersionUsesReleaseMetadataInBothModes(t *testing.T) { for _, terminalMode := range []bool{false, true} { voice := &fakeVoice{} - a, err := new_application(context.Background(), &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: config.Defaults(), TerminalMode: terminalMode}) + a, err := newApplication(context.Background(), &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: config.Defaults(), TerminalMode: terminalMode}) if err != nil { t.Fatal(err) } defer a.ui.close() - a.handle_input(input.Decision{Command: command.Version, Interrupt: true}) + a.handleInput(input.Decision{Command: command.Version, Interrupt: true}) if len(voice.messages) != 1 || voice.messages[0] != "Fenrir screen reader version "+version.Label() { t.Fatal("spoken version differs from CLI metadata", voice.messages) } diff --git a/internal/app/voice_profiles.go b/internal/app/voice_profiles.go index 6c47824f..819d9820 100644 --- a/internal/app/voice_profiles.go +++ b/internal/app/voice_profiles.go @@ -12,7 +12,7 @@ import ( "git.stormux.org/storm/screenreader-common/voiceprofiles" ) -func (ui *internalUI) manage_profiles(action string, parent *interaction.Session, draft config.Settings, discovery preferences.Discovery, restore func(config.Settings)) { +func (ui *internalUI) manageProfiles(action string, parent *interaction.Session, draft config.Settings, discovery preferences.Discovery, restore func(config.Settings)) { ui.profileSequence++ sequence := ui.profileSequence index := -1 @@ -28,7 +28,7 @@ func (ui *internalUI) manage_profiles(action string, parent *interaction.Session if index < 0 || index >= len(draft.VoiceProfiles.Profiles) { return } - next, err := config.Apply_primary_voice(draft, draft.VoiceProfiles.Profiles[index]) + next, err := config.ApplyPrimaryVoice(draft, draft.VoiceProfiles.Profiles[index]) if err != nil { ui.failed("Could not select voice profile: {0}", err) return @@ -36,7 +36,7 @@ func (ui *internalUI) manage_profiles(action string, parent *interaction.Session restore(next) return } - p := config.Primary_voice(draft) + p := config.PrimaryVoice(draft) p.Name = "" if p.Device == "" { p.Device = "/dev/ttyUSB0" @@ -62,8 +62,8 @@ func (ui *internalUI) manage_profiles(action string, parent *interaction.Session } } open := func(catalog sd.Catalog) { - editor := voiceprofiles.New_editor(p, voiceprofiles.Drivers(), catalog) - child, err := interaction.New_session(editor.Form()) + editor := voiceprofiles.NewEditor(p, voiceprofiles.Drivers(), catalog) + child, err := interaction.NewSession(editor.Form()) if err != nil { ui.failed("Could not edit voice profiles: {0}", err) return @@ -72,7 +72,7 @@ func (ui *internalUI) manage_profiles(action string, parent *interaction.Session ui.session = child ui.returnToParent = func() { restore(draft) } ui.changed = func(session *interaction.Session) { - editor.Refresh_session(session) + editor.RefreshSession(session) if ui.previewSpeech == nil { return } @@ -80,7 +80,7 @@ func (ui *internalUI) manage_profiles(action string, parent *interaction.Session if err != nil { return // An incomplete edit must leave the working voice available. } - if next, err := config.Apply_primary_voice(draft, profile); err == nil { + if next, err := config.ApplyPrimaryVoice(draft, profile); err == nil { ui.previewSpeech(next.Presentation.Speech) } } diff --git a/internal/app/voice_profiles_test.go b/internal/app/voice_profiles_test.go index 4b9d495b..bcc2f0f3 100644 --- a/internal/app/voice_profiles_test.go +++ b/internal/app/voice_profiles_test.go @@ -18,18 +18,18 @@ import ( func TestVoiceProfileMenuAddCancelPersistAndRemove(t *testing.T) { path := filepath.Join(t.TempDir(), "settings.toml") - a := settings_ui_application(t, &fakeKeys{}, &fakeVoice{}, path) - a.ui.open_settings(config.Defaults(), path) - receive_ui(t, a.ui) + a := settingsUiApplication(t, &fakeKeys{}, &fakeVoice{}, path) + a.ui.openSettings(config.Defaults(), path) + receiveUi(t, a.ui) activate := func(id string) { t.Helper() - if !a.ui.session.Focus_control("voice-profiles", id) { + if !a.ui.session.FocusControl("voice-profiles", id) { t.Fatal("missing profile control", id) } a.ui.handle(interaction.Key{Name: "enter"}) } activate("add") - if c, _ := a.ui.session.Focused_control(); c.ID != "name" { + if c, _ := a.ui.session.FocusedControl(); c.ID != "name" { t.Fatal(c) } a.ui.handle(interaction.Key{Text: "Discarded"}) @@ -39,9 +39,9 @@ func TestVoiceProfileMenuAddCancelPersistAndRemove(t *testing.T) { } activate("add") a.ui.handle(interaction.Key{Text: "Reading"}) - a.ui.session.Focus_control(voiceprofiles.PageID, "rate") + a.ui.session.FocusControl(voiceprofiles.PageID, "rate") a.ui.handle(interaction.Key{Name: "right"}) - a.ui.session.Focus_control(voiceprofiles.PageID, "save") + a.ui.session.FocusControl(voiceprofiles.PageID, "save") a.ui.handle(interaction.Key{Name: "enter"}) if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { t.Fatal("child dialog saved before parent confirmation", err) @@ -51,19 +51,19 @@ func TestVoiceProfileMenuAddCancelPersistAndRemove(t *testing.T) { t.Fatal("rate did not survive add") } a.ui.handle(interaction.Key{Name: "escape"}) - a.ui.session.Focus_control("presentation", "ok") + a.ui.session.FocusControl("presentation", "ok") a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) + finishPersistence(t, a, false) loaded, _, err := config.Load(path, nil) if err != nil || len(loaded.VoiceProfiles.Profiles) != 1 || loaded.VoiceProfiles.Profiles[0].Name != "Reading" { t.Fatal(loaded.VoiceProfiles, err) } - a.ui.open_settings(loaded, path) - receive_ui(t, a.ui) + a.ui.openSettings(loaded, path) + receiveUi(t, a.ui) activate("remove") - a.ui.session.Focus_control("presentation", "ok") + a.ui.session.FocusControl("presentation", "ok") a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) + finishPersistence(t, a, false) loaded, _, err = config.Load(path, nil) if err != nil || len(loaded.VoiceProfiles.Profiles) != 0 { t.Fatal(loaded.VoiceProfiles, err) @@ -72,7 +72,7 @@ func TestVoiceProfileMenuAddCancelPersistAndRemove(t *testing.T) { func TestQuickVoiceProfileFailureBackendChangeAndWrap(t *testing.T) { settings := config.Defaults() settings.VoiceProfiles.Profiles = []voiceprofiles.Profile{{Name: "Reading", Driver: "speech-dispatcher", Rate: 30, Volume: 80}, {Name: "Hardware", Driver: "dectalk", Device: "/dev/fixture", BaudRate: 9600, Rate: 40, Volume: 90}} - menu, voice := new_quick_settings("speech-dispatcher"), &fakeVoice{} + menu, voice := newQuickSettings("speech-dispatcher"), &fakeVoice{} for range 6 { menu.command(command.NextQuickEntry, &settings, voice) } @@ -85,7 +85,7 @@ func TestQuickVoiceProfileFailureBackendChangeAndWrap(t *testing.T) { menu.selectSpeech = func(_ config.Speech, done func(error, bool)) { done(nil, true) } for _, name := range []string{"Reading", "Hardware", "Reading", "Hardware"} { menu.command(command.NextQuickValue, &settings, voice) - if got := settings.VoiceProfiles.Matching(config.Primary_voice(settings)); got != name { + if got := settings.VoiceProfiles.Matching(config.PrimaryVoice(settings)); got != name { t.Fatal(got, name, voice.messages) } } @@ -93,33 +93,33 @@ func TestQuickVoiceProfileFailureBackendChangeAndWrap(t *testing.T) { t.Fatal("profile changed echo or missed selection") } saved := before - copy_speech_selection(&saved.Presentation.Speech, settings.Presentation.Speech) + copySpeechSelection(&saved.Presentation.Speech, settings.Presentation.Speech) if saved.Presentation.Speech.Driver != "dectalk" || saved.Presentation.Speech.HardwareDevice != "/dev/fixture" { t.Fatal("quick save lost backend") } } func TestMenuVoiceProfileRestoresSavedBackendAfterQuickChange(t *testing.T) { - a, _, path := selection_application(t, true) + a, _, path := selectionApplication(t, true) draft := a.settings.saveDraft - profile := config.Primary_voice(draft) + profile := config.PrimaryVoice(draft) profile.Name = "Saved voice" draft.VoiceProfiles.Profiles = []voiceprofiles.Profile{profile} a.settings.live.Presentation.Speech.Module = "temporary" prepared := false a.prepareSpeech = func(selected config.Speech) (speech.Transport, error) { prepared = true; return &preparedVoice{}, nil } - doc, err := config.Open_document(path, draft) + doc, err := config.OpenDocument(path, draft) if err != nil { t.Fatal(err) } - if !a.save_menu_settings(doc, draft, func(err error) { + if !a.saveMenuSettings(doc, draft, func(err error) { if err != nil { t.Error(err) } }) { t.Fatal("save not admitted") } - a.settings_save_result(committed_menu_result(t, a)) + a.settingsSaveResult(committedMenuResult(t, a)) if !prepared || a.settings.live.Presentation.Speech.Module != "" { t.Fatal("menu profile left temporary backend active") } @@ -128,7 +128,7 @@ func TestMenuVoiceProfileRestoresSavedBackendAfterQuickChange(t *testing.T) { func TestQuickVoiceProfilePreservesLaterNumericAdjustment(t *testing.T) { settings := config.Defaults() settings.VoiceProfiles.Profiles = []voiceprofiles.Profile{{Name: "Reading", Driver: "speech-dispatcher", Rate: 30, Volume: 80}} - menu, voice := new_quick_settings("speech-dispatcher"), &fakeVoice{} + menu, voice := newQuickSettings("speech-dispatcher"), &fakeVoice{} var complete func(error, bool) menu.selectSpeech = func(_ config.Speech, done func(error, bool)) { complete = done } for range 6 { @@ -136,7 +136,7 @@ func TestQuickVoiceProfilePreservesLaterNumericAdjustment(t *testing.T) { } menu.command(command.NextQuickValue, &settings, voice) menu.command(command.NextQuickEntry, &settings, voice) // wraps to the module - quick_select_rate(menu, &settings, voice) + quickSelectRate(menu, &settings, voice) menu.command(command.NextQuickValue, &settings, voice) complete(nil, true) if settings.Presentation.Speech.Rate != 10 || settings.Presentation.Speech.Volume != 80 { @@ -146,9 +146,9 @@ func TestQuickVoiceProfilePreservesLaterNumericAdjustment(t *testing.T) { func TestCancelledProfileDiscoveryCannotReplaceNewerEditor(t *testing.T) { path := filepath.Join(t.TempDir(), "settings.toml") - a := settings_ui_application(t, &fakeKeys{}, &fakeVoice{}, path) - a.ui.open_settings(config.Defaults(), path) - receive_ui(t, a.ui) + a := settingsUiApplication(t, &fakeKeys{}, &fakeVoice{}, path) + a.ui.openSettings(config.Defaults(), path) + receiveUi(t, a.ui) first, second := make(chan struct{}), make(chan struct{}) requests := make(chan int, 2) a.ui.discoverChoices = func(settings config.Settings) preferences.Discovery { @@ -163,26 +163,26 @@ func TestCancelledProfileDiscoveryCannotReplaceNewerEditor(t *testing.T) { } draft := config.Defaults() restore := func(next config.Settings) { - session, err := preferences.New_session(next, nil) + session, err := preferences.NewSession(next, nil) if err != nil { t.Fatal(err) } a.ui.session = session a.ui.returnToParent = nil } - a.ui.manage_profiles("add-profile", a.ui.session, draft, preferences.Discovery{Driver: "dectalk"}, restore) + a.ui.manageProfiles("add-profile", a.ui.session, draft, preferences.Discovery{Driver: "dectalk"}, restore) <-requests a.ui.handle(interaction.Key{Name: "escape"}) draft.Presentation.Speech.Rate = 20 - a.ui.manage_profiles("add-profile", a.ui.session, draft, preferences.Discovery{Driver: "dectalk"}, restore) + a.ui.manageProfiles("add-profile", a.ui.session, draft, preferences.Discovery{Driver: "dectalk"}, restore) <-requests close(first) - receive_ui(t, a.ui) + receiveUi(t, a.ui) if a.ui.session != nil { t.Fatal("cancelled discovery reopened an older editor") } close(second) - receive_ui(t, a.ui) + receiveUi(t, a.ui) if got := a.ui.session.Values()[voiceprofiles.PageID+".rate"].Number; got != 20 { t.Fatal("newer draft lost", got) } @@ -192,8 +192,8 @@ func TestQuickVoiceProfileDefaultRestoresSavedVoice(t *testing.T) { settings := config.Defaults() settings.Presentation.Speech.Rate = 20 settings.VoiceProfiles.Profiles = []voiceprofiles.Profile{{Name: "Reading", Driver: "speech-dispatcher", Module: "fixture", Rate: 30, Volume: 80}} - saved := config.Primary_voice(settings) - menu, voice := new_quick_settings("speech-dispatcher"), &fakeVoice{} + saved := config.PrimaryVoice(settings) + menu, voice := newQuickSettings("speech-dispatcher"), &fakeVoice{} menu.savedVoice = &saved menu.selectSpeech = func(_ config.Speech, done func(error, bool)) { done(nil, true) } for range 6 { @@ -207,7 +207,7 @@ func TestQuickVoiceProfileDefaultRestoresSavedVoice(t *testing.T) { t.Fatal("profile not applied", settings.Presentation.Speech) } menu.command(command.NextQuickValue, &settings, voice) // Wraps to Default. - if !voiceprofiles.Same_voice(config.Primary_voice(settings), saved) { + if !voiceprofiles.SameVoice(config.PrimaryVoice(settings), saved) { t.Fatal("Default did not restore the saved voice", settings.Presentation.Speech) } if got := voice.messages[len(voice.messages)-1]; got != "Default" { @@ -221,15 +221,15 @@ func TestQuickVoiceProfileDefaultRestoresSavedVoice(t *testing.T) { t.Fatal("session voice not Custom", got) } menu.command(command.NextQuickValue, &settings, voice) - if !voiceprofiles.Same_voice(config.Primary_voice(settings), saved) { + if !voiceprofiles.SameVoice(config.PrimaryVoice(settings), saved) { t.Fatal("Default unavailable from a custom voice", settings.Presentation.Speech) } } func TestQuickVoiceProfileOfferedWithoutProfiles(t *testing.T) { settings := config.Defaults() - saved := config.Primary_voice(settings) - menu, voice := new_quick_settings("speech-dispatcher"), &fakeVoice{} + saved := config.PrimaryVoice(settings) + menu, voice := newQuickSettings("speech-dispatcher"), &fakeVoice{} menu.savedVoice = &saved for range 6 { menu.command(command.NextQuickEntry, &settings, voice) @@ -240,86 +240,86 @@ func TestQuickVoiceProfileOfferedWithoutProfiles(t *testing.T) { } func TestVoiceProfileEditorPreviewsAndRestoresParentDraft(t *testing.T) { - a, voice, _, prepared := preview_application(t) - a.open_settings() - receive_ui(t, a.ui) - if !a.ui.session.Focus_control("voice-profiles", "add") { + a, voice, _, prepared := previewApplication(t) + a.openSettings() + receiveUi(t, a.ui) + if !a.ui.session.FocusControl("voice-profiles", "add") { t.Fatal("missing Add Voice Profile") } a.ui.handle(interaction.Key{Name: "enter"}) - a.ui.session.Focus_control(voiceprofiles.PageID, "rate") + a.ui.session.FocusControl(voiceprofiles.PageID, "rate") a.ui.handle(interaction.Key{Name: "right"}) - if got := last_parameters(t, voice); got.Rate != 10 { + if got := lastParameters(t, voice); got.Rate != 10 { t.Fatal("profile rate was not previewed", got) } // Module changes use the same silent preparation as ordinary settings. control := a.ui.session.Values()[voiceprofiles.PageID+".module"] control.Choices = append(control.Choices, interaction.Choice{ID: "fixture", Label: "fixture", Literal: true}) - a.ui.session.Replace_choices(voiceprofiles.PageID, "module", control.Choices, "fixture") + a.ui.session.ReplaceChoices(voiceprofiles.PageID, "module", control.Choices, "fixture") a.ui.handle(interaction.Key{Name: "tab"}) if got := <-prepared; got.Module != "fixture" { t.Fatal("profile module was not previewed", got) } - finish_preview(t, a, voice) + finishPreview(t, a, voice) if a.settings.live.Presentation.Speech.Rate != 0 || a.settings.live.Presentation.Speech.Module != "" { t.Fatal("preview committed the profile") } a.ui.handle(interaction.Key{Name: "escape"}) - if got := last_parameters(t, voice); got.Rate != 0 { + if got := lastParameters(t, voice); got.Rate != 0 { t.Fatal("cancel did not restore parent rate", got) } if got := <-prepared; got.Module != "" { t.Fatal("cancel did not restore parent module", got) } - finish_preview(t, a, voice) + finishPreview(t, a, voice) } func TestNewVoiceProfileCanBeConfirmedOnItsTabAndSelectedImmediately(t *testing.T) { - a, voice, path, _ := preview_application(t) - a.open_settings() - receive_ui(t, a.ui) - a.ui.session.Focus_control("voice-profiles", "add") + a, voice, path, _ := previewApplication(t) + a.openSettings() + receiveUi(t, a.ui) + a.ui.session.FocusControl("voice-profiles", "add") a.ui.handle(interaction.Key{Name: "enter"}) a.ui.handle(interaction.Key{Text: "Reading"}) - a.ui.session.Focus_control(voiceprofiles.PageID, "rate") + a.ui.session.FocusControl(voiceprofiles.PageID, "rate") a.ui.handle(interaction.Key{Name: "right"}) - a.ui.session.Focus_control(voiceprofiles.PageID, "save") + a.ui.session.FocusControl(voiceprofiles.PageID, "save") a.ui.handle(interaction.Key{Name: "enter"}) - if !a.ui.session.Focus_control("voice-profiles", "ok") { + if !a.ui.session.FocusControl("voice-profiles", "ok") { t.Fatal("profile tab has no way to confirm its changes") } a.ui.handle(interaction.Key{Name: "enter"}) - finish_persistence(t, a, false) + finishPersistence(t, a, false) loaded, _, err := config.Load(path, nil) if err != nil || len(loaded.VoiceProfiles.Profiles) != 1 || len(a.settings.live.VoiceProfiles.Profiles) != 1 { t.Fatal("new profile missing from disk or runtime", loaded.VoiceProfiles, a.settings.live.VoiceProfiles, err) } for range 6 { - a.handle_command(command.NextQuickEntry) + a.handleCommand(command.NextQuickEntry) } - a.handle_command(command.NextQuickValue) - finish_selection(t, a) + a.handleCommand(command.NextQuickValue) + finishSelection(t, a) if got := a.settings.live.Presentation.Speech.Rate; got != 10 { t.Fatal("new profile not immediately selectable", got, voice.messages) } } func TestUseVoiceProfilePreviewsWithoutCommittingPrimary(t *testing.T) { - a, voice, path, prepared := preview_application(t) + a, voice, path, prepared := previewApplication(t) draft := a.settings.live draft.VoiceProfiles.Profiles = []voiceprofiles.Profile{{Name: "Reading", Driver: "speech-dispatcher", Module: "fixture", Rate: 30, Volume: 80}} if err := config.Save(path, draft); err != nil { t.Fatal(err) } - a.open_settings() - receive_ui(t, a.ui) - a.ui.session.Focus_control("voice-profiles", "use") + a.openSettings() + receiveUi(t, a.ui) + a.ui.session.FocusControl("voice-profiles", "use") a.ui.handle(interaction.Key{Name: "enter"}) if got := <-prepared; got.Module != "fixture" { t.Fatal("Use Voice Profile did not preview the module", got) } - finish_preview(t, a, voice) - if got := last_parameters(t, voice); got.Rate != 30 || got.Volume != 80 { + finishPreview(t, a, voice) + if got := lastParameters(t, voice); got.Rate != 30 || got.Volume != 80 { t.Fatal("Use Voice Profile did not preview its numbers", got) } if a.settings.live.Presentation.Speech.Module != "" { @@ -329,5 +329,5 @@ func TestUseVoiceProfilePreviewsWithoutCommittingPrimary(t *testing.T) { if got := <-prepared; got.Module != "" { t.Fatal("menu Cancel did not restore its original module", got) } - finish_preview(t, a, voice) + finishPreview(t, a, voice) } diff --git a/internal/applicationoverrides/codex/codex_test.go b/internal/applicationoverrides/codex/codex_test.go index 38c80c32..d7bc59ca 100644 --- a/internal/applicationoverrides/codex/codex_test.go +++ b/internal/applicationoverrides/codex/codex_test.go @@ -11,7 +11,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func accept_event(t *testing.T, a *Adapter, event Event) { +func acceptEvent(t *testing.T, a *Adapter, event Event) { t.Helper() event.Version, event.Session, event.Epoch = 1, "fixture-session", 1 if err := a.Accept(event); err != nil { @@ -21,21 +21,21 @@ func accept_event(t *testing.T, a *Adapter, event Event) { func TestCompleteChunksDeduplicationHistoryAndStatus(t *testing.T) { a := &Adapter{} - accept_event(t, a, Event{Kind: "status", Status: "working"}) - accept_event(t, a, Event{Kind: "message", ID: "first", Text: "Whole ", Parts: 2}) + acceptEvent(t, a, Event{Kind: "status", Status: "working"}) + acceptEvent(t, a, Event{Kind: "message", ID: "first", Text: "Whole ", Parts: 2}) if frame := a.Observe(screen.Snapshot{}); len(frame.Updates) != 0 { t.Fatal("partial message spoken") } - accept_event(t, a, Event{Kind: "message", ID: "first", Text: "reply", Part: 1, Parts: 2}) + acceptEvent(t, a, Event{Kind: "message", ID: "first", Text: "reply", Part: 1, Parts: 2}) frame := a.Observe(screen.Snapshot{}) if !frame.OwnsPresentation || len(frame.Updates) != 1 || frame.Updates[0].Text != "Whole reply" { t.Fatal(frame) } - accept_event(t, a, Event{Kind: "message", ID: "first", Text: "Whole reply", Parts: 1}) + acceptEvent(t, a, Event{Kind: "message", ID: "first", Text: "Whole reply", Parts: 1}) if len(a.Observe(screen.Snapshot{}).Updates) != 0 { t.Fatal("duplicate spoken") } - accept_event(t, a, Event{Kind: "message", ID: "second", Text: "Old reply", Parts: 1, Baseline: true}) + acceptEvent(t, a, Event{Kind: "message", ID: "second", Text: "Old reply", Parts: 1, Baseline: true}) if len(a.Observe(screen.Snapshot{}).Updates) != 0 { t.Fatal("baseline spoken") } @@ -52,7 +52,7 @@ func TestCompleteChunksDeduplicationHistoryAndStatus(t *testing.T) { if got, _ := a.Command(command.ReadLiveRegion2); got.Text != "Whole reply" { t.Fatal("suspension lost history") } - accept_event(t, a, Event{Kind: "status", Status: "closed"}) + acceptEvent(t, a, Event{Kind: "status", Status: "closed"}) if a.Observe(screen.Snapshot{}).Recognized { t.Fatal("exit retained presentation ownership") } @@ -60,7 +60,7 @@ func TestCompleteChunksDeduplicationHistoryAndStatus(t *testing.T) { func TestRejectInterleavedSessionOutOfOrderAndOversize(t *testing.T) { a := &Adapter{} - accept_event(t, a, Event{Kind: "status", Status: "idle"}) + acceptEvent(t, a, Event{Kind: "status", Status: "idle"}) if err := a.Accept(Event{Version: 1, Epoch: 1, Session: "another-session", Kind: "status", Status: "working"}); err == nil { t.Fatal("another session attached") } @@ -74,8 +74,8 @@ func TestRejectInterleavedSessionOutOfOrderAndOversize(t *testing.T) { func TestConversationSwitchRejectsPreviousFollower(t *testing.T) { a := &Adapter{} - accept_event(t, a, Event{Kind: "status", Status: "working"}) - accept_event(t, a, Event{Kind: "message", ID: "old", Text: "Previous conversation", Parts: 1}) + acceptEvent(t, a, Event{Kind: "status", Status: "working"}) + acceptEvent(t, a, Event{Kind: "message", ID: "old", Text: "Previous conversation", Parts: 1}) if err := a.Accept(Event{Version: 1, Epoch: 2, Session: "new-session", Kind: "status", Status: "idle"}); err != nil { t.Fatal(err) } diff --git a/internal/applicationoverrides/ninjam/ninjam.go b/internal/applicationoverrides/ninjam/ninjam.go index 7bdc2eab..5be74cba 100644 --- a/internal/applicationoverrides/ninjam/ninjam.go +++ b/internal/applicationoverrides/ninjam/ninjam.go @@ -45,7 +45,7 @@ func (a *Adapter) Close() { a.Reset(); a.latest = "" } // PageUp/PageDown browse existing chat. Rebaseline the next redraw instead of // announcing it as incoming traffic. Linux input key codes are protocol data. -func (a *Adapter) Note_key(key uint16) { +func (a *Adapter) NoteKey(key uint16) { if key == 104 || key == 109 { a.historyNavigation = true a.historyAt = time.Now() @@ -100,7 +100,7 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { stable := a.previous.Active && a.previous.Terminal == next.Terminal && a.previous.Generation == next.Generation && a.previous.Rows == next.Rows && a.previous.Cols == next.Cols chatHeight := max(next.Rows/4, 4) chatTop := next.Rows - 2 - chatHeight - focusID, focusText, volumePan := selected_control(next, chatTop) + focusID, focusText, volumePan := selectedControl(next, chatTop) if next.Y == next.Rows-3 { focusID, focusText = "chat", i18n.T("Chat message") frame.Input = &screen.Region{Left: 0, Top: next.Y, Right: next.Cols - 1, Bottom: next.Y} @@ -121,10 +121,10 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { before, after := strings.Fields(a.volumePan), strings.Fields(volumePan) var changed []string if before[0] != after[0] { - changed = append(changed, spoken_volume(after[0])) + changed = append(changed, spokenVolume(after[0])) } if before[1] != after[1] { - changed = append(changed, spoken_pan(after[1])) + changed = append(changed, spokenPan(after[1])) } spoken = strings.Join(changed, " ") } @@ -134,14 +134,14 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { frame.Updates = append(frame.Updates, presentation.Message{Text: instruction}) } - chat := chat_lines(next, chatTop+1, next.Rows-4) + chat := chatLines(next, chatTop+1, next.Rows-4) if stable && len(chat) == 0 && len(a.chat) != 0 { // A transient cleared chat area during redraw is not new history. chat = slices.Clone(a.chat) } historyNavigation := a.historyNavigation && time.Since(a.historyAt) < 2*time.Second if stable && !historyNavigation { - for _, text := range appended_lines(a.chat, chat) { + for _, text := range appendedLines(a.chat, chat) { frame.Updates = append(frame.Updates, presentation.Message{Text: text}) a.latest = text } @@ -194,7 +194,7 @@ func fields(line []rune) []field { return result } -func selected_control(snapshot screen.Snapshot, chatTop int) (string, string, string) { +func selectedControl(snapshot screen.Snapshot, chatTop int) (string, string, string) { if len(snapshot.Attributes) != len(snapshot.Cells) { return "", "", "" } @@ -267,7 +267,7 @@ func selected_control(snapshot screen.Snapshot, chatTop int) (string, string, st default: if parts := strings.Fields(value); len(parts) == 2 && strings.HasSuffix(parts[0], "dB") { volumePan = value - value = i18n.Format("Volume and pan {0}", spoken_volume(parts[0])+" "+spoken_pan(parts[1])) + value = i18n.Format("Volume and pan {0}", spokenVolume(parts[0])+" "+spokenPan(parts[1])) } if len(controls) >= 5 && index == 0 { value = i18n.Format("Channel name {0}", value) @@ -295,7 +295,7 @@ func selected_control(snapshot screen.Snapshot, chatTop int) (string, string, st } // Keep signs and pan directions audible regardless of the punctuation profile. -func spoken_volume(value string) string { +func spokenVolume(value string) string { if strings.HasPrefix(value, "-") { return i18n.Format("minus {0}", value[1:]) } @@ -305,7 +305,7 @@ func spoken_volume(value string) string { return value } -func spoken_pan(value string) string { +func spokenPan(value string) string { if value == "center" { return i18n.T("center") } @@ -318,7 +318,7 @@ func spoken_pan(value string) string { return value } -func chat_lines(snapshot screen.Snapshot, first, last int) []string { +func chatLines(snapshot screen.Snapshot, first, last int) []string { var result []string previousFull := false for row := first; row <= last; row++ { @@ -338,7 +338,7 @@ func chat_lines(snapshot screen.Snapshot, first, last int) []string { return result } -func appended_lines(previous, next []string) []string { +func appendedLines(previous, next []string) []string { if slices.Equal(previous, next) { return nil } diff --git a/internal/applicationoverrides/ninjam/ninjam_test.go b/internal/applicationoverrides/ninjam/ninjam_test.go index 319d531d..090a0001 100644 --- a/internal/applicationoverrides/ninjam/ninjam_test.go +++ b/internal/applicationoverrides/ninjam/ninjam_test.go @@ -87,7 +87,7 @@ func TestControlsHaveContextAndState(t *testing.T) { func TestFocusChatMetersAndValueReflow(t *testing.T) { a := &ninjam.Adapter{} r := reader.New() - update := func(s screen.Snapshot) []string { return texts(r.Update_application(s, a.Observe(s))) } + update := func(s screen.Snapshot) []string { return texts(r.UpdateApplication(s, a.Observe(s))) } update(snapshot(0, " ", "0.0dB center", " first")) got := update(snapshot(1, " ", "0.0dB center", " first", " second")) if !slices.Equal(got, []string{"Master Volume and pan 0.0dB center", " second"}) { @@ -115,13 +115,13 @@ func TestReviewResumesOnlyOnApplicationNavigation(t *testing.T) { for _, direct := range []bool{false, true} { a, r := &ninjam.Adapter{}, reader.New() s := snapshot(0, " ", "0.0dB center", " old") - r.Update_application(s, a.Observe(s)) + r.UpdateApplication(s, a.Observe(s)) r.Command(command.CurrentLine) if direct { - r.Note_input(true, false, false) + r.NoteInput(true, false, false) } s = snapshot(1, " ", "0.0dB center", " old", " new") - got := texts(r.Update_application(s, a.Observe(s))) + got := texts(r.UpdateApplication(s, a.Observe(s))) want := []string{" new"} if direct { want = append([]string{"Master Volume and pan 0.0dB center"}, want...) @@ -139,7 +139,7 @@ func TestChatScrollPagingRepetitionAndResize(t *testing.T) { if got := texts(frame.Updates); !slices.Equal(got, []string{" d"}) { t.Fatal("repeated message", got) } - a.Note_key(104) + a.NoteKey(104) // An interval update can arrive before the application's history redraw. a.Observe(snapshot(0, " ", "0.0dB center", " b", " c", " d", " d")) frame = a.Observe(snapshot(0, " ", "0.0dB center", " old", " b", " c", " d")) @@ -161,19 +161,19 @@ func TestChatAlongsideTypingAndMutedAutomaticReading(t *testing.T) { a, r := &ninjam.Adapter{}, reader.New() s := snapshot(-1, " ", "0.0dB center", " old") s.Y = 21 - r.Update_application(s, a.Observe(s)) - r.Note_input(true, true, false) + r.UpdateApplication(s, a.Observe(s)) + r.NoteInput(true, true, false) s = snapshot(-1, " ", "0.0dB center", " old", " incoming") s.Y, s.X = 21, 1 s.Line(21)[0] = 'a' - got := texts(r.Update_application(s, a.Observe(s))) + got := texts(r.UpdateApplication(s, a.Observe(s))) if !slices.Equal(got, []string{"a", " incoming"}) { t.Fatal(got) } r.Configure(false, true) s = snapshot(-1, " ", "0.0dB center", " incoming", " silent") s.Y = 21 - if got := texts(r.Update_application(s, a.Observe(s))); len(got) != 0 { + if got := texts(r.UpdateApplication(s, a.Observe(s))); len(got) != 0 { t.Fatal(got) } if result, _ := a.Command(command.ReadLiveRegion1); result.Text != " silent" { @@ -269,7 +269,7 @@ func TestVolumeAndPanAnnounceOnlyChangedComponent(t *testing.T) { } update := func(value string, chat ...string) []string { s := makeSnapshot(value, chat...) - return texts(r.Update_application(s, a.Observe(s))) + return texts(r.UpdateApplication(s, a.Observe(s))) } update("0.0dB center", " old") for _, trial := range []struct{ value, want string }{ diff --git a/internal/applicationoverrides/rogue/rogue.go b/internal/applicationoverrides/rogue/rogue.go index 3ec92dee..bda3ab13 100644 --- a/internal/applicationoverrides/rogue/rogue.go +++ b/internal/applicationoverrides/rogue/rogue.go @@ -52,13 +52,13 @@ func (a *Adapter) Command(id command.ID) (presentation.CommandResult, bool) { if slot := slices.Index(ids, id); slot >= 0 { regions := a.regions if len(regions) == 0 { - regions = region_names() + regions = regionNames() } return presentation.CommandResult{Text: regions[slot].Read()}, true } if id == command.ListReadingRegions { var entries []string - for slot, region := range region_names() { + for slot, region := range regionNames() { entries = append(entries, i18n.Format("Live region {0}: {1}", strconv.Itoa(slot+1), region.Name)) } return presentation.CommandResult{Text: strings.Join(entries, ". ")}, true @@ -66,7 +66,7 @@ func (a *Adapter) Command(id command.ID) (presentation.CommandResult, bool) { return presentation.CommandResult{}, false } -func region_names() []applicationoverrides.Region { +func regionNames() []applicationoverrides.Region { return []applicationoverrides.Region{ {Name: i18n.T("Health")}, {Name: i18n.T("Status")}, {Name: i18n.T("Latest message")}, {Name: i18n.T("Surroundings")}, @@ -89,12 +89,12 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { options := strings.Contains(next.Text(0), `Terse output ("terse"):`) && strings.Contains(string(next.Cells), `Inventory style ("inven"):`) page := strings.Contains(string(next.Cells), "--Press space to continue--") if options || page && (stable || stats != nil) { - a.regions = region_names() + a.regions = regionNames() a.regions[2].Text = a.latest a.previous, a.dialog = next, true return applicationoverrides.Frame{Recognized: true, Regions: slices.Clone(a.regions)} } - x, y, found := player_position(next) + x, y, found := playerPosition(next) if stats == nil || !found { a.Reset() return applicationoverrides.Frame{} @@ -111,22 +111,22 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { // A visible clear permits the same message to be announced on a later turn. // Messages replaced between captures cannot be recovered from screenshots. a.message = message - regions := region_names() + regions := regionNames() regions[0].Text = i18n.Format("{0} of {1}", stats[3], stats[4]) regions[1].Text = strings.TrimSpace(next.Text(23)) regions[2].Text = a.latest regions[3].Text = surroundings(next, x, y) - entities := visible_entities(next) + entities := visibleEntities(next) var monsters, objects []string for _, item := range entities { text := describe(item, x, y) - if is_monster(item.glyph) { + if isMonster(item.glyph) { monsters = append(monsters, text) } else { objects = append(objects, text) } } - regions[4].Text, regions[5].Text = join_entities(monsters), join_entities(objects) + regions[4].Text, regions[5].Text = joinEntities(monsters), joinEntities(objects) if !stable || len(a.stats) == 0 { frame.Updates = append(frame.Updates, presentation.Message{Text: regions[0].Read()}) if stats[10] != "" { @@ -160,16 +160,16 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { if stable && !a.dialog && len(a.stats) != 0 && stats[1] == a.stats[1] { counts := map[rune]int{} for _, item := range a.entities { - if is_monster(item.glyph) { + if isMonster(item.glyph) { counts[item.glyph]++ } } for _, item := range entities { - if is_monster(item.glyph) && counts[item.glyph] > 0 { + if isMonster(item.glyph) && counts[item.glyph] > 0 { counts[item.glyph]-- continue } - if !is_monster(item.glyph) && slices.Contains(a.entities, item) { + if !isMonster(item.glyph) && slices.Contains(a.entities, item) { continue } frame.Updates = append(frame.Updates, presentation.Message{Text: describe(item, x, y)}) @@ -181,7 +181,7 @@ func (a *Adapter) Observe(next screen.Snapshot) applicationoverrides.Frame { return frame } -func player_position(s screen.Snapshot) (int, int, bool) { +func playerPosition(s screen.Snapshot) (int, int, bool) { x, y := -1, -1 for row := 1; row <= mapBottom; row++ { for col, glyph := range s.Line(row)[:80] { @@ -196,13 +196,13 @@ func player_position(s screen.Snapshot) (int, int, bool) { return x, y, x >= 0 } -func is_monster(glyph rune) bool { return glyph >= 'A' && glyph <= 'Z' } +func isMonster(glyph rune) bool { return glyph >= 'A' && glyph <= 'Z' } -func visible_entities(s screen.Snapshot) []entity { +func visibleEntities(s screen.Snapshot) []entity { var result []entity for y := 1; y <= mapBottom; y++ { for x, glyph := range s.Line(y)[:80] { - if is_monster(glyph) || strings.ContainsRune("+^%*!?$:)],=/", glyph) { + if isMonster(glyph) || strings.ContainsRune("+^%*!?$:)],=/", glyph) { result = append(result, entity{x, y, glyph}) } } @@ -210,7 +210,7 @@ func visible_entities(s screen.Snapshot) []entity { return result } -func join_entities(items []string) string { +func joinEntities(items []string) string { if len(items) == 0 { return i18n.T("None visible") } @@ -243,12 +243,12 @@ func describe(item entity, x, y int) string { if item.x > x { offsets = append(offsets, i18n.Format("east {0}", strconv.Itoa(item.x-x))) } - return i18n.Format("{0}, {1}", glyph_name(item.glyph), strings.Join(offsets, ", ")) + return i18n.Format("{0}, {1}", glyphName(item.glyph), strings.Join(offsets, ", ")) } -func glyph_name(glyph rune) string { +func glyphName(glyph rune) string { // These are Rogue's own English monster names, rather than Fenrir labels. - if is_monster(glyph) { + if isMonster(glyph) { return []string{"aquator", "bat", "centaur", "dragon", "emu", "venus flytrap", "griffin", "hobgoblin", "ice monster", "jabberwock", "kestrel", "leprechaun", "medusa", "nymph", "orc", "phantom", "quagga", "rattlesnake", "snake", "troll", "black unicorn", "vampire", "wraith", "xeroc", "yeti", "zombie"}[glyph-'A'] } switch glyph { diff --git a/internal/applicationoverrides/rogue/rogue_test.go b/internal/applicationoverrides/rogue/rogue_test.go index c9b71df6..1f42078c 100644 --- a/internal/applicationoverrides/rogue/rogue_test.go +++ b/internal/applicationoverrides/rogue/rogue_test.go @@ -80,7 +80,7 @@ func TestNamedRegionsAndVisibleMap(t *testing.T) { func TestMessagesHealthAndHungerWithoutMapChatter(t *testing.T) { a := &rogue.Adapter{} r := reader.New() - update := func(s screen.Snapshot) []string { return texts(r.Update_application(s, a.Observe(s))) } + update := func(s screen.Snapshot) []string { return texts(r.UpdateApplication(s, a.Observe(s))) } update(game(24, 80, "", initialStatus)) if got := update(game(24, 80, "", initialStatus)); len(got) != 0 { t.Fatal("idle chatter", got) @@ -200,14 +200,14 @@ func TestDialogsAndContextBoundaries(t *testing.T) { func TestRawReviewStillReadsActualMap(t *testing.T) { a, r := &rogue.Adapter{}, reader.New() s := game(24, 80, "", initialStatus) - r.Update_application(s, a.Observe(s)) + r.UpdateApplication(s, a.Observe(s)) if got := r.Command(command.CurrentLine); !strings.Contains(got.Text, "@") { t.Fatal(got) } - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s = game(24, 80, "", initialStatus) s.Line(5)[10], s.Line(5)[11], s.X = '.', '@', 11 - if got := texts(r.Update_application(s, a.Observe(s))); len(got) != 0 { + if got := texts(r.UpdateApplication(s, a.Observe(s))); len(got) != 0 { t.Fatal("movement spoke map", got) } } diff --git a/internal/clipboard/display.go b/internal/clipboard/display.go index eb1031d0..7cdf6134 100644 --- a/internal/clipboard/display.go +++ b/internal/clipboard/display.go @@ -29,9 +29,9 @@ import ( type Target struct{ Display, Authority string } -// Display_candidates never falls through an explicit setting or DISPLAY to a +// DisplayCandidates never falls through an explicit setting or DISPLAY to a // different session. Discovery uses existing local sockets, not a fixed :0..:9. -func Display_candidates(configured, current, authority, home, socketDirectory string) ([]Target, error) { +func DisplayCandidates(configured, current, authority, home, socketDirectory string) ([]Target, error) { if authority == "" { authority = filepath.Join(home, ".Xauthority") } @@ -71,14 +71,14 @@ func Display_candidates(configured, current, authority, home, socketDirectory st return targets, nil } -func system_targets(configured string) ([]Target, error) { +func systemTargets(configured string) ([]Target, error) { home, _ := os.UserHomeDir() if os.Geteuid() == 0 && os.Getenv("SUDO_UID") != "" { if caller, err := user.LookupId(os.Getenv("SUDO_UID")); err == nil { home = caller.HomeDir } } - targets, err := Display_candidates(configured, os.Getenv("DISPLAY"), os.Getenv("XAUTHORITY"), home, "/tmp/.X11-unix") + targets, err := DisplayCandidates(configured, os.Getenv("DISPLAY"), os.Getenv("XAUTHORITY"), home, "/tmp/.X11-unix") if err != nil { return nil, err } diff --git a/internal/clipboard/history.go b/internal/clipboard/history.go index b97a5fc6..51e983f4 100644 --- a/internal/clipboard/history.go +++ b/internal/clipboard/history.go @@ -34,9 +34,9 @@ type History struct { limit int } -func New_history(limit int) *History { return &History{limit: max(1, limit)} } +func NewHistory(limit int) *History { return &History{limit: max(1, limit)} } -func Validate_text(text string) error { +func ValidateText(text string) error { if len(text) > MaxBytes || !utf8.ValidString(text) { return fmt.Errorf("clipboard text must be valid UTF-8 and at most 4 MiB") } @@ -44,7 +44,7 @@ func Validate_text(text string) error { } func (h *History) Add(text string) error { - if err := Validate_text(text); err != nil { + if err := ValidateText(text); err != nil { return err } h.entries = append([]string{text}, h.entries[:min(len(h.entries), h.limit-1)]...) @@ -64,11 +64,11 @@ func (h *History) Move(delta int) { h.index = (h.index + delta + len(h.entries)) % len(h.entries) } } -func (h *History) First() { h.index = 0 } -func (h *History) Last() { h.index = max(0, len(h.entries)-1) } -func (h *History) At_first() bool { return len(h.entries) > 0 && h.index == 0 } -func (h *History) At_last() bool { return len(h.entries) > 0 && h.index == len(h.entries)-1 } -func (h *History) Clear() { h.entries, h.index = nil, 0 } +func (h *History) First() { h.index = 0 } +func (h *History) Last() { h.index = max(0, len(h.entries)-1) } +func (h *History) AtFirst() bool { return len(h.entries) > 0 && h.index == 0 } +func (h *History) AtLast() bool { return len(h.entries) > 0 && h.index == len(h.entries)-1 } +func (h *History) Clear() { h.entries, h.index = nil, 0 } // Refresh adopts shared entries while retaining this reader's selected copy. // Count duplicates from the oldest end so a new identical copy stays distinct. diff --git a/internal/clipboard/history_test.go b/internal/clipboard/history_test.go index f6fc85d0..3419b9ab 100644 --- a/internal/clipboard/history_test.go +++ b/internal/clipboard/history_test.go @@ -27,18 +27,18 @@ import ( ) func TestHistoryLimitUnicodeWrappingAndClear(t *testing.T) { - history := New_history(2) + history := NewHistory(2) for _, text := range []string{"old", "é界\nnext", "new"} { if err := history.Add(text); err != nil { t.Fatal(err) } } history.Move(-1) - if text, ok := history.Current(); !ok || text != "é界\nnext" || !history.At_last() { + if text, ok := history.Current(); !ok || text != "é界\nnext" || !history.AtLast() { t.Fatal(text, ok) } history.Move(1) - if text, _ := history.Current(); text != "new" || !history.At_first() { + if text, _ := history.Current(); text != "new" || !history.AtFirst() { t.Fatal(text) } history.Last() @@ -60,7 +60,7 @@ func TestHistoryLimitUnicodeWrappingAndClear(t *testing.T) { func TestDisplaySelectionDoesNotFallThroughAndDiscoversHigherNumbers(t *testing.T) { root := t.TempDir() for _, fixture := range []struct{ configured, current, want string }{{":8", ":7", ":8"}, {"", ":7", ":7"}} { - targets, err := Display_candidates(fixture.configured, fixture.current, "/test/auth", root, "/does-not-exist") + targets, err := DisplayCandidates(fixture.configured, fixture.current, "/test/auth", root, "/does-not-exist") if err != nil || len(targets) != 1 || targets[0] != (Target{fixture.want, "/test/auth"}) { t.Fatal(targets, err) } @@ -73,7 +73,7 @@ func TestDisplaySelectionDoesNotFallThroughAndDiscoversHigherNumbers(t *testing. if err := os.WriteFile(filepath.Join(root, "X3"), nil, 0600); err != nil { t.Fatal(err) } - targets, err := Display_candidates("", "", "", root, root) + targets, err := DisplayCandidates("", "", "", root, root) if err != nil || len(targets) != 1 || targets[0].Display != ":42" { t.Fatal(targets, err) } @@ -82,7 +82,7 @@ func TestDisplaySelectionDoesNotFallThroughAndDiscoversHigherNumbers(t *testing. t.Fatal(err) } defer other.Close() - if _, err := Display_candidates("", "", "", root, root); err == nil { + if _, err := DisplayCandidates("", "", "", root, root); err == nil { t.Fatal("silently chose among multiple desktops") } } @@ -91,32 +91,32 @@ func TestFileRoundTripBoundsPrivacyAndNonregularInput(t *testing.T) { root := t.TempDir() path := filepath.Join(root, "clipboard") text := "é界\nsecond line\n" - if err := write_file(path, text); err != nil { + if err := writeFile(path, text); err != nil { t.Fatal(err) } - if got, err := read_file(path); err != nil || got != text { + if got, err := readFile(path); err != nil || got != text { t.Fatal(got, err) } info, err := os.Stat(path) if err != nil || info.Mode().Perm() != 0600 { t.Fatal(info, err) } - if err := write_file(path, strings.Repeat("x", MaxBytes+1)); err == nil { + if err := writeFile(path, strings.Repeat("x", MaxBytes+1)); err == nil { t.Fatal("oversize export accepted") } - if got, _ := read_file(path); got != text { + if got, _ := readFile(path); got != text { t.Fatal("failed export changed original") } if err := syscall.Mkfifo(filepath.Join(root, "fifo"), 0600); err != nil { t.Fatal(err) } - if _, err := read_file(filepath.Join(root, "fifo")); err == nil { + if _, err := readFile(filepath.Join(root, "fifo")); err == nil { t.Fatal("FIFO accepted") } if err := os.WriteFile(path, []byte{0xff}, 0600); err != nil { t.Fatal(err) } - if _, err := read_file(path); err == nil { + if _, err := readFile(path); err == nil { t.Fatal("invalid UTF-8 imported") } } diff --git a/internal/clipboard/persistence.go b/internal/clipboard/persistence.go index 4991e3cf..4f865140 100644 --- a/internal/clipboard/persistence.go +++ b/internal/clipboard/persistence.go @@ -25,7 +25,7 @@ type Snapshot struct { Selected int `json:"selected"` } -func History_path(home string, terminalMode bool) string { +func HistoryPath(home string, terminalMode bool) string { if terminalMode { return filepath.Join(home, ".local/state/fenrir/clipboard/terminal.json") } @@ -36,13 +36,13 @@ func (h *History) Snapshot() Snapshot { return Snapshot{Version: 1, Entries: append([]string{}, h.entries...), Selected: h.index} } -func validate_snapshot(state Snapshot) error { +func validateSnapshot(state Snapshot) error { if state.Version != 1 || len(state.Entries) > 10000 || state.Selected < 0 || (len(state.Entries) == 0 && state.Selected != 0) || (len(state.Entries) > 0 && state.Selected >= len(state.Entries)) { return fmt.Errorf("invalid clipboard history") } total := 0 for _, text := range state.Entries { - if err := Validate_text(text); err != nil { + if err := ValidateText(text); err != nil { return err } total += len(text) @@ -54,7 +54,7 @@ func validate_snapshot(state Snapshot) error { } func (h *History) Restore(state Snapshot) error { - if err := validate_snapshot(state); err != nil { + if err := validateSnapshot(state); err != nil { return err } h.entries = append([]string(nil), state.Entries[:min(len(state.Entries), h.limit)]...) @@ -70,8 +70,8 @@ func (h *History) Resize(limit int) { // A stable lock inode serializes only individual transactions. Closing it // releases ownership; another reader can immediately read, update or clear. -func acquire_history(path string, create bool) (*os.File, error) { - if err := private_directory(filepath.Dir(path), create); err != nil { +func acquireHistory(path string, create bool) (*os.File, error) { + if err := privateDirectory(filepath.Dir(path), create); err != nil { if !create && errors.Is(err, os.ErrNotExist) { return nil, nil } @@ -95,7 +95,7 @@ func acquire_history(path string, create bool) (*os.File, error) { err = nil } if err == nil { - err = remove_temporary_history(path) + err = removeTemporaryHistory(path) } if err != nil { file.Close() @@ -104,7 +104,7 @@ func acquire_history(path string, create bool) (*os.File, error) { return file, nil } -func private_directory(path string, create bool) error { +func privateDirectory(path string, create bool) error { if create { if err := os.MkdirAll(path, 0700); err != nil { return err @@ -120,9 +120,9 @@ func private_directory(path string, create bool) error { return nil } -func load_history(path string) (Snapshot, error) { +func loadHistory(path string) (Snapshot, error) { empty := Snapshot{Version: 1} - if err := private_directory(filepath.Dir(path), false); err != nil { + if err := privateDirectory(filepath.Dir(path), false); err != nil { if errors.Is(err, os.ErrNotExist) { return empty, nil } @@ -154,14 +154,14 @@ func load_history(path string) (Snapshot, error) { if err := json.Unmarshal(data, &state); err != nil { return empty, fmt.Errorf("invalid clipboard history JSON") } - if err := validate_snapshot(state); err != nil { + if err := validateSnapshot(state); err != nil { return empty, err } return state, nil } -func save_history(path string, state Snapshot) error { - if err := validate_snapshot(state); err != nil { +func saveHistory(path string, state Snapshot) error { + if err := validateSnapshot(state); err != nil { return err } data, err := json.Marshal(state) @@ -171,7 +171,7 @@ func save_history(path string, state Snapshot) error { if len(data) > maxHistoryBytes { return fmt.Errorf("clipboard history exceeds 64 MiB") } - if err := private_directory(filepath.Dir(path), true); err != nil { + if err := privateDirectory(filepath.Dir(path), true); err != nil { return err } // Do not replace symlinks, devices or directories supplied at the destination. @@ -186,7 +186,8 @@ func save_history(path string, state Snapshot) error { if err != nil { return err } - defer os.Remove(file.Name()) + // After a successful rename the temporary name no longer exists. + defer func() { _ = os.Remove(file.Name()) }() _, writeErr := file.Write(data) err = errors.Join(writeErr, file.Sync(), file.Close()) if err != nil { @@ -195,11 +196,11 @@ func save_history(path string, state Snapshot) error { if err := os.Rename(file.Name(), path); err != nil { return err } - return sync_directory(filepath.Dir(path)) + return syncDirectory(filepath.Dir(path)) } -func remove_history(path string) error { - if err := private_directory(filepath.Dir(path), false); err != nil { +func removeHistory(path string) error { + if err := privateDirectory(filepath.Dir(path), false); err != nil { if errors.Is(err, os.ErrNotExist) { return nil } @@ -212,10 +213,10 @@ func remove_history(path string) error { if err != nil { return err } - return sync_directory(filepath.Dir(path)) + return syncDirectory(filepath.Dir(path)) } -func sync_directory(path string) error { +func syncDirectory(path string) error { dir, err := os.Open(path) if err != nil { return err @@ -225,7 +226,7 @@ func sync_directory(path string) error { // A killed process can leave an atomic-write temporary file. Only clean this // history's own files after acquiring its lock, including when clearing it. -func remove_temporary_history(path string) error { +func removeTemporaryHistory(path string) error { entries, err := os.ReadDir(filepath.Dir(path)) if err != nil { return err diff --git a/internal/clipboard/persistence_test.go b/internal/clipboard/persistence_test.go index e26d8397..de9f67ab 100644 --- a/internal/clipboard/persistence_test.go +++ b/internal/clipboard/persistence_test.go @@ -17,14 +17,14 @@ import ( func TestPersistentHistoryRoundTripResizeAndPrivateModes(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") - history := New_history(3) + history := NewHistory(3) for _, text := range []string{"old", "é界\nsecond line", "🎃"} { if err := history.Add(text); err != nil { t.Fatal(err) } } history.Move(1) - store := New_persistence(path, false) + store := NewPersistence(path, false) store.Enable(history.Snapshot(), 3) if err := store.Close(); err != nil { t.Fatal(err) @@ -35,15 +35,15 @@ func TestPersistentHistoryRoundTripResizeAndPrivateModes(t *testing.T) { t.Fatal(info, err) } } - store = New_persistence(path, true) + store = NewPersistence(path, true) if store.LoadErr != nil { t.Fatal(store.LoadErr) } - restored := New_history(2) + restored := NewHistory(2) if err := restored.Restore(store.Initial); err != nil { t.Fatal(err) } - if got, _ := restored.Current(); got != "é界\nsecond line" || !restored.At_last() { + if got, _ := restored.Current(); got != "é界\nsecond line" || !restored.AtLast() { t.Fatal(got) } if err := store.Close(); err != nil { @@ -62,11 +62,11 @@ func TestPersistentHistoryRoundTripResizeAndPrivateModes(t *testing.T) { func TestPersistenceDisabledDoesNotReadOrCreateAndModesAreSeparate(t *testing.T) { home := t.TempDir() - terminalPath := History_path(home, true) - if !strings.HasPrefix(terminalPath, home+string(os.PathSeparator)) || History_path(home, false) != "/var/lib/fenrir/clipboard/tty.json" || terminalPath == History_path(home, false) { - t.Fatal(terminalPath, History_path(home, false)) + terminalPath := HistoryPath(home, true) + if !strings.HasPrefix(terminalPath, home+string(os.PathSeparator)) || HistoryPath(home, false) != "/var/lib/fenrir/clipboard/tty.json" || terminalPath == HistoryPath(home, false) { + t.Fatal(terminalPath, HistoryPath(home, false)) } - store := New_persistence(terminalPath, false) + store := NewPersistence(terminalPath, false) if store.LoadErr != nil || len(store.Initial.Entries) != 0 { t.Fatal(store) } @@ -79,7 +79,7 @@ func TestPersistenceDisabledDoesNotReadOrCreateAndModesAreSeparate(t *testing.T) // A pre-existing malformed file is also ignored while disabled. path := filepath.Join(home, "malformed.json") os.WriteFile(path, []byte("not json"), 0600) - store = New_persistence(path, false) + store = NewPersistence(path, false) if store.LoadErr != nil { t.Fatal("disabled persistence read a file", store.LoadErr) } @@ -89,7 +89,7 @@ func TestPersistenceDisabledDoesNotReadOrCreateAndModesAreSeparate(t *testing.T) func TestPersistenceClearWinsOverQueuedWritesAndQuitFlushes(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "clipboard.json") state := Snapshot{Version: 1, Entries: []string{"first"}} - store := New_persistence(path, false) + store := NewPersistence(path, false) store.Enable(state, 200) deadline := time.Now().Add(time.Second) for { @@ -111,12 +111,12 @@ func TestPersistenceClearWinsOverQueuedWritesAndQuitFlushes(t *testing.T) { if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { t.Fatal("old write resurrected cleared history", err) } - store = New_persistence(path, false) + store = NewPersistence(path, false) store.Enable(state, 200) if err := store.Close(); err != nil { t.Fatal(err) } - got, err := load_history(path) + got, err := loadHistory(path) if err != nil || !reflect.DeepEqual(got, state) { t.Fatal("quit did not flush newest state", got, err) } @@ -129,7 +129,7 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) { } path := filepath.Join(root, "history.json") for _, data := range [][]byte{ - []byte("not JSON"), []byte{0xff}, + []byte("not JSON"), {0xff}, []byte(`{"version":2,"entries":[],"selected":0}`), []byte(`{"version":1,"entries":["word"],"selected":2}`), []byte(`{"version":1,"entries":[],"selected":-1}`), @@ -137,18 +137,18 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) { if err := os.WriteFile(path, data, 0600); err != nil { t.Fatal(err) } - if _, err := load_history(path); err == nil { + if _, err := loadHistory(path); err == nil { t.Fatal("invalid snapshot accepted") } } state := Snapshot{Version: 1, Entries: []string{"word"}} - if err := save_history(path, state); err != nil { + if err := saveHistory(path, state); err != nil { t.Fatal(err) } if err := os.Chmod(path, 0644); err != nil { t.Fatal(err) } - if _, err := load_history(path); err == nil { + if _, err := loadHistory(path); err == nil { t.Fatal("public file accepted") } os.Chmod(path, 0600) @@ -158,14 +158,14 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) { } file.Truncate(maxHistoryBytes + 1) file.Close() - if _, err := load_history(path); err == nil { + if _, err := loadHistory(path); err == nil { t.Fatal("oversized file accepted") } - if err := save_history(path, state); err != nil { + if err := saveHistory(path, state); err != nil { t.Fatal(err) } before, _ := os.ReadFile(path) - if err := save_history(path, Snapshot{Version: 1, Entries: []string{strings.Repeat("x", MaxBytes+1)}}); err == nil { + if err := saveHistory(path, Snapshot{Version: 1, Entries: []string{strings.Repeat("x", MaxBytes+1)}}); err == nil { t.Fatal("oversized entry saved") } after, _ := os.ReadFile(path) @@ -176,22 +176,22 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) { if err := os.Symlink(path, link); err != nil { t.Fatal(err) } - if _, err := load_history(link); err == nil { + if _, err := loadHistory(link); err == nil { t.Fatal("symlink read") } - if err := save_history(link, state); err == nil { + if err := saveHistory(link, state); err == nil { t.Fatal("symlink replaced") } fifo := filepath.Join(root, "fifo") if err := syscall.Mkfifo(fifo, 0600); err != nil { t.Fatal(err) } - if _, err := load_history(fifo); err == nil { + if _, err := loadHistory(fifo); err == nil { t.Fatal("FIFO accepted") } public := filepath.Join(root, "public") os.Mkdir(public, 0755) - if err := save_history(filepath.Join(public, "history.json"), state); err == nil { + if err := saveHistory(filepath.Join(public, "history.json"), state); err == nil { t.Fatal("public directory accepted") } var decoded Snapshot @@ -213,7 +213,7 @@ func TestClearRemovesTemporaryHistoryLeftByInterruptedWrite(t *testing.T) { t.Fatal(err) } } - store := New_persistence(path, false) + store := NewPersistence(path, false) store.Clear() if err := store.Close(); err != nil { t.Fatal(err) @@ -228,15 +228,15 @@ func TestClearRemovesTemporaryHistoryLeftByInterruptedWrite(t *testing.T) { func TestPersistenceRetriesAfterHistoryLockTimeout(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") - lock, err := acquire_history(path, true) + lock, err := acquireHistory(path, true) if err != nil { t.Fatal(err) } defer lock.Close() - if err := save_history(path, Snapshot{Version: 1, Entries: []string{"shared"}}); err != nil { + if err := saveHistory(path, Snapshot{Version: 1, Entries: []string{"shared"}}); err != nil { t.Fatal(err) } - store := New_persistence(path, true) + store := NewPersistence(path, true) defer store.Close() if !errors.Is(store.LoadErr, syscall.EWOULDBLOCK) { t.Fatalf("expected startup lock contention, got %v", store.LoadErr) @@ -268,10 +268,10 @@ func TestPersistenceRetriesAfterHistoryLockTimeout(t *testing.T) { func TestEnableMergePreservesSavedSelection(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") state := Snapshot{Version: 1, Entries: []string{"newer", "selected"}, Selected: 1} - if err := save_history(path, state); err != nil { + if err := saveHistory(path, state); err != nil { t.Fatal(err) } - update, err := apply_history(path, historyJob{action: "enable", state: Snapshot{Version: 1, Entries: []string{"retained"}}, limit: 10}) + update, err := applyHistory(path, historyJob{action: "enable", state: Snapshot{Version: 1, Entries: []string{"retained"}}, limit: 10}) if err != nil { t.Fatal(err) } diff --git a/internal/clipboard/shared_history.go b/internal/clipboard/shared_history.go index 88671fdb..c7fd1e43 100644 --- a/internal/clipboard/shared_history.go +++ b/internal/clipboard/shared_history.go @@ -48,14 +48,14 @@ type Persistence struct { lastErr error } -func New_persistence(path string, load bool) *Persistence { +func NewPersistence(path string, load bool) *Persistence { p := &Persistence{Initial: Snapshot{Version: 1}, InitialEnabled: load, wake: make(chan struct{}, 1), errors: make(chan error, 1), updates: make(chan HistoryUpdate, 1), done: make(chan struct{})} if load { - file, err := acquire_history(path, false) + file, err := acquireHistory(path, false) if err == nil { - p.InitialEnabled, err = persistence_enabled(file) + p.InitialEnabled, err = persistenceEnabled(file) if err == nil && p.InitialEnabled { - p.Initial, err = load_history(path) + p.Initial, err = loadHistory(path) } if file != nil { file.Close() @@ -121,7 +121,7 @@ func (p *Persistence) report(err error) { p.lastErr = err if err != nil { select { - case <-p.errors: + case _ = <-p.errors: // Keep only the newest error. default: } p.errors <- err @@ -146,7 +146,7 @@ func (p *Persistence) run(path string, watching bool) { p.jobs = nil p.mutex.Unlock() for _, job := range jobs { - update, err := apply_history(path, job) + update, err := applyHistory(path, job) acknowledged = job.sequence p.report(err) if job.action == "enable" { @@ -167,16 +167,16 @@ func (p *Persistence) run(path string, watching bool) { if !watching { continue } - nextSignature := history_signature(path) + nextSignature := historySignature(path) if nextSignature == signature && !retryLock { continue } - file, err := acquire_history(path, false) + file, err := acquireHistory(path, false) update := HistoryUpdate{State: Snapshot{Version: 1}, Sequence: acknowledged} if err == nil { - update.Enabled, err = persistence_enabled(file) + update.Enabled, err = persistenceEnabled(file) if err == nil && update.Enabled { - update.State, err = load_history(path) + update.State, err = loadHistory(path) } if file != nil { file.Close() @@ -210,7 +210,7 @@ func (p *Persistence) publish(update HistoryUpdate) { p.updates <- update } -func history_signature(path string) string { +func historySignature(path string) string { result := "" for _, name := range []string{path, path + ".lock"} { info, err := os.Lstat(name) @@ -226,7 +226,7 @@ func history_signature(path string) string { // The empty original lock file means enabled. One metadata byte coordinates // disabling without retaining clipboard text or resurrecting a deleted file. -func persistence_enabled(file *os.File) (bool, error) { +func persistenceEnabled(file *os.File) (bool, error) { if file == nil { return true, nil } @@ -244,7 +244,7 @@ func persistence_enabled(file *os.File) (bool, error) { return value[0] == '1', nil } -func set_persistence_enabled(file *os.File, enabled bool) error { +func setPersistenceEnabled(file *os.File, enabled bool) error { value := []byte("0") if enabled { value[0] = '1' @@ -253,36 +253,36 @@ func set_persistence_enabled(file *os.File, enabled bool) error { return errors.Join(err, file.Sync()) } -func apply_history(path string, job historyJob) (HistoryUpdate, error) { +func applyHistory(path string, job historyJob) (HistoryUpdate, error) { result := HistoryUpdate{State: Snapshot{Version: 1}} create := job.action == "enable" || job.action == "add" || job.action == "disable" - file, err := acquire_history(path, create) + file, err := acquireHistory(path, create) if err != nil { return result, err } if file != nil { defer file.Close() } - result.Enabled, err = persistence_enabled(file) + result.Enabled, err = persistenceEnabled(file) if err != nil { return result, err } switch job.action { case "clear", "disable": if job.action == "disable" { - if err := set_persistence_enabled(file, false); err != nil { + if err := setPersistenceEnabled(file, false); err != nil { return result, err } result.Enabled = false } - return result, remove_history(path) + return result, removeHistory(path) case "enable": - if err := validate_snapshot(job.state); err != nil { + if err := validateSnapshot(job.state); err != nil { return result, err } // Enabling deliberately saves retained memory, but preserves newer shared // entries when another reader already has an active saved history. - state, err := load_history(path) + state, err := loadHistory(path) if err != nil { return result, err } @@ -304,16 +304,16 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) { } } } - result.State = trim_history(state, job.limit) + result.State = trimHistory(state, job.limit) if len(result.State.Entries) > 0 { - err = save_history(path, result.State) + err = saveHistory(path, result.State) } else { - err = remove_history(path) + err = removeHistory(path) } if err != nil { return result, err } - if err := set_persistence_enabled(file, true); err != nil { + if err := setPersistenceEnabled(file, true); err != nil { return result, err } result.Enabled = true @@ -322,13 +322,13 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) { if !result.Enabled { return result, nil } - result.State, err = load_history(path) + result.State, err = loadHistory(path) if err != nil { return result, err } switch job.action { case "add": - if err := Validate_text(job.text); err != nil { + if err := ValidateText(job.text); err != nil { return result, err } if job.imported && len(result.State.Entries) > 0 && result.State.Entries[0] == job.text { @@ -336,11 +336,11 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) { } result.State.Entries = append([]string{job.text}, result.State.Entries...) result.State.Selected = 0 - result.State = trim_history(result.State, job.limit) + result.State = trimHistory(result.State, job.limit) case "select": // Navigation cannot recreate entries removed by another reader. if job.state.Selected < len(job.state.Entries) && job.state.Selected >= 0 { - history := New_history(10000) + history := NewHistory(10000) if err := history.Restore(job.state); err != nil { return result, err } @@ -350,15 +350,15 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) { result.State.Selected = history.Snapshot().Selected } case "resize": - result.State = trim_history(result.State, job.limit) + result.State = trimHistory(result.State, job.limit) } if len(result.State.Entries) == 0 { return result, nil } - return result, save_history(path, result.State) + return result, saveHistory(path, result.State) } -func trim_history(state Snapshot, limit int) Snapshot { +func trimHistory(state Snapshot, limit int) Snapshot { state.Entries = state.Entries[:min(len(state.Entries), max(1, limit))] state.Selected = min(state.Selected, max(0, len(state.Entries)-1)) return state diff --git a/internal/clipboard/shared_persistence_test.go b/internal/clipboard/shared_persistence_test.go index 15e0d8a3..1a873cd7 100644 --- a/internal/clipboard/shared_persistence_test.go +++ b/internal/clipboard/shared_persistence_test.go @@ -34,7 +34,7 @@ func TestSharedClipboardProcess(t *testing.T) { if path == "" { return } - store := New_persistence(path, true) + store := NewPersistence(path, true) current := sharedReply{State: store.Initial, Enabled: store.InitialEnabled} if store.LoadErr != nil { current.Error = store.LoadErr.Error() @@ -114,7 +114,7 @@ type sharedProcess struct { decoder *json.Decoder } -func start_shared_process(t *testing.T, path string) *sharedProcess { +func startSharedProcess(t *testing.T, path string) *sharedProcess { t.Helper() command := exec.Command(os.Args[0], "-test.run=^TestSharedClipboardProcess$") command.Env = append(os.Environ(), "FENRIR_CLIPBOARD_PROCESS_PATH="+path) @@ -196,7 +196,7 @@ func (p *sharedProcess) await(t *testing.T, entries []string, enabled bool) shar func TestPersistentClipboardSharesAcrossProcessesAndClearCannotResurrect(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") - first, second := start_shared_process(t, path), start_shared_process(t, path) + first, second := startSharedProcess(t, path), startSharedProcess(t, path) first.action(t, sharedCommand{Action: "add", Text: "first"}) second.await(t, []string{"first"}, true) second.action(t, sharedCommand{Action: "add", Text: "second"}) @@ -224,7 +224,7 @@ func TestPersistentClipboardSharesAcrossProcessesAndClearCannotResurrect(t *test first.await(t, []string{"retained"}, true) first.action(t, sharedCommand{Action: "quit"}) second.action(t, sharedCommand{Action: "add", Text: "survivor"}) - third := start_shared_process(t, path) + third := startSharedProcess(t, path) third.await(t, []string{"survivor", "retained"}, true) if err := second.command.Process.Kill(); err != nil { t.Fatal(err) @@ -235,7 +235,7 @@ func TestPersistentClipboardSharesAcrossProcessesAndClearCannotResurrect(t *test func TestPersistentClipboardConcurrentProcessCopiesKeepBothUpdates(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") - first, second := start_shared_process(t, path), start_shared_process(t, path) + first, second := startSharedProcess(t, path), startSharedProcess(t, path) var group sync.WaitGroup for _, process := range []*sharedProcess{first, second} { group.Add(1) @@ -247,7 +247,7 @@ func TestPersistentClipboardConcurrentProcessCopiesKeepBothUpdates(t *testing.T) }() } group.Wait() - state, err := load_history(path) + state, err := loadHistory(path) if err != nil || len(state.Entries) != 8 { t.Fatal("lost concurrent copies", state, err) } @@ -263,7 +263,7 @@ func TestPersistentClipboardConcurrentProcessCopiesKeepBothUpdates(t *testing.T) } func TestPersistentClipboardRefreshRetainsLocalSelectionAndDuplicateIdentity(t *testing.T) { - history := New_history(5) + history := NewHistory(5) history.Add("same") history.Add("middle") history.Add("same") @@ -284,7 +284,7 @@ func TestPersistentClipboardRefreshRetainsLocalSelectionAndDuplicateIdentity(t * func TestPersistenceQueuedEnableThenClearStillParticipates(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") - store := New_persistence(path, false) + store := NewPersistence(path, false) store.Enable(Snapshot{Version: 1, Entries: []string{"old"}}, 200) store.Clear() store.Add("fresh", 200) @@ -313,7 +313,7 @@ func TestPersistenceQueuedEnableThenClearStillParticipates(t *testing.T) { func TestPersistenceDuplicateXImportsAreOneEntryButCopiesRemainDistinct(t *testing.T) { path := filepath.Join(t.TempDir(), "private", "terminal.json") - first, second := New_persistence(path, true), New_persistence(path, true) + first, second := NewPersistence(path, true), NewPersistence(path, true) first.Import("shared X text", 200) if err := first.Close(); err != nil { t.Fatal(err) @@ -323,7 +323,7 @@ func TestPersistenceDuplicateXImportsAreOneEntryButCopiesRemainDistinct(t *testi if err := second.Close(); err != nil { t.Fatal(err) } - state, err := load_history(path) + state, err := loadHistory(path) if err != nil || !reflect.DeepEqual(state.Entries, []string{"shared X text", "shared X text"}) { t.Fatal(state, err) } diff --git a/internal/clipboard/worker.go b/internal/clipboard/worker.go index 66574c1d..1d716c70 100644 --- a/internal/clipboard/worker.go +++ b/internal/clipboard/worker.go @@ -64,9 +64,9 @@ type Worker struct { epoch uint64 } -func New_worker(ctx context.Context, paste func(context.Context, string, int) error) *Worker { +func NewWorker(ctx context.Context, paste func(context.Context, string, int) error) *Worker { ctx, cancel := context.WithCancel(ctx) - w := &Worker{jobs: make(chan queuedRequest, 1), results: make(chan Result, 8), ctx: ctx, cancel: cancel, done: make(chan struct{}), targets: system_targets, paste: paste} + w := &Worker{jobs: make(chan queuedRequest, 1), results: make(chan Result, 8), ctx: ctx, cancel: cancel, done: make(chan struct{}), targets: systemTargets, paste: paste} go w.run() return w } @@ -119,9 +119,9 @@ func (w *Worker) run() { result := Result{Request: request} switch request.Command { case command.ImportClipboard: - result.Text, result.Err = read_file(request.Path) + result.Text, result.Err = readFile(request.Path) case command.ExportClipboard: - result.Err = write_file(request.Path, request.Text) + result.Err = writeFile(request.Path, request.Text) case command.PasteClipboard: if ctx.Err() != nil { result.Err = ctx.Err() @@ -167,7 +167,7 @@ func (w *Worker) run() { } } -func read_file(path string) (string, error) { +func readFile(path string) (string, error) { file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK, 0) if err != nil { return "", err @@ -184,18 +184,19 @@ func read_file(path string) (string, error) { if err != nil { return "", err } - return string(data), Validate_text(string(data)) + return string(data), ValidateText(string(data)) } -func write_file(path, text string) error { - if err := Validate_text(text); err != nil { +func writeFile(path, text string) error { + if err := ValidateText(text); err != nil { return err } file, err := os.CreateTemp(filepath.Dir(path), ".fenrir-clipboard-*") if err != nil { return err } - defer os.Remove(file.Name()) + // After a successful rename the temporary name no longer exists. + defer func() { _ = os.Remove(file.Name()) }() _, writeErr := file.WriteString(text) err = errors.Join(writeErr, file.Sync(), file.Close()) if err != nil { diff --git a/internal/clipboard/worker_test.go b/internal/clipboard/worker_test.go index 33e8b4ff..89a1b5e0 100644 --- a/internal/clipboard/worker_test.go +++ b/internal/clipboard/worker_test.go @@ -46,7 +46,7 @@ func TestQueuedPasteCannotStartAfterTargetRetirement(t *testing.T) { func TestActivePasteCancellationDoesNotBlockShutdown(t *testing.T) { started := make(chan struct{}) - worker := New_worker(context.Background(), func(ctx context.Context, text string, terminal int) error { + worker := NewWorker(context.Background(), func(ctx context.Context, text string, terminal int) error { close(started) <-ctx.Done() return ctx.Err() diff --git a/internal/clipboard/xclip.go b/internal/clipboard/xclip.go index ac2bb547..de5484d5 100644 --- a/internal/clipboard/xclip.go +++ b/internal/clipboard/xclip.go @@ -104,7 +104,7 @@ func (x *xClipboard) read(ctx context.Context) (string, error) { } text = string(runes) } - return text, Validate_text(text) + return text, ValidateText(text) } return "", nil // Images, files and unowned selections are ordinary no-data. } @@ -113,7 +113,7 @@ func (x *xClipboard) write(ctx context.Context, text string) error { if text == "" { return fmt.Errorf("clipboard text is empty") } - if err := Validate_text(text); err != nil { + if err := ValidateText(text); err != nil { return err } // The owner outlives this request. Its parent-death signal and Close own @@ -129,14 +129,14 @@ func (x *xClipboard) write(ctx context.Context, text string) error { defer func() { if !accepted { _ = cmd.Process.Kill() - <-done + _ = <-done // Exit status of a killed writer is expected. } }() for { select { case <-ctx.Done(): return ctx.Err() - case <-done: + case _ = <-done: return fmt.Errorf("X clipboard writer exited before acknowledgement") default: } @@ -160,7 +160,7 @@ func (x *xClipboard) write(ctx context.Context, text string) error { func (x *xClipboard) close() { if x.owner != nil { _ = x.owner.Process.Kill() - <-x.ownerDone + _ = <-x.ownerDone // Exit status of a killed owner is expected. x.owner = nil x.ownerDone = nil } diff --git a/internal/config/application.go b/internal/config/application.go index 1c5a2ab1..124777c4 100644 --- a/internal/config/application.go +++ b/internal/config/application.go @@ -14,9 +14,9 @@ import ( "github.com/pelletier/go-toml/v2" ) -// Application_setting admits only settings which can be applied and restored +// ApplicationSetting admits only settings which can be applied and restored // without changing devices, routing, storage, or other process-wide services. -func Application_setting(path string) bool { +func ApplicationSetting(path string) bool { switch path { case "presentation.speech.enabled", "presentation.speech.rate", "presentation.speech.pitch", "presentation.speech.volume", "presentation.speech.module", "presentation.speech.language", "presentation.speech.voice", "presentation.sound.enabled", "presentation.sound.volume", "presentation.progress.enabled", @@ -34,11 +34,11 @@ func Application_setting(path string) bool { return false } -// Open_application_document overlays a sparse, current-schema profile on the +// OpenApplicationDocument overlays a sparse, current-schema profile on the // application's inherited settings. Missing files inherit everything. -func Open_application_document(path string, base Settings) (*Document, error) { +func OpenApplicationDocument(path string, base Settings) (*Document, error) { doc := &Document{Settings: base, path: path, applicationBase: &base, applicationFields: make(map[string]bool)} - data, err := read_document(path) + data, err := readDocument(path) if errors.Is(err, os.ErrNotExist) { return doc, nil } @@ -59,7 +59,7 @@ func Open_application_document(path string, base Settings) (*Document, error) { } continue } - if !Application_setting(path) { + if !ApplicationSetting(path) { return fmt.Errorf("setting %s is not supported in application profiles", path) } doc.applicationFields[path] = true @@ -79,19 +79,19 @@ func Open_application_document(path string, base Settings) (*Document, error) { return doc, nil } -// Apply_application preserves inherited session state for every omitted field. -func (d *Document) Apply_application(base Settings) Settings { +// ApplyApplication preserves inherited session state for every omitted field. +func (d *Document) ApplyApplication(base Settings) Settings { for path := range d.applicationFields { - setting_value(reflect.ValueOf(&base).Elem(), path).Set(setting_value(reflect.ValueOf(d.Settings), path)) + settingValue(reflect.ValueOf(&base).Elem(), path).Set(settingValue(reflect.ValueOf(d.Settings), path)) } return base } -func (d *Document) save_application(settings Settings) error { +func (d *Document) saveApplication(settings Settings) error { fields := make(map[string]any) selectionChanged := false for _, path := range []string{"presentation.speech.module", "presentation.speech.language", "presentation.speech.voice"} { - selectionChanged = selectionChanged || d.applicationFields[path] || !reflect.DeepEqual(setting_value(reflect.ValueOf(settings), path).Interface(), setting_value(reflect.ValueOf(*d.applicationBase), path).Interface()) + selectionChanged = selectionChanged || d.applicationFields[path] || !reflect.DeepEqual(settingValue(reflect.ValueOf(settings), path).Interface(), settingValue(reflect.ValueOf(*d.applicationBase), path).Interface()) } var visit func(reflect.Value, reflect.Value, string) visit = func(value, base reflect.Value, prefix string) { @@ -103,7 +103,7 @@ func (d *Document) save_application(settings Settings) error { continue } speechSelection := selectionChanged && (path == "presentation.speech.module" || path == "presentation.speech.language" || path == "presentation.speech.voice") - if !Application_setting(path) || (!speechSelection && !d.applicationFields[path] && reflect.DeepEqual(child.Interface(), inherited.Interface())) { + if !ApplicationSetting(path) || (!speechSelection && !d.applicationFields[path] && reflect.DeepEqual(child.Interface(), inherited.Interface())) { continue } parts := strings.Split(path, ".") @@ -122,14 +122,14 @@ func (d *Document) save_application(settings Settings) error { if err != nil { return err } - return save_data(d.path, data) + return saveData(d.path, data) } -// Apply_application_settings copies the supported live settings only. Inherited +// ApplyApplicationSettings copies the supported live settings only. Inherited // next-launch choices must never replace the running backend or layout. -func Apply_application_settings(base Settings, source Settings) Settings { +func ApplyApplicationSettings(base Settings, source Settings) Settings { for _, definition := range Definitions() { - if Application_setting(definition.Path) { + if ApplicationSetting(definition.Path) { if err := definition.Set(&base, definition.Value(source)); err != nil { panic(err) } diff --git a/internal/config/application_test.go b/internal/config/application_test.go index 2c87e314..6417b3ef 100644 --- a/internal/config/application_test.go +++ b/internal/config/application_test.go @@ -13,7 +13,7 @@ import ( func TestApplicationDocumentSparseInheritanceAndExplicitValues(t *testing.T) { path := filepath.Join(t.TempDir(), "applications", "ninjam.toml") base := Defaults() - doc, err := Open_application_document(path, base) + doc, err := OpenApplicationDocument(path, base) if err != nil { t.Fatal(err) } @@ -34,7 +34,7 @@ func TestApplicationDocumentSparseInheritanceAndExplicitValues(t *testing.T) { // A new ordinary voice is inherited; explicitly saved rate/echo survive. base.Presentation.Speech.Voice = "New default" base.Presentation.Speech.Rate = 12 - doc, err = Open_application_document(path, base) + doc, err = OpenApplicationDocument(path, base) if err != nil || doc.Settings.Presentation.Speech.Voice != "New default" || !doc.Settings.Keyboard.WordEcho { t.Fatal(doc, err) } @@ -42,14 +42,14 @@ func TestApplicationDocumentSparseInheritanceAndExplicitValues(t *testing.T) { t.Fatal(err) } base.Presentation.Speech.Rate = 60 - doc, err = Open_application_document(path, base) + doc, err = OpenApplicationDocument(path, base) if err != nil || doc.Settings.Presentation.Speech.Rate != 12 { t.Fatal("explicit value equal to previous base lost", doc, err) } session := base session.Presentation.Speech.Enabled = false session.Reading.Automatic = false - effective := doc.Apply_application(session) + effective := doc.ApplyApplication(session) if effective.Presentation.Speech.Enabled || effective.Reading.Automatic || effective.Presentation.Speech.Rate != 12 { t.Fatal("session state overwritten", effective) } @@ -70,14 +70,14 @@ func TestApplicationDocumentRejectsInvalidProfilesAndExternalChanges(t *testing. if err := os.WriteFile(path, []byte(data), 0600); err != nil { t.Fatal(err) } - if _, err := Open_application_document(path, Defaults()); err == nil { + if _, err := OpenApplicationDocument(path, Defaults()); err == nil { t.Fatal("invalid profile accepted", data) } } if err := os.WriteFile(path, []byte("[presentation.speech]\nrate = 10\n"), 0600); err != nil { t.Fatal(err) } - doc, err := Open_application_document(path, Defaults()) + doc, err := OpenApplicationDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -99,7 +99,7 @@ func TestApplicationVoiceSelectionSavedTogether(t *testing.T) { base := Defaults() base.Presentation.Speech.Module = "original-module" base.Presentation.Speech.Language = "en" - doc, err := Open_application_document(path, base) + doc, err := OpenApplicationDocument(path, base) if err != nil { t.Fatal(err) } @@ -110,7 +110,7 @@ func TestApplicationVoiceSelectionSavedTogether(t *testing.T) { } base.Presentation.Speech.Module = "different-module" base.Presentation.Speech.Language = "fr" - doc, err = Open_application_document(path, base) + doc, err = OpenApplicationDocument(path, base) if err != nil || doc.Settings.Presentation.Speech.Module != "original-module" || doc.Settings.Presentation.Speech.Language != "en" || doc.Settings.Presentation.Speech.Voice != "Application voice" { t.Fatal("coupled voice selection changed", doc, err) } diff --git a/internal/config/config.go b/internal/config/config.go index eaba2b31..0baf57ee 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -172,17 +172,17 @@ type Reading struct { } func Defaults() Settings { - return Settings{InternalUI: InternalUI{AnnounceGridCoordinates: true, AnnounceItemPosition: true}, Screen: Screen{IgnoredVTs: []int{}}, Review: Review{LineBreak: true, EndOfScreen: true, LeaveReviewOnCursorChange: true, LeaveReviewOnScreenChange: true}, Prompt: Prompt{ExactMatches: []string{}, CustomPatterns: []string{}}, Version: 3, Presentation: Presentation{DateTime: DateTime{TimeFormat: "locale", DateFormat: "locale"}, Progress: Progress{Enabled: true}, Sound: Sound{Enabled: true, Volume: 0.7, Driver: "pulse", Theme: "default", Device: "default"}, Speech: Speech{Enabled: true, Rate: 0, Volume: 100, Driver: "speech-dispatcher"}}, Keyboard: Keyboard{MultiPressTimeoutMS: int(input.DefaultMultiPressTimeout / time.Millisecond), Layout: "desktop", CharacterEcho: true}, Reading: Reading{Emoticons: true, RepeatedSymbolsMin: 4, Spellcheck: true, SpellcheckSound: true, Attributes: "none", AttributeFormat: presentation.Default_attribute_format, Indentation: "none", RaisePitchForCapitals: true, Automatic: true, CursorEcho: true, Mode: "cursor", PunctuationProfile: "default", PunctuationLevel: "some"}, Clipboard: Clipboard{NumberOfClipboards: 200, ExportPath: "/tmp/fenrirClipboard"}, General: General{ScriptPath: "/usr/share/fenrirscreenreader/scripts", ScriptKeys: []string{"KEY_COMPOSE"}}, Scripts: Scripts{Workers: 2, QueueLimit: 16, OutputBytes: 1 << 20}, Remote: Remote{Enabled: true, EnableCommandRemote: true, EnableSettingsRemote: true}} + return Settings{InternalUI: InternalUI{AnnounceGridCoordinates: true, AnnounceItemPosition: true}, Screen: Screen{IgnoredVTs: []int{}}, Review: Review{LineBreak: true, EndOfScreen: true, LeaveReviewOnCursorChange: true, LeaveReviewOnScreenChange: true}, Prompt: Prompt{ExactMatches: []string{}, CustomPatterns: []string{}}, Version: 3, Presentation: Presentation{DateTime: DateTime{TimeFormat: "locale", DateFormat: "locale"}, Progress: Progress{Enabled: true}, Sound: Sound{Enabled: true, Volume: 0.7, Driver: "pulse", Theme: "default", Device: "default"}, Speech: Speech{Enabled: true, Rate: 0, Volume: 100, Driver: "speech-dispatcher"}}, Keyboard: Keyboard{MultiPressTimeoutMS: int(input.DefaultMultiPressTimeout / time.Millisecond), Layout: "desktop", CharacterEcho: true}, Reading: Reading{Emoticons: true, RepeatedSymbolsMin: 4, Spellcheck: true, SpellcheckSound: true, Attributes: "none", AttributeFormat: presentation.DefaultAttributeFormat, Indentation: "none", RaisePitchForCapitals: true, Automatic: true, CursorEcho: true, Mode: "cursor", PunctuationProfile: "default", PunctuationLevel: "some"}, Clipboard: Clipboard{NumberOfClipboards: 200, ExportPath: "/tmp/fenrirClipboard"}, General: General{ScriptPath: "/usr/share/fenrirscreenreader/scripts", ScriptKeys: []string{"KEY_COMPOSE"}}, Scripts: Scripts{Workers: 2, QueueLimit: 16, OutputBytes: 1 << 20}, Remote: Remote{Enabled: true, EnableCommandRemote: true, EnableSettingsRemote: true}} } func (s Settings) Validate() error { if err := s.VoiceProfiles.Validate(); err != nil { return err } - if err := sound.Validate_selection(s.Presentation.Sound.Driver, s.Presentation.Sound.Device); err != nil { + if err := sound.ValidateSelection(s.Presentation.Sound.Driver, s.Presentation.Sound.Device); err != nil { return err } - if err := sound.Validate_theme(s.Presentation.Sound.Theme); err != nil { + if err := sound.ValidateTheme(s.Presentation.Sound.Theme); err != nil { return err } seenVTs := make(map[int]bool) @@ -198,26 +198,26 @@ func (s Settings) Validate() error { if _, err := prompt.New(s.Prompt.ExactMatches, s.Prompt.CustomPatterns); err != nil { return err } - if err := punctuation.Validate_name(s.Reading.PunctuationProfile); err != nil { + if err := punctuation.ValidateName(s.Reading.PunctuationProfile); err != nil { return err } if s.Scripts.Workers < 1 || s.Scripts.Workers > 32 || s.Scripts.QueueLimit < 1 || s.Scripts.QueueLimit > 1024 || s.Scripts.OutputBytes < 1 || s.Scripts.OutputBytes > 4<<20 || s.Scripts.TimeoutSeconds < 0 || s.Scripts.TimeoutSeconds > 86400 { return fmt.Errorf("invalid script execution limits") } if s.Keyboard.FenrirKeys != nil { - if err := input.Validate_modifier_keys(s.Keyboard.FenrirKeys, s.General.ScriptKeys); err != nil { + if err := input.ValidateModifierKeys(s.Keyboard.FenrirKeys, s.General.ScriptKeys); err != nil { return err } } for _, key := range s.General.ScriptKeys { - if _, ok := input.Key_code(key); !ok { + if _, ok := input.KeyCode(key); !ok { return fmt.Errorf("invalid script key %q", key) } } if strings.ContainsAny(s.General.ScriptPath, "\x00\r\n") || strings.ContainsAny(s.Remote.SocketFile, "\x00\r\n") { return fmt.Errorf("invalid script or remote path") } - if err := validate_definitions(s); err != nil { + if err := validateDefinitions(s); err != nil { return err } if s.Clipboard.NumberOfClipboards < 1 || s.Clipboard.NumberOfClipboards > 10000 { @@ -230,7 +230,7 @@ func (s Settings) Validate() error { return fmt.Errorf("unsupported settings version %d (expected 3)", s.Version) } selected := s.Presentation.Speech - if err := speech.Validate_driver_options(selected.Driver, speech.Options{Module: selected.Module, Language: selected.Language, Voice: selected.Voice, Hardware: speech.HardwareOptions{Device: selected.HardwareDevice, BaudRate: selected.HardwareBaudRate}}); err != nil { + if err := speech.ValidateDriverOptions(selected.Driver, speech.Options{Module: selected.Module, Language: selected.Language, Voice: selected.Voice, Hardware: speech.HardwareOptions{Device: selected.HardwareDevice, BaudRate: selected.HardwareBaudRate}}); err != nil { return err } for _, path := range s.Keyboard.Devices { @@ -269,10 +269,10 @@ func Decode(data []byte) (Settings, error) { return Settings{}, fmt.Errorf("parse settings: %w", err) } if header.Version == nil || *header.Version == 1 { - return decode_v1(data) + return decodeV1(data) } if *header.Version == 2 { - return decode_v2(data) + return decodeV2(data) } settings := Defaults() if err := toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields().Decode(&settings); err != nil { @@ -309,10 +309,10 @@ func Load(requested string, paths []string) (Settings, string, error) { return Defaults(), "", nil } -// Load_startup loads settings and returns their save destination. System +// LoadStartup loads settings and returns their save destination. System // fallback settings seed a user's first save without making /etc the destination. // An explicit --config path remains the destination; errors name the source. -func Load_startup(requested string, paths []string) (Settings, string, error) { +func LoadStartup(requested string, paths []string) (Settings, string, error) { settings, path, err := Load(requested, paths) if err == nil && requested == "" && len(paths) != 0 { path = paths[0] @@ -330,22 +330,22 @@ func Save(path string, settings Settings) error { if err != nil { return err } - return save_data(path, data) + return saveData(path, data) } -func save_data(path string, data []byte) error { +func saveData(path string, data []byte) error { absolutePath, err := filepath.Abs(path) if err != nil { return err } if absolutePath == SystemPath { // System settings also seed unprivileged users' first launch. - return save_data_with_permissions(path, data, 0644, 0755) + return saveDataWithPermissions(path, data, 0644, 0755) } - return save_data_with_permissions(path, data, 0600, 0700) + return saveDataWithPermissions(path, data, 0600, 0700) } -func save_data_with_permissions(path string, data []byte, fileMode, dirMode os.FileMode) error { +func saveDataWithPermissions(path string, data []byte, fileMode, dirMode os.FileMode) error { dir := filepath.Dir(path) if err := os.MkdirAll(dir, dirMode); err != nil { return err @@ -354,7 +354,8 @@ func save_data_with_permissions(path string, data []byte, fileMode, dirMode os.F if err != nil { return err } - defer os.Remove(file.Name()) + // After a successful rename the temporary name no longer exists. + defer func() { _ = os.Remove(file.Name()) }() if _, err := file.Write(data); err != nil { file.Close() return err diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 5e074c43..66d2da75 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -227,9 +227,9 @@ func TestAtomicSavePermissionsForSystemAndPersonalSettings(t *testing.T) { if system { // Exercise the system writer in a private directory, without // writing to the installed configuration or requiring root. - return save_data_with_permissions(path, data, fileMode, dirMode) + return saveDataWithPermissions(path, data, fileMode, dirMode) } - return save_data(path, data) + return saveData(path, data) } for _, data := range []string{"initial", "replacement"} { if err := save([]byte(data)); err != nil { diff --git a/internal/config/definitions.go b/internal/config/definitions.go index 2ccc36b9..81e45263 100644 --- a/internal/config/definitions.go +++ b/internal/config/definitions.go @@ -27,10 +27,10 @@ import ( "strings" "time" - "git.stormux.org/storm/fenrir/internal/datetime" "git.stormux.org/storm/fenrir/internal/punctuation" "git.stormux.org/storm/fenrir/internal/sound" "git.stormux.org/storm/fenrir/internal/speech" + "git.stormux.org/storm/screenreader-common/datetime" ) // Section and Definition are derived from the typed TOML schema. A labelled @@ -104,7 +104,7 @@ func Definitions() []Definition { return result } -func setting_value(settings reflect.Value, path string) reflect.Value { +func settingValue(settings reflect.Value, path string) reflect.Value { for _, name := range strings.Split(path, ".") { structType := settings.Type() found := false @@ -123,7 +123,7 @@ func setting_value(settings reflect.Value, path string) reflect.Value { } func (d Definition) Value(settings Settings) any { - value := setting_value(reflect.ValueOf(settings), d.Path) + value := settingValue(reflect.ValueOf(settings), d.Path) if value.Kind() == reflect.Slice { return append([]string(nil), value.Interface().([]string)...) } @@ -132,7 +132,7 @@ func (d Definition) Value(settings Settings) any { // Set assigns a typed draft value. Validation still runs on the entire draft. func (d Definition) Set(settings *Settings, value any) error { - target := setting_value(reflect.ValueOf(settings).Elem(), d.Path) + target := settingValue(reflect.ValueOf(settings).Elem(), d.Path) source := reflect.ValueOf(value) if !source.IsValid() || source.Type() != target.Type() { return fmt.Errorf("invalid value type for %s", d.Path) @@ -147,7 +147,7 @@ func (d Definition) Available(settings Settings) bool { if d.SpeechCapability == "" { return true } - driver, err := speech.Find_driver(settings.Presentation.Speech.Driver) + driver, err := speech.FindDriver(settings.Presentation.Speech.Driver) if err != nil { return false } @@ -180,7 +180,7 @@ func (d Definition) Choices(settings Settings) []Choice { home, _ := os.UserHomeDir() var result []Choice found := false - for _, name := range sound.Theme_names(home) { + for _, name := range sound.ThemeNames(home) { result = append(result, Choice{ID: name, Label: name}) found = found || name == settings.Presentation.Sound.Theme } @@ -192,7 +192,7 @@ func (d Definition) Choices(settings Settings) []Choice { case "speech-baud": var result []Choice found := false - for _, baud := range speech.Baud_rates() { + for _, baud := range speech.BaudRates() { id := strconv.Itoa(baud) label := id if baud == 0 { @@ -212,9 +212,9 @@ func (d Definition) Choices(settings Settings) []Choice { return []Choice{{ID: "none", Label: "none"}, {ID: "speech", Label: "speech"}, {ID: "beeps", Label: "beeps"}, {ID: "both", Label: "speech and beeps"}} case "time-format", "date-format": now := time.Now() - options := datetime.Time_options(now) + options := datetime.TimeOptions(now) if d.ChoiceSource == "date-format" { - options = datetime.Date_options(now) + options = datetime.DateOptions(now) } var result []Choice for _, option := range options { @@ -249,7 +249,7 @@ func (d Definition) Choices(settings Settings) []Choice { return nil } -func validate_definitions(settings Settings) error { +func validateDefinitions(settings Settings) error { for _, definition := range Definitions() { if !definition.Available(settings) { continue @@ -269,7 +269,7 @@ func validate_definitions(settings Settings) error { // Driver support is independent of transient local availability. Module // choices are discovered by the selected backend, never a static allowlist. if definition.ChoiceSource == "speech-driver" { - if _, err := speech.Find_driver(value.(string)); err != nil { + if _, err := speech.FindDriver(value.(string)); err != nil { return err } } @@ -286,9 +286,9 @@ func validate_definitions(settings Settings) error { return nil } -// Ordered_sections preserves explicit sibling order and appends omitted sections +// OrderedSections preserves explicit sibling order and appends omitted sections // in schema order. Nested paths never create duplicate top-level tabs. -func Ordered_sections(sections []Section, order []string) []Section { +func OrderedSections(sections []Section, order []string) []Section { result := append([]Section(nil), sections...) ranks := make(map[string]int) for index, id := range order { diff --git a/internal/config/document.go b/internal/config/document.go index 80eff648..4bd759ad 100644 --- a/internal/config/document.go +++ b/internal/config/document.go @@ -44,7 +44,7 @@ type Document struct { applicationFields map[string]bool } -func read_document(path string) ([]byte, error) { +func readDocument(path string) ([]byte, error) { // Remote SAVEAS can name an arbitrary destination. A FIFO must not // block opening before we can establish that it is a regular file. file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK, 0) @@ -66,9 +66,9 @@ func read_document(path string) ([]byte, error) { return data, err } -func Open_document(path string, fallback Settings) (*Document, error) { +func OpenDocument(path string, fallback Settings) (*Document, error) { doc := &Document{Settings: fallback, path: path} - data, err := read_document(path) + data, err := readDocument(path) if !errors.Is(err, os.ErrNotExist) { if err != nil { return nil, err @@ -143,7 +143,7 @@ func Open_document(path string, fallback Settings) (*Document, error) { // Save checks for external edits made since the menu opened before writing. // Atomic replacement uses the same system/private permissions policy as Save. func (d *Document) Save(settings Settings) error { - data, err := read_document(d.path) + data, err := readDocument(d.path) if d.existed { if err != nil { return err @@ -160,14 +160,14 @@ func (d *Document) Save(settings Settings) error { return err } if d.applicationBase != nil { - return d.save_application(settings) + return d.saveApplication(settings) } // The same schema drives persistence and the form, including nested groups. var output bytes.Buffer fmt.Fprintf(&output, "version = %d\n", settings.Version) var encode func([]Section) error encode = func(sections []Section) error { - for _, section := range Ordered_sections(sections, d.Order) { + for _, section := range OrderedSections(sections, d.Order) { if section.ID == "voice_profiles" { if len(settings.VoiceProfiles.Profiles) == 0 { continue @@ -181,7 +181,7 @@ func (d *Document) Save(settings Settings) error { continue } - value := setting_value(reflect.ValueOf(settings), section.ID) + value := settingValue(reflect.ValueOf(settings), section.ID) fields := make(map[string]any) for index := range value.NumField() { if value.Field(index).Kind() != reflect.Struct { @@ -209,5 +209,5 @@ func (d *Document) Save(settings Settings) error { if err := encode(Sections()); err != nil { return err } - return save_data(d.path, output.Bytes()) + return saveData(d.path, output.Bytes()) } diff --git a/internal/config/document_test.go b/internal/config/document_test.go index 86224589..a3e37817 100644 --- a/internal/config/document_test.go +++ b/internal/config/document_test.go @@ -30,7 +30,7 @@ func TestDocumentPreservesSectionOrderAndPrivateAtomicSave(t *testing.T) { if err := os.WriteFile(path, []byte("version=1\n[ 'speech' ]\nrate=40\n[reading]\nautomatic=false\n"), 0644); err != nil { t.Fatal(err) } - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -42,7 +42,7 @@ func TestDocumentPreservesSectionOrderAndPrivateAtomicSave(t *testing.T) { if err := doc.Save(settings); err != nil { t.Fatal(err) } - loaded, err := Open_document(path, Defaults()) + loaded, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -68,7 +68,7 @@ func TestDocumentRejectsExternalEditsAndInvalidSettings(t *testing.T) { t.Fatal(err) } } - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -99,7 +99,7 @@ func TestDocumentRejectsExternalEditsAndInvalidSettings(t *testing.T) { func TestDocumentDefaultsAndDottedTables(t *testing.T) { path := filepath.Join(t.TempDir(), "settings.toml") - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -109,14 +109,14 @@ func TestDocumentDefaultsAndDottedTables(t *testing.T) { if err := os.WriteFile(path, []byte("reading.automatic=false\nspeech = {rate=30}\n"), 0600); err != nil { t.Fatal(err) } - doc, err = Open_document(path, Defaults()) + doc, err = OpenDocument(path, Defaults()) if err != nil || !reflect.DeepEqual(doc.Order, []string{"reading", "presentation", "presentation.speech"}) { t.Fatal(doc, err) } if err := os.WriteFile(path, []byte(strings.Repeat("#", (1<<20)+1)), 0600); err != nil { t.Fatal(err) } - if _, err := Open_document(path, Defaults()); err == nil { + if _, err := OpenDocument(path, Defaults()); err == nil { t.Fatal("oversize document accepted") } } diff --git a/internal/config/migrate.go b/internal/config/migrate.go index 5419f7bd..49dd3186 100644 --- a/internal/config/migrate.go +++ b/internal/config/migrate.go @@ -24,9 +24,9 @@ import ( "github.com/pelletier/go-toml/v2" ) -// decode_v1 is the explicit migration boundary for the prototype's flat +// decodeV1 is the explicit migration boundary for the prototype's flat // speech/sound tables. Unknown keys and mixed old/new schemas are rejected. -func decode_v1(data []byte) (Settings, error) { +func decodeV1(data []byte) (Settings, error) { defaults := Defaults() type oldSpeech struct { Enabled bool `toml:"enabled"` @@ -61,7 +61,7 @@ func decode_v1(data []byte) (Settings, error) { // Version 2 briefly exposed Socket under Presentation. Migrate it away without // carrying an endpoint override into either runtime settings or future saves. -func decode_v2(data []byte) (Settings, error) { +func decodeV2(data []byte) (Settings, error) { defaults := Defaults() var old struct { Version int `toml:"version"` diff --git a/internal/config/migrate_test.go b/internal/config/migrate_test.go index 223190f4..b5975ee4 100644 --- a/internal/config/migrate_test.go +++ b/internal/config/migrate_test.go @@ -54,7 +54,7 @@ cursor_echo = false if err := os.WriteFile(path, original, 0600); err != nil { t.Fatal(err) } - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -78,7 +78,7 @@ cursor_echo = false if err != nil || !strings.Contains(string(data), "version = 3") || strings.Contains(string(data), "\n[sound]") || strings.Contains(string(data), "socket =") { t.Fatal(string(data), err) } - got, err := Open_document(path, Defaults()) + got, err := OpenDocument(path, Defaults()) wantedOrder := []string{"clipboard", "presentation", "presentation.sound", "presentation.speech", "presentation.progress", "presentation.time_and_date", "keyboard", "reading", "internal_ui", "review", "screen", "general", "scripts", "remote", "prompt"} if err != nil || !reflect.DeepEqual(got.Settings, wanted) || !reflect.DeepEqual(got.Order, wantedOrder) { t.Fatal(got, err) @@ -114,7 +114,7 @@ func TestNestedDottedAndInlineSectionsShareOrder(t *testing.T) { if err := os.WriteFile(path, []byte(input), 0600); err != nil { t.Fatal(err) } - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } @@ -125,7 +125,7 @@ func TestNestedDottedAndInlineSectionsShareOrder(t *testing.T) { if err := doc.Save(doc.Settings); err != nil { t.Fatal(err) } - saved, err := Open_document(path, Defaults()) + saved, err := OpenDocument(path, Defaults()) if err == nil { saved.Settings.Keyboard.Devices = doc.Settings.Keyboard.Devices } diff --git a/internal/config/multi_press_test.go b/internal/config/multi_press_test.go index bd3f6c7a..c51e354a 100644 --- a/internal/config/multi_press_test.go +++ b/internal/config/multi_press_test.go @@ -29,7 +29,7 @@ func TestMultiPressTimeoutDefaultsValidationAndSave(t *testing.T) { if err := Save(path, settings); err != nil { t.Fatal(err) } - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } diff --git a/internal/config/prompt_test.go b/internal/config/prompt_test.go index 14c61cd2..fe8fc9c6 100644 --- a/internal/config/prompt_test.go +++ b/internal/config/prompt_test.go @@ -15,7 +15,7 @@ func TestPromptSettingsValidationAndSave(t *testing.T) { t.Fatal(err) } path := filepath.Join(t.TempDir(), "settings.toml") - doc, err := Open_document(path, settings) + doc, err := OpenDocument(path, settings) if err != nil { t.Fatal(err) } diff --git a/internal/config/review_test.go b/internal/config/review_test.go index 2a774b67..37f4bdf7 100644 --- a/internal/config/review_test.go +++ b/internal/config/review_test.go @@ -23,7 +23,7 @@ func TestReviewOptionsMigrationAndDocumentSave(t *testing.T) { if err := Save(path, settings); err != nil { t.Fatal(err) } - doc, err := Open_document(path, Defaults()) + doc, err := OpenDocument(path, Defaults()) if err != nil { t.Fatal(err) } diff --git a/internal/config/screen_test.go b/internal/config/screen_test.go index eb520420..b8adc77d 100644 --- a/internal/config/screen_test.go +++ b/internal/config/screen_test.go @@ -21,7 +21,7 @@ func TestIgnoredVTValidationAndPersistence(t *testing.T) { t.Fatal(err) } path := filepath.Join(t.TempDir(), "settings.toml") - doc, err := Open_document(path, settings) + doc, err := OpenDocument(path, settings) if err != nil { t.Fatal(err) } diff --git a/internal/config/scripts_test.go b/internal/config/scripts_test.go index 3c06b62b..c30c788f 100644 --- a/internal/config/scripts_test.go +++ b/internal/config/scripts_test.go @@ -30,7 +30,7 @@ func TestScriptDefaultsAndSaveRoundTrip(t *testing.T) { t.Fatal(version, settings, err) } path := filepath.Join(t.TempDir(), "settings.toml") - doc, err := Open_document(path, settings) + doc, err := OpenDocument(path, settings) if err != nil { t.Fatal(err) } diff --git a/internal/config/startup_test.go b/internal/config/startup_test.go index 4e94db16..e2214b1d 100644 --- a/internal/config/startup_test.go +++ b/internal/config/startup_test.go @@ -50,12 +50,12 @@ func TestStartupSaveDestinationAndLegacySettingsIgnored(t *testing.T) { paths, destination = []string{systemPath}, systemPath } systemBefore, _ := os.ReadFile(systemPath) - settings, path, err := Load_startup(requested, paths) + settings, path, err := LoadStartup(requested, paths) if err != nil || path != destination || settings.Presentation.Speech.Rate != rate { t.Fatalf("startup: destination=%q rate=%d err=%v", path, settings.Presentation.Speech.Rate, err) } // Follow the settings menu's document save workflow, then restart. - doc, err := Open_document(path, settings) + doc, err := OpenDocument(path, settings) if err != nil || doc.Settings.Presentation.Speech.Rate != rate { t.Fatalf("open settings: %+v %v", doc, err) } @@ -63,7 +63,7 @@ func TestStartupSaveDestinationAndLegacySettingsIgnored(t *testing.T) { if err := doc.Save(settings); err != nil { t.Fatal(err) } - restarted, path, err := Load_startup(requested, paths) + restarted, path, err := LoadStartup(requested, paths) if err != nil || path != destination || restarted.Presentation.Speech.Rate != 55 { t.Fatalf("restart: destination=%q rate=%d err=%v", path, restarted.Presentation.Speech.Rate, err) } @@ -86,10 +86,10 @@ func TestStartupErrorsIdentifySource(t *testing.T) { if err := os.WriteFile(systemPath, []byte("invalid=true"), 0600); err != nil { t.Fatal(err) } - if _, path, err := Load_startup("", []string{userPath, systemPath}); err == nil || path != systemPath { + if _, path, err := LoadStartup("", []string{userPath, systemPath}); err == nil || path != systemPath { t.Fatal("invalid fallback did not identify source", path, err) } - if _, path, err := Load_startup(userPath, []string{systemPath}); err == nil || path != userPath { + if _, path, err := LoadStartup(userPath, []string{systemPath}); err == nil || path != userPath { t.Fatal("explicit missing file did not identify source", path, err) } } diff --git a/internal/config/voice_profiles.go b/internal/config/voice_profiles.go index 21f1f5c7..fafc1fbe 100644 --- a/internal/config/voice_profiles.go +++ b/internal/config/voice_profiles.go @@ -5,7 +5,7 @@ package config import "git.stormux.org/storm/screenreader-common/voiceprofiles" -func Primary_voice(settings Settings) voiceprofiles.Profile { +func PrimaryVoice(settings Settings) voiceprofiles.Profile { s := settings.Presentation.Speech p := voiceprofiles.Profile{Driver: s.Driver, Module: s.Module, Language: s.Language, Voice: s.Voice, Rate: s.Rate, Pitch: s.Pitch, Volume: s.Volume} if s.Driver != "speech-dispatcher" { @@ -22,7 +22,7 @@ func Primary_voice(settings Settings) voiceprofiles.Profile { return p } -func Apply_primary_voice(settings Settings, p voiceprofiles.Profile) (Settings, error) { +func ApplyPrimaryVoice(settings Settings, p voiceprofiles.Profile) (Settings, error) { if err := p.Normalize().Validate(); err != nil { return settings, err } diff --git a/internal/config/voice_profiles_test.go b/internal/config/voice_profiles_test.go index 7e0c3777..36319843 100644 --- a/internal/config/voice_profiles_test.go +++ b/internal/config/voice_profiles_test.go @@ -14,7 +14,7 @@ func TestVoiceProfilesPersistenceAndPrimaryScope(t *testing.T) { p := voiceprofiles.Profile{Name: "Reading", Driver: "speech-dispatcher", Module: "fixture", Voice: "Reader", Language: "es", Rate: 30, Pitch: -5, Volume: 80} settings.VoiceProfiles.Profiles = []voiceprofiles.Profile{p} path := filepath.Join(t.TempDir(), "settings.toml") - doc, err := Open_document(path, settings) + doc, err := OpenDocument(path, settings) if err != nil { t.Fatal(err) } @@ -26,7 +26,7 @@ func TestVoiceProfilesPersistenceAndPrimaryScope(t *testing.T) { t.Fatal(loaded.VoiceProfiles, err) } original := loaded - loaded, err = Apply_primary_voice(loaded, p) + loaded, err = ApplyPrimaryVoice(loaded, p) if err != nil || loaded.Presentation.Speech.Voice != "Reader" || loaded.Presentation.Speech.Rate != 30 { t.Fatal(loaded, err) } @@ -34,7 +34,7 @@ func TestVoiceProfilesPersistenceAndPrimaryScope(t *testing.T) { t.Fatal("profile changed unrelated settings") } loaded.VoiceProfiles = loaded.VoiceProfiles.Remove(0) - doc, err = Open_document(path, loaded) + doc, err = OpenDocument(path, loaded) if err != nil { t.Fatal(err) } diff --git a/internal/console/decode_linux.go b/internal/console/decode_linux.go index 76f7fe72..89681c4d 100644 --- a/internal/console/decode_linux.go +++ b/internal/console/decode_linux.go @@ -27,9 +27,9 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -// decode_snapshot uses the VCSA header and native-endian UTF-32 VCSU cells. Glyph +// decodeSnapshot uses the VCSA header and native-endian UTF-32 VCSU cells. Glyph // numbers from VCSA are deliberately not treated as Unicode characters. -func decode_snapshot(tty int, header, text []byte) (screen.Snapshot, error) { +func decodeSnapshot(tty int, header, text []byte) (screen.Snapshot, error) { if len(header) < 4 { return screen.Snapshot{}, fmt.Errorf("short VCSA header") } @@ -56,7 +56,7 @@ func decode_snapshot(tty int, header, text []byte) (screen.Snapshot, error) { return snapshot, nil } -func decode_attributes(snapshot *screen.Snapshot, data []byte) error { +func decodeAttributes(snapshot *screen.Snapshot, data []byte) error { if len(data) != 4+len(snapshot.Cells)*2 { return fmt.Errorf("VCSA size %d does not match %dx%d console", len(data), snapshot.Cols, snapshot.Rows) } diff --git a/internal/console/decode_linux_test.go b/internal/console/decode_linux_test.go index 0c9fe943..6345f3ff 100644 --- a/internal/console/decode_linux_test.go +++ b/internal/console/decode_linux_test.go @@ -33,24 +33,24 @@ func TestVCSAAttributesUseNativeWordsAndKeepUnicode(t *testing.T) { data := []byte{1, 2, 0, 0, 0, 0, 0, 0} binary.NativeEndian.PutUint16(data[4:], 0x1741) binary.NativeEndian.PutUint16(data[6:], 0x8742) - snapshot, err := decode_snapshot(2, data, text) + snapshot, err := decodeSnapshot(2, data, text) if err != nil { t.Fatal(err) } - if err := decode_attributes(&snapshot, data); err != nil { + if err := decodeAttributes(&snapshot, data); err != nil { t.Fatal(err) } if string(snapshot.Cells) != "é界" || snapshot.Attributes[0] != (screen.Attribute{Foreground: screen.ColorIndexed | 7, Background: screen.ColorIndexed | 4}) || snapshot.Attributes[1] != (screen.Attribute{Foreground: screen.ColorIndexed | 7, Background: screen.ColorIndexed, Style: screen.ConsoleHigh}) { t.Fatal("attributes corrupted Unicode or cell order", snapshot) } - if got := presentation.Format_attributes(snapshot.Attributes[0], "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirBlink"); got != "light gray|blue||" { + if got := presentation.FormatAttributes(snapshot.Attributes[0], "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirBlink"); got != "light gray|blue||" { t.Fatal(got) } - if got := presentation.Format_attributes(snapshot.Attributes[1], "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirBlink"); got != "light gray|black||" { + if got := presentation.FormatAttributes(snapshot.Attributes[1], "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirBlink"); got != "light gray|black||" { t.Fatal(got) } for _, invalid := range [][]byte{data[:4], data[:7], append(append([]byte{}, data...), 0)} { - if err := decode_attributes(&snapshot, invalid); err == nil { + if err := decodeAttributes(&snapshot, invalid); err == nil { t.Fatal("accepted partial or oversized VCSA", invalid) } } @@ -61,7 +61,7 @@ func TestDecodeUnicodeAndGeometry(t *testing.T) { for index, value := range []uint32{'é', '界', 0, 0x110000} { binary.NativeEndian.PutUint32(data[index*4:], value) } - snapshot, err := decode_snapshot(2, []byte{2, 2, 1, 0}, data) + snapshot, err := decodeSnapshot(2, []byte{2, 2, 1, 0}, data) if err != nil { t.Fatal(err) } @@ -69,11 +69,11 @@ func TestDecodeUnicodeAndGeometry(t *testing.T) { t.Fatalf("wrong Unicode: %+v", snapshot) } for _, header := range [][]byte{{}, {0, 2, 0, 0}, {2, 2, 2, 0}, {2, 2, 0, 2}} { - if _, err := decode_snapshot(1, header, data); err == nil { + if _, err := decodeSnapshot(1, header, data); err == nil { t.Fatalf("accepted invalid header %v", header) } } - if _, err := decode_snapshot(1, []byte{2, 2, 0, 0}, data[:12]); err == nil { + if _, err := decodeSnapshot(1, []byte{2, 2, 0, 0}, data[:12]); err == nil { t.Fatal("accepted resize mismatch") } } diff --git a/internal/console/discovery_linux.go b/internal/console/discovery_linux.go index d1d83f45..ca2c4a73 100644 --- a/internal/console/discovery_linux.go +++ b/internal/console/discovery_linux.go @@ -28,12 +28,12 @@ type deviceIdentity struct { changed syscall.Timespec } -func identity_from_stat(stat *syscall.Stat_t) deviceIdentity { +func identityFromStat(stat *syscall.Stat_t) deviceIdentity { return deviceIdentity{device: uint64(stat.Dev), inode: stat.Ino, rdev: uint64(stat.Rdev), changed: stat.Ctim} } -func device_identity(path string) (deviceIdentity, error) { +func statDeviceIdentity(path string) (deviceIdentity, error) { var stat syscall.Stat_t err := syscall.Stat(path, &stat) - return identity_from_stat(&stat), err + return identityFromStat(&stat), err } diff --git a/internal/console/discovery_linux_test.go b/internal/console/discovery_linux_test.go index d0e0e8f3..1cb222ac 100644 --- a/internal/console/discovery_linux_test.go +++ b/internal/console/discovery_linux_test.go @@ -35,7 +35,7 @@ func BenchmarkCachedDeviceScan(b *testing.B) { if err := os.WriteFile(path, nil, 0600); err != nil { b.Fatal(err) } - identity, err := device_identity(path) + identity, err := statDeviceIdentity(path) if err != nil { b.Fatal(err) } @@ -45,7 +45,7 @@ func BenchmarkCachedDeviceScan(b *testing.B) { b.ReportAllocs() b.ResetTimer() for b.Loop() { - if err := k.scan_paths(paths); err != nil { + if err := k.scanPaths(paths); err != nil { b.Fatal(err) } } @@ -56,7 +56,7 @@ func TestScanCachesRejectionsAndRetriesReplacement(t *testing.T) { if err := os.WriteFile(path, nil, 0600); err != nil { t.Fatal(err) } - identity, err := device_identity(path) + identity, err := statDeviceIdentity(path) if err != nil { t.Fatal(err) } @@ -64,7 +64,7 @@ func TestScanCachesRejectionsAndRetriesReplacement(t *testing.T) { // A cached non-keyboard must not be reopened. This regular file would // fail libevdev initialization and lose its cache entry if probed. for range 3 { - if err := k.scan_paths([]string{path}); err != nil { + if err := k.scanPaths([]string{path}); err != nil { t.Fatal(err) } if _, ok := k.rejected[path]; !ok { @@ -96,7 +96,7 @@ func TestScanInvalidatesMissingAndChangedNodes(t *testing.T) { if err := os.WriteFile(path, nil, 0600); err != nil { t.Fatal(err) } - identity, err := device_identity(path) + identity, err := statDeviceIdentity(path) if err != nil { t.Fatal(err) } @@ -108,7 +108,7 @@ func TestScanInvalidatesMissingAndChangedNodes(t *testing.T) { t.Fatal("changed node was not probed") } k.rejected[path] = identity - if err := k.scan_paths(nil); err != nil { + if err := k.scanPaths(nil); err != nil { t.Fatal(err) } if len(k.rejected) != 0 { diff --git a/internal/console/live_modifiers_linux_test.go b/internal/console/live_modifiers_linux_test.go index f6544b87..8a87d56b 100644 --- a/internal/console/live_modifiers_linux_test.go +++ b/internal/console/live_modifiers_linux_test.go @@ -13,24 +13,24 @@ import ( ) func TestConsoleModifierUpdateWaitsForCaptureAndHeldChord(t *testing.T) { - layout, _, err := input.Load_bindings([]string{"../../config/keyboard/laptop.toml"}) + layout, _, err := input.LoadBindings([]string{"../../config/keyboard/laptop.toml"}) if err != nil { t.Fatal(err) } - router, err := input.New_router(layout) + router, err := input.NewRouter(layout) if err != nil { t.Fatal(err) } - if err := router.Configure_modifiers([]string{"KEY_INSERT"}, []string{"KEY_COMPOSE"}); err != nil { + if err := router.ConfigureModifiers([]string{"KEY_INSERT"}, []string{"KEY_COMPOSE"}); err != nil { t.Fatal(err) } - if err := router.Configure_scripts([]string{"KEY_COMPOSE"}, []input.ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { + if err := router.ConfigureScripts([]string{"KEY_COMPOSE"}, []input.ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { t.Fatal(err) } keys := &Keyboards{router: router} update := func(want bool) { t.Helper() - applied, err := keys.Update_modifiers([]string{"KEY_META"}, []string{"KEY_CAPSLOCK"}) + applied, err := keys.UpdateModifiers([]string{"KEY_META"}, []string{"KEY_CAPSLOCK"}) if err != nil || applied != want { t.Fatal(applied, err) } diff --git a/internal/console/native_linux.go b/internal/console/native_linux.go index 49bf2e93..6238a928 100644 --- a/internal/console/native_linux.go +++ b/internal/console/native_linux.go @@ -77,27 +77,27 @@ import ( "git.stormux.org/storm/fenrir/internal/input" ) -func kernel_error(code C.int) error { +func kernelError(code C.int) error { if code >= 0 { return nil } return syscall.Errno(-code) } -func query_usage(path string) (uint16, error) { +func queryUsage(path string) (uint16, error) { file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOCTTY, 0) if err != nil { return 0, err } defer file.Close() var mask C.ushort - if err := kernel_error(C.console_usage(C.int(file.Fd()), &mask)); err != nil { + if err := kernelError(C.console_usage(C.int(file.Fd()), &mask)); err != nil { return 0, err } return uint16(mask), nil } -func query_state(path string) (bool, bool, bool, error) { +func queryState(path string) (bool, bool, bool, error) { file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOCTTY, 0) if err != nil { return false, false, false, err @@ -105,7 +105,7 @@ func query_state(path string) (bool, bool, bool, error) { defer file.Close() var mode C.int var leds C.uchar - if err := kernel_error(C.console_state(C.int(file.Fd()), &mode, &leds)); err != nil { + if err := kernelError(C.console_state(C.int(file.Fd()), &mode, &leds)); err != nil { return false, false, false, err } return mode == C.KD_TEXT, leds&C.LED_NUM != 0, leds&C.LED_CAP != 0, nil @@ -120,13 +120,13 @@ type Device struct { syncing bool } -func open_device(path string) (*Device, error) { +func openDevice(path string) (*Device, error) { fd, err := syscall.Open(path, syscall.O_RDWR|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0) if err != nil { return nil, err } device := &Device{path: path, fd: fd} - if err := kernel_error(C.libevdev_new_from_fd(C.int(fd), &device.dev)); err != nil { + if err := kernelError(C.libevdev_new_from_fd(C.int(fd), &device.dev)); err != nil { syscall.Close(fd) return nil, err } @@ -142,21 +142,21 @@ func (d *Device) keyboard() bool { return has(C.KEY_A) && has(C.KEY_Z) && has(C.KEY_ENTER) || has(C.KEY_KP7) && has(C.KEY_KP5) && has(C.KEY_KP1) } -func (d *Device) create_forwarder() error { +func (d *Device) createForwarder() error { name := C.CString("fenrir forwarding " + filepath.Base(d.path)) defer C.free(unsafe.Pointer(name)) C.libevdev_set_name(d.dev, name) // The physical keyboard already generates repeats. A second repeating // virtual device would duplicate them. C.libevdev_disable_event_type(d.dev, C.EV_REP) - if err := kernel_error(C.libevdev_uinput_create_from_device(d.dev, C.LIBEVDEV_UINPUT_OPEN_MANAGED, &d.virtual)); err != nil { + if err := kernelError(C.libevdev_uinput_create_from_device(d.dev, C.LIBEVDEV_UINPUT_OPEN_MANAGED, &d.virtual)); err != nil { return err } return syscall.SetNonblock(int(C.libevdev_uinput_get_fd(d.virtual)), true) } func (d *Device) forward(eventType, code uint16, value int32) error { - return kernel_error(C.libevdev_uinput_write_event(d.virtual, C.uint(eventType), C.uint(code), C.int(value))) + return kernelError(C.libevdev_uinput_write_event(d.virtual, C.uint(eventType), C.uint(code), C.int(value))) } func (d *Device) held() bool { @@ -178,7 +178,7 @@ func (d *Device) release(router *input.Router) error { } router.Drop(d.fd) if d.grabbed { - errs = append(errs, kernel_error(C.libevdev_grab(d.dev, C.LIBEVDEV_UNGRAB))) + errs = append(errs, kernelError(C.libevdev_grab(d.dev, C.LIBEVDEV_UNGRAB))) d.grabbed = false } return errors.Join(errs...) @@ -205,7 +205,7 @@ type Keyboards struct { uiMap *os.File } -func Open_keyboards(paths []string, router input.Router) (*Keyboards, error) { +func OpenKeyboards(paths []string, router input.Router) (*Keyboards, error) { watcher, err := newReadinessWatcher(syscall.EPOLLIN) if err != nil { return nil, fmt.Errorf("watch keyboards: %w", err) @@ -227,10 +227,10 @@ func (k *Keyboards) Scan() error { if len(paths) == 0 { paths, _ = filepath.Glob("/dev/input/event*") } - return k.scan_paths(paths) + return k.scanPaths(paths) } -func (k *Keyboards) scan_paths(paths []string) error { +func (k *Keyboards) scanPaths(paths []string) error { started := time.Now() probed, skipped := 0, 0 defer func() { diagnostic.Timing("keyboard scan", started, "probed", probed, "cached", skipped) }() @@ -244,14 +244,14 @@ func (k *Keyboards) scan_paths(paths []string) error { if k.devices[path] != nil { continue } - identity, statErr := device_identity(path) + identity, statErr := statDeviceIdentity(path) if cached, ok := k.rejected[path]; ok && statErr == nil && cached == identity { rejected[path] = cached skipped++ continue } probed++ - device, err := open_device(path) + device, err := openDevice(path) if err != nil { if len(k.paths) != 0 { return fmt.Errorf("open keyboard %s: %w", path, err) @@ -263,20 +263,20 @@ func (k *Keyboards) scan_paths(paths []string) error { // opens remain retryable; hotplug creates a different node identity. var stat syscall.Stat_t if err := syscall.Fstat(device.fd, &stat); err == nil { - rejected[path] = identity_from_stat(&stat) + rejected[path] = identityFromStat(&stat) } - device.close(&k.router) + _ = device.close(&k.router) // Rejected device; nothing to report. if len(k.paths) != 0 { return fmt.Errorf("%s is not a supported keyboard", path) } continue } - if err := device.create_forwarder(); err != nil { - device.close(&k.router) + if err := device.createForwarder(); err != nil { + _ = device.close(&k.router) // The setup error is reported instead. return fmt.Errorf("create uinput forwarder for %s (is /dev/uinput available?): %w", path, err) } if err := k.watcher.add(device.fd); err != nil { - device.close(&k.router) + _ = device.close(&k.router) // The setup error is reported instead. return fmt.Errorf("watch keyboard %s: %w", path, err) } k.devices[path] = device @@ -284,7 +284,7 @@ func (k *Keyboards) scan_paths(paths []string) error { return nil } -func (k *Keyboards) Pass_next() { k.router.Pass_next() } +func (k *Keyboards) PassNext() { k.router.PassNext() } // Events wakes the application when a keyboard is readable, without reading it. // A nil event means readiness; a non-nil event is a fatal watcher error. @@ -308,9 +308,9 @@ func (k *Keyboards) Close() error { return errors.Join(errs...) } -// Update_modifiers waits for every keyboard to release its old chord before +// UpdateModifiers waits for every keyboard to release its old chord before // replacing the router; the existing evdev grabs remain owned throughout. -func (k *Keyboards) Update_modifiers(fenrirKeys, scriptKeys []string) (bool, error) { +func (k *Keyboards) UpdateModifiers(fenrirKeys, scriptKeys []string) (bool, error) { if k.router.Captured() || !k.router.Idle() { return false, nil } @@ -320,7 +320,7 @@ func (k *Keyboards) Update_modifiers(fenrirKeys, scriptKeys []string) (bool, err } } candidate := k.router - if err := candidate.Configure_modifiers(fenrirKeys, scriptKeys); err != nil { + if err := candidate.ConfigureModifiers(fenrirKeys, scriptKeys); err != nil { return false, err } k.router = candidate @@ -341,7 +341,7 @@ func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) er for path, device := range k.devices { drained, err := k.drain(device, numLock, handle) if errors.Is(err, syscall.ENODEV) || errors.Is(err, syscall.EIO) { - device.close(&k.router) + _ = device.close(&k.router) // The device is already gone. delete(k.devices, path) continue } @@ -356,7 +356,7 @@ func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) er // Wait for all physical keys to be released before taking ownership. // This avoids stealing half a Ctrl+Alt+Fn chord at a VT switch. if textMode && !device.grabbed && drained && !device.held() { - if err := kernel_error(C.libevdev_grab(device.dev, C.LIBEVDEV_GRAB)); err != nil { + if err := kernelError(C.libevdev_grab(device.dev, C.LIBEVDEV_GRAB)); err != nil { return fmt.Errorf("grab %s (another reader may own it): %w", path, err) } // A press can race the last read and EVIOCGRAB. Refresh the kernel @@ -365,7 +365,7 @@ func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) er code := C.libevdev_next_event(device.dev, C.LIBEVDEV_READ_FLAG_FORCE_SYNC, &event) if code < 0 { C.libevdev_grab(device.dev, C.LIBEVDEV_UNGRAB) - return kernel_error(code) + return kernelError(code) } device.syncing = true ready, err := k.drain(device, numLock, handle) @@ -405,7 +405,7 @@ func (k *Keyboards) drain(device *Device, numLock bool, handle func(input.Decisi return true, device.feedback() } if code < 0 { - return false, kernel_error(code) + return false, kernelError(code) } if code == C.LIBEVDEV_READ_STATUS_SYNC && !device.syncing { device.syncing = true @@ -420,7 +420,7 @@ func (k *Keyboards) drain(device *Device, numLock bool, handle func(input.Decisi diagnostic.Timing("keyboard event age", time.UnixMicro(int64(C.input_event_time_us(&event)))) } decision = k.router.Key(device.fd, uint16(event.code), int32(event.value), numLock, device.syncing) - if err := k.ui_text(uint16(event.code), decision); err != nil { + if err := k.uiText(uint16(event.code), decision); err != nil { return false, err } } @@ -429,7 +429,7 @@ func (k *Keyboards) drain(device *Device, numLock bool, handle func(input.Decisi if err != nil { return false, err } - toggleErr := kernel_error(C.toggle_caps_lock(C.int(file.Fd()))) + toggleErr := kernelError(C.toggle_caps_lock(C.int(file.Fd()))) if err := errors.Join(toggleErr, file.Close()); err != nil { return false, err } @@ -454,14 +454,14 @@ func (d *Device) feedback() error { return nil } if code < 0 { - return kernel_error(code) + return kernelError(code) } if event._type == C.EV_LED { value := C.enum_libevdev_led_value(C.LIBEVDEV_LED_OFF) if event.value != 0 { value = C.LIBEVDEV_LED_ON } - if err := kernel_error(C.libevdev_kernel_set_led_value(d.dev, C.uint(event.code), value)); err != nil { + if err := kernelError(C.libevdev_kernel_set_led_value(d.dev, C.uint(event.code), value)); err != nil { return err } } diff --git a/internal/console/paste_linux_test.go b/internal/console/paste_linux_test.go index 0fa06456..19535776 100644 --- a/internal/console/paste_linux_test.go +++ b/internal/console/paste_linux_test.go @@ -52,7 +52,7 @@ func TestConsolePasteRejectsChangedTargetAndFailedInjection(t *testing.T) { if err := source.Paste(context.Background(), "text", 2); err == nil { t.Fatal("failed TIOCSTI reported success") } - source.Configure_ignored_vts([]int{2}) + source.ConfigureIgnoredVts([]int{2}) if err := source.Paste(context.Background(), "text", 2); err == nil || !strings.Contains(err.Error(), "active VT changed") { t.Fatal("paste attempted injection into ignored VT", err) } @@ -60,7 +60,7 @@ func TestConsolePasteRejectsChangedTargetAndFailedInjection(t *testing.T) { if err != nil || len(data) != 0 { t.Fatal("paste wrote to terminal output", data, err) } - source.Configure_ignored_vts(nil) + source.ConfigureIgnoredVts(nil) source.usage = func(string) (uint16, error) { return 3, nil } source.state = func(string) (bool, bool, bool, error) { t.Fatal("paste queried unused target") diff --git a/internal/console/source_linux.go b/internal/console/source_linux.go index 0f0e23c6..7fa14873 100644 --- a/internal/console/source_linux.go +++ b/internal/console/source_linux.go @@ -44,8 +44,8 @@ type Source struct { ignoredVTs atomic.Uint64 // Paste checks policy from its background worker. } -// Configure_ignored_vts receives the validated console policy from the event loop. -func (s *Source) Configure_ignored_vts(numbers []int) { +// ConfigureIgnoredVts receives the validated console policy from the event loop. +func (s *Source) ConfigureIgnoredVts(numbers []int) { var mask uint64 for _, number := range numbers { mask |= uint64(1) << uint(number) @@ -65,7 +65,7 @@ func OpenSource() (*Source, error) { changes.Close() return nil, err } - source := &Source{root: "/", state: query_state, usage: query_usage, changes: changes, watcher: watcher} + source := &Source{root: "/", state: queryState, usage: queryUsage, changes: changes, watcher: watcher} if err := watcher.add(int(changes.Fd())); err != nil { source.Close() return nil, fmt.Errorf("watch foreground console: %w", err) @@ -126,7 +126,7 @@ func (s *Source) State() (int, bool, bool, error) { // a ReadFile buffer for a device whose stat size is zero. All requests stay // UTF-32 aligned. A short or oversized screen still goes through Decode's // geometry check and the caller's bounded resize retry. -func read_unicode(reader io.Reader, cells int) ([]byte, error) { +func readUnicode(reader io.Reader, cells int) ([]byte, error) { data := make([]byte, (cells+1)*4) n, err := io.ReadFull(reader, data) if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { @@ -135,7 +135,7 @@ func read_unicode(reader io.Reader, cells int) ([]byte, error) { return data[:n], err } -func read_unicode_file(path string, cells int) ([]byte, error) { +func readUnicodeFile(path string, cells int) ([]byte, error) { started := time.Now() defer func() { diagnostic.Timing("Unicode console read", started) }() file, err := os.Open(path) @@ -143,7 +143,7 @@ func read_unicode_file(path string, cells int) ([]byte, error) { return nil, err } defer file.Close() - return read_unicode(file, cells) + return readUnicode(file, cells) } func readHeader(path string) ([]byte, error) { @@ -157,7 +157,7 @@ func readHeader(path string) ([]byte, error) { return header, err } -func read_attributes_file(path string) ([]byte, error) { +func readAttributesFile(path string) ([]byte, error) { file, err := os.Open(path) if err != nil { return nil, err @@ -194,20 +194,20 @@ func (s *Source) read() (screen.Snapshot, error) { if !textMode { return screen.Snapshot{Terminal: number}, nil } - header, err := read_attributes_file(filepath.Join(s.root, "dev", fmt.Sprintf("vcsa%d", number))) + header, err := readAttributesFile(filepath.Join(s.root, "dev", fmt.Sprintf("vcsa%d", number))) if err != nil { return screen.Snapshot{}, fmt.Errorf("read console header: %w", err) } - text, err := read_unicode_file(filepath.Join(s.root, "dev", fmt.Sprintf("vcsu%d", number)), int(header[0])*int(header[1])) + text, err := readUnicodeFile(filepath.Join(s.root, "dev", fmt.Sprintf("vcsu%d", number)), int(header[0])*int(header[1])) if err != nil { return screen.Snapshot{}, fmt.Errorf("read Unicode console /dev/vcsu%d (a UTF-8 text VT is required): %w", number, err) } - snapshot, err := decode_snapshot(number, header, text) + snapshot, err := decodeSnapshot(number, header, text) if err != nil { lastErr = err continue } - if err := decode_attributes(&snapshot, header); err != nil { + if err := decodeAttributes(&snapshot, header); err != nil { lastErr = err continue } diff --git a/internal/console/source_linux_test.go b/internal/console/source_linux_test.go index dae61ffc..9c7c729c 100644 --- a/internal/console/source_linux_test.go +++ b/internal/console/source_linux_test.go @@ -106,7 +106,7 @@ func TestSourceWaitsForConsoleOwner(t *testing.T) { if _, active, _, err := source.State(); !errors.Is(err, problem) || active { t.Fatal("usage failure permitted a target probe", active, err) } - source.Configure_ignored_vts([]int{terminal}) + source.ConfigureIgnoredVts([]int{terminal}) if _, active, _, err := source.State(); err != nil || active { t.Fatal("ignored console queried usage", active, err) } @@ -219,7 +219,7 @@ func TestSourceUsesActiveVTAndSkipsGraphics(t *testing.T) { t.Fatal("source dropped attributes", snapshot.Attributes) } allowedState := source.state - source.Configure_ignored_vts([]int{2, 7, 8, 10}) + source.ConfigureIgnoredVts([]int{2, 7, 8, 10}) source.state = func(string) (bool, bool, bool, error) { t.Fatal("queried ignored console") return true, false, false, nil @@ -231,7 +231,7 @@ func TestSourceUsesActiveVTAndSkipsGraphics(t *testing.T) { if err != nil || snapshot.Terminal != 2 || snapshot.Active || len(snapshot.Cells) != 0 || len(snapshot.Attributes) != 0 { t.Fatal("ignored VT retained screen data", snapshot, err) } - source.Configure_ignored_vts(nil) + source.ConfigureIgnoredVts(nil) source.state = allowedState snapshot, err = source.Read() if err != nil || !snapshot.Active || string(snapshot.Cells) != "界a" || !snapshot.NumLock || !snapshot.CapsLock { diff --git a/internal/console/ui_linux.go b/internal/console/ui_linux.go index ab63f030..d879efff 100644 --- a/internal/console/ui_linux.go +++ b/internal/console/ui_linux.go @@ -88,7 +88,7 @@ func (k *Keyboards) Capture(enabled bool) (result error) { return nil } -func (k *Keyboards) ui_text(code uint16, decision input.Decision) error { +func (k *Keyboards) uiText(code uint16, decision input.Decision) error { if decision.UI == nil || decision.UI.Name != "" || k.uiMap == nil { return nil } diff --git a/internal/console/unicode_linux_test.go b/internal/console/unicode_linux_test.go index f43e03c6..041165c0 100644 --- a/internal/console/unicode_linux_test.go +++ b/internal/console/unicode_linux_test.go @@ -45,7 +45,7 @@ func TestUnicodeReadBoundedAlignedAndComplete(t *testing.T) { for _, size := range []int{0, 4, cells*4 - 4, cells * 4, cells*4 + 4, cells * 8} { for _, limit := range []int{0, 128} { reader := &unicodeReader{Reader: bytes.NewReader(make([]byte, size)), limit: limit} - data, err := read_unicode(reader, cells) + data, err := readUnicode(reader, cells) if err != nil || len(data) != min(size, (cells+1)*4) { t.Fatalf("size %d limit %d: got %d bytes, %v", size, limit, len(data), err) } @@ -66,7 +66,7 @@ type failedReader struct{} func (failedReader) Read([]byte) (int, error) { return 0, io.ErrClosedPipe } func TestUnicodeReadPreservesIOError(t *testing.T) { - if _, err := read_unicode(failedReader{}, 80*25); !errors.Is(err, io.ErrClosedPipe) { + if _, err := readUnicode(failedReader{}, 80*25); !errors.Is(err, io.ErrClosedPipe) { t.Fatalf("lost I/O error: %v", err) } } diff --git a/internal/control/coexistence_linux.go b/internal/control/coexistence_linux.go index 755ca9f9..a1cf3e16 100644 --- a/internal/control/coexistence_linux.go +++ b/internal/control/coexistence_linux.go @@ -14,7 +14,7 @@ import ( "syscall" ) -func (s *Server) endpoint_snapshot() []endpoint { +func (s *Server) endpointSnapshot() []endpoint { s.endpointsMu.RLock() defer s.endpointsMu.RUnlock() return slices.Clone(s.endpoints) @@ -22,18 +22,18 @@ func (s *Server) endpoint_snapshot() []endpoint { // Every default instance has a private endpoint. The first available instance // also serves the shared path, and a survivor claims it after that owner exits. -func (s *Server) claim_main() bool { +func (s *Server) claimMain() bool { if s.options.SocketFile != "" || s.ctx.Err() != nil { return false } s.endpointsMu.Lock() defer s.endpointsMu.Unlock() for _, endpoint := range s.endpoints { - if endpoint.path == s.main_path() { + if endpoint.path == s.mainPath() { return false } } - endpoint, err := listen(s.main_path()) + endpoint, err := listen(s.mainPath()) if err != nil { return false // Active readers and unrelated paths are preserved. } @@ -49,8 +49,8 @@ func (s *Server) claim_main() bool { return true } -func (s *Server) private_path(data instance) string { - path := filepath.Join(filepath.Dir(s.main_path()), fmt.Sprintf("fenrirscreenreader-%d.sock", data.PID)) +func (s *Server) privatePath(data instance) string { + path := filepath.Join(filepath.Dir(s.mainPath()), fmt.Sprintf("fenrirscreenreader-%d.sock", data.PID)) if slices.Contains(data.SocketFiles, path) { return path } @@ -60,11 +60,11 @@ func (s *Server) private_path(data instance) string { // Ancestry identifies ordinary PTY children. Reattached Screen sessions and // detached helpers can lose that ancestry, so also use the caller's own X11 // identity. Neither a single terminal nor a console is a safe default. -func (s *Server) route_target(pid, uid int) (string, error) { +func (s *Server) routeTarget(pid, uid int) (string, error) { instances := s.instances() var terminals, consoles []instance for _, data := range instances { - if s.private_path(data) == "" { + if s.privatePath(data) == "" { continue } if data.ScreenDriver == "vcsaDriver" && (data.uid == 0 || data.uid == uid) { @@ -77,7 +77,7 @@ func (s *Server) route_target(pid, uid int) (string, error) { var ancestors []int var ancestorReader *instance ancestry: - for ancestor := pid; ancestor > 1 && !seen[ancestor]; ancestor = parent_pid(ancestor) { + for ancestor := pid; ancestor > 1 && !seen[ancestor]; ancestor = parentPid(ancestor) { seen[ancestor] = true ancestors = append(ancestors, ancestor) for _, data := range terminals { @@ -97,7 +97,7 @@ ancestry: lookup := s.screenReader if lookup == nil { lookup = func(ancestors []int, uid int, readers []instance) (instance, bool, error) { - return attached_screen_reader("/proc", ancestors, uid, readers) + return attachedScreenReader("/proc", ancestors, uid, readers) } } if reader, handled, err := lookup(ancestors, uid, readers); handled { @@ -109,8 +109,8 @@ ancestry: if ancestorReader != nil { return s.destination(*ancestorReader) } - identity := process_identity(pid, uid) - return s.route_identity(identity, uid, terminals, consoles) + identity := lookupProcessIdentity(pid, uid) + return s.routeIdentity(identity, uid, terminals, consoles) } type processIdentity struct { @@ -121,7 +121,7 @@ type processIdentity struct { // Read only identity fields from the credentialed process, never a supplied PID // or environment in the request text. Environment is a routing hint, not an // authorization grant; the destination still checks the original SO_PEERCRED. -func process_identity(pid, uid int) processIdentity { +func lookupProcessIdentity(pid, uid int) processIdentity { var identity processIdentity info, err := os.Stat(fmt.Sprintf("/proc/%d", pid)) if err != nil { @@ -164,7 +164,7 @@ func process_identity(pid, uid int) processIdentity { return identity } -func (s *Server) route_identity(identity processIdentity, uid int, terminals, consoles []instance) (string, error) { +func (s *Server) routeIdentity(identity processIdentity, uid int, terminals, consoles []instance) (string, error) { var matches []instance if identity.console { // A real controlling VT takes precedence over inherited X11 variables. @@ -174,7 +174,7 @@ func (s *Server) route_identity(identity processIdentity, uid int, terminals, co if data.uid != uid || data.WindowID != identity.window { continue } - target := process_identity(data.PID, data.uid) + target := lookupProcessIdentity(data.PID, data.uid) if target.display == identity.display { matches = append(matches, data) } @@ -193,7 +193,7 @@ func (s *Server) destination(data instance) (string, error) { if !data.ConnectionHandoff { return "", fmt.Errorf("reader %d cannot accept a connection handoff", data.PID) } - path := s.private_path(data) + path := s.privatePath(data) info, err := os.Lstat(path) if err != nil || info.Mode()&os.ModeSocket == 0 { return "", fmt.Errorf("reader %d private socket is unavailable", data.PID) diff --git a/internal/control/coexistence_test.go b/internal/control/coexistence_test.go index d3351155..c65d675b 100644 --- a/internal/control/coexistence_test.go +++ b/internal/control/coexistence_test.go @@ -60,11 +60,11 @@ func TestControlProcess(t *testing.T) { _ = json.NewEncoder(os.Stdout).Encode(reply) os.Exit(0) } - run_reader_process(mode) + runReaderProcess(mode) os.Exit(0) } -func child_command(mode string) *exec.Cmd { +func childCommand(mode string) *exec.Cmd { command := exec.Command(os.Args[0], "-test.run=^TestControlProcess$") command.Env = append(os.Environ(), "FENRIR_CONTROL_PROCESS="+mode) // A fixture must not inherit the developer's real VT as its controlling TTY. @@ -74,7 +74,7 @@ func child_command(mode string) *exec.Cmd { // Screen daemons launched by a fixture may be reparented to PID 1 and never // reach the coordinator; their full ancestry still belongs to that fixture. -func fixture_ancestors(ancestors []int, coordinator int) []int { +func fixtureAncestors(ancestors []int, coordinator int) []int { for i, pid := range ancestors { if pid == coordinator { return ancestors[:i] @@ -95,9 +95,9 @@ func TestFixtureScreenInspectionExcludesHostAndKeepsPrivateSessions(t *testing.T {"coordinator caller", []int{300, 100}, false}, } { t.Run(trial.name, func(t *testing.T) { - f := new_screen_fixture(t) + f := newScreenFixture(t) f.attach(200, 300, "/dev/null", true) - reader, handled, err := attached_screen_reader(f.root, fixture_ancestors(trial.ancestors, 300), os.Geteuid(), []instance{{PID: 300}}) + reader, handled, err := attachedScreenReader(f.root, fixtureAncestors(trial.ancestors, 300), os.Geteuid(), []instance{{PID: 300}}) if err != nil || handled != trial.handled || handled && reader.PID != 300 { t.Fatalf("reader=%+v handled=%v err=%v; want handled=%v", reader, handled, err, trial.handled) } @@ -105,16 +105,16 @@ func TestFixtureScreenInspectionExcludesHostAndKeepsPrivateSessions(t *testing.T } } -func run_reader_process(mode string) { +func runReaderProcess(mode string) { encoder := json.NewEncoder(os.Stdout) directory := os.Getenv("FENRIR_CONTROL_DIRECTORY") // Processes above the test coordinator belong to the host, not this fixture. // Screen sessions created by the native test remain inside the inspected tree. coordinator := os.Getppid() lookup := func(ancestors []int, uid int, readers []instance) (instance, bool, error) { - return attached_screen_reader("/proc", fixture_ancestors(ancestors, coordinator), uid, readers) + return attachedScreenReader("/proc", fixtureAncestors(ancestors, coordinator), uid, readers) } - server, err := open_server(context.Background(), Options{Directory: directory, RegistryDirectory: filepath.Join(directory, "registry"), TerminalMode: mode == "terminal", WindowID: os.Getenv("WINDOWID")}, lookup) + server, err := openServer(context.Background(), Options{Directory: directory, RegistryDirectory: filepath.Join(directory, "registry"), TerminalMode: mode == "terminal", WindowID: os.Getenv("WINDOWID")}, lookup) if err != nil { _ = encoder.Encode(processReply{Error: err.Error()}) return @@ -138,7 +138,7 @@ func run_reader_process(mode string) { if json.Unmarshal(scanner.Bytes(), &request) != nil || request.Stop { return } - command := child_command("client") + command := childCommand("client") command.Env = append(command.Env, "FENRIR_CONTROL_PATH="+request.Path, "FENRIR_CONTROL_TEXT="+request.Text) data, err := command.Output() var reply processReply @@ -159,9 +159,9 @@ type readerProcess struct { stopped bool } -func start_reader_process(t *testing.T, directory, mode string) *readerProcess { +func startReaderProcess(t *testing.T, directory, mode string) *readerProcess { t.Helper() - command := child_command(mode) + command := childCommand(mode) command.Env = append(command.Env, "FENRIR_CONTROL_DIRECTORY="+directory) command.Stderr = os.Stderr input, err := command.StdinPipe() @@ -218,7 +218,7 @@ func (p *readerProcess) send(t *testing.T, path, text string) processReply { return reply } -func check_receipt(t *testing.T, reply processReply, instancePID int, text string) { +func checkReceipt(t *testing.T, reply processReply, instancePID int, text string) { t.Helper() var receipt requestReceipt if err := json.Unmarshal([]byte(reply.Response), &receipt); err != nil { @@ -229,7 +229,7 @@ func check_receipt(t *testing.T, reply processReply, instancePID int, text strin } } -func wait_main_owner(t *testing.T, observer *Server, expectedCount int, excludedPID int) int { +func waitMainOwner(t *testing.T, observer *Server, expectedCount int, excludedPID int) int { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { @@ -253,21 +253,21 @@ func wait_main_owner(t *testing.T, observer *Server, expectedCount int, excluded func TestReadersCoexistInBothStartupOrdersAndSurviveOwnerExit(t *testing.T) { for _, order := range []string{"tty-first", "terminal-first"} { t.Run(order, func(t *testing.T) { - options := private_options(t) + options := privateOptions(t) observer := &Server{ctx: context.Background(), options: options} - mainPath := observer.main_path() + mainPath := observer.mainPath() var tty, first, second, owner *readerProcess if order == "tty-first" { - tty = start_reader_process(t, options.Directory, "tty") + tty = startReaderProcess(t, options.Directory, "tty") owner = tty - first = start_reader_process(t, options.Directory, "terminal") + first = startReaderProcess(t, options.Directory, "terminal") } else { - first = start_reader_process(t, options.Directory, "terminal") + first = startReaderProcess(t, options.Directory, "terminal") owner = first - tty = start_reader_process(t, options.Directory, "tty") + tty = startReaderProcess(t, options.Directory, "tty") } - second = start_reader_process(t, options.Directory, "terminal") - if got := wait_main_owner(t, observer, 3, 0); got != owner.pid { + second = startReaderProcess(t, options.Directory, "terminal") + if got := waitMainOwner(t, observer, 3, 0); got != owner.pid { t.Fatal("startup replaced the shared owner", got, owner.pid) } listing := first.send(t, mainPath, "COMMAND LS").Response @@ -277,12 +277,12 @@ func TestReadersCoexistInBothStartupOrdersAndSurviveOwnerExit(t *testing.T) { } } for _, reader := range []*readerProcess{tty, first, second} { - check_receipt(t, reader.send(t, mainPath, "COMMAND SAY shared"), reader.pid, "COMMAND SAY shared") + checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY shared"), reader.pid, "COMMAND SAY shared") privatePath := filepath.Join(options.Directory, fmt.Sprintf("fenrirscreenreader-%d.sock", reader.pid)) - check_receipt(t, second.send(t, privatePath, "COMMAND SAY private"), reader.pid, "COMMAND SAY private") + checkReceipt(t, second.send(t, privatePath, "COMMAND SAY private"), reader.pid, "COMMAND SAY private") } // An unrelated caller must not fall through to the console reader. - client := child_command("client") + client := childCommand("client") client.Env = append(client.Env, "FENRIR_CONTROL_PATH="+mainPath, "FENRIR_CONTROL_TEXT=COMMAND SAY legacy") data, err := client.Output() if err != nil { @@ -296,19 +296,19 @@ func TestReadersCoexistInBothStartupOrdersAndSurviveOwnerExit(t *testing.T) { t.Fatal("unidentified caller reached a reader", reply) } owner.stop(t) - wait_main_owner(t, observer, 2, owner.pid) + waitMainOwner(t, observer, 2, owner.pid) for _, reader := range []*readerProcess{tty, first, second} { if reader != owner { - check_receipt(t, reader.send(t, mainPath, "COMMAND SAY survivor"), reader.pid, "COMMAND SAY survivor") + checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY survivor"), reader.pid, "COMMAND SAY survivor") } } }) } } -func external_request(t *testing.T, path, text string) processReply { +func externalRequest(t *testing.T, path, text string) processReply { t.Helper() - client := child_command("client") + client := childCommand("client") client.Env = append(client.Env, "FENRIR_CONTROL_PATH="+path, "FENRIR_CONTROL_TEXT="+text) data, err := client.Output() if err != nil { @@ -322,20 +322,20 @@ func external_request(t *testing.T, path, text string) processReply { } func TestTerminalReadersRejectAmbiguityAndRecoverAfterOwnerFailure(t *testing.T) { - options := private_options(t) + options := privateOptions(t) observer := &Server{ctx: context.Background(), options: options} - mainPath := observer.main_path() - first := start_reader_process(t, options.Directory, "terminal") - second := start_reader_process(t, options.Directory, "terminal") - third := start_reader_process(t, options.Directory, "terminal") - wait_main_owner(t, observer, 3, 0) + mainPath := observer.mainPath() + first := startReaderProcess(t, options.Directory, "terminal") + second := startReaderProcess(t, options.Directory, "terminal") + third := startReaderProcess(t, options.Directory, "terminal") + waitMainOwner(t, observer, 3, 0) for _, reader := range []*readerProcess{first, second, third} { - check_receipt(t, reader.send(t, mainPath, "COMMAND SAY terminal"), reader.pid, "COMMAND SAY terminal") + checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY terminal"), reader.pid, "COMMAND SAY terminal") } - if reply := external_request(t, mainPath, "COMMAND SAY ambiguous"); !strings.Contains(reply.Response, "unique reader") { + if reply := externalRequest(t, mainPath, "COMMAND SAY ambiguous"); !strings.Contains(reply.Response, "unique reader") { t.Fatal("arbitrary terminal selected", reply) } - if reply := external_request(t, mainPath, "LIST"); strings.Count(reply.Response, "pid=") != 6 { + if reply := externalRequest(t, mainPath, "LIST"); strings.Count(reply.Response, "pid=") != 6 { // Each record contains both pid= and ppid=. t.Fatal("ambiguous caller could not discover instances", reply) } @@ -367,9 +367,9 @@ func TestTerminalReadersRejectAmbiguityAndRecoverAfterOwnerFailure(t *testing.T) t.Fatal(err) } _ = first.command.Wait() - wait_main_owner(t, observer, 2, first.pid) + waitMainOwner(t, observer, 2, first.pid) for _, reader := range []*readerProcess{second, third} { - check_receipt(t, reader.send(t, mainPath, "COMMAND SAY recovered"), reader.pid, "COMMAND SAY recovered") + checkReceipt(t, reader.send(t, mainPath, "COMMAND SAY recovered"), reader.pid, "COMMAND SAY recovered") } } @@ -382,48 +382,48 @@ func TestWindowRoutingWithoutReaderAncestor(t *testing.T) { name = "console-first" } t.Run(name, func(t *testing.T) { - options := private_options(t) + options := privateOptions(t) observer := &Server{ctx: context.Background(), options: options} - mainPath := observer.main_path() + mainPath := observer.mainPath() t.Setenv("DISPLAY", ":fixture") t.Setenv("WINDOWID", "42") var terminal *readerProcess if consoleFirst { - start_reader_process(t, options.Directory, "tty") + startReaderProcess(t, options.Directory, "tty") } - terminal = start_reader_process(t, options.Directory, "terminal") + terminal = startReaderProcess(t, options.Directory, "terminal") if !consoleFirst { - start_reader_process(t, options.Directory, "tty") + startReaderProcess(t, options.Directory, "tty") } // This client is a sibling, not a child, of the terminal reader. text := "command application codex" - check_receipt(t, external_request(t, mainPath, text), terminal.pid, text) + checkReceipt(t, externalRequest(t, mainPath, text), terminal.pid, text) t.Setenv("WINDOWID", "43") - second := start_reader_process(t, options.Directory, "terminal") - check_receipt(t, external_request(t, mainPath, text), second.pid, text) + second := startReaderProcess(t, options.Directory, "terminal") + checkReceipt(t, externalRequest(t, mainPath, text), second.pid, text) t.Setenv("WINDOWID", "42") - check_receipt(t, external_request(t, mainPath, text), terminal.pid, text) + checkReceipt(t, externalRequest(t, mainPath, text), terminal.pid, text) // Even a sole terminal on a different display is not a match. t.Setenv("DISPLAY", ":other") - if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { + if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { t.Fatal("cross-display routing", reply) } t.Setenv("DISPLAY", ":fixture") t.Setenv("WINDOWID", "unknown") - if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { + if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { t.Fatal("unknown window routed", reply) } t.Setenv("WINDOWID", "") - if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { + if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { t.Fatal("unidentified background caller routed", reply) } t.Setenv("WINDOWID", "42") - start_reader_process(t, options.Directory, "terminal") - if reply := external_request(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { + startReaderProcess(t, options.Directory, "terminal") + if reply := externalRequest(t, mainPath, text); !strings.Contains(reply.Response, "unique reader") { t.Fatal("duplicate window routed arbitrarily", reply) } // Discovery remains usable when routing is ambiguous. - if reply := external_request(t, mainPath, "ls"); !strings.Contains(reply.Response, "pid=") { + if reply := externalRequest(t, mainPath, "ls"); !strings.Contains(reply.Response, "pid=") { t.Fatal("discovery failed", reply) } }) @@ -431,7 +431,7 @@ func TestWindowRoutingWithoutReaderAncestor(t *testing.T) { } func TestConsoleIdentityAndUnknownCallers(t *testing.T) { - options := private_options(t) + options := privateOptions(t) console := instance{PID: os.Getpid(), uid: os.Geteuid(), ScreenDriver: "vcsaDriver"} server := &Server{ctx: context.Background(), options: options} for _, trial := range []struct { @@ -448,13 +448,13 @@ func TestConsoleIdentityAndUnknownCallers(t *testing.T) { {"unknown window", processIdentity{window: "42", display: ":fixture"}, []instance{console}, false}, } { t.Run(trial.name, func(t *testing.T) { - _, err := server.route_identity(trial.identity, os.Geteuid(), nil, trial.consoles) + _, err := server.routeIdentity(trial.identity, os.Geteuid(), nil, trial.consoles) if (err == nil) != trial.valid { t.Fatal("unexpected routing", err) } }) } - if got := process_identity(os.Getpid(), os.Geteuid()+1); got != (processIdentity{}) { + if got := lookupProcessIdentity(os.Getpid(), os.Geteuid()+1); got != (processIdentity{}) { t.Fatal("read identity of a different UID", got) } } diff --git a/internal/control/handoff_linux.go b/internal/control/handoff_linux.go index 4b4e92d0..2562e45d 100644 --- a/internal/control/handoff_linux.go +++ b/internal/control/handoff_linux.go @@ -55,7 +55,7 @@ func handoff(caller *net.UnixConn, path string) error { return sendErr } -func receive_request(connection *net.UnixConn) (string, *net.UnixConn, error) { +func receiveRequest(connection *net.UnixConn) (string, *net.UnixConn, error) { _ = connection.SetReadDeadline(time.Now().Add(250 * time.Millisecond)) var buffer [8192]byte control := make([]byte, syscall.CmsgSpace(4)) @@ -108,6 +108,6 @@ func receive_request(connection *net.UnixConn) (string, *net.UnixConn, error) { } return "", unix, nil } - text, err := read_request(connection, buffer[:count]) + text, err := readRequest(connection, buffer[:count]) return text, nil, err } diff --git a/internal/control/handoff_test.go b/internal/control/handoff_test.go index d96cfe3e..484bfbe0 100644 --- a/internal/control/handoff_test.go +++ b/internal/control/handoff_test.go @@ -12,14 +12,14 @@ import ( "testing" ) -func socket_pair(t *testing.T, path string) (*net.UnixConn, *net.UnixConn) { +func socketPair(t *testing.T, path string) (*net.UnixConn, *net.UnixConn) { t.Helper() listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { t.Fatal(err) } t.Cleanup(func() { listener.Close() }) - client := connect_remote(t, path) + client := connectRemote(t, path) server, err := listener.AcceptUnix() if err != nil { t.Fatal(err) @@ -29,8 +29,8 @@ func socket_pair(t *testing.T, path string) (*net.UnixConn, *net.UnixConn) { } func TestHandoffReadsOriginalCallerBytesAndRejectsInvalidDescriptors(t *testing.T) { - options := private_options(t) - caller, original := socket_pair(t, filepath.Join(options.Directory, "caller.sock")) + options := privateOptions(t) + caller, original := socketPair(t, filepath.Join(options.Directory, "caller.sock")) if _, err := io.WriteString(caller, "COMMAND SAY original\n"); err != nil { t.Fatal(err) } @@ -55,12 +55,12 @@ func TestHandoffReadsOriginalCallerBytesAndRejectsInvalidDescriptors(t *testing. {"header", "INVALID\n", []int{int(file.Fd())}, false}, } { t.Run(trial.name, func(t *testing.T) { - sender, receiver := socket_pair(t, filepath.Join(options.Directory, trial.name+".sock")) + sender, receiver := socketPair(t, filepath.Join(options.Directory, trial.name+".sock")) if _, _, err := sender.WriteMsgUnix([]byte(trial.header), syscall.UnixRights(trial.fds...), nil); err != nil { t.Fatal(err) } _ = sender.CloseWrite() - _, forwarded, err := receive_request(receiver) + _, forwarded, err := receiveRequest(receiver) if !trial.valid { if forwarded != nil { forwarded.Close() @@ -78,7 +78,7 @@ func TestHandoffReadsOriginalCallerBytesAndRejectsInvalidDescriptors(t *testing. if err != nil || pid != os.Getpid() || uid != os.Geteuid() { t.Fatal("caller credentials changed", pid, uid, err) } - text, err := read_request(forwarded, nil) + text, err := readRequest(forwarded, nil) if err != nil || text != "COMMAND SAY original" { t.Fatal("handoff substituted caller bytes", text, err) } diff --git a/internal/control/registry_linux.go b/internal/control/registry_linux.go index ba4c3975..359c117d 100644 --- a/internal/control/registry_linux.go +++ b/internal/control/registry_linux.go @@ -44,7 +44,7 @@ type instance struct { uid int } -func (s *Server) registry_dir() string { +func (s *Server) registryDir() string { if s.options.RegistryDirectory != "" { return s.options.RegistryDirectory } @@ -52,7 +52,7 @@ func (s *Server) registry_dir() string { } func (s *Server) register() error { - dir := s.registry_dir() + dir := s.registryDir() if err := os.Mkdir(dir, os.ModeSticky|0777); err != nil && !os.IsExist(err) { return err } @@ -81,9 +81,9 @@ func (s *Server) register() error { if s.options.TerminalMode { data.ScreenDriver, data.KeyboardDriver, data.WindowID = "ptyDriver", "x11Driver", s.options.WindowID } - for _, endpoint := range s.endpoint_snapshot() { + for _, endpoint := range s.endpointSnapshot() { data.SocketFiles = append(data.SocketFiles, endpoint.path) - data.MainSocket = data.MainSocket || endpoint.path == s.main_path() + data.MainSocket = data.MainSocket || endpoint.path == s.mainPath() } encoded, err := json.Marshal(data) if err != nil { @@ -93,7 +93,8 @@ func (s *Server) register() error { if err != nil { return err } - defer os.Remove(file.Name()) + // After a successful rename the temporary name no longer exists. + defer func() { _ = os.Remove(file.Name()) }() if _, err := file.Write(append(encoded, '\n')); err != nil { file.Close() return err @@ -113,7 +114,7 @@ func (s *Server) register() error { return nil } -func (s *Server) refresh_registry() { +func (s *Server) refreshRegistry() { ticker := time.NewTicker(200 * time.Millisecond) lastRefresh := time.Now() defer ticker.Stop() @@ -122,7 +123,7 @@ func (s *Server) refresh_registry() { case <-s.ctx.Done(): return case <-ticker.C: - if s.claim_main() || time.Since(lastRefresh) >= 10*time.Second { + if s.claimMain() || time.Since(lastRefresh) >= 10*time.Second { _ = s.register() lastRefresh = time.Now() } @@ -131,7 +132,7 @@ func (s *Server) refresh_registry() { } func (s *Server) instances() []instance { - entries, _ := os.ReadDir(s.registry_dir()) + entries, _ := os.ReadDir(s.registryDir()) var instances []instance for _, entry := range entries { if s.ctx.Err() != nil { @@ -140,7 +141,7 @@ func (s *Server) instances() []instance { if !strings.HasSuffix(entry.Name(), ".json") { continue } - path := filepath.Join(s.registry_dir(), entry.Name()) + path := filepath.Join(s.registryDir(), entry.Name()) file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) if err != nil { continue @@ -185,7 +186,7 @@ func (s *Server) list() string { return strings.Join(lines, "\n") } -func parent_pid(pid int) int { +func parentPid(pid int) int { data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) if err != nil { return 0 diff --git a/internal/control/screen_linux.go b/internal/control/screen_linux.go index 480cc47c..5b06f90e 100644 --- a/internal/control/screen_linux.go +++ b/internal/control/screen_linux.go @@ -17,11 +17,11 @@ import ( // its current display processes through the server's open terminal devices, // then use their reader ancestry. No Screen commands or init services are used. // procRoot is explicit so device, ownership and ambiguity cases can be tested. -func attached_screen_reader(procRoot string, ancestors []int, uid int, readers []instance) (instance, bool, error) { +func attachedScreenReader(procRoot string, ancestors []int, uid int, readers []instance) (instance, bool, error) { for _, pid := range ancestors { processPath := filepath.Join(procRoot, strconv.Itoa(pid)) info, err := os.Stat(processPath) - if err != nil || !owned_by(info, uid) { + if err != nil || !ownedBy(info, uid) { continue } command, err := os.ReadFile(filepath.Join(processPath, "cmdline")) @@ -37,18 +37,18 @@ func attached_screen_reader(procRoot string, ancestors []int, uid int, readers [ if err != nil { continue } - reader, err := screen_display_reader(procRoot, processPath, uid, executable, readers) + reader, err := screenDisplayReader(procRoot, processPath, uid, executable, readers) return reader, true, err } return instance{}, false, nil } -func owned_by(info os.FileInfo, uid int) bool { +func ownedBy(info os.FileInfo, uid int) bool { stat, ok := info.Sys().(*syscall.Stat_t) return ok && int(stat.Uid) == uid } -func screen_display_reader(procRoot, serverPath string, uid int, executable os.FileInfo, readers []instance) (instance, error) { +func screenDisplayReader(procRoot, serverPath string, uid int, executable os.FileInfo, readers []instance) (instance, error) { fdPath := filepath.Join(serverPath, "fd") files, err := os.ReadDir(fdPath) if err != nil { @@ -79,14 +79,14 @@ func screen_display_reader(procRoot, serverPath string, uid int, executable os.F } path := filepath.Join(procRoot, process.Name()) info, err := os.Stat(path) - if err != nil || !owned_by(info, uid) { + if err != nil || !ownedBy(info, uid) { continue } data, err := os.ReadFile(filepath.Join(path, "stat")) if err != nil { continue } - _, tty := process_parent_tty(data) + _, tty := processParentTty(data) if tty == 0 || !displays[tty] { continue } @@ -113,7 +113,7 @@ func screen_display_reader(procRoot, serverPath string, uid int, executable os.F if err != nil { break } - ancestor, _ = process_parent_tty(data) + ancestor, _ = processParentTty(data) } } if len(matches) == 1 { @@ -124,7 +124,7 @@ func screen_display_reader(procRoot, serverPath string, uid int, executable os.F return instance{}, fmt.Errorf("Screen session does not identify a unique attached reader; use its private socket") } -func process_parent_tty(data []byte) (int, uint32) { +func processParentTty(data []byte) (int, uint32) { end := bytes.LastIndexByte(data, ')') if end < 0 { return 0, 0 diff --git a/internal/control/screen_native_test.go b/internal/control/screen_native_test.go index 782bbfa0..e1a6e627 100644 --- a/internal/control/screen_native_test.go +++ b/internal/control/screen_native_test.go @@ -66,13 +66,13 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) { if err != nil { t.Skip("GNU Screen not installed") } - options := private_options(t) + options := privateOptions(t) // The shared owner and an unrelated old-window reader must never receive // messages intended for the terminal displaying the reattached session. t.Setenv("DISPLAY", ":fixture") t.Setenv("WINDOWID", "old") - start_reader_process(t, options.Directory, "tty") - start_reader_process(t, options.Directory, "terminal") + startReaderProcess(t, options.Directory, "tty") + startReaderProcess(t, options.Directory, "terminal") options.TerminalMode, options.WindowID = true, "current" server, err := Open(context.Background(), options) if err != nil { @@ -117,7 +117,7 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) { } defer connection.Close() connection.SetDeadline(time.Now().Add(3 * time.Second)) - if err := json.NewEncoder(connection).Encode(processCommand{Path: server.main_path(), Text: text}); err != nil { + if err := json.NewEncoder(connection).Encode(processCommand{Path: server.mainPath(), Text: text}); err != nil { t.Fatal(err) } var reply processReply @@ -137,7 +137,7 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) { time.Sleep(10 * time.Millisecond) } if reply := send("COMMAND SAY detached"); !strings.Contains(reply.Response, "unique attached reader") { - for pid := reply.PID; pid > 1; pid = parent_pid(pid) { + for pid := reply.PID; pid > 1; pid = parentPid(pid) { command, _ := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) executable, _ := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid)) t.Logf("ancestor %d command %q executable %q", pid, command, executable) @@ -175,7 +175,7 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) { for { reply := send("COMMAND SAY attached") if !strings.HasPrefix(reply.Response, "Remote routing failed:") { - check_receipt(t, reply, os.Getpid(), "COMMAND SAY attached") + checkReceipt(t, reply, os.Getpid(), "COMMAND SAY attached") break } if time.Now().After(deadline) { @@ -183,5 +183,5 @@ func TestNativeScreenReattachmentRoutesSayAndNotify(t *testing.T) { } time.Sleep(10 * time.Millisecond) } - check_receipt(t, send("COMMAND NOTIFY notification"), os.Getpid(), "COMMAND NOTIFY notification") + checkReceipt(t, send("COMMAND NOTIFY notification"), os.Getpid(), "COMMAND NOTIFY notification") } diff --git a/internal/control/screen_test.go b/internal/control/screen_test.go index 3b295b99..2842fd61 100644 --- a/internal/control/screen_test.go +++ b/internal/control/screen_test.go @@ -17,7 +17,7 @@ type screenFixture struct { t *testing.T } -func new_screen_fixture(t *testing.T) screenFixture { +func newScreenFixture(t *testing.T) screenFixture { t.Helper() f := screenFixture{root: t.TempDir(), t: t} f.executable = filepath.Join(f.root, "screen") @@ -72,7 +72,7 @@ func (f screenFixture) attach(pid, reader int, device string, sameExecutable boo func TestScreenAttachmentRouting(t *testing.T) { for _, scenario := range []string{"attached", "detached", "other executable", "ambiguous", "duplicate displays", "reattached", "no reader", "wrong uid"} { t.Run(scenario, func(t *testing.T) { - f := new_screen_fixture(t) + f := newScreenFixture(t) uid := os.Geteuid() readers := []instance{{PID: 300}, {PID: 400}} if scenario != "detached" { @@ -98,7 +98,7 @@ func TestScreenAttachmentRouting(t *testing.T) { f.process(400, 1, 0, "reader", "") f.attach(201, 400, "/dev/zero", true) } - reader, handled, err := attached_screen_reader(f.root, []int{120, 100}, uid, readers) + reader, handled, err := attachedScreenReader(f.root, []int{120, 100}, uid, readers) valid := scenario == "attached" || scenario == "duplicate displays" || scenario == "reattached" if handled != (scenario != "wrong uid") || (err == nil && handled) != valid { t.Fatal(reader, handled, err) @@ -117,17 +117,17 @@ func TestScreenAttachmentRouting(t *testing.T) { } func TestScreenRoutingIgnoresEnvironmentWithoutServerAncestor(t *testing.T) { - f := new_screen_fixture(t) + f := newScreenFixture(t) f.attach(200, 300, "/dev/null", true) t.Setenv("STY", "100.session") - if _, handled, err := attached_screen_reader(f.root, []int{120}, os.Geteuid(), []instance{{PID: 300}}); handled || err != nil { + if _, handled, err := attachedScreenReader(f.root, []int{120}, os.Geteuid(), []instance{{PID: 300}}); handled || err != nil { t.Fatal("environment selected an unrelated Screen session", handled, err) } // A broken ancestry cycle must terminate without choosing an unrelated reader. f.process(301, 302, 0, "cycle", "") f.process(302, 301, 0, "cycle", "") f.attach(201, 301, "/dev/zero", true) - reader, handled, err := attached_screen_reader(f.root, []int{120, 100}, os.Geteuid(), []instance{{PID: 300}}) + reader, handled, err := attachedScreenReader(f.root, []int{120, 100}, os.Geteuid(), []instance{{PID: 300}}) if !handled || err != nil || reader.PID != 300 { t.Fatal(reader, handled, err) } diff --git a/internal/control/server_linux.go b/internal/control/server_linux.go index 0c552c57..bed06d33 100644 --- a/internal/control/server_linux.go +++ b/internal/control/server_linux.go @@ -76,7 +76,7 @@ type Server struct { done chan struct{} } -func (s *Server) main_path() string { +func (s *Server) mainPath() string { if s.options.Directory != "" { return filepath.Join(s.options.Directory, filepath.Base(MainSocket)) } @@ -84,15 +84,15 @@ func (s *Server) main_path() string { } func Open(ctx context.Context, options Options) (*Server, error) { - return open_server(ctx, options, nil) + return openServer(ctx, options, nil) } // Keep process inspection injectable so fixture readers can exclude the host's // terminal ancestry while retaining real sockets, credentials and handoffs. -func open_server(ctx context.Context, options Options, lookup screenLookup) (*Server, error) { +func openServer(ctx context.Context, options Options, lookup screenLookup) (*Server, error) { ctx, cancel := context.WithCancel(ctx) s := &Server{ctx: ctx, cancel: cancel, options: options, screenReader: lookup, requests: make(chan Request, 32), clients: make(chan struct{}, 8), done: make(chan struct{})} - paths := []string{filepath.Join(filepath.Dir(s.main_path()), fmt.Sprintf("fenrirscreenreader-%d.sock", os.Getpid())), s.main_path()} + paths := []string{filepath.Join(filepath.Dir(s.mainPath()), fmt.Sprintf("fenrirscreenreader-%d.sock", os.Getpid())), s.mainPath()} if options.SocketFile != "" { paths = []string{options.SocketFile} } @@ -114,7 +114,7 @@ func open_server(ctx context.Context, options Options, lookup screenLookup) (*Se for _, endpoint := range s.endpoints { s.workers.Go(func() { s.accept(endpoint) }) } - s.workers.Go(s.refresh_registry) + s.workers.Go(s.refreshRegistry) return s, nil } @@ -132,7 +132,7 @@ func listen(path string) (endpoint, error) { return endpoint{}, fmt.Errorf("%w %s", errSocketBusy, path) } if errors.Is(dialErr, syscall.EACCES) { - return endpoint{}, fmt.Errorf("%w %s: %v", errSocketBusy, path, dialErr) + return endpoint{}, fmt.Errorf("%w %s: %w", errSocketBusy, path, dialErr) } if !errors.Is(dialErr, syscall.ECONNREFUSED) { return endpoint{}, fmt.Errorf("cannot establish remote socket is stale: %s: %w", path, dialErr) @@ -165,7 +165,7 @@ func listen(path string) (endpoint, error) { // checked by the application before any request may mutate reader state. if err := os.Chmod(path, 0666); err != nil { listener.Close() - os.Remove(path) + _ = os.Remove(path) // Best effort; the chmod error is reported. return endpoint{}, err } info, err := os.Lstat(path) @@ -239,7 +239,7 @@ func peer(connection *net.UnixConn) (int, int, error) { return int(credentials.Pid), int(credentials.Uid), nil } -func read_request(connection *net.UnixConn, data []byte) (string, error) { +func readRequest(connection *net.UnixConn, data []byte) (string, error) { _ = connection.SetReadDeadline(time.Now().Add(250 * time.Millisecond)) var buffer [8130]byte if len(data) > 8129 { @@ -253,7 +253,7 @@ func read_request(connection *net.UnixConn, data []byte) (string, error) { } if err != nil { var timeout net.Error - if err != io.EOF && !(errors.As(err, &timeout) && timeout.Timeout() && len(data) > 0) { + if !errors.Is(err, io.EOF) && !(errors.As(err, &timeout) && timeout.Timeout() && len(data) > 0) { return "", err } break @@ -276,9 +276,9 @@ func (s *Server) handle(connection *net.UnixConn, path string) { // Route before consuming request bytes. A handed-off descriptor carries // both the caller's kernel credentials and the caller's original request. var routingErr error - if path == s.main_path() { + if path == s.mainPath() { var target string - target, routingErr = s.route_target(pid, uid) + target, routingErr = s.routeTarget(pid, uid) if routingErr == nil && target != "" { routingErr = handoff(connection, target) if routingErr == nil { @@ -286,20 +286,20 @@ func (s *Server) handle(connection *net.UnixConn, path string) { } } } - text, forwarded, err := receive_request(connection) + text, forwarded, err := receiveRequest(connection) if forwarded != nil { defer forwarded.Close() connection = forwarded pid, uid, err = peer(connection) if err == nil { // Handoffs never nest and never supply replacement request text. - text, err = read_request(connection, nil) + text, err = readRequest(connection, nil) } } if err != nil || text == "" { return } - if is_list(text) { + if isList(text) { _ = connection.SetWriteDeadline(time.Now().Add(250 * time.Millisecond)) _, _ = io.WriteString(connection, s.list()+"\n") return @@ -332,7 +332,7 @@ func (s *Server) handle(connection *net.UnixConn, path string) { } } -func is_list(text string) bool { +func isList(text string) bool { switch strings.ToUpper(text) { case "LS", "LIST", "COMMAND LS", "COMMAND LIST": return true diff --git a/internal/control/server_test.go b/internal/control/server_test.go index 3fdc668c..4200621e 100644 --- a/internal/control/server_test.go +++ b/internal/control/server_test.go @@ -30,7 +30,7 @@ import ( "time" ) -func private_options(t *testing.T) Options { +func privateOptions(t *testing.T) Options { t.Helper() directory, err := os.MkdirTemp("/tmp", "fenrir-remote-") if err != nil { @@ -40,7 +40,7 @@ func private_options(t *testing.T) Options { return Options{Directory: directory, RegistryDirectory: filepath.Join(directory, "registry")} } -func connect_remote(t *testing.T, path string) *net.UnixConn { +func connectRemote(t *testing.T, path string) *net.UnixConn { t.Helper() connection, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { @@ -52,13 +52,13 @@ func connect_remote(t *testing.T, path string) *net.UnixConn { } func TestPythonSocketProtocolAndRegistry(t *testing.T) { - options := private_options(t) + options := privateOptions(t) server, err := Open(context.Background(), options) if err != nil { t.Fatal(err) } defer server.Close() - connection := connect_remote(t, server.main_path()) + connection := connectRemote(t, server.mainPath()) if _, err := io.WriteString(connection, "command say Existing Bash script\n"); err != nil { t.Fatal(err) } @@ -72,14 +72,14 @@ func TestPythonSocketProtocolAndRegistry(t *testing.T) { t.Fatal("command was not delivered") } for _, command := range []string{"LIST", "command ls"} { - connection := connect_remote(t, server.main_path()) + connection := connectRemote(t, server.mainPath()) io.WriteString(connection, command+"\n") response, err := io.ReadAll(connection) if err != nil || !strings.Contains(string(response), "screen=vcsaDriver keyboard=evdevDriver main_socket=yes") { t.Fatal(string(response), err) } } - info, err := os.Stat(server.main_path()) + info, err := os.Stat(server.mainPath()) if err != nil || info.Mode().Perm() != 0666 { t.Fatal(info, err) } @@ -90,12 +90,12 @@ func TestPythonSocketProtocolAndRegistry(t *testing.T) { } func TestRequestTimeoutReturnsErrorInsteadOfSilentSuccess(t *testing.T) { - server, err := Open(context.Background(), private_options(t)) + server, err := Open(context.Background(), privateOptions(t)) if err != nil { t.Fatal(err) } defer server.Close() - connection := connect_remote(t, server.main_path()) + connection := connectRemote(t, server.mainPath()) if _, err := io.WriteString(connection, "SETTING SAVE\n"); err != nil { t.Fatal(err) } @@ -111,7 +111,7 @@ func TestRequestTimeoutReturnsErrorInsteadOfSilentSuccess(t *testing.T) { } func TestFullRequestQueueReturnsErrorInsteadOfSilentSuccess(t *testing.T) { - server, err := Open(context.Background(), private_options(t)) + server, err := Open(context.Background(), privateOptions(t)) if err != nil { t.Fatal(err) } @@ -119,7 +119,7 @@ func TestFullRequestQueueReturnsErrorInsteadOfSilentSuccess(t *testing.T) { for range cap(server.requests) { server.requests <- Request{} } - connection := connect_remote(t, server.main_path()) + connection := connectRemote(t, server.mainPath()) if _, err := io.WriteString(connection, "SETTING SAVE\n"); err != nil { t.Fatal(err) } @@ -132,12 +132,12 @@ func TestFullRequestQueueReturnsErrorInsteadOfSilentSuccess(t *testing.T) { func TestCancelledRequestReturnsUnknownCompletion(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - server, err := Open(ctx, private_options(t)) + server, err := Open(ctx, privateOptions(t)) if err != nil { t.Fatal(err) } defer server.Close() - connection := connect_remote(t, server.main_path()) + connection := connectRemote(t, server.mainPath()) if _, err := io.WriteString(connection, "SETTING SAVE\n"); err != nil { t.Fatal(err) } @@ -154,7 +154,7 @@ func TestCancelledRequestReturnsUnknownCompletion(t *testing.T) { } func TestSocketCoexistenceAndCleanupNeverReplaceActiveReader(t *testing.T) { - options := private_options(t) + options := privateOptions(t) server, err := Open(context.Background(), options) if err != nil { t.Fatal(err) @@ -168,7 +168,7 @@ func TestSocketCoexistenceAndCleanupNeverReplaceActiveReader(t *testing.T) { if len(server.instances()) != 1 { t.Fatal("active registry entry removed") } - if connection, err := net.Dial("unix", server.main_path()); err != nil { + if connection, err := net.Dial("unix", server.mainPath()); err != nil { t.Fatal("main socket lost", err) } else { connection.Close() @@ -177,7 +177,7 @@ func TestSocketCoexistenceAndCleanupNeverReplaceActiveReader(t *testing.T) { func TestSocketRejectsSymlinksAndUnrelatedFiles(t *testing.T) { for _, symlink := range []bool{false, true} { - options := private_options(t) + options := privateOptions(t) path := filepath.Join(options.Directory, "fenrirscreenreader-daemon.sock") if symlink { if err := os.Symlink("/dev/null", path); err != nil { @@ -197,16 +197,16 @@ func TestSocketRejectsSymlinksAndUnrelatedFiles(t *testing.T) { } func TestSilentAndOversizedClientsDoNotBlockOtherRequests(t *testing.T) { - server, err := Open(context.Background(), private_options(t)) + server, err := Open(context.Background(), privateOptions(t)) if err != nil { t.Fatal(err) } defer server.Close() - silent := connect_remote(t, server.main_path()) + silent := connectRemote(t, server.mainPath()) defer silent.Close() - oversized := connect_remote(t, server.main_path()) + oversized := connectRemote(t, server.mainPath()) io.WriteString(oversized, strings.Repeat("x", 9000)) - good := connect_remote(t, server.main_path()) + good := connectRemote(t, server.mainPath()) io.WriteString(good, "COMMAND INTERRUPT\n") select { case request := <-server.Requests(): @@ -225,7 +225,7 @@ func TestSilentAndOversizedClientsDoNotBlockOtherRequests(t *testing.T) { } func TestStaleSocketReplacementAndPrivateInstanceSelection(t *testing.T) { - options := private_options(t) + options := privateOptions(t) path := filepath.Join(options.Directory, "stale.sock") old, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { @@ -257,11 +257,11 @@ func TestStaleSocketReplacementAndPrivateInstanceSelection(t *testing.T) { } options.TerminalMode = true server := &Server{ctx: context.Background(), options: options} - target, err := server.route_target(pid, os.Geteuid()) + target, err := server.routeTarget(pid, os.Geteuid()) if err != nil || target != privatePath { t.Fatal("registered ancestor instance not selected", target, err) } - target, err = server.route_target(pid, os.Geteuid()+1) + target, err = server.routeTarget(pid, os.Geteuid()+1) if err == nil || target != "" { t.Fatal("forwarded to another user's instance", target, err) } diff --git a/internal/datetime/datetime.go b/internal/datetime/datetime.go deleted file mode 100644 index e3c4e4fa..00000000 --- a/internal/datetime/datetime.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// Authors: Storm Dragon, Angus Kola -// SPDX-License-Identifier: GPL-3.0-or-later - -package datetime - -import common "git.stormux.org/storm/screenreader-common/datetime" - -type Option = common.Option - -var Time_options = common.TimeOptions -var Date_options = common.DateOptions -var Format_time = common.FormatTime -var Format_date = common.FormatDate -var Valid_time = common.ValidTime -var Valid_date = common.ValidDate diff --git a/internal/datetime/datetime_test.go b/internal/datetime/datetime_test.go deleted file mode 100644 index ca0ded53..00000000 --- a/internal/datetime/datetime_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later - -package datetime - -import ( - "testing" - "time" -) - -func TestFormatsAndExamples(t *testing.T) { - now := time.Date(2026, 10, 25, 14, 5, 9, 0, time.FixedZone("fixture", -4*3600)) - for _, testCase := range []struct { - id, want string - date bool - }{ - {"24-hour", "14:05", false}, - {"24-hour-seconds", "14:05:09", false}, - {"24-hour-words", "14 hours and 05 minutes", false}, - {"24-hour-seconds-words", "14 hours, 05 minutes and 09 seconds", false}, - {"numbers-dm", "25/10", true}, - {"numbers-md", "10/25", true}, - {"numbers-dmy", "25/10/2026", true}, - {"numbers-mdy", "10/25/2026", true}, - {"numbers-ymd", "2026/10/25", true}, - } { - format := Format_time - if testCase.date { - format = Format_date - } - if got, ok := format(testCase.id, now); !ok || got != testCase.want { - t.Fatal(testCase.id, got, ok) - } - } - for _, date := range []bool{false, true} { - options, format, valid := Time_options(now), Format_time, Valid_time - if date { - options, format, valid = Date_options(now), Format_date, Valid_date - } - for _, option := range options { - got, ok := format(option.Value, now) - if !ok || !valid(option.Value) || got == "" || got != option.Label { - t.Fatal(option, got, ok) - } - } - if got, ok := format("%arbitrary", now); ok || got != "" || valid("%arbitrary") { - t.Fatal("invalid preset accepted") - } - } - if got, _ := Format_time("24-hour-seconds", now.Add(10*time.Hour)); got != "00:05:09" { - t.Fatal(got) - } -} diff --git a/internal/emoji/catalog.go b/internal/emoji/catalog.go index a47b060b..a9d9a0b6 100644 --- a/internal/emoji/catalog.go +++ b/internal/emoji/catalog.go @@ -6,44 +6,32 @@ package emoji import ( - "sort" - "git.stormux.org/storm/fenrir/internal/interaction" commonemoji "git.stormux.org/storm/screenreader-common/emoji" ) const MenuTitle = "Emoji Menu" -// New_session builds an independent draft. Search is local to each category; +// NewSession builds an independent draft. Search is local to each category; // the first All tab searches the complete catalog. -func New_session() (*interaction.Session, error) { +func NewSession() (*interaction.Session, error) { form := interaction.Form{Type: interaction.TabForm, Title: MenuTitle} - var all []interaction.Choice - sharedCategories := commonemoji.Categories() - addTab := func(id, label string, choices []interaction.Choice) { - form.Tabs = append(form.Tabs, interaction.Tab{ID: id, Label: label, Controls: []interaction.Control{{ - ID: "emoji", Label: "Emoji", Kind: interaction.Grid, Choices: choices, Columns: 6, Action: "copy_emoji", - }}}) - } - for _, category := range sharedCategories { - choices := make([]interaction.Choice, len(category.Entries)) - for index, entry := range category.Entries { + for _, tab := range commonemoji.PickerTabs() { + choices := make([]interaction.Choice, len(tab.Entries)) + for index, entry := range tab.Entries { choices[index] = interaction.Choice{ID: entry.ID, Label: entry.Label} } - all = append(all, choices...) - addTab(category.ID, category.Label, choices) + form.Tabs = append(form.Tabs, interaction.Tab{ID: tab.ID, Label: tab.Label, Controls: []interaction.Control{{ + ID: "emoji", Label: "Emoji", Kind: interaction.Grid, Choices: choices, Columns: commonemoji.PickerColumns, Action: "copy_emoji", + }}}) } - sort.SliceStable(all, func(i, j int) bool { return all[i].Label < all[j].Label }) - form.Tabs = append([]interaction.Tab{{ID: "all", Label: "All", Controls: []interaction.Control{{ - ID: "emoji", Label: "Emoji", Kind: interaction.Grid, Choices: all, Columns: 6, Action: "copy_emoji", - }}}}, form.Tabs...) - return interaction.New_session(form) + return interaction.NewSession(form) } // Selection returns the selected Unicode sequence and readable name. It never // returns a selection from another tab or from an empty search. func Selection(session *interaction.Session) (string, string, bool) { - control, ok := session.Focused_control() + control, ok := session.FocusedControl() if !ok || control.Kind != interaction.Grid || control.Selected < 0 || control.Selected >= len(control.Choices) { return "", "", false } diff --git a/internal/emoji/catalog_test.go b/internal/emoji/catalog_test.go index 9e6b6d68..747ee3cf 100644 --- a/internal/emoji/catalog_test.go +++ b/internal/emoji/catalog_test.go @@ -14,7 +14,7 @@ import ( ) func TestCategorySelectionAndIndependentSearches(t *testing.T) { - session, err := New_session() + session, err := NewSession() if err != nil { t.Fatal(err) } @@ -42,12 +42,12 @@ func TestCategorySelectionAndIndependentSearches(t *testing.T) { if value, _, _ := Selection(session); value != "🇯🇵" { t.Fatal("All search/selection not retained", value) } - other, err := New_session() + other, err := NewSession() if err != nil { t.Fatal(err) } other.Handle(interaction.Key{Name: "tab"}) - control, controlOK := other.Focused_control() + control, controlOK := other.FocusedControl() value, _, selectionOK := Selection(other) if !controlOK || control.Text != "" || !selectionOK || value == "🇯🇵" { t.Fatal("new session inherited previous search") @@ -57,7 +57,7 @@ func TestCategorySelectionAndIndependentSearches(t *testing.T) { func TestBundledTranslationSearchPreservesEmoji(t *testing.T) { previous := i18n.Use(i18n.New(t.TempDir(), "de")) t.Cleanup(func() { i18n.Use(previous) }) - session, err := New_session() + session, err := NewSession() if err != nil { t.Fatal(err) } @@ -117,7 +117,7 @@ func TestExpandedCatalogCategoriesAndUniqueEmojiIDs(t *testing.T) { } func TestKissMarkSearch(t *testing.T) { - session, err := New_session() + session, err := NewSession() if err != nil { t.Fatal(err) } @@ -128,7 +128,7 @@ func TestKissMarkSearch(t *testing.T) { } previous := i18n.Use(i18n.New(t.TempDir(), "de")) t.Cleanup(func() { i18n.Use(previous) }) - localized, err := New_session() + localized, err := NewSession() if err != nil { t.Fatal(err) } @@ -140,7 +140,7 @@ func TestKissMarkSearch(t *testing.T) { } func TestNewCategoryNavigation(t *testing.T) { - session, err := New_session() + session, err := NewSession() if err != nil { t.Fatal(err) } diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index ba1eafa8..e7214e61 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -15,105 +15,45 @@ // You should have received a copy of the GNU General Public License along with // this program. If not, see . -// Package i18n combines installed and bundled Fenrir gettext catalogs. Screen -// contents and internal command/cue IDs must never pass through this package. +// Package i18n is Fenrir's setup of the shared gettext loader: the "fenrir" +// domain, installed catalogs under /usr/share/locale and the catalogs bundled +// from locale/. Screen contents and internal command/cue IDs must never pass +// through this package. package i18n import ( "embed" - "os" - "strconv" - "strings" - "sync/atomic" + "io/fs" - "github.com/leonelquinteros/gotext" + common "git.stormux.org/storm/screenreader-common/i18n" ) const Domain = "fenrir" -const LocaleDir = "/usr/share/locale" +const LocaleDir = common.LocaleDir //go:embed locale/*/LC_MESSAGES/fenrir.po var bundled embed.FS -type Catalog struct{ locales []*gotext.Locale } +type Catalog = common.Catalog -var current atomic.Pointer[Catalog] +var active common.Active -// Language follows Python gettext's environment precedence. LANGUAGE may list -// several languages separated by colons; C/POSIX stop catalog fallback. -func Language() string { - for _, name := range []string{"LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"} { - if value := os.Getenv(name); value != "" { - return value - } - } - return "C" -} +// Language follows Python gettext's environment precedence. +func Language() string { return common.Language() } +// New loads Fenrir's installed catalogs under root, then its bundled ones. func New(root, languages string) *Catalog { - catalog := &Catalog{} - for _, language := range strings.Split(languages, ":") { - language = strings.TrimSpace(language) - if index := strings.IndexByte(language, '.'); index >= 0 { - modifier := "" - if at := strings.IndexByte(language[index:], '@'); at >= 0 { - modifier = language[index+at:] - } - language = language[:index] + modifier - } - if language == "C" || language == "POSIX" { - break - } - if language == "" || strings.ContainsAny(language, "/\\") { - continue - } - locale := gotext.NewLocale(root, language) - locale.AddDomain(Domain) - catalog.locales = append(catalog.locales, locale) - // Keep each language's additions ahead of the next LANGUAGE fallback. - // Installed contributor translations retain priority within a language. - local := gotext.NewLocaleFSWithPath(language, bundled, "locale") - local.AddDomain(Domain) - catalog.locales = append(catalog.locales, local) - } - return catalog + return common.New(Domain, root, languages, fs.FS(bundled), "locale") } // Use installs an immutable catalog and returns the previous one. Configure // once at startup; no catalog loading belongs on the input/event path. -func Use(catalog *Catalog) *Catalog { return current.Swap(catalog) } +func Use(catalog *Catalog) *Catalog { return active.Use(catalog) } -func T(message string) string { - if catalog := current.Load(); catalog != nil { - for _, locale := range catalog.locales { - if locale.IsTranslated(message) { - return locale.Get(message) - } - } - } - return message -} +func T(message string) string { return active.T(message) } -func N(singular, plural string, count int) string { - if catalog := current.Load(); catalog != nil { - for _, locale := range catalog.locales { - if locale.IsTranslatedN(singular, count) { - return locale.GetN(singular, plural, count) - } - } - } - if count == 1 { - return singular - } - return plural -} +func N(singular, plural string, count int) string { return active.N(singular, plural, count) } // Format substitutes Python-style positional fields after lookup. Keeping // {0}/{1} intact lets the Go reader reuse existing catalog message IDs. -func Format(message string, fields ...string) string { - replacements := []string{"{{", "{", "}}", "}"} - for index, value := range fields { - replacements = append(replacements, "{"+strconv.Itoa(index)+"}", value) - } - return strings.NewReplacer(replacements...).Replace(T(message)) -} +func Format(message string, fields ...string) string { return active.Format(message, fields...) } diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index a1229b71..2fa97340 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -91,8 +91,8 @@ func TestLanguagePrecedenceAndCStopsFallback(t *testing.T) { } } catalog := New(t.TempDir(), "C.UTF-8:de") - if len(catalog.locales) != 0 { - t.Fatal("C locale continued translation fallback") + if got := catalog.T("Fenrir Menu"); got != "Fenrir Menu" { + t.Fatal("C locale continued translation fallback", got) } } diff --git a/internal/i18n/locale/de/LC_MESSAGES/fenrir.po b/internal/i18n/locale/de/LC_MESSAGES/fenrir.po index e15550bf..26f90a37 100644 --- a/internal/i18n/locale/de/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/de/LC_MESSAGES/fenrir.po @@ -99,7 +99,7 @@ msgstr "Außerirdischer" msgid "Alien monster" msgstr "Außerirdisches Monster" -#: internal/emoji/catalog.go internal/emoji/catalog.go:37 +#: screenreader-common/emoji/picker.go msgid "All" msgstr "Alle" @@ -1019,11 +1019,11 @@ msgstr "Elefant" msgid "Elf" msgstr "Elf(e)" -#: internal/emoji/catalog.go:25 internal/emoji/catalog.go:38 +#: internal/emoji/catalog.go:25 msgid "Emoji" msgstr "Emoji" -#: internal/command/descriptions.go:55 internal/emoji/catalog.go:15 +#: internal/command/descriptions.go:55 internal/emoji/catalog.go:13 msgid "Emoji Menu" msgstr "Emoji-Menü" @@ -2778,7 +2778,7 @@ msgstr "Funkeln" msgid "Speech" msgstr "Sprache" -#: internal/speech/drivers.go:49 +#: internal/speech/drivers.go:50 msgid "Speech Dispatcher" msgstr "Speech Dispatcher" diff --git a/internal/i18n/locale/es/LC_MESSAGES/fenrir.po b/internal/i18n/locale/es/LC_MESSAGES/fenrir.po index 94124f4b..6a072463 100644 --- a/internal/i18n/locale/es/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/es/LC_MESSAGES/fenrir.po @@ -99,7 +99,7 @@ msgstr "Alienígena" msgid "Alien monster" msgstr "Monstruo alienígena" -#: internal/emoji/catalog.go internal/emoji/catalog.go:37 +#: screenreader-common/emoji/picker.go msgid "All" msgstr "Todos" @@ -1021,11 +1021,11 @@ msgstr "Elefante" msgid "Elf" msgstr "Elfo" -#: internal/emoji/catalog.go:25 internal/emoji/catalog.go:38 +#: internal/emoji/catalog.go:25 msgid "Emoji" msgstr "Emoji" -#: internal/command/descriptions.go:55 internal/emoji/catalog.go:15 +#: internal/command/descriptions.go:55 internal/emoji/catalog.go:13 msgid "Emoji Menu" msgstr "Menú de emojis" @@ -2787,7 +2787,7 @@ msgstr "Destellos" msgid "Speech" msgstr "Voz" -#: internal/speech/drivers.go:49 +#: internal/speech/drivers.go:50 msgid "Speech Dispatcher" msgstr "Speech Dispatcher" diff --git a/internal/i18n/locale/fenrir.pot b/internal/i18n/locale/fenrir.pot index aef2c522..20d883f3 100644 --- a/internal/i18n/locale/fenrir.pot +++ b/internal/i18n/locale/fenrir.pot @@ -89,7 +89,7 @@ msgstr "" msgid "Alien monster" msgstr "" -#: internal/emoji/catalog.go internal/emoji/catalog.go:37 +#: screenreader-common/emoji/picker.go msgid "All" msgstr "" @@ -997,11 +997,11 @@ msgstr "" msgid "Elf" msgstr "" -#: internal/emoji/catalog.go:25 internal/emoji/catalog.go:38 +#: internal/emoji/catalog.go:25 msgid "Emoji" msgstr "" -#: internal/command/descriptions.go:55 internal/emoji/catalog.go:15 +#: internal/command/descriptions.go:55 internal/emoji/catalog.go:13 msgid "Emoji Menu" msgstr "" @@ -2729,7 +2729,7 @@ msgstr "" msgid "Speech" msgstr "" -#: internal/speech/drivers.go:49 +#: internal/speech/drivers.go:50 msgid "Speech Dispatcher" msgstr "" diff --git a/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po b/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po index 4d2d49da..3b0869d3 100644 --- a/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po @@ -100,7 +100,7 @@ msgstr "ufoludek" msgid "Alien monster" msgstr "Potwór z kosmosu" -#: internal/emoji/catalog.go internal/emoji/catalog.go:37 +#: screenreader-common/emoji/picker.go msgid "All" msgstr "Wszystkie" @@ -1021,11 +1021,11 @@ msgstr "Słoń" msgid "Elf" msgstr "elf" -#: internal/emoji/catalog.go:25 internal/emoji/catalog.go:38 +#: internal/emoji/catalog.go:25 msgid "Emoji" msgstr "Emoji" -#: internal/command/descriptions.go:55 internal/emoji/catalog.go:15 +#: internal/command/descriptions.go:55 internal/emoji/catalog.go:13 msgid "Emoji Menu" msgstr "Menu emoji" @@ -2781,7 +2781,7 @@ msgstr "Iskierki" msgid "Speech" msgstr "Mowa" -#: internal/speech/drivers.go:49 +#: internal/speech/drivers.go:50 msgid "Speech Dispatcher" msgstr "Speech Dispatcher" diff --git a/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po b/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po index f96fef6c..9a7cfbd1 100644 --- a/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po @@ -98,7 +98,7 @@ msgstr "Alienígena" msgid "Alien monster" msgstr "Monstro alienígena" -#: internal/emoji/catalog.go internal/emoji/catalog.go:37 +#: screenreader-common/emoji/picker.go msgid "All" msgstr "Todos" @@ -1019,11 +1019,11 @@ msgstr "Elefante" msgid "Elf" msgstr "Elfo" -#: internal/emoji/catalog.go:25 internal/emoji/catalog.go:38 +#: internal/emoji/catalog.go:25 msgid "Emoji" msgstr "Emoji" -#: internal/command/descriptions.go:55 internal/emoji/catalog.go:15 +#: internal/command/descriptions.go:55 internal/emoji/catalog.go:13 msgid "Emoji Menu" msgstr "Menu de emojis" @@ -2785,7 +2785,7 @@ msgstr "Brilhos" msgid "Speech" msgstr "Fala" -#: internal/speech/drivers.go:49 +#: internal/speech/drivers.go:50 msgid "Speech Dispatcher" msgstr "Speech Dispatcher" diff --git a/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po b/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po index a5ab161d..4a54ec37 100644 --- a/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po @@ -97,7 +97,7 @@ msgstr "Инопланетянин" msgid "Alien monster" msgstr "Инопланетное чудовище" -#: internal/emoji/catalog.go internal/emoji/catalog.go:37 +#: screenreader-common/emoji/picker.go msgid "All" msgstr "Все" @@ -1018,11 +1018,11 @@ msgstr "Слон" msgid "Elf" msgstr "Эльф" -#: internal/emoji/catalog.go:25 internal/emoji/catalog.go:38 +#: internal/emoji/catalog.go:25 msgid "Emoji" msgstr "Эмодзи" -#: internal/command/descriptions.go:55 internal/emoji/catalog.go:15 +#: internal/command/descriptions.go:55 internal/emoji/catalog.go:13 msgid "Emoji Menu" msgstr "Меню эмодзи" @@ -2777,7 +2777,7 @@ msgstr "Искры" msgid "Speech" msgstr "Речь" -#: internal/speech/drivers.go:49 +#: internal/speech/drivers.go:50 msgid "Speech Dispatcher" msgstr "Speech Dispatcher" diff --git a/internal/input/additional_review_test.go b/internal/input/additional_review_test.go index 527428ec..4c2f3f42 100644 --- a/internal/input/additional_review_test.go +++ b/internal/input/additional_review_test.go @@ -11,7 +11,7 @@ import ( func TestAdditionalReviewChordsConsumeHoldsAndBalanceReleases(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -30,7 +30,7 @@ func TestAdditionalReviewChordsConsumeHoldsAndBalanceReleases(t *testing.T) { for _, controlKey := range []uint16{KeyCtrl, KeyRightCtrl} { for _, modifierFirst := range []bool{false, true} { for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/application_overrides_test.go b/internal/input/application_overrides_test.go index 57bcb1be..f6b922f8 100644 --- a/internal/input/application_overrides_test.go +++ b/internal/input/application_overrides_test.go @@ -10,13 +10,13 @@ import ( func TestApplicationsChordConsumesRepeatsAndBothReleaseOrders(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, numLock := range []bool{false, true} { for _, modifierFirst := range []bool{false, true} { - r, err := New_router(bindings) + r, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/attributes_test.go b/internal/input/attributes_test.go index dcbcf3c9..39214681 100644 --- a/internal/input/attributes_test.go +++ b/internal/input/attributes_test.go @@ -10,13 +10,13 @@ import ( func TestAttributeBindingsNumLockRepeatsAndRelease(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, numLock := range []bool{false, true} { for _, modifierFirst := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -62,13 +62,13 @@ func TestAttributeBindingsNumLockRepeatsAndRelease(t *testing.T) { func TestAttributeToggleChordBothLayoutsNumLockAndReleases(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, numLock := range []bool{false, true} { for _, modifierFirst := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/bindings.go b/internal/input/bindings.go index 31376396..8a9db297 100644 --- a/internal/input/bindings.go +++ b/internal/input/bindings.go @@ -76,8 +76,8 @@ type chord struct { var modifierNames = map[string]modifiers{"FENRIR": fenrirModifier, "CTRL": ctrlModifier, "SHIFT": shiftModifier, "ALT": altModifier} -// Decode_bindings rejects unsupported keys, commands and duplicate chords. -func Decode_bindings(data []byte) (Layout, error) { +// DecodeBindings rejects unsupported keys, commands and duplicate chords. +func DecodeBindings(data []byte) (Layout, error) { var file Layout if err := toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields().Decode(&file); err != nil { return Layout{}, err @@ -85,12 +85,12 @@ func Decode_bindings(data []byte) (Layout, error) { if file.Version != 1 { return Layout{}, fmt.Errorf("unsupported keyboard version %d", file.Version) } - _, err := New_router(file) + _, err := NewRouter(file) return file, err } -// New_router compiles a private layout. Reset and capture preserve these bindings. -func New_router(layout Layout) (Router, error) { +// NewRouter compiles a private layout. Reset and capture preserve these bindings. +func NewRouter(layout Layout) (Router, error) { bindings := layout.Bindings router := Router{bindings: make(map[chord]command.ID), doubleBindings: make(map[chord]command.ID), tripleBindings: make(map[chord]command.ID), multiPressTimeout: DefaultMultiPressTimeout} keys := layout.FenrirKeys diff --git a/internal/input/bindings_test.go b/internal/input/bindings_test.go index 04c98457..b996770a 100644 --- a/internal/input/bindings_test.go +++ b/internal/input/bindings_test.go @@ -27,7 +27,7 @@ import ( "git.stormux.org/storm/fenrir/internal/command" ) -func desktop_data(t *testing.T) []byte { +func desktopData(t *testing.T) []byte { t.Helper() data, err := os.ReadFile("../../config/keyboard/desktop.toml") if err != nil { @@ -36,13 +36,13 @@ func desktop_data(t *testing.T) []byte { return data } -func desktop_router(t *testing.T) Router { +func desktopRouter(t *testing.T) Router { t.Helper() - bindings, err := Decode_bindings(desktop_data(t)) + bindings, err := DecodeBindings(desktopData(t)) if err != nil { t.Fatal(err) } - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -52,18 +52,18 @@ func desktop_router(t *testing.T) Router { func TestRuntimeLayoutsAreIndependentAndRetainedAcrossReset(t *testing.T) { root := t.TempDir() path := filepath.Join(root, "custom.toml") - if err := os.WriteFile(path, []byte(strings.Replace(string(desktop_data(t)), `keys = ["FENRIR", "F"]`, `keys = ["FENRIR", "G"]`, 1)), 0600); err != nil { + if err := os.WriteFile(path, []byte(strings.Replace(string(desktopData(t)), `keys = ["FENRIR", "F"]`, `keys = ["FENRIR", "G"]`, 1)), 0600); err != nil { t.Fatal(err) } - bindings, selected, err := Load_bindings([]string{path}) + bindings, selected, err := LoadBindings([]string{path}) if err != nil || selected != path { t.Fatal(selected, err) } - custom, err := New_router(bindings) + custom, err := NewRouter(bindings) if err != nil { t.Fatal(err) } - desktop := desktop_router(t) + desktop := desktopRouter(t) for range 2 { custom.Key(0, KeyInsert, 1, false, false) if got := custom.Key(0, 34, 1, false, false); got.Command != command.FenrirMenu || got.Forward { @@ -80,14 +80,14 @@ func TestRuntimeLayoutsAreIndependentAndRetainedAcrossReset(t *testing.T) { } // Editing the file affects the next load, without rebuilding or mutating // an already running router. - if err := os.WriteFile(path, desktop_data(t), 0600); err != nil { + if err := os.WriteFile(path, desktopData(t), 0600); err != nil { t.Fatal(err) } - updated, _, err := Load_bindings([]string{path}) + updated, _, err := LoadBindings([]string{path}) if err != nil { t.Fatal(err) } - reloaded, err := New_router(updated) + reloaded, err := NewRouter(updated) if err != nil { t.Fatal(err) } @@ -100,7 +100,7 @@ func TestRuntimeLayoutsAreIndependentAndRetainedAcrossReset(t *testing.T) { func TestBothLayoutsProvideAllClipboardCommands(t *testing.T) { want := []command.ID{command.SetMark, command.RemoveMarks, command.MarkedText, command.CopyMarked, command.CopyLastEcho, command.CurrentClipboard, command.PreviousClipboard, command.NextClipboard, command.FirstClipboard, command.LastClipboard, command.ClearClipboard, command.PasteClipboard, command.ImportClipboard, command.ExportClipboard, command.ImportXClipboard, command.ExportXClipboard} for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -121,13 +121,13 @@ func TestPythonTrackingChordsConsumePressRepeatAndBothReleases(t *testing.T) { layout string key uint16 }{{"desktop", 55}, {"laptop", 21}} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + fixture.layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + fixture.layout + ".toml"}) if err != nil { t.Fatal(err) } for _, modifierFirst := range []bool{false, true} { for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -153,7 +153,7 @@ func TestPythonTrackingChordsConsumePressRepeatAndBothReleases(t *testing.T) { } func TestLaptopRuntimeLayoutAndModifierChords(t *testing.T) { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/laptop.toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/laptop.toml"}) if err != nil { t.Fatal(err) } @@ -164,7 +164,7 @@ func TestLaptopRuntimeLayoutAndModifierChords(t *testing.T) { {23, 0, command.CurrentLine}, {22, KeyShift, command.Top}, {36, KeyCtrl, command.FirstText}, {52, KeyShift, command.Position}, {KeyF, 0, command.FenrirMenu}, } { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -184,21 +184,21 @@ func TestLaptopRuntimeLayoutAndModifierChords(t *testing.T) { func TestLayoutPathSelection(t *testing.T) { home, bundle := t.TempDir(), t.TempDir() - paths, err := Layout_paths("laptop", home, 1000, bundle) + paths, err := LayoutPaths("laptop", home, 1000, bundle) if err != nil || !reflect.DeepEqual(paths, []string{filepath.Join(home, ".local/share/stormux/fenrirscreenreader/keyboard/laptop.toml"), "/etc/fenrirscreenreader/keyboard/laptop.toml", filepath.Join(bundle, "laptop.toml")}) { t.Fatal(paths, err) } - paths, err = Layout_paths("desktop.toml", home, 0, bundle) + paths, err = LayoutPaths("desktop.toml", home, 0, bundle) if err != nil || len(paths) != 2 || paths[0] != "/etc/fenrirscreenreader/keyboard/desktop.toml" { t.Fatal(paths, err) } path := filepath.Join(t.TempDir(), "custom.toml") - paths, err = Layout_paths(path, home, 1000, bundle) + paths, err = LayoutPaths(path, home, 1000, bundle) if err != nil || !reflect.DeepEqual(paths, []string{path}) { t.Fatal(paths, err) } for _, value := range []string{"", "desktop.conf", "../desktop", "../desktop.conf", "\x00"} { - if _, err := Layout_paths(value, home, 1000, bundle); err == nil { + if _, err := LayoutPaths(value, home, 1000, bundle); err == nil { t.Fatal("invalid selection", value) } } @@ -207,38 +207,38 @@ func TestLayoutPathSelection(t *testing.T) { func TestInvalidLayoutNeverFallsThroughOrMerges(t *testing.T) { root := t.TempDir() bad, good := filepath.Join(root, "bad.toml"), filepath.Join(root, "desktop.toml") - if err := os.WriteFile(good, desktop_data(t), 0600); err != nil { + if err := os.WriteFile(good, desktopData(t), 0600); err != nil { t.Fatal(err) } for _, data := range []string{"version=1\n", "version=1\nunknown=true\n", strings.Repeat("#", (1<<20)+1)} { if err := os.WriteFile(bad, []byte(data), 0600); err != nil { t.Fatal(err) } - if _, selected, err := Load_bindings([]string{bad, good}); err == nil || selected != bad { + if _, selected, err := LoadBindings([]string{bad, good}); err == nil || selected != bad { t.Fatal("bad layout ignored", selected, err) } } - if _, _, err := Load_bindings([]string{filepath.Join(root, "missing.toml")}); err == nil { + if _, _, err := LoadBindings([]string{filepath.Join(root, "missing.toml")}); err == nil { t.Fatal("missing layout accepted") } - if _, selected, err := Load_bindings([]string{filepath.Join(root, "missing.toml"), good}); err != nil || selected != good { + if _, selected, err := LoadBindings([]string{filepath.Join(root, "missing.toml"), good}); err != nil || selected != good { t.Fatal(selected, err) } base := "version=1\n[[bindings]]\nname='Example'\nkeys=%s\ncommand='help'\n" for _, keys := range []string{`['FENRIR','FENRIR','F']`, `['CTRL','F']`, `['A']`, `['FENRIR','UNKNOWN','F']`} { - if _, err := Decode_bindings([]byte(strings.Replace(base, "%s", keys, 1))); err == nil { + if _, err := DecodeBindings([]byte(strings.Replace(base, "%s", keys, 1))); err == nil { t.Fatal("unsupported chord accepted", keys) } } duplicate := strings.Replace(base, "%s", "['FENRIR','SHIFT','F']", 1) + "[[bindings]]\nname='Duplicate'\nkeys=['SHIFT','FENRIR','F']\ncommand='quit'\n" - if _, err := Decode_bindings([]byte(duplicate)); err == nil { + if _, err := DecodeBindings([]byte(duplicate)); err == nil { t.Fatal("reordered duplicate modifiers accepted") } } func TestQuickSettingsChordsInBothLayouts(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -261,7 +261,7 @@ func TestQuickSettingsChordsInBothLayouts(t *testing.T) { {KeyDown, false, true, command.PreviousQuickValue}, {31, true, false, command.SaveSettings}, } { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/capslock_test.go b/internal/input/capslock_test.go index f52bd8d3..6b1e5da7 100644 --- a/internal/input/capslock_test.go +++ b/internal/input/capslock_test.go @@ -9,13 +9,13 @@ import ( "testing" ) -func laptop_router(t *testing.T) Router { +func laptopRouter(t *testing.T) Router { t.Helper() - layout, _, err := Load_bindings([]string{"../../config/keyboard/laptop.toml"}) + layout, _, err := LoadBindings([]string{"../../config/keyboard/laptop.toml"}) if err != nil { t.Fatal(err) } - router, err := New_router(layout) + router, err := NewRouter(layout) if err != nil { t.Fatal(err) } @@ -24,7 +24,7 @@ func laptop_router(t *testing.T) Router { func TestLaptopCapsLockModifier(t *testing.T) { for _, releaseCapsFirst := range []bool{false, true} { - r := laptop_router(t) + r := laptopRouter(t) for range 2 { if got := r.Key(0, KeyCapsLock, 1, false, false); got.Forward || got.ToggleCapsLock { t.Fatal(got) @@ -50,7 +50,7 @@ func TestLaptopCapsLockModifier(t *testing.T) { t.Fatal("Super became Fenrir", got) } } - desktop := desktop_router(t) + desktop := desktopRouter(t) if got := desktop.Key(0, KeyCapsLock, 1, false, false); !got.Forward { t.Fatal("desktop Caps Lock consumed", got) } @@ -66,7 +66,7 @@ func TestLaptopShiftCapsLockGesture(t *testing.T) { for _, shiftFirst := range []bool{false, true} { for _, releaseShiftFirst := range []bool{false, true} { for _, extraKey := range []uint16{0, 22, KeyCtrl} { - r := laptop_router(t) + r := laptopRouter(t) keys := []uint16{KeyCapsLock, shift} if shiftFirst { keys = []uint16{shift, KeyCapsLock} @@ -103,12 +103,12 @@ func TestLaptopShiftCapsLockGesture(t *testing.T) { func TestCapsLockCapturePassAndRepair(t *testing.T) { for _, mode := range []string{"capture", "pass", "repair", "drop", "reset"} { - r := laptop_router(t) + r := laptopRouter(t) if mode == "capture" { r.Capture(true) } if mode == "pass" { - r.Pass_next() + r.PassNext() } r.Key(0, KeyShift, 1, false, false) got := r.Key(0, KeyCapsLock, 1, false, false) @@ -131,16 +131,16 @@ func TestCapsLockCapturePassAndRepair(t *testing.T) { func TestLayoutModifierValidation(t *testing.T) { for _, keys := range []string{`["UNKNOWN"]`, `["CAPSLOCK", "CAPSLOCK"]`} { - data := strings.Replace(string(desktop_data(t)), "version = 1", "version = 1\nfenrir_keys = "+keys, 1) - if _, err := Decode_bindings([]byte(data)); err == nil { + data := strings.Replace(string(desktopData(t)), "version = 1", "version = 1\nfenrir_keys = "+keys, 1) + if _, err := DecodeBindings([]byte(data)); err == nil { t.Fatal("invalid modifier keys accepted", keys) } } - r := laptop_router(t) - if got := r.script_name(KeyCapsLock, false); got != "KEY_FENRIR" { + r := laptopRouter(t) + if got := r.scriptName(KeyCapsLock, false); got != "KEY_FENRIR" { t.Fatal(got) } - if got := r.script_name(KeyMeta, false); got == "KEY_FENRIR" { + if got := r.scriptName(KeyMeta, false); got == "KEY_FENRIR" { t.Fatal(got) } } diff --git a/internal/input/double_press_test.go b/internal/input/double_press_test.go index 1c276869..07a280ba 100644 --- a/internal/input/double_press_test.go +++ b/internal/input/double_press_test.go @@ -19,11 +19,11 @@ func TestTimeDateDoublePress(t *testing.T) { if err != nil { t.Fatal(err) } - bindings, err := Decode_bindings(data) + bindings, err := DecodeBindings(data) if err != nil { t.Fatal(err) } - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -73,7 +73,7 @@ func TestTimeDateDoublePress(t *testing.T) { case "other device": device = 2 case "pass next": - router.Pass_next() + router.PassNext() if got := router.Key(1, keyT, 1, false, false); !got.Forward || got.Command != "" { t.Fatal(got) } @@ -95,7 +95,7 @@ func TestTimeDateDoublePress(t *testing.T) { func TestDoubleCommandValidationAndRemapping(t *testing.T) { for _, doubleCommand := range []command.ID{command.Date, "unknown"} { - router, err := New_router(Layout{Bindings: []Binding{{Name: "Clock", Keys: []string{"FENRIR", "G"}, Command: command.Time, DoubleCommand: doubleCommand}}}) + router, err := NewRouter(Layout{Bindings: []Binding{{Name: "Clock", Keys: []string{"FENRIR", "G"}, Command: command.Time, DoubleCommand: doubleCommand}}}) if doubleCommand == "unknown" { if err == nil { t.Fatal("unknown double command accepted") diff --git a/internal/input/emoji_test.go b/internal/input/emoji_test.go index ae9b1e81..0af2b09c 100644 --- a/internal/input/emoji_test.go +++ b/internal/input/emoji_test.go @@ -12,12 +12,12 @@ import ( func TestEmojiChordBothLayoutsAndReleaseOrders(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, release := range [][]uint16{{KeyInsert, KeyCtrl, 18}, {18, KeyCtrl, KeyInsert}} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/layout.go b/internal/input/layout.go index 40e750a1..0b1f29f9 100644 --- a/internal/input/layout.go +++ b/internal/input/layout.go @@ -26,9 +26,9 @@ import ( "strings" ) -// Layout_paths keeps named TOML layouts in Fenrir's keyboard directories. +// LayoutPaths keeps named TOML layouts in Fenrir's keyboard directories. // Explicit paths select exactly one file. The bundle is an on-disk runtime asset. -func Layout_paths(layout, home string, uid int, bundledDirectory string) ([]string, error) { +func LayoutPaths(layout, home string, uid int, bundledDirectory string) ([]string, error) { if strings.TrimSpace(layout) == "" || strings.ContainsAny(layout, "\x00\r\n") { return nil, fmt.Errorf("keyboard layout cannot be empty or contain control characters") } @@ -57,9 +57,9 @@ func Layout_paths(layout, home string, uid int, bundledDirectory string) ([]stri return paths, nil } -// Load_bindings selects one whole file. A malformed or unreadable candidate +// LoadBindings selects one whole file. A malformed or unreadable candidate // stops loading; only absent named candidates advance to the next directory. -func Load_bindings(paths []string) (Layout, string, error) { +func LoadBindings(paths []string) (Layout, string, error) { for _, path := range paths { file, err := os.Open(path) if errors.Is(err, os.ErrNotExist) { @@ -76,7 +76,7 @@ func Load_bindings(paths []string) (Layout, string, error) { if len(data) > 1<<20 { return Layout{}, path, fmt.Errorf("keyboard layout exceeds 1 MiB") } - bindings, err := Decode_bindings(data) + bindings, err := DecodeBindings(data) return bindings, path, err } return Layout{}, "", fmt.Errorf("keyboard layout not found (searched %s)", strings.Join(paths, ", ")) diff --git a/internal/input/learn.go b/internal/input/learn.go index 5ad3ec65..d3a01249 100644 --- a/internal/input/learn.go +++ b/internal/input/learn.go @@ -18,7 +18,7 @@ type LearnKey struct { Bare bool } -func (r *Router) learn_key(device int, key uint16, numLock bool) *LearnKey { +func (r *Router) learnKey(device int, key uint16, numLock bool) *LearnKey { pressed := &LearnKey{Code: key, Bare: r.empty()} seen := map[uint16]bool{} for _, held := range r.keys { @@ -30,12 +30,12 @@ func (r *Router) learn_key(device int, key uint16, numLock bool) *LearnKey { pressed.Held = append(pressed.Held, code) } slices.Sort(pressed.Held) - id, scriptChord := r.script_binding(key, numLock) + id, scriptChord := r.scriptBinding(key, numLock) if !scriptChord { id = r.binding(key, numLock) } - if !pure_modifier(key) && !r.reader_modifier(key, numLock) { - id = r.multi_press(device, r.binding_chord(key, numLock), id, scriptChord) + if !pureModifier(key) && !r.readerModifier(key, numLock) { + id = r.multiPress(device, r.bindingChord(key, numLock), id, scriptChord) } pressed.Command = id return pressed diff --git a/internal/input/learn_test.go b/internal/input/learn_test.go index 4051efad..243a45af 100644 --- a/internal/input/learn_test.go +++ b/internal/input/learn_test.go @@ -12,11 +12,11 @@ import ( func TestCapturedKeysDescribeActualBindingsWithoutDispatch(t *testing.T) { bindings := []Binding{{Name: "Custom", Keys: []string{"FENRIR", "Z"}, Command: command.Time, DoubleCommand: command.Date, TripleCommand: command.Quit}} - router, err := New_router(Layout{Bindings: bindings, FenrirKeys: []string{"INSERT", "KP0"}}) + router, err := NewRouter(Layout{Bindings: bindings, FenrirKeys: []string{"INSERT", "KP0"}}) if err != nil { t.Fatal(err) } - if err := router.Configure_scripts([]string{"KEY_COMPOSE", "KEY_META"}, []ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { + if err := router.ConfigureScripts([]string{"KEY_COMPOSE", "KEY_META"}, []ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { t.Fatal(err) } now := time.Unix(1000, 0) @@ -43,7 +43,7 @@ func TestCapturedKeysDescribeActualBindingsWithoutDispatch(t *testing.T) { } now = now.Add(50 * time.Millisecond) } - compose, _ := Key_code("KEY_COMPOSE") + compose, _ := KeyCode("KEY_COMPOSE") for _, modifier := range []uint16{compose, KeyMeta} { press(modifier, "") press(22, "script:example") @@ -51,8 +51,8 @@ func TestCapturedKeysDescribeActualBindingsWithoutDispatch(t *testing.T) { router.Key(0, modifier, 0, false, false) } press(88, "") // F12 has no binding but retains its physical identity. - if Key_name(88) != "KEY_F12" { - t.Fatal(Key_name(88)) + if KeyName(88) != "KEY_F12" { + t.Fatal(KeyName(88)) } if got := router.Key(2, KeyRightShift, 1, false, true); got.Learn != nil || got.Forward { t.Fatal("sync spoke", got) @@ -69,12 +69,12 @@ func TestCapturedKeysDescribeActualBindingsWithoutDispatch(t *testing.T) { func TestTutorialEntryAliasesAndNumLockIdentification(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, entry := range []uint16{KeyH, 59} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -83,7 +83,7 @@ func TestTutorialEntryAliasesAndNumLockIdentification(t *testing.T) { t.Fatal(layout, entry, got) } } - router, _ := New_router(bindings) + router, _ := NewRouter(bindings) router.Capture(true) for _, numLock := range []bool{false, true} { got := router.Key(0, KeyKP8, 1, numLock, false) diff --git a/internal/input/modifiers_linux.go b/internal/input/modifiers_linux.go index 9092fa3a..1a261fb5 100644 --- a/internal/input/modifiers_linux.go +++ b/internal/input/modifiers_linux.go @@ -10,11 +10,11 @@ import ( "strings" ) -// Modifier_codes expands generic modifiers to their physical left/right keys. -func Modifier_codes(names []string) (map[uint16]bool, error) { +// ModifierCodes expands generic modifiers to their physical left/right keys. +func ModifierCodes(names []string) (map[uint16]bool, error) { keys := make(map[uint16]bool) for _, name := range names { - code, ok := Key_code(name) + code, ok := KeyCode(name) if !ok { return nil, fmt.Errorf("invalid modifier key %q", name) } @@ -33,12 +33,12 @@ func Modifier_codes(names []string) (map[uint16]bool, error) { return keys, nil } -// Fenrir_codes validates the supported configurable reader modifiers. -func Fenrir_codes(names []string) (map[uint16]bool, error) { +// FenrirCodes validates the supported configurable reader modifiers. +func FenrirCodes(names []string) (map[uint16]bool, error) { if len(names) == 0 { return nil, fmt.Errorf("select at least one Fenrir key") } - keys, err := Modifier_codes(names) + keys, err := ModifierCodes(names) if err != nil { return nil, err } @@ -46,37 +46,37 @@ func Fenrir_codes(names []string) (map[uint16]bool, error) { switch code { case KeyInsert, KeyKP0, KeyCapsLock, KeyMeta, KeyRightMeta: default: - return nil, fmt.Errorf("unsupported Fenrir key %q", Key_name(code)) + return nil, fmt.Errorf("unsupported Fenrir key %q", KeyName(code)) } } return keys, nil } -func Validate_modifier_keys(fenrirKeys, scriptKeys []string) error { - reader, err := Fenrir_codes(fenrirKeys) +func ValidateModifierKeys(fenrirKeys, scriptKeys []string) error { + reader, err := FenrirCodes(fenrirKeys) if err != nil { return err } - scripts, err := Modifier_codes(scriptKeys) + scripts, err := ModifierCodes(scriptKeys) if err != nil { return err } for code := range scripts { if reader[code] { - return fmt.Errorf("%s cannot be both a Fenrir key and a script key", Key_name(code)) + return fmt.Errorf("%s cannot be both a Fenrir key and a script key", KeyName(code)) } } return nil } -func (r *Router) Set_fenrir_keys(names []string) error { - keys, err := Fenrir_codes(names) +func (r *Router) SetFenrirKeys(names []string) error { + keys, err := FenrirCodes(names) if err != nil { return err } for key := range keys { if r.scriptKeys[key] { - return fmt.Errorf("%s cannot be both a Fenrir key and a script key", Key_name(key)) + return fmt.Errorf("%s cannot be both a Fenrir key and a script key", KeyName(key)) } } r.Reset() @@ -84,44 +84,44 @@ func (r *Router) Set_fenrir_keys(names []string) error { return nil } -// Fenrir_keys returns the effective selection for the settings form. -func (r *Router) Fenrir_keys() []string { +// FenrirKeys returns the effective selection for the settings form. +func (r *Router) FenrirKeys() []string { var keys []string for _, code := range []uint16{KeyKP0, KeyInsert, KeyCapsLock, KeyMeta, KeyRightMeta} { - if !r.reader_modifier(code, false) { + if !r.readerModifier(code, false) { continue } - if code == KeyMeta && r.reader_modifier(KeyRightMeta, false) { + if code == KeyMeta && r.readerModifier(KeyRightMeta, false) { keys = append(keys, "KEY_META") continue } - if code == KeyRightMeta && r.reader_modifier(KeyMeta, false) { + if code == KeyRightMeta && r.readerModifier(KeyMeta, false) { continue } - keys = append(keys, Key_name(code)) + keys = append(keys, KeyName(code)) } return keys } -func (r *Router) script_modifier(key uint16, numLock bool) bool { +func (r *Router) scriptModifier(key uint16, numLock bool) bool { return r.scriptKeys[key] && (key != KeyKP0 || !numLock) } -// Available_fenrir_keys keeps explicitly configured script keys out of reader +// AvailableFenrirKeys keeps explicitly configured script keys out of reader // defaults. Explicit reader selections are validated instead of being changed. -func Available_fenrir_keys(readerNames, scriptNames []string) ([]string, error) { - reader, err := Fenrir_codes(readerNames) +func AvailableFenrirKeys(readerNames, scriptNames []string) ([]string, error) { + reader, err := FenrirCodes(readerNames) if err != nil { return nil, err } - scripts, err := Modifier_codes(scriptNames) + scripts, err := ModifierCodes(scriptNames) if err != nil { return nil, err } var names []string for _, key := range []uint16{KeyKP0, KeyInsert, KeyCapsLock, KeyMeta, KeyRightMeta} { if reader[key] && !scripts[key] { - names = append(names, Key_name(key)) + names = append(names, KeyName(key)) } } if len(names) == 0 { @@ -130,23 +130,23 @@ func Available_fenrir_keys(readerNames, scriptNames []string) ([]string, error) return names, nil } -func (r *Router) Configure_modifiers(fenrirKeys, scriptKeys []string) error { +func (r *Router) ConfigureModifiers(fenrirKeys, scriptKeys []string) error { if fenrirKeys == nil { var err error - fenrirKeys, err = Available_fenrir_keys(r.Fenrir_keys(), scriptKeys) + fenrirKeys, err = AvailableFenrirKeys(r.FenrirKeys(), scriptKeys) if err != nil { return err } } - if err := Validate_modifier_keys(fenrirKeys, scriptKeys); err != nil { + if err := ValidateModifierKeys(fenrirKeys, scriptKeys); err != nil { return err } candidate := *r candidate.scriptKeys = nil - if err := candidate.Set_fenrir_keys(fenrirKeys); err != nil { + if err := candidate.SetFenrirKeys(fenrirKeys); err != nil { return err } - if err := candidate.Configure_scripts(scriptKeys, nil); err != nil { + if err := candidate.ConfigureScripts(scriptKeys, nil); err != nil { return err } candidate.scriptBindings = r.scriptBindings diff --git a/internal/input/modifiers_test.go b/internal/input/modifiers_test.go index 5e5290ad..7040b0a0 100644 --- a/internal/input/modifiers_test.go +++ b/internal/input/modifiers_test.go @@ -13,43 +13,43 @@ func TestModifierConflictsUsePhysicalAliases(t *testing.T) { {"KEY_INSERT", "KEY_INSERT"}, {"KEY_KP0", "KEY_KP0"}, {"KEY_CAPSLOCK", "KEY_CAPSLOCK"}, {"KEY_META", "KEY_LEFTMETA"}, {"KEY_META", "KEY_RIGHTMETA"}, {"KEY_RIGHTMETA", "KEY_META"}, } { - if err := Validate_modifier_keys([]string{pair[0]}, []string{pair[1]}); err == nil { + if err := ValidateModifierKeys([]string{pair[0]}, []string{pair[1]}); err == nil { t.Fatal("accepted overlap", pair) } } - r := desktop_router(t) - if err := r.Configure_modifiers(nil, []string{"KEY_META"}); err != nil { + r := desktopRouter(t) + if err := r.ConfigureModifiers(nil, []string{"KEY_META"}); err != nil { t.Fatal(err) } - if r.reader_modifier(KeyMeta, false) || r.reader_modifier(KeyRightMeta, false) || !r.scriptKeys[KeyMeta] || !r.scriptKeys[KeyRightMeta] { + if r.readerModifier(KeyMeta, false) || r.readerModifier(KeyRightMeta, false) || !r.scriptKeys[KeyMeta] || !r.scriptKeys[KeyRightMeta] { t.Fatal("default reader stole explicit script key") } - if err := r.Configure_modifiers([]string{"KEY_META"}, []string{"KEY_RIGHTMETA"}); err == nil { + if err := r.ConfigureModifiers([]string{"KEY_META"}, []string{"KEY_RIGHTMETA"}); err == nil { t.Fatal("explicit conflict accepted") } - if !r.scriptKeys[KeyMeta] || r.reader_modifier(KeyMeta, false) { + if !r.scriptKeys[KeyMeta] || r.readerModifier(KeyMeta, false) { t.Fatal("failed reconfiguration changed keys") } - if err := r.Configure_modifiers([]string{"KEY_META"}, []string{"KEY_COMPOSE"}); err != nil { + if err := r.ConfigureModifiers([]string{"KEY_META"}, []string{"KEY_COMPOSE"}); err != nil { t.Fatal("could not move script key to reader", err) } - if r.scriptKeys[KeyMeta] || !r.reader_modifier(KeyRightMeta, false) { + if r.scriptKeys[KeyMeta] || !r.readerModifier(KeyRightMeta, false) { t.Fatal("old assignment survived") } } func TestConfigurableScriptModifiersAndNumLock(t *testing.T) { for _, key := range []uint16{KeyInsert, KeyKP0, KeyCapsLock, KeyMeta, KeyRightMeta} { - r := desktop_router(t) - if err := r.Configure_modifiers([]string{"KEY_CAPSLOCK"}, []string{Key_name(key)}); err != nil { + r := desktopRouter(t) + if err := r.ConfigureModifiers([]string{"KEY_CAPSLOCK"}, []string{KeyName(key)}); err != nil { if key != KeyCapsLock { t.Fatal(err) } - if err := r.Configure_modifiers([]string{"KEY_INSERT"}, []string{Key_name(key)}); err != nil { + if err := r.ConfigureModifiers([]string{"KEY_INSERT"}, []string{KeyName(key)}); err != nil { t.Fatal(err) } } - if err := r.Configure_scripts([]string{Key_name(key)}, []ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { + if err := r.ConfigureScripts([]string{KeyName(key)}, []ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { t.Fatal(err) } if got := r.Key(0, key, 1, false, false); got.Forward || got.Command != "" { @@ -74,8 +74,8 @@ func TestConfigurableScriptModifiersAndNumLock(t *testing.T) { } func TestCapsLockScriptModifierKeepsShiftToggle(t *testing.T) { - r := desktop_router(t) - if err := r.Configure_modifiers([]string{"KEY_INSERT"}, []string{"KEY_CAPSLOCK"}); err != nil { + r := desktopRouter(t) + if err := r.ConfigureModifiers([]string{"KEY_INSERT"}, []string{"KEY_CAPSLOCK"}); err != nil { t.Fatal(err) } r.Key(0, KeyShift, 1, false, false) @@ -96,14 +96,14 @@ func TestCapsLockScriptModifierKeepsShiftToggle(t *testing.T) { } func TestModifierReconfigurationPreservesInstalledScriptBindings(t *testing.T) { - r := desktop_router(t) - if err := r.Configure_modifiers([]string{"KEY_INSERT"}, []string{"KEY_COMPOSE"}); err != nil { + r := desktopRouter(t) + if err := r.ConfigureModifiers([]string{"KEY_INSERT"}, []string{"KEY_COMPOSE"}); err != nil { t.Fatal(err) } - if err := r.Configure_scripts([]string{"KEY_COMPOSE"}, []ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { + if err := r.ConfigureScripts([]string{"KEY_COMPOSE"}, []ScriptBinding{{ID: "script:example", Keys: []string{"KEY_SCRIPT", "KEY_U"}}}); err != nil { t.Fatal(err) } - if err := r.Configure_modifiers([]string{"KEY_META"}, []string{"KEY_CAPSLOCK"}); err != nil { + if err := r.ConfigureModifiers([]string{"KEY_META"}, []string{"KEY_CAPSLOCK"}); err != nil { t.Fatal(err) } r.Key(0, KeyCapsLock, 1, false, false) diff --git a/internal/input/multi_press.go b/internal/input/multi_press.go index 1001c05c..a404f4db 100644 --- a/internal/input/multi_press.go +++ b/internal/input/multi_press.go @@ -12,9 +12,9 @@ import ( const DefaultMultiPressTimeout = 200 * time.Millisecond -// Set_multi_press_timeout changes the window between consecutive fresh presses. +// SetMultiPressTimeout changes the window between consecutive fresh presses. // It preserves bindings and physical key ownership, but starts a new sequence. -func (r *Router) Set_multi_press_timeout(timeout time.Duration) error { +func (r *Router) SetMultiPressTimeout(timeout time.Duration) error { if timeout < time.Millisecond || timeout > 5*time.Second { return fmt.Errorf("multi-press timeout must be between 1 and 5000 milliseconds") } @@ -23,7 +23,7 @@ func (r *Router) Set_multi_press_timeout(timeout time.Duration) error { return nil } -func (r *Router) multi_press(device int, combo chord, id command.ID, scriptChord bool) command.ID { +func (r *Router) multiPress(device int, combo chord, id command.ID, scriptChord bool) command.ID { if scriptChord || id == "" || r.doubleBindings[combo] == "" { r.lastPress = time.Time{} return id diff --git a/internal/input/multi_press_test.go b/internal/input/multi_press_test.go index 0312d3cf..21ea9034 100644 --- a/internal/input/multi_press_test.go +++ b/internal/input/multi_press_test.go @@ -14,7 +14,7 @@ func TestTriplePressSequences(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { for _, modifierFirst := range []bool{false, true} { t.Run(layout+"/"+map[bool]string{false: "key first", true: "modifier first"}[modifierFirst], func(t *testing.T) { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -31,11 +31,11 @@ func TestTriplePressSequences(t *testing.T) { bindings.Bindings[index].TripleCommand = command.CurrentLine } } - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } - if err := router.Set_multi_press_timeout(700 * time.Millisecond); err != nil { + if err := router.SetMultiPressTimeout(700 * time.Millisecond); err != nil { t.Fatal(err) } now := time.Unix(1000, 0) @@ -77,7 +77,7 @@ func TestTriplePressSequences(t *testing.T) { func TestTriplePressBoundariesAndInvalidation(t *testing.T) { for _, scenario := range []string{"inside", "at boundary", "outside", "backward clock", "other chord", "typing", "numlock", "reset", "capture", "drop", "repair", "unchanged repair", "other device", "pass next", "reconfigure"} { t.Run(scenario, func(t *testing.T) { - router, err := New_router(Layout{Bindings: []Binding{{Name: "Review", Keys: []string{"KP5"}, Command: command.CurrentWord, DoubleCommand: command.CurrentChar, TripleCommand: command.CurrentLine}, {Name: "Other", Keys: []string{"FENRIR", "KP5"}, Command: command.Time, DoubleCommand: command.Date}}}) + router, err := NewRouter(Layout{Bindings: []Binding{{Name: "Review", Keys: []string{"KP5"}, Command: command.CurrentWord, DoubleCommand: command.CurrentChar, TripleCommand: command.CurrentLine}, {Name: "Other", Keys: []string{"FENRIR", "KP5"}, Command: command.Time, DoubleCommand: command.Date}}}) if err != nil { t.Fatal(err) } @@ -136,13 +136,13 @@ func TestTriplePressBoundariesAndInvalidation(t *testing.T) { case "other device": device = 2 case "pass next": - router.Pass_next() + router.PassNext() if got := router.Key(1, KeyKP5, 1, false, false); !got.Forward || got.Command != "" { t.Fatal(got) } router.Key(1, KeyKP5, 0, false, false) case "reconfigure": - if err := router.Set_multi_press_timeout(500 * time.Millisecond); err != nil { + if err := router.SetMultiPressTimeout(500 * time.Millisecond); err != nil { t.Fatal(err) } } @@ -158,13 +158,13 @@ func TestTripleBindingValidation(t *testing.T) { "version=1\n[[bindings]]\nname='Review'\nkeys=['KP5']\ncommand='current_word'\ntriple_command='current_line'\n", "version=1\n[[bindings]]\nname='Review'\nkeys=['KP5']\ncommand='current_word'\ndouble_command='current_character'\ntriple_command='unknown'\n", } { - if _, err := Decode_bindings([]byte(data)); err == nil { + if _, err := DecodeBindings([]byte(data)); err == nil { t.Fatal("invalid triple accepted", data) } } - router := desktop_router(t) + router := desktopRouter(t) for _, timeout := range []time.Duration{0, -time.Second, time.Millisecond - time.Nanosecond, 5*time.Second + time.Nanosecond} { - if err := router.Set_multi_press_timeout(timeout); err == nil { + if err := router.SetMultiPressTimeout(timeout); err == nil { t.Fatal(timeout) } } @@ -177,7 +177,7 @@ func TestRetainedFeatureKeyNames(t *testing.T) { if bare { keys = keys[1:] } - _, err := New_router(Layout{Bindings: []Binding{{Name: "Retained key", Keys: keys, Command: command.Help}}}) + _, err := NewRouter(Layout{Bindings: []Binding{{Name: "Retained key", Keys: keys, Command: command.Help}}}) wantValid := !bare || key == "KPMINUS" || key == "KPSLASH" if (err == nil) != wantValid { t.Fatal(key, bare, err) diff --git a/internal/input/notifications_test.go b/internal/input/notifications_test.go index a41b0cee..b86b058f 100644 --- a/internal/input/notifications_test.go +++ b/internal/input/notifications_test.go @@ -11,7 +11,7 @@ import ( func TestNotificationBindingsInBothLayouts(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -21,7 +21,7 @@ func TestNotificationBindingsInBothLayouts(t *testing.T) { }{ {false, command.LastNotification}, {true, command.NotificationHistory}, } { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/progress_test.go b/internal/input/progress_test.go index 7cde77a2..3ab1aa52 100644 --- a/internal/input/progress_test.go +++ b/internal/input/progress_test.go @@ -31,12 +31,12 @@ func TestPythonProgressBindingsAndNumLockPassThrough(t *testing.T) { if err != nil { t.Fatal(err) } - bindings, err := Decode_bindings(data) + bindings, err := DecodeBindings(data) if err != nil { t.Fatal(err) } for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -64,7 +64,7 @@ func TestPythonProgressBindingsAndNumLockPassThrough(t *testing.T) { func TestDeletionMetadataDoesNotChangeKeyRouting(t *testing.T) { for _, key := range []uint16{KeyBackspace, KeyDelete} { - router := desktop_router(t) + router := desktopRouter(t) for _, value := range []int32{1, 2} { got := router.Key(0, key, value, false, false) if !got.Forward || !got.Deletion || !got.Interrupt || got.Typing { @@ -78,13 +78,13 @@ func TestDeletionMetadataDoesNotChangeKeyRouting(t *testing.T) { t.Fatal("deletion release changed", got) } } - router := desktop_router(t) + router := desktopRouter(t) router.Key(0, KeyInsert, 1, false, false) if got := router.Key(0, KeyBackspace, 1, false, false); got.Deletion || got.Forward || got.Command != command.PassNext { t.Fatal("reader chord became deletion", got) } for _, key := range []uint16{KeyEnter, KeyLeft, KeyKPDot} { - router := desktop_router(t) + router := desktopRouter(t) if got := router.Key(0, key, 1, false, false); got.Deletion { t.Fatal("unrelated key became deletion", key, got) } diff --git a/internal/input/regions_test.go b/internal/input/regions_test.go index 8f15d9de..c286542e 100644 --- a/internal/input/regions_test.go +++ b/internal/input/regions_test.go @@ -13,7 +13,7 @@ import ( func TestRegionChordsInBothLayoutsConsumeRepeatsAndEitherReleaseOrder(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -24,7 +24,7 @@ func TestRegionChordsInBothLayoutsConsumeRepeatsAndEitherReleaseOrder(t *testing } for _, modifierFirst := range []bool{false, true} { for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } @@ -70,27 +70,27 @@ func TestRegionChordsInBothLayoutsConsumeRepeatsAndEitherReleaseOrder(t *testing func TestWindowDoublePressSurvivesX11AggregateControlSamples(t *testing.T) { for _, modifier := range []uint16{KeyCtrl, KeyRightCtrl} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/laptop.toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/laptop.toml"}) if err != nil { t.Fatal(err) } - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } now := time.Unix(1000, 0) router.now = func() time.Time { return now } for _, want := range []command.ID{command.SetWindow, command.ClearWindow} { - router.Observe_modifier(1, KeyCtrl, 0, false) + router.ObserveModifier(1, KeyCtrl, 0, false) router.Key(0, KeyInsert, 1, false, false) router.Key(0, modifier, 1, false, false) - router.Observe_modifier(1, KeyCtrl, 1, false) + router.ObserveModifier(1, KeyCtrl, 1, false) if got := router.Key(0, 9, 1, false, false); got.Command != want || got.Forward { t.Fatal("control modifier shadow broke double press", modifier, got, want) } router.Key(0, 9, 0, false, false) router.Key(0, modifier, 0, false, false) - router.Observe_modifier(1, KeyCtrl, 0, false) + router.ObserveModifier(1, KeyCtrl, 0, false) router.Key(0, KeyInsert, 0, false, false) now = now.Add(100 * time.Millisecond) } diff --git a/internal/input/router.go b/internal/input/router.go index 0184204c..22aee6b9 100644 --- a/internal/input/router.go +++ b/internal/input/router.go @@ -143,7 +143,7 @@ func (r *Router) Idle() bool { return r.empty() } // release has not arrived yet. func (r *Router) Held(device int) bool { return len(r.keys[device]) != 0 } -func (r *Router) Pass_next() { +func (r *Router) PassNext() { r.lastPress = time.Time{} r.passArmed = true } @@ -154,12 +154,12 @@ func (r *Router) Key(device int, key uint16, value int32, numLock, syncEvent boo return r.key(device, key, value, numLock, syncEvent, syncEvent) } -// Observe_modifier records an aggregate X11 modifier sample on its separate +// ObserveModifier records an aggregate X11 modifier sample on its separate // shadow device. These samples accompany ordinary presses/releases; they are // not evidence of lost input and must not cancel a pending double press. The // next physical action still checks the complete chord and timeout. Actual // state repair, handoff and capture continue to invalidate through Key/Reset. -func (r *Router) Observe_modifier(device int, key uint16, value int32, numLock bool) { +func (r *Router) ObserveModifier(device int, key uint16, value int32, numLock bool) { if key == KeyCtrl || key == KeyShift || key == KeyAlt { r.key(device, key, value, numLock, true, false) } @@ -188,7 +188,7 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re if r.empty() { r.passing = false } - toggle := key == KeyCapsLock && exists && !state.forwarded && r.Caps_modifier() && r.capsShift && !r.capsUsed && !syncEvent && !r.captured && !r.passing + toggle := key == KeyCapsLock && exists && !state.forwarded && r.CapsModifier() && r.capsShift && !r.capsUsed && !syncEvent && !r.captured && !r.passing if key == KeyCapsLock { r.capsShift, r.capsUsed = false, false } @@ -199,16 +199,16 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re } if exists { if state.ui { - if r.captured && value == 2 && !syncEvent && !pure_modifier(key) && key != KeyEsc && key != KeyEnter && key != KeyKPEnter && key != KeySpace { - decision := r.ui_key(key) + if r.captured && value == 2 && !syncEvent && !pureModifier(key) && key != KeyEsc && key != KeyEnter && key != KeyKPEnter && key != KeySpace { + decision := r.uiKey(key) decision.UI.Repeat = true return decision } return Decision{} } if state.forwarded { - typing := !syncEvent && r.typing_key(key, numLock) - return Decision{Code: key, Forward: true, Deletion: !syncEvent && deletion_key(key, numLock), Typing: typing, WordBoundary: typing && key == KeySpace, Interrupt: !syncEvent && !pure_modifier(key)} + typing := !syncEvent && r.typingKey(key, numLock) + return Decision{Code: key, Forward: true, Deletion: !syncEvent && deletionKey(key, numLock), Typing: typing, WordBoundary: typing && key == KeySpace, Interrupt: !syncEvent && !pureModifier(key)} } commandID := state.commandID if value == 2 && repeatable(commandID) && !syncEvent { @@ -220,7 +220,7 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re if value == 2 { return Decision{} } - if !syncEvent && r.Caps_modifier() { + if !syncEvent && r.CapsModifier() { switch key { case KeyCapsLock: r.capsShift, r.capsUsed = r.down(KeyShift) || r.down(KeyRightShift), false @@ -244,13 +244,13 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re if r.captured { var learn *LearnKey if !syncEvent { - learn = r.learn_key(device, key, numLock) + learn = r.learnKey(device, key, numLock) } held[key] = heldKey{ui: true} - if syncEvent || pure_modifier(key) || r.reader_modifier(key, numLock) { + if syncEvent || pureModifier(key) || r.readerModifier(key, numLock) { return Decision{Learn: learn, Keypress: !syncEvent, Interrupt: !syncEvent && (key == KeyCtrl || key == KeyRightCtrl)} } - decision := r.ui_key(key) + decision := r.uiKey(key) decision.Learn = learn decision.Keypress = true return decision @@ -261,30 +261,30 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re commandID := command.ID("") scriptChord := false if !r.passing { - commandID, scriptChord = r.script_binding(key, numLock) + commandID, scriptChord = r.scriptBinding(key, numLock) if !scriptChord { commandID = r.binding(key, numLock) } } - if !syncEvent && !pure_modifier(key) && !r.reader_modifier(key, numLock) { - commandID = r.multi_press(device, r.binding_chord(key, numLock), commandID, scriptChord) + if !syncEvent && !pureModifier(key) && !r.readerModifier(key, numLock) { + commandID = r.multiPress(device, r.bindingChord(key, numLock), commandID, scriptChord) } - forwarded := commandID == "" && !scriptChord && !(r.reader_modifier(key, numLock) && !r.passing) + forwarded := commandID == "" && !scriptChord && !(r.readerModifier(key, numLock) && !r.passing) held[key] = heldKey{forwarded: forwarded, commandID: commandID} if syncEvent { return Decision{Forward: forwarded} } - typing := forwarded && r.typing_key(key, numLock) - return Decision{Code: key, Keypress: true, Deletion: forwarded && deletion_key(key, numLock), Typing: typing, WordBoundary: typing && key == KeySpace, Forward: forwarded, Command: commandID, Interrupt: commandID != "" || forwarded && (!pure_modifier(key) || key == KeyCtrl || key == KeyRightCtrl)} + typing := forwarded && r.typingKey(key, numLock) + return Decision{Code: key, Keypress: true, Deletion: forwarded && deletionKey(key, numLock), Typing: typing, WordBoundary: typing && key == KeySpace, Forward: forwarded, Command: commandID, Interrupt: commandID != "" || forwarded && (!pureModifier(key) || key == KeyCtrl || key == KeyRightCtrl)} } -func (r *Router) typing_key(key uint16, numLock bool) bool { +func (r *Router) typingKey(key uint16, numLock bool) bool { for scriptKey := range r.scriptKeys { - if r.script_modifier(scriptKey, numLock) && r.down(scriptKey) { + if r.scriptModifier(scriptKey, numLock) && r.down(scriptKey) { return false } } - if r.down(KeyCtrl) || r.down(KeyRightCtrl) || r.down(KeyAlt) || r.reader_down(numLock) || r.down(KeyMeta) || r.down(KeyRightMeta) { + if r.down(KeyCtrl) || r.down(KeyRightCtrl) || r.down(KeyAlt) || r.readerDown(numLock) || r.down(KeyMeta) || r.down(KeyRightMeta) { return false } // Physical text-key positions, independent of keyboard layout. AltGr is @@ -321,45 +321,45 @@ func (r *Router) empty() bool { return true } -func (r *Router) reader_modifier(key uint16, numLock bool) bool { +func (r *Router) readerModifier(key uint16, numLock bool) bool { if r.readerKeys == nil { return key == KeyInsert || key == KeyMeta || key == KeyRightMeta || key == KeyKP0 && !numLock } return r.readerKeys[key] && (key != KeyKP0 || !numLock) } -// Caps_modifier reports whether Caps Lock is reserved for reader or script chords. -func (r *Router) Caps_modifier() bool { return r.readerKeys[KeyCapsLock] || r.scriptKeys[KeyCapsLock] } +// CapsModifier reports whether Caps Lock is reserved for reader or script chords. +func (r *Router) CapsModifier() bool { return r.readerKeys[KeyCapsLock] || r.scriptKeys[KeyCapsLock] } -// Reader_keys supplies the X11 adapter with the physical keys to intercept. -func (r *Router) Reader_keys() []uint16 { +// ReaderKeys supplies the X11 adapter with the physical keys to intercept. +func (r *Router) ReaderKeys() []uint16 { var keys []uint16 for _, key := range []uint16{KeyInsert, KeyMeta, KeyRightMeta, KeyCapsLock, KeyKP0} { - if r.reader_modifier(key, false) { + if r.readerModifier(key, false) { keys = append(keys, key) } } return keys } -func (r *Router) reader_down(numLock bool) bool { - for _, key := range r.Reader_keys() { - if r.reader_modifier(key, numLock) && r.down(key) { +func (r *Router) readerDown(numLock bool) bool { + for _, key := range r.ReaderKeys() { + if r.readerModifier(key, numLock) && r.down(key) { return true } } return false } -func pure_modifier(key uint16) bool { +func pureModifier(key uint16) bool { return key == KeyCtrl || key == KeyRightCtrl || key == KeyShift || key == KeyRightShift || key == KeyAlt || key == KeyRightAlt || key == KeyInsert || key == KeyMeta || key == KeyRightMeta } func (r *Router) binding(key uint16, numLock bool) command.ID { - if r.reader_modifier(key, numLock) || pure_modifier(key) { + if r.readerModifier(key, numLock) || pureModifier(key) { return "" } - combo := r.binding_chord(key, numLock) + combo := r.bindingChord(key, numLock) if combo.modifiers&fenrirModifier != 0 { if id := r.bindings[combo]; id != "" { return id @@ -372,9 +372,9 @@ func (r *Router) binding(key uint16, numLock bool) command.ID { return r.bindings[combo] } -func (r *Router) binding_chord(key uint16, numLock bool) chord { +func (r *Router) bindingChord(key uint16, numLock bool) chord { var mods modifiers - if r.reader_down(numLock) { + if r.readerDown(numLock) { mods |= fenrirModifier } if r.down(KeyCtrl) || r.down(KeyRightCtrl) { @@ -401,6 +401,6 @@ func repeatable(commandID command.ID) bool { return false } -func deletion_key(key uint16, numLock bool) bool { +func deletionKey(key uint16, numLock bool) bool { return key == KeyBackspace || key == KeyDelete || key == KeyKPDot && !numLock } diff --git a/internal/input/router_test.go b/internal/input/router_test.go index a7a728bc..be1a3eea 100644 --- a/internal/input/router_test.go +++ b/internal/input/router_test.go @@ -23,7 +23,7 @@ import ( ) func TestReviewAndReleaseOrder(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) if got := router.Key(1, KeyInsert, 1, false, false); got.Forward || got.Interrupt { t.Fatalf("modifier: %+v", got) } @@ -46,7 +46,7 @@ func TestReviewAndReleaseOrder(t *testing.T) { } func TestTypingNumLockAndControl(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) if got := router.Key(1, KeyKP0, 1, true, false); !got.Forward || !got.Interrupt { t.Fatalf("numeric zero must interrupt like other typing: %+v", got) } @@ -75,8 +75,8 @@ func TestTypingNumLockAndControl(t *testing.T) { } func TestPassNextChordAndReset(t *testing.T) { - router := desktop_router(t) - router.Pass_next() + router := desktopRouter(t) + router.PassNext() if got := router.Key(1, KeyInsert, 1, false, false); !got.Forward { t.Fatal("pass-next swallowed Insert") } @@ -99,7 +99,7 @@ func TestPassNextChordAndReset(t *testing.T) { } func TestSyncAndDisconnectDoNotRunCommands(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) router.Key(1, KeyInsert, 1, false, true) if got := router.Key(1, KeyQ, 1, false, true); got.Forward || got.Command != "" || got.Interrupt { t.Fatalf("sync ran command: %+v", got) @@ -111,7 +111,7 @@ func TestSyncAndDisconnectDoNotRunCommands(t *testing.T) { } func TestBareKeypadEnterIsConsumed(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) if got := router.Key(0, KeyKPEnter, 1, false, false); got.Command != "temp_disable_speech" || got.Forward || !got.Interrupt { t.Fatal("keypad Enter did not temporarily silence speech", got) } @@ -134,7 +134,7 @@ func TestBareKeypadEnterIsConsumed(t *testing.T) { func TestKeypressExcludesRepeatsReleasesAndStateRepair(t *testing.T) { for _, key := range []uint16{KeyKPEnter, KeyKP8, KeyShift, KeyInsert, KeyF} { for _, capture := range []bool{false, true} { - router := desktop_router(t) + router := desktopRouter(t) router.Capture(capture) if got := router.Key(0, key, 1, false, false); !got.Keypress { t.Fatal("fresh press not reported", key, capture, got) @@ -164,7 +164,7 @@ func TestTypingMetadataExcludesCommandsNavigationAndShortcuts(t *testing.T) { {KeyRight, 0, false, false, false}, {KeyBackspace, 0, false, false, false}, {KeyTab, 0, false, false, false}, {KeyF, KeyInsert, false, false, false}, } { - router := desktop_router(t) + router := desktopRouter(t) if testCase.modifier != 0 { router.Key(0, testCase.modifier, 1, testCase.numLock, false) } diff --git a/internal/input/screen_range_test.go b/internal/input/screen_range_test.go index 02ee7524..f5f40ee1 100644 --- a/internal/input/screen_range_test.go +++ b/internal/input/screen_range_test.go @@ -11,7 +11,7 @@ import ( func TestScreenRangeChordsConsumePressHoldAndBothReleaseOrders(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -24,7 +24,7 @@ func TestScreenRangeChordsConsumePressHoldAndBothReleaseOrders(t *testing.T) { } { for _, modifierFirst := range []bool{false, true} { for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/script_keys_linux.go b/internal/input/script_keys_linux.go index 4cdaa904..53c8c363 100644 --- a/internal/input/script_keys_linux.go +++ b/internal/input/script_keys_linux.go @@ -43,7 +43,7 @@ type ScriptBinding struct { Keys []string } -func Key_code(name string) (uint16, bool) { +func KeyCode(name string) (uint16, bool) { name = strings.ToUpper(name) aliases := map[string]string{"KEY_CTRL": "KEY_LEFTCTRL", "KEY_SHIFT": "KEY_LEFTSHIFT", "KEY_ALT": "KEY_LEFTALT", "KEY_META": "KEY_LEFTMETA"} if alias := aliases[name]; alias != "" { @@ -55,16 +55,16 @@ func Key_code(name string) (uint16, bool) { return uint16(code), code >= 0 && code <= int(C.KEY_MAX) } -func Valid_script_key(name string) bool { +func ValidScriptKey(name string) bool { if name == "KEY_SCRIPT" || name == "KEY_FENRIR" { return true } - _, ok := Key_code(name) + _, ok := KeyCode(name) return ok } -// Key_name retains the physical left/right/keypad identity for tutorial input. -func Key_name(code uint16) string { +// KeyName retains the physical left/right/keypad identity for tutorial input. +func KeyName(code uint16) string { name := C.libevdev_event_code_get_name(C.EV_KEY, C.uint(code)) if name == nil { return strconv.Itoa(int(code)) @@ -72,20 +72,20 @@ func Key_name(code uint16) string { return C.GoString(name) } -func Script_chord(keys []string) string { +func ScriptChord(keys []string) string { keys = slices.Clone(keys) slices.Sort(keys) return strings.Join(keys, ",") } -func (r *Router) Configure_scripts(keys []string, bindings []ScriptBinding) error { - scriptKeys, err := Modifier_codes(keys) +func (r *Router) ConfigureScripts(keys []string, bindings []ScriptBinding) error { + scriptKeys, err := ModifierCodes(keys) if err != nil { return err } for code := range scriptKeys { - if r.reader_modifier(code, false) { - return fmt.Errorf("%s cannot be both a Fenrir key and a script key", Key_name(code)) + if r.readerModifier(code, false) { + return fmt.Errorf("%s cannot be both a Fenrir key and a script key", KeyName(code)) } } scriptBindings := make(map[string]command.ID) @@ -94,11 +94,11 @@ func (r *Router) Configure_scripts(keys []string, bindings []ScriptBinding) erro return fmt.Errorf("script binding has no command") } for _, name := range binding.Keys { - if !Valid_script_key(name) { + if !ValidScriptKey(name) { return fmt.Errorf("invalid script shortcut %q", name) } } - chord := Script_chord(binding.Keys) + chord := ScriptChord(binding.Keys) if _, exists := scriptBindings[chord]; exists { return fmt.Errorf("duplicate script shortcut %s", chord) } @@ -108,7 +108,7 @@ func (r *Router) Configure_scripts(keys []string, bindings []ScriptBinding) erro return nil } -func (r *Router) Script_keys() []uint16 { +func (r *Router) ScriptKeys() []uint16 { var keys []uint16 for key := range r.scriptKeys { keys = append(keys, key) @@ -117,7 +117,7 @@ func (r *Router) Script_keys() []uint16 { return keys } -func (r *Router) script_name(key uint16, numLock bool) string { +func (r *Router) scriptName(key uint16, numLock bool) string { // Python normalizes left/right modifiers before resolving reader modifiers. physical := key switch key { @@ -130,10 +130,10 @@ func (r *Router) script_name(key uint16, numLock bool) string { case KeyRightMeta: key = KeyMeta } - if r.script_modifier(physical, numLock) { + if r.scriptModifier(physical, numLock) { return "KEY_SCRIPT" } - if r.reader_modifier(physical, numLock) { + if r.readerModifier(physical, numLock) { return "KEY_FENRIR" } switch key { @@ -151,11 +151,11 @@ func (r *Router) script_name(key uint16, numLock bool) string { return C.GoString(name) } -func (r *Router) script_binding(key uint16, numLock bool) (command.ID, bool) { - active := r.script_modifier(key, numLock) +func (r *Router) scriptBinding(key uint16, numLock bool) (command.ID, bool) { + active := r.scriptModifier(key, numLock) if !active { for scriptKey := range r.scriptKeys { - if r.script_modifier(scriptKey, numLock) && r.down(scriptKey) { + if r.scriptModifier(scriptKey, numLock) && r.down(scriptKey) { active = true break } @@ -167,10 +167,10 @@ func (r *Router) script_binding(key uint16, numLock bool) (command.ID, bool) { names := map[string]bool{} for _, held := range r.keys { for code := range held { - names[r.script_name(code, numLock)] = true + names[r.scriptName(code, numLock)] = true } } - names[r.script_name(key, numLock)] = true + names[r.scriptName(key, numLock)] = true if !names["KEY_SCRIPT"] { return "", false } @@ -178,7 +178,7 @@ func (r *Router) script_binding(key uint16, numLock bool) (command.ID, bool) { for name := range names { keys = append(keys, name) } - if id := r.scriptBindings[Script_chord(keys)]; id != "" { + if id := r.scriptBindings[ScriptChord(keys)]; id != "" { return id, true } // Modifier prefixes are silent. Nonmatching script chords are consumed. diff --git a/internal/input/script_keys_test.go b/internal/input/script_keys_test.go index 81a6c13b..c068ae3b 100644 --- a/internal/input/script_keys_test.go +++ b/internal/input/script_keys_test.go @@ -24,8 +24,8 @@ import ( func TestScriptChordsModifiersRepeatsAndReleaseOrders(t *testing.T) { for _, releaseModifierFirst := range []bool{true, false} { - router := new_script_router(t, []string{"KEY_COMPOSE"}, []ScriptBinding{{ID: "script:music", Keys: []string{"KEY_SCRIPT", "KEY_SHIFT", "KEY_U"}}}) - compose, _ := Key_code("KEY_COMPOSE") + router := newScriptRouter(t, []string{"KEY_COMPOSE"}, []ScriptBinding{{ID: "script:music", Keys: []string{"KEY_SCRIPT", "KEY_SHIFT", "KEY_U"}}}) + compose, _ := KeyCode("KEY_COMPOSE") for _, key := range []uint16{compose, KeyRightShift} { if result := router.Key(0, key, 1, false, false); result.Forward || result.Command != "" { t.Fatal(result) @@ -52,22 +52,22 @@ func TestScriptChordsModifiersRepeatsAndReleaseOrders(t *testing.T) { } } -func new_script_router(t *testing.T, keys []string, bindings []ScriptBinding) Router { +func newScriptRouter(t *testing.T, keys []string, bindings []ScriptBinding) Router { t.Helper() - router, err := New_router(Layout{Bindings: []Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) + router, err := NewRouter(Layout{Bindings: []Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) if err != nil { t.Fatal(err) } - if err := router.Configure_scripts(keys, bindings); err != nil { + if err := router.ConfigureScripts(keys, bindings); err != nil { t.Fatal(err) } return router } func TestScriptRoutingHandoffPassNextAndUnbound(t *testing.T) { - router := new_script_router(t, []string{"KEY_F12"}, []ScriptBinding{{ID: "script:a", Keys: []string{"KEY_SCRIPT", "KEY_A"}}}) - f12, _ := Key_code("KEY_F12") - router.Pass_next() + router := newScriptRouter(t, []string{"KEY_F12"}, []ScriptBinding{{ID: "script:a", Keys: []string{"KEY_SCRIPT", "KEY_A"}}}) + f12, _ := KeyCode("KEY_F12") + router.PassNext() if result := router.Key(0, f12, 1, false, false); !result.Forward { t.Fatal(result) } diff --git a/internal/input/spellcheck_test.go b/internal/input/spellcheck_test.go index 1d03287a..593a48d0 100644 --- a/internal/input/spellcheck_test.go +++ b/internal/input/spellcheck_test.go @@ -10,12 +10,12 @@ import ( func TestSpellcheckChordCaptureReleaseAndHeldDelete(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, releases := range [][]uint16{{KeyInsert, 31}, {31, KeyInsert}} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/spelling_test.go b/internal/input/spelling_test.go index 0c8cea6f..291b8a97 100644 --- a/internal/input/spelling_test.go +++ b/internal/input/spelling_test.go @@ -12,7 +12,7 @@ import ( func TestBundledSpellingPressesAndHeldActions(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -24,7 +24,7 @@ func TestBundledSpellingPressesAndHeldActions(t *testing.T) { {KeyKP8, 23, []command.ID{command.CurrentLine, command.SpellLine, command.PhoneticLine, command.CurrentLine}}, {KeyKP2, 51, []command.ID{command.CurrentChar, command.PhoneticChar, command.CurrentChar}}, } { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/ui.go b/internal/input/ui.go index 05c733f6..40278e83 100644 --- a/internal/input/ui.go +++ b/internal/input/ui.go @@ -41,7 +41,7 @@ func (r *Router) Capture(enabled bool) { func (r *Router) Captured() bool { return r.captured } -func (r *Router) ui_key(code uint16) Decision { +func (r *Router) uiKey(code uint16) Decision { key := &interaction.Key{ Shift: r.down(KeyShift) || r.down(KeyRightShift), Ctrl: r.down(KeyCtrl) || r.down(KeyRightCtrl), diff --git a/internal/input/ui_test.go b/internal/input/ui_test.go index 18fd672d..cfdc4570 100644 --- a/internal/input/ui_test.go +++ b/internal/input/ui_test.go @@ -25,7 +25,7 @@ import ( ) func TestMenuChordAndCaptureSwallowEveryKey(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) router.Key(1, KeyInsert, 1, false, false) if got := router.Key(1, KeyF, 1, false, false); got.Command != command.FenrirMenu || got.Forward { t.Fatal(got) @@ -46,11 +46,11 @@ func TestMenuChordAndCaptureSwallowEveryKey(t *testing.T) { } func TestCaptureClearsPassNextAndDrainsHeldKeys(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) if !router.Key(1, KeyCtrl, 1, false, false).Forward { t.Fatal("fixture modifier not forwarded") } - router.Pass_next() + router.PassNext() router.Capture(true) if len(router.Forwarded(1)) != 0 { t.Fatal("forwarded state survived capture") @@ -76,7 +76,7 @@ func TestCaptureClearsPassNextAndDrainsHeldKeys(t *testing.T) { } func TestCapturedModifiersRepeatAndSync(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) router.Capture(true) if got := router.Key(3, KeyCtrl, 1, false, false); !got.Interrupt || got.Forward || got.UI != nil { t.Fatal("captured Control did not stop speech", got) @@ -103,7 +103,7 @@ func TestCapturedModifiersRepeatAndSync(t *testing.T) { } func TestDesktopTOMLValidated(t *testing.T) { - bindings, err := Decode_bindings(desktop_data(t)) + bindings, err := DecodeBindings(desktopData(t)) if err != nil || len(bindings.Bindings) == 0 { t.Fatal(bindings, err) } @@ -111,14 +111,14 @@ func TestDesktopTOMLValidated(t *testing.T) { {"version = 1", "version = 2"}, {"fenrir_menu", "unknown"}, {"\"FENRIR\", \"F\"", "\"FENRIR\", \"UNKNOWN\""}, } { - if _, err := Decode_bindings([]byte(strings.Replace(string(desktop_data(t)), replacement.old, replacement.new, 1))); err == nil { + if _, err := DecodeBindings([]byte(strings.Replace(string(desktopData(t)), replacement.old, replacement.new, 1))); err == nil { t.Fatal("invalid layout accepted", replacement) } } } func TestCapturedPageKeysReachInternalUI(t *testing.T) { - router := desktop_router(t) + router := desktopRouter(t) router.Capture(true) for _, step := range []struct { code uint16 diff --git a/internal/input/version_test.go b/internal/input/version_test.go index 6d682770..b8822e17 100644 --- a/internal/input/version_test.go +++ b/internal/input/version_test.go @@ -11,13 +11,13 @@ import ( func TestVersionChordConsumesRepeatsAndBothReleaseOrders(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } for _, modifierFirst := range []bool{false, true} { for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/input/vertical_character_test.go b/internal/input/vertical_character_test.go index 758db25d..e7e70d6e 100644 --- a/internal/input/vertical_character_test.go +++ b/internal/input/vertical_character_test.go @@ -11,7 +11,7 @@ import ( func TestVerticalCharacterChordsRepeatAndRelease(t *testing.T) { for _, layout := range []string{"desktop", "laptop"} { - bindings, _, err := Load_bindings([]string{"../../config/keyboard/" + layout + ".toml"}) + bindings, _, err := LoadBindings([]string{"../../config/keyboard/" + layout + ".toml"}) if err != nil { t.Fatal(err) } @@ -24,7 +24,7 @@ func TestVerticalCharacterChordsRepeatAndRelease(t *testing.T) { for _, controlKey := range []uint16{KeyCtrl, KeyRightCtrl} { for _, modifierFirst := range []bool{false, true} { for _, numLock := range []bool{false, true} { - router, err := New_router(bindings) + router, err := NewRouter(bindings) if err != nil { t.Fatal(err) } diff --git a/internal/interaction/choice_test.go b/internal/interaction/choice_test.go index 64c5b9b5..002321b1 100644 --- a/internal/interaction/choice_test.go +++ b/internal/interaction/choice_test.go @@ -29,7 +29,7 @@ func TestGroupedChoicesTraversalIsolationAndSelection(t *testing.T) { {ID: "sound.enabled", Label: "Sound enabled", Group: "Sound", Kind: CheckBox}, {ID: "ok", Label: "OK", Kind: Button, Action: "save"}, }}}} - session, err := New_session(form) + session, err := NewSession(form) if err != nil { t.Fatal(err) } @@ -79,7 +79,7 @@ func TestComboChangesSpeakOnlyValueAndFocusRepeatsLabel(t *testing.T) { {ID: "format", Label: "Format", Kind: ComboBox, Choices: []Choice{{ID: "one", Label: "First"}, {ID: "two", Label: "Second"}, {ID: "three", Label: "Third"}}}, {ID: "ok", Label: "OK", Kind: Button, Action: "save"}, }}}} - session, err := New_session(form) + session, err := NewSession(form) if err != nil { t.Fatal(err) } @@ -113,7 +113,7 @@ func TestChoiceDefinitionsRejectMissingAndDuplicateSelections(t *testing.T) { } { control.ID, control.Label, control.Kind = "driver", "Driver", ComboBox form := Form{Type: TabForm, Title: "Settings", Tabs: []Tab{{ID: "presentation", Label: "Presentation", Controls: []Control{control}}}} - if _, err := New_session(form); err == nil { + if _, err := NewSession(form); err == nil { t.Fatal("invalid combo accepted", control) } } diff --git a/internal/interaction/dynamic_grid_test.go b/internal/interaction/dynamic_grid_test.go index 619daeb1..71fab4f8 100644 --- a/internal/interaction/dynamic_grid_test.go +++ b/internal/interaction/dynamic_grid_test.go @@ -9,10 +9,10 @@ import ( ) func TestEmptyAndRefreshedGridKeepsFocusSearchAndLiteralWords(t *testing.T) { - form := grid_form() + form := gridForm() form.Tabs[0].Controls[0].Choices = nil form.Tabs[0].Controls[0].DeleteAction = "remove" - session, err := New_session(form) + session, err := NewSession(form) if err != nil { t.Fatal(err) } @@ -21,10 +21,10 @@ func TestEmptyAndRefreshedGridKeepsFocusSearchAndLiteralWords(t *testing.T) { t.Fatal(got) } session.Handle(Key{Text: "c"}) - session.Set_choices("one", "grid", []Choice{{ID: "cat", Label: "cat", Literal: true}, {ID: "car", Label: "car", Literal: true}}) + session.SetChoices("one", "grid", []Choice{{ID: "cat", Label: "cat", Literal: true}, {ID: "car", Label: "car", Literal: true}}) session.Handle(Key{Name: "right"}) - session.Set_choices("one", "grid", []Choice{{ID: "car", Label: "car", Literal: true}, {ID: "cat", Label: "cat", Literal: true}}) - control, _ := session.Focused_control() + session.SetChoices("one", "grid", []Choice{{ID: "car", Label: "car", Literal: true}, {ID: "cat", Label: "cat", Literal: true}}) + control, _ := session.FocusedControl() if control.Text != "c" || control.Choices[control.Selected].ID != "car" { t.Fatal(control) } @@ -34,13 +34,13 @@ func TestEmptyAndRefreshedGridKeepsFocusSearchAndLiteralWords(t *testing.T) { if got := session.Handle(Key{Name: "delete"}); got.Action != "remove" { t.Fatal(got) } - session.Set_choices("one", "grid", nil) + session.SetChoices("one", "grid", nil) if !strings.Contains(session.Describe(), "No matches") { t.Fatal(session.Describe()) } // Updating a grid must own its choices, independently of worker buffers. choices := []Choice{{ID: "cat", Label: "cat", Literal: true}} - session.Set_choices("one", "grid", choices) + session.SetChoices("one", "grid", choices) choices[0].Label = "wrong" if !strings.Contains(session.Describe(), "cat") { t.Fatal(session.Describe()) diff --git a/internal/interaction/grid_test.go b/internal/interaction/grid_test.go index 6750ed24..5c70e07f 100644 --- a/internal/interaction/grid_test.go +++ b/internal/interaction/grid_test.go @@ -9,7 +9,7 @@ import ( "testing" ) -func grid_form() Form { +func gridForm() Form { return Form{Type: TabForm, Title: "Picker", Tabs: []Tab{{ID: "one", Label: "One", Controls: []Control{{ ID: "grid", Label: "Items", Kind: Grid, Columns: 3, Action: "choose", Choices: []Choice{{ID: "a", Label: "Apple"}, {ID: "b", Label: "Bat"}, {ID: "c", Label: "Cat"}, @@ -18,7 +18,7 @@ func grid_form() Form { } func TestGridNavigationRaggedRowsAndActivation(t *testing.T) { - session, err := New_session(grid_form()) + session, err := NewSession(gridForm()) if err != nil { t.Fatal(err) } @@ -28,7 +28,7 @@ func TestGridNavigationRaggedRowsAndActivation(t *testing.T) { {"up", "d"}, {"left", "c"}, {"home", "a"}, {"left", "a"}, {"end", "é"}, {"right", "é"}, } { session.Handle(Key{Name: trial.key}) - control, _ := session.Focused_control() + control, _ := session.FocusedControl() if got := control.Choices[control.Selected].ID; got != trial.want { t.Fatalf("%s: got %s, want %s", trial.key, got, trial.want) } @@ -40,8 +40,8 @@ func TestGridNavigationRaggedRowsAndActivation(t *testing.T) { } func TestGridPrefixEmptyResultsUnicodeAndIsolation(t *testing.T) { - form := grid_form() - session, err := New_session(form) + form := gridForm() + session, err := NewSession(form) if err != nil { t.Fatal(err) } @@ -50,7 +50,7 @@ func TestGridPrefixEmptyResultsUnicodeAndIsolation(t *testing.T) { t.Fatal(got) } session.Handle(Key{Name: "right"}) - control, _ := session.Focused_control() + control, _ := session.FocusedControl() if control.Selected != 5 { t.Fatal("filtered selection lost catalog index", control) } @@ -70,7 +70,7 @@ func TestGridPrefixEmptyResultsUnicodeAndIsolation(t *testing.T) { t.Fatal(got) } session.Handle(Key{Name: "backspace"}) - control, _ = session.Focused_control() + control, _ = session.FocusedControl() if control.Text != "" || form.Tabs[0].Controls[0].Selected != 0 || form.Tabs[0].Controls[0].Text != "" { t.Fatal("Unicode deletion or form isolation failed", control) } @@ -80,14 +80,14 @@ func TestGridPrefixEmptyResultsUnicodeAndIsolation(t *testing.T) { } func TestGridValidation(t *testing.T) { - form := grid_form() + form := gridForm() form.Tabs[0].Controls[0].Columns = 0 - if _, err := New_session(form); err == nil { + if _, err := NewSession(form); err == nil { t.Fatal("zero-width grid accepted") } - form = grid_form() + form = gridForm() form.Tabs[0].Controls[0].Choices[1].ID = "a" - if _, err := New_session(form); err == nil { + if _, err := NewSession(form); err == nil { t.Fatal("duplicate values accepted") } } @@ -102,11 +102,11 @@ func TestGridSpeechDetailOptions(t *testing.T) { {false, true, "Bat. 2 of 7", "Japan. 2 of 2"}, {false, false, "Bat", "Japan"}, } { - session, err := New_session(grid_form()) + session, err := NewSession(gridForm()) if err != nil { t.Fatal(err) } - session.Configure_grid(trial.coordinates, trial.position) + session.ConfigureGrid(trial.coordinates, trial.position) session.Handle(Key{Name: "tab"}) if got := session.Handle(Key{Name: "right"}).Speech; got != trial.want { t.Fatalf("%+v: %q", trial, got) diff --git a/internal/interaction/list_test.go b/internal/interaction/list_test.go index cd085a1e..a287c615 100644 --- a/internal/interaction/list_test.go +++ b/internal/interaction/list_test.go @@ -7,7 +7,7 @@ package interaction import "testing" func TestListPrefixSearch(t *testing.T) { - session, err := New_session(Form{Type: TabForm, Title: "Picker", Tabs: []Tab{{ID: "items", Label: "Items", Controls: []Control{ + session, err := NewSession(Form{Type: TabForm, Title: "Picker", Tabs: []Tab{{ID: "items", Label: "Items", Controls: []Control{ {ID: "list", Label: "Item", Kind: List, Items: []string{"Default", "NetworkManager", "Ninjam", "Éclair"}, Action: "choose"}, {ID: "cancel", Label: "Cancel", Kind: Button, Action: "cancel"}, }}}}) diff --git a/internal/interaction/session_test.go b/internal/interaction/session_test.go index 2fbb1537..bd37a9b0 100644 --- a/internal/interaction/session_test.go +++ b/internal/interaction/session_test.go @@ -24,15 +24,15 @@ import ( func TestInvalidNumberUpDownStepRejected(t *testing.T) { for _, step := range []float64{-1, math.NaN(), math.Inf(1), math.Inf(-1)} { - form := test_form() + form := testForm() form.Tabs[0].Controls[1].UpDownStep = step - if _, err := New_session(form); err == nil { + if _, err := NewSession(form); err == nil { t.Fatalf("invalid Up/Down step %v accepted", step) } } } -func test_form() Form { +func testForm() Form { return Form{Type: TabForm, Title: "Settings", Tabs: []Tab{ {ID: "speech", Label: "Speech", Controls: []Control{ {ID: "enabled", Label: "Speech enabled", Kind: CheckBox, Checked: true}, @@ -46,8 +46,8 @@ func test_form() Form { } func TestTabFormTraversalControlsAndIsolation(t *testing.T) { - form := test_form() - session, err := New_session(form) + form := testForm() + session, err := NewSession(form) if err != nil { t.Fatal(err) } @@ -134,7 +134,7 @@ func TestTabFormTraversalControlsAndIsolation(t *testing.T) { func TestListCategoryFormReturnsSelectionWithoutSideEffects(t *testing.T) { form := Form{Type: TabForm, Title: "Picker", Tabs: []Tab{{ID: "category", Label: "Category", Controls: []Control{{ID: "items", Label: "Items", Kind: List, Items: []string{"First", "Second"}, Action: "choose"}}}}} - session, err := New_session(form) + session, err := NewSession(form) if err != nil { t.Fatal(err) } @@ -154,9 +154,9 @@ func TestListCategoryFormReturnsSelectionWithoutSideEffects(t *testing.T) { } func TestUnknownFormTypeRejected(t *testing.T) { - form := test_form() + form := testForm() form.Type = "unknown" - if _, err := New_session(form); err == nil { + if _, err := NewSession(form); err == nil { t.Fatal("unknown form type accepted") } } diff --git a/internal/interaction/shared.go b/internal/interaction/shared.go index b2426640..a06722e2 100644 --- a/internal/interaction/shared.go +++ b/internal/interaction/shared.go @@ -31,6 +31,6 @@ const ( FlatForm = shared.FlatForm ) -func New_session(form Form) (*Session, error) { +func NewSession(form Form) (*Session, error) { return shared.NewSession(form, shared.Messages{Translate: i18n.T}) } diff --git a/internal/interaction/visibility_test.go b/internal/interaction/visibility_test.go index 7e864969..941b2844 100644 --- a/internal/interaction/visibility_test.go +++ b/internal/interaction/visibility_test.go @@ -6,21 +6,21 @@ package interaction import "testing" func TestHiddenControlsRetainDraftAndRemainOutsideBothTabOrders(t *testing.T) { - session, err := New_session(test_form()) + session, err := NewSession(testForm()) if err != nil { t.Fatal(err) } - session.Set_hidden("speech", "range", true) + session.SetHidden("speech", "range", true) for _, want := range []string{"enabled", "text", "ok", "cancel", ""} { session.Handle(Key{Name: "tab"}) - got, focused := session.Focused_control() + got, focused := session.FocusedControl() if focused != (want != "") || got.ID != want { t.Fatal(got, want) } } for _, want := range []string{"cancel", "ok", "text", "enabled", ""} { session.Handle(Key{Name: "tab", Shift: true}) - got, focused := session.Focused_control() + got, focused := session.FocusedControl() if focused != (want != "") || got.ID != want { t.Fatal(got, want) } @@ -29,17 +29,17 @@ func TestHiddenControlsRetainDraftAndRemainOutsideBothTabOrders(t *testing.T) { session.Handle(Key{Name: "tab"}) session.Handle(Key{Ctrl: true, Text: "a"}) session.Handle(Key{Text: "draft"}) - session.Set_hidden("speech", "text", true) - if got, _ := session.Focused_control(); got.ID != "ok" { + session.SetHidden("speech", "text", true) + if got, _ := session.FocusedControl(); got.ID != "ok" { t.Fatal("hidden focus retained", got) } - session.Set_hidden("speech", "text", false) + session.SetHidden("speech", "text", false) session.Handle(Key{Name: "tab", Shift: true}) if got := session.Values()["speech.text"]; got.Text != "draft" || got.Hidden { t.Fatal(got) } for _, id := range []string{"enabled", "range", "text", "ok", "cancel"} { - session.Set_hidden("speech", id, true) + session.SetHidden("speech", id, true) } if got := session.Handle(Key{Name: "tab"}).Speech; got != "Speech tab" { t.Fatal("all-hidden tab trapped focus", got) diff --git a/internal/notifications/shared_linux.go b/internal/notifications/shared_linux.go index 84e3aee7..317226a9 100644 --- a/internal/notifications/shared_linux.go +++ b/internal/notifications/shared_linux.go @@ -74,7 +74,7 @@ type Client struct { // readers; production uses the empty namespace and the kernel account ID. func New(ctx context.Context, uid int, namespace string) *Client { ctx, cancel := context.WithCancel(ctx) - c := &Client{UID: uid, id: fmt.Sprintf("%x", random_id()), address: fmt.Sprintf("@fenrir-notifications.%d%s", uid, namespace), ctx: ctx, cancel: cancel, + c := &Client{UID: uid, id: fmt.Sprintf("%x", randomId()), address: fmt.Sprintf("@fenrir-notifications.%d%s", uid, namespace), ctx: ctx, cancel: cancel, wake: make(chan struct{}, 1), updates: make(chan struct{}, 1), sounds: make(chan func(context.Context), 1), done: make(chan struct{})} go c.run() return c @@ -93,11 +93,11 @@ func (c *Client) Publish(text string, received time.Time) { if text == "" { return } - c.adopt(Snapshot{Entries: []Entry{{ID: fmt.Sprintf("%x", random_id()), Text: text, Received: received.UTC()}}}) + c.adopt(Snapshot{Entries: []Entry{{ID: fmt.Sprintf("%x", randomId()), Text: text, Received: received.UTC()}}}) signal(c.wake) } -func random_id() [16]byte { +func randomId() [16]byte { var id [16]byte // crypto/rand.Read cannot return an error with the Go version we require. _, _ = rand.Read(id[:]) @@ -122,9 +122,9 @@ func (c *Client) adopt(state Snapshot) { } } -// Claim_sound fails closed if coordination is unavailable. Notification speech +// ClaimSound fails closed if coordination is unavailable. Notification speech // never depends on its success, and history synchronization cannot call speech. -func (c *Client) Claim_sound(ctx context.Context) bool { +func (c *Client) ClaimSound(ctx context.Context) bool { if last := c.Snapshot().LastSound; !last.IsZero() && time.Since(last) < SoundInterval { return false } @@ -160,7 +160,7 @@ func (c *Client) run() { case <-c.wake: case <-tick.C: case play := <-c.sounds: - if c.Claim_sound(c.ctx) { + if c.ClaimSound(c.ctx) { play(c.ctx) } } @@ -215,7 +215,7 @@ func (c *Client) transact(ctx context.Context, claim, leaving bool) (response, e defer connection.Close() stopConnection := context.AfterFunc(ctx, func() { connection.Close() }) defer stopConnection() - uid, err := peer_uid(connection.(*net.UnixConn)) + uid, err := peerUid(connection.(*net.UnixConn)) if err != nil || uid != c.UID && uid != 0 { return result, fmt.Errorf("notification coordinator belongs to another account") } @@ -287,7 +287,7 @@ func (b *broker) serve() { } func (b *broker) handle(connection *net.UnixConn) { - uid, err := peer_uid(connection) + uid, err := peerUid(connection) if err != nil || uid != 0 && uid != b.uid { return } @@ -357,7 +357,7 @@ replicate: b.workers.Wait() } -func peer_uid(connection *net.UnixConn) (int, error) { +func peerUid(connection *net.UnixConn) (int, error) { raw, err := connection.SyscallConn() if err != nil { return -1, err diff --git a/internal/notifications/shared_test.go b/internal/notifications/shared_test.go index 34079cc4..addafead 100644 --- a/internal/notifications/shared_test.go +++ b/internal/notifications/shared_test.go @@ -17,14 +17,14 @@ import ( "time" ) -func test_client(t *testing.T, namespace string) *Client { +func testClient(t *testing.T, namespace string) *Client { t.Helper() c := New(context.Background(), os.Geteuid(), namespace) t.Cleanup(c.Close) return c } -func wait_history(t *testing.T, c *Client, want int) Snapshot { +func waitHistory(t *testing.T, c *Client, want int) Snapshot { t.Helper() deadline := time.NewTimer(5 * time.Second) defer deadline.Stop() @@ -41,10 +41,10 @@ func wait_history(t *testing.T, c *Client, want int) Snapshot { } func TestSharedHistoryConcurrentPublishingBoundAndSingleCue(t *testing.T) { - namespace := fmt.Sprintf(".%x", random_id()) + namespace := fmt.Sprintf(".%x", randomId()) var clients []*Client for range 4 { - clients = append(clients, test_client(t, namespace)) + clients = append(clients, testClient(t, namespace)) } var workers sync.WaitGroup for index, client := range clients { @@ -56,7 +56,7 @@ func TestSharedHistoryConcurrentPublishingBoundAndSingleCue(t *testing.T) { } workers.Wait() for _, client := range clients { - wait_history(t, client, Limit) + waitHistory(t, client, Limit) } // Reconcile after reaching the limit: all replicas must agree on the same // newest 100 IDs rather than just having the same length. @@ -75,7 +75,7 @@ func TestSharedHistoryConcurrentPublishingBoundAndSingleCue(t *testing.T) { } accepted := make(chan bool, len(clients)) for _, client := range clients { - workers.Go(func() { accepted <- client.Claim_sound(context.Background()) }) + workers.Go(func() { accepted <- client.ClaimSound(context.Background()) }) } workers.Wait() close(accepted) @@ -89,59 +89,59 @@ func TestSharedHistoryConcurrentPublishingBoundAndSingleCue(t *testing.T) { t.Fatal("multiple readers admitted the notification cue", count) } for _, client := range clients { - if client.Claim_sound(context.Background()) { + if client.ClaimSound(context.Background()) { t.Fatal("a repeated cue escaped the shared cooldown") } } } func TestCoordinatorTakeoverAndHistoryLifetime(t *testing.T) { - namespace := fmt.Sprintf(".%x", random_id()) - owner := test_client(t, namespace) + namespace := fmt.Sprintf(".%x", randomId()) + owner := testClient(t, namespace) owner.Publish("Before takeover", time.Now()) - if !owner.Claim_sound(context.Background()) { + if !owner.ClaimSound(context.Background()) { t.Fatal("first cue was rejected") } - survivor := test_client(t, namespace) - wait_history(t, survivor, 1) + survivor := testClient(t, namespace) + waitHistory(t, survivor, 1) // Synchronize the cue timestamp before terminating the coordinator. if _, err := survivor.exchange(context.Background(), false); err != nil { t.Fatal(err) } owner.Close() - if survivor.Claim_sound(context.Background()) { + if survivor.ClaimSound(context.Background()) { t.Fatal("coordinator exit reset the cooldown") } survivor.Publish("After takeover", time.Now()) if _, err := survivor.exchange(context.Background(), false); err != nil { t.Fatal(err) } - joining := test_client(t, namespace) - wait_history(t, joining, 2) + joining := testClient(t, namespace) + waitHistory(t, joining, 2) survivor.Close() joining.Close() - fresh := test_client(t, namespace) + fresh := testClient(t, namespace) if _, err := fresh.exchange(context.Background(), false); err != nil { t.Fatal(err) } - if len(fresh.Snapshot().Entries) != 0 || !fresh.Claim_sound(context.Background()) { + if len(fresh.Snapshot().Entries) != 0 || !fresh.ClaimSound(context.Background()) { t.Fatal("history or cooldown survived the last reader") } } func TestCoordinatorExitFlushesNotificationToSurvivingReader(t *testing.T) { - namespace := fmt.Sprintf(".%x", random_id()) - owner := test_client(t, namespace) + namespace := fmt.Sprintf(".%x", randomId()) + owner := testClient(t, namespace) if _, err := owner.exchange(context.Background(), false); err != nil { t.Fatal(err) } - survivor := test_client(t, namespace) + survivor := testClient(t, namespace) if _, err := survivor.exchange(context.Background(), false); err != nil { t.Fatal(err) } owner.Publish("Immediately before exit", time.Now()) owner.Close() - wait_history(t, survivor, 1) + waitHistory(t, survivor, 1) if _, err := survivor.exchange(context.Background(), false); err != nil { t.Fatal(err) } @@ -151,8 +151,8 @@ func TestCoordinatorExitFlushesNotificationToSurvivingReader(t *testing.T) { } func TestMutedSoundRequestsUseSharedCooldown(t *testing.T) { - namespace := fmt.Sprintf(".%x", random_id()) - first, second := test_client(t, namespace), test_client(t, namespace) + namespace := fmt.Sprintf(".%x", randomId()) + first, second := testClient(t, namespace), testClient(t, namespace) played := make(chan struct{}, 4) play := func(context.Context) { played <- struct{}{} } first.Sound(play) @@ -170,16 +170,16 @@ func TestMutedSoundRequestsUseSharedCooldown(t *testing.T) { } func TestCanceledClaimDoesNotConsumeCooldownAndNamespacesStaySeparate(t *testing.T) { - namespace := fmt.Sprintf(".%x", random_id()) - first := test_client(t, namespace) - second := test_client(t, namespace+".other") + namespace := fmt.Sprintf(".%x", randomId()) + first := testClient(t, namespace) + second := testClient(t, namespace+".other") ctx, cancel := context.WithCancel(context.Background()) cancel() - if first.Claim_sound(ctx) { + if first.ClaimSound(ctx) { t.Fatal("canceled cue was accepted") } first.Publish("Private history", time.Now()) - if !first.Claim_sound(context.Background()) || !second.Claim_sound(context.Background()) { + if !first.ClaimSound(context.Background()) || !second.ClaimSound(context.Background()) { t.Fatal("unrelated histories shared a cooldown") } if len(second.Snapshot().Entries) != 0 { @@ -188,8 +188,8 @@ func TestCanceledClaimDoesNotConsumeCooldownAndNamespacesStaySeparate(t *testing } func TestBrokerRejectsInvalidFramesAndAdmitsCueAfterCooldown(t *testing.T) { - namespace := fmt.Sprintf(".%x", random_id()) - c := test_client(t, namespace) + namespace := fmt.Sprintf(".%x", randomId()) + c := testClient(t, namespace) if _, err := c.exchange(context.Background(), false); err != nil { t.Fatal(err) } @@ -217,7 +217,7 @@ func TestBrokerRejectsInvalidFramesAndAdmitsCueAfterCooldown(t *testing.T) { b.mu.Lock() b.state.LastSound = time.Now().Add(-SoundInterval) b.mu.Unlock() - if !c.Claim_sound(context.Background()) { + if !c.ClaimSound(context.Background()) { t.Fatal("expired cooldown did not admit a cue") } } @@ -266,7 +266,7 @@ type notificationProcess struct { stopped bool } -func start_process(t *testing.T, namespace string) *notificationProcess { +func startProcess(t *testing.T, namespace string) *notificationProcess { t.Helper() command := exec.Command(os.Args[0], "-test.run=^TestNotificationProcess$") command.Env = append(os.Environ(), "FENRIR_NOTIFICATION_PROCESS="+namespace) @@ -327,21 +327,21 @@ func (p *notificationProcess) stop(t *testing.T) { func TestFourProcessesShareHistoryAndCooldownAcrossCoordinatorExit(t *testing.T) { for _, crash := range []bool{false, true} { t.Run(fmt.Sprintf("crash=%v", crash), func(t *testing.T) { - check_four_processes(t, crash) + checkFourProcesses(t, crash) }) } } -func check_four_processes(t *testing.T, crash bool) { +func checkFourProcesses(t *testing.T, crash bool) { t.Helper() - namespace := fmt.Sprintf(".%x", random_id()) - processes := []*notificationProcess{start_process(t, namespace)} + namespace := fmt.Sprintf(".%x", randomId()) + processes := []*notificationProcess{startProcess(t, namespace)} want := processes[0].send(t, processRequest{Publish: "One targeted notification", Claim: true}) if len(want.State.Entries) != 1 || !want.Allowed { t.Fatal(want) } for range 3 { - processes = append(processes, start_process(t, namespace)) + processes = append(processes, startProcess(t, namespace)) } for _, process := range processes[1:] { got := process.send(t, processRequest{Claim: true}) diff --git a/internal/preferences/application_test.go b/internal/preferences/application_test.go index 4d1b09ee..221eb136 100644 --- a/internal/preferences/application_test.go +++ b/internal/preferences/application_test.go @@ -11,7 +11,7 @@ import ( func TestApplicationSettingsOnlyExposeRestorableControls(t *testing.T) { base := config.Defaults() - session, err := New_application_session(base, nil, "Ninjam application settings") + session, err := NewApplicationSession(base, nil, "Ninjam application settings") if err != nil { t.Fatal(err) } @@ -24,9 +24,9 @@ func TestApplicationSettingsOnlyExposeRestorableControls(t *testing.T) { if _, exists := values["presentation.speech.voice"]; !exists { t.Fatal("voice control missing") } - tab_to_control(t, session, "speech.rate") + tabToControl(t, session, "speech.rate") session.Handle(interaction.Key{Name: "up"}) - saved, err := Application_settings(session, base) + saved, err := ApplicationSettings(session, base) if err != nil || saved.Presentation.Speech.Rate != base.Presentation.Speech.Rate+10 || saved.Keyboard.Layout != base.Keyboard.Layout { t.Fatal(saved, err) } diff --git a/internal/preferences/discovery.go b/internal/preferences/discovery.go index 66607dc9..003dee39 100644 --- a/internal/preferences/discovery.go +++ b/internal/preferences/discovery.go @@ -18,9 +18,9 @@ type Discovery struct { Err error } -// Discover_choices runs only in a worker, never on the input loop. -func Discover_choices(settings config.Settings) Discovery { - driver, err := speech.Find_driver(settings.Presentation.Speech.Driver) +// DiscoverChoices runs only in a worker, never on the input loop. +func DiscoverChoices(settings config.Settings) Discovery { + driver, err := speech.FindDriver(settings.Presentation.Speech.Driver) if err == nil { err = driver.Availability() } @@ -46,7 +46,7 @@ func (d Discovery) Choices(settings config.Settings) Choices { for _, module := range d.Catalog.Modules { modules = append(modules, config.Choice{ID: module, Label: module}) } - result["presentation.speech.module"] = preserve_choice(modules, selected.Module, d.Err) + result["presentation.speech.module"] = preserveChoice(modules, selected.Module, d.Err) voices := d.Catalog.Voices[selected.Module] err := d.Err if moduleErr := d.Catalog.Errors[selected.Module]; moduleErr != nil { @@ -60,10 +60,10 @@ func (d Discovery) Choices(settings config.Settings) Choices { seen[voice.Language] = true } } - result["presentation.speech.language"] = preserve_choice(languages, selected.Language, err) + result["presentation.speech.language"] = preserveChoice(languages, selected.Language, err) filtered := voices if selected.Language != "" { - filtered = speech.Language_voices(voices, selected.Language) + filtered = speech.LanguageVoices(voices, selected.Language) } else { espeak := strings.Contains(strings.ToLower(selected.Module), "espeak") if selected.Module == "" { @@ -75,7 +75,7 @@ func (d Discovery) Choices(settings config.Settings) Choices { } } if espeak { - filtered = speech.Language_voices(voices, "") + filtered = speech.LanguageVoices(voices, "") } } voiceChoices := []config.Choice{{ID: "", Label: "default"}} @@ -88,11 +88,11 @@ func (d Discovery) Choices(settings config.Settings) Choices { voiceChoices = append(voiceChoices, config.Choice{ID: voice.Name, Label: voice.Name}) } } - result["presentation.speech.voice"] = preserve_choice(voiceChoices, selected.Voice, err) + result["presentation.speech.voice"] = preserveChoice(voiceChoices, selected.Voice, err) return result } -func preserve_choice(choices []config.Choice, saved string, err error) []config.Choice { +func preserveChoice(choices []config.Choice, saved string, err error) []config.Choice { if err != nil { choices[0].Unavailable = err.Error() } @@ -106,10 +106,10 @@ func preserve_choice(choices []config.Choice, saved string, err error) []config. return append(choices, config.Choice{ID: saved, Label: saved, Unavailable: reason}) } -// Refresh_speech updates driver visibility and dependent choices. Driver changes +// RefreshSpeech updates driver visibility and dependent choices. Driver changes // keep hidden edits; module/language changes clear their dependent selections. // The result tells the host when a different driver's catalog may be needed. -func (d Discovery) Refresh_speech(session *interaction.Session, previous *config.Settings) bool { +func (d Discovery) RefreshSpeech(session *interaction.Session, previous *config.Settings) bool { next := *previous values := session.Values() for path, target := range map[string]*string{ @@ -132,11 +132,11 @@ func (d Discovery) Refresh_speech(session *interaction.Session, previous *config driverChanged := next.Presentation.Speech.Driver != previous.Presentation.Speech.Driver *previous = next if driverChanged { - driver, _ := speech.Find_driver(next.Presentation.Speech.Driver) - session.Set_hidden("presentation", "speech.test", !driver.Hardware) + driver, _ := speech.FindDriver(next.Presentation.Speech.Driver) + session.SetHidden("presentation", "speech.test", !driver.Hardware) for _, definition := range config.Definitions() { if definition.SpeechCapability != "" { - session.Set_hidden("presentation", strings.TrimPrefix(definition.Path, "presentation."), !definition.Available(next)) + session.SetHidden("presentation", strings.TrimPrefix(definition.Path, "presentation."), !definition.Available(next)) } } // Keep each backend's hidden selections intact while another driver is @@ -152,27 +152,27 @@ func (d Discovery) Refresh_speech(session *interaction.Session, previous *config next.Presentation.Speech.Voice = "" choices := d.Choices(next) if moduleChanged { - session.Replace_choices("presentation", "speech.language", interaction_choices(choices["presentation.speech.language"]), "") + session.ReplaceChoices("presentation", "speech.language", interactionChoices(choices["presentation.speech.language"]), "") } - session.Replace_choices("presentation", "speech.voice", interaction_choices(choices["presentation.speech.voice"]), "") + session.ReplaceChoices("presentation", "speech.voice", interactionChoices(choices["presentation.speech.voice"]), "") *previous = next return false } -// Refresh_catalog applies a worker result to the current selector draft. It +// RefreshCatalog applies a worker result to the current selector draft. It // never moves focus or resets a selection made while discovery was pending. -func (d Discovery) Refresh_catalog(session *interaction.Session, selected config.Settings) { +func (d Discovery) RefreshCatalog(session *interaction.Session, selected config.Settings) { choices := d.Choices(selected) for path, value := range map[string]string{ "presentation.speech.module": selected.Presentation.Speech.Module, "presentation.speech.language": selected.Presentation.Speech.Language, "presentation.speech.voice": selected.Presentation.Speech.Voice, } { - session.Replace_choices("presentation", strings.TrimPrefix(path, "presentation."), interaction_choices(choices[path]), value) + session.ReplaceChoices("presentation", strings.TrimPrefix(path, "presentation."), interactionChoices(choices[path]), value) } } -func interaction_choices(choices []config.Choice) []interaction.Choice { +func interactionChoices(choices []config.Choice) []interaction.Choice { result := make([]interaction.Choice, 0, len(choices)) for _, choice := range choices { result = append(result, interaction.Choice{ID: choice.ID, Label: choice.Label, Unavailable: choice.Unavailable}) diff --git a/internal/preferences/discovery_test.go b/internal/preferences/discovery_test.go index 5cc1ee19..7e7eedc6 100644 --- a/internal/preferences/discovery_test.go +++ b/internal/preferences/discovery_test.go @@ -33,12 +33,12 @@ func TestModuleDiscoveryAndOfflinePreservation(t *testing.T) { base := config.Defaults() base.Presentation.Speech.Module = "saved-module" t.Setenv("SPEECHD_ADDRESS", "unix_socket:"+filepath.Join(t.TempDir(), "missing.sock")) - offline := Discover_choices(base).Choices(base) + offline := DiscoverChoices(base).Choices(base) choices := offline["presentation.speech.module"] if len(choices) != 2 || choices[1].ID != "saved-module" || choices[1].Unavailable == "" { t.Fatal(choices) } - session, err := New_session(base, nil, offline) + session, err := NewSession(base, nil, offline) if err != nil { t.Fatal(err) } @@ -69,7 +69,7 @@ func TestModuleDiscoveryAndOfflinePreservation(t *testing.T) { done <- request }() t.Setenv("SPEECHD_ADDRESS", "unix_socket:"+path) - online := Discover_choices(base).Choices(base)["presentation.speech.module"] + online := DiscoverChoices(base).Choices(base)["presentation.speech.module"] if request := <-done; request != "LIST OUTPUT_MODULES\r\n" { t.Fatal(request) } @@ -96,19 +96,19 @@ func TestDependentSpeechChoicesKeepSavedVoicesAndFilterEspeak(t *testing.T) { if got := choices["presentation.speech.voice"]; len(got) != 4 || got[3].ID != "German" || got[3].Unavailable != "" { t.Fatal("valid saved voice lost", got) } - session, err := New_session(base, nil, choices) + session, err := NewSession(base, nil, choices) if err != nil { t.Fatal(err) } previous := base - session.Replace_choices("presentation", "speech.language", interaction_choices(choices["presentation.speech.language"]), "de") - discovery.Refresh_speech(session, &previous) + session.ReplaceChoices("presentation", "speech.language", interactionChoices(choices["presentation.speech.language"]), "de") + discovery.RefreshSpeech(session, &previous) values := session.Values() if got := values["presentation.speech.voice"]; len(got.Choices) != 2 || got.Choices[1].ID != "German" || got.Selected != 0 { t.Fatal(got) } - session.Replace_choices("presentation", "speech.module", interaction_choices(choices["presentation.speech.module"]), "fixture") - discovery.Refresh_speech(session, &previous) + session.ReplaceChoices("presentation", "speech.module", interactionChoices(choices["presentation.speech.module"]), "fixture") + discovery.RefreshSpeech(session, &previous) values = session.Values() if values["presentation.speech.language"].Selected != 0 || values["presentation.speech.voice"].Selected != 0 || len(values["presentation.speech.voice"].Choices) != 2 { t.Fatal(values) @@ -121,7 +121,7 @@ func TestDependentSpeechChoicesKeepSavedVoicesAndFilterEspeak(t *testing.T) { t.Fatal(path, got) } } - session, err = New_session(base, nil, offline) + session, err = NewSession(base, nil, offline) if err != nil { t.Fatal(err) } @@ -139,7 +139,7 @@ func TestHardwareDriverChangesHideDispatcherChoicesAndPreserveDevice(t *testing. base.Presentation.Speech.Language = "en" base.Presentation.Speech.Voice = "Fixture Voice" discovery := Discovery{Driver: "speech-dispatcher", Catalog: speech.Catalog{Modules: []string{"fixture"}, Voices: map[string][]speech.Voice{"fixture": {{Name: "Fixture Voice", Language: "en"}}}}} - session, err := New_session(base, nil, discovery.Choices(base)) + session, err := NewSession(base, nil, discovery.Choices(base)) if err != nil { t.Fatal(err) } @@ -151,8 +151,8 @@ func TestHardwareDriverChangesHideDispatcherChoicesAndPreserveDevice(t *testing. choices = definition.Choices(base) } } - session.Replace_choices("presentation", "speech.driver", interaction_choices(choices), id) - discovery.Refresh_speech(session, &previous) + session.ReplaceChoices("presentation", "speech.driver", interactionChoices(choices), id) + discovery.RefreshSpeech(session, &previous) draft, err := Settings(session, base) if err != nil { t.Fatal(id, err) diff --git a/internal/preferences/hardware_form_test.go b/internal/preferences/hardware_form_test.go index 465a805b..ddf57e1c 100644 --- a/internal/preferences/hardware_form_test.go +++ b/internal/preferences/hardware_form_test.go @@ -10,10 +10,10 @@ import ( "git.stormux.org/storm/fenrir/internal/interaction" ) -func focus_setting(t *testing.T, session *interaction.Session, id string) { +func focusSetting(t *testing.T, session *interaction.Session, id string) { t.Helper() for range 100 { - if control, ok := session.Focused_control(); ok && control.ID == id { + if control, ok := session.FocusedControl(); ok && control.ID == id { return } session.Handle(interaction.Key{Name: "tab"}) @@ -23,7 +23,7 @@ func focus_setting(t *testing.T, session *interaction.Session, id string) { func TestHardwareControlsUpdateImmediatelyAndKeepDraftEdits(t *testing.T) { base := config.Defaults() - session, err := New_session(base, nil) + session, err := NewSession(base, nil) if err != nil { t.Fatal(err) } @@ -34,25 +34,25 @@ func TestHardwareControlsUpdateImmediatelyAndKeepDraftEdits(t *testing.T) { t.Fatal("hardware control initially visible", path) } } - focus_setting(t, session, "speech.driver") + focusSetting(t, session, "speech.driver") session.Handle(interaction.Key{Name: "down"}) - if !discovery.Refresh_speech(session, &previous) { + if !discovery.RefreshSpeech(session, &previous) { t.Fatal("driver change not detected") } - if control, _ := session.Focused_control(); control.ID != "speech.driver" { + if control, _ := session.FocusedControl(); control.ID != "speech.driver" { t.Fatal("driver change moved focus", control) } - focus_setting(t, session, "speech.hardware_device") + focusSetting(t, session, "speech.hardware_device") session.Handle(interaction.Key{Text: "/dev/fixture-synth"}) - focus_setting(t, session, "speech.hardware_baud_rate") + focusSetting(t, session, "speech.hardware_baud_rate") session.Handle(interaction.Key{Name: "end"}) draft, err := Settings(session, base) if err != nil || draft.Presentation.Speech.HardwareDevice != "/dev/fixture-synth" || draft.Presentation.Speech.HardwareBaudRate != 115200 { t.Fatal(draft, err) } - focus_setting(t, session, "speech.driver") + focusSetting(t, session, "speech.driver") session.Handle(interaction.Key{Name: "down"}) - discovery.Refresh_speech(session, &previous) + discovery.RefreshSpeech(session, &previous) for _, path := range []string{"presentation.speech.hardware_device", "presentation.speech.hardware_baud_rate", "presentation.speech.module", "presentation.speech.language", "presentation.speech.voice"} { if !session.Values()[path].Hidden { t.Fatal("irrelevant USB control visible", path) @@ -62,13 +62,13 @@ func TestHardwareControlsUpdateImmediatelyAndKeepDraftEdits(t *testing.T) { t.Fatal("USB test button hidden") } session.Handle(interaction.Key{Name: "up"}) - discovery.Refresh_speech(session, &previous) + discovery.RefreshSpeech(session, &previous) draft, err = Settings(session, base) if err != nil || draft.Presentation.Speech.HardwareDevice != "/dev/fixture-synth" || draft.Presentation.Speech.HardwareBaudRate != 115200 { t.Fatal("driver round trip lost edits", draft, err) } session.Handle(interaction.Key{Name: "home"}) - discovery.Refresh_speech(session, &previous) + discovery.RefreshSpeech(session, &previous) if !session.Values()["presentation.speech.test"].Hidden || session.Values()["presentation.speech.module"].Hidden { t.Fatal("Speech Dispatcher controls not restored") } @@ -79,15 +79,15 @@ func TestEveryHardwareFormCanSavePortAndTypedBaud(t *testing.T) { base := config.Defaults() base.Presentation.Speech.Driver = driver base.Presentation.Speech.HardwareDevice = "/dev/fixture-original" - session, err := New_session(base, nil) + session, err := NewSession(base, nil) if err != nil { t.Fatal(err) } if driver != "dectalk-usb" { - focus_setting(t, session, "speech.hardware_device") + focusSetting(t, session, "speech.hardware_device") session.Handle(interaction.Key{Ctrl: true, Text: "a"}) session.Handle(interaction.Key{Text: "/dev/fixture-updated"}) - focus_setting(t, session, "speech.hardware_baud_rate") + focusSetting(t, session, "speech.hardware_baud_rate") session.Handle(interaction.Key{Name: "home"}) session.Handle(interaction.Key{Name: "down"}) } diff --git a/internal/preferences/modifiers.go b/internal/preferences/modifiers.go index aa5d5ef1..be481dd4 100644 --- a/internal/preferences/modifiers.go +++ b/internal/preferences/modifiers.go @@ -22,7 +22,7 @@ var modifierOptions = []modifierOption{ {name: "KEY_META", Label: "Super"}, } -func reader_names(settings config.Settings) []string { +func readerNames(settings config.Settings) []string { if settings.Keyboard.FenrirKeys != nil { return settings.Keyboard.FenrirKeys } @@ -35,16 +35,16 @@ func reader_names(settings config.Settings) []string { default: names = []string{"KEY_KP0", "KEY_INSERT", "KEY_META"} } - available, err := input.Available_fenrir_keys(names, settings.General.ScriptKeys) + available, err := input.AvailableFenrirKeys(names, settings.General.ScriptKeys) if err != nil { return []string{} } return available } -func modifier_checked(names []string, name string) bool { - keys, _ := input.Modifier_codes(names) - option, _ := input.Modifier_codes([]string{name}) +func modifierChecked(names []string, name string) bool { + keys, _ := input.ModifierCodes(names) + option, _ := input.ModifierCodes([]string{name}) for key := range option { if keys[key] { return true @@ -53,13 +53,13 @@ func modifier_checked(names []string, name string) bool { return false } -func modifier_controls(settings config.Settings) []interaction.Control { +func modifierControls(settings config.Settings) []interaction.Control { var controls []interaction.Control for _, role := range []struct { id, Label string names []string }{ - {id: "fenrir_key.", Label: "Fenrir keys", names: reader_names(settings)}, + {id: "fenrir_key.", Label: "Fenrir keys", names: readerNames(settings)}, {id: "script_key.", Label: "Script keys", names: settings.General.ScriptKeys}, } { options := slices.Clone(modifierOptions) @@ -67,13 +67,13 @@ func modifier_controls(settings config.Settings) []interaction.Control { options = append(options, modifierOption{name: "KEY_COMPOSE", Label: "Compose"}) } for _, option := range options { - controls = append(controls, interaction.Control{ID: role.id + option.name, Label: option.Label, Group: role.Label, Kind: interaction.CheckBox, Checked: modifier_checked(role.names, option.name)}) + controls = append(controls, interaction.Control{ID: role.id + option.name, Label: option.Label, Group: role.Label, Kind: interaction.CheckBox, Checked: modifierChecked(role.names, option.name)}) } } return controls } -func selected_modifiers(values map[string]interaction.Control, prefix string, names []string, options []modifierOption) ([]string, bool, error) { +func selectedModifiers(values map[string]interaction.Control, prefix string, names []string, options []modifierOption) ([]string, bool, error) { selected := slices.Clone(names) changed := false for _, option := range options { @@ -81,7 +81,7 @@ func selected_modifiers(values map[string]interaction.Control, prefix string, na if !ok { return nil, false, fmt.Errorf("missing modifier checkbox %s", option.name) } - if control.Checked == modifier_checked(names, option.name) { + if control.Checked == modifierChecked(names, option.name) { continue } changed = true @@ -89,21 +89,21 @@ func selected_modifiers(values map[string]interaction.Control, prefix string, na selected = append(selected, option.name) continue } - selected = slices.DeleteFunc(selected, func(name string) bool { return modifier_checked([]string{name}, option.name) }) + selected = slices.DeleteFunc(selected, func(name string) bool { return modifierChecked([]string{name}, option.name) }) } return selected, changed, nil } -func modifier_settings(values map[string]interaction.Control, base *config.Settings) error { - reader, changed, err := selected_modifiers(values, "fenrir_key.", reader_names(*base), modifierOptions) +func modifierSettings(values map[string]interaction.Control, base *config.Settings) error { + reader, changed, err := selectedModifiers(values, "fenrir_key.", readerNames(*base), modifierOptions) if err != nil { return err } - scripts, _, err := selected_modifiers(values, "script_key.", base.General.ScriptKeys, append(slices.Clone(modifierOptions), modifierOption{name: "KEY_COMPOSE", Label: "Compose"})) + scripts, _, err := selectedModifiers(values, "script_key.", base.General.ScriptKeys, append(slices.Clone(modifierOptions), modifierOption{name: "KEY_COMPOSE", Label: "Compose"})) if err != nil { return err } - if err := input.Validate_modifier_keys(reader, scripts); err != nil { + if err := input.ValidateModifierKeys(reader, scripts); err != nil { return err } if changed { diff --git a/internal/preferences/modifiers_test.go b/internal/preferences/modifiers_test.go index 033726db..9b24f6ae 100644 --- a/internal/preferences/modifiers_test.go +++ b/internal/preferences/modifiers_test.go @@ -12,10 +12,10 @@ import ( "git.stormux.org/storm/fenrir/internal/interaction" ) -func focus_modifier(t *testing.T, s *interaction.Session, id string) { +func focusModifier(t *testing.T, s *interaction.Session, id string) { t.Helper() for range 40 { - if control, ok := s.Focused_control(); ok && control.ID == id { + if control, ok := s.FocusedControl(); ok && control.ID == id { return } s.Handle(interaction.Key{Name: "tab"}) @@ -29,7 +29,7 @@ func TestModifierCheckboxesRejectConflictAndSaveSelections(t *testing.T) { base.Keyboard.Devices = []string{} base.Keyboard.FenrirKeys = []string{key} base.General.ScriptKeys = []string{"KEY_COMPOSE", "KEY_F9"} - session, err := New_session(base, []string{"keyboard"}) + session, err := NewSession(base, []string{"keyboard"}) if err != nil { t.Fatal(err) } @@ -39,12 +39,12 @@ func TestModifierCheckboxesRejectConflictAndSaveSelections(t *testing.T) { t.Fatal(control) } } - focus_modifier(t, session, "script_key."+key) + focusModifier(t, session, "script_key."+key) session.Handle(interaction.Key{Name: "space"}) if _, err := Settings(session, base); err == nil { t.Fatal("overlapping checkbox roles saved", key) } - focus_modifier(t, session, "fenrir_key."+key) + focusModifier(t, session, "fenrir_key."+key) session.Handle(interaction.Key{Name: "space"}) if _, err := Settings(session, base); err == nil { t.Fatal("all reader keys unchecked accepted") @@ -53,17 +53,17 @@ func TestModifierCheckboxesRejectConflictAndSaveSelections(t *testing.T) { if key == replacement { replacement = "KEY_CAPSLOCK" } - focus_modifier(t, session, "fenrir_key."+replacement) + focusModifier(t, session, "fenrir_key."+replacement) session.Handle(interaction.Key{Name: "space"}) draft, err := Settings(session, base) - if err != nil || !modifier_checked(draft.General.ScriptKeys, key) || !modifier_checked(draft.Keyboard.FenrirKeys, replacement) || modifier_checked(draft.Keyboard.FenrirKeys, key) { + if err != nil || !modifierChecked(draft.General.ScriptKeys, key) || !modifierChecked(draft.Keyboard.FenrirKeys, replacement) || modifierChecked(draft.Keyboard.FenrirKeys, key) { t.Fatal(draft.Keyboard, draft.General, err) } if !reflect.DeepEqual(base.Keyboard.FenrirKeys, []string{key}) || len(base.General.ScriptKeys) != 2 { t.Fatal("draft changed original") } path := filepath.Join(t.TempDir(), "settings.toml") - doc, err := config.Open_document(path, base) + doc, err := config.OpenDocument(path, base) if err != nil { t.Fatal(err) } @@ -74,7 +74,7 @@ func TestModifierCheckboxesRejectConflictAndSaveSelections(t *testing.T) { if err != nil || !reflect.DeepEqual(saved.Keyboard.FenrirKeys, draft.Keyboard.FenrirKeys) || !reflect.DeepEqual(saved.General.ScriptKeys, draft.General.ScriptKeys) { t.Fatal(saved.Keyboard, saved.General, err) } - if !modifier_checked(saved.General.ScriptKeys, "KEY_F9") { + if !modifierChecked(saved.General.ScriptKeys, "KEY_F9") { t.Fatal("custom script key lost") } } @@ -85,7 +85,7 @@ func TestModifierCheckboxesPreserveSideSpecificSuperAndDefaults(t *testing.T) { base.Keyboard.Devices = []string{} base.Keyboard.FenrirKeys = []string{"KEY_RIGHTMETA"} base.General.ScriptKeys = []string{"KEY_LEFTMETA"} - session, err := New_session(base, []string{"keyboard"}) + session, err := NewSession(base, []string{"keyboard"}) if err != nil { t.Fatal(err) } @@ -96,7 +96,7 @@ func TestModifierCheckboxesPreserveSideSpecificSuperAndDefaults(t *testing.T) { base = config.Defaults() base.Keyboard.Devices = []string{} base.General.ScriptKeys = []string{"KEY_META", "KEY_COMPOSE"} - session, err = New_session(base, []string{"keyboard"}) + session, err = NewSession(base, []string{"keyboard"}) if err != nil { t.Fatal(err) } diff --git a/internal/preferences/settings.go b/internal/preferences/settings.go index f181a094..f5898b37 100644 --- a/internal/preferences/settings.go +++ b/internal/preferences/settings.go @@ -37,31 +37,31 @@ type Choices map[string][]config.Choice const MenuTitle = "Fenrir Menu" -func New_session(settings config.Settings, order []string, discovered ...Choices) (*interaction.Session, error) { - return new_session(settings, order, MenuTitle, false, discovered...) +func NewSession(settings config.Settings, order []string, discovered ...Choices) (*interaction.Session, error) { + return newSession(settings, order, MenuTitle, false, discovered...) } -func New_application_session(settings config.Settings, order []string, title string, discovered ...Choices) (*interaction.Session, error) { - return new_session(settings, order, title, true, discovered...) +func NewApplicationSession(settings config.Settings, order []string, title string, discovered ...Choices) (*interaction.Session, error) { + return newSession(settings, order, title, true, discovered...) } -func new_session(settings config.Settings, order []string, title string, application bool, discovered ...Choices) (*interaction.Session, error) { +func newSession(settings config.Settings, order []string, title string, application bool, discovered ...Choices) (*interaction.Session, error) { if err := settings.Validate(); err != nil { return nil, err } form := interaction.Form{Type: interaction.TabForm, Title: title} - for _, section := range config.Ordered_sections(config.Sections(), order) { + for _, section := range config.OrderedSections(config.Sections(), order) { if section.Label == "" { continue } tab := interaction.Tab{ID: section.ID, Label: section.Label} - var append_section func(config.Section, string) error - append_section = func(section config.Section, group string) error { + var appendSection func(config.Section, string) error + appendSection = func(section config.Section, group string) error { for _, definition := range section.Settings { - if application && !config.Application_setting(definition.Path) { + if application && !config.ApplicationSetting(definition.Path) { continue } - control, err := make_control(definition, settings, discovered) + control, err := makeControl(definition, settings, discovered) if err != nil { return err } @@ -69,25 +69,25 @@ func new_session(settings config.Settings, order []string, title string, applica control.Group = group tab.Controls = append(tab.Controls, control) } - for _, child := range config.Ordered_sections(section.Sections, order) { + for _, child := range config.OrderedSections(section.Sections, order) { label := child.Label if group != "" { label = group + ". " + label } - if err := append_section(child, label); err != nil { + if err := appendSection(child, label); err != nil { return err } } if section.ID == "keyboard" && !application { - tab.Controls = append(tab.Controls, modifier_controls(settings)...) + tab.Controls = append(tab.Controls, modifierControls(settings)...) } if section.ID == "presentation.speech" { - driver, _ := speech.Find_driver(settings.Presentation.Speech.Driver) + driver, _ := speech.FindDriver(settings.Presentation.Speech.Driver) tab.Controls = append(tab.Controls, interaction.Control{ID: "speech.test", Label: "Test synthesizer", Group: "Speech", Kind: interaction.Button, Action: "test-synthesizer", Hidden: !driver.Hardware}) } return nil } - if err := append_section(section, ""); err != nil { + if err := appendSection(section, ""); err != nil { return nil, err } if len(tab.Controls) == 0 { @@ -103,10 +103,10 @@ func new_session(settings config.Settings, order []string, title string, applica interaction.Control{ID: "cancel", Label: "Cancel", Kind: interaction.Button, Action: "cancel"}) form.Tabs = append(form.Tabs, profiles) } - return interaction.New_session(form) + return interaction.NewSession(form) } -func make_control(definition config.Definition, settings config.Settings, discovered []Choices) (interaction.Control, error) { +func makeControl(definition config.Definition, settings config.Settings, discovered []Choices) (interaction.Control, error) { control := interaction.Control{Label: definition.Label, Hidden: !definition.Available(settings)} value := definition.Value(settings) if definition.ChoiceSource != "" { @@ -164,14 +164,14 @@ func make_control(definition config.Definition, settings config.Settings, discov } func Settings(session *interaction.Session, base config.Settings) (config.Settings, error) { - return settings_values(session, base, false) + return settingsValues(session, base, false) } -func Application_settings(session *interaction.Session, base config.Settings) (config.Settings, error) { - return settings_values(session, base, true) +func ApplicationSettings(session *interaction.Session, base config.Settings) (config.Settings, error) { + return settingsValues(session, base, true) } -func settings_values(session *interaction.Session, base config.Settings, application bool) (config.Settings, error) { +func settingsValues(session *interaction.Session, base config.Settings, application bool) (config.Settings, error) { values := session.Values() // Visibility follows the form's selected driver, including unsaved switches. driver, hasDriver := values["presentation.speech.driver"] @@ -182,7 +182,7 @@ func settings_values(session *interaction.Session, base config.Settings, applica base.Presentation.Speech.Driver = driver.Choices[driver.Selected].ID } for _, definition := range config.Definitions() { - if !definition.Available(base) || (application && !config.Application_setting(definition.Path)) { + if !definition.Available(base) || (application && !config.ApplicationSetting(definition.Path)) { continue } control, ok := values[definition.Path] @@ -230,7 +230,7 @@ func settings_values(session *interaction.Session, base config.Settings, applica } } if !application { - if err := modifier_settings(values, &base); err != nil { + if err := modifierSettings(values, &base); err != nil { return config.Settings{}, err } } diff --git a/internal/preferences/settings_test.go b/internal/preferences/settings_test.go index 7d59313c..f8e0a925 100644 --- a/internal/preferences/settings_test.go +++ b/internal/preferences/settings_test.go @@ -30,7 +30,7 @@ import ( func TestSettingsFormCoversSchemaAndReturnsIsolatedDraft(t *testing.T) { base := config.Defaults() base.Keyboard.Devices = []string{"/dev/input/event-test"} - session, err := New_session(base, []string{"presentation", "presentation.speech", "presentation.sound"}) + session, err := NewSession(base, []string{"presentation", "presentation.speech", "presentation.sound"}) if err != nil { t.Fatal(err) } @@ -50,7 +50,7 @@ func TestSettingsFormCoversSchemaAndReturnsIsolatedDraft(t *testing.T) { } session.Handle(interaction.Key{Name: "tab"}) session.Handle(interaction.Key{Name: "space"}) - tab_to_control(t, session, "speech.rate") + tabToControl(t, session, "speech.rate") session.Handle(interaction.Key{Name: "up"}) draft, err := Settings(session, base) if err != nil { @@ -78,18 +78,18 @@ func TestSpeechRateArrowSteps(t *testing.T) { } { base := config.Defaults() base.Presentation.Speech.Rate = trial.start - session, err := new_session(base, []string{"presentation"}, MenuTitle, application) + session, err := newSession(base, []string{"presentation"}, MenuTitle, application) if err != nil { t.Fatal(err) } - tab_to_control(t, session, "speech.rate") + tabToControl(t, session, "speech.rate") result := session.Handle(interaction.Key{Name: trial.key}) if want := "Rate " + strconv.Itoa(trial.want); result.Speech != want { t.Fatalf("application=%v, rate=%d, key=%s: speech=%q, want %q", application, trial.start, trial.key, result.Speech, want) } var draft config.Settings if application { - draft, err = Application_settings(session, base) + draft, err = ApplicationSettings(session, base) } else { draft, err = Settings(session, base) } @@ -102,7 +102,7 @@ func TestSpeechRateArrowSteps(t *testing.T) { func TestReadingModeIsConstrainedAndSavedInDraft(t *testing.T) { base := config.Defaults() - session, err := New_session(base, []string{"reading"}) + session, err := NewSession(base, []string{"reading"}) if err != nil { t.Fatal(err) } @@ -124,7 +124,7 @@ func TestCapitalCheckboxesRoundTripIndependently(t *testing.T) { base.Reading.RaisePitchForCapitals = choices&1 != 0 base.Reading.BeepForCapitals = choices&2 != 0 base.Reading.SayCapForCapitals = choices&4 != 0 - session, err := New_session(base, []string{"reading"}) + session, err := NewSession(base, []string{"reading"}) if err != nil { t.Fatal(err) } @@ -150,7 +150,7 @@ func TestCapitalCheckboxesRoundTripIndependently(t *testing.T) { } func TestInvalidDeviceEntryDoesNotSubmit(t *testing.T) { - session, err := New_session(config.Defaults(), []string{"keyboard"}) + session, err := NewSession(config.Defaults(), []string{"keyboard"}) if err != nil { t.Fatal(err) } @@ -166,7 +166,7 @@ func TestKeyboardLayoutComboBox(t *testing.T) { for _, saved := range []string{"desktop", "laptop", "/tmp/custom.toml"} { base := config.Defaults() base.Keyboard.Layout = saved - session, err := New_session(base, []string{"keyboard"}) + session, err := NewSession(base, []string{"keyboard"}) if err != nil { t.Fatal(err) } @@ -197,7 +197,7 @@ func TestKeyboardLayoutComboBox(t *testing.T) { func TestKeyboardEchoCheckboxesSaveIndependently(t *testing.T) { base := config.Defaults() - session, err := New_session(base, []string{"keyboard"}) + session, err := NewSession(base, []string{"keyboard"}) if err != nil { t.Fatal(err) } @@ -221,7 +221,7 @@ func TestKeyboardEchoCheckboxesSaveIndependently(t *testing.T) { func TestClipboardSyncCheckboxPreservesAdvancedSettings(t *testing.T) { base := config.Defaults() base.Clipboard.SyncDisplay, base.Clipboard.ExportPath, base.Clipboard.NumberOfClipboards = ":42", "/tmp/fixture-clipboard", 3 - session, err := New_session(base, []string{"clipboard"}) + session, err := NewSession(base, []string{"clipboard"}) if err != nil { t.Fatal(err) } @@ -237,7 +237,7 @@ func TestClipboardSyncCheckboxPreservesAdvancedSettings(t *testing.T) { func TestPresentationGroupsFollowSchemaAndFileOrder(t *testing.T) { base := config.Defaults() - session, err := New_session(base, []string{"reading", "presentation", "presentation.sound", "presentation.speech"}) + session, err := NewSession(base, []string{"reading", "presentation", "presentation.sound", "presentation.speech"}) if err != nil { t.Fatal(err) } @@ -268,13 +268,13 @@ func TestConstrainedChoicesKeepStableIDsAndIgnoreTextEditing(t *testing.T) { base := config.Defaults() base.Presentation.Speech.Module = "fixture-module" base.Keyboard.Devices = []string{} - session, err := New_session(base, nil, Choices{"presentation.speech.module": { + session, err := NewSession(base, nil, Choices{"presentation.speech.module": { {ID: "", Label: "default"}, {ID: "fixture-module", Label: "Fixture module", Unavailable: "fixture server offline"}, }}) if err != nil { t.Fatal(err) } - tab_to_control(t, session, "speech.driver") + tabToControl(t, session, "speech.driver") session.Handle(interaction.Key{Ctrl: true, Text: "a"}) session.Handle(interaction.Key{Text: "invented-driver"}) session.Handle(interaction.Key{Name: "tab"}) @@ -296,7 +296,7 @@ func TestSoundChoicesPreserveUnavailableThemeAndFileOnlyDevice(t *testing.T) { base := config.Defaults() base.Presentation.Sound.Theme = "missing-fixture-theme" base.Presentation.Sound.Device = "plughw:CARD=Generic,DEV=0" - session, err := New_session(base, []string{"presentation", "presentation.sound"}) + session, err := NewSession(base, []string{"presentation", "presentation.sound"}) if err != nil { t.Fatal(err) } @@ -315,7 +315,7 @@ func TestSoundChoicesPreserveUnavailableThemeAndFileOnlyDevice(t *testing.T) { func TestInternalUIOptionsAndApplicationIsolation(t *testing.T) { base := config.Defaults() - session, err := New_session(base, []string{"internal_ui"}) + session, err := NewSession(base, []string{"internal_ui"}) if err != nil { t.Fatal(err) } @@ -335,7 +335,7 @@ func TestInternalUIOptionsAndApplicationIsolation(t *testing.T) { t.Fatal("options did not save independently", draft.InternalUI) } } - application, err := New_application_session(base, nil, "Application settings") + application, err := NewApplicationSession(base, nil, "Application settings") if err != nil { t.Fatal(err) } @@ -346,11 +346,11 @@ func TestInternalUIOptionsAndApplicationIsolation(t *testing.T) { } } -// tab_to_control moves focus with Tab, as a user would, until id is focused. -func tab_to_control(t *testing.T, session *interaction.Session, id string) { +// tabToControl moves focus with Tab, as a user would, until id is focused. +func tabToControl(t *testing.T, session *interaction.Session, id string) { t.Helper() for range 64 { - if control, ok := session.Focused_control(); ok && control.ID == id { + if control, ok := session.FocusedControl(); ok && control.ID == id { return } session.Handle(interaction.Key{Name: "tab"}) diff --git a/internal/presentation/attributes.go b/internal/presentation/attributes.go index 120a9ce8..9f2d141e 100644 --- a/internal/presentation/attributes.go +++ b/internal/presentation/attributes.go @@ -10,10 +10,10 @@ import ( "strings" ) -// Default_attribute_format is Python Fenrir's default, including its tokens. -const Default_attribute_format = "Background fenrirBGColor,Foreground fenrirFGColor,fenrirUnderline,fenrirBold,fenrirBlink, Font fenrirFont,Fontsize fenrirFontSize" +// DefaultAttributeFormat is Python Fenrir's default, including its tokens. +const DefaultAttributeFormat = "Background fenrirBGColor,Foreground fenrirFGColor,fenrirUnderline,fenrirBold,fenrirBlink, Font fenrirFont,Fontsize fenrirFontSize" -func attribute_color(color uint32, background bool) string { +func attributeColor(color uint32, background bool) string { if color == screen.ColorDefault { return i18n.T("default") } @@ -38,10 +38,10 @@ func attribute_color(color uint32, background bool) string { return fmt.Sprintf("#%02x%02x%02x", value, value, value) } -// Format_attributes substitutes the Python tokens. Font metadata is not +// FormatAttributes substitutes the Python tokens. Font metadata is not // available from either backend; default means unspecified, not a detected font. -func Format_attributes(attribute screen.Attribute, format string) string { - pairs := []string{"fenrirFGColor", attribute_color(attribute.Foreground, false), "fenrirBGColor", attribute_color(attribute.Background, true), "fenrirFontSize", i18n.T("default"), "fenrirFont", i18n.T("default")} +func FormatAttributes(attribute screen.Attribute, format string) string { + pairs := []string{"fenrirFGColor", attributeColor(attribute.Foreground, false), "fenrirBGColor", attributeColor(attribute.Background, true), "fenrirFontSize", i18n.T("default"), "fenrirFont", i18n.T("default")} for _, style := range []struct { token, text string mask uint32 @@ -59,8 +59,8 @@ func Format_attributes(attribute screen.Attribute, format string) string { return strings.NewReplacer(pairs...).Replace(format) } -func Attribute_message(attribute screen.Attribute, mode, format string) Message { - text := Format_attributes(attribute, format) +func AttributeMessage(attribute screen.Attribute, mode, format string) Message { + text := FormatAttributes(attribute, format) if mode == "beeps" || strings.TrimSpace(text) == "" && !attribute.Default() { text = i18n.T("has attribute") } diff --git a/internal/presentation/attributes_test.go b/internal/presentation/attributes_test.go index c8cfa0b0..db7ef8ff 100644 --- a/internal/presentation/attributes_test.go +++ b/internal/presentation/attributes_test.go @@ -12,7 +12,7 @@ import ( func TestAttributeColorsStylesAndPythonFormat(t *testing.T) { format := "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirUnderline|fenrirItalics|fenrirBlink|fenrirReverse|fenrirStrikethrough|fenrirFontSize|fenrirFont" a := screen.Attribute{Foreground: screen.ColorIndexed | 1, Background: screen.ColorIndexed | 4, Style: screen.Bold | screen.Underline | screen.Italic | screen.Blink | screen.Reverse | screen.Strike} - if got := Format_attributes(a, format); got != "red|blue|bold|underline|italic|blink|reverse|strikethrough|default|default" { + if got := FormatAttributes(a, format); got != "red|blue|bold|underline|italic|blink|reverse|strikethrough|default|default" { t.Fatal(got) } for _, trial := range []struct { @@ -24,14 +24,14 @@ func TestAttributeColorsStylesAndPythonFormat(t *testing.T) { {screen.ColorIndexed | 16, "#000000"}, {screen.ColorIndexed | 196, "#ff0000"}, {screen.ColorIndexed | 231, "#ffffff"}, {screen.ColorIndexed | 232, "#080808"}, {screen.ColorIndexed | 255, "#eeeeee"}, } { - if got := Format_attributes(screen.Attribute{Foreground: trial.color}, "fenrirFGColor"); got != trial.want { + if got := FormatAttributes(screen.Attribute{Foreground: trial.color}, "fenrirFGColor"); got != trial.want { t.Fatal(trial, got) } } - if got := Format_attributes(screen.Attribute{}, "fenrirBold fenrirUnderline fenrirBlink"); strings.TrimSpace(got) != "" { + if got := FormatAttributes(screen.Attribute{}, "fenrirBold fenrirUnderline fenrirBlink"); strings.TrimSpace(got) != "" { t.Fatal(got) } - if got := Format_attributes(a, ""); got != "" { + if got := FormatAttributes(a, ""); got != "" { t.Fatal(got) } } diff --git a/internal/presentation/indentation.go b/internal/presentation/indentation.go index 373b6412..2b344318 100644 --- a/internal/presentation/indentation.go +++ b/internal/presentation/indentation.go @@ -10,10 +10,10 @@ import ( "git.stormux.org/storm/fenrir/internal/i18n" ) -// Indentation_level counts leading visible whitespace cells. Terminal backends +// IndentationLevel counts leading visible whitespace cells. Terminal backends // normally expand tabs already; a literal tab advances to the next 8-cell stop. // Blank rows have no meaningful indentation, including terminal padding. -func Indentation_level(line []rune) (int, bool) { +func IndentationLevel(line []rune) (int, bool) { level := 0 for _, char := range line { if !unicode.IsSpace(char) { @@ -28,7 +28,7 @@ func Indentation_level(line []rune) (int, bool) { return 0, false } -func Indentation_message(level int, mode string) Message { +func IndentationMessage(level int, mode string) Message { message := Message{Text: i18n.T("indented ") + strconv.Itoa(level) + " "} if mode == "beeps" || mode == "both" { message.Indentation = &Indentation{Level: level, Speech: mode == "both"} diff --git a/internal/presentation/indentation_test.go b/internal/presentation/indentation_test.go index 99baf2b3..009104bd 100644 --- a/internal/presentation/indentation_test.go +++ b/internal/presentation/indentation_test.go @@ -15,7 +15,7 @@ func TestIndentationCountsVisibleWhitespaceAndIgnoresBlankRows(t *testing.T) { {"\t \tvalue", 16, true}, {"\u00a0\u2003É", 2, true}, {"", 0, false}, {" ", 0, false}, {"\t ", 0, false}, } { - level, valid := Indentation_level([]rune(trial.text)) + level, valid := IndentationLevel([]rune(trial.text)) if level != trial.level || valid != trial.valid { t.Fatalf("%q: %d %v", trial.text, level, valid) } diff --git a/internal/presentation/phonetic.go b/internal/presentation/phonetic.go index 2e8acb34..be5780b7 100644 --- a/internal/presentation/phonetic.go +++ b/internal/presentation/phonetic.go @@ -9,9 +9,9 @@ import ( "git.stormux.org/storm/screenreader-common/phonetic" ) -// Phonetic_letter matches the shared spelling alphabet with Fenrir capitalization. +// PhoneticLetter matches the shared spelling alphabet with Fenrir capitalization. // Other runes use the active punctuation profile's character naming instead. -func Phonetic_letter(char rune) string { +func PhoneticLetter(char rune) string { word := phonetic.Letter(char) if word == "" { return "" diff --git a/internal/presentation/phonetic_test.go b/internal/presentation/phonetic_test.go index 893993cf..3037e915 100644 --- a/internal/presentation/phonetic_test.go +++ b/internal/presentation/phonetic_test.go @@ -14,7 +14,7 @@ func TestPythonPhoneticNamesAndUnicodeFallback(t *testing.T) { {'w', "whiskey"}, {'W', "Whiskey"}, {'x', "x ray"}, {'X', "X ray"}, {'É', ""}, {'界', ""}, {'1', ""}, {'?', ""}, {' ', ""}, } { - if got := Phonetic_letter(trial.char); got != trial.want { + if got := PhoneticLetter(trial.char); got != trial.want { t.Fatal(trial, got) } } diff --git a/internal/presentation/text.go b/internal/presentation/text.go index 4864fb46..1af54586 100644 --- a/internal/presentation/text.go +++ b/internal/presentation/text.go @@ -37,8 +37,8 @@ func Line(s screen.Snapshot, row int) string { return text } -// Line_message describes a row with Python's blank-line sound alternative. -func Line_message(s screen.Snapshot, row int) Message { +// LineMessage describes a row with Python's blank-line sound alternative. +func LineMessage(s screen.Snapshot, row int) Message { message := Message{Text: Line(s, row)} if strings.TrimSpace(s.Text(row)) == "" { message.Cue = Blank @@ -46,7 +46,7 @@ func Line_message(s screen.Snapshot, row int) Message { return message } -func Character_message(char rune) Message { +func CharacterMessage(char rune) Message { return Message{Text: Character(char), Character: &char} } diff --git a/internal/progress/monitor.go b/internal/progress/monitor.go index 1c13378f..60d0faae 100644 --- a/internal/progress/monitor.go +++ b/internal/progress/monitor.go @@ -80,7 +80,7 @@ func (m *Monitor) Update(previous, next screen.Snapshot, editingRow int) { changedCount = len(changedRows) scrollStart, scrollEnd := 0, 0 if len(changedRows) > 1 { - scrollStart, scrollEnd = screen.Scrolled_overlap(previous, next) + scrollStart, scrollEnd = screen.ScrolledOverlap(previous, next) } var lines []string length := 0 diff --git a/internal/progress/monitor_test.go b/internal/progress/monitor_test.go index a9d27c08..9f681025 100644 --- a/internal/progress/monitor_test.go +++ b/internal/progress/monitor_test.go @@ -44,7 +44,7 @@ func TestWholeRowThrottlingAndFinalValue(t *testing.T) { t.Fatal(value, ok) } for percentage := 51; percentage <= 100; percentage++ { - next := snapshot("Download "+format_percent(percentage), "") + next := snapshot("Download "+formatPercent(percentage), "") m.Update(after, next, -1) after = next } @@ -152,4 +152,4 @@ func TestMultilineLongRowsAndActivity(t *testing.T) { } } -func format_percent(value int) string { return fmt.Sprint(value) + "%" } +func formatPercent(value int) string { return fmt.Sprint(value) + "%" } diff --git a/internal/progress/patterns.go b/internal/progress/patterns.go index ffa2091f..1a901c0e 100644 --- a/internal/progress/patterns.go +++ b/internal/progress/patterns.go @@ -58,7 +58,7 @@ var ( const sizeField = `\d+(?:\.\d+)?(?:[kKmMgGtT](?:i?[bB])?)?` const clockField = `(?:(?:\d+:)?\d{2}:\d{2}|--:--:--)` -func curl_percentage(text string) (float64, bool) { +func curlPercentage(text string) (float64, bool) { match := curlPattern.FindStringSubmatch(text) if match == nil { return 0, false @@ -69,7 +69,7 @@ func curl_percentage(text string) (float64, bool) { return total, total <= 100 && total == received && uploaded <= 100 } -func status_fields(text string) bool { +func statusFields(text string) bool { names := make(map[string]bool) for _, match := range fieldPattern.FindAllStringSubmatch(text, -1) { switch name := strings.ToLower(match[1]); name { @@ -86,10 +86,10 @@ func explicit(text string) bool { if urlPattern.MatchString(text) { return false } - if _, ok := curl_percentage(text); ok { + if _, ok := curlPercentage(text); ok { return true } - return status_fields(text) || percentPattern.MatchString(text) && (barPattern.MatchString(text) || ratePattern.MatchString(text)) + return statusFields(text) || percentPattern.MatchString(text) && (barPattern.MatchString(text) || ratePattern.MatchString(text)) } // Detect ports Python's screen-update detector. Prefer measured progress, then @@ -105,10 +105,10 @@ func Detect(text string) (Indicator, bool) { } return Indicator{}, false } - if value, ok := curl_percentage(text); ok { + if value, ok := curlPercentage(text); ok { return Indicator{Percentage: value}, true } - if transferPattern.MatchString(text) || status_fields(text) { + if transferPattern.MatchString(text) || statusFields(text) { return activity(2 * time.Second), true } if match := fractionPattern.FindStringSubmatch(text); match != nil && !fractionNoise.MatchString(text) { diff --git a/internal/prompt/detector.go b/internal/prompt/detector.go index 3c532bb2..87b97e0e 100644 --- a/internal/prompt/detector.go +++ b/internal/prompt/detector.go @@ -44,7 +44,7 @@ func New(exactMatches, customPatterns []string) (*Detector, error) { return detector, nil } -func (d *Detector) matches_prompt(text string) bool { +func (d *Detector) matchesPrompt(text string) bool { if text == "" { return false } @@ -80,7 +80,7 @@ func (d *Detector) Observe(next screen.Snapshot) string { if stable { for row := 0; row < next.Rows; row++ { text := strings.TrimSpace(next.Text(row)) - if counts[text] > d.previous[text] && (completionPattern.MatchString(text) || row == next.Y && d.matches_prompt(text)) { + if counts[text] > d.previous[text] && (completionPattern.MatchString(text) || row == next.Y && d.matchesPrompt(text)) { result = text break } diff --git a/internal/punctuation/profile.go b/internal/punctuation/profile.go index 09b15059..212e2a0f 100644 --- a/internal/punctuation/profile.go +++ b/internal/punctuation/profile.go @@ -38,7 +38,7 @@ type Processor struct { func Levels() []string { return []string{"none", "some", "most", "all"} } -func Validate_name(name string) error { +func ValidateName(name string) error { if strings.TrimSpace(name) == "" || strings.ContainsAny(name, "\x00\r\n") { return fmt.Errorf("punctuation profile cannot be empty or contain control characters") } @@ -52,7 +52,7 @@ func Validate_name(name string) error { } func Paths(name, home string, uid int, bundledDirectory string) ([]string, error) { - if err := Validate_name(name); err != nil { + if err := ValidateName(name); err != nil { return nil, err } if strings.ContainsRune(name, filepath.Separator) { @@ -192,7 +192,7 @@ func (p *Processor) Text(text, level string) string { embeddedEnd++ } embedded = index > 0 && embeddedEnd < len(chars) && - is_word_rune(chars[index-1]) && is_word_rune(chars[embeddedEnd]) + isWordRune(chars[index-1]) && isWordRune(chars[embeddedEnd]) if embedded && embeddedEnd == index+1 { before, after := chars[index-1], chars[embeddedEnd] if char == '\'' && unicode.IsLetter(before) && unicode.IsLetter(after) || @@ -222,6 +222,6 @@ func (p *Processor) Text(text, level string) string { return result.String() } -func is_word_rune(char rune) bool { +func isWordRune(char rune) bool { return unicode.IsLetter(char) || unicode.IsNumber(char) || unicode.IsMark(char) } diff --git a/internal/punctuation/profile_test.go b/internal/punctuation/profile_test.go index 1b7a8784..10332a14 100644 --- a/internal/punctuation/profile_test.go +++ b/internal/punctuation/profile_test.go @@ -150,7 +150,7 @@ func TestNumericPercentSpeech(t *testing.T) { {"don't 3.14 1,000 12:30", "don't 3.14 1,000 12:30"}, } { for _, options := range []TextOptions{{}, {Emoticons: true, RepeatedSymbols: true, RepeatedSymbolsMin: 4}} { - if got := strings.Join(strings.Fields(processor.Process_text(trial.text, "some", options)), " "); got != trial.want { + if got := strings.Join(strings.Fields(processor.ProcessText(trial.text, "some", options)), " "); got != trial.want { t.Errorf("%q, options %+v: got %q, want %q", trial.text, options, got, trial.want) } } diff --git a/internal/punctuation/text_processing.go b/internal/punctuation/text_processing.go index 03d7301e..92fb9a86 100644 --- a/internal/punctuation/text_processing.go +++ b/internal/punctuation/text_processing.go @@ -19,10 +19,10 @@ type TextOptions struct { RepeatedSymbolsMin int } -// Process_text substitutes complete tokens before ordinary punctuation. Each +// ProcessText substitutes complete tokens before ordinary punctuation. Each // generated name is emitted once, without processing punctuation inside it. // Whitespace belongs to neither neighboring token, so adjacent emoticons work. -func (p *Processor) Process_text(text, level string, options TextOptions) string { +func (p *Processor) ProcessText(text, level string, options TextOptions) string { if !options.Emoticons && !options.RepeatedSymbols { return p.Text(text, level) } @@ -32,15 +32,15 @@ func (p *Processor) Process_text(text, level string, options TextOptions) string if !unicode.IsSpace(char) { continue } - result.WriteString(p.process_token(text[tokenStart:index], level, options)) + result.WriteString(p.processToken(text[tokenStart:index], level, options)) result.WriteString(p.Text(string(char), level)) tokenStart = index + utf8.RuneLen(char) } - result.WriteString(p.process_token(text[tokenStart:], level, options)) + result.WriteString(p.processToken(text[tokenStart:], level, options)) return result.String() } -func (p *Processor) process_token(token, level string, options TextOptions) string { +func (p *Processor) processToken(token, level string, options TextOptions) string { if options.Emoticons { if name, exists := emoticonNames[token]; exists { return i18n.T(name) diff --git a/internal/punctuation/text_processing_test.go b/internal/punctuation/text_processing_test.go index d9d5c55f..0e2a6599 100644 --- a/internal/punctuation/text_processing_test.go +++ b/internal/punctuation/text_processing_test.go @@ -43,24 +43,24 @@ func TestTextSubstitutionsAndBoundaries(t *testing.T) { {"[#####--]", " 5 number dash dash "}, {"Oo", "WTF?"}, } { - if got := processor.Process_text(trial.text, "some", options); got != trial.want { + if got := processor.ProcessText(trial.text, "some", options); got != trial.want { t.Errorf("%q: %q, want %q", trial.text, got, trial.want) } } for _, text := range []string{"hello :)!", "path/to:)file", "https://example.invalid/:)", "https://example.invalid/:-/", "(o_O)", "###", "##--##", "a####b", "https://example.invalid/####", "10000", "aaaa", "🙂🙂🙂🙂", "", "[]", "[###]", "[##--##]", "[a####b]", "[https://example.invalid/####]"} { for _, level := range Levels() { - if got, want := processor.Process_text(text, level, options), processor.Text(text, level); got != want { + if got, want := processor.ProcessText(text, level, options), processor.Text(text, level); got != want { t.Errorf("%q, %s changed ordinary processing: %q, want %q", text, level, got, want) } } } - if got := processor.Process_text("\t:)\u00a0:) \n", "none", options); got != "\tsmile\u00a0smile \n" { + if got := processor.ProcessText("\t:)\u00a0:) \n", "none", options); got != "\tsmile\u00a0smile \n" { t.Fatal("whitespace changed", got) } - if got := processor.Process_text("##### ####", "all", options); got != "5 number space 4 number" { + if got := processor.ProcessText("##### ####", "all", options); got != "5 number space 4 number" { t.Fatal("generated names were processed again", got) } - if got := processor.Process_text("Oo", "all", options); got != "WTF?" { + if got := processor.ProcessText("Oo", "all", options); got != "WTF?" { t.Fatal("punctuation in emoticon name processed again", got) } } @@ -72,20 +72,20 @@ func TestSubstitutionOptionsAndProfileNames(t *testing.T) { } text := ":) #####" for _, level := range Levels() { - if got := processor.Process_text(text, level, TextOptions{}); got != processor.Text(text, level) { + if got := processor.ProcessText(text, level, TextOptions{}); got != processor.Text(text, level) { t.Fatal("disabled substitutions changed text", level, got) } } options := TextOptions{RepeatedSymbols: true, RepeatedSymbolsMin: 5} - if got := processor.Process_text("####", "some", options); got != processor.Text("####", "some") { + if got := processor.ProcessText("####", "some", options); got != processor.Text("####", "some") { t.Fatal("minimum ignored", got) } - if got := processor.Process_text("#####", "none", options); got != processor.Text("#####", "none") { + if got := processor.ProcessText("#####", "none", options); got != processor.Text("#####", "none") { t.Fatal("summarized unselected symbol", got) } for _, minimum := range []int{0, 1} { options.RepeatedSymbolsMin = minimum - if got := processor.Process_text("#####", "some", options); got != processor.Text("#####", "some") { + if got := processor.ProcessText("#####", "some", options); got != processor.Text("#####", "some") { t.Fatal("invalid options summarized text", got) } } @@ -99,20 +99,20 @@ func TestSubstitutionOptionsAndProfileNames(t *testing.T) { if err != nil { t.Fatal(err) } - if got := custom.Process_text("////", "some", options); got != "4 path/separator" { + if got := custom.ProcessText("////", "some", options); got != "4 path/separator" { t.Fatal("custom name changed or processed twice", got) } - if got := custom.Process_text("[////####]", "some", options); got != " 4 path/separator 4 number " { + if got := custom.ProcessText("[////####]", "some", options); got != " 4 path/separator 4 number " { t.Fatal("mixed summary reprocessed custom name", got) } - if got := custom.Process_text("////####", "some", options); got != "4 path/separator 4 number" { + if got := custom.ProcessText("////####", "some", options); got != "4 path/separator 4 number" { t.Fatal("unbracketed summary reprocessed custom name", got) } french, _, err := Load([]string{"../../config/punctuation/fr.toml"}) if err != nil { t.Fatal(err) } - if got := french.Process_text("#####", "most", options); got != "5 dièse" { + if got := french.ProcessText("#####", "most", options); got != "5 dièse" { t.Fatal("localized profile name lost", got) } if got := processor.Character('#'); got != "hash" { @@ -151,7 +151,7 @@ func TestRepeatedSymbolsRespectOptionsAndLevels(t *testing.T) { } } } - if got := processor.Process_text(text, level, options); got != want { + if got := processor.ProcessText(text, level, options); got != want { t.Errorf("%q, level %s, options %+v: got %q, want %q", text, level, options, got, want) } } @@ -188,7 +188,7 @@ msgstr "{1}: {0}" t.Fatal(err) } options := TextOptions{Emoticons: true, RepeatedSymbols: true, RepeatedSymbolsMin: 4} - if got := processor.Process_text(":) #####", "some", options); got != "translated-smile translated-number: 5" { + if got := processor.ProcessText(":) #####", "some", options); got != "translated-smile translated-number: 5" { t.Fatal("translation or positional order lost", got) } } diff --git a/internal/reader/application_feedback_test.go b/internal/reader/application_feedback_test.go index 607eebc1..107fa555 100644 --- a/internal/reader/application_feedback_test.go +++ b/internal/reader/application_feedback_test.go @@ -18,17 +18,17 @@ func TestApplicationComposerCursorFeedback(t *testing.T) { for _, mode := range []string{"left", "right", "status redraw", "leave review", "passive", "cursor off", "automatic off", "outside input", "edited input", "other adapter"} { t.Run(mode, func(t *testing.T) { r := New() - r.Configure_review(true, true, true, true) + r.ConfigureReview(true, true, true, true) before := fixture("Working", "› hello") before.X, before.Y = 7, 1 frame := applicationoverrides.Frame{Recognized: true, OwnsPresentation: true, InputCursor: true, Input: &screen.Region{Left: 2, Top: 1, Right: 19, Bottom: 1}} - r.Update_application(before, frame) + r.UpdateApplication(before, frame) next := fixture("Working", "› hello") next.X, next.Y = 6, 1 - want := []presentation.Message{presentation.Character_message('o')} + want := []presentation.Message{presentation.CharacterMessage('o')} if mode == "right" { before.X = 5 - r.Update_application(before, frame) + r.UpdateApplication(before, frame) } if mode == "status redraw" { copy(next.Line(0), []rune("Reading file")) @@ -37,7 +37,7 @@ func TestApplicationComposerCursorFeedback(t *testing.T) { r.Command(command.CurrentLine) } if mode != "passive" { - r.Note_input(true, false, false) + r.NoteInput(true, false, false) } switch mode { case "passive": @@ -58,7 +58,7 @@ func TestApplicationComposerCursorFeedback(t *testing.T) { frame.InputCursor = false want = nil } - if got := r.Update_application(next, frame); !reflect.DeepEqual(got, want) { + if got := r.UpdateApplication(next, frame); !reflect.DeepEqual(got, want) { t.Fatal(mode, got, want) } if mode == "leave review" && r.review.Active() { @@ -70,39 +70,39 @@ func TestApplicationComposerCursorFeedback(t *testing.T) { func TestApplicationActivityUsesSoundTimerWithoutScreenRedraws(t *testing.T) { r := New() - r.Configure_progress(true) + r.ConfigureProgress(true) r.Configure(false, false) // Working cues are independent of speech/automatic reading. s := fixture("Working", "› ") frame := applicationoverrides.Frame{Recognized: true, OwnsPresentation: true, Activity: true} - r.Update_application(s, frame) + r.UpdateApplication(s, frame) now := time.Now() for _, elapsed := range []time.Duration{0, 4 * time.Second, 8 * time.Second} { - if value, ok := r.Next_progress(now.Add(elapsed)); !ok || value != 50 { + if value, ok := r.NextProgress(now.Add(elapsed)); !ok || value != 50 { t.Fatal(elapsed, value, ok) } - if _, ok := r.Next_progress(now.Add(elapsed + 3999*time.Millisecond)); ok { + if _, ok := r.NextProgress(now.Add(elapsed + 3999*time.Millisecond)); ok { t.Fatal("activity flooded") } } frame.Activity = false - r.Update_application(s, frame) - if r.Progress_active() { + r.UpdateApplication(s, frame) + if r.ProgressActive() { t.Fatal("idle retained activity") } - if _, ok := r.Next_progress(now.Add(12 * time.Second)); ok { + if _, ok := r.NextProgress(now.Add(12 * time.Second)); ok { t.Fatal("idle beeped") } frame.Activity = true - r.Configure_progress(false) - r.Update_application(s, frame) - if _, ok := r.Next_progress(now.Add(16 * time.Second)); ok { + r.ConfigureProgress(false) + r.UpdateApplication(s, frame) + if _, ok := r.NextProgress(now.Add(16 * time.Second)); ok { t.Fatal("progress toggle ignored") } - r.Configure_progress(true) - r.Update_application(s, frame) + r.ConfigureProgress(true) + r.UpdateApplication(s, frame) s.Active = false - r.Update_application(s, frame) - if _, ok := r.Next_progress(now.Add(20 * time.Second)); ok { + r.UpdateApplication(s, frame) + if _, ok := r.NextProgress(now.Add(20 * time.Second)); ok { t.Fatal("inactive terminal beeped") } } diff --git a/internal/reader/application_override.go b/internal/reader/application_override.go index 8bbd309d..9befd918 100644 --- a/internal/reader/application_override.go +++ b/internal/reader/application_override.go @@ -11,7 +11,7 @@ import ( // Cursor feedback requires unchanged composer text. Comparing masked snapshots // allows simultaneous tool/status redraws outside the input field to stay quiet. -func input_cursor_feedback(previous, next screen.Snapshot) []presentation.Message { +func inputCursorFeedback(previous, next screen.Snapshot) []presentation.Message { if !slices.Equal(previous.Cells, next.Cells) { return nil } @@ -26,7 +26,7 @@ type SessionState struct { regions *terminalRegions } -func clone_regions(source *terminalRegions) *terminalRegions { +func cloneRegions(source *terminalRegions) *terminalRegions { if source == nil { return nil } @@ -45,33 +45,33 @@ func clone_regions(source *terminalRegions) *terminalRegions { return &result } -func (r *Reader) Capture_session() SessionState { - return r.Capture_terminal_session(r.screen.Terminal) +func (r *Reader) CaptureSession() SessionState { + return r.CaptureTerminalSession(r.screen.Terminal) } -func (r *Reader) Capture_terminal_session(terminal int) SessionState { - return SessionState{r.automatic, r.trackingMode, r.attributeConfigured, r.attributeMode, r.attributeResumeMode, clone_regions(r.regions[terminal])} +func (r *Reader) CaptureTerminalSession(terminal int) SessionState { + return SessionState{r.automatic, r.trackingMode, r.attributeConfigured, r.attributeMode, r.attributeResumeMode, cloneRegions(r.regions[terminal])} } -func (r *Reader) Restore_session(state SessionState, terminal int) { +func (r *Reader) RestoreSession(state SessionState, terminal int) { r.automatic = state.automatic - r.Configure_tracking(state.mode) + r.ConfigureTracking(state.mode) r.attributeConfigured, r.attributeMode, r.attributeResumeMode = state.attributeConfigured, state.attributeMode, state.attributeResumeMode if r.regions == nil { r.regions = make(map[int]*terminalRegions) } - r.regions[terminal] = clone_regions(state.regions) + r.regions[terminal] = cloneRegions(state.regions) r.regionRevision++ r.attributeKnown, r.indentKnown = false, false - r.Reset_progress() + r.ResetProgress() } -func (r *Reader) Clear_session_regions(terminal int) { +func (r *Reader) ClearSessionRegions(terminal int) { delete(r.regions, terminal) r.regionRevision++ } -func input_snapshot(snapshot screen.Snapshot, region screen.Region) screen.Snapshot { +func inputSnapshot(snapshot screen.Snapshot, region screen.Region) screen.Snapshot { snapshot.Cells = slices.Clone(snapshot.Cells) for row := range snapshot.Rows { for col := range snapshot.Cols { diff --git a/internal/reader/attributes.go b/internal/reader/attributes.go index 8935ea44..5f8b7921 100644 --- a/internal/reader/attributes.go +++ b/internal/reader/attributes.go @@ -11,7 +11,7 @@ import ( "time" ) -func (r *Reader) Configure_attributes(mode, format string) { +func (r *Reader) ConfigureAttributes(mode, format string) { // Configuration is the saved/quick-menu choice. Reapplying unchanged // settings must not overwrite the shortcut's temporary session state. if mode != r.attributeConfigured { @@ -21,10 +21,10 @@ func (r *Reader) Configure_attributes(mode, format string) { } } r.attributeFormat = format - r.review.Configure_attributes(format) + r.review.ConfigureAttributes(format) } -func (r *Reader) toggle_attributes() string { +func (r *Reader) toggleAttributes() string { if r.attributeMode == "" || r.attributeMode == "none" { r.attributeMode = r.attributeResumeMode if r.attributeMode == "" { @@ -36,7 +36,7 @@ func (r *Reader) toggle_attributes() string { return i18n.T("announcement of attributes disabled") } -func (r *Reader) attribute_feedback(announce bool) *presentation.Message { +func (r *Reader) attributeFeedback(announce bool) *presentation.Message { attribute, valid := r.review.Attribute() if !valid { r.attributeKnown = false @@ -52,7 +52,7 @@ func (r *Reader) attribute_feedback(announce bool) *presentation.Message { if attribute.Default() && r.attributeMode == "beeps" { return nil } - message := presentation.Attribute_message(attribute, r.attributeMode, r.attributeFormat) + message := presentation.AttributeMessage(attribute, r.attributeMode, r.attributeFormat) if attribute.Default() { message.Cue = "" } @@ -62,13 +62,13 @@ func (r *Reader) attribute_feedback(announce bool) *presentation.Message { return &message } -func (r *Reader) automatic_attributes(previous, next screen.Snapshot, switched bool) *presentation.Message { +func (r *Reader) automaticAttributes(previous, next screen.Snapshot, switched bool) *presentation.Message { if switched { r.attributeKnown = false } - announce := !switched && next.Active && r.automatic && r.cursorEcho && r.trackingMode == "cursor" && !r.review.Active() && r.region_state().allows(next.X, next.Y, next.Cols, true, true) + announce := !switched && next.Active && r.automatic && r.cursorEcho && r.trackingMode == "cursor" && !r.review.Active() && r.regionState().allows(next.X, next.Y, next.Cols, true, true) if announce && (previous.X != next.X || previous.Y != next.Y) { announce = !r.applicationInputAt.IsZero() && time.Since(r.applicationInputAt) < 300*time.Millisecond } - return r.attribute_feedback(announce) + return r.attributeFeedback(announce) } diff --git a/internal/reader/attributes_test.go b/internal/reader/attributes_test.go index 570b00f2..b3b6db77 100644 --- a/internal/reader/attributes_test.go +++ b/internal/reader/attributes_test.go @@ -12,7 +12,7 @@ import ( "time" ) -func attribute_fixture() screen.Snapshot { +func attributeFixture() screen.Snapshot { s := fixture("alpha", "bravo", "third") s.Attributes = make([]screen.Attribute, len(s.Cells)) for index := range s.Attributes { @@ -24,8 +24,8 @@ func attribute_fixture() screen.Snapshot { func TestAttributeManualAndReviewOwnership(t *testing.T) { r := New() - r.Configure_attributes("both", "fenrirFGColor fenrirBold fenrirBlink") - s := attribute_fixture() + r.ConfigureAttributes("both", "fenrirFGColor fenrirBold fenrirBlink") + s := attributeFixture() r.Update(s) if got := r.Command(command.AttributeCursor).Text; got != "default " || r.review.Active() { t.Fatal(got, r.review.Active()) @@ -64,32 +64,32 @@ func TestAutomaticAttributeNavigationStyleOnlyDefaultsAndModes(t *testing.T) { for _, mode := range []string{"none", "speech", "beeps", "both"} { t.Run(mode, func(t *testing.T) { r := New() - r.Configure_attributes(mode, "fenrirFGColor fenrirBold fenrirBlink") - s := attribute_fixture() + r.ConfigureAttributes(mode, "fenrirFGColor fenrirBold fenrirBlink") + s := attributeFixture() r.Update(s) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = 1 output := r.Update(s) - feedback := attribute_messages(output) + feedback := attributeMessages(output) if (len(feedback) == 1) != (mode != "none") { t.Fatal(output) } if len(feedback) > 0 && ((feedback[0].Cue == presentation.HasAttributes) != (mode == "beeps" || mode == "both")) { t.Fatal(feedback) } - if got := attribute_messages(r.Update(s)); len(got) != 0 { + if got := attributeMessages(r.Update(s)); len(got) != 0 { t.Fatal("repeat", got) } // Same cell/text/cursor, only its style changes, even after input expires. r.applicationInputAt = time.Time{} s.Attributes = append([]screen.Attribute(nil), s.Attributes...) s.Attributes[s.Cols].Style = screen.Underline - if got := attribute_messages(r.Update(s)); (len(got) == 1) != (mode != "none") { + if got := attributeMessages(r.Update(s)); (len(got) == 1) != (mode != "none") { t.Fatal("style-only", got) } - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = 2 - got := attribute_messages(r.Update(s)) + got := attributeMessages(r.Update(s)) if (len(got) == 1) != (mode == "speech" || mode == "both") { t.Fatal("default", got) } @@ -100,7 +100,7 @@ func TestAutomaticAttributeNavigationStyleOnlyDefaultsAndModes(t *testing.T) { } } -func attribute_messages(messages []presentation.Message) []presentation.Message { +func attributeMessages(messages []presentation.Message) []presentation.Message { var result []presentation.Message for _, message := range messages { if message.Attributes != nil { @@ -114,10 +114,10 @@ func TestAttributeSessionMissingDataAndSuppression(t *testing.T) { for _, trial := range []string{"session", "inactive", "automatic", "cursor echo", "table", "highlight", "detached", "passive cursor", "missing"} { t.Run(trial, func(t *testing.T) { r := New() - r.Configure_attributes("both", "fenrirBold") - s := attribute_fixture() + r.ConfigureAttributes("both", "fenrirBold") + s := attributeFixture() r.Update(s) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = 1 switch trial { case "session": @@ -129,7 +129,7 @@ func TestAttributeSessionMissingDataAndSuppression(t *testing.T) { case "cursor echo": r.Configure(true, false) case "table", "highlight": - r.Configure_tracking(trial) + r.ConfigureTracking(trial) case "detached": r.Command(command.CurrentLine) case "passive cursor": @@ -137,7 +137,7 @@ func TestAttributeSessionMissingDataAndSuppression(t *testing.T) { case "missing": s.Attributes = nil } - if got := attribute_messages(r.Update(s)); len(got) > 0 { + if got := attributeMessages(r.Update(s)); len(got) > 0 { t.Fatal(got) } }) @@ -146,17 +146,17 @@ func TestAttributeSessionMissingDataAndSuppression(t *testing.T) { func TestAttributeEmptyFormatDoesNotClaimDefaultHasAttributes(t *testing.T) { r := New() - r.Configure_attributes("both", "") - s := attribute_fixture() + r.ConfigureAttributes("both", "") + s := attributeFixture() r.Update(s) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = 1 - if got := attribute_messages(r.Update(s)); len(got) != 1 || got[0].Text != "has attribute" { + if got := attributeMessages(r.Update(s)); len(got) != 1 || got[0].Text != "has attribute" { t.Fatal(got) } - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = 2 - if got := attribute_messages(r.Update(s)); len(got) != 0 { + if got := attributeMessages(r.Update(s)); len(got) != 0 { t.Fatal(got) } } @@ -165,8 +165,8 @@ func TestAttributeSessionToggleResumesModeAndKeepsConfiguredDefault(t *testing.T for _, mode := range []string{"none", "speech", "beeps", "both"} { t.Run(mode, func(t *testing.T) { r := New() - r.Configure_attributes(mode, "fenrirBold") - s := attribute_fixture() + r.ConfigureAttributes(mode, "fenrirBold") + s := attributeFixture() r.Update(s) expected := "announcement of attributes disabled" if mode == "none" { @@ -175,7 +175,7 @@ func TestAttributeSessionToggleResumesModeAndKeepsConfiguredDefault(t *testing.T if got := r.Command(command.ToggleAttributes).Text; got != expected { t.Fatal(got) } - r.Configure_attributes(mode, "fenrirBold") // Unrelated quick/menu activity. + r.ConfigureAttributes(mode, "fenrirBold") // Unrelated quick/menu activity. result := r.Command(command.NextLine) message := result.Attributes if (message != nil) != (mode == "none") { @@ -202,7 +202,7 @@ func TestAttributeSessionToggleResumesModeAndKeepsConfiguredDefault(t *testing.T if mode == nextMode { nextMode = "both" } - r.Configure_attributes(nextMode, "fenrirBold") + r.ConfigureAttributes(nextMode, "fenrirBold") r.Command(command.PreviousLine) result = r.Command(command.NextLine) if got := result.Attributes; got == nil || got.Text != "bold" || !got.Attributes.Speech { diff --git a/internal/reader/changes.go b/internal/reader/changes.go index ddd23f10..5b194c9b 100644 --- a/internal/reader/changes.go +++ b/internal/reader/changes.go @@ -29,10 +29,10 @@ import ( func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presentation.Message) { if slices.Equal(previous.Cells, next.Cells) { if cursorEcho && next.Y != previous.Y { - return []presentation.Message{presentation.Line_message(next, next.Y)} + return []presentation.Message{presentation.LineMessage(next, next.Y)} } if cursorEcho && next.X != previous.X { - return []presentation.Message{presentation.Character_message(next.Line(next.Y)[next.X])} + return []presentation.Message{presentation.CharacterMessage(next.Line(next.Y)[next.X])} } return nil } @@ -41,7 +41,7 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta // body while moving the cursor onto an already drawn button row. if cursorEcho && next.Y != previous.Y && strings.TrimSpace(next.Text(next.Y)) != "" && slices.Equal(previous.Line(next.Y), next.Line(next.Y)) { defer func() { - output = append(output, presentation.Line_message(next, next.Y)) + output = append(output, presentation.LineMessage(next, next.Y)) }() } // Match a scroll as one shift so old lines aren't read a second time. @@ -69,7 +69,7 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta } scrollStart, scrollEnd := 0, 0 if len(changedRows) > 1 { - scrollStart, scrollEnd = screen.Scrolled_overlap(previous, next) + scrollStart, scrollEnd = screen.ScrolledOverlap(previous, next) kept := changedRows[:0] for _, row := range changedRows { if row < scrollStart || row >= scrollEnd { @@ -87,7 +87,7 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta slices.Equal(before[:next.X], after[:next.X]) && strings.TrimRight(string(before[previous.X:]), " ") == strings.TrimRight(string(after[next.X:]), " ") { removed := before[next.X:previous.X] if len(removed) == 1 { - return []presentation.Message{presentation.Character_message(removed[0])} + return []presentation.Message{presentation.CharacterMessage(removed[0])} } return []presentation.Message{{Text: string(removed)}} } @@ -103,7 +103,7 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta inserted := after[start:endAfter] if len(inserted) != 0 && strings.TrimSpace(string(inserted)) != "" { if len(inserted) == 1 { - return []presentation.Message{presentation.Character_message(inserted[0])} + return []presentation.Message{presentation.CharacterMessage(inserted[0])} } return []presentation.Message{{Text: string(inserted)}} } diff --git a/internal/reader/command_result_test.go b/internal/reader/command_result_test.go index dc58755e..0b86feee 100644 --- a/internal/reader/command_result_test.go +++ b/internal/reader/command_result_test.go @@ -51,8 +51,8 @@ func TestFallbackMessagesTranslateWithoutChangingScreenContentOrMetadata(t *test func TestCommandResultsRetainFeedbackAcrossCommandsAndUpdates(t *testing.T) { r := New() - r.Configure_attributes("both", "fenrirBold") - r.Configure_indentation("speech") + r.ConfigureAttributes("both", "fenrirBold") + r.ConfigureIndentation("speech") s := fixture("root", " child") s.Attributes = make([]screen.Attribute, len(s.Cells)) for index := range s.Attributes { diff --git a/internal/reader/deletion_test.go b/internal/reader/deletion_test.go index c1f05514..abe07218 100644 --- a/internal/reader/deletion_test.go +++ b/internal/reader/deletion_test.go @@ -19,25 +19,25 @@ func TestDeletionEchoWithAutomaticReadingDisabled(t *testing.T) { beforeX, afterX int want []presentation.Message }{ - {"backspace", "$ abc", "$ ab", 5, 4, []presentation.Message{presentation.Character_message('c')}}, - {"delete", "$ abc", "$ ac", 3, 3, []presentation.Message{presentation.Character_message('b')}}, - {"midline backspace", "$ abc", "$ ac", 4, 3, []presentation.Message{presentation.Character_message('b')}}, - {"unicode", "$ café", "$ caf", 6, 5, []presentation.Message{presentation.Character_message('é')}}, - {"punctuation", "$ .", "$ ", 3, 2, []presentation.Message{presentation.Character_message('.')}}, - {"space", "$ ab ", "$ ab", 5, 4, []presentation.Message{presentation.Character_message(' ')}}, + {"backspace", "$ abc", "$ ab", 5, 4, []presentation.Message{presentation.CharacterMessage('c')}}, + {"delete", "$ abc", "$ ac", 3, 3, []presentation.Message{presentation.CharacterMessage('b')}}, + {"midline backspace", "$ abc", "$ ac", 4, 3, []presentation.Message{presentation.CharacterMessage('b')}}, + {"unicode", "$ café", "$ caf", 6, 5, []presentation.Message{presentation.CharacterMessage('é')}}, + {"punctuation", "$ .", "$ ", 3, 2, []presentation.Message{presentation.CharacterMessage('.')}}, + {"space", "$ ab ", "$ ab", 5, 4, []presentation.Message{presentation.CharacterMessage(' ')}}, {"word", "$ one two", "$ one ", 9, 6, []presentation.Message{{Text: "two"}}}, {"forward word", "$ one two", "$ two", 2, 2, []presentation.Message{{Text: "one "}}}, } { t.Run(trial.name, func(t *testing.T) { r := New() r.Configure(false, false) - r.Configure_echo(false, false, false) + r.ConfigureEcho(false, false, false) before := fixture(trial.before, "background") before.X = trial.beforeX r.Update(before) r.Command(command.CurrentLine) - r.Note_input(true, false, false) - r.Note_deletion() + r.NoteInput(true, false, false) + r.NoteDeletion() // An unchanged capture and background output can precede the edit. r.Update(before) background := fixture(trial.before, "changed background") @@ -69,14 +69,14 @@ func TestDeletionEchoRejectsUnconfirmedChanges(t *testing.T) { before.X, after.X = 5, 4 r.Update(before) if mode != "no key" { - r.Note_input(true, false, false) - r.Note_deletion() + r.NoteInput(true, false, false) + r.NoteDeletion() } switch mode { case "expired": r.progressDeletionAt = time.Now().Add(-time.Second) case "other key": - r.Note_input(true, false, false) + r.NoteInput(true, false, false) case "reader command": r.Command(command.CurrentLine) case "redraw": @@ -97,7 +97,7 @@ func TestDeletionEchoRejectsUnconfirmedChanges(t *testing.T) { case "inactive": after.Active = false case "live region": - r.ensure_regions().live[0] = &screen.Region{Right: before.Cols - 1} + r.ensureRegions().live[0] = &screen.Region{Right: before.Cols - 1} } if got := r.Update(after); len(got) != 0 { t.Fatal("unconfirmed or excluded deletion spoke", got) diff --git a/internal/reader/diagnostics.go b/internal/reader/diagnostics.go index 96af54d0..6716be23 100644 --- a/internal/reader/diagnostics.go +++ b/internal/reader/diagnostics.go @@ -33,7 +33,7 @@ type AttributeChange struct { Before, After screen.Attribute } -func (r *Reader) trace_update(previous, next screen.Snapshot, switched bool, pendingInput int, path string, output []presentation.Message) { +func (r *Reader) traceUpdate(previous, next screen.Snapshot, switched bool, pendingInput int, path string, output []presentation.Message) { comparable := previous.Rows == next.Rows && previous.Cols == next.Cols && next.Rows > 0 && next.Cols > 0 && len(previous.Cells) == next.Rows*next.Cols && len(next.Cells) == len(previous.Cells) previousAttributes := len(previous.Attributes) > 0 && len(previous.Attributes) == len(previous.Cells) diff --git a/internal/reader/diagnostics_test.go b/internal/reader/diagnostics_test.go index 15d22010..eb177e7b 100644 --- a/internal/reader/diagnostics_test.go +++ b/internal/reader/diagnostics_test.go @@ -30,7 +30,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func capture_diagnostics(t *testing.T, level slog.Leveler) *bytes.Buffer { +func captureDiagnostics(t *testing.T, level slog.Leveler) *bytes.Buffer { t.Helper() var log bytes.Buffer previousLogger := slog.Default() @@ -39,7 +39,7 @@ func capture_diagnostics(t *testing.T, level slog.Leveler) *bytes.Buffer { return &log } -func check_update_record(t *testing.T, log *bytes.Buffer, fields map[string]string) map[string]json.RawMessage { +func checkUpdateRecord(t *testing.T, log *bytes.Buffer, fields map[string]string) map[string]json.RawMessage { t.Helper() lines := bytes.Split(bytes.TrimSpace(log.Bytes()), []byte("\n")) var record map[string]json.RawMessage @@ -61,7 +61,7 @@ func check_update_record(t *testing.T, log *bytes.Buffer, fields map[string]stri func TestReaderDiagnosticsCursorAndStatusWithoutText(t *testing.T) { var level slog.LevelVar level.Set(slog.LevelDebug) - log := capture_diagnostics(t, &level) + log := captureDiagnostics(t, &level) r := New() r.Update(fixture("PRIVATE first", "PRIVATE second", "1/2 PRIVATE")) r.Command(command.CurrentLine) @@ -69,12 +69,12 @@ func TestReaderDiagnosticsCursorAndStatusWithoutText(t *testing.T) { log.Reset() next := fixture("PRIVATE first", "PRIVATE second", "2/2 PRIVATE") next.Y = 1 - r.Note_input(true, false, false) - want := []presentation.Message{presentation.Character_message('2'), {Text: "PRIVATE second"}} + r.NoteInput(true, false, false) + want := []presentation.Message{presentation.CharacterMessage('2'), {Text: "PRIVATE second"}} if got := r.Update(next); !reflect.DeepEqual(got, want) { t.Fatal("diagnostics changed cursor feedback", got) } - check_update_record(t, log, map[string]string{ + checkUpdateRecord(t, log, map[string]string{ "cursor": "[0,1]", "previous_cursor": "[0,0]", "mode": `"cursor"`, "text_rows": "[2]", "text_cells": "1", "messages": "2", "message_lengths": "[1,14]", "path": `"screen-changes"`, "review": "false", "cursor_echo": "true", @@ -99,7 +99,7 @@ func TestReaderDiagnosticsStationaryCursorAndSuppression(t *testing.T) { {"automatic off", "cursor", "automatic-disabled", false, false, "0"}, } { t.Run(testCase.name, func(t *testing.T) { - log := capture_diagnostics(t, slog.LevelDebug) + log := captureDiagnostics(t, slog.LevelDebug) before := fixture("PRIVATE first", "PRIVATE second", "third", "status") before.Attributes = make([]screen.Attribute, len(before.Cells)) next := before @@ -111,14 +111,14 @@ func TestReaderDiagnosticsStationaryCursorAndSuppression(t *testing.T) { } r := New() r.Configure(testCase.automatic, true) - r.Configure_tracking(testCase.mode) + r.ConfigureTracking(testCase.mode) r.Update(before) if testCase.review { r.Command(command.CurrentLine) } log.Reset() r.Update(next) - check_update_record(t, log, map[string]string{ + checkUpdateRecord(t, log, map[string]string{ "cursor": "[0,0]", "previous_cursor": "[0,0]", "text_rows": "[]", "attribute_rows": "[0,1]", "attribute_cells": "40", "attributes": "true", "path": `"` + testCase.path + `"`, "messages": testCase.messages, @@ -129,14 +129,14 @@ func TestReaderDiagnosticsStationaryCursorAndSuppression(t *testing.T) { } func TestReaderDiagnosticsBoundAttributeDetailsAndHandleSessionChanges(t *testing.T) { - log := capture_diagnostics(t, slog.LevelDebug) + log := captureDiagnostics(t, slog.LevelDebug) r := New() r.Update(screen.Snapshot{}) // Inactive captures may have no geometry or cells. - check_update_record(t, log, map[string]string{"path": `"inactive"`, "comparable": "false"}) + checkUpdateRecord(t, log, map[string]string{"path": `"inactive"`, "comparable": "false"}) before := fixture("PRIVATE", "PRIVATE", "PRIVATE", "PRIVATE") before.Attributes = make([]screen.Attribute, len(before.Cells)) r.Update(before) - check_update_record(t, log, map[string]string{"path": `"session-change"`, "comparable": "false"}) + checkUpdateRecord(t, log, map[string]string{"path": `"session-change"`, "comparable": "false"}) next := before next.Attributes = make([]screen.Attribute, len(before.Cells)) for index := range next.Attributes { @@ -144,7 +144,7 @@ func TestReaderDiagnosticsBoundAttributeDetailsAndHandleSessionChanges(t *testin } log.Reset() r.Update(next) - record := check_update_record(t, log, map[string]string{ + record := checkUpdateRecord(t, log, map[string]string{ "attribute_changes_truncated": "true", "attribute_cells": "80", "attribute_rows": "[0,1,2,3]", }) var changes []AttributeChange diff --git a/internal/reader/dialog_test.go b/internal/reader/dialog_test.go index edaa2ff5..684d63b8 100644 --- a/internal/reader/dialog_test.go +++ b/internal/reader/dialog_test.go @@ -13,7 +13,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func dialog_snapshot(lines map[int]string, x, y int) screen.Snapshot { +func dialogSnapshot(lines map[int]string, x, y int) screen.Snapshot { snapshot := screen.Snapshot{Terminal: 1, Active: true, Rows: 25, Cols: 80, X: x, Y: y} snapshot.Cells = make([]rune, snapshot.Rows*snapshot.Cols) for index := range snapshot.Cells { @@ -35,10 +35,10 @@ func TestDialogBodyWithUnchangedCursorRow(t *testing.T) { }{ { name: "saved preferences body", - before: dialog_snapshot(map[int]string{ + before: dialogSnapshot(map[int]string{ 8: "I38", 14: "< OK >", }, 0, 19), - after: dialog_snapshot(map[int]string{ + after: dialogSnapshot(map[int]string{ 8: "I38", 9: "Loaded saved preferences from", 10: "/tmp/I38_preferences.conf", 12: "Missing or invalid values will be prompted.", 14: "< OK >", }, 2, 14), @@ -49,11 +49,11 @@ func TestDialogBodyWithUnchangedCursorRow(t *testing.T) { }, { name: "last warning line", - before: dialog_snapshot(map[int]string{ + before: dialogSnapshot(map[int]string{ 0: "I38", 1: "I38Lock is not available with the current screen reader setup.", 2: "Requires i38lock and either Cthulhu or Orca 50 or newer.", 22: "< OK >", }, 2, 3), - after: dialog_snapshot(map[int]string{ + after: dialogSnapshot(map[int]string{ 0: "I38", 1: "I38Lock is not available with the current screen reader setup.", 2: "Requires i38lock and either Cthulhu or Orca 50 or newer.", 3: "Please choose another screen lock method.", 22: "< OK >", @@ -122,7 +122,7 @@ func TestDialogRedrawRespectsReadingModes(t *testing.T) { case "cursor off": r.Configure(true, false) case "table", "highlight": - r.Configure_tracking(mode) + r.ConfigureTracking(mode) case "review": r.Command(command.CurrentLine) case "automatic off": diff --git a/internal/reader/echo.go b/internal/reader/echo.go index b8e6b452..745318fe 100644 --- a/internal/reader/echo.go +++ b/internal/reader/echo.go @@ -26,15 +26,15 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func (r *Reader) Configure_echo(characterEcho, wordEcho, echoOnCapsLock bool) { +func (r *Reader) ConfigureEcho(characterEcho, wordEcho, echoOnCapsLock bool) { r.characterEcho, r.wordEcho, r.echoOnCapsLock = characterEcho, wordEcho, echoOnCapsLock } const echoWindow = 500 * time.Millisecond -// Note_input associates direct application input with cursor movement and echo. +// NoteInput associates direct application input with cursor movement and echo. // It never speaks raw keys: password fields without screen echo stay silent. -func (r *Reader) Note_input(forwarded, typing, wordBoundary bool) { +func (r *Reader) NoteInput(forwarded, typing, wordBoundary bool) { r.progressDeletionAt = time.Time{} r.applicationInputAt = time.Time{} if forwarded { @@ -54,9 +54,9 @@ func (r *Reader) Note_input(forwarded, typing, wordBoundary bool) { r.inputAt = time.Now() } -// typing_echo handles a cursor-anchored edit following text input. Unrelated +// typingEcho handles a cursor-anchored edit following text input. Unrelated // output still goes through changes, even with all typing echo disabled. -func (r *Reader) typing_echo(previous, next screen.Snapshot) ([]presentation.Message, bool) { +func (r *Reader) typingEcho(previous, next screen.Snapshot) ([]presentation.Message, bool) { if r.inputCount == 0 { return nil, false } @@ -104,16 +104,16 @@ func (r *Reader) typing_echo(previous, next screen.Snapshot) ([]presentation.Mes advance := end - start if next.Y != previous.Y || end > rowEnd || !slices.Equal(before[start:rowEnd-advance], next.Cells[end:rowEnd]) || !slices.Equal(before[rowEnd:], next.Cells[rowEnd:]) || - !all_spaces(before[rowEnd-advance:rowEnd]) { + !allSpaces(before[rowEnd-advance:rowEnd]) { return nil, false } } var output []presentation.Message for index := start; index < end; index++ { - if !r.region_state().allows(index%next.Cols, index/next.Cols, next.Cols, false, true) { + if !r.regionState().allows(index%next.Cols, index/next.Cols, next.Cols, false, true) { continue } - r.completed_word(index, next) + r.completedWord(index, next) char := next.Cells[index] if r.wordEcho && boundary && unicode.IsSpace(char) { wordStart := index @@ -124,13 +124,13 @@ func (r *Reader) typing_echo(previous, next screen.Snapshot) ([]presentation.Mes output = append(output, presentation.Message{Text: string(next.Cells[wordStart:index])}) } } else if !unicode.IsSpace(char) && (r.characterEcho || r.echoOnCapsLock && next.CapsLock) { - output = append(output, presentation.Character_message(char)) + output = append(output, presentation.CharacterMessage(char)) } } return output, true } -func all_spaces(cells []rune) bool { +func allSpaces(cells []rune) bool { for _, char := range cells { if !unicode.IsSpace(char) { return false @@ -142,15 +142,15 @@ func all_spaces(cells []rune) bool { // Deletion echo uses only text verified against the previous screen. Like // typing echo, it remains available with autoread/cursor/character echo off, // but never exposes text excluded by a live region. -func (r *Reader) deletion_echo(deleted []rune, next screen.Snapshot) []presentation.Message { +func (r *Reader) deletionEcho(deleted []rune, next screen.Snapshot) []presentation.Message { var allowed []rune for index, char := range deleted { - if r.region_state().allows(next.X+index, next.Y, next.Cols, false, true) { + if r.regionState().allows(next.X+index, next.Y, next.Cols, false, true) { allowed = append(allowed, char) } } if len(allowed) == 1 { - return []presentation.Message{presentation.Character_message(allowed[0])} + return []presentation.Message{presentation.CharacterMessage(allowed[0])} } if len(allowed) > 1 { return []presentation.Message{{Text: string(allowed)}} diff --git a/internal/reader/echo_test.go b/internal/reader/echo_test.go index ee9748bb..5c752c48 100644 --- a/internal/reader/echo_test.go +++ b/internal/reader/echo_test.go @@ -32,21 +32,21 @@ func TestTypingEchoBooleanCombinations(t *testing.T) { for _, capsOnly := range []bool{false, true} { for _, capsLock := range []bool{false, true} { r := New() - r.Configure_echo(character, word, capsOnly) + r.ConfigureEcho(character, word, capsOnly) before := fixture("$ ") before.X, before.CapsLock = 2, capsLock r.Update(before) - r.Note_input(true, true, false) + r.NoteInput(true, true, false) after := fixture("$ a") after.X, after.CapsLock = 3, capsLock var want []presentation.Message if character || capsOnly && capsLock { - want = []presentation.Message{presentation.Character_message('a')} + want = []presentation.Message{presentation.CharacterMessage('a')} } if got := r.Update(after); !reflect.DeepEqual(got, want) { t.Fatal("character policy", character, word, capsOnly, capsLock, got, want) } - r.Note_input(true, true, true) + r.NoteInput(true, true, true) after.X = 4 // Space advances over an already-blank cell. want = nil if word { @@ -63,18 +63,18 @@ func TestTypingEchoBooleanCombinations(t *testing.T) { func TestEchoSeparatesTypingNavigationDeletionAndIncomingOutput(t *testing.T) { r := New() - r.Configure_echo(false, false, false) + r.ConfigureEcho(false, false, false) before := fixture("$ a", "output") before.X = 3 r.Update(before) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) after := fixture("$ ", "output") after.X = 2 - if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('a')}) { + if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('a')}) { t.Fatal("typing settings disabled deletion feedback", got) } after.X = 1 - if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message(' ')}) { + if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage(' ')}) { t.Fatal("typing settings disabled cursor navigation", got) } r.Configure(true, false) @@ -84,17 +84,17 @@ func TestEchoSeparatesTypingNavigationDeletionAndIncomingOutput(t *testing.T) { } changed := fixture("$ ", "output!") changed.Y, changed.X = 1, 7 - if got := r.Update(changed); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('!')}) { + if got := r.Update(changed); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('!')}) { t.Fatal("incoming output was suppressed as typing", got) } - r.Note_input(true, true, false) + r.NoteInput(true, true, false) if got := r.Update(changed); len(got) != 0 { t.Fatal("un-echoed input spoke raw keys", got) } r.inputAt = time.Now().Add(-time.Second) changed = fixture("$ ", "output!x") changed.Y, changed.X = 1, 8 - if got := r.Update(changed); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('x')}) { + if got := r.Update(changed); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('x')}) { t.Fatal("stale input suppressed later output", got) } } @@ -102,40 +102,40 @@ func TestEchoSeparatesTypingNavigationDeletionAndIncomingOutput(t *testing.T) { func TestWordEchoBatchUnicodeMidlineAndSpaceNavigation(t *testing.T) { for _, character := range []bool{false, true} { r := New() - r.Configure_echo(character, true, false) + r.ConfigureEcho(character, true, false) before := fixture("$ ") before.X = 2 r.Update(before) for _, char := range "café two " { - r.Note_input(true, true, char == ' ') + r.NoteInput(true, true, char == ' ') } after := fixture("$ café two ") after.X = 11 want := []presentation.Message{{Text: "café"}, {Text: "two"}} if character { - want = []presentation.Message{presentation.Character_message('c'), presentation.Character_message('a'), presentation.Character_message('f'), presentation.Character_message('é'), {Text: "café"}, presentation.Character_message('t'), presentation.Character_message('w'), presentation.Character_message('o'), {Text: "two"}} + want = []presentation.Message{presentation.CharacterMessage('c'), presentation.CharacterMessage('a'), presentation.CharacterMessage('f'), presentation.CharacterMessage('é'), {Text: "café"}, presentation.CharacterMessage('t'), presentation.CharacterMessage('w'), presentation.CharacterMessage('o'), {Text: "two"}} } if got := r.Update(after); !reflect.DeepEqual(got, want) { t.Fatal("batched typing", character, got, want) } - r.Note_input(true, false, false) + r.NoteInput(true, false, false) after.X = 12 - if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message(' ')}) { + if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage(' ')}) { t.Fatal("navigation triggered word echo", got) } } r := New() - r.Configure_echo(false, true, false) + r.ConfigureEcho(false, true, false) before := fixture("$ one two") before.X = 4 r.Update(before) - r.Note_input(true, true, false) + r.NoteInput(true, true, false) after := fixture("$ onXe two") after.X = 5 if got := r.Update(after); len(got) != 0 { t.Fatal("midline insertion escaped disabled character echo", got) } - r.Note_input(true, true, true) + r.NoteInput(true, true, true) after = fixture("$ onX e two") after.X = 6 if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{{Text: "onX"}}) { @@ -150,10 +150,10 @@ func TestTypingEchoIndependentOfAutomaticReadingAndReview(t *testing.T) { before.X = 2 r.Update(before) r.Command(command.CurrentLine) - r.Note_input(true, true, false) + r.NoteInput(true, true, false) after := fixture("$ a") after.X = 3 - if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('a')}) { + if got := r.Update(after); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('a')}) { t.Fatal("automatic reading or review disabled typing echo", got) } } diff --git a/internal/reader/indentation.go b/internal/reader/indentation.go index 6c7e2197..4d2a0843 100644 --- a/internal/reader/indentation.go +++ b/internal/reader/indentation.go @@ -13,9 +13,9 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func (r *Reader) Configure_indentation(mode string) { r.indentationMode = mode } +func (r *Reader) ConfigureIndentation(mode string) { r.indentationMode = mode } -func (r *Reader) indentation_feedback(announce bool) *presentation.Message { +func (r *Reader) indentationFeedback(announce bool) *presentation.Message { level, valid := r.review.Indentation() if !valid { return nil // Blank rows preserve the last meaningful level. @@ -25,24 +25,24 @@ func (r *Reader) indentation_feedback(announce bool) *presentation.Message { if !announce || !changed || r.indentationMode == "" || r.indentationMode == "none" { return nil } - message := presentation.Indentation_message(level, r.indentationMode) + message := presentation.IndentationMessage(level, r.indentationMode) return &message } -func (r *Reader) automatic_indentation(previous, next screen.Snapshot, switched bool) *presentation.Message { +func (r *Reader) automaticIndentation(previous, next screen.Snapshot, switched bool) *presentation.Message { if switched { r.indentKnown = false } // Passive program output must not create indentation chatter. Match Python's // cursor-input window and suppress automatic cursor feedback during review. announce := !switched && next.Active && r.automatic && r.cursorEcho && r.trackingMode == "cursor" && !r.review.Active() && - r.region_state().allows(next.X, next.Y, next.Cols, true, true) && + r.regionState().allows(next.X, next.Y, next.Cols, true, true) && !r.applicationInputAt.IsZero() && time.Since(r.applicationInputAt) < 300*time.Millisecond if announce { // A hidden leading-whitespace edit must not produce indentation cues // at an otherwise visible cursor farther along the same row. for col, char := range next.Line(next.Y) { - if !r.region_state().allows(col, next.Y, next.Cols, true, true) { + if !r.regionState().allows(col, next.Y, next.Cols, true, true) { announce = false break } @@ -60,5 +60,5 @@ func (r *Reader) automatic_indentation(previous, next screen.Snapshot, switched // A cursor moving with new program output is not line navigation. announce = slices.Equal(previous.Line(next.Y), next.Line(next.Y)) } - return r.indentation_feedback(announce) + return r.indentationFeedback(announce) } diff --git a/internal/reader/indentation_test.go b/internal/reader/indentation_test.go index e9415601..d50d0b58 100644 --- a/internal/reader/indentation_test.go +++ b/internal/reader/indentation_test.go @@ -13,11 +13,11 @@ func TestIndentationNavigationModesBlankRowsAndRepeatedLevels(t *testing.T) { for _, mode := range []string{"none", "speech", "beeps", "both"} { t.Run(mode, func(t *testing.T) { r := New() - r.Configure_indentation(mode) + r.ConfigureIndentation(mode) s := fixture("root", " first", " second", "", " third", "root again") r.Update(s) for _, row := range []int{1, 2, 3, 4, 5} { - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = row output := r.Update(s) wantIndent := mode != "none" && (row == 1 || row == 5) @@ -29,7 +29,7 @@ func TestIndentationNavigationModesBlankRowsAndRepeatedLevels(t *testing.T) { if row == 5 { level = 0 } - if output[0].Text != presentation.Indentation_message(level, mode).Text || + if output[0].Text != presentation.IndentationMessage(level, mode).Text || (output[0].Indentation != nil) != (mode == "beeps" || mode == "both") { t.Fatal(output[0]) } @@ -47,7 +47,7 @@ func TestIndentationNavigationModesBlankRowsAndRepeatedLevels(t *testing.T) { func TestIndentationEditsIncludeDedentToZeroWithoutOrdinaryTypingChatter(t *testing.T) { r := New() - r.Configure_indentation("speech") + r.ConfigureIndentation("speech") s := fixture("value") r.Update(s) for _, trial := range []struct { @@ -56,13 +56,13 @@ func TestIndentationEditsIncludeDedentToZeroWithoutOrdinaryTypingChatter(t *test }{{" value", 4}, {" value", 2}, {"value", 0}} { s = fixture(trial.text) s.X = trial.level - r.Note_input(true, false, false) + r.NoteInput(true, false, false) output := r.Update(s) - if len(output) == 0 || output[0].Text != presentation.Indentation_message(trial.level, "speech").Text { + if len(output) == 0 || output[0].Text != presentation.IndentationMessage(trial.level, "speech").Text { t.Fatal(output) } } - r.Note_input(true, true, false) + r.NoteInput(true, true, false) s = fixture("Zvalue") s.X = 1 for _, message := range r.Update(s) { @@ -76,20 +76,20 @@ func TestIndentationDoesNotFollowPassiveOutputDisabledReadingOrOtherTracking(t * for _, trial := range []string{"passive", "automatic off", "cursor off", "table", "highlight", "session", "output", "detached"} { t.Run(trial, func(t *testing.T) { r := New() - r.Configure_indentation("both") + r.ConfigureIndentation("both") s := fixture("root", " child") r.Update(s) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) s.Y = 1 switch trial { case "passive": - r.Note_input(false, false, false) + r.NoteInput(false, false, false) case "automatic off": r.Configure(false, true) case "cursor off": r.Configure(true, false) case "table", "highlight": - r.Configure_tracking(trial) + r.ConfigureTracking(trial) case "session": s.Generation++ case "output": @@ -97,7 +97,7 @@ func TestIndentationDoesNotFollowPassiveOutputDisabledReadingOrOtherTracking(t * s.Y = 1 case "detached": r.Command(command.CurrentLine) - r.Note_input(false, false, false) + r.NoteInput(false, false, false) } for _, message := range r.Update(s) { if message.Indentation != nil { @@ -110,7 +110,7 @@ func TestIndentationDoesNotFollowPassiveOutputDisabledReadingOrOtherTracking(t * func TestReviewIndentationWithAutomaticReadingOffAndApplicationCursorElsewhere(t *testing.T) { r := New() - r.Configure_indentation("speech") + r.ConfigureIndentation("speech") r.Configure(false, false) s := fixture("root", " child", "", " peer", "root again") r.Update(s) diff --git a/internal/reader/progress.go b/internal/reader/progress.go index 048527a4..25643191 100644 --- a/internal/reader/progress.go +++ b/internal/reader/progress.go @@ -26,13 +26,13 @@ import ( ) // Progress is independent of automatic reading and speech mute. -func (r *Reader) Configure_progress(enabled bool) { +func (r *Reader) ConfigureProgress(enabled bool) { if r.progressEnabled != enabled { r.progress.Reset() } r.progressEnabled = enabled } -func (r *Reader) Next_progress(now time.Time) (float64, bool) { +func (r *Reader) NextProgress(now time.Time) (float64, bool) { if r.applicationActivity && r.progressEnabled { // Use the existing spinner's fixed pitch, once every four seconds. This reports // activity, not a guessed completion percentage, and needs no repaint. @@ -45,19 +45,19 @@ func (r *Reader) Next_progress(now time.Time) (float64, bool) { } return r.progress.Next(now) } -func (r *Reader) Reset_progress() { r.progress.Reset(); r.applicationActivity = false } +func (r *Reader) ResetProgress() { r.progress.Reset(); r.applicationActivity = false } -func (r *Reader) Progress_active() bool { +func (r *Reader) ProgressActive() bool { return r.applicationActivity && r.progressEnabled || r.progress.Active() } -func (r *Reader) Note_deletion() { r.progressDeletionAt = time.Now() } +func (r *Reader) NoteDeletion() { r.progressDeletionAt = time.Now() } // A recent deletion key alone is insufficient: match the actual cursor-row // deletion so background progress, including another row in the same snapshot, // remains available to the detector. The same evidence permits deletion echo // while automatic reading is disabled, without speaking other screen changes. -func (r *Reader) match_deletion(previous, next screen.Snapshot) []rune { +func (r *Reader) matchDeletion(previous, next screen.Snapshot) []rune { if r.progressDeletionAt.IsZero() || time.Since(r.progressDeletionAt) > echoWindow || previous.Y != next.Y || next.X > previous.X { return nil } @@ -75,7 +75,7 @@ func (r *Reader) match_deletion(previous, next screen.Snapshot) []rune { count = beforeEnd - afterEnd } if count <= 0 || next.X+count > next.Cols || !slices.Equal(before[:next.X], after[:next.X]) || - !slices.Equal(before[next.X+count:], after[next.X:next.Cols-count]) || !all_spaces(after[next.Cols-count:]) { + !slices.Equal(before[next.X+count:], after[next.X:next.Cols-count]) || !allSpaces(after[next.Cols-count:]) { return nil } r.progressDeletionAt = time.Time{} diff --git a/internal/reader/progress_test.go b/internal/reader/progress_test.go index c9dc010e..9ce2f012 100644 --- a/internal/reader/progress_test.go +++ b/internal/reader/progress_test.go @@ -27,33 +27,33 @@ import ( func TestProgressIndependentOfAutomaticReadingAndTypingEcho(t *testing.T) { r := New() - r.Configure_progress(true) + r.ConfigureProgress(true) r.Configure(false, false) before, after := fixture("Download 20%", ""), fixture("Download 30%", "") r.Update(before) - if _, ok := r.Next_progress(time.Now()); ok { + if _, ok := r.NextProgress(time.Now()); ok { t.Fatal("initial screen") } if output := r.Update(after); len(output) != 0 { t.Fatal("enabled autoread") } - if value, ok := r.Next_progress(time.Now()); !ok || value != 30 { + if value, ok := r.NextProgress(time.Now()); !ok || value != 30 { t.Fatal(value, ok) } - r.Configure_progress(false) + r.ConfigureProgress(false) r.Update(fixture("Download 40%", "")) - if _, ok := r.Next_progress(time.Now().Add(time.Second)); ok { + if _, ok := r.NextProgress(time.Now().Add(time.Second)); ok { t.Fatal("disabled progress") } - r.Configure_progress(true) + r.ConfigureProgress(true) // Typing a percentage must stay silent even when key echo is disabled. - r.Configure_echo(false, false, false) + r.ConfigureEcho(false, false, false) before, after = fixture("50", ""), fixture("50%", "") before.X, after.X = 2, 3 r.Update(before) - r.Note_input(true, true, false) + r.NoteInput(true, true, false) r.Update(after) - if _, ok := r.Next_progress(time.Now().Add(2 * time.Second)); ok || r.Progress_active() { + if _, ok := r.NextProgress(time.Now().Add(2 * time.Second)); ok || r.ProgressActive() { t.Fatal("typing recognized as progress") } } @@ -62,8 +62,8 @@ func TestProgressIgnoresDeletionButKeepsOtherRows(t *testing.T) { for _, mode := range []string{"backspace", "delete", "word deletion", "background together", "background before edit", "passive change", "expired"} { t.Run(mode, func(t *testing.T) { r := New() - r.Configure_progress(true) - r.Configure_echo(false, false, false) + r.ConfigureProgress(true) + r.ConfigureEcho(false, false, false) before, after := fixture("type 2% abc", "Download 20%"), fixture("type 2% ab", "Download 20%") before.X, after.X = 11, 10 if mode == "delete" { @@ -79,8 +79,8 @@ func TestProgressIgnoresDeletionButKeepsOtherRows(t *testing.T) { } r.Update(before) if mode != "passive change" { - r.Note_input(true, false, false) - r.Note_deletion() + r.NoteInput(true, false, false) + r.NoteDeletion() if mode == "expired" { r.progressDeletionAt = time.Now().Add(-time.Second) } @@ -89,14 +89,14 @@ func TestProgressIgnoresDeletionButKeepsOtherRows(t *testing.T) { update := fixture("type 2% abc", "Download 30%") update.X = 11 r.Update(update) - if value, ok := r.Next_progress(time.Now()); !ok || value != 30 { + if value, ok := r.NextProgress(time.Now()); !ok || value != 30 { t.Fatal("lost background output", value, ok) } after = fixture("type 2% ab", "Download 30%") after.X = 10 } output := r.Update(after) - value, ok := r.Next_progress(time.Now().Add(time.Second)) + value, ok := r.NextProgress(time.Now().Add(time.Second)) switch mode { case "background together": if !ok || value != 30 { @@ -111,7 +111,7 @@ func TestProgressIgnoresDeletionButKeepsOtherRows(t *testing.T) { t.Fatal("deletion produced progress", value) } } - if mode == "backspace" && !reflect.DeepEqual(output, []presentation.Message{presentation.Character_message('c')}) { + if mode == "backspace" && !reflect.DeepEqual(output, []presentation.Message{presentation.CharacterMessage('c')}) { t.Fatal("lost deletion speech", output) } }) diff --git a/internal/reader/reader.go b/internal/reader/reader.go index 60c7236d..ecedbaa6 100644 --- a/internal/reader/reader.go +++ b/internal/reader/reader.go @@ -64,7 +64,7 @@ type Reader struct { func New() *Reader { r := &Reader{automatic: true, cursorEcho: true, characterEcho: true, trackingMode: "cursor"} - r.Configure_attributes("none", presentation.Default_attribute_format) + r.ConfigureAttributes("none", presentation.DefaultAttributeFormat) return r } @@ -72,27 +72,27 @@ func (r *Reader) Configure(automatic, cursorEcho bool) { r.automatic, r.cursorEcho = automatic, cursorEcho } -func (r *Reader) Configure_tracking(mode string) { +func (r *Reader) ConfigureTracking(mode string) { r.trackingMode = mode - r.review.Set_table_mode(mode == "table") + r.review.SetTableMode(mode == "table") } -func (r *Reader) Tracking_mode() string { return r.trackingMode } -func (r *Reader) Automatic_reading() bool { return r.automatic } +func (r *Reader) TrackingMode() string { return r.trackingMode } +func (r *Reader) AutomaticReading() bool { return r.automatic } -func (r *Reader) Configure_review(lineBreak, endOfScreen, leaveOnCursorChange, leaveOnScreenChange bool) { +func (r *Reader) ConfigureReview(lineBreak, endOfScreen, leaveOnCursorChange, leaveOnScreenChange bool) { r.review.Configure(lineBreak, endOfScreen, leaveOnScreenChange) r.keepReviewOnCursorChange = !leaveOnCursorChange } -func (r *Reader) Set_mark() presentation.Message { return r.review.Set_mark() } -func (r *Reader) Clear_marks() { r.review.Clear_marks() } -func (r *Reader) Marked_text(copying bool) (string, bool) { return r.review.Marked_text(copying) } +func (r *Reader) SetMark() presentation.Message { return r.review.SetMark() } +func (r *Reader) ClearMarks() { r.review.ClearMarks() } +func (r *Reader) MarkedText(copying bool) (string, bool) { return r.review.MarkedText(copying) } func (r *Reader) Update(next screen.Snapshot) []presentation.Message { - return r.Update_application(next, applicationoverrides.Frame{}) + return r.UpdateApplication(next, applicationoverrides.Frame{}) } -func (r *Reader) Update_application(next screen.Snapshot, frame applicationoverrides.Frame) (output []presentation.Message) { +func (r *Reader) UpdateApplication(next screen.Snapshot, frame applicationoverrides.Frame) (output []presentation.Message) { r.completedWords = nil previous := r.screen r.applicationActivity = next.Active && frame.Recognized && frame.OwnsPresentation && frame.Activity && r.progressEnabled @@ -101,14 +101,14 @@ func (r *Reader) Update_application(next screen.Snapshot, frame applicationoverr if !r.keepReviewOnCursorChange && r.review.Active() && !r.applicationInputAt.IsZero() && time.Since(r.applicationInputAt) < 300*time.Millisecond && previous.Active && next.Active && previous.Terminal == next.Terminal && previous.Generation == next.Generation && previous.Rows == next.Rows && previous.Cols == next.Cols && (previous.X != next.X || previous.Y != next.Y || frame.Recognized && frame.FocusChanged) { - r.review.Resume_tracking() + r.review.ResumeTracking() } switched := r.review.Update(next) r.screen = next path := "screen-changes" if diagnostic.Enabled() { pendingInput := r.inputCount - defer func() { r.trace_update(previous, next, switched, pendingInput, path, output) }() + defer func() { r.traceUpdate(previous, next, switched, pendingInput, path, output) }() } if frame.Recognized && frame.OwnsPresentation { path = "application" @@ -126,10 +126,10 @@ func (r *Reader) Update_application(next screen.Snapshot, frame applicationoverr if frame.OwnsPresentation { return } - if message := r.automatic_attributes(previous, next, switched); message != nil { + if message := r.automaticAttributes(previous, next, switched); message != nil { output = append([]presentation.Message{*message}, output...) } - if message := r.automatic_indentation(previous, next, switched); message != nil { + if message := r.automaticIndentation(previous, next, switched); message != nil { output = append([]presentation.Message{*message}, output...) } }() @@ -156,34 +156,34 @@ func (r *Reader) Update_application(next screen.Snapshot, frame applicationoverr return nil } output := []presentation.Message{{Text: i18n.Format("screen {0}", strconv.Itoa(next.Terminal)), Cue: presentation.TTYChanged}} - if r.region_state().allows(next.X, next.Y, next.Cols, true, true) { - output = append(output, presentation.Line_message(r.Automatic_snapshot(), next.Y)) + if r.regionState().allows(next.X, next.Y, next.Cols, true, true) { + output = append(output, presentation.LineMessage(r.AutomaticSnapshot(), next.Y)) } return output } - regions := r.region_state() - typingPrevious := regions.filtered_snapshot(previous, false, true) - typingNext := regions.filtered_snapshot(next, false, true) + regions := r.regionState() + typingPrevious := regions.filteredSnapshot(previous, false, true) + typingNext := regions.filteredSnapshot(next, false, true) if frame.OwnsPresentation { if frame.Input == nil { r.inputCount = 0 } else { - typingPrevious = input_snapshot(typingPrevious, *frame.Input) - typingNext = input_snapshot(typingNext, *frame.Input) + typingPrevious = inputSnapshot(typingPrevious, *frame.Input) + typingNext = inputSnapshot(typingNext, *frame.Input) } } - if echo, matched := r.typing_echo(typingPrevious, typingNext); matched { + if echo, matched := r.typingEcho(typingPrevious, typingNext); matched { r.progress.Reset() - if !frame.OwnsPresentation && r.progressEnabled && regions.has_live() { + if !frame.OwnsPresentation && r.progressEnabled && regions.hasLive() { // Typing can update a ruler/progress region in the same snapshot. // Inspect only live regions here, so typed percentages elsewhere // cannot become progress cues, even on the same physical row. - r.progress.Update(regions.live_snapshot(previous), regions.live_snapshot(next), -1) + r.progress.Update(regions.liveSnapshot(previous), regions.liveSnapshot(next), -1) } path = "typing-echo" return echo } - deleted := r.match_deletion(previous, next) + deleted := r.matchDeletion(previous, next) if frame.OwnsPresentation && frame.Input == nil { deleted = nil } @@ -195,30 +195,30 @@ func (r *Reader) Update_application(next screen.Snapshot, frame applicationoverr if len(deleted) > 0 { deletionRow = next.Y } - r.progress.Update(regions.progress_snapshot(previous), regions.progress_snapshot(next), deletionRow) + r.progress.Update(regions.progressSnapshot(previous), regions.progressSnapshot(next), deletionRow) } if !r.automatic { path = "automatic-disabled" if len(deleted) > 0 { path = "deletion-echo" - return r.deletion_echo(deleted, next) + return r.deletionEcho(deleted, next) } return nil } if frame.OwnsPresentation { if len(deleted) > 0 { - return r.deletion_echo(deleted, next) + return r.deletionEcho(deleted, next) } if frame.InputCursor && frame.Input != nil && r.cursorEcho && !r.review.Active() && !r.applicationInputAt.IsZero() && time.Since(r.applicationInputAt) < 300*time.Millisecond && frame.Input.Contains(previous.X, previous.Y, next.Cols) && frame.Input.Contains(next.X, next.Y, next.Cols) && regions.allows(next.X, next.Y, next.Cols, true, true) { - return input_cursor_feedback(typingPrevious, typingNext) + return inputCursorFeedback(typingPrevious, typingNext) } return nil } - readingPrevious := regions.filtered_snapshot(previous, true, true) - readingNext := r.Automatic_snapshot() + readingPrevious := regions.filteredSnapshot(previous, true, true) + readingNext := r.AutomaticSnapshot() if r.trackingMode == "highlight" && !r.review.Active() { if output := highlights(readingPrevious, readingNext); len(output) > 0 { path = "highlight" @@ -233,22 +233,22 @@ func (r *Reader) Update_application(next screen.Snapshot, frame applicationoverr func (r *Reader) Command(id command.ID) presentation.CommandResult { r.applicationInputAt = time.Time{} r.progressDeletionAt = time.Time{} - if result, handled := r.region_command(id); handled { + if result, handled := r.regionCommand(id); handled { return result } switch id { case command.ToggleAttributes: - return presentation.CommandResult{Text: r.toggle_attributes()} + return presentation.CommandResult{Text: r.toggleAttributes()} case command.ToggleTracking: switch r.trackingMode { case "cursor": - r.Configure_tracking("table") + r.ConfigureTracking("table") return presentation.CommandResult{Text: i18n.T("table mode")} case "table": - r.Configure_tracking("highlight") + r.ConfigureTracking("highlight") return presentation.CommandResult{Text: i18n.T("highlight tracking")} default: - r.Configure_tracking("cursor") + r.ConfigureTracking("cursor") return presentation.CommandResult{Text: i18n.T("cursor tracking")} } case command.AutoRead: @@ -264,7 +264,7 @@ func (r *Reader) Command(id command.ID) presentation.CommandResult { previousRow := r.review.Row() result := r.review.Execute(id) afterAttribute, afterKnown := r.review.Attribute() - result.Attributes = r.attribute_feedback(id != command.AttributeCursor && beforeKnown && afterKnown && beforeAttribute != afterAttribute) - result.Indentation = r.indentation_feedback(r.review.Row() != previousRow) + result.Attributes = r.attributeFeedback(id != command.AttributeCursor && beforeKnown && afterKnown && beforeAttribute != afterAttribute) + result.Indentation = r.indentationFeedback(r.review.Row() != previousRow) return result } diff --git a/internal/reader/reader_test.go b/internal/reader/reader_test.go index f720a248..8a90489d 100644 --- a/internal/reader/reader_test.go +++ b/internal/reader/reader_test.go @@ -42,10 +42,10 @@ func fixture(lines ...string) screen.Snapshot { func TestAutomaticTypingDeletionCursorAndScroll(t *testing.T) { before, after := fixture("$ ", ""), fixture("$ a", "") before.X, after.X = 2, 3 - if got := changes(before, after, true); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('a')}) { + if got := changes(before, after, true); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('a')}) { t.Fatal(got) } - if got := changes(after, before, true); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('a')}) { + if got := changes(after, before, true); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('a')}) { t.Fatal(got) } before, after = fixture("first", "second", "third"), fixture("second", "third", "fourth") @@ -81,21 +81,21 @@ func TestReviewSurvivesStationaryUpdatesAndExitsOnCursorMovement(t *testing.T) { t.Fatal("stationary application cursor reset review", got) } next := fixture("alpha", "omega!") - if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('!')}) { + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('!')}) { t.Fatal("review suppressed new output", got) } if !r.review.Active() { t.Fatal("text change without cursor movement left review") } next.Y = 1 - r.Note_input(true, false, false) + r.NoteInput(true, false, false) if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{{Text: "omega!"}}) || r.review.Active() { t.Fatal("vertical cursor movement did not restore line feedback", got) } r.Command(command.CurrentLine) next.X = 1 - r.Note_input(true, false, false) - if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('m')}) || r.review.Active() { + r.NoteInput(true, false, false) + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('m')}) || r.review.Active() { t.Fatal("horizontal cursor movement did not restore character feedback", got) } } @@ -108,7 +108,7 @@ func TestCursorMovementLeavesReviewWithFeedbackDisabled(t *testing.T) { r.Update(s) r.Command(command.CurrentLine) s.Y = 1 - r.Note_input(true, false, false) + r.NoteInput(true, false, false) if got := r.Update(s); len(got) != 0 || r.review.Active() { t.Fatal("disabled feedback changed review exit behavior", options, got, r.review.Active()) } @@ -127,10 +127,10 @@ func TestCursorMovementPreservesReviewWithoutRecentApplicationInput(t *testing.T r.Command(command.CurrentLine) switch testCase { case "reader command": - r.Note_input(true, false, false) - r.Note_input(false, false, false) // A reader paste is not application input. + r.NoteInput(true, false, false) + r.NoteInput(false, false, false) // A reader paste is not application input. case "expired input": - r.Note_input(true, false, false) + r.NoteInput(true, false, false) r.applicationInputAt = time.Now().Add(-time.Second) } s.Y = 1 @@ -189,7 +189,7 @@ func TestReadingSettingsPreserveReviewAndNewOutput(t *testing.T) { } changed := fixture("alpha", "omega!") changed.Y = 1 - if got := r.Update(changed); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('!')}) { + if got := r.Update(changed); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('!')}) { t.Fatal("cursor echo setting suppressed new output", got) } } @@ -210,7 +210,7 @@ func TestBackspaceSpeaksRemovedTextWithoutDeletedLabel(t *testing.T) { before.X, after.X = 2+len([]rune(testCase.text)), 2 want := []presentation.Message{{Text: testCase.want}} if chars := []rune(testCase.text); len(chars) == 1 { - want = []presentation.Message{presentation.Character_message(chars[0])} + want = []presentation.Message{presentation.CharacterMessage(chars[0])} } if got := changes(before, after, true); !reflect.DeepEqual(got, want) { t.Fatalf("got %v, want %q", got, testCase.want) @@ -238,7 +238,7 @@ func TestScrollWithBlankAndUnicodeWhitespaceRows(t *testing.T) { } before, after := fixture("a", "", ""), fixture("", "", "") before.X = 1 - if got := changes(before, after, true); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('a')}) { + if got := changes(before, after, true); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('a')}) { t.Fatalf("deleting last character on blank screen: %v", got) } } diff --git a/internal/reader/regions.go b/internal/reader/regions.go index fe57b125..03d3f72e 100644 --- a/internal/reader/regions.go +++ b/internal/reader/regions.go @@ -32,19 +32,19 @@ var clearLiveRegions = [...]command.ID{ command.ClearLiveRegion7, command.ClearLiveRegion8, command.ClearLiveRegion9, command.ClearLiveRegion10, } -func (r *Reader) region_state() *terminalRegions { return r.regions[r.screen.Terminal] } +func (r *Reader) regionState() *terminalRegions { return r.regions[r.screen.Terminal] } -func (r *Reader) ensure_regions() *terminalRegions { +func (r *Reader) ensureRegions() *terminalRegions { if r.regions == nil { r.regions = make(map[int]*terminalRegions) } - if r.region_state() == nil { + if r.regionState() == nil { r.regions[r.screen.Terminal] = &terminalRegions{} } - return r.region_state() + return r.regionState() } -func (s *terminalRegions) has_live() bool { +func (s *terminalRegions) hasLive() bool { if s != nil { for _, region := range s.live { if region != nil { @@ -72,11 +72,11 @@ func (s *terminalRegions) allows(x, y, cols int, window, live bool) bool { return true } -// filtered_snapshot never alters the source snapshot. Masking before diffing +// filteredSnapshot never alters the source snapshot. Masking before diffing // keeps excluded churn out of typing/scroll classification, rather than trying // to remove strings from an already flattened presentation. -func (s *terminalRegions) filtered_snapshot(snapshot screen.Snapshot, window, live bool) screen.Snapshot { - if s == nil || (!window || s.window == nil) && (!live || !s.has_live()) { +func (s *terminalRegions) filteredSnapshot(snapshot screen.Snapshot, window, live bool) screen.Snapshot { + if s == nil || (!window || s.window == nil) && (!live || !s.hasLive()) { return snapshot } snapshot.Cells = slices.Clone(snapshot.Cells) @@ -96,17 +96,17 @@ func (s *terminalRegions) filtered_snapshot(snapshot screen.Snapshot, window, li return snapshot } -// Automatic_snapshot is also used by prompt restoration: an excluded update +// AutomaticSnapshot is also used by prompt restoration: an excluded update // must not restore speech or bypass the automatic-reading filter. -func (r *Reader) Automatic_snapshot() screen.Snapshot { - return r.region_state().filtered_snapshot(r.screen, true, true) +func (r *Reader) AutomaticSnapshot() screen.Snapshot { + return r.regionState().filteredSnapshot(r.screen, true, true) } -func (r *Reader) Region_revision() uint64 { return r.regionRevision } +func (r *Reader) RegionRevision() uint64 { return r.regionRevision } -// live_snapshot retains only live-region cells for progress detection alongside +// liveSnapshot retains only live-region cells for progress detection alongside // a confirmed typing edit. Unlike automatic speech, progress may inspect them. -func (s *terminalRegions) live_snapshot(snapshot screen.Snapshot) screen.Snapshot { +func (s *terminalRegions) liveSnapshot(snapshot screen.Snapshot) screen.Snapshot { snapshot.Cells = slices.Clone(snapshot.Cells) for row := range snapshot.Rows { for col := range snapshot.Cols { @@ -120,7 +120,7 @@ func (s *terminalRegions) live_snapshot(snapshot screen.Snapshot) screen.Snapsho // An explicit live region remains eligible for progress even when it lies // outside a reading window. The window otherwise excludes outside progress. -func (s *terminalRegions) progress_snapshot(snapshot screen.Snapshot) screen.Snapshot { +func (s *terminalRegions) progressSnapshot(snapshot screen.Snapshot) screen.Snapshot { if s == nil || s.window == nil { return snapshot } @@ -135,7 +135,7 @@ func (s *terminalRegions) progress_snapshot(snapshot screen.Snapshot) screen.Sna return snapshot } -func (r *Reader) reset_region_feedback() { +func (r *Reader) resetRegionFeedback() { r.regionRevision++ r.progress.Reset() r.inputCount, r.inputBoundary = 0, false @@ -143,25 +143,25 @@ func (r *Reader) reset_region_feedback() { r.attributeKnown, r.indentKnown = false, false } -// Set_window is shared by marked keyboard commands and validated remote +// SetWindow is shared by marked keyboard commands and validated remote // coordinates. Regions belong to the terminal, never a guessed process name. -func (r *Reader) Set_window(x1, y1, x2, y2 int) error { +func (r *Reader) SetWindow(x1, y1, x2, y2 int) error { if !r.screen.Active || min(x1, x2, y1, y2) < 0 || max(x1, x2) >= r.screen.Cols || max(y1, y2) >= r.screen.Rows { return fmt.Errorf("Window coordinates must be inside the active screen") } - r.ensure_regions().window = &screen.Region{Left: min(x1, x2), Top: min(y1, y2), Right: max(x1, x2), Bottom: max(y1, y2)} - r.reset_region_feedback() + r.ensureRegions().window = &screen.Region{Left: min(x1, x2), Top: min(y1, y2), Right: max(x1, x2), Bottom: max(y1, y2)} + r.resetRegionFeedback() return nil } -func (r *Reader) Clear_window() { - if state := r.region_state(); state != nil { +func (r *Reader) ClearWindow() { + if state := r.regionState(); state != nil { state.window = nil } - r.reset_region_feedback() + r.resetRegionFeedback() } -func (r *Reader) region_command(id command.ID) (presentation.CommandResult, bool) { +func (r *Reader) regionCommand(id command.ID) (presentation.CommandResult, bool) { readSlot, clearSlot := slices.Index(readLiveRegions[:], id), slices.Index(clearLiveRegions[:], id) known := readSlot >= 0 || clearSlot >= 0 || id == command.SetWindow || id == command.ClearWindow || id == command.SetLiveRegion || id == command.ListReadingRegions || id == command.ClearLiveRegions || id == command.ClearReadingRegions @@ -172,7 +172,7 @@ func (r *Reader) region_command(id command.ID) (presentation.CommandResult, bool if !r.screen.Active { return presentation.CommandResult{Text: i18n.T("no text console"), Cue: presentation.Error}, true } - state := r.region_state() + state := r.regionState() switch { case readSlot >= 0 || clearSlot >= 0: slot := max(readSlot, clearSlot) @@ -181,7 +181,7 @@ func (r *Reader) region_command(id command.ID) (presentation.CommandResult, bool result.Text = i18n.Format("Live region {0} not set", number) } else if clearSlot >= 0 { state.live[slot] = nil - r.reset_region_feedback() + r.resetRegionFeedback() result.Text = i18n.Format("Live region {0} cleared", number) } else { result.Text = state.live[slot].Text(r.screen) @@ -192,57 +192,57 @@ func (r *Reader) region_command(id command.ID) (presentation.CommandResult, bool } } case id == command.SetLiveRegion: - region, ok := r.review.Marked_region(true) + region, ok := r.review.MarkedRegion(true) if !ok { result.Text = i18n.T("One or two marks are needed") break } - state = r.ensure_regions() + state = r.ensureRegions() slot := slices.Index(state.live[:], nil) if slot < 0 { result.Text = i18n.T("All 10 live regions are set") break } state.live[slot] = ®ion - r.review.Clear_marks() - r.reset_region_feedback() + r.review.ClearMarks() + r.resetRegionFeedback() result.Text = i18n.Format("Live region {0} set", strconv.Itoa(slot+1)) case id == command.SetWindow: - region, ok := r.review.Marked_region(false) + region, ok := r.review.MarkedRegion(false) if !ok { result.Text = i18n.T("Set window begin and end marks") break } - r.ensure_regions().window = ®ion - r.review.Clear_marks() - r.reset_region_feedback() + r.ensureRegions().window = ®ion + r.review.ClearMarks() + r.resetRegionFeedback() result.Text = i18n.Format("Window Mode on for terminal {0}", strconv.Itoa(r.screen.Terminal)) case id == command.ClearWindow: if state == nil || state.window == nil { result.Text = i18n.T("Not in window Mode") } else { - r.Clear_window() + r.ClearWindow() result.Text = i18n.Format("Window Mode off for terminal {0}", strconv.Itoa(r.screen.Terminal)) } case id == command.ClearLiveRegions: if state != nil { state.live = [10]*screen.Region{} } - r.reset_region_feedback() + r.resetRegionFeedback() result.Text = i18n.T("Live regions cleared") case id == command.ClearReadingRegions: delete(r.regions, r.screen.Terminal) - r.reset_region_feedback() + r.resetRegionFeedback() result.Text = i18n.T("Reading regions cleared") case id == command.ListReadingRegions: var entries []string if state != nil { if state.window != nil { - entries = append(entries, i18n.Format("Reading window: {0}", region_description(*state.window))) + entries = append(entries, i18n.Format("Reading window: {0}", regionDescription(*state.window))) } for slot, region := range state.live { if region != nil { - entries = append(entries, i18n.Format("Live region {0}: {1}", strconv.Itoa(slot+1), region_description(*region))) + entries = append(entries, i18n.Format("Live region {0}: {1}", strconv.Itoa(slot+1), regionDescription(*region))) } } } @@ -254,7 +254,7 @@ func (r *Reader) region_command(id command.ID) (presentation.CommandResult, bool return result, true } -func region_description(region screen.Region) string { +func regionDescription(region screen.Region) string { if region.ToLineEnd { return i18n.Format("row {0}, column {1} to end of line", strconv.Itoa(region.Top+1), strconv.Itoa(region.Left+1)) } diff --git a/internal/reader/regions_test.go b/internal/reader/regions_test.go index a687bbe2..b3cd21c3 100644 --- a/internal/reader/regions_test.go +++ b/internal/reader/regions_test.go @@ -15,19 +15,19 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func region_mark(t *testing.T, r *Reader, x, y int) { +func regionMark(t *testing.T, r *Reader, x, y int) { t.Helper() snapshot := r.screen snapshot.X, snapshot.Y = x, y r.Update(snapshot) r.Command(command.FollowCursor) r.Command(command.CurrentChar) - if result := r.Set_mark(); result.Text != "set mark" { + if result := r.SetMark(); result.Text != "set mark" { t.Fatal(result) } } -func region_command(t *testing.T, r *Reader, id command.ID, want string) { +func regionCommand(t *testing.T, r *Reader, id command.ID, want string) { t.Helper() if result := r.Command(id); result.Text != want { t.Fatalf("%s: %+v; want %q", id, result, want) @@ -38,29 +38,29 @@ func TestLiveRegionVimRulerTypingLatestReadAndClear(t *testing.T) { for _, echo := range []bool{false, true} { t.Run(map[bool]string{false: "echo disabled", true: "echo enabled"}[echo], func(t *testing.T) { r := New() - r.Configure_echo(echo, false, false) + r.ConfigureEcho(echo, false, false) before := fixture("compose", "1,8 All") before.X = 7 r.Update(before) - region_mark(t, r, 0, 1) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") - if _, ok := r.Marked_text(true); ok { + regionMark(t, r, 0, 1) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") + if _, ok := r.MarkedText(true); ok { t.Fatal("successful creation retained marks") } r.Command(command.FollowCursor) r.Update(before) after := fixture("composeX", "1,9 All") after.X = 8 - r.Note_input(true, true, false) + r.NoteInput(true, true, false) got := r.Update(after) var want []presentation.Message if echo { - want = []presentation.Message{presentation.Character_message('X')} + want = []presentation.Message{presentation.CharacterMessage('X')} } if !reflect.DeepEqual(got, want) { t.Fatal("ruler broke typing echo", got, want) } - region_command(t, r, command.ReadLiveRegion1, "1,9 All") + regionCommand(t, r, command.ReadLiveRegion1, "1,9 All") if !strings.Contains(r.Command(command.ReadScreen).Text, "1,9 All") { t.Fatal("manual read lost excluded text") } @@ -69,7 +69,7 @@ func TestLiveRegionVimRulerTypingLatestReadAndClear(t *testing.T) { if got := r.Update(after); len(got) != 0 { t.Fatal("passive ruler spoke", got) } - region_command(t, r, command.ClearLiveRegion1, "Live region 1 cleared") + regionCommand(t, r, command.ClearLiveRegion1, "Live region 1 cleared") if got := r.Update(after); len(got) != 0 { t.Fatal("clear replayed hidden history", got) } @@ -86,10 +86,10 @@ func TestLiveRegionRectangleUnicodeEdgesAndReversedMarks(t *testing.T) { r := New() s := fixture("LEFTabcRIGHT", "LEFT界éxRIGHT", "untouched") r.Update(s) - region_mark(t, r, 6, 1) - region_mark(t, r, 4, 0) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") - region_command(t, r, command.ReadLiveRegion1, "abc\n界éx") + regionMark(t, r, 6, 1) + regionMark(t, r, 4, 0) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") + regionCommand(t, r, command.ReadLiveRegion1, "abc\n界éx") r.Command(command.FollowCursor) next := fixture("LEFTxyzRIGHT", "LEFTé界qRIGHT", "untouched") next.X, next.Y = r.screen.X, r.screen.Y @@ -98,7 +98,7 @@ func TestLiveRegionRectangleUnicodeEdgesAndReversedMarks(t *testing.T) { } next = fixture("LEFTxyzRIGH!", "LEFTé界qRIGHT", "untouched") next.X, next.Y = r.screen.X, r.screen.Y - if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('!')}) { + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('!')}) { t.Fatal("adjacent character lost", got) } if s.Text(0) != "LEFTabcRIGHT" { @@ -109,104 +109,104 @@ func TestLiveRegionRectangleUnicodeEdgesAndReversedMarks(t *testing.T) { func TestLiveRegionSlotsReuseLimitListingAndIndependentTerminals(t *testing.T) { r := New() r.Update(fixture("first", "second")) - region_command(t, r, command.ReadLiveRegion2, "Live region 2 not set") - region_command(t, r, command.SetLiveRegion, "One or two marks are needed") + regionCommand(t, r, command.ReadLiveRegion2, "Live region 2 not set") + regionCommand(t, r, command.SetLiveRegion, "One or two marks are needed") for slot := range 10 { - region_mark(t, r, 0, slot%2) - region_command(t, r, command.SetLiveRegion, "Live region "+strconv.Itoa(slot+1)+" set") + regionMark(t, r, 0, slot%2) + regionCommand(t, r, command.SetLiveRegion, "Live region "+strconv.Itoa(slot+1)+" set") } - region_mark(t, r, 0, 0) - region_command(t, r, command.SetLiveRegion, "All 10 live regions are set") - if _, ok := r.Marked_text(true); !ok { + regionMark(t, r, 0, 0) + regionCommand(t, r, command.SetLiveRegion, "All 10 live regions are set") + if _, ok := r.MarkedText(true); !ok { t.Fatal("failed creation discarded marks") } listing := r.Command(command.ListReadingRegions).Text if !strings.Contains(listing, "Live region 10: row 2, column 1 to end of line") { t.Fatal(listing) } - region_command(t, r, command.ClearLiveRegion4, "Live region 4 cleared") - region_command(t, r, command.SetLiveRegion, "Live region 4 set") - region_command(t, r, command.ReadLiveRegion4, "first") + regionCommand(t, r, command.ClearLiveRegion4, "Live region 4 cleared") + regionCommand(t, r, command.SetLiveRegion, "Live region 4 set") + regionCommand(t, r, command.ReadLiveRegion4, "first") other := fixture("another terminal", "status") other.Terminal = 3 r.Update(other) - region_command(t, r, command.ReadLiveRegion1, "Live region 1 not set") - region_command(t, r, command.ListReadingRegions, "No reading regions set") - region_mark(t, r, 0, 1) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") - region_command(t, r, command.ClearReadingRegions, "Reading regions cleared") + regionCommand(t, r, command.ReadLiveRegion1, "Live region 1 not set") + regionCommand(t, r, command.ListReadingRegions, "No reading regions set") + regionMark(t, r, 0, 1) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") + regionCommand(t, r, command.ClearReadingRegions, "Reading regions cleared") r.Update(fixture("new first", "new second")) - region_command(t, r, command.ReadLiveRegion1, "new first") - region_command(t, r, command.ClearLiveRegions, "Live regions cleared") - region_command(t, r, command.ReadLiveRegion10, "Live region 10 not set") + regionCommand(t, r, command.ReadLiveRegion1, "new first") + regionCommand(t, r, command.ClearLiveRegions, "Live regions cleared") + regionCommand(t, r, command.ReadLiveRegion10, "Live region 10 not set") fresh := New() fresh.Update(r.screen) - region_command(t, fresh, command.ReadLiveRegion1, "Live region 1 not set") + regionCommand(t, fresh, command.ReadLiveRegion1, "Live region 1 not set") } func TestRegionsSurviveFocusBufferAndResizeWithClippedReads(t *testing.T) { r := New() r.Update(fixture("editor", "status at bottom")) - region_mark(t, r, 7, 1) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 7, 1) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") s := r.screen s.Active = false r.Update(s) s.Active = true r.Update(s) - region_command(t, r, command.ReadLiveRegion1, "at bottom") + regionCommand(t, r, command.ReadLiveRegion1, "at bottom") s.Generation++ r.Update(s) - region_command(t, r, command.ReadLiveRegion1, "at bottom") + regionCommand(t, r, command.ReadLiveRegion1, "at bottom") s = screen.Snapshot{Terminal: s.Terminal, Active: true, Rows: 1, Cols: 5, Cells: []rune("small")} r.Update(s) - region_command(t, r, command.ReadLiveRegion1, "Live region 1 outside screen") + regionCommand(t, r, command.ReadLiveRegion1, "Live region 1 outside screen") r.Update(fixture("editor", "status new contents")) - region_command(t, r, command.ReadLiveRegion1, "new contents") + regionCommand(t, r, command.ReadLiveRegion1, "new contents") } func TestReadingWindowAndLiveRegionComposeWithoutRestrictingReview(t *testing.T) { r := New() r.Update(fixture("outer text", "IN abc OUT", "IN def OUT")) - region_command(t, r, command.SetWindow, "Set window begin and end marks") - region_mark(t, r, 5, 2) - region_mark(t, r, 3, 1) - region_command(t, r, command.SetWindow, "Window Mode on for terminal 2") - if got := r.Automatic_snapshot().Text(1); got != " abc" { + regionCommand(t, r, command.SetWindow, "Set window begin and end marks") + regionMark(t, r, 5, 2) + regionMark(t, r, 3, 1) + regionCommand(t, r, command.SetWindow, "Window Mode on for terminal 2") + if got := r.AutomaticSnapshot().Text(1); got != " abc" { t.Fatal(got) } - region_mark(t, r, 3, 2) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 3, 2) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") next := fixture("changed outer", "IN abc NEW", "IN XYZ NEW") next.X, next.Y = r.screen.X, r.screen.Y if got := r.Update(next); len(got) != 0 { t.Fatal("outside window/live region spoke", got) } - region_command(t, r, command.ReadLiveRegion1, "XYZ NEW") + regionCommand(t, r, command.ReadLiveRegion1, "XYZ NEW") if got := r.Command(command.ReadScreen).Text; !strings.Contains(got, "changed outer") || !strings.Contains(got, "XYZ NEW") { t.Fatal("window clipped manual review", got) } next = fixture("changed outer", "IN qbc NEW", "IN XYZ NEW") next.X, next.Y = r.screen.X, r.screen.Y - if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('q')}) { + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('q')}) { t.Fatal("inside window did not speak", got) } - region_command(t, r, command.ClearWindow, "Window Mode off for terminal 2") - region_command(t, r, command.ReadLiveRegion1, "XYZ NEW") - region_command(t, r, command.ClearReadingRegions, "Reading regions cleared") - region_command(t, r, command.ListReadingRegions, "No reading regions set") + regionCommand(t, r, command.ClearWindow, "Window Mode off for terminal 2") + regionCommand(t, r, command.ReadLiveRegion1, "XYZ NEW") + regionCommand(t, r, command.ClearReadingRegions, "Reading regions cleared") + regionCommand(t, r, command.ListReadingRegions, "No reading regions set") } func TestLiveRegionProgressAloneAndConcurrentTyping(t *testing.T) { for _, typing := range []bool{false, true} { r := New() - r.Configure_progress(true) - r.Configure_echo(true, false, false) + r.ConfigureProgress(true) + r.ConfigureEcho(true, false, false) before := fixture("compose", "Download 20%") before.X = 7 r.Update(before) - region_mark(t, r, 0, 1) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 0, 1) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") r.Command(command.FollowCursor) r.Update(before) after := fixture("compose", "Download 30%") @@ -214,20 +214,20 @@ func TestLiveRegionProgressAloneAndConcurrentTyping(t *testing.T) { if typing { after = fixture("composeX", "Download 30%") after.X = 8 - r.Note_input(true, true, false) + r.NoteInput(true, true, false) } output := r.Update(after) if len(output) > 0 && (!typing || len(output) != 1 || output[0].Character == nil || *output[0].Character != 'X') { t.Fatal("progress region spoke", typing, output) } - if value, ok := r.Next_progress(time.Now().Add(time.Second)); !ok || value != 30 { + if value, ok := r.NextProgress(time.Now().Add(time.Second)); !ok || value != 30 { t.Fatal("lost region progress", typing, value, ok) } - r.Configure_progress(false) + r.ConfigureProgress(false) after = fixture("composeX", "Download 40%") after.X = 8 r.Update(after) - if _, ok := r.Next_progress(time.Now().Add(2 * time.Second)); ok { + if _, ok := r.NextProgress(time.Now().Add(2 * time.Second)); ok { t.Fatal("disabled monitor beeped") } } @@ -235,36 +235,36 @@ func TestLiveRegionProgressAloneAndConcurrentTyping(t *testing.T) { func TestLiveRegionKeepsProgressOutsideWindowAndSuppressesSameRowTypedPercentages(t *testing.T) { r := New() - r.Configure_progress(true) + r.ConfigureProgress(true) r.Update(fixture("editor", "Download 20%")) - if err := r.Set_window(0, 0, 19, 0); err != nil { + if err := r.SetWindow(0, 0, 19, 0); err != nil { t.Fatal(err) } - region_mark(t, r, 0, 1) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 0, 1) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") next := fixture("editor", "Download 30%") next.Y = 1 if got := r.Update(next); len(got) != 0 { t.Fatal(got) } - if value, ok := r.Next_progress(time.Now()); !ok || value != 30 { + if value, ok := r.NextProgress(time.Now()); !ok || value != 30 { t.Fatal("window hid an explicit live progress region", value, ok) } // A progress field and typing can also share one physical row. r = New() - r.Configure_progress(true) + r.ConfigureProgress(true) s := fixture("20 Download 20%") s.X = 2 r.Update(s) - region_mark(t, r, 4, 0) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 4, 0) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") r.Command(command.FollowCursor) r.Update(s) next = fixture("20% Download 30%") next.X = 3 - r.Note_input(true, true, false) + r.NoteInput(true, true, false) r.Update(next) - if value, ok := r.Next_progress(time.Now()); !ok || value != 30 { + if value, ok := r.NextProgress(time.Now()); !ok || value != 30 { t.Fatal("typed percentage won over live progress on the same row", value, ok) } } @@ -273,8 +273,8 @@ func TestLiveRegionFilteringPreservesScrollAndDeletion(t *testing.T) { r := New() s := fixture("old first", "old second", "old third", "status 1") r.Update(s) - region_mark(t, r, 0, 3) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 0, 3) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") r.Command(command.FollowCursor) next := fixture("old second", "old third", "new fourth", "status 2") next.Y = 3 @@ -284,11 +284,11 @@ func TestLiveRegionFilteringPreservesScrollAndDeletion(t *testing.T) { s = fixture("composeX", "old third", "new fourth", "status 2") s.X = 8 r.Update(s) - r.Note_input(true, false, false) - r.Note_deletion() + r.NoteInput(true, false, false) + r.NoteDeletion() next = fixture("compose", "old third", "new fourth", "status 3") next.X = 7 - if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('X')}) { + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('X')}) { t.Fatal("ruler hid deletion feedback", got) } } @@ -299,22 +299,22 @@ func TestLiveRegionSuppressesCursorHighlightAttributesIndentationAndWordFeedback s := fixture("outside", " helo") s.Attributes = make([]screen.Attribute, len(s.Cells)) r.Update(s) - region_mark(t, r, 0, 1) - region_command(t, r, command.SetLiveRegion, "Live region 1 set") + regionMark(t, r, 0, 1) + regionCommand(t, r, command.SetLiveRegion, "Live region 1 set") r.Command(command.FollowCursor) - r.Configure_tracking(mode) - r.Configure_indentation("both") - r.Configure_attributes("both", "fenrirBold") - r.Configure_echo(true, true, true) + r.ConfigureTracking(mode) + r.ConfigureIndentation("both") + r.ConfigureAttributes("both", "fenrirBold") + r.ConfigureEcho(true, true, true) next := fixture("outside", " helo ") next.Y, next.X = 1, 9 next.Attributes = make([]screen.Attribute, len(next.Cells)) for col := range 9 { next.Attributes[next.Cols+col].Style = screen.Bold } - r.Note_input(true, true, true) - if got := r.Update(next); len(got) != 0 || len(r.Completed_words()) != 0 { - t.Fatal("excluded automatic feedback", mode, got, r.Completed_words()) + r.NoteInput(true, true, true) + if got := r.Update(next); len(got) != 0 || len(r.CompletedWords()) != 0 { + t.Fatal("excluded automatic feedback", mode, got, r.CompletedWords()) } if got := r.Command(command.CurrentLine).Text; !strings.Contains(got, "helo") { t.Fatal("manual review lost live content", mode, got) diff --git a/internal/reader/spellcheck.go b/internal/reader/spellcheck.go index 17c038f3..7da5df11 100644 --- a/internal/reader/spellcheck.go +++ b/internal/reader/spellcheck.go @@ -9,14 +9,14 @@ import ( "git.stormux.org/storm/fenrir/internal/spellcheck" ) -// Spellcheck_word observes the active cursor without moving it or entering review. -func (r *Reader) Spellcheck_word() string { return r.review.Spellcheck_word() } +// SpellcheckWord observes the active cursor without moving it or entering review. +func (r *Reader) SpellcheckWord() string { return r.review.SpellcheckWord() } -// Completed_words contains only screen-confirmed typing from the latest Update. +// CompletedWords contains only screen-confirmed typing from the latest Update. // Raw keys, cursor navigation, deletion and passive output never supply words. -func (r *Reader) Completed_words() []string { return r.completedWords } +func (r *Reader) CompletedWords() []string { return r.completedWords } -func (r *Reader) completed_word(index int, snapshot screen.Snapshot) { +func (r *Reader) completedWord(index int, snapshot screen.Snapshot) { char := snapshot.Cells[index] if !spellcheck.Separator(char) { return diff --git a/internal/reader/spellcheck_test.go b/internal/reader/spellcheck_test.go index 99f59370..3180fdf6 100644 --- a/internal/reader/spellcheck_test.go +++ b/internal/reader/spellcheck_test.go @@ -11,57 +11,57 @@ import ( "testing" ) -func spell_snapshot(text string) screen.Snapshot { +func spellSnapshot(text string) screen.Snapshot { return screen.Snapshot{Terminal: 2, Active: true, Rows: 1, Cols: 80, X: len([]rune(text)), Cells: []rune(text + strings.Repeat(" ", 80-len([]rune(text))))} } func TestSpellcheckOnlyUsesConfirmedCompletedWords(t *testing.T) { for _, text := range []string{"helo ", "café!", "don't ", "one,two ", "https://example.com ", "foo.bar ", "./program ", "--option "} { r := New() - r.Configure_echo(false, false, false) - before := spell_snapshot("$ ") + r.ConfigureEcho(false, false, false) + before := spellSnapshot("$ ") before.X = 2 r.Update(before) for _, char := range text { - r.Note_input(true, true, char == ' ') + r.NoteInput(true, true, char == ' ') } - after := spell_snapshot("$ " + text) + after := spellSnapshot("$ " + text) after.X = 2 + len([]rune(text)) r.Update(after) want := map[string][]string{"helo ": {"helo"}, "café!": {"café"}, "don't ": {"don't"}, "one,two ": {"one", "two"}}[text] - if !reflect.DeepEqual(r.Completed_words(), want) { - t.Fatal(text, r.Completed_words(), want) + if !reflect.DeepEqual(r.CompletedWords(), want) { + t.Fatal(text, r.CompletedWords(), want) } r.Update(after) - if len(r.Completed_words()) != 0 { + if len(r.CompletedWords()) != 0 { t.Fatal("repeated unchanged word") } } for _, input := range []bool{false, true} { r := New() - before := spell_snapshot("$ ") + before := spellSnapshot("$ ") before.X = 2 r.Update(before) if input { for range 8 { - r.Note_input(true, true, true) + r.NoteInput(true, true, true) } } r.Update(before) - if len(r.Completed_words()) != 0 { + if len(r.CompletedWords()) != 0 { t.Fatal("password input leaked") } - r.Note_input(false, false, false) + r.NoteInput(false, false, false) after := fixture("$ typo ") after.X = 7 r.Update(after) - if len(r.Completed_words()) != 0 { + if len(r.CompletedWords()) != 0 { t.Fatal("passive output checked") } - r.Note_input(true, false, false) + r.NoteInput(true, false, false) after.X-- r.Update(after) - if len(r.Completed_words()) != 0 { + if len(r.CompletedWords()) != 0 { t.Fatal("navigation checked") } } @@ -72,11 +72,11 @@ func TestSpellcheckSourceRespectsReviewWithoutMovingCursors(t *testing.T) { snapshot := fixture("alpha beta") snapshot.X = 7 r.Update(snapshot) - if got := r.Spellcheck_word(); got != "beta" || r.review.Active() { + if got := r.SpellcheckWord(); got != "beta" || r.review.Active() { t.Fatal(got, r.review.Active()) } r.Command(command.PreviousWord) - if got := r.Spellcheck_word(); got != "alpha" || !r.review.Active() || r.screen.X != 7 { + if got := r.SpellcheckWord(); got != "alpha" || !r.review.Active() || r.screen.X != 7 { t.Fatal(got, r.screen.X) } } diff --git a/internal/reader/tracking_test.go b/internal/reader/tracking_test.go index a51fb563..c9f3676e 100644 --- a/internal/reader/tracking_test.go +++ b/internal/reader/tracking_test.go @@ -36,8 +36,8 @@ func TestCursorNavigationWithStatusChanges(t *testing.T) { r.Command(command.NextLine) after := fixture("Message one", "Message two", "2/2 messages") after.Y = 1 - r.Note_input(true, false, false) - want := []presentation.Message{presentation.Character_message('2'), {Text: "Message two"}} + r.NoteInput(true, false, false) + want := []presentation.Message{presentation.CharacterMessage('2'), {Text: "Message two"}} if got := r.Update(after); !reflect.DeepEqual(got, want) { t.Fatal("status line hid focused message", got) } @@ -46,7 +46,7 @@ func TestCursorNavigationWithStatusChanges(t *testing.T) { } // Cursor feedback disabled still leaves incoming text available. r.Configure(true, false) - if got := r.Update(before); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('1')}) { + if got := r.Update(before); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('1')}) { t.Fatal("cursor setting suppressed status output", got) } // New command output commonly leaves the cursor on an unchanged blank row. @@ -61,8 +61,8 @@ func TestCursorNavigationWithStatusChanges(t *testing.T) { func TestTrackingCycleDefaultsAndReview(t *testing.T) { r := New() - if r.Tracking_mode() != "cursor" { - t.Fatal(r.Tracking_mode()) + if r.TrackingMode() != "cursor" { + t.Fatal(r.TrackingMode()) } r.Update(fixture("one | two")) for range 2 { @@ -72,11 +72,11 @@ func TestTrackingCycleDefaultsAndReview(t *testing.T) { } } } - r.Configure_tracking("table") + r.ConfigureTracking("table") if got := r.Command(command.CurrentWord).Text; got != "one Column 1" { t.Fatal("table command was not dispatched", got) } - r.Configure_tracking("cursor") + r.ConfigureTracking("cursor") if got := r.Command(command.CurrentWord).Text; got != "one" { t.Fatal("leaving table mode broke ordinary review", got) } @@ -85,7 +85,7 @@ func TestTrackingCycleDefaultsAndReview(t *testing.T) { func TestTableHeadersAfterCommandOutputAndExplicitClear(t *testing.T) { r := New() r.Update(fixture("$ free -h", "", "", "", "")) - r.Configure_tracking("table") + r.ConfigureTracking("table") next := fixture("$ free -h", " total used", "Mem: 12 3", "Swap: 4 0", "$ ") next.Y = 4 if output := r.Update(next); len(output) == 0 || r.review.Active() { @@ -97,12 +97,12 @@ func TestTableHeadersAfterCommandOutputAndExplicitClear(t *testing.T) { if got := r.Command(command.NextWord).Text; got != "12 total" { t.Fatal("command output headers were not available through reader dispatch", got) } - r.Clear_marks() + r.ClearMarks() if got := r.Command(command.CurrentWord).Text; got != "12 Column 2" { t.Fatal("reader clear did not clear headers", got) } r.Command(command.PreviousLine) - r.Set_mark() + r.SetMark() r.Command(command.NextLine) if got := r.Command(command.CurrentWord).Text; got != "12 total" { t.Fatal("manual selection after clear failed through reader dispatch", got) @@ -122,7 +122,7 @@ func TestHighlightSelectionAndSuppression(t *testing.T) { return next } r := New() - r.Configure_tracking("highlight") + r.ConfigureTracking("highlight") r.Update(selectRow(0)) next := selectRow(1) if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{{Text: "Second message"}}) { @@ -158,7 +158,7 @@ func TestReviewCursorExitPolicyPreservesMuttWorkflowAndPassiveReview(t *testing. for _, leave := range []bool{false, true} { for _, id := range []command.ID{command.CurrentLine, command.CurrentWord, command.NextChar, command.LastText, command.Top, command.Bottom} { r := New() - r.Configure_review(true, true, leave, true) + r.ConfigureReview(true, true, leave, true) before := fixture("First message", "Second message", "status") r.Update(before) r.Command(id) @@ -169,7 +169,7 @@ func TestReviewCursorExitPolicyPreservesMuttWorkflowAndPassiveReview(t *testing. t.Fatal("passive movement left review", id) } next.Y = 0 - r.Note_input(true, false, false) + r.NoteInput(true, false, false) r.Update(next) if r.review.Active() == leave { t.Fatal("cursor exit policy ignored", id, leave) @@ -186,11 +186,11 @@ func TestReviewCursorExitPolicyPreservesMuttWorkflowAndPassiveReview(t *testing. func TestScreenExitPolicyIsIndependentOfRecentApplicationInput(t *testing.T) { r := New() - r.Configure_review(true, true, true, false) + r.ConfigureReview(true, true, true, false) before := fixture("first", "second") r.Update(before) r.Command(command.Bottom) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) next := before next.Terminal++ next.Y = 1 diff --git a/internal/review/additional_actions_test.go b/internal/review/additional_actions_test.go index 981a84db..f443f15b 100644 --- a/internal/review/additional_actions_test.go +++ b/internal/review/additional_actions_test.go @@ -21,7 +21,7 @@ func TestAdditionalReportsUseActiveCursorWithoutMovingIt(t *testing.T) { kind := " text cursor " if detached { r.Execute(command.CurrentChar) - r.Set_mark() + r.SetMark() s.X, s.Y = 0, 2 r.Update(s) kind = " review cursor " @@ -106,7 +106,7 @@ func TestAdditionalScreenCharactersUsePhysicalCorners(t *testing.T) { var r Review s := fixture(lines...) r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) for _, trial := range []struct { id command.ID x, y int @@ -133,10 +133,10 @@ func TestAdditionalReportsReadWholeTableRowAndResetWithSession(t *testing.T) { s.X = 7 r.Update(s) r.Execute(command.CurrentChar) - r.Set_mark() - r.Set_table_mode(true) + r.SetMark() + r.SetTableMode(true) r.Execute(command.CurrentWord) - r.Set_mark() + r.SetMark() if got := r.Execute(command.LineToCursor).Text; got != "Name|Su" { t.Fatal("line report lost row scope", got) } diff --git a/internal/review/attributes.go b/internal/review/attributes.go index b9c648cc..f4c9e506 100644 --- a/internal/review/attributes.go +++ b/internal/review/attributes.go @@ -8,7 +8,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func (r *Review) Configure_attributes(format string) { r.attributeFormat = format } +func (r *Review) ConfigureAttributes(format string) { r.attributeFormat = format } func (r *Review) Attribute() (screen.Attribute, bool) { if !r.ready || len(r.screen.Attributes) != len(r.screen.Cells) || len(r.screen.Attributes) == 0 { @@ -17,10 +17,10 @@ func (r *Review) Attribute() (screen.Attribute, bool) { return r.screen.Attributes[r.y*r.screen.Cols+r.x], true } -func (r *Review) attribute_cursor() string { +func (r *Review) attributeCursor() string { attribute, valid := r.Attribute() if !valid { return "" } - return presentation.Format_attributes(attribute, r.attributeFormat) + return presentation.FormatAttributes(attribute, r.attributeFormat) } diff --git a/internal/review/bottom.go b/internal/review/bottom.go index 5862a452..c45fbd6f 100644 --- a/internal/review/bottom.go +++ b/internal/review/bottom.go @@ -24,7 +24,7 @@ import ( func (r *Review) bottom() string { r.x, r.y = 0, r.screen.Rows-1 if r.tableMode { - r.sync_table_column() + r.syncTableColumn() } return i18n.T("Bottom") } diff --git a/internal/review/current_line.go b/internal/review/current_line.go index a49f65ad..44d2ecc5 100644 --- a/internal/review/current_line.go +++ b/internal/review/current_line.go @@ -24,10 +24,10 @@ import ( func (r *Review) currentLine() string { r.x = 0 - return r.line_text() + return r.lineText() } -func (r *Review) line_text() string { +func (r *Review) lineText() string { if strings.TrimSpace(r.screen.Text(r.y)) == "" { r.result.Cue = presentation.Blank } diff --git a/internal/review/cursor_column.go b/internal/review/cursor_column.go index 9e39ed56..ee8cda1a 100644 --- a/internal/review/cursor_column.go +++ b/internal/review/cursor_column.go @@ -9,7 +9,7 @@ import ( "git.stormux.org/storm/fenrir/internal/i18n" ) -func (r *Review) cursor_column() string { - r.result.After.Text = r.cursor_scope() + i18n.T(" column number") +func (r *Review) cursorColumn() string { + r.result.After.Text = r.cursorScope() + i18n.T(" column number") return strconv.Itoa(r.x + 1) } diff --git a/internal/review/cursor_line.go b/internal/review/cursor_line.go index 5b745573..7c5b5df7 100644 --- a/internal/review/cursor_line.go +++ b/internal/review/cursor_line.go @@ -9,7 +9,7 @@ import ( "git.stormux.org/storm/fenrir/internal/i18n" ) -func (r *Review) cursor_line() string { - r.result.After.Text = r.cursor_scope() + i18n.T(" line number") +func (r *Review) cursorLine() string { + r.result.After.Text = r.cursorScope() + i18n.T(" line number") return strconv.Itoa(r.y + 1) } diff --git a/internal/review/cursor_scope.go b/internal/review/cursor_scope.go index de7a461b..549d5f2c 100644 --- a/internal/review/cursor_scope.go +++ b/internal/review/cursor_scope.go @@ -5,7 +5,7 @@ package review import "git.stormux.org/storm/fenrir/internal/i18n" -func (r *Review) cursor_scope() string { +func (r *Review) cursorScope() string { if r.reviewing { return i18n.T(" review cursor ") } diff --git a/internal/review/follow_cursor.go b/internal/review/follow_cursor.go index 89627149..beedd026 100644 --- a/internal/review/follow_cursor.go +++ b/internal/review/follow_cursor.go @@ -25,12 +25,12 @@ func (r *Review) followCursor() string { if !r.reviewing { return i18n.T("Not in Review Mode") } - r.Resume_tracking() + r.ResumeTracking() return i18n.T("Exiting Review Mode") } -// Resume_tracking silently returns review ownership to the application cursor. -func (r *Review) Resume_tracking() { +// ResumeTracking silently returns review ownership to the application cursor. +func (r *Review) ResumeTracking() { r.reviewing = false r.x, r.y = r.screen.X, r.screen.Y } diff --git a/internal/review/indentation.go b/internal/review/indentation.go index ba970bdb..2b2fe471 100644 --- a/internal/review/indentation.go +++ b/internal/review/indentation.go @@ -12,5 +12,5 @@ func (r *Review) Indentation() (int, bool) { if !r.ready { return 0, false } - return presentation.Indentation_level(r.screen.Line(r.y)) + return presentation.IndentationLevel(r.screen.Line(r.y)) } diff --git a/internal/review/line_from_cursor.go b/internal/review/line_from_cursor.go index cb946d09..1df16d0c 100644 --- a/internal/review/line_from_cursor.go +++ b/internal/review/line_from_cursor.go @@ -3,7 +3,7 @@ package review -func (r *Review) line_from_cursor() string { - r.result.After.Text = r.cursor_scope() - return r.screen_range(r.y*r.screen.Cols+r.x, (r.y+1)*r.screen.Cols) +func (r *Review) lineFromCursor() string { + r.result.After.Text = r.cursorScope() + return r.screenRange(r.y*r.screen.Cols+r.x, (r.y+1)*r.screen.Cols) } diff --git a/internal/review/line_to_cursor.go b/internal/review/line_to_cursor.go index b23ddff2..df6d5818 100644 --- a/internal/review/line_to_cursor.go +++ b/internal/review/line_to_cursor.go @@ -3,7 +3,7 @@ package review -func (r *Review) line_to_cursor() string { - r.result.After.Text = r.cursor_scope() - return r.screen_range(r.y*r.screen.Cols, r.y*r.screen.Cols+r.x) +func (r *Review) lineToCursor() string { + r.result.After.Text = r.cursorScope() + return r.screenRange(r.y*r.screen.Cols, r.y*r.screen.Cols+r.x) } diff --git a/internal/review/marks.go b/internal/review/marks.go index 5e6bf7e3..07069fbe 100644 --- a/internal/review/marks.go +++ b/internal/review/marks.go @@ -25,12 +25,12 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func (r *Review) Set_mark() presentation.Message { +func (r *Review) SetMark() presentation.Message { if !r.ready || !r.reviewing { return presentation.Message{Text: i18n.T("no review cursor")} } if r.tableMode { - return r.set_table_headers() + return r.setTableHeaders() } point := r.y*r.screen.Cols + r.x cue := presentation.PlaceStartMark @@ -43,7 +43,7 @@ func (r *Review) Set_mark() presentation.Message { return presentation.Message{Text: i18n.T("set mark"), Cue: cue} } -func (r *Review) Clear_marks() { +func (r *Review) ClearMarks() { r.markCount = 0 if r.tableMode { r.tableHeaders = nil @@ -53,10 +53,10 @@ func (r *Review) Clear_marks() { } } -// Marked_region is rectangular, unlike clipboard selection. A single mark +// MarkedRegion is rectangular, unlike clipboard selection. A single mark // optionally selects the rest of its physical row. Table header marks never // enter markCount and cannot accidentally become reading regions. -func (r *Review) Marked_region(singleLine bool) (screen.Region, bool) { +func (r *Review) MarkedRegion(singleLine bool) (screen.Region, bool) { if !r.ready || r.markCount == 0 || r.markCount < 2 && !singleLine { return screen.Region{}, false } @@ -68,9 +68,9 @@ func (r *Review) Marked_region(singleLine bool) (screen.Region, bool) { return screen.Region{Left: min(x1, x2), Top: min(y1, y2), Right: max(x1, x2), Bottom: max(y1, y2)}, true } -// Marked_text uses inclusive Unicode cell positions in either direction. Copy +// MarkedText uses inclusive Unicode cell positions in either direction. Copy // with one mark takes the current review cursor as its second endpoint. -func (r *Review) Marked_text(copying bool) (string, bool) { +func (r *Review) MarkedText(copying bool) (string, bool) { if !r.ready || r.markCount == 0 || !copying && r.markCount < 2 { return "", false } diff --git a/internal/review/marks_test.go b/internal/review/marks_test.go index a640e7ff..8e479b29 100644 --- a/internal/review/marks_test.go +++ b/internal/review/marks_test.go @@ -29,38 +29,38 @@ func TestMarksUnicodeReverseSingleMarkAndSessionRetirement(t *testing.T) { snapshot := screen.Snapshot{Active: true, Terminal: 1, Rows: 2, Cols: 5, Cells: []rune("é界abcnext ")} var review Review review.Update(snapshot) - if got := review.Set_mark(); got.Text != "no review cursor" { + if got := review.SetMark(); got.Text != "no review cursor" { t.Fatal(got) } review.Execute(command.CurrentChar) - if got := review.Set_mark(); got.Cue != presentation.PlaceStartMark { + if got := review.SetMark(); got.Cue != presentation.PlaceStartMark { t.Fatal(got) } review.Execute(command.NextChar) - if text, ok := review.Marked_text(true); !ok || text != "é界" { + if text, ok := review.MarkedText(true); !ok || text != "é界" { t.Fatal(text, ok) } - if _, ok := review.Marked_text(false); ok { + if _, ok := review.MarkedText(false); ok { t.Fatal("preview accepted one mark") } review.Execute(command.NextLine) - if got := review.Set_mark(); got.Cue != presentation.PlaceEndMark { + if got := review.SetMark(); got.Cue != presentation.PlaceEndMark { t.Fatal(got) } - if text, ok := review.Marked_text(false); !ok || text != "é界abc\nne" { + if text, ok := review.MarkedText(false); !ok || text != "é界abc\nne" { t.Fatal(text, ok) } - review.Clear_marks() - review.Set_mark() + review.ClearMarks() + review.SetMark() review.Execute(command.Top) review.Execute(command.LineStart) - review.Set_mark() - if text, ok := review.Marked_text(false); !ok || text != "é界abc\nne" { + review.SetMark() + if text, ok := review.MarkedText(false); !ok || text != "é界abc\nne" { t.Fatal("reverse selection", text, ok) } snapshot.Generation++ review.Update(snapshot) - if _, ok := review.Marked_text(true); ok { + if _, ok := review.MarkedText(true); ok { t.Fatal("marks survived screen replacement") } } diff --git a/internal/review/navigation.go b/internal/review/navigation.go index e45c3e84..255f4005 100644 --- a/internal/review/navigation.go +++ b/internal/review/navigation.go @@ -8,7 +8,7 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func (r *Review) screen_boundary(forward bool) string { +func (r *Review) screenBoundary(forward bool) string { if r.suppressScreenBoundary { return "" } @@ -20,30 +20,30 @@ func (r *Review) screen_boundary(forward bool) string { return i18n.T("start of screen") } -func (r *Review) line_break() { +func (r *Review) lineBreak() { if !r.suppressLineBreak { r.result.After.Text, r.result.After.Cue = i18n.T("line break"), presentation.LineEnd } } -func (r *Review) move_character(forward bool) string { +func (r *Review) moveCharacter(forward bool) string { if forward { if r.x == r.screen.Cols-1 { if r.y == r.screen.Rows-1 { - return r.screen_boundary(true) + return r.screenBoundary(true) } r.x, r.y = 0, r.y+1 - r.line_break() + r.lineBreak() } else { r.x++ } } else { if r.x == 0 { if r.y == 0 { - return r.screen_boundary(false) + return r.screenBoundary(false) } r.x, r.y = r.screen.Cols-1, r.y-1 - r.line_break() + r.lineBreak() } else { r.x-- } diff --git a/internal/review/navigation_test.go b/internal/review/navigation_test.go index 21a40b8e..1964dc3d 100644 --- a/internal/review/navigation_test.go +++ b/internal/review/navigation_test.go @@ -137,9 +137,9 @@ func TestReviewLineEndpointsAndTopBottom(t *testing.T) { func TestTableBoundaryContextAndModeSynchronization(t *testing.T) { var r Review r.Update(fixture("Name|Subject|Empty", "José|É!|")) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.CurrentWord) - r.Set_mark() + r.SetMark() r.Execute(command.NextLine) for _, trial := range []struct { id command.ID @@ -172,9 +172,9 @@ func TestTableBoundaryContextAndModeSynchronization(t *testing.T) { t.Fatal("Bottom kept old table column", got) } r.Execute(command.FollowCursor) - r.Set_table_mode(false) + r.SetTableMode(false) r.Execute(command.LineEnd) - r.Set_table_mode(true) + r.SetTableMode(true) if got := r.Execute(command.CurrentWord).Text; got != "Empty Column 3" { t.Fatal("mode change did not resynchronize", got) } @@ -186,9 +186,9 @@ func TestReviewScreenChangePolicyAndClamping(t *testing.T) { r.Configure(true, true, leave) s := fixture("header|value", "data|cell") r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.CurrentWord) - r.Set_mark() + r.SetMark() r.Execute(command.Bottom) r.Execute(command.LineEnd) s.Terminal++ diff --git a/internal/review/next_character.go b/internal/review/next_character.go index 20e97275..fb8cb27b 100644 --- a/internal/review/next_character.go +++ b/internal/review/next_character.go @@ -18,5 +18,5 @@ package review func (r *Review) nextCharacter() string { - return r.move_character(true) + return r.moveCharacter(true) } diff --git a/internal/review/next_line.go b/internal/review/next_line.go index 9e45285e..8965b68a 100644 --- a/internal/review/next_line.go +++ b/internal/review/next_line.go @@ -19,8 +19,8 @@ package review func (r *Review) nextLine() string { if r.y == r.screen.Rows-1 { - return r.screen_boundary(true) + return r.screenBoundary(true) } r.y++ - return r.line_text() + return r.lineText() } diff --git a/internal/review/phonetic_character.go b/internal/review/phonetic_character.go index e111875a..79e98921 100644 --- a/internal/review/phonetic_character.go +++ b/internal/review/phonetic_character.go @@ -5,4 +5,4 @@ package review import "git.stormux.org/storm/fenrir/internal/command" -func (r *Review) phonetic_character() string { return r.spelling_text(command.CurrentChar, true) } +func (r *Review) phoneticCharacter() string { return r.spellingText(command.CurrentChar, true) } diff --git a/internal/review/phonetic_line.go b/internal/review/phonetic_line.go index 803ad78a..6e640f82 100644 --- a/internal/review/phonetic_line.go +++ b/internal/review/phonetic_line.go @@ -5,4 +5,4 @@ package review import "git.stormux.org/storm/fenrir/internal/command" -func (r *Review) phonetic_line() string { return r.spelling_text(command.CurrentLine, true) } +func (r *Review) phoneticLine() string { return r.spellingText(command.CurrentLine, true) } diff --git a/internal/review/phonetic_word.go b/internal/review/phonetic_word.go index 57988296..4a0b9a0b 100644 --- a/internal/review/phonetic_word.go +++ b/internal/review/phonetic_word.go @@ -5,4 +5,4 @@ package review import "git.stormux.org/storm/fenrir/internal/command" -func (r *Review) phonetic_word() string { return r.spelling_text(command.CurrentWord, true) } +func (r *Review) phoneticWord() string { return r.spellingText(command.CurrentWord, true) } diff --git a/internal/review/previous_character.go b/internal/review/previous_character.go index 46bada6a..e0f99cbb 100644 --- a/internal/review/previous_character.go +++ b/internal/review/previous_character.go @@ -18,5 +18,5 @@ package review func (r *Review) previousCharacter() string { - return r.move_character(false) + return r.moveCharacter(false) } diff --git a/internal/review/previous_line.go b/internal/review/previous_line.go index 17c0bd42..25ed325d 100644 --- a/internal/review/previous_line.go +++ b/internal/review/previous_line.go @@ -19,8 +19,8 @@ package review func (r *Review) previousLine() string { if r.y == 0 { - return r.screen_boundary(false) + return r.screenBoundary(false) } r.y-- - return r.line_text() + return r.lineText() } diff --git a/internal/review/review.go b/internal/review/review.go index 7160af0e..056ac46e 100644 --- a/internal/review/review.go +++ b/internal/review/review.go @@ -55,23 +55,23 @@ func (r *Review) Configure(lineBreak, endOfScreen, leaveOnScreenChange bool) { // handlers is the explicit list of review actions. Add an action file and an // entry here; input bindings live separately in package input. var handlers = map[command.ID]func(*Review) string{ - command.AttributeCursor: (*Review).attribute_cursor, - command.CursorLine: (*Review).cursor_line, - command.CursorColumn: (*Review).cursor_column, - command.LineToCursor: (*Review).line_to_cursor, - command.LineFromCursor: (*Review).line_from_cursor, - command.ScreenFirstChar: (*Review).screen_first_character, - command.ScreenLastChar: (*Review).screen_last_character, - command.ScreenBeforeCursor: (*Review).screen_before_cursor, - command.ScreenAfterCursor: (*Review).screen_after_cursor, - command.ReviewUp: (*Review).review_up, - command.ReviewDown: (*Review).review_down, + command.AttributeCursor: (*Review).attributeCursor, + command.CursorLine: (*Review).cursorLine, + command.CursorColumn: (*Review).cursorColumn, + command.LineToCursor: (*Review).lineToCursor, + command.LineFromCursor: (*Review).lineFromCursor, + command.ScreenFirstChar: (*Review).screenFirstCharacter, + command.ScreenLastChar: (*Review).screenLastCharacter, + command.ScreenBeforeCursor: (*Review).screenBeforeCursor, + command.ScreenAfterCursor: (*Review).screenAfterCursor, + command.ReviewUp: (*Review).reviewUp, + command.ReviewDown: (*Review).reviewDown, - command.SpellWord: (*Review).spell_word, - command.PhoneticWord: (*Review).phonetic_word, - command.SpellLine: (*Review).spell_line, - command.PhoneticLine: (*Review).phonetic_line, - command.PhoneticChar: (*Review).phonetic_character, + command.SpellWord: (*Review).spellWord, + command.PhoneticWord: (*Review).phoneticWord, + command.SpellLine: (*Review).spellLine, + command.PhoneticLine: (*Review).phoneticLine, + command.PhoneticChar: (*Review).phoneticCharacter, command.PreviousLine: (*Review).previousLine, command.CurrentLine: (*Review).currentLine, command.NextLine: (*Review).nextLine, @@ -100,7 +100,7 @@ func (r *Review) Update(next screen.Snapshot) bool { r.screen = next r.ready = next.Active if switched { - r.Clear_marks() + r.ClearMarks() r.tableHeaders = nil r.tableLayout = tableLayout{} r.tableManual, r.tableAutoDisabled = false, false @@ -118,7 +118,7 @@ func (r *Review) Update(next screen.Snapshot) bool { } r.x, r.y = max(0, min(r.x, next.Cols-1)), max(0, min(r.y, next.Rows-1)) if r.tableMode && (switched || !r.reviewing) { - r.sync_table_column() + r.syncTableColumn() } return switched } @@ -149,12 +149,12 @@ func (r *Review) execute(id command.ID) string { // Reports use the active cursor without entering detached review. default: if !r.reviewing { - r.start_table_review() + r.startTableReview() } r.reviewing = true } if r.tableMode { - if text, handled := r.table_command(id); handled { + if text, handled := r.tableCommand(id); handled { return text } } diff --git a/internal/review/review_down.go b/internal/review/review_down.go index b2a5a649..053036d7 100644 --- a/internal/review/review_down.go +++ b/internal/review/review_down.go @@ -3,6 +3,6 @@ package review -func (r *Review) review_down() string { - return r.vertical_character(1) +func (r *Review) reviewDown() string { + return r.verticalCharacter(1) } diff --git a/internal/review/review_up.go b/internal/review/review_up.go index 08d2ffc9..2565d003 100644 --- a/internal/review/review_up.go +++ b/internal/review/review_up.go @@ -3,6 +3,6 @@ package review -func (r *Review) review_up() string { - return r.vertical_character(-1) +func (r *Review) reviewUp() string { + return r.verticalCharacter(-1) } diff --git a/internal/review/screen_after_cursor.go b/internal/review/screen_after_cursor.go index 418242d0..6574d31e 100644 --- a/internal/review/screen_after_cursor.go +++ b/internal/review/screen_after_cursor.go @@ -17,6 +17,6 @@ package review -func (r *Review) screen_after_cursor() string { - return r.screen_range(r.y*r.screen.Cols+r.x, r.screen.Rows*r.screen.Cols) +func (r *Review) screenAfterCursor() string { + return r.screenRange(r.y*r.screen.Cols+r.x, r.screen.Rows*r.screen.Cols) } diff --git a/internal/review/screen_before_cursor.go b/internal/review/screen_before_cursor.go index 34c68991..0f399f56 100644 --- a/internal/review/screen_before_cursor.go +++ b/internal/review/screen_before_cursor.go @@ -17,6 +17,6 @@ package review -func (r *Review) screen_before_cursor() string { - return r.screen_range(0, r.y*r.screen.Cols+r.x+1) +func (r *Review) screenBeforeCursor() string { + return r.screenRange(0, r.y*r.screen.Cols+r.x+1) } diff --git a/internal/review/screen_first_character.go b/internal/review/screen_first_character.go index f03c52c1..336b068d 100644 --- a/internal/review/screen_first_character.go +++ b/internal/review/screen_first_character.go @@ -5,10 +5,10 @@ package review import "git.stormux.org/storm/fenrir/internal/i18n" -func (r *Review) screen_first_character() string { +func (r *Review) screenFirstCharacter() string { r.x, r.y = 0, 0 if r.tableMode { - r.sync_table_column() + r.syncTableColumn() } return r.currentCharacter() + " " + i18n.T("first character in screen") } diff --git a/internal/review/screen_last_character.go b/internal/review/screen_last_character.go index 60c481e8..fbd2f3bd 100644 --- a/internal/review/screen_last_character.go +++ b/internal/review/screen_last_character.go @@ -5,10 +5,10 @@ package review import "git.stormux.org/storm/fenrir/internal/i18n" -func (r *Review) screen_last_character() string { +func (r *Review) screenLastCharacter() string { r.x, r.y = r.screen.Cols-1, r.screen.Rows-1 if r.tableMode { - r.sync_table_column() + r.syncTableColumn() } return r.currentCharacter() + " " + i18n.T("last character in screen") } diff --git a/internal/review/screen_range.go b/internal/review/screen_range.go index 39672bab..9a01d63b 100644 --- a/internal/review/screen_range.go +++ b/internal/review/screen_range.go @@ -24,9 +24,9 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -// screen_range reads a half-open range of screen cells, retaining row breaks +// screenRange reads a half-open range of screen cells, retaining row breaks // and indentation while omitting terminal padding. It never moves either cursor. -func (r *Review) screen_range(start, end int) string { +func (r *Review) screenRange(start, end int) string { var lines []string for start < end { rowEnd := min((start/r.screen.Cols+1)*r.screen.Cols, end) diff --git a/internal/review/screen_range_test.go b/internal/review/screen_range_test.go index 652258c2..e06b9c9d 100644 --- a/internal/review/screen_range_test.go +++ b/internal/review/screen_range_test.go @@ -79,8 +79,8 @@ func TestScreenRangesPreferDetachedReviewAndKeepTableScope(t *testing.T) { snapshot.X, snapshot.Y = 7, 0 review.Update(snapshot) review.Execute(command.CurrentChar) - review.Set_mark() - review.Set_table_mode(true) + review.SetMark() + review.SetTableMode(true) review.Execute(command.NextLine) // Application cursor moves while detached review stays on the second row. snapshot.X, snapshot.Y = 0, 2 diff --git a/internal/review/spell_line.go b/internal/review/spell_line.go index d5aa4efe..aa501d35 100644 --- a/internal/review/spell_line.go +++ b/internal/review/spell_line.go @@ -5,4 +5,4 @@ package review import "git.stormux.org/storm/fenrir/internal/command" -func (r *Review) spell_line() string { return r.spelling_text(command.CurrentLine, false) } +func (r *Review) spellLine() string { return r.spellingText(command.CurrentLine, false) } diff --git a/internal/review/spell_word.go b/internal/review/spell_word.go index d111032e..58a19613 100644 --- a/internal/review/spell_word.go +++ b/internal/review/spell_word.go @@ -5,4 +5,4 @@ package review import "git.stormux.org/storm/fenrir/internal/command" -func (r *Review) spell_word() string { return r.spelling_text(command.CurrentWord, false) } +func (r *Review) spellWord() string { return r.spellingText(command.CurrentWord, false) } diff --git a/internal/review/spellcheck.go b/internal/review/spellcheck.go index 812add57..ec929b32 100644 --- a/internal/review/spellcheck.go +++ b/internal/review/spellcheck.go @@ -3,9 +3,9 @@ package review -func (r *Review) Spellcheck_word() string { +func (r *Review) SpellcheckWord() string { if !r.ready || r.screen.Cols <= 0 || len(r.screen.Cells) == 0 { return "" } - return r.raw_word() + return r.rawWord() } diff --git a/internal/review/spelling.go b/internal/review/spelling.go index c61ecab7..21ceec5a 100644 --- a/internal/review/spelling.go +++ b/internal/review/spelling.go @@ -11,10 +11,10 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func (r *Review) spelling_text(scope command.ID, phonetic bool) string { +func (r *Review) spellingText(scope command.ID, phonetic bool) string { var text string if r.tableMode && scope != command.CurrentLine { - cells := r.current_table_cells() + cells := r.currentTableCells() if len(cells) == 0 || r.tableColumn >= len(cells) { return i18n.T("no table data") } @@ -34,7 +34,7 @@ func (r *Review) spelling_text(scope command.ID, phonetic bool) string { case command.CurrentLine: text = r.screen.Text(r.y) case command.CurrentWord: - text = r.raw_word() + text = r.rawWord() case command.CurrentChar: text = string(r.screen.Line(r.y)[r.x]) } diff --git a/internal/review/spelling_test.go b/internal/review/spelling_test.go index 9332993a..59f2cb3e 100644 --- a/internal/review/spelling_test.go +++ b/internal/review/spelling_test.go @@ -77,9 +77,9 @@ func TestTableSpellingKeepsCellScopeAndExcludesHeaders(t *testing.T) { var review Review snapshot := fixture("Name|Subject|Empty", "Same|A book!||Tail") review.Update(snapshot) - review.Set_table_mode(true) + review.SetTableMode(true) review.Execute(command.CurrentWord) - review.Set_mark() + review.SetMark() review.Execute(command.NextLine) review.Execute(command.NextWord) if got := review.Execute(command.CurrentWord).Text; got != "A book! Subject" { diff --git a/internal/review/table.go b/internal/review/table.go index 16f27b00..82e4c6a6 100644 --- a/internal/review/table.go +++ b/internal/review/table.go @@ -33,7 +33,7 @@ type TableCell struct { // Match Python's delimiter preference and two-or-more-space aligned columns. // Bounds come directly from screen positions, never byte offsets or searches // for cell text (which can repeat within a row). -func table_cells(line []rune) []TableCell { +func tableCells(line []rune) []TableCell { end := len(line) for end > 0 && (line[end-1] == ' ' || line[end-1] == 0) { end-- @@ -41,7 +41,7 @@ func table_cells(line []rune) []TableCell { if end == 0 { return nil } - separator := table_separator(line[:end]) + separator := tableSeparator(line[:end]) var cells []TableCell appendCell := func(start, end int) { for start < end && unicode.IsSpace(line[start]) { @@ -80,7 +80,7 @@ func table_cells(line []rune) []TableCell { return cells } -func (r *Review) Set_table_mode(enabled bool) { +func (r *Review) SetTableMode(enabled bool) { if r.tableMode == enabled { return } @@ -89,12 +89,12 @@ func (r *Review) Set_table_mode(enabled bool) { r.tableLayout = tableLayout{} r.tableManual, r.tableAutoDisabled = false, false if enabled && r.ready { - r.sync_table_column() + r.syncTableColumn() } } -func (r *Review) sync_table_column() { - cells := r.current_table_cells() +func (r *Review) syncTableColumn() { + cells := r.currentTableCells() r.tableColumn = 0 for index, cell := range cells { if r.x < cell.start { @@ -104,7 +104,7 @@ func (r *Review) sync_table_column() { } } -func (r *Review) column_header() string { +func (r *Review) columnHeader() string { if r.tableColumn < len(r.tableHeaders) && r.tableHeaders[r.tableColumn] != "" { return r.tableHeaders[r.tableColumn] } @@ -112,17 +112,17 @@ func (r *Review) column_header() string { return "Column " + strconv.Itoa(r.tableColumn+1) } -func (r *Review) table_cell_text(cells []TableCell) string { +func (r *Review) tableCellText(cells []TableCell) string { cell := cells[r.tableColumn] text := string(r.screen.Line(r.y)[cell.start:cell.end]) if text == "" { text = i18n.T("blank") } - return text + " " + r.column_header() + return text + " " + r.columnHeader() } -func (r *Review) set_table_headers() presentation.Message { - layout := r.layout_at(r.y) +func (r *Review) setTableHeaders() presentation.Message { + layout := r.layoutAt(r.y) cells := layout.cells(r.screen.Line(r.y)) if len(cells) == 0 { return presentation.Message{Text: i18n.T("could not set header row")} @@ -135,14 +135,14 @@ func (r *Review) set_table_headers() presentation.Message { return presentation.Message{Text: i18n.T("header row set"), Cue: presentation.PlaceStartMark} } -func (r *Review) table_command(id command.ID) (string, bool) { +func (r *Review) tableCommand(id command.ID) (string, bool) { switch id { case command.CurrentWord, command.PreviousWord, command.NextWord, command.LineStart, command.LineEnd, command.CurrentChar, command.PreviousChar, command.NextChar, command.FirstText, command.LastText: default: return "", false } - cells := r.current_table_cells() + cells := r.currentTableCells() if len(cells) == 0 { return i18n.T("no table data"), true } @@ -156,7 +156,7 @@ func (r *Review) table_command(id command.ID) (string, bool) { } switch id { case command.CurrentWord: - return r.table_cell_text(cells), true + return r.tableCellText(cells), true case command.PreviousWord, command.NextWord, command.LineStart, command.LineEnd: boundary := "" switch id { @@ -180,7 +180,7 @@ func (r *Review) table_command(id command.ID) (string, bool) { r.tableColumn = len(cells) - 1 } r.x = min(cells[r.tableColumn].start, r.screen.Cols-1) - text := r.table_cell_text(cells) + text := r.tableCellText(cells) if boundary != "" { r.result.After.Text = boundary } else if id == command.LineStart { @@ -218,10 +218,10 @@ func (r *Review) table_command(id command.ID) (string, bool) { r.x++ case command.FirstText: r.x = first - return character() + " " + i18n.Format("first character in cell {0}", r.column_header()), true + return character() + " " + i18n.Format("first character in cell {0}", r.columnHeader()), true case command.LastText: r.x = last - return character() + " " + i18n.Format("last character in cell {0}", r.column_header()), true + return character() + " " + i18n.Format("last character in cell {0}", r.columnHeader()), true } return character(), true } diff --git a/internal/review/table_layout.go b/internal/review/table_layout.go index 2d039dde..5817e6eb 100644 --- a/internal/review/table_layout.go +++ b/internal/review/table_layout.go @@ -15,7 +15,7 @@ type tableLayout struct { breaks []int } -func table_separator(line []rune) rune { +func tableSeparator(line []rune) rune { for _, candidate := range []rune{',', '|', ';', '\t'} { if strings.ContainsRune(string(line), candidate) { return candidate @@ -24,7 +24,7 @@ func table_separator(line []rune) rune { return 0 } -func table_trim_cell(line []rune, start, end int) TableCell { +func tableTrimCell(line []rune, start, end int) TableCell { for start < end && (unicode.IsSpace(line[start]) || line[start] == 0) { start++ } @@ -43,29 +43,29 @@ func (layout tableLayout) cells(line []rune) []TableCell { start := 0 for index, value := range line { if value == layout.separator { - cells = append(cells, table_trim_cell(line, start, index)) + cells = append(cells, tableTrimCell(line, start, index)) start = index + 1 } } - return append(cells, table_trim_cell(line, start, len(line))) + return append(cells, tableTrimCell(line, start, len(line))) } if len(layout.breaks) == 0 { - return table_cells(line) + return tableCells(line) } var cells []TableCell start := 0 for _, boundary := range layout.breaks { boundary = min(boundary, len(line)) - cells = append(cells, table_trim_cell(line, start, boundary)) + cells = append(cells, tableTrimCell(line, start, boundary)) start = boundary } - return append(cells, table_trim_cell(line, start, len(line))) + return append(cells, tableTrimCell(line, start, len(line))) } // Shared whitespace gutters separate aligned columns, including single-space // gutters. A gutter needs text after it in the heading and at least one data // row, so spaces inside "Mounted on" do not split an empty data tail. -func aligned_table_layout(header []rune, rows ...[]rune) tableLayout { +func alignedTableLayout(header []rune, rows ...[]rune) tableLayout { var layout tableLayout width := len(header) for _, data := range rows { @@ -92,10 +92,10 @@ func aligned_table_layout(header []rune, rows ...[]rune) tableLayout { } before, after := false, false for _, data := range rows { - before = before || table_trim_cell(data, 0, start).start != start - after = after || table_trim_cell(data, index, width).start != width + before = before || tableTrimCell(data, 0, start).start != start + after = after || tableTrimCell(data, index, width).start != width } - if !before || !after || table_trim_cell(header, index, width).start == width { + if !before || !after || tableTrimCell(header, index, width).start == width { continue } layout.breaks = append(layout.breaks, (start+index)/2) @@ -103,9 +103,9 @@ func aligned_table_layout(header []rune, rows ...[]rune) tableLayout { return layout } -func (r *Review) layout_at(row int) tableLayout { +func (r *Review) layoutAt(row int) tableLayout { header := r.screen.Line(row) - separator := table_separator(header) + separator := tableSeparator(header) if separator != 0 { return tableLayout{separator: separator} } @@ -113,42 +113,42 @@ func (r *Review) layout_at(row int) tableLayout { rows := [][]rune{r.screen.Line(row + 1)} // Include subsequent numeric rows when inferring gutters: longer names // and values must not cross a boundary inferred from a shorter row. - if table_numeric_fields(rows[0]) >= 2 { + if tableNumericFields(rows[0]) >= 2 { for next := row + 2; next < r.screen.Rows; next++ { line := r.screen.Line(next) - if table_numeric_fields(line) == 0 { + if tableNumericFields(line) == 0 { break } rows = append(rows, line) } } - return aligned_table_layout(header, rows...) + return alignedTableLayout(header, rows...) } return tableLayout{} } -func table_numeric(text string) bool { +func tableNumeric(text string) bool { text = strings.TrimSpace(text) text = strings.TrimLeft(text, "+-~<>") return len(text) > 0 && text[0] >= '0' && text[0] <= '9' } -func table_numeric_fields(line []rune) int { +func tableNumericFields(line []rune) int { numbers := 0 for _, field := range strings.Fields(string(line)) { - if table_numeric(field) { + if tableNumeric(field) { numbers++ } } return numbers } -func table_evidence(line []rune, cells []TableCell) (labels, numbers int) { +func tableEvidence(line []rune, cells []TableCell) (labels, numbers int) { for _, cell := range cells { text := string(line[cell.start:cell.end]) if text != "" { labels++ - if table_numeric(text) { + if tableNumeric(text) { numbers++ } } @@ -160,15 +160,15 @@ func table_evidence(line []rune, cells []TableCell) (labels, numbers int) { // textual heading followed by several numeric fields avoids treating the shell // prompt, command echo, ordinary prose, or headerless numeric data as headers. // Text-only tables remain available through explicit header selection. -func (r *Review) current_table_cells() []TableCell { +func (r *Review) currentTableCells() []TableCell { line := r.screen.Line(r.y) if r.tableManual { return r.tableLayout.cells(line) } r.tableHeaders = nil - layout, headerRow, ok := r.automatic_table_at(r.y) + layout, headerRow, ok := r.automaticTableAt(r.y) if !ok { - return table_cells(line) + return tableCells(line) } if !r.tableAutoDisabled { header := r.screen.Line(headerRow) @@ -180,31 +180,31 @@ func (r *Review) current_table_cells() []TableCell { } // Locate the visible table containing a row without changing review state. -func (r *Review) automatic_table_at(targetRow int) (tableLayout, int, bool) { +func (r *Review) automaticTableAt(targetRow int) (tableLayout, int, bool) { line := r.screen.Line(targetRow) for row := targetRow; row >= 0; row-- { header := r.screen.Line(row) if strings.Trim(string(header), " \x00\t\r") == "" { break } - if row+1 >= r.screen.Rows || table_numeric_fields(header) > 0 { + if row+1 >= r.screen.Rows || tableNumericFields(header) > 0 { continue } - layout := r.layout_at(row) + layout := r.layoutAt(row) cells := layout.cells(header) - labels, numbers := table_evidence(header, cells) + labels, numbers := tableEvidence(header, cells) if labels < 2 || numbers != 0 { continue } data := r.screen.Line(row + 1) dataCells := layout.cells(data) - _, numbers = table_evidence(data, dataCells) + _, numbers = tableEvidence(data, dataCells) if len(dataCells) != len(cells) || numbers < 2 { continue } current := layout.cells(line) if row != targetRow { - _, numbers = table_evidence(line, current) + _, numbers = tableEvidence(line, current) if numbers == 0 || len(current) != len(cells) { continue } @@ -212,7 +212,7 @@ func (r *Review) automatic_table_at(targetRow int) (tableLayout, int, bool) { for between := row + 1; between < targetRow; between++ { middle := r.screen.Line(between) middleCells := layout.cells(middle) - _, numbers = table_evidence(middle, middleCells) + _, numbers = tableEvidence(middle, middleCells) if numbers == 0 || len(middleCells) != len(cells) { contiguous = false break @@ -230,7 +230,7 @@ func (r *Review) automatic_table_at(targetRow int) (tableLayout, int, bool) { // Seed a new review at the first data cell of the table at, or immediately // above, the application cursor. Do this on entry rather than during Update: // detached review would otherwise suppress automatic reading of new output. -func (r *Review) start_table_review() { +func (r *Review) startTableReview() { if !r.tableMode || r.tableManual || r.tableAutoDisabled { return } @@ -238,7 +238,7 @@ func (r *Review) start_table_review() { if row < 0 || row >= r.screen.Rows { continue } - layout, headerRow, ok := r.automatic_table_at(row) + layout, headerRow, ok := r.automaticTableAt(row) if !ok || row == headerRow { continue } diff --git a/internal/review/table_layout_test.go b/internal/review/table_layout_test.go index 84bdf607..20643f9c 100644 --- a/internal/review/table_layout_test.go +++ b/internal/review/table_layout_test.go @@ -11,7 +11,7 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func table_fixture(lines ...string) screen.Snapshot { +func tableFixture(lines ...string) screen.Snapshot { width := 1 for _, line := range lines { width = max(width, len([]rune(line))) @@ -34,11 +34,11 @@ var freeTable = []string{ func TestTableFreeAutomaticAndManualHeaders(t *testing.T) { for _, manual := range []bool{false, true} { r := Review{} - r.Update(table_fixture(freeTable...)) - r.Set_table_mode(true) + r.Update(tableFixture(freeTable...)) + r.SetTableMode(true) r.Execute(command.CurrentLine) if manual { - r.Set_mark() + r.SetMark() } r.Execute(command.NextLine) for col, want := range []string{"Mem: Column 1", "31Gi total", "9.5Gi used", "9.7Gi free", "3.0Gi shared", "15Gi buff/cache", "21Gi available"} { @@ -96,13 +96,13 @@ func TestTableLinuxCommandLayouts(t *testing.T) { } { t.Run(trial.name, func(t *testing.T) { var r Review - s := table_fixture(trial.lines...) + s := tableFixture(trial.lines...) s.Y = 1 if trial.name == "vmstat" { s.Y = 2 } r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) for col, want := range trial.wants { id := command.CurrentWord if col != 0 { @@ -124,13 +124,13 @@ func TestTableLinuxCommandLayouts(t *testing.T) { func TestTableClearHeadersOverrideAndModeReset(t *testing.T) { var r Review - r.Update(table_fixture(freeTable...)) - r.Set_table_mode(true) + r.Update(tableFixture(freeTable...)) + r.SetTableMode(true) r.Execute(command.NextLine) if got := r.Execute(command.NextWord).Text; got != "31Gi total" { t.Fatal(got) } - r.Clear_marks() + r.ClearMarks() if got := r.Execute(command.CurrentWord).Text; got != "31Gi Column 2" { t.Fatal("clear reassigned headers", got) } @@ -143,16 +143,16 @@ func TestTableClearHeadersOverrideAndModeReset(t *testing.T) { r.Execute(command.LineStart) r.Execute(command.NextWord) r.Execute(command.PreviousLine) - if got := r.Set_mark().Text; got != "header row set" { + if got := r.SetMark().Text; got != "header row set" { t.Fatal(got) } r.Execute(command.NextLine) if got := r.Execute(command.CurrentWord).Text; got != "31Gi total" { t.Fatal("manual override after clear", got) } - r.Clear_marks() - r.Set_table_mode(false) - r.Set_table_mode(true) + r.ClearMarks() + r.SetTableMode(false) + r.SetTableMode(true) if got := r.Execute(command.CurrentWord).Text; got != "31Gi total" { t.Fatal("mode reset did not restore automatic headers", got) } @@ -166,10 +166,10 @@ func TestTableAutomaticHeadersStayInOutputBlock(t *testing.T) { {"Name Used Free", "one 12 34", "$ next", "56 78"}, } { var r Review - s := table_fixture(lines...) + s := tableFixture(lines...) s.Y = len(lines) - 1 r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.CurrentWord) if len(r.tableHeaders) != 0 { t.Fatal("guessed an unrelated header", lines, r.tableHeaders) @@ -179,13 +179,13 @@ func TestTableAutomaticHeadersStayInOutputBlock(t *testing.T) { func TestTableAutomaticHeadersFollowNewOutput(t *testing.T) { var r Review - after := table_fixture(append(append([]string{"$ free -h"}, freeTable...), "$ ")...) + after := tableFixture(append(append([]string{"$ free -h"}, freeTable...), "$ ")...) before := after before.Cells = []rune(strings.Repeat(" ", len(after.Cells))) copy(before.Cells, []rune("$ free -h")) before.Y = 1 r.Update(before) - r.Set_table_mode(true) + r.SetTableMode(true) after.Y = 4 r.Update(after) if got := r.Execute(command.CurrentWord).Text; got != "Mem: Column 1" { @@ -206,10 +206,10 @@ func TestTableAutomaticHeadersFollowNewOutput(t *testing.T) { func TestTableReviewLandingOnlyOnEntry(t *testing.T) { var r Review - s := table_fixture(append(append([]string{"$ free -h"}, freeTable...), "$ ")...) + s := tableFixture(append(append([]string{"$ free -h"}, freeTable...), "$ ")...) s.Y, s.X = 4, 2 r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) if got := r.Execute(command.CurrentWord).Text; got != "Mem: Column 1" || r.x != 0 || r.y != 2 || r.tableColumn != 0 { t.Fatal("wrong initial cell", got, r.x, r.y, r.tableColumn) } @@ -232,17 +232,17 @@ func TestTableReviewLandingGuards(t *testing.T) { if trial == "unrelated output" { lines = append(lines[:3], "unrelated output", "$ ") } - s := table_fixture(lines...) + s := tableFixture(lines...) s.Y = len(lines) - 1 r.Update(s) - r.Set_table_mode(trial != "cursor" && trial != "highlight") + r.SetTableMode(trial != "cursor" && trial != "highlight") if trial == "cleared" { - r.Clear_marks() + r.ClearMarks() } if trial == "manual" { r.Execute(command.Top) - r.Set_mark() - r.Resume_tracking() + r.SetMark() + r.ResumeTracking() } r.Execute(command.CurrentWord) if r.y != s.Y { @@ -254,10 +254,10 @@ func TestTableReviewLandingGuards(t *testing.T) { func TestTableReviewLandingFindsLatestOutput(t *testing.T) { var r Review - s := table_fixture("Name|Used|Free", "old|12|34", "$ next", "Name|Used|Free", "new|56|78", "$ ") + s := tableFixture("Name|Used|Free", "old|12|34", "$ next", "Name|Used|Free", "new|56|78", "$ ") s.Y = 5 r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) if got := r.Execute(command.CurrentWord).Text; got != "new Name" || r.y != 4 { t.Fatal("landed on an older table", got, r.y) } @@ -265,32 +265,32 @@ func TestTableReviewLandingFindsLatestOutput(t *testing.T) { func TestTableManualHeadersOverrideAutomaticAndClear(t *testing.T) { var r Review - r.Update(table_fixture("Name|Used|Free", "example|12|34", "Custom|First|Second", "other||56")) - r.Set_table_mode(true) + r.Update(tableFixture("Name|Used|Free", "example|12|34", "Custom|First|Second", "other||56")) + r.SetTableMode(true) r.Execute(command.NextLine) if got := r.Execute(command.NextWord).Text; got != "12 Used" { t.Fatal(got) } r.Execute(command.NextLine) - r.Set_mark() + r.SetMark() r.Execute(command.NextLine) if got := r.Execute(command.CurrentWord).Text; got != "blank First" { t.Fatal("manual headers did not replace automatic", got) } - r.Clear_marks() + r.ClearMarks() if got := r.Execute(command.CurrentWord).Text; got != "blank Column 2" { t.Fatal(got) } - r.Set_table_mode(false) - if got := r.Set_mark().Text; got != "set mark" { + r.SetTableMode(false) + if got := r.SetMark().Text; got != "set mark" { t.Fatal("ordinary marks broken", got) } } func TestTableEmptyInteriorFieldAndTextOnlyManualHeader(t *testing.T) { var r Review - r.Update(table_fixture("Name Used Free", "alpha 12 34", "beta 56")) - r.Set_table_mode(true) + r.Update(tableFixture("Name Used Free", "alpha 12 34", "beta 56")) + r.SetTableMode(true) r.Execute(command.NextLine) r.Execute(command.NextWord) r.Execute(command.NextLine) @@ -301,13 +301,13 @@ func TestTableEmptyInteriorFieldAndTextOnlyManualHeader(t *testing.T) { t.Fatal(got) } r = Review{} - r.Update(table_fixture("Name Description", "alpha two words")) - r.Set_table_mode(true) + r.Update(tableFixture("Name Description", "alpha two words")) + r.SetTableMode(true) r.Execute(command.CurrentWord) if len(r.tableHeaders) != 0 { t.Fatal("text-only headers should require selection") } - r.Set_mark() + r.SetMark() r.Execute(command.NextLine) if got := r.Execute(command.NextWord).Text; got != "two words Description" { t.Fatal("manual text-only table", got) @@ -318,19 +318,19 @@ func TestTableAutomaticHeaderSessionResetAndReplacement(t *testing.T) { for _, change := range []string{"terminal", "generation", "resize"} { t.Run(change, func(t *testing.T) { var r Review - s := table_fixture("Name|Used|Free", "example|12|34") + s := tableFixture("Name|Used|Free", "example|12|34") s.Y = 1 r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.NextWord) - r.Clear_marks() + r.ClearMarks() switch change { case "terminal": s.Terminal++ case "generation": s.Generation++ case "resize": - s = table_fixture("Name|Used|Free", "example|12|34", "") + s = tableFixture("Name|Used|Free", "example|12|34", "") s.Y = 1 } r.Update(s) diff --git a/internal/review/table_test.go b/internal/review/table_test.go index 0df3fdc4..05963276 100644 --- a/internal/review/table_test.go +++ b/internal/review/table_test.go @@ -27,8 +27,8 @@ import ( func TestTableHeadersColumnsCharactersAndMarks(t *testing.T) { r := Review{} r.Update(fixture("Name | Subject", "José | Hello world", "Other |", "", "Name | Subject")) - r.Set_table_mode(true) - if got := r.Set_mark(); got.Text != "no review cursor" { + r.SetTableMode(true) + if got := r.SetMark(); got.Text != "no review cursor" { t.Fatal("header command silently entered review", got) } check := func(id command.ID, want string) { @@ -38,10 +38,10 @@ func TestTableHeadersColumnsCharactersAndMarks(t *testing.T) { } } check(command.CurrentWord, "Name Column 1") - if got := r.Set_mark(); got.Text != "header row set" { + if got := r.SetMark(); got.Text != "header row set" { t.Fatal(got) } - if _, ok := r.Marked_text(true); ok { + if _, ok := r.MarkedText(true); ok { t.Fatal("header command created a clipboard mark") } check(command.NextLine, "José | Hello world") @@ -61,18 +61,18 @@ func TestTableHeadersColumnsCharactersAndMarks(t *testing.T) { check(command.CurrentWord, "blank Subject") check(command.NextLine, "blank") check(command.NextWord, "no table data") - if got := r.Set_mark(); got.Text != "could not set header row" { + if got := r.SetMark(); got.Text != "could not set header row" { t.Fatal(got) } // An empty row must not discard the selected column or stored headers. check(command.NextLine, "Name | Subject") check(command.CurrentWord, "Subject Subject") - r.Set_table_mode(false) + r.SetTableMode(false) check(command.CurrentWord, "Subject") - if got := r.Set_mark(); got.Text != "set mark" { + if got := r.SetMark(); got.Text != "set mark" { t.Fatal("ordinary clipboard marks did not return", got) } - r.Set_table_mode(true) + r.SetTableMode(true) check(command.CurrentWord, "Subject Column 2") } @@ -80,7 +80,7 @@ func TestTableRuneBoundsEmptyCellsAndShortRows(t *testing.T) { for _, text := range []string{"é,é,,界", "é|é||界", "é;é;;界", "é\té\t\t界", " é é 界 "} { r := Review{} r.Update(fixture(text, "short")) - r.Set_table_mode(true) + r.SetTableMode(true) if got := r.Execute(command.NextWord).Text; got != "é Column 2" { t.Fatal(text, got) } @@ -105,9 +105,9 @@ func TestTableSessionChangesClearHeadersAndPosition(t *testing.T) { r := Review{} s := fixture("Name|Subject", "é|hello") r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.CurrentWord) - r.Set_mark() + r.SetMark() r.Execute(command.NextWord) for _, next := range []screen.Snapshot{ {Terminal: s.Terminal}, @@ -129,14 +129,14 @@ func TestTableResumingTrackingPreservesHeaders(t *testing.T) { var r Review s := fixture("Name|Subject", "Sender|Hello") r.Update(s) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.CurrentWord) - r.Set_mark() + r.SetMark() if got := r.Execute(command.NextWord).Text; got != "Subject Subject" { t.Fatal(got) } s.X, s.Y = 1, 1 - r.Resume_tracking() + r.ResumeTracking() r.Update(s) if r.Active() { t.Fatal("table review retained the old position after cursor movement") diff --git a/internal/review/top.go b/internal/review/top.go index 8b0a4376..57ae6231 100644 --- a/internal/review/top.go +++ b/internal/review/top.go @@ -24,7 +24,7 @@ import ( func (r *Review) top() string { r.x, r.y = 0, 0 if r.tableMode { - r.sync_table_column() + r.syncTableColumn() } return i18n.T("Top") } diff --git a/internal/review/vertical_character.go b/internal/review/vertical_character.go index 23f1151c..607b3594 100644 --- a/internal/review/vertical_character.go +++ b/internal/review/vertical_character.go @@ -8,20 +8,20 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func (r *Review) vertical_character(direction int) string { +func (r *Review) verticalCharacter(direction int) string { nextRow := r.y + direction if nextRow < 0 { - return r.screen_boundary(false) + return r.screenBoundary(false) } if nextRow >= r.screen.Rows { - return r.screen_boundary(true) + return r.screenBoundary(true) } r.y = nextRow // Snapshots retain terminal padding, so a short or blank row need not // clamp the column. Table review also retains the selected cell: an // absolute column outside it must not read a neighbouring cell instead. if r.tableMode { - cells := r.current_table_cells() + cells := r.currentTableCells() if r.tableColumn >= len(cells) { return i18n.T("no table data") } diff --git a/internal/review/vertical_character_test.go b/internal/review/vertical_character_test.go index a9666194..2116f741 100644 --- a/internal/review/vertical_character_test.go +++ b/internal/review/vertical_character_test.go @@ -91,9 +91,9 @@ func TestVerticalCharacterScreenEdgesAndSessionReset(t *testing.T) { func TestVerticalCharacterTableScopeRetainsAbsoluteColumn(t *testing.T) { var r Review r.Update(fixture("Name|Subject", "é|long word", "wide label|other", "only", "x|", "Name|Subject")) - r.Set_table_mode(true) + r.SetTableMode(true) r.Execute(command.CurrentWord) - r.Set_mark() + r.SetMark() r.Execute(command.NextWord) for _, trial := range []struct { action command.ID @@ -118,7 +118,7 @@ func TestVerticalCharacterTableScopeRetainsAbsoluteColumn(t *testing.T) { if got := r.Execute(command.CurrentWord).Text; got != "Subject Subject" { t.Fatal("vertical review lost header or selected cell", got) } - r.Set_table_mode(false) + r.SetTableMode(false) if got := r.Execute(command.ReviewDown).Text; got != "g" { t.Fatal("ordinary review did not return", got) } diff --git a/internal/review/word.go b/internal/review/word.go index f10c88bf..e4fbb9b8 100644 --- a/internal/review/word.go +++ b/internal/review/word.go @@ -24,9 +24,9 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -// word_start selects the containing word, or searches backward through whitespace. +// wordStart selects the containing word, or searches backward through whitespace. // Coordinates are screen cells, so Unicode never becomes a byte offset. -func (r *Review) word_start(position int) (int, bool) { +func (r *Review) wordStart(position int) (int, bool) { s := r.screen for position >= 0 && unicode.IsSpace(s.Cells[position]) { position-- @@ -40,7 +40,7 @@ func (r *Review) word_start(position int) (int, bool) { return position, true } -func (r *Review) word_at(position int) string { +func (r *Review) wordAt(position int) string { s := r.screen line := s.Line(position / s.Cols) start, end := position%s.Cols, position%s.Cols @@ -50,7 +50,7 @@ func (r *Review) word_at(position int) string { return string(line[start:end]) } -func (r *Review) screen_blank() bool { +func (r *Review) screenBlank() bool { for _, char := range r.screen.Cells { if !unicode.IsSpace(char) { return false @@ -59,60 +59,60 @@ func (r *Review) screen_blank() bool { return true } -func (r *Review) blank_word() string { +func (r *Review) blankWord() string { r.result.Cue = presentation.Blank return i18n.T("blank") } func (r *Review) word() string { - if r.screen_blank() { - return r.blank_word() + if r.screenBlank() { + return r.blankWord() } - start, ok := r.word_start(r.y*r.screen.Cols + r.x) + start, ok := r.wordStart(r.y*r.screen.Cols + r.x) if !ok { - return r.screen_boundary(false) + return r.screenBoundary(false) } - return r.select_word(start) + return r.selectWord(start) } -// raw_word shares selection with spelling without moving the review cursor. -func (r *Review) raw_word() string { - start, ok := r.word_start(r.y*r.screen.Cols + r.x) +// rawWord shares selection with spelling without moving the review cursor. +func (r *Review) rawWord() string { + start, ok := r.wordStart(r.y*r.screen.Cols + r.x) if !ok { return "" } - return r.word_at(start) + return r.wordAt(start) } -func (r *Review) select_word(position int) string { +func (r *Review) selectWord(position int) string { if r.y != position/r.screen.Cols { - r.line_break() + r.lineBreak() } r.x, r.y = position%r.screen.Cols, position/r.screen.Cols - return r.word_at(position) + return r.wordAt(position) } func (r *Review) moveWord(forward bool) string { - if r.screen_blank() { - return r.blank_word() + if r.screenBlank() { + return r.blankWord() } s := r.screen position := r.y*s.Cols + r.x if !forward { - start, ok := r.word_start(position) + start, ok := r.wordStart(position) if !ok { - return r.screen_boundary(false) + return r.screenBoundary(false) } - previous, ok := r.word_start(start - 1) + previous, ok := r.wordStart(start - 1) if !ok { - return r.screen_boundary(false) + return r.screenBoundary(false) } - return r.select_word(previous) + return r.selectWord(previous) } for target := position + 1; target < s.Rows*s.Cols; target++ { if !unicode.IsSpace(s.Cells[target]) && (target%s.Cols == 0 || unicode.IsSpace(s.Cells[target-1])) { - return r.select_word(target) + return r.selectWord(target) } } - return r.screen_boundary(true) + return r.screenBoundary(true) } diff --git a/internal/screen/region.go b/internal/screen/region.go index b911800e..781ea51f 100644 --- a/internal/screen/region.go +++ b/internal/screen/region.go @@ -13,7 +13,7 @@ type Region struct { ToLineEnd bool } -func (r Region) Right_edge(cols int) int { +func (r Region) RightEdge(cols int) int { if r.ToLineEnd { return cols - 1 } @@ -21,11 +21,11 @@ func (r Region) Right_edge(cols int) int { } func (r Region) Contains(x, y, cols int) bool { - return x >= r.Left && x <= r.Right_edge(cols) && y >= r.Top && y <= r.Bottom + return x >= r.Left && x <= r.RightEdge(cols) && y >= r.Top && y <= r.Bottom } func (r Region) Text(s Snapshot) string { - right := r.Right_edge(s.Cols) + right := r.RightEdge(s.Cols) if r.Left > right || r.Top >= s.Rows { return "" } diff --git a/internal/screen/scroll.go b/internal/screen/scroll.go index 3c3d3f19..18648ce6 100644 --- a/internal/screen/scroll.go +++ b/internal/screen/scroll.go @@ -26,7 +26,7 @@ import ( // rows fixed. Suppress the longest contiguous shifted overlap, while leaving // every other changed row available for normal feedback. Partial overlaps // require two nonblank rows: a lone repeated label or a blank area is ambiguous. -func Scrolled_overlap(previous, next Snapshot) (bestStart, bestEnd int) { +func ScrolledOverlap(previous, next Snapshot) (bestStart, bestEnd int) { // Match a whole-screen scroll first, including sparse screens. Ignore // whitespace-only overlaps, which cannot establish that anything scrolled. firstText := slices.IndexFunc(next.Cells, func(cell rune) bool { return !unicode.IsSpace(cell) }) diff --git a/internal/scripts/discovery.go b/internal/scripts/discovery.go index 27282e9f..069295a6 100644 --- a/internal/scripts/discovery.go +++ b/internal/scripts/discovery.go @@ -60,7 +60,7 @@ func Paths(home, configured, bundled string) []string { return paths } -func Parse_filename(filename string) (Script, bool) { +func ParseFilename(filename string) (Script, bool) { if strings.HasPrefix(filename, ".") { return Script{}, false } @@ -75,7 +75,7 @@ func Parse_filename(filename string) (Script, bool) { keys := strings.Split(parts[len(parts)-1], "__+__") hasScript := false for _, key := range keys { - if !input.Valid_script_key(key) { + if !input.ValidScriptKey(key) { return Script{}, false } hasScript = hasScript || key == "KEY_SCRIPT" @@ -115,11 +115,11 @@ func Discover(paths []string, occupied map[string]bool) ([]Script, []error) { if err != nil || !info.Mode().IsRegular() { continue } - script, ok := Parse_filename(entry.Name()) + script, ok := ParseFilename(entry.Name()) if !ok || loadedNames[script.Name] || loadedIDs[script.ID] { continue } - chord := input.Script_chord(script.Keys) + chord := input.ScriptChord(script.Keys) if shortcuts[chord] { continue } diff --git a/internal/scripts/discovery_test.go b/internal/scripts/discovery_test.go index b67d5a04..2afe31f7 100644 --- a/internal/scripts/discovery_test.go +++ b/internal/scripts/discovery_test.go @@ -38,13 +38,13 @@ func TestPythonFilenameGrammar(t *testing.T) { {"keys__-__KEY_A__+__KEY_B", []string{"KEY_A", "KEY_B", "KEY_SCRIPT"}}, {"media__-__KEY_PLAYPAUSE", []string{"KEY_PLAYPAUSE", "KEY_SCRIPT"}}, } { - script, ok := Parse_filename(fixture.name) + script, ok := ParseFilename(fixture.name) if !ok || !reflect.DeepEqual(script.Keys, fixture.keys) { t.Fatal(fixture.name, script, ok) } } for _, name := range []string{"__hidden__-__KEY_A.sh", ".hidden__-__KEY_A", "bad__-__KEY_A__-__KEY_B", "bad__-__KEY_NO_SUCH_KEY", "bad__-__KEY_A__+__", "unbound.sh"} { - if _, ok := Parse_filename(name); ok { + if _, ok := ParseFilename(name); ok { t.Fatal("accepted invalid filename", name) } } @@ -77,7 +77,7 @@ func TestPythonDiscoveryPrecedenceVariantsAndConflicts(t *testing.T) { if err := os.Mkdir(filepath.Join(local, "directory__-__KEY_F.sh"), 0700); err != nil { t.Fatal(err) } - result, problems := Discover([]string{filepath.Join(root, "missing"), local, system}, map[string]bool{input.Script_chord([]string{"KEY_D", "KEY_SCRIPT"}): true}) + result, problems := Discover([]string{filepath.Join(root, "missing"), local, system}, map[string]bool{input.ScriptChord([]string{"KEY_D", "KEY_SCRIPT"}): true}) if len(problems) != 0 { t.Fatal(problems) } diff --git a/internal/scripts/music_test.go b/internal/scripts/music_test.go index 5090208f..d513dc42 100644 --- a/internal/scripts/music_test.go +++ b/internal/scripts/music_test.go @@ -58,7 +58,7 @@ func TestInstalledMusicControllerWithFakePlayerctl(t *testing.T) { if err := os.WriteFile(path, data, 0700); err != nil { t.Fatal(err) } - runner := New_runner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 4096, Timeout: time.Second}, func(int) string { return "Username" }) + runner := NewRunner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 4096, Timeout: time.Second}, func(int) string { return "Username" }) defer runner.Close() for _, fixture := range []struct{ key, action string }{{"z", "previous"}, {"x", "play"}, {"c", "play-pause"}, {"v", "stop"}, {"b", "next"}, {"s", "shuffle toggle"}, {"u", "metadata"}, {"minus", "volume 0.05-"}, {"equal", "volume 0.05+"}} { link := filepath.Join(root, "musicplayer__-__key_shift__+__key_"+fixture.key+".sh") @@ -69,7 +69,7 @@ func TestInstalledMusicControllerWithFakePlayerctl(t *testing.T) { t.Fatal(err) } runner.Submit(Invocation{Script: Script{Path: link}}) - result := receive_result(t, runner) + result := receiveResult(t, runner) actions, err := os.ReadFile(filepath.Join(root, "actions")) if err != nil || result.Err != nil || result.Stderr != "" || !strings.Contains(string(actions), fixture.action) { t.Fatal(fixture, result, string(actions), err) diff --git a/internal/scripts/runner_linux.go b/internal/scripts/runner_linux.go index 42099c93..c6607715 100644 --- a/internal/scripts/runner_linux.go +++ b/internal/scripts/runner_linux.go @@ -66,7 +66,7 @@ type Runner struct { done chan struct{} } -func New_runner(ctx context.Context, limits Limits, username func(int) string) *Runner { +func NewRunner(ctx context.Context, limits Limits, username func(int) string) *Runner { ctx, cancel := context.WithCancel(ctx) r := &Runner{ctx: ctx, cancel: cancel, limits: limits, username: username, jobs: make(chan Invocation, limits.Queue), results: make(chan Result, limits.Workers), active: make(map[*Invocation]context.CancelFunc), done: make(chan struct{})} for range limits.Workers { diff --git a/internal/scripts/runner_test.go b/internal/scripts/runner_test.go index 375c42fb..a04725fd 100644 --- a/internal/scripts/runner_test.go +++ b/internal/scripts/runner_test.go @@ -27,7 +27,7 @@ import ( "time" ) -func fixture_script(t *testing.T, body string) Script { +func fixtureScript(t *testing.T, body string) Script { t.Helper() path := filepath.Join(t.TempDir(), "script with spaces__-__KEY_A.sh") if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body+"\n"), 0700); err != nil { @@ -36,7 +36,7 @@ func fixture_script(t *testing.T, body string) Script { return Script{Path: path} } -func receive_result(t *testing.T, runner *Runner) Result { +func receiveResult(t *testing.T, runner *Runner) Result { t.Helper() select { case result := <-runner.Results(): @@ -48,70 +48,70 @@ func receive_result(t *testing.T, runner *Runner) Result { } func TestRunnerPreservesArgumentsOutputAndNonzeroExit(t *testing.T) { - runner := New_runner(context.Background(), Limits{Workers: 1, Queue: 2, OutputBytes: 4096}, func(terminal int) string { + runner := NewRunner(context.Background(), Limits{Workers: 1, Queue: 2, OutputBytes: 4096}, func(terminal int) string { if terminal != 3 { t.Error(terminal) } return "Username; echo not-a-shell" }) defer runner.Close() - script := fixture_script(t, "echo \"$1\"\necho problem >&2\nexit 9") + script := fixtureScript(t, "echo \"$1\"\necho problem >&2\nexit 9") if !runner.Submit(Invocation{Script: script, Terminal: 3}) { t.Fatal("submit failed") } - result := receive_result(t, runner) + result := receiveResult(t, runner) if result.Err != nil || result.Stdout != "Username; echo not-a-shell\n" || result.Stderr != "problem\n" { t.Fatal(result) } } func TestRunnerDrainsFloodedOutputAndBoundsRetention(t *testing.T) { - runner := New_runner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 64, Timeout: time.Second}, nil) + runner := NewRunner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 64, Timeout: time.Second}, nil) defer runner.Close() - script := fixture_script(t, "i=0; while [ \"$i\" -lt 10000 ]; do echo output; echo error >&2; i=$((i+1)); done") + script := fixtureScript(t, "i=0; while [ \"$i\" -lt 10000 ]; do echo output; echo error >&2; i=$((i+1)); done") runner.Submit(Invocation{Script: script}) - result := receive_result(t, runner) + result := receiveResult(t, runner) if result.Err != nil || !result.Truncated || len(result.Stdout) != 64 || len(result.Stderr) != 64 { t.Fatal(result) } } func TestRunnerTimeoutFreesWorkerAndCancellationInvalidatesQueuedWork(t *testing.T) { - runner := New_runner(context.Background(), Limits{Workers: 1, Queue: 2, OutputBytes: 4096, Timeout: 150 * time.Millisecond}, nil) + runner := NewRunner(context.Background(), Limits{Workers: 1, Queue: 2, OutputBytes: 4096, Timeout: 150 * time.Millisecond}, nil) defer runner.Close() - slow := fixture_script(t, "sleep 30 &\nwait") + slow := fixtureScript(t, "sleep 30 &\nwait") runner.Submit(Invocation{Script: slow}) - if result := receive_result(t, runner); !errors.Is(result.Err, context.DeadlineExceeded) { + if result := receiveResult(t, runner); !errors.Is(result.Err, context.DeadlineExceeded) { t.Fatal(result) } - runner.Submit(Invocation{Script: fixture_script(t, "echo recovered")}) - if result := receive_result(t, runner); result.Err != nil || result.Stdout != "recovered\n" { + runner.Submit(Invocation{Script: fixtureScript(t, "echo recovered")}) + if result := receiveResult(t, runner); result.Err != nil || result.Stdout != "recovered\n" { t.Fatal(result) } generation := runner.Cancel() marker := filepath.Join(t.TempDir(), "must-not-run") - runner.Submit(Invocation{Script: fixture_script(t, "touch '"+marker+"'")}) - if result := receive_result(t, runner); !errors.Is(result.Err, context.Canceled) { + runner.Submit(Invocation{Script: fixtureScript(t, "touch '"+marker+"'")}) + if result := receiveResult(t, runner); !errors.Is(result.Err, context.Canceled) { t.Fatal(result) } if _, err := os.Stat(marker); !os.IsNotExist(err) { t.Fatal("stale invocation executed", err) } - runner.Submit(Invocation{Script: fixture_script(t, "echo new-session"), Generation: generation}) - if result := receive_result(t, runner); result.Stdout != "new-session\n" { + runner.Submit(Invocation{Script: fixtureScript(t, "echo new-session"), Generation: generation}) + if result := receiveResult(t, runner); result.Stdout != "new-session\n" { t.Fatal(result) } } func TestRunnerBoundsInheritedPipeWaitAndShutdown(t *testing.T) { - runner := New_runner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 4096}, nil) - script := fixture_script(t, "sleep 30 &\necho parent-finished") + runner := NewRunner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 4096}, nil) + script := fixtureScript(t, "sleep 30 &\necho parent-finished") runner.Submit(Invocation{Script: script}) - result := receive_result(t, runner) + result := receiveResult(t, runner) if result.Err == nil || !strings.Contains(result.Stdout, "parent-finished") { t.Fatal(result) } - runner.Submit(Invocation{Script: fixture_script(t, "sleep 30")}) + runner.Submit(Invocation{Script: fixtureScript(t, "sleep 30")}) started := time.Now() runner.Close() if time.Since(started) > time.Second { @@ -120,7 +120,7 @@ func TestRunnerBoundsInheritedPipeWaitAndShutdown(t *testing.T) { } func TestRunnerFileChecksAndQueueBound(t *testing.T) { - runner := New_runner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 32}, nil) + runner := NewRunner(context.Background(), Limits{Workers: 1, Queue: 1, OutputBytes: 32}, nil) defer runner.Close() path := filepath.Join(t.TempDir(), "not-executable") if err := os.WriteFile(path, []byte("#!/bin/sh\n"), 0600); err != nil { @@ -128,7 +128,7 @@ func TestRunnerFileChecksAndQueueBound(t *testing.T) { } for _, fixture := range []struct{ path, want string }{{path, "Script file is not executable"}, {filepath.Dir(path), "Script source is not a valid file"}, {path + "missing", "Script file not found"}} { runner.Submit(Invocation{Script: Script{Path: fixture.path}}) - result := receive_result(t, runner) + result := receiveResult(t, runner) if result.Err == nil || result.Err.Error() != fixture.want { t.Fatal(result) } diff --git a/internal/sound/alsa.go b/internal/sound/alsa.go index 11650e10..b8eab101 100644 --- a/internal/sound/alsa.go +++ b/internal/sound/alsa.go @@ -31,14 +31,14 @@ import ( type alsaPCM struct{ handle *C.snd_pcm_t } -func open_alsa(s *Service, device string) error { +func openAlsa(s *Service, device string) error { name := C.CString(device) defer C.free(unsafe.Pointer(name)) pcm := &alsaPCM{} if result := C.fenrir_pcm_open(&pcm.handle, name); result < 0 { return fmt.Errorf("open ALSA PCM %q: %s", device, C.GoString(C.snd_strerror(result))) } - s.start_pcm(pcm) + s.startPcm(pcm) return nil } @@ -51,10 +51,10 @@ func (p *alsaPCM) write(samples []float32) (int, error) { } return int(result) * 2, nil } -func (p *alsaPCM) prepare() error { return pcm_error(C.snd_pcm_prepare(p.handle)) } -func (p *alsaPCM) drain() error { return pcm_error(C.snd_pcm_drain(p.handle)) } +func (p *alsaPCM) prepare() error { return pcmError(C.snd_pcm_prepare(p.handle)) } +func (p *alsaPCM) drain() error { return pcmError(C.snd_pcm_drain(p.handle)) } func (p *alsaPCM) close() { C.snd_pcm_drop(p.handle); C.snd_pcm_close(p.handle) } -func pcm_error(result C.int) error { +func pcmError(result C.int) error { if result < 0 { return syscall.Errno(-result) } diff --git a/internal/sound/drivers.go b/internal/sound/drivers.go index 60b7cfd9..92adec99 100644 --- a/internal/sound/drivers.go +++ b/internal/sound/drivers.go @@ -36,10 +36,10 @@ type Driver struct { // Drivers is the shared startup, validation and form registry. PipeWire uses // its PulseAudio service; explicit selections never switch drivers on failure. func Drivers() []Driver { - return []Driver{{ID: "pulse", Label: "PulseAudio", open: open_pulse}, {ID: "alsa", Label: "ALSA", open: open_alsa}} + return []Driver{{ID: "pulse", Label: "PulseAudio", open: openPulse}, {ID: "alsa", Label: "ALSA", open: openAlsa}} } -func Find_driver(id string) (Driver, error) { +func FindDriver(id string) (Driver, error) { for _, driver := range Drivers() { if driver.ID == id { return driver, nil @@ -48,8 +48,8 @@ func Find_driver(id string) (Driver, error) { return Driver{}, fmt.Errorf("unknown sound driver %q", id) } -func Validate_selection(driver, device string) error { - if _, err := Find_driver(driver); err != nil { +func ValidateSelection(driver, device string) error { + if _, err := FindDriver(driver); err != nil { return err } if strings.TrimSpace(device) == "" || strings.ContainsAny(device, "\x00\r\n") { diff --git a/internal/sound/indentation.go b/internal/sound/indentation.go index bd77c23e..4d43c375 100644 --- a/internal/sound/indentation.go +++ b/internal/sound/indentation.go @@ -5,17 +5,17 @@ package sound // Use progress's pitch mapping with a triangle wave to distinguish indentation // from progress's clipped sine. Cache 0..100 columns before input opens. -func indentation_clips() [101]*clip { +func indentationClips() [101]*clip { var clips [101]*clip for level := range clips { - clips[level] = progress_tone_shape(float64(level), true) + clips[level] = progressToneShape(float64(level), true) } return clips } // Indentation uses ordinary cue admission, independently of the progress // monitor and its cancellation/coalescing state. Deeper levels use tone 100. -func (s *Service) Play_indentation(level int) bool { +func (s *Service) PlayIndentation(level int) bool { if s == nil || s.closed.Load() || s.finishing.Load() || level < 0 { return false } diff --git a/internal/sound/indentation_test.go b/internal/sound/indentation_test.go index 01bcd58e..0cf71843 100644 --- a/internal/sound/indentation_test.go +++ b/internal/sound/indentation_test.go @@ -9,8 +9,8 @@ import ( ) func TestIndentationTriangleCacheAndIndependentProgressCancellation(t *testing.T) { - s := &Service{tones: progress_clips(), indentationTones: indentation_clips()} - s.Set_volume(0.5) + s := &Service{tones: progressClips(), indentationTones: indentationClips()} + s.SetVolume(0.5) for level, item := range s.indentationTones { if item == nil || len(item.samples) != len(s.tones[level].samples) || slices.Equal(item.samples, s.tones[level].samples) { t.Fatal("missing or undifferentiated triangle tone", level) @@ -25,13 +25,13 @@ func TestIndentationTriangleCacheAndIndependentProgressCancellation(t *testing.T if len(item.samples) != len(progress.samples) || slices.Equal(item.samples, progress.samples) { t.Fatal("tone shape/duration", level) } - if !s.Play_indentation(level) || s.pending.Load() != item || s.progress.Load() != nil { + if !s.PlayIndentation(level) || s.pending.Load() != item || s.progress.Load() != nil { t.Fatal(level) } - s.Clear_progress() - s.Discard_progress() + s.ClearProgress() + s.DiscardProgress() buffer := make([]float32, 100) - s.read_samples(buffer) + s.readSamples(buffer) if s.current != item || s.progressing { t.Fatal("progress cancellation affected indentation", level) } @@ -41,11 +41,11 @@ func TestIndentationTriangleCacheAndIndependentProgressCancellation(t *testing.T } } } - if s.Play_indentation(-1) { + if s.PlayIndentation(-1) { t.Fatal("negative indentation accepted") } s.closed.Store(true) - if s.Play_indentation(1) { + if s.PlayIndentation(1) { t.Fatal("closed service accepted sound") } } diff --git a/internal/sound/notification.go b/internal/sound/notification.go index 0a3f5ba9..eac1bea3 100644 --- a/internal/sound/notification.go +++ b/internal/sound/notification.go @@ -22,10 +22,10 @@ type notificationPlayback struct { err error // published by closing drained } -// Play_wait runs on the speech worker, never the reader's input loop. A +// PlayWait runs on the speech worker, never the reader's input loop. A // completion means the output device drained, rather than just received samples. // Missing, silent or disconnected sound leaves speech available immediately. -func (s *Service) Play_wait(ctx context.Context, cue presentation.Cue) error { +func (s *Service) PlayWait(ctx context.Context, cue presentation.Cue) error { if s == nil || s.closed.Load() || s.finishing.Load() || math.Float32frombits(s.volume.Load()) == 0 { return nil } @@ -56,7 +56,7 @@ func (s *Service) Play_wait(ctx context.Context, cue presentation.Cue) error { } } -func (s *Service) drain_notification(request *notificationPlayback, drain func(context.Context) error) error { +func (s *Service) drainNotification(request *notificationPlayback, drain func(context.Context) error) error { ctx, cancel := context.WithTimeout(context.Background(), pcmTimeout) defer cancel() request.err = drain(ctx) @@ -68,7 +68,7 @@ func (s *Service) drain_notification(request *notificationPlayback, drain func(c // A callback blocked for the whole drain would also block its drain reply. Yield // empty reads at a paced interval so requests are consumed without feeding any // more samples (including silence) until the server acknowledges the drain. -func (s *Service) read_pulse_samples(samples []float32, drainRequests chan<- *notificationPlayback) (int, error) { +func (s *Service) readPulseSamples(samples []float32, drainRequests chan<- *notificationPlayback) (int, error) { if s.draining != nil { timer := time.NewTimer(audioPeriod) defer timer.Stop() @@ -81,8 +81,8 @@ func (s *Service) read_pulse_samples(samples []float32, drainRequests chan<- *no return 0, nil } } - count, err := s.read_samples(samples) - if err != errNotificationDrain { + count, err := s.readSamples(samples) + if !errors.Is(err, errNotificationDrain) { return count, err } select { diff --git a/internal/sound/notification_test.go b/internal/sound/notification_test.go index ac2237cf..bc473622 100644 --- a/internal/sound/notification_test.go +++ b/internal/sound/notification_test.go @@ -14,22 +14,22 @@ import ( "git.stormux.org/storm/fenrir/internal/presentation" ) -func notification_service(t *testing.T) *Service { +func notificationService(t *testing.T) *Service { t.Helper() s := &Service{clips: map[presentation.Cue]*clip{ presentation.Notification: {samples: []float32{.1, -.1, .2, -.2}}, presentation.Top: {samples: []float32{.3, -.3}}, presentation.Stopped: {samples: []float32{.4, -.4}}, }, done: make(chan struct{}), errors: make(chan error, 1)} - s.Set_volume(1) + s.SetVolume(1) t.Cleanup(s.Close) return s } -func queue_notification(t *testing.T, s *Service, ctx context.Context) <-chan error { +func queueNotification(t *testing.T, s *Service, ctx context.Context) <-chan error { t.Helper() result := make(chan error, 1) - go func() { result <- s.Play_wait(ctx, presentation.Notification) }() + go func() { result <- s.PlayWait(ctx, presentation.Notification) }() deadline := time.NewTimer(time.Second) defer deadline.Stop() tick := time.NewTicker(time.Millisecond) @@ -47,21 +47,21 @@ func queue_notification(t *testing.T, s *Service, ctx context.Context) <-chan er } func TestNotificationSoundPreservesTailAndWaitsForDeviceDrain(t *testing.T) { - s := notification_service(t) + s := notificationService(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - result := queue_notification(t, s, ctx) + result := queueNotification(t, s, ctx) buffer := make([]float32, 2) - s.read_samples(buffer) + s.readSamples(buffer) if !slices.Equal(buffer, []float32{.1, -.1}) { t.Fatal(buffer) } s.Play(presentation.Top) - s.read_samples(buffer) + s.readSamples(buffer) if !slices.Equal(buffer, []float32{.2, -.2}) { t.Fatal("cue interrupted notification tail", buffer) } - if _, err := s.read_samples(buffer); err != errNotificationDrain { + if _, err := s.readSamples(buffer); err != errNotificationDrain { t.Fatal(err) } select { @@ -69,7 +69,7 @@ func TestNotificationSoundPreservesTailAndWaitsForDeviceDrain(t *testing.T) { t.Fatal("speech released before drain") default: } - if err := s.drain_notification(s.draining, func(context.Context) error { + if err := s.drainNotification(s.draining, func(context.Context) error { select { case <-result: t.Fatal("speech released during drain") @@ -82,16 +82,16 @@ func TestNotificationSoundPreservesTailAndWaitsForDeviceDrain(t *testing.T) { if err := <-result; err != nil { t.Fatal(err) } - s.read_samples(buffer) + s.readSamples(buffer) if !slices.Equal(buffer, []float32{.3, -.3}) { t.Fatal("ordinary cue did not resume", buffer) } } func TestNotificationCancellationAndCloseReleaseWaiter(t *testing.T) { - s := notification_service(t) + s := notificationService(t) ctx, cancel := context.WithCancel(context.Background()) - result := queue_notification(t, s, ctx) + result := queueNotification(t, s, ctx) cancel() if err := <-result; !errors.Is(err, context.Canceled) { t.Fatal(err) @@ -99,7 +99,7 @@ func TestNotificationCancellationAndCloseReleaseWaiter(t *testing.T) { if s.notification.Load() != nil { t.Fatal("canceled cue remained pending") } - result = queue_notification(t, s, context.Background()) + result = queueNotification(t, s, context.Background()) s.Close() if err := <-result; err != nil { t.Fatal(err) @@ -107,12 +107,12 @@ func TestNotificationCancellationAndCloseReleaseWaiter(t *testing.T) { } func TestNotificationMissingAndZeroVolumeSkipWaiting(t *testing.T) { - s := notification_service(t) - if err := s.Play_wait(context.Background(), presentation.Blank); err != nil { + s := notificationService(t) + if err := s.PlayWait(context.Background(), presentation.Blank); err != nil { t.Fatal(err) } - s.Set_volume(0) - if err := s.Play_wait(context.Background(), presentation.Notification); err != nil { + s.SetVolume(0) + if err := s.PlayWait(context.Background(), presentation.Notification); err != nil { t.Fatal(err) } if s.notification.Load() != nil { @@ -121,14 +121,14 @@ func TestNotificationMissingAndZeroVolumeSkipWaiting(t *testing.T) { } func TestPulseNotificationBoundaryStopsFeedingUntilDrained(t *testing.T) { - s := notification_service(t) + s := notificationService(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - result := queue_notification(t, s, ctx) + result := queueNotification(t, s, ctx) drainRequests := make(chan *notificationPlayback, 1) buffer := make([]float32, 4) - s.read_pulse_samples(buffer, drainRequests) - if count, err := s.read_pulse_samples(buffer, drainRequests); count != 0 || err != nil { + s.readPulseSamples(buffer, drainRequests) + if count, err := s.readPulseSamples(buffer, drainRequests); count != 0 || err != nil { t.Fatal(count, err) } var request *notificationPlayback @@ -137,11 +137,11 @@ func TestPulseNotificationBoundaryStopsFeedingUntilDrained(t *testing.T) { case <-ctx.Done(): t.Fatal("Pulse did not request drain") } - if count, err := s.read_pulse_samples(buffer, drainRequests); count != 0 || err != nil { + if count, err := s.readPulseSamples(buffer, drainRequests); count != 0 || err != nil { t.Fatal("Pulse fed silence before drain", count, err) } - s.drain_notification(request, func(context.Context) error { return nil }) - if count, err := s.read_pulse_samples(buffer, drainRequests); count != len(buffer) || err != nil { + s.drainNotification(request, func(context.Context) error { return nil }) + if count, err := s.readPulseSamples(buffer, drainRequests); count != len(buffer) || err != nil { t.Fatal("Pulse did not resume", count, err) } if err := <-result; err != nil { @@ -150,13 +150,13 @@ func TestPulseNotificationBoundaryStopsFeedingUntilDrained(t *testing.T) { } func TestPCMNotificationDrainsAndContinuesPlayback(t *testing.T) { - s := notification_service(t) + s := notificationService(t) pcm := &fakePCM{} - s.start_pcm(pcm) + s.startPcm(pcm) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() for range 2 { - if err := s.Play_wait(ctx, presentation.Notification); err != nil { + if err := s.PlayWait(ctx, presentation.Notification); err != nil { t.Fatal(err) } } @@ -178,7 +178,7 @@ func TestALSANullNotificationAndShutdown(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for range 2 { - if err := s.Play_wait(ctx, presentation.Notification); err != nil { + if err := s.PlayWait(ctx, presentation.Notification); err != nil { t.Fatal(err) } } @@ -201,7 +201,7 @@ func TestPrivatePulseNotificationAndShutdown(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for range 2 { - if err := s.Play_wait(ctx, presentation.Notification); err != nil { + if err := s.PlayWait(ctx, presentation.Notification); err != nil { t.Fatal(err) } } diff --git a/internal/sound/pcm.go b/internal/sound/pcm.go index f6b0f9e4..29e6d525 100644 --- a/internal/sound/pcm.go +++ b/internal/sound/pcm.go @@ -24,7 +24,7 @@ type pcmOutput interface { close() } -func (s *Service) start_pcm(pcm pcmOutput) { +func (s *Service) startPcm(pcm pcmOutput) { drained := make(chan error, 1) s.closeBackend = pcm.close s.drainBackend = func(ctx context.Context) error { @@ -38,7 +38,7 @@ func (s *Service) start_pcm(pcm pcmOutput) { } } s.workers.Go(func() { - err := s.run_pcm(pcm) + err := s.runPcm(pcm) drained <- err if err != nil && !s.closed.Load() { select { @@ -49,7 +49,7 @@ func (s *Service) start_pcm(pcm pcmOutput) { }) } -func (s *Service) run_pcm(pcm pcmOutput) error { +func (s *Service) runPcm(pcm pcmOutput) error { // Pace even a virtual PCM such as ALSA's null sink. No busy silence loop, // and the same cancellation and cue priority apply to both audio drivers. tick := time.NewTicker(audioPeriod) @@ -61,12 +61,12 @@ func (s *Service) run_pcm(pcm pcmOutput) error { return nil case <-tick.C: } - count, err := s.read_samples(samples) - if err == errNotificationDrain { + count, err := s.readSamples(samples) + if errors.Is(err, errNotificationDrain) { request := s.draining s.draining = nil - if err := s.drain_notification(request, func(ctx context.Context) error { - if err := s.drain_pcm(ctx, pcm); err != nil { + if err := s.drainNotification(request, func(ctx context.Context) error { + if err := s.drainPcm(ctx, pcm); err != nil { return err } return pcm.prepare() @@ -75,21 +75,21 @@ func (s *Service) run_pcm(pcm pcmOutput) error { } continue } - if err == pulse.EndOfData { + if errors.Is(err, pulse.EndOfData) { ctx, cancel := context.WithTimeout(context.Background(), pcmTimeout) defer cancel() - return s.drain_pcm(ctx, pcm) + return s.drainPcm(ctx, pcm) } if err != nil { return err } - if err := s.write_pcm(pcm, samples[:count]); err != nil { + if err := s.writePcm(pcm, samples[:count]); err != nil { return err } } } -func (s *Service) write_pcm(pcm pcmOutput, samples []float32) error { +func (s *Service) writePcm(pcm pcmOutput, samples []float32) error { ctx, cancel := context.WithTimeout(context.Background(), pcmTimeout) defer cancel() for len(samples) > 0 { @@ -117,26 +117,26 @@ func (s *Service) write_pcm(pcm pcmOutput, samples []float32) error { case err == nil && count > 0: continue } - if err := s.wait_pcm(ctx); err != nil { + if err := s.waitPcm(ctx); err != nil { return err } } return nil } -func (s *Service) drain_pcm(ctx context.Context, pcm pcmOutput) error { +func (s *Service) drainPcm(ctx context.Context, pcm pcmOutput) error { for { err := pcm.drain() if !errors.Is(err, syscall.EAGAIN) && !errors.Is(err, syscall.EINTR) { return err } - if err := s.wait_pcm(ctx); err != nil { + if err := s.waitPcm(ctx); err != nil { return err } } } -func (s *Service) wait_pcm(ctx context.Context) error { +func (s *Service) waitPcm(ctx context.Context) error { timer := time.NewTimer(audioPeriod) defer timer.Stop() select { diff --git a/internal/sound/pcm_test.go b/internal/sound/pcm_test.go index 5e36eb7e..a3814313 100644 --- a/internal/sound/pcm_test.go +++ b/internal/sound/pcm_test.go @@ -59,7 +59,7 @@ func TestPCMShortWritesAndUnderrunRecoveryPreserveSampleOrder(t *testing.T) { return 2, nil } samples := []float32{1, -1, .5, -.5, .25, -.25} - if err := s.write_pcm(pcm, samples); err != nil { + if err := s.writePcm(pcm, samples); err != nil { t.Fatal(err) } if !slices.Equal(pcm.received, samples) || pcm.preparations != 2 { @@ -70,25 +70,25 @@ func TestPCMShortWritesAndUnderrunRecoveryPreserveSampleOrder(t *testing.T) { func TestPCMStallsAndDrainRespectCancellation(t *testing.T) { s := &Service{done: make(chan struct{})} pcm := &fakePCM{writeSamples: func([]float32) (int, error) { return 0, syscall.EAGAIN }, drainResult: func() error { return syscall.EAGAIN }} - if err := s.write_pcm(pcm, []float32{1, 1}); !errors.Is(err, context.DeadlineExceeded) { + if err := s.writePcm(pcm, []float32{1, 1}); !errors.Is(err, context.DeadlineExceeded) { t.Fatal("write did not expire", err) } ctx, cancel := context.WithCancel(context.Background()) cancel() - if err := s.drain_pcm(ctx, pcm); !errors.Is(err, context.Canceled) { + if err := s.drainPcm(ctx, pcm); !errors.Is(err, context.Canceled) { t.Fatal("drain did not cancel", err) } close(s.done) - if err := s.drain_pcm(context.Background(), pcm); !errors.Is(err, context.Canceled) { + if err := s.drainPcm(context.Background(), pcm); !errors.Is(err, context.Canceled) { t.Fatal("close did not cancel drain", err) } } func TestPCMShutdownUsesSharedCueVolumeAndDrainsBeforeClose(t *testing.T) { s := &Service{clips: map[presentation.Cue]*clip{presentation.Stopped: {samples: []float32{.8, -.8, .4, -.4}}}, done: make(chan struct{}), errors: make(chan error, 1)} - s.Set_volume(.5) + s.SetVolume(.5) pcm := &fakePCM{} - s.start_pcm(pcm) + s.startPcm(pcm) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := s.Finish(ctx); err != nil { @@ -108,7 +108,7 @@ func TestPCMShutdownUsesSharedCueVolumeAndDrainsBeforeClose(t *testing.T) { func TestPCMFailureDisablesOutputWithoutBlockingAdmission(t *testing.T) { s := &Service{done: make(chan struct{}), errors: make(chan error, 1)} pcm := &fakePCM{writeSamples: func([]float32) (int, error) { return 0, syscall.ENODEV }} - s.start_pcm(pcm) + s.startPcm(pcm) select { case err := <-s.Errors(): if !errors.Is(err, syscall.ENODEV) { @@ -129,7 +129,7 @@ func TestALSANullSinkLifecycleWithoutHardwareOrDesktopAudio(t *testing.T) { t.Fatal(err) } defer s.Close() - if !s.Play(presentation.Ready) || !s.Play_progress(50) { + if !s.Play(presentation.Ready) || !s.PlayProgress(50) { t.Fatal("shared audio admission failed") } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) @@ -145,7 +145,7 @@ func TestMissingPackKeepsGeneratedTonesOnALSANull(t *testing.T) { t.Fatal(s, err) } defer s.Close() - if s.Play(presentation.Ready) || !s.Play_progress(50) { + if s.Play(presentation.Ready) || !s.PlayProgress(50) { t.Fatal("missing cue or generated tone admission") } } diff --git a/internal/sound/player.go b/internal/sound/player.go index ecaefefd..21f3315c 100644 --- a/internal/sound/player.go +++ b/internal/sound/player.go @@ -19,12 +19,12 @@ import ( type soundBackend interface { Play(presentation.Cue) bool - Play_wait(context.Context, presentation.Cue) error - Play_progress(float64) bool - Play_indentation(int) bool - Discard_progress() - Clear_progress() - Set_volume(float64) + PlayWait(context.Context, presentation.Cue) error + PlayProgress(float64) bool + PlayIndentation(int) bool + DiscardProgress() + ClearProgress() + SetVolume(float64) Errors() <-chan error Finish(context.Context) error Close() @@ -45,8 +45,8 @@ type Player struct { once sync.Once } -func Open_recovering(ctx context.Context, roots []string, options Options) *Player { - return new_player(ctx, options.Volume, func() (soundBackend, error) { +func OpenRecovering(ctx context.Context, roots []string, options Options) *Player { + return newPlayer(ctx, options.Volume, func() (soundBackend, error) { service, err := Open(roots, options) if service == nil { return nil, err @@ -58,16 +58,16 @@ func Open_recovering(ctx context.Context, roots []string, options Options) *Play }) } -func new_player(ctx context.Context, volume float64, open func() (soundBackend, error)) *Player { +func newPlayer(ctx context.Context, volume float64, open func() (soundBackend, error)) *Player { ctx, cancel := context.WithCancel(ctx) p := &Player{cancel: cancel, done: make(chan struct{}), errors: make(chan error, 1)} p.volume.Store(math.Float64bits(volume)) // Even a driver whose connection or stream-start call ignores cancellation // cannot hold startup forever. Never retry an attempt that is still stuck. - backend, err := sound_attempt(ctx, open) + backend, err := soundAttempt(ctx, open) if err == nil { p.connection.Store(&soundConnection{backend}) - backend.Set_volume(volume) + backend.SetVolume(volume) } else { slog.Warn("sound unavailable or incomplete", "reconnecting", true, "error", err, "at", time.Now()) } @@ -77,7 +77,7 @@ func new_player(ctx context.Context, volume float64, open func() (soundBackend, // A timed-out native/library call is quarantined once. A late result is closed // by its own worker; no further opener goroutines are started for this player. -func sound_attempt(ctx context.Context, open func() (soundBackend, error)) (soundBackend, error) { +func soundAttempt(ctx context.Context, open func() (soundBackend, error)) (soundBackend, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() type result struct { @@ -119,7 +119,7 @@ func (p *Player) run(ctx context.Context, open func() (soundBackend, error), ini var backend soundBackend err := audio.Retry(retryContext, func(ctx context.Context) error { var err error - backend, err = sound_attempt(ctx, open) + backend, err = soundAttempt(ctx, open) return err }, func(err error) bool { return !errors.Is(err, errSoundAttemptStalled) && !errors.Is(err, context.Canceled) @@ -133,7 +133,7 @@ func (p *Player) run(ctx context.Context, open func() (soundBackend, error), ini } connection = &soundConnection{backend} p.connection.Store(connection) - backend.Set_volume(math.Float64frombits(p.volume.Load())) + backend.SetVolume(math.Float64frombits(p.volume.Load())) slog.Info("sound connection restored", "at", time.Now()) } select { @@ -158,43 +158,43 @@ func (p *Player) Play(cue presentation.Cue) bool { return false } -func (p *Player) Play_wait(ctx context.Context, cue presentation.Cue) error { +func (p *Player) PlayWait(ctx context.Context, cue presentation.Cue) error { if connection := p.connection.Load(); connection != nil { - return connection.backend.Play_wait(ctx, cue) + return connection.backend.PlayWait(ctx, cue) } return nil } -func (p *Player) Play_progress(value float64) bool { +func (p *Player) PlayProgress(value float64) bool { if connection := p.connection.Load(); connection != nil { - return connection.backend.Play_progress(value) + return connection.backend.PlayProgress(value) } return false } -func (p *Player) Play_indentation(level int) bool { +func (p *Player) PlayIndentation(level int) bool { if connection := p.connection.Load(); connection != nil { - return connection.backend.Play_indentation(level) + return connection.backend.PlayIndentation(level) } return false } -func (p *Player) Discard_progress() { +func (p *Player) DiscardProgress() { if connection := p.connection.Load(); connection != nil { - connection.backend.Discard_progress() + connection.backend.DiscardProgress() } } -func (p *Player) Clear_progress() { +func (p *Player) ClearProgress() { if connection := p.connection.Load(); connection != nil { - connection.backend.Clear_progress() + connection.backend.ClearProgress() } } -func (p *Player) Set_volume(volume float64) { +func (p *Player) SetVolume(volume float64) { p.volume.Store(math.Float64bits(volume)) if connection := p.connection.Load(); connection != nil { - connection.backend.Set_volume(volume) + connection.backend.SetVolume(volume) } } diff --git a/internal/sound/player_test.go b/internal/sound/player_test.go index d2df9db7..60c818ef 100644 --- a/internal/sound/player_test.go +++ b/internal/sound/player_test.go @@ -24,21 +24,21 @@ type fakeBackend struct { volume atomic.Uint64 } -func fake_backend() *fakeBackend { +func newFakeBackend() *fakeBackend { return &fakeBackend{errors: make(chan error, 1), closed: make(chan struct{})} } -func (f *fakeBackend) Play(presentation.Cue) bool { f.plays.Add(1); return true } -func (f *fakeBackend) Play_wait(context.Context, presentation.Cue) error { f.plays.Add(1); return nil } -func (f *fakeBackend) Play_progress(float64) bool { return true } -func (f *fakeBackend) Play_indentation(int) bool { return true } -func (f *fakeBackend) Discard_progress() {} -func (f *fakeBackend) Clear_progress() {} -func (f *fakeBackend) Set_volume(volume float64) { f.volume.Store(math.Float64bits(volume)) } -func (f *fakeBackend) Errors() <-chan error { return f.errors } -func (f *fakeBackend) Finish(context.Context) error { return nil } -func (f *fakeBackend) Close() { f.once.Do(func() { close(f.closed) }) } +func (f *fakeBackend) Play(presentation.Cue) bool { f.plays.Add(1); return true } +func (f *fakeBackend) PlayWait(context.Context, presentation.Cue) error { f.plays.Add(1); return nil } +func (f *fakeBackend) PlayProgress(float64) bool { return true } +func (f *fakeBackend) PlayIndentation(int) bool { return true } +func (f *fakeBackend) DiscardProgress() {} +func (f *fakeBackend) ClearProgress() {} +func (f *fakeBackend) SetVolume(volume float64) { f.volume.Store(math.Float64bits(volume)) } +func (f *fakeBackend) Errors() <-chan error { return f.errors } +func (f *fakeBackend) Finish(context.Context) error { return nil } +func (f *fakeBackend) Close() { f.once.Do(func() { close(f.closed) }) } -func wait_player(t *testing.T, player *Player, backend *fakeBackend) { +func waitPlayer(t *testing.T, player *Player, backend *fakeBackend) { t.Helper() deadline := time.NewTimer(time.Second) defer deadline.Stop() @@ -57,11 +57,11 @@ func wait_player(t *testing.T, player *Player, backend *fakeBackend) { } func TestSoundPlayerRecoversStartupAndDisconnectWithoutReplayingCues(t *testing.T) { - first, second := fake_backend(), fake_backend() + first, second := newFakeBackend(), newFakeBackend() firstGate, secondGate := make(chan struct{}), make(chan struct{}) attempts := make(chan int, 8) count := 0 - player := new_player(context.Background(), 0.7, func() (soundBackend, error) { + player := newPlayer(context.Background(), 0.7, func() (soundBackend, error) { count++ attempts <- count switch count { @@ -80,12 +80,12 @@ func TestSoundPlayerRecoversStartupAndDisconnectWithoutReplayingCues(t *testing. defer player.Close() <-attempts <-attempts - if player.Play(presentation.Ready) || player.Play_progress(50) || player.Play_indentation(2) { + if player.Play(presentation.Ready) || player.PlayProgress(50) || player.PlayIndentation(2) { t.Fatal("offline sound suppressed speech fallback") } - player.Set_volume(0.4) + player.SetVolume(0.4) close(firstGate) - wait_player(t, player, first) + waitPlayer(t, player, first) if !player.Play(presentation.Ready) { t.Fatal("recovered sound rejected cue") } @@ -94,9 +94,9 @@ func TestSoundPlayerRecoversStartupAndDisconnectWithoutReplayingCues(t *testing. if player.Play(presentation.Error) { t.Fatal("disconnected sound accepted stale cue") } - player.Set_volume(0.2) + player.SetVolume(0.2) close(secondGate) - wait_player(t, player, second) + waitPlayer(t, player, second) if second.plays.Load() != 0 || first.plays.Load() != 1 { t.Fatal("recovery replayed old cues", first.plays.Load(), second.plays.Load()) } @@ -109,11 +109,11 @@ func TestSoundPlayerRecoversStartupAndDisconnectWithoutReplayingCues(t *testing. func TestUnresponsiveSoundAttemptIsCancelledAndLateResultClosed(t *testing.T) { gate := make(chan struct{}) - backend := fake_backend() + backend := newFakeBackend() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() started := time.Now() - got, err := sound_attempt(ctx, func() (soundBackend, error) { <-gate; return backend, nil }) + got, err := soundAttempt(ctx, func() (soundBackend, error) { <-gate; return backend, nil }) if got != nil || !errors.Is(err, context.DeadlineExceeded) || time.Since(started) > time.Second { t.Fatal("sound attempt blocked caller", got, err) } @@ -124,7 +124,7 @@ func TestUnresponsiveSoundAttemptIsCancelledAndLateResultClosed(t *testing.T) { t.Fatal("late sound result leaked") } attempts := 0 - player := new_player(context.Background(), 0.7, func() (soundBackend, error) { + player := newPlayer(context.Background(), 0.7, func() (soundBackend, error) { attempts++ return nil, errors.Join(errSoundAttemptStalled, context.DeadlineExceeded) }) @@ -140,10 +140,10 @@ func TestUnresponsiveSoundAttemptIsCancelledAndLateResultClosed(t *testing.T) { } func TestSoundPlayerCloseDoesNotWaitForHungReconnect(t *testing.T) { - backend := fake_backend() + backend := newFakeBackend() gate, entered := make(chan struct{}), make(chan struct{}) attempts := 0 - player := new_player(context.Background(), 0.7, func() (soundBackend, error) { + player := newPlayer(context.Background(), 0.7, func() (soundBackend, error) { attempts++ if attempts == 1 { return nil, syscall.ENOENT diff --git a/internal/sound/progress.go b/internal/sound/progress.go index 5f1268a8..24acc920 100644 --- a/internal/sound/progress.go +++ b/internal/sound/progress.go @@ -30,10 +30,10 @@ const progressGain = 1.03 * 1.02 // Precompute integer percentages before opening the stream. Admission and the // audio callback only move pointers; fractional progress rounds to the nearest // percent. The cache is bounded to 101 short clips (about 1.6 MiB). -func progress_clips() [101]*clip { +func progressClips() [101]*clip { var clips [101]*clip for percentage := range clips { - clips[percentage] = progress_tone(float64(percentage)) + clips[percentage] = progressTone(float64(percentage)) } return clips } @@ -41,12 +41,12 @@ func progress_clips() [101]*clip { // Match Cthulhu's NVDA-style tones: 110 * 2^(percent/25) Hz, clipped sine, // 40 ms padded to an integer cycle, 7000/32768 amplitude per channel. Generate // at its 44100 Hz rate, then interpolate onto our shared 48000 Hz stream. -func progress_tone(percentage float64) *clip { - return progress_tone_shape(percentage, false) +func progressTone(percentage float64) *clip { + return progressToneShape(percentage, false) } // The triangle variant shares progress's pitch, duration and resampling. -func progress_tone_shape(percentage float64, triangle bool) *clip { +func progressToneShape(percentage float64, triangle bool) *clip { const sourceRate = tones.SampleRate native := tones.Samples(tones.ProgressFrequency(percentage), 40, triangle) count := len(native) @@ -66,9 +66,9 @@ func progress_tone_shape(percentage float64, triangle bool) *clip { return &clip{samples: samples} } -// Play_progress coalesces progress separately from ordinary cues. Progress +// PlayProgress coalesces progress separately from ordinary cues. Progress // never replaces startup/review sounds and never cuts a progress tone short. -func (s *Service) Play_progress(percentage float64) bool { +func (s *Service) PlayProgress(percentage float64) bool { if s == nil || s.closed.Load() || s.finishing.Load() || math.IsNaN(percentage) || math.IsInf(percentage, 0) || percentage < 0 || percentage > 100 { return false } @@ -80,17 +80,17 @@ func (s *Service) Play_progress(percentage float64) bool { return true } -// Discard_progress drops waiting tones after passive redraws or prompts while +// DiscardProgress drops waiting tones after passive redraws or prompts while // letting the short tone already playing finish. -func (s *Service) Discard_progress() { +func (s *Service) DiscardProgress() { if s != nil { s.progress.Store(nil) } } -// Clear_progress drops pending/playing tones at input, menu capture, and +// ClearProgress drops pending/playing tones at input, menu capture, and // session handoff without touching any ordinary sound cue. -func (s *Service) Clear_progress() { +func (s *Service) ClearProgress() { if s == nil { return } diff --git a/internal/sound/progress_test.go b/internal/sound/progress_test.go index f9fd301f..ba72257b 100644 --- a/internal/sound/progress_test.go +++ b/internal/sound/progress_test.go @@ -32,7 +32,7 @@ import ( func TestProgressTonePitchDurationStereoAndVolume(t *testing.T) { for _, percentage := range []float64{0, 25, 50, 75, 100} { - item := progress_tone(percentage) + item := progressTone(percentage) frames := len(item.samples) / 2 if frames < sampleRate*40/1000 || frames > sampleRate*50/1000 { t.Fatal("duration", frames) @@ -53,11 +53,11 @@ func TestProgressTonePitchDurationStereoAndVolume(t *testing.T) { t.Fatal("pitch", percentage, gotHz, wantHz) } } - s := &Service{tones: progress_clips()} - s.Set_volume(.25) - s.Play_progress(50) + s := &Service{tones: progressClips()} + s.SetVolume(.25) + s.PlayProgress(50) buffer := make([]float32, len(s.tones[50].samples)) - s.read_samples(buffer) + s.readSamples(buffer) for index, value := range buffer { if value != s.tones[50].samples[index]*(float32(.25)*float32(1.0506)) { t.Fatal("unscaled progress") @@ -70,68 +70,68 @@ func TestProgressPriorityCoalescingAndCancellation(t *testing.T) { presentation.Ready: {samples: []float32{1, 1, 2, 2}}, presentation.Top: {samples: []float32{3, 3, 4, 4}}, }, tones: [101]*clip{0: {samples: []float32{5, 5, 6, 6}}, 50: {samples: []float32{7, 7, 8, 8}}, 100: {samples: []float32{9, 9}}}} - s.Set_volume(1) + s.SetVolume(1) buffer := make([]float32, 2) read := func(want float32) { t.Helper() - s.read_samples(buffer) + s.readSamples(buffer) if math.Abs(float64(buffer[0]-want)) > 0.00001 { t.Fatal("wrong audio", buffer, want) } } s.Play(presentation.Ready) - s.Play_progress(0) + s.PlayProgress(0) read(1) s.Play(presentation.Top) - s.Play_progress(50) + s.PlayProgress(50) read(2) read(3) read(4) read(7 * 1.0506) - s.Play_progress(0) - s.Play_progress(100) + s.PlayProgress(0) + s.PlayProgress(100) read(8 * 1.0506) read(9 * 1.0506) read(0) // Ordinary cues can interrupt a tone, and a pending tone survives that cue. - s.Play_progress(50) + s.PlayProgress(50) read(7 * 1.0506) - s.Play_progress(100) + s.PlayProgress(100) s.Play(presentation.Top) read(3) read(4) read(9 * 1.0506) - s.Play_progress(50) + s.PlayProgress(50) read(7 * 1.0506) - s.Play_progress(100) - s.Clear_progress() + s.PlayProgress(100) + s.ClearProgress() read(0) s.Play(presentation.Top) read(3) - s.Clear_progress() + s.ClearProgress() read(4) // Shutdown stops progress admission and discards pending tones. - s.Play_progress(100) + s.PlayProgress(100) s.Finish(context.Background()) read(0) - if s.Play_progress(50) { + if s.PlayProgress(50) { t.Fatal("accepted during shutdown") } s.Close() - if s.Play_progress(50) { + if s.PlayProgress(50) { t.Fatal("accepted after close") } } func TestProgressAdmissionIsBoundedAndConcurrent(t *testing.T) { - s := &Service{tones: progress_clips()} - s.Set_volume(1) + s := &Service{tones: progressClips()} + s.SetVolume(1) for _, value := range []float64{-1, 101, math.NaN(), math.Inf(1)} { - if s.Play_progress(value) { + if s.PlayProgress(value) { t.Fatal("invalid progress", value) } } - s.Play_progress(49.6) + s.PlayProgress(49.6) if s.progress.Load() != s.tones[50] { t.Fatal("fraction rounding") } @@ -139,54 +139,54 @@ func TestProgressAdmissionIsBoundedAndConcurrent(t *testing.T) { var workers sync.WaitGroup workers.Go(func() { for range 10000 { - s.Play_progress(50) - s.Discard_progress() - s.Clear_progress() - s.Play_progress(100) + s.PlayProgress(50) + s.DiscardProgress() + s.ClearProgress() + s.PlayProgress(100) } }) buffer := make([]float32, 128) for range 10000 { - s.read_samples(buffer) + s.readSamples(buffer) } workers.Wait() if !slices.Equal(cached, s.tones[50].samples) { t.Fatal("mutated cache") } - if allocations := testing.AllocsPerRun(100, func() { s.Play_progress(50) }); allocations != 0 { + if allocations := testing.AllocsPerRun(100, func() { s.PlayProgress(50) }); allocations != 0 { t.Fatal("admission allocates", allocations) } - if allocations := testing.AllocsPerRun(100, func() { s.read_samples(buffer) }); allocations != 0 { + if allocations := testing.AllocsPerRun(100, func() { s.readSamples(buffer) }); allocations != 0 { t.Fatal("callback allocates", allocations) } } func TestDiscardProgressPreservesEntirePlayingTone(t *testing.T) { - s := &Service{tones: progress_clips()} - s.Set_volume(1) - s.Play_progress(50) + s := &Service{tones: progressClips()} + s.SetVolume(1) + s.PlayProgress(50) tone := s.tones[50].samples split := len(tone) / 4 * 2 // Keep stereo frames paired. first := make([]float32, split) - s.read_samples(first) - s.Play_progress(100) - s.Discard_progress() + s.readSamples(first) + s.PlayProgress(100) + s.DiscardProgress() tail := make([]float32, len(tone)-split) - s.read_samples(tail) + s.readSamples(tail) for index, value := range append(first, tail...) { if value != tone[index]*float32(progressGain) { t.Fatalf("tone cut short or altered at sample %d: got %v, want %v", index, value, tone[index]*float32(progressGain)) } } - s.read_samples(tail) + s.readSamples(tail) for _, value := range tail { if value != 0 { t.Fatal("discarded waiting tone still played") } } // A reset must not prevent the next job from making progress sounds. - s.Play_progress(100) - s.read_samples(tail) + s.PlayProgress(100) + s.readSamples(tail) if !slices.ContainsFunc(tail, func(value float32) bool { return value != 0 }) { t.Fatal("new progress tone was lost after discard") } @@ -196,7 +196,7 @@ func TestProgressSamplesMatchCthulhuReference(t *testing.T) { // Digest of Cthulhu's unmodified progress_tone_wav for integer 0..100, // independently resampled from 44100 Hz PCM16 to our 48000 Hz stereo float. hash := sha256.New() - for _, item := range progress_clips() { + for _, item := range progressClips() { for _, sample := range item.samples { if err := binary.Write(hash, binary.LittleEndian, sample); err != nil { t.Fatal(err) diff --git a/internal/sound/pulse.go b/internal/sound/pulse.go index 5a636f27..1eb0ad8b 100644 --- a/internal/sound/pulse.go +++ b/internal/sound/pulse.go @@ -27,7 +27,7 @@ import ( "github.com/jfreymuth/pulse/proto" ) -func open_pulse(s *Service, _ string) error { +func openPulse(s *Service, _ string) error { options := []pulse.ClientOption{pulse.ClientApplicationName("Fenrir sounds"), pulse.ClientTimeout(500 * time.Millisecond)} // Try the invoking user's session, then the bundled PipeWire helper's // socket and the system-wide service, unless PULSE_SERVER selects a server. @@ -37,7 +37,7 @@ func open_pulse(s *Service, _ string) error { return fmt.Errorf("connect sound server: %w", err) } drainRequests := make(chan *notificationPlayback, 1) - read := func(samples []float32) (int, error) { return s.read_pulse_samples(samples, drainRequests) } + read := func(samples []float32) (int, error) { return s.readPulseSamples(samples, drainRequests) } stream, err := client.NewPlayback(pulse.Float32Reader(read), pulse.PlaybackStereo, pulse.PlaybackSampleRate(sampleRate), pulse.PlaybackLatency(0.02), pulse.PlaybackMediaName("Fenrir sound cues")) if err != nil { client.Close() @@ -59,7 +59,7 @@ func open_pulse(s *Service, _ string) error { case <-s.done: return case request := <-drainRequests: - if err := s.drain_notification(request, s.drainBackend); err != nil { + if err := s.drainNotification(request, s.drainBackend); err != nil { s.errors <- fmt.Errorf("notification sound drain: %w", err) return } diff --git a/internal/sound/service.go b/internal/sound/service.go index ec442441..f7ede399 100644 --- a/internal/sound/service.go +++ b/internal/sound/service.go @@ -62,18 +62,18 @@ type Service struct { // Open may return a usable service plus warnings for missing individual cues. // Availability failures are nonfatal to speech and keyboard operation. func Open(roots []string, options Options) (*Service, error) { - if err := Validate_selection(options.Driver, options.Device); err != nil { + if err := ValidateSelection(options.Driver, options.Device); err != nil { return nil, err } volume := options.Volume if math.IsNaN(volume) || math.IsInf(volume, 0) || volume < 0 || volume > 1 { return nil, fmt.Errorf("sound volume must be between 0.0 and 1.0") } - clips, warning := load_theme(roots) + clips, warning := loadTheme(roots) // Generated tones remain available even without an installed sound pack. - s := &Service{clips: clips, tones: progress_clips(), indentationTones: indentation_clips(), errors: make(chan error, 1), done: make(chan struct{})} - s.Set_volume(volume) - driver, _ := Find_driver(options.Driver) + s := &Service{clips: clips, tones: progressClips(), indentationTones: indentationClips(), errors: make(chan error, 1), done: make(chan struct{})} + s.SetVolume(volume) + driver, _ := FindDriver(options.Driver) if err := driver.open(s, options.Device); err != nil { return nil, errors.Join(warning, err) } @@ -82,9 +82,9 @@ func Open(roots []string, options Options) (*Service, error) { func (s *Service) Errors() <-chan error { return s.errors } -// Set_volume applies a validated 0..1 gain to the next audio buffer, including +// SetVolume applies a validated 0..1 gain to the next audio buffer, including // any cue or progress tone already playing. Cached samples remain unchanged. -func (s *Service) Set_volume(volume float64) { +func (s *Service) SetVolume(volume float64) { s.volume.Store(math.Float32bits(float32(volume))) } @@ -123,13 +123,13 @@ func (s *Service) Play(cue presentation.Cue) bool { return false } -func (s *Service) read_samples(samples []float32) (int, error) { +func (s *Service) readSamples(samples []float32) (int, error) { clear(samples) if s.closed.Load() { return len(samples), nil } // Notification cues retain their tail despite ordinary cue updates. Their - // boundary drains the device before speech is released by Play_wait. + // boundary drains the device before speech is released by PlayWait. if s.current != nil && s.current.notification != nil { request := s.current.notification if request.ctx.Err() != nil || s.finishing.Load() { @@ -139,7 +139,7 @@ func (s *Service) read_samples(samples []float32) (int, error) { s.draining, s.current = request, nil return 0, errNotificationDrain } - return s.copy_samples(samples) + return s.copySamples(samples) } if s.cancelProgress.Swap(false) && s.progressing { s.current, s.progressing = nil, false @@ -168,10 +168,10 @@ func (s *Service) read_samples(samples []float32) (int, error) { s.current = nil return 0, pulse.EndOfData } - return s.copy_samples(samples) + return s.copySamples(samples) } -func (s *Service) copy_samples(samples []float32) (int, error) { +func (s *Service) copySamples(samples []float32) (int, error) { if s.current != nil { count := copy(samples, s.current.samples[s.offset:]) volume := math.Float32frombits(s.volume.Load()) @@ -198,7 +198,7 @@ func (s *Service) Finish(ctx context.Context) error { if s == nil || s.closed.Load() || s.finishing.Swap(true) { return nil } - s.Clear_progress() + s.ClearProgress() item := s.clips[presentation.Stopped] if item == nil || math.Float32frombits(s.volume.Load()) == 0 { return nil @@ -228,7 +228,7 @@ func (s *Service) Close() { } s.pending.Store(nil) s.notification.Store(nil) - s.Clear_progress() + s.ClearProgress() s.startup.Store(nil) if s.done != nil { close(s.done) diff --git a/internal/sound/service_test.go b/internal/sound/service_test.go index f4a89124..3798e425 100644 --- a/internal/sound/service_test.go +++ b/internal/sound/service_test.go @@ -36,16 +36,16 @@ import ( func TestVolumeScalesSamplesWithoutChangingCachedCues(t *testing.T) { item := &clip{samples: []float32{0.8, -0.4}} s := &Service{clips: map[presentation.Cue]*clip{presentation.Ready: item}} - s.Set_volume(0.25) + s.SetVolume(0.25) buffer := make([]float32, 4) s.Play(presentation.Ready) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0.2 || buffer[1] != -0.1 || buffer[2] != 0 || item.samples[0] != 0.8 { t.Fatal("volume changed samples or source cue", buffer, item.samples) } - s.Set_volume(0) + s.SetVolume(0) s.Play(presentation.Ready) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0 || buffer[1] != 0 { t.Fatal("zero volume was audible", buffer) } @@ -65,13 +65,13 @@ func TestVolumeChangesApplyToPlayingCuesAndProgress(t *testing.T) { s.Play(presentation.Ready) case "progress": s.tones[50] = item - s.Play_progress(50) + s.PlayProgress(50) gain = progressGain } buffer := make([]float32, 2) for index, volume := range []float64{0.7, 0.1, 0, 1} { - s.Set_volume(volume) - s.read_samples(buffer) + s.SetVolume(volume) + s.readSamples(buffer) for channel, sample := range buffer { want := original[index*2+channel] * (float32(volume) * gain) if sample != want { @@ -88,8 +88,8 @@ func TestVolumeChangesApplyToPlayingCuesAndProgress(t *testing.T) { func TestZeroVolumeSkipsShutdownPlayback(t *testing.T) { s := &Service{clips: map[presentation.Cue]*clip{presentation.Stopped: {samples: []float32{1, 1}}}} - s.Set_volume(0.7) - s.Set_volume(0) + s.SetVolume(0.7) + s.SetVolume(0) if err := s.Finish(context.Background()); err != nil || s.pending.Load() != nil { t.Fatal("zero volume queued shutdown audio", err) } @@ -100,13 +100,13 @@ func TestShutdownSubmitsFinalCueThenDrainsBeforeClose(t *testing.T) { presentation.Ready: {samples: []float32{0.8, 0.8, 0.8, 0.8, 0.8, 0.8}}, presentation.Stopped: {samples: []float32{0.4, -0.4, 0.8, -0.8}}, }} - s.Set_volume(0.5) + s.SetVolume(0.5) var operations []string s.drainBackend = func(context.Context) error { operations = append(operations, "drain"); return nil } s.closeBackend = func() { operations = append(operations, "close") } s.Play(presentation.Ready) buffer := make([]float32, 2) - s.read_samples(buffer) // Shutdown must replace even an unfinished startup. + s.readSamples(buffer) // Shutdown must replace even an unfinished startup. ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() result := make(chan error, 1) @@ -118,15 +118,15 @@ func TestShutdownSubmitsFinalCueThenDrainsBeforeClose(t *testing.T) { runtime.Gosched() } s.Play(presentation.Ready) // Admission has stopped; must not replace shutdown. - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0.2 || buffer[1] != -0.2 { t.Fatal("wrong shutdown start", buffer) } - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0.4 || buffer[1] != -0.4 { t.Fatal("shutdown tail lost", buffer) } - if n, err := s.read_samples(buffer); n != 0 || err != pulse.EndOfData { + if n, err := s.readSamples(buffer); n != 0 || err != pulse.EndOfData { t.Fatal("final stream did not terminate", n, err) } if err := <-result; err != nil { @@ -143,7 +143,7 @@ func TestShutdownSubmitsFinalCueThenDrainsBeforeClose(t *testing.T) { func TestShutdownDoesNotHangWithoutAudioCallbacks(t *testing.T) { s := &Service{clips: map[presentation.Cue]*clip{presentation.Stopped: {samples: []float32{1, 1}}}} - s.Set_volume(1) + s.SetVolume(1) ctx, cancel := context.WithCancel(context.Background()) cancel() if err := s.Finish(ctx); !errors.Is(err, context.Canceled) { @@ -157,25 +157,25 @@ func TestLatestCueReplacesPendingAndPlayingAudio(t *testing.T) { presentation.Top: {samples: []float32{1, 2, 3, 4, 5, 6}}, presentation.Bottom: {samples: []float32{7, 8}}, }} - s.Set_volume(1) + s.SetVolume(1) buffer := make([]float32, 4) s.Play(presentation.Top) s.Play(presentation.Bottom) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 7 || buffer[1] != 8 || buffer[2] != 0 { t.Fatal("stale pending cue", buffer) } s.Play(presentation.Top) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 1 || buffer[3] != 4 { t.Fatal("wrong first chunk", buffer) } s.Play(presentation.Bottom) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 7 || buffer[2] != 0 { t.Fatal("old playing cue continued", buffer) } - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0 { t.Fatal("cue replayed", buffer) } @@ -184,7 +184,7 @@ func TestLatestCueReplacesPendingAndPlayingAudio(t *testing.T) { s.Close() s.Close() s.Play(presentation.Top) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0 || closed != 1 { t.Fatal("closed service replayed or closed twice") } @@ -197,25 +197,25 @@ func TestStartupCompletesBeforeLatestScreenCue(t *testing.T) { presentation.Blank: {samples: []float32{7, 8}}, presentation.Top: {samples: []float32{9, 10}}, }} - s.Set_volume(1) + s.SetVolume(1) s.Play(presentation.Ready) s.Play(presentation.TTYChanged) s.Play(presentation.Blank) buffer := make([]float32, 2) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 1 || buffer[1] != 2 { t.Fatal("initial blank replaced startup", buffer) } s.Play(presentation.Top) - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 3 || buffer[1] != 4 { t.Fatal("startup tail was interrupted", buffer) } - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 9 || buffer[1] != 10 { t.Fatal("latest cue did not follow startup", buffer) } - s.read_samples(buffer) + s.readSamples(buffer) if buffer[0] != 0 || buffer[1] != 0 { t.Fatal("stale startup cues replayed", buffer) } @@ -223,17 +223,17 @@ func TestStartupCompletesBeforeLatestScreenCue(t *testing.T) { func TestRapidCueAdmissionDoesNotWaitForAudio(t *testing.T) { s := &Service{clips: map[presentation.Cue]*clip{presentation.Blank: {samples: []float32{1, 1}}}} - s.Set_volume(1) + s.SetVolume(1) var workers sync.WaitGroup workers.Go(func() { for index := range 10000 { - s.Set_volume(float64(index%11) / 10) + s.SetVolume(float64(index%11) / 10) s.Play(presentation.Blank) } }) buffer := make([]float32, 128) for range 10000 { - s.read_samples(buffer) + s.readSamples(buffer) } workers.Wait() if allocations := testing.AllocsPerRun(100, func() { s.Play(presentation.Blank) }); allocations != 0 { @@ -290,7 +290,7 @@ func TestSoundServerWithoutRuntimeDirectoryUsesCurrentUserAndSystemFallback(t *t func BenchmarkCueAdmission(b *testing.B) { s := &Service{clips: map[presentation.Cue]*clip{presentation.Blank: {samples: []float32{1, 1}}}} - s.Set_volume(1) + s.SetVolume(1) b.ReportAllocs() for b.Loop() { s.Play(presentation.Blank) diff --git a/internal/sound/theme.go b/internal/sound/theme.go index 3d247330..1c4fab80 100644 --- a/internal/sound/theme.go +++ b/internal/sound/theme.go @@ -49,15 +49,15 @@ type iconMap struct { Icons map[presentation.Cue]string `toml:"icons"` } -// Validate_theme accepts a single pack name or an absolute pack directory. -func Validate_theme(theme string) error { +// ValidateTheme accepts a single pack name or an absolute pack directory. +func ValidateTheme(theme string) error { if strings.TrimSpace(theme) == "" || strings.ContainsAny(theme, "\x00\r\n") || theme == "." || theme == ".." || (!filepath.IsAbs(theme) && filepath.Base(theme) != theme) { return fmt.Errorf("sound theme must be a name or an absolute directory") } return nil } -func Theme_paths(home, theme string) []string { +func ThemePaths(home, theme string) []string { if filepath.IsAbs(theme) { return []string{theme} } @@ -71,11 +71,11 @@ func Theme_paths(home, theme string) []string { ) } -// Theme_names is used by the settings worker, never by the input/audio loop. +// ThemeNames is used by the settings worker, never by the input/audio loop. // Limit directory enumeration; retain saved choices separately in the form. -func Theme_names(home string) []string { +func ThemeNames(home string) []string { names := map[string]bool{"default": true} - for _, path := range Theme_paths(home, "default") { + for _, path := range ThemePaths(home, "default") { directory, err := os.Open(filepath.Dir(path)) if err != nil { continue @@ -83,7 +83,7 @@ func Theme_names(home string) []string { entries, _ := directory.ReadDir(256) directory.Close() for _, entry := range entries { - if entry.IsDir() && Validate_theme(entry.Name()) == nil { + if entry.IsDir() && ValidateTheme(entry.Name()) == nil { names[entry.Name()] = true } } @@ -100,7 +100,7 @@ func Theme_names(home string) []string { // Load and resample once, before input grabs. No disk or decoding work belongs // on the input loop or the audio callback. Python soundicons.conf is not read. -func load_theme(roots []string) (map[presentation.Cue]*clip, error) { +func loadTheme(roots []string) (map[presentation.Cue]*clip, error) { var root string for _, candidate := range roots { info, err := os.Stat(candidate) @@ -146,7 +146,7 @@ func load_theme(roots []string) (map[presentation.Cue]*clip, error) { if name == "" || filepath.Base(name) != name || name == "." || name == ".." { return nil, fmt.Errorf("sound cue %q requires a filename in the theme directory", cue) } - item, err := decode_file(filepath.Join(root, name)) + item, err := decodeFile(filepath.Join(root, name)) if err != nil { problems = append(problems, fmt.Errorf("%s: %w", cue, err)) continue @@ -156,7 +156,7 @@ func load_theme(roots []string) (map[presentation.Cue]*clip, error) { return clips, errors.Join(problems...) } -func decode_file(path string) (*clip, error) { +func decodeFile(path string) (*clip, error) { file, err := os.Open(path) if err != nil { return nil, err @@ -169,5 +169,5 @@ func decode_file(path string) (*clip, error) { if !info.Mode().IsRegular() || info.Size() > 4<<20 { return nil, fmt.Errorf("sound must be a regular WAV file at most 4 MiB") } - return decode_wav(io.LimitReader(file, (4<<20)+1)) + return decodeWav(io.LimitReader(file, (4<<20)+1)) } diff --git a/internal/sound/theme_test.go b/internal/sound/theme_test.go index 81b58e6d..c682a5e4 100644 --- a/internal/sound/theme_test.go +++ b/internal/sound/theme_test.go @@ -31,7 +31,7 @@ import ( func TestBundledNormalizedPackDecodesAndContainsEveryCue(t *testing.T) { root := "../../config/sound/default" - clips, err := load_theme([]string{root}) + clips, err := loadTheme([]string{root}) if err != nil || len(clips) != 20 { t.Fatal(len(clips), err) } @@ -40,7 +40,7 @@ func TestBundledNormalizedPackDecodesAndContainsEveryCue(t *testing.T) { t.Fatal(paths, err) } for _, path := range paths { - item, err := decode_file(path) + item, err := decodeFile(path) if err != nil || item == nil || len(item.samples) == 0 { t.Fatal(path, err) } @@ -52,7 +52,7 @@ func TestBundledNormalizedPackDecodesAndContainsEveryCue(t *testing.T) { } } -func test_wav(rate uint32) []byte { +func testWav(rate uint32) []byte { var data bytes.Buffer data.WriteString("RIFF") binary.Write(&data, binary.LittleEndian, uint32(40)) @@ -73,27 +73,27 @@ func test_wav(rate uint32) []byte { } func TestWAVDecodeAndResample(t *testing.T) { - item, err := decode_wav(bytes.NewReader(test_wav(48000))) + item, err := decodeWav(bytes.NewReader(testWav(48000))) if err != nil || len(item.samples) != 4 || item.samples[0] != 0.25 || item.samples[1] != 0.25 || item.samples[2] != -0.25 { t.Fatalf("mono decoding: %+v, %v", item, err) } - item, err = decode_wav(bytes.NewReader(test_wav(24000))) + item, err = decodeWav(bytes.NewReader(testWav(24000))) if err != nil || len(item.samples) != 8 { t.Fatalf("resampling: %+v, %v", item, err) } - for _, data := range [][]byte{[]byte("invalid"), test_wav(1), test_wav(48000)[:45]} { - if _, err := decode_wav(bytes.NewReader(data)); err == nil { + for _, data := range [][]byte{[]byte("invalid"), testWav(1), testWav(48000)[:45]} { + if _, err := decodeWav(bytes.NewReader(data)); err == nil { t.Fatal("accepted invalid or truncated WAV") } } - base := test_wav(48000) + base := testWav(48000) extended := append([]byte(nil), base[:36]...) extended = append(extended, 22, 0, 16, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71) extended = append(extended, base[36:]...) binary.LittleEndian.PutUint32(extended[4:], uint32(len(extended)-8)) binary.LittleEndian.PutUint32(extended[16:], 40) binary.LittleEndian.PutUint16(extended[20:], 0xfffe) - item, err = decode_wav(bytes.NewReader(extended)) + item, err = decodeWav(bytes.NewReader(extended)) if err != nil || len(item.samples) != 4 || item.samples[0] != 0.25 { t.Fatalf("extended PCM: %+v %v", item, err) } @@ -107,19 +107,19 @@ func TestThemeTOMLAndPartialAvailability(t *testing.T) { t.Fatal(err) } } - write("cue.wav", test_wav(48000)) + write("cue.wav", testWav(48000)) write("soundicons.toml", []byte("[icons]\nready = 'cue.wav'\nblank = 'missing.wav'\n")) - clips, err := load_theme([]string{root}) + clips, err := loadTheme([]string{root}) if err == nil || len(clips) != 1 || clips[presentation.Ready] == nil { t.Fatal("partial theme disabled good cue", clips, err) } for _, data := range []string{"[icons]\nready = '../other.wav'", "[icons]\nunknown = 'cue.wav'", "driver = 'external'", "[icons"} { write("soundicons.toml", []byte(data)) - if _, err := load_theme([]string{root}); err == nil { + if _, err := loadTheme([]string{root}); err == nil { t.Fatal("accepted invalid theme", data) } } - if _, err := load_theme([]string{filepath.Join(root, "missing")}); err == nil { + if _, err := loadTheme([]string{filepath.Join(root, "missing")}); err == nil { t.Fatal("missing sound pack was not reported") } } @@ -129,18 +129,18 @@ func TestInstalledThemeWhenRequested(t *testing.T) { if root == "" { t.Skip("set FENRIR_TEST_SOUND_THEME to decode an installed pack without playing it") } - clips, err := load_theme([]string{root}) + clips, err := loadTheme([]string{root}) if err != nil || len(clips) != 16 { t.Fatalf("installed cues=%d, %v", len(clips), err) } } func FuzzWAVDecode(f *testing.F) { - f.Add(test_wav(48000)) - f.Add(test_wav(24000)) + f.Add(testWav(48000)) + f.Add(testWav(24000)) f.Add([]byte("RIFF")) f.Fuzz(func(t *testing.T, data []byte) { - item, err := decode_wav(bytes.NewReader(data)) + item, err := decodeWav(bytes.NewReader(data)) if err == nil && (len(item.samples) == 0 || len(item.samples) > sampleRate*2*10) { t.Fatal("invalid decoded size", len(item.samples)) } @@ -150,7 +150,7 @@ func FuzzWAVDecode(f *testing.F) { func TestSelectedThemesNeverMergeOrSubstitutePacks(t *testing.T) { first, second := t.TempDir(), t.TempDir() for _, root := range []string{first, second} { - if err := os.WriteFile(filepath.Join(root, "cue.wav"), test_wav(48000), 0600); err != nil { + if err := os.WriteFile(filepath.Join(root, "cue.wav"), testWav(48000), 0600); err != nil { t.Fatal(err) } } @@ -160,11 +160,11 @@ func TestSelectedThemesNeverMergeOrSubstitutePacks(t *testing.T) { if err := os.WriteFile(filepath.Join(second, "soundicons.toml"), []byte("[icons]\nready='cue.wav'\n"), 0600); err != nil { t.Fatal(err) } - clips, err := load_theme([]string{first, second}) + clips, err := loadTheme([]string{first, second}) if err == nil || clips[presentation.Ready] != nil { t.Fatal("missing cue substituted from a lower priority pack", err) } - clips, err = load_theme([]string{filepath.Join(first, "missing"), second}) + clips, err = loadTheme([]string{filepath.Join(first, "missing"), second}) if err != nil || clips[presentation.Ready] == nil { t.Fatal("named search did not find later installation", err) } @@ -178,25 +178,25 @@ func TestThemeNamesPathsAndValidation(t *testing.T) { t.Fatal(err) } } - names := Theme_names(home) + names := ThemeNames(home) if names[0] != "default" || !slices.Contains(names, "alpha") || !slices.Contains(names, "zeta") { t.Fatal(names) } - paths := Theme_paths(home, "alpha") + paths := ThemePaths(home, "alpha") if paths[0] != filepath.Join(root, "alpha") { t.Fatal(paths) } explicit := filepath.Join(home, "custom") - if got := Theme_paths(home, explicit); !slices.Equal(got, []string{explicit}) { + if got := ThemePaths(home, explicit); !slices.Equal(got, []string{explicit}) { t.Fatal(got) } for _, name := range []string{"default", "alpha", explicit} { - if err := Validate_theme(name); err != nil { + if err := ValidateTheme(name); err != nil { t.Fatal(name, err) } } for _, name := range []string{"", " ", "..", ".", "../other", "sub/pack", "bad\x00name", "bad\nname"} { - if Validate_theme(name) == nil { + if ValidateTheme(name) == nil { t.Fatal("invalid theme accepted", name) } } diff --git a/internal/sound/wav.go b/internal/sound/wav.go index c29e7925..2ec4b1c0 100644 --- a/internal/sound/wav.go +++ b/internal/sound/wav.go @@ -27,7 +27,7 @@ import ( // Fenrir's cues are short PCM WAV files. Validate RIFF chunk bounds before // decoding, then resample once to the persistent stream's stereo rate. -func decode_wav(reader io.Reader) (*clip, error) { +func decodeWav(reader io.Reader) (*clip, error) { data, err := io.ReadAll(io.LimitReader(reader, (4<<20)+1)) if err != nil { return nil, err diff --git a/internal/speech/address_test.go b/internal/speech/address_test.go index 17e1238a..bb0cc4e4 100644 --- a/internal/speech/address_test.go +++ b/internal/speech/address_test.go @@ -70,13 +70,13 @@ func TestSpeechAddressUsedByClientAndDiscovery(t *testing.T) { t.Run(network, func(t *testing.T) { var server *fakeServer if network == "unix" { - server = new_fake_server(t, false) + server = newFakeServer(t, false) } else { listener, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { t.Fatal(err) } - server = new_fake_server_listener(t, false, listener) + server = newFakeServerListener(t, false, listener) } address := "unix_socket:" + server.path if network == "tcp4" { @@ -96,17 +96,17 @@ func TestSpeechAddressUsedByClientAndDiscovery(t *testing.T) { if err := client.Say("connection fixture"); err != nil { t.Fatal(err) } - wait_event(t, server.events, "say:connection fixture") + waitEvent(t, server.events, "say:connection fixture") if err := client.Cancel(); err != nil { t.Fatal(err) } - wait_event(t, server.events, "CANCEL 41") + waitEvent(t, server.events, "CANCEL 41") }) } } func TestInvalidAddressDoesNotFallBack(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) t.Setenv("SPEECHD_ADDRESS", "unsupported:address") t.Setenv("SPEECHD_SOCKET", server.path) if _, err := Open(Options{}); err == nil || !strings.Contains(err.Error(), "unsupported") { diff --git a/internal/speech/autospawn_test.go b/internal/speech/autospawn_test.go index 2bd04ec4..d2d370c3 100644 --- a/internal/speech/autospawn_test.go +++ b/internal/speech/autospawn_test.go @@ -111,7 +111,7 @@ func TestSpeechSpawnUsesConfiguredExecutableAndReportsRefusal(t *testing.T) { func TestExistingSpeechServerDoesNotInvokeSpawn(t *testing.T) { t.Setenv("SPEECHD_CMD", "/nonexistent/speech-dispatcher") - server := new_fake_server(t, false) + server := newFakeServer(t, false) client, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -140,10 +140,10 @@ func TestDiscoveryDoesNotSpawn(t *testing.T) { if _, err := Discover(options); err == nil { t.Fatal("expected connection failure") } - if _, err := discover_modules(options); err == nil { + if _, err := discoverModules(options); err == nil { t.Fatal("expected connection failure") } - if _, err := discover_voices(options); err == nil { + if _, err := discoverVoices(options); err == nil { t.Fatal("expected connection failure") } if _, err := os.Stat(marker); !os.IsNotExist(err) { diff --git a/internal/speech/catalog.go b/internal/speech/catalog.go index 878aa6ae..a98b0b61 100644 --- a/internal/speech/catalog.go +++ b/internal/speech/catalog.go @@ -17,7 +17,7 @@ type Voice = sd.Voice // server default, and per-module errors. type Catalog = sd.Discovery -func Validate_selection(module, language, voice string) error { +func ValidateSelection(module, language, voice string) error { return sd.ValidSelection(module, language, voice) } @@ -26,38 +26,38 @@ func Validate_selection(module, language, voice string) error { // retain successful modules and mark unavailable voice lists explicitly. func Discover(options Options) (Catalog, error) { result := Catalog{Voices: map[string][]Voice{}, Errors: map[string]error{}} - w, err := connect_options(options) + w, err := connectOptions(options) if err != nil { return result, err } defer w.Close() - ctx, cancel := context.WithTimeout(option_context(options), 4*time.Second) + ctx, cancel := context.WithTimeout(optionContext(options), 4*time.Second) defer cancel() return sd.DiscoverQuery(ctx, w) } -var Normalize_language = sd.NormalizeLanguage -var Language_voices = sd.LanguageVoices +var NormalizeLanguage = sd.NormalizeLanguage +var LanguageVoices = sd.LanguageVoices // Prepare checks membership because SSIP SET may accept unknown synthesis // names without verifying them. The resulting client has not spoken anything. func Prepare(driver string, options Options) (Transport, error) { - return Prepare_context(context.Background(), driver, options) + return PrepareContext(context.Background(), driver, options) } -// Prepare_context bounds discovery and connection setup together. -func Prepare_context(ctx context.Context, driver string, options Options) (Transport, error) { +// PrepareContext bounds discovery and connection setup together. +func PrepareContext(ctx context.Context, driver string, options Options) (Transport, error) { options.context = ctx - if err := Validate_selection(options.Module, options.Language, options.Voice); err != nil { + if err := ValidateSelection(options.Module, options.Language, options.Voice); err != nil { return nil, err } - d, err := Find_driver(driver) + d, err := FindDriver(driver) if err != nil { return nil, err } if d.Voices == nil { if options.Module == "" && options.Language == "" && options.Voice == "" { - return Open_driver_context(ctx, driver, options) + return OpenDriverContext(ctx, driver, options) } return nil, fmt.Errorf("speech driver does not support voice discovery") } @@ -84,33 +84,33 @@ func Prepare_context(ctx context.Context, driver string, options Options) (Trans } languageFound, voiceFound := options.Language == "", options.Voice == "" for _, voice := range voices { - languageMatches := options.Language == "" || Normalize_language(voice.Language) == Normalize_language(options.Language) + languageMatches := options.Language == "" || NormalizeLanguage(voice.Language) == NormalizeLanguage(options.Language) languageFound = languageFound || languageMatches voiceFound = voiceFound || voice.Name == options.Voice && languageMatches } if !languageFound || !voiceFound { return nil, fmt.Errorf("speech language or voice is unavailable for module %q", options.Module) } - return Open_driver_context(ctx, driver, options) + return OpenDriverContext(ctx, driver, options) } // A live change queries only its target, so a slow unrelated module cannot // consume its discovery budget or prevent selecting a working synthesizer. -func discover_voices(options Options) ([]Voice, error) { - if err := Validate_selection(options.Module, options.Language, options.Voice); err != nil { +func discoverVoices(options Options) ([]Voice, error) { + if err := ValidateSelection(options.Module, options.Language, options.Voice); err != nil { return nil, err } - w, err := connect_options(options) + w, err := connectOptions(options) if err != nil { return nil, err } defer w.Close() if options.Module != "" { - if _, err = w.Command(option_context(options), "SET SELF OUTPUT_MODULE "+options.Module); err != nil { + if _, err = w.Command(optionContext(options), "SET SELF OUTPUT_MODULE "+options.Module); err != nil { return nil, err } } - rows, err := w.Command(option_context(options), "LIST SYNTHESIS_VOICES") + rows, err := w.Command(optionContext(options), "LIST SYNTHESIS_VOICES") if err != nil { return nil, err } diff --git a/internal/speech/catalog_test.go b/internal/speech/catalog_test.go index 590e51cc..039bfeff 100644 --- a/internal/speech/catalog_test.go +++ b/internal/speech/catalog_test.go @@ -12,7 +12,7 @@ import ( ) func TestLargeVoiceCatalogAndSilentPreparation(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) server.mu.Lock() for index := range 14805 { server.voices = append(server.voices, fmt.Sprintf("Voice %d\ten-US\tnone", index)) @@ -60,7 +60,7 @@ func TestBoundedRepliesAndInjection(t *testing.T) { } func TestCandidateRejectionLeavesOriginalClientUsable(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) original, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -76,7 +76,7 @@ func TestCandidateRejectionLeavesOriginalClientUsable(t *testing.T) { if err := original.Say("still working"); err != nil { t.Fatal(err) } - wait_event(t, server.events, "say:still working") + waitEvent(t, server.events, "say:still working") } func TestCatalogPreservesEspeakVoiceWhitespace(t *testing.T) { @@ -84,10 +84,10 @@ func TestCatalogPreservesEspeakVoiceWhitespace(t *testing.T) { if err != nil || len(voices) != 1 || voices[0].Name != "Cherokee " { t.Fatal(voices, err) } - if err := Validate_selection("espeak-ng", "chr", "Cherokee "); err != nil { + if err := ValidateSelection("espeak-ng", "chr", "Cherokee "); err != nil { t.Fatal(err) } - if err := Validate_selection("espeak-ng", "chr", " "); err == nil { + if err := ValidateSelection("espeak-ng", "chr", " "); err == nil { t.Fatal("accepted whitespace-only name") } } diff --git a/internal/speech/client.go b/internal/speech/client.go index 1b86e82a..ff69e77f 100644 --- a/internal/speech/client.go +++ b/internal/speech/client.go @@ -30,8 +30,6 @@ import ( sd "git.stormux.org/storm/screenreader-common/speechdispatcher" ) -const commandTimeout = 5 * time.Second - type Rejection = sd.Rejection type Options struct { @@ -65,7 +63,7 @@ type Client struct { closeOnce sync.Once } -func option_context(options Options) context.Context { +func optionContext(options Options) context.Context { if options.context != nil { return options.context } @@ -80,7 +78,7 @@ func Open(options Options) (*Client, error) { return nil, fmt.Errorf("speech pitch and volume must be between -100 and 100") } } - if err := Validate_selection(options.Module, options.Language, options.Voice); err != nil { + if err := ValidateSelection(options.Module, options.Language, options.Voice); err != nil { return nil, err } backend := sd.NewWithSettings(options.Socket, sd.Settings{ @@ -89,7 +87,7 @@ func Open(options Options) (*Client, error) { OutputModule: options.Module, Language: options.Language, SynthesisVoice: options.Voice, Punctuation: "NONE", Capitalization: "NONE", }) - if err := backend.Connect(option_context(options)); err != nil { + if err := backend.Connect(optionContext(options)); err != nil { backend.Close(context.Background()) return nil, err } @@ -107,7 +105,7 @@ func (c *Client) Configure(parameters Parameters) error { } return c.client.Configure(context.Background(), ¶meters.Rate, ¶meters.Pitch, ¶meters.Volume) } -func (c *Client) Set_pitch(pitch int) error { +func (c *Client) SetPitch(pitch int) error { return c.client.Configure(context.Background(), nil, &pitch, nil) } func (c *Client) Say(text string) error { @@ -119,9 +117,12 @@ func (c *Client) Say(text string) error { return c.client.SpeakText(context.Background(), text) } func (c *Client) Cancel() error { return c.client.Cancel(context.Background()) } -func (c *Client) Close() { c.closeOnce.Do(func() { c.client.Shutdown(context.Background()) }) } -func (c *Client) abort() { c.client.Abort() } +func (c *Client) Close() { + // Shutdown is best-effort teardown; there is no caller to report to. + c.closeOnce.Do(func() { _ = c.client.Shutdown(context.Background()) }) +} +func (c *Client) abort() { c.client.Abort() } -func connect_options(options Options) (*sd.Query, error) { - return sd.OpenQuery(option_context(options), options.Socket, options.autospawn, true) +func connectOptions(options Options) (*sd.Query, error) { + return sd.OpenQuery(optionContext(options), options.Socket, options.autospawn, true) } diff --git a/internal/speech/client_test.go b/internal/speech/client_test.go index dfce8828..4906e2c9 100644 --- a/internal/speech/client_test.go +++ b/internal/speech/client_test.go @@ -33,7 +33,7 @@ import ( ) func TestSpeechAcknowledgementWaitsForBusyDispatcher(t *testing.T) { - server := new_fake_server(t, true) + server := newFakeServer(t, true) client, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -41,7 +41,7 @@ func TestSpeechAcknowledgementWaitsForBusyDispatcher(t *testing.T) { defer client.Close() result := make(chan error, 1) go func() { result <- client.Say("startup") }() - wait_event(t, server.events, "say:startup") + waitEvent(t, server.events, "say:startup") // Voice catalog requests can occupy the dispatcher for more than 750 ms. time.Sleep(time.Second) close(server.ack) @@ -64,16 +64,16 @@ type fakeServer struct { wg sync.WaitGroup } -func new_fake_server(t *testing.T, block bool) *fakeServer { +func newFakeServer(t *testing.T, block bool) *fakeServer { t.Helper() listener, err := net.Listen("unix", filepath.Join(t.TempDir(), "s")) if err != nil { t.Fatal(err) } - return new_fake_server_listener(t, block, listener) + return newFakeServerListener(t, block, listener) } -func new_fake_server_listener(t *testing.T, block bool, listener net.Listener) *fakeServer { +func newFakeServerListener(t *testing.T, block bool, listener net.Listener) *fakeServer { t.Helper() server := &fakeServer{path: listener.Addr().String(), events: make(chan string, 64), ack: make(chan struct{}), stop: make(chan struct{})} if !block { @@ -187,7 +187,7 @@ func (s *fakeServer) serve(conn net.Conn) { } func TestSSIPDotStuffingAndTargetedCancellation(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) client, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -197,15 +197,15 @@ func TestSSIPDotStuffingAndTargetedCancellation(t *testing.T) { if err := client.Say(text); err != nil { t.Fatal(err) } - wait_event(t, server.events, "say:"+text) + waitEvent(t, server.events, "say:"+text) if err := client.Cancel(); err != nil { t.Fatal(err) } - wait_event(t, server.events, "CANCEL 41") + waitEvent(t, server.events, "CANCEL 41") } func TestSingleCharactersUseOneCommandWithoutSpeakHandshake(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) client, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -228,12 +228,12 @@ func TestSingleCharactersUseOneCommandWithoutSpeakHandshake(t *testing.T) { if err := client.Say(text); err != nil { t.Fatal(err) } - wait_event(t, server.events, "say:"+strings.ReplaceAll(text, "\x00", "")) + waitEvent(t, server.events, "say:"+strings.ReplaceAll(text, "\x00", "")) } } func TestSSIPControlWorksWhileSpeakAcknowledgementIsBlocked(t *testing.T) { - server := new_fake_server(t, true) + server := newFakeServer(t, true) client, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -241,11 +241,11 @@ func TestSSIPControlWorksWhileSpeakAcknowledgementIsBlocked(t *testing.T) { defer client.Close() result := make(chan error, 1) go func() { result <- client.Say("blocked") }() - wait_event(t, server.events, "say:blocked") + waitEvent(t, server.events, "say:blocked") if err := client.Cancel(); err != nil { t.Fatal(err) } - wait_event(t, server.events, "CANCEL 41") + waitEvent(t, server.events, "CANCEL 41") close(server.ack) if err := <-result; err != nil { t.Fatal(err) @@ -261,7 +261,7 @@ func TestSpeechOptionsRejectCommandInjection(t *testing.T) { } func TestLiveParametersUseSpeakingClientAndRejectInvalidValues(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) pitch, volume := -20, 90 client, err := Open(Options{Socket: server.path, Rate: 80, Pitch: &pitch, Volume: &volume}) if err != nil { @@ -293,11 +293,11 @@ func TestLiveParametersUseSpeakingClientAndRejectInvalidValues(t *testing.T) { if err := client.Say("feedback"); err != nil { t.Fatal(err) } - wait_event(t, server.events, "say:feedback") + waitEvent(t, server.events, "say:feedback") if err := client.Cancel(); err != nil { t.Fatal(err) } - wait_event(t, server.events, "CANCEL 41") + waitEvent(t, server.events, "CANCEL 41") } func TestDefaultSocketForSudo(t *testing.T) { diff --git a/internal/speech/drivers.go b/internal/speech/drivers.go index c521da5a..b53d67fb 100644 --- a/internal/speech/drivers.go +++ b/internal/speech/drivers.go @@ -21,6 +21,7 @@ import ( "context" "fmt" + "git.stormux.org/storm/screenreader-common/hardware/transport" sd "git.stormux.org/storm/screenreader-common/speechdispatcher" ) @@ -50,12 +51,12 @@ var drivers = append([]Driver{{ Open: func(options Options) (Transport, error) { return Open(options) }, - Modules: discover_modules, + Modules: discoverModules, Catalog: Discover, - Voices: discover_voices, -}}, hardware_drivers()...) + Voices: discoverVoices, +}}, hardwareDrivers()...) -func hardware_drivers() []Driver { +func hardwareDrivers() []Driver { var result []Driver for _, entry := range []struct{ id, label string }{ {"dectalk", "DECtalk"}, {"dectalk-usb", "DECtalk USB"}, @@ -64,10 +65,10 @@ func hardware_drivers() []Driver { driver := Driver{ID: entry.id, Label: entry.label, Serial: entry.id != "dectalk-usb", Hardware: true, - Open: func(options Options) (Transport, error) { return open_hardware(entry.id, options) }, + Open: func(options Options) (Transport, error) { return openHardware(entry.id, options) }, } if entry.id == "dectalk-usb" { - driver.Check = usb_available + driver.Check = transport.USBAvailable } result = append(result, driver) } @@ -78,7 +79,7 @@ func hardware_drivers() []Driver { // settings validation, UI choices, discovery and startup from the same entry. func Drivers() []Driver { return append([]Driver(nil), drivers...) } -func Find_driver(id string) (Driver, error) { +func FindDriver(id string) (Driver, error) { for _, driver := range drivers { if driver.ID == id { return driver, nil @@ -87,18 +88,18 @@ func Find_driver(id string) (Driver, error) { return Driver{}, fmt.Errorf("unknown speech driver %q", id) } -func Open_driver(id string, options Options) (Transport, error) { - return Open_driver_context(context.Background(), id, options) +func OpenDriver(id string, options Options) (Transport, error) { + return OpenDriverContext(context.Background(), id, options) } -// Open_driver_context bounds connection setup without binding the live client to ctx. -func Open_driver_context(ctx context.Context, id string, options Options) (Transport, error) { +// OpenDriverContext bounds connection setup without binding the live client to ctx. +func OpenDriverContext(ctx context.Context, id string, options Options) (Transport, error) { options.context = ctx - driver, err := Find_driver(id) + driver, err := FindDriver(id) if err != nil { return nil, err } - if err := Validate_driver_options(id, options); err != nil { + if err := ValidateDriverOptions(id, options); err != nil { return nil, err } if err = driver.Availability(); err != nil { @@ -111,21 +112,21 @@ func Open_driver_context(ctx context.Context, id string, options Options) (Trans return client, nil } -// discover_modules uses a separate, bounded connection. It never changes the +// discoverModules uses a separate, bounded connection. It never changes the // active speaking client or cancels speech. Only Prepare permits daemon startup. -func discover_modules(options Options) ([]string, error) { - wire, err := connect_options(options) +func discoverModules(options Options) ([]string, error) { + wire, err := connectOptions(options) if err != nil { return nil, err } defer wire.Close() - modules, err := wire.Command(option_context(options), "LIST OUTPUT_MODULES") + modules, err := wire.Command(optionContext(options), "LIST OUTPUT_MODULES") if err != nil { return nil, err } seen := map[string]bool{} for _, module := range modules { - if !valid_module(module) || module == "" || seen[module] { + if !validModule(module) || module == "" || seen[module] { return nil, fmt.Errorf("invalid Speech Dispatcher module list") } seen[module] = true @@ -133,4 +134,4 @@ func discover_modules(options Options) ([]string, error) { return modules, nil } -func valid_module(module string) bool { return sd.ValidModule(module) } +func validModule(module string) bool { return sd.ValidModule(module) } diff --git a/internal/speech/drivers_test.go b/internal/speech/drivers_test.go index 75032aac..b55651c1 100644 --- a/internal/speech/drivers_test.go +++ b/internal/speech/drivers_test.go @@ -29,10 +29,10 @@ func TestRegistryIsTheImplementationAndSelectionBoundary(t *testing.T) { t.Fatal(available) } available[0].ID = "altered" - if _, err := Find_driver("speech-dispatcher"); err != nil { + if _, err := FindDriver("speech-dispatcher"); err != nil { t.Fatal("registry aliased", err) } - if _, err := Open_driver("invented", Options{}); err == nil { + if _, err := OpenDriver("invented", Options{}); err == nil { t.Fatal("unknown driver opened") } // A supported but locally unavailable backend must not block another driver, @@ -41,25 +41,25 @@ func TestRegistryIsTheImplementationAndSelectionBoundary(t *testing.T) { opened := false drivers = append(Drivers(), Driver{ID: "fixture", Label: "Fixture", Check: func() error { return errors.New("fixture dependency missing") }, Open: func(Options) (Transport, error) { opened = true; return nil, nil }}) defer func() { drivers = original }() - if _, err := Find_driver("fixture"); err != nil { + if _, err := FindDriver("fixture"); err != nil { t.Fatal("unavailable support disappeared", err) } if err := Drivers()[0].Availability(); err != nil { t.Fatal("unselected dependency blocked supported driver", err) } - if _, err := Open_driver("fixture", Options{}); err == nil || opened { + if _, err := OpenDriver("fixture", Options{}); err == nil || opened { t.Fatal("unavailable driver constructed or fell back", opened, err) } } func TestModuleDiscoveryDoesNotSpeakOrChangeActiveClient(t *testing.T) { - server := new_fake_server(t, false) - driver, err := Find_driver("speech-dispatcher") + server := newFakeServer(t, false) + driver, err := FindDriver("speech-dispatcher") if err != nil { t.Fatal(err) } t.Setenv("SPEECHD_ADDRESS", "unix_socket:"+server.path) - client, err := Open_driver(driver.ID, Options{Rate: 80}) + client, err := OpenDriver(driver.ID, Options{Rate: 80}) if err != nil { t.Fatal(err) } diff --git a/internal/speech/hardware.go b/internal/speech/hardware.go index fd172db1..47c2f569 100644 --- a/internal/speech/hardware.go +++ b/internal/speech/hardware.go @@ -13,10 +13,9 @@ import ( "sync/atomic" "git.stormux.org/storm/screenreader-common/hardware" + "git.stormux.org/storm/screenreader-common/hardware/transport" ) -var errHardwareCanceled = errors.New("hardware speech write canceled") - // Hardware device settings take effect at launch. Serial paths are explicit; // DECtalk USB finds a single native device, without probing serial ports. type HardwareOptions struct { @@ -24,11 +23,11 @@ type HardwareOptions struct { BaudRate int } -// Baud_rates supplies validation and settings choices from the same list. +// BaudRates supplies validation and settings choices from the same list. // Zero retains the saved default, which selects 9600 on open. -func Baud_rates() []int { return []int{0, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200} } +func BaudRates() []int { return append([]int{0}, transport.BaudRates()...) } -func hardware_driver(id string) bool { +func hardwareDriver(id string) bool { switch id { case "dectalk", "dectalk-usb", "litetalk", "doubletalk", "tripletalk": return true @@ -36,11 +35,11 @@ func hardware_driver(id string) bool { return false } -func Validate_driver_options(id string, options Options) error { - if err := Validate_selection(options.Module, options.Language, options.Voice); err != nil { +func ValidateDriverOptions(id string, options Options) error { + if err := ValidateSelection(options.Module, options.Language, options.Voice); err != nil { return err } - if !hardware_driver(id) { + if !hardwareDriver(id) { return nil } if options.Module != "" || options.Language != "" || options.Voice != "" { @@ -53,22 +52,29 @@ func Validate_driver_options(id string, options Options) error { if device == "" || !filepath.IsAbs(device) || strings.ContainsAny(device, "\x00\r\n") { return fmt.Errorf("%s requires an explicit absolute hardware_device path", id) } - if slices.Contains(Baud_rates(), options.Hardware.BaudRate) { + if slices.Contains(BaudRates(), options.Hardware.BaudRate) { return nil } return fmt.Errorf("unsupported hardware_baud_rate %d", options.Hardware.BaudRate) } -// Write checks cancellation between packets. Cancel must bypass a blocked -// normal write; Close releases resources after stopping in-flight operations. -type hardwarePort interface { - Write([]byte, func() bool) error - Cancel([]byte) error - Close() +// openHardware opens the shared transport for a validated hardware driver. +func openHardware(id string, options Options) (Transport, error) { + if err := ValidateDriverOptions(id, options); err != nil { + return nil, err + } + if err := hardwareParameters(options); err != nil { + return nil, err + } + port, err := transport.Open(id, options.Hardware.Device, options.Hardware.BaudRate) + if err != nil { + return nil, err + } + return newHardwareClient(id, options, port), nil } type HardwareClient struct { - port hardwarePort + port transport.Port dectalk bool usb bool mu sync.Mutex // Serialized settings/text; cancellation never takes this lock. @@ -79,7 +85,7 @@ type HardwareClient struct { closed atomic.Bool } -func new_hardware_client(id string, options Options, port hardwarePort) *HardwareClient { +func newHardwareClient(id string, options Options, port transport.Port) *HardwareClient { parameters := Parameters{Rate: options.Rate} if options.Pitch != nil { parameters.Pitch = *options.Pitch @@ -90,7 +96,7 @@ func new_hardware_client(id string, options Options, port hardwarePort) *Hardwar return &HardwareClient{port: port, dectalk: id == "dectalk" || id == "dectalk-usb", usb: id == "dectalk-usb", parameters: parameters} } -func hardware_parameters(options Options) error { +func hardwareParameters(options Options) error { parameters := Parameters{Rate: options.Rate} if options.Pitch != nil { parameters.Pitch = *options.Pitch @@ -136,8 +142,8 @@ func (c *HardwareClient) configure(generation uint64) error { return nil } -func ignore_hardware_cancel(err error) error { - if errors.Is(err, errHardwareCanceled) { +func ignoreHardwareCancel(err error) error { + if errors.Is(err, transport.ErrCanceled) { return nil } return err @@ -150,17 +156,17 @@ func (c *HardwareClient) Configure(parameters Parameters) error { c.mu.Lock() defer c.mu.Unlock() c.parameters = parameters - return ignore_hardware_cancel(c.configure(c.generation.Load())) + return ignoreHardwareCancel(c.configure(c.generation.Load())) } -func (c *HardwareClient) Set_pitch(pitch int) error { +func (c *HardwareClient) SetPitch(pitch int) error { if pitch < -100 || pitch > 100 { return fmt.Errorf("speech pitch must be between -100 and 100") } c.mu.Lock() defer c.mu.Unlock() c.parameters.Pitch = pitch - return ignore_hardware_cancel(c.configure(c.generation.Load())) + return ignoreHardwareCancel(c.configure(c.generation.Load())) } func (c *HardwareClient) Say(text string) error { @@ -168,9 +174,9 @@ func (c *HardwareClient) Say(text string) error { defer c.mu.Unlock() generation := c.generation.Load() if err := c.configure(generation); err != nil { - return ignore_hardware_cancel(err) + return ignoreHardwareCancel(err) } - return ignore_hardware_cancel(c.write(c.profile().Text(text), generation)) + return ignoreHardwareCancel(c.write(c.profile().Text(text), generation)) } func (c *HardwareClient) Cancel() error { diff --git a/internal/speech/hardware_linux.go b/internal/speech/hardware_linux.go deleted file mode 100644 index f591accc..00000000 --- a/internal/speech/hardware_linux.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later - -//go:build linux && cgo - -package speech - -/* -#cgo LDFLAGS: -ldl -#include -#include "hardware_native.h" -*/ -import "C" - -import ( - "errors" - "fmt" - "io" - "sync" - "syscall" - "time" - "unsafe" -) - -type serialPort struct { - mu sync.Mutex - native *C.SpeechSerial -} - -func open_hardware(id string, options Options) (Transport, error) { - if err := Validate_driver_options(id, options); err != nil { - return nil, err - } - if err := hardware_parameters(options); err != nil { - return nil, err - } - var port hardwarePort - if id == "dectalk-usb" { - var status C.int - native := C.speech_usb_open(&status) - if native == nil { - return nil, usb_error(status) - } - usb := &usbPort{ - send: func(endpoint byte, data []byte) error { - status := C.speech_usb_write(native, C.uchar(endpoint), unsafe.Pointer(&data[0]), C.int(len(data))) - if status != 0 { - return usb_error(status) - } - return nil - }, - close: func() { C.speech_usb_close(native) }, - } - if err := usb.Write([]byte("[:timeout 1]"), func() bool { return false }); err != nil { - usb.Close() - return nil, err - } - port = usb - } else { - path := C.CString(options.Hardware.Device) - defer C.free(unsafe.Pointer(path)) - baud := options.Hardware.BaudRate - if baud == 0 { - baud = 9600 - } - xon := C.int(0) - if id == "dectalk" { - xon = 1 - } - var status C.int - native := C.speech_serial_open(path, C.int(baud), xon, &status) - if native == nil { - return nil, fmt.Errorf("open hardware speech %s: %w", options.Hardware.Device, syscall.Errno(-status)) - } - port = &serialPort{native: native} - } - return new_hardware_client(id, options, port), nil -} - -func (p *serialPort) Write(data []byte, canceled func() bool) error { - for len(data) > 0 { - p.mu.Lock() - if canceled() { - p.mu.Unlock() - return errHardwareCanceled - } - if p.native == nil { - p.mu.Unlock() - return errors.New("serial speech closed") - } - count := int(C.speech_serial_write(p.native, unsafe.Pointer(&data[0]), C.size_t(min(len(data), 64)))) - p.mu.Unlock() - if count > 0 { - data = data[count:] - continue - } - if count == 0 { - return io.ErrNoProgress - } - err := syscall.Errno(-count) - if err != syscall.EAGAIN && err != syscall.EINTR { - return fmt.Errorf("write serial speech: %w", err) - } - // XOFF can legitimately last while buffered speech is being spoken. - // Each write is nonblocking; only this worker waits, and cancellation - // or shutdown breaks the retry loop without waiting for XON. - time.Sleep(5 * time.Millisecond) - } - return nil -} - -func (p *serialPort) Cancel(command []byte) error { - p.mu.Lock() - defer p.mu.Unlock() - if p.native == nil { - return nil - } - deadline := time.Now().Add(commandTimeout) - for { - count := int(C.speech_serial_cancel(p.native, C.uchar(command[0]))) - if count == 1 { - return nil - } - if count == 0 { - return io.ErrNoProgress - } - err := syscall.Errno(-count) - if (err != syscall.EAGAIN && err != syscall.EINTR) || time.Now().After(deadline) { - return fmt.Errorf("cancel serial speech: %w", err) - } - // Resuming terminal output can complete asynchronously. Retry the - // immediate byte within a bounded interval, rather than treating the - // first EAGAIN after TCOON as a device failure. - time.Sleep(5 * time.Millisecond) - } -} - -func (p *serialPort) Close() { - p.mu.Lock() - defer p.mu.Unlock() - if p.native != nil { - C.speech_serial_close(p.native) - p.native = nil - } -} - -// Different endpoints can transfer concurrently. Only Close takes exclusive -// ownership, after each bounded native call has returned. -type usbPort struct { - mu sync.RWMutex - send func(byte, []byte) error - close func() -} - -func usb_available() error { - if C.speech_usb_available() == 0 { - return errors.New("DECtalk USB requires libusb-1.0.so.0") - } - return nil -} - -func usb_error(status C.int) error { - switch status { - case -100: - return errors.New("DECtalk USB requires libusb-1.0.so.0") - case -101: - return errors.New("multiple DECtalk USB devices found; connect one for this reader") - case -102: - return errors.New("short DECtalk USB write") - case -4: - return errors.New("DECtalk USB device 0dd0:2001 unavailable or disconnected") - case -3: - return errors.New("DECtalk USB access denied") - case -6: - return errors.New("DECtalk USB interface is busy") - case -7: - return errors.New("DECtalk USB write timed out") - } - return fmt.Errorf("DECtalk USB error %d", status) -} - -func (p *usbPort) transfer(endpoint byte, data []byte, canceled func() bool) error { - p.mu.RLock() - defer p.mu.RUnlock() - if p.send == nil { - return errors.New("USB speech closed") - } - for len(data) > 0 { - if canceled() { - return errHardwareCanceled - } - count := min(64, len(data)) - if err := p.send(endpoint, data[:count]); err != nil { - if canceled() { - return errHardwareCanceled - } - return err - } - data = data[count:] - } - return nil -} - -func (p *usbPort) Write(data []byte, canceled func() bool) error { - return p.transfer(0x02, data, canceled) -} -func (p *usbPort) Cancel(command []byte) error { - return p.transfer(0x04, command, func() bool { return false }) -} -func (p *usbPort) Close() { - p.mu.Lock() - defer p.mu.Unlock() - if p.send != nil { - if p.close != nil { - p.close() - } - p.send, p.close = nil, nil - } -} diff --git a/internal/speech/hardware_linux_test.go b/internal/speech/hardware_linux_test.go index 920fb77c..4fbd57c2 100644 --- a/internal/speech/hardware_linux_test.go +++ b/internal/speech/hardware_linux_test.go @@ -6,15 +6,11 @@ package speech import ( - "bytes" "context" "errors" "fmt" "os" - "reflect" "strings" - "sync" - "sync/atomic" "syscall" "testing" "time" @@ -22,18 +18,18 @@ import ( ) func TestHardwarePreviewKeepsTemporaryPortUntilCanceledAndReleasesIt(t *testing.T) { - master, path := hardware_pty(t) + master, path := hardwarePty(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan error, 1) go func() { - done <- Test_hardware(ctx, "dectalk", Options{Hardware: HardwareOptions{Device: path}}, "test sample") + done <- TestHardware(ctx, "dectalk", Options{Hardware: HardwareOptions{Device: path}}, "test sample") }() want := "[:ra 180][:dv ap 122][:dv g5 73]test sample\x0b" - if got := string(read_hardware(t, master, len(want))); got != want { + if got := string(readHardware(t, master, len(want))); got != want { t.Fatal(got) } - if other, err := Open_driver("dectalk", Options{Hardware: HardwareOptions{Device: path}}); err == nil { + if other, err := OpenDriver("dectalk", Options{Hardware: HardwareOptions{Device: path}}); err == nil { other.Close() t.Fatal("preview closed before device could speak") } @@ -46,14 +42,14 @@ func TestHardwarePreviewKeepsTemporaryPortUntilCanceledAndReleasesIt(t *testing. case <-time.After(time.Second): t.Fatal("preview did not cancel") } - client, err := Open_driver("dectalk", Options{Hardware: HardwareOptions{Device: path}}) + client, err := OpenDriver("dectalk", Options{Hardware: HardwareOptions{Device: path}}) if err != nil { t.Fatal("preview retained port", err) } client.Close() } -func hardware_pty(t *testing.T) (*os.File, string) { +func hardwarePty(t *testing.T) (*os.File, string) { t.Helper() fd, err := syscall.Open("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0) if err != nil { @@ -72,7 +68,7 @@ func hardware_pty(t *testing.T) (*os.File, string) { return master, fmt.Sprintf("/dev/pts/%d", number) } -func read_hardware(t *testing.T, master *os.File, count int) []byte { +func readHardware(t *testing.T, master *os.File, count int) []byte { t.Helper() var result []byte deadline := time.Now().Add(2 * time.Second) @@ -95,7 +91,7 @@ func read_hardware(t *testing.T, master *os.File, count int) []byte { return result } -func assert_hardware_idle(t *testing.T, master *os.File) { +func assertHardwareIdle(t *testing.T, master *os.File) { t.Helper() var buffer [128]byte if n, err := syscall.Read(int(master.Fd()), buffer[:]); n > 0 || err != syscall.EAGAIN { @@ -103,7 +99,7 @@ func assert_hardware_idle(t *testing.T, master *os.File) { } } -func hardware_termios(t *testing.T, fd int) syscall.Termios { +func hardwareTermios(t *testing.T, fd int) syscall.Termios { t.Helper() var value syscall.Termios if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TCGETS, uintptr(unsafe.Pointer(&value))); err != 0 { @@ -115,25 +111,25 @@ func hardware_termios(t *testing.T, fd int) syscall.Termios { func TestNativeSerialHardwareLifecycle(t *testing.T) { for _, id := range []string{"dectalk", "litetalk", "doubletalk", "tripletalk"} { t.Run(id, func(t *testing.T) { - master, path := hardware_pty(t) + master, path := hardwarePty(t) slave, err := syscall.Open(path, syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0) if err != nil { t.Fatal(err) } defer syscall.Close(slave) - original := hardware_termios(t, slave) + original := hardwareTermios(t, slave) options := Options{Hardware: HardwareOptions{Device: path, BaudRate: 19200}} - transport, err := Open_driver(id, options) + transport, err := OpenDriver(id, options) if err != nil { t.Fatal(err) } defer transport.Close() - configured := hardware_termios(t, slave) + configured := hardwareTermios(t, slave) if configured.Cflag&syscall.CS8 == 0 || configured.Lflag&(syscall.ICANON|syscall.ECHO) != 0 || configured.Iflag&(syscall.IXOFF|syscall.IXANY) != 0 || (configured.Iflag&syscall.IXON != 0) != (id == "dectalk") { t.Fatal("serial mode", configured) } - assert_hardware_idle(t, master) // Opening a candidate never speaks. - if other, err := Open_driver(id, options); err == nil { + assertHardwareIdle(t, master) // Opening a candidate never speaks. + if other, err := OpenDriver(id, options); err == nil { other.Close() t.Fatal("another reader acquired an owned serial device") } @@ -149,24 +145,24 @@ func TestNativeSerialHardwareLifecycle(t *testing.T) { want = "[:ra 180][:dv ap 122][:dv g5 86]Hello world \x0b" cancel = "\x03" } - if got := string(read_hardware(t, master, len(want))); got != want { + if got := string(readHardware(t, master, len(want))); got != want { t.Fatalf("%q != %q", got, want) } if err := transport.Configure(Parameters{Volume: 100}); err != nil { t.Fatal(err) } - assert_hardware_idle(t, master) + assertHardwareIdle(t, master) if err := transport.Cancel(); err != nil { t.Fatal(err) } - if got := string(read_hardware(t, master, 1)); got != cancel { + if got := string(readHardware(t, master, 1)); got != cancel { t.Fatal(got) } transport.Close() - if restored := hardware_termios(t, slave); restored != original { + if restored := hardwareTermios(t, slave); restored != original { t.Fatal("termios not restored", restored, original) } - reopened, err := Open_driver(id, options) + reopened, err := OpenDriver(id, options) if err != nil { t.Fatal("serial lock survived close", err) } @@ -176,8 +172,8 @@ func TestNativeSerialHardwareLifecycle(t *testing.T) { } func TestSerialCancellationStopsLargeWriteAndAllowsFreshSpeech(t *testing.T) { - master, path := hardware_pty(t) - transport, err := Open_driver("dectalk", Options{Hardware: HardwareOptions{Device: path}}) + master, path := hardwarePty(t) + transport, err := OpenDriver("dectalk", Options{Hardware: HardwareOptions{Device: path}}) if err != nil { t.Fatal(err) } @@ -185,10 +181,10 @@ func TestSerialCancellationStopsLargeWriteAndAllowsFreshSpeech(t *testing.T) { if err := transport.Configure(Parameters{}); err != nil { t.Fatal(err) } - read_hardware(t, master, len("[:ra 180][:dv ap 122][:dv g5 73]")) + readHardware(t, master, len("[:ra 180][:dv ap 122][:dv g5 73]")) done := make(chan error, 1) go func() { done <- transport.Say(strings.Repeat("x", 1<<20)) }() - if string(read_hardware(t, master, 1)) != "x" { + if string(readHardware(t, master, 1)) != "x" { t.Fatal("text write did not start") } if err := transport.Cancel(); err != nil { @@ -216,15 +212,15 @@ func TestSerialCancellationStopsLargeWriteAndAllowsFreshSpeech(t *testing.T) { t.Fatal(err) } want := "[:ra 180][:dv ap 122][:dv g5 73]fresh\x0b" - if got := string(read_hardware(t, master, len(want))); got != want { + if got := string(readHardware(t, master, len(want))); got != want { t.Fatalf("stale output %q", got) } - assert_hardware_idle(t, master) + assertHardwareIdle(t, master) } func TestSerialDisconnectReturnsError(t *testing.T) { - master, path := hardware_pty(t) - transport, err := Open_driver("litetalk", Options{Hardware: HardwareOptions{Device: path}}) + master, path := hardwarePty(t) + transport, err := OpenDriver("litetalk", Options{Hardware: HardwareOptions{Device: path}}) if err != nil { t.Fatal(err) } @@ -236,8 +232,8 @@ func TestSerialDisconnectReturnsError(t *testing.T) { } func TestSerialXoffPauseRemainsCancelable(t *testing.T) { - master, path := hardware_pty(t) - transport, err := Open_driver("dectalk", Options{Hardware: HardwareOptions{Device: path}}) + master, path := hardwarePty(t) + transport, err := OpenDriver("dectalk", Options{Hardware: HardwareOptions{Device: path}}) if err != nil { t.Fatal(err) } @@ -245,7 +241,7 @@ func TestSerialXoffPauseRemainsCancelable(t *testing.T) { if err := transport.Configure(Parameters{}); err != nil { t.Fatal(err) } - read_hardware(t, master, len("[:ra 180][:dv ap 122][:dv g5 73]")) + readHardware(t, master, len("[:ra 180][:dv ap 122][:dv g5 73]")) // Packet mode acknowledges that the terminal processed XOFF before the // write starts; this does not rely on a sleep or on filling a PTY buffer. packetMode := int32(1) @@ -255,7 +251,7 @@ func TestSerialXoffPauseRemainsCancelable(t *testing.T) { if _, err := syscall.Write(int(master.Fd()), []byte{0x13}); err != nil { t.Fatal(err) } - if got := read_hardware(t, master, 1)[0]; got&syscall.TIOCPKT_STOP == 0 { + if got := readHardware(t, master, 1)[0]; got&syscall.TIOCPKT_STOP == 0 { t.Fatal("XOFF was not processed", got) } packetMode = 0 @@ -276,7 +272,7 @@ func TestSerialXoffPauseRemainsCancelable(t *testing.T) { if err != nil { t.Fatal(err) } - configured := hardware_termios(t, slave) + configured := hardwareTermios(t, slave) syscall.Close(slave) if configured.Iflag&syscall.IXON == 0 { t.Fatal("cancellation did not restore XON/XOFF") @@ -289,94 +285,14 @@ func TestSerialXoffPauseRemainsCancelable(t *testing.T) { case <-time.After(time.Second): t.Fatal("cancel failed during flow pause") } - if got := string(read_hardware(t, master, 1)); got != "\x03" { + if got := string(readHardware(t, master, 1)); got != "\x03" { t.Fatal(got) } if err := transport.Say("resumed"); err != nil { t.Fatal(err) } want := "[:ra 180][:dv ap 122][:dv g5 73]resumed\x0b" - if got := string(read_hardware(t, master, len(want))); got != want { + if got := string(readHardware(t, master, len(want))); got != want { t.Fatal(got) } } - -func TestUSBCancelBypassesBlockedPacketAndDiscardsRemainingText(t *testing.T) { - started, release := make(chan struct{}), make(chan struct{}) - var releaseOnce sync.Once - unblock := func() { releaseOnce.Do(func() { close(release) }) } - defer unblock() - var normal, immediate atomic.Int32 - port := &usbPort{send: func(endpoint byte, data []byte) error { - if endpoint == 0x04 { - if !bytes.Equal(data, []byte{0x06}) { - return fmt.Errorf("bad cancellation %x", data) - } - immediate.Add(1) - } else if bytes.HasPrefix(data, []byte("xxx")) { - if normal.Add(1) == 1 { - close(started) - <-release - } - } - return nil - }} - client := new_hardware_client("dectalk-usb", Options{}, port) - done := make(chan error, 1) - go func() { done <- client.Say(strings.Repeat("x", 200)) }() - select { - case <-started: - case <-time.After(time.Second): - t.Fatal("packet not started") - } - if err := client.Cancel(); err != nil { - t.Fatal(err) - } - if immediate.Load() != 1 { - t.Fatal("immediate endpoint was blocked") - } - unblock() - select { - case err := <-done: - if err != nil { - t.Fatal(err) - } - case <-time.After(time.Second): - t.Fatal("stale send stuck") - } - if normal.Load() != 1 { - t.Fatal("more stale packets transmitted", normal.Load()) - } - client.Close() -} - -func TestUSBPacketLimitsFailureAndCleanup(t *testing.T) { - var sizes []int - closed := 0 - port := &usbPort{send: func(endpoint byte, data []byte) error { - if endpoint != 2 { - t.Fatal(endpoint) - } - sizes = append(sizes, len(data)) - return nil - }, close: func() { closed++ }} - if err := port.Write(make([]byte, 130), func() bool { return false }); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(sizes, []int{64, 64, 2}) { - t.Fatal(sizes) - } - failure := errors.New("short transfer") - port.send = func(byte, []byte) error { return failure } - if err := port.Write(make([]byte, 70), func() bool { return false }); !errors.Is(err, failure) { - t.Fatal(err) - } - port.Close() - port.Close() - if closed != 1 { - t.Fatal(closed) - } - if err := port.Write([]byte{1}, func() bool { return false }); err == nil { - t.Fatal("closed USB device accepted write") - } -} diff --git a/internal/speech/hardware_native.c b/internal/speech/hardware_native.c deleted file mode 100644 index 758290b7..00000000 --- a/internal/speech/hardware_native.c +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "hardware_native.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct SpeechSerial { - int fd; - struct termios original; -}; - -SpeechSerial *speech_serial_open(const char *path, int baud, int xon, int *status) { - SpeechSerial *port = calloc(1, sizeof(*port)); - *status = -ENOMEM; - if (!port) return NULL; - port->fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC); - if (port->fd < 0) goto failed; - // A short-lived candidate must never configure another reader's device. - if (flock(port->fd, LOCK_EX | LOCK_NB) < 0) goto failed; - if (tcgetattr(port->fd, &port->original) < 0) goto failed; - struct termios options = port->original; - cfmakeraw(&options); - options.c_cflag |= CLOCAL | CREAD; - options.c_cflag &= ~(CRTSCTS | CSTOPB); - options.c_iflag &= ~(IXON | IXOFF | IXANY); - if (xon) options.c_iflag |= IXON; - options.c_cc[VSTART] = 0x11; - options.c_cc[VSTOP] = 0x13; - speed_t speed; - switch (baud) { - case 1200: speed = B1200; break; - case 2400: speed = B2400; break; - case 4800: speed = B4800; break; - case 9600: speed = B9600; break; - case 19200: speed = B19200; break; - case 38400: speed = B38400; break; - case 57600: speed = B57600; break; - case 115200: speed = B115200; break; - default: errno = EINVAL; goto failed; - } - cfsetispeed(&options, speed); - cfsetospeed(&options, speed); - options.c_cc[VMIN] = 0; - options.c_cc[VTIME] = 0; - if (tcsetattr(port->fd, TCSANOW, &options) < 0) goto failed; - *status = 0; - return port; -failed: - *status = -errno; - if (port->fd >= 0) close(port->fd); - free(port); - return NULL; -} - -int speech_serial_write(SpeechSerial *port, const void *data, size_t length) { - ssize_t result = write(port->fd, data, length); - return result < 0 ? -errno : (int)result; -} - -int speech_serial_cancel(SpeechSerial *port, unsigned char command) { - if (tcflush(port->fd, TCOFLUSH) < 0) return -errno; - if (tcflow(port->fd, TCOON) < 0) return -errno; - // TCOON clears an explicit tcflow stop, but not a received XOFF in Linux's - // N_TTY discipline. Temporarily clearing IXON restarts that output path. - // Restore software flow control immediately after submitting the cancel. - struct termios options; - if (tcgetattr(port->fd, &options) < 0) return -errno; - int xon = (options.c_iflag & IXON) != 0; - if (xon) { - struct termios resumed = options; - resumed.c_iflag &= ~IXON; - if (tcsetattr(port->fd, TCSANOW, &resumed) < 0) return -errno; - } - int result = speech_serial_write(port, &command, 1); - if (xon && tcsetattr(port->fd, TCSANOW, &options) < 0) return -errno; - return result; -} - -void speech_serial_close(SpeechSerial *port) { - tcsetattr(port->fd, TCSANOW, &port->original); - close(port->fd); - free(port); -} - -// Optional libusb 1.0 ABI, resolved at runtime like Enchant. Neither headers -// nor a link-time libusb dependency are required for other speech drivers. -typedef struct libusb_context USBContext; -typedef struct libusb_device USBDevice; -typedef struct libusb_device_handle USBHandle; -struct USBDescriptor { - uint8_t length, type; - uint16_t usb; - uint8_t device_class, subclass, protocol, packet_size; - uint16_t vendor, product, device; - uint8_t manufacturer, product_name, serial, configurations; -}; - -struct SpeechUSB { - void *library; - USBContext *context; - USBHandle *handle; - int claimed; - int (*init)(USBContext **); - void (*exit)(USBContext *); - ssize_t (*get_device_list)(USBContext *, USBDevice ***); - void (*free_device_list)(USBDevice **, int); - int (*get_device_descriptor)(USBDevice *, struct USBDescriptor *); - int (*open)(USBDevice *, USBHandle **); - void (*close)(USBHandle *); - int (*get_configuration)(USBHandle *, int *); - int (*set_configuration)(USBHandle *, int); - int (*claim_interface)(USBHandle *, int); - int (*release_interface)(USBHandle *, int); - int (*bulk_transfer)(USBHandle *, unsigned char, unsigned char *, int, int *, unsigned int); -}; - -void speech_usb_close(SpeechUSB *port) { - if (!port) return; - if (port->claimed) port->release_interface(port->handle, 0); - if (port->handle) port->close(port->handle); - if (port->context) port->exit(port->context); - if (port->library) dlclose(port->library); - free(port); -} - -static SpeechUSB *load_usb(void) { - SpeechUSB *port = calloc(1, sizeof(*port)); - if (!port) return NULL; - port->library = dlopen("libusb-1.0.so.0", RTLD_NOW | RTLD_LOCAL); - if (!port->library) goto failed; -#define LOAD(field) port->field = dlsym(port->library, "libusb_" #field); if (!port->field) goto failed - LOAD(init); LOAD(exit); LOAD(get_device_list); LOAD(free_device_list); - LOAD(get_device_descriptor); LOAD(open); LOAD(close); - LOAD(get_configuration); LOAD(set_configuration); - LOAD(claim_interface); LOAD(release_interface); LOAD(bulk_transfer); -#undef LOAD - return port; -failed: - speech_usb_close(port); - return NULL; -} - -int speech_usb_available(void) { - SpeechUSB *port = load_usb(); - if (!port) return 0; - speech_usb_close(port); - return 1; -} - -SpeechUSB *speech_usb_open(int *status) { - *status = -100; - SpeechUSB *port = load_usb(); - if (!port) return NULL; - *status = port->init(&port->context); - if (*status < 0) goto failed; - USBDevice **devices = NULL; - ssize_t count = port->get_device_list(port->context, &devices); - if (count < 0) { *status = (int)count; goto failed; } - USBDevice *selected = NULL; - int matches = 0; - for (ssize_t index = 0; index < count; index++) { - struct USBDescriptor descriptor; - if (port->get_device_descriptor(devices[index], &descriptor) == 0 && - descriptor.vendor == 0x0dd0 && descriptor.product == 0x2001) { - selected = devices[index]; - matches++; - } - } - *status = matches == 0 ? -4 : -101; - if (matches == 1) *status = port->open(selected, &port->handle); - port->free_device_list(devices, 1); - if (*status < 0) goto failed; - int configuration = 0; - *status = port->get_configuration(port->handle, &configuration); - if (*status < 0) goto failed; - if (configuration == 0) { - *status = port->set_configuration(port->handle, 1); - if (*status < 0) goto failed; - } - *status = port->claim_interface(port->handle, 0); - if (*status < 0) goto failed; - port->claimed = 1; - return port; -failed: - speech_usb_close(port); - return NULL; -} - -int speech_usb_write(SpeechUSB *port, unsigned char endpoint, void *data, int length) { - int transferred = 0; - int result = port->bulk_transfer(port->handle, endpoint, data, length, &transferred, 1000); - // Never replay a partial failed transfer: it may already be on the wire. - if (result < 0) return result; - return transferred == length ? 0 : -102; -} diff --git a/internal/speech/hardware_native.h b/internal/speech/hardware_native.h deleted file mode 100644 index aca116a4..00000000 --- a/internal/speech/hardware_native.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later -#ifndef FENRIR_SPEECH_HARDWARE_H -#define FENRIR_SPEECH_HARDWARE_H -#include - -typedef struct SpeechSerial SpeechSerial; -SpeechSerial *speech_serial_open(const char *path, int baud, int xon, int *status); -int speech_serial_write(SpeechSerial *port, const void *data, size_t length); -int speech_serial_cancel(SpeechSerial *port, unsigned char command); -void speech_serial_close(SpeechSerial *port); - -typedef struct SpeechUSB SpeechUSB; -int speech_usb_available(void); -SpeechUSB *speech_usb_open(int *status); -int speech_usb_write(SpeechUSB *port, unsigned char endpoint, void *data, int length); -void speech_usb_close(SpeechUSB *port); -#endif diff --git a/internal/speech/hardware_preview.go b/internal/speech/hardware_preview.go index 39225868..6ff55130 100644 --- a/internal/speech/hardware_preview.go +++ b/internal/speech/hardware_preview.go @@ -9,11 +9,11 @@ import ( "time" ) -// Test_hardware opens a temporary client; it never replaces the reader's +// TestHardware opens a temporary client; it never replaces the reader's // transport. Keep the connection while the device speaks: Close cancels its // buffer, and these devices provide no speech-completion acknowledgement. -func Test_hardware(ctx context.Context, driverID string, options Options, text string) error { - driver, err := Find_driver(driverID) +func TestHardware(ctx context.Context, driverID string, options Options, text string) error { + driver, err := FindDriver(driverID) if err != nil { return err } @@ -25,7 +25,7 @@ func Test_hardware(ctx context.Context, driverID string, options Options, text s if err := ctx.Err(); err != nil { return err } - client, err := Open_driver(driverID, options) + client, err := OpenDriver(driverID, options) if err != nil { return err } diff --git a/internal/speech/hardware_test.go b/internal/speech/hardware_test.go index 9560568a..0b315fc6 100644 --- a/internal/speech/hardware_test.go +++ b/internal/speech/hardware_test.go @@ -8,6 +8,9 @@ import ( "reflect" "strings" "testing" + "time" + + "git.stormux.org/storm/screenreader-common/hardware/transport" ) type recordingHardware struct { @@ -19,7 +22,7 @@ type recordingHardware struct { func (p *recordingHardware) Write(data []byte, canceled func() bool) error { if canceled() { - return errHardwareCanceled + return transport.ErrCanceled } if p.fail != nil { return p.fail @@ -37,7 +40,7 @@ func TestHardwareProtocolsMatchPythonFixtures(t *testing.T) { for _, id := range []string{"dectalk", "dectalk-usb", "litetalk", "doubletalk", "tripletalk"} { t.Run(id, func(t *testing.T) { port := &recordingHardware{} - client := new_hardware_client(id, Options{}, port) + client := newHardwareClient(id, Options{}, port) parameters := Parameters{Rate: 100, Pitch: -100, Volume: 0} if err := client.Configure(parameters); err != nil { t.Fatal(err) @@ -105,7 +108,7 @@ func TestHardwareRangesAndNativeMidpoints(t *testing.T) { func TestHardwareFailedSettingsAreRetriedAndPitchRestores(t *testing.T) { port := &recordingHardware{fail: errors.New("disconnected")} - client := new_hardware_client("dectalk", Options{}, port) + client := newHardwareClient("dectalk", Options{}, port) if err := client.Configure(Parameters{}); err == nil { t.Fatal("failed write accepted") } @@ -113,13 +116,13 @@ func TestHardwareFailedSettingsAreRetriedAndPitchRestores(t *testing.T) { if err := client.Configure(Parameters{}); err != nil { t.Fatal(err) } - if err := client.Set_pitch(100); err != nil { + if err := client.SetPitch(100); err != nil { t.Fatal(err) } if err := client.Say("A"); err != nil { t.Fatal(err) } - if err := client.Set_pitch(0); err != nil { + if err := client.SetPitch(0); err != nil { t.Fatal(err) } want := []string{"[:ra 180]", "[:dv ap 122]", "[:dv g5 73]", "[:dv ap 350]", "A\x0b", "[:dv ap 122]"} @@ -129,7 +132,7 @@ func TestHardwareFailedSettingsAreRetriedAndPitchRestores(t *testing.T) { if err := client.Configure(Parameters{Rate: 101}); err == nil { t.Fatal("invalid rate accepted") } - if err := client.Set_pitch(-101); err == nil { + if err := client.SetPitch(-101); err == nil { t.Fatal("invalid pitch accepted") } } @@ -137,24 +140,78 @@ func TestHardwareFailedSettingsAreRetriedAndPitchRestores(t *testing.T) { func TestHardwareValidationDoesNotOpenDevices(t *testing.T) { for _, id := range []string{"dectalk", "litetalk", "doubletalk", "tripletalk"} { options := Options{Hardware: HardwareOptions{Device: "/dev/fixture-synth"}} - if err := Validate_driver_options(id, options); err != nil { + if err := ValidateDriverOptions(id, options); err != nil { t.Fatal(id, err) } for _, path := range []string{"", "auto", "ttyUSB0", "/dev/ttyUSB0\n"} { options.Hardware.Device = path - if err := Validate_driver_options(id, options); err == nil { + if err := ValidateDriverOptions(id, options); err == nil { t.Fatal(id, path) } } options.Hardware = HardwareOptions{Device: "/dev/fixture-synth", BaudRate: 12345} - if err := Validate_driver_options(id, options); err == nil { + if err := ValidateDriverOptions(id, options); err == nil { t.Fatal("unsupported baud accepted") } } - if err := Validate_driver_options("dectalk-usb", Options{}); err != nil { + if err := ValidateDriverOptions("dectalk-usb", Options{}); err != nil { t.Fatal(err) } - if err := Validate_driver_options("dectalk-usb", Options{Voice: "invented"}); err == nil { + if err := ValidateDriverOptions("dectalk-usb", Options{Voice: "invented"}); err == nil { t.Fatal("hardware voice accepted") } } + +// blockingHardware holds its first write until released, then reports +// whether the client canceled it meanwhile, as the shared transport does. +type blockingHardware struct { + started, release chan struct{} + writes, cancels chan string +} + +func (p *blockingHardware) Write(data []byte, canceled func() bool) error { + if strings.HasPrefix(string(data), "xxx") { + close(p.started) + <-p.release + if canceled() { + return transport.ErrCanceled + } + } + p.writes <- string(data) + return nil +} +func (p *blockingHardware) Cancel(data []byte) error { p.cancels <- string(data); return nil } +func (p *blockingHardware) Close() {} + +func TestHardwareCancelBypassesBlockedWriteAndDropsStaleText(t *testing.T) { + port := &blockingHardware{started: make(chan struct{}), release: make(chan struct{}), writes: make(chan string, 8), cancels: make(chan string, 2)} + client := newHardwareClient("dectalk-usb", Options{}, port) + done := make(chan error, 1) + go func() { done <- client.Say(strings.Repeat("x", 200)) }() + select { + case <-port.started: + case <-time.After(time.Second): + t.Fatal("write not started") + } + if err := client.Cancel(); err != nil { + t.Fatal(err) + } + if got := <-port.cancels; got != "\x06" { + t.Fatalf("cancel %q", got) + } + close(port.release) + select { + case err := <-done: + if err != nil { + t.Fatal("cancellation surfaced as an error", err) + } + case <-time.After(time.Second): + t.Fatal("stale write stuck") + } + for len(port.writes) > 0 { + if got := <-port.writes; strings.Contains(got, "xxx") { + t.Fatal("stale text transmitted") + } + } + client.Close() +} diff --git a/internal/speech/hardware_usb_native_test.go b/internal/speech/hardware_usb_native_test.go deleted file mode 100644 index ee0d0ebf..00000000 --- a/internal/speech/hardware_usb_native_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later - -//go:build linux && cgo - -package speech - -import ( - "encoding/hex" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -func TestNativeUSBUsesOptionalABIAndReleasesResources(t *testing.T) { - root := t.TempDir() - library := filepath.Join(root, "libusb-1.0.so.0") - if output, err := exec.Command("cc", "-shared", "-fPIC", "-Wall", "-Wextra", "-Werror", "-o", library, "testdata/usb_fixture.c").CombinedOutput(); err != nil { - t.Fatalf("build USB fixture: %v: %s", err, output) - } - for _, mode := range []string{"ok", "unconfigured", "missing", "multiple", "denied", "busy", "short", "timeout"} { - t.Run(mode, func(t *testing.T) { - log := filepath.Join(t.TempDir(), "usb.log") - cmd := exec.Command(os.Args[0], "-test.run=^TestNativeUSBFixtureProcess$") - cmd.Env = append(os.Environ(), "LD_LIBRARY_PATH="+root, "FENRIR_USB_FIXTURE=1", "USB_FIXTURE_MODE="+mode, "USB_FIXTURE_LOG="+log) - if output, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("fixture process: %v: %s", err, output) - } - data, err := os.ReadFile(log) - if err != nil { - t.Fatal(err) - } - text := string(data) - if !strings.HasPrefix(text, "init\nlist\n") || !strings.Contains(text, "free-list\n") || !strings.HasSuffix(text, "exit\n") { - t.Fatal("USB cleanup", text) - } - opened := mode != "missing" && mode != "multiple" && mode != "denied" - if strings.Contains(text, "\nclose\n") != opened { - t.Fatal("handle cleanup", text) - } - claimed := opened && mode != "busy" - if strings.Contains(text, "\nrelease\n") != claimed { - t.Fatal("interface cleanup", text) - } - if mode == "ok" || mode == "unconfigured" { - for _, want := range []string{"write-02:" + hex.EncodeToString([]byte("[:timeout 1]")), "write-02:" + hex.EncodeToString([]byte("[:ra 180]")), "write-02:" + hex.EncodeToString([]byte("hello\x0b")), "write-04:06"} { - if !strings.Contains(text, want+"\n") { - t.Fatal("missing transfer", want, text) - } - } - } - if strings.Contains(text, "set-configuration\n") != (mode == "unconfigured") { - t.Fatal("unexpected USB configuration change", text) - } - }) - } -} - -func TestNativeUSBFixtureProcess(t *testing.T) { - if os.Getenv("FENRIR_USB_FIXTURE") != "1" { - return - } - transport, err := Open_driver("dectalk-usb", Options{}) - mode := os.Getenv("USB_FIXTURE_MODE") - if mode != "ok" && mode != "unconfigured" { - if err == nil { - transport.Close() - t.Fatal("USB failure accepted", mode) - } - return - } - if err != nil { - t.Fatal(err) - } - defer transport.Close() - if err := transport.Configure(Parameters{}); err != nil { - t.Fatal(err) - } - if err := transport.Say("hello"); err != nil { - t.Fatal(err) - } - if err := transport.Cancel(); err != nil { - t.Fatal(err) - } -} diff --git a/internal/speech/latency_test.go b/internal/speech/latency_test.go index 23c56675..fc45be30 100644 --- a/internal/speech/latency_test.go +++ b/internal/speech/latency_test.go @@ -30,13 +30,13 @@ func TestTimingDiagnosticsExcludeSpeechText(t *testing.T) { previousLogger := slog.Default() slog.SetDefault(slog.New(slog.NewTextHandler(&output, &slog.HandlerOptions{Level: slog.LevelDebug}))) defer slog.SetDefault(previousLogger) - fake := new_recording_transport() + fake := newRecordingTransport() s := New(fake) defer s.Close() const privateText = "private speech fixture" s.Interrupt() s.Say(privateText) - wait_event(t, fake.changed, "sent:"+privateText) + waitEvent(t, fake.changed, "sent:"+privateText) s.Close() if strings.Contains(output.String(), privateText) { t.Fatal("timing diagnostics included speech text") @@ -55,7 +55,7 @@ type latencyTransport struct { func (f *latencyTransport) Say(string) error { f.sent <- struct{}{}; return nil } func (f *latencyTransport) Cancel() error { time.Sleep(time.Millisecond); return nil } func (f *latencyTransport) Close() {} -func (f *latencyTransport) Set_pitch(int) error { return nil } +func (f *latencyTransport) SetPitch(int) error { return nil } func (f *latencyTransport) Configure(Parameters) error { return nil } // Model a fixed acknowledgement cost to expose unnecessary cancellation waits. diff --git a/internal/speech/prelude_test.go b/internal/speech/prelude_test.go index 41ed9dba..05f35670 100644 --- a/internal/speech/prelude_test.go +++ b/internal/speech/prelude_test.go @@ -11,11 +11,11 @@ import ( ) func TestSpeechPreludeFinishesBeforeSpeechAndPreservesFIFO(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() service := New(fake) defer service.Close() release := make(chan struct{}) - service.Say_after("notification", func(ctx context.Context) { + service.SayAfter("notification", func(ctx context.Context) { fake.record("sound:start") select { case <-release: @@ -24,7 +24,7 @@ func TestSpeechPreludeFinishesBeforeSpeechAndPreservesFIFO(t *testing.T) { fake.record("sound:drained") }) service.Say("following text") - wait_event(t, fake.changed, "sound:start") + waitEvent(t, fake.changed, "sound:start") fake.mu.Lock() events := append([]string(nil), fake.events...) fake.mu.Unlock() @@ -32,7 +32,7 @@ func TestSpeechPreludeFinishesBeforeSpeechAndPreservesFIFO(t *testing.T) { t.Fatal(events) } close(release) - wait_event(t, fake.changed, "sent:following text") + waitEvent(t, fake.changed, "sent:following text") fake.mu.Lock() defer fake.mu.Unlock() want := []string{"sound:start", "sound:drained", "say:notification", "sent:notification", "say:following text", "sent:following text"} @@ -44,11 +44,11 @@ func TestSpeechPreludeFinishesBeforeSpeechAndPreservesFIFO(t *testing.T) { func TestSpeechPreludeInterruptMuteAndCloseDiscardDelayedSpeech(t *testing.T) { for _, action := range []string{"interrupt", "mute", "close"} { t.Run(action, func(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() service := New(fake) defer service.Close() entered, stopped := make(chan struct{}), make(chan struct{}) - service.Say_after("discarded notification", func(ctx context.Context) { + service.SayAfter("discarded notification", func(ctx context.Context) { close(entered) <-ctx.Done() close(stopped) @@ -58,7 +58,7 @@ func TestSpeechPreludeInterruptMuteAndCloseDiscardDelayedSpeech(t *testing.T) { case "interrupt": service.Interrupt() case "mute": - service.Toggle_mute() + service.ToggleMute() case "close": service.Close() } @@ -68,11 +68,11 @@ func TestSpeechPreludeInterruptMuteAndCloseDiscardDelayedSpeech(t *testing.T) { t.Fatal("sound wait was not canceled") } if action == "mute" { - service.Toggle_mute() + service.ToggleMute() } if action != "close" { service.Say("fresh review") - wait_event(t, fake.changed, "sent:fresh review") + waitEvent(t, fake.changed, "sent:fresh review") } fake.mu.Lock() defer fake.mu.Unlock() diff --git a/internal/speech/recovery_test.go b/internal/speech/recovery_test.go index 6f223b43..6a5d9f70 100644 --- a/internal/speech/recovery_test.go +++ b/internal/speech/recovery_test.go @@ -39,8 +39,8 @@ func (f *disconnectedTransport) Reopen(ctx context.Context) (Transport, error) { func TestRecoveryKeepsAdmissionResponsiveAndDropsOutageSpeech(t *testing.T) { entered, release := make(chan struct{}), make(chan struct{}) - fresh := new_recording_transport() - broken := &disconnectedTransport{recordingTransport: new_recording_transport(), reopen: func(ctx context.Context) (Transport, error) { + fresh := newRecordingTransport() + broken := &disconnectedTransport{recordingTransport: newRecordingTransport(), reopen: func(ctx context.Context) (Transport, error) { close(entered) select { case <-release: @@ -59,7 +59,7 @@ func TestRecoveryKeepsAdmissionResponsiveAndDropsOutageSpeech(t *testing.T) { service.Interrupt() service.Configure(Parameters{Rate: 70, Pitch: 10, Volume: 90}) service.Say("discarded during outage") - service.Toggle_mute() + service.ToggleMute() service.Say("discarded while muted") close(admitted) }() @@ -69,11 +69,11 @@ func TestRecoveryKeepsAdmissionResponsiveAndDropsOutageSpeech(t *testing.T) { t.Fatal("audio recovery blocked input admission") } close(release) - wait_event(t, fresh.changed, "configure:70:10:90") - service.Toggle_mute() - service.Say_with_pitch("fresh", 60) - wait_event(t, fresh.changed, "sent:fresh") - wait_event(t, fresh.changed, "pitch:10") + waitEvent(t, fresh.changed, "configure:70:10:90") + service.ToggleMute() + service.SayWithPitch("fresh", 60) + waitEvent(t, fresh.changed, "sent:fresh") + waitEvent(t, fresh.changed, "pitch:10") fresh.mu.Lock() joined := strings.Join(fresh.events, "|") fresh.mu.Unlock() @@ -91,7 +91,7 @@ func TestRecoveryFailureIsFatalAndShutdownCancelsReopen(t *testing.T) { for _, failure := range []bool{true, false} { t.Run(strconv.FormatBool(failure), func(t *testing.T) { entered := make(chan struct{}) - broken := &disconnectedTransport{recordingTransport: new_recording_transport(), reopen: func(ctx context.Context) (Transport, error) { + broken := &disconnectedTransport{recordingTransport: newRecordingTransport(), reopen: func(ctx context.Context) (Transport, error) { close(entered) if failure { return nil, syscall.EACCES @@ -124,7 +124,7 @@ func TestRecoveryFailureIsFatalAndShutdownCancelsReopen(t *testing.T) { } func TestSpeechRecoveryDeadlineReportsFailure(t *testing.T) { - broken := &disconnectedTransport{recordingTransport: new_recording_transport(), reopen: func(ctx context.Context) (Transport, error) { + broken := &disconnectedTransport{recordingTransport: newRecordingTransport(), reopen: func(ctx context.Context) (Transport, error) { <-ctx.Done() return nil, ctx.Err() }} @@ -155,14 +155,14 @@ func TestOpenContextCancelsSilentHandshakeAndDoesNotOwnLiveClient(t *testing.T) ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) defer cancel() started := time.Now() - client, err := Open_driver_context(ctx, "speech-dispatcher", Options{Socket: listener.Addr().String()}) + client, err := OpenDriverContext(ctx, "speech-dispatcher", Options{Socket: listener.Addr().String()}) if client != nil || err == nil || time.Since(started) > time.Second { t.Fatal("silent handshake ignored cancellation", client, err) } (<-accepted).Close() - server := new_fake_server(t, false) + server := newFakeServer(t, false) ctx, cancel = context.WithCancel(context.Background()) - client, err = Open_driver_context(ctx, "speech-dispatcher", Options{Socket: server.path}) + client, err = OpenDriverContext(ctx, "speech-dispatcher", Options{Socket: server.path}) if err != nil { t.Fatal(err) } @@ -213,7 +213,7 @@ func TestStartupWithoutSudoRetriesUntilPrivateDaemonAppears(t *testing.T) { go func() { result <- audio.Retry(ctx, func(ctx context.Context) error { var err error - client, err = Open_driver_context(ctx, "speech-dispatcher", Options{}) + client, err = OpenDriverContext(ctx, "speech-dispatcher", Options{}) if err != nil { select { case failed <- struct{}{}: @@ -232,7 +232,7 @@ func TestStartupWithoutSudoRetriesUntilPrivateDaemonAppears(t *testing.T) { if err != nil { t.Fatal(err) } - server := new_fake_server_listener(t, false, listener) + server := newFakeServerListener(t, false, listener) if err := <-result; err != nil { t.Fatal(err) } @@ -244,11 +244,11 @@ func TestStartupWithoutSudoRetriesUntilPrivateDaemonAppears(t *testing.T) { if err := client.Say("late daemon ready"); err != nil { t.Fatal(err) } - wait_event(t, server.events, "say:late daemon ready") + waitEvent(t, server.events, "say:late daemon ready") } func TestClientReconnectsAfterPrivateServerDropsBothConnections(t *testing.T) { - server := new_fake_server(t, false) + server := newFakeServer(t, false) client, err := Open(Options{Socket: server.path}) if err != nil { t.Fatal(err) @@ -257,7 +257,7 @@ func TestClientReconnectsAfterPrivateServerDropsBothConnections(t *testing.T) { defer service.Close() service.Configure(Parameters{Rate: 30, Pitch: 10, Volume: 70}) service.Say("before disconnect") - wait_event(t, server.events, "say:before disconnect") + waitEvent(t, server.events, "say:before disconnect") server.mu.Lock() for _, conn := range server.connections { conn.Close() @@ -286,5 +286,5 @@ func TestClientReconnectsAfterPrivateServerDropsBothConnections(t *testing.T) { } } service.Say("after reconnect") - wait_event(t, server.events, "say:after reconnect") + waitEvent(t, server.events, "say:after reconnect") } diff --git a/internal/speech/replacement_test.go b/internal/speech/replacement_test.go index 531a8b01..742aeedd 100644 --- a/internal/speech/replacement_test.go +++ b/internal/speech/replacement_test.go @@ -31,31 +31,31 @@ func (f *replacementTransport) Configure(p Parameters) error { } func TestReplacementPreservesMuteParametersAndFailureRecovery(t *testing.T) { - old := &replacementTransport{recordingTransport: new_recording_transport()} + old := &replacementTransport{recordingTransport: newRecordingTransport()} service := New(old) defer service.Close() service.Configure(Parameters{Rate: 55, Pitch: 12, Volume: 80}) - wait_event(t, old.changed, "configure:55:12:80") - bad := &replacementTransport{recordingTransport: new_recording_transport(), configureErr: errors.New("fixture refusal")} + waitEvent(t, old.changed, "configure:55:12:80") + bad := &replacementTransport{recordingTransport: newRecordingTransport(), configureErr: errors.New("fixture refusal")} if err := service.Replace(bad); err == nil || !bad.closed.Load() || old.closed.Load() { t.Fatal("failed replacement changed active client", err) } service.Say("old survives") - wait_event(t, old.changed, "sent:old survives") - service.Toggle_mute() + waitEvent(t, old.changed, "sent:old survives") + service.ToggleMute() service.Say("discarded") - next := &replacementTransport{recordingTransport: new_recording_transport()} + next := &replacementTransport{recordingTransport: newRecordingTransport()} if err := service.Replace(next); err != nil { t.Fatal(err) } if !old.closed.Load() { t.Fatal("old client not released") } - wait_event(t, next.changed, "configure:55:12:80") - service.Toggle_mute() - service.Say_with_pitch("E", 70) + waitEvent(t, next.changed, "configure:55:12:80") + service.ToggleMute() + service.SayWithPitch("E", 70) service.Say("new feedback") - wait_event(t, next.changed, "sent:new feedback") + waitEvent(t, next.changed, "sent:new feedback") next.mu.Lock() defer next.mu.Unlock() for _, event := range next.events { @@ -66,11 +66,11 @@ func TestReplacementPreservesMuteParametersAndFailureRecovery(t *testing.T) { } func TestShutdownDuringReplacementClosesBothClients(t *testing.T) { - old := &replacementTransport{recordingTransport: new_recording_transport()} + old := &replacementTransport{recordingTransport: newRecordingTransport()} service := New(old) service.Configure(Parameters{Volume: 100}) - wait_event(t, old.changed, "configure:0:0:100") - next := &replacementTransport{recordingTransport: new_recording_transport(), configured: make(chan struct{}), resume: make(chan struct{})} + waitEvent(t, old.changed, "configure:0:0:100") + next := &replacementTransport{recordingTransport: newRecordingTransport(), configured: make(chan struct{}), resume: make(chan struct{})} done := make(chan error, 1) go func() { done <- service.Replace(next) }() <-next.configured diff --git a/internal/speech/service.go b/internal/speech/service.go index 5c52b1a7..549673fc 100644 --- a/internal/speech/service.go +++ b/internal/speech/service.go @@ -35,7 +35,7 @@ type Transport interface { // naming so the shared punctuation processor's names are spoken once. Say(string) error Configure(Parameters) error - Set_pitch(int) error + SetPitch(int) error Cancel() error Close() } @@ -134,15 +134,15 @@ func (s *Service) Say(text string) { s.enqueue(utterance{text: text}) } -// Say_after keeps a cancellable sound prelude and its speech in one FIFO +// SayAfter keeps a cancellable sound prelude and its speech in one FIFO // entry. Neither the prelude nor later speech runs on the input dispatcher. -func (s *Service) Say_after(text string, before func(context.Context)) { +func (s *Service) SayAfter(text string, before func(context.Context)) { s.enqueue(utterance{text: text, before: before}) } -// Say_with_parameters previews one utterance without changing saved or live +// SayWithParameters previews one utterance without changing saved or live // defaults. The serialized worker restores its latest normal parameters. -func (s *Service) Say_with_parameters(text string, parameters Parameters) { +func (s *Service) SayWithParameters(text string, parameters Parameters) { if err := parameters.Validate(); err != nil { s.fail(err) return @@ -150,9 +150,9 @@ func (s *Service) Say_with_parameters(text string, parameters Parameters) { s.enqueue(utterance{text: text, parameters: ¶meters}) } -// Say_with_pitch scopes the override and restoration to one queued request. +// SayWithPitch scopes the override and restoration to one queued request. // Interruption discards both together; configuration never leaks into later speech. -func (s *Service) Say_with_pitch(text string, pitch int) { +func (s *Service) SayWithPitch(text string, pitch int) { if pitch < -100 || pitch > 100 { s.fail(errors.New("speech pitch must be between -100 and 100")) return @@ -193,7 +193,7 @@ func (s *Service) interrupt() { signal(s.cancelWake) } -func (s *Service) Toggle_mute() bool { +func (s *Service) ToggleMute() bool { s.mu.Lock() defer s.mu.Unlock() if s.closed { @@ -217,7 +217,7 @@ func (s *Service) fail(err error) { // Recovery belongs to the delivery worker. Admission and cancellation never // wait for a new daemon, and speech from the outage is never replayed. -func (s *Service) recover_transport(problem error, parameters *Parameters) bool { +func (s *Service) recoverTransport(problem error, parameters *Parameters) bool { reopener, ok := s.transport.(interface { Reopen(context.Context) (Transport, error) }) @@ -291,7 +291,7 @@ func (s *Service) deliver() { return case <-s.wake: case fault := <-s.faults: - if fault.epoch == s.transportEpoch && !s.recover_transport(fault.err, currentParameters) { + if fault.epoch == s.transportEpoch && !s.recoverTransport(fault.err, currentParameters) { return } } @@ -307,7 +307,7 @@ func (s *Service) deliver() { err := s.transport.Configure(parameters) s.dispatch.Unlock() if err != nil { - if !s.recover_transport(err, currentParameters) { + if !s.recoverTransport(err, currentParameters) { return } } @@ -379,7 +379,7 @@ func (s *Service) deliver() { diagnostic.Timing("speech send", started, "generation", generation) s.dispatch.Unlock() if err != nil { - if !s.recover_transport(err, currentParameters) { + if !s.recoverTransport(err, currentParameters) { return } } @@ -401,14 +401,14 @@ func (s *Service) say(item utterance, normalPitch int, normalParameters *Paramet if item.pitch == nil { return s.transport.Say(item.text) } - if err := s.transport.Set_pitch(*item.pitch); err != nil { + if err := s.transport.SetPitch(*item.pitch); err != nil { return err } err := s.transport.Say(item.text) - return errors.Join(err, s.transport.Set_pitch(normalPitch)) + return errors.Join(err, s.transport.SetPitch(normalPitch)) } -func (s *Service) cancel_transport() error { +func (s *Service) cancelTransport() error { s.transportMu.RLock() defer s.transportMu.RUnlock() if s.transport == nil { @@ -448,12 +448,12 @@ func (s *Service) cancel() { if !s.dispatch.TryLock() { // Stop audible speech even while a stale send is blocked. A // second cancel after that send finishes closes the late-send race. - _ = s.cancel_transport() + _ = s.cancelTransport() s.dispatch.Lock() } // With dispatch held, no send can race this cancel. The usual // idle-send path needs only this one acknowledgement. - _ = s.cancel_transport() + _ = s.cancelTransport() diagnostic.Timing("speech cancel barrier", started, "generation", generation) s.mu.Lock() // Every intervening interrupt is covered: fresh sends have been diff --git a/internal/speech/service_test.go b/internal/speech/service_test.go index bba81fbd..40c861cc 100644 --- a/internal/speech/service_test.go +++ b/internal/speech/service_test.go @@ -35,7 +35,7 @@ type recordingTransport struct { once sync.Once } -func new_recording_transport() *recordingTransport { +func newRecordingTransport() *recordingTransport { return &recordingTransport{changed: make(chan string, 64), release: make(chan struct{})} } @@ -55,7 +55,7 @@ func (f *recordingTransport) Say(text string) error { return nil } -func (f *recordingTransport) Set_pitch(pitch int) error { +func (f *recordingTransport) SetPitch(pitch int) error { f.record(fmt.Sprintf("pitch:%d", pitch)) return nil } @@ -69,17 +69,17 @@ func (f *recordingTransport) unblock() { f.once.Do(func() { close(f.release) }) func (f *recordingTransport) Close() { f.unblock() } func TestConfigurationSurvivesInterruptAndMuteBeforeFeedback(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() service := New(fake) defer service.Close() service.Say("old") - wait_event(t, fake.changed, "say:old") + waitEvent(t, fake.changed, "say:old") service.Configure(Parameters{Rate: 70, Pitch: 10, Volume: 90}) service.Interrupt() service.Configure(Parameters{Rate: 90, Pitch: 20, Volume: 80}) service.Say("new feedback") fake.unblock() - wait_event(t, fake.changed, "sent:new feedback") + waitEvent(t, fake.changed, "sent:new feedback") fake.mu.Lock() events := append([]string(nil), fake.events...) fake.mu.Unlock() @@ -95,22 +95,22 @@ func TestConfigurationSurvivesInterruptAndMuteBeforeFeedback(t *testing.T) { if configured < 0 || configured >= spoken { t.Fatal(events) } - service.Toggle_mute() + service.ToggleMute() service.Configure(Parameters{Rate: 100, Pitch: 0, Volume: 100}) - wait_event(t, fake.changed, "configure:100:0:100") - service.Toggle_mute() + waitEvent(t, fake.changed, "configure:100:0:100") + service.ToggleMute() service.Say("unmuted feedback") - wait_event(t, fake.changed, "sent:unmuted feedback") + waitEvent(t, fake.changed, "sent:unmuted feedback") } func TestParameterPreviewRestoresNormalParametersBeforeLaterSpeech(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() service := New(fake) defer service.Close() service.Configure(Parameters{Rate: 40, Pitch: 10, Volume: 90}) - service.Say_with_parameters("preview", Parameters{Rate: -20, Pitch: 30, Volume: 50}) + service.SayWithParameters("preview", Parameters{Rate: -20, Pitch: 30, Volume: 50}) service.Say("normal") - wait_event(t, fake.changed, "sent:normal") + waitEvent(t, fake.changed, "sent:normal") fake.mu.Lock() defer fake.mu.Unlock() want := []string{"configure:40:10:90", "configure:-20:30:50", "say:preview", "sent:preview", "configure:40:10:90", "say:normal", "sent:normal"} @@ -120,13 +120,13 @@ func TestParameterPreviewRestoresNormalParametersBeforeLaterSpeech(t *testing.T) } func TestCapitalPitchRestoresBeforeFollowingSpeech(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() service := New(fake) defer service.Close() service.Configure(Parameters{Rate: 80, Pitch: 10, Volume: 100}) - service.Say_with_pitch("E", 60) + service.SayWithPitch("E", 60) service.Say("e") - wait_event(t, fake.changed, "sent:e") + waitEvent(t, fake.changed, "sent:e") fake.mu.Lock() defer fake.mu.Unlock() want := []string{"configure:80:10:100", "pitch:60", "say:E", "sent:E", "pitch:10", "say:e", "sent:e"} @@ -136,20 +136,20 @@ func TestCapitalPitchRestoresBeforeFollowingSpeech(t *testing.T) { } func TestInterruptedCapitalDoesNotLeakPitchOrReplayQueuedCapital(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() service := New(fake) defer service.Close() service.Configure(Parameters{Rate: 80, Pitch: -10, Volume: 100}) - service.Say_with_pitch("old", 60) - wait_event(t, fake.changed, "say:old") - service.Say_with_pitch("discarded", 70) + service.SayWithPitch("old", 60) + waitEvent(t, fake.changed, "say:old") + service.SayWithPitch("discarded", 70) service.Interrupt() service.Configure(Parameters{Rate: 90, Pitch: 20, Volume: 100}) - service.Say_with_pitch("E", 80) + service.SayWithPitch("E", 80) service.Say("fresh") - wait_event(t, fake.changed, "cancel") + waitEvent(t, fake.changed, "cancel") fake.unblock() - wait_event(t, fake.changed, "sent:fresh") + waitEvent(t, fake.changed, "sent:fresh") fake.mu.Lock() defer fake.mu.Unlock() joined := strings.Join(fake.events, "|") @@ -158,7 +158,7 @@ func TestInterruptedCapitalDoesNotLeakPitchOrReplayQueuedCapital(t *testing.T) { } } -func wait_event(t *testing.T, events <-chan string, expected string) { +func waitEvent(t *testing.T, events <-chan string, expected string) { t.Helper() timeout := time.NewTimer(2 * time.Second) defer timeout.Stop() @@ -175,15 +175,15 @@ func wait_event(t *testing.T, events <-chan string, expected string) { } func TestPassiveSpeechIsFIFOWithoutCancellation(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() s := New(fake) defer s.Close() s.Say("old") - wait_event(t, fake.changed, "say:old") + waitEvent(t, fake.changed, "say:old") s.Say("second") s.Say("third") fake.unblock() - wait_event(t, fake.changed, "sent:third") + waitEvent(t, fake.changed, "sent:third") fake.mu.Lock() defer fake.mu.Unlock() if want := []string{"say:old", "sent:old", "say:second", "sent:second", "say:third", "sent:third"}; !reflect.DeepEqual(fake.events, want) { @@ -192,12 +192,12 @@ func TestPassiveSpeechIsFIFOWithoutCancellation(t *testing.T) { } func TestIdleInterruptNeedsOnlyOneCancellation(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() s := New(fake) defer s.Close() s.Interrupt() s.Say("fresh") - wait_event(t, fake.changed, "sent:fresh") + waitEvent(t, fake.changed, "sent:fresh") fake.mu.Lock() defer fake.mu.Unlock() want := []string{"cancel", "say:fresh", "sent:fresh"} @@ -207,18 +207,18 @@ func TestIdleInterruptNeedsOnlyOneCancellation(t *testing.T) { } func TestInterruptCancelsBlockedSendAndGatesFreshSpeech(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() s := New(fake) defer s.Close() s.Say("old") - wait_event(t, fake.changed, "say:old") + waitEvent(t, fake.changed, "say:old") s.Say("discarded") s.Interrupt() s.Say("fresh") // This must arrive while Say is blocked, before its acknowledgement. - wait_event(t, fake.changed, "cancel") + waitEvent(t, fake.changed, "cancel") fake.unblock() - wait_event(t, fake.changed, "sent:fresh") + waitEvent(t, fake.changed, "sent:fresh") fake.mu.Lock() defer fake.mu.Unlock() want := []string{"say:old", "cancel", "sent:old", "cancel", "say:fresh", "sent:fresh"} @@ -228,22 +228,22 @@ func TestInterruptCancelsBlockedSendAndGatesFreshSpeech(t *testing.T) { } func TestMuteDiscardsSuppressedSpeechAndUnmuteDoesNotReplay(t *testing.T) { - fake := new_recording_transport() + fake := newRecordingTransport() s := New(fake) defer s.Close() s.Say("old") - wait_event(t, fake.changed, "say:old") + waitEvent(t, fake.changed, "say:old") s.Say("discarded") - if !s.Toggle_mute() { + if !s.ToggleMute() { t.Fatal("mute failed") } s.Say("suppressed") - if s.Toggle_mute() { + if s.ToggleMute() { t.Fatal("unmute failed") } s.Say("fresh") fake.unblock() - wait_event(t, fake.changed, "sent:fresh") + waitEvent(t, fake.changed, "sent:fresh") fake.mu.Lock() defer fake.mu.Unlock() for _, event := range fake.events { @@ -269,22 +269,22 @@ func (f *gatedCancelTransport) Cancel() error { return nil } -func (f *gatedCancelTransport) open_gate() { f.gateOnce.Do(func() { close(f.gate) }) } -func (f *gatedCancelTransport) Close() { f.open_gate(); f.recordingTransport.Close() } +func (f *gatedCancelTransport) openGate() { f.gateOnce.Do(func() { close(f.gate) }) } +func (f *gatedCancelTransport) Close() { f.openGate(); f.recordingTransport.Close() } func TestRapidInterruptsDoNotRecancelSettledGeneration(t *testing.T) { - fake := &gatedCancelTransport{recordingTransport: new_recording_transport(), gate: make(chan struct{})} + fake := &gatedCancelTransport{recordingTransport: newRecordingTransport(), gate: make(chan struct{})} s := New(fake) defer s.Close() s.Say("old") - wait_event(t, fake.changed, "say:old") + waitEvent(t, fake.changed, "say:old") s.Interrupt() - wait_event(t, fake.changed, "cancel:1") + waitEvent(t, fake.changed, "cancel:1") s.Interrupt() // Leaves a wake token while cancellation is already running. s.Say("fresh") - fake.open_gate() + fake.openGate() fake.unblock() - wait_event(t, fake.changed, "sent:fresh") + waitEvent(t, fake.changed, "sent:fresh") s.Close() if got := fake.calls.Load(); got != 2 { t.Fatalf("intervening interrupts should share the blocked-send barrier, got %d cancels", got) @@ -292,19 +292,19 @@ func TestRapidInterruptsDoNotRecancelSettledGeneration(t *testing.T) { } func TestInterruptsDuringIdleCancelShareOneBarrier(t *testing.T) { - fake := &gatedCancelTransport{recordingTransport: new_recording_transport(), gate: make(chan struct{})} + fake := &gatedCancelTransport{recordingTransport: newRecordingTransport(), gate: make(chan struct{})} s := New(fake) defer s.Close() s.Interrupt() - wait_event(t, fake.changed, "cancel:1") + waitEvent(t, fake.changed, "cancel:1") for range 20 { s.Interrupt() s.Say("discarded") } s.Interrupt() s.Say("fresh") - fake.open_gate() - wait_event(t, fake.changed, "sent:fresh") + fake.openGate() + waitEvent(t, fake.changed, "sent:fresh") s.Close() if got := fake.calls.Load(); got != 1 { t.Fatalf("idle cancellation should cover intervening input, got %d calls", got) diff --git a/internal/speech/testdata/usb_fixture.c b/internal/speech/testdata/usb_fixture.c deleted file mode 100644 index 8f9a3862..00000000 --- a/internal/speech/testdata/usb_fixture.c +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later -// Private libusb ABI fixture. It never enumerates or opens real USB devices. -#include -#include -#include -#include -#include - -typedef struct { int unused; } Context; -typedef struct { int unused; } Device; -typedef struct { int unused; } Handle; -typedef struct { - uint8_t length, type; - uint16_t usb; - uint8_t device_class, subclass, protocol, packet_size; - uint16_t vendor, product, device; - uint8_t manufacturer, product_name, serial, configurations; -} Descriptor; -static Context context; -static Device device; -static Handle handle; -static Device *devices[] = {&device, &device, NULL}; - -static int mode(const char *value) { return strcmp(getenv("USB_FIXTURE_MODE"), value) == 0; } -static void record(const char *message) { - FILE *log = fopen(getenv("USB_FIXTURE_LOG"), "a"); - if (!log) abort(); - fprintf(log, "%s\n", message); - fclose(log); -} -int libusb_init(Context **result) { record("init"); *result = &context; return 0; } -void libusb_exit(Context *value) { (void)value; record("exit"); } -ssize_t libusb_get_device_list(Context *value, Device ***result) { (void)value; record("list"); *result = devices; return mode("multiple") ? 2 : 1; } -void libusb_free_device_list(Device **value, int unref) { (void)value; (void)unref; record("free-list"); } -int libusb_get_device_descriptor(Device *value, Descriptor *result) { - (void)value; - memset(result, 0, sizeof(*result)); - result->vendor = 0x0dd0; - result->product = mode("missing") ? 0x1002 : 0x2001; - return 0; -} -int libusb_open(Device *value, Handle **result) { (void)value; record("open"); if (mode("denied")) return -3; *result = &handle; return 0; } -void libusb_close(Handle *value) { (void)value; record("close"); } -int libusb_get_configuration(Handle *value, int *result) { (void)value; record("configuration"); *result = mode("unconfigured") ? 0 : 1; return 0; } -int libusb_set_configuration(Handle *value, int configuration) { (void)value; if (configuration != 1) abort(); record("set-configuration"); return 0; } -int libusb_claim_interface(Handle *value, int interface) { (void)value; if (interface != 0) abort(); record("claim"); return mode("busy") ? -6 : 0; } -int libusb_release_interface(Handle *value, int interface) { (void)value; if (interface != 0) abort(); record("release"); return 0; } -int libusb_bulk_transfer(Handle *value, unsigned char endpoint, unsigned char *data, int length, int *transferred, unsigned int timeout) { - (void)value; - if (length > 64 || timeout != 1000) abort(); - char message[256]; - int offset = snprintf(message, sizeof(message), "write-%02x:", endpoint); - for (int index = 0; index < length; index++) offset += snprintf(message + offset, sizeof(message) - offset, "%02x", data[index]); - record(message); - *transferred = mode("short") ? length - 1 : length; - return mode("timeout") ? -7 : 0; -} diff --git a/internal/spellcheck/dictionary.go b/internal/spellcheck/dictionary.go index 36732134..14056b8d 100644 --- a/internal/spellcheck/dictionary.go +++ b/internal/spellcheck/dictionary.go @@ -27,7 +27,7 @@ type EnchantDictionary struct { native *C.SpellDictionary } -func open_dictionary(language string) (Dictionary, error) { +func openDictionary(language string) (Dictionary, error) { if language == "" { return nil, fmt.Errorf("the session has no spelling language") } diff --git a/internal/spellcheck/exceptions.go b/internal/spellcheck/exceptions.go index 795227c6..d03a9d40 100644 --- a/internal/spellcheck/exceptions.go +++ b/internal/spellcheck/exceptions.go @@ -17,11 +17,11 @@ import ( "time" ) -func Exceptions_path(home string) string { +func ExceptionsPath(home string) string { return filepath.Join(home, ".local/share/stormux/fenrirscreenreader/spelling/exceptions.json") } -func load_exceptions(path string) (map[string]string, error) { +func loadExceptions(path string) (map[string]string, error) { words := make(map[string]string) file, err := os.Open(path) if errors.Is(err, os.ErrNotExist) { @@ -43,7 +43,7 @@ func load_exceptions(path string) (map[string]string, error) { return nil, err } for _, word := range entries { - if !valid_word(word) { + if !validWord(word) { return nil, fmt.Errorf("invalid exceptions file") } words[strings.ToLower(word)] = word @@ -51,7 +51,7 @@ func load_exceptions(path string) (map[string]string, error) { return words, nil } -func exception_list(words map[string]string) []string { +func exceptionList(words map[string]string) []string { entries := make([]string, 0, len(words)) for _, word := range words { entries = append(entries, word) @@ -62,7 +62,7 @@ func exception_list(words map[string]string) []string { // Each edit reloads the latest list while holding a stable, per-file lock. // Atomic replacement alone cannot protect against another reader's stale copy. -func update_exceptions(ctx context.Context, path string, operation Operation, word string) (map[string]string, error) { +func updateExceptions(ctx context.Context, path string, operation Operation, word string) (map[string]string, error) { if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { return nil, err } @@ -99,7 +99,7 @@ func update_exceptions(ctx context.Context, path string, operation Operation, wo case <-timer.C: } } - words, err := load_exceptions(path) + words, err := loadExceptions(path) if err != nil { return nil, err } @@ -109,14 +109,14 @@ func update_exceptions(ctx context.Context, path string, operation Operation, wo } else { delete(words, key) } - if err := save_exceptions(path, words); err != nil { + if err := saveExceptions(path, words); err != nil { return nil, err } return words, nil } -func save_exceptions(path string, words map[string]string) error { - data, err := json.MarshalIndent(exception_list(words), "", " ") +func saveExceptions(path string, words map[string]string) error { + data, err := json.MarshalIndent(exceptionList(words), "", " ") if err != nil { return err } @@ -131,7 +131,8 @@ func save_exceptions(path string, words map[string]string) error { if err != nil { return err } - defer os.Remove(file.Name()) + // After a successful rename the temporary name no longer exists. + defer func() { _ = os.Remove(file.Name()) }() if _, err := file.Write(append(data, '\n')); err != nil { file.Close() return err diff --git a/internal/spellcheck/exceptions_test.go b/internal/spellcheck/exceptions_test.go index b0d55511..4a6926cc 100644 --- a/internal/spellcheck/exceptions_test.go +++ b/internal/spellcheck/exceptions_test.go @@ -20,12 +20,12 @@ import ( func TestExceptionEditsPreserveOtherReadersChanges(t *testing.T) { path := filepath.Join(t.TempDir(), "exceptions.json") options := Options{ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{}, nil }} - first, second := New_service(context.Background(), options), New_service(context.Background(), options) + first, second := NewService(context.Background(), options), NewService(context.Background(), options) defer first.Close() defer second.Close() // Both readers load the original list, then the user switches between them. - receive_result(t, first, Request{Operation: Inspect}) - receive_result(t, second, Request{Operation: Inspect}) + receiveResult(t, first, Request{Operation: Inspect}) + receiveResult(t, second, Request{Operation: Inspect}) for _, edit := range []struct { service *Service request Request @@ -37,12 +37,12 @@ func TestExceptionEditsPreserveOtherReadersChanges(t *testing.T) { {second, Request{Operation: Add, Word: "Gamma"}, []string{"Beta", "Gamma"}}, {first, Request{Operation: Add, Word: "Alpha"}, []string{"Alpha", "Beta", "Gamma"}}, } { - result := receive_result(t, edit.service, edit.request) + result := receiveResult(t, edit.service, edit.request) if result.Err != nil || !reflect.DeepEqual(result.Exceptions, edit.want) { t.Fatalf("edit %v: result=%+v, want=%v", edit.request, result, edit.want) } - words, err := load_exceptions(path) - if err != nil || !reflect.DeepEqual(exception_list(words), edit.want) { + words, err := loadExceptions(path) + if err != nil || !reflect.DeepEqual(exceptionList(words), edit.want) { t.Fatalf("saved exceptions=%v, error=%v, want=%v", words, err, edit.want) } } @@ -54,10 +54,10 @@ func TestExceptionWriterProcess(t *testing.T) { if path == "" { return } - service := New_service(context.Background(), Options{ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{}, nil }}) + service := NewService(context.Background(), Options{ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{}, nil }}) defer service.Close() encoder, decoder := json.NewEncoder(os.Stdout), json.NewDecoder(os.Stdin) - result := receive_result(t, service, Request{Operation: Inspect}) + result := receiveResult(t, service, Request{Operation: Inspect}) if result.Err != nil { t.Fatal(result.Err) } @@ -72,7 +72,7 @@ func TestExceptionWriterProcess(t *testing.T) { } t.Fatal(err) } - result := receive_result(t, service, request) + result := receiveResult(t, service, request) if result.Err != nil { t.Fatal(result.Err) } @@ -88,7 +88,7 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) { encoder *json.Encoder decoder *json.Decoder } - start_writer := func() Writer { + startWriter := func() Writer { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestExceptionWriterProcess$") cmd.Env = append(os.Environ(), "FENRIR_EXCEPTION_TEST_PATH="+path) @@ -122,7 +122,7 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) { } return writer } - first, second := start_writer(), start_writer() + first, second := startWriter(), startWriter() for _, edit := range []struct { writer Writer word string @@ -137,8 +137,8 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) { t.Fatal(err) } } - words, err := load_exceptions(path) - if err != nil || !reflect.DeepEqual(exception_list(words), []string{"Alpha", "Beta"}) { + words, err := loadExceptions(path) + if err != nil || !reflect.DeepEqual(exceptionList(words), []string{"Alpha", "Beta"}) { t.Fatal("lost concurrent addition", words, err) } info, err := os.Stat(path + ".lock") @@ -149,7 +149,7 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) { func TestExceptionLockCancellationAndInvalidStorePreserveData(t *testing.T) { path := filepath.Join(t.TempDir(), "exceptions.json") - if err := save_exceptions(path, map[string]string{"alpha": "Alpha"}); err != nil { + if err := saveExceptions(path, map[string]string{"alpha": "Alpha"}); err != nil { t.Fatal(err) } lock, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0600) @@ -162,23 +162,23 @@ func TestExceptionLockCancellationAndInvalidStorePreserveData(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() - if _, err := update_exceptions(ctx, path, Add, "Beta"); !errors.Is(err, context.DeadlineExceeded) { + if _, err := updateExceptions(ctx, path, Add, "Beta"); !errors.Is(err, context.DeadlineExceeded) { t.Fatal("lock wait ignored cancellation", err) } - words, err := load_exceptions(path) - if err != nil || !reflect.DeepEqual(exception_list(words), []string{"Alpha"}) { + words, err := loadExceptions(path) + if err != nil || !reflect.DeepEqual(exceptionList(words), []string{"Alpha"}) { t.Fatal("cancelled edit changed data", words, err) } if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_UN); err != nil { t.Fatal(err) } - if _, err := update_exceptions(context.Background(), path, Add, "Beta"); err != nil { + if _, err := updateExceptions(context.Background(), path, Add, "Beta"); err != nil { t.Fatal("edit failed after lock release", err) } if err := os.WriteFile(path, []byte("invalid JSON"), 0600); err != nil { t.Fatal(err) } - if _, err := update_exceptions(context.Background(), path, Add, "Gamma"); err == nil { + if _, err := updateExceptions(context.Background(), path, Add, "Gamma"); err == nil { t.Fatal("edit overwrote invalid shared file") } data, err := os.ReadFile(path) diff --git a/internal/spellcheck/service.go b/internal/spellcheck/service.go index 14239e1c..0f9f9c9b 100644 --- a/internal/spellcheck/service.go +++ b/internal/spellcheck/service.go @@ -48,7 +48,7 @@ type Service struct { once sync.Once } -func New_service(parent context.Context, options Options) *Service { +func NewService(parent context.Context, options Options) *Service { ctx, cancel := context.WithCancel(parent) s := &Service{ctx: ctx, cancel: cancel, requests: make(chan Request, 16), automatic: make(chan Request, 32), results: make(chan Result, 32), done: make(chan struct{})} go s.run(options) @@ -84,7 +84,7 @@ type commandEntry struct { // Commands are tested as executable PATH entries, never executed. Builtins are // accepted separately because they have no executable file. Aliases/functions // belong to the child shell and cannot be discovered from the reader process. -func valid_command(word string, cache map[string]commandEntry) bool { +func validCommand(word string, cache map[string]commandEntry) bool { if strings.ContainsAny(word, "/\\\x00") { return false } @@ -107,13 +107,13 @@ func (s *Service) run(options Options) { defer close(s.done) open := options.OpenDictionary if open == nil { - open = open_dictionary + open = openDictionary } dict, dictionaryErr := open(options.Language) if dict != nil { defer dict.Close() } - words, storeErr := load_exceptions(options.ExceptionsPath) + words, storeErr := loadExceptions(options.ExceptionsPath) cache := make(map[string]commandEntry) for { var request Request @@ -133,12 +133,12 @@ func (s *Service) run(options Options) { result := Result{Request: request, Language: options.Language, Word: Word(request.Word), Available: dict != nil && dictionaryErr == nil, DictionaryError: dictionaryErr, Err: storeErr} if request.Operation == Add || request.Operation == Remove { result.Word = strings.TrimSpace(request.Word) - if result.Err == nil && !valid_word(result.Word) { + if result.Err == nil && !validWord(result.Word) { result.Err = fmt.Errorf("enter a single word of at most 128 characters") } if result.Err == nil { var draft map[string]string - draft, result.Err = update_exceptions(s.ctx, options.ExceptionsPath, request.Operation, result.Word) + draft, result.Err = updateExceptions(s.ctx, options.ExceptionsPath, request.Operation, result.Word) if result.Err == nil { words = draft } @@ -146,7 +146,7 @@ func (s *Service) run(options Options) { } else if result.Err == nil && result.Word != "" { _, result.Correct = words[strings.ToLower(result.Word)] if request.Operation == Automatic && !result.Correct { - result.Correct = valid_command(result.Word, cache) + result.Correct = validCommand(result.Word, cache) } if !result.Correct && result.Available { result.Correct, result.Err = dict.Check(result.Word) @@ -156,7 +156,7 @@ func (s *Service) run(options Options) { } } if request.Operation != Automatic { - result.Exceptions = exception_list(words) + result.Exceptions = exceptionList(words) } select { case s.results <- result: diff --git a/internal/spellcheck/service_test.go b/internal/spellcheck/service_test.go index 3d1125ca..fe088bc3 100644 --- a/internal/spellcheck/service_test.go +++ b/internal/spellcheck/service_test.go @@ -30,7 +30,7 @@ func (*TestDictionary) Suggest(string) ([]string, error) { } func (*TestDictionary) Close() {} -func receive_result(t *testing.T, service *Service, request Request) Result { +func receiveResult(t *testing.T, service *Service, request Request) Result { t.Helper() if !service.Submit(request) { t.Fatal("request not accepted") @@ -81,18 +81,18 @@ func TestGlobalExceptionsPersistenceRemoveAndFailedWriteIsolation(t *testing.T) path := filepath.Join(t.TempDir(), "spelling", "exceptions.json") dict := &TestDictionary{} options := Options{Language: "en_US", ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return dict, nil }} - service := New_service(context.Background(), options) + service := NewService(context.Background(), options) defer service.Close() - if got := receive_result(t, service, Request{Word: "helo"}); got.Correct || !reflect.DeepEqual(got.Suggestions, []string{"hello", "help", "held"}) { + if got := receiveResult(t, service, Request{Word: "helo"}); got.Correct || !reflect.DeepEqual(got.Suggestions, []string{"hello", "help", "held"}) { t.Fatal(got) } for _, word := range []string{"Fenrir", "Café"} { - if got := receive_result(t, service, Request{Operation: Add, Word: word}); got.Err != nil { + if got := receiveResult(t, service, Request{Operation: Add, Word: word}); got.Err != nil { t.Fatal(got) } } for _, operation := range []Operation{Inspect, Automatic} { - if got := receive_result(t, service, Request{Operation: operation, Word: "FENRIR"}); !got.Correct || len(got.Suggestions) != 0 { + if got := receiveResult(t, service, Request{Operation: operation, Word: "FENRIR"}); !got.Correct || len(got.Suggestions) != 0 { t.Fatal(got) } } @@ -105,15 +105,15 @@ func TestGlobalExceptionsPersistenceRemoveAndFailedWriteIsolation(t *testing.T) } service.Close() options.Language = "de_DE" - service = New_service(context.Background(), options) + service = NewService(context.Background(), options) defer service.Close() - if got := receive_result(t, service, Request{Word: "café"}); !got.Correct { + if got := receiveResult(t, service, Request{Word: "café"}); !got.Correct { t.Fatal("exception was language-specific", got) } - if got := receive_result(t, service, Request{Operation: Remove, Word: "Fenrir"}); got.Err != nil || !reflect.DeepEqual(got.Exceptions, []string{"Café"}) { + if got := receiveResult(t, service, Request{Operation: Remove, Word: "Fenrir"}); got.Err != nil || !reflect.DeepEqual(got.Exceptions, []string{"Café"}) { t.Fatal(got) } - if got := receive_result(t, service, Request{Word: "Fenrir"}); got.Correct { + if got := receiveResult(t, service, Request{Word: "Fenrir"}); got.Correct { t.Fatal("removed exception accepted", got) } // Replace the parent with a file so failure is deterministic even as root. @@ -123,16 +123,16 @@ func TestGlobalExceptionsPersistenceRemoveAndFailedWriteIsolation(t *testing.T) if err := os.WriteFile(filepath.Dir(path), []byte("blocked"), 0600); err != nil { t.Fatal(err) } - if got := receive_result(t, service, Request{Operation: Add, Word: "wrongword"}); got.Err == nil { + if got := receiveResult(t, service, Request{Operation: Add, Word: "wrongword"}); got.Err == nil { t.Fatal("failed write announced success", got) } - if got := receive_result(t, service, Request{Word: "wrongword"}); got.Correct { + if got := receiveResult(t, service, Request{Word: "wrongword"}); got.Correct { t.Fatal("failed addition changed memory", got) } - if got := receive_result(t, service, Request{Operation: Remove, Word: "Café"}); got.Err == nil { + if got := receiveResult(t, service, Request{Operation: Remove, Word: "Café"}); got.Err == nil { t.Fatal(got) } - if got := receive_result(t, service, Request{Word: "café"}); !got.Correct { + if got := receiveResult(t, service, Request{Word: "café"}); !got.Correct { t.Fatal("failed removal changed memory", got) } } @@ -151,10 +151,10 @@ func TestPATHCommandsBuiltinsAndNeverExecute(t *testing.T) { t.Fatal(err) } dict := &TestDictionary{} - service := New_service(context.Background(), Options{ExceptionsPath: filepath.Join(root, "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return dict, nil }}) + service := NewService(context.Background(), Options{ExceptionsPath: filepath.Join(root, "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return dict, nil }}) defer service.Close() for _, word := range []string{"tac", "cd", "readarray", "ulimit"} { - if got := receive_result(t, service, Request{Operation: Automatic, Word: word}); !got.Correct { + if got := receiveResult(t, service, Request{Operation: Automatic, Word: word}); !got.Correct { t.Fatal(word, got) } } @@ -162,35 +162,35 @@ func TestPATHCommandsBuiltinsAndNeverExecute(t *testing.T) { t.Fatal(dict.calls) } for _, word := range []string{"notexecutable", "directory", "typo"} { - if got := receive_result(t, service, Request{Operation: Automatic, Word: word}); got.Correct { + if got := receiveResult(t, service, Request{Operation: Automatic, Word: word}); got.Correct { t.Fatal(word, got) } } if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) { t.Fatal("command executed", err) } - if got := receive_result(t, service, Request{Word: "tac"}); got.Correct { + if got := receiveResult(t, service, Request{Word: "tac"}); got.Correct { t.Fatal("manual lexical check skipped", got) } } func TestMissingDictionaryStillAllowsExceptionManagement(t *testing.T) { - service := New_service(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return nil, errors.New("missing dictionary") }}) + service := NewService(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return nil, errors.New("missing dictionary") }}) defer service.Close() - if got := receive_result(t, service, Request{Word: "hello"}); got.Available || got.DictionaryError == nil || got.Correct { + if got := receiveResult(t, service, Request{Word: "hello"}); got.Available || got.DictionaryError == nil || got.Correct { t.Fatal(got) } - if got := receive_result(t, service, Request{Operation: Add, Word: "Fenrir"}); got.Err != nil { + if got := receiveResult(t, service, Request{Operation: Add, Word: "Fenrir"}); got.Err != nil { t.Fatal(got) } - if got := receive_result(t, service, Request{Word: "fenrir"}); !got.Correct { + if got := receiveResult(t, service, Request{Word: "fenrir"}); !got.Correct { t.Fatal(got) } } func TestSlowDictionaryDoesNotBlockInputSubmissionOrShutdown(t *testing.T) { gate := make(chan struct{}) - service := New_service(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{gate: gate}, nil }}) + service := NewService(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{gate: gate}, nil }}) started := time.Now() for range 100 { service.Submit(Request{Operation: Automatic, Word: "helo"}) @@ -206,7 +206,7 @@ func TestSlowDictionaryDoesNotBlockInputSubmissionOrShutdown(t *testing.T) { } func TestActualEnchantDictionaryAndRankedSuggestions(t *testing.T) { - dict, err := open_dictionary("en_US") + dict, err := openDictionary("en_US") if err != nil { t.Skip(err) } @@ -220,7 +220,7 @@ func TestActualEnchantDictionaryAndRankedSuggestions(t *testing.T) { if suggestions, err := dict.Suggest("helo"); err != nil || len(suggestions) == 0 { t.Fatal(suggestions, err) } - if dict, err := open_dictionary("zz_ZZ"); err == nil { + if dict, err := openDictionary("zz_ZZ"); err == nil { dict.Close() t.Fatal("missing dictionary accepted") } diff --git a/internal/spellcheck/words.go b/internal/spellcheck/words.go index d57a23e0..ae885e9b 100644 --- a/internal/spellcheck/words.go +++ b/internal/spellcheck/words.go @@ -15,13 +15,13 @@ import ( func Language() string { for _, name := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} { if value := os.Getenv(name); value != "" { - return language_tag(value) + return languageTag(value) } } return "" } -func language_tag(value string) string { +func languageTag(value string) string { value, _, _ = strings.Cut(strings.TrimSpace(value), ".") value, _, _ = strings.Cut(value, "@") if value == "C" || value == "POSIX" { @@ -45,13 +45,13 @@ func Word(value string) string { return "" } value = strings.TrimFunc(value, func(char rune) bool { return !unicode.IsLetter(char) && !unicode.IsMark(char) }) - if !valid_word(value) { + if !validWord(value) { return "" } return value } -func valid_word(value string) bool { +func validWord(value string) bool { if !utf8.ValidString(value) || utf8.RuneCountInString(value) > 128 || value == "" { return false } diff --git a/internal/terminal/application_override_linux_test.go b/internal/terminal/application_override_linux_test.go index 7d33ea2c..c03917eb 100644 --- a/internal/terminal/application_override_linux_test.go +++ b/internal/terminal/application_override_linux_test.go @@ -20,7 +20,7 @@ import ( func TestNinjamOverrideTerminalPresentation(t *testing.T) { for _, monochrome := range []bool{false, true} { t.Run(fmt.Sprint(monochrome), func(t *testing.T) { - e, err := new_emulator(24, 100) + e, err := newEmulator(24, 100) if err != nil { t.Fatal(err) } @@ -49,7 +49,7 @@ func TestNinjamOverrideTerminalPresentation(t *testing.T) { e.feed([]byte("\x1b[17;1HCHAT\x1b[20;1H old\x1b[21;1H" + chat + "\x1b[23;1H#####\x1b[24;1H[QUIT NINJAM] : fixture.invalid : 120.0BPM 16BPI\x1b[24;1H")) s := e.snapshot(true, false) var result []string - for _, message := range r.Update_application(s, a.Observe(s)) { + for _, message := range r.UpdateApplication(s, a.Observe(s)) { if message.Text != "" { result = append(result, message.Text) } @@ -60,7 +60,7 @@ func TestNinjamOverrideTerminalPresentation(t *testing.T) { t.Fatal(got) } r.Command(command.CurrentLine) - r.Note_input(true, false, false) + r.NoteInput(true, false, false) if got := paint(1, "0.0dB center", " new"); !slices.Equal(got, []string{"Master Volume and pan 0.0dB center", " new"}) { t.Fatal(got) } diff --git a/internal/terminal/application_override_native_linux_test.go b/internal/terminal/application_override_native_linux_test.go index ca744585..9a4963ff 100644 --- a/internal/terminal/application_override_native_linux_test.go +++ b/internal/terminal/application_override_native_linux_test.go @@ -54,7 +54,7 @@ func TestNetworkManagerOverrideNative(t *testing.T) { _ = quit.Run() }() } - master, slave, err := open_pty(24, 100) + master, slave, err := openPty(24, 100) if err != nil { t.Fatal(err) } @@ -71,7 +71,7 @@ func TestNetworkManagerOverrideNative(t *testing.T) { if err := syscall.SetNonblock(master, true); err != nil { t.Fatal(err) } - emulator, err := new_emulator(24, 100) + emulator, err := newEmulator(24, 100) if err != nil { t.Fatal(err) } diff --git a/internal/terminal/emulator_linux.go b/internal/terminal/emulator_linux.go index b0fc277d..9db0b160 100644 --- a/internal/terminal/emulator_linux.go +++ b/internal/terminal/emulator_linux.go @@ -36,8 +36,8 @@ type Emulator struct { rows, cols int } -func new_emulator(rows, cols int) (*Emulator, error) { - if !valid_size(rows, cols) { +func newEmulator(rows, cols int) (*Emulator, error) { + if !validSize(rows, cols) { return nil, fmt.Errorf("unsupported terminal geometry %dx%d", cols, rows) } vt := C.terminal_vterm(C.int(rows), C.int(cols)) diff --git a/internal/terminal/emulator_linux_test.go b/internal/terminal/emulator_linux_test.go index 4ed78e77..3afbba4a 100644 --- a/internal/terminal/emulator_linux_test.go +++ b/internal/terminal/emulator_linux_test.go @@ -34,7 +34,7 @@ import ( ) func TestPTYAttributeOnlyHighlightMovement(t *testing.T) { - emulator, err := new_emulator(4, 30) + emulator, err := newEmulator(4, 30) if err != nil { t.Fatal(err) } @@ -45,7 +45,7 @@ func TestPTYAttributeOnlyHighlightMovement(t *testing.T) { t.Fatal("reverse video attributes were discarded") } engine := reader.New() - engine.Configure_tracking("highlight") + engine.ConfigureTracking("highlight") engine.Update(before) emulator.feed([]byte("\x1b[1;1HFirst message\x1b[2;1H\x1b[7mSecond message\x1b[0m\x1b[4;1H")) after := emulator.snapshot(true, false) @@ -68,7 +68,7 @@ func TestPTYAttributeOnlyHighlightMovement(t *testing.T) { } func TestPTYUnicodeSplitSequencesAndSharedReview(t *testing.T) { - emulator, err := new_emulator(4, 20) + emulator, err := newEmulator(4, 20) if err != nil { t.Fatal(err) } @@ -99,7 +99,7 @@ func TestPTYUnicodeSplitSequencesAndSharedReview(t *testing.T) { } func TestPTYAlternateScreenResizeAndScroll(t *testing.T) { - emulator, err := new_emulator(3, 12) + emulator, err := newEmulator(3, 12) if err != nil { t.Fatal(err) } @@ -143,7 +143,7 @@ func TestPTYAlternateScreenResizeAndScroll(t *testing.T) { func TestPTYReverseSearchPromptReplacement(t *testing.T) { for _, promptWidth := range []int{2, 23, 24, 25, 26, 40} { t.Run(fmt.Sprint(promptWidth), func(t *testing.T) { - emulator, err := new_emulator(3, 80) + emulator, err := newEmulator(3, 80) if err != nil { t.Fatal(err) } @@ -162,7 +162,7 @@ func TestPTYReverseSearchPromptReplacement(t *testing.T) { } func TestPTYCarriageReturnEraseAndCursorEcho(t *testing.T) { - emulator, err := new_emulator(3, 20) + emulator, err := newEmulator(3, 20) if err != nil { t.Fatal(err) } @@ -174,7 +174,7 @@ func TestPTYCarriageReturnEraseAndCursorEcho(t *testing.T) { t.Fatal("shared automatic reading", got) } emulator.feed([]byte("\b \b")) - if got := engine.Update(emulator.snapshot(true, false)); !reflect.DeepEqual(got, []presentation.Message{presentation.Character_message('o')}) { + if got := engine.Update(emulator.snapshot(true, false)); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('o')}) { t.Fatal("shared deletion echo", got) } emulator.feed([]byte("\rnew\x1b[K")) @@ -190,7 +190,7 @@ func TestPTYCarriageReturnEraseAndCursorEcho(t *testing.T) { } func TestPTYChatScrollRegionPreservesFixedRows(t *testing.T) { - emulator, err := new_emulator(7, 30) + emulator, err := newEmulator(7, 30) if err != nil { t.Fatal(err) } @@ -220,7 +220,7 @@ func TestTerminalEnvironmentValidation(t *testing.T) { t.Fatal("missing shell", err) } for _, size := range [][2]int{{0, 80}, {25, 0}, {1001, 80}, {1000, 2000}} { - if emulator, err := new_emulator(size[0], size[1]); err == nil { + if emulator, err := newEmulator(size[0], size[1]); err == nil { emulator.close() t.Fatal("accepted excessive geometry", size) } @@ -229,19 +229,19 @@ func TestTerminalEnvironmentValidation(t *testing.T) { func TestPTYTypingEchoAtMarginsAndWithWideCharacters(t *testing.T) { for _, enabled := range []bool{false, true} { - emulator, err := new_emulator(3, 5) + emulator, err := newEmulator(3, 5) if err != nil { t.Fatal(err) } engine := reader.New() - engine.Configure_echo(enabled, false, false) + engine.ConfigureEcho(enabled, false, false) engine.Update(emulator.snapshot(true, false)) for _, char := range "abcdefghijklmnop q 界r" { - engine.Note_input(true, true, char == ' ') + engine.NoteInput(true, true, char == ' ') emulator.feed([]byte(string(char))) var want []presentation.Message if enabled && char != ' ' { - want = []presentation.Message{presentation.Character_message(char)} + want = []presentation.Message{presentation.CharacterMessage(char)} } if got := engine.Update(emulator.snapshot(true, false)); !reflect.DeepEqual(got, want) { t.Fatalf("echo=%v, char=%q: got %v, want %v", enabled, char, got, want) @@ -254,13 +254,13 @@ func TestPTYTypingEchoAtMarginsAndWithWideCharacters(t *testing.T) { func TestProgressAfterTerminalScroll(t *testing.T) { for _, mode := range []string{"percent", "spinner", "scroll region"} { t.Run(mode, func(t *testing.T) { - emulator, err := new_emulator(79, 318) + emulator, err := newEmulator(79, 318) if err != nil { t.Fatal(err) } defer emulator.close() engine := reader.New() - engine.Configure_progress(true) + engine.ConfigureProgress(true) // Fill the screen, then produce newline-terminated updates exactly as a // script does at the bottom of the viewport. A fixed status row exercises // a terminal multiplexer-style scrolling region too. @@ -281,7 +281,7 @@ func TestProgressAfterTerminalScroll(t *testing.T) { } emulator.feed([]byte(text)) engine.Update(emulator.snapshot(true, false)) - if value, ok := engine.Next_progress(now.Add(time.Duration(index) * 2 * time.Second)); !ok || value != want { + if value, ok := engine.NextProgress(now.Add(time.Duration(index) * 2 * time.Second)); !ok || value != want { t.Fatalf("scroll update %d: value=%v accepted=%v", index, value, ok) } } @@ -292,35 +292,35 @@ func TestProgressAfterTerminalScroll(t *testing.T) { func TestProgressIgnoresTerminalBackspaceAndDelete(t *testing.T) { for _, key := range []string{"backspace", "delete"} { t.Run(key, func(t *testing.T) { - emulator, err := new_emulator(3, 40) + emulator, err := newEmulator(3, 40) if err != nil { t.Fatal(err) } defer emulator.close() engine := reader.New() - engine.Configure_progress(true) + engine.ConfigureProgress(true) emulator.feed([]byte("type 2% abc")) if key == "delete" { emulator.feed([]byte("\x1b[1;11H")) } engine.Update(emulator.snapshot(true, false)) - engine.Note_input(true, false, false) - engine.Note_deletion() + engine.NoteInput(true, false, false) + engine.NoteDeletion() if key == "backspace" { emulator.feed([]byte("\b \b")) } else { emulator.feed([]byte("\x1b[P")) } output := engine.Update(emulator.snapshot(true, false)) - if value, ok := engine.Next_progress(time.Now()); ok { + if value, ok := engine.NextProgress(time.Now()); ok { t.Fatal("deletion beeped", value) } - if key == "backspace" && !reflect.DeepEqual(output, []presentation.Message{presentation.Character_message('c')}) { + if key == "backspace" && !reflect.DeepEqual(output, []presentation.Message{presentation.CharacterMessage('c')}) { t.Fatal("deletion feedback lost", output) } emulator.feed([]byte("\x1b[2;1HDownload 30%\x1b[1;11H")) engine.Update(emulator.snapshot(true, false)) - if value, ok := engine.Next_progress(time.Now()); !ok || value != 30 { + if value, ok := engine.NextProgress(time.Now()); !ok || value != 30 { t.Fatal("background progress stopped", value, ok) } }) @@ -328,13 +328,13 @@ func TestProgressIgnoresTerminalBackspaceAndDelete(t *testing.T) { } func TestPTYAttributesReportStylesPaletteRGBAndDefaults(t *testing.T) { - emulator, err := new_emulator(2, 30) + emulator, err := newEmulator(2, 30) if err != nil { t.Fatal(err) } defer emulator.close() engine := reader.New() - engine.Configure_attributes("speech", "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirUnderline|fenrirItalics|fenrirBlink|fenrirReverse|fenrirStrikethrough") + engine.ConfigureAttributes("speech", "fenrirFGColor|fenrirBGColor|fenrirBold|fenrirUnderline|fenrirItalics|fenrirBlink|fenrirReverse|fenrirStrikethrough") for _, trial := range []struct{ sgr, want string }{ {"1;4;3;5;7;9;31;44", "red|blue|bold|underline|italic|blink|reverse|strikethrough"}, {"38;5;196;48;5;232", "#ff0000|#080808||||||"}, diff --git a/internal/terminal/keyboard_linux.go b/internal/terminal/keyboard_linux.go index e7787f69..aa8e9ec3 100644 --- a/internal/terminal/keyboard_linux.go +++ b/internal/terminal/keyboard_linux.go @@ -40,11 +40,11 @@ type Keyboard struct{ session *Session } func (k *Keyboard) Events() <-chan error { return k.session.inputEvents } func (k *Keyboard) Scan() error { return nil } -func (k *Keyboard) Pass_next() { k.session.router.Pass_next() } +func (k *Keyboard) PassNext() { k.session.router.PassNext() } func (k *Keyboard) Capture(enabled bool) error { s := k.session if enabled && !s.grabbed { - status, err := s.capture_keyboard() + status, err := s.captureKeyboard() if err != nil { return err } @@ -72,19 +72,19 @@ func (k *Keyboard) Close() error { return nil } -// Update_modifiers applies only between complete chords and outside modal capture. +// UpdateModifiers applies only between complete chords and outside modal capture. // The native transaction retains the previous grabs if any new grab is refused. -func (k *Keyboard) Update_modifiers(fenrirKeys, scriptKeys []string) (bool, error) { +func (k *Keyboard) UpdateModifiers(fenrirKeys, scriptKeys []string) (bool, error) { s := k.session if s.router.Captured() || s.grabbed || s.captureBlocked || len(s.held) != 0 || len(s.replayed) != 0 { return false, nil } candidate := s.router - if err := candidate.Configure_modifiers(fenrirKeys, scriptKeys); err != nil { + if err := candidate.ConfigureModifiers(fenrirKeys, scriptKeys); err != nil { return false, err } var keys []C.int - for _, key := range append(candidate.Reader_keys(), candidate.Script_keys()...) { + for _, key := range append(candidate.ReaderKeys(), candidate.ScriptKeys()...) { keys = append(keys, C.int(key)) } var keyPointer *C.int @@ -92,7 +92,7 @@ func (k *Keyboard) Update_modifiers(fenrirKeys, scriptKeys []string) (bool, erro keyPointer = &keys[0] } status := C.terminal_x_update_keys(s.x, keyPointer, C.int(len(keys))) - if err := native_error(status); err != nil { + if err := nativeError(status); err != nil { return false, fmt.Errorf("update X11 modifier keys: %w", err) } if status != 0 { @@ -102,11 +102,11 @@ func (k *Keyboard) Update_modifiers(fenrirKeys, scriptKeys []string) (bool, erro return true, nil } -// capture_keyboard treats desktop/focus contention as a refused chord, not a +// captureKeyboard treats desktop/focus contention as a refused chord, not a // terminal-session failure. Keep modal intent while discarding stale key state. -func (s *Session) capture_keyboard() (int, error) { +func (s *Session) captureKeyboard() (int, error) { status := C.terminal_x_consume(s.x) - if err := native_error(status); err != nil { + if err := nativeError(status); err != nil { return 0, fmt.Errorf("acquire X11 terminal keyboard: %w", err) } if status == 0 { @@ -139,7 +139,7 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error if code == 0 { break } - if err := native_error(code); err != nil { + if err := nativeError(code); err != nil { return fmt.Errorf("X11 terminal input: %w", err) } if event._type != 1 { @@ -176,7 +176,7 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error value = 1 } if modifier.key != key { - s.router.Observe_modifier(1, modifier.key, value, numLock) + s.router.ObserveModifier(1, modifier.key, value, numLock) } } value := int32(event.value) @@ -186,7 +186,7 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error } } decision := s.router.Key(0, key, value, numLock, false) - if key == input.KeyCapsLock && s.router.Caps_modifier() { + if key == input.KeyCapsLock && s.router.CapsModifier() { if value == 1 { s.capsConsumed = !decision.Forward s.capsRestore = uint32(event.state)&2 != 0 @@ -197,7 +197,7 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error if s.capsRestore { enabled = 1 } - if err := native_error(C.terminal_x_caps_lock(s.x, enabled)); err != nil { + if err := nativeError(C.terminal_x_caps_lock(s.x, enabled)); err != nil { return err } } @@ -206,14 +206,14 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error } } if decision.ToggleCapsLock { - if err := native_error(C.terminal_x_toggle_caps(s.x)); err != nil { + if err := nativeError(C.terminal_x_toggle_caps(s.x)); err != nil { return err } } // Acquire before dispatch: a failed capture must not execute a command // or open a form from a partial, stale chord. if event.value == 1 && !decision.Forward && !s.grabbed { - status, err := s.capture_keyboard() + status, err := s.captureKeyboard() if err != nil { return err } @@ -254,5 +254,5 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error if s.captureBlocked && C.terminal_x_keys_down(s.x) == 0 { s.captureBlocked = false } - return s.relay_input() + return s.relayInput() } diff --git a/internal/terminal/mutt_linux_test.go b/internal/terminal/mutt_linux_test.go index 42a9c959..c0f1dbf3 100644 --- a/internal/terminal/mutt_linux_test.go +++ b/internal/terminal/mutt_linux_test.go @@ -41,11 +41,11 @@ func TestMuttCursorNavigation(t *testing.T) { t.Skip("set FENRIR_MUTT_TEST=1 to exercise installed mutt with a private mailbox") } for _, mode := range []string{"cursor", "highlight"} { - t.Run(mode, func(t *testing.T) { test_mutt_navigation(t, mode) }) + t.Run(mode, func(t *testing.T) { testMuttNavigation(t, mode) }) } } -func test_mutt_navigation(t *testing.T, mode string) { +func testMuttNavigation(t *testing.T, mode string) { program, err := exec.LookPath("mutt") if err != nil { t.Fatal(err) @@ -62,7 +62,7 @@ func test_mutt_navigation(t *testing.T, mode string) { if err := os.WriteFile(mailbox, []byte(messages.String()), 0600); err != nil { t.Fatal(err) } - master, slave, err := open_pty(12, 80) + master, slave, err := openPty(12, 80) if err != nil { t.Fatal(err) } @@ -81,7 +81,7 @@ func test_mutt_navigation(t *testing.T, mode string) { if err := syscall.SetNonblock(master, true); err != nil { t.Fatal(err) } - emulator, err := new_emulator(12, 80) + emulator, err := newEmulator(12, 80) if err != nil { t.Fatal(err) } @@ -111,7 +111,7 @@ func test_mutt_navigation(t *testing.T, mode string) { t.Fatalf("mailbox did not open: %q", string(initial.Cells)) } engine := reader.New() - engine.Configure_tracking(mode) + engine.ConfigureTracking(mode) engine.Update(initial) var selections []int for index := 2; index <= 15; index++ { @@ -124,7 +124,7 @@ func test_mutt_navigation(t *testing.T, mode string) { for _, index := range selections { // Reviewing a message must not suppress the next application arrow. engine.Command(command.CurrentLine) - engine.Note_input(true, false, false) + engine.NoteInput(true, false, false) arrow := "\x1bOB" // ncurses enables application cursor keys if index < previousIndex { arrow = "\x1bOA" diff --git a/internal/terminal/ninjam_live_linux_test.go b/internal/terminal/ninjam_live_linux_test.go index cace92ec..a16ecffa 100644 --- a/internal/terminal/ninjam_live_linux_test.go +++ b/internal/terminal/ninjam_live_linux_test.go @@ -70,7 +70,7 @@ func TestNinjamLiveOverride(t *testing.T) { } defer trace.Close() encoder := json.NewEncoder(trace) - master, slave, err := open_pty(24, 100) + master, slave, err := openPty(24, 100) if err != nil { t.Fatal(err) } @@ -90,7 +90,7 @@ func TestNinjamLiveOverride(t *testing.T) { if err := syscall.SetNonblock(master, true); err != nil { t.Fatal(err) } - emulator, err := new_emulator(24, 100) + emulator, err := newEmulator(24, 100) if err != nil { t.Fatal(err) } @@ -121,7 +121,7 @@ func TestNinjamLiveOverride(t *testing.T) { snapshot := emulator.snapshot(true, false) if adapter != nil { frame := adapter.Observe(snapshot) - for _, message := range engine.Update_application(snapshot, frame) { + for _, message := range engine.UpdateApplication(snapshot, frame) { if message.Text != "" { output = append(output, message.Text) if err := encoder.Encode(map[string]any{"at": time.Now().UTC(), "text": message.Text}); err != nil { @@ -192,12 +192,12 @@ func TestNinjamLiveOverride(t *testing.T) { }) saveScreen("connected-screen") adapter = &ninjam.Adapter{} - engine.Configure_tracking("highlight") + engine.ConfigureTracking("highlight") pump() if focus() != "Master unmuted" { t.Fatal("initial master control:", focus()) } - send := func(data string) { engine.Note_input(true, false, false); write(data) } + send := func(data string) { engine.NoteInput(true, false, false); write(data) } send("\r") waitFor("master muted", 2*time.Second, func() bool { return focus() == "Master muted" }) send("\r") @@ -263,7 +263,7 @@ func TestNinjamLiveOverride(t *testing.T) { send("\r") waitFor("local muted", 2*time.Second, func() bool { return strings.HasSuffix(focus(), " muted") && !strings.HasSuffix(focus(), " unmuted") }) if os.Getenv("FENRIR_NINJAM_TEST_PEER") == "1" { - peerStep, peerFocus, peerWrite := start_ninjam_live_peer(t, program, host+":"+port, preload, root) + peerStep, peerFocus, peerWrite := startNinjamLivePeer(t, program, host+":"+port, preload, root) peerPump = peerStep waitFor("silent test peer channel", 12*time.Second, func() bool { return strings.Contains(screenText(), "Peer Fixture") }) for count := 0; count < 64 && !strings.Contains(focus(), "channel Peer Fixture"); count++ { @@ -378,9 +378,9 @@ func TestNinjamLiveOverride(t *testing.T) { t.Log("PASS: live master/local mute, volume/pan, navigation after review, quiet meters, rename/input prompts, resize, private incoming chat, semantic region reads, and shell return") } -// start_ninjam_live_peer adds a clocked-silence test channel, never a microphone. +// startNinjamLivePeer adds a clocked-silence test channel, never a microphone. // It exists only in the explicit two-account test and is cleaned up by t.Cleanup. -func start_ninjam_live_peer(t *testing.T, program, address, preload, root string) (func(), func() string, func(string)) { +func startNinjamLivePeer(t *testing.T, program, address, preload, root string) (func(), func() string, func(string)) { t.Helper() directory, err := os.MkdirTemp(root, "peer-") if err != nil { @@ -390,7 +390,7 @@ func start_ninjam_live_peer(t *testing.T, program, address, preload, root string if err := os.WriteFile(filepath.Join(directory, "ninjam.config"), []byte(configuration), 0600); err != nil { t.Fatal(err) } - master, slave, err := open_pty(24, 100) + master, slave, err := openPty(24, 100) if err != nil { t.Fatal(err) } @@ -410,7 +410,7 @@ func start_ninjam_live_peer(t *testing.T, program, address, preload, root string if err := syscall.SetNonblock(master, true); err != nil { t.Fatal(err) } - emulator, err := new_emulator(24, 100) + emulator, err := newEmulator(24, 100) if err != nil { t.Fatal(err) } diff --git a/internal/terminal/output_linux_test.go b/internal/terminal/output_linux_test.go index 8ebefe02..1b2fbc57 100644 --- a/internal/terminal/output_linux_test.go +++ b/internal/terminal/output_linux_test.go @@ -41,14 +41,14 @@ func TestTerminalOutputBackpressurePreservesBytes(t *testing.T) { defer output.Close() want := bytes.Repeat([]byte("\x1b[1mredraw é界\x1b[0m\r\n"), 16384) session := &Session{output: output, outputPending: bytes.Clone(want)} - if err := session.flush_output(); err != nil { + if err := session.flushOutput(); err != nil { t.Fatal(err) } remaining := len(session.outputPending) if remaining == 0 || remaining == len(want) { t.Fatalf("expected partial write, %d of %d bytes remain", remaining, len(want)) } - if err := session.flush_output(); err != nil || len(session.outputPending) != remaining { + if err := session.flushOutput(); err != nil || len(session.outputPending) != remaining { t.Fatalf("full output must defer without losing data: remaining=%d err=%v", len(session.outputPending), err) } var got []byte @@ -62,7 +62,7 @@ func TestTerminalOutputBackpressurePreservesBytes(t *testing.T) { if len(session.outputPending) == 0 { break } - if err := session.flush_output(); err != nil { + if err := session.flushOutput(); err != nil { t.Fatal(err) } } else if err != nil { @@ -76,7 +76,7 @@ func TestTerminalOutputBackpressurePreservesBytes(t *testing.T) { syscall.Close(pipeFds[0]) pipeFds[0] = -1 session.outputPending = []byte("closed") - if err := session.flush_output(); !errors.Is(err, syscall.EPIPE) { + if err := session.flushOutput(); !errors.Is(err, syscall.EPIPE) { t.Fatalf("closed output: %v", err) } } diff --git a/internal/terminal/paste_linux.go b/internal/terminal/paste_linux.go index 79e7f9c3..fcc50bfb 100644 --- a/internal/terminal/paste_linux.go +++ b/internal/terminal/paste_linux.go @@ -31,10 +31,10 @@ import ( "git.stormux.org/storm/fenrir/internal/clipboard" ) -// Queue_paste belongs to the app loop. The existing nonblocking PTY relay +// QueuePaste belongs to the app loop. The existing nonblocking PTY relay // drains it, preserving byte order and the child application's paste mode. -func (s *Session) Queue_paste(text string) error { - if err := clipboard.Validate_text(text); err != nil { +func (s *Session) QueuePaste(text string) error { + if err := clipboard.ValidateText(text); err != nil { return err } if !s.active || s.eof || s.closed { @@ -57,11 +57,11 @@ func (s *Session) Queue_paste(text string) error { n = C.vterm_output_read(s.vt.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) s.pending = append(s.pending, bytes[:int(n)]...) s.pasteEnd = len(s.pending) - s.arm_watch() + s.armWatch() return nil } -func (s *Session) retire_paste() { +func (s *Session) retirePaste() { if s.pasteEnd == 0 { return } diff --git a/internal/terminal/paste_linux_test.go b/internal/terminal/paste_linux_test.go index 97d40247..649f32cf 100644 --- a/internal/terminal/paste_linux_test.go +++ b/internal/terminal/paste_linux_test.go @@ -25,7 +25,7 @@ import ( func TestQueuedPasteUsesChildBracketedModeAndRetiresWithTarget(t *testing.T) { for _, bracketed := range []bool{false, true} { - vt, err := new_emulator(2, 20) + vt, err := newEmulator(2, 20) if err != nil { t.Fatal(err) } @@ -33,7 +33,7 @@ func TestQueuedPasteUsesChildBracketedModeAndRetiresWithTarget(t *testing.T) { vt.feed([]byte("\x1b[?2004h")) } session := &Session{vt: vt, active: true, pending: []byte("before"), arm: make(chan waitState, 1)} - if err := session.Queue_paste("é界\n"); err != nil { + if err := session.QueuePaste("é界\n"); err != nil { t.Fatal(err) } want := "beforeé界\n" @@ -45,16 +45,16 @@ func TestQueuedPasteUsesChildBracketedModeAndRetiresWithTarget(t *testing.T) { } session.pending = append(session.pending, "after"...) session.active = false - session.retire_paste() + session.retirePaste() if string(session.pending) != "beforeafter" { t.Fatalf("paste survived focus loss: %q", session.pending) } session.active = true - if err := session.Queue_paste("old buffer"); err != nil { + if err := session.QueuePaste("old buffer"); err != nil { t.Fatal(err) } vt.feed([]byte("\x1b[?1049h")) - session.retire_paste() + session.retirePaste() if string(session.pending) != "beforeafter" { t.Fatal("paste survived screen replacement") } diff --git a/internal/terminal/pty_linux.go b/internal/terminal/pty_linux.go index 64ff4be1..60f49a92 100644 --- a/internal/terminal/pty_linux.go +++ b/internal/terminal/pty_linux.go @@ -33,9 +33,9 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func open_pty(rows, cols int) (int, int, error) { +func openPty(rows, cols int) (int, int, error) { var master, slave C.int - err := native_error(C.terminal_pty(&master, &slave, C.int(rows), C.int(cols))) + err := nativeError(C.terminal_pty(&master, &slave, C.int(rows), C.int(cols))) return int(master), int(slave), err } @@ -44,7 +44,7 @@ type waitState struct { } // The app loop replaces stale requests before handing readiness back to watch. -func (s *Session) arm_watch() { +func (s *Session) armWatch() { select { case <-s.arm: default: @@ -75,7 +75,7 @@ func (s *Session) watch(xfd int) { } if code < 0 || code&2 != 0 { select { - case s.events <- native_error(code): + case s.events <- nativeError(code): default: } } @@ -102,7 +102,7 @@ func (s *Session) Read() (screen.Snapshot, error) { if _, _, _, err := s.State(); err != nil { return screen.Snapshot{}, err } - if err := s.flush_output(); err != nil { + if err := s.flushOutput(); err != nil { return screen.Snapshot{}, err } var buffer [32768]byte @@ -129,20 +129,20 @@ func (s *Session) Read() (screen.Snapshot, error) { total += n s.vt.feed(buffer[:n]) s.outputPending = append(s.outputPending, buffer[:n]...) - if err := s.flush_output(); err != nil { + if err := s.flushOutput(); err != nil { return screen.Snapshot{}, err } } snapshot := s.vt.snapshot(s.active, s.lock) - s.retire_paste() + s.retirePaste() snapshot.CapsLock = s.capsLock - s.arm_watch() + s.armWatch() return snapshot, nil } -// flush_output preserves partial writes and retries after stdout becomes writable. +// flushOutput preserves partial writes and retries after stdout becomes writable. // Raw nonblocking writes keep a slow terminal from holding the app event loop. -func (s *Session) flush_output() error { +func (s *Session) flushOutput() error { for len(s.outputPending) > 0 { n, err := syscall.Write(int(s.output.Fd()), s.outputPending) if n > 0 { @@ -165,9 +165,9 @@ func (s *Session) flush_output() error { return nil } -// relay_input forwards stdin and queued key bytes to the child PTY. +// relayInput forwards stdin and queued key bytes to the child PTY. // The caller handles X11 key events before relaying terminal input. -func (s *Session) relay_input() error { +func (s *Session) relayInput() error { var bytes [4096]byte for total := 0; total < 65536 && len(s.pending) < 1<<20; { n, err := syscall.Read(int(s.input.Fd()), bytes[:]) @@ -206,6 +206,6 @@ func (s *Session) relay_input() error { return err } } - s.arm_watch() + s.armWatch() return nil } diff --git a/internal/terminal/rogue_live_linux_test.go b/internal/terminal/rogue_live_linux_test.go index 27d198d8..b0b968bb 100644 --- a/internal/terminal/rogue_live_linux_test.go +++ b/internal/terminal/rogue_live_linux_test.go @@ -36,7 +36,7 @@ func TestRogueLiveOverride(t *testing.T) { if rows > 24 { cols = 100 } - master, slave, err := open_pty(rows, cols) + master, slave, err := openPty(rows, cols) if err != nil { t.Fatal(err) } @@ -55,7 +55,7 @@ func TestRogueLiveOverride(t *testing.T) { if err := syscall.SetNonblock(master, true); err != nil { t.Fatal(err) } - e, err := new_emulator(rows, cols) + e, err := newEmulator(rows, cols) if err != nil { t.Fatal(err) } @@ -82,7 +82,7 @@ func TestRogueLiveOverride(t *testing.T) { if active { s := e.snapshot(true, false) frame = a.Observe(s) - for _, message := range r.Update_application(s, frame) { + for _, message := range r.UpdateApplication(s, frame) { if message.Text != "" { output = append(output, message.Text) } @@ -104,7 +104,7 @@ func TestRogueLiveOverride(t *testing.T) { } send := func(text string) { t.Helper() - r.Note_input(true, false, false) + r.NoteInput(true, false, false) if _, err := syscall.Write(master, []byte(text)); err != nil { t.Fatal(err) } diff --git a/internal/terminal/session_linux.go b/internal/terminal/session_linux.go index ce0facfd..c50eecdd 100644 --- a/internal/terminal/session_linux.go +++ b/internal/terminal/session_linux.go @@ -85,14 +85,14 @@ type Session struct { } } -func native_error(code C.int) error { +func nativeError(code C.int) error { if code < 0 { return syscall.Errno(-code) } return nil } -func valid_size(rows, cols int) bool { +func validSize(rows, cols int) bool { return rows > 0 && cols > 0 && rows <= 1000 && cols <= 2000 && rows*cols <= 1_000_000 } @@ -108,10 +108,10 @@ func Open(inputFile, outputFile *os.File, router input.Router) (*Session, error) if shell == "" { return nil, fmt.Errorf("-x requires SHELL to name your shell") } - return open_session(inputFile, outputFile, window, exec.Command(shell), router) + return openSession(inputFile, outputFile, window, exec.Command(shell), router) } -func open_session(inputFile, outputFile *os.File, window uint64, child *exec.Cmd, router input.Router) (_ *Session, result error) { +func openSession(inputFile, outputFile *os.File, window uint64, child *exec.Cmd, router input.Router) (_ *Session, result error) { s := &Session{input: inputFile, output: outputFile, master: -1, router: router, held: make(map[int]uint16), replayed: make(map[int]uint16), events: make(chan error, 1), inputEvents: make(chan error, 1), arm: make(chan waitState, 1), stop: make(chan struct{}), exited: make(chan struct{}), @@ -122,11 +122,11 @@ func open_session(inputFile, outputFile *os.File, window uint64, child *exec.Cmd } }() var rows, cols C.int - if err := native_error(C.terminal_size(C.int(inputFile.Fd()), &rows, &cols)); err != nil { + if err := nativeError(C.terminal_size(C.int(inputFile.Fd()), &rows, &cols)); err != nil { return nil, fmt.Errorf("-x requires a terminal on stdin: %w", err) } s.rows, s.cols = int(rows), int(cols) - if !valid_size(s.rows, s.cols) { + if !validSize(s.rows, s.cols) { return nil, fmt.Errorf("unsupported terminal geometry %dx%d", s.cols, s.rows) } var xError C.int @@ -135,20 +135,20 @@ func open_session(inputFile, outputFile *os.File, window uint64, child *exec.Cmd return nil, fmt.Errorf("open X11 terminal or acquire its keys (error %d); check DISPLAY, WINDOWID and competing grabs", xError) } var scriptKeys []C.int - for _, key := range append(router.Reader_keys(), router.Script_keys()...) { + for _, key := range append(router.ReaderKeys(), router.ScriptKeys()...) { scriptKeys = append(scriptKeys, C.int(key)) } if len(scriptKeys) > 0 { - if err := native_error(C.terminal_x_script_keys(s.x, &scriptKeys[0], C.int(len(scriptKeys)))); err != nil { + if err := nativeError(C.terminal_x_script_keys(s.x, &scriptKeys[0], C.int(len(scriptKeys)))); err != nil { return nil, fmt.Errorf("acquire script modifier keys: %w", err) } } - emulator, err := new_emulator(s.rows, s.cols) + emulator, err := newEmulator(s.rows, s.cols) if err != nil { return nil, err } s.vt = emulator - master, slave, err := open_pty(s.rows, s.cols) + master, slave, err := openPty(s.rows, s.cols) if err != nil { return nil, err } @@ -161,7 +161,7 @@ func open_session(inputFile, outputFile *os.File, window uint64, child *exec.Cmd if err := syscall.Pipe2(s.wake[:], syscall.O_CLOEXEC|syscall.O_NONBLOCK); err != nil { return nil, err } - if err := native_error(C.terminal_raw(C.int(inputFile.Fd()), &s.saved, &s.flags)); err != nil { + if err := nativeError(C.terminal_raw(C.int(inputFile.Fd()), &s.saved, &s.flags)); err != nil { return nil, fmt.Errorf("set terminal mode: %w", err) } s.raw = true @@ -183,7 +183,7 @@ func open_session(inputFile, outputFile *os.File, window uint64, child *exec.Cmd func (s *Session) State() (int, bool, bool, error) { var active, lock, capsLock, rows, cols C.int - if err := native_error(C.terminal_x_state(s.x, &active, &lock, &capsLock)); err != nil { + if err := nativeError(C.terminal_x_state(s.x, &active, &lock, &capsLock)); err != nil { return 0, false, false, err } if s.active && active == 0 { @@ -194,7 +194,7 @@ func (s *Session) State() (int, bool, bool, error) { s.grabbed = false } s.active, s.lock = active != 0, lock != 0 - s.retire_paste() + s.retirePaste() s.capsLock = capsLock != 0 // Synchronous X queries can buffer key events before the readiness worker // sees the socket. Preserve that wakeup even when Xlib drained the fd. @@ -204,14 +204,14 @@ func (s *Session) State() (int, bool, bool, error) { default: } } - if err := native_error(C.terminal_size(C.int(s.input.Fd()), &rows, &cols)); err != nil { + if err := nativeError(C.terminal_size(C.int(s.input.Fd()), &rows, &cols)); err != nil { return 0, false, false, err } if int(rows) != s.rows || int(cols) != s.cols { - if !valid_size(int(rows), int(cols)) { + if !validSize(int(rows), int(cols)) { return 0, false, false, fmt.Errorf("unsupported terminal geometry %dx%d", cols, rows) } - if err := native_error(C.terminal_resize(C.int(s.master), rows, cols)); err != nil { + if err := nativeError(C.terminal_resize(C.int(s.master), rows, cols)); err != nil { return 0, false, false, err } s.vt.resize(int(rows), int(cols)) @@ -236,7 +236,7 @@ func (s *Session) Close() error { s.workers.Wait() var result error if s.raw { - result = native_error(C.terminal_restore(C.int(s.input.Fd()), &s.saved, s.flags)) + result = nativeError(C.terminal_restore(C.int(s.input.Fd()), &s.saved, s.flags)) // A child may exit while its alternate screen or input modes are // active. Restore xterm's normal screen, cursor and keyboard modes. _, err := s.output.WriteString("\x1b[?1049l\x1b[?1l\x1b>\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m") diff --git a/tools/translations/dynamic.json b/tools/translations/dynamic.json index 04604b70..45ae8f5b 100644 --- a/tools/translations/dynamic.json +++ b/tools/translations/dynamic.json @@ -51,9 +51,6 @@ "most", "all" ], - "internal/emoji/catalog.go": [ - "All" - ], "internal/punctuation/text_processing.go": [ "number" ], diff --git a/tools/translations/main.go b/tools/translations/main.go index 42309c76..7a948618 100644 --- a/tools/translations/main.go +++ b/tools/translations/main.go @@ -2,256 +2,70 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Run from the repository root: go run ./tools/translations [check|update]. +// Extraction, merging and checks are shared with Cthulhu through +// screenreader-common's catalogtool; this file holds Fenrir's rules. package main import ( - "bytes" - "encoding/json" "fmt" - "go/ast" - "go/parser" - "go/token" "os" - "os/exec" "path/filepath" - "reflect" - "regexp" - "slices" - "strconv" "strings" - commonemoji "git.stormux.org/storm/screenreader-common/emoji" - "git.stormux.org/storm/screenreader-common/internalui" - "git.stormux.org/storm/screenreader-common/quicksettings" - "git.stormux.org/storm/screenreader-common/voiceprofiles" - "github.com/leonelquinteros/gotext" + "git.stormux.org/storm/screenreader-common/i18n/catalogtool" "github.com/pelletier/go-toml/v2" ) -const catalogDir = "internal/i18n/locale" +var config = catalogtool.Config{ + Domain: "fenrir", + Project: "Fenrir", + Command: "go run ./tools/translations", + CatalogDir: "internal/i18n/locale", + SourceRoot: "internal", + Rules: catalogtool.Rules{ + Calls: []string{"i18n.T", "i18n.Format", ".say", ".failed"}, + Plural: []string{"i18n.N"}, + Keys: []string{"Label", "Title"}, + AllValueFiles: []string{"internal/command/descriptions.go", "internal/punctuation/emoticons.go"}, + Tags: []string{"label", "quick"}, + Vars: func(name string) bool { + return name == "MenuTitle" || strings.HasPrefix(name, "tutorial") && name != "tutorialMode" + }, + }, + Shared: catalogtool.Shared{Emoji: true, QuickSettings: true, InternalUI: true, VoiceProfiles: true}, + DynamicFile: "tools/translations/dynamic.json", + Extra: punctuationNames, +} func main() { - if err := run(); err != nil { + mode := "" + if len(os.Args) > 1 { + mode = os.Args[1] + } + if err := catalogtool.Run(config, mode, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run() error { - messages, err := extract() - if err != nil { - return err - } - var pot bytes.Buffer - pot.WriteString("# Fenrir reader messages. Generated by go run ./tools/translations.\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: fenrir\\n\"\n\"Content-Type: text/plain; charset=UTF-8\\n\"\n\"Content-Transfer-Encoding: 8bit\\n\"\n") - ids := make([]string, 0, len(messages)) - for id := range messages { - ids = append(ids, id) - } - slices.Sort(ids) - for _, id := range ids { - refs := messages[id] - slices.Sort(refs) - fmt.Fprintf(&pot, "\n#: %s\nmsgid %s\nmsgstr \"\"\n", strings.Join(slices.Compact(refs), " "), strconv.Quote(id)) - } - mode := "extract" - if len(os.Args) > 1 { - mode = os.Args[1] - } - potPath := filepath.Join(catalogDir, "fenrir.pot") - if mode == "check" { - existing, err := os.ReadFile(potPath) - if err != nil { - return err - } - if !bytes.Equal(existing, pot.Bytes()) { - return fmt.Errorf("%s is stale; run go run ./tools/translations update", potPath) - } - } else if mode == "extract" || mode == "update" { - if err := os.WriteFile(potPath, pot.Bytes(), 0644); err != nil { - return err - } - } else { - return fmt.Errorf("usage: go run ./tools/translations [check|update]") - } - files, err := filepath.Glob(catalogDir + "/*/LC_MESSAGES/fenrir.po") - if err != nil { - return err - } - if len(files) == 0 { - return fmt.Errorf("no language catalogs") - } - fields := regexp.MustCompile(`\{(?:[0-9]+|[a-z_]+)?\}`) - for _, file := range files { - if mode == "update" { - output, err := exec.Command("msgmerge", "--update", "--backup=none", "--no-fuzzy-matching", file, potPath).CombinedOutput() - if err != nil { - return fmt.Errorf("%s: %s: %w", file, output, err) - } - } - if mode != "check" { - continue - } - data, err := os.ReadFile(file) - if err != nil { - return err - } - if regexp.MustCompile(`(?m)^#,.*\bfuzzy\b`).Match(data) { - return fmt.Errorf("%s: fuzzy translations require review", file) - } - output, err := exec.Command("msgfmt", "--check", "--check-format", "-o", os.DevNull, file).CombinedOutput() - if err != nil { - return fmt.Errorf("%s: %s: %w", file, output, err) - } - po := gotext.NewPo() - po.ParseFile(file) - for _, id := range ids { - if !po.IsTranslated(id) { - return fmt.Errorf("%s: untranslated %q", file, id) - } - expected, actual := fields.FindAllString(id, -1), fields.FindAllString(po.Get(id), -1) - slices.Sort(expected) - slices.Sort(actual) - if !slices.Equal(expected, actual) { - return fmt.Errorf("%s: changed fields in %q", file, id) - } - translated := po.Get(id) - if strings.HasPrefix(id, " ") != strings.HasPrefix(translated, " ") || strings.HasSuffix(id, " ") != strings.HasSuffix(translated, " ") { - return fmt.Errorf("%s: changed boundary whitespace in %q", file, id) - } - } - fmt.Printf("%s: %d/%d translated\n", file, len(ids), len(ids)) - } - fmt.Printf("%d reader message IDs, %d languages\n", len(ids), len(files)) - return nil -} - -func extract() (map[string][]string, error) { - messages := map[string][]string{} - add := func(id, ref string) { - if id != "" { - messages[id] = append(messages[id], ref) - } - } - allStrings := map[string]map[string]bool{} - err := filepath.WalkDir("internal", func(path string, entry os.DirEntry, err error) error { - if err != nil { - return err - } - if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { - return nil - } - fs := token.NewFileSet() - file, err := parser.ParseFile(fs, path, nil, 0) - if err != nil { - return err - } - literals := map[string]bool{} - allStrings[path] = literals - value := func(expr ast.Expr) string { - if lit, ok := expr.(*ast.BasicLit); ok && lit.Kind == token.STRING { - text, _ := strconv.Unquote(lit.Value) - return text - } - return "" - } - ref := func(n ast.Node) string { return fmt.Sprintf("%s:%d", path, fs.Position(n.Pos()).Line) } - ast.Inspect(file, func(n ast.Node) bool { - switch node := n.(type) { - case *ast.BasicLit: - if node.Kind == token.STRING { - literals[value(node)] = true - } - case *ast.CallExpr: - if fn, ok := node.Fun.(*ast.SelectorExpr); ok && len(node.Args) > 0 { - owner, _ := fn.X.(*ast.Ident) - if owner != nil && owner.Name == "i18n" && (fn.Sel.Name == "T" || fn.Sel.Name == "Format" || fn.Sel.Name == "N") || fn.Sel.Name == "say" || fn.Sel.Name == "failed" { - add(value(node.Args[0]), ref(node)) - if fn.Sel.Name == "N" { - // Plural messages need plural POT entries and checks; fail - // explicitly until the first reader call site is introduced. - err = fmt.Errorf("plural extraction required at %s", ref(node)) - } - } - } - case *ast.KeyValueExpr: - if key, ok := node.Key.(*ast.Ident); ok && (key.Name == "Label" || key.Name == "Title") { - add(value(node.Value), ref(node)) - } - if path == "internal/command/descriptions.go" || path == "internal/punctuation/emoticons.go" { - add(value(node.Value), ref(node)) - } - case *ast.Field: - if node.Tag != nil { - tag := reflect.StructTag(value(node.Tag)) - for _, name := range []string{"label", "quick"} { - add(tag.Get(name), ref(node)) - } - } - case *ast.ValueSpec: - for index, name := range node.Names { - if index < len(node.Values) && (name.Name == "MenuTitle" || strings.HasPrefix(name.Name, "tutorial") && name.Name != "tutorialMode") { - add(value(node.Values[index]), ref(node)) - } - } - } - return true - }) - return err - }) - if err != nil { - return nil, err - } - // Shared picker data and toolkit messages live in screenreader-common, outside the reader's - // internal/ tree scanned above. Its English labels remain Fenrir message IDs. - for _, category := range commonemoji.Categories() { - add(category.Label, "screenreader-common/emoji/catalog.go") - for _, entry := range category.Entries { - add(entry.Label, "screenreader-common/emoji/catalog.go") - } - } - for _, id := range quicksettings.MessageIDs() { - add(id, "screenreader-common/quicksettings/menu.go") - } - for _, id := range internalui.MessageIDs() { - add(id, "screenreader-common/internalui") - } - for _, id := range voiceprofiles.MessageIDs() { - add(id, "screenreader-common/voiceprofiles/editor.go") - } - // Dynamic labels without a directly extractable lookup. Each must still - // occur in its source, so removals/renames cannot silently leave stale IDs. - data, err := os.ReadFile("tools/translations/dynamic.json") - if err != nil { - return nil, err - } - var dynamic map[string][]string - if err := json.Unmarshal(data, &dynamic); err != nil { - return nil, err - } - for path, ids := range dynamic { - for _, id := range ids { - if !allStrings[path][id] { - return nil, fmt.Errorf("stale dynamic message %q in %s", id, path) - } - add(id, path) - } - } +// punctuationNames adds symbol names from punctuation profiles marked for +// translation. +func punctuationNames(add func(id, ref string)) error { profiles, err := filepath.Glob("config/punctuation/*.toml") if err != nil { - return nil, err + return err } for _, path := range profiles { data, err := os.ReadFile(path) if err != nil { - return nil, err + return err } var profile struct { Translate bool Symbols map[string]string } if err := toml.Unmarshal(data, &profile); err != nil { - return nil, err + return err } if profile.Translate { for _, name := range profile.Symbols { @@ -259,5 +73,5 @@ func extract() (map[string][]string, error) { } } } - return messages, nil + return nil }