From 5dfa03870620c8806700310d9ef96cea24c99c43 Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Mon, 16 Nov 2026 20:10:47 -0500 Subject: [PATCH] Adopt common v0.8.0 and preserve canceled hardware settings --- .golangci.yml | 14 +- AGENTS.md | 26 +- CONTRIBUTING.md | 16 +- README.md | 32 +- cmd/cthulhu/greeter.go | 8 +- cmd/cthulhu/greeter_test.go | 6 +- cmd/cthulhu/main.go | 6 +- .../Arch-Linux/cthulhu-git/PKGBUILD | 1 + docs/tentacle-remote-authorization.md | 2 +- docs/tentacle-remote-braille.md | 2 +- docs/tentacle-remote-capture.md | 2 +- docs/tentacle-remote-keyboard.md | 4 +- docs/tentacle-remote-speech.md | 6 +- docs/tentacle-secret-entries.md | 2 +- docs/testing/browser-lists.md | 2 +- go.mod | 15 +- go.sum | 20 +- internal/app/app.go | 10 +- internal/app/app_test.go | 4 +- internal/app/braille_context.go | 4 +- internal/app/braille_frames.go | 26 +- internal/app/braille_presentation.go | 4 +- internal/app/braille_remote.go | 12 +- internal/app/braille_routing.go | 2 +- internal/app/browser_actions_native_test.go | 14 +- internal/app/browser_button_names.go | 4 +- internal/app/browser_button_names_test.go | 8 +- internal/app/browser_dynamic_test.go | 4 +- internal/app/browser_lists.go | 29 +- internal/app/browser_lists_test.go | 26 ++ internal/app/browser_mode.go | 2 +- .../app/browser_replacement_native_test.go | 12 +- internal/app/capitalization.go | 2 +- internal/app/clipboard_watch.go | 18 +- internal/app/clipboard_watch_test.go | 6 +- internal/app/configured_speaker.go | 80 +++- .../app/configured_speaker_native_test.go | 30 +- internal/app/current_line.go | 10 +- internal/app/current_line_test.go | 12 +- internal/app/current_speech_source.go | 4 +- internal/app/date_time.go | 2 +- internal/app/date_time_test.go | 2 +- internal/app/document_review.go | 16 +- internal/app/echo_speaker.go | 12 +- internal/app/echo_speaker_test.go | 16 +- internal/app/emoji_menu.go | 20 +- internal/app/emoji_menu_test.go | 7 +- internal/app/event_accessibility.go | 24 +- internal/app/event_loop.go | 8 +- internal/app/event_presentation.go | 10 +- internal/app/event_review_results.go | 34 +- internal/app/flat_review.go | 4 +- internal/app/focus_gate.go | 10 +- internal/app/gui_table_test.go | 36 +- internal/app/indentation.go | 8 +- internal/app/internal_ui.go | 183 +++++---- internal/app/internal_ui_native_test.go | 22 +- internal/app/internal_ui_secret_test.go | 10 +- internal/app/internal_ui_test.go | 6 +- internal/app/laptop_layout_test.go | 4 +- internal/app/live_settings.go | 4 +- internal/app/ocr_activate.go | 72 ++-- internal/app/ocr_commands.go | 48 +-- internal/app/ocr_copy.go | 10 +- internal/app/ocr_native_test.go | 4 +- internal/app/ocr_read_all.go | 12 +- internal/app/ocr_reading_test.go | 50 +-- internal/app/ocr_refresh.go | 14 +- internal/app/ocr_refresh_activation_test.go | 70 ++-- internal/app/ocr_selection.go | 4 +- internal/app/ocr_session.go | 104 ++--- internal/app/ocr_session_test.go | 216 +++++------ internal/app/phonetic_hints.go | 2 +- internal/app/preferences.go | 10 +- internal/app/preferences_application.go | 4 +- internal/app/preferences_apply.go | 32 +- internal/app/preferences_echo_preview_test.go | 4 +- internal/app/preferences_feedback_test.go | 2 +- internal/app/preferences_preview.go | 8 +- internal/app/preferences_session.go | 34 +- internal/app/preferences_session_test.go | 12 +- internal/app/preferences_tentacles.go | 2 +- internal/app/preferences_test.go | 2 +- internal/app/progress_bars.go | 2 +- internal/app/progress_bars_test.go | 20 +- internal/app/progress_browser_native_test.go | 2 +- internal/app/progress_native_test.go | 8 +- internal/app/progress_settings.go | 4 +- internal/app/radio_sound.go | 4 +- internal/app/radio_sound_test.go | 14 +- internal/app/read_all.go | 6 +- internal/app/reading_context.go | 30 +- internal/app/reading_preferences_test.go | 34 +- internal/app/reading_speech_test.go | 2 +- internal/app/remote.go | 2 +- internal/app/remote_speech_render.go | 2 +- internal/app/remote_speech_render_test.go | 108 +++--- internal/app/remote_speech_stream.go | 14 +- internal/app/remote_speech_stream_test.go | 174 ++++----- internal/app/remote_speech_voice.go | 6 +- internal/app/remote_speech_voice_test.go | 50 +-- internal/app/review_spelling.go | 4 +- internal/app/review_spelling_test.go | 4 +- internal/app/runtime_commands.go | 8 +- internal/app/runtime_commands_test.go | 2 +- internal/app/runtime_platform_test.go | 2 +- internal/app/runtime_shutdown.go | 2 +- internal/app/runtime_test.go | 4 +- internal/app/runtime_workers.go | 2 +- internal/app/screen_lock.go | 2 +- .../app/speech_context_observation_test.go | 32 +- .../speech_current_line_observation_test.go | 40 +- internal/app/speech_delivery.go | 36 +- .../app/speech_document_observation_test.go | 52 +-- internal/app/speech_interrupt.go | 18 +- internal/app/speech_mode.go | 10 +- internal/app/speech_mode_test.go | 2 +- internal/app/speech_native_where_am_i_test.go | 36 +- internal/app/speech_observation.go | 36 +- internal/app/speech_observation_test.go | 58 +-- .../app/speech_review_observation_test.go | 32 +- internal/app/speech_settings.go | 57 +-- internal/app/speech_uninterruptible.go | 4 +- .../app/speech_where_am_i_observation_test.go | 32 +- internal/app/speech_worker.go | 8 +- internal/app/submitted_text.go | 2 +- internal/app/submitted_text_native_test.go | 2 +- internal/app/submitted_text_test.go | 6 +- internal/app/tentacle_install_test.go | 50 +-- internal/app/tentacle_interaction.go | 15 +- internal/app/tentacle_interaction_test.go | 6 +- internal/app/tentacle_lifecycle.go | 2 +- internal/app/tentacle_lifecycle_requests.go | 4 +- internal/app/tentacle_management.go | 2 +- internal/app/tentacle_management_test.go | 124 +++--- internal/app/tentacle_output.go | 4 +- internal/app/tentacle_reader.go | 151 ++++---- internal/app/tentacle_reader_test.go | 145 ++++--- internal/app/tentacle_remote_braille.go | 10 +- internal/app/tentacle_remote_braille_test.go | 50 +-- internal/app/tentacle_remote_capture.go | 4 +- internal/app/tentacle_remote_capture_test.go | 62 +-- .../app/tentacle_remote_connection_test.go | 138 +++---- internal/app/tentacle_remote_consent.go | 45 ++- internal/app/tentacle_remote_consent_test.go | 107 ++++-- internal/app/tentacle_remote_keyboard.go | 4 +- .../tentacle_remote_keyboard_native_test.go | 20 +- .../app/tentacle_remote_keyboard_owner.go | 12 +- .../tentacle_remote_keyboard_owner_test.go | 48 +-- internal/app/tentacle_remote_keyboard_test.go | 42 +- internal/app/tentacle_remote_speech.go | 14 +- internal/app/tentacle_remote_speech_test.go | 30 +- internal/app/tentacle_repositories.go | 2 +- internal/app/tentacle_repositories_test.go | 8 +- internal/app/tentacle_settings_test.go | 8 +- internal/app/tentacle_startup.go | 10 +- internal/app/tentacle_uninterruptible_test.go | 22 +- internal/app/tentacle_upgrade_failure_test.go | 8 +- .../app/tentacle_upgrade_lifecycle_test.go | 34 +- internal/app/tentacles.go | 22 +- internal/app/tentacles_test.go | 4 +- internal/app/terminal_events.go | 14 +- internal/app/terminal_events_test.go | 4 +- internal/app/test_helpers_test.go | 9 - internal/app/voice_profiles_test.go | 18 +- internal/app/window_switcher.go | 2 +- internal/app/window_switcher_test.go | 14 +- internal/app/window_titles.go | 6 +- internal/app/wine_events.go | 18 +- internal/app/wine_events_test.go | 2 +- internal/atspi/adapter.go | 4 +- internal/atspi/adapter_actions_native.go | 8 +- internal/atspi/adapter_document_native.go | 30 +- .../atspi/adapter_event_callback_native.go | 18 +- internal/atspi/adapter_foreground_native.go | 8 +- internal/atspi/adapter_menu_states_native.go | 2 +- internal/atspi/adapter_native_test.go | 8 +- internal/atspi/adapter_ocr_native.go | 2 +- internal/atspi/adapter_references_native.go | 22 +- internal/atspi/adapter_snapshot_native.go | 6 +- internal/atspi/adapter_tree_native.go | 30 +- internal/atspi/adapter_tree_test.go | 4 +- .../atspi/adapter_window_switcher_native.go | 4 +- internal/atspi/braille_native.go | 4 +- internal/atspi/capture_diagnostics.go | 16 +- internal/atspi/capture_diagnostics_test.go | 20 +- internal/atspi/current_line_native.go | 10 +- internal/atspi/document.go | 12 +- internal/atspi/document_error.go | 4 +- internal/atspi/document_error_test.go | 8 +- internal/atspi/document_rows.go | 2 +- internal/atspi/document_view.go | 28 +- internal/atspi/entry_name_native.go | 2 +- internal/atspi/foreground.go | 2 +- internal/atspi/foreground_test.go | 2 +- internal/atspi/live_regions.go | 2 +- internal/atspi/live_regions_native.go | 4 +- internal/atspi/live_regions_test.go | 2 +- internal/atspi/ocr_geometry.go | 16 +- internal/atspi/ocr_geometry_test.go | 2 +- internal/atspi/panel_applet_native_test.go | 4 +- internal/atspi/panel_menu_native_test.go | 8 +- internal/atspi/preferences_native_test.go | 58 +-- internal/atspi/replaced_feed_native_test.go | 2 +- internal/atspi/review_cache_native_test.go | 14 +- internal/atspi/review_table_native.go | 4 +- internal/atspi/review_table_native_test.go | 4 +- internal/atspi/speech_metadata_native.go | 14 +- internal/atspi/tentacle_item_native.go | 2 +- internal/atspi/text.go | 30 +- internal/atspi/text_bounds_test.go | 8 +- internal/atspi/text_component_test.go | 4 +- internal/atspi/text_input_native.go | 2 +- internal/atspi/text_native.go | 14 +- internal/atspi/text_viewport.go | 34 +- internal/atspi/text_viewport_test.go | 16 +- internal/atspi/window_switcher.go | 4 +- internal/braille/braille.go | 20 +- internal/clipboard/clipboard.go | 10 +- internal/clipboard/native.go | 2 +- internal/config/legacy_mapping.go | 34 +- internal/config/ocr_test.go | 4 +- internal/config/profile_mapping.go | 44 +-- internal/config/validation.go | 7 +- internal/config/voice_profiles.go | 16 +- internal/config/voice_profiles_test.go | 24 +- internal/datetime/datetime.go | 17 - internal/emoji/catalog.go | 75 +++- internal/emoji/catalog_test.go | 83 ++-- internal/i18n/i18n.go | 49 +++ internal/i18n/i18n_test.go | 37 ++ internal/i18n/locale/cthulhu.pot | 150 ++++++++ internal/input/commands.go | 2 +- internal/input/review_presses.go | 2 +- internal/interaction/grid_test.go | 29 -- internal/interaction/secret_test.go | 93 ----- internal/interaction/session_test.go | 191 ---------- internal/interaction/shared.go | 54 --- internal/logging/duckdb.go | 358 +----------------- internal/logging/duckdb_schema.go | 327 ++++++++++++++++ .../{duckdb_test.go => duckdb_schema_test.go} | 49 +-- internal/logging/multi_writer.go | 79 ++++ internal/logging/multi_writer_test.go | 89 +++++ internal/ocr/capture.go | 18 +- internal/ocr/capture_test.go | 38 +- internal/ocr/cursor.go | 12 +- internal/ocr/engine.go | 20 +- internal/ocr/engine_test.go | 36 +- internal/ocr/model.go | 12 +- internal/ocr/native_test.go | 6 +- internal/ocr/preprocess.go | 4 +- internal/ocr/process.go | 22 +- internal/ocr/tsv.go | 28 +- internal/ocr/tsv_test.go | 2 +- internal/platform/wayland/keyboard.go | 8 +- internal/platform/wayland/protocol.go | 28 +- internal/platform/wayland/protocol_test.go | 220 +++++------ internal/platform/wayland/routing.go | 48 +-- internal/platform/wayland/routing_test.go | 190 +++++----- internal/platform/wayland/ui.go | 30 +- internal/platform/wayland/ui_test.go | 2 +- internal/platform/xorg/commands_bindings.go | 18 +- internal/platform/xorg/commands_chord.go | 14 +- internal/platform/xorg/commands_ocr.go | 20 +- internal/platform/xorg/commands_owner.go | 2 +- internal/platform/xorg/commands_owner_loop.go | 40 +- internal/platform/xorg/commands_remote.go | 54 +-- internal/platform/xorg/commands_security.go | 2 +- internal/platform/xorg/commands_ui.go | 34 +- internal/platform/xorg/steam_focus.go | 8 +- .../platform/xorg/steam_focus_native_test.go | 28 +- internal/preferences/applications.go | 10 +- internal/preferences/applications_test.go | 2 +- internal/preferences/braille.go | 4 +- internal/preferences/catalog_protocol.go | 4 +- internal/preferences/catalog_protocol_test.go | 12 +- internal/preferences/catalog_voices.go | 4 +- internal/preferences/echo.go | 6 +- internal/preferences/extensions.go | 29 +- internal/preferences/general.go | 6 +- internal/preferences/native.h | 2 +- internal/preferences/native_widgets.c | 6 +- internal/preferences/protocol.go | 3 +- internal/preferences/sound.go | 8 +- internal/preferences/speech.go | 55 +-- internal/preferences/tentacles.go | 4 +- internal/preferences/tentacles_test.go | 10 +- internal/preferences/ui.go | 16 +- internal/preferences/ui_values.go | 30 +- internal/preferences/voice_profiles.go | 58 ++- internal/presentation/control_values_test.go | 2 +- internal/presentation/document_line.go | 2 +- internal/presentation/libreoffice.go | 2 +- internal/presentation/presentation.go | 8 +- internal/presentation/reading.go | 12 +- internal/presentation/sound_cues.go | 4 +- internal/presentation/speech.go | 4 +- internal/remote/registrations.go | 4 +- internal/remote/service.go | 2 +- internal/review/current_line.go | 2 +- internal/review/current_line_test.go | 14 +- internal/review/document.go | 16 +- internal/review/document_benchmark_test.go | 14 +- internal/review/document_braille_routing.go | 10 +- internal/review/document_caret.go | 10 +- .../review/document_caret_editable_test.go | 6 +- internal/review/document_caret_glyph_test.go | 10 +- internal/review/document_caret_line.go | 10 +- internal/review/document_caret_nodes.go | 12 +- internal/review/document_caret_ranges.go | 12 +- internal/review/document_caret_text.go | 8 +- internal/review/document_diagnostics.go | 6 +- .../document_inline_replacement_test.go | 24 +- internal/review/document_lists.go | 2 +- internal/review/document_lists_test.go | 4 +- internal/review/document_named_link.go | 10 +- internal/review/document_native_caret.go | 6 +- internal/review/document_navigation_reader.go | 2 +- internal/review/document_replacement.go | 28 +- internal/review/document_replacement_test.go | 12 +- internal/review/document_table.go | 8 +- internal/review/document_tooltip_test.go | 8 +- internal/review/document_visual_line.go | 28 +- .../document_visual_line_native_test.go | 4 +- internal/review/document_visual_line_test.go | 26 +- internal/review/document_worker.go | 28 +- internal/review/flat.go | 6 +- internal/review/flat_browser_native_test.go | 2 +- internal/review/flat_layout.go | 28 +- internal/review/flat_robustness_test.go | 2 +- internal/review/flat_worker.go | 2 +- internal/review/interest.go | 2 +- internal/review/interest_test.go | 4 +- internal/review/read_all.go | 8 +- internal/review/where_am_i.go | 2 +- internal/review/where_am_i_test.go | 2 +- internal/review/worker.go | 8 +- internal/sound/indentation.go | 6 +- internal/sound/indentation_test.go | 6 +- internal/sound/position.go | 6 +- internal/sound/progress.go | 6 +- internal/sound/progress_test.go | 26 +- internal/sound/service.go | 54 +-- internal/sound/service_test.go | 20 +- internal/sound/speech_beep.go | 10 +- internal/sound/tone.go | 2 +- internal/speech/hardware.go | 145 ++++--- internal/speech/hardware_test.go | 8 +- internal/speech/serial_native.go | 65 ---- internal/speech/serial_native_test.go | 53 +-- internal/speech/serial_unavailable.go | 14 - internal/tentacle/bindings.go | 12 +- internal/tentacle/containment.go | 28 +- internal/tentacle/containment_test.go | 110 +++--- internal/tentacle/diagnostics.go | 2 +- internal/tentacle/diagnostics_test.go | 4 +- internal/tentacle/install.go | 50 +-- internal/tentacle/install_test.go | 76 ++-- internal/tentacle/load_test.go | 20 +- internal/tentacle/local.go | 4 +- internal/tentacle/manager.go | 6 +- internal/tentacle/page_store.go | 10 +- internal/tentacle/page_store_test.go | 6 +- internal/tentacle/process.go | 42 +- internal/tentacle/protocol.go | 32 +- internal/tentacle/protocol_test.go | 16 +- internal/tentacle/reader_test.go | 12 +- internal/tentacle/registry.go | 16 +- internal/tentacle/remote.go | 70 ++-- internal/tentacle/remote_background_test.go | 6 +- internal/tentacle/remote_braille.go | 14 +- internal/tentacle/remote_braille_test.go | 12 +- internal/tentacle/remote_capture.go | 24 +- internal/tentacle/remote_capture_test.go | 12 +- internal/tentacle/remote_key.go | 10 +- internal/tentacle/remote_key_test.go | 24 +- internal/tentacle/remote_output.go | 8 +- internal/tentacle/remote_output_test.go | 10 +- internal/tentacle/remote_policy.go | 4 +- internal/tentacle/remote_policy_test.go | 10 +- internal/tentacle/remote_speech.go | 22 +- internal/tentacle/remote_speech_test.go | 32 +- internal/tentacle/remote_test.go | 40 +- internal/tentacle/repository.go | 36 +- internal/tentacle/repository_test.go | 26 +- internal/tentacle/sdk_test.go | 34 +- internal/tentacle/session.go | 60 +-- internal/tentacle/session_test.go | 120 +++--- internal/tentacle/supervisor.go | 16 +- internal/tentacle/supervisor_test.go | 78 ++-- internal/tentacle/updates.go | 26 +- internal/tentaclewire/form.go | 199 ++++++++++ internal/tentaclewire/form_test.go | 142 +++++++ internal/tentaclewire/interaction.go | 34 +- internal/tentaclewire/interaction_test.go | 7 +- internal/tentaclewire/reader.go | 55 ++- internal/tentaclewire/reader_test.go | 43 +-- internal/tentaclewire/remote_speech.go | 8 +- internal/tentaclewire/wire.go | 6 +- internal/version/build.go | 4 +- internal/version/build_test.go | 4 +- internal/version/version.go | 2 +- internal/wine/diagnostics_test.go | 2 +- internal/wine/helper_staging.go | 2 +- internal/wine/live_settings_test.go | 8 +- internal/wine/manager.go | 36 +- internal/wine/proton.go | 18 +- internal/wine/proton_test.go | 56 +-- sdk/go/tentacle/tentacle.go | 25 +- tools/translations/main.go | 46 +++ 410 files changed, 5353 insertions(+), 4803 deletions(-) delete mode 100644 internal/datetime/datetime.go create mode 100644 internal/i18n/i18n.go create mode 100644 internal/i18n/i18n_test.go create mode 100644 internal/i18n/locale/cthulhu.pot delete mode 100644 internal/interaction/grid_test.go delete mode 100644 internal/interaction/secret_test.go delete mode 100644 internal/interaction/session_test.go delete mode 100644 internal/interaction/shared.go create mode 100644 internal/logging/duckdb_schema.go rename internal/logging/{duckdb_test.go => duckdb_schema_test.go} (83%) create mode 100644 internal/logging/multi_writer.go create mode 100644 internal/logging/multi_writer_test.go delete mode 100644 internal/speech/serial_native.go delete mode 100644 internal/speech/serial_unavailable.go create mode 100644 internal/tentaclewire/form.go create mode 100644 internal/tentaclewire/form_test.go create mode 100644 tools/translations/main.go diff --git a/.golangci.yml b/.golangci.yml index a0eff15..e273409 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,14 +1,16 @@ version: "2" run: - # The Braille helper and the DuckDB debug-log sink live behind build tags; - # without listing them here those files are silently never analyzed. - # Analyzing with these tags needs the same development libraries as the - # Arch PKGBUILD (at-spi2, gtk3, brltty, liblouis), plus duckdb headers - # until the master-tracking package recipe builds the DuckDB feature. + # The Braille helper lives behind a build tag; without listing it here those + # files are silently never analyzed. Analyzing with it needs the same + # development libraries as the Arch PKGBUILD (at-spi2, gtk3, brltty, + # liblouis). + # + # The optional DuckDB debug-log sink is deliberately not listed, so this gate + # does not require DuckDB headers. When changing that feature, lint it with: + # golangci-lint run --build-tags duckdb ./... build-tags: - brlapi - - duckdb timeout: 5m linters: diff --git a/AGENTS.md b/AGENTS.md index 8fce30a..bd03ef6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,22 +20,27 @@ Reader-independent Go code shared with Fenrir lives in `git.stormux.org/storm/screenreader-common`; check it before duplicating pure data or behavior. Shared packages own the emoji catalog, internal interaction toolkit, Speech Dispatcher client and language matching, date/time formatting, -phonetic spelling alphabet, tone generation, and hardware synthesizer protocols. +phonetic spelling alphabet, tone generation, and hardware synthesizer protocols and serial/USB transport. Change shared behavior and its unit tests in the common module. Reader integration tests, device ownership, queues, playback, and presentation remain here. -`internal/interaction` is a compatibility adapter to the common `internalui` -toolkit; core rich forms use `internalUI.OpenUI`. Change control behavior and -its model tests in the common module. Keep Cthulhu's picker form, +Every reader form runs on the common `internalui` toolkit directly. Core forms +build an `internalui.Form` and open it with `internalUI.OpenUI`. Tentacle forms +arrive as `tentaclewire.Form` (the element JSON Tentacles send), which +`tentaclewire.NewSession` validates against the external limits and converts; +`tentaclewire.SubmissionValues` maps results back. That JSON is the Tentacle +wire format and must not change silently. Change control behavior and its model +tests in the common module. Keep Cthulhu's picker form, AT-SPI insertion, clipboard choice, speech, and Braille integration here. For shared changes, test the common package, tag a version, and update the pinned module in `go.mod`; keep local `go.work` or `replace` paths out of commits. -The common module must remain compatible with Cthulhu's Go minimum. +The common module, Fenrir and Cthulhu share the Go 1.27.2 minimum; raise it in all three together. ## Build, Test, and Development Commands -Use Go 1.24+ with CGO and development libraries listed by the Arch `PKGBUILD`. -Tagged DuckDB builds also need the DuckDB headers while the master-tracking -`cthulhu-git` recipe does not build this unreleased feature. +Use Go 1.27.2 or newer with CGO and development libraries listed by the Arch `PKGBUILD`. +The DuckDB debug-log sink is optional and behind the `duckdb` build tag. +Normal builds, tests and the lint gate do not need DuckDB; only work on that +feature needs its headers. - `go build -o build/cthulhu ./cmd/cthulhu`: build the reader. - `go build -tags brlapi -o build/cthulhu-braille ./cmd/cthulhu-braille`: build the Braille helper. @@ -44,13 +49,14 @@ Tagged DuckDB builds also need the DuckDB headers while the master-tracking - `go test ./... -count=1`: run default tests; native cases may skip. - `go test -tags brlapi ./... -count=1`: run packaging checks. - `go vet ./...`: check common Go errors. -- `golangci-lint run ./...`: run the configured lint gate (`.golangci.yml`, v2 schema; build tags brlapi/duckdb set there; keep the linter built with a Go at least as new as the project toolchain or it reports typecheck garbage). +- `golangci-lint run ./...`: run the configured lint gate (`.golangci.yml`, v2 schema; the brlapi build tag is set there; keep the linter built with a Go at least as new as the project toolchain or it reports typecheck garbage). When changing the DuckDB sink, also run `golangci-lint run --build-tags duckdb ./...`. - `go run ./cmd/parityledger validate testdata/parity-ledger.csv`: validate parity records. +- `go run ./tools/translations check`: confirm `internal/i18n/locale/cthulhu.pot` is current and catalogs are complete (needs GNU gettext); `update` regenerates it after message changes. - `./build/cthulhu --check-config`: validate settings; `./build/cthulhu` starts the reader. ## Coding Style & Naming Conventions -Use `gofmt`, exported PascalCase identifiers, private camelCase identifiers, and lowercase packages. Preserve license headers. Follow existing Python conventions; run `shellcheck` for edited shell scripts. Keep complete user-facing messages separate from internal identifiers and preserve deliberate speech/Braille segmentation. +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. Packages are lowercase, and initialisms keep one case (`ID`, `URL`). Run `go vet ./...` and `golangci-lint run ./...` before submitting. Preserve license headers. Follow existing Python conventions; run `shellcheck` for edited shell scripts. Keep complete user-facing messages separate from internal identifiers and preserve deliberate speech/Braille segmentation. ## Behavior & Accessibility Safeguards diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 185e2e6..8e2159f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,7 +33,7 @@ Record changed behavior and remaining acceptance gaps in the contribution descri ## Development and Architecture -Use Go 1.24 or newer, CGO, `pkg-config`, and development libraries for GTK3, AT-SPI, GStreamer, and X11. Braille builds also require BRLTTY/BrlAPI and liblouis. The Arch `PKGBUILD` lists runtime and build dependencies. +Use Go 1.27.2 or newer, CGO, `pkg-config`, and development libraries for GTK3, AT-SPI, GStreamer, and X11. Braille builds also require BRLTTY/BrlAPI and liblouis. The Arch `PKGBUILD` lists runtime and build dependencies. ```sh ./build-cthulhu.sh --output-dir build @@ -56,11 +56,13 @@ they use isolated fake tools and require no network or running reader. Start verification with the affected packages; run broader checks when the change affects shared behavior or before submission where practical. Format edited Go files with `gofmt`; run `shellcheck` for edited shell scripts. Use deterministic tests and synchronization instead of timing sleeps. Keep fixtures generic, without real usernames or personal identifiers. Lint with `golangci-lint run ./...` before submission. The configuration in -`.golangci.yml` is v2-schema and already sets the `brlapi` and `duckdb` -build tags, so tagged native files are analyzed; that needs the same -development libraries as the Arch `PKGBUILD` plus DuckDB headers while the -master-tracking `cthulhu-git` recipe does not build the unreleased DuckDB -feature. Keep `golangci-lint` built with a Go version at least +`.golangci.yml` is v2-schema and already sets the `brlapi` build tag, so +tagged native files are analyzed; that needs the same development libraries +as the Arch `PKGBUILD`. The optional DuckDB debug-log sink is not part of +this gate and needs no DuckDB headers. When changing that feature, also run +`golangci-lint run --build-tags duckdb ./...` and +`go test -tags duckdb ./internal/logging/ ./cmd/cthulhu/` with the DuckDB +headers installed. Keep `golangci-lint` built with a Go version at least as new as the project toolchain: an older linter cannot decode current export data and reports spurious typecheck errors. Deliberate exclusions (cleanup `Close` calls, test-fixture error handling, style checks that @@ -166,7 +168,7 @@ git show legacy:src/cthulhu/settings.py Use the newer Orca implementation as the first reference for Firefox, Thunderbird, and LibreOffice when available. [LibreOffice support](LIBREOFFICE_SUPPORT.md) describes its integration boundaries and remaining acceptance checks. Reference implementations guide behavior; do not mechanically copy Python class or plugin boundaries. Preserve accepted behavior unless the user chooses a deliberate difference, and describe that difference. Do not modify reference checkouts or installed readers without authorization. -Use complete messages and self-contained labels with placeholders for variable content. Keep internal states, commands, and settings identifiers independent of user-facing wording. Preserve deliberate speech/Braille segmentation, verbosity, and separate role/state announcements. Apply these rules within the change; adding translation infrastructure or sweeping existing strings requires separate scope. +Use complete messages and self-contained labels with placeholders for variable content. Keep internal states, commands, and settings identifiers independent of user-facing wording. Preserve deliberate speech/Braille segmentation, verbosity, and separate role/state announcements. Apply these rules within the change. Wrap new user-facing messages with `i18n.T` or `i18n.Format` and run `go run ./tools/translations update`; never translate application text, accessible names or Tentacle-provided text. Sweeping existing strings into translations requires separate scope. See the shared [translation guide](https://git.stormux.org/storm/screenreader-common/src/branch/master/TRANSLATIONS.md). ## Accessibility and Settings Verification diff --git a/README.md b/README.md index 67a589b..f53fec6 100644 --- a/README.md +++ b/README.md @@ -375,12 +375,13 @@ Add `--append` to preserve earlier sessions, for example `--append` requires `--debug-file` or `--debug-db`. A log can still grow during a long session. Builds compiled with `-tags duckdb` (needs the DuckDB headers at build time; -the packaged Arch build is one) also accept `--debug-db PATH`, which writes -the same redacted debug records to a DuckDB database instead of, or in -addition to, the NDJSON file. `libduckdb` is loaded only when the flag is -used, so it is an optional runtime dependency (an Arch `optdepends`); the -reader runs normally without it, and `--debug-db` reports that the `duckdb` -package must be installed: +the `cthulhu-git` Arch package does not build it) also accept +`--debug-db PATH`, which writes the same redacted debug records to a DuckDB +database instead of, or in addition to, the NDJSON file. This is an optional +developer feature; normal builds, tests and the lint gate do not need DuckDB. +`libduckdb` is loaded only when the flag is used, so it is an optional runtime +dependency; the reader runs normally without it, and `--debug-db` reports that +the `duckdb` package must be installed: `cthulhu --debug-db /tmp/cthulhu.duckdb`. Passing both flags writes both sinks. Without `--append` an existing database at the path is replaced; with `--append` each run adds a row to the `sessions` table (`session_id`, @@ -648,6 +649,16 @@ and Braille checks remain necessary. On an updating page, traverse headings in both directions, pause and continue, read changing lines with arrows and word commands, then verify Tab, selection, editable fields and browser chrome. +## Localization + +Cthulhu selects its interface language from `LANGUAGE`, `LC_ALL`, +`LC_MESSAGES` or `LANG`. Translations are bundled from +[internal/i18n/locale](internal/i18n/locale); missing translations fall back +to English. Translation support is new: so far the template holds the shared +internal UI and quick-settings messages, and Cthulhu's own messages are being +wrapped in stages. 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 Fenrir. + ## Primary voice profiles Preferences has a **Voice Profiles** tab. Start with **Add Voice Profile**; @@ -676,7 +687,14 @@ the preset. Failed speech changes retain the previous configuration. Cthulhu's existing restriction on combining hardware primary speech with a separate echo synthesizer still applies. -Standalone builds pin `screenreader-common v0.7.0`, which supplies the shared +Hardware speech supports LiteTalk, DoubleTalk LT, TripleTalk and DECtalk over a +serial port, and DECtalk USB. Serial synthesizers need a device path and baud +rate; Cthulhu locks the device while it uses it, so another reader cannot +drive the same synthesizer at the same time. DECtalk USB finds a single +connected device itself and needs libusb 1.0 at runtime, which is loaded only +when DECtalk USB is selected. + +Standalone builds pin `screenreader-common v0.8.0`, which supplies the shared profile model and editor. A sibling Go workspace can use local common-module changes during development. See [profile verification](docs/testing/voice-profiles.md). diff --git a/cmd/cthulhu/greeter.go b/cmd/cthulhu/greeter.go index 8db837b..fd0803b 100644 --- a/cmd/cthulhu/greeter.go +++ b/cmd/cthulhu/greeter.go @@ -18,7 +18,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/config" ) -func greeter_account(name string) (*user.User, error) { +func lookupGreeterAccount(name string) (*user.User, error) { if name != "lightdm" { return nil, fmt.Errorf("unsupported greeter %q; supported: lightdm", name) } @@ -32,13 +32,13 @@ func greeter_account(name string) (*user.User, error) { return account, nil } -func copy_greeter_settings(ctx context.Context, settings config.Settings, account *user.User, stdout, stderr io.Writer) error { +func copyGreeterSettings(ctx context.Context, settings config.Settings, account *user.User, stdout, stderr io.Writer) error { if account.Uid != strconv.Itoa(os.Geteuid()) { executable, err := os.Executable() if err != nil { return fmt.Errorf("find Cthulhu executable: %w", err) } - command, err := greeter_copy_command(ctx, executable, settings, account) + command, err := greeterCopyCommand(ctx, executable, settings, account) if err != nil { return err } @@ -61,7 +61,7 @@ func copy_greeter_settings(ctx context.Context, settings config.Settings, accoun return nil } -func greeter_copy_command(ctx context.Context, executable string, settings config.Settings, account *user.User) (*exec.Cmd, error) { +func greeterCopyCommand(ctx context.Context, executable string, settings config.Settings, account *user.User) (*exec.Cmd, error) { contents, err := config.GreeterSettings(settings) if err != nil { return nil, err diff --git a/cmd/cthulhu/greeter_test.go b/cmd/cthulhu/greeter_test.go index 350cfa0..e565409 100644 --- a/cmd/cthulhu/greeter_test.go +++ b/cmd/cthulhu/greeter_test.go @@ -34,7 +34,7 @@ func TestGreeterCopyUsesDestinationHomeAndPreservesSource(t *testing.T) { account := &user.User{Username: "Username", Uid: strconv.Itoa(os.Geteuid()), HomeDir: filepath.Join(directory, "greeter-home")} t.Setenv("XDG_DATA_HOME", filepath.Join(directory, "source-data")) var output bytes.Buffer - if err := copy_greeter_settings(context.Background(), settings, account, &output, &output); err != nil { + if err := copyGreeterSettings(context.Background(), settings, account, &output, &output); err != nil { t.Fatal(err) } target := filepath.Join(account.HomeDir, ".local", "share", "cthulhu", "user-settings-go.toml") @@ -55,7 +55,7 @@ func TestGreeterCopyUsesDestinationHomeAndPreservesSource(t *testing.T) { } // A second copy must replace settings without leaving a stale value. settings.EnableEchoByWord = false - if err := copy_greeter_settings(context.Background(), settings, account, &output, &output); err != nil { + if err := copyGreeterSettings(context.Background(), settings, account, &output, &output); err != nil { t.Fatal(err) } copied, err = config.Load(target) @@ -69,7 +69,7 @@ func TestGreeterCopyRequestsOnlyDestinationAccountPrivileges(t *testing.T) { settings.Path = "/private/source/settings.toml" settings.EnableEchoByWord = true account := &user.User{Username: "Username"} - command, err := greeter_copy_command(context.Background(), "/usr/bin/cthulhu", settings, account) + command, err := greeterCopyCommand(context.Background(), "/usr/bin/cthulhu", settings, account) if err != nil { t.Fatal(err) } diff --git a/cmd/cthulhu/main.go b/cmd/cthulhu/main.go index f5bdfd2..54a31d0 100644 --- a/cmd/cthulhu/main.go +++ b/cmd/cthulhu/main.go @@ -35,6 +35,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" "git.stormux.org/storm/cthulhu/internal/clipboard" "git.stormux.org/storm/cthulhu/internal/config" + "git.stormux.org/storm/cthulhu/internal/i18n" "git.stormux.org/storm/cthulhu/internal/logging" "git.stormux.org/storm/cthulhu/internal/notificationui" "git.stormux.org/storm/cthulhu/internal/ocrcapture" @@ -57,6 +58,7 @@ func main() { } func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (result error) { + i18n.Use(i18n.New(i18n.LocaleDir, i18n.Language())) options := flag.NewFlagSet("cthulhu", flag.ContinueOnError) options.SetOutput(stderr) tentacleFile := options.String("tentacles", "", "explicit local tentacle launch list (experimental JSON)") @@ -177,7 +179,7 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res } if *greeter != "" { var err error - greeterAccount, err = greeter_account(*greeter) + greeterAccount, err = lookupGreeterAccount(*greeter) if err != nil { return err } @@ -253,7 +255,7 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res return nil } if greeterAccount != nil { - return copy_greeter_settings(ctx, settings, greeterAccount, stdout, stderr) + return copyGreeterSettings(ctx, settings, greeterAccount, stdout, stderr) } if *replace || *shortReplace { if err := replaceRunning(ctx); err != nil { diff --git a/distro-packages/Arch-Linux/cthulhu-git/PKGBUILD b/distro-packages/Arch-Linux/cthulhu-git/PKGBUILD index 96ecb28..2549c84 100644 --- a/distro-packages/Arch-Linux/cthulhu-git/PKGBUILD +++ b/distro-packages/Arch-Linux/cthulhu-git/PKGBUILD @@ -43,6 +43,7 @@ depends=( ) optdepends=( 'git: Discover and update Tentacle repositories' + 'libusb: DECtalk USB hardware speech' 'tesseract: OCR engine for text recognition' 'tesseract-data-eng: English OCR language data' ) diff --git a/docs/tentacle-remote-authorization.md b/docs/tentacle-remote-authorization.md index 125eb69..1a36baf 100644 --- a/docs/tentacle-remote-authorization.md +++ b/docs/tentacle-remote-authorization.md @@ -97,7 +97,7 @@ unchanged. No public form schema flag lets a child choose its own trust level. From the reader checkout: ```sh -GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off go test -race ./internal/tentacle ./internal/tentaclewire ./internal/interaction ./sdk/... -count=1 -timeout=240s +GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off go test -race ./internal/tentacle ./internal/tentaclewire ./sdk/... -count=1 -timeout=240s GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off go test -race ./internal/app -run 'Tentacle|InternalUI|ScreenLock|XTermHandoff|Remote|CommandLoop' -count=1 -timeout=180s python3 -B tests/native_remote_input.py python3 tests/native_internal_ui.py diff --git a/docs/tentacle-remote-braille.md b/docs/tentacle-remote-braille.md index 48c2c3c..c03dc63 100644 --- a/docs/tentacle-remote-braille.md +++ b/docs/tentacle-remote-braille.md @@ -25,7 +25,7 @@ saturation and revocation. ## Reader owners -`start_remote_braille` attaches an owner for sessions installed with +`startRemoteBraille` attaches an owner for sessions installed with `braille-stream`, from local launch and managed startup. **Controlled computer.** A `size` request starts `cthulhu-braille --virtual`, diff --git a/docs/tentacle-remote-capture.md b/docs/tentacle-remote-capture.md index b983512..3bf0c8d 100644 --- a/docs/tentacle-remote-capture.md +++ b/docs/tentacle-remote-capture.md @@ -87,7 +87,7 @@ Debug logs record capture-ending reasons and remote speech text handed to the software speech backend, with spelling/language state and priority. Remote speech text is omitted at ordinary log levels, as for other private reader output. -`start_remote_capture` attaches this owner for sessions installed with +`startRemoteCapture` attaches this owner for sessions installed with `keyboard-capture`, from both local launch and managed startup. It enters capture only for a current controller lease while the reader is unlocked, not handed off and showing no reader UI. Revocation of the lease ends capture. diff --git a/docs/tentacle-remote-keyboard.md b/docs/tentacle-remote-keyboard.md index a004bd2..78c75bf 100644 --- a/docs/tentacle-remote-keyboard.md +++ b/docs/tentacle-remote-keyboard.md @@ -122,7 +122,7 @@ original-epoch cleanup/process-exit barrier; unconfirmed retirement blocks replacement. The quarantined `app.run_remote_keyboard` worker now joins this supervisor to the authenticated mailbox with a required policy callback; see [its lifecycle and native evidence](testing/remote-input-helper.md#quarantined-leasemailbox-worker). -`start_remote_keyboard` is now its production caller; see below. +`startRemoteKeyboard` is now its production caller; see below. No capture event API, production Xorg input owner or supervised helper attachment, core escape/bypass integration or installed Remote keyboard command is @@ -139,7 +139,7 @@ suite or native/hardware acceptance was performed; no active reader was replaced ## Production attachment (2026-11-06) -Local launch and managed-session startup now call `start_remote_keyboard` +Local launch and managed-session startup now call `startRemoteKeyboard` for every session installed with `keyboard-inject`, next to the speech owner. It attaches the mailbox before the child becomes active and runs the existing lease/mailbox worker with one `remoteinput.Supervisor` retained for the reader diff --git a/docs/tentacle-remote-speech.md b/docs/tentacle-remote-speech.md index c6b6d0d..e4420db 100644 --- a/docs/tentacle-remote-speech.md +++ b/docs/tentacle-remote-speech.md @@ -240,7 +240,7 @@ warnings remain in place pending live acceptance. ### Isolated synthesis prerequisite -The configured software backend now has an internal `open_remote_voice` +The configured software backend now has an internal `openRemoteVoice` primitive. It lazily creates one independent Speech Dispatcher speaking/control pair using the last successfully committed default voice settings. Ordinary reader startup creates no additional connections. Hardware and unconnected or @@ -278,7 +278,7 @@ acceptance test is available from these prerequisites alone. ### Literal utterance rendering prerequisite -`prepare_remote_utterance` now validates a complete speak assembly, retaining its +`prepareRemoteUtterance` now validates a complete speak assembly, retaining its single priority for a future stream owner. It rejects non-speak effects, mixed priorities and assemblies beyond the existing 64-frame/256-KiB limits. It joins adjacent text with the same language/spelling state across IPC fragment @@ -333,7 +333,7 @@ no active or installed reader was replaced. ### Incoming stream prerequisite -`run_remote_speech_playback` now joins the isolated renderer to an explicit +`runRemoteSpeechPlayback` now joins the isolated renderer to an explicit delivery channel. It is not registered with production sessions and provides no default authorization callback. Its caller must supply the reader's original-lease/focus/output check, bind policy loss to the delivery lifetime, diff --git a/docs/tentacle-secret-entries.md b/docs/tentacle-secret-entries.md index b4e0d9f..7183cca 100644 --- a/docs/tentacle-secret-entries.md +++ b/docs/tentacle-secret-entries.md @@ -57,7 +57,7 @@ interfaces exist. Never retry a rejected secret form as an ordinary entry. Focused automated checks: ```sh -GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off go test -race ./internal/interaction ./internal/tentaclewire ./internal/tentacle ./sdk/... -count=1 +GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off go test -race ./internal/tentaclewire ./internal/tentacle ./sdk/... -count=1 GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off go test -race ./internal/app -run 'TestInternalUI|TestReaderTentacle' -count=1 python3 tests/native_internal_ui.py ``` diff --git a/docs/testing/browser-lists.md b/docs/testing/browser-lists.md index 23e619e..df59e47 100644 --- a/docs/testing/browser-lists.md +++ b/docs/testing/browser-lists.md @@ -55,7 +55,7 @@ reopening the list. Automated checks: ```sh -go test ./internal/input ./internal/review ./internal/interaction ./internal/app -count=1 +go test ./internal/input ./internal/review ./internal/app -count=1 CTHULHU_NATIVE_BROWSER_TESTS=lists,keys,document,modes,editing python3 tests/native_browser.py python3 tests/native_internal_ui.py ``` diff --git a/go.mod b/go.mod index aceed94..a07cca1 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,12 @@ module git.stormux.org/storm/cthulhu -go 1.24.0 +go 1.27.2 -require github.com/pelletier/go-toml/v2 v2.4.3 +require ( + git.stormux.org/storm/screenreader-common v0.8.0 + github.com/godbus/dbus/v5 v5.1.0 + github.com/gorilla/websocket v1.5.3 + github.com/pelletier/go-toml/v2 v2.4.3 +) -require github.com/godbus/dbus/v5 v5.1.0 - -require github.com/gorilla/websocket v1.5.3 - -require git.stormux.org/storm/screenreader-common v0.7.0 +require github.com/leonelquinteros/gotext v1.8.0 // indirect diff --git a/go.sum b/go.sum index c378845..979bd03 100644 --- a/go.sum +++ b/go.sum @@ -1,22 +1,10 @@ -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/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU= +github.com/leonelquinteros/gotext v1.8.0/go.mod h1:Wqke380+8unZq2F4oTmmqmbUY9zWQMzwImdC34XOAo8= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= diff --git a/internal/app/app.go b/internal/app/app.go index 50ae463..c38a8c4 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -81,7 +81,7 @@ type textAttributeCaptureConfigurer interface { SetCaptureTextAttributes(bool) } -func random_string(messages []string) string { +func randomString(messages []string) string { if len(messages) == 0 { return "" } @@ -284,7 +284,7 @@ func Run(ctx context.Context, options Options) error { return pronunciationSpeechText(readingSpeechText(text, settings.Reading), settings.Pronunciations) } } - ocrSession := new_ocr_session(logger, commands, adapter, objectReview, speechOutput, speechMessages, brailleOutput, focusGate, live) + ocrSession := newOcrSession(logger, commands, adapter, objectReview, speechOutput, speechMessages, brailleOutput, focusGate, live) brailleOutput.ocr = ocrSession brailleOutput.document = objectReview focusGate.ocr = ocrSession @@ -300,7 +300,7 @@ func Run(ctx context.Context, options Options) error { tentacles.output = &tentacleOutput{speech: speechMessages, braille: brailleOutput, gate: focusGate, live: live} focusGate.tentacleOutput = tentacles.output focusGate.remotePolicy = tentacle.NewRemotePolicy() - focusGate.sync_remote_policy() + focusGate.syncRemotePolicy() tentacles.remotePolicy = focusGate.remotePolicy services = append(services, lifecycle.Service{Name: "tentacles", Start: tentacles.Start, Stop: tentacles.Stop}) } @@ -352,7 +352,7 @@ func Run(ctx context.Context, options Options) error { brailleOutput.FlashConfirmation(message, live.Load().Braille) } preferences.announceEchoPreview = func(label, value string) { - speechOutput.Enqueue(echo_preview_speech(label, value)) + speechOutput.Enqueue(echoPreviewSpeech(label, value)) } services = append(services, lifecycle.Service{Name: "preferences", Start: preferences.Start, Stop: preferences.Stop}) @@ -402,7 +402,7 @@ func Run(ctx context.Context, options Options) error { sounds.Enqueue(sound.Cue{Name: "start"}) } if speechMessages != nil && !focusGate.Locked() { - speechMessages.EnqueueStartup(speechRequest{Text: random_string(startupMessages), Role: "system", Cause: "startup"}) + speechMessages.EnqueueStartup(speechRequest{Text: randomString(startupMessages), Role: "system", Cause: "startup"}) } commandWorker := commandRuntime{ logger: logger, commands: commands, focusChanges: focusChanges, focusGate: focusGate, diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 3daef49..f8cdaf2 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -54,7 +54,7 @@ func TestRunSpeaksFocusEventsAndStops(t *testing.T) { select { case text := <-speaker.spoken: if index == 0 { - if !contains_string(startupMessages, text) { + if !containsString(startupMessages, text) { t.Fatalf("startup speech = %q, want one of %q", text, startupMessages) } continue @@ -78,7 +78,7 @@ func TestRunSpeaksFocusEventsAndStops(t *testing.T) { } select { case text := <-speaker.spoken: - if !contains_string(shutdownMessages, text) { + if !containsString(shutdownMessages, text) { t.Fatalf("shutdown speech = %q, want one of %q", text, shutdownMessages) } default: diff --git a/internal/app/braille_context.go b/internal/app/braille_context.go index 2c01cdf..14c2e32 100644 --- a/internal/app/braille_context.go +++ b/internal/app/braille_context.go @@ -11,7 +11,7 @@ import ( // Python includes context at the first line of text areas and omits desktop // ancestry within web documents. Verbosity changes roles, not group labels. -func braille_context_frame(frame braille.Frame, snapshot atspi.Snapshot, options config.BrailleOptions) braille.Frame { +func brailleContextFrame(frame braille.Frame, snapshot atspi.Snapshot, options config.BrailleOptions) braille.Frame { if snapshot.Role == "terminal" || snapshot.TextCaretKnown && snapshot.BrailleLineStart > 0 { return frame } @@ -49,7 +49,7 @@ func braille_context_frame(frame braille.Frame, snapshot atspi.Snapshot, options if ancestor.Role == "table" && ancestor.LayoutTable { continue } - text := braille_object_frame(ancestor, options).Text + text := brailleObjectFrame(ancestor, options).Text if text != "" { parts = append(parts, text) } diff --git a/internal/app/braille_frames.go b/internal/app/braille_frames.go index afe7c87..40cb529 100644 --- a/internal/app/braille_frames.go +++ b/internal/app/braille_frames.go @@ -46,7 +46,7 @@ func (worker *brailleWorker) SetInternalUIFrame(frame *braille.Frame) { worker.flashContext = nil worker.protectedFlash = false worker.internalUIFrame = nil - next := worker.shown_base_locked() + next := worker.shownBaseLocked() if frame != nil { next = *frame next.WordWrap = worker.wordWrap @@ -107,7 +107,7 @@ func (worker *brailleWorker) enqueueSecureFrameLocked(frame braille.Frame, base if worker.internalUIFrame != nil { if base { worker.baseFrame = frame - worker.export_locked(frame, 0) // Not displayed: unroutable. + worker.exportLocked(frame, 0) // Not displayed: unroutable. } return false } @@ -118,14 +118,14 @@ func (worker *brailleWorker) enqueueSecureFrameLocked(frame braille.Frame, base // A peer's display owns the base position; keep the newest local // frame for restoration without showing it. worker.baseFrame = frame - worker.export_locked(frame, 0) + worker.exportLocked(frame, 0) return false } if base { worker.flashContext = nil if worker.protectedFlash { worker.baseFrame = frame - worker.export_locked(frame, 0) + worker.exportLocked(frame, 0) return false } worker.flashGeneration++ @@ -149,7 +149,7 @@ func (worker *brailleWorker) enqueueSecureFrameLocked(frame braille.Frame, base worker.baseFrame.ID = frame.ID } if base { - worker.export_locked(frame, frame.ID) + worker.exportLocked(frame, frame.ID) } frame.Routes = append([]braille.TextRoute(nil), frame.Routes...) frame.Dots = append([]byte(nil), frame.Dots...) @@ -168,20 +168,20 @@ func (worker *brailleWorker) wakeDisplay() { } func (worker *brailleWorker) Flash(text string, options config.BrailleOptions) bool { - return worker.flash_message(text, options, false) + return worker.flashMessage(text, options, false) } // Confirmation flashes survive the automatic focus change caused by Apply/OK. // Normal flashes keep their existing focus-replacement behavior. func (worker *brailleWorker) FlashConfirmation(text string, options config.BrailleOptions) bool { - return worker.flash_message(text, options, true) + return worker.flashMessage(text, options, true) } -func (worker *brailleWorker) flash_message(text string, options config.BrailleOptions, confirmation bool) bool { - return worker.flash_message_guarded(text, options, confirmation, nil, 0) +func (worker *brailleWorker) flashMessage(text string, options config.BrailleOptions, confirmation bool) bool { + return worker.flashMessageGuarded(text, options, confirmation, nil, 0) } -func (worker *brailleWorker) flash_message_guarded(text string, options config.BrailleOptions, confirmation bool, owner context.Context, sequence uint64) bool { +func (worker *brailleWorker) flashMessageGuarded(text string, options config.BrailleOptions, confirmation bool, owner context.Context, sequence uint64) bool { if text == "" || !options.FlashMessages { return false } @@ -222,7 +222,7 @@ func (worker *brailleWorker) flash_message_guarded(text string, options config.B worker.flashTimer = nil worker.flashContext = nil worker.protectedFlash = false - queued := worker.enqueueFrameLocked(worker.shown_base_locked(), false) + queued := worker.enqueueFrameLocked(worker.shownBaseLocked(), false) worker.mu.Unlock() if queued { worker.wakeDisplay() @@ -248,7 +248,7 @@ func (worker *brailleWorker) DismissConfirmation() { worker.flashTimer.Stop() worker.flashTimer = nil } - queued := worker.enqueueFrameLocked(worker.shown_base_locked(), false) + queued := worker.enqueueFrameLocked(worker.shownBaseLocked(), false) worker.mu.Unlock() if queued { worker.wakeDisplay() @@ -306,7 +306,7 @@ func (worker *brailleWorker) retirePresentationLocked(owner context.Context) boo worker.flashTimer.Stop() worker.flashTimer = nil } - return worker.enqueueFrameLocked(worker.shown_base_locked(), false) + return worker.enqueueFrameLocked(worker.shownBaseLocked(), false) } func (worker *brailleWorker) retirePresentation(owner context.Context) { diff --git a/internal/app/braille_presentation.go b/internal/app/braille_presentation.go index 24e4819..6e32163 100644 --- a/internal/app/braille_presentation.go +++ b/internal/app/braille_presentation.go @@ -197,7 +197,7 @@ func brailleFocusFrame(s atspi.Snapshot) braille.Frame { } func brailleFocusFrameWithOptions(s atspi.Snapshot, options config.BrailleOptions, configured ...config.TextAttributeSettings) braille.Frame { - return braille_context_frame(braille_object_frame(s, options, configured...), s, options) + return brailleContextFrame(brailleObjectFrame(s, options, configured...), s, options) } // Embedded-object placeholders stand for child accessibles in native text. @@ -217,7 +217,7 @@ func brailleDisplayedText(snapshot atspi.Snapshot) string { return "" } -func braille_object_frame(s atspi.Snapshot, options config.BrailleOptions, configured ...config.TextAttributeSettings) braille.Frame { +func brailleObjectFrame(s atspi.Snapshot, options config.BrailleOptions, configured ...config.TextAttributeSettings) braille.Frame { if frame, handled := libreOfficeBrailleFrame(s, options); handled { return frame } diff --git a/internal/app/braille_remote.go b/internal/app/braille_remote.go index a14444c..25cc2cf 100644 --- a/internal/app/braille_remote.go +++ b/internal/app/braille_remote.go @@ -12,21 +12,21 @@ import ( "git.stormux.org/storm/cthulhu/internal/braille" ) -// shown_base_locked is the frame a flash, reader UI or message restores to: +// shownBaseLocked is the frame a flash, reader UI or message restores to: // a peer's cells while they own the display, otherwise the application frame. -func (worker *brailleWorker) shown_base_locked() braille.Frame { +func (worker *brailleWorker) shownBaseLocked() braille.Frame { if worker.remoteFrame != nil { return *worker.remoteFrame } return worker.baseFrame } -// export_locked offers an accepted application frame to a Remote exporter. +// exportLocked offers an accepted application frame to a Remote exporter. // Only base frames reach it: reader UI, flashed messages and secure-input // frames are never exported. The callback must not block. // id is the displayed frame's ID, or 0 when the frame is stored but not // shown, so routing from the peer can only reach the frame it saw. -func (worker *brailleWorker) export_locked(frame braille.Frame, id uint64) { +func (worker *brailleWorker) exportLocked(frame braille.Frame, id uint64) { if worker.remoteExport == nil || worker.secure || frame.Raw { return } @@ -115,8 +115,8 @@ func (worker *brailleWorker) SetRemoteCells(cells []int, gesture func(string, in } } -// remote_gesture_locked reports a key pressed on a displayed peer frame. -func (worker *brailleWorker) remote_gesture_locked(event braille.RoutingEvent) (func(string, int), string, int, bool) { +// remoteGestureLocked reports a key pressed on a displayed peer frame. +func (worker *brailleWorker) remoteGestureLocked(event braille.RoutingEvent) (func(string, int), string, int, bool) { frame := worker.frame if !frame.Raw || worker.remoteGesture == nil || frame.ID == 0 || event.ID != frame.ID { return nil, "", 0, false diff --git a/internal/app/braille_routing.go b/internal/app/braille_routing.go index 8f8e5e7..bae1098 100644 --- a/internal/app/braille_routing.go +++ b/internal/app/braille_routing.go @@ -15,7 +15,7 @@ type brailleRouter interface { func (worker *brailleWorker) route(ctx context.Context, event braille.RoutingEvent) { worker.mu.Lock() - if callback, gesture, index, ok := worker.remote_gesture_locked(event); ok { + if callback, gesture, index, ok := worker.remoteGestureLocked(event); ok { worker.mu.Unlock() callback(gesture, index) // Must not block. return diff --git a/internal/app/browser_actions_native_test.go b/internal/app/browser_actions_native_test.go index 040d87a..931b7a0 100644 --- a/internal/app/browser_actions_native_test.go +++ b/internal/app/browser_actions_native_test.go @@ -157,7 +157,7 @@ func TestNativeBrowserActionOwnership(t *testing.T) { } defer worker.Stop(context.Background()) worker.SyncFocus(focus) - await_result := func() review.Result { + awaitResult := func() review.Result { t.Helper() select { case result := <-worker.Results(): @@ -170,21 +170,21 @@ func TestNativeBrowserActionOwnership(t *testing.T) { return review.Result{} } } - move_caret := func(command review.DocumentCaretCommand) review.Result { + moveCaret := func(command review.DocumentCaretCommand) review.Result { t.Helper() if err := worker.MoveDocumentCaret(command); err != nil { t.Fatal(err) } - return await_result() + return awaitResult() } previousContent := "Initial mode content" for _, mode := range []string{"Basic", "Advanced"} { // Use the reader's command path so asynchronous replacement events // exercise its bounded recapture and cursor recovery. - move_caret(review.CaretDocumentStart) + moveCaret(review.CaretDocumentStart) reached := false for step := 0; step < 16; step++ { - move := move_caret(review.CaretNextLine) + move := moveCaret(review.CaretNextLine) if strings.TrimSpace(move.DocumentCaretText) == strings.ToUpper(mode) { reached = true break @@ -196,7 +196,7 @@ func TestNativeBrowserActionOwnership(t *testing.T) { if err := worker.ActivateDocumentCaret(); err != nil { t.Fatal(err) } - if result := await_result(); !result.DocumentActivate { + if result := awaitResult(); !result.DocumentActivate { t.Fatalf("missing activation result: %+v", result) } activated := false @@ -239,7 +239,7 @@ func TestNativeBrowserActionOwnership(t *testing.T) { } readNewContent := false for step := 0; step < 8; step++ { - move := move_caret(review.CaretNextLine) + move := moveCaret(review.CaretNextLine) if strings.TrimSpace(move.DocumentCaretText) == mode+" mode content" { readNewContent = true break diff --git a/internal/app/browser_button_names.go b/internal/app/browser_button_names.go index 7ee27b0..2b14334 100644 --- a/internal/app/browser_button_names.go +++ b/internal/app/browser_button_names.go @@ -24,7 +24,7 @@ type pendingBrowserButtonName struct { inputSequence uint64 } -func (handler *accessibilityEventHandler) defer_browser_button_name(event atspi.Event, activity input.Activity) bool { +func (handler *accessibilityEventHandler) deferBrowserButtonName(event atspi.Event, activity input.Activity) bool { browser := handler.browser if event.Type != atspi.AccessibleNameEvent || event.Source.LiveRegion || event.Source.Editable || browser == nil || !browser.ready || !browser.document.Valid() || @@ -51,7 +51,7 @@ func (handler *accessibilityEventHandler) defer_browser_button_name(event atspi. return true } -func (handler *accessibilityEventHandler) flush_browser_button_name() { +func (handler *accessibilityEventHandler) flushBrowserButtonName() { pending := &handler.state.pending.browserButtonName document, generation, inputSequence := pending.document, pending.generation, pending.inputSequence event, _ := pending.take() diff --git a/internal/app/browser_button_names_test.go b/internal/app/browser_button_names_test.go index 67f45ee..6435be3 100644 --- a/internal/app/browser_button_names_test.go +++ b/internal/app/browser_button_names_test.go @@ -81,7 +81,7 @@ func TestProcessEventsCoalescesWebButtonNames(t *testing.T) { } } // Native input releases echo ownership before the next focus event. - browser.pointer_input() + browser.pointerInput() // A redundant native focus notification must not discard the final name. event.Type = atspi.FocusEvent adapter.events <- event @@ -134,7 +134,7 @@ func TestWebButtonNameScopeAndCancellation(t *testing.T) { case "other focus": state.focusedID.Path = "/other" } - deferred := handler.defer_browser_button_name(event, source.activity) + deferred := handler.deferBrowserButtonName(event, source.activity) if kind == "live" || kind == "desktop" || kind == "entry" || kind == "other focus" { if deferred { t.Fatal("unrelated event was delayed") @@ -145,7 +145,7 @@ func TestWebButtonNameScopeAndCancellation(t *testing.T) { t.Fatal("web button name was not delayed") } timer := state.pending.browserButtonName.timer - handler.defer_browser_button_name(event, source.activity) + handler.deferBrowserButtonName(event, source.activity) if state.pending.browserButtonName.timer != timer { t.Fatal("duplicate name postponed presentation") } @@ -167,7 +167,7 @@ func TestWebButtonNameScopeAndCancellation(t *testing.T) { case "clear": state.pending.clear() } - handler.flush_browser_button_name() + handler.flushBrowserButtonName() want := 0 if kind == "settled" { want = 1 diff --git a/internal/app/browser_dynamic_test.go b/internal/app/browser_dynamic_test.go index 238f7a1..10e030a 100644 --- a/internal/app/browser_dynamic_test.go +++ b/internal/app/browser_dynamic_test.go @@ -150,12 +150,12 @@ func TestNativeBrowserDynamicNavigation(t *testing.T) { if event.Type == atspi.AccessibleNameEvent && event.Source.ID() == counter.Source.ID() { updates++ state.current = event.Source - if !handler.defer_browser_button_name(event, input.Activity{}) { + if !handler.deferBrowserButtonName(event, input.Activity{}) { t.Fatal("native web button name was not coalesced") } } case <-state.pending.browserButtonName.ready: - handler.flush_browser_button_name() + handler.flushBrowserButtonName() case <-ctx.Done(): t.Fatal("native counter did not finish: ", ctx.Err()) } diff --git a/internal/app/browser_lists.go b/internal/app/browser_lists.go index 21fdd02..ddc90fb 100644 --- a/internal/app/browser_lists.go +++ b/internal/app/browser_lists.go @@ -6,16 +6,21 @@ package app import ( "context" + "errors" "fmt" "strconv" "strings" "unicode" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/review" + commonui "git.stormux.org/storm/screenreader-common/internalui" ) +// maxBrowserListItems bounds a core document list; Tentacle forms keep their +// smaller protocol limit. +const maxBrowserListItems = 65536 + type documentListSource interface { ListDocument(context.Context, review.DocumentTarget, int) (review.DocumentListSnapshot, error) SelectDocumentList(review.DocumentListSnapshot, int) error @@ -44,7 +49,7 @@ func documentListTarget(binding input.DocumentListBinding) review.DocumentTarget return target } -func (ui *internalUI) browserList(ctx context.Context, binding input.DocumentListBinding) (*interaction.Session, review.DocumentListSnapshot, error) { +func (ui *internalUI) browserList(ctx context.Context, binding input.DocumentListBinding) (*commonui.Session, review.DocumentListSnapshot, error) { if ui.documents == nil { return nil, review.DocumentListSnapshot{}, review.ErrNoCurrent } @@ -55,7 +60,10 @@ func (ui *internalUI) browserList(ctx context.Context, binding input.DocumentLis if len(list.Entries) == 0 { return nil, list, nil } - items := make([]interaction.Item, 0, len(list.Entries)) + if len(list.Entries) > maxBrowserListItems { + return nil, list, errors.New("too many list items") + } + items := make([]commonui.Choice, 0, len(list.Entries)) for index, position := range list.Entries { snapshot := position.Snapshot label := position.Label @@ -87,12 +95,23 @@ func (ui *internalUI) browserList(ctx context.Context, binding input.DocumentLis label += ", not checked" } } - items = append(items, interaction.Item{ID: strconv.Itoa(index), Label: label}) + items = append(items, commonui.Choice{ID: strconv.Itoa(index), Label: label, Literal: true}) } title := fmt.Sprintf("%s: %d items found", binding.Title, len(items)) if len(items) == 1 { title = binding.Title + ": 1 item found" } - session, err := interaction.NewNavigationSession(title, items, list.Selected) + session, err := newCoreSession(browserListForm(title, items, list.Selected)) return session, list, err } + +// browserListForm is a single list whose selected row follows the reading +// caret. Activation returns the chosen entry's index as its ID. +func browserListForm(title string, items []commonui.Choice, selected int) commonui.Form { + if selected < 0 || selected >= len(items) { + selected = 0 + } + return commonui.Form{Type: commonui.FlatForm, Title: title, Detailed: true, Tabs: []commonui.Tab{{ID: "list", Label: title, Controls: []commonui.Control{ + {ID: "items", Label: title, Kind: commonui.List, Choices: items, Selected: selected, SelectAction: true}, + }}}} +} diff --git a/internal/app/browser_lists_test.go b/internal/app/browser_lists_test.go index c436b8c..e9cc657 100644 --- a/internal/app/browser_lists_test.go +++ b/internal/app/browser_lists_test.go @@ -7,12 +7,14 @@ package app import ( "context" "fmt" + "strconv" "testing" "time" "git.stormux.org/storm/cthulhu/internal/atspi" "git.stormux.org/storm/cthulhu/internal/input" "git.stormux.org/storm/cthulhu/internal/review" + commonui "git.stormux.org/storm/screenreader-common/internalui" ) type listTestSource struct { @@ -95,3 +97,27 @@ func TestBrowserListCatalogMapsAllOrcaListTypes(t *testing.T) { } } } + +func TestBrowserListFormKeepsCaretRowBeyondTentacleLimit(t *testing.T) { + items := make([]commonui.Choice, 300) + for index := range items { + items[index] = commonui.Choice{ID: strconv.Itoa(index), Label: "Example item", Literal: true} + } + session, err := newCoreSession(browserListForm("Links: 300 items found", items, 299)) + if err != nil { + t.Fatal(err) + } + if got := session.Open(); got != "Links: 300 items found. Example item" { + t.Fatalf("opening = %q", got) + } + if effect := session.Handle(commonui.Key{Name: "enter"}); effect.Action != "299" { + t.Fatalf("lost initial selection: %+v", effect) + } + session, err = newCoreSession(browserListForm("Links: 300 items found", items, -1)) + if err != nil { + t.Fatal(err) + } + if effect := session.Handle(commonui.Key{Name: "enter"}); effect.Action != "0" { + t.Fatalf("missing caret row did not start at the top: %+v", effect) + } +} diff --git a/internal/app/browser_mode.go b/internal/app/browser_mode.go index 31a9feb..934d74b 100644 --- a/internal/app/browser_mode.go +++ b/internal/app/browser_mode.go @@ -403,7 +403,7 @@ func (browser *browserModeController) observeCommand(command input.Command) { browser.mutex.Unlock() } -func (browser *browserModeController) pointer_input() { +func (browser *browserModeController) pointerInput() { browser.mutex.Lock() defer browser.mutex.Unlock() browser.navigation = atspi.ObjectID{} diff --git a/internal/app/browser_replacement_native_test.go b/internal/app/browser_replacement_native_test.go index 3d2996a..a950a32 100644 --- a/internal/app/browser_replacement_native_test.go +++ b/internal/app/browser_replacement_native_test.go @@ -20,14 +20,14 @@ import ( ) func TestNativeBrowserInlineReplacementNavigation(t *testing.T) { - run_native_replacement_navigation(t, false) + runNativeReplacementNavigation(t, false) } func TestNativeBrowserGeneratedLinkNavigation(t *testing.T) { - run_native_replacement_navigation(t, true) + runNativeReplacementNavigation(t, true) } -func run_native_replacement_navigation(t *testing.T, generated bool) { +func runNativeReplacementNavigation(t *testing.T, generated bool) { t.Helper() if os.Getenv("CTHULHU_NATIVE_BROWSER") != "1" { t.Skip("requires private browser session") @@ -92,7 +92,7 @@ document.addEventListener('keydown', event => { } defer worker.Stop(context.Background()) worker.SyncFocus(document) - dump_generated_tree := func() { + dumpGeneratedTree := func() { if !generated { return } @@ -121,7 +121,7 @@ document.addEventListener('keydown', event => { // require the exact text and subsequent navigation/replacement // checks rather than requiring the transient native caret to stick. if result.Err != nil || result.CaretErr != nil && !generated || !result.Moved || result.DocumentCaretText != want { - dump_generated_tree() + dumpGeneratedTree() t.Fatalf("%s: text=%q want=%q err=%v caret=%v diagnostics=%+v", command, result.DocumentCaretText, want, result.Err, result.CaretErr, result.DocumentDiagnostics) } @@ -220,7 +220,7 @@ document.addEventListener('keydown', event => { } for index, want := range []string{attribution, after} { if got := result.ReadAllLines[index].Contents[0].Text; got != want { - dump_generated_tree() + dumpGeneratedTree() t.Fatalf("Read All line %d: %q, want %q", index, got, want) } } diff --git a/internal/app/capitalization.go b/internal/app/capitalization.go index 1d2a951..20cb3f7 100644 --- a/internal/app/capitalization.go +++ b/internal/app/capitalization.go @@ -24,7 +24,7 @@ func capitalVoice(customEcho bool) string { // Called only by serialized speech delivery, after mode and context handling. // No cue outlives its owning request's cancellation context. -func (worker *speechWorker) present_capital(ctx context.Context, request speechRequest) error { +func (worker *speechWorker) presentCapital(ctx context.Context, request speechRequest) error { if worker.capitalization == nil { return nil } diff --git a/internal/app/clipboard_watch.go b/internal/app/clipboard_watch.go index fa90e9f..9ca7a14 100644 --- a/internal/app/clipboard_watch.go +++ b/internal/app/clipboard_watch.go @@ -27,7 +27,7 @@ type clipboardScope struct { enabled bool } -func clipboard_scope(live *liveSettings, gate *focusGate) clipboardScope { +func newClipboardScope(live *liveSettings, gate *focusGate) clipboardScope { scope := clipboardScope{settings: live.current.Load()} if name := live.application.Load(); name != nil { scope.application = *name @@ -40,7 +40,7 @@ func clipboard_scope(live *liveSettings, gate *focusGate) clipboardScope { return scope } -func run_automatic_clipboard(ctx context.Context, logger *slog.Logger, live *liveSettings, gate *focusGate, speech speechEnqueuer) <-chan struct{} { +func runAutomaticClipboard(ctx context.Context, logger *slog.Logger, live *liveSettings, gate *focusGate, speech speechEnqueuer) <-chan struct{} { done := make(chan struct{}) go func() { defer close(done) @@ -50,7 +50,7 @@ func run_automatic_clipboard(ctx context.Context, logger *slog.Logger, live *liv // No helper or clipboard reads until an application enables the feature. ticker := time.NewTicker(20 * time.Millisecond) defer ticker.Stop() - for !clipboard_scope(live, gate).enabled { + for !newClipboardScope(live, gate).enabled { select { case <-ctx.Done(): return @@ -59,14 +59,14 @@ func run_automatic_clipboard(ctx context.Context, logger *slog.Logger, live *liv } } ticker.Stop() - if err := watch_clipboard(ctx, live, gate, speech); err != nil && ctx.Err() == nil { + if err := watchClipboard(ctx, live, gate, speech); err != nil && ctx.Err() == nil { logger.Warn("automatic clipboard reading unavailable", "error", err) } }() return done } -func watch_clipboard(ctx context.Context, live *liveSettings, gate *focusGate, speech speechEnqueuer) error { +func watchClipboard(ctx context.Context, live *liveSettings, gate *focusGate, speech speechEnqueuer) error { executable, err := os.Executable() if err != nil { return err @@ -118,17 +118,17 @@ func watch_clipboard(ctx context.Context, live *liveSettings, gate *focusGate, s failures <- err }() defer func() { cancel(); out.Close(); <-readerDone }() - return serve_clipboard_changes(ctx, live, gate, speech, json.NewEncoder(in), changes, failures) + return serveClipboardChanges(ctx, live, gate, speech, json.NewEncoder(in), changes, failures) } -func serve_clipboard_changes(ctx context.Context, live *liveSettings, gate *focusGate, speech speechEnqueuer, encoder *json.Encoder, changes <-chan clipboard.TextChange, failures <-chan error) error { +func serveClipboardChanges(ctx context.Context, live *liveSettings, gate *focusGate, speech speechEnqueuer, encoder *json.Encoder, changes <-chan clipboard.TextChange, failures <-chan error) error { ticker := time.NewTicker(20 * time.Millisecond) defer ticker.Stop() var previous clipboardScope var epoch uint64 var lastText string update := func() error { - scope := clipboard_scope(live, gate) + scope := newClipboardScope(live, gate) if scope == previous { return nil } @@ -162,7 +162,7 @@ func serve_clipboard_changes(ctx context.Context, live *liveSettings, gate *focu if change.Ready { continue } - if clipboard_scope(live, gate) != previous { + if newClipboardScope(live, gate) != previous { if err := update(); err != nil { return err } diff --git a/internal/app/clipboard_watch_test.go b/internal/app/clipboard_watch_test.go index 4fda302..e19338a 100644 --- a/internal/app/clipboard_watch_test.go +++ b/internal/app/clipboard_watch_test.go @@ -30,7 +30,7 @@ func TestAutomaticClipboardQueuesTextAndNormalInputCancels(t *testing.T) { changes <- clipboard.TextChange{Text: "Third", Epoch: 1, Timestamp: 40} close(changes) var output bytes.Buffer - serve_clipboard_changes(context.Background(), live, nil, worker, json.NewEncoder(&output), changes, nil) + serveClipboardChanges(context.Background(), live, nil, worker, json.NewEncoder(&output), changes, nil) if len(worker.pending) != 3 { t.Fatalf("clipboard queue = %+v", worker.pending) } @@ -77,7 +77,7 @@ func TestAutomaticClipboardRejectsDisabledAndStaleApplications(t *testing.T) { close(changes) speech := &fakeSpeechQueue{spoken: make(chan string, 1), interrupt: make(chan struct{}, 1)} var output bytes.Buffer - serve_clipboard_changes(context.Background(), live, nil, speech, json.NewEncoder(&output), changes, nil) + serveClipboardChanges(context.Background(), live, nil, speech, json.NewEncoder(&output), changes, nil) if len(speech.spoken) != 0 || len(speech.interrupt) != 0 { t.Fatal("disabled/stale clipboard was spoken") } @@ -89,7 +89,7 @@ func TestAutomaticClipboardDisabledStartsNoHelperAndStops(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) live := &liveSettings{clipboardChanges: make(chan struct{}, 1)} live.Store(config.DefaultSettings()) - done := run_automatic_clipboard(ctx, slog.New(slog.DiscardHandler), live, nil, discardSpeech{}) + done := runAutomaticClipboard(ctx, slog.New(slog.DiscardHandler), live, nil, discardSpeech{}) cancel() select { case <-done: diff --git a/internal/app/configured_speaker.go b/internal/app/configured_speaker.go index 6386087..8c1f5bc 100644 --- a/internal/app/configured_speaker.go +++ b/internal/app/configured_speaker.go @@ -7,6 +7,7 @@ package app import ( "context" "errors" + "path/filepath" "sync" "unicode" "unicode/utf8" @@ -71,14 +72,14 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti } hardware.settings = settings hardware.mu.Unlock() - speaker.retire_remote_voice(settings) + speaker.retireRemoteVoice(settings) return nil } if software, ok := current.(*echoSpeaker); ok && settings.SpeechServerFactory != "hardwarefactory" { if err := software.UpdateConfiguration(ctx, settings); err != nil { return err } - speaker.retire_remote_voice(settings) + speaker.retireRemoteVoice(settings) return nil } var candidate configuredVoice @@ -88,6 +89,9 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti } else { candidate = newEchoSpeaker(speaker.socket, settings) } + if old, ok := current.(*hardwareSpeaker); ok && settings.SpeechServerFactory == "hardwarefactory" && old.sameDevice(settings) { + return speaker.reopenHardware(ctx, old, candidate, settings) + } if err := candidate.Connect(ctx); err != nil { return err } @@ -106,7 +110,7 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti } speaker.active = candidate speaker.mu.Unlock() - speaker.retire_remote_voice(settings) + speaker.retireRemoteVoice(settings) // The new backend is committed. A retired connection's cleanup error must // not report this successful swap as a rejected preferences transaction. if current != nil { @@ -114,6 +118,53 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti } return nil } + +// reopenHardware moves a hardware device to new settings (synthesizer or baud +// rate). The transport locks the device, so the current owner is released +// before the new one opens; if the new settings cannot open it, the previous +// configuration is reopened so speech keeps working. +func (speaker *configuredSpeaker) reopenHardware(ctx context.Context, old *hardwareSpeaker, candidate configuredVoice, settings config.Settings) error { + speaker.mu.Lock() + if speaker.closed || ctx.Err() != nil { + speaker.mu.Unlock() + return errors.New("speech configuration was canceled") + } + speaker.active = nil + speaker.mu.Unlock() + _ = old.Close(context.Background()) // Being replaced; Close cancels speech first. + connectErr := candidate.Connect(ctx) + if connectErr == nil { + connectErr = ctx.Err() + if connectErr != nil { + // Release a connected candidate before restoring the exclusive + // device lock. A failed Connect has no live client to close. + _ = candidate.Close(context.Background()) + } + } + next := candidate + if connectErr != nil { + old.mu.RLock() + next = &hardwareSpeaker{device: old.device, baud: old.baud, synth: old.synth, settings: old.settings} + old.mu.RUnlock() + if err := next.Connect(context.Background()); err != nil { + return errors.Join(connectErr, err) + } + } + speaker.mu.Lock() + if speaker.closed { + speaker.mu.Unlock() + _ = next.Close(context.Background()) + return errors.New("speech configuration was canceled") + } + speaker.active = next + speaker.mu.Unlock() + if connectErr != nil { + return connectErr + } + speaker.retireRemoteVoice(settings) + return nil +} + func (speaker *configuredSpeaker) voice() (configuredVoice, error) { speaker.mu.RLock() defer speaker.mu.RUnlock() @@ -172,18 +223,18 @@ func (speaker *configuredSpeaker) SpeakAndWait(ctx context.Context, text string, return voice.SpeakAndWait(ctx, text, began) } -func (speaker *configuredSpeaker) speak_uninterruptible(ctx context.Context, text string) error { +func (speaker *configuredSpeaker) speakUninterruptible(ctx context.Context, text string) error { voice, err := speaker.voice() if err != nil { return err } reader, ok := voice.(interface { - speak_uninterruptible(context.Context, string) error + speakUninterruptible(context.Context, string) error }) if !ok { return errors.New("speech backend does not report utterance completion") } - return reader.speak_uninterruptible(ctx, text) + return reader.speakUninterruptible(ctx, text) } func (speaker *configuredSpeaker) Cancel(ctx context.Context) error { speaker.mu.RLock() @@ -244,12 +295,12 @@ func (speaker *hardwareSpeaker) SpeakEcho(ctx context.Context, text string) erro return speaker.speak(ctx, text, true, "default") } func (speaker *hardwareSpeaker) SpeakCharacter(ctx context.Context, text string) error { - return speaker.speak_character(ctx, text, false) + return speaker.speakCharacter(ctx, text, false) } func (speaker *hardwareSpeaker) SpeakEchoCharacter(ctx context.Context, text string) error { - return speaker.speak_character(ctx, text, true) + return speaker.speakCharacter(ctx, text, true) } -func (speaker *hardwareSpeaker) speak_character(ctx context.Context, text string, echo bool) error { +func (speaker *hardwareSpeaker) speakCharacter(ctx context.Context, text string, echo bool) error { r, size := utf8.DecodeRuneInString(text) kind := "default" if size == len(text) && unicode.IsUpper(r) { @@ -314,5 +365,16 @@ func (speaker *hardwareSpeaker) SpeakVoiceAndWait(ctx context.Context, text, kin } return nil } + +// sameDevice reports whether settings name the device this speaker holds: +// both DECtalk USB, or the same serial path. +func (speaker *hardwareSpeaker) sameDevice(settings config.Settings) bool { + usb := speaker.synth == "dectalk-usb" + if usb || settings.SpeechOutputModule == "dectalk-usb" { + return usb && settings.SpeechOutputModule == "dectalk-usb" + } + return filepath.Clean(speaker.device) == filepath.Clean(settings.HardwareSpeechDevice) +} + func (speaker *hardwareSpeaker) Cancel(ctx context.Context) error { return speaker.client.Cancel(ctx) } func (speaker *hardwareSpeaker) Close(ctx context.Context) error { return speaker.client.Close(ctx) } diff --git a/internal/app/configured_speaker_native_test.go b/internal/app/configured_speaker_native_test.go index 403ab3c..cb28f37 100644 --- a/internal/app/configured_speaker_native_test.go +++ b/internal/app/configured_speaker_native_test.go @@ -8,6 +8,7 @@ package app import ( "context" + "errors" "fmt" "io" "log/slog" @@ -22,7 +23,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/preferences" ) -func test_hardware_switch(t *testing.T, speaker *configuredSpeaker, software config.Settings) { +func testHardwareSwitch(t *testing.T, speaker *configuredSpeaker, software config.Settings) { t.Helper() fd, err := syscall.Open("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK, 0600) if err != nil { @@ -81,6 +82,17 @@ func test_hardware_switch(t *testing.T, speaker *configuredSpeaker, software con t.Fatal("failed Apply committed a missing device") } check(speaker.Speak, "Retained", "\x010S\x0199P\x019VRetained\r") + old := speaker.active.(*hardwareSpeaker) + updateContext, cancelUpdate := context.WithCancel(ctx) + defer cancelUpdate() + candidate := &cancelOnConnectVoice{configuredVoice: old, cancel: cancelUpdate} + if err := speaker.reopenHardware(updateContext, old, candidate, hardware); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled hardware replacement = %v", err) + } + if !candidate.closed { + t.Fatal("canceled hardware candidate was not closed before rollback") + } + check(speaker.Speak, "Restored", "\x18\x010S\x0199P\x019VRestored\r") if err := speaker.UpdateConfiguration(ctx, software); err != nil { t.Fatal(err) } @@ -88,3 +100,19 @@ func test_hardware_switch(t *testing.T, speaker *configuredSpeaker, software con t.Fatal("unexpected fixture device") } } + +type cancelOnConnectVoice struct { + configuredVoice + cancel context.CancelFunc + closed bool +} + +func (voice *cancelOnConnectVoice) Connect(context.Context) error { + voice.cancel() + return nil +} + +func (voice *cancelOnConnectVoice) Close(context.Context) error { + voice.closed = true + return nil +} diff --git a/internal/app/current_line.go b/internal/app/current_line.go index edcb6aa..4bb5c94 100644 --- a/internal/app/current_line.go +++ b/internal/app/current_line.go @@ -10,7 +10,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/review" ) -func (handler *eventReviewHandler) current_line(command input.Command) { +func (handler *eventReviewHandler) currentLine(command input.Command) { if handler.focusGate.Locked() || handler.focusGate.Suspended() { return } @@ -33,7 +33,7 @@ func (handler *eventReviewHandler) current_line(command input.Command) { } } -func (handler *eventReviewHandler) present_current_line(result review.Result) { +func (handler *eventReviewHandler) presentCurrentLine(result review.Result) { if !handler.objectReview.CurrentDocumentResult(result) || result.DocumentFocus != handler.objectReview.Focus() || handler.focusGate.Locked() || handler.focusGate.Suspended() { return } @@ -53,9 +53,9 @@ func (handler *eventReviewHandler) present_current_line(result review.Result) { if result.CurrentLineBrowse || nativeSource { sources := atspi.DocumentLine{Contents: []atspi.DocumentContent{{Snapshot: result.DocumentPosition.Snapshot}}, SourceContexts: [][]atspi.Snapshot{result.DocumentCaretContext}} - request.origin = document_line_speech_origin(sources) + request.origin = documentLineSpeechOrigin(sources) if result.DocumentCaretLine != nil { - if origin := document_line_speech_origin(*result.DocumentCaretLine); origin != speechOriginLocal { + if origin := documentLineSpeechOrigin(*result.DocumentCaretLine); origin != speechOriginLocal { request.origin = origin } } @@ -63,7 +63,7 @@ func (handler *eventReviewHandler) present_current_line(result review.Result) { text := result.DocumentCaretText request.Text = presentation.FlatReviewText(text, false) request.Role = result.DocumentPosition.Snapshot.Role - set_review_spelling(&request, text, result.FlatSpeech) + setReviewSpelling(&request, text, result.FlatSpeech) } handler.speech.Enqueue(request) } diff --git a/internal/app/current_line_test.go b/internal/app/current_line_test.go index 02f64f2..5430826 100644 --- a/internal/app/current_line_test.go +++ b/internal/app/current_line_test.go @@ -81,19 +81,19 @@ func TestCurrentLinePresentationAndStaleResults(t *testing.T) { {"", review.FlatSpeak, errors.New("unavailable"), "Could not read current line.", nil}, } { result := review.Result{CurrentLine: true, DocumentFocus: focus, DocumentCaretText: probe.text, FlatSpeech: probe.style, Err: probe.err} - handler.present_current_line(result) + handler.presentCurrentLine(result) got := <-queue.requests if got.Text != probe.want || !reflect.DeepEqual(got.Spelling, probe.spelling) { t.Fatalf("current line: %+v, want %q %v", got, probe.want, probe.spelling) } } worker.ResetDocument(focus) - handler.present_current_line(review.Result{CurrentLine: true, DocumentFocus: focus}) + handler.presentCurrentLine(review.Result{CurrentLine: true, DocumentFocus: focus}) if len(queue.requests) != 0 { t.Fatal("stale report was spoken") } worker.SyncFocus(atspi.ObjectID{BusName: ":1.42", Path: "/other"}) - handler.present_current_line(review.Result{CurrentLine: true, DocumentFocus: focus, DocumentEpoch: worker.DocumentEpoch()}) + handler.presentCurrentLine(review.Result{CurrentLine: true, DocumentFocus: focus, DocumentEpoch: worker.DocumentEpoch()}) if len(queue.requests) != 0 { t.Fatal("report from previous focus was spoken") } @@ -122,11 +122,11 @@ func TestCurrentLineSecureFocus(t *testing.T) { } else { handler.syncForeground = secure } - handler.current_line(input.PresentCurrentLine) + handler.currentLine(input.PresentCurrentLine) // An already completed read must also be rejected on secure input. - result := native_current_line_result() + result := nativeCurrentLineResult() result.DocumentFocus = focus - handler.present_current_line(result) + handler.presentCurrentLine(result) if len(queue.requests) != 0 { t.Fatal("current line spoke during lock or handoff") } diff --git a/internal/app/current_speech_source.go b/internal/app/current_speech_source.go index 59ba77d..7b4df2f 100644 --- a/internal/app/current_speech_source.go +++ b/internal/app/current_speech_source.go @@ -29,8 +29,8 @@ func (state *eventLoopState) setCurrentDocument(result review.Result) { if result.Err != nil || !state.current.ID().Valid() || len(sources) == 0 || sources[0].ID() != state.current.ID() { return } - origin := review_speech_origin(sources) - if source := accessibility_speech_origin(state.current); source != speechOriginLocal { + origin := reviewSpeechOrigin(sources) + if source := accessibilitySpeechOrigin(state.current); source != speechOriginLocal { origin = source } state.currentSpeech = currentSpeechSource{origin: origin, focus: result.DocumentFocus, epoch: result.DocumentEpoch} diff --git a/internal/app/date_time.go b/internal/app/date_time.go index ff9ebaa..e1861a4 100644 --- a/internal/app/date_time.go +++ b/internal/app/date_time.go @@ -8,8 +8,8 @@ import ( "time" "git.stormux.org/storm/cthulhu/internal/config" - "git.stormux.org/storm/cthulhu/internal/datetime" "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/screenreader-common/datetime" ) // The command worker supplies local wall time and one immutable settings snapshot. diff --git a/internal/app/date_time_test.go b/internal/app/date_time_test.go index 2a40402..bda9a90 100644 --- a/internal/app/date_time_test.go +++ b/internal/app/date_time_test.go @@ -10,9 +10,9 @@ import ( "time" "git.stormux.org/storm/cthulhu/internal/config" - "git.stormux.org/storm/cthulhu/internal/datetime" "git.stormux.org/storm/cthulhu/internal/input" "git.stormux.org/storm/cthulhu/internal/preferences" + "git.stormux.org/storm/screenreader-common/datetime" ) func TestDateTimeFormats(t *testing.T) { diff --git a/internal/app/document_review.go b/internal/app/document_review.go index 1c49b2d..fe89ad0 100644 --- a/internal/app/document_review.go +++ b/internal/app/document_review.go @@ -197,7 +197,7 @@ func presentDocumentCaretResult(logger *slog.Logger, speech speechEnqueuer, resu "source_path", result.DocumentPosition.Object.ID().Path, "virtual_caret_offset", result.DocumentPosition.Offset, "native_text_start", result.DocumentCaretStart, "native_text_end", result.DocumentCaretEnd, - "line_fragments", document_line_ranges(result.DocumentCaretLine), + "line_fragments", documentLineRanges(result.DocumentCaretLine), "caret_sync_error", result.CaretErr, "braille_line_available", result.DocumentBrailleLine != nil || result.DocumentCaretLine != nil, "braille_read_error", result.DocumentBrailleErr) @@ -220,9 +220,9 @@ func presentDocumentCaretResult(logger *slog.Logger, speech speechEnqueuer, resu } text = "blank" } - request := speechRequest{origin: document_speech_origin(result.DocumentPosition.Snapshot, result.DocumentCaretContext), Text: text, Role: result.DocumentPosition.Snapshot.Role, Cause: "document-caret"} + request := speechRequest{origin: documentSpeechOrigin(result.DocumentPosition.Snapshot, result.DocumentCaretContext), Text: text, Role: result.DocumentPosition.Snapshot.Role, Cause: "document-caret"} if result.DocumentCaretLine != nil { - if origin := document_line_speech_origin(*result.DocumentCaretLine); origin != speechOriginLocal { + if origin := documentLineSpeechOrigin(*result.DocumentCaretLine); origin != speechOriginLocal { request.origin = origin } } @@ -270,7 +270,7 @@ func presentDocumentCaretResult(logger *slog.Logger, speech speechEnqueuer, resu review.CaretNextWord, review.CaretPreviousWord: line := atspi.DocumentLine{Contents: []atspi.DocumentContent{{Snapshot: result.DocumentPosition.Snapshot, Text: text, RawText: result.DocumentCaretRawText}}} if result.DocumentCaretCommand != review.CaretNextWord && result.DocumentCaretCommand != review.CaretPreviousWord { - request.Line = document_speech_line(line) + request.Line = documentSpeechLine(line) } roles := map[string]bool{result.DocumentPosition.Snapshot.Role: true} // Chromium commonly exposes link/heading text in static descendants. @@ -301,7 +301,7 @@ func presentDocumentCaretResult(logger *slog.Logger, speech speechEnqueuer, resu speech.Enqueue(request) } -func document_line_ranges(line *atspi.DocumentLine) []map[string]any { +func documentLineRanges(line *atspi.DocumentLine) []map[string]any { if line == nil { return nil } @@ -402,8 +402,8 @@ func presentDocumentResult(logger *slog.Logger, speech speechEnqueuer, result re text = "No more large objects." } default: - origin = document_speech_origin(result.DocumentPosition.Snapshot, result.DocumentCaretContext) - if link := result.DocumentPosition.LinkedHeading; link != nil && accessibility_speech_origin(*link) == speechOriginSecret { + origin = documentSpeechOrigin(result.DocumentPosition.Snapshot, result.DocumentCaretContext) + if link := result.DocumentPosition.LinkedHeading; link != nil && accessibilitySpeechOrigin(*link) == speechOriginSecret { origin = speechOriginSecret } if link := result.DocumentPosition.LinkedHeading; link != nil { @@ -467,7 +467,7 @@ func presentDocumentResult(logger *slog.Logger, speech speechEnqueuer, result re logger.Warn("document caret synchronization failed", "error", result.CaretErr) } } - voiceType := ancestor_voice(result.DocumentCaretContext) + voiceType := ancestorVoice(result.DocumentCaretContext) if result.DocumentPosition.LinkedHeading != nil { voiceType = "hyperlink" } diff --git a/internal/app/echo_speaker.go b/internal/app/echo_speaker.go index 47b88d5..87bae42 100644 --- a/internal/app/echo_speaker.go +++ b/internal/app/echo_speaker.go @@ -59,7 +59,7 @@ func (speaker *echoSpeaker) UpdateConfiguration(ctx context.Context, settings co voiceSettings["echo"] = echoSpeechSettings(settings) echoSettings := settings echoSettings.DefaultVoice = config.EffectiveVoice(settings, "default") - merge_echo_voice(&echoSettings.DefaultVoice, settings.EchoVoice) + mergeEchoVoice(&echoSettings.DefaultVoice, settings.EchoVoice) echoSettings.DefaultVoice = config.EffectiveVoice(echoSettings, "uppercase") if settings.UseCustomEchoSpeechServer { echoSettings.SpeechOutputModule = settings.EchoSpeechServer @@ -120,12 +120,12 @@ func (speaker *echoSpeaker) SpeakVoice(ctx context.Context, text, kind string) e return client.Speak(ctx, text) } func (speaker *echoSpeaker) SpeakCharacter(ctx context.Context, text string) error { - return speaker.speak_character(ctx, text, false) + return speaker.speakCharacter(ctx, text, false) } func (speaker *echoSpeaker) SpeakEchoCharacter(ctx context.Context, text string) error { - return speaker.speak_character(ctx, text, true) + return speaker.speakCharacter(ctx, text, true) } -func (speaker *echoSpeaker) speak_character(ctx context.Context, text string, custom bool) error { +func (speaker *echoSpeaker) speakCharacter(ctx context.Context, text string, custom bool) error { speaker.mu.RLock() defer speaker.mu.RUnlock() kind := "default" @@ -152,7 +152,7 @@ func (speaker *echoSpeaker) SpeakAndWait(ctx context.Context, text string, began return speaker.SpeakVoiceAndWait(ctx, text, "default", began) } -func (speaker *echoSpeaker) speak_uninterruptible(ctx context.Context, text string) error { +func (speaker *echoSpeaker) speakUninterruptible(ctx context.Context, text string) error { return speaker.SpeakVoiceAndWait(ctx, text, "system", nil) } @@ -187,7 +187,7 @@ func (speaker *echoSpeaker) Close(ctx context.Context) error { speaker.voices = nil return result } -func merge_echo_voice(voice *config.Voice, echo config.Voice) { +func mergeEchoVoice(voice *config.Voice, echo config.Voice) { if echo.Rate != nil { voice.Rate = echo.Rate } diff --git a/internal/app/echo_speaker_test.go b/internal/app/echo_speaker_test.go index f38e3c4..f258de7 100644 --- a/internal/app/echo_speaker_test.go +++ b/internal/app/echo_speaker_test.go @@ -26,11 +26,11 @@ import ( func TestEchoSpeakerSwitchesBothVoicesTransactionally(t *testing.T) { for _, wrapped := range []bool{false, true} { - t.Run(fmt.Sprintf("configured=%v", wrapped), func(t *testing.T) { test_echo_speaker(t, wrapped) }) + t.Run(fmt.Sprintf("configured=%v", wrapped), func(t *testing.T) { testEchoSpeaker(t, wrapped) }) } } -func test_echo_speaker(t *testing.T, wrapped bool) { +func testEchoSpeaker(t *testing.T, wrapped bool) { path := filepath.Join(t.TempDir(), "speech.sock") listener, err := net.Listen("unix", path) if err != nil { @@ -165,7 +165,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) { // Exercise the new request path through the actual configured backend // and private SSIP connections, including a failure in the echo client // after preparation of the new main client has already succeeded. - readerWorker, session, _ := reader_extension_fixture(t, "normal") + readerWorker, session, _ := readerExtensionFixture(t, "normal") base := settings base.Path = readerWorker.settings.Path readerWorker.settings, readerWorker.globalSettings = base, base @@ -175,18 +175,18 @@ func test_echo_speaker(t *testing.T, wrapped bool) { configuration.Module = "tentacle-module" profileRate := 65.0 configuration.DefaultVoice.Rate = &profileRate - if _, err := readerWorker.apply_reader_request(ctx, session, tentaclewire.ReaderRequest{Speech: &configuration}, false); err != nil { + if _, err := readerWorker.applyReaderRequest(ctx, session, tentaclewire.ReaderRequest{Speech: &configuration}, false); err != nil { t.Fatal(err) } check(false, "tentacle-module", "65") check(true, "echo-module", "80") configuration.Module, configuration.EchoServer = "candidate-module", "rejected" - if _, err := readerWorker.apply_reader_request(ctx, session, tentaclewire.ReaderRequest{Speech: &configuration}, false); err == nil { + if _, err := readerWorker.applyReaderRequest(ctx, session, tentaclewire.ReaderRequest{Speech: &configuration}, false); err == nil { t.Fatal("failed echo client accepted through reader API") } check(false, "tentacle-module", "65") check(true, "echo-module", "80") - if _, err := readerWorker.apply_reader_request(ctx, session, tentaclewire.ReaderRequest{RestoreSpeech: true}, false); err != nil { + if _, err := readerWorker.applyReaderRequest(ctx, session, tentaclewire.ReaderRequest{RestoreSpeech: true}, false); err != nil { t.Fatal(err) } check(false, "", "") @@ -258,7 +258,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) { Family: &config.VoiceFamily{Name: "Preview voice", Lang: "en"}} previewSpeech := newSpeechWorker(slog.New(slog.DiscardHandler), speaker) previewWorker.announceEchoPreview = func(label, value string) { - if err := previewSpeech.deliver(ctx, echo_preview_speech(label, value)); err != nil { + if err := previewSpeech.deliver(ctx, echoPreviewSpeech(label, value)); err != nil { t.Fatal(err) } } @@ -625,7 +625,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) { } checkCharacters("-30") if wrapped { - test_hardware_switch(t, speaker.(*configuredSpeaker), settings) + testHardwareSwitch(t, speaker.(*configuredSpeaker), settings) check(false, "", "") checkCharacters("-30") } diff --git a/internal/app/emoji_menu.go b/internal/app/emoji_menu.go index c2218ea..8aeab9e 100644 --- a/internal/app/emoji_menu.go +++ b/internal/app/emoji_menu.go @@ -7,21 +7,19 @@ package app import ( "context" "time" - - "git.stormux.org/storm/cthulhu/internal/interaction" ) type emojiTextSource interface { TypeText(context.Context, string) error } -func (ui *internalUI) emoji_insertion_allowed() bool { +func (ui *internalUI) emojiInsertionAllowed() bool { if owner, ok := ui.keys.(interface{ BrowseNavigationEnabled() bool }); ok { return !owner.BrowseNavigationEnabled() } return true } -func (ui *internalUI) select_emoji(ctx context.Context, selection interaction.Value, copyChecked bool) { +func (ui *internalUI) selectEmoji(ctx context.Context, id, label string, copyChecked bool) { if ctx.Err() != nil || ui.gate.Locked() || ui.gate.Suspended() { return } @@ -30,21 +28,21 @@ func (ui *internalUI) select_emoji(ctx context.Context, selection interaction.Va var message string if copyChecked { message = "Copy failed" - if ui.emojiCopier != nil && ui.emojiCopier.Copy(actionCtx, selection.Selected) == nil { - message = "Copied " + selection.Text + " to clipboard" + if ui.emojiCopier != nil && ui.emojiCopier.Copy(actionCtx, id) == nil { + message = "Copied " + label + " to clipboard" } - } else if !ui.emoji_insertion_allowed() { + } else if !ui.emojiInsertionAllowed() { message = "Emoji insertion unavailable in browse mode" } else { message = "Emoji insertion unavailable" - if ui.emojiSource != nil && ui.emojiSource.TypeText(actionCtx, selection.Selected) == nil { - message = "Inserted " + selection.Text + if ui.emojiSource != nil && ui.emojiSource.TypeText(actionCtx, id) == nil { + message = "Inserted " + label } } - ui.emoji_message(message) + ui.emojiMessage(message) } -func (ui *internalUI) emoji_message(message string) { +func (ui *internalUI) emojiMessage(message string) { if ui.gate.Locked() || ui.gate.Suspended() { return } diff --git a/internal/app/emoji_menu_test.go b/internal/app/emoji_menu_test.go index b1050e8..c2234ea 100644 --- a/internal/app/emoji_menu_test.go +++ b/internal/app/emoji_menu_test.go @@ -9,7 +9,6 @@ import ( "time" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" ) type emojiTestSource struct { @@ -102,7 +101,7 @@ func TestEmojiTypingFailure(t *testing.T) { source := &emojiTestSource{keys: &uiTestKeys{}, calls: make(chan string, 1), err: errors.New("unsupported")} output := &ocrTestOutput{speech: make(chan speechRequest, 1)} ui := &internalUI{keys: source.keys, emojiSource: source, speech: output, gate: &focusGate{}} - ui.select_emoji(context.Background(), interaction.Value{Selected: "🐐", Text: "Goat"}, false) + ui.selectEmoji(context.Background(), "🐐", "Goat", false) if got := (<-output.speech).Text; got != "Emoji insertion unavailable" { t.Fatal(got) } @@ -117,11 +116,11 @@ func TestEmojiBrowseModeBlocksTypingAndAllowsCopy(t *testing.T) { copier := &ocrTestCopier{copied: make(chan string, 1)} output := &ocrTestOutput{speech: make(chan speechRequest, 2)} ui := &internalUI{keys: keys, emojiSource: source, emojiCopier: copier, speech: output, gate: &focusGate{}} - ui.select_emoji(context.Background(), interaction.Value{Selected: "🐐", Text: "Goat"}, false) + ui.selectEmoji(context.Background(), "🐐", "Goat", false) if got := (<-output.speech).Text; got != "Emoji insertion unavailable in browse mode" { t.Fatal(got) } - ui.select_emoji(context.Background(), interaction.Value{Selected: "🐐", Text: "Goat"}, true) + ui.selectEmoji(context.Background(), "🐐", "Goat", true) if got := (<-output.speech).Text; got != "Copied Goat to clipboard" { t.Fatal(got) } diff --git a/internal/app/event_accessibility.go b/internal/app/event_accessibility.go index 05d86d0..fe6f7a2 100644 --- a/internal/app/event_accessibility.go +++ b/internal/app/event_accessibility.go @@ -69,7 +69,7 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { if event.Type == atspi.MouseButtonEvent { state.pending.clear() if browser != nil { - browser.pointer_input() + browser.pointerInput() } logger.Debug("released virtual caret for pointer input") return @@ -119,7 +119,7 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { return } syncForeground() - if handler.handle_window_switcher(event) { + if handler.handleWindowSwitcher(event) { return } if handler.messaging.handle(event) { @@ -135,7 +135,7 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { if webScripts.handle(event) { return } - if handler.handle_progress_bar(event) { + if handler.handleProgressBar(event) { return } ending := event.Type == atspi.DefunctStateEvent || event.Type == atspi.WindowDestroyedEvent || event.Type == atspi.WindowDeactivatedEvent @@ -266,7 +266,7 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { return } pending, _ := state.pending.terminalRepaint.take() - if is_trivial_terminal_repaint(pending) { + if isTrivialTerminalRepaint(pending) { logger.Debug("dropped trivial terminal repaint fragment", "role", pending.Source.Role) return } @@ -290,7 +290,7 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { state.pending.terminalDeletion.clear() logger.Debug("coalesced terminal deletion with following insertion", "role", event.Source.Role) } else if !(event.Type == atspi.TextDeletedEvent && sameTerminal && !userDeletion && - (should_ignore_terminal_scrollback(event) || terminalReplacementOverlap(pendingDeletion, event))) { + (shouldIgnoreTerminalScrollback(event) || terminalReplacementOverlap(pendingDeletion, event))) { // An overlapping deletion from the same terminal is part of the same // repaint burst. It is handled below: scroll shifts return // early, anything else replaces the pending deletion. Either @@ -312,7 +312,7 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { if handler.acceptFocusedEvent(event, activity) { return } - if handler.defer_browser_button_name(event, activity) { + if handler.deferBrowserButtonName(event, activity) { return } if handler.handleSelectionAndClipboard(event, activity, intent) { @@ -328,16 +328,16 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { } if event.Type == atspi.TextDeletedEvent && event.Source.Role == "terminal" { if state.pending.terminalRepaint.event.Type != "" && - !should_ignore_terminal_scrollback(event) && - (is_user_terminal_deletion(event, intent) || !terminalReplacementOverlap(state.pending.terminalRepaint.event, event)) { + !shouldIgnoreTerminalScrollback(event) && + (isUserTerminalDeletion(event, intent) || !terminalReplacementOverlap(state.pending.terminalRepaint.event, event)) { flushTerminalRepaint() } - if should_ignore_terminal_scrollback(event) { + if shouldIgnoreTerminalScrollback(event) { logger.Debug("skipped terminal scrollback deletion", "role", event.Source.Role) return } deletionIntent := input.NoIntent - if is_user_terminal_deletion(event, intent) { + if isUserTerminalDeletion(event, intent) { deletionIntent = input.DeleteIntent } state.pending.terminalDeletion.schedule(event, deletionIntent, terminalMutationDebounce) @@ -347,12 +347,12 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) { // briefly so a newer rewrite of the same region replaces it before // either speaks. A rewrite of a different region, or appended output // from the same terminal, first flushes the held repaint in order. - if is_latest_wins_terminal_repaint(event, intent, replacedDeletion) { + if isLatestWinsTerminalRepaint(event, intent, replacedDeletion) { if state.pending.terminalRepaint.event.Type != "" && !terminalReplacementOverlap(state.pending.terminalRepaint.event, event) { flushTerminalRepaint() } - state.pending.terminalRepaint.coalesce_terminal_repaint(event) + state.pending.terminalRepaint.coalesceTerminalRepaint(event) logger.Debug("queued latest-wins terminal repaint", "role", event.Source.Role) if autocompleteRequest.Text != "" { speech.Enqueue(autocompleteRequest) diff --git a/internal/app/event_loop.go b/internal/app/event_loop.go index 73310a8..696c750 100644 --- a/internal/app/event_loop.go +++ b/internal/app/event_loop.go @@ -314,10 +314,10 @@ func processEventsWithAttributes( } case <-state.pending.browserButtonName.ready: syncForeground() - eventHandler.flush_browser_button_name() + eventHandler.flushBrowserButtonName() case <-state.pending.radioSound.ready: syncForeground() - presenter.flush_radio_sound(focusGate) + presenter.flushRadioSound(focusGate) case <-state.pending.caret.ready: if focusGate.Locked() { state.pending.clear() @@ -345,7 +345,7 @@ func processEventsWithAttributes( continue } event, _ := state.pending.terminalRepaint.take() - if is_trivial_terminal_repaint(event) { + if isTrivialTerminalRepaint(event) { logger.Debug("dropped trivial terminal repaint fragment", "role", event.Source.Role) continue } @@ -353,7 +353,7 @@ func processEventsWithAttributes( case command := <-reviewRequests: switch command { case input.PresentCurrentLine, input.SpellCurrentLine, input.PhoneticCurrentLine: - reviewHandler.current_line(command) + reviewHandler.currentLine(command) case input.PresentWindowTitle: syncForeground() titles.present() diff --git a/internal/app/event_presentation.go b/internal/app/event_presentation.go index 97908b8..22cc8d1 100644 --- a/internal/app/event_presentation.go +++ b/internal/app/event_presentation.go @@ -130,7 +130,7 @@ func (presenter *eventPresenter) speak(event atspi.Event, capturedIntent ...inpu state.typingText = event.Source.Text } } - if state.submitted_text_clear(event, recentInput(inputSource)) { + if state.submittedTextClear(event, recentInput(inputSource)) { // Focus, caret suppression and Braille were already updated by the // event handler. Only omit speech for the entry's submission clear. logger.Debug("skipped deletion feedback after submitting text", "role", event.Source.Role) @@ -179,7 +179,7 @@ func (presenter *eventPresenter) speak(event atspi.Event, capturedIntent ...inpu // The control's own focus event will present its role and cue. cues = nil } - cues = presenter.coalesce_radio_sound(event, cues) + cues = presenter.coalesceRadioSound(event, cues) cueParts := make([]string, 0, len(cues)) for _, cue := range cues { cueParts = append(cueParts, cue.Name+":"+strconv.FormatFloat(cue.Pan, 'g', -1, 64)) @@ -225,7 +225,7 @@ func (presenter *eventPresenter) speak(event atspi.Event, capturedIntent ...inpu (event.Type == atspi.CaretEvent && intent == input.LineIntent || isFocusGainEvent(event)) { line = &speechLine{Object: event.Source.ID(), Raw: event.Source.BrailleLine} } - browseContext := browser.speech_context_enabled() && event.Source.BusName == browser.document.BusName + browseContext := browser.speechContextEnabled() && event.Source.BusName == browser.document.BusName context := event.Source.SpeechContext if !browseContext && isFocusGainEvent(event) { // Named articles label a focused descendant even in focus mode (for @@ -241,8 +241,8 @@ func (presenter *eventPresenter) speak(event atspi.Event, capturedIntent ...inpu browseContext = len(context) != 0 } speech.Enqueue(speechRequest{ - origin: accessibility_speech_origin(event.Source), - Context: context, ResetContext: !browseContext, VoiceType: ancestor_voice(event.Source.SpeechContext), + origin: accessibilitySpeechOrigin(event.Source), + Context: context, ResetContext: !browseContext, VoiceType: ancestorVoice(event.Source.SpeechContext), Window: eventWindow(event), IntroducesWindow: (event.Type == atspi.WindowActivatedEvent || event.Type == atspi.WindowCreateEvent) && activationTitle(event) != "", diff --git a/internal/app/event_review_results.go b/internal/app/event_review_results.go index bebcdf6..bf40131 100644 --- a/internal/app/event_review_results.go +++ b/internal/app/event_review_results.go @@ -47,17 +47,17 @@ func (handler *eventReviewHandler) whereAmI() { state.pending.terminalDeletion.clear() state.pending.terminalRepaint.clear() origin := handler.currentSpeechOrigin() - observer, observing := handler.speech.(interface{ remote_observation_active() bool }) - if observing && observer.remote_observation_active() && origin == speechOriginUnknown && handler.objectReview != nil && state.current.ID() == handler.objectReview.Focus() && + observer, observing := handler.speech.(interface{ remoteObservationActive() bool }) + if observing && observer.remoteObservationActive() && origin == speechOriginUnknown && handler.objectReview != nil && state.current.ID() == handler.objectReview.Focus() && !(handler.browser != nil && handler.browser.ready && handler.browser.mode == review.BrowseMode) { if err := handler.objectReview.ReadWhereAmI(state.currentRevision); err == nil { return } } - handler.present_where_am_i(origin) + handler.presentWhereAmI(origin) } -func where_am_i_speech(snapshot atspi.Snapshot, options presentation.Options) presentation.Speech { +func whereAmISpeech(snapshot atspi.Snapshot, options presentation.Options) presentation.Speech { // Python's Where Am I is speech-only. Do not suppress the role merely // because ordinary focus presentation replaces it with a sound cue. options.EnableSound = false @@ -68,7 +68,7 @@ func where_am_i_speech(snapshot atspi.Snapshot, options presentation.Options) pr return spoken } -func (handler *eventReviewHandler) present_native_where_am_i(result review.Result) { +func (handler *eventReviewHandler) presentNativeWhereAmI(result review.Result) { state := handler.state if handler.focusGate.Locked() || handler.focusGate.Suspended() || handler.objectReview == nil || !handler.objectReview.CurrentDocumentResult(result) || result.DocumentFocus != handler.objectReview.Focus() || @@ -79,22 +79,22 @@ func (handler *eventReviewHandler) present_native_where_am_i(result review.Resul source, ancestry := result.DocumentPosition.Snapshot, result.DocumentCaretContext if result.Err == nil && source.ID() == state.current.ID() && len(ancestry) > 0 && ancestry[0].ID() == source.ID() && ancestry[len(ancestry)-1].Role == "application" && - review_speech_origin(ancestry) == speechOriginLocal && accessibility_speech_origin(source) == speechOriginLocal && - accessibility_speech_origin(state.current) == speechOriginLocal && source.Role == state.current.Role { + reviewSpeechOrigin(ancestry) == speechOriginLocal && accessibilitySpeechOrigin(source) == speechOriginLocal && + accessibilitySpeechOrigin(state.current) == speechOriginLocal && source.Role == state.current.Role { // Fresh ancestry alone cannot authorize older cached text. Require the // complete fresh report, including formula and chunk boundaries, to match. - fresh := where_am_i_speech(source, state.presentationOptions) - cached := where_am_i_speech(state.current, state.presentationOptions) + fresh := whereAmISpeech(source, state.presentationOptions) + cached := whereAmISpeech(state.current, state.presentationOptions) if fresh.Text == cached.Text && slices.Equal(fresh.Chunks, cached.Chunks) { origin = speechOriginLocal } } - handler.present_where_am_i(origin) + handler.presentWhereAmI(origin) } -func (handler *eventReviewHandler) present_where_am_i(origin speechOrigin) { +func (handler *eventReviewHandler) presentWhereAmI(origin speechOrigin) { state := handler.state - spoken := where_am_i_speech(state.current, state.presentationOptions) + spoken := whereAmISpeech(state.current, state.presentationOptions) text := spoken.Text role := state.current.Role if text == "" { @@ -110,7 +110,7 @@ func (handler *eventReviewHandler) handle(result review.Result) { handler.refreshPresentation() state := handler.state logger := handler.logger - speech := contextSpeechQueue{speechEnqueuer: handler.speech, enabled: handler.browser.speech_context_enabled()} + speech := contextSpeechQueue{speechEnqueuer: handler.speech, enabled: handler.browser.speechContextEnabled()} objectReview := handler.objectReview browser := handler.browser brailleOutput := handler.brailleOutput @@ -131,11 +131,11 @@ func (handler *eventReviewHandler) handle(result review.Result) { return } if result.WhereAmI { - handler.present_native_where_am_i(result) + handler.presentNativeWhereAmI(result) return } if result.CurrentLine { - handler.present_current_line(result) + handler.presentCurrentLine(result) return } if result.ReadAllPosition { @@ -194,7 +194,7 @@ func (handler *eventReviewHandler) handle(result review.Result) { if text == "" && len(cues) == 0 { return } - speech.Enqueue(speechRequest{origin: document_line_speech_origin(result.DocumentLineData), Text: text, Chunks: spoken.Chunks, FallbackText: fallback.Text, FallbackChunks: fallback.Chunks, Sound: cues, Role: "text", Cause: "document-caret-line", Line: document_speech_line(result.DocumentLineData), Context: result.DocumentLineData.Context, VoiceType: document_line_voice(result.DocumentLineData)}) + speech.Enqueue(speechRequest{origin: documentLineSpeechOrigin(result.DocumentLineData), Text: text, Chunks: spoken.Chunks, FallbackText: fallback.Text, FallbackChunks: fallback.Chunks, Sound: cues, Role: "text", Cause: "document-caret-line", Line: documentSpeechLine(result.DocumentLineData), Context: result.DocumentLineData.Context, VoiceType: documentLineVoice(result.DocumentLineData)}) return } if result.DocumentTarget != 0 || result.DocumentCaretCommand != 0 || result.DocumentFragment { @@ -310,7 +310,7 @@ func presentObjectReviewResult(logger *slog.Logger, speech speechEnqueuer, resul text = objectReviewBoundaryMessage(result.Direction) } else { options.EnableSound = false - origin = review_speech_origin(result.Position.SourceContext) + origin = reviewSpeechOrigin(result.Position.SourceContext) spoken = presentation.FocusSpeechWithOptions(result.Position.Current, options) text = spoken.Text role = result.Position.Current.Role diff --git a/internal/app/flat_review.go b/internal/app/flat_review.go index 9f522db..1567fb6 100644 --- a/internal/app/flat_review.go +++ b/internal/app/flat_review.go @@ -96,8 +96,8 @@ func presentFlatReviewResult(logger *slog.Logger, speech speechEnqueuer, result request.Line = &speechLine{Object: result.FlatPosition.Object, Raw: result.FlatPosition.Text} } if hasContent { - request.origin = review_speech_origin(result.FlatPosition.SourceContexts...) - set_review_spelling(&request, result.FlatPosition.Text, result.FlatSpeech) + request.origin = reviewSpeechOrigin(result.FlatPosition.SourceContexts...) + setReviewSpelling(&request, result.FlatPosition.Text, result.FlatSpeech) } if result.FlatWarning { logger.Warn("flat review content incomplete", "omitted_text_objects", result.FlatCompleteness.OmittedObjects, diff --git a/internal/app/focus_gate.go b/internal/app/focus_gate.go index 8a15ce5..01c4993 100644 --- a/internal/app/focus_gate.go +++ b/internal/app/focus_gate.go @@ -70,7 +70,7 @@ func (gate *focusGate) SetSuspended(suspended bool) bool { return false } gate.retireTentacleOutput() - gate.sync_remote_policy() + gate.syncRemotePolicy() if gate.commands != nil { gate.commands.SetCommandGrabs(!suspended && !gate.secure.Load()) } @@ -79,7 +79,7 @@ func (gate *focusGate) SetSuspended(suspended bool) bool { // Called during startup or with gate.mutex held. Cancellation never calls back // into the gate or runtime locks. Lock/unlock and handoff cannot restore consent. -func (gate *focusGate) sync_remote_policy() { +func (gate *focusGate) syncRemotePolicy() { if gate.remotePolicy != nil { gate.remotePolicy.SetAvailable(!gate.secure.Load() && !gate.suspended.Load()) } @@ -99,7 +99,7 @@ func (gate *focusGate) retireTentacleOutput() { } } -func (gate *focusGate) dismiss_confirmation() { +func (gate *focusGate) dismissConfirmation() { if gate != nil && gate.braille != nil { gate.braille.DismissConfirmation() } @@ -145,7 +145,7 @@ func (speaker gatedSpeech) InterruptForUser() { if speaker.gate.Locked() || speaker.gate.Suspended() { return } - speaker.gate.dismiss_confirmation() + speaker.gate.dismissConfirmation() if interrupt, ok := speaker.speech.(interface{ InterruptForUser() }); ok { interrupt.InterruptForUser() } else { @@ -166,7 +166,7 @@ func (speaker gatedSpeech) InterruptForInput(event input.Event) bool { if speech, ok := speaker.speech.(interface{ InterruptForInput(input.Event) bool }); ok { interrupted := speech.InterruptForInput(event) if interrupted { - speaker.gate.dismiss_confirmation() + speaker.gate.dismissConfirmation() } return interrupted } diff --git a/internal/app/gui_table_test.go b/internal/app/gui_table_test.go index 6f5fde7..a3e74a7 100644 --- a/internal/app/gui_table_test.go +++ b/internal/app/gui_table_test.go @@ -26,7 +26,7 @@ func TestGUITableNormalizedFocusRetainsOwnerAndTitle(t *testing.T) { close(completed) }() window := atspi.NewObjectID(":1.22", "/preferences") - cell_event := func(path, name, rowText string, row, column int, eventType string) atspi.Event { + cellEvent := func(path, name, rowText string, row, column int, eventType string) atspi.Event { cell := atspi.NewSnapshot(path, name, "table cell", "", "") cell.BusName = window.BusName cell.TablePath, cell.TableName = "/preferences/reading", "Reading settings" @@ -40,7 +40,7 @@ func TestGUITableNormalizedFocusRetainsOwnerAndTitle(t *testing.T) { } return event } - expect_speech := func(event atspi.Event, sequence uint64, want string) { + expectSpeech := func(event atspi.Event, sequence uint64, want string) { t.Helper() inputs.set(sequence) adapter.events <- event @@ -55,21 +55,21 @@ func TestGUITableNormalizedFocusRetainsOwnerAndTitle(t *testing.T) { } // The adapter resolves the table's initial focus to a selected cell. GTK // need not send another focused-state event as Up/Down changes rows. - first := cell_event("/reading/0/state", "unchecked", "unchecked, Only speak displayed text", 0, 0, atspi.FocusedStateEvent) - expect_speech(first, 1, "Reading settings, unchecked, Only speak displayed text") - second := cell_event("/reading/1/state", "checked", "checked, Break speech into chunks between pauses", 1, 0, atspi.SelectionChangedEvent) - expect_speech(second, 2, "checked, Break speech into chunks between pauses") + first := cellEvent("/reading/0/state", "unchecked", "unchecked, Only speak displayed text", 0, 0, atspi.FocusedStateEvent) + expectSpeech(first, 1, "Reading settings, unchecked, Only speak displayed text") + second := cellEvent("/reading/1/state", "checked", "checked, Break speech into chunks between pauses", 1, 0, atspi.SelectionChangedEvent) + expectSpeech(second, 2, "checked, Break speech into chunks between pauses") duplicate := second duplicate.Type = atspi.ActiveDescendantEvent adapter.events <- duplicate - right := cell_event("/reading/1/label", "Break speech into chunks between pauses", second.Source.TableRowText, 1, 1, atspi.ActiveDescendantEvent) - expect_speech(right, 3, "Break speech into chunks between pauses") + right := cellEvent("/reading/1/label", "Break speech into chunks between pauses", second.Source.TableRowText, 1, 1, atspi.ActiveDescendantEvent) + expectSpeech(right, 3, "Break speech into chunks between pauses") left := second left.Type = atspi.ActiveDescendantEvent - expect_speech(left, 4, "checked") + expectSpeech(left, 4, "checked") up := first up.Type = atspi.SelectionChangedEvent - expect_speech(up, 5, "unchecked, Only speak displayed text") + expectSpeech(up, 5, "unchecked, Only speak displayed text") // Background tables and another bus cannot inherit the focused table. other := second other.OriginPath, other.Source.TablePath = "/unrelated", "/unrelated" @@ -78,26 +78,26 @@ func TestGUITableNormalizedFocusRetainsOwnerAndTitle(t *testing.T) { other.OriginPath, other.Source.TablePath = first.OriginPath, first.Source.TablePath other.Source.BusName = ":1.99" adapter.events <- other - expect_speech(second, 6, "checked, Break speech into chunks between pauses") + expectSpeech(second, 6, "checked, Break speech into chunks between pauses") // A third description cell participates in full-row speech, while // horizontal movement reads just that cell. description := "Reads numbers one digit at a time." rowText := "unchecked, Speak numbers as digits, " + description - third := cell_event("/reading/2/state", "unchecked", rowText, 2, 0, atspi.SelectionChangedEvent) - expect_speech(third, 7, rowText) - descriptionCell := cell_event("/reading/2/description", description, rowText, 2, 2, atspi.ActiveDescendantEvent) - expect_speech(descriptionCell, 8, description) + third := cellEvent("/reading/2/state", "unchecked", rowText, 2, 0, atspi.SelectionChangedEvent) + expectSpeech(third, 7, rowText) + descriptionCell := cellEvent("/reading/2/description", description, rowText, 2, 2, atspi.ActiveDescendantEvent) + expectSpeech(descriptionCell, 8, description) button := atspi.NewSnapshot("/preferences/apply", "Apply", "button", "", "") button.BusName = window.BusName focus := atspi.NewEvent(atspi.FocusEvent, button) focus.Window = window - expect_speech(focus, 9, "Apply, button") + expectSpeech(focus, 9, "Apply, button") adapter.events <- up // A table selection after leaving the table is noise. // Returning through a cell focus event establishes ownership and speaks // the table name again, without changing the user's row-reading option. first.OriginPath = first.Source.Path - expect_speech(first, 10, "Reading settings, unchecked, Only speak displayed text") - expect_speech(second, 11, "checked, Break speech into chunks between pauses") + expectSpeech(first, 10, "Reading settings, unchecked, Only speak displayed text") + expectSpeech(second, 11, "checked, Break speech into chunks between pauses") cancel() <-completed } diff --git a/internal/app/indentation.go b/internal/app/indentation.go index dcdd92b..03a5c4c 100644 --- a/internal/app/indentation.go +++ b/internal/app/indentation.go @@ -22,7 +22,7 @@ type indentationData struct { } type indentationHistory map[atspi.ObjectID]indentationData -func indentation_data(line string) indentationData { +func newIndentationData(line string) indentationData { var data indentationData for _, value := range line { switch value { @@ -39,11 +39,11 @@ func indentation_data(line string) indentationData { return data } -func (worker *speechWorker) line_text(text string, line *speechLine) string { +func (worker *speechWorker) lineText(text string, line *speechLine) string { if line == nil || worker.reading == nil { return text } - data := indentation_data(line.Raw) + data := newIndentationData(line.Raw) previous, known := worker.indentation[line.Object] if worker.indentation == nil || len(worker.indentation) >= 128 && !known { worker.indentation = make(indentationHistory) @@ -73,7 +73,7 @@ func (worker *speechWorker) line_text(text string, line *speechLine) string { return strings.TrimSuffix(fmt.Sprintf("indentation %d %s, %s", data.columns, word, text), ", ") } -func document_speech_line(line atspi.DocumentLine) *speechLine { +func documentSpeechLine(line atspi.DocumentLine) *speechLine { if len(line.Contents) == 0 { return nil } diff --git a/internal/app/internal_ui.go b/internal/app/internal_ui.go index 9b26604..423f147 100644 --- a/internal/app/internal_ui.go +++ b/internal/app/internal_ui.go @@ -17,8 +17,8 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" "git.stormux.org/storm/cthulhu/internal/braille" "git.stormux.org/storm/cthulhu/internal/emoji" + "git.stormux.org/storm/cthulhu/internal/i18n" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/review" "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) @@ -32,21 +32,23 @@ type accessibleActionSource interface { AccessibleActions(context.Context, atspi.ObjectID) (atspi.ActionSet, error) PerformAccessibleAction(context.Context, atspi.ActionTarget, string) error } + +// internalUIResult carries the submitted controls keyed by page.control. +// They are for submission only and may contain plaintext secrets. type internalUIResult struct { - Controls map[string]commonui.Control // Submission only; may contain secrets. + Controls map[string]commonui.Control Activated string - Values map[string]interaction.Value Cancelled bool Err error } type internalUINotice struct { ctx context.Context - value interaction.Presentation + value commonui.Result } type internalUIRequest struct { localOnly bool ctx context.Context - session *interaction.Session + session *commonui.Session result chan internalUIResult ready chan error } @@ -72,34 +74,49 @@ type internalUI struct { done chan struct{} } -func (ui *internalUI) Open(ctx context.Context, form interaction.Form) (<-chan internalUIResult, error) { - return ui.open_form(ctx, form, false) +// Open runs a Tentacle form under the external protocol limits. Its values +// come back keyed tentaclewire.FormTab + "." + element ID. +func (ui *internalUI) Open(ctx context.Context, form tentaclewire.Form) (<-chan internalUIResult, error) { + return ui.openTentacleForm(ctx, form, false) } -// OpenLocal is core-only. Unknown input backends cannot silently fall back to -// ordinary forms when authorizing remote access or handling its secrets/trust. -func (ui *internalUI) OpenLocal(ctx context.Context, form interaction.Form) (<-chan internalUIResult, error) { - return ui.open_form(ctx, form, true) +// OpenLocal is for Tentacle sessions holding remote grants. Unknown input +// backends cannot silently fall back to ordinary forms while remote access +// or its secrets are involved. +func (ui *internalUI) OpenLocal(ctx context.Context, form tentaclewire.Form) (<-chan internalUIResult, error) { + return ui.openTentacleForm(ctx, form, true) } -func (ui *internalUI) open_form(ctx context.Context, form interaction.Form, localOnly bool) (<-chan internalUIResult, error) { - session, err := interaction.NewSession(form) +func (ui *internalUI) openTentacleForm(ctx context.Context, form tentaclewire.Form, localOnly bool) (<-chan internalUIResult, error) { + session, err := tentaclewire.NewSession(form) if err != nil { return nil, err } - return ui.open_session(ctx, session, localOnly) + return ui.openSession(ctx, session, localOnly) } -// OpenUI is the core-only rich form API. localOnly preserves the same input -// authorization boundary as OpenLocal; rich controls do not extend the wire API. +// OpenUI runs a core form with translated toolkit and form text. localOnly +// gives it the same input authorization boundary as OpenLocal. func (ui *internalUI) OpenUI(ctx context.Context, form commonui.Form, localOnly bool) (<-chan internalUIResult, error) { - session, err := interaction.NewUnifiedSession(form, commonui.Messages{}) + session, err := newCoreSession(form) if err != nil { return nil, err } - return ui.open_session(ctx, session, localOnly) + return ui.openSession(ctx, session, localOnly) } -func (ui *internalUI) open_session(ctx context.Context, session *interaction.Session, localOnly bool) (<-chan internalUIResult, error) { + +func newCoreSession(form commonui.Form) (*commonui.Session, error) { + return commonui.NewSession(form, commonui.Messages{Translate: i18n.T}) +} + +// opening announces the form title with its first focus. +func opening(session *commonui.Session) commonui.Result { + output := session.Presentation() + output.Speech = session.Open() + return output +} + +func (ui *internalUI) openSession(ctx context.Context, session *commonui.Session, localOnly bool) (<-chan internalUIResult, error) { request := internalUIRequest{ctx: ctx, session: session, result: make(chan internalUIResult, 1), ready: make(chan error, 1), localOnly: localOnly} select { case <-ctx.Done(): @@ -130,7 +147,7 @@ func (ui *internalUI) Notice(ctx context.Context, value tentaclewire.Presentatio return } select { - case ui.notices <- internalUINotice{ctx, interaction.Presentation{Speech: value.Speech, Braille: value.Braille, Cursor: -1}}: + case ui.notices <- internalUINotice{ctx, commonui.Result{Speech: value.Speech, Braille: value.Braille, Cursor: -1}}: default: } } @@ -147,7 +164,7 @@ func (ui *internalUI) Handle(event input.CommandEvent) bool { return true } -func (ui *internalUI) present(output interaction.Presentation) { +func (ui *internalUI) present(output commonui.Result) { if ui.gate.Locked() || ui.gate.Suspended() { return } @@ -161,7 +178,7 @@ func (ui *internalUI) present(output interaction.Presentation) { func (ui *internalUI) run(ctx context.Context) { defer close(ui.done) - var session *interaction.Session + var session *commonui.Session var sessionID uint64 var target atspi.ActionTarget var documentList review.DocumentListSnapshot @@ -172,8 +189,8 @@ func (ui *internalUI) run(ctx context.Context) { var requestDone <-chan struct{} finish := func(reply internalUIResult) error { if emojiActive && session != nil { - if values := session.Values(); values != nil { - copyEmoji = values["copy"].Checked + if checked, ok := emoji.CopyChecked(session); ok { + copyEmoji = checked } } emojiActive = false @@ -194,7 +211,7 @@ func (ui *internalUI) run(ctx context.Context) { reply.Err = closeErr } if reply.Cancelled || reply.Err != nil { - reply.Activated, reply.Values, reply.Controls = "", nil, nil + reply.Activated, reply.Controls = "", nil } result <- reply close(result) @@ -247,7 +264,7 @@ func (ui *internalUI) run(ctx context.Context) { continue } session, result, requestDone = request.session, request.result, request.ctx.Done() - ui.present(session.Opening()) + ui.present(opening(session)) request.ready <- nil case event := <-ui.events: if binding, ok := input.LookupDocumentList(event.Command); ok { @@ -274,7 +291,7 @@ func (ui *internalUI) run(ctx context.Context) { ui.browserListMessage(message) continue } - ui.present(session.Opening()) + ui.present(opening(session)) continue } if event.Command == input.EmojiMenu { @@ -287,7 +304,7 @@ func (ui *internalUI) run(ctx context.Context) { cancel() if err != nil || sessionID == 0 || ui.keys.InternalUISession() != sessionID { _ = finish(internalUIResult{Cancelled: true}) - ui.emoji_message("Emoji Menu unavailable") + ui.emojiMessage("Emoji Menu unavailable") continue } session, err = emoji.NewSession(copyEmoji) @@ -296,7 +313,7 @@ func (ui *internalUI) run(ctx context.Context) { continue } emojiActive = true - ui.present(session.Opening()) + ui.present(opening(session)) continue } if event.Command == input.ShowActions { @@ -335,17 +352,13 @@ func (ui *internalUI) run(ctx context.Context) { } continue } - items := make([]interaction.Item, 0, len(actions.Actions)) - for _, action := range actions.Actions { - items = append(items, interaction.Item{ID: action.Name, Label: action.Label}) - } - session, err = interaction.NewSession(interaction.Form{Title: "Actions", Elements: []interaction.Element{{ID: "actions", Label: "Actions", Kind: interaction.List, Items: items}}}) + session, err = newCoreSession(actionsForm(actions.Actions)) if err != nil { _ = finish(internalUIResult{Err: err}) continue } target = actions.Target - ui.present(session.Opening()) + ui.present(opening(session)) continue } if session == nil || event.UISession != sessionID { @@ -355,11 +368,14 @@ func (ui *internalUI) run(ctx context.Context) { _ = finish(internalUIResult{Cancelled: true}) continue } - key := internal_ui_event(event) + key := internalUIKey(event) if emojiActive { - copyEmoji = session.Values()["copy"].Checked + copyEmoji, _ = emoji.CopyChecked(session) } effect := session.Handle(key) + if emojiActive { + emoji.SyncCopy(session) + } if effect.Cancelled { _ = finish(internalUIResult{Cancelled: true}) continue @@ -370,7 +386,7 @@ func (ui *internalUI) run(ctx context.Context) { } if effect.Paste { clipboardCtx, cancel := context.WithTimeout(ctx, time.Second) - text, err := read_internal_clipboard(clipboardCtx) + text, err := readInternalClipboard(clipboardCtx) cancel() if ui.keys.InternalUISession() != sessionID { _ = finish(internalUIResult{Cancelled: true}) @@ -379,7 +395,7 @@ func (ui *internalUI) run(ctx context.Context) { if err == nil { effect = session.Insert(text) } else { - effect.Presentation = interaction.Presentation{Speech: "Clipboard text unavailable", Braille: "Clipboard text unavailable", Cursor: -1} + effect = commonui.Result{Speech: "Clipboard text unavailable", Braille: "Clipboard text unavailable", Cursor: -1} } } if effect.Copy != nil { @@ -394,30 +410,30 @@ func (ui *internalUI) run(ctx context.Context) { if err != nil { message = "Copy failed" } else if strings.EqualFold(key.Text, "x") { - effect = session.Handle(interaction.Event{Key: interaction.Delete}) + effect = session.Handle(commonui.Key{Name: "delete"}) message = "Cut" } - effect.Presentation = session.Presentation() + effect = session.Presentation() effect.Speech = message } - if effect.Activated != "" { - values := session.Values() + if effect.Action != "" { if emojiActive { - if effect.Activated != "select-grid-item" || values["grid"].Selected == "" { + id, label, selected := emoji.Selection(session) + if effect.Action != emoji.SelectAction || !selected { continue } + copyChecked, _ := emoji.CopyChecked(session) closeErr := finish(internalUIResult{}) if closeErr == nil && !ui.gate.Locked() && !ui.gate.Suspended() { - ui.select_emoji(ctx, values["grid"], values["copy"].Checked) + ui.selectEmoji(ctx, id, label, copyChecked) } continue } actionTarget := target selectedList := documentList - controls := session.ControlValues() - closeErr := finish(internalUIResult{Activated: effect.Activated, Values: values, Controls: controls}) + closeErr := finish(internalUIResult{Activated: effect.Action, Controls: session.Values()}) if len(selectedList.Entries) > 0 && closeErr == nil && !ui.gate.Locked() && !ui.gate.Suspended() { - index, err := strconv.Atoi(effect.Activated) + index, err := strconv.Atoi(effect.Action) if err == nil { err = ui.documents.SelectDocumentList(selectedList, index) } @@ -427,7 +443,7 @@ func (ui *internalUI) run(ctx context.Context) { } if actionTarget.Object.Valid() && closeErr == nil { actionCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - err := ui.actions.PerformAccessibleAction(actionCtx, actionTarget, effect.Activated) + err := ui.actions.PerformAccessibleAction(actionCtx, actionTarget, effect.Action) cancel() if err != nil && !ui.gate.Locked() && !ui.gate.Suspended() { ui.speech.Enqueue(speechRequest{Text: "Action unavailable", Role: "system", Cause: "internal-ui"}) @@ -444,50 +460,53 @@ func (ui *internalUI) run(ctx context.Context) { continue } if effect.Speech != "" || effect.Braille != "" { - ui.present(effect.Presentation) + ui.present(effect) } } } } -func internal_ui_event(event input.CommandEvent) interaction.Event { - key := interaction.Text - switch event.Chord.Symbol { - case 0xff52, 0xff97: - key = interaction.Up - case 0xff54, 0xff99: - key = interaction.Down - case 0xff51, 0xff96: - key = interaction.Left - case 0xff53, 0xff98: - key = interaction.Right - case 0xff50, 0xff95: - key = interaction.Home - case 0xff57, 0xff9c: - key = interaction.End - case 0xff55, 0xff9a: - key = interaction.PageUp - case 0xff56, 0xff9b: - key = interaction.PageDown - case 0xff09, 0xfe20: - key = interaction.Tab - case 0xff0d, 0xff8d: - key = interaction.Enter - case 0xff1b: - key = interaction.Escape - case 0xff08: - key = interaction.Backspace - case 0xffff, 0xff9f: - key = interaction.Delete - } +// internalUIKeyNames maps keysyms, including keypad forms, to toolkit keys. +var internalUIKeyNames = map[uint32]string{ + 0xff52: "up", 0xff97: "up", + 0xff54: "down", 0xff99: "down", + 0xff51: "left", 0xff96: "left", + 0xff53: "right", 0xff98: "right", + 0xff50: "home", 0xff95: "home", + 0xff57: "end", 0xff9c: "end", + 0xff55: "pageup", 0xff9a: "pageup", + 0xff56: "pagedown", 0xff9b: "pagedown", + 0xff09: "tab", 0xfe20: "tab", + 0xff0d: "enter", 0xff8d: "enter", + 0xff1b: "escape", + 0xff08: "backspace", + 0xffff: "delete", 0xff9f: "delete", +} + +func internalUIKey(event input.CommandEvent) commonui.Key { text := event.Text if event.Chord.CthulhuModifier { text = "" } - return interaction.Event{Key: key, Text: text, Shift: event.Chord.Modifiers&1 != 0, Control: event.Chord.Modifiers&4 != 0, Alt: event.Chord.Modifiers&(8|64) != 0} + name := internalUIKeyNames[event.Chord.Symbol] + if name == "" && text == " " { + name = "space" + } + return commonui.Key{Name: name, Text: text, Shift: event.Chord.Modifiers&1 != 0, Ctrl: event.Chord.Modifiers&4 != 0, Alt: event.Chord.Modifiers&(8|64) != 0} } -func read_internal_clipboard(ctx context.Context) (string, error) { +// actionsForm lists the accessible actions of the object of interest. +func actionsForm(actions []atspi.AccessibleAction) commonui.Form { + choices := make([]commonui.Choice, 0, len(actions)) + for _, action := range actions { + choices = append(choices, commonui.Choice{ID: action.Name, Label: action.Label, Literal: true}) + } + return commonui.Form{Type: commonui.FlatForm, Title: "Actions", Detailed: true, Tabs: []commonui.Tab{{ID: "actions", Label: "Actions", Controls: []commonui.Control{ + {ID: "actions", Label: "Actions", Kind: commonui.List, Choices: choices, SelectAction: true}, + }}}} +} + +func readInternalClipboard(ctx context.Context) (string, error) { command := exec.CommandContext(ctx, "xclip", "-selection", "clipboard", "-out") output, err := command.StdoutPipe() if err != nil { diff --git a/internal/app/internal_ui_native_test.go b/internal/app/internal_ui_native_test.go index 54cf77d..be5703f 100644 --- a/internal/app/internal_ui_native_test.go +++ b/internal/app/internal_ui_native_test.go @@ -15,9 +15,9 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/platform/xorg" "git.stormux.org/storm/cthulhu/internal/review" + "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) func TestNativeInternalUIActionsAndEntry(t *testing.T) { @@ -122,7 +122,7 @@ func TestNativeInternalUIActionsAndEntry(t *testing.T) { if err != nil { t.Fatal(err) } - result, err := ui.Open(ctx, interaction.Form{Title: "Example", Elements: []interaction.Element{{ID: "code", Label: "Code", Kind: interaction.Entry}}}) + result, err := ui.Open(ctx, tentaclewire.Form{Title: "Example", Elements: []tentaclewire.Element{{ID: "code", Label: "Code", Kind: tentaclewire.Entry}}}) if err != nil { t.Fatal(err) } @@ -144,14 +144,14 @@ copied: t.Fatal("entry copy did not complete") } } - clipboardText, err := read_internal_clipboard(ctx) + clipboardText, err := readInternalClipboard(ctx) if err != nil || clipboardText != "aB!" { t.Fatalf("copied text = %q, %v", clipboardText, err) } key("BackSpace", "ctrl+v", "d", "Return") select { case submitted := <-result: - if submitted.Err != nil || submitted.Values["code"].Text != "aB!d" { + if submitted.Err != nil || tentaclewire.SubmissionValues(submitted.Controls)["code"].Text != "aB!d" { t.Fatalf("entry result=%+v", submitted) } case <-ctx.Done(): @@ -167,9 +167,9 @@ copied: } // The same real X11 capture must protect a secret entry. The existing // clipboard remains available for explicit paste, but copy/cut cannot replace it. - result, err = ui.Open(ctx, interaction.Form{Title: "Secret fixture", Elements: []interaction.Element{ - {ID: "key", Label: "Channel key", Kind: interaction.Entry, Secret: true}, - {ID: "submit", Label: "Connect", Kind: interaction.Button}, + result, err = ui.Open(ctx, tentaclewire.Form{Title: "Secret fixture", Elements: []tentaclewire.Element{ + {ID: "key", Label: "Channel key", Kind: tentaclewire.Entry, Secret: true}, + {ID: "submit", Label: "Connect", Kind: tentaclewire.Button}, }}) if err != nil { t.Fatal(err) @@ -188,13 +188,13 @@ secretOpened: key("s", "e", "c", "r", "e", "t", "Home", "Right", "Delete", "BackSpace", "ctrl+a", "ctrl+c", "ctrl+x", "ctrl+v", "Tab", "shift+Tab", "Return") select { case submitted := <-result: - if submitted.Err != nil || submitted.Cancelled || submitted.Values["key"].Text != "aB!" { + if submitted.Err != nil || submitted.Cancelled || tentaclewire.SubmissionValues(submitted.Controls)["key"].Text != "aB!" { t.Fatal("secret submission failed") } case <-ctx.Done(): t.Fatal("secret form did not submit") } - if clipboard, err := read_internal_clipboard(ctx); err != nil || clipboard != "aB!" { + if clipboard, err := readInternalClipboard(ctx); err != nil || clipboard != "aB!" { t.Fatal("secret copy/cut changed the clipboard") } allowedSecretSpeech := map[string]bool{ @@ -249,7 +249,7 @@ secretOpened: if text != "q🐐" { t.Fatalf("emoji insertion: %q", text) } - if clipboard, err := read_internal_clipboard(ctx); err != nil || clipboard != "aB!" { + if clipboard, err := readInternalClipboard(ctx); err != nil || clipboard != "aB!" { t.Fatalf("clipboard changed with copying off: %q %v", clipboard, err) } // The next invocation remembers copying off and replaces a selection with a @@ -262,7 +262,7 @@ secretOpened: if text != "🧑‍🚀" { t.Fatalf("emoji selection replacement: %q", text) } - if clipboard, err := read_internal_clipboard(ctx); err != nil || clipboard != "aB!" { + if clipboard, err := readInternalClipboard(ctx); err != nil || clipboard != "aB!" { t.Fatalf("clipboard choice not remembered: %q %v", clipboard, err) } // A cancelled picker has no application or clipboard side effects. diff --git a/internal/app/internal_ui_secret_test.go b/internal/app/internal_ui_secret_test.go index 8829818..ded9d5c 100644 --- a/internal/app/internal_ui_secret_test.go +++ b/internal/app/internal_ui_secret_test.go @@ -12,7 +12,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/braille" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" + "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) type secretTestKeys struct { @@ -42,8 +42,8 @@ func TestInternalUISecretOutputAndLifetime(t *testing.T) { defer func() { cancel(); <-ui.done }() formCtx, closeForm := context.WithCancel(ctx) defer closeForm() - result, err := ui.Open(formCtx, interaction.Form{Title: "Connection", Elements: []interaction.Element{ - {ID: "key", Label: "Channel key", Kind: interaction.Entry, Secret: true}, + result, err := ui.Open(formCtx, tentaclewire.Form{Title: "Connection", Elements: []tentaclewire.Element{ + {ID: "key", Label: "Channel key", Kind: tentaclewire.Entry, Secret: true}, }}) if err != nil { t.Fatal(err) @@ -76,10 +76,10 @@ func TestInternalUISecretOutputAndLifetime(t *testing.T) { select { case got := <-result: if ending == "submit" { - if got.Err != nil || got.Cancelled || got.Activated != "key" || got.Values["key"].Text != "fixture猫" { + if got.Err != nil || got.Cancelled || got.Activated != "key" || tentaclewire.SubmissionValues(got.Controls)["key"].Text != "fixture猫" { t.Fatal("secret not delivered on successful submission") } - } else if got.Values != nil || got.Controls != nil || got.Activated != "" || !got.Cancelled && got.Err == nil { + } else if got.Controls != nil || got.Activated != "" || !got.Cancelled && got.Err == nil { t.Fatal("failed or cancelled form delivered secret values") } case <-ctx.Done(): diff --git a/internal/app/internal_ui_test.go b/internal/app/internal_ui_test.go index f85d81f..1cb2182 100644 --- a/internal/app/internal_ui_test.go +++ b/internal/app/internal_ui_test.go @@ -14,8 +14,8 @@ import ( "git.stormux.org/storm/cthulhu/internal/braille" "git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/review" + "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) type uiTestKeys struct{ session atomic.Uint64 } @@ -89,7 +89,7 @@ func TestInternalUIActionsAndFormUseSameHost(t *testing.T) { case <-ctx.Done(): t.Fatal("selection was not announced") } - result, err := ui.Open(ctx, interaction.Form{Title: "Example", Elements: []interaction.Element{{ID: "entry", Label: "Code", Kind: interaction.Entry}}}) + result, err := ui.Open(ctx, tentaclewire.Form{Title: "Example", Elements: []tentaclewire.Element{{ID: "entry", Label: "Code", Kind: tentaclewire.Entry}}}) if err != nil { t.Fatal(err) } @@ -103,7 +103,7 @@ func TestInternalUIActionsAndFormUseSameHost(t *testing.T) { ui.Handle(input.CommandEvent{Command: input.InternalUIKey, UISession: 1, Chord: input.CommandChord{Symbol: 0xff0d}}) select { case submitted := <-result: - if submitted.Activated != "entry" || submitted.Values["entry"].Text != "é" { + if submitted.Activated != "entry" || tentaclewire.SubmissionValues(submitted.Controls)["entry"].Text != "é" { t.Fatalf("form=%+v", submitted) } case <-ctx.Done(): diff --git a/internal/app/laptop_layout_test.go b/internal/app/laptop_layout_test.go index 3cd17c0..2930a89 100644 --- a/internal/app/laptop_layout_test.go +++ b/internal/app/laptop_layout_test.go @@ -55,7 +55,7 @@ func TestLaptopLayoutSessionAndExplicitPreferences(t *testing.T) { } } checkLaptop(worker.settings) - worker.cycle_progress_output() + worker.cycleProgressOutput() if worker.globalSettings.KeyboardLayout != global.KeyboardLayout || !reflect.DeepEqual(worker.globalSettings.CthulhuModifierKeys, global.CthulhuModifierKeys) { t.Fatal("progress shortcut cached the startup keyboard in global settings") } @@ -81,7 +81,7 @@ func TestLaptopLayoutSessionAndExplicitPreferences(t *testing.T) { if response := worker.applyNext(t.Context(), next, false, false); !response.Accepted { t.Fatal(response.Message) } - worker.cycle_progress_output() + worker.cycleProgressOutput() cached := worker.appSettings[worker.activeApp] if cached.KeyboardLayout != app.KeyboardLayout || !reflect.DeepEqual(cached.CthulhuModifierKeys, app.CthulhuModifierKeys) { t.Fatal("session changes cached the startup keyboard in application settings") diff --git a/internal/app/live_settings.go b/internal/app/live_settings.go index 6b3e5de..d748774 100644 --- a/internal/app/live_settings.go +++ b/internal/app/live_settings.go @@ -27,9 +27,9 @@ type liveSettings struct { func (live *liveSettings) Store(settings config.Settings) { live.current.Store(&settings) - live.notify_clipboard() + live.notifyClipboard() } -func (live *liveSettings) notify_clipboard() { +func (live *liveSettings) notifyClipboard() { select { case live.clipboardChanges <- struct{}{}: default: diff --git a/internal/app/ocr_activate.go b/internal/app/ocr_activate.go index d43e224..51b7575 100644 --- a/internal/app/ocr_activate.go +++ b/internal/app/ocr_activate.go @@ -44,19 +44,19 @@ func (helper ocrDialogConfirmer) Confirm(ctx context.Context, word string) (bool return output.String() == "yes\n", nil } -func (session *ocrSession) activate_locked() { +func (session *ocrSession) activateLocked() { if session.cursor == nil || session.refreshing || session.refreshFailed || session.activating || session.clicker == nil || session.activateRequests == nil || - !session.current_locked(session.job) || session.job.kind == ocr.ClipboardSource { - session.status_locked("OCR activation unavailable; refresh the screen result") + !session.currentLocked(session.job) || session.job.kind == ocr.ClipboardSource { + session.statusLocked("OCR activation unavailable; refresh the screen result") return } word, ok := session.cursor.CurrentWord() if !ok { - session.status_locked("Move to a recognized word to activate it") + session.statusLocked("Move to a recognized word to activate it") return } if _, ok = session.pixels.Transform.ScreenRectangle(word.Bounds); !ok { - session.status_locked("OCR word has no screen position") + session.statusLocked("OCR word has no screen position") return } if session.autoTimer != nil { @@ -70,15 +70,15 @@ func (session *ocrSession) activate_locked() { session.activateRequests <- ocrActivateRequest{job: job, word: word, capture: session.pixels} } -func (session *ocrSession) activation_current(request ocrActivateRequest) bool { +func (session *ocrSession) activationCurrent(request ocrActivateRequest) bool { session.mu.Lock() defer session.mu.Unlock() - return session.activating && !session.activationInterrupted && session.current_locked(request.job) + return session.activating && !session.activationInterrupted && session.currentLocked(request.job) } func (session *ocrSession) activate(request ocrActivateRequest) { - if !session.activation_current(request) { - session.finish_activation(request, true, "OCR source changed") + if !session.activationCurrent(request) { + session.finishActivation(request, true, "OCR source changed") return } ctx, cancel := context.WithTimeout(request.job.ctx, 35*time.Second) @@ -87,7 +87,7 @@ func (session *ocrSession) activate(request ocrActivateRequest) { session.mu.Lock() current := session.activating && session.generation == request.job.generation && session.cancel != nil if current { - session.retire_locked() + session.retireLocked() } session.mu.Unlock() if current && !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) { @@ -97,59 +97,59 @@ func (session *ocrSession) activate(request ocrActivateRequest) { } } if current { - session.release_input() + session.releaseInput() } return } if session.settings().OCR.ConfirmClick { if session.confirmer == nil { - session.finish_activation(request, false, "OCR confirmation unavailable") + session.finishActivation(request, false, "OCR confirmation unavailable") return } confirmed, err := session.confirmer.Confirm(ctx, request.word.Text) - session.wait_activation_source(ctx, request) + session.waitActivationSource(ctx, request) if err != nil || !confirmed { - session.finish_activation(request, false, "OCR activation cancelled") + session.finishActivation(request, false, "OCR activation cancelled") return } } - if !session.activation_current(request) { - session.finish_activation(request, true, "OCR source changed") + if !session.activationCurrent(request) { + session.finishActivation(request, true, "OCR source changed") return } - if err := session.validate_activation(ctx, request); err != nil { - session.finish_activation(request, true, "OCR source changed; refresh before activation") + if err := session.validateActivation(ctx, request); err != nil { + session.finishActivation(request, true, "OCR source changed; refresh before activation") return } rectangle, ok := request.capture.Transform.ScreenRectangle(request.word.Bounds) if !ok { - session.finish_activation(request, true, "OCR word has no screen position") + session.finishActivation(request, true, "OCR word has no screen position") return } point := image.Pt(rectangle.Min.X+(rectangle.Dx()-1)/2, rectangle.Min.Y+(rectangle.Dy()-1)/2) session.mu.Lock() - if !session.activating || session.activationInterrupted || !session.current_locked(request.job) { + if !session.activating || session.activationInterrupted || !session.currentLocked(request.job) { session.mu.Unlock() - session.finish_activation(request, true, "OCR source changed") + session.finishActivation(request, true, "OCR source changed") return } - session.retire_locked() + session.retireLocked() session.mu.Unlock() clickCtx, clickCancel := context.WithTimeout(context.Background(), time.Second) defer clickCancel() if err := session.clicker.ClickOCR(clickCtx, request.job.foreground.Client.Window, request.capture.RootBounds, point); err != nil { session.mu.Lock() - session.status_locked("OCR click unavailable") + session.statusLocked("OCR click unavailable") session.mu.Unlock() } } -func (session *ocrSession) wait_activation_source(ctx context.Context, request ocrActivateRequest) { +func (session *ocrSession) waitActivationSource(ctx context.Context, request ocrActivateRequest) { deadline := time.NewTimer(time.Second) defer deadline.Stop() ticker := time.NewTicker(20 * time.Millisecond) defer ticker.Stop() - for !session.activation_current(request) { + for !session.activationCurrent(request) { select { case <-ctx.Done(): return @@ -160,15 +160,15 @@ func (session *ocrSession) wait_activation_source(ctx context.Context, request o } } -func (session *ocrSession) finish_activation(request ocrActivateRequest, stale bool, message string) { +func (session *ocrSession) finishActivation(request ocrActivateRequest, stale bool, message string) { session.mu.Lock() if !session.activating || session.generation != request.job.generation || request.job.ctx.Err() != nil { session.mu.Unlock() return } - if session.activationInterrupted || !session.current_locked(request.job) { - session.retire_locked() - session.status_locked("OCR source changed") + if session.activationInterrupted || !session.currentLocked(request.job) { + session.retireLocked() + session.statusLocked("OCR source changed") session.mu.Unlock() return } @@ -180,25 +180,25 @@ func (session *ocrSession) finish_activation(request ocrActivateRequest, stale b cancel() session.mu.Lock() defer session.mu.Unlock() - if !session.activating || session.activationInterrupted || !session.current_locked(request.job) { - session.retire_locked() + if !session.activating || session.activationInterrupted || !session.currentLocked(request.job) { + session.retireLocked() return } if err != nil { - session.retire_locked() - session.status_locked("OCR review unavailable") + session.retireLocked() + session.statusLocked("OCR review unavailable") return } session.activating = false if stale { session.refreshFailed = true } else { - session.schedule_refresh_locked() + session.scheduleRefreshLocked() } - session.status_locked(message) + session.statusLocked(message) } -func (session *ocrSession) validate_activation(ctx context.Context, request ocrActivateRequest) error { +func (session *ocrSession) validateActivation(ctx context.Context, request ocrActivateRequest) error { if request.capture.Pixels == nil { return ocr.ErrSourceChanged } diff --git a/internal/app/ocr_commands.go b/internal/app/ocr_commands.go index d554cf6..9e45a2e 100644 --- a/internal/app/ocr_commands.go +++ b/internal/app/ocr_commands.go @@ -11,7 +11,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/ocr" ) -func ocr_cursor_command(command input.Command) (ocr.Unit, int) { +func ocrCursorCommand(command input.Command) (ocr.Unit, int) { switch command { case input.OCRPreviousCharacter, input.ReviewPreviousCharacter: return ocr.Character, -1 @@ -54,8 +54,8 @@ func (session *ocrSession) Handle(event input.CommandEvent) bool { } session.mu.Lock() defer session.mu.Unlock() - if kind, ok := ocr_source_command(event.Command); ok { - session.request_locked(kind, event.Timestamp) + if kind, ok := ocrSourceCommand(event.Command); ok { + session.requestLocked(kind, event.Timestamp) return true } if session.activating { @@ -64,24 +64,24 @@ func (session *ocrSession) Handle(event input.CommandEvent) bool { if session.cancel == nil { return strings.HasPrefix(string(event.Command), "ocr-") } - if !session.current_locked(session.job) { - session.retire_locked() + if !session.currentLocked(session.job) { + session.retireLocked() return strings.HasPrefix(string(event.Command), "ocr-") } if event.Timestamp != 0 && (session.cutoff == 0 || int32(event.Timestamp-session.cutoff) > 0) { session.cutoff = event.Timestamp } if session.cursor != nil { - from, to := session.selection_locked() + from, to := session.selectionLocked() session.logger.Debug("OCR review command", "command", event.Command, "generation", session.generation, "focus_path", session.focus.Path, "source_path", session.source.Object.Path, "offset", session.cursor.Offset(), "selection_start", from, "selection_end", to) } switch event.Command { case input.OCRDismiss, input.OCRDismissAndPass: - session.retire_locked() + session.retireLocked() if event.Command == input.OCRDismiss { - session.status_locked("OCR dismissed") + session.statusLocked("OCR dismissed") } return true case input.OCRSelectAll: @@ -91,7 +91,7 @@ func (session *ocrSession) Handle(event input.CommandEvent) bool { session.selectionAnchor = 0 position, _ := session.cursor.Set(session.cursor.Length()) session.speech.Enqueue(speechRequest{Text: "OCR text selected", Role: "system", Cause: "ocr-selection", context: session.job.ctx}) - frame := session.frame_locked(position) + frame := session.frameLocked(position) if session.display != nil { session.display.EnqueueFrame(frame) } @@ -100,24 +100,24 @@ func (session *ocrSession) Handle(event input.CommandEvent) bool { "braille_text", frame.Text, "braille_cursor", frame.Cursor) return true case input.OCRCopySelection: - session.copy_selection_locked() + session.copySelectionLocked() return true case input.OCRActivate: - session.activate_locked() + session.activateLocked() return true case input.OCRRefresh: - session.refresh_locked(false) + session.refreshLocked(false) return true case input.ReadAll: - session.read_all_locked(event.Timestamp) + session.readAllLocked(event.Timestamp) return true } - if unit, step := ocr_cursor_command(event.Command); unit != 0 { + if unit, step := ocrCursorCommand(event.Command); unit != 0 { if session.cursor == nil { return true } moves := step != 0 || unit >= ocr.LineStart - oldStart, oldEnd := session.selection_locked() + oldStart, oldEnd := session.selectionLocked() if moves { previous := session.cursor.Offset() if event.Chord.Modifiers&1 != 0 { @@ -130,20 +130,20 @@ func (session *ocrSession) Handle(event input.CommandEvent) bool { } position := session.cursor.Move(unit, step) if moves && event.Chord.Modifiers&1 != 0 { - if message := session.selection_change_locked(oldStart, oldEnd); message != "" { - session.present_request_locked(position, unit, speechRequest{Text: message, Role: "text", Cause: "ocr-selection", context: session.job.ctx}) + if message := session.selectionChangeLocked(oldStart, oldEnd); message != "" { + session.presentRequestLocked(position, unit, speechRequest{Text: message, Role: "text", Cause: "ocr-selection", context: session.job.ctx}) return true } } if step != 0 && !position.Moved { - session.present_request_locked(position, unit, speechRequest{Text: "OCR text boundary", Role: "system", Cause: "ocr-status", context: session.job.ctx}) + session.presentRequestLocked(position, unit, speechRequest{Text: "OCR text boundary", Role: "system", Cause: "ocr-status", context: session.job.ctx}) return true } - session.present_spelling_locked(position, unit, flat_review_speech(event.Command)) + session.presentSpellingLocked(position, unit, flatReviewSpeech(event.Command)) return true } // Ordinary reader commands restore their existing source/routing first. - session.retire_locked() + session.retireLocked() return false } @@ -189,7 +189,7 @@ func (session *ocrSession) Input(event input.Event) { case "Control_L", "Control_R": chord.Modifiers |= 4 case "Alt_L", "Alt_R", "Meta_L", "Meta_R", "Super_L", "Super_R": - session.retire_locked() + session.retireLocked() return } for _, modifier := range settings.CthulhuModifierKeys { @@ -207,12 +207,12 @@ func (session *ocrSession) Input(event input.Event) { } } if err != nil { - session.retire_locked() + session.retireLocked() return } bindings, err := input.ResolveCommandBindings(input.KeyboardLayout(settings.KeyboardLayout), false, settings.KeyBindings) if err != nil { - session.retire_locked() + session.retireLocked() return } if session.cursor == nil { @@ -222,6 +222,6 @@ func (session *ocrSession) Input(event input.Event) { } if bindings[chord] == "" { session.logger.Debug("OCR dismissed by unclaimed input", "chord", input.FormatCommandChord(chord)) - session.retire_locked() + session.retireLocked() } } diff --git a/internal/app/ocr_copy.go b/internal/app/ocr_copy.go index 321d30d..c24e7a4 100644 --- a/internal/app/ocr_copy.go +++ b/internal/app/ocr_copy.go @@ -38,15 +38,15 @@ type ocrCopyRequest struct { automatic bool } -func (session *ocrSession) copy_selection_locked() { +func (session *ocrSession) copySelectionLocked() { if session.cursor == nil || session.selectionAnchor < 0 || session.selectionAnchor == session.cursor.Offset() { - session.status_locked("No OCR text selected") + session.statusLocked("No OCR text selected") return } start, end := min(session.selectionAnchor, session.cursor.Offset()), max(session.selectionAnchor, session.cursor.Offset()) value, ok := session.cursor.Slice(start, end) if !ok || value == "" || session.copier == nil || session.copyRequests == nil { - session.status_locked("OCR copy unavailable") + session.statusLocked("OCR copy unavailable") return } request := ocrCopyRequest{ctx: session.job.ctx, generation: session.generation, text: value} @@ -69,7 +69,7 @@ func (session *ocrSession) copy(request ocrCopyRequest) { err := session.copier.Copy(request.ctx, request.text) session.mu.Lock() defer session.mu.Unlock() - if request.ctx.Err() != nil || request.generation != session.generation || !session.current_locked(session.job) { + if request.ctx.Err() != nil || request.generation != session.generation || !session.currentLocked(session.job) { return } // A successful optional copy must not cancel initial Say All or replace its @@ -82,5 +82,5 @@ func (session *ocrSession) copy(request ocrCopyRequest) { message = "OCR copy unavailable" session.logger.Debug("OCR copy failed", "error", err) } - session.status_locked(message) + session.statusLocked(message) } diff --git a/internal/app/ocr_native_test.go b/internal/app/ocr_native_test.go index f2cae35..21b81f0 100644 --- a/internal/app/ocr_native_test.go +++ b/internal/app/ocr_native_test.go @@ -55,7 +55,7 @@ func TestNativeOCRSession(t *testing.T) { gate := newFocusGate(keys) live := &liveSettings{} live.Store(settings) - session := new_ocr_session(logger, keys, adapter, objectReview, output, nil, output, gate, live) + session := newOcrSession(logger, keys, adapter, objectReview, output, nil, output, gate, live) session.capture = ocr.NewCapturer(executable) gate.ocr = session for _, service := range []interface { @@ -163,7 +163,7 @@ func TestNativeOCRSession(t *testing.T) { } // Observe actual focused-widget speech, not merely a valid frame identity. for { - got := ocr_test_receive(t, output.speech) + got := ocrTestReceive(t, output.speech) if strings.Contains(got.Text, "Painted OCR target") { break } diff --git a/internal/app/ocr_read_all.go b/internal/app/ocr_read_all.go index 676c433..44fe6bd 100644 --- a/internal/app/ocr_read_all.go +++ b/internal/app/ocr_read_all.go @@ -4,16 +4,16 @@ package app -// read_all_locked starts ordinary paced speech from the current virtual +// readAllLocked starts ordinary paced speech from the current virtual // offset. Progress moves only OCR's cursor and braille; native focus is intact. -func (session *ocrSession) read_all_locked(timestamp uint32) { +func (session *ocrSession) readAllLocked(timestamp uint32) { if session.cursor == nil || session.readAll == nil { - session.status_locked("OCR Say All is unavailable") + session.statusLocked("OCR Say All is unavailable") return } lines := session.cursor.LinesFrom() if len(lines) == 0 { - session.status_locked("OCR text boundary") + session.statusLocked("OCR text boundary") return } job := session.job @@ -27,14 +27,14 @@ func (session *ocrSession) read_all_locked(timestamp uint32) { parts = append(parts, readAllPart{Text: line.Text, Began: func() { session.mu.Lock() defer session.mu.Unlock() - if ctx.Err() != nil || !session.current_locked(job) || session.cursor == nil { + if ctx.Err() != nil || !session.currentLocked(job) || session.cursor == nil { return } position, ok := session.cursor.Set(offset) if !ok { return } - frame := session.frame_locked(position) + frame := session.frameLocked(position) if session.display != nil { session.display.EnqueueFrame(frame) } diff --git a/internal/app/ocr_reading_test.go b/internal/app/ocr_reading_test.go index 1e6963c..f276722 100644 --- a/internal/app/ocr_reading_test.go +++ b/internal/app/ocr_reading_test.go @@ -13,7 +13,7 @@ import ( ) func TestOCRAutomaticReadAllOnceWithCopyAndRefresh(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) reader := &ocrTestReadAll{} copier := &ocrTestCopier{copied: make(chan string, 1)} session.readAll, session.copier = reader, copier @@ -22,38 +22,38 @@ func TestOCRAutomaticReadAllOnceWithCopyAndRefresh(t *testing.T) { session.live = &liveSettings{} session.live.Store(settings) session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) // A pending job must keep the initiating preferences. settings.OCR.AutoReadAll, settings.OCR.CopyFirstResult = false, false session.live.Store(settings) engine.results <- ocr.Result{Text: "é one\n猫 two"} - request := ocr_test_receive(t, output.speech) + request := ocrTestReceive(t, output.speech) if request.Cause != "read-all" || len(request.ReadAll) != 2 || request.ReadAll[0].Text != "é one" || reader.timestamp != 100 { t.Fatalf("initial reading: %+v", request) } - frame := ocr_test_receive(t, output.frames) + frame := ocrTestReceive(t, output.frames) if frame.Text != "é one" || frame.Cursor != 0 || frame.Virtual == nil { t.Fatalf("initial braille: %+v", frame) } - if text := ocr_test_receive(t, copier.copied); text != "é one\n猫 two" { + if text := ocrTestReceive(t, copier.copied); text != "é one\n猫 two" { t.Fatal(text) } request.ReadAll[1].Began() - frame = ocr_test_receive(t, output.frames) + frame = ocrTestReceive(t, output.frames) if frame.Text != "猫 two" || frame.Virtual.SourceStart != 6 { t.Fatalf("paced braille: %+v", frame) } session.Handle(input.CommandEvent{Command: input.OCRRefresh, Timestamp: 101}) - ocr_test_receive(t, engine.calls) // Worker has also finished the optional copy. + ocrTestReceive(t, engine.calls) // Worker has also finished the optional copy. if request.context.Err() != context.Canceled { t.Fatal("manual refresh did not cancel old reading") } engine.results <- ocr.Result{Text: "é one\n猫 two"} - if got := ocr_test_receive(t, output.speech); got.Text != "OCR text unchanged" || len(got.ReadAll) != 0 { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR text unchanged" || len(got.ReadAll) != 0 { t.Fatalf("copy interrupted reading or refresh restarted it: %+v", got) } - ocr_test_receive(t, output.frames) // Status, then current review frame. - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.frames) // Status, then current review frame. + ocrTestReceive(t, output.frames) request.ReadAll[0].Began() select { case got := <-output.frames: @@ -65,21 +65,21 @@ func TestOCRAutomaticReadAllOnceWithCopyAndRefresh(t *testing.T) { func TestOCRPeriodicRefreshWaitsForSayAll(t *testing.T) { for _, interrupted := range []bool{false, true} { t.Run(map[bool]string{false: "completed", true: "interrupted"}[interrupted], func(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) session.readAll = &ocrTestReadAll{} settings := session.settings() settings.OCR.AutoReadAll = true session.live = &liveSettings{} session.live.Store(settings) session.Handle(input.CommandEvent{Command: input.OCRWindow}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "first\nsecond"} - request := ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + request := ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) settings.OCR.AutoRefresh = true session.live.Store(settings) session.mu.Lock() - session.refresh_locked(true) + session.refreshLocked(true) if session.refreshing || request.context.Err() != nil { session.mu.Unlock() t.Fatal("periodic refresh truncated Say All") @@ -91,15 +91,15 @@ func TestOCRPeriodicRefreshWaitsForSayAll(t *testing.T) { } else { completeSpeechRequest(request, nil) } - session.refresh_locked(true) + session.refreshLocked(true) if !session.refreshing { session.mu.Unlock() t.Fatal("periodic refresh did not resume after reading") } session.mu.Unlock() - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "changed"} - if got := ocr_test_receive(t, output.speech); got.Text != "changed" || len(got.ReadAll) != 0 { + if got := ocrTestReceive(t, output.speech); got.Text != "changed" || len(got.ReadAll) != 0 { t.Fatalf("automatic refresh restarted Say All: %+v", got) } }) @@ -107,12 +107,12 @@ func TestOCRPeriodicRefreshWaitsForSayAll(t *testing.T) { } func TestOCRShiftSelectionAnnouncesChangedRanges(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) session.Handle(input.CommandEvent{Command: input.OCRWindow}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "é猫abc\nnext"} - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) steps := []struct { command input.Command shift bool @@ -138,12 +138,12 @@ func TestOCRShiftSelectionAnnouncesChangedRanges(t *testing.T) { modifiers = 1 } session.Handle(input.CommandEvent{Command: step.command, Chord: input.CommandChord{Modifiers: modifiers}}) - if got := ocr_test_receive(t, output.speech); got.Text != step.speech { + if got := ocrTestReceive(t, output.speech); got.Text != step.speech { t.Fatalf("%s shift=%v: %q, want %q", step.command, step.shift, got.Text, step.speech) } - frame := ocr_test_receive(t, output.frames) + frame := ocrTestReceive(t, output.frames) session.mu.Lock() - start, end := session.selection_locked() + start, end := session.selectionLocked() offset := session.cursor.Offset() session.mu.Unlock() if offset != step.offset || start != step.start || end != step.end || frame.Virtual == nil { diff --git a/internal/app/ocr_refresh.go b/internal/app/ocr_refresh.go index ab29e2f..61797c9 100644 --- a/internal/app/ocr_refresh.go +++ b/internal/app/ocr_refresh.go @@ -34,11 +34,11 @@ func remapOCROffset(oldText, newText string, offset int) int { return min(offset, len(newRunes)) } -func (session *ocrSession) finish_refresh_locked(job ocrJob, interest review.Interest, capture ocr.Capture, result ocr.Result, err error) { +func (session *ocrSession) finishRefreshLocked(job ocrJob, interest review.Interest, capture ocr.Capture, result ocr.Result, err error) { session.refreshing = false if err != nil { session.refreshFailed = true - session.status_locked("OCR refresh failed; activate after a successful refresh") + session.statusLocked("OCR refresh failed; activate after a successful refresh") return } previous := session.cursor.Text() @@ -53,16 +53,16 @@ func (session *ocrSession) finish_refresh_locked(job ocrJob, interest review.Int session.selectionAnchor = anchor session.refreshFailed = result.Text == "" if result.Text == "" { - session.status_locked("No text recognized") + session.statusLocked("No text recognized") } else if result.Text != previous { - session.status_locked(ocrChangedAnnouncement(previous, result.Text)) + session.statusLocked(ocrChangedAnnouncement(previous, result.Text)) } else if !job.automatic { - session.status_locked("OCR text unchanged") + session.statusLocked("OCR text unchanged") } if session.display != nil { - session.display.EnqueueFrame(session.frame_locked(position)) + session.display.EnqueueFrame(session.frameLocked(position)) } - session.schedule_refresh_locked() + session.scheduleRefreshLocked() } func ocrChangedAnnouncement(previous, current string) string { diff --git a/internal/app/ocr_refresh_activation_test.go b/internal/app/ocr_refresh_activation_test.go index 6299e7e..ee512b9 100644 --- a/internal/app/ocr_refresh_activation_test.go +++ b/internal/app/ocr_refresh_activation_test.go @@ -14,27 +14,27 @@ import ( ) func TestOCRClipboardRefreshKeepsSnapshotAndCursor(t *testing.T) { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) session.Handle(input.CommandEvent{Command: input.OCRClipboard, Timestamp: 100}) - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "one two", Words: []ocr.Word{{Text: "one", Span: ocr.Span{Start: 0, End: 3}}, {Text: "two", Span: ocr.Span{Start: 4, End: 7}}}} - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) session.Handle(input.CommandEvent{Command: input.OCRNextWord, Timestamp: 101}) - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) session.Handle(input.CommandEvent{Command: input.OCRRefresh, Timestamp: 102}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) select { case <-capture.calls: t.Fatal("clipboard refresh fetched a changed clipboard") default: } engine.results <- ocr.Result{Text: "one three", Words: []ocr.Word{{Text: "one", Span: ocr.Span{Start: 0, End: 3}}, {Text: "three", Span: ocr.Span{Start: 4, End: 9}}}} - if got := ocr_test_receive(t, output.speech); got.Text != "one three" { + if got := ocrTestReceive(t, output.speech); got.Text != "one three" { t.Fatal(got) } session.mu.Lock() @@ -57,10 +57,10 @@ func TestOCRRefreshRetainsUnchangedSuffixAcrossInsertion(t *testing.T) { } func TestOCRStaleActivationCannotRetireReplacement(t *testing.T) { - session, keys, _, engine, _ := ocr_test_session(t) + session, keys, _, engine, _ := ocrTestSession(t) defer func() { engine.results <- ocr.Result{}; engine.results <- ocr.Result{} }() session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100}) - ocr_test_receive(t, keys.calls) + ocrTestReceive(t, keys.calls) session.mu.Lock() old := session.job session.mu.Unlock() @@ -77,7 +77,7 @@ func TestOCRStaleActivationCannotRetireReplacement(t *testing.T) { } func TestOCRAutoRefreshWaitsForEachJob(t *testing.T) { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) live := &liveSettings{} settings := config.DefaultSettings() settings.OCR.AutoRefresh = true @@ -85,24 +85,24 @@ func TestOCRAutoRefreshWaitsForEachJob(t *testing.T) { live.Store(settings) session.live = live session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100}) - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "ready"} - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) select { case <-capture.calls: t.Fatal("automatic OCR jobs overlapped") case <-time.After(600 * time.Millisecond): } engine.results <- ocr.Result{Text: "ready"} - ocr_test_receive(t, output.frames) - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, output.frames) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) } type ocrTestClicker struct{ points chan image.Point } @@ -134,7 +134,7 @@ func TestOCRActivationChecksFreshPixelsBeforeClick(t *testing.T) { {"inaccessible-window/changed", input.OCRWindow, true}, } { t.Run(test.name, func(t *testing.T) { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) if test.command == input.OCRWindow { session.focus, session.window = atspi.ObjectID{}, atspi.ObjectID{} session.geometry, session.interest = nil, nil @@ -154,23 +154,23 @@ func TestOCRActivationChecksFreshPixelsBeforeClick(t *testing.T) { Transform: ocr.Transform{ImageContent: image.Rect(0, 0, 100, 50), ScreenBounds: bounds, HasScreenMapping: true}}, ctx.Err() } session.Handle(input.CommandEvent{Command: test.command, Timestamp: 100}) - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "go", Width: 100, Height: 50, Words: []ocr.Word{{Text: "go", Bounds: image.Rect(10, 10, 30, 20), Span: ocr.Span{Start: 0, End: 2}}}} - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) if test.changed { paint = color.RGBA{R: 30, A: 255} } session.Handle(input.CommandEvent{Command: input.OCRActivate, Timestamp: 101}) - if got := ocr_test_receive(t, confirmer.called); got != "go" { + if got := ocrTestReceive(t, confirmer.called); got != "go" { t.Fatal(got) } - ocr_test_receive(t, capture.calls) + ocrTestReceive(t, capture.calls) if test.changed { - if got := ocr_test_receive(t, output.speech); got.Text != "OCR source changed; refresh before activation" { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR source changed; refresh before activation" { t.Fatal(got) } select { diff --git a/internal/app/ocr_selection.go b/internal/app/ocr_selection.go index ce4d709..2bd948c 100644 --- a/internal/app/ocr_selection.go +++ b/internal/app/ocr_selection.go @@ -11,8 +11,8 @@ import ( // Selection is owned by the session's anchor and cursor. Compare ranges in the // current document without retaining text or inventing a native object identity. -func (session *ocrSession) selection_change_locked(oldStart, oldEnd int) string { - start, end := session.selection_locked() +func (session *ocrSession) selectionChangeLocked(oldStart, oldEnd int) string { + start, end := session.selectionLocked() var changes []string fragment := func(from, to int, selected bool) { if from < 0 || to <= from { diff --git a/internal/app/ocr_session.go b/internal/app/ocr_session.go index 112a29e..0d7ae51 100644 --- a/internal/app/ocr_session.go +++ b/internal/app/ocr_session.go @@ -114,7 +114,7 @@ type ocrSession struct { activationInterrupted bool } -func new_ocr_session(logger *slog.Logger, commands commandListener, adapter Adapter, interest *review.Worker, speech speechEnqueuer, readAll ocrReadAllStarter, display brailleFrameEnqueuer, gate *focusGate, live *liveSettings) *ocrSession { +func newOcrSession(logger *slog.Logger, commands commandListener, adapter Adapter, interest *review.Worker, speech speechEnqueuer, readAll ocrReadAllStarter, display brailleFrameEnqueuer, gate *focusGate, live *liveSettings) *ocrSession { executable, _ := os.Executable() session := &ocrSession{logger: logger, interest: interest, speech: gatedSpeech{speech: speech, gate: gate}, readAll: readAll, display: display, gate: gate, live: live, capture: ocr.NewCapturer(executable), engine: ocr.NewEngine(), copier: xclipOCRCopier{}, copyRequests: make(chan ocrCopyRequest, 1), @@ -160,7 +160,7 @@ func (session *ocrSession) signal() { } } -func (session *ocrSession) retire_locked() { +func (session *ocrSession) retireLocked() { if session.autoTimer != nil { session.autoTimer.Stop() session.autoTimer = nil @@ -193,7 +193,7 @@ func (session *ocrSession) Retire() { } session.mu.Lock() defer session.mu.Unlock() - session.retire_locked() + session.retireLocked() } func (session *ocrSession) Secure() { @@ -202,13 +202,13 @@ func (session *ocrSession) Secure() { } session.mu.Lock() defer session.mu.Unlock() - session.retire_locked() + session.retireLocked() session.focus, session.window = atspi.ObjectID{}, atspi.ObjectID{} session.focusForeground = 0 clear(session.held) } -func ocr_source_command(command input.Command) (ocr.SourceKind, bool) { +func ocrSourceCommand(command input.Command) (ocr.SourceKind, bool) { switch command { case input.OCRObject: return ocr.ObjectSource, true @@ -222,8 +222,8 @@ func ocr_source_command(command input.Command) (ocr.SourceKind, bool) { return "", false } -func (session *ocrSession) request_locked(kind ocr.SourceKind, timestamp uint32) { - session.retire_locked() +func (session *ocrSession) requestLocked(kind ocr.SourceKind, timestamp uint32) { + session.retireLocked() session.cutoff = timestamp if session.ctx == nil || session.ctx.Err() != nil { return @@ -232,12 +232,12 @@ func (session *ocrSession) request_locked(kind ocr.SourceKind, timestamp uint32) return } if session.keys == nil || session.foreground == nil { - session.status_locked("OCR source unavailable") + session.statusLocked("OCR source unavailable") return } foreground := session.foreground.Foreground() if !foreground.Client.Known || foreground.Client.Window == 0 { - session.status_locked("OCR source unavailable") + session.statusLocked("OCR source unavailable") return } // An inaccessible client may leave the previous application's AT-SPI focus @@ -246,7 +246,7 @@ func (session *ocrSession) request_locked(kind ocr.SourceKind, timestamp uint32) session.focus, session.window = atspi.ObjectID{}, atspi.ObjectID{} } if kind == ocr.ObjectSource && (session.geometry == nil || session.interest == nil || !session.focus.Valid()) { - session.status_locked("OCR source unavailable") + session.statusLocked("OCR source unavailable") return } session.generation++ @@ -259,8 +259,8 @@ func (session *ocrSession) request_locked(kind ocr.SourceKind, timestamp uint32) session.signal() } -func (session *ocrSession) refresh_locked(automatic bool) { - if session.cancel == nil || session.cursor == nil || session.refreshing || !session.current_locked(session.job) { +func (session *ocrSession) refreshLocked(automatic bool) { + if session.cancel == nil || session.cursor == nil || session.refreshing || !session.currentLocked(session.job) { return } if automatic && (session.job.kind == ocr.ClipboardSource || !session.settings().OCR.AutoRefresh) { @@ -272,7 +272,7 @@ func (session *ocrSession) refresh_locked(automatic bool) { select { case _ = <-session.readAllDone: default: - session.schedule_refresh_locked() + session.scheduleRefreshLocked() return } } @@ -296,7 +296,7 @@ func (session *ocrSession) refresh_locked(automatic bool) { session.signal() } -func (session *ocrSession) schedule_refresh_locked() { +func (session *ocrSession) scheduleRefreshLocked() { if session.autoTimer != nil { session.autoTimer.Stop() session.autoTimer = nil @@ -307,7 +307,7 @@ func (session *ocrSession) schedule_refresh_locked() { } } -func (session *ocrSession) timer_channel() <-chan time.Time { +func (session *ocrSession) timerChannel() <-chan time.Time { session.mu.Lock() defer session.mu.Unlock() if session.autoTimer != nil { @@ -322,14 +322,14 @@ func (session *ocrSession) run() { select { case <-session.ctx.Done(): session.Retire() - session.release_input() + session.releaseInput() return case <-session.wake: session.mu.Lock() job, active, ready := session.job, session.cancel != nil, session.cursor != nil && !session.refreshing session.mu.Unlock() if !active { - session.release_input() + session.releaseInput() continue } if !ready { @@ -339,16 +339,16 @@ func (session *ocrSession) run() { session.copy(request) case request := <-session.activateRequests: session.activate(request) - case <-session.timer_channel(): + case <-session.timerChannel(): session.mu.Lock() session.autoTimer = nil - session.refresh_locked(true) + session.refreshLocked(true) session.mu.Unlock() } } } -func (session *ocrSession) release_input() { +func (session *ocrSession) releaseInput() { if session.keys == nil { return } @@ -369,7 +369,7 @@ func (session *ocrSession) release_input() { } } -func (session *ocrSession) current_locked(job ocrJob) bool { +func (session *ocrSession) currentLocked(job ocrJob) bool { return session.cancel != nil && session.generation == job.generation && job.ctx.Err() == nil && !session.gate.Locked() && !session.gate.Suspended() && session.focus == job.focus && session.foreground.Foreground() == job.foreground @@ -403,7 +403,7 @@ func (session *ocrSession) recognize(job ocrJob) { request.Bounds = geometry.ScreenBounds if err == nil { session.mu.Lock() - if session.current_locked(job) { + if session.currentLocked(job) { session.source = interest } else { err = context.Canceled @@ -442,12 +442,12 @@ func (session *ocrSession) recognize(job ocrJob) { } } session.mu.Lock() - current := session.current_locked(job) + current := session.currentLocked(job) if current { if job.refresh { - session.finish_refresh_locked(job, interest, capture, result, err) + session.finishRefreshLocked(job, interest, capture, result, err) } else if err != nil || result.Text == "" { - session.retire_locked() + session.retireLocked() message := "OCR recognition failed" switch { case errors.Is(err, ocr.ErrUnavailable): @@ -459,20 +459,20 @@ func (session *ocrSession) recognize(job ocrJob) { case errors.Is(err, atspi.ErrOCRGeometry), errors.Is(err, atspi.ErrObjectNotFound), errors.Is(err, review.ErrNoCurrent), errors.Is(err, ocr.ErrSource), errors.Is(err, ocr.ErrCapture): message = "OCR source unavailable" } - session.status_locked(message) + session.statusLocked(message) } else { session.source, session.pixels = interest, capture session.cursor = ocr.NewCursor(result) session.selectionAnchor = -1 if job.autoReadAll && session.readAll != nil { if session.display != nil { - session.display.EnqueueFrame(session.frame_locked(session.cursor.Current(ocr.LineUnit))) + session.display.EnqueueFrame(session.frameLocked(session.cursor.Current(ocr.LineUnit))) } - session.read_all_locked(job.timestamp) + session.readAllLocked(job.timestamp) } else { - session.present_locked(session.cursor.Current(ocr.LineUnit), ocr.LineUnit) + session.presentLocked(session.cursor.Current(ocr.LineUnit), ocr.LineUnit) } - session.schedule_refresh_locked() + session.scheduleRefreshLocked() if job.copyFirstResult && session.copier != nil && session.copyRequests != nil { select { case session.copyRequests <- ocrCopyRequest{ctx: job.ctx, generation: job.generation, text: result.Text, automatic: true}: @@ -481,15 +481,15 @@ func (session *ocrSession) recognize(job ocrJob) { } } } else if session.generation == job.generation { - session.retire_locked() + session.retireLocked() } session.mu.Unlock() if !job.refresh && (!current || err != nil || result.Text == "") { - session.release_input() + session.releaseInput() } } -func (session *ocrSession) status_locked(message string) { +func (session *ocrSession) statusLocked(message string) { if session.gate.Locked() || session.gate.Suspended() { return } @@ -500,43 +500,43 @@ func (session *ocrSession) status_locked(message string) { session.logger.Debug("OCR status", "text", message) } -func (session *ocrSession) present_locked(position ocr.Position, unit ocr.Unit) { - session.present_spelling_locked(position, unit, review.FlatSpeak) +func (session *ocrSession) presentLocked(position ocr.Position, unit ocr.Unit) { + session.presentSpellingLocked(position, unit, review.FlatSpeak) } -func (session *ocrSession) present_spelling_locked(position ocr.Position, unit ocr.Unit, style review.FlatSpeech) { +func (session *ocrSession) presentSpellingLocked(position ocr.Position, unit ocr.Unit, style review.FlatSpeech) { text := presentationOCRText(position.Text, unit) request := speechRequest{Text: text, Role: "text", Cause: "ocr-cursor", context: session.job.ctx, Character: unit == ocr.Character || unit == ocr.LineStart || unit == ocr.LineEnd} - set_review_spelling(&request, position.Text, style) - session.present_request_locked(position, unit, request) + setReviewSpelling(&request, position.Text, style) + session.presentRequestLocked(position, unit, request) } -func (session *ocrSession) present_request_locked(position ocr.Position, unit ocr.Unit, request speechRequest) { +func (session *ocrSession) presentRequestLocked(position ocr.Position, unit ocr.Unit, request speechRequest) { session.speech.Enqueue(request) - frame := session.frame_locked(position) + frame := session.frameLocked(position) if session.display != nil { session.display.EnqueueFrame(frame) } - from, to := session.selection_locked() + from, to := session.selectionLocked() session.logger.Debug("OCR cursor presentation", "generation", session.generation, "source_path", session.source.Object.Path, "focus_path", session.focus.Path, "unit", unit, "offset", position.Offset, "line_start", position.LineStart, "selection_start", from, "selection_end", to, "speech_text", request.Text, "spelling", request.Spelling, "braille_text", frame.Text, "braille_cursor", frame.Cursor) } -func (session *ocrSession) selection_locked() (int, int) { +func (session *ocrSession) selectionLocked() (int, int) { if session.cursor == nil || session.selectionAnchor < 0 { return -1, -1 } return min(session.selectionAnchor, session.cursor.Offset()), max(session.selectionAnchor, session.cursor.Offset()) } -func (session *ocrSession) frame_locked(position ocr.Position) braille.Frame { - frame := ocr_braille_frame(position) +func (session *ocrSession) frameLocked(position ocr.Position) braille.Frame { + frame := ocrBrailleFrame(position) start := position.LineStart + position.Cursor - frame.Cursor length := utf8.RuneCountInString(frame.Text) frame.Virtual = &braille.VirtualRoute{Generation: session.generation, Start: 0, End: length, SourceStart: start} - if from, to := session.selection_locked(); from >= 0 && from != to { + if from, to := session.selectionLocked(); from >= 0 && from != to { indicator := byte(session.settings().Braille.SelectionIndicator) if indicator != 0 { frame.Dots = make([]byte, length) @@ -550,7 +550,7 @@ func (session *ocrSession) frame_locked(position ocr.Position) braille.Frame { // Keep long Unicode lines inside the helper frame limit without losing the // cursor. This is a presentation window; the document keeps the full line. -func ocr_braille_frame(position ocr.Position) braille.Frame { +func ocrBrailleFrame(position ocr.Position) braille.Frame { if len(position.Line) <= 10000 { return braille.Frame{Text: position.Line, Cursor: position.Cursor} } @@ -606,7 +606,7 @@ func (session *ocrSession) Observe(event atspi.Event) bool { return false } if session.cancel != nil && session.foreground.Foreground() != session.job.foreground { - session.retire_locked() + session.retireLocked() } if isFocusGainEvent(event) && !event.ForegroundMismatch && !eventBypassesXTermHandoff(event) && (session.foreground == nil || event.Foreground.Epoch == 0 || event.Foreground.Epoch == session.foreground.Foreground().Epoch) { @@ -615,7 +615,7 @@ func (session *ocrSession) Observe(event atspi.Event) bool { } session.window = eventWindow(event) if session.focus != event.Source.ID() { - session.retire_locked() + session.retireLocked() } session.focus = event.Source.ID() if session.foreground != nil { @@ -630,7 +630,7 @@ func (session *ocrSession) Observe(event atspi.Event) bool { (event.Source.ID() == session.source.Object || event.Source.ID() == session.job.window) windowLost := event.Type != atspi.DefunctStateEvent && session.cancel != nil && eventWindow(event) == session.job.window if sourceLost || windowLost { - session.retire_locked() + session.retireLocked() session.focus = atspi.ObjectID{} } } @@ -648,7 +648,7 @@ func (session *ocrSession) ForegroundChanged() { return } if session.cancel != nil && session.foreground.Foreground() != session.job.foreground { - session.retire_locked() + session.retireLocked() } } @@ -676,7 +676,7 @@ func (session *ocrSession) RouteBraille(ctx context.Context, generation uint64, } session.mu.Lock() defer session.mu.Unlock() - if generation != session.generation || session.cursor == nil || !session.current_locked(session.job) || ctx.Err() != nil { + if generation != session.generation || session.cursor == nil || !session.currentLocked(session.job) || ctx.Err() != nil { return } position, ok := session.cursor.Set(offset) @@ -686,5 +686,5 @@ func (session *ocrSession) RouteBraille(ctx context.Context, generation uint64, session.selectionAnchor = -1 session.logger.Debug("OCR braille route", "command", "braille-route", "generation", generation, "focus_path", session.focus.Path, "source_path", session.source.Object.Path, "offset", offset) - session.present_locked(position, ocr.Character) + session.presentLocked(position, ocr.Character) } diff --git a/internal/app/ocr_session_test.go b/internal/app/ocr_session_test.go index 3e344ca..6ccfdde 100644 --- a/internal/app/ocr_session_test.go +++ b/internal/app/ocr_session_test.go @@ -142,7 +142,7 @@ func (output *ocrTestOutput) Enqueue(request speechRequest) { output.speech < func (*ocrTestOutput) Interrupt() {} func (output *ocrTestOutput) EnqueueFrame(frame braille.Frame) { output.frames <- frame } -func ocr_test_receive[T any](t *testing.T, channel <-chan T) T { +func ocrTestReceive[T any](t *testing.T, channel <-chan T) T { t.Helper() select { case result := <-channel: @@ -153,10 +153,10 @@ func ocr_test_receive[T any](t *testing.T, channel <-chan T) T { var empty T return empty } -func ocr_test_focus(path, role string) atspi.Event { +func ocrTestFocus(path, role string) atspi.Event { return atspi.Event{Type: atspi.FocusEvent, Source: atspi.Snapshot{BusName: ":1.42", Path: path, Role: role}, Window: atspi.NewObjectID(":1.42", "/window")} } -func ocr_test_session(t *testing.T) (*ocrSession, *ocrTestKeys, *ocrTestCapture, *ocrTestEngine, *ocrTestOutput) { +func ocrTestSession(t *testing.T) (*ocrSession, *ocrTestKeys, *ocrTestCapture, *ocrTestEngine, *ocrTestOutput) { t.Helper() keys := &ocrTestKeys{calls: make(chan string, 32)} monitor := &ocrTestForeground{state: atspi.ForegroundState{Epoch: 1, Client: xorg.Foreground{Known: true, Window: 42, PID: 123, Width: 100, Height: 50}}} @@ -170,7 +170,7 @@ func ocr_test_session(t *testing.T) (*ocrSession, *ocrTestKeys, *ocrTestCapture, if err := session.Start(context.Background()); err != nil { t.Fatal(err) } - session.Observe(ocr_test_focus("/focus", "image")) + session.Observe(ocrTestFocus("/focus", "image")) t.Cleanup(func() { engine.results <- ocr.Result{} ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) @@ -183,41 +183,41 @@ func ocr_test_session(t *testing.T) (*ocrSession, *ocrTestKeys, *ocrTestCapture, } func TestOCRSessionCommandsOwnSourceAndRunePresentation(t *testing.T) { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) if !session.Handle(input.CommandEvent{Command: input.OCRObject, Timestamp: 100}) { t.Fatal("OCR command not claimed") } - if got := ocr_test_receive(t, keys.calls); got != "pending" { + if got := ocrTestReceive(t, keys.calls); got != "pending" { t.Fatal(got) } - request := ocr_test_receive(t, capture.calls) + request := ocrTestReceive(t, capture.calls) if request.Kind != ocr.ObjectSource || request.Foreground != 42 || request.Bounds != image.Rect(10, 20, 110, 70) || request.Generation == 0 { t.Fatalf("capture: %+v", request) } - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "é one\ntwo", Words: []ocr.Word{{Text: "é", Span: ocr.Span{Start: 0, End: 1}}, {Text: "one", Span: ocr.Span{Start: 2, End: 5}}, {Text: "two", Span: ocr.Span{Start: 6, End: 9}}}} - if got := ocr_test_receive(t, keys.calls); got != "review" { + if got := ocrTestReceive(t, keys.calls); got != "review" { t.Fatal(got) } - if got := ocr_test_receive(t, output.speech); got.Text != "é one" { + if got := ocrTestReceive(t, output.speech); got.Text != "é one" { t.Fatal(got) } - if got := ocr_test_receive(t, output.frames); got.Text != "é one" || got.Cursor != 0 || len(got.Routes) != 0 { + if got := ocrTestReceive(t, output.frames); got.Text != "é one" || got.Cursor != 0 || len(got.Routes) != 0 { t.Fatalf("braille: %+v", got) } session.Input(input.NewKeyEvent(1, true, "Right")) session.Handle(input.CommandEvent{Command: input.OCRNextCharacter, Timestamp: 101}) - if got := ocr_test_receive(t, output.speech); got.Text != "space" || !got.Character { + if got := ocrTestReceive(t, output.speech); got.Text != "space" || !got.Character { t.Fatal(got) } - if got := ocr_test_receive(t, output.frames); got.Cursor != 1 { + if got := ocrTestReceive(t, output.frames); got.Cursor != 1 { t.Fatal(got) } session.Handle(input.CommandEvent{Command: input.OCRNextWord, Timestamp: 102}) - if got := ocr_test_receive(t, output.speech); got.Text != "one" { + if got := ocrTestReceive(t, output.speech); got.Text != "one" { t.Fatal(got) } - if got := ocr_test_receive(t, output.frames); got.Cursor != 2 { + if got := ocrTestReceive(t, output.frames); got.Cursor != 2 { t.Fatal(got) } // A repeated activation of the same top-level is not a focus change. @@ -234,14 +234,14 @@ func TestOCRSessionCommandsOwnSourceAndRunePresentation(t *testing.T) { if !session.Handle(input.CommandEvent{Command: tc.command}) { t.Fatal("OCR did not claim spelling") } - if got := ocr_test_receive(t, output.speech); !reflect.DeepEqual(got.Spelling, tc.parts) { + if got := ocrTestReceive(t, output.speech); !reflect.DeepEqual(got.Spelling, tc.parts) { t.Fatalf("OCR spelling: %+v", got) } - if got := ocr_test_receive(t, output.frames); got.Text != "é one" || got.Cursor != 2 { + if got := ocrTestReceive(t, output.frames); got.Text != "é one" || got.Cursor != 2 { t.Fatalf("spelling moved OCR braille cursor: %+v", got) } } - event := ocr_test_focus("/window", "frame") + event := ocrTestFocus("/window", "frame") event.Type = atspi.WindowActivatedEvent if !session.Observe(event) { t.Fatal("duplicate activation discarded OCR") @@ -249,26 +249,26 @@ func TestOCRSessionCommandsOwnSourceAndRunePresentation(t *testing.T) { event.Type = atspi.WindowDeactivatedEvent session.Observe(event) session.Handle(input.CommandEvent{Command: input.OCRNextLine, Timestamp: 103}) - if got := ocr_test_receive(t, output.speech); got.Text != "two" { + if got := ocrTestReceive(t, output.speech); got.Text != "two" { t.Fatal(got) } - if got := ocr_test_receive(t, output.frames); got.Text != "two" || got.Cursor != 2 { + if got := ocrTestReceive(t, output.frames); got.Text != "two" || got.Cursor != 2 { t.Fatal(got) } session.Handle(input.CommandEvent{Command: input.OCRDismiss, Timestamp: 104}) - if got := ocr_test_receive(t, output.speech); got.Text != "OCR dismissed" { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR dismissed" { t.Fatal(got) } - if got := ocr_test_receive(t, keys.calls); got != "released" { + if got := ocrTestReceive(t, keys.calls); got != "released" { t.Fatal(got) } } func TestOCRSessionSupersedesAndJoinsBeforeNewJob(t *testing.T) { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100}) - first := ocr_test_receive(t, capture.calls) - firstContext := ocr_test_receive(t, engine.calls) + first := ocrTestReceive(t, capture.calls) + firstContext := ocrTestReceive(t, engine.calls) session.Handle(input.CommandEvent{Command: input.OCRClipboard, Timestamp: 101}) if firstContext.Err() != context.Canceled { t.Fatal("replacement did not cancel old job") @@ -279,13 +279,13 @@ func TestOCRSessionSupersedesAndJoinsBeforeNewJob(t *testing.T) { default: } engine.results <- ocr.Result{Text: "stale result"} - second := ocr_test_receive(t, capture.calls) + second := ocrTestReceive(t, capture.calls) if first.Kind != ocr.WindowSource || second.Kind != ocr.ClipboardSource || second.Generation <= first.Generation { t.Fatalf("generations: %+v %+v", first, second) } - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "current result"} - if got := ocr_test_receive(t, output.speech); got.Text != "current result" { + if got := ocrTestReceive(t, output.speech); got.Text != "current result" { t.Fatal(got) } // Source options/pixels are owned until dismissal, even for clipboard OCR. @@ -301,20 +301,20 @@ func TestOCRSessionSupersedesAndJoinsBeforeNewJob(t *testing.T) { func TestOCRSessionRetiresEveryJobBoundary(t *testing.T) { for _, boundary := range []string{"input", "same-client-focus", "password", "source-destroyed", "foreground", "lock", "terminal", "dialog", "shutdown"} { t.Run(boundary, func(t *testing.T) { - session, keys, _, engine, output := ocr_test_session(t) + session, keys, _, engine, output := ocrTestSession(t) session.Handle(input.CommandEvent{Command: input.OCRObject, Timestamp: 100}) - jobContext := ocr_test_receive(t, engine.calls) + jobContext := ocrTestReceive(t, engine.calls) switch boundary { case "input": event := input.NewKeyEvent(1, true, "a") event.Timestamp = 101 session.Input(event) case "same-client-focus": - session.Observe(ocr_test_focus("/other", "image")) + session.Observe(ocrTestFocus("/other", "image")) case "password": - session.Observe(ocr_test_focus("/password", "password text")) + session.Observe(ocrTestFocus("/password", "password text")) case "source-destroyed": - event := ocr_test_focus("/image", "image") + event := ocrTestFocus("/image", "image") event.Type = atspi.DefunctStateEvent session.Observe(event) case "foreground": @@ -342,7 +342,7 @@ func TestOCRSessionRetiresEveryJobBoundary(t *testing.T) { t.Fatal("job not canceled") } engine.results <- ocr.Result{Text: "late private text"} - for ocr_test_receive(t, keys.calls) != "released" { + for ocrTestReceive(t, keys.calls) != "released" { } select { case got := <-output.speech: @@ -356,13 +356,13 @@ func TestOCRSessionRetiresEveryJobBoundary(t *testing.T) { func TestOCRSessionPasswordFocusAllowsVisibleCapture(t *testing.T) { for _, command := range []input.Command{input.OCRObject, input.OCRWindow, input.OCRDesktop, input.OCRClipboard} { t.Run(string(command), func(t *testing.T) { - session, _, capture, engine, output := ocr_test_session(t) - session.Observe(ocr_test_focus("/protected", "password text")) + session, _, capture, engine, output := ocrTestSession(t) + session.Observe(ocrTestFocus("/protected", "password text")) session.Handle(input.CommandEvent{Command: command}) - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "Visible label"} - if got := ocr_test_receive(t, output.speech); got.Text != "Visible label" { + if got := ocrTestReceive(t, output.speech); got.Text != "Visible label" { t.Fatal(got) } }) @@ -373,7 +373,7 @@ func TestOCRSessionScreenSourcesWithoutAccessibility(t *testing.T) { for _, command := range []input.Command{input.OCRWindow, input.OCRDesktop, input.OCRClipboard} { for _, staleFocus := range []bool{false, true} { t.Run(string(command)+fmt.Sprint("/stale=", staleFocus), func(t *testing.T) { - session, _, capture, engine, output := ocr_test_session(t) + session, _, capture, engine, output := ocrTestSession(t) session.geometry, session.interest = nil, nil if staleFocus { session.focusForeground = 99 @@ -381,28 +381,28 @@ func TestOCRSessionScreenSourcesWithoutAccessibility(t *testing.T) { session.focus, session.window = atspi.ObjectID{}, atspi.ObjectID{} } session.Handle(input.CommandEvent{Command: command, Timestamp: 100}) - request := ocr_test_receive(t, capture.calls) + request := ocrTestReceive(t, capture.calls) if request.Foreground != 42 || request.Bounds != (image.Rectangle{}) { t.Fatalf("non-object capture: %+v", request) } - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "Visible text"} - if got := ocr_test_receive(t, output.speech); got.Text != "Visible text" { + if got := ocrTestReceive(t, output.speech); got.Text != "Visible text" { t.Fatal(got) } - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.frames) session.Handle(input.CommandEvent{Command: input.OCRRefresh, Timestamp: 101}) if command != input.OCRClipboard { - ocr_test_receive(t, capture.calls) + ocrTestReceive(t, capture.calls) } - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "Updated text"} - if got := ocr_test_receive(t, output.speech); got.Text != "Updated text" { + if got := ocrTestReceive(t, output.speech); got.Text != "Updated text" { t.Fatal(got) } - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.frames) session.Handle(input.CommandEvent{Command: input.OCRDismiss}) - if got := ocr_test_receive(t, output.speech); got.Text != "OCR dismissed" { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR dismissed" { t.Fatal(got) } }) @@ -412,14 +412,14 @@ func TestOCRSessionScreenSourcesWithoutAccessibility(t *testing.T) { func TestOCRSessionObjectStillRequiresAccessibleFocus(t *testing.T) { for _, staleFocus := range []bool{false, true} { - session, _, capture, _, output := ocr_test_session(t) + session, _, capture, _, output := ocrTestSession(t) if staleFocus { session.focusForeground = 99 } else { session.focus = atspi.ObjectID{} } session.Handle(input.CommandEvent{Command: input.OCRObject}) - if got := ocr_test_receive(t, output.speech); got.Text != "OCR source unavailable" { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR source unavailable" { t.Fatal(got) } select { @@ -431,25 +431,25 @@ func TestOCRSessionObjectStillRequiresAccessibleFocus(t *testing.T) { } func TestOCRSessionLockRetiresInaccessibleWindowResult(t *testing.T) { - session, keys, _, engine, output := ocr_test_session(t) + session, keys, _, engine, output := ocrTestSession(t) session.focus, session.window = atspi.ObjectID{}, atspi.ObjectID{} session.geometry = nil session.Handle(input.CommandEvent{Command: input.OCRWindow}) - ocr_test_receive(t, keys.calls) - jobContext := ocr_test_receive(t, engine.calls) + ocrTestReceive(t, keys.calls) + jobContext := ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "Visible text"} - ocr_test_receive(t, keys.calls) - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + ocrTestReceive(t, keys.calls) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) session.gate.ocr = session session.gate.SetLocked(true, nil, nil, nil, nil, &brailleWorker{}) if jobContext.Err() != context.Canceled || session.Reviewing() { t.Fatal("screen lock retained OCR result") } - if got := ocr_test_receive(t, output.frames); got.Text != "" { + if got := ocrTestReceive(t, output.frames); got.Text != "" { t.Fatal("screen lock retained OCR braille text") } - for ocr_test_receive(t, keys.calls) != "released" { + for ocrTestReceive(t, keys.calls) != "released" { } for _, command := range []input.Command{input.OCRObject, input.OCRWindow, input.OCRDesktop, input.OCRClipboard} { session.Handle(input.CommandEvent{Command: command}) @@ -463,7 +463,7 @@ func TestOCRSessionLockRetiresInaccessibleWindowResult(t *testing.T) { func TestOCRSessionSourceAndDependencyErrors(t *testing.T) { for _, failure := range []error{ocr.ErrUnavailable, nil, atspi.ErrOCRGeometry} { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) engine.err = failure if errors.Is(failure, atspi.ErrOCRGeometry) { session.geometry.(*ocrTestGeometry).err = failure @@ -474,8 +474,8 @@ func TestOCRSessionSourceAndDependencyErrors(t *testing.T) { } session.Handle(input.CommandEvent{Command: command}) if !errors.Is(failure, atspi.ErrOCRGeometry) { - ocr_test_receive(t, capture.calls) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, capture.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{} } want := "No text recognized" @@ -485,18 +485,18 @@ func TestOCRSessionSourceAndDependencyErrors(t *testing.T) { if failure == atspi.ErrOCRGeometry { want = "OCR source unavailable" } - if got := ocr_test_receive(t, output.speech); got.Text != want { + if got := ocrTestReceive(t, output.speech); got.Text != want { t.Fatal(got) } - for ocr_test_receive(t, keys.calls) != "released" { + for ocrTestReceive(t, keys.calls) != "released" { } } } func TestOCRSessionDelayedInitiatingInputAndChordRetirement(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100}) - jobContext := ocr_test_receive(t, engine.calls) + jobContext := ocrTestReceive(t, engine.calls) event := input.NewKeyEvent(1, true, "o") event.Timestamp = 100 session.Input(event) @@ -504,7 +504,7 @@ func TestOCRSessionDelayedInitiatingInputAndChordRetirement(t *testing.T) { t.Fatal("delayed command observation canceled job") } engine.results <- ocr.Result{Text: "result"} - ocr_test_receive(t, output.speech) + ocrTestReceive(t, output.speech) session.Input(input.NewKeyEvent(2, true, "Control_L")) session.Input(input.NewKeyEvent(3, true, "Right")) if jobContext.Err() != nil { @@ -520,7 +520,7 @@ func TestOCRSessionDelayedInitiatingInputAndChordRetirement(t *testing.T) { func TestOCRSessionCancellationDuringCaptureAndInputEntry(t *testing.T) { for _, phase := range []string{"capture", "input-entry"} { t.Run(phase, func(t *testing.T) { - session, keys, capture, engine, output := ocr_test_session(t) + session, keys, capture, engine, output := ocrTestSession(t) started := make(chan context.Context, 1) block := func(ctx context.Context) error { started <- ctx; <-ctx.Done(); return ctx.Err() } if phase == "capture" { @@ -530,15 +530,15 @@ func TestOCRSessionCancellationDuringCaptureAndInputEntry(t *testing.T) { } session.Handle(input.CommandEvent{Command: input.OCRWindow}) if phase == "input-entry" { - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "ready"} } - jobContext := ocr_test_receive(t, started) + jobContext := ocrTestReceive(t, started) session.Retire() if jobContext.Err() != context.Canceled { t.Fatal("native operation not canceled") } - for ocr_test_receive(t, keys.calls) != "released" { + for ocrTestReceive(t, keys.calls) != "released" { } select { case got := <-output.speech: @@ -550,20 +550,20 @@ func TestOCRSessionCancellationDuringCaptureAndInputEntry(t *testing.T) { } func TestOCRSessionReleaseFailureIsReported(t *testing.T) { - session, keys, _, engine, output := ocr_test_session(t) + session, keys, _, engine, output := ocrTestSession(t) keys.releaseErr = errors.New("release failed") session.Handle(input.CommandEvent{Command: input.OCRWindow}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "ready"} - ocr_test_receive(t, output.speech) + ocrTestReceive(t, output.speech) session.Retire() - if err := ocr_test_receive(t, session.failures); err != keys.releaseErr { + if err := ocrTestReceive(t, session.failures); err != keys.releaseErr { t.Fatal(err) } } func TestOCRSessionWaitForPhysicalReleaseRetries(t *testing.T) { - session, keys, _, engine, output := ocr_test_session(t) + session, keys, _, engine, output := ocrTestSession(t) count := 0 keys.release = func() error { count++ @@ -573,13 +573,13 @@ func TestOCRSessionWaitForPhysicalReleaseRetries(t *testing.T) { return nil } session.Handle(input.CommandEvent{Command: input.OCRWindow}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "ready"} - ocr_test_receive(t, output.speech) + ocrTestReceive(t, output.speech) session.Retire() releases := 0 for releases < 2 { - if ocr_test_receive(t, keys.calls) == "released" { + if ocrTestReceive(t, keys.calls) == "released" { releases++ } } @@ -593,15 +593,15 @@ func TestOCRSessionWaitForPhysicalReleaseRetries(t *testing.T) { func TestOCRSessionRecognizesCthulhuAndNativeKeypadNames(t *testing.T) { for _, name := range []string{"KP_Insert", "Caps_Lock", "KP_Next", "KP_Prior"} { t.Run(name, func(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) settings := session.settings() settings.CthulhuModifierKeys = []string{"Insert", "KP_Insert", "Caps_Lock"} session.live = &liveSettings{} session.live.Store(settings) session.Handle(input.CommandEvent{Command: input.OCRWindow}) - jobContext := ocr_test_receive(t, engine.calls) + jobContext := ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "ready"} - ocr_test_receive(t, output.speech) + ocrTestReceive(t, output.speech) session.Input(input.NewKeyEvent(1, true, name)) if jobContext.Err() != nil { t.Fatalf("claimed native key %s retired OCR", name) @@ -612,66 +612,66 @@ func TestOCRSessionRecognizesCthulhuAndNativeKeypadNames(t *testing.T) { func TestOCRBrailleKeepsCursorInLongUnicodeLine(t *testing.T) { line := strings.Repeat("界", 5000) - frame := ocr_braille_frame(ocr.Position{Line: line, Cursor: 4999}) + frame := ocrBrailleFrame(ocr.Position{Line: line, Cursor: 4999}) if len(frame.Text) > 10000 || frame.Cursor != 1999 || len([]rune(frame.Text)) != 2000 || []rune(frame.Text)[frame.Cursor] != '界' { t.Fatalf("long-line cursor lost: bytes=%d cursor=%d", len(frame.Text), frame.Cursor) } } func TestOCRSelectionCopySayAllAndBrailleRouting(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) copier := &ocrTestCopier{copied: make(chan string, 2)} reader := &ocrTestReadAll{} session.copier = copier session.readAll = reader session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "é one\n猫 two"} - ocr_test_receive(t, output.speech) - initial := ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.speech) + initial := ocrTestReceive(t, output.frames) if initial.Virtual == nil || initial.Virtual.Generation == 0 || initial.Virtual.SourceStart != 0 { t.Fatalf("missing OCR route: %+v", initial) } session.Handle(input.CommandEvent{Command: input.OCRNextCharacter, Chord: input.CommandChord{Modifiers: 1}, Timestamp: 101}) - ocr_test_receive(t, output.speech) - selected := ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.speech) + selected := ocrTestReceive(t, output.frames) if selected.Cursor != 1 || len(selected.Dots) != 5 || selected.Dots[0] == 0 || selected.Dots[1] != 0 { t.Fatalf("selection frame: %+v", selected) } session.Handle(input.CommandEvent{Command: input.OCRCopySelection, Timestamp: 102}) - if got := ocr_test_receive(t, copier.copied); got != "é" { + if got := ocrTestReceive(t, copier.copied); got != "é" { t.Fatalf("copied %q", got) } - if got := ocr_test_receive(t, output.speech); got.Text != "OCR text copied to clipboard" { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR text copied to clipboard" { t.Fatal(got) } - ocr_test_receive(t, output.frames) // copy status + ocrTestReceive(t, output.frames) // copy status session.Handle(input.CommandEvent{Command: input.OCRSelectAll, Timestamp: 103}) - if got := ocr_test_receive(t, output.speech); got.Text != "OCR text selected" { + if got := ocrTestReceive(t, output.speech); got.Text != "OCR text selected" { t.Fatal(got) } - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.frames) session.Handle(input.CommandEvent{Command: input.OCRCopySelection, Timestamp: 104}) - if got := ocr_test_receive(t, copier.copied); got != "é one\n猫 two" { + if got := ocrTestReceive(t, copier.copied); got != "é one\n猫 two" { t.Fatalf("copied all %q", got) } - ocr_test_receive(t, output.speech) - ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.speech) + ocrTestReceive(t, output.frames) session.RouteBraille(context.Background(), initial.Virtual.Generation, 6) - if got := ocr_test_receive(t, output.speech); got.Text != "猫" { + if got := ocrTestReceive(t, output.speech); got.Text != "猫" { t.Fatal(got) } - routed := ocr_test_receive(t, output.frames) + routed := ocrTestReceive(t, output.frames) if routed.Text != "猫 two" || routed.Cursor != 0 || routed.Virtual.SourceStart != 6 { t.Fatalf("routed frame: %+v", routed) } session.Handle(input.CommandEvent{Command: input.ReadAll, Timestamp: 105}) - request := ocr_test_receive(t, output.speech) + request := ocrTestReceive(t, output.speech) if reader.timestamp != 105 || len(request.ReadAll) != 1 || request.ReadAll[0].Text != "猫 two" { t.Fatalf("Say All request: %+v", request) } request.ReadAll[0].Began() - if got := ocr_test_receive(t, output.frames); got.Cursor != 0 || got.Virtual == nil { + if got := ocrTestReceive(t, output.frames); got.Cursor != 0 || got.Virtual == nil { t.Fatalf("Say All braille: %+v", got) } session.Retire() @@ -686,12 +686,12 @@ func TestOCRSelectionCopySayAllAndBrailleRouting(t *testing.T) { } func TestOCRBrailleWorkerRoutesOnlyCurrentVirtualFrame(t *testing.T) { - session, _, _, engine, output := ocr_test_session(t) + session, _, _, engine, output := ocrTestSession(t) session.Handle(input.CommandEvent{Command: input.OCRWindow}) - ocr_test_receive(t, engine.calls) + ocrTestReceive(t, engine.calls) engine.results <- ocr.Result{Text: "é猫"} - ocr_test_receive(t, output.speech) - frame := ocr_test_receive(t, output.frames) + ocrTestReceive(t, output.speech) + frame := ocrTestReceive(t, output.frames) native := &recordingBrailleRouter{calls: make(chan atspi.BrailleRoute, 1)} worker := &brailleWorker{ocr: session, router: native, logger: slog.New(slog.DiscardHandler), wake: make(chan struct{}, 1), cancel: func() {}} worker.EnqueueFrame(frame) @@ -703,15 +703,15 @@ func TestOCRBrailleWorkerRoutesOnlyCurrentVirtualFrame(t *testing.T) { default: } worker.route(context.Background(), braille.RoutingEvent{ID: id, Offset: 1}) - if got := ocr_test_receive(t, output.speech); got.Text != "猫" { + if got := ocrTestReceive(t, output.speech); got.Text != "猫" { t.Fatal(got) } if len(native.calls) != 0 { t.Fatal("OCR routing moved the native caret") } session.Retire() - ocr_test_receive(t, output.frames) // routed presentation - ocr_test_receive(t, output.frames) // retired blank frame + ocrTestReceive(t, output.frames) // routed presentation + ocrTestReceive(t, output.frames) // retired blank frame worker.route(context.Background(), braille.RoutingEvent{ID: id, Offset: 0}) select { case <-output.speech: diff --git a/internal/app/phonetic_hints.go b/internal/app/phonetic_hints.go index 35c67de..0dd5efb 100644 --- a/internal/app/phonetic_hints.go +++ b/internal/app/phonetic_hints.go @@ -15,7 +15,7 @@ const phoneticHintDelay = 300 * time.Millisecond // The speech owner retains the hint with its character request. Waiting here // keeps output ordered without blocking input or accessibility event handling; // the normal input, settings, secure-session and shutdown barriers cancel it. -func (worker *speechWorker) deliver_phonetic_hint(ctx context.Context, request speechRequest) (bool, error) { +func (worker *speechWorker) deliverPhoneticHint(ctx context.Context, request speechRequest) (bool, error) { if !request.PhoneticHint || !request.Character || request.Role == "password text" || worker.reading == nil || !worker.reading().PhoneticCharacterHints || worker.inputActivity == nil { return false, nil diff --git a/internal/app/preferences.go b/internal/app/preferences.go index 0dd807c..494eb2c 100644 --- a/internal/app/preferences.go +++ b/internal/app/preferences.go @@ -107,7 +107,7 @@ type savedApplicationSettings struct { } func newPreferencesWorker(logger *slog.Logger, settings config.Settings, updater any) *preferencesWorker { - saved := config.Primary_voice(settings) + saved := config.PrimaryVoice(settings) return &preferencesWorker{savedVoice: &saved, logger: logger, settings: settings, globalSettings: settings, appSettings: make(map[string]config.Settings), updater: updater, extensionRequests: make(chan readerSettingsCall, 16), extensions: make(map[string]*readerExtension), speechCommands: make(chan input.Command, 16), remoteChanges: make(chan remoteSettingsChange, 16), discover: speech.Discover, readSpeechDefaults: speech.ReadDefaults, open: make(chan string, 1), applicationChanges: make(chan string, 1), done: make(chan struct{})} } @@ -120,10 +120,10 @@ func (worker *preferencesWorker) Start(ctx context.Context) error { select { case <-ctx.Done(): return - case <-worker.extension_changes(): - worker.sync_extensions(ctx) + case <-worker.extensionChanges(): + worker.syncExtensions(ctx) case call := <-worker.extensionRequests: - worker.handle_reader_call(ctx, call, false) + worker.handleReaderCall(ctx, call, false) case command := <-worker.speechCommands: worker.handleSpeechCommand(ctx, command) case change := <-worker.remoteChanges: @@ -181,7 +181,7 @@ func (worker *preferencesWorker) SetApplication(application string) { } if worker.live != nil { worker.live.requestedApplication.Store(&application) - worker.live.notify_clipboard() + worker.live.notifyClipboard() } select { case worker.applicationChanges <- application: diff --git a/internal/app/preferences_application.go b/internal/app/preferences_application.go index 64d5ddc..0f5002b 100644 --- a/internal/app/preferences_application.go +++ b/internal/app/preferences_application.go @@ -60,7 +60,7 @@ func (worker *preferencesWorker) applicationSettings(application string) (config if !mapped { return worker.globalSettings, nil } - worker.remember_application(application, persistedGlobal, settings) + worker.rememberApplication(application, persistedGlobal, settings) settings = config.RebaseApplicationSettings(persistedGlobal, worker.globalSettings, settings) worker.appSettings[application] = settings return worker.quickSpeech.apply(settings), nil @@ -83,7 +83,7 @@ func (worker *preferencesWorker) switchApplication(ctx context.Context, applicat worker.activeApp = application if worker.live != nil { worker.live.application.Store(&application) - worker.live.notify_clipboard() + worker.live.notifyClipboard() } } diff --git a/internal/app/preferences_apply.go b/internal/app/preferences_apply.go index ef6c156..87dcd9e 100644 --- a/internal/app/preferences_apply.go +++ b/internal/app/preferences_apply.go @@ -25,7 +25,7 @@ func (worker *preferencesWorker) response(message string, accepted bool) prefere if err == nil { _, err = store.Load() } - return preferences.Response{Values: preferences.FromSettings(settings), ExtensionPages: worker.extension_pages(), CanSave: err == nil, + return preferences.Response{Values: preferences.FromSettings(settings), ExtensionPages: worker.extensionPages(), CanSave: err == nil, Message: message, Accepted: accepted} } @@ -47,7 +47,7 @@ func (worker *preferencesWorker) apply(ctx context.Context, request preferences. if err != nil { return worker.response("Settings were not applied: "+err.Error(), false) } - transaction, err := worker.prepare_extension_pages(ctx, request.ExtensionPages) + transaction, err := worker.prepareExtensionPages(ctx, request.ExtensionPages) if err != nil { return worker.response("Tentacle settings were not applied: "+err.Error(), false) } @@ -55,7 +55,7 @@ func (worker *preferencesWorker) apply(ctx context.Context, request preferences. defer func() { worker.stagedReader = nil }() response := worker.applyNext(ctx, next, request.Save, request.Close) if response.Accepted && request.Save && len(request.ExtensionPages) > 0 { - if err := worker.save_extension_pages(); err != nil { + if err := worker.saveExtensionPages(); err != nil { response.Message = "Applied for this session, but tentacle preferences could not be saved: " + err.Error() response.Close = false } @@ -84,7 +84,7 @@ func (worker *preferencesWorker) applyNext(ctx context.Context, next config.Sett // An explicit preferences Apply replaces the session's quick speech choices. if worker.editingActive { worker.quickSpeech = quickSpeechSettings{} - worker.remember_saved_voice(next, scopeApp) + worker.rememberSavedVoice(next, scopeApp) } if worker.editingActive { worker.editing = next @@ -134,24 +134,24 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S if worker.bindings == nil { return errors.New("Key bindings cannot be changed by this input backend.") } - if err := worker.apply_keyboard(ctx, next, keyboardChanged); err != nil { + if err := worker.applyKeyboard(ctx, next, keyboardChanged); err != nil { return errors.New("Key bindings were not applied: " + err.Error()) } defer func() { if !bindingsCommitted { rollbackCtx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - if err := worker.apply_keyboard(rollbackCtx, worker.settings, keyboardChanged); err != nil { + if err := worker.applyKeyboard(rollbackCtx, worker.settings, keyboardChanged); err != nil { worker.logger.Error("restore key bindings after failed preferences apply", "error", err) } } }() } - effectiveNext := worker.effective_settings(next) - effectiveCurrent := worker.effective_settings(worker.settings) + effectiveNext := worker.effectiveSettings(next) + effectiveCurrent := worker.effectiveSettings(worker.settings) if worker.stagedReader != nil { for _, extension := range worker.stagedReader.extensions { - if err := worker.reader_allowed(ctx, extension.session); err != nil { + if err := worker.readerAllowed(ctx, extension.session); err != nil { return err } } @@ -172,7 +172,7 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S } }() if next.EnableSpeech && (speechChanged || !worker.settings.EnableSpeech) { - if message := worker.apply_speech_settings(ctx, effectiveNext); message != "" { + if message := worker.applySpeechSettings(ctx, effectiveNext); message != "" { return errors.New(message) } speechApplied = true @@ -193,7 +193,7 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S } if worker.stagedReader != nil { for _, extension := range worker.stagedReader.extensions { - if err := worker.reader_allowed(ctx, extension.session); err != nil { + if err := worker.readerAllowed(ctx, extension.session); err != nil { return err } } @@ -201,11 +201,11 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S worker.speechOverride, worker.speechOverrideOwner = worker.stagedReader.override, worker.stagedReader.owner } bindingsCommitted = true - worker.commit_settings(next) + worker.commitSettings(next) return nil } -func (worker *preferencesWorker) apply_keyboard(ctx context.Context, settings config.Settings, keyboardChanged bool) error { +func (worker *preferencesWorker) applyKeyboard(ctx context.Context, settings config.Settings, keyboardChanged bool) error { if updater, ok := worker.bindings.(interface { SetKeyboardConfiguration(context.Context, input.KeyboardLayout, []string, []input.BindingOverride) error }); ok { @@ -217,7 +217,7 @@ func (worker *preferencesWorker) apply_keyboard(ctx context.Context, settings co return worker.bindings.SetKeyBindings(ctx, settings.KeyBindings) } -func (worker *preferencesWorker) apply_speech_settings(ctx context.Context, next config.Settings) string { +func (worker *preferencesWorker) applySpeechSettings(ctx context.Context, next config.Settings) string { var err error if worker.updater == nil { @@ -243,7 +243,7 @@ func (worker *preferencesWorker) apply_speech_settings(ctx context.Context, next // Commit follows the existing backend updates and keyboard rollback boundary. // It publishes settings to runtime consumers without changing their ownership. -func (worker *preferencesWorker) commit_settings(next config.Settings) { +func (worker *preferencesWorker) commitSettings(next config.Settings) { soundChanged := soundConfiguration(next) != soundConfiguration(worker.settings) worker.settings = next if updater, ok := worker.braille.(interface{ SetWordWrap(bool) }); ok { @@ -273,7 +273,7 @@ func (worker *preferencesWorker) commit_settings(next config.Settings) { worker.textAttributes.SetCaptureTextAttributes(captureTextAttributes(next)) } if worker.live != nil { - worker.live.Store(worker.effective_settings(next)) + worker.live.Store(worker.effectiveSettings(next)) } if worker.speechWorker != nil && next.EnableSpeech { worker.speechWorker.SetEnabled(true) diff --git a/internal/app/preferences_echo_preview_test.go b/internal/app/preferences_echo_preview_test.go index e9f50b8..ed76fa8 100644 --- a/internal/app/preferences_echo_preview_test.go +++ b/internal/app/preferences_echo_preview_test.go @@ -240,7 +240,7 @@ func TestEchoPreviewFocusSpeechWaitsForBothVoices(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { worker.Stop(context.Background()) }) - worker.Enqueue(echo_preview_speech("Key echo person", "Selected voice")) + worker.Enqueue(echoPreviewSpeech("Key echo person", "Selected voice")) label := expectSpeechCall(t, &speaker.controlledSpeaker, "default:Key echo person") worker.Enqueue(speechRequest{Text: "Later control"}) select { @@ -266,7 +266,7 @@ func TestEchoPreviewFocusSpeechRemainsInterruptible(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { worker.Stop(context.Background()) }) - worker.Enqueue(echo_preview_speech("Key echo person", "Selected voice")) + worker.Enqueue(echoPreviewSpeech("Key echo person", "Selected voice")) label := expectSpeechCall(t, &speaker.controlledSpeaker, "default:Key echo person") close(label.done) value := expectSpeechCall(t, &speaker.controlledSpeaker, "echo:Selected voice") diff --git a/internal/app/preferences_feedback_test.go b/internal/app/preferences_feedback_test.go index 47da097..4b44d07 100644 --- a/internal/app/preferences_feedback_test.go +++ b/internal/app/preferences_feedback_test.go @@ -161,7 +161,7 @@ func TestPreferencesApplyAnnouncesBeforeReplyAndPreservesSaveFailure(t *testing. requests := make(chan preferences.Request) readDone := make(chan error, 1) done := make(chan error, 1) - go func() { done <- worker.serve_preferences(ctx, ctx, json.NewEncoder(writer), requests, readDone) }() + go func() { done <- worker.servePreferences(ctx, ctx, json.NewEncoder(writer), requests, readDone) }() values := preferences.FromSettings(settings) rate := 65.0 values.Rate = &rate diff --git a/internal/app/preferences_preview.go b/internal/app/preferences_preview.go index a58f25c..a697b3e 100644 --- a/internal/app/preferences_preview.go +++ b/internal/app/preferences_preview.go @@ -16,7 +16,7 @@ import ( func (worker *preferencesWorker) preview(ctx context.Context, request preferences.Request) preferences.Response { if request.EchoPreview != "" { - return worker.preview_echo_voice(ctx, request) + return worker.previewEchoVoice(ctx, request) } next := worker.settings if worker.editingActive { @@ -53,7 +53,7 @@ func (worker *preferencesWorker) preview(ctx context.Context, request preference return response } -func (worker *preferencesWorker) preview_echo_voice(ctx context.Context, request preferences.Request) preferences.Response { +func (worker *preferencesWorker) previewEchoVoice(ctx context.Context, request preferences.Request) preferences.Response { response := worker.response("Speech settings previewed.", false) response.Preview = true var value *float64 @@ -117,7 +117,7 @@ func (worker *preferencesWorker) preview_echo_voice(ctx context.Context, request return response } -func echo_preview_speech(label, value string) speechRequest { +func echoPreviewSpeech(label, value string) speechRequest { parts := []readAllPart{} if label != "" { parts = append(parts, readAllPart{Text: label, VoiceType: "default"}) @@ -130,7 +130,7 @@ func echo_preview_speech(label, value string) speechRequest { func (worker *preferencesWorker) restorePreview(ctx context.Context) preferences.Response { response := worker.response("Speech settings restored.", false) - if err := worker.updateSpeech(ctx, worker.effective_settings(worker.settings)); err != nil { + if err := worker.updateSpeech(ctx, worker.effectiveSettings(worker.settings)); err != nil { response.Message = "Speech settings could not be restored: " + err.Error() return response } diff --git a/internal/app/preferences_session.go b/internal/app/preferences_session.go index 3561a47..692c87a 100644 --- a/internal/app/preferences_session.go +++ b/internal/app/preferences_session.go @@ -97,7 +97,7 @@ func (worker *preferencesWorker) window(ctx context.Context) (result error) { } }() encoder := json.NewEncoder(in) - initial, err := worker.initial_response(childCtx) + initial, err := worker.initialResponse(childCtx) if err != nil { return err } @@ -107,25 +107,25 @@ func (worker *preferencesWorker) window(ctx context.Context) (result error) { requests := make(chan preferences.Request, 1) readDone := make(chan error, 1) readerStopped := make(chan struct{}) - go read_preferences_requests(childCtx, stop, out, requests, readDone, readerStopped) + go readPreferencesRequests(childCtx, stop, out, requests, readDone, readerStopped) defer func() { stop() out.Close() <-readerStopped }() - return worker.serve_preferences(ctx, childCtx, encoder, requests, readDone) + return worker.servePreferences(ctx, childCtx, encoder, requests, readDone) } -func (worker *preferencesWorker) initial_response(childCtx context.Context) (preferences.Response, error) { +func (worker *preferencesWorker) initialResponse(childCtx context.Context) (preferences.Response, error) { if worker.choosingApplication { return preferences.Response{ChooseApplication: true}, nil } var err error initial := worker.response("Apply and OK save settings. Cancel discards unapplied edits.", true) initial.Application = worker.editApp - worker.sync_extensions(childCtx) + worker.syncExtensions(childCtx) if worker.editApp == "" { - initial.ExtensionPages = worker.extension_pages() + initial.ExtensionPages = worker.extensionPages() } if worker.editApp == "" { snapshot := worker.tentacles.Snapshot() @@ -149,18 +149,18 @@ func (worker *preferencesWorker) initial_response(childCtx context.Context) (pre } } if worker.editApp == "" { - if err := worker.load_extension_pages(childCtx); err != nil { + if err := worker.loadExtensionPages(childCtx); err != nil { worker.logger.Warn("load tentacle preference pages", "error", err) initial.Message += " Some tentacle pages could not load; their last valid controls were retained." } - initial.ExtensionPages = worker.extension_pages() + initial.ExtensionPages = worker.extensionPages() } return initial, nil } // The reader owns decoding only. Its caller closes the pipe and joins it before // waiting for the child; cancellation also releases a full request mailbox. -func read_preferences_requests(childCtx context.Context, stop context.CancelFunc, out io.Reader, requests chan<- preferences.Request, readDone chan<- error, readerStopped chan<- struct{}) { +func readPreferencesRequests(childCtx context.Context, stop context.CancelFunc, out io.Reader, requests chan<- preferences.Request, readDone chan<- error, readerStopped chan<- struct{}) { defer close(readerStopped) defer stop() scanner := bufio.NewScanner(out) @@ -183,7 +183,7 @@ func read_preferences_requests(childCtx context.Context, stop context.CancelFunc // The worker goroutine serializes apply/preview replies and repeated-open // requests. Preview restoration precedes pipe joins and child cleanup. -func (worker *preferencesWorker) serve_preferences(ctx, childCtx context.Context, encoder *json.Encoder, requests <-chan preferences.Request, readDone <-chan error) error { +func (worker *preferencesWorker) servePreferences(ctx, childCtx context.Context, encoder *json.Encoder, requests <-chan preferences.Request, readDone <-chan error) error { previewActive := false defer func() { if !previewActive || ctx.Err() != nil { @@ -191,7 +191,7 @@ func (worker *preferencesWorker) serve_preferences(ctx, childCtx context.Context } restoreCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second) defer cancel() - if err := worker.updateSpeech(restoreCtx, worker.effective_settings(worker.settings)); err != nil { + if err := worker.updateSpeech(restoreCtx, worker.effectiveSettings(worker.settings)); err != nil { worker.logger.Error("restore speech settings after preferences exit", "error", err) } }() @@ -199,15 +199,15 @@ func (worker *preferencesWorker) serve_preferences(ctx, childCtx context.Context select { case <-ctx.Done(): return ctx.Err() - case <-worker.extension_changes(): - worker.sync_extensions(ctx) + case <-worker.extensionChanges(): + worker.syncExtensions(ctx) if worker.editApp == "" { - if err := encoder.Encode(preferences.Response{ExtensionsOnly: true, ExtensionPages: worker.extension_pages()}); err != nil { + if err := encoder.Encode(preferences.Response{ExtensionsOnly: true, ExtensionPages: worker.extensionPages()}); err != nil { return err } } case call := <-worker.extensionRequests: - worker.handle_reader_call(ctx, call, true) + worker.handleReaderCall(ctx, call, true) case command := <-worker.speechCommands: if command == input.CycleProgressBarOutput { worker.announceSpeechSetting("Close preferences before changing progress bar output with its shortcut.") @@ -226,7 +226,7 @@ func (worker *preferencesWorker) serve_preferences(ctx, childCtx context.Context return err case request := <-requests: if request.Tentacle != nil { - response := worker.manage_tentacle(childCtx, request) + response := worker.manageTentacle(childCtx, request) if err := encoder.Encode(response); err != nil { return err } @@ -237,7 +237,7 @@ func (worker *preferencesWorker) serve_preferences(ctx, childCtx context.Context return errors.New("invalid application preferences selection") } worker.choosingApplication = false - initial, err := worker.initial_response(childCtx) + initial, err := worker.initialResponse(childCtx) if err != nil { return err } diff --git a/internal/app/preferences_session_test.go b/internal/app/preferences_session_test.go index 2710e7e..e359039 100644 --- a/internal/app/preferences_session_test.go +++ b/internal/app/preferences_session_test.go @@ -41,10 +41,10 @@ func TestPreferencesSessionRestoresPreviewAfterRejectedApplyAndReopen(t *testing readDone := make(chan error, 1) done := make(chan error, 1) go func() { - done <- worker.serve_preferences(ctx, ctx, json.NewEncoder(writer), requests, readDone) + done <- worker.servePreferences(ctx, ctx, json.NewEncoder(writer), requests, readDone) }() decoder := json.NewDecoder(reader) - read_response := func() preferences.Response { + readResponse := func() preferences.Response { t.Helper() var response preferences.Response if err := decoder.Decode(&response); err != nil { @@ -60,7 +60,7 @@ func TestPreferencesSessionRestoresPreviewAfterRejectedApplyAndReopen(t *testing case <-ctx.Done(): t.Fatal(ctx.Err()) } - if response := read_response(); !response.Accepted || !response.Preview { + if response := readResponse(); !response.Accepted || !response.Preview { t.Fatalf("preview was rejected: %+v", response) } if len(updates) != 1 { @@ -70,7 +70,7 @@ func TestPreferencesSessionRestoresPreviewAfterRejectedApplyAndReopen(t *testing t.Fatalf("preview did not reach speech: %+v", update) } worker.Open() - if response := read_response(); !response.Present || response.Close { + if response := readResponse(); !response.Present || response.Close { t.Fatalf("reopen did not raise the existing window: %+v", response) } values.Punctuation = 99 @@ -79,7 +79,7 @@ func TestPreferencesSessionRestoresPreviewAfterRejectedApplyAndReopen(t *testing case <-ctx.Done(): t.Fatal(ctx.Err()) } - if response := read_response(); response.Accepted || response.Close { + if response := readResponse(); response.Accepted || response.Close { t.Fatalf("invalid draft committed or closed: %+v", response) } readDone <- io.EOF @@ -129,7 +129,7 @@ func TestChooserSelectionSavesSelectedProfileWhileAnotherAppIsActive(t *testing. requests := make(chan preferences.Request) readDone := make(chan error, 1) done := make(chan error, 1) - go func() { done <- worker.serve_preferences(ctx, ctx, json.NewEncoder(writer), requests, readDone) }() + go func() { done <- worker.servePreferences(ctx, ctx, json.NewEncoder(writer), requests, readDone) }() requests <- preferences.Request{Application: "Chosen Application"} decoder := json.NewDecoder(reader) var initial preferences.Response diff --git a/internal/app/preferences_tentacles.go b/internal/app/preferences_tentacles.go index a002b97..6de4e61 100644 --- a/internal/app/preferences_tentacles.go +++ b/internal/app/preferences_tentacles.go @@ -13,7 +13,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentacle" ) -func (worker *preferencesWorker) manage_tentacle(ctx context.Context, request preferences.Request) preferences.Response { +func (worker *preferencesWorker) manageTentacle(ctx context.Context, request preferences.Request) preferences.Response { response := preferences.Response{} if worker.choosingApplication || worker.editApp != "" || request.Application != "" { response.Message = "Tentacles can only be managed in global preferences." diff --git a/internal/app/preferences_test.go b/internal/app/preferences_test.go index c8e87aa..3982f70 100644 --- a/internal/app/preferences_test.go +++ b/internal/app/preferences_test.go @@ -33,7 +33,7 @@ func TestPreferencesInitialRetainsLargeVoiceCatalog(t *testing.T) { worker := newPreferencesWorker(slog.New(slog.DiscardHandler), config.DefaultSettings(), nil) worker.discover = func(context.Context, string) (speech.Catalog, error) { return catalog, nil } worker.readSpeechDefaults = func(context.Context, string) (speech.Settings, error) { return speech.Settings{}, nil } - response, err := worker.initial_response(t.Context()) + response, err := worker.initialResponse(t.Context()) if err != nil || !reflect.DeepEqual(response.Catalog, catalog) { t.Fatalf("initial response lost discovered voices: err=%v", err) } diff --git a/internal/app/progress_bars.go b/internal/app/progress_bars.go index 945de27..7972bfe 100644 --- a/internal/app/progress_bars.go +++ b/internal/app/progress_bars.go @@ -64,7 +64,7 @@ func (history *ProgressBarHistory) report(id atspi.ObjectID, percentage float64, // Handle progress before ordinary focused-object filtering. This path never // changes window ownership, native focus, review or browser mode. -func (handler *accessibilityEventHandler) handle_progress_bar(event atspi.Event) bool { +func (handler *accessibilityEventHandler) handleProgressBar(event atspi.Event) bool { percentage, shaderProgress := webscripts.ShaderProgress(event.Source.ApplicationProcess, event.Type, event.Source.Role, event.Source.Name) if !shaderProgress && (!isValueChangeEvent(event.Type) || event.Source.Role != "progress bar") { return false diff --git a/internal/app/progress_bars_test.go b/internal/app/progress_bars_test.go index 94e439d..d6f2dff 100644 --- a/internal/app/progress_bars_test.go +++ b/internal/app/progress_bars_test.go @@ -57,7 +57,7 @@ func TestSteamShaderProgressUsesSharedOutputAndGates(t *testing.T) { } for _, percentage := range []int{18, 18, 19, 100} { event.Source.Name = fmt.Sprintf("Processing Vulkan shaders (%d%%)", percentage) - if handled := handler.handle_progress_bar(event); handled != step.wantHandled { + if handled := handler.handleProgressBar(event); handled != step.wantHandled { t.Fatalf("handled=%t, want %t", handled, step.wantHandled) } } @@ -96,7 +96,7 @@ func TestProgressSecureEpochAndBrailleGates(t *testing.T) { state.current = event.Source handler := &accessibilityEventHandler{state: state, live: live, speech: speech, brailleOutput: frames, focusGate: gate} gate.secure.Store(true) - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(speech.requests) != 0 || len(frames.frames) != 0 { t.Fatal("progress bypassed secure input") } @@ -104,12 +104,12 @@ func TestProgressSecureEpochAndBrailleGates(t *testing.T) { handler.foreground = &titleProbeSource{} state.foregroundState.Epoch = 2 event.Foreground.Epoch = 1 - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(speech.requests) != 0 || len(frames.frames) != 0 { t.Fatal("stale epoch produced progress output") } event.Foreground.Epoch = 2 - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(speech.requests) != 1 || len(frames.frames) != 1 { t.Fatal("displayed progress failed to update") } @@ -117,7 +117,7 @@ func TestProgressSecureEpochAndBrailleGates(t *testing.T) { t.Fatalf("progress braille: %+v", frame) } event.Source.Path, event.Source.CurrentValue = "/other-progress", 50 - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(frames.frames) != 0 { t.Fatal("unrelated progress took over braille") } @@ -200,7 +200,7 @@ func TestProgressModesBackgroundAndFocusOwnership(t *testing.T) { handler := &accessibilityEventHandler{state: state, live: live, speech: speech} event := atspi.NewEvent(atspi.ValueChangedEvent, atspi.Snapshot{BusName: ":1.1", Path: "/progress", Role: "progress bar", ValueKnown: true, CurrentValue: 50.25, MaximumValue: 100, StatesKnown: true, Visible: true, Showing: true}) event.Window = state.owner.window - handled := handler.handle_progress_bar(event) + handled := handler.handleProgressBar(event) if mode == "off" { if handled || len(speech.requests) != 0 { t.Fatal("off bypassed focused-control fallback") @@ -225,23 +225,23 @@ func TestProgressModesBackgroundAndFocusOwnership(t *testing.T) { } event.Source.CurrentValue = 75 event.ForegroundMismatch = true - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(speech.requests) != 0 { t.Fatal("background reporting enabled by default") } settings.ProgressBar.ReportBackground = true live.Store(settings) - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(speech.requests) != 1 { t.Fatal("opted-in background reporting was lost") } <-speech.requests event.Source.Showing = false - if handler.handle_progress_bar(event) { + if handler.handleProgressBar(event) { t.Fatal("offscreen progress did not use focused fallback") } event.Source.Showing, event.Source.Indeterminate = true, true - if handler.handle_progress_bar(event) { + if handler.handleProgressBar(event) { t.Fatal("indeterminate progress generated output") } }) diff --git a/internal/app/progress_browser_native_test.go b/internal/app/progress_browser_native_test.go index 004efac..c6cd99e 100644 --- a/internal/app/progress_browser_native_test.go +++ b/internal/app/progress_browser_native_test.go @@ -64,7 +64,7 @@ focused: if seen[event.Source.Name] { continue } - if !handler.handle_progress_bar(event) || len(speech.requests) != 1 { + if !handler.handleProgressBar(event) || len(speech.requests) != 1 { t.Fatalf("web progress was lost: %+v", event) } request := <-speech.requests diff --git a/internal/app/progress_native_test.go b/internal/app/progress_native_test.go index 8ab98d6..07e406f 100644 --- a/internal/app/progress_native_test.go +++ b/internal/app/progress_native_test.go @@ -98,7 +98,7 @@ func TestNativeProgressBars(t *testing.T) { t.Fatalf("foreground progress capture: %+v", event) } state.owner.window, state.owner.applicationBus = event.Window, event.Source.BusName - if !handler.handle_progress_bar(event) { + if !handler.handleProgressBar(event) { t.Fatal("foreground progress was lost") } request := <-speech.requests @@ -110,19 +110,19 @@ func TestNativeProgressBars(t *testing.T) { if !event.ForegroundMismatch { t.Fatal("native background progress was not identified") } - handler.handle_progress_bar(event) + handler.handleProgressBar(event) if len(speech.requests) != 0 { t.Fatal("background output enabled by default") } settings.ProgressBar.ReportBackground = true live.Store(settings) - handler.handle_progress_bar(event) + handler.handleProgressBar(event) request = <-speech.requests if request.Text != "75 percent" || len(request.Sound) != 1 { t.Fatalf("background output: %+v", request) } event = update(0.9, true) - if event.Source.Showing || handler.handle_progress_bar(event) { + if event.Source.Showing || handler.handleProgressBar(event) { t.Fatal("hidden progress generated automatic output") } } diff --git a/internal/app/progress_settings.go b/internal/app/progress_settings.go index e907ded..f42255c 100644 --- a/internal/app/progress_settings.go +++ b/internal/app/progress_settings.go @@ -9,7 +9,7 @@ import "git.stormux.org/storm/cthulhu/internal/config" // The preferences worker owns shortcut changes, just like GUI changes. // Follow NVDA+U's off -> speak -> beep -> both -> off order. Saving remains // explicit; application profiles continue to inherit unchanged global values. -func (worker *preferencesWorker) cycle_progress_output() { +func (worker *preferencesWorker) cycleProgressOutput() { next := worker.settings message := "" switch next.ProgressBar.OutputMode { @@ -31,6 +31,6 @@ func (worker *preferencesWorker) cycle_progress_output() { } worker.setGlobalSettings(profileNext) } - worker.commit_settings(next) + worker.commitSettings(next) worker.announceSpeechSetting(message) } diff --git a/internal/app/radio_sound.go b/internal/app/radio_sound.go index 6a04615..5569a8a 100644 --- a/internal/app/radio_sound.go +++ b/internal/app/radio_sound.go @@ -22,7 +22,7 @@ type pendingRadioSound struct { inputSequence uint64 } -func (presenter *eventPresenter) coalesce_radio_sound(event atspi.Event, cues []sound.Cue) []sound.Cue { +func (presenter *eventPresenter) coalesceRadioSound(event atspi.Event, cues []sound.Cue) []sound.Cue { pending := &presenter.state.pending.radioSound if isFocusGainEvent(event) && event.Source.ID() != pending.event.Source.ID() { pending.clear() @@ -53,7 +53,7 @@ func (presenter *eventPresenter) coalesce_radio_sound(event atspi.Event, cues [] return cues } -func (presenter *eventPresenter) flush_radio_sound(gate *focusGate) { +func (presenter *eventPresenter) flushRadioSound(gate *focusGate) { pending := &presenter.state.pending.radioSound sequence := pending.inputSequence event, _ := pending.take() diff --git a/internal/app/radio_sound_test.go b/internal/app/radio_sound_test.go index 69fea4e..f9e9379 100644 --- a/internal/app/radio_sound_test.go +++ b/internal/app/radio_sound_test.go @@ -16,7 +16,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/sound" ) -func radio_sound_fixture(t *testing.T) (*eventPresenter, *fakeSpeechQueue, func(atspi.Event)) { +func radioSoundFixture(t *testing.T) (*eventPresenter, *fakeSpeechQueue, func(atspi.Event)) { t.Helper() logger := slog.New(slog.DiscardHandler) state := &eventLoopState{} @@ -37,7 +37,7 @@ func radio_sound_fixture(t *testing.T) (*eventPresenter, *fakeSpeechQueue, func( } func TestRadioFocusSoundCoalescesSelectionWithoutDelayingLabel(t *testing.T) { - presenter, queue, present := radio_sound_fixture(t) + presenter, queue, present := radioSoundFixture(t) option := atspi.Snapshot{BusName: ":1.7", Path: "/radio", Role: "radio button", Name: "Laptop", Mnemonic: "l"} present(atspi.NewEvent(atspi.FocusEvent, option)) request := <-queue.requests @@ -72,7 +72,7 @@ func TestRadioFocusSoundCoalescesSelectionWithoutDelayingLabel(t *testing.T) { func TestRadioFocusSoundRetiresStalePendingState(t *testing.T) { for _, change := range []string{"none", "focus", "input", "window", "lock", "handoff", "defunct", "disabled"} { t.Run(change, func(t *testing.T) { - presenter, queue, present := radio_sound_fixture(t) + presenter, queue, present := radioSoundFixture(t) option := atspi.Snapshot{BusName: ":1.7", Path: "/radio", Role: "radio button", Name: "Option"} present(atspi.NewEvent(atspi.FocusEvent, option)) <-queue.requests @@ -94,7 +94,7 @@ func TestRadioFocusSoundRetiresStalePendingState(t *testing.T) { case "disabled": presenter.state.presentationOptions.EnableSound = false } - presenter.flush_radio_sound(gate) + presenter.flushRadioSound(gate) if change != "none" { if len(queue.requests) != 0 { t.Fatal("retired focus emitted a delayed sound") @@ -110,7 +110,7 @@ func TestRadioFocusSoundRetiresStalePendingState(t *testing.T) { } func TestProcessEventsFlushesUncheckedRadioSound(t *testing.T) { - presenter, queue, _ := radio_sound_fixture(t) + presenter, queue, _ := radioSoundFixture(t) adapter := &fakeAdapter{events: make(chan atspi.Event, 1)} ctx, cancel := context.WithCancel(t.Context()) done := make(chan error, 1) @@ -135,12 +135,12 @@ func TestProcessEventsFlushesUncheckedRadioSound(t *testing.T) { } func TestDeferredRadioSoundPreservesUnavailableCueFallback(t *testing.T) { - presenter, queue, present := radio_sound_fixture(t) + presenter, queue, present := radioSoundFixture(t) present(atspi.NewEvent(atspi.FocusEvent, atspi.Snapshot{BusName: ":1.7", Path: "/radio", Role: "radio button", Name: "Option"})) <-queue.requests presenter.state.presentationOptions.SoundCueAvailable = func(string) bool { return false } presenter.speech = outputQueue{speech: queue, sounds: rejectingSound{}} - presenter.flush_radio_sound(nil) + presenter.flushRadioSound(nil) if request := <-queue.requests; request.Text != "not selected" { t.Fatalf("missing state-sound fallback: %+v", request) } diff --git a/internal/app/read_all.go b/internal/app/read_all.go index 9661d07..d5b8a2c 100644 --- a/internal/app/read_all.go +++ b/internal/app/read_all.go @@ -46,7 +46,7 @@ func presentReadAllResult(logger *slog.Logger, speech speechEnqueuer, result rev // One request owns the original observation ticket. Conservatively // keep the entire reading private if any spoken line is sensitive // or lacks source metadata, including sentence-mode continuations. - if source := document_line_speech_origin(line); source != speechOriginLocal { + if source := documentLineSpeechOrigin(line); source != speechOriginLocal { origin = source } var began func() @@ -62,9 +62,9 @@ func presentReadAllResult(logger *slog.Logger, speech speechEnqueuer, result rev chunks = append(chunks, readAllLineParts(value, began, options.SayAllStyle)...) began = nil } - chunks[0].Line = document_speech_line(line) + chunks[0].Line = documentSpeechLine(line) for index := range chunks { - chunks[index].VoiceType = document_line_voice(line) + chunks[index].VoiceType = documentLineVoice(line) } chunks[0].Context = line.Context parts = append(parts, chunks...) diff --git a/internal/app/reading_context.go b/internal/app/reading_context.go index c38fb0a..bffcaa9 100644 --- a/internal/app/reading_context.go +++ b/internal/app/reading_context.go @@ -12,13 +12,13 @@ import ( "git.stormux.org/storm/cthulhu/internal/review" ) -func (worker *speechWorker) context_messages(ancestors []atspi.Snapshot) []string { - return worker.context_messages_for(ancestors, false) +func (worker *speechWorker) contextMessages(ancestors []atspi.Snapshot) []string { + return worker.contextMessagesFor(ancestors, false) } -func (worker *speechWorker) context_messages_for(ancestors []atspi.Snapshot, sayAll bool) []string { +func (worker *speechWorker) contextMessagesFor(ancestors []atspi.Snapshot, sayAll bool) []string { var messages []string - for _, message := range worker.context_announcements_for(ancestors, sayAll) { + for _, message := range worker.contextAnnouncementsFor(ancestors, sayAll) { messages = append(messages, message.text) } return messages @@ -29,7 +29,7 @@ type readingContextMessage struct { leaving bool } -func (worker *speechWorker) context_announcements_for(ancestors []atspi.Snapshot, sayAll bool) []readingContextMessage { +func (worker *speechWorker) contextAnnouncementsFor(ancestors []atspi.Snapshot, sayAll bool) []readingContextMessage { if ancestors == nil || worker.reading == nil { return nil } @@ -90,16 +90,16 @@ func (worker *speechWorker) context_announcements_for(ancestors []atspi.Snapshot return messages } -func (worker *speechWorker) deliver_context(ctx context.Context, request speechRequest) error { +func (worker *speechWorker) deliverContext(ctx context.Context, request speechRequest) error { if request.ResetContext { worker.speechContext = nil worker.speechContextObservation = nil return nil } - return worker.deliver_context_for(ctx, request, request.Context, false) + return worker.deliverContextFor(ctx, request, request.Context, false) } -func (browser *browserModeController) speech_context_enabled() bool { +func (browser *browserModeController) speechContextEnabled() bool { return browser != nil && browser.ready && browser.mode == review.BrowseMode && browser.document.Valid() } @@ -115,15 +115,15 @@ func (queue contextSpeechQueue) Enqueue(request speechRequest) { queue.speechEnqueuer.Enqueue(request) } -func (worker *speechWorker) deliver_context_for(ctx context.Context, request speechRequest, ancestors []atspi.Snapshot, sayAll bool) error { +func (worker *speechWorker) deliverContextFor(ctx context.Context, request speechRequest, ancestors []atspi.Snapshot, sayAll bool) error { previousObservation := worker.speechContextObservation - messages := worker.context_announcements_for(ancestors, sayAll) + messages := worker.contextAnnouncementsFor(ancestors, sayAll) if ancestors != nil && worker.reading != nil { // Source classification precedes presentation filtering. Independently // check every retained context, including its unfiltered ancestry. - eligible := exportable_speech(request) + eligible := exportableSpeech(request) for _, ancestor := range ancestors { - eligible = eligible && accessibility_speech_origin(ancestor) == speechOriginLocal + eligible = eligible && accessibilitySpeechOrigin(ancestor) == speechOriginLocal } if eligible { worker.speechContextObservation = request.observation @@ -140,7 +140,7 @@ func (worker *speechWorker) deliver_context_for(ctx context.Context, request spe delivery.observation = previousObservation } worker.logDelivery(ctx, delivery, message.text, -1) - worker.observe_speech(ctx, delivery, message.text, false) + worker.observeSpeech(ctx, delivery, message.text, false) if voiced, ok := worker.speaker.(interface { SpeakVoice(context.Context, string, string) error }); ok { @@ -154,7 +154,7 @@ func (worker *speechWorker) deliver_context_for(ctx context.Context, request spe return nil } -func document_line_voice(line atspi.DocumentLine) string { +func documentLineVoice(line atspi.DocumentLine) string { for _, content := range line.Contents { if content.Snapshot.Role == "link" { return "hyperlink" @@ -163,7 +163,7 @@ func document_line_voice(line atspi.DocumentLine) string { return "default" } -func ancestor_voice(ancestors []atspi.Snapshot) string { +func ancestorVoice(ancestors []atspi.Snapshot) string { for _, ancestor := range ancestors { if ancestor.Role == "link" { return "hyperlink" diff --git a/internal/app/reading_preferences_test.go b/internal/app/reading_preferences_test.go index e47d996..20012ff 100644 --- a/internal/app/reading_preferences_test.go +++ b/internal/app/reading_preferences_test.go @@ -41,7 +41,7 @@ func TestIndentationTracksRawSpacingAndModes(t *testing.T) { {" text", "text", "text", 0}, } { cues = nil - if got := worker.line_text(tc.spoken, &speechLine{Object: id, Raw: tc.raw}); got != tc.want { + if got := worker.lineText(tc.spoken, &speechLine{Object: id, Raw: tc.raw}); got != tc.want { t.Fatalf("%q: %q, want %q", tc.raw, got, tc.want) } if tc.frequency == 0 { @@ -53,16 +53,16 @@ func TestIndentationTracksRawSpacingAndModes(t *testing.T) { } } reading.IndentationPresentationMode = "beeps" - if got := worker.line_text("text", &speechLine{Object: id, Raw: " text"}); got != "text" { + if got := worker.lineText("text", &speechLine{Object: id, Raw: " text"}); got != "text" { t.Fatal("beeps mode spoke indentation") } reading.OnlySpeakDisplayedText = true cues = nil - if got := worker.line_text("text", &speechLine{Object: id, Raw: " text"}); got != "text" || len(cues) != 0 { + if got := worker.lineText("text", &speechLine{Object: id, Raw: " text"}); got != "text" || len(cues) != 0 { t.Fatal("displayed-text mode presented indentation") } reading.OnlySpeakDisplayedText, reading.EnableIndentation = false, false - if got := worker.line_text("text", &speechLine{Object: id, Raw: "text"}); got != "text" { + if got := worker.lineText("text", &speechLine{Object: id, Raw: "text"}); got != "text" { t.Fatal("disabled indentation spoke") } } @@ -73,21 +73,21 @@ func TestNavigationContextFlagsAndTransitions(t *testing.T) { worker.reading = func() config.ReadingSettings { return reading } list := atspi.Snapshot{BusName: ":1.42", Path: "/list", Role: "list", Name: "Items"} panel := atspi.Snapshot{BusName: ":1.42", Path: "/panel", Role: "panel", Name: "Options"} - if got := worker.context_messages([]atspi.Snapshot{list, panel}); !reflect.DeepEqual(got, []string{"Options panel", "Items list"}) { + if got := worker.contextMessages([]atspi.Snapshot{list, panel}); !reflect.DeepEqual(got, []string{"Options panel", "Items list"}) { t.Fatalf("enter context = %v", got) } - if got := worker.context_messages([]atspi.Snapshot{list, panel}); len(got) != 0 { + if got := worker.contextMessages([]atspi.Snapshot{list, panel}); len(got) != 0 { t.Fatal("unchanged context repeated") } reading.SpeakContextList = false - if got := worker.context_messages([]atspi.Snapshot{panel}); len(got) != 0 { + if got := worker.contextMessages([]atspi.Snapshot{panel}); len(got) != 0 { t.Fatal("disabled list exit announced") } - if got := worker.context_messages([]atspi.Snapshot{}); !reflect.DeepEqual(got, []string{"Leaving Options panel."}) { + if got := worker.contextMessages([]atspi.Snapshot{}); !reflect.DeepEqual(got, []string{"Leaving Options panel."}) { t.Fatalf("exit context = %v", got) } reading.OnlySpeakDisplayedText = true - if got := worker.context_messages([]atspi.Snapshot{list, panel}); len(got) != 0 { + if got := worker.contextMessages([]atspi.Snapshot{list, panel}); len(got) != 0 { t.Fatal("displayed-text mode announced context") } } @@ -99,12 +99,12 @@ func TestListContextCountFollowsSpeechVerbosity(t *testing.T) { worker.reading = func() config.ReadingSettings { return reading } worker.verbosity = func() int { return verbosity } list := atspi.Snapshot{BusName: ":1.42", Path: "/list", Role: "list", Name: "Tasks", ChildCount: 3, ChildCountKnown: true} - if got := worker.context_messages([]atspi.Snapshot{list}); !reflect.DeepEqual(got, []string{"Tasks, 3 items"}) { + if got := worker.contextMessages([]atspi.Snapshot{list}); !reflect.DeepEqual(got, []string{"Tasks, 3 items"}) { t.Fatalf("verbose list context = %v", got) } - worker.context_messages([]atspi.Snapshot{}) + worker.contextMessages([]atspi.Snapshot{}) verbosity = 0 - if got := worker.context_messages([]atspi.Snapshot{list}); !reflect.DeepEqual(got, []string{"Tasks list"}) { + if got := worker.contextMessages([]atspi.Snapshot{list}); !reflect.DeepEqual(got, []string{"Tasks list"}) { t.Fatalf("brief list context = %v", got) } } @@ -125,16 +125,16 @@ func TestSayAllContextFlagsAreIndependentOfNavigation(t *testing.T) { worker := newSpeechWorker(slog.New(slog.DiscardHandler), nil) worker.reading = func() config.ReadingSettings { return reading } ancestor := atspi.Snapshot{BusName: ":1.42", Path: "/context", Role: test.role} - if got := worker.context_messages_for([]atspi.Snapshot{ancestor}, true); len(got) != 1 { + if got := worker.contextMessagesFor([]atspi.Snapshot{ancestor}, true); len(got) != 1 { t.Fatalf("%s Say All context = %v", test.role, got) } test.disable(&reading) worker.speechContext = nil - if got := worker.context_messages_for([]atspi.Snapshot{ancestor}, true); len(got) != 0 { + if got := worker.contextMessagesFor([]atspi.Snapshot{ancestor}, true); len(got) != 0 { t.Fatalf("%s disabled Say All context = %v", test.role, got) } worker.speechContext = nil - if got := worker.context_messages([]atspi.Snapshot{ancestor}); len(got) != 1 { + if got := worker.contextMessages([]atspi.Snapshot{ancestor}); len(got) != 1 { t.Fatalf("%s navigation context changed = %v", test.role, got) } } @@ -150,7 +150,7 @@ func TestNavigationContextCollapsesRepeatedPanels(t *testing.T) { } check := func(ancestors []atspi.Snapshot, want []string) { t.Helper() - if got := worker.context_messages(ancestors); !reflect.DeepEqual(got, want) { + if got := worker.contextMessages(ancestors); !reflect.DeepEqual(got, want) { t.Fatalf("context = %v, want %v", got, want) } } @@ -255,7 +255,7 @@ func TestTypedCapitalRetainsCharacterAndCustomEcho(t *testing.T) { t.Fatalf("capital insertion routing = %+v", request) } // Document spelling must retain case after replacing letters with words. - set_review_spelling(&request, "Aa", review.FlatPhonetic) + setReviewSpelling(&request, "Aa", review.FlatPhonetic) if !reflect.DeepEqual(request.SpellingVoices, []string{"uppercase", ""}) { t.Fatal("phonetic spelling lost uppercase voice") } diff --git a/internal/app/reading_speech_test.go b/internal/app/reading_speech_test.go index 4bfd720..3f890de 100644 --- a/internal/app/reading_speech_test.go +++ b/internal/app/reading_speech_test.go @@ -45,7 +45,7 @@ func TestPronunciationPreservesCharacterReadingAndSpelling(t *testing.T) { {"echo", speechRequest{Text: "a", Character: true, CustomEcho: true}, []string{"a"}}, {"spelling", func() speechRequest { request := speechRequest{Text: "Aa"} - set_review_spelling(&request, "Aa", review.FlatSpell) + setReviewSpelling(&request, "Aa", review.FlatSpell) return request }(), []string{"A", "a"}}, {"word", speechRequest{Text: "a"}, []string{"article"}}, diff --git a/internal/app/remote.go b/internal/app/remote.go index 26dee86..4cad5ea 100644 --- a/internal/app/remote.go +++ b/internal/app/remote.go @@ -78,7 +78,7 @@ func (presenter remoteSpeech) RuntimeStateSnapshot() string { } func (presenter remoteSpeech) PresentAccessibleEvent(event remote.AccessibleEvent) bool { - return presenter.wine != nil && presenter.wine.present_event(event, presenter.presentWineEditor) + return presenter.wine != nil && presenter.wine.presentEvent(event, presenter.presentWineEditor) } func (presenter remoteSpeech) PresentMessage(message string) bool { diff --git a/internal/app/remote_speech_render.go b/internal/app/remote_speech_render.go index 0ba7117..bff7c47 100644 --- a/internal/app/remote_speech_render.go +++ b/internal/app/remote_speech_render.go @@ -23,7 +23,7 @@ type remoteSpeechUtterance struct { fragments []speech.Fragment } -func prepare_remote_utterance(frames []tentaclewire.RemoteSpeech) (remoteSpeechUtterance, error) { +func prepareRemoteUtterance(frames []tentaclewire.RemoteSpeech) (remoteSpeechUtterance, error) { var utterance remoteSpeechUtterance if len(frames) == 0 || len(frames) > tentaclewire.RemoteSpeechQueueSize { return utterance, errors.New("invalid Remote speech assembly") diff --git a/internal/app/remote_speech_render_test.go b/internal/app/remote_speech_render_test.go index 45379cb..eb69d93 100644 --- a/internal/app/remote_speech_render_test.go +++ b/internal/app/remote_speech_render_test.go @@ -16,11 +16,11 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) -func remote_render_frame(priority int, parts ...tentaclewire.RemoteSpeechPart) tentaclewire.RemoteSpeech { +func remoteRenderFrame(priority int, parts ...tentaclewire.RemoteSpeechPart) tentaclewire.RemoteSpeech { return tentaclewire.RemoteSpeech{Kind: "speak", Priority: priority, Parts: parts} } -func (server *isolatedVoiceServer) next_utterance(t *testing.T) isolatedVoiceUtterance { +func (server *isolatedVoiceServer) nextUtterance(t *testing.T) isolatedVoiceUtterance { t.Helper() select { case utterance := <-server.queued: @@ -31,7 +31,7 @@ func (server *isolatedVoiceServer) next_utterance(t *testing.T) isolatedVoiceUtt } } -func (server *isolatedVoiceServer) end_utterance(t *testing.T, utterance isolatedVoiceUtterance) { +func (server *isolatedVoiceServer) endUtterance(t *testing.T, utterance isolatedVoiceUtterance) { t.Helper() server.mutex.Lock() connection := server.connections[utterance.id] @@ -40,7 +40,7 @@ func (server *isolatedVoiceServer) end_utterance(t *testing.T, utterance isolate connection.send(fmt.Sprintf("702-1\r\n702-%d\r\n702 END\r\n", utterance.id)) } -func remote_render_result(t *testing.T, finished <-chan error) error { +func remoteRenderResult(t *testing.T, finished <-chan error) error { t.Helper() select { case err := <-finished: @@ -52,21 +52,21 @@ func remote_render_result(t *testing.T, finished <-chan error) error { } func TestRemoteSpeechRenderingPreservesAssemblyAndLiteralMetadata(t *testing.T) { - speaker, server := isolated_voice_fixture(t) - voice, err := speaker.open_remote_voice(t.Context()) + speaker, server := isolatedVoiceFixture(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } frames := []tentaclewire.RemoteSpeech{ - remote_render_frame(2, tentaclewire.RemoteSpeechPart{Text: " hello"}), - remote_render_frame(2, + remoteRenderFrame(2, tentaclewire.RemoteSpeechPart{Text: " hello"}), + remoteRenderFrame(2, tentaclewire.RemoteSpeechPart{Text: " world\t"}, tentaclewire.RemoteSpeechPart{Text: "aa", Characters: true}, tentaclewire.RemoteSpeechPart{Text: "é\n.\nQUIT\r\n..literal\rend ", Language: "fr"}, tentaclewire.RemoteSpeechPart{End: true}, tentaclewire.RemoteSpeechPart{Text: " again "}), } - utterance, err := prepare_remote_utterance(frames) + utterance, err := prepareRemoteUtterance(frames) if err != nil { t.Fatal(err) } @@ -81,7 +81,7 @@ func TestRemoteSpeechRenderingPreservesAssemblyAndLiteralMetadata(t *testing.T) {"é\n.\nQUIT\n..literal\nend ", "fr", "off"}, {" again ", "en-GB", "off"}, } { - got := server.next_utterance(t) + got := server.nextUtterance(t) if got.text != expected.text || got.language != expected.language || got.spelling != expected.spelling || got.ssml != "off" || got.module != "default" || got.voiceType != "FEMALE2" || got.synthesis != "" { t.Fatalf("fragment %d = %#v; want %#v in plain-text mode", index, got, expected) } @@ -90,9 +90,9 @@ func TestRemoteSpeechRenderingPreservesAssemblyAndLiteralMetadata(t *testing.T) t.Fatal("queue acknowledgement finished assembly") default: } - server.end_utterance(t, got) + server.endUtterance(t, got) } - if err := remote_render_result(t, finished); err != nil { + if err := remoteRenderResult(t, finished); err != nil { t.Fatal(err) } // Successful rendering restores the effective server default and leaves @@ -100,35 +100,35 @@ func TestRemoteSpeechRenderingPreservesAssemblyAndLiteralMetadata(t *testing.T) large := strings.Repeat("界 ", 1200) frames = nil for _, part := range []string{large[:3000], large[3000:]} { - frames = append(frames, remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: part})) + frames = append(frames, remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: part})) } - utterance, err = prepare_remote_utterance(frames) + utterance, err = prepareRemoteUtterance(frames) if err != nil { t.Fatal(err) } go func() { finished <- voice.SpeakUtteranceAndWait(t.Context(), utterance) }() - got := server.next_utterance(t) + got := server.nextUtterance(t) if got.text != large || got.language != "en-GB" || got.spelling != "off" { t.Fatal("next assembly inherited state or lost split text") } - server.end_utterance(t, got) - if err := remote_render_result(t, finished); err != nil { + server.endUtterance(t, got) + if err := remoteRenderResult(t, finished); err != nil { t.Fatal(err) } } func TestRemoteSpeechRenderingRestoresNamedVoice(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) settings := speaker.settings settings.DefaultVoice.Family = &config.VoiceFamily{Name: "configured voice"} if err := speaker.UpdateConfiguration(t.Context(), settings); err != nil { t.Fatal(err) } - voice, err := speaker.open_remote_voice(t.Context()) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } - utterance, err := prepare_remote_utterance([]tentaclewire.RemoteSpeech{remote_render_frame(0, + utterance, err := prepareRemoteUtterance([]tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "default"}, tentaclewire.RemoteSpeechPart{Text: "foreign", Language: "fr"}, tentaclewire.RemoteSpeechPart{Text: "restored"})}) @@ -138,13 +138,13 @@ func TestRemoteSpeechRenderingRestoresNamedVoice(t *testing.T) { finished := make(chan error, 1) go func() { finished <- voice.SpeakUtteranceAndWait(t.Context(), utterance) }() for _, named := range []string{"configured voice", "", "configured voice"} { - got := server.next_utterance(t) + got := server.nextUtterance(t) if got.synthesis != named || got.module != "default" || named == "" && got.voiceType != "MALE1" { t.Fatalf("language switch did not scope the named voice: %#v", got) } - server.end_utterance(t, got) + server.endUtterance(t, got) } - if err := remote_render_result(t, finished); err != nil { + if err := remoteRenderResult(t, finished); err != nil { t.Fatal(err) } } @@ -159,15 +159,15 @@ func TestRemoteSpeechRenderingRejectsUnknownBackendDefaults(t *testing.T) { {"GET VOICE_TYPE", "251-NO_VOICE\r\n251 OK\r\n"}, } { t.Run(test.command+test.reply, func(t *testing.T) { - speaker, server := isolated_voice_fixture(t) - voice, err := speaker.open_remote_voice(t.Context()) + speaker, server := isolatedVoiceFixture(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } server.mutex.Lock() server.queryReplies = map[string]string{test.command: test.reply} server.mutex.Unlock() - utterance, err := prepare_remote_utterance([]tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "never queued"})}) + utterance, err := prepareRemoteUtterance([]tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "never queued"})}) if err != nil { t.Fatal(err) } @@ -187,12 +187,12 @@ func TestRemoteSpeechRenderingRejectsUnknownBackendDefaults(t *testing.T) { } func TestRemoteSpeechRenderingCancellationDuringMetadata(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) if err := speaker.SpeakVoice(t.Context(), "local status", "system"); err != nil { t.Fatal(err) } - server.next_utterance(t) - voice, err := speaker.open_remote_voice(t.Context()) + server.nextUtterance(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } @@ -201,7 +201,7 @@ func TestRemoteSpeechRenderingCancellationDuringMetadata(t *testing.T) { server.mutex.Lock() server.holdCommand, server.held, server.resume = "GET LANGUAGE", held, resume server.mutex.Unlock() - utterance, err := prepare_remote_utterance([]tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "never queued"})}) + utterance, err := prepareRemoteUtterance([]tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "never queued"})}) if err != nil { t.Fatal(err) } @@ -218,7 +218,7 @@ func TestRemoteSpeechRenderingCancellationDuringMetadata(t *testing.T) { if err := voice.Cancel(t.Context()); err != nil { t.Fatal(err) } - if err := remote_render_result(t, finished); !errors.Is(err, context.Canceled) { + if err := remoteRenderResult(t, finished); !errors.Is(err, context.Canceled) { t.Fatal("metadata cancellation was lost", err) } if id, _ := server.pending("local status"); id == 0 { @@ -234,20 +234,20 @@ func TestRemoteSpeechRenderingCancellationDuringMetadata(t *testing.T) { func TestRemoteSpeechRenderingCancellationKeepsLocalOutputAndDropsSuffix(t *testing.T) { for _, operation := range []string{"remote", "caller", "configuration"} { t.Run(operation, func(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) if err := speaker.SpeakVoice(t.Context(), "local status", "system"); err != nil { t.Fatal(err) } - server.next_utterance(t) + server.nextUtterance(t) if err := speaker.SpeakEcho(t.Context(), "local echo"); err != nil { t.Fatal(err) } - server.next_utterance(t) - voice, err := speaker.open_remote_voice(t.Context()) + server.nextUtterance(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } - utterance, err := prepare_remote_utterance([]tentaclewire.RemoteSpeech{remote_render_frame(0, + utterance, err := prepareRemoteUtterance([]tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "prefix", Characters: true, Language: "fr"}, tentaclewire.RemoteSpeechPart{End: true}, tentaclewire.RemoteSpeechPart{Text: "suffix"})}) if err != nil { @@ -257,7 +257,7 @@ func TestRemoteSpeechRenderingCancellationKeepsLocalOutputAndDropsSuffix(t *test defer cancel() finished := make(chan error, 1) go func() { finished <- voice.SpeakUtteranceAndWait(ctx, utterance) }() - server.next_utterance(t) + server.nextUtterance(t) switch operation { case "remote": err = voice.Cancel(t.Context()) @@ -266,12 +266,12 @@ func TestRemoteSpeechRenderingCancellationKeepsLocalOutputAndDropsSuffix(t *test case "configuration": // A committed replacement is modeled without cancelling local // speech: retirement must target only the old isolated handle. - speaker.retire_remote_voice(speaker.settings) + speaker.retireRemoteVoice(speaker.settings) } if err != nil { t.Fatal(err) } - if err := remote_render_result(t, finished); !errors.Is(err, context.Canceled) { + if err := remoteRenderResult(t, finished); !errors.Is(err, context.Canceled) { t.Fatal("rendering survived cancellation", err) } for _, text := range []string{"local status", "local echo"} { @@ -287,7 +287,7 @@ func TestRemoteSpeechRenderingCancellationKeepsLocalOutputAndDropsSuffix(t *test if voice.ctx.Err() == nil { t.Fatal("partially rendered handle was reused") } - if _, err := speaker.open_remote_voice(t.Context()); err != nil { + if _, err := speaker.openRemoteVoice(t.Context()); err != nil { t.Fatal("retired renderer retained ownership", err) } }) @@ -295,34 +295,34 @@ func TestRemoteSpeechRenderingCancellationKeepsLocalOutputAndDropsSuffix(t *test } func TestRemoteSpeechRenderingRejectsWholeInvalidAssembly(t *testing.T) { - valid := remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "prefix"}) + valid := remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "prefix"}) for _, frames := range [][]tentaclewire.RemoteSpeech{ nil, {valid, {Kind: "cancel"}}, - {valid, remote_render_frame(1, tentaclewire.RemoteSpeechPart{Text: "changed priority"})}, - {valid, remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "bad", Language: "fr\nQUIT"})}, - {valid, remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: strings.Repeat("x", 6200)})}, + {valid, remoteRenderFrame(1, tentaclewire.RemoteSpeechPart{Text: "changed priority"})}, + {valid, remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "bad", Language: "fr\nQUIT"})}, + {valid, remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: strings.Repeat("x", 6200)})}, append(make([]tentaclewire.RemoteSpeech, 64), valid), } { - if _, err := prepare_remote_utterance(frames); err == nil { + if _, err := prepareRemoteUtterance(frames); err == nil { t.Fatal("invalid assembly admitted") } } // Each frame fits IPC, but the retained assembly exceeds the byte budget. frames := make([]tentaclewire.RemoteSpeech, 64) for index := range frames { - frames[index] = remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: strings.Repeat("x", 5000)}) + frames[index] = remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: strings.Repeat("x", 5000)}) } - if _, err := prepare_remote_utterance(frames); err == nil { + if _, err := prepareRemoteUtterance(frames); err == nil { t.Fatal("oversized assembly admitted") } for _, invalid := range []string{"bad\x00text", "bad\x1btext", "bad\x7ftext"} { - speaker, server := isolated_voice_fixture(t) - voice, err := speaker.open_remote_voice(t.Context()) + speaker, server := isolatedVoiceFixture(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } - utterance, err := prepare_remote_utterance([]tentaclewire.RemoteSpeech{valid, remote_render_frame(0, + utterance, err := prepareRemoteUtterance([]tentaclewire.RemoteSpeech{valid, remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{End: true}, tentaclewire.RemoteSpeechPart{Text: invalid})}) if err != nil { t.Fatal("wire-valid fixture rejected too early", err) @@ -339,12 +339,12 @@ func TestRemoteSpeechRenderingRejectsWholeInvalidAssembly(t *testing.T) { } func TestRemoteSpeechRenderingBackendRejectionAndEmptyBoundaries(t *testing.T) { - speaker, server := isolated_voice_fixture(t) - voice, err := speaker.open_remote_voice(t.Context()) + speaker, server := isolatedVoiceFixture(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } - utterance, err := prepare_remote_utterance([]tentaclewire.RemoteSpeech{remote_render_frame(0, + utterance, err := prepareRemoteUtterance([]tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{End: true}, tentaclewire.RemoteSpeechPart{End: true})}) if err != nil { t.Fatal(err) @@ -352,7 +352,7 @@ func TestRemoteSpeechRenderingBackendRejectionAndEmptyBoundaries(t *testing.T) { if err := voice.SpeakUtteranceAndWait(t.Context(), utterance); err != nil { t.Fatal(err) } - utterance, err = prepare_remote_utterance([]tentaclewire.RemoteSpeech{remote_render_frame(0, + utterance, err = prepareRemoteUtterance([]tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "never queued", Language: "rejected"})}) if err != nil { t.Fatal(err) diff --git a/internal/app/remote_speech_stream.go b/internal/app/remote_speech_stream.go index c1865b4..85d4bc2 100644 --- a/internal/app/remote_speech_stream.go +++ b/internal/app/remote_speech_stream.go @@ -40,9 +40,9 @@ type remoteSpeechStreamError struct { func (err *remoteSpeechStreamError) Error() string { return err.cause.Error() } func (err *remoteSpeechStreamError) Unwrap() error { return err.cause } -// run_remote_speech_playback supplies the isolated backend to the stream owner. +// runRemoteSpeechPlayback supplies the isolated backend to the stream owner. // The caller supplies original-lease policy and optional local-output admission. -func run_remote_speech_playback(ctx context.Context, speaker *configuredSpeaker, +func runRemoteSpeechPlayback(ctx context.Context, speaker *configuredSpeaker, incoming <-chan tentacle.RemoteSpeechDelivery, allow func(tentacle.RemoteSpeechDelivery) bool, admit remoteSpeechAdmission, logger *slog.Logger) error { if speaker == nil || allow == nil { @@ -62,11 +62,11 @@ func run_remote_speech_playback(ctx context.Context, speaker *configuredSpeaker, } } defer closeVoice() - return run_remote_speech_stream(ctx, incoming, allow, admit, func(request context.Context, delivery tentacle.RemoteSpeechDelivery, utterance remoteSpeechUtterance) error { + return runRemoteSpeechStream(ctx, incoming, allow, admit, func(request context.Context, delivery tentacle.RemoteSpeechDelivery, utterance remoteSpeechUtterance) error { if voice == nil || voice.ctx.Err() != nil || voiceLease != delivery.Lease { closeVoice() var err error - voice, err = speaker.open_remote_voice(request) + voice, err = speaker.openRemoteVoice(request) if err != nil { return err } @@ -102,13 +102,13 @@ func run_remote_speech_playback(ctx context.Context, speaker *configuredSpeaker, }) } -// run_remote_speech_stream retains complete deliveries until cleanup. allow must +// runRemoteSpeechStream retains complete deliveries until cleanup. allow must // recheck original lease, focus and output policy without backend I/O. render // must honor cancellation, recheck policy after acquisition, and complete scoped // backend cleanup before returning. Neither callback may observe this output. // The caller must retire the session on error. A dequeue retains mailbox budget // until completion/discard, including while a cancelled renderer is closing. -func run_remote_speech_stream(ctx context.Context, incoming <-chan tentacle.RemoteSpeechDelivery, +func runRemoteSpeechStream(ctx context.Context, incoming <-chan tentacle.RemoteSpeechDelivery, allow func(tentacle.RemoteSpeechDelivery) bool, admit remoteSpeechAdmission, render func(context.Context, tentacle.RemoteSpeechDelivery, remoteSpeechUtterance) error) error { @@ -213,7 +213,7 @@ func run_remote_speech_stream(ctx context.Context, incoming <-chan tentacle.Remo continue } } - utterance, err := prepare_remote_utterance(delivery.Speeches) + utterance, err := prepareRemoteUtterance(delivery.Speeches) if err != nil { delivery.Release() return &remoteSpeechStreamError{lease: delivery.Lease, cause: err} diff --git a/internal/app/remote_speech_stream_test.go b/internal/app/remote_speech_stream_test.go index 02af02a..a09e5eb 100644 --- a/internal/app/remote_speech_stream_test.go +++ b/internal/app/remote_speech_stream_test.go @@ -36,7 +36,7 @@ type remoteStreamFixture struct { allowed atomic.Bool } -func remote_stream_fixture(t *testing.T, hold bool, admission ...remoteSpeechAdmission) *remoteStreamFixture { +func newRemoteStreamFixture(t *testing.T, hold bool, admission ...remoteSpeechAdmission) *remoteStreamFixture { t.Helper() ctx, cancel := context.WithCancel(t.Context()) f := &remoteStreamFixture{ctx: ctx, cancel: cancel, hold: hold, @@ -48,7 +48,7 @@ func remote_stream_fixture(t *testing.T, hold bool, admission ...remoteSpeechAdm admit = admission[0] } go func() { - f.done <- run_remote_speech_stream(ctx, f.incoming, func(tentacle.RemoteSpeechDelivery) bool { return f.allowed.Load() }, admit, + f.done <- runRemoteSpeechStream(ctx, f.incoming, func(tentacle.RemoteSpeechDelivery) bool { return f.allowed.Load() }, admit, func(ctx context.Context, _ tentacle.RemoteSpeechDelivery, utterance remoteSpeechUtterance) error { call := remoteStreamCall{ctx: ctx, utterance: utterance, finish: make(chan error, 1), stopped: make(chan struct{}), cleanup: make(chan struct{})} f.started <- call @@ -68,7 +68,7 @@ func remote_stream_fixture(t *testing.T, hold bool, admission ...remoteSpeechAdm return f } -func remote_stream_wait(t *testing.T, done <-chan struct{}) { +func remoteStreamWait(t *testing.T, done <-chan struct{}) { t.Helper() select { case <-done: @@ -79,10 +79,10 @@ func remote_stream_wait(t *testing.T, done <-chan struct{}) { func (f *remoteStreamFixture) send(t *testing.T, effect tentaclewire.RemoteSpeech) <-chan struct{} { t.Helper() - return f.send_delivery(t, f.ctx, f.lease, []tentaclewire.RemoteSpeech{effect}) + return f.sendDelivery(t, f.ctx, f.lease, []tentaclewire.RemoteSpeech{effect}) } -func (f *remoteStreamFixture) send_delivery(t *testing.T, ctx context.Context, lease tentaclewire.RemoteLease, frames []tentaclewire.RemoteSpeech) <-chan struct{} { +func (f *remoteStreamFixture) sendDelivery(t *testing.T, ctx context.Context, lease tentaclewire.RemoteLease, frames []tentaclewire.RemoteSpeech) <-chan struct{} { t.Helper() released := make(chan struct{}) var calls atomic.Int32 @@ -97,7 +97,7 @@ func (f *remoteStreamFixture) send_delivery(t *testing.T, ctx context.Context, l } func (f *remoteStreamFixture) speak(t *testing.T, text string, priority int) <-chan struct{} { - return f.send(t, remote_render_frame(priority, tentaclewire.RemoteSpeechPart{Text: text})) + return f.send(t, remoteRenderFrame(priority, tentaclewire.RemoteSpeechPart{Text: text})) } func (f *remoteStreamFixture) next(t *testing.T, text string) remoteStreamCall { @@ -117,20 +117,20 @@ func (f *remoteStreamFixture) next(t *testing.T, text string) remoteStreamCall { func (f *remoteStreamFixture) barrier(t *testing.T) { t.Helper() paused := false - remote_stream_wait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "pause", Paused: &paused})) + remoteStreamWait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "pause", Paused: &paused})) } func (f *remoteStreamFixture) stop(t *testing.T) { t.Helper() f.cancel() - err := remote_render_result(t, f.done) + err := remoteRenderResult(t, f.done) if !errors.Is(err, context.Canceled) { t.Fatalf("stream shutdown = %v", err) } } func TestRemoteSpeechStreamPriorityAndCleanup(t *testing.T) { - f := remote_stream_fixture(t, true) + f := newRemoteStreamFixture(t, true) firstRelease := f.speak(t, "active", 0) first := f.next(t, "active") normalRelease := f.speak(t, "normal", 0) @@ -142,7 +142,7 @@ func TestRemoteSpeechStreamPriorityAndCleanup(t *testing.T) { default: } nowRelease := f.speak(t, "now", 2) - remote_stream_wait(t, first.stopped) + remoteStreamWait(t, first.stopped) f.barrier(t) select { case <-firstRelease: @@ -153,7 +153,7 @@ func TestRemoteSpeechStreamPriorityAndCleanup(t *testing.T) { } close(first.cleanup) now := f.next(t, "now") - remote_stream_wait(t, firstRelease) + remoteStreamWait(t, firstRelease) secondNowRelease := f.speak(t, "second now", 2) f.barrier(t) select { @@ -169,7 +169,7 @@ func TestRemoteSpeechStreamPriorityAndCleanup(t *testing.T) { normal := f.next(t, "normal") normal.finish <- nil for _, release := range []<-chan struct{}{normalRelease, nextRelease, nowRelease, secondNowRelease} { - remote_stream_wait(t, release) + remoteStreamWait(t, release) } f.stop(t) } @@ -177,7 +177,7 @@ func TestRemoteSpeechStreamPriorityAndCleanup(t *testing.T) { func TestRemoteSpeechStreamCancelAndPause(t *testing.T) { for _, kind := range []string{"cancel", "pause"} { t.Run(kind, func(t *testing.T) { - f := remote_stream_fixture(t, true) + f := newRemoteStreamFixture(t, true) activeRelease := f.speak(t, "active", 0) active := f.next(t, "active") pendingRelease := f.speak(t, "discard pending", 0) @@ -186,15 +186,15 @@ func TestRemoteSpeechStreamCancelAndPause(t *testing.T) { paused := true effect.Paused = &paused } - remote_stream_wait(t, f.send(t, effect)) - remote_stream_wait(t, active.stopped) - remote_stream_wait(t, pendingRelease) + remoteStreamWait(t, f.send(t, effect)) + remoteStreamWait(t, active.stopped) + remoteStreamWait(t, pendingRelease) futureRelease := f.speak(t, "future", 0) close(active.cleanup) future := f.next(t, "future") - remote_stream_wait(t, activeRelease) + remoteStreamWait(t, activeRelease) future.finish <- nil - remote_stream_wait(t, futureRelease) + remoteStreamWait(t, futureRelease) f.stop(t) }) } @@ -203,52 +203,52 @@ func TestRemoteSpeechStreamCancelAndPause(t *testing.T) { func TestRemoteSpeechStreamFreshSpeechAfterPause(t *testing.T) { for _, cancelFirst := range []bool{false, true} { t.Run(map[bool]string{false: "speak", true: "cancel then speak"}[cancelFirst], func(t *testing.T) { - f := remote_stream_fixture(t, false) + f := newRemoteStreamFixture(t, false) paused := true - remote_stream_wait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "pause", Paused: &paused})) + remoteStreamWait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "pause", Paused: &paused})) if cancelFirst { - remote_stream_wait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "cancel"})) + remoteStreamWait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "cancel"})) } released := f.speak(t, "new navigation", 0) call := f.next(t, "new navigation") call.finish <- nil - remote_stream_wait(t, released) + remoteStreamWait(t, released) f.stop(t) }) } } func TestRemoteSpeechStreamRevocationAndReplacement(t *testing.T) { - f := remote_stream_fixture(t, true) + f := newRemoteStreamFixture(t, true) leaseContext, revoke := context.WithCancel(f.ctx) - firstRelease := f.send_delivery(t, leaseContext, f.lease, []tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "old"})}) + firstRelease := f.sendDelivery(t, leaseContext, f.lease, []tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "old"})}) first := f.next(t, "old") - pendingRelease := f.send_delivery(t, leaseContext, f.lease, []tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "old pending"})}) + pendingRelease := f.sendDelivery(t, leaseContext, f.lease, []tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "old pending"})}) f.barrier(t) revoke() - remote_stream_wait(t, first.stopped) - remote_stream_wait(t, pendingRelease) - remote_stream_wait(t, f.send_delivery(t, leaseContext, f.lease, []tentaclewire.RemoteSpeech{remote_render_frame(2, tentaclewire.RemoteSpeechPart{Text: "stale"})})) + remoteStreamWait(t, first.stopped) + remoteStreamWait(t, pendingRelease) + remoteStreamWait(t, f.sendDelivery(t, leaseContext, f.lease, []tentaclewire.RemoteSpeech{remoteRenderFrame(2, tentaclewire.RemoteSpeechPart{Text: "stale"})})) f.lease.Epoch++ newRelease := f.speak(t, "replacement", 0) f.barrier(t) close(first.cleanup) replacement := f.next(t, "replacement") - remote_stream_wait(t, firstRelease) + remoteStreamWait(t, firstRelease) replacement.finish <- nil - remote_stream_wait(t, newRelease) + remoteStreamWait(t, newRelease) f.stop(t) } func TestRemoteSpeechStreamEOFRetainsBudgetThroughCleanup(t *testing.T) { - f := remote_stream_fixture(t, true) + f := newRemoteStreamFixture(t, true) activeRelease := f.speak(t, "active", 0) active := f.next(t, "active") pendingRelease := f.speak(t, "pending", 0) f.barrier(t) close(f.incoming) - remote_stream_wait(t, active.stopped) - remote_stream_wait(t, pendingRelease) + remoteStreamWait(t, active.stopped) + remoteStreamWait(t, pendingRelease) select { case <-activeRelease: t.Fatal("EOF released active budget before cleanup") @@ -257,16 +257,16 @@ func TestRemoteSpeechStreamEOFRetainsBudgetThroughCleanup(t *testing.T) { default: } close(active.cleanup) - if err := remote_render_result(t, f.done); err != nil { + if err := remoteRenderResult(t, f.done); err != nil { t.Fatal(err) } - remote_stream_wait(t, activeRelease) + remoteStreamWait(t, activeRelease) } func TestRemoteSpeechStreamRechecksPolicyAndFailsClosed(t *testing.T) { for _, cause := range []string{"policy", "backend", "invalid", "overflow", "bytes"} { t.Run(cause, func(t *testing.T) { - f := remote_stream_fixture(t, false) + f := newRemoteStreamFixture(t, false) activeRelease := f.speak(t, "active", 0) active := f.next(t, "active") pendingRelease := f.speak(t, "pending", 0) @@ -275,26 +275,26 @@ func TestRemoteSpeechStreamRechecksPolicyAndFailsClosed(t *testing.T) { case "policy": f.allowed.Store(false) active.finish <- nil - remote_stream_wait(t, pendingRelease) - remote_stream_wait(t, f.speak(t, "denied", 2)) + remoteStreamWait(t, pendingRelease) + remoteStreamWait(t, f.speak(t, "denied", 2)) f.stop(t) case "backend": active.finish <- errors.New("backend failure") - if err := remote_render_result(t, f.done); err == nil || errors.Is(err, context.Canceled) { + if err := remoteRenderResult(t, f.done); err == nil || errors.Is(err, context.Canceled) { t.Fatalf("backend failure did not retire the stream: %v", err) } case "invalid": - remote_stream_wait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "speak"})) + remoteStreamWait(t, f.send(t, tentaclewire.RemoteSpeech{Kind: "speak"})) // Release precedes error return; wait for the owned result. - if err := remote_render_result(t, f.done); err == nil { + if err := remoteRenderResult(t, f.done); err == nil { t.Fatal("invalid assembly was accepted") } case "overflow": for range tentaclewire.RemoteSpeechQueueSize - 2 { f.speak(t, "bounded", 0) } - remote_stream_wait(t, f.speak(t, "overflow", 0)) - if err := remote_render_result(t, f.done); err == nil { + remoteStreamWait(t, f.speak(t, "overflow", 0)) + if err := remoteRenderResult(t, f.done); err == nil { t.Fatal("owner exceeded retained frame budget") } case "bytes": @@ -302,25 +302,25 @@ func TestRemoteSpeechStreamRechecksPolicyAndFailsClosed(t *testing.T) { for range 52 { f.speak(t, strings.Repeat("x", 5000), 0) } - remote_stream_wait(t, f.speak(t, strings.Repeat("x", 5000), 0)) - if err := remote_render_result(t, f.done); err == nil { + remoteStreamWait(t, f.speak(t, strings.Repeat("x", 5000), 0)) + if err := remoteRenderResult(t, f.done); err == nil { t.Fatal("owner exceeded retained byte budget") } } - remote_stream_wait(t, activeRelease) - remote_stream_wait(t, pendingRelease) + remoteStreamWait(t, activeRelease) + remoteStreamWait(t, pendingRelease) }) } } func TestRemoteSpeechStreamIsolatedBackendCancellation(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) ctx, cancel := context.WithCancel(t.Context()) defer cancel() incoming := make(chan tentacle.RemoteSpeechDelivery, 8) done := make(chan error, 1) go func() { - done <- run_remote_speech_playback(ctx, speaker, incoming, func(tentacle.RemoteSpeechDelivery) bool { return true }, nil, nil) + done <- runRemoteSpeechPlayback(ctx, speaker, incoming, func(tentacle.RemoteSpeechDelivery) bool { return true }, nil, nil) }() lease := tentaclewire.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1} send := func(effect tentaclewire.RemoteSpeech) <-chan struct{} { @@ -330,36 +330,36 @@ func TestRemoteSpeechStreamIsolatedBackendCancellation(t *testing.T) { } localDone := make(chan error, 1) go func() { localDone <- speaker.SpeakAndWait(ctx, "local status", nil) }() - local := server.next_utterance(t) - remoteRelease := send(remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "remote first"})) - remote := server.next_utterance(t) + local := server.nextUtterance(t) + remoteRelease := send(remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "remote first"})) + remote := server.nextUtterance(t) if remote.priority != "TEXT" || local.priority != "MESSAGE" { t.Fatal("incoming speech can compete with local output priority") } if local.id == remote.id { t.Fatal("stream acquired the local speaking client") } - remote_stream_wait(t, send(tentaclewire.RemoteSpeech{Kind: "cancel"})) - remote_stream_wait(t, remoteRelease) + remoteStreamWait(t, send(tentaclewire.RemoteSpeech{Kind: "cancel"})) + remoteStreamWait(t, remoteRelease) server.mutex.Lock() localPending := server.connections[local.id].pending server.mutex.Unlock() if localPending == "" { t.Fatal("remote cancel removed local status") } - nextRelease := send(remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "remote after cancel"})) - next := server.next_utterance(t) + nextRelease := send(remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "remote after cancel"})) + next := server.nextUtterance(t) if next.text != "remote after cancel" || next.id == local.id || next.id == remote.id { t.Fatal("cancelled renderer was reused or replayed") } - server.end_utterance(t, next) - remote_stream_wait(t, nextRelease) - server.end_utterance(t, local) - if err := remote_render_result(t, localDone); err != nil { + server.endUtterance(t, next) + remoteStreamWait(t, nextRelease) + server.endUtterance(t, local) + if err := remoteRenderResult(t, localDone); err != nil { t.Fatal(err) } cancel() - if err := remote_render_result(t, done); !errors.Is(err, context.Canceled) { + if err := remoteRenderResult(t, done); !errors.Is(err, context.Canceled) { t.Fatalf("stream shutdown: %v", err) } } @@ -367,7 +367,7 @@ func TestRemoteSpeechStreamIsolatedBackendCancellation(t *testing.T) { func TestRemoteSpeechStreamEarlyBackendCompletionKeepsReading(t *testing.T) { for _, terminal := range []int{702, 703} { t.Run(fmt.Sprint(terminal), func(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) server.mutex.Lock() server.queryReplies = map[string]string{"SPEAK": fmt.Sprintf( "230 OK\r\n%d-1\r\n%d-1\r\n%d DONE\r\n225-1\r\n225 QUEUED\r\n", terminal, terminal, terminal)} @@ -377,21 +377,21 @@ func TestRemoteSpeechStreamEarlyBackendCompletionKeepsReading(t *testing.T) { incoming := make(chan tentacle.RemoteSpeechDelivery, 8) done := make(chan error, 1) go func() { - done <- run_remote_speech_playback(ctx, speaker, incoming, func(tentacle.RemoteSpeechDelivery) bool { return true }, nil, nil) + done <- runRemoteSpeechPlayback(ctx, speaker, incoming, func(tentacle.RemoteSpeechDelivery) bool { return true }, nil, nil) }() lease := tentaclewire.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1} for _, text := range []string{"first", "second", "third"} { released := make(chan struct{}) incoming <- tentacle.RemoteSpeechDelivery{Context: ctx, Lease: lease, - Speeches: []tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: text})}, + Speeches: []tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: text})}, Release: func() { close(released) }} - if got := server.next_utterance(t); got.text != text { + if got := server.nextUtterance(t); got.text != text { t.Fatalf("remote output = %q, want %q", got.text, text) } - remote_stream_wait(t, released) + remoteStreamWait(t, released) } cancel() - if err := remote_render_result(t, done); !errors.Is(err, context.Canceled) { + if err := remoteRenderResult(t, done); !errors.Is(err, context.Canceled) { t.Fatalf("stream shutdown: %v", err) } }) @@ -399,7 +399,7 @@ func TestRemoteSpeechStreamEarlyBackendCompletionKeepsReading(t *testing.T) { } func TestRemoteSpeechStreamPolicyLossDuringAcquisition(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) held, resume := make(chan struct{}), make(chan struct{}) server.mutex.Lock() server.holdCommand, server.held, server.resume = "HISTORY GET CLIENT_ID", held, resume @@ -418,22 +418,22 @@ func TestRemoteSpeechStreamPolicyLossDuringAcquisition(t *testing.T) { released := make(chan struct{}) incoming <- tentacle.RemoteSpeechDelivery{Context: t.Context(), Lease: tentaclewire.RemoteLease{Lease: strings.Repeat("c", 32), Epoch: 1}, - Speeches: []tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: "denied after acquisition"})}, + Speeches: []tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: "denied after acquisition"})}, Release: func() { close(released) }} done := make(chan error, 1) go func() { - done <- run_remote_speech_playback(t.Context(), speaker, incoming, func(tentacle.RemoteSpeechDelivery) bool { return allowed.Load() }, nil, nil) + done <- runRemoteSpeechPlayback(t.Context(), speaker, incoming, func(tentacle.RemoteSpeechDelivery) bool { return allowed.Load() }, nil, nil) }() - remote_stream_wait(t, held) + remoteStreamWait(t, held) allowed.Store(false) server.mutex.Lock() server.holdCommand = "" server.mutex.Unlock() close(resume) - if err := remote_render_result(t, done); err == nil { + if err := remoteRenderResult(t, done); err == nil { t.Fatal("policy loss during acquisition was accepted") } - remote_stream_wait(t, released) + remoteStreamWait(t, released) select { case <-server.queued: t.Fatal("policy loss exposed speech to the backend") @@ -443,13 +443,13 @@ func TestRemoteSpeechStreamPolicyLossDuringAcquisition(t *testing.T) { func TestRemoteSpeechStreamVoiceRetiresWithOriginalLease(t *testing.T) { for _, state := range []string{"active", "idle"} { - t.Run(state, func(t *testing.T) { test_remote_stream_lease_voice(t, state == "active") }) + t.Run(state, func(t *testing.T) { testRemoteStreamLeaseVoice(t, state == "active") }) } } -func test_remote_stream_lease_voice(t *testing.T, active bool) { +func testRemoteStreamLeaseVoice(t *testing.T, active bool) { t.Helper() - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) ctx, cancel := context.WithCancel(t.Context()) defer cancel() leaseContext, revoke := context.WithCancel(ctx) @@ -457,30 +457,30 @@ func test_remote_stream_lease_voice(t *testing.T, active bool) { incoming := make(chan tentacle.RemoteSpeechDelivery, 4) done := make(chan error, 1) go func() { - done <- run_remote_speech_playback(ctx, speaker, incoming, func(delivery tentacle.RemoteSpeechDelivery) bool { return delivery.Context.Err() == nil }, nil, nil) + done <- runRemoteSpeechPlayback(ctx, speaker, incoming, func(delivery tentacle.RemoteSpeechDelivery) bool { return delivery.Context.Err() == nil }, nil, nil) }() send := func(lifetime context.Context, epoch uint64, text string) <-chan struct{} { released := make(chan struct{}) incoming <- tentacle.RemoteSpeechDelivery{Context: lifetime, Lease: tentaclewire.RemoteLease{Lease: strings.Repeat("d", 32), Epoch: epoch}, - Speeches: []tentaclewire.RemoteSpeech{remote_render_frame(0, tentaclewire.RemoteSpeechPart{Text: text})}, + Speeches: []tentaclewire.RemoteSpeech{remoteRenderFrame(0, tentaclewire.RemoteSpeechPart{Text: text})}, Release: func() { close(released) }} return released } firstRelease := send(leaseContext, 1, "first lease") - first := server.next_utterance(t) + first := server.nextUtterance(t) if !active { - server.end_utterance(t, first) - remote_stream_wait(t, firstRelease) + server.endUtterance(t, first) + remoteStreamWait(t, firstRelease) } speaker.mu.RLock() oldVoice := speaker.remote speaker.mu.RUnlock() revoke() - remote_stream_wait(t, oldVoice.closed) - remote_stream_wait(t, firstRelease) + remoteStreamWait(t, oldVoice.closed) + remoteStreamWait(t, firstRelease) nextRelease := send(ctx, 2, "replacement lease") - next := server.next_utterance(t) + next := server.nextUtterance(t) if next.id == first.id || next.text != "replacement lease" { t.Fatal("replacement inherited the retired backend client") } @@ -494,10 +494,10 @@ func test_remote_stream_lease_voice(t *testing.T, active bool) { if pending != "replacement lease" { t.Fatal("old lease cleanup removed replacement speech") } - server.end_utterance(t, next) - remote_stream_wait(t, nextRelease) + server.endUtterance(t, next) + remoteStreamWait(t, nextRelease) cancel() - if err := remote_render_result(t, done); !errors.Is(err, context.Canceled) { + if err := remoteRenderResult(t, done); !errors.Is(err, context.Canceled) { t.Fatalf("stream shutdown: %v", err) } } diff --git a/internal/app/remote_speech_voice.go b/internal/app/remote_speech_voice.go index c58392e..a53826a 100644 --- a/internal/app/remote_speech_voice.go +++ b/internal/app/remote_speech_voice.go @@ -29,11 +29,11 @@ type remoteSpeechVoice struct { renderCancel context.CancelFunc // Protected by request; never backend I/O. } -// open_remote_voice is called only by an output worker, never an input callback. +// openRemoteVoice is called only by an output worker, never an input callback. // Acquisition neither changes the local configuration nor opens a serial device. // There is at most one handle; a replacement requires its predecessor to close. // ctx bounds acquisition only. A future lease owner must Close on revocation. -func (speaker *configuredSpeaker) open_remote_voice(ctx context.Context) (*remoteSpeechVoice, error) { +func (speaker *configuredSpeaker) openRemoteVoice(ctx context.Context) (*remoteSpeechVoice, error) { if !speaker.update.TryLock() { return nil, errors.New("speech configuration is busy") } @@ -78,7 +78,7 @@ func (speaker *configuredSpeaker) open_remote_voice(ctx context.Context) (*remot // A successful configuration commit retires the old remote voice. A failed // preparation must leave it usable. Handles never silently adopt new settings. -func (speaker *configuredSpeaker) retire_remote_voice(settings config.Settings) { +func (speaker *configuredSpeaker) retireRemoteVoice(settings config.Settings) { speaker.mu.Lock() speaker.settings = settings remote := speaker.remote diff --git a/internal/app/remote_speech_voice_test.go b/internal/app/remote_speech_voice_test.go index 7247c1b..50c1fef 100644 --- a/internal/app/remote_speech_voice_test.go +++ b/internal/app/remote_speech_voice_test.go @@ -56,7 +56,7 @@ type isolatedVoiceServer struct { held, resume chan struct{} } -func isolated_voice_fixture(t *testing.T) (*configuredSpeaker, *isolatedVoiceServer) { +func isolatedVoiceFixture(t *testing.T) (*configuredSpeaker, *isolatedVoiceServer) { t.Helper() path := filepath.Join(t.TempDir(), "speech.sock") listener, err := net.Listen("unix", path) @@ -226,7 +226,7 @@ func (server *isolatedVoiceServer) pending(text string) (int, string) { return 0, "" } -func begin_isolated_speech(t *testing.T, voice *remoteSpeechVoice, ctx context.Context, text string) <-chan error { +func beginIsolatedSpeech(t *testing.T, voice *remoteSpeechVoice, ctx context.Context, text string) <-chan error { t.Helper() began := make(chan struct{}) finished := make(chan error, 1) @@ -241,7 +241,7 @@ func begin_isolated_speech(t *testing.T, voice *remoteSpeechVoice, ctx context.C return finished } -func finish_isolated_speech(t *testing.T, finished <-chan error) { +func finishIsolatedSpeech(t *testing.T, finished <-chan error) { t.Helper() select { case err := <-finished: @@ -256,20 +256,20 @@ func finish_isolated_speech(t *testing.T, finished <-chan error) { func TestRemoteSpeechVoiceCancellationKeepsLocalStatusAndEcho(t *testing.T) { for _, operation := range []string{"cancel", "caller", "close"} { t.Run(operation, func(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) if err := speaker.SpeakVoice(t.Context(), "local status", "system"); err != nil { t.Fatal(err) } if err := speaker.SpeakEcho(t.Context(), "local echo"); err != nil { t.Fatal(err) } - voice, err := speaker.open_remote_voice(t.Context()) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(t.Context()) defer cancel() - finished := begin_isolated_speech(t, voice, ctx, "remote") + finished := beginIsolatedSpeech(t, voice, ctx, "remote") remoteID, _ := server.pending("remote") statusID, _ := server.pending("local status") echoID, _ := server.pending("local echo") @@ -292,7 +292,7 @@ func TestRemoteSpeechVoiceCancellationKeepsLocalStatusAndEcho(t *testing.T) { if err != nil { t.Fatal(err) } - finish_isolated_speech(t, finished) + finishIsolatedSpeech(t, finished) if id, _ := server.pending("local status"); id != statusID { t.Fatal("remote cancellation discarded local status") } @@ -304,11 +304,11 @@ func TestRemoteSpeechVoiceCancellationKeepsLocalStatusAndEcho(t *testing.T) { } if operation != "close" { // Notification cleanup leaves the same isolated connection reusable. - finished = begin_isolated_speech(t, voice, t.Context(), "remote again") + finished = beginIsolatedSpeech(t, voice, t.Context(), "remote again") if err := speaker.Cancel(t.Context()); err != nil { t.Fatal(err) } - finish_isolated_speech(t, finished) + finishIsolatedSpeech(t, finished) if id, _ := server.pending("local status"); id != 0 { t.Fatal("core cancellation failed to stop local output") } @@ -318,15 +318,15 @@ func TestRemoteSpeechVoiceCancellationKeepsLocalStatusAndEcho(t *testing.T) { } func TestRemoteSpeechVoiceConfigurationAndOwnership(t *testing.T) { - speaker, server := isolated_voice_fixture(t) - voice, err := speaker.open_remote_voice(t.Context()) + speaker, server := isolatedVoiceFixture(t) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } - if _, err := speaker.open_remote_voice(t.Context()); err == nil { + if _, err := speaker.openRemoteVoice(t.Context()); err == nil { t.Fatal("two simultaneous Remote voices admitted") } - finished := begin_isolated_speech(t, voice, t.Context(), "old settings") + finished := beginIsolatedSpeech(t, voice, t.Context(), "old settings") settings := config.DefaultSettings() settings.SpeechOutputModule = "rejected" if err := speaker.UpdateConfiguration(t.Context(), settings); err == nil { @@ -339,15 +339,15 @@ func TestRemoteSpeechVoiceConfigurationAndOwnership(t *testing.T) { if err := speaker.UpdateConfiguration(t.Context(), settings); err != nil { t.Fatal(err) } - finish_isolated_speech(t, finished) + finishIsolatedSpeech(t, finished) if err := voice.SpeakAndWait(t.Context(), "stale", nil); !errors.Is(err, context.Canceled) { t.Fatal("retired handle reused new configuration", err) } - replacement, err := speaker.open_remote_voice(t.Context()) + replacement, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal(err) } - finished = begin_isolated_speech(t, replacement, t.Context(), "new settings") + finished = beginIsolatedSpeech(t, replacement, t.Context(), "new settings") if _, module := server.pending("new settings"); module != "replacement" { t.Fatal("isolated voice used stale settings", module) } @@ -360,26 +360,26 @@ func TestRemoteSpeechVoiceConfigurationAndOwnership(t *testing.T) { if err := speaker.Close(t.Context()); err != nil { t.Fatal(err) } - finish_isolated_speech(t, finished) - if _, err := speaker.open_remote_voice(t.Context()); err == nil { + finishIsolatedSpeech(t, finished) + if _, err := speaker.openRemoteVoice(t.Context()); err == nil { t.Fatal("closed speaker admitted Remote") } } func TestRemoteSpeechVoiceCompletionAndAcquisitionLifetime(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) ctx, cancel := context.WithCancel(t.Context()) defer cancel() server.mutex.Lock() before := server.accepted server.mutex.Unlock() - voice, err := speaker.open_remote_voice(ctx) + voice, err := speaker.openRemoteVoice(ctx) if err != nil { t.Fatal(err) } // Acquisition cancellation must not become accidental session revocation. cancel() - finished := begin_isolated_speech(t, voice, t.Context(), "complete") + finished := beginIsolatedSpeech(t, voice, t.Context(), "complete") server.mutex.Lock() if server.accepted != before+2 { t.Error("isolated voice did not open exactly one speaking/control pair") @@ -408,7 +408,7 @@ func TestRemoteSpeechVoiceCompletionAndAcquisitionLifetime(t *testing.T) { if err := voice.Close(t.Context()); err != nil { t.Fatal(err) } - if _, err := speaker.open_remote_voice(t.Context()); err != nil { + if _, err := speaker.openRemoteVoice(t.Context()); err != nil { t.Fatal("closed voice retained exclusive ownership", err) } } @@ -416,17 +416,17 @@ func TestRemoteSpeechVoiceCompletionAndAcquisitionLifetime(t *testing.T) { func TestRemoteSpeechVoiceRejectsUnavailableBackendsAndCancelledAcquisition(t *testing.T) { for _, active := range []configuredVoice{nil, &hardwareSpeaker{}} { speaker := &configuredSpeaker{active: active} - if _, err := speaker.open_remote_voice(t.Context()); err == nil { + if _, err := speaker.openRemoteVoice(t.Context()); err == nil { t.Fatal("unavailable software backend admitted Remote") } } - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) ctx, cancel := context.WithCancel(t.Context()) cancel() server.mutex.Lock() before := server.accepted server.mutex.Unlock() - if _, err := speaker.open_remote_voice(ctx); !errors.Is(err, context.Canceled) { + if _, err := speaker.openRemoteVoice(ctx); !errors.Is(err, context.Canceled) { t.Fatal("cancelled acquisition succeeded", err) } server.mutex.Lock() diff --git a/internal/app/review_spelling.go b/internal/app/review_spelling.go index 5c0652e..276f795 100644 --- a/internal/app/review_spelling.go +++ b/internal/app/review_spelling.go @@ -17,7 +17,7 @@ import ( // Shared by review spelling and learn mode, matching Python Cthulhu's names. func phoneticLetter(letter rune) string { return phonetic.Letter(letter) } -func flat_review_speech(command input.Command) review.FlatSpeech { +func flatReviewSpeech(command input.Command) review.FlatSpeech { switch command { case input.ReviewSpellWord, input.ReviewSpellLine: return review.FlatSpell @@ -29,7 +29,7 @@ func flat_review_speech(command input.Command) review.FlatSpeech { // Preserve blank/whitespace announcements. Otherwise spell Unicode runes as // separate utterances, retaining repeated letters and character-mode speech. -func set_review_spelling(request *speechRequest, text string, style review.FlatSpeech) { +func setReviewSpelling(request *speechRequest, text string, style review.FlatSpeech) { if style == review.FlatSpeak || strings.TrimSpace(text) == "" { return } diff --git a/internal/app/review_spelling_test.go b/internal/app/review_spelling_test.go index 753e357..fb1049d 100644 --- a/internal/app/review_spelling_test.go +++ b/internal/app/review_spelling_test.go @@ -39,7 +39,7 @@ func TestFlatReviewSpellingPresentation(t *testing.T) { } { queue := &fakeSpeechQueue{requests: make(chan speechRequest, 1), spoken: make(chan string, 1)} unit, step := flatReviewCommand(tc.command) - result := review.Result{FlatUnit: unit, FlatStep: step, FlatSpeech: flat_review_speech(tc.command), FlatPosition: review.FlatPosition{Text: tc.text}} + result := review.Result{FlatUnit: unit, FlatStep: step, FlatSpeech: flatReviewSpeech(tc.command), FlatPosition: review.FlatPosition{Text: tc.text}} presentFlatReviewResult(slog.New(slog.DiscardHandler), queue, result) request := <-queue.requests if !reflect.DeepEqual(request.Spelling, tc.parts) || request.Character != tc.character { @@ -74,7 +74,7 @@ func TestReviewSpellingDeliveryAndInterruption(t *testing.T) { speaker := &spellingTestSpeaker{} worker := newSpeechWorker(slog.New(slog.DiscardHandler), speaker) request := speechRequest{Text: "book", Cause: "flat-review"} - set_review_spelling(&request, strings.Repeat("book", 20), style) + setReviewSpelling(&request, strings.Repeat("book", 20), style) if err := worker.deliver(context.Background(), request); err != nil { t.Fatal(err) } diff --git a/internal/app/runtime_commands.go b/internal/app/runtime_commands.go index 979418b..ad5ab04 100644 --- a/internal/app/runtime_commands.go +++ b/internal/app/runtime_commands.go @@ -124,7 +124,7 @@ func (worker commandRuntime) run(ctx context.Context) error { if speechMessages != nil { speechMessages.ProtectCommand(state.Timestamp) } - focusGate.dismiss_confirmation() + focusGate.dismissConfirmation() speechOutput.Enqueue(speechRequest{Text: state.Text(), Role: "system", Cause: "lock-state"}) logger.Debug("keyboard lock state changed", "key", state.Name, "locked", state.Locked) case event := <-commands.Commands(): @@ -143,7 +143,7 @@ func (worker commandRuntime) run(ctx context.Context) error { if speechMessages != nil { speechMessages.ProtectCommand(event.Timestamp) } - focusGate.dismiss_confirmation() + focusGate.dismissConfirmation() logger.Debug("keyboard command received", "command", command, "input_timestamp", event.Timestamp) if command == input.ToggleCommandBypass { if focusGate != nil { @@ -191,7 +191,7 @@ func (worker commandRuntime) run(ctx context.Context) error { learn.present("Tentacles disabled.", "tentacles-disabled") case input.CycleSpeechMode: if speechMessages != nil { - mode := speechMessages.cycle_speech_mode() + mode := speechMessages.cycleSpeechMode() speechOutput.Enqueue(speechRequest{Text: mode.announcement(), Role: "system", Cause: "speech-mode", ForceSpeech: true}) } case input.Quit: @@ -311,7 +311,7 @@ func (worker commandRuntime) run(ctx context.Context) error { } } else if unit, step := flatReviewCommand(command); unit != 0 { logger.Info("flat review command received", "command", command) - if err := objectReview.ReadFlatWithSpeech(unit, step, flat_review_speech(command)); err != nil { + if err := objectReview.ReadFlatWithSpeech(unit, step, flatReviewSpeech(command)); err != nil { logger.Warn("queue flat review", "error", err) } } diff --git a/internal/app/runtime_commands_test.go b/internal/app/runtime_commands_test.go index 5a1eaf8..3f3b55e 100644 --- a/internal/app/runtime_commands_test.go +++ b/internal/app/runtime_commands_test.go @@ -166,7 +166,7 @@ func TestRunRoutesNotificationCommands(t *testing.T) { select { case message := <-speaker.spoken: - if !contains_string(startupMessages, message) { + if !containsString(startupMessages, message) { t.Fatalf("startup speech = %q, want one of %q", message, startupMessages) } case <-time.After(time.Second): diff --git a/internal/app/runtime_platform_test.go b/internal/app/runtime_platform_test.go index b3783df..fbd3f70 100644 --- a/internal/app/runtime_platform_test.go +++ b/internal/app/runtime_platform_test.go @@ -79,7 +79,7 @@ func TestRunWaylandWithoutX11SpeaksAndStops(t *testing.T) { for _, expected := range []string{"", "Save", "push button"} { select { case spoken := <-speaker.spoken: - if expected == "" && contains_string(startupMessages, spoken) || expected != "" && spoken == expected { + if expected == "" && containsString(startupMessages, spoken) || expected != "" && spoken == expected { continue } t.Fatalf("speech = %q, expected %q", spoken, expected) diff --git a/internal/app/runtime_shutdown.go b/internal/app/runtime_shutdown.go index e0aa72a..0c3c506 100644 --- a/internal/app/runtime_shutdown.go +++ b/internal/app/runtime_shutdown.go @@ -82,7 +82,7 @@ func stopRuntime(runtime runtimeShutdown) error { farewellContext, cancelFarewell := context.WithTimeout(context.Background(), farewellTimeout) runtime.speech.InterruptForUser() farewellError := runtime.speech.EnqueueAndWait(farewellContext, speechRequest{ - Text: random_string(shutdownMessages), + Text: randomString(shutdownMessages), Role: "system", Cause: "shutdown", }) diff --git a/internal/app/runtime_test.go b/internal/app/runtime_test.go index 46af168..f15fb82 100644 --- a/internal/app/runtime_test.go +++ b/internal/app/runtime_test.go @@ -31,10 +31,10 @@ import ( ) func TestRandomString(t *testing.T) { - if got := random_string(nil); got != "" { + if got := randomString(nil); got != "" { t.Fatalf("random_string(nil) = %q, want empty string", got) } - if got := random_string([]string{"only"}); got != "only" { + if got := randomString([]string{"only"}); got != "only" { t.Fatalf("random_string(single item) = %q, want %q", got, "only") } } diff --git a/internal/app/runtime_workers.go b/internal/app/runtime_workers.go index 533fab7..a2c47df 100644 --- a/internal/app/runtime_workers.go +++ b/internal/app/runtime_workers.go @@ -93,6 +93,6 @@ func startRuntimeWorkers(ctx context.Context, command commandRuntime, inputListe } workers.inputDone = inputDone workers.copyDone = runCopyFeedback(ctx, copyChanges, inputListener, speech, command.live, command.ocr) - workers.autoClipboardDone = run_automatic_clipboard(ctx, command.logger, command.live, command.focusGate, speech) + workers.autoClipboardDone = runAutomaticClipboard(ctx, command.logger, command.live, command.focusGate, speech) return workers } diff --git a/internal/app/screen_lock.go b/internal/app/screen_lock.go index b395661..01fbddf 100644 --- a/internal/app/screen_lock.go +++ b/internal/app/screen_lock.go @@ -143,7 +143,7 @@ func (gate *focusGate) SetLocked(active bool, adapter Adapter, listener InputLis gate.bypass.restore() } gate.retireTentacleOutput() - gate.sync_remote_policy() + gate.syncRemotePolicy() for _, target := range []any{adapter, listener, commands} { if controller, ok := target.(secureInputController); ok { controller.SetSecureInputActive(active) diff --git a/internal/app/speech_context_observation_test.go b/internal/app/speech_context_observation_test.go index 500f532..4a5f997 100644 --- a/internal/app/speech_context_observation_test.go +++ b/internal/app/speech_context_observation_test.go @@ -14,7 +14,7 @@ import ( ) func TestRemoteSpeechContextObservationTransitions(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.reading = func() config.ReadingSettings { return config.DefaultSettings().Reading } list := atspi.Snapshot{BusName: ":1.42", Path: "/list", Role: "list", Name: "Items"} for _, request := range []speechRequest{ @@ -30,12 +30,12 @@ func TestRemoteSpeechContextObservationTransitions(t *testing.T) { if got := <-worker.speaker.(*observationSpeaker).spoken; got != want { t.Fatalf("local context speech = %q, want %q", got, want) } - if got := observed_speech(t, session); got.Kind != "speak" || got.Parts[0].Text != want || !got.Parts[1].End || got.Parts[0].Characters { + if got := observedSpeech(t, session); got.Kind != "speak" || got.Parts[0].Text != want || !got.Parts[1].End || got.Parts[0].Characters { t.Fatalf("observed context speech = %+v, want %q", got, want) } } worker.InterruptForUser() - if got := observed_speech(t, session); got.Kind != "cancel" { + if got := observedSpeech(t, session); got.Kind != "cancel" { t.Fatal("unexpected context output", got) } } @@ -43,7 +43,7 @@ func TestRemoteSpeechContextObservationTransitions(t *testing.T) { func TestRemoteSpeechContextObservationPrivateSources(t *testing.T) { for _, privacy := range []string{"unclassified", "password", "unknown", "invalid", "defunct", "ancestor", "history", "remote", "reset"} { t.Run(privacy, func(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.reading = func() config.ReadingSettings { return config.DefaultSettings().Reading } list := atspi.Snapshot{BusName: ":1.42", Path: "/list", Role: "list", Name: "Private"} request := speechRequest{origin: speechOriginLocal, Text: "Inside", Context: []atspi.Snapshot{list}} @@ -53,7 +53,7 @@ func TestRemoteSpeechContextObservationPrivateSources(t *testing.T) { case "password": // Presentation may retain only an article/list while discarding // a private outer ancestor. Preserve the original classification. - request.origin = accessibility_speech_origin(atspi.Snapshot{Role: "text", SpeechContext: []atspi.Snapshot{list, {Role: "password text"}}}) + request.origin = accessibilitySpeechOrigin(atspi.Snapshot{Role: "text", SpeechContext: []atspi.Snapshot{list, {Role: "password text"}}}) case "unknown", "invalid": request.Context = append(request.Context, atspi.Snapshot{Role: privacy}) case "defunct": @@ -77,11 +77,11 @@ func TestRemoteSpeechContextObservationPrivateSources(t *testing.T) { if err := worker.EnqueueAndWait(t.Context(), speechRequest{origin: speechOriginLocal, Text: "Outside", Context: []atspi.Snapshot{}}); err != nil { t.Fatal(err) } - if got := observed_speech(t, session); got.Kind != "speak" || got.Parts[0].Text != "Outside" { + if got := observedSpeech(t, session); got.Kind != "speak" || got.Parts[0].Text != "Outside" { t.Fatal("private context or cached label exported", got) } worker.InterruptForUser() - if got := observed_speech(t, session); got.Kind != "cancel" { + if got := observedSpeech(t, session); got.Kind != "cancel" { t.Fatal("unexpected private context output", got) } if privacy != "reset" { @@ -101,13 +101,13 @@ func TestRemoteSpeechContextObservationPrivateSources(t *testing.T) { func TestRemoteSpeechContextObservationCachedLabelsKeepOriginalLease(t *testing.T) { for _, priorConsent := range []bool{false, true} { t.Run(map[bool]string{false: "before-consent", true: "replacement"}[priorConsent], func(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.reading = func() config.ReadingSettings { return config.DefaultSettings().Reading } revoke := func() { t.Helper() session.RevokeRemote() var event tentaclewire.SessionEvent - if json.Unmarshal(observation_call(t, session, "event"), &event) != nil || event.Kind != "remote.revoked" { + if json.Unmarshal(observationCall(t, session, "event"), &event) != nil || event.Kind != "remote.revoked" { t.Fatal("expected old lease revocation") } } @@ -120,7 +120,7 @@ func TestRemoteSpeechContextObservationCachedLabelsKeepOriginalLease(t *testing. } if priorConsent { for _, want := range []string{"Old list", "Inside"} { - if got := observed_speech(t, session); got.Kind != "speak" || got.Parts[0].Text != want { + if got := observedSpeech(t, session); got.Kind != "speak" || got.Parts[0].Text != want { t.Fatal("missing original lease output", got) } } @@ -133,11 +133,11 @@ func TestRemoteSpeechContextObservationCachedLabelsKeepOriginalLease(t *testing. if _, err := session.AuthorizeRemoteWithApproval(approval, "controlled", []string{"output-observe"}); err != nil { t.Fatal(err) } - observation_call(t, session, "open") + observationCall(t, session, "open") if err := worker.EnqueueAndWait(t.Context(), speechRequest{origin: speechOriginLocal, Text: "Outside", Context: []atspi.Snapshot{}}); err != nil { t.Fatal(err) } - if got := observed_speech(t, session); got.Kind != "speak" || got.Parts[0].Text != "Outside" { + if got := observedSpeech(t, session); got.Kind != "speak" || got.Parts[0].Text != "Outside" { t.Fatal("cached exit label acquired new consent", got) } for _, want := range []string{"Old list", "Inside", "Leaving Old list.", "Outside"} { @@ -146,7 +146,7 @@ func TestRemoteSpeechContextObservationCachedLabelsKeepOriginalLease(t *testing. } } worker.InterruptForUser() - if got := observed_speech(t, session); got.Kind != "cancel" { + if got := observedSpeech(t, session); got.Kind != "cancel" { t.Fatal("unexpected replacement output", got) } }) @@ -154,7 +154,7 @@ func TestRemoteSpeechContextObservationCachedLabelsKeepOriginalLease(t *testing. } func TestRemoteSpeechContextObservationSayAllAndSpelling(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.reading = func() config.ReadingSettings { return config.DefaultSettings().Reading } list := atspi.Snapshot{BusName: ":1.42", Path: "/list", Role: "list", Name: "Items"} for _, request := range []speechRequest{ @@ -166,12 +166,12 @@ func TestRemoteSpeechContextObservationSayAllAndSpelling(t *testing.T) { } } for index, want := range []string{"Items list", "First", "Leaving Items list.", "Second", "Items list", "a", "a"} { - if got := observed_speech(t, session); got.Kind != "speak" || got.Parts[0].Text != want || got.Parts[0].Characters != (index >= 5) { + if got := observedSpeech(t, session); got.Kind != "speak" || got.Parts[0].Text != want || got.Parts[0].Characters != (index >= 5) { t.Fatalf("context/chunk/spelling boundary lost, want %q: %+v", want, got) } } worker.InterruptForUser() - if got := observed_speech(t, session); got.Kind != "cancel" { + if got := observedSpeech(t, session); got.Kind != "cancel" { t.Fatal("repeated context during spelling", got) } } diff --git a/internal/app/speech_current_line_observation_test.go b/internal/app/speech_current_line_observation_test.go index 037a52a..d9c85e6 100644 --- a/internal/app/speech_current_line_observation_test.go +++ b/internal/app/speech_current_line_observation_test.go @@ -14,7 +14,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/review" ) -func current_line_observation_request(t *testing.T, result review.Result) speechRequest { +func currentLineObservationRequest(t *testing.T, result review.Result) speechRequest { t.Helper() focus := atspi.NewObjectID(":1.42", "/focus") worker, err := review.NewWorker(&fakeAdapter{}, time.Second) @@ -27,7 +27,7 @@ func current_line_observation_request(t *testing.T, result review.Result) speech browser: &browserModeController{ready: true, mode: review.BrowseMode, focus: focus, document: result.DocumentPosition.Document.ID()}} result.DocumentFocus = focus - handler.present_current_line(result) + handler.presentCurrentLine(result) select { case request := <-queue.requests: return request @@ -73,9 +73,9 @@ func TestRemoteCurrentLineSourcePrivacy(t *testing.T) { case "failure": result.Err = errors.New("fixture unavailable") } - request := current_line_observation_request(t, result) - if exportable_speech(request) != (source == "ordinary" || source == "ordinary-neighbor") { - t.Fatalf("source %s produced exportable=%v", source, exportable_speech(request)) + request := currentLineObservationRequest(t, result) + if exportableSpeech(request) != (source == "ordinary" || source == "ordinary-neighbor") { + t.Fatalf("source %s produced exportable=%v", source, exportableSpeech(request)) } if source != "failure" && request.Text != "book" { t.Fatal("privacy classification changed local text") @@ -86,7 +86,7 @@ func TestRemoteCurrentLineSourcePrivacy(t *testing.T) { } func TestRemoteCurrentLineResolvedOutput(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } for _, probe := range []struct { text string @@ -103,11 +103,11 @@ func TestRemoteCurrentLineResolvedOutput(t *testing.T) { result := review.Result{CurrentLineBrowse: true, FlatSpeech: probe.style, DocumentCaretText: probe.text, DocumentPosition: review.DocumentPosition{Snapshot: source}, DocumentCaretContext: []atspi.Snapshot{source, {Role: "paragraph"}, {Role: "document web"}}} - if err := worker.EnqueueAndWait(t.Context(), current_line_observation_request(t, result)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), currentLineObservationRequest(t, result)); err != nil { t.Fatal(err) } for _, want := range probe.want { - value := observed_speech(t, session) + value := observedSpeech(t, session) if value.Kind != "speak" || len(value.Parts) != 2 || value.Parts[0].Text != want || value.Parts[0].Characters != probe.characters || !value.Parts[1].End { t.Fatal("current-line delivery lost resolved text, repetition or character state", value) @@ -119,11 +119,11 @@ func TestRemoteCurrentLineResolvedOutput(t *testing.T) { // A sensitive ancestor must suppress every spelling/phonetic part, // while the complete local reading remains available. result.DocumentCaretContext[1].Role = "password text" - if err := worker.EnqueueAndWait(t.Context(), current_line_observation_request(t, result)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), currentLineObservationRequest(t, result)); err != nil { t.Fatal(err) } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("sensitive current-line output reached the child", value) } for _, want := range probe.want { @@ -134,7 +134,7 @@ func TestRemoteCurrentLineResolvedOutput(t *testing.T) { } } -func native_current_line_result() review.Result { +func nativeCurrentLineResult() review.Result { source := atspi.Snapshot{BusName: ":1.42", Path: "/focus", Role: "text"} return review.Result{DocumentCaretText: "Native colour.", DocumentPosition: review.DocumentPosition{Snapshot: source}, DocumentCaretContext: []atspi.Snapshot{source, {BusName: source.BusName, Path: "/window", Role: "frame"}, @@ -144,7 +144,7 @@ func native_current_line_result() review.Result { func TestRemoteNativeCurrentLineSourcePrivacy(t *testing.T) { for _, privacy := range []string{"ordinary", "password", "ancestor", "unknown", "invalid", "defunct", "missing", "truncated", "mismatched", "foreign", "failure"} { t.Run(privacy, func(t *testing.T) { - result := native_current_line_result() + result := nativeCurrentLineResult() switch privacy { case "password": result.DocumentPosition.Snapshot.Role = "password text" @@ -168,9 +168,9 @@ func TestRemoteNativeCurrentLineSourcePrivacy(t *testing.T) { case "failure": result.Err = errors.New("fixture unavailable") } - request := current_line_observation_request(t, result) - if exportable_speech(request) != (privacy == "ordinary") { - t.Fatalf("native source %s produced exportable=%v", privacy, exportable_speech(request)) + request := currentLineObservationRequest(t, result) + if exportableSpeech(request) != (privacy == "ordinary") { + t.Fatalf("native source %s produced exportable=%v", privacy, exportableSpeech(request)) } if privacy != "failure" && request.Text != result.DocumentCaretText { t.Fatal("privacy classification changed local native reading") @@ -180,7 +180,7 @@ func TestRemoteNativeCurrentLineSourcePrivacy(t *testing.T) { } func TestRemoteNativeCurrentLineResolvedOutput(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } for _, probe := range []struct { style review.FlatSpeech @@ -193,18 +193,18 @@ func TestRemoteNativeCurrentLineResolvedOutput(t *testing.T) { {review.FlatPhonetic, "book", []string{"bravo", "oscar", "oscar", "kilo"}, false}, {review.FlatSpeak, "\n", []string{"blank"}, false}, } { - result := native_current_line_result() + result := nativeCurrentLineResult() result.FlatSpeech, result.DocumentCaretText = probe.style, probe.text for _, private := range []bool{false, true} { if private { result.DocumentCaretContext[1].Role = "password text" } - if err := worker.EnqueueAndWait(t.Context(), current_line_observation_request(t, result)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), currentLineObservationRequest(t, result)); err != nil { t.Fatal(err) } for _, want := range probe.want { if !private { - value := observed_speech(t, session) + value := observedSpeech(t, session) if value.Kind != "speak" || len(value.Parts) != 2 || value.Parts[0].Text != want || value.Parts[0].Characters != probe.characters || !value.Parts[1].End { t.Fatal("native report lost resolved output or spelling boundaries", value) @@ -215,7 +215,7 @@ func TestRemoteNativeCurrentLineResolvedOutput(t *testing.T) { } } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("private native output reached the child", value) } } diff --git a/internal/app/speech_delivery.go b/internal/app/speech_delivery.go index 3e9aff6..96f9578 100644 --- a/internal/app/speech_delivery.go +++ b/internal/app/speech_delivery.go @@ -32,10 +32,10 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) } // Suppressed utterances must not cancel the spoken mode announcement. // Mode changes already interrupt the synth through the worker barrier. - if handled, err := worker.deliver_mode(ctx, request); handled { + if handled, err := worker.deliverMode(ctx, request); handled { return err } - if handled, err := worker.deliver_phonetic_hint(ctx, request); handled { + if handled, err := worker.deliverPhoneticHint(ctx, request); handled { return err } // Incoming output always queues. Only input/command handling may cancel @@ -43,7 +43,7 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) if len(request.Spelling) != 0 { // One parent request owns its context; letter recursion must not // re-announce it or alter the original character's voice choice. - if err := worker.deliver_context(ctx, request); err != nil { + if err := worker.deliverContext(ctx, request); err != nil { return err } request.Context = nil @@ -70,7 +70,7 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) } return nil } - if err := worker.deliver_context(ctx, request); err != nil { + if err := worker.deliverContext(ctx, request); err != nil { return err } if len(request.ReadAll) != 0 { @@ -85,15 +85,15 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) return err } if part.Context != nil && !request.ResetContext { - if err := worker.deliver_context_for(ctx, request, part.Context, true); err != nil { + if err := worker.deliverContextFor(ctx, request, part.Context, true); err != nil { return err } } - text := worker.transformText(worker.line_text(part.Text, part.Line)) + text := worker.transformText(worker.lineText(part.Text, part.Line)) delivery := request delivery.VoiceType, delivery.CustomEcho = part.VoiceType, part.VoiceType == "echo" worker.logDelivery(ctx, delivery, text, index) - worker.observe_speech(ctx, delivery, text, false) + worker.observeSpeech(ctx, delivery, text, false) if worker.history != nil && !request.ExcludeFromHistory && request.Cause != "speech-history" { worker.history.add(text, request.Role) } @@ -113,18 +113,18 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) } if request.Uninterruptible { reader, ok := worker.speaker.(interface { - speak_uninterruptible(context.Context, string) error + speakUninterruptible(context.Context, string) error }) if !ok { return errors.New("speech backend does not support uninterruptible completion") } - text := worker.transformText(worker.line_text(request.Text, request.Line)) - worker.record_delivery(ctx, request, text) - return reader.speak_uninterruptible(ctx, text) + text := worker.transformText(worker.lineText(request.Text, request.Line)) + worker.recordDelivery(ctx, request, text) + return reader.speakUninterruptible(ctx, text) } if request.Confirmation { - text := worker.transformText(worker.line_text(request.Text, request.Line)) - worker.record_delivery(ctx, request, text) + text := worker.transformText(worker.lineText(request.Text, request.Line)) + worker.recordDelivery(ctx, request, text) if voiced, ok := worker.speaker.(interface { SpeakVoiceAndWait(context.Context, string, string, func()) error }); ok { @@ -211,7 +211,7 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) return context.Canceled } if index == 0 { - chunk = worker.line_text(chunk, request.Line) + chunk = worker.lineText(chunk, request.Line) } text := chunk // Character navigation and literal spelling must retain the original @@ -222,14 +222,14 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) text = worker.transformText(chunk) } if (request.Character && capitalCharacter(chunk)) || request.VoiceType == "uppercase" { - if err := worker.present_capital(ctx, request); err != nil { + if err := worker.presentCapital(ctx, request); err != nil { return err } } part := request part.Append = request.Append || index > 0 - worker.record_delivery(ctx, part, text) - worker.observe_speech(ctx, part, text, characters && utf8.RuneCountInString(text) == 1 && !strings.ContainsAny(text, "\r\n\x00")) + worker.recordDelivery(ctx, part, text) + worker.observeSpeech(ctx, part, text, characters && utf8.RuneCountInString(text) == 1 && !strings.ContainsAny(text, "\r\n\x00")) if err := speak(ctx, text); err != nil { return fmt.Errorf("speak: %w", err) } @@ -237,7 +237,7 @@ func (worker *speechWorker) deliver(ctx context.Context, request speechRequest) return nil } -func (worker *speechWorker) record_delivery(ctx context.Context, request speechRequest, text string) { +func (worker *speechWorker) recordDelivery(ctx context.Context, request speechRequest, text string) { worker.logDelivery(ctx, request, text, -1) if worker.history != nil && !request.ExcludeFromHistory && request.Cause != "speech-history" { worker.history.add(text, request.Role) diff --git a/internal/app/speech_document_observation_test.go b/internal/app/speech_document_observation_test.go index 72306cd..957ef4a 100644 --- a/internal/app/speech_document_observation_test.go +++ b/internal/app/speech_document_observation_test.go @@ -18,7 +18,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) -func document_observation_request(t *testing.T, kind string, result review.Result) speechRequest { +func documentObservationRequest(t *testing.T, kind string, result review.Result) speechRequest { t.Helper() queue := &fakeSpeechQueue{requests: make(chan speechRequest, 1), spoken: make(chan string, 1)} logger := slog.New(slog.DiscardHandler) @@ -33,7 +33,7 @@ func document_observation_request(t *testing.T, kind string, result review.Resul presentReadAllResult(logger, queue, result, options) case "current-line": result.CurrentLineBrowse = true - return current_line_observation_request(t, result) + return currentLineObservationRequest(t, result) } select { case request := <-queue.requests: @@ -73,9 +73,9 @@ func TestRemoteDocumentSpeechSourcePrivacy(t *testing.T) { DocumentCaretCommand: review.CaretNextLine, DocumentCaretContext: ancestors, DocumentPosition: review.DocumentPosition{Snapshot: snapshot}, ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{{Context: ancestors, Contents: []atspi.DocumentContent{{Snapshot: snapshot, Text: "Reading. Next sentence."}}}}} - request := document_observation_request(t, kind, result) - if exportable_speech(request) != (source == "ordinary") { - t.Fatalf("source %s produced exportable=%v", source, exportable_speech(request)) + request := documentObservationRequest(t, kind, result) + if exportableSpeech(request) != (source == "ordinary") { + t.Fatalf("source %s produced exportable=%v", source, exportableSpeech(request)) } }) } @@ -85,20 +85,20 @@ func TestRemoteDocumentSpeechSourcePrivacy(t *testing.T) { {Contents: []atspi.DocumentContent{{Text: "text without source metadata"}}}, {Contents: []atspi.DocumentContent{{Snapshot: atspi.Snapshot{Role: "text"}}, {Snapshot: atspi.Snapshot{Role: "password text"}}}}, } { - if document_line_speech_origin(line) == speechOriginLocal { + if documentLineSpeechOrigin(line) == speechOriginLocal { t.Fatal("unclassified or mixed private line was exportable") } } for _, kind := range []string{"caret", "navigation", "read-all"} { - request := document_observation_request(t, kind, review.Result{Err: errors.New("fixture failure"), ReadAllContext: t.Context()}) - if exportable_speech(request) { + request := documentObservationRequest(t, kind, review.Result{Err: errors.New("fixture failure"), ReadAllContext: t.Context()}) + if exportableSpeech(request) { t.Fatal("local failure status was exported", kind) } } } func TestRemoteDocumentSpeechFragmentPrivacy(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) for _, kind := range []string{"caret", "read-all"} { for _, source := range []string{"ordinary", "password", "ancestor", "snapshot-ancestor", "unknown", "unknown-role", "invalid", "defunct", "missing"} { t.Run(kind+"/"+source, func(t *testing.T) { @@ -129,20 +129,20 @@ func TestRemoteDocumentSpeechFragmentPrivacy(t *testing.T) { DocumentPosition: review.DocumentPosition{Snapshot: caret}, DocumentCaretText: "Joined colour.", DocumentCaretContext: []atspi.Snapshot{caret, {Role: "document web"}}, DocumentCaretLine: &line, ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line}} - request := document_observation_request(t, kind, result) - if exportable_speech(request) != (source == "ordinary") { - t.Fatalf("fragment %s produced exportable=%v", source, exportable_speech(request)) + request := documentObservationRequest(t, kind, result) + if exportableSpeech(request) != (source == "ordinary") { + t.Fatalf("fragment %s produced exportable=%v", source, exportableSpeech(request)) } if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } if source == "ordinary" { - if value := observed_speech(t, session); value.Kind != "speak" || value.Parts[0].Text != "Joined colour." { + if value := observedSpeech(t, session); value.Kind != "speak" || value.Parts[0].Text != "Joined colour." { t.Fatal("ordinary fragmented reading was not exported", value) } } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("fragment privacy failed before cancellation", value) } select { @@ -190,8 +190,8 @@ func TestRemoteDocumentSpeechCapturedNeighborPrivacy(t *testing.T) { t.Fatal("fixture caret has a password ancestor") } } - request := document_observation_request(t, "read-all", review.Result{ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line}}) - if len(request.ReadAll) == 0 || exportable_speech(request) { + request := documentObservationRequest(t, "read-all", review.Result{ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line}}) + if len(request.ReadAll) == 0 || exportableSpeech(request) { t.Fatal("captured neighbor ancestry was lost before speech admission") } } @@ -204,33 +204,33 @@ func (speaker *observationSpeaker) SpeakAndWait(ctx context.Context, text string } func TestRemoteReadAllObservationResolvedChunksAndPrivateBatch(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } line := atspi.DocumentLine{Contents: []atspi.DocumentContent{{Snapshot: atspi.Snapshot{Role: "text"}, Text: "First colour. Second colour."}}} - request := document_observation_request(t, "read-all", review.Result{ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line}}) + request := documentObservationRequest(t, "read-all", review.Result{ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line}}) if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } for _, want := range []string{"First color.", "Second color."} { - value := observed_speech(t, session) + value := observedSpeech(t, session) if value.Kind != "speak" || len(value.Parts) != 2 || value.Parts[0].Text != want || !value.Parts[1].End { t.Fatal("Say All did not export resolved sentence boundaries", value) } } private := line private.Context = []atspi.Snapshot{{Role: "password text"}} - request = document_observation_request(t, "read-all", review.Result{ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line, private, line}}) + request = documentObservationRequest(t, "read-all", review.Result{ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{line, private, line}}) if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("mixed private Say All batch was exported", value) } } func TestRemoteReadAllObservationKeepsOriginalLease(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) speaker := &continuousSpeaker{started: make(chan string, 2), finish: make(chan struct{}, 2)} worker.speaker = speaker // No requests have been admitted yet. worker.Enqueue(speechRequest{origin: speechOriginLocal, ReadAll: []readAllPart{{Text: "First"}, {Text: "Second"}}}) @@ -239,12 +239,12 @@ func TestRemoteReadAllObservationKeepsOriginalLease(t *testing.T) { case <-time.After(time.Second): t.Fatal("Say All did not start") } - if value := observed_speech(t, session); value.Parts[0].Text != "First" { + if value := observedSpeech(t, session); value.Parts[0].Text != "First" { t.Fatal("first line missing", value) } session.RevokeRemote() var event tentaclewire.SessionEvent - if json.Unmarshal(observation_call(t, session, "event"), &event) != nil || event.Kind != "remote.revoked" { + if json.Unmarshal(observationCall(t, session, "event"), &event) != nil || event.Kind != "remote.revoked" { t.Fatal("missing revocation") } approval, err := session.BeginRemoteApproval("controlled", []string{"output-observe"}) @@ -254,7 +254,7 @@ func TestRemoteReadAllObservationKeepsOriginalLease(t *testing.T) { if _, err := session.AuthorizeRemoteWithApproval(approval, "controlled", []string{"output-observe"}); err != nil { t.Fatal(err) } - observation_call(t, session, "open") + observationCall(t, session, "open") speaker.finish <- struct{}{} select { case text := <-speaker.started: @@ -269,7 +269,7 @@ func TestRemoteReadAllObservationKeepsOriginalLease(t *testing.T) { t.Fatal(err) } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("old Say All continued under replacement consent", value) } } diff --git a/internal/app/speech_interrupt.go b/internal/app/speech_interrupt.go index d5a2cee..a87e51c 100644 --- a/internal/app/speech_interrupt.go +++ b/internal/app/speech_interrupt.go @@ -49,7 +49,7 @@ func (worker *speechWorker) SetEnabled(enabled bool) { } func (worker *speechWorker) interruptLocked() { - worker.retire_remote_speech_locked() + worker.retireRemoteSpeechLocked() if worker.hintCancel != nil { worker.hintCancel() } @@ -77,7 +77,7 @@ func (worker *speechWorker) interruptLocked() { worker.pending = nil worker.generation++ worker.interrupting = true - worker.observe_cancel_locked() + worker.observeCancelLocked() select { case worker.interrupt <- struct{}{}: @@ -89,7 +89,7 @@ func (worker *speechWorker) BeginReadAll(ctx context.Context, timestamp uint32) worker.mutex.Lock() defer worker.mutex.Unlock() worker.startupUntil = time.Time{} - if !worker.has_uninterruptible_locked() { + if !worker.hasUninterruptibleLocked() { worker.interruptLocked() } else if worker.readAllCancel != nil { worker.readAllCancel() @@ -103,7 +103,7 @@ func (worker *speechWorker) BeginReadAll(ctx context.Context, timestamp uint32) func (worker *speechWorker) InterruptForInput(event input.Event) bool { worker.mutex.Lock() defer worker.mutex.Unlock() - return worker.interrupt_for_input_locked(event) + return worker.interruptForInputLocked(event) } // Terminal keystrokes normally belong entirely to its delegated reader. Only @@ -115,10 +115,10 @@ func (worker *speechWorker) InterruptForHandoffInput(event input.Event) bool { if !worker.handoffSpeech { return false } - return worker.interrupt_for_input_locked(event) + return worker.interruptForInputLocked(event) } -func (worker *speechWorker) interrupt_for_input_locked(event input.Event) bool { +func (worker *speechWorker) interruptForInputLocked(event input.Event) bool { if event.Timestamp != 0 && worker.commandTimestamp != 0 && int32(event.Timestamp-worker.commandTimestamp) <= 0 { return false } @@ -135,7 +135,7 @@ func (worker *speechWorker) interrupt_for_input_locked(event input.Event) bool { if event.Timestamp != 0 { worker.lastInputTimestamp = event.Timestamp } - if worker.has_uninterruptible_locked() { + if worker.hasUninterruptibleLocked() { return false } worker.startupUntil = time.Time{} @@ -155,7 +155,7 @@ func (worker *speechWorker) ProtectCommand(timestamp uint32) { if timestamp != 0 { worker.commandTimestamp = timestamp } - if !worker.has_uninterruptible_locked() { + if !worker.hasUninterruptibleLocked() { worker.startupUntil = time.Time{} worker.interruptLocked() } @@ -173,7 +173,7 @@ func (worker *speechWorker) EnqueueStartup(request speechRequest) { func (worker *speechWorker) InterruptForUser() { worker.mutex.Lock() defer worker.mutex.Unlock() - if worker.has_uninterruptible_locked() { + if worker.hasUninterruptibleLocked() { return } worker.startupUntil = time.Time{} diff --git a/internal/app/speech_mode.go b/internal/app/speech_mode.go index 39e6268..c32ae02 100644 --- a/internal/app/speech_mode.go +++ b/internal/app/speech_mode.go @@ -31,7 +31,7 @@ func (mode speechMode) announcement() string { } } -func (worker *speechWorker) cycle_speech_mode() speechMode { +func (worker *speechWorker) cycleSpeechMode() speechMode { worker.mutex.Lock() defer worker.mutex.Unlock() worker.mode = (worker.mode + 1) % 3 @@ -43,7 +43,7 @@ func (worker *speechWorker) cycle_speech_mode() speechMode { // Capture mode and beep cancellation together so a concurrent mode change or // key press cannot leave a beep running behind its interruption barrier. -func (worker *speechWorker) deliver_mode(ctx context.Context, request speechRequest) (bool, error) { +func (worker *speechWorker) deliverMode(ctx context.Context, request speechRequest) (bool, error) { worker.mutex.Lock() mode := worker.mode if request.ForceSpeech || mode == speechModeSpeech { @@ -52,13 +52,13 @@ func (worker *speechWorker) deliver_mode(ctx context.Context, request speechRequ } if mode == speechModeOff { worker.mutex.Unlock() - worker.log_mode_delivery(ctx, request, mode) + worker.logModeDelivery(ctx, request, mode) return true, nil } beepContext, cancelBeep := context.WithCancel(ctx) worker.beepCancel = cancelBeep worker.mutex.Unlock() - worker.log_mode_delivery(ctx, request, mode) + worker.logModeDelivery(ctx, request, mode) defer func() { cancelBeep() worker.mutex.Lock() @@ -71,7 +71,7 @@ func (worker *speechWorker) deliver_mode(ctx context.Context, request speechRequ return true, worker.beep(beepContext) } -func (worker *speechWorker) log_mode_delivery(ctx context.Context, request speechRequest, mode speechMode) { +func (worker *speechWorker) logModeDelivery(ctx context.Context, request speechRequest, mode speechMode) { // Say All depends on synth completion. In beeps/off, do not run those // callbacks and race the reading cursor to the end of the document. text := request.Text diff --git a/internal/app/speech_mode_test.go b/internal/app/speech_mode_test.go index 640e63d..2869d1a 100644 --- a/internal/app/speech_mode_test.go +++ b/internal/app/speech_mode_test.go @@ -162,7 +162,7 @@ func TestSpeechModeSwitchCancelsActiveBeepAndDropsPendingSpeech(t *testing.T) { t.Fatal("beep did not start") } worker.Enqueue(speechRequest{Text: "Queued"}) - if got := worker.cycle_speech_mode(); got != speechModeOff { + if got := worker.cycleSpeechMode(); got != speechModeOff { t.Fatalf("mode = %v", got) } select { diff --git a/internal/app/speech_native_where_am_i_test.go b/internal/app/speech_native_where_am_i_test.go index de89f30..cb4e1f2 100644 --- a/internal/app/speech_native_where_am_i_test.go +++ b/internal/app/speech_native_where_am_i_test.go @@ -17,9 +17,9 @@ import ( "git.stormux.org/storm/cthulhu/internal/review" ) -func native_where_am_i_handler(t *testing.T) (*eventReviewHandler, *fakeSpeechQueue, review.Result) { +func nativeWhereAmIHandler(t *testing.T) (*eventReviewHandler, *fakeSpeechQueue, review.Result) { t.Helper() - result := native_current_line_result() + result := nativeCurrentLineResult() result.WhereAmI, result.DocumentFocus = true, result.DocumentPosition.Snapshot.ID() result.DocumentPosition.Snapshot.Name = "Native colour." worker, err := review.NewWorker(&fakeAdapter{}, time.Second) @@ -36,9 +36,9 @@ func native_where_am_i_handler(t *testing.T) (*eventReviewHandler, *fakeSpeechQu return handler, queue, result } -func native_where_am_i_request(t *testing.T, privacy string) speechRequest { +func nativeWhereAmIRequest(t *testing.T, privacy string) speechRequest { t.Helper() - handler, queue, result := native_where_am_i_handler(t) + handler, queue, result := nativeWhereAmIHandler(t) switch privacy { case "password": result.DocumentPosition.Snapshot.Role = "password text" @@ -74,9 +74,9 @@ func native_where_am_i_request(t *testing.T, privacy string) speechRequest { func TestRemoteNativeWhereAmISourcePrivacy(t *testing.T) { for _, privacy := range []string{"ordinary", "password", "ancestor", "unknown", "invalid", "defunct", "missing", "truncated", "mismatched", "foreign", "changed-text", "cached-ancestor", "fresh-ancestor", "failure"} { t.Run(privacy, func(t *testing.T) { - request := native_where_am_i_request(t, privacy) - if exportable_speech(request) != (privacy == "ordinary") { - t.Fatalf("privacy %s produced exportable=%v", privacy, exportable_speech(request)) + request := nativeWhereAmIRequest(t, privacy) + if exportableSpeech(request) != (privacy == "ordinary") { + t.Fatalf("privacy %s produced exportable=%v", privacy, exportableSpeech(request)) } if !strings.Contains(request.Text, "Native colour.") || request.Cause != "where-am-i" { t.Fatal("privacy verification changed the local report", request.Text) @@ -88,7 +88,7 @@ func TestRemoteNativeWhereAmISourcePrivacy(t *testing.T) { func TestRemoteNativeWhereAmIRetiresCapture(t *testing.T) { for _, change := range []string{"snapshot", "focus", "epoch", "lock", "handoff", "foreground"} { t.Run(change, func(t *testing.T) { - handler, queue, result := native_where_am_i_handler(t) + handler, queue, result := nativeWhereAmIHandler(t) switch change { case "snapshot": handler.state.setCurrent(handler.state.current) @@ -121,14 +121,14 @@ type whereAmIObservationQueue struct { active bool } -func (queue *whereAmIObservationQueue) remote_observation_active() bool { return queue.active } +func (queue *whereAmIObservationQueue) remoteObservationActive() bool { return queue.active } func (capturer *whereAmICapturer) ReadFocusedSnapshot(context.Context, atspi.ObjectID) (atspi.DocumentContent, error) { return capturer.content, nil } func TestRemoteNativeWhereAmIQueuesCapture(t *testing.T) { - handler, queue, result := native_where_am_i_handler(t) + handler, queue, result := nativeWhereAmIHandler(t) capturer := &whereAmICapturer{fakeAdapter: &fakeAdapter{}, content: atspi.DocumentContent{ Snapshot: result.DocumentPosition.Snapshot, SourceContext: result.DocumentCaretContext}} worker, err := review.NewWorker(capturer, time.Second) @@ -140,7 +140,7 @@ func TestRemoteNativeWhereAmIQueuesCapture(t *testing.T) { observedQueue := &whereAmIObservationQueue{fakeSpeechQueue: queue} handler.speech = observedQueue handler.whereAmI() - if request := <-queue.requests; exportable_speech(request) { + if request := <-queue.requests; exportableSpeech(request) { t.Fatal("inactive observation authorized native export") } <-queue.spoken @@ -156,7 +156,7 @@ func TestRemoteNativeWhereAmIQueuesCapture(t *testing.T) { select { case captured := <-worker.Results(): handler.handle(captured) - if request := <-queue.requests; !exportable_speech(request) { + if request := <-queue.requests; !exportableSpeech(request) { t.Fatal("ordinary native report stayed private after fresh verification") } case <-time.After(time.Second): @@ -165,31 +165,31 @@ func TestRemoteNativeWhereAmIQueuesCapture(t *testing.T) { } func TestRemoteNativeWhereAmIResolvedOutput(t *testing.T) { - worker, session, _, _ := observation_fixture(t) - if !worker.remote_observation_active() { + worker, session, _, _ := observationFixture(t) + if !worker.remoteObservationActive() { t.Fatal("live software observer did not enable source verification") } worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } for _, privacy := range []string{"ordinary", "ancestor", "changed-text", "failure"} { - if err := worker.EnqueueAndWait(t.Context(), native_where_am_i_request(t, privacy)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), nativeWhereAmIRequest(t, privacy)); err != nil { t.Fatal(err) } for len(worker.speaker.(*observationSpeaker).spoken) > 0 { want := <-worker.speaker.(*observationSpeaker).spoken if privacy == "ordinary" { - value := observed_speech(t, session) + value := observedSpeech(t, session) if value.Kind != "speak" || len(value.Parts) != 2 || value.Parts[0].Text != want || !value.Parts[1].End { t.Fatal("native Where Am I export lost resolved text or chunks", value) } } } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("private native report reached the child", value) } } session.RevokeRemote() - if worker.remote_observation_active() { + if worker.remoteObservationActive() { t.Fatal("revoked observer still enabled native verification") } } diff --git a/internal/app/speech_observation.go b/internal/app/speech_observation.go index a1323e7..3655651 100644 --- a/internal/app/speech_observation.go +++ b/internal/app/speech_observation.go @@ -22,7 +22,7 @@ const ( speechOriginSecret ) -func accessibility_speech_origin(source atspi.Snapshot) speechOrigin { +func accessibilitySpeechOrigin(source atspi.Snapshot) speechOrigin { if source.Role == "password text" { return speechOriginSecret } @@ -33,37 +33,37 @@ func accessibility_speech_origin(source atspi.Snapshot) speechOrigin { return speechOriginSecret } } - if !known_speech_source(source) { + if !knownSpeechSource(source) { return speechOriginUnknown } for _, ancestor := range source.SpeechContext { - if !known_speech_source(ancestor) { + if !knownSpeechSource(ancestor) { return speechOriginUnknown } } return speechOriginLocal } -func known_speech_source(source atspi.Snapshot) bool { +func knownSpeechSource(source atspi.Snapshot) bool { return !source.Defunct && source.Role != "" && source.Role != "unknown" && source.Role != "invalid" } // Document producers may remove the current object from their presentation // context. Inspect the original sources before that filtering, including every // content object in an assembled line. A mixed sensitive line stays private. -func document_speech_origin(source atspi.Snapshot, ancestors []atspi.Snapshot) speechOrigin { - if origin := accessibility_speech_origin(source); origin != speechOriginLocal { +func documentSpeechOrigin(source atspi.Snapshot, ancestors []atspi.Snapshot) speechOrigin { + if origin := accessibilitySpeechOrigin(source); origin != speechOriginLocal { return origin } for _, ancestor := range ancestors { - if origin := accessibility_speech_origin(ancestor); origin != speechOriginLocal { + if origin := accessibilitySpeechOrigin(ancestor); origin != speechOriginLocal { return origin } } return speechOriginLocal } -func document_line_speech_origin(line atspi.DocumentLine) speechOrigin { +func documentLineSpeechOrigin(line atspi.DocumentLine) speechOrigin { if len(line.Contents) == 0 { return speechOriginUnknown } @@ -72,13 +72,13 @@ func document_line_speech_origin(line atspi.DocumentLine) speechOrigin { return speechOriginUnknown } for _, source := range sources { - if origin := document_speech_origin(source, nil); origin != speechOriginLocal { + if origin := documentSpeechOrigin(source, nil); origin != speechOriginLocal { return origin } } } for _, content := range line.Contents { - if origin := document_speech_origin(content.Snapshot, line.Context); origin != speechOriginLocal { + if origin := documentSpeechOrigin(content.Snapshot, line.Context); origin != speechOriginLocal { return origin } } @@ -87,7 +87,7 @@ func document_line_speech_origin(line atspi.DocumentLine) speechOrigin { // Review privacy metadata comes from the same owned capture as its text. // Missing ancestry and unknown roles deny export, including any joined zone. -func review_speech_origin(contexts ...[]atspi.Snapshot) speechOrigin { +func reviewSpeechOrigin(contexts ...[]atspi.Snapshot) speechOrigin { if len(contexts) == 0 { return speechOriginUnknown } @@ -96,7 +96,7 @@ func review_speech_origin(contexts ...[]atspi.Snapshot) speechOrigin { return speechOriginUnknown } for _, source := range sources { - if origin := document_speech_origin(source, source.SpeechContext); origin != speechOriginLocal { + if origin := documentSpeechOrigin(source, source.SpeechContext); origin != speechOriginLocal { return origin } } @@ -104,7 +104,7 @@ func review_speech_origin(contexts ...[]atspi.Snapshot) speechOrigin { return speechOriginLocal } -func exportable_speech(request speechRequest) bool { +func exportableSpeech(request speechRequest) bool { if request.origin != speechOriginLocal || request.Role == "password text" || request.ExcludeFromHistory || request.Confirmation || request.Uninterruptible || request.ForceSpeech { return false @@ -117,7 +117,7 @@ func exportable_speech(request speechRequest) bool { return true } -func (worker *speechWorker) observe_remote_output(manager *tentacle.Manager) { +func (worker *speechWorker) observeRemoteOutput(manager *tentacle.Manager) { worker.mutex.Lock() defer worker.mutex.Unlock() worker.remoteOutput = manager.CaptureRemoteSpeechOutput @@ -125,7 +125,7 @@ func (worker *speechWorker) observe_remote_output(manager *tentacle.Manager) { // Optional source verification must not add native reads to ordinary commands // when no live observer could receive their output. -func (worker *speechWorker) remote_observation_active() bool { +func (worker *speechWorker) remoteObservationActive() bool { worker.mutex.Lock() defer worker.mutex.Unlock() return worker.running && worker.enabled && !worker.secure && worker.mode == speechModeSpeech && @@ -135,8 +135,8 @@ func (worker *speechWorker) remote_observation_active() bool { // Serialize observation with user interruption. No event may be published after // that interruption's cancel using an older delivery generation. This performs // bounded IPC queue admission only, never pipe, relay or backend I/O. -func (worker *speechWorker) observe_speech(ctx context.Context, request speechRequest, text string, characters bool) { - if request.observation == nil || !exportable_speech(request) || ctx.Err() != nil { +func (worker *speechWorker) observeSpeech(ctx context.Context, request speechRequest, text string, characters bool) { + if request.observation == nil || !exportableSpeech(request) || ctx.Err() != nil { return } worker.mutex.Lock() @@ -149,7 +149,7 @@ func (worker *speechWorker) observe_speech(ctx context.Context, request speechRe _ = request.observation.PublishText(text, characters) } -func (worker *speechWorker) observe_cancel_locked() { +func (worker *speechWorker) observeCancelLocked() { if worker.remoteOutput != nil && !worker.secure { if output := worker.remoteOutput(); output != nil { _ = output.Cancel() diff --git a/internal/app/speech_observation_test.go b/internal/app/speech_observation_test.go index 5ad8d48..140c1a3 100644 --- a/internal/app/speech_observation_test.go +++ b/internal/app/speech_observation_test.go @@ -58,7 +58,7 @@ func (speaker *observationSpeaker) SpeakCharacter(ctx context.Context, text stri return speaker.Speak(ctx, text) } -func observation_fixture(t *testing.T) (*speechWorker, *tentacle.Session, *tentacle.Manager, *tentacle.RemotePolicy) { +func observationFixture(t *testing.T) (*speechWorker, *tentacle.Session, *tentacle.Manager, *tentacle.RemotePolicy) { t.Helper() executable, err := os.Executable() if err != nil { @@ -100,10 +100,10 @@ func observation_fixture(t *testing.T) (*speechWorker, *tentacle.Session, *tenta if _, err := session.AuthorizeRemoteWithApproval(approval, "controlled", []string{"output-observe"}); err != nil { t.Fatal(err) } - observation_call(t, session, "open") + observationCall(t, session, "open") speaker := &observationSpeaker{fakeSpeaker{spoken: make(chan string, 64)}} worker := newSpeechWorker(slog.New(slog.DiscardHandler), speaker) - worker.observe_remote_output(manager) + worker.observeRemoteOutput(manager) if err := worker.Start(t.Context()); err != nil { t.Fatal(err) } @@ -117,7 +117,7 @@ func observation_fixture(t *testing.T) (*speechWorker, *tentacle.Session, *tenta return worker, session, manager, policy } -func observation_call(t *testing.T, session *tentacle.Session, command string) json.RawMessage { +func observationCall(t *testing.T, session *tentacle.Session, command string) json.RawMessage { t.Helper() ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() @@ -137,17 +137,17 @@ func observation_call(t *testing.T, session *tentacle.Session, command string) j } } -func observed_speech(t *testing.T, session *tentacle.Session) tentaclewire.RemoteSpeech { +func observedSpeech(t *testing.T, session *tentacle.Session) tentaclewire.RemoteSpeech { t.Helper() var event tentaclewire.SessionEvent - if err := json.Unmarshal(observation_call(t, session, "event"), &event); err != nil || event.Kind != "remote.output" || event.Speech == nil { + if err := json.Unmarshal(observationCall(t, session, "event"), &event); err != nil || event.Kind != "remote.output" || event.Speech == nil { t.Fatal("expected observed speech event", event.Kind, err) } return *event.Speech } func TestRemoteSpeechObservationResolvedOutputAndPrivateOrigins(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } for _, request := range []speechRequest{ {Text: "colour", origin: speechOriginLocal}, @@ -160,7 +160,7 @@ func TestRemoteSpeechObservationResolvedOutputAndPrivateOrigins(t *testing.T) { } } for index, text := range []string{"color", "A", "one", "two", "a", "b"} { - speech := observed_speech(t, session) + speech := observedSpeech(t, session) if speech.Kind != "speak" || len(speech.Parts) != 2 || speech.Parts[0].Text != text || speech.Parts[0].Characters != (index == 1 || index >= 4) || !speech.Parts[1].End { t.Fatal("observation preceded policy/character resolution", speech) @@ -182,19 +182,19 @@ func TestRemoteSpeechObservationResolvedOutputAndPrivateOrigins(t *testing.T) { } } worker.InterruptForUser() - if speech := observed_speech(t, session); speech.Kind != "cancel" { + if speech := observedSpeech(t, session); speech.Kind != "cancel" { t.Fatal("exported private output before cancellation", speech) } } func TestRemoteSpeechObservationAccessibilityPresenter(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) state := &eventLoopState{} state.presentationOptions = presentation.DefaultOptions() presenter := eventPresenter{state: state, logger: slog.New(slog.DiscardHandler), speech: worker} presenter.speak(atspi.Event{Type: atspi.CaretEvent, Source: atspi.Snapshot{Path: "/entry", Role: "entry", CaretCharacter: "a"}}) - speech := observed_speech(t, session) + speech := observedSpeech(t, session) if speech.Kind != "speak" || speech.Parts[0].Text != "a" || !speech.Parts[0].Characters { t.Fatal("ordinary accessibility speech did not reach observation", speech) } @@ -216,13 +216,13 @@ func TestRemoteSpeechObservationAccessibilityPresenter(t *testing.T) { t.Fatal(err) } worker.InterruptForUser() - if speech := observed_speech(t, session); speech.Kind != "cancel" { + if speech := observedSpeech(t, session); speech.Kind != "cancel" { t.Fatal("filtered presentation context hid a private ancestor", speech) } } func TestRemoteSpeechObservationModesAndGeneration(t *testing.T) { - worker, session, manager, _ := observation_fixture(t) + worker, session, manager, _ := observationFixture(t) for _, mode := range []speechMode{speechModeOff, speechModeBeeps} { worker.mutex.Lock() worker.mode = mode @@ -237,12 +237,12 @@ func TestRemoteSpeechObservationModesAndGeneration(t *testing.T) { old := speechRequest{origin: speechOriginLocal, observation: manager.CaptureRemoteSpeechOutput(), deliveryGeneration: worker.generation} worker.mutex.Unlock() worker.InterruptForUser() - worker.observe_speech(t.Context(), old, "stale generation", false) - if speech := observed_speech(t, session); speech.Kind != "cancel" { + worker.observeSpeech(t.Context(), old, "stale generation", false) + if speech := observedSpeech(t, session); speech.Kind != "cancel" { t.Fatal("exported suppressed speech", speech) } worker.InterruptForUser() - if speech := observed_speech(t, session); speech.Kind != "cancel" { + if speech := observedSpeech(t, session); speech.Kind != "cancel" { t.Fatal("older generation overtook cancellation", speech) } } @@ -250,7 +250,7 @@ func TestRemoteSpeechObservationModesAndGeneration(t *testing.T) { func TestRemoteSpeechObservationRevokedBeforeDelivery(t *testing.T) { for _, change := range []string{"revoke", "lock", "handoff"} { t.Run(change, func(t *testing.T) { - worker, session, manager, policy := observation_fixture(t) + worker, session, manager, policy := observationFixture(t) request := speechRequest{origin: speechOriginLocal, observation: manager.CaptureRemoteSpeechOutput()} if request.observation == nil { t.Fatal("no observation ticket") @@ -267,9 +267,9 @@ func TestRemoteSpeechObservationRevokedBeforeDelivery(t *testing.T) { gate.SetSuspended(true) gate.SetSuspended(false) } - worker.observe_speech(t.Context(), request, "retired", false) + worker.observeSpeech(t.Context(), request, "retired", false) var event tentaclewire.SessionEvent - if err := json.Unmarshal(observation_call(t, session, "event"), &event); err != nil || event.Kind != "remote.revoked" { + if err := json.Unmarshal(observationCall(t, session, "event"), &event); err != nil || event.Kind != "remote.revoked" { t.Fatal("retirement exported text", event.Kind, err) } }) @@ -295,7 +295,7 @@ func (speaker *observationBarrierSpeaker) Speak(ctx context.Context, text string } func TestRemoteSpeechObservationCancellationBarrier(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) speaker := &observationBarrierSpeaker{fakeSpeaker: fakeSpeaker{spoken: make(chan string, 4)}, began: make(chan struct{}), release: make(chan struct{})} worker.speaker = speaker // No requests have reached this worker yet. @@ -305,12 +305,12 @@ func TestRemoteSpeechObservationCancellationBarrier(t *testing.T) { case <-time.After(time.Second): t.Fatal("backend did not block") } - if speech := observed_speech(t, session); speech.Parts[0].Text != "old active" { + if speech := observedSpeech(t, session); speech.Parts[0].Text != "old active" { t.Fatal("missing first attempt") } worker.Enqueue(speechRequest{Text: "old pending", origin: speechOriginLocal}) worker.InterruptForUser() - if speech := observed_speech(t, session); speech.Kind != "cancel" { + if speech := observedSpeech(t, session); speech.Kind != "cancel" { t.Fatal("cancel overtaken by pending output", speech) } close(speaker.release) @@ -319,13 +319,13 @@ func TestRemoteSpeechObservationCancellationBarrier(t *testing.T) { if err := worker.EnqueueAndWait(ctx, speechRequest{Text: "new generation", origin: speechOriginLocal}); err != nil { t.Fatal(err) } - if speech := observed_speech(t, session); speech.Parts[0].Text != "new generation" { + if speech := observedSpeech(t, session); speech.Parts[0].Text != "new generation" { t.Fatal("old pending speech crossed interruption", speech) } } func TestRemoteSpeechObservationQueuedAuthorityDoesNotFollowReconnect(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.reading = func() config.ReadingSettings { return config.DefaultSettings().Reading } speaker := &observationBarrierSpeaker{fakeSpeaker: fakeSpeaker{spoken: make(chan string, 8)}, began: make(chan struct{}), release: make(chan struct{})} @@ -349,7 +349,7 @@ func TestRemoteSpeechObservationQueuedAuthorityDoesNotFollowReconnect(t *testing worker.Enqueue(speechRequest{Text: "old consent", origin: speechOriginLocal, Context: []atspi.Snapshot{list}}) session.RevokeRemote() var event tentaclewire.SessionEvent - if err := json.Unmarshal(observation_call(t, session, "event"), &event); err != nil || event.Kind != "remote.revoked" { + if err := json.Unmarshal(observationCall(t, session, "event"), &event); err != nil || event.Kind != "remote.revoked" { t.Fatal("expected old lease revocation", err) } list.Name = "Before consent" @@ -361,20 +361,20 @@ func TestRemoteSpeechObservationQueuedAuthorityDoesNotFollowReconnect(t *testing if _, err := session.AuthorizeRemoteWithApproval(approval, "controlled", []string{"output-observe"}); err != nil { t.Fatal(err) } - observation_call(t, session, "open") + observationCall(t, session, "open") worker.Enqueue(speechRequest{Text: "new consent", origin: speechOriginLocal, Context: []atspi.Snapshot{}}) close(speaker.release) - if speech := observed_speech(t, session); speech.Kind != "speak" || speech.Parts[0].Text != "new consent" { + if speech := observedSpeech(t, session); speech.Kind != "speak" || speech.Parts[0].Text != "new consent" { t.Fatal("queued output acquired replacement consent", speech) } worker.InterruptForUser() - if speech := observed_speech(t, session); speech.Kind != "cancel" { + if speech := observedSpeech(t, session); speech.Kind != "cancel" { t.Fatal("unexpected output after replacement delivery", speech) } } func TestRemoteSpeechObservationOverflowPreservesLocalSpeech(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) // Exceed the complete utterance's frame budget. Remote must retire without // making local speech depend on a healthy child or exposing a prefix. text := strings.Repeat("x", 768*tentaclewire.RemoteSpeechQueueSize+1) diff --git a/internal/app/speech_review_observation_test.go b/internal/app/speech_review_observation_test.go index 569cfe9..2072011 100644 --- a/internal/app/speech_review_observation_test.go +++ b/internal/app/speech_review_observation_test.go @@ -16,7 +16,7 @@ import ( // Exercise the actual owned-tree cursors and presentation producers rather // than attaching an allow flag to synthetic text. -func review_observation_result(t *testing.T, kind, privacy string) review.Result { +func reviewObservationResult(t *testing.T, kind, privacy string) review.Result { t.Helper() id := func(path string) atspi.ObjectID { return atspi.NewObjectID(":1.42", path) } node := func(path, role, text string, x int32) atspi.TreeNode { @@ -98,7 +98,7 @@ func review_observation_result(t *testing.T, kind, privacy string) review.Result return result } -func review_observation_request(t *testing.T, kind string, result review.Result) speechRequest { +func reviewObservationRequest(t *testing.T, kind string, result review.Result) speechRequest { t.Helper() queue := &fakeSpeechQueue{requests: make(chan speechRequest, 1), spoken: make(chan string, 1)} logger := slog.New(slog.DiscardHandler) @@ -114,16 +114,16 @@ func TestRemoteReviewSourcePrivacy(t *testing.T) { for _, kind := range []string{"object", "line"} { for _, privacy := range []string{"ordinary", "password", "ancestor", "snapshot-ancestor", "unknown", "unknown-role", "invalid", "defunct", "unknown-ancestor", "unknown-snapshot-ancestor", "missing", "stale", "failure", "boundary"} { t.Run(kind+"/"+privacy, func(t *testing.T) { - result := review_observation_result(t, kind, privacy) + result := reviewObservationResult(t, kind, privacy) if privacy == "failure" { result.Err = errors.New("private fixture failure") } else if privacy == "boundary" { result.Moved = false result.FlatStep = 1 } - request := review_observation_request(t, kind, result) - if exportable_speech(request) != (privacy == "ordinary") { - t.Fatalf("privacy %s produced exportable=%v", privacy, exportable_speech(request)) + request := reviewObservationRequest(t, kind, result) + if exportableSpeech(request) != (privacy == "ordinary") { + t.Fatalf("privacy %s produced exportable=%v", privacy, exportableSpeech(request)) } if privacy != "failure" && privacy != "boundary" && privacy != "password" && !strings.Contains(request.Text, "Review colour.") { t.Fatal("privacy classification changed local reading", request.Text) @@ -135,22 +135,22 @@ func TestRemoteReviewSourcePrivacy(t *testing.T) { func TestRemoteFlatReviewChecksOnlySpokenZones(t *testing.T) { for _, kind := range []string{"word", "character"} { - result := review_observation_result(t, kind, "snapshot-ancestor") - request := review_observation_request(t, kind, result) - if !exportable_speech(request) || len(result.FlatPosition.SourceContexts) != 1 { + result := reviewObservationResult(t, kind, "snapshot-ancestor") + request := reviewObservationRequest(t, kind, result) + if !exportableSpeech(request) || len(result.FlatPosition.SourceContexts) != 1 { t.Fatal("private neighboring zone blocked ordinary word/character", kind) } } } func TestRemoteReviewResolvedOutput(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } for _, kind := range []string{"object", "line"} { for _, style := range []review.FlatSpeech{review.FlatSpeak, review.FlatSpell, review.FlatPhonetic} { - result := review_observation_result(t, kind, "ordinary") + result := reviewObservationResult(t, kind, "ordinary") result.FlatSpeech = style - request := review_observation_request(t, kind, result) + request := reviewObservationRequest(t, kind, result) if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } @@ -158,7 +158,7 @@ func TestRemoteReviewResolvedOutput(t *testing.T) { // this includes pronunciation and repeated spelling characters. for len(worker.speaker.(*observationSpeaker).spoken) > 0 { want := <-worker.speaker.(*observationSpeaker).spoken - value := observed_speech(t, session) + value := observedSpeech(t, session) characters := request.Character if len([]rune(want)) != 1 { characters = false // Expanded spaces/phonetic words use ordinary speech. @@ -168,13 +168,13 @@ func TestRemoteReviewResolvedOutput(t *testing.T) { t.Fatal("review export differed from resolved local output", value, want) } } - result = review_observation_result(t, kind, "snapshot-ancestor") + result = reviewObservationResult(t, kind, "snapshot-ancestor") result.FlatSpeech = style - if err := worker.EnqueueAndWait(t.Context(), review_observation_request(t, kind, result)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), reviewObservationRequest(t, kind, result)); err != nil { t.Fatal(err) } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("private review reached the child", value) } if len(worker.speaker.(*observationSpeaker).spoken) == 0 { diff --git a/internal/app/speech_settings.go b/internal/app/speech_settings.go index 1c83852..4e4bbdd 100644 --- a/internal/app/speech_settings.go +++ b/internal/app/speech_settings.go @@ -13,6 +13,7 @@ import ( "time" "git.stormux.org/storm/cthulhu/internal/config" + "git.stormux.org/storm/cthulhu/internal/i18n" "git.stormux.org/storm/cthulhu/internal/input" "git.stormux.org/storm/cthulhu/internal/speech" "git.stormux.org/storm/cthulhu/internal/tentaclewire" @@ -44,7 +45,7 @@ func (worker *preferencesWorker) announceSpeechSetting(message string) { func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, command input.Command) { if command == input.CycleProgressBarOutput { - worker.cycle_progress_output() + worker.cycleProgressOutput() return } ctx, cancel := context.WithTimeout(ctx, 6*time.Second) @@ -62,14 +63,14 @@ func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, comman } return } - worker.sync_extensions(ctx) + worker.syncExtensions(ctx) quickCommand, ok := quickSettingCommands[command] if !ok { return } - host := &quickSettingsHost{worker: worker, ctx: ctx, settings: worker.effective_settings(worker.settings)} + host := &quickSettingsHost{worker: worker, ctx: ctx, settings: worker.effectiveSettings(worker.settings)} if worker.quickMenu == nil { - worker.quickMenu = quicksettings.New(nil, quicksettings.Messages{}) + worker.quickMenu = quicksettings.New(nil, quicksettings.Messages{Translate: i18n.T}) } if !worker.quickMenu.Replace(host.categories()) && quicksettings.IsValueChange(quickCommand) { worker.announceSpeechSetting("The selected setting is no longer available") @@ -81,7 +82,7 @@ func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, comman return } if result.Changed { - if !worker.apply_quick_setting(ctx, host, result) { + if !worker.applyQuickSetting(ctx, host, result) { return } } @@ -100,7 +101,7 @@ var quickSettingCommands = map[input.Command]quicksettings.Command{ input.SelectNextSpeechCategory: quicksettings.NextCategory, } -var hardwareSynthesizers = []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} +var hardwareSynthesizers = []string{"litetalk", "doubletalk", "tripletalk", "dectalk", "dectalk-usb"} // quickToggle is one boolean setting in the Reading or Keyboard category. type quickToggle struct { @@ -187,7 +188,7 @@ func (host *quickSettingsHost) categories() []quicksettings.Category { } var tentacles []quicksettings.Entry host.extensions = make(map[string]readerQuickSetting) - for _, setting := range host.worker.quick_settings() { + for _, setting := range host.worker.quickSettings() { id := "tentacle." + setting.key host.extensions[id] = setting tentacles = append(tentacles, quicksettings.Entry{ID: id, Label: setting.setting.Label, Kind: quicksettings.Choice}) @@ -224,7 +225,7 @@ func (host *quickSettingsHost) Value(entry quicksettings.Entry) quicksettings.Va } switch entry.ID { case "speech.profile": - return quicksettings.Value{Choice: host.voice_profile_choice(settings)} + return quicksettings.Value{Choice: host.voiceProfileChoice(settings)} case "speech.rate": return number(settings.DefaultVoice.Rate, 0) case "speech.pitch": @@ -274,7 +275,7 @@ func (host *quickSettingsHost) catalog() bool { func (host *quickSettingsHost) Options(entry quicksettings.Entry) []quicksettings.Option { switch entry.ID { case "speech.profile": - return host.settings.VoiceProfiles.Quick_options(config.Primary_voice(host.settings), host.saved_voice()) + return host.settings.VoiceProfiles.QuickOptions(config.PrimaryVoice(host.settings), host.savedVoiceProfile()) case "speech.module": var options []quicksettings.Option if host.hardware() { @@ -398,22 +399,22 @@ func (host *quickSettingsHost) set(settings *config.Settings, entry quicksetting return true } -// apply_quick_setting applies one change for this session. Speech changes are +// applyQuickSetting applies one change for this session. Speech changes are // validated by reconfiguring speech first; failures leave settings unchanged. -func (worker *preferencesWorker) apply_quick_setting(ctx context.Context, host *quickSettingsHost, result quicksettings.Result) bool { +func (worker *preferencesWorker) applyQuickSetting(ctx context.Context, host *quickSettingsHost, result quicksettings.Result) bool { if setting, ok := host.extensions[result.Entry.ID]; ok { - return worker.handle_extension_quick(ctx, setting, result.Value.Choice) + return worker.handleExtensionQuick(ctx, setting, result.Value.Choice) } next := host.settings var speechChanged bool if result.Entry.ID == "speech.profile" { - p, ok := next.VoiceProfiles.Quick_profile(result.Value.Choice, host.saved_voice()) + p, ok := next.VoiceProfiles.QuickProfile(result.Value.Choice, host.savedVoiceProfile()) if !ok { worker.announceSpeechSetting("Choose a saved voice profile") return false } var err error - next, err = config.Apply_primary_voice(next, p) + next, err = config.ApplyPrimaryVoice(next, p) if err != nil { worker.announceSpeechSetting("Voice profile was not changed: " + err.Error()) return false @@ -526,50 +527,50 @@ func quickSpeechVoices(module string, voices []speech.Voice) []speech.Voice { return speech.LocaleVoices(voices) } -// 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 (host *quickSettingsHost) voice_profile_choice(settings config.Settings) string { - return settings.VoiceProfiles.Quick_choice(config.Primary_voice(settings), host.saved_voice()) +func (host *quickSettingsHost) voiceProfileChoice(settings config.Settings) string { + return settings.VoiceProfiles.QuickChoice(config.PrimaryVoice(settings), host.savedVoiceProfile()) } -func (host *quickSettingsHost) saved_voice() *voiceprofiles.Profile { +func (host *quickSettingsHost) savedVoiceProfile() *voiceprofiles.Profile { if host.worker == nil { return nil } - return host.worker.saved_voice() + return host.worker.savedVoiceProfile() } -// saved_voice is the voice quick settings "Default" restores: the focused +// savedVoiceProfile is the voice quick settings "Default" restores: the focused // application's saved voice when it has its own, otherwise the global voice // from startup or the last explicit Apply. -func (worker *preferencesWorker) saved_voice() *voiceprofiles.Profile { +func (worker *preferencesWorker) savedVoiceProfile() *voiceprofiles.Profile { saved, ok := worker.savedApplications[worker.activeApp] if worker.savedVoice == nil || !ok { return worker.savedVoice } // Rebase onto the saved global voice so an application that inherits the // global voice keeps following it. - global, err := config.Apply_primary_voice(saved.global, *worker.savedVoice) + global, err := config.ApplyPrimaryVoice(saved.global, *worker.savedVoice) if err != nil { global = saved.global } - voice := config.Primary_voice(worker.effective_settings(config.RebaseApplicationSettings(saved.global, global, saved.application))) + voice := config.PrimaryVoice(worker.effectiveSettings(config.RebaseApplicationSettings(saved.global, global, saved.application))) return &voice } -// remember_saved_voice records the voice that quick settings "Default" +// rememberSavedVoice records the voice that quick settings "Default" // restores after an explicit Apply. An application Apply records only that // application's saved settings, over the global settings it was edited from. -func (worker *preferencesWorker) remember_saved_voice(settings config.Settings, application string) { +func (worker *preferencesWorker) rememberSavedVoice(settings config.Settings, application string) { if application != "" { - worker.remember_application(application, worker.globalSettings, settings) + worker.rememberApplication(application, worker.globalSettings, settings) return } - saved := config.Primary_voice(worker.effective_settings(settings)) + saved := config.PrimaryVoice(worker.effectiveSettings(settings)) worker.savedVoice = &saved } -func (worker *preferencesWorker) remember_application(application string, global, settings config.Settings) { +func (worker *preferencesWorker) rememberApplication(application string, global, settings config.Settings) { if worker.savedApplications == nil { worker.savedApplications = make(map[string]savedApplicationSettings) } diff --git a/internal/app/speech_uninterruptible.go b/internal/app/speech_uninterruptible.go index 7e787c3..671941d 100644 --- a/internal/app/speech_uninterruptible.go +++ b/internal/app/speech_uninterruptible.go @@ -12,7 +12,7 @@ import ( // starts at admission, covering time spent in the bounded pending queue too. const uninterruptibleSpeechTimeout = 30 * time.Second -func (worker *speechWorker) has_uninterruptible_locked() bool { +func (worker *speechWorker) hasUninterruptibleLocked() bool { if worker.uninterruptibleContext != nil && worker.uninterruptibleContext.Err() == nil { return true } @@ -26,7 +26,7 @@ func (worker *speechWorker) has_uninterruptible_locked() bool { // Preserve unrelated queued speech when explicitly stopping protected output. // The existing cancellation barrier prevents CANCEL overtaking it. -func (worker *speechWorker) stop_uninterruptible() { +func (worker *speechWorker) stopUninterruptible() { worker.mutex.Lock() defer worker.mutex.Unlock() retained := worker.pending[:0] diff --git a/internal/app/speech_where_am_i_observation_test.go b/internal/app/speech_where_am_i_observation_test.go index 593ecef..198d8c1 100644 --- a/internal/app/speech_where_am_i_observation_test.go +++ b/internal/app/speech_where_am_i_observation_test.go @@ -15,11 +15,11 @@ import ( "git.stormux.org/storm/cthulhu/internal/review" ) -func where_am_i_observation_handler(t *testing.T, privacy string) (*eventReviewHandler, *fakeSpeechQueue) { +func whereAmIObservationHandler(t *testing.T, privacy string) (*eventReviewHandler, *fakeSpeechQueue) { t.Helper() // Use owned-tree ancestry, as document movement does, rather than treating // the presentation's filtered SpeechContext as a complete source capture. - position := review_observation_result(t, "object", privacy).Position + position := reviewObservationResult(t, "object", privacy).Position focus := atspi.NewObjectID(":1.42", "/document") worker, err := review.NewWorker(&fakeAdapter{}, time.Second) if err != nil { @@ -42,7 +42,7 @@ func where_am_i_observation_handler(t *testing.T, privacy string) (*eventReviewH func TestRemoteWhereAmIInvalidatesSource(t *testing.T) { for _, change := range []string{"same-object-update", "say-all-position", "focus", "epoch", "foreground", "missing-owner", "no-location"} { t.Run(change, func(t *testing.T) { - handler, queue := where_am_i_observation_handler(t, "ordinary") + handler, queue := whereAmIObservationHandler(t, "ordinary") switch change { case "same-object-update": // Even identical native text cannot reuse older capture ancestry. @@ -64,7 +64,7 @@ func TestRemoteWhereAmIInvalidatesSource(t *testing.T) { } handler.whereAmI() request := <-queue.requests - if exportable_speech(request) { + if exportableSpeech(request) { t.Fatal("Where Am I reused retired source classification") } if change != "no-location" && !strings.Contains(request.Text, "Review colour.") { @@ -75,20 +75,20 @@ func TestRemoteWhereAmIInvalidatesSource(t *testing.T) { } func TestRemoteWhereAmIRejectsMismatchedSource(t *testing.T) { - handler, queue := where_am_i_observation_handler(t, "ordinary") + handler, queue := whereAmIObservationHandler(t, "ordinary") current := handler.state.current handler.state.setCurrentDocument(review.Result{DocumentFocus: handler.objectReview.Focus(), DocumentPosition: review.DocumentPosition{Snapshot: current}, DocumentCaretContext: []atspi.Snapshot{{BusName: current.BusName, Path: "/other", Role: "static"}}}) handler.whereAmI() - if exportable_speech(<-queue.requests) { + if exportableSpeech(<-queue.requests) { t.Fatal("unrelated ancestry authorized Where Am I export") } } func TestRemoteWhereAmISecureFocus(t *testing.T) { for _, mode := range []string{"lock", "handoff", "foreground-handoff"} { - handler, queue := where_am_i_observation_handler(t, "ordinary") + handler, queue := whereAmIObservationHandler(t, "ordinary") if mode == "lock" { handler.focusGate.SetLocked(true, nil, nil, nil, nil, &brailleWorker{}) } else if mode == "foreground-handoff" { @@ -104,32 +104,32 @@ func TestRemoteWhereAmISecureFocus(t *testing.T) { } func TestRemoteWhereAmIResolvedOutput(t *testing.T) { - worker, session, _, _ := observation_fixture(t) + worker, session, _, _ := observationFixture(t) worker.textTransform = func(text string) string { return strings.ReplaceAll(text, "colour", "color") } for _, privacy := range []string{"ordinary", "snapshot-ancestor", "missing", "stale"} { - request := where_am_i_observation_request(t, privacy) + request := whereAmIObservationRequest(t, privacy) if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } for len(worker.speaker.(*observationSpeaker).spoken) > 0 { want := <-worker.speaker.(*observationSpeaker).spoken if privacy == "ordinary" { - value := observed_speech(t, session) + value := observedSpeech(t, session) if value.Kind != "speak" || len(value.Parts) != 2 || value.Parts[0].Text != want || !value.Parts[1].End { t.Fatal("Where Am I export differed from resolved local chunks", value, want) } } } worker.InterruptForUser() - if value := observed_speech(t, session); value.Kind != "cancel" { + if value := observedSpeech(t, session); value.Kind != "cancel" { t.Fatal("private Where Am I reached the child", value) } } } -func where_am_i_observation_request(t *testing.T, privacy string) speechRequest { +func whereAmIObservationRequest(t *testing.T, privacy string) speechRequest { t.Helper() - handler, queue := where_am_i_observation_handler(t, privacy) + handler, queue := whereAmIObservationHandler(t, privacy) handler.whereAmI() return <-queue.requests } @@ -137,9 +137,9 @@ func where_am_i_observation_request(t *testing.T, privacy string) speechRequest func TestRemoteWhereAmISourcePrivacy(t *testing.T) { for _, privacy := range []string{"ordinary", "password", "ancestor", "snapshot-ancestor", "unknown", "unknown-role", "invalid", "defunct", "unknown-ancestor", "unknown-snapshot-ancestor", "missing", "stale"} { t.Run(privacy, func(t *testing.T) { - request := where_am_i_observation_request(t, privacy) - if exportable_speech(request) != (privacy == "ordinary") { - t.Fatalf("privacy %s produced exportable=%v", privacy, exportable_speech(request)) + request := whereAmIObservationRequest(t, privacy) + if exportableSpeech(request) != (privacy == "ordinary") { + t.Fatalf("privacy %s produced exportable=%v", privacy, exportableSpeech(request)) } if privacy != "password" && !strings.Contains(request.Text, "Review colour.") { t.Fatal("source privacy changed local Where Am I", request.Text) diff --git a/internal/app/speech_worker.go b/internal/app/speech_worker.go index 629faa8..ccdd7c3 100644 --- a/internal/app/speech_worker.go +++ b/internal/app/speech_worker.go @@ -212,8 +212,8 @@ func (worker *speechWorker) Enqueue(request speechRequest) { return } request.observation = nil - worker.retire_remote_speech_locked() - if worker.remoteOutput != nil && exportable_speech(request) && !worker.secure { + worker.retireRemoteSpeechLocked() + if worker.remoteOutput != nil && exportableSpeech(request) && !worker.secure { request.observation = worker.remoteOutput() } request.Append = true @@ -230,7 +230,7 @@ func (worker *speechWorker) Enqueue(request speechRequest) { } else if worker.confirmationID != 0 { request.Append = true } - if worker.has_uninterruptible_locked() { + if worker.hasUninterruptibleLocked() { request.Append = true } // Pair a title with the next announcement from its window. User input @@ -309,7 +309,7 @@ func (worker *speechWorker) Stop(ctx context.Context) error { return nil } worker.running = false - worker.retire_remote_speech_locked() + worker.retireRemoteSpeechLocked() worker.confirmationID = 0 if worker.uninterruptibleCancel != nil { worker.uninterruptibleCancel() diff --git a/internal/app/submitted_text.go b/internal/app/submitted_text.go index 55a4309..d37b16a 100644 --- a/internal/app/submitted_text.go +++ b/internal/app/submitted_text.go @@ -12,7 +12,7 @@ import ( // A submission can clear an entry before its message appears in a transcript. // Do not mistake that clear for an editing command. Unknown input/caret data, // other controls and selected-text replacement keep their existing feedback. -func (state *eventLoopState) submitted_text_clear(event atspi.Event, activity input.Activity) bool { +func (state *eventLoopState) submittedTextClear(event atspi.Event, activity input.Activity) bool { source := event.Source if event.Type != atspi.TextDeletedEvent || event.Payload == "" || event.Detail1 != 0 || !activity.PlainEnter || activity.Sequence == 0 || !atspi.IsEchoEditField(source) || diff --git a/internal/app/submitted_text_native_test.go b/internal/app/submitted_text_native_test.go index 8c0312c..aad2fba 100644 --- a/internal/app/submitted_text_native_test.go +++ b/internal/app/submitted_text_native_test.go @@ -87,7 +87,7 @@ func TestNativeSubmissionClearAndSelectedReplacement(t *testing.T) { if !listener.RecentInput().PlainEnter { t.Fatal("native X11 Enter activity missing") } - got := submitted_text_speech(t, listener, focus, event) + got := submittedTextSpeech(t, listener, focus, event) if mode == "submit" && len(got) != 1 { t.Fatalf("native submission echoed deletion: %q; snapshot=%+v", got, event.Source) } diff --git a/internal/app/submitted_text_test.go b/internal/app/submitted_text_test.go index d6f3899..9c0bd5c 100644 --- a/internal/app/submitted_text_test.go +++ b/internal/app/submitted_text_test.go @@ -26,7 +26,7 @@ func TestSubmittedMessageIsAnnouncedOnce(t *testing.T) { tracker := &input.IntentTracker{} tracker.Observe(input.NewKeyEvent(0, true, key)) tracker.Observe(input.NewKeyEvent(0, false, key)) - got := submitted_text_speech(t, tracker, entry, deletion, + got := submittedTextSpeech(t, tracker, entry, deletion, atspi.NewEvent(atspi.CaretEvent, entry.Source), message) want := []string{"text", "Username: A sample message."} if !slices.Equal(got, want) { @@ -82,7 +82,7 @@ func TestSubmissionClearPreservesEditingFeedback(t *testing.T) { if test.insert != "" { events = append(events, atspi.NewEventWithPayload(atspi.TextInsertedEvent, entry, test.insert)) } - got := submitted_text_speech(t, tracker, events...) + got := submittedTextSpeech(t, tracker, events...) // Initial focus also presents an existing selection. got = got[1:] if !slices.Equal(got, test.want) { @@ -92,7 +92,7 @@ func TestSubmissionClearPreservesEditingFeedback(t *testing.T) { } } -func submitted_text_speech(t *testing.T, inputSource any, events ...atspi.Event) []string { +func submittedTextSpeech(t *testing.T, inputSource any, events ...atspi.Event) []string { t.Helper() adapter := &fakeAdapter{events: make(chan atspi.Event, len(events))} for _, event := range events { diff --git a/internal/app/tentacle_install_test.go b/internal/app/tentacle_install_test.go index 2f57987..50bbc45 100644 --- a/internal/app/tentacle_install_test.go +++ b/internal/app/tentacle_install_test.go @@ -30,7 +30,7 @@ func (transport installTransport) RoundTrip(request *http.Request) (*http.Respon return transport(request) } -func install_fixture(t *testing.T) (tentacle.Repository, []byte) { +func installFixture(t *testing.T) (tentacle.Repository, []byte) { t.Helper() program, err := os.Executable() if err != nil { @@ -73,7 +73,7 @@ func install_fixture(t *testing.T) (tentacle.Repository, []byte) { return repository, data.Bytes() } -func set_install_transport(t *testing.T, transport installTransport) { +func setInstallTransport(t *testing.T, transport installTransport) { t.Helper() previous := http.DefaultTransport http.DefaultTransport = transport @@ -81,22 +81,22 @@ func set_install_transport(t *testing.T, transport installTransport) { } func TestRepositoryPackageInstallEnableDisableRemoveAndOfflineRestart(t *testing.T) { - test_repository_package_install(t, false) + testRepositoryPackageInstall(t, false) } func TestSupervisedRepositoryPackageInstall(t *testing.T) { - test_repository_package_install(t, true) + testRepositoryPackageInstall(t, true) } -func test_repository_package_install(t *testing.T, contained bool) { - repository, data := install_fixture(t) +func testRepositoryPackageInstall(t *testing.T, contained bool) { + repository, data := installFixture(t) downloads := 0 - set_install_transport(t, func(*http.Request) (*http.Response, error) { + setInstallTransport(t, func(*http.Request) (*http.Response, error) { downloads++ return &http.Response{StatusCode: 200, ContentLength: int64(len(data)), Body: io.NopCloser(bytes.NewReader(data)), Header: make(http.Header)}, nil }) registryPath := filepath.Join(t.TempDir(), "tentacles.toml") - owner, bindings := managed_tentacle_fixture(t, registryPath, contained) + owner, bindings := managedTentacleFixture(t, registryPath, contained) if binary := os.Getenv("CTHULHU_TENTACLE_GUARDIAN_BINARY"); contained && binary != "" { owner.guardianProgram = []string{binary, "--tentacle-guardian"} } @@ -111,7 +111,7 @@ func test_repository_package_install(t *testing.T, contained bool) { t.Fatal(err) } id := tentacle.PackageID(repository, "echo") - wait_managed_state(t, owner, id, "disabled") + waitManagedState(t, owner, id, "disabled") entry := owner.Snapshot().Entries[0].Entry if entry.Enabled || downloads != 1 { t.Fatal(entry, downloads) @@ -119,23 +119,23 @@ func test_repository_package_install(t *testing.T, contained bool) { if err := owner.Manage(context.Background(), tentacle.ManagementRequest{Action: "install-enable", ID: "echo", URL: repository.URL}); err == nil { t.Fatal("duplicate install accepted") } - manage_tentacle(t, owner, "enable", id, nil) - wait_managed_state(t, owner, id, "active") + manageTentacle(t, owner, "enable", id, nil) + waitManagedState(t, owner, id, "active") owner.Invoke(context.Background(), bindings.TentacleBindings()[0].Command) waitTentacle(t, func() bool { _, err := os.Stat(entry.Program[len(entry.Program)-1]); return err == nil }) - manage_tentacle(t, owner, "disable", id, nil) - wait_managed_state(t, owner, id, "disabled") + manageTentacle(t, owner, "disable", id, nil) + waitManagedState(t, owner, id, "disabled") if _, err := os.Stat(entry.Program[0]); err != nil { t.Fatal("disable deleted package", err) } - manage_tentacle(t, owner, "enable", id, nil) - wait_managed_state(t, owner, id, "active") + manageTentacle(t, owner, "enable", id, nil) + waitManagedState(t, owner, id, "active") shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := owner.Stop(shutdown); err != nil { t.Fatal(err) } - restarted, _ := managed_tentacle_fixture(t, registryPath, contained) + restarted, _ := managedTentacleFixture(t, registryPath, contained) if binary := os.Getenv("CTHULHU_TENTACLE_GUARDIAN_BINARY"); contained && binary != "" { restarted.guardianProgram = []string{binary, "--tentacle-guardian"} } @@ -146,7 +146,7 @@ func test_repository_package_install(t *testing.T, contained bool) { if err := restarted.Start(context.Background()); err != nil { t.Fatal(err) } - wait_managed_state(t, restarted, id, "active") + waitManagedState(t, restarted, id, "active") if downloads != 1 { t.Fatal("enable/restart downloaded update", downloads) } @@ -156,7 +156,7 @@ func test_repository_package_install(t *testing.T, contained bool) { if _, err := os.Stat(entry.Program[0]); err != nil { t.Fatal("source removal deleted package", err) } - manage_tentacle(t, restarted, "remove", id, nil) + manageTentacle(t, restarted, "remove", id, nil) waitTentacle(t, func() bool { _, err := os.Stat(entry.PackageDirectory); return os.IsNotExist(err) }) disk, err := (&tentacle.Registry{Path: registryPath}).Load() if err != nil || len(disk) != 0 { @@ -165,7 +165,7 @@ func test_repository_package_install(t *testing.T, contained bool) { } func TestRepositoryPackageInstallFailureCancellationAndChangedCatalog(t *testing.T) { - repository, data := install_fixture(t) + repository, data := installFixture(t) for _, problem := range []string{"save failure", "cancel during download", "catalog changed", "emergency disable"} { t.Run(problem, func(t *testing.T) { registryPath := filepath.Join(t.TempDir(), "tentacles.toml") @@ -176,14 +176,14 @@ func TestRepositoryPackageInstallFailureCancellationAndChangedCatalog(t *testing if err := registry.SaveState(nil, []tentacle.Repository{repository}); err != nil { t.Fatal(err) } - owner, _ := managed_tentacle_fixture(t, registryPath, false) + owner, _ := managedTentacleFixture(t, registryPath, false) if err := owner.Start(context.Background()); err != nil { t.Fatal(err) } waitTentacle(t, func() bool { return len(owner.Snapshot().Repositories) == 1 }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - set_install_transport(t, func(request *http.Request) (*http.Response, error) { + setInstallTransport(t, func(request *http.Request) (*http.Response, error) { switch problem { case "save failure": if err := os.WriteFile(registryPath, []byte("# external edit\n"), 0600); err != nil { @@ -220,12 +220,12 @@ func TestRepositoryPackageInstallFailureCancellationAndChangedCatalog(t *testing func TestInstallEnableReportsActivationAndDisablesFailedStarts(t *testing.T) { for _, problem := range []string{"none", "manager", "program", "registration", "bindings"} { t.Run(problem, func(t *testing.T) { - repository, data := install_fixture(t) - set_install_transport(t, func(*http.Request) (*http.Response, error) { + repository, data := installFixture(t) + setInstallTransport(t, func(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(data)), Header: make(http.Header)}, nil }) registryPath := filepath.Join(t.TempDir(), "tentacles.toml") - owner, bindings := managed_tentacle_fixture(t, registryPath, false) + owner, bindings := managedTentacleFixture(t, registryPath, false) if problem == "manager" { owner.newManager = func() (*tentacle.Manager, error) { return nil, errors.New("fixture containment unavailable") } } @@ -253,7 +253,7 @@ func TestInstallEnableReportsActivationAndDisablesFailedStarts(t *testing.T) { } worker := newPreferencesWorker(owner.logger, config.DefaultSettings(), nil) worker.tentacles = owner - response := worker.manage_tentacle(context.Background(), preferences.Request{Tentacle: &tentacle.ManagementRequest{Action: "install-enable", URL: repository.URL, ID: "echo"}}) + response := worker.manageTentacle(context.Background(), preferences.Request{Tentacle: &tentacle.ManagementRequest{Action: "install-enable", URL: repository.URL, ID: "echo"}}) if response.Accepted != (problem == "none") { t.Fatalf("unexpected installation response: %+v", response) } diff --git a/internal/app/tentacle_interaction.go b/internal/app/tentacle_interaction.go index f496aac..226577a 100644 --- a/internal/app/tentacle_interaction.go +++ b/internal/app/tentacle_interaction.go @@ -12,12 +12,11 @@ import ( "time" "git.stormux.org/storm/cthulhu/internal/atspi" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) type tentacleForms interface { - Open(context.Context, interaction.Form) (<-chan internalUIResult, error) + Open(context.Context, tentaclewire.Form) (<-chan internalUIResult, error) Notice(context.Context, tentaclewire.Presentation) } @@ -92,7 +91,7 @@ func (runtime *tentacleRuntime) interact(ctx context.Context, command tentacleCo } cleanupNext = value.Next if value.Remote != nil { - action, approvalErr := runtime.authorize_remote_request(ctx, command.session, *value.Remote) + action, approvalErr := runtime.authorizeRemoteRequest(ctx, command.session, *value.Remote) submission := tentaclewire.Submission{} if approvalErr != nil { submission.Cancelled = true @@ -119,11 +118,11 @@ func (runtime *tentacleRuntime) interact(ctx context.Context, command tentacleCo } } if value.Reader != nil { - if !command.reader || runtime.readerSettings == nil || value.Next != "" && !runtime.reader_continuation(command, value.Next) { + if !command.reader || runtime.readerSettings == nil || value.Next != "" && !runtime.readerContinuation(command, value.Next) { command.session.Disable() return } - state, readerErr := runtime.readerSettings.request_reader(ctx, command.session, *value.Reader) + state, readerErr := runtime.readerSettings.requestReader(ctx, command.session, *value.Reader) if value.Next == "" { if readerErr != nil { runtime.report("Tentacle settings were not applied: " + readerErr.Error()) @@ -153,7 +152,7 @@ func (runtime *tentacleRuntime) interact(ctx context.Context, command tentacleCo return } formCtx, closeForm := context.WithCancel(ctx) - replies, openErr := runtime.open_tentacle_form(formCtx, command, *value.Form) + replies, openErr := runtime.openTentacleForm(formCtx, command, *value.Form) if openErr != nil { closeForm() _, _ = runtime.callInteraction(ctx, command, value.Next, tentaclewire.Submission{Cancelled: true}) @@ -176,7 +175,7 @@ func (runtime *tentacleRuntime) interact(ctx context.Context, command tentacleCo raw = completed continue } - submission = tentaclewire.Submission{Activated: reply.Activated, Values: reply.Values, Cancelled: reply.Cancelled || reply.Err != nil} + submission = tentaclewire.Submission{Activated: reply.Activated, Values: tentaclewire.SubmissionValues(reply.Controls), Cancelled: reply.Cancelled || reply.Err != nil} if submission.Cancelled { submission.Activated, submission.Values = "", nil } @@ -222,7 +221,7 @@ func (runtime *tentacleRuntime) interact(ctx context.Context, command tentacleCo } } -func (runtime *tentacleRuntime) open_tentacle_form(ctx context.Context, command tentacleCommand, form interaction.Form) (<-chan internalUIResult, error) { +func (runtime *tentacleRuntime) openTentacleForm(ctx context.Context, command tentacleCommand, form tentaclewire.Form) (<-chan internalUIResult, error) { if len(command.session.RemoteGrants()) != 0 { local, ok := runtime.forms.(localTentacleForms) if !ok { diff --git a/internal/app/tentacle_interaction_test.go b/internal/app/tentacle_interaction_test.go index 52307f0..1f33057 100644 --- a/internal/app/tentacle_interaction_test.go +++ b/internal/app/tentacle_interaction_test.go @@ -4,8 +4,8 @@ import ( "context" "encoding/json" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/tentacle" + "git.stormux.org/storm/cthulhu/internal/tentaclewire" sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle" "log/slog" "os" @@ -32,7 +32,7 @@ func TestTentacleInteractionPeer(t *testing.T) { return sdk.Interaction{Form: &sdk.Form{Title: "Wormhole menu", Elements: []sdk.Element{{ID: "code", Label: "Wormhole code", Kind: sdk.Entry, Required: true, MaxLength: 256}}}, Next: next}, nil } submit := func(_ context.Context, raw json.RawMessage) (any, error) { - if err := write_tentacle_fixture_marker(marker, raw); err != nil { + if err := writeTentacleFixtureMarker(marker, raw); err != nil { return nil, err } return sdk.Interaction{Presentation: sdk.Presentation{Speech: "Submitted", Braille: "Submitted"}}, nil @@ -161,7 +161,7 @@ func TestInternalUINoticeCannotReachAnotherForm(t *testing.T) { ui := &internalUI{keys: keys, speech: output, gate: &focusGate{}, events: make(chan input.CommandEvent, 16), requests: make(chan internalUIRequest, 1), notices: make(chan internalUINotice, 4), done: make(chan struct{})} go ui.run(ctx) defer func() { cancel(); <-ui.done }() - form := interaction.Form{Title: "Receive", Elements: []interaction.Element{{ID: "code", Label: "Code", Kind: interaction.Entry}}} + form := tentaclewire.Form{Title: "Receive", Elements: []tentaclewire.Element{{ID: "code", Label: "Code", Kind: tentaclewire.Entry}}} formCtx, closeForm := context.WithCancel(ctx) first, err := ui.Open(formCtx, form) if err != nil { diff --git a/internal/app/tentacle_lifecycle.go b/internal/app/tentacle_lifecycle.go index 6bd7a4b..b730819 100644 --- a/internal/app/tentacle_lifecycle.go +++ b/internal/app/tentacle_lifecycle.go @@ -50,7 +50,7 @@ type tentacleLifecycle struct { watchers []<-chan struct{} } -func (runtime *tentacleRuntime) run_managed(ctx context.Context) error { +func (runtime *tentacleRuntime) runManaged(ctx context.Context) error { entries, loadError := runtime.registry.Load() owner := &tentacleLifecycle{ ctx: ctx, diff --git a/internal/app/tentacle_lifecycle_requests.go b/internal/app/tentacle_lifecycle_requests.go index 5240087..4bb8c47 100644 --- a/internal/app/tentacle_lifecycle_requests.go +++ b/internal/app/tentacle_lifecycle_requests.go @@ -31,7 +31,7 @@ func (owner *tentacleLifecycle) handleRequest(call tentacleManagementCall) { return } if strings.HasPrefix(call.request.Action, "repository-") { - next, err := change_tentacle_repositories(owner.repositories, call.request, call.repository) + next, err := changeTentacleRepositories(owner.repositories, call.request, call.repository) if err == nil { err = owner.runtime.registry.SaveState(owner.entries, next) } @@ -56,7 +56,7 @@ func (owner *tentacleLifecycle) handleRequest(call tentacleManagementCall) { if startup, exists := owner.startups[call.request.ID]; exists && startup.previous != nil { owner.failStartup(call.request.ID, "Tentacle update was cancelled by another operation.") } - next, err := change_tentacle_entries(owner.entries, call.request) + next, err := changeTentacleEntries(owner.entries, call.request) if err == nil && call.request.Action != "retry" && reflect.DeepEqual(next, owner.entries) { // Saved enablement is intent, not proof of a live session. An // explicit enable/update must recover a failed or starting entry. diff --git a/internal/app/tentacle_management.go b/internal/app/tentacle_management.go index e298b37..1f6baa2 100644 --- a/internal/app/tentacle_management.go +++ b/internal/app/tentacle_management.go @@ -188,7 +188,7 @@ func (runtime *tentacleRuntime) Manage(ctx context.Context, request tentacle.Man } } -func change_tentacle_entries(entries []tentacle.Entry, request tentacle.ManagementRequest) ([]tentacle.Entry, error) { +func changeTentacleEntries(entries []tentacle.Entry, request tentacle.ManagementRequest) ([]tentacle.Entry, error) { next := tentacle.CloneEntries(entries) index := slices.IndexFunc(next, func(entry tentacle.Entry) bool { return entry.ID == request.ID }) if request.Action == "add" || request.Action == "update" { diff --git a/internal/app/tentacle_management_test.go b/internal/app/tentacle_management_test.go index 7c97b00..8c8cc33 100644 --- a/internal/app/tentacle_management_test.go +++ b/internal/app/tentacle_management_test.go @@ -16,7 +16,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentacle" ) -func managed_tentacle_fixture(t *testing.T, path string, contained bool) (*tentacleRuntime, *tentacleBindingRecorder) { +func managedTentacleFixture(t *testing.T, path string, contained bool) (*tentacleRuntime, *tentacleBindingRecorder) { t.Helper() bindings := &tentacleBindingRecorder{} runtime := newTentacleRuntime(slog.New(slog.DiscardHandler), bindings, "", "auto") @@ -42,7 +42,7 @@ func managed_tentacle_fixture(t *testing.T, path string, contained bool) (*tenta return runtime, bindings } -func manage_tentacle(t *testing.T, runtime *tentacleRuntime, action, id string, entry *tentacle.Entry) { +func manageTentacle(t *testing.T, runtime *tentacleRuntime, action, id string, entry *tentacle.Entry) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() @@ -51,7 +51,7 @@ func manage_tentacle(t *testing.T, runtime *tentacleRuntime, action, id string, } } -func probe_entry(t *testing.T, id, mode string) tentacle.Entry { +func probeEntry(t *testing.T, id, mode string) tentacle.Entry { t.Helper() executable, err := os.Executable() if err != nil { @@ -60,7 +60,7 @@ func probe_entry(t *testing.T, id, mode string) tentacle.Entry { return tentacle.Entry{ID: id, Program: []string{executable, "-test.run=^TestTentacleReaderPeer$", "--", "reader-peer", filepath.Join(t.TempDir(), mode)}} } -func wait_managed_state(t *testing.T, runtime *tentacleRuntime, id, state string) { +func waitManagedState(t *testing.T, runtime *tentacleRuntime, id, state string) { t.Helper() waitTentacle(t, func() bool { for _, status := range runtime.Snapshot().Entries { @@ -74,28 +74,28 @@ func wait_managed_state(t *testing.T, runtime *tentacleRuntime, id, state string func TestManagedTentaclePersistenceLifecycleAndRecovery(t *testing.T) { path := filepath.Join(t.TempDir(), "tentacles.toml") - runtime, bindings := managed_tentacle_fixture(t, path, false) + runtime, bindings := managedTentacleFixture(t, path, false) if err := runtime.Start(context.Background()); err != nil { t.Fatal(err) } - first := probe_entry(t, "first", "called") - second := probe_entry(t, "second", "called") - manage_tentacle(t, runtime, "add", first.ID, &first) - manage_tentacle(t, runtime, "add", second.ID, &second) + first := probeEntry(t, "first", "called") + second := probeEntry(t, "second", "called") + manageTentacle(t, runtime, "add", first.ID, &first) + manageTentacle(t, runtime, "add", second.ID, &second) if len(bindings.TentacleBindings()) != 0 { t.Fatal("adding disabled entries launched them") } - manage_tentacle(t, runtime, "enable", first.ID, nil) - wait_managed_state(t, runtime, first.ID, "active") + manageTentacle(t, runtime, "enable", first.ID, nil) + waitManagedState(t, runtime, first.ID, "active") firstCommand := bindings.TentacleBindings()[0].Command - manage_tentacle(t, runtime, "enable", first.ID, nil) + manageTentacle(t, runtime, "enable", first.ID, nil) if bindings.TentacleBindings()[0].Command != firstCommand { t.Fatal("enable of active entry restarted it") } - manage_tentacle(t, runtime, "enable", second.ID, nil) - wait_managed_state(t, runtime, second.ID, "active") - manage_tentacle(t, runtime, "disable", first.ID, nil) - wait_managed_state(t, runtime, first.ID, "disabled") + manageTentacle(t, runtime, "enable", second.ID, nil) + waitManagedState(t, runtime, second.ID, "active") + manageTentacle(t, runtime, "disable", first.ID, nil) + waitManagedState(t, runtime, first.ID, "disabled") waitTentacle(t, func() bool { bound := bindings.TentacleBindings() return len(bound) > 0 && bound[0].Command != firstCommand @@ -105,8 +105,8 @@ func TestManagedTentaclePersistenceLifecycleAndRecovery(t *testing.T) { t.Fatal("stale command invoked disabled child") } secondCommand := bindings.TentacleBindings()[0].Command - manage_tentacle(t, runtime, "retry", second.ID, nil) - wait_managed_state(t, runtime, second.ID, "active") + manageTentacle(t, runtime, "retry", second.ID, nil) + waitManagedState(t, runtime, second.ID, "active") if bindings.TentacleBindings()[0].Command == secondCommand { t.Fatal("retry reused old session identity") } @@ -123,14 +123,14 @@ func TestManagedTentaclePersistenceLifecycleAndRecovery(t *testing.T) { if err := runtime.Stop(ctx); err != nil { t.Fatal(err) } - restarted, _ := managed_tentacle_fixture(t, path, false) + restarted, _ := managedTentacleFixture(t, path, false) if err := restarted.Start(context.Background()); err != nil { t.Fatal(err) } - wait_managed_state(t, restarted, second.ID, "active") - wait_managed_state(t, restarted, first.ID, "disabled") - manage_tentacle(t, restarted, "remove", first.ID, nil) - manage_tentacle(t, restarted, "remove", second.ID, nil) + waitManagedState(t, restarted, second.ID, "active") + waitManagedState(t, restarted, first.ID, "disabled") + manageTentacle(t, restarted, "remove", first.ID, nil) + manageTentacle(t, restarted, "remove", second.ID, nil) loaded, err = (&tentacle.Registry{Path: path}).Load() if err != nil || len(loaded) != 0 { t.Fatalf("remove all: %v %v", loaded, err) @@ -142,25 +142,25 @@ func TestManagedTentaclePersistenceLifecycleAndRecovery(t *testing.T) { func TestManagedTentacleFailureRetryAndSaveFailure(t *testing.T) { path := filepath.Join(t.TempDir(), "tentacles.toml") - runtime, bindings := managed_tentacle_fixture(t, path, false) + runtime, bindings := managedTentacleFixture(t, path, false) if err := runtime.Start(context.Background()); err != nil { t.Fatal(err) } - entry := probe_entry(t, "probe", "crash") + entry := probeEntry(t, "probe", "crash") entry.Enabled = true - manage_tentacle(t, runtime, "add", entry.ID, &entry) - wait_managed_state(t, runtime, entry.ID, "active") + manageTentacle(t, runtime, "add", entry.ID, &entry) + waitManagedState(t, runtime, entry.ID, "active") runtime.Invoke(context.Background(), bindings.TentacleBindings()[0].Command) - wait_managed_state(t, runtime, entry.ID, "failed") + waitManagedState(t, runtime, entry.ID, "failed") if !runtime.Snapshot().Entries[0].Entry.Enabled { t.Fatal("failure changed desired enablement") } - manage_tentacle(t, runtime, "retry", entry.ID, nil) - wait_managed_state(t, runtime, entry.ID, "active") + manageTentacle(t, runtime, "retry", entry.ID, nil) + waitManagedState(t, runtime, entry.ID, "active") entry.Program[len(entry.Program)-1] = filepath.Join(t.TempDir(), "called") entry.Presentation = true - manage_tentacle(t, runtime, "update", entry.ID, &entry) - wait_managed_state(t, runtime, entry.ID, "active") + manageTentacle(t, runtime, "update", entry.ID, &entry) + waitManagedState(t, runtime, entry.ID, "active") if !runtime.Snapshot().Entries[0].Entry.Presentation { t.Fatal("grant lost") } @@ -183,7 +183,7 @@ func TestManagedTentacleEmptyAndBrokenRegistryDoNotLaunch(t *testing.T) { t.Fatal(err) } } - runtime, _ := managed_tentacle_fixture(t, path, false) + runtime, _ := managedTentacleFixture(t, path, false) runtime.newManager = func() (*tentacle.Manager, error) { t.Error("empty/broken registry initialized host") return nil, tentacle.ErrUnavailable @@ -191,7 +191,7 @@ func TestManagedTentacleEmptyAndBrokenRegistryDoNotLaunch(t *testing.T) { if err := runtime.Start(context.Background()); err != nil { t.Fatal(err) } - entry := probe_entry(t, "probe", "called") + entry := probeEntry(t, "probe", "called") err := runtime.Manage(context.Background(), tentacle.ManagementRequest{Action: "add", ID: entry.ID, Entry: &entry}) if (err != nil) != broken { t.Fatalf("broken=%v: %v", broken, err) @@ -203,25 +203,25 @@ func TestManagedTentacleEmptyAndBrokenRegistryDoNotLaunch(t *testing.T) { } func TestPreferencesTentacleOperationsAreGlobalAndSeparate(t *testing.T) { - runtime, _ := managed_tentacle_fixture(t, filepath.Join(t.TempDir(), "tentacles.toml"), false) + runtime, _ := managedTentacleFixture(t, filepath.Join(t.TempDir(), "tentacles.toml"), false) if err := runtime.Start(context.Background()); err != nil { t.Fatal(err) } worker := newPreferencesWorker(slog.New(slog.DiscardHandler), config.DefaultSettings(), nil) worker.tentacles = runtime - entry := probe_entry(t, "probe", "called") + entry := probeEntry(t, "probe", "called") request := preferences.Request{Tentacle: &tentacle.ManagementRequest{Action: "add", ID: entry.ID, Entry: &entry}} worker.editApp = "Example" - if response := worker.manage_tentacle(context.Background(), request); response.Accepted { + if response := worker.manageTentacle(context.Background(), request); response.Accepted { t.Fatal("application preferences added a program") } worker.editApp = "" request.Save = true - if response := worker.manage_tentacle(context.Background(), request); response.Accepted { + if response := worker.manageTentacle(context.Background(), request); response.Accepted { t.Fatal("mixed settings request accepted") } request.Save = false - if response := worker.manage_tentacle(context.Background(), request); !response.Accepted || response.Tentacles == nil || len(response.Tentacles.Entries) != 1 { + if response := worker.manageTentacle(context.Background(), request); !response.Accepted || response.Tentacles == nil || len(response.Tentacles.Entries) != 1 { t.Fatalf("add: %+v", response) } } @@ -237,7 +237,7 @@ func TestManagedTentacleGuardianPeer(t *testing.T) { } func TestManagedSupervisedTentacle(t *testing.T) { - runtime, bindings := managed_tentacle_fixture(t, filepath.Join(t.TempDir(), "tentacles.toml"), true) + runtime, bindings := managedTentacleFixture(t, filepath.Join(t.TempDir(), "tentacles.toml"), true) readerGroup, err := os.ReadFile("/proc/self/cgroup") if err != nil { t.Fatal(err) @@ -252,10 +252,10 @@ func TestManagedSupervisedTentacle(t *testing.T) { if err := runtime.Start(context.Background()); err != nil { t.Fatal(err) } - entry := probe_entry(t, "probe", "called") + entry := probeEntry(t, "probe", "called") entry.Enabled = true - manage_tentacle(t, runtime, "add", entry.ID, &entry) - wait_managed_state(t, runtime, entry.ID, "active") + manageTentacle(t, runtime, "add", entry.ID, &entry) + waitManagedState(t, runtime, entry.ID, "active") runtime.Invoke(context.Background(), bindings.TentacleBindings()[0].Command) marker := entry.Program[len(entry.Program)-1] waitTentacle(t, func() bool { _, err := os.Stat(marker); return err == nil }) @@ -278,10 +278,10 @@ func TestManagedSupervisedTentacle(t *testing.T) { if err != nil || string(readerGroup) != string(afterGroup) { t.Fatal("management moved the reader") } - manage_tentacle(t, runtime, "disable", entry.ID, nil) + manageTentacle(t, runtime, "disable", entry.ID, nil) waitTentacle(t, func() bool { return len(bindings.TentacleBindings()) == 0 }) - manage_tentacle(t, runtime, "enable", entry.ID, nil) - wait_managed_state(t, runtime, entry.ID, "active") + manageTentacle(t, runtime, "enable", entry.ID, nil) + waitManagedState(t, runtime, entry.ID, "active") ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := runtime.Stop(ctx); err != nil { @@ -296,21 +296,21 @@ func TestManagedTentacleCancelledStartupAndConcurrentDisable(t *testing.T) { for _, operation := range []string{"cancel", "disable", "remove"} { t.Run(operation, func(t *testing.T) { registryPath := filepath.Join(t.TempDir(), "tentacles.toml") - owner, bindings := managed_tentacle_fixture(t, registryPath, false) + owner, bindings := managedTentacleFixture(t, registryPath, false) if err := owner.Start(context.Background()); err != nil { t.Fatal(err) } - entry := probe_entry(t, "probe", "stall") - manage_tentacle(t, owner, "add", entry.ID, &entry) + entry := probeEntry(t, "probe", "stall") + manageTentacle(t, owner, "add", entry.ID, &entry) ctx, cancel := context.WithCancel(context.Background()) defer cancel() result := make(chan error, 1) go func() { result <- owner.Manage(ctx, tentacle.ManagementRequest{Action: "enable", ID: entry.ID}) }() - wait_managed_state(t, owner, entry.ID, "starting") + waitManagedState(t, owner, entry.ID, "starting") if operation == "cancel" { cancel() } else { - manage_tentacle(t, owner, operation, entry.ID, nil) + manageTentacle(t, owner, operation, entry.ID, nil) } select { case err := <-result: @@ -340,17 +340,17 @@ func TestManagedTentacleCancelledStartupAndConcurrentDisable(t *testing.T) { } func TestManagedTentacleEnableRestartsFailedSession(t *testing.T) { - owner, bindings := managed_tentacle_fixture(t, filepath.Join(t.TempDir(), "tentacles.toml"), false) + owner, bindings := managedTentacleFixture(t, filepath.Join(t.TempDir(), "tentacles.toml"), false) if err := owner.Start(context.Background()); err != nil { t.Fatal(err) } - entry := probe_entry(t, "probe", "crash") + entry := probeEntry(t, "probe", "crash") entry.Enabled = true - manage_tentacle(t, owner, "add", entry.ID, &entry) + manageTentacle(t, owner, "add", entry.ID, &entry) command := bindings.TentacleBindings()[0].Command owner.Invoke(context.Background(), command) - wait_managed_state(t, owner, entry.ID, "failed") - manage_tentacle(t, owner, "enable", entry.ID, nil) + waitManagedState(t, owner, entry.ID, "failed") + manageTentacle(t, owner, "enable", entry.ID, nil) status := owner.Snapshot().Entries[0] if status.State != "active" || !status.Entry.Enabled || status.Message != "" { t.Fatalf("enable reported success without restarting: %+v", status) @@ -376,19 +376,19 @@ func (bindings *cancellingTentacleBindings) SetTentacleBindings(ctx context.Cont func TestManagedTentacleCancellationDuringBindingsRollsBack(t *testing.T) { path := filepath.Join(t.TempDir(), "tentacles.toml") - owner, bindings := managed_tentacle_fixture(t, path, false) + owner, bindings := managedTentacleFixture(t, path, false) ctx, cancel := context.WithCancel(context.Background()) defer cancel() owner.input = &cancellingTentacleBindings{tentacleBindingRecorder: bindings, cancel: cancel} if err := owner.Start(context.Background()); err != nil { t.Fatal(err) } - first := probe_entry(t, "first", "called") + first := probeEntry(t, "first", "called") first.Enabled = true - manage_tentacle(t, owner, "add", first.ID, &first) + manageTentacle(t, owner, "add", first.ID, &first) firstCommand := bindings.TentacleBindings()[0].Command - second := probe_entry(t, "second", "called") - manage_tentacle(t, owner, "add", second.ID, &second) + second := probeEntry(t, "second", "called") + manageTentacle(t, owner, "add", second.ID, &second) if err := owner.Manage(ctx, tentacle.ManagementRequest{Action: "enable", ID: second.ID}); err == nil { t.Fatal("startup cancelled during binding reported success") } @@ -410,7 +410,7 @@ func TestUpdatePreservesEnabledState(t *testing.T) { for _, enabled := range []bool{false, true} { current := tentacle.Entry{ID: "example", Program: []string{"/bin/true"}, Enabled: enabled, Version: "0.1.3"} replacement := tentacle.Entry{ID: "example", Program: []string{"/bin/true"}, Enabled: !enabled, Version: "0.1.4"} - next, err := change_tentacle_entries( + next, err := changeTentacleEntries( []tentacle.Entry{current}, tentacle.ManagementRequest{ Action: "update", diff --git a/internal/app/tentacle_output.go b/internal/app/tentacle_output.go index ae9512a..ad2dbb8 100644 --- a/internal/app/tentacle_output.go +++ b/internal/app/tentacle_output.go @@ -75,7 +75,7 @@ func (owner *tentacleOutput) Stop() { defer owner.mutex.Unlock() owner.retireLocked() if owner.speech != nil { - owner.speech.stop_uninterruptible() + owner.speech.stopUninterruptible() } } @@ -128,7 +128,7 @@ func (owner *tentacleOutput) Present(ticket tentacleOutputTicket, value tentacle if value.Braille != "" && owner.braille != nil && owner.live != nil { settings := owner.live.Load() if settings.EnableBraille { - if owner.braille.flash_message_guarded(value.Braille, settings.Braille, false, ticket.ctx, ticket.brailleSequence) { + if owner.braille.flashMessageGuarded(value.Braille, settings.Braille, false, ticket.ctx, ticket.brailleSequence) { owner.braille.mu.Lock() if owner.braille.flashContext == ticket.ctx { owner.braille.logger.Debug("queued tentacle braille message", "command", command, diff --git a/internal/app/tentacle_reader.go b/internal/app/tentacle_reader.go index 67c1724..5f07051 100644 --- a/internal/app/tentacle_reader.go +++ b/internal/app/tentacle_reader.go @@ -13,7 +13,6 @@ import ( "time" "git.stormux.org/storm/cthulhu/internal/config" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/preferences" "git.stormux.org/storm/cthulhu/internal/tentacle" "git.stormux.org/storm/cthulhu/internal/tentaclewire" @@ -41,14 +40,14 @@ type readerTransaction struct { owner string } -func copy_reader_value[T any](value T) T { +func copyReaderValue[T any](value T) T { data, _ := json.Marshal(value) var result T _ = json.Unmarshal(data, &result) return result } -func (runtime *tentacleRuntime) signal_extensions() { +func (runtime *tentacleRuntime) signalExtensions() { if runtime == nil { return } @@ -57,13 +56,13 @@ func (runtime *tentacleRuntime) signal_extensions() { default: } } -func (worker *preferencesWorker) extension_changes() <-chan struct{} { +func (worker *preferencesWorker) extensionChanges() <-chan struct{} { if worker.tentacles == nil { return nil } return worker.tentacles.extensionChanges } -func (runtime *tentacleRuntime) reader_sessions() map[string]*tentacle.Session { +func (runtime *tentacleRuntime) readerSessions() map[string]*tentacle.Session { sessions := map[string]*tentacle.Session{} if runtime == nil { return sessions @@ -83,11 +82,11 @@ func (runtime *tentacleRuntime) reader_sessions() map[string]*tentacle.Session { // Called only by the settings owner. Revocation wakes this mailbox even if no // preferences window is open. No native input callback waits for restoration. -func (worker *preferencesWorker) sync_extensions(ctx context.Context) { +func (worker *preferencesWorker) syncExtensions(ctx context.Context) { if ctx.Err() != nil { return } - sessions := worker.tentacles.reader_sessions() + sessions := worker.tentacles.readerSessions() if worker.extensions == nil { worker.extensions = map[string]*readerExtension{} } @@ -101,16 +100,16 @@ func (worker *preferencesWorker) sync_extensions(ctx context.Context) { continue } value := session.Extensions() - worker.load_page_store() + worker.loadPageStore() for index := range value.Pages { page := &value.Pages[index] if saved := worker.savedPages[session.TentacleID()][page.ID]; saved != nil && tentaclewire.ValidatePageValues(*page, saved) == nil { - page.Values = copy_reader_value(saved) + page.Values = copyReaderValue(saved) } } worker.extensionRevision++ worker.extensions[id] = &readerExtension{session: session, value: value, revision: worker.extensionRevision} - if err := validate_reader_extensions(worker.extensions); err != nil { + if err := validateReaderExtensions(worker.extensions); err != nil { delete(worker.extensions, id) session.Disable() worker.announceSpeechSetting("A tentacle exceeded the reader settings limits and was disabled.") @@ -134,7 +133,7 @@ func (worker *preferencesWorker) sync_extensions(ctx context.Context) { } } } -func (worker *preferencesWorker) load_page_store() { +func (worker *preferencesWorker) loadPageStore() { if worker.pageStore != nil { return } @@ -148,26 +147,26 @@ func (worker *preferencesWorker) load_page_store() { } } -func (worker *preferencesWorker) effective_settings(base config.Settings) config.Settings { +func (worker *preferencesWorker) effectiveSettings(base config.Settings) config.Settings { if worker.speechOverride != nil { return worker.speechOverride.Apply(base) } return base } -func (worker *preferencesWorker) extension_pages() []preferences.ExtensionPage { +func (worker *preferencesWorker) extensionPages() []preferences.ExtensionPage { if worker.editApp != "" { return nil } var pages []preferences.ExtensionPage - for _, id := range sorted_extension_ids(worker.extensions) { + for _, id := range sortedExtensionIds(worker.extensions) { extension := worker.extensions[id] for _, page := range extension.value.Pages { - pages = append(pages, preferences.ExtensionPage{Session: id, Revision: extension.revision, PreferencePage: copy_reader_value(page)}) + pages = append(pages, preferences.ExtensionPage{Session: id, Revision: extension.revision, PreferencePage: copyReaderValue(page)}) } } return pages } -func sorted_extension_ids(extensions map[string]*readerExtension) []string { +func sortedExtensionIds(extensions map[string]*readerExtension) []string { ids := make([]string, 0, len(extensions)) for id := range extensions { ids = append(ids, id) @@ -181,10 +180,10 @@ func sorted_extension_ids(extensions map[string]*readerExtension) []string { }) return ids } -func (worker *preferencesWorker) reader_state(extension *readerExtension) tentaclewire.ReaderState { - return copy_reader_value(tentaclewire.ReaderState{Speech: tentaclewire.SpeechFromSettings(worker.effective_settings(worker.settings)), DefaultSpeech: tentaclewire.SpeechFromSettings(worker.settings), Extensions: extension.value}) +func (worker *preferencesWorker) readerState(extension *readerExtension) tentaclewire.ReaderState { + return copyReaderValue(tentaclewire.ReaderState{Speech: tentaclewire.SpeechFromSettings(worker.effectiveSettings(worker.settings)), DefaultSpeech: tentaclewire.SpeechFromSettings(worker.settings), Extensions: extension.value}) } -func (worker *preferencesWorker) request_reader(ctx context.Context, session *tentacle.Session, request tentaclewire.ReaderRequest) (*tentaclewire.ReaderState, error) { +func (worker *preferencesWorker) requestReader(ctx context.Context, session *tentacle.Session, request tentaclewire.ReaderRequest) (*tentaclewire.ReaderState, error) { call := readerSettingsCall{ctx: ctx, session: session, request: request, result: make(chan readerSettingsResult, 1)} select { case worker.extensionRequests <- call: @@ -202,7 +201,7 @@ func (worker *preferencesWorker) request_reader(ctx context.Context, session *te return nil, tentacle.ErrUnavailable } } -func (worker *preferencesWorker) handle_reader_call(ctx context.Context, call readerSettingsCall, windowOpen bool) { +func (worker *preferencesWorker) handleReaderCall(ctx context.Context, call readerSettingsCall, windowOpen bool) { callCtx, cancel := context.WithCancel(ctx) defer cancel() stop := context.AfterFunc(call.ctx, cancel) @@ -211,11 +210,11 @@ func (worker *preferencesWorker) handle_reader_call(ctx context.Context, call re stopSession := context.AfterFunc(call.session.OutputContext(), cancel) defer stopSession() } - worker.sync_extensions(ctx) - state, err := worker.apply_reader_request(callCtx, call.session, call.request, windowOpen) + worker.syncExtensions(ctx) + state, err := worker.applyReaderRequest(callCtx, call.session, call.request, windowOpen) call.result <- readerSettingsResult{state, err} } -func (worker *preferencesWorker) reader_allowed(ctx context.Context, session *tentacle.Session) error { +func (worker *preferencesWorker) readerAllowed(ctx context.Context, session *tentacle.Session) error { if err := ctx.Err(); err != nil { return err } @@ -232,15 +231,15 @@ func (worker *preferencesWorker) reader_allowed(ctx context.Context, session *te } return nil } -func (worker *preferencesWorker) reader_transaction() readerTransaction { +func (worker *preferencesWorker) readerTransaction() readerTransaction { extensions := map[string]*readerExtension{} for id, extension := range worker.extensions { - extensions[id] = &readerExtension{session: extension.session, value: copy_reader_value(extension.value), revision: extension.revision} + extensions[id] = &readerExtension{session: extension.session, value: copyReaderValue(extension.value), revision: extension.revision} } - return readerTransaction{extensions, copy_reader_value(worker.speechOverride), worker.speechOverrideOwner} + return readerTransaction{extensions, copyReaderValue(worker.speechOverride), worker.speechOverrideOwner} } -func (worker *preferencesWorker) stage_reader_request(ctx context.Context, transaction *readerTransaction, session *tentacle.Session, request tentaclewire.ReaderRequest) error { - if err := worker.reader_allowed(ctx, session); err != nil { +func (worker *preferencesWorker) stageReaderRequest(ctx context.Context, transaction *readerTransaction, session *tentacle.Session, request tentaclewire.ReaderRequest) error { + if err := worker.readerAllowed(ctx, session); err != nil { return err } if err := tentaclewire.ValidateReaderRequest(request); err != nil { @@ -264,7 +263,7 @@ func (worker *preferencesWorker) stage_reader_request(ctx context.Context, trans return tentacle.ErrProtocol } } - transaction.extensions[id].value = copy_reader_value(*request.Extensions) + transaction.extensions[id].value = copyReaderValue(*request.Extensions) transaction.extensions[id].revision++ } if request.Speech != nil || request.RestoreSpeech { @@ -278,13 +277,13 @@ func (worker *preferencesWorker) stage_reader_request(ctx context.Context, trans if err := config.Validate(next); err != nil { return err } - transaction.override, transaction.owner = copy_reader_value(request.Speech), id + transaction.override, transaction.owner = copyReaderValue(request.Speech), id } } - return validate_reader_extensions(transaction.extensions) + return validateReaderExtensions(transaction.extensions) } -func (worker *preferencesWorker) commit_reader_transaction(ctx context.Context, session *tentacle.Session, transaction readerTransaction) error { - if err := worker.reader_allowed(ctx, session); err != nil { +func (worker *preferencesWorker) commitReaderTransaction(ctx context.Context, session *tentacle.Session, transaction readerTransaction) error { + if err := worker.readerAllowed(ctx, session); err != nil { return err } next := worker.settings @@ -300,10 +299,10 @@ func (worker *preferencesWorker) commit_reader_transaction(ctx context.Context, if err != nil { return err } - if err := worker.reader_allowed(ctx, session); err != nil { + if err := worker.readerAllowed(ctx, session); err != nil { restoreCtx, restoreCancel := context.WithTimeout(context.Background(), 6*time.Second) defer restoreCancel() - if restoreErr := worker.updateSpeech(restoreCtx, worker.effective_settings(worker.settings)); restoreErr != nil { + if restoreErr := worker.updateSpeech(restoreCtx, worker.effectiveSettings(worker.settings)); restoreErr != nil { worker.logger.Error("restore revoked speech transaction", "error", restoreErr) } return err @@ -316,21 +315,21 @@ func (worker *preferencesWorker) commit_reader_transaction(ctx context.Context, } return nil } -func (worker *preferencesWorker) apply_reader_request(ctx context.Context, session *tentacle.Session, request tentaclewire.ReaderRequest, windowOpen bool) (*tentaclewire.ReaderState, error) { - if err := worker.reader_allowed(ctx, session); err != nil { +func (worker *preferencesWorker) applyReaderRequest(ctx context.Context, session *tentacle.Session, request tentaclewire.ReaderRequest, windowOpen bool) (*tentaclewire.ReaderState, error) { + if err := worker.readerAllowed(ctx, session); err != nil { return nil, err } if windowOpen && (request.Speech != nil || request.RestoreSpeech || request.Extensions != nil) { return nil, errors.New("close preferences before changing reader settings from a command") } - transaction := worker.reader_transaction() - if err := worker.stage_reader_request(ctx, &transaction, session, request); err != nil { + transaction := worker.readerTransaction() + if err := worker.stageReaderRequest(ctx, &transaction, session, request); err != nil { return nil, err } - if err := worker.commit_reader_transaction(ctx, session, transaction); err != nil { + if err := worker.commitReaderTransaction(ctx, session, transaction); err != nil { return nil, err } - state := worker.reader_state(worker.extensions[session.Identity()]) + state := worker.readerState(worker.extensions[session.Identity()]) if request.Snapshot { catalogCtx, cancel := context.WithTimeout(ctx, 4*time.Second) catalog, err := worker.discover(catalogCtx, worker.socket) @@ -365,10 +364,10 @@ func (worker *preferencesWorker) apply_reader_request(ctx context.Context, sessi return &state, nil } -func (worker *preferencesWorker) extension_effect(ctx context.Context, extension *readerExtension, command string, event tentaclewire.ExtensionEvent) (tentaclewire.ReaderRequest, error) { +func (worker *preferencesWorker) extensionEffect(ctx context.Context, extension *readerExtension, command string, event tentaclewire.ExtensionEvent) (tentaclewire.ReaderRequest, error) { arguments := any(event) for transition := 0; transition < 16; transition++ { - if err := worker.reader_allowed(ctx, extension.session); err != nil { + if err := worker.readerAllowed(ctx, extension.session); err != nil { return tentaclewire.ReaderRequest{}, err } data, err := json.Marshal(arguments) @@ -393,10 +392,10 @@ func (worker *preferencesWorker) extension_effect(ctx context.Context, extension } return *value.Reader, nil } - if !worker.tentacles.reader_continuation(tentacleCommand{session: extension.session}, value.Next) { + if !worker.tentacles.readerContinuation(tentacleCommand{session: extension.session}, value.Next) { return tentaclewire.ReaderRequest{}, tentacle.ErrProtocol } - state, snapshotErr := worker.apply_reader_request(ctx, extension.session, *value.Reader, true) + state, snapshotErr := worker.applyReaderRequest(ctx, extension.session, *value.Reader, true) submission := tentaclewire.Submission{Reader: state} if snapshotErr != nil { submission.Error = snapshotErr.Error() @@ -408,11 +407,11 @@ func (worker *preferencesWorker) extension_effect(ctx context.Context, extension // Optional page loading happens before GTK constructs controls. Handlers may // inspect the reader/catalog and replace declarations, but cannot apply speech. -func (worker *preferencesWorker) load_extension_pages(ctx context.Context) error { +func (worker *preferencesWorker) loadExtensionPages(ctx context.Context) error { loadCtx, cancel := context.WithTimeout(ctx, 6*time.Second) defer cancel() var failures error - for _, view := range worker.extension_pages() { + for _, view := range worker.extensionPages() { if !view.Load { continue } @@ -420,14 +419,14 @@ func (worker *preferencesWorker) load_extension_pages(ctx context.Context) error if extension == nil { continue } - event := tentaclewire.ExtensionEvent{Event: "preferences.open", ID: view.ID, Reader: worker.reader_state(extension)} - request, err := worker.extension_effect(loadCtx, extension, view.Command, event) + event := tentaclewire.ExtensionEvent{Event: "preferences.open", ID: view.ID, Reader: worker.readerState(extension)} + request, err := worker.extensionEffect(loadCtx, extension, view.Command, event) if err == nil && (request.Speech != nil || request.RestoreSpeech || request.Extensions == nil) { err = errors.New("opening a preference page may only update its declarations") } - transaction := worker.reader_transaction() + transaction := worker.readerTransaction() if err == nil { - err = worker.stage_reader_request(loadCtx, &transaction, extension.session, request) + err = worker.stageReaderRequest(loadCtx, &transaction, extension.session, request) } if err == nil { worker.extensions = transaction.extensions @@ -435,13 +434,13 @@ func (worker *preferencesWorker) load_extension_pages(ctx context.Context) error failures = errors.Join(failures, err) } } - worker.sync_extensions(ctx) + worker.syncExtensions(ctx) return failures } -func (worker *preferencesWorker) prepare_extension_pages(ctx context.Context, drafts []preferences.PageDraft) (readerTransaction, error) { - worker.sync_extensions(ctx) - transaction := worker.reader_transaction() +func (worker *preferencesWorker) prepareExtensionPages(ctx context.Context, drafts []preferences.PageDraft) (readerTransaction, error) { + worker.syncExtensions(ctx) + transaction := worker.readerTransaction() if len(drafts) == 0 { return transaction, nil } @@ -479,8 +478,8 @@ func (worker *preferencesWorker) prepare_extension_pages(ctx context.Context, dr if reflect.DeepEqual(page.Values, draft.Values) { continue } - event := tentaclewire.ExtensionEvent{Event: "preferences.apply", ID: page.ID, Values: draft.Values, Reader: worker.reader_state(extension)} - request, err := worker.extension_effect(ctx, extension, page.Command, event) + event := tentaclewire.ExtensionEvent{Event: "preferences.apply", ID: page.ID, Values: draft.Values, Reader: worker.readerState(extension)} + request, err := worker.extensionEffect(ctx, extension, page.Command, event) if err != nil { return transaction, err } @@ -490,7 +489,7 @@ func (worker *preferencesWorker) prepare_extension_pages(ctx context.Context, dr if speechProposals > 1 { return transaction, errors.New("multiple pages proposed conflicting speech changes") } - if err := worker.stage_reader_request(ctx, &transaction, extension.session, request); err != nil { + if err := worker.stageReaderRequest(ctx, &transaction, extension.session, request); err != nil { return transaction, err } staged := transaction.extensions[draft.Session] @@ -500,7 +499,7 @@ func (worker *preferencesWorker) prepare_extension_pages(ctx context.Context, dr // A callback may replace choices or normalize input. Otherwise // the successfully submitted draft becomes its committed value. if request.Extensions == nil { - staged.value.Pages[index].Values = copy_reader_value(draft.Values) + staged.value.Pages[index].Values = copyReaderValue(draft.Values) } found = true } @@ -510,10 +509,10 @@ func (worker *preferencesWorker) prepare_extension_pages(ctx context.Context, dr } staged.revision++ } - return transaction, validate_reader_extensions(transaction.extensions) + return transaction, validateReaderExtensions(transaction.extensions) } -func validate_reader_extensions(extensions map[string]*readerExtension) error { +func validateReaderExtensions(extensions map[string]*readerExtension) error { total := 0 for _, extension := range extensions { if err := tentaclewire.ValidateExtensions(extension.value); err != nil { @@ -530,21 +529,21 @@ func validate_reader_extensions(extensions map[string]*readerExtension) error { } return nil } -func (worker *preferencesWorker) save_extension_pages() error { +func (worker *preferencesWorker) saveExtensionPages() error { if worker.pageStore == nil { return nil } if worker.pageLoadError != nil { return worker.pageLoadError } - values := copy_reader_value(worker.savedPages) + values := copyReaderValue(worker.savedPages) if values == nil { values = tentacle.PageValues{} } for _, extension := range worker.extensions { - pages := map[string]map[string]interaction.Value{} + pages := map[string]map[string]tentaclewire.Value{} for _, page := range extension.value.Pages { - pages[page.ID] = copy_reader_value(page.Values) + pages[page.ID] = copyReaderValue(page.Values) } if len(pages) > 0 { values[extension.session.TentacleID()] = pages @@ -566,9 +565,9 @@ type readerQuickSetting struct { setting tentaclewire.QuickSetting } -func (worker *preferencesWorker) quick_settings() []readerQuickSetting { +func (worker *preferencesWorker) quickSettings() []readerQuickSetting { var result []readerQuickSetting - for _, id := range sorted_extension_ids(worker.extensions) { + for _, id := range sortedExtensionIds(worker.extensions) { extension := worker.extensions[id] for _, setting := range extension.value.QuickSettings { result = append(result, readerQuickSetting{id + "/" + setting.ID, extension, setting}) @@ -577,10 +576,10 @@ func (worker *preferencesWorker) quick_settings() []readerQuickSetting { return result } -// handle_extension_quick asks the tentacle to select option; the shared quick +// handleExtensionQuick asks the tentacle to select option; the shared quick // menu has already chosen it and announces it after success. -func (worker *preferencesWorker) handle_extension_quick(ctx context.Context, setting readerQuickSetting, selected string) bool { - var option interaction.Item +func (worker *preferencesWorker) handleExtensionQuick(ctx context.Context, setting readerQuickSetting, selected string) bool { + var option tentaclewire.FormItem found := false for _, candidate := range setting.setting.Options { if candidate.ID == selected && !candidate.Disabled { @@ -592,11 +591,11 @@ func (worker *preferencesWorker) handle_extension_quick(ctx context.Context, set worker.announceSpeechSetting(setting.setting.Label + " was not changed") return false } - event := tentaclewire.ExtensionEvent{Event: "quick-setting", ID: setting.setting.ID, Selected: option.ID, Reader: worker.reader_state(setting.extension)} - request, err := worker.extension_effect(ctx, setting.extension, setting.setting.Command, event) - transaction := worker.reader_transaction() + event := tentaclewire.ExtensionEvent{Event: "quick-setting", ID: setting.setting.ID, Selected: option.ID, Reader: worker.readerState(setting.extension)} + request, err := worker.extensionEffect(ctx, setting.extension, setting.setting.Command, event) + transaction := worker.readerTransaction() if err == nil { - err = worker.stage_reader_request(ctx, &transaction, setting.extension.session, request) + err = worker.stageReaderRequest(ctx, &transaction, setting.extension.session, request) } if err == nil { found := false @@ -619,7 +618,7 @@ func (worker *preferencesWorker) handle_extension_quick(ctx context.Context, set } } if err == nil { - err = worker.commit_reader_transaction(ctx, setting.extension.session, transaction) + err = worker.commitReaderTransaction(ctx, setting.extension.session, transaction) } if err != nil { worker.logger.Warn("apply tentacle quick setting", "error", err) @@ -629,7 +628,7 @@ func (worker *preferencesWorker) handle_extension_quick(ctx context.Context, set return true } -func (runtime *tentacleRuntime) reader_continuation(command tentacleCommand, id string) bool { +func (runtime *tentacleRuntime) readerContinuation(command tentacleCommand, id string) bool { for _, registered := range command.session.Commands() { if registered.ID == id { return registered.Reader && !registered.Settings diff --git a/internal/app/tentacle_reader_test.go b/internal/app/tentacle_reader_test.go index 26447bf..7540f53 100644 --- a/internal/app/tentacle_reader_test.go +++ b/internal/app/tentacle_reader_test.go @@ -18,7 +18,6 @@ import ( "git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/preferences" "git.stormux.org/storm/cthulhu/internal/speech" "git.stormux.org/storm/cthulhu/internal/tentacle" @@ -27,7 +26,7 @@ import ( ) // A private protocol fixture, not an installable or bundled tentacle. -func reader_probe_extensions() sdk.Extensions { +func readerProbeExtensions() sdk.Extensions { return sdk.Extensions{Pages: []sdk.PreferencePage{{ID: "probe", Title: "Extension probe", Command: "apply", Elements: []sdk.Element{ {ID: "rate", Label: "Probe rate", Kind: sdk.Entry, Required: true, MaxLength: 3}, {ID: "enabled", Label: "Probe enabled", Kind: sdk.CheckBox}, @@ -122,7 +121,7 @@ func TestTentacleReaderExtensionPeer(t *testing.T) { configuration.DefaultVoice.Rate = &rate return sdk.Interaction{Reader: &sdk.ReaderRequest{Speech: &configuration}}, nil }}} - extensions := reader_probe_extensions() + extensions := readerProbeExtensions() if strings.HasPrefix(mode, "load") { extensions.Pages[0].Load = true } @@ -148,10 +147,10 @@ func (recorder *readerSpeechRecorder) UpdateConfiguration(ctx context.Context, n if next.SpeechOutputModule == recorder.failure && recorder.failure != "" { return errors.New("module unavailable") } - recorder.values = append(recorder.values, copy_reader_value(next)) + recorder.values = append(recorder.values, copyReaderValue(next)) return nil } -func reader_extension_fixture(t *testing.T, mode string) (*preferencesWorker, *tentacle.Session, *readerSpeechRecorder) { +func readerExtensionFixture(t *testing.T, mode string) (*preferencesWorker, *tentacle.Session, *readerSpeechRecorder) { t.Helper() manager, err := tentacle.NewManager(tentacle.DefaultLimits(), nil) if err != nil { @@ -197,20 +196,20 @@ func reader_extension_fixture(t *testing.T, mode string) (*preferencesWorker, *t worker.discover = func(context.Context, string) (speech.Catalog, error) { return speech.Catalog{"alpha": {{Name: "Example voice", Language: "en"}}}, nil } - worker.sync_extensions(t.Context()) + worker.syncExtensions(t.Context()) return worker, session, recorder } -func reader_page_request(worker *preferencesWorker, rate string) preferences.Request { - page := worker.extension_pages()[0] - values := copy_reader_value(page.Values) - values["rate"] = interaction.Value{Text: rate} +func readerPageRequest(worker *preferencesWorker, rate string) preferences.Request { + page := worker.extensionPages()[0] + values := copyReaderValue(page.Values) + values["rate"] = tentaclewire.Value{Text: rate} return preferences.Request{Values: preferences.FromSettings(worker.settings), ExtensionPages: []preferences.PageDraft{{Session: page.Session, ID: page.ID, Revision: page.Revision, Values: values}}} } func TestReaderExtensionPageApplyCancelSaveAndReopen(t *testing.T) { - worker, session, recorder := reader_extension_fixture(t, "normal") - before := copy_reader_value(worker.settings) + worker, session, recorder := readerExtensionFixture(t, "normal") + before := copyReaderValue(worker.settings) // Creating or editing a draft has no effect until Apply reaches the owner. - request := reader_page_request(worker, "73") + request := readerPageRequest(worker, "73") if len(recorder.values) != 0 || worker.speechOverride != nil { t.Fatal("draft changed runtime") } @@ -225,7 +224,7 @@ func TestReaderExtensionPageApplyCancelSaveAndReopen(t *testing.T) { if !reflect.DeepEqual(worker.settings, before) { t.Fatal("override overwrote base settings") } - if worker.extension_pages()[0].Values["rate"].Text != "73" { + if worker.extensionPages()[0].Values["rate"].Text != "73" { t.Fatal("draft not committed") } store, _ := config.NewStore(worker.settings.Path) @@ -240,8 +239,8 @@ func TestReaderExtensionPageApplyCancelSaveAndReopen(t *testing.T) { // Re-registering after a new session loads only saved page values, not speech. worker.extensions = map[string]*readerExtension{} worker.speechOverride, worker.speechOverrideOwner = nil, "" - worker.sync_extensions(t.Context()) - if worker.extension_pages()[0].Values["rate"].Text != "73" || worker.speechOverride != nil { + worker.syncExtensions(t.Context()) + if worker.extensionPages()[0].Values["rate"].Text != "73" || worker.speechOverride != nil { t.Fatal("page restoration activated speech") } response = worker.apply(t.Context(), request) @@ -250,10 +249,10 @@ func TestReaderExtensionPageApplyCancelSaveAndReopen(t *testing.T) { } } func TestReaderExtensionQuickNavigationRollbackDefaultAndBaseEdits(t *testing.T) { - worker, _, recorder := reader_extension_fixture(t, "normal") + worker, _, recorder := readerExtensionFixture(t, "normal") var messages []string worker.announce = func(message string) { messages = append(messages, message) } - probe := "tentacle." + worker.quick_settings()[0].key + probe := "tentacle." + worker.quickSettings()[0].key selectQuickSetting(t, worker, probe) if messages[len(messages)-1] != "Tentacles. Probe mode Default" { t.Fatal(messages) @@ -263,7 +262,7 @@ func TestReaderExtensionQuickNavigationRollbackDefaultAndBaseEdits(t *testing.T) t.Fatal("quick override corrupted base") } worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting) - if messages[len(messages)-1] != "Probe mode was not changed" || worker.quick_settings()[0].setting.Selected != "fast" || *worker.live.Load().DefaultVoice.Rate != 80 { + if messages[len(messages)-1] != "Probe mode was not changed" || worker.quickSettings()[0].setting.Selected != "fast" || *worker.live.Load().DefaultVoice.Rate != 80 { t.Fatal("failed switch committed") } // Built-in changes edit the active temporary override, not the normal voice. @@ -292,8 +291,8 @@ func TestReaderExtensionQuickNavigationRollbackDefaultAndBaseEdits(t *testing.T) func TestReaderExtensionRejectionCrashAndFailedApplyLeaveDraftUncommitted(t *testing.T) { for _, mode := range []string{"reject", "crash", "normal"} { t.Run(mode, func(t *testing.T) { - worker, _, recorder := reader_extension_fixture(t, mode) - request := reader_page_request(worker, "74") + worker, _, recorder := readerExtensionFixture(t, mode) + request := readerPageRequest(worker, "74") if mode == "normal" { worker.braille = &recordingBrailleSettings{err: errors.New("braille failed")} request.Values.EnableBraille = !worker.settings.EnableBraille @@ -306,7 +305,7 @@ func TestReaderExtensionRejectionCrashAndFailedApplyLeaveDraftUncommitted(t *tes if len(recorder.values) != 2 || *recorder.values[0].DefaultVoice.Rate != 74 || *recorder.values[1].DefaultVoice.Rate != 50 { t.Fatal("speech not rolled back after later failure", recorder.values) } - if worker.extension_pages()[0].Values["rate"].Text != "70" { + if worker.extensionPages()[0].Values["rate"].Text != "70" { t.Fatal("page values committed on failure") } } @@ -314,20 +313,20 @@ func TestReaderExtensionRejectionCrashAndFailedApplyLeaveDraftUncommitted(t *tes } } func TestReaderExtensionRevocationRestoresAndRemovesContributions(t *testing.T) { - worker, session, _ := reader_extension_fixture(t, "normal") - selectQuickSetting(t, worker, "tentacle."+worker.quick_settings()[0].key) + worker, session, _ := readerExtensionFixture(t, "normal") + selectQuickSetting(t, worker, "tentacle."+worker.quickSettings()[0].key) value := tentaclewire.SpeechFromSettings(worker.settings) rate := 82.0 value.DefaultVoice.Rate = &rate - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { t.Fatal(err) } session.Disable() - worker.sync_extensions(t.Context()) - if worker.speechOverride != nil || len(worker.extension_pages()) != 0 || len(worker.quick_settings()) != 0 || *worker.live.Load().DefaultVoice.Rate != 50 { + worker.syncExtensions(t.Context()) + if worker.speechOverride != nil || len(worker.extensionPages()) != 0 || len(worker.quickSettings()) != 0 || *worker.live.Load().DefaultVoice.Rate != 50 { t.Fatal("revoked contributions survived") } - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err == nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err == nil { t.Fatal("late effect applied") } message := "" @@ -338,18 +337,18 @@ func TestReaderExtensionRevocationRestoresAndRemovesContributions(t *testing.T) } } func TestReaderExtensionRevocationDuringBackendPreparation(t *testing.T) { - worker, session, recorder := reader_extension_fixture(t, "normal") + worker, session, recorder := readerExtensionFixture(t, "normal") value := tentaclewire.SpeechFromSettings(worker.settings) rate := 82.0 value.DefaultVoice.Rate = &rate recorder.hook = func() { session.Disable() } - _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false) + _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false) if err == nil || worker.speechOverride != nil || *worker.live.Load().DefaultVoice.Rate != 50 { t.Fatal("revoked update committed", err) } } func TestReaderExtensionSnapshotBoundsAndPreferenceWindowGate(t *testing.T) { - worker, session, _ := reader_extension_fixture(t, "normal") + worker, session, _ := readerExtensionFixture(t, "normal") worker.discover = func(context.Context, string) (speech.Catalog, error) { voices := make([]speech.Voice, 10000) for index := range voices { @@ -357,7 +356,7 @@ func TestReaderExtensionSnapshotBoundsAndPreferenceWindowGate(t *testing.T) { } return speech.Catalog{"alpha": voices, "beta": nil}, nil } - state, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Snapshot: true, Module: "alpha"}, true) + state, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Snapshot: true, Module: "alpha"}, true) if err != nil || !state.CatalogTruncated || len(state.Voices) == 0 || len(state.Modules) != 2 { t.Fatal(state, err) } @@ -366,36 +365,36 @@ func TestReaderExtensionSnapshotBoundsAndPreferenceWindowGate(t *testing.T) { t.Fatal("oversized continuation") } value := state.Speech - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, true); err == nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, true); err == nil { t.Fatal("changed speech behind preferences draft") } ctx, cancel := context.WithCancel(t.Context()) cancel() - if _, err := worker.apply_reader_request(ctx, session, tentaclewire.ReaderRequest{Speech: &value}, false); err == nil { + if _, err := worker.applyReaderRequest(ctx, session, tentaclewire.ReaderRequest{Speech: &value}, false); err == nil { t.Fatal("cancelled request applied") } - page := worker.extension_pages()[0] - page.Values["rate"] = interaction.Value{Text: "1"} - if worker.extension_pages()[0].Values["rate"].Text != "70" { + page := worker.extensionPages()[0] + page.Values["rate"] = tentaclewire.Value{Text: "1"} + if worker.extensionPages()[0].Values["rate"].Text != "70" { t.Fatal("snapshot aliases page values") } } func TestReaderExtensionSlowCallbackTimesOutAndRetiresSession(t *testing.T) { - worker, session, _ := reader_extension_fixture(t, "slow") + worker, session, _ := readerExtensionFixture(t, "slow") ctx, cancel := context.WithTimeout(t.Context(), 40*time.Millisecond) defer cancel() - response := worker.apply(ctx, reader_page_request(worker, "75")) + response := worker.apply(ctx, readerPageRequest(worker, "75")) if response.Accepted || worker.speechOverride != nil { t.Fatal("timeout applied") } waitTentacle(t, func() bool { state, _ := session.Status(); return state != tentacle.Active }) - worker.sync_extensions(t.Context()) - if len(worker.extension_pages()) != 0 { + worker.syncExtensions(t.Context()) + if len(worker.extensionPages()) != 0 { t.Fatal("timed-out page survived") } } func TestReaderExtensionWorkerMailboxAndProtocolContinuation(t *testing.T) { - worker, session, _ := reader_extension_fixture(t, "normal") + worker, session, _ := readerExtensionFixture(t, "normal") // The real runtime interaction asks the worker for a snapshot, receives it // through the protocol continuation, and proposes a speech change. if err := worker.Start(t.Context()); err != nil { @@ -412,23 +411,23 @@ func TestReaderExtensionWorkerMailboxAndProtocolContinuation(t *testing.T) { raw, _ := json.Marshal(sdk.Interaction{Reader: &sdk.ReaderRequest{Snapshot: true}, Next: "receive"}) worker.tentacles.interact(t.Context(), command, raw) // Query through the same owner mailbox; do not read mutable worker state. - state, err := worker.request_reader(t.Context(), session, tentaclewire.ReaderRequest{Snapshot: true}) + state, err := worker.requestReader(t.Context(), session, tentaclewire.ReaderRequest{Snapshot: true}) if err != nil || state.Speech.DefaultVoice.Rate == nil || *state.Speech.DefaultVoice.Rate != 77 { t.Fatal(state, err) } session.Disable() - worker.tentacles.signal_extensions() + worker.tentacles.signalExtensions() // Sync is owner-serialized by the next request, proving queued late work is rejected. - if _, err := worker.request_reader(t.Context(), session, tentaclewire.ReaderRequest{RestoreSpeech: true}); err == nil { + if _, err := worker.requestReader(t.Context(), session, tentaclewire.ReaderRequest{RestoreSpeech: true}); err == nil { t.Fatal("revoked mailbox work accepted") } } func TestReaderExtensionPersistFailureReportsSessionOnly(t *testing.T) { - worker, _, _ := reader_extension_fixture(t, "normal") + worker, _, _ := readerExtensionFixture(t, "normal") if err := os.WriteFile(worker.pageStore.Path, []byte(`{}`), 0600); err != nil { t.Fatal(err) } - request := reader_page_request(worker, "76") + request := readerPageRequest(worker, "76") request.Save = true request.Close = true response := worker.apply(t.Context(), request) @@ -442,11 +441,11 @@ func TestReaderExtensionPersistFailureReportsSessionOnly(t *testing.T) { } func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) { - worker, session, recorder := reader_extension_fixture(t, "normal") + worker, session, recorder := readerExtensionFixture(t, "normal") value := tentaclewire.SpeechFromSettings(worker.settings) rate := 83.0 value.DefaultVoice.Rate = &rate - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { t.Fatal(err) } appSettings := worker.settings @@ -458,7 +457,7 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) { if *worker.live.Load().DefaultVoice.Rate != 83 || worker.live.Load().SpeechVerbosityLevel != 0 { t.Fatal("application switch lost override or app preferences") } - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{RestoreSpeech: true}, false); err != nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{RestoreSpeech: true}, false); err != nil { t.Fatal(err) } if *worker.live.Load().DefaultVoice.Rate != 61 { @@ -470,7 +469,7 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) { t.Fatal(err) } count := len(recorder.values) - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { t.Fatal(err) } if len(recorder.values) != count || worker.live.Load().EnableSpeech { @@ -489,67 +488,67 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) { } count = len(recorder.values) session.Disable() - worker.sync_extensions(t.Context()) + worker.syncExtensions(t.Context()) if worker.speechOverride != nil || len(recorder.values) != count { t.Fatal("disabled speech required a backend restoration") } } func TestReaderExtensionOwnershipLockAndAtomicContributionUpdate(t *testing.T) { - worker, first, _ := reader_extension_fixture(t, "normal") - _, second, _ := reader_extension_fixture(t, "other") + worker, first, _ := readerExtensionFixture(t, "normal") + _, second, _ := readerExtensionFixture(t, "other") worker.tentacles.publishCommands([]*tentacle.Session{first, second}) - worker.sync_extensions(t.Context()) + worker.syncExtensions(t.Context()) value := tentaclewire.SpeechFromSettings(worker.settings) rate := 85.0 value.DefaultVoice.Rate = &rate - if _, err := worker.apply_reader_request(t.Context(), first, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { + if _, err := worker.applyReaderRequest(t.Context(), first, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { t.Fatal(err) } for _, request := range []tentaclewire.ReaderRequest{{Speech: &value}, {RestoreSpeech: true}} { - if _, err := worker.apply_reader_request(t.Context(), second, request, false); err == nil { + if _, err := worker.applyReaderRequest(t.Context(), second, request, false); err == nil { t.Fatal("another session changed the owner's override") } } - extensions := copy_reader_value(worker.extensions[first.Identity()].value) + extensions := copyReaderValue(worker.extensions[first.Identity()].value) extensions.QuickSettings[0].Label = "Renamed probe" value.Module = "unavailable" - if _, err := worker.apply_reader_request(t.Context(), first, tentaclewire.ReaderRequest{Speech: &value, Extensions: &extensions}, false); err == nil { + if _, err := worker.applyReaderRequest(t.Context(), first, tentaclewire.ReaderRequest{Speech: &value, Extensions: &extensions}, false); err == nil { t.Fatal("unavailable module accepted") } if worker.extensions[first.Identity()].value.QuickSettings[0].Label != "Probe mode" { t.Fatal("partial contribution update committed") } worker.tentacles.output.gate.secure.Store(true) - if _, err := worker.apply_reader_request(t.Context(), first, tentaclewire.ReaderRequest{RestoreSpeech: true}, false); err == nil { + if _, err := worker.applyReaderRequest(t.Context(), first, tentaclewire.ReaderRequest{RestoreSpeech: true}, false); err == nil { t.Fatal("locked reader accepted request") } worker.tentacles.output.gate.secure.Store(false) worker.tentacles.output.gate.suspended.Store(true) - if _, err := worker.apply_reader_request(t.Context(), first, tentaclewire.ReaderRequest{Snapshot: true}, false); err == nil { + if _, err := worker.applyReaderRequest(t.Context(), first, tentaclewire.ReaderRequest{Snapshot: true}, false); err == nil { t.Fatal("suspended reader exposed state") } worker.tentacles.output.gate.suspended.Store(false) } func TestReaderExtensionRestorationFailureRetainsWorkingVoiceAndReports(t *testing.T) { - worker, session, recorder := reader_extension_fixture(t, "normal") + worker, session, recorder := readerExtensionFixture(t, "normal") value := tentaclewire.SpeechFromSettings(worker.settings) value.Module = "alpha" - if _, err := worker.apply_reader_request(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { + if _, err := worker.applyReaderRequest(t.Context(), session, tentaclewire.ReaderRequest{Speech: &value}, false); err != nil { t.Fatal(err) } worker.settings.SpeechOutputModule = "unavailable" message := "" worker.announce = func(text string) { message = text } session.Disable() - worker.sync_extensions(t.Context()) + worker.syncExtensions(t.Context()) if worker.speechOverride == nil || worker.live.Load().SpeechOutputModule != "alpha" || !strings.Contains(message, "could not be restored") { t.Fatal("failed restoration lost working speech", message) } - if len(worker.extension_pages()) != 0 || len(worker.quick_settings()) != 0 { + if len(worker.extensionPages()) != 0 || len(worker.quickSettings()) != 0 { t.Fatal("revoked UI survived failed restoration") } recorder.failure = "" - worker.sync_extensions(t.Context()) + worker.syncExtensions(t.Context()) if worker.speechOverride != nil || worker.live.Load().SpeechOutputModule != "unavailable" { t.Fatal("later restoration did not recover") } @@ -559,7 +558,7 @@ func TestReaderExtensionManagedLifecycleRestoresWithoutAnotherCommand(t *testing for _, ending := range []string{"disable", "remove", "exit", "emergency"} { t.Run(ending, func(t *testing.T) { directory := t.TempDir() - runtime, _ := managed_tentacle_fixture(t, filepath.Join(directory, "tentacles.toml"), false) + runtime, _ := managedTentacleFixture(t, filepath.Join(directory, "tentacles.toml"), false) runtime.output = tentacleOutputFixture(t) settings := config.DefaultSettings() settings.Path = filepath.Join(directory, "settings.toml") @@ -589,8 +588,8 @@ func TestReaderExtensionManagedLifecycleRestoresWithoutAnotherCommand(t *testing t.Fatal(err) } entry := tentacle.Entry{ID: "managed-reader-probe", Enabled: true, Presentation: true, Interaction: true, ReaderSettings: true, Program: []string{executable, "-test.run=^TestTentacleReaderExtensionPeer$", "--", "reader-extension-peer", "normal"}} - manage_tentacle(t, runtime, "add", entry.ID, &entry) - sessions := runtime.reader_sessions() + manageTentacle(t, runtime, "add", entry.ID, &entry) + sessions := runtime.readerSessions() if len(sessions) != 1 { t.Fatal("reader session not published", runtime.Snapshot()) } @@ -601,7 +600,7 @@ func TestReaderExtensionManagedLifecycleRestoresWithoutAnotherCommand(t *testing configuration := tentaclewire.SpeechFromSettings(settings) rate := 87.0 configuration.DefaultVoice.Rate = &rate - if _, err := worker.request_reader(t.Context(), session, tentaclewire.ReaderRequest{Speech: &configuration}); err != nil { + if _, err := worker.requestReader(t.Context(), session, tentaclewire.ReaderRequest{Speech: &configuration}); err != nil { t.Fatal(err) } if *worker.live.Load().DefaultVoice.Rate != 87 { @@ -609,7 +608,7 @@ func TestReaderExtensionManagedLifecycleRestoresWithoutAnotherCommand(t *testing } switch ending { case "disable", "remove": - manage_tentacle(t, runtime, ending, entry.ID, nil) + manageTentacle(t, runtime, ending, entry.ID, nil) case "exit": replies, err := session.Invoke(t.Context(), "apply", json.RawMessage(`{"event":"exit"}`)) if err != nil { @@ -633,8 +632,8 @@ func TestReaderExtensionManagedLifecycleRestoresWithoutAnotherCommand(t *testing func TestReaderExtensionPageLoadCanInspectCatalogWithoutChangingSpeech(t *testing.T) { for _, mode := range []string{"load", "load-snapshot", "load-denied"} { t.Run(mode, func(t *testing.T) { - worker, _, recorder := reader_extension_fixture(t, mode) - response, err := worker.initial_response(t.Context()) + worker, _, recorder := readerExtensionFixture(t, mode) + response, err := worker.initialResponse(t.Context()) if err != nil { t.Fatal(err) } diff --git a/internal/app/tentacle_remote_braille.go b/internal/app/tentacle_remote_braille.go index 80f9e5b..4c0c897 100644 --- a/internal/app/tentacle_remote_braille.go +++ b/internal/app/tentacle_remote_braille.go @@ -35,9 +35,9 @@ type processVirtualBraille struct { done chan struct{} } -// start_virtual_braille runs `cthulhu-braille --virtual`. It opens no display; +// startVirtualBraille runs `cthulhu-braille --virtual`. It opens no display; // translation stays in the disposable helper, as for the physical display. -func start_virtual_braille(path string) (virtualBraille, error) { +func startVirtualBraille(path string) (virtualBraille, error) { cmd := exec.Command(path, "--virtual") stdin, err := cmd.StdinPipe() if err != nil { @@ -97,14 +97,14 @@ func (helper *processVirtualBraille) Close() { } } -// start_remote_braille attaches the Remote Braille owner for a session +// startRemoteBraille attaches the Remote Braille owner for a session // installed with braille-stream. As the controlled computer it exports the // application Braille frame, rendered by a virtual helper at the controller's // width, and applies the controller's pan and route gestures. As the // controller it shows the peer's cells on the local display and reports local // pan and route keys. Reader UI, flashed messages and secure frames are never // exported; lock, handoff and revocation end both directions. -func (runtime *tentacleRuntime) start_remote_braille(ctx context.Context, session *tentacle.Session) <-chan struct{} { +func (runtime *tentacleRuntime) startRemoteBraille(ctx context.Context, session *tentacle.Session) <-chan struct{} { done := make(chan struct{}) owner := runtime.output if owner == nil || owner.braille == nil || owner.gate == nil || runtime.remotePolicy == nil || @@ -115,7 +115,7 @@ func (runtime *tentacleRuntime) start_remote_braille(ctx context.Context, sessio worker := owner.braille launch := runtime.virtualBraille if launch == nil { - launch = func() (virtualBraille, error) { return start_virtual_braille(worker.path) } + launch = func() (virtualBraille, error) { return startVirtualBraille(worker.path) } } requests := session.EnableRemoteBraille() allowed := func() bool { diff --git a/internal/app/tentacle_remote_braille_test.go b/internal/app/tentacle_remote_braille_test.go index 792602c..c136075 100644 --- a/internal/app/tentacle_remote_braille_test.go +++ b/internal/app/tentacle_remote_braille_test.go @@ -52,10 +52,10 @@ func (router peerRouteRecorder) RouteBraille(_ context.Context, route atspi.Brai return nil } -func braille_fixture(t *testing.T, grants []string) (*tentacle.Session, *tentacle.RemotePolicy, *brailleWorker, *fakeVirtualBraille, peerRouteRecorder) { +func brailleFixture(t *testing.T, grants []string) (*tentacle.Session, *tentacle.RemotePolicy, *brailleWorker, *fakeVirtualBraille, peerRouteRecorder) { t.Helper() policy := tentacle.NewRemotePolicy() - session := keyboard_owner_session(t, policy, grants) + session := keyboardOwnerSession(t, policy, grants) router := peerRouteRecorder{routes: make(chan atspi.BrailleRoute, 4)} worker := &brailleWorker{logger: slog.New(slog.DiscardHandler), wake: make(chan struct{}, 1), cancel: func() {}, connected: true, cells: 20, router: router, frame: braille.Frame{Cursor: -1}, baseFrame: braille.Frame{Cursor: -1}} @@ -63,7 +63,7 @@ func braille_fixture(t *testing.T, grants []string) (*tentacle.Session, *tentacl runtime := &tentacleRuntime{logger: slog.New(slog.DiscardHandler), remotePolicy: policy, announcements: make(chan string, 4), output: &tentacleOutput{braille: worker, gate: &focusGate{}}, virtualBraille: func() (virtualBraille, error) { return fake, nil }} ctx, cancel := context.WithCancel(t.Context()) - done := runtime.start_remote_braille(ctx, session) + done := runtime.startRemoteBraille(ctx, session) t.Cleanup(func() { cancel() select { @@ -75,7 +75,7 @@ func braille_fixture(t *testing.T, grants []string) (*tentacle.Session, *tentacl return session, policy, worker, fake, router } -func braille_open(t *testing.T, session *tentacle.Session, role string, grants []string) tentaclewire.RemoteLease { +func brailleOpen(t *testing.T, session *tentacle.Session, role string, grants []string) tentaclewire.RemoteLease { t.Helper() approval, err := session.BeginRemoteApproval(role, grants) if err != nil { @@ -85,19 +85,19 @@ func braille_open(t *testing.T, session *tentacle.Session, role string, grants [ t.Fatal(err) } var lease tentaclewire.RemoteLease - if json.Unmarshal(keyboard_owner_invoke(t, session, "open", nil), &lease) != nil || lease.Epoch == 0 { + if json.Unmarshal(keyboardOwnerInvoke(t, session, "open", nil), &lease) != nil || lease.Epoch == 0 { t.Fatal("lease did not open") } return lease } -func braille_call(t *testing.T, session *tentacle.Session, lease tentaclewire.RemoteLease, sequence uint64, value tentaclewire.RemoteBraille) { +func brailleCall(t *testing.T, session *tentacle.Session, lease tentaclewire.RemoteLease, sequence uint64, value tentaclewire.RemoteBraille) { t.Helper() request := tentaclewire.RemoteBrailleRequest{RemoteOperation: tentaclewire.RemoteOperation{Lease: lease.Lease, Epoch: lease.Epoch, Sequence: sequence}, Braille: value} - keyboard_owner_invoke(t, session, "rpc", map[string]any{"Method": "remote.braille", "Params": request}) + keyboardOwnerInvoke(t, session, "rpc", map[string]any{"Method": "remote.braille", "Params": request}) } -func wait_until(t *testing.T, what string, predicate func() bool) { +func waitUntil(t *testing.T, what string, predicate func() bool) { t.Helper() deadline := time.Now().Add(5 * time.Second) for !predicate() { @@ -109,12 +109,12 @@ func wait_until(t *testing.T, what string, predicate func() bool) { } func TestRemoteBrailleExportsApplicationFramesOnly(t *testing.T) { - session, policy, worker, fake, router := braille_fixture(t, []string{"braille-stream"}) + session, policy, worker, fake, router := brailleFixture(t, []string{"braille-stream"}) route := braille.TextRoute{Start: 0, End: 5, SourceStart: 0, TextLength: 5, BusName: ":1.2", Path: "/text", SourceText: "hello"} worker.EnqueueFrame(braille.Frame{Text: "hello", Cursor: -1, Routes: []braille.TextRoute{route}}) - lease := braille_open(t, session, "controlled", []string{"braille-stream"}) - braille_call(t, session, lease, 1, tentaclewire.RemoteBraille{Op: "size", Width: 20}) - wait_until(t, "width and initial frame", func() bool { return len(fake.seen()) >= 2 }) + lease := brailleOpen(t, session, "controlled", []string{"braille-stream"}) + brailleCall(t, session, lease, 1, tentaclewire.RemoteBraille{Op: "size", Width: 20}) + waitUntil(t, "width and initial frame", func() bool { return len(fake.seen()) >= 2 }) seen := fake.seen() if seen[0].Width == nil || *seen[0].Width != 20 || seen[1].Frame == nil || seen[1].Frame.Text != "hello" || seen[1].Frame.ID == 0 || seen[1].Frame.Routes != nil { t.Fatalf("initial export = %+v", seen) @@ -122,12 +122,12 @@ func TestRemoteBrailleExportsApplicationFramesOnly(t *testing.T) { exportedID := seen[1].Frame.ID fake.responses <- braille.VirtualResponse{Cells: []int{1, 3, 9}} var event tentaclewire.SessionEvent - if json.Unmarshal(keyboard_owner_invoke(t, session, "event", nil), &event) != nil || event.Kind != "remote.braille" || !reflect.DeepEqual(event.Braille.Cells, []int{1, 3, 9}) { + if json.Unmarshal(keyboardOwnerInvoke(t, session, "event", nil), &event) != nil || event.Kind != "remote.braille" || !reflect.DeepEqual(event.Braille.Cells, []int{1, 3, 9}) { t.Fatal("cells not published", event) } - braille_call(t, session, lease, 2, tentaclewire.RemoteBraille{Op: "gesture", Gesture: "route", Index: 3}) - braille_call(t, session, lease, 3, tentaclewire.RemoteBraille{Op: "gesture", Gesture: "pan-right"}) - wait_until(t, "gestures", func() bool { return len(fake.seen()) >= 4 }) + brailleCall(t, session, lease, 2, tentaclewire.RemoteBraille{Op: "gesture", Gesture: "route", Index: 3}) + brailleCall(t, session, lease, 3, tentaclewire.RemoteBraille{Op: "gesture", Gesture: "pan-right"}) + waitUntil(t, "gestures", func() bool { return len(fake.seen()) >= 4 }) if seen = fake.seen(); seen[2].Route == nil || *seen[2].Route != 3 || seen[3].Pan != "right" { t.Fatalf("gestures = %+v", seen[2:]) } @@ -143,7 +143,7 @@ func TestRemoteBrailleExportsApplicationFramesOnly(t *testing.T) { // Reader UI is never exported; application frames under it are, unroutable. worker.SetInternalUIFrame(&braille.Frame{Text: "private form", Cursor: -1}) worker.EnqueueFrame(braille.Frame{Text: "world", Cursor: -1}) - wait_until(t, "frame under reader UI", func() bool { return len(fake.seen()) >= 5 }) + waitUntil(t, "frame under reader UI", func() bool { return len(fake.seen()) >= 5 }) for _, request := range fake.seen() { if request.Frame != nil && request.Frame.Text == "private form" { t.Fatal("reader UI frame exported") @@ -168,17 +168,17 @@ func TestRemoteBrailleExportsApplicationFramesOnly(t *testing.T) { } func TestRemoteBrailleControllerShowsPeerCellsAndReportsKeys(t *testing.T) { - session, policy, worker, _, _ := braille_fixture(t, []string{"braille-stream", "remote-present"}) + session, policy, worker, _, _ := brailleFixture(t, []string{"braille-stream", "remote-present"}) worker.EnqueueFrame(braille.Frame{Text: "local", Cursor: -1}) worker.SetContraction(true, "en-ueb-g2.ctb") - lease := braille_open(t, session, "controller", []string{"braille-stream"}) - braille_call(t, session, lease, 1, tentaclewire.RemoteBraille{Op: "geometry"}) + lease := brailleOpen(t, session, "controller", []string{"braille-stream"}) + brailleCall(t, session, lease, 1, tentaclewire.RemoteBraille{Op: "geometry"}) var event tentaclewire.SessionEvent - if json.Unmarshal(keyboard_owner_invoke(t, session, "event", nil), &event) != nil || event.Braille == nil || event.Braille.Op != "geometry" || event.Braille.Width != 20 { + if json.Unmarshal(keyboardOwnerInvoke(t, session, "event", nil), &event) != nil || event.Braille == nil || event.Braille.Op != "geometry" || event.Braille.Width != 20 { t.Fatal("geometry not reported", event) } - braille_call(t, session, lease, 2, tentaclewire.RemoteBraille{Op: "cells", Cells: []int{1, 2, 255}}) - wait_until(t, "peer cells", func() bool { return worker.current().Raw }) + brailleCall(t, session, lease, 2, tentaclewire.RemoteBraille{Op: "cells", Cells: []int{1, 2, 255}}) + waitUntil(t, "peer cells", func() bool { return worker.current().Raw }) frame := worker.current() if frame.Text != "⠁⠂⣿" || frame.Contract || frame.Table != "" || frame.WordWrap { t.Fatalf("peer frame = %+v", frame) @@ -193,12 +193,12 @@ func TestRemoteBrailleControllerShowsPeerCellsAndReportsKeys(t *testing.T) { worker.route(t.Context(), braille.RoutingEvent{ID: frame.ID, Offset: -1, Pan: "right"}) worker.route(t.Context(), braille.RoutingEvent{ID: frame.ID + 99, Offset: 0}) // Stale. for _, want := range []tentaclewire.RemoteBraille{{Op: "gesture", Gesture: "route", Index: 1}, {Op: "gesture", Gesture: "pan-right"}} { - if json.Unmarshal(keyboard_owner_invoke(t, session, "event", nil), &event) != nil || event.Braille == nil || !reflect.DeepEqual(*event.Braille, want) { + if json.Unmarshal(keyboardOwnerInvoke(t, session, "event", nil), &event) != nil || event.Braille == nil || !reflect.DeepEqual(*event.Braille, want) { t.Fatal("gesture changed", event) } } policy.SetAvailable(false) - wait_until(t, "local frame restored", func() bool { return !worker.current().Raw }) + waitUntil(t, "local frame restored", func() bool { return !worker.current().Raw }) if text := worker.current().Text; text != "newer" { t.Fatal("restored frame", text) } diff --git a/internal/app/tentacle_remote_capture.go b/internal/app/tentacle_remote_capture.go index 7a75633..09b8a78 100644 --- a/internal/app/tentacle_remote_capture.go +++ b/internal/app/tentacle_remote_capture.go @@ -24,13 +24,13 @@ type remoteCaptureInput interface { EndRemoteCapture(context.Context, uint64) error } -// start_remote_capture attaches the controller capture owner for a session +// startRemoteCapture attaches the controller capture owner for a session // installed with keyboard-capture. Without a native capture owner remote.focus // stays owner-unavailable. Capture is entered only on a request for the current // controller lease while the reader is unlocked, not handed off and showing no // reader UI. Revocation, policy or the core escape end it; ending releases all // forwarded keys through the stream before the local focus event. -func (runtime *tentacleRuntime) start_remote_capture(ctx context.Context, session *tentacle.Session) <-chan struct{} { +func (runtime *tentacleRuntime) startRemoteCapture(ctx context.Context, session *tentacle.Session) <-chan struct{} { done := make(chan struct{}) capture, ok := runtime.input.(remoteCaptureInput) owner := runtime.output diff --git a/internal/app/tentacle_remote_capture_test.go b/internal/app/tentacle_remote_capture_test.go index 3304f95..9e93454 100644 --- a/internal/app/tentacle_remote_capture_test.go +++ b/internal/app/tentacle_remote_capture_test.go @@ -70,24 +70,24 @@ func (fake *fakeCaptureInput) emit(event input.RemoteCaptureEvent) { } } -func capture_next_event(t *testing.T, session *tentacle.Session) tentaclewire.SessionEvent { +func captureNextEvent(t *testing.T, session *tentacle.Session) tentaclewire.SessionEvent { t.Helper() var event tentaclewire.SessionEvent - if err := json.Unmarshal(keyboard_owner_invoke(t, session, "event", nil), &event); err != nil { + if err := json.Unmarshal(keyboardOwnerInvoke(t, session, "event", nil), &event); err != nil { t.Fatal(err) } return event } -func capture_fixture(t *testing.T) (*tentacle.Session, *tentacle.RemotePolicy, *fakeCaptureInput, *tentacleRuntime) { +func captureFixture(t *testing.T) (*tentacle.Session, *tentacle.RemotePolicy, *fakeCaptureInput, *tentacleRuntime) { t.Helper() policy := tentacle.NewRemotePolicy() - session := keyboard_owner_session(t, policy, []string{"keyboard-capture", "remote-present"}) + session := keyboardOwnerSession(t, policy, []string{"keyboard-capture", "remote-present"}) fake := &fakeCaptureInput{begun: make(chan struct{}, 4), ended: make(chan uint64, 4)} runtime := &tentacleRuntime{logger: slog.New(slog.DiscardHandler), remotePolicy: policy, input: fake, output: &tentacleOutput{gate: &focusGate{}}, announcements: make(chan string, 1)} ctx, cancel := context.WithCancel(t.Context()) - done := runtime.start_remote_capture(ctx, session) + done := runtime.startRemoteCapture(ctx, session) t.Cleanup(func() { cancel() select { @@ -99,7 +99,7 @@ func capture_fixture(t *testing.T) (*tentacle.Session, *tentacle.RemotePolicy, * return session, policy, fake, runtime } -func capture_open(t *testing.T, session *tentacle.Session) tentaclewire.RemoteLease { +func captureOpen(t *testing.T, session *tentacle.Session) tentaclewire.RemoteLease { t.Helper() grants := []string{"keyboard-capture"} approval, err := session.BeginRemoteApproval("controller", grants) @@ -110,58 +110,58 @@ func capture_open(t *testing.T, session *tentacle.Session) tentaclewire.RemoteLe t.Fatal(err) } var lease tentaclewire.RemoteLease - if json.Unmarshal(keyboard_owner_invoke(t, session, "open", nil), &lease) != nil || lease.Epoch == 0 { + if json.Unmarshal(keyboardOwnerInvoke(t, session, "open", nil), &lease) != nil || lease.Epoch == 0 { t.Fatal("controller lease did not open") } return lease } -func capture_focus(t *testing.T, session *tentacle.Session, lease tentaclewire.RemoteLease, sequence uint64, remote bool) { +func captureFocus(t *testing.T, session *tentacle.Session, lease tentaclewire.RemoteLease, sequence uint64, remote bool) { t.Helper() request := tentaclewire.RemoteFocusRequest{RemoteOperation: tentaclewire.RemoteOperation{Lease: lease.Lease, Epoch: lease.Epoch, Sequence: sequence}, Remote: remote} - keyboard_owner_invoke(t, session, "rpc", map[string]any{"Method": "remote.focus", "Params": request}) + keyboardOwnerInvoke(t, session, "rpc", map[string]any{"Method": "remote.focus", "Params": request}) } func TestRemoteCaptureForwardsKeysAndReportsFocus(t *testing.T) { - session, _, fake, _ := capture_fixture(t) - lease := capture_open(t, session) - capture_focus(t, session, lease, 1, true) + session, _, fake, _ := captureFixture(t) + lease := captureOpen(t, session) + captureFocus(t, session, lease, 1, true) <-fake.begun if fake.prefix != "tentacle/"+session.Identity()+"/" { t.Fatal("capture prefix does not name this Tentacle", fake.prefix) } - if event := capture_next_event(t, session); event.Kind != "remote.focus" || event.Focus != "remote" || event.Reason != "requested" { + if event := captureNextEvent(t, session); event.Kind != "remote.focus" || event.Focus != "remote" || event.Reason != "requested" { t.Fatal("missing remote focus", event) } fake.emit(input.RemoteCaptureEvent{Key: &input.RemoteCaptureTransition{Code: 38, Name: "a", Pressed: true}}) fake.emit(input.RemoteCaptureEvent{Key: &input.RemoteCaptureTransition{Code: 38, Pressed: true, Repeat: true}}) fake.emit(input.RemoteCaptureEvent{Key: &input.RemoteCaptureTransition{Code: 38}}) for _, want := range []tentaclewire.RemoteCapturedKey{{Code: 38, Name: "a", Pressed: true}, {Code: 38, Pressed: true, Repeat: true}, {Code: 38}} { - if event := capture_next_event(t, session); event.Kind != "remote.input" || event.Input == nil || *event.Input != want { + if event := captureNextEvent(t, session); event.Kind != "remote.input" || event.Input == nil || *event.Input != want { t.Fatal("captured key changed", event) } } fake.emit(input.RemoteCaptureEvent{Ended: "escape"}) - if event := capture_next_event(t, session); event.Kind != "remote.focus" || event.Focus != "local" || event.Reason != "escape" { + if event := captureNextEvent(t, session); event.Kind != "remote.focus" || event.Focus != "local" || event.Reason != "escape" { t.Fatal("escape not reported", event) } // Re-enter, then leave by request. - capture_focus(t, session, lease, 2, true) + captureFocus(t, session, lease, 2, true) <-fake.begun - capture_next_event(t, session) - capture_focus(t, session, lease, 3, false) + captureNextEvent(t, session) + captureFocus(t, session, lease, 3, false) <-fake.ended - if event := capture_next_event(t, session); event.Focus != "local" || event.Reason != "requested" { + if event := captureNextEvent(t, session); event.Focus != "local" || event.Reason != "requested" { t.Fatal("requested local focus not reported", event) } } func TestRemoteCaptureRevocationEndsCapture(t *testing.T) { - session, policy, fake, _ := capture_fixture(t) - lease := capture_open(t, session) - capture_focus(t, session, lease, 1, true) + session, policy, fake, _ := captureFixture(t) + lease := captureOpen(t, session) + captureFocus(t, session, lease, 1, true) <-fake.begun - capture_next_event(t, session) + captureNextEvent(t, session) policy.SetAvailable(false) // Lock or handoff. select { case <-fake.ended: @@ -172,19 +172,19 @@ func TestRemoteCaptureRevocationEndsCapture(t *testing.T) { } func TestRemoteCaptureRefusesUnderReaderPolicyOrGrabFailure(t *testing.T) { - session, _, fake, runtime := capture_fixture(t) - lease := capture_open(t, session) + session, _, fake, runtime := captureFixture(t) + lease := captureOpen(t, session) runtime.output.gate.suspended.Store(true) - capture_focus(t, session, lease, 1, true) - if event := capture_next_event(t, session); event.Focus != "local" || event.Reason != "local" { + captureFocus(t, session, lease, 1, true) + if event := captureNextEvent(t, session); event.Focus != "local" || event.Reason != "local" { t.Fatal("suspended reader entered remote focus", event) } runtime.output.gate.suspended.Store(false) fake.mu.Lock() fake.refuse = true fake.mu.Unlock() - capture_focus(t, session, lease, 2, true) - if event := capture_next_event(t, session); event.Focus != "local" || event.Reason != "unavailable" { + captureFocus(t, session, lease, 2, true) + if event := captureNextEvent(t, session); event.Focus != "local" || event.Reason != "unavailable" { t.Fatal("failed grab not reported", event) } if len(fake.begun) != 0 { @@ -194,11 +194,11 @@ func TestRemoteCaptureRefusesUnderReaderPolicyOrGrabFailure(t *testing.T) { func TestRemoteCaptureRequiresGrantAndOwner(t *testing.T) { policy := tentacle.NewRemotePolicy() - session := keyboard_owner_session(t, policy, []string{"remote-present"}) + session := keyboardOwnerSession(t, policy, []string{"remote-present"}) runtime := &tentacleRuntime{logger: slog.New(slog.DiscardHandler), remotePolicy: policy, input: &fakeCaptureInput{begun: make(chan struct{}, 1), ended: make(chan uint64, 1)}, output: &tentacleOutput{gate: &focusGate{}}} select { - case <-runtime.start_remote_capture(t.Context(), session): + case <-runtime.startRemoteCapture(t.Context(), session): case <-time.After(time.Second): t.Fatal("ungranted session attached capture") } diff --git a/internal/app/tentacle_remote_connection_test.go b/internal/app/tentacle_remote_connection_test.go index 9e0a579..0aba7a3 100644 --- a/internal/app/tentacle_remote_connection_test.go +++ b/internal/app/tentacle_remote_connection_test.go @@ -25,20 +25,20 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" "git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/review" "git.stormux.org/storm/cthulhu/internal/tentacle" "git.stormux.org/storm/cthulhu/internal/tentaclewire" + commonui "git.stormux.org/storm/screenreader-common/internalui" ) // This uses the source-built external executable and real host/SDK IPC. Only // OpenLocal submissions are synthetic; it cannot prove physical-source input. -func remote_command_fixture(t *testing.T, setup ...func(*tentacleRuntime)) (*tentacleRuntime, *consentTestForms, input.Command) { +func remoteCommandFixture(t *testing.T, setup ...func(*tentacleRuntime)) (*tentacleRuntime, *consentTestForms, input.Command) { t.Helper() - return remote_command_fixture_grants(t, []string{"output-observe", "remote-present"}, setup...) + return remoteCommandFixtureGrants(t, []string{"output-observe", "remote-present"}, setup...) } -func remote_command_fixture_grants(t *testing.T, grants []string, setup ...func(*tentacleRuntime)) (*tentacleRuntime, *consentTestForms, input.Command) { +func remoteCommandFixtureGrants(t *testing.T, grants []string, setup ...func(*tentacleRuntime)) (*tentacleRuntime, *consentTestForms, input.Command) { t.Helper() program := os.Getenv("CTHULHU_REMOTE_BINARY") if program == "" { @@ -90,14 +90,18 @@ func remote_command_fixture_grants(t *testing.T, grants []string, setup ...func( return runtime, forms, command } -func next_remote_form(t *testing.T, forms *consentTestForms) consentFormRequest { +func nextRemoteForm(t *testing.T, forms *consentTestForms) consentFormRequest { t.Helper() select { case request := <-forms.requests: if request.ctx.Err() != nil { t.Fatal("form already cancelled") } - if _, err := interaction.NewSession(request.form); err != nil { + if request.core != nil { + if _, err := newCoreSession(*request.core); err != nil { + t.Fatal("invalid core form", err) + } + } else if _, err := tentaclewire.NewSession(request.form); err != nil { t.Fatal("invalid form", err) } return request @@ -107,14 +111,14 @@ func next_remote_form(t *testing.T, forms *consentTestForms) consentFormRequest } } -func select_remote_relay(t *testing.T, forms *consentTestForms, address, role string) consentFormRequest { +func selectRemoteRelay(t *testing.T, forms *consentTestForms, address, role string) consentFormRequest { t.Helper() - selection := next_remote_form(t, forms) + selection := nextRemoteForm(t, forms) if selection.form.Title != "Remote" || selection.form.Elements[0].ID != "cancel" { t.Fatal("missing compact connection form") } - selectionSession, _ := interaction.NewSession(selection.form) - if effect := selectionSession.Handle(interaction.Event{Key: interaction.Enter}); effect.Activated != "cancel" { + selectionSession, _ := tentaclewire.NewSession(selection.form) + if effect := selectionSession.Handle(commonui.Key{Name: "enter"}); effect.Action != "cancel" { t.Fatal("empty entries blocked Cancel") } for _, element := range selection.form.Elements { @@ -123,25 +127,25 @@ func select_remote_relay(t *testing.T, forms *consentTestForms, address, role st } // The only Tentacle checkbox is remembering the host and key; // access is chosen solely in the reader-owned approval form. - if element.Kind == interaction.CheckBox && element.ID != "remember" { + if element.Kind == tentaclewire.CheckBox && element.ID != "remember" { t.Fatal("permissions duplicated") } } - selection.reply <- internalUIResult{Activated: "options", Values: map[string]interaction.Value{"host": {Text: address}, "role": {Selected: role}}} - options := next_remote_form(t, forms) + selection.reply <- tentacleReply("options", map[string]tentaclewire.Value{"host": {Text: address}, "role": {Selected: role}}) + options := nextRemoteForm(t, forms) if options.form.Title != "Remote options" { t.Fatal("missing options") } return options } -func approve_remote_form(t *testing.T, forms *consentTestForms, consent consentFormRequest, role string, extra ...string) consentFormRequest { +func approveRemoteForm(t *testing.T, forms *consentTestForms, consent consentFormRequest, role string, extra ...string) consentFormRequest { t.Helper() - if !strings.Contains(consent.form.Title, "Remote access for remote") { + if consent.core == nil || !strings.Contains(consent.core.Title, "Remote access for remote") { t.Fatal("missing reader approval") } - for _, element := range consent.form.Elements { - if element.Checked { + for _, control := range consentControls(t, consent) { + if control.Checked { t.Fatal("permission preselected") } } @@ -149,19 +153,15 @@ func approve_remote_form(t *testing.T, forms *consentTestForms, consent consentF if role == "controlled" { grant = "output-observe" } - values := map[string]interaction.Value{grant: {Checked: true}} - for _, name := range extra { - values[name] = interaction.Value{Checked: true} - } - consent.reply <- internalUIResult{Activated: "approve", Values: values} - progress := next_remote_form(t, forms) + consent.reply <- consentReply(append([]string{grant}, extra...)...) + progress := nextRemoteForm(t, forms) if progress.form.Title != "Connecting Remote" { t.Fatal("approval did not start connection", progress.form.Title) } return progress } -func remote_consent_listener(t *testing.T) net.Listener { +func remoteConsentListener(t *testing.T) net.Listener { t.Helper() key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { @@ -193,28 +193,28 @@ func remote_consent_listener(t *testing.T) net.Listener { return listener } -func prepare_remote_consent(t *testing.T, forms *consentTestForms, address, role string) consentFormRequest { +func prepareRemoteConsent(t *testing.T, forms *consentTestForms, address, role string) consentFormRequest { t.Helper() - options := select_remote_relay(t, forms, address, role) + options := selectRemoteRelay(t, forms, address, role) options.reply <- internalUIResult{Activated: "inspect-certificate"} - next_remote_form(t, forms) // Cancellable progress. - review := next_remote_form(t, forms) // Poll replaces progress automatically. + nextRemoteForm(t, forms) // Cancellable progress. + review := nextRemoteForm(t, forms) // Poll replaces progress automatically. if review.form.Title != "Review Remote relay certificate" { t.Fatal("inspection did not advance") } review.reply <- internalUIResult{Activated: "trust-once"} - options = next_remote_form(t, forms) - options.reply <- internalUIResult{Activated: "connect", Values: map[string]interaction.Value{"channel-key": {Text: "synthetic-fixture"}}} - next_remote_form(t, forms) // Verified preflight; no lease/key sent. - return next_remote_form(t, forms) + options = nextRemoteForm(t, forms) + options.reply <- tentacleReply("connect", map[string]tentaclewire.Value{"channel-key": {Text: "synthetic-fixture"}}) + nextRemoteForm(t, forms) // Verified preflight; no lease/key sent. + return nextRemoteForm(t, forms) } func TestRemoteConnectionCommandConsentDenialAndPolicyCancellation(t *testing.T) { for _, mode := range []string{"deny", "empty", "lock", "handoff"} { t.Run(mode, func(t *testing.T) { - runtime, forms, command := remote_command_fixture(t) - listener := remote_consent_listener(t) - consent := prepare_remote_consent(t, forms, listener.Addr().String(), "controller") + runtime, forms, command := remoteCommandFixture(t) + listener := remoteConsentListener(t) + consent := prepareRemoteConsent(t, forms, listener.Addr().String(), "controller") switch mode { case "deny": consent.reply <- internalUIResult{Cancelled: true} @@ -233,7 +233,7 @@ func TestRemoteConnectionCommandConsentDenialAndPolicyCancellation(t *testing.T) // The command must recover after a denied/cancelled review, without // keeping an awaiting flag or reviving the previous approval. runtime.Invoke(t.Context(), command) - form := next_remote_form(t, forms) + form := nextRemoteForm(t, forms) if form.form.Title != "Remote" { t.Fatal("stale setup survived cancellation") } @@ -262,10 +262,10 @@ func TestRemoteConnectionCommandCancelsInspectionOnHandoff(t *testing.T) { io.Copy(io.Discard, connection) close(closed) }() - runtime, forms, _ := remote_command_fixture(t) - credentials := select_remote_relay(t, forms, listener.Addr().String(), "controller") + runtime, forms, _ := remoteCommandFixture(t) + credentials := selectRemoteRelay(t, forms, listener.Addr().String(), "controller") credentials.reply <- internalUIResult{Activated: "inspect-certificate"} - inspection := next_remote_form(t, forms) + inspection := nextRemoteForm(t, forms) select { case <-accepted: case <-time.After(5 * time.Second): @@ -415,7 +415,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { var rendered isolatedVoiceUtterance var configure []func(*tentacleRuntime) if test.playback { - speaker, fixture := isolated_voice_fixture(t) + speaker, fixture := isolatedVoiceFixture(t) server = fixture configure = append(configure, func(runtime *tentacleRuntime) { worker := runtime.output.speech @@ -436,14 +436,14 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { var keyLog string if keyboard { grants = append(grants, "keyboard-inject") - helper, log := keyboard_owner_helper(t) + helper, log := keyboardOwnerHelper(t) keyLog = log if ending == "missing-helper" { helper = filepath.Join(t.TempDir(), "absent") } configure = append(configure, func(runtime *tentacleRuntime) { runtime.remoteInputHelper = helper }) } - runtime, forms, shortcut := remote_command_fixture_grants(t, grants, configure...) + runtime, forms, shortcut := remoteCommandFixtureGrants(t, grants, configure...) if role == "controlled" { worker := runtime.output.speech worker.speaker = &observationSpeaker{fakeSpeaker{spoken: make(chan string, 64)}} @@ -476,28 +476,28 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { t.Fatal("Remote fixture session unavailable") } } - credentials := select_remote_relay(t, forms, listener.Addr().String(), role) + credentials := selectRemoteRelay(t, forms, listener.Addr().String(), role) credentials.reply <- internalUIResult{Activated: "inspect-certificate"} - inspection := next_remote_form(t, forms) + inspection := nextRemoteForm(t, forms) select { case <-probed: case <-time.After(5 * time.Second): t.Fatal("certificate probe did not finish") } - inspection = next_remote_form(t, forms) + inspection = nextRemoteForm(t, forms) if inspection.form.Title != "Review Remote relay certificate" { t.Fatal("certificate result was not automatic") } inspection.reply <- internalUIResult{Activated: "trust-once"} - credentials = next_remote_form(t, forms) - credentials.reply <- internalUIResult{Activated: "connect", Values: map[string]interaction.Value{"channel-key": {Text: "synthetic-fixture"}}} - next_remote_form(t, forms) // Verified certificate progress. - consent := next_remote_form(t, forms) + credentials = nextRemoteForm(t, forms) + credentials.reply <- tentacleReply("connect", map[string]tentaclewire.Value{"channel-key": {Text: "synthetic-fixture"}}) + nextRemoteForm(t, forms) // Verified certificate progress. + consent := nextRemoteForm(t, forms) var extra []string if keyboard { extra = append(extra, "keyboard-inject") } - status := approve_remote_form(t, forms, consent, role, extra...) + status := approveRemoteForm(t, forms, consent, role, extra...) select { case <-joined: case <-time.After(5 * time.Second): @@ -515,7 +515,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { } for _, closeMode := range []string{"close", "escape"} { runtime.Invoke(t.Context(), shortcut) - reopened := next_remote_form(t, forms) + reopened := nextRemoteForm(t, forms) if reopened.form.Title != "Remote status" { t.Fatal("status reopening requested new consent") } @@ -546,7 +546,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { } close(speechReady) if ending == "missing-helper" { - remote_stream_wait(t, closed) + remoteStreamWait(t, closed) if _, err := os.Stat(keyLog); !os.IsNotExist(err) { t.Fatal("missing helper unexpectedly delivered input", err) } @@ -560,18 +560,18 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { }) } if ending == "backend-failure" { - remote_stream_wait(t, closed) + remoteStreamWait(t, closed) // Backend failure retires the lease, while the process and // mailbox owner remain usable for an explicit new connection. runtime.Invoke(t.Context(), shortcut) - selection := next_remote_form(t, forms) + selection := nextRemoteForm(t, forms) if selection.form.Title == "Remote status" { // An ended attempt remains inspectable until explicitly // closed, as with ordinary transport failure. selection.reply <- internalUIResult{Activated: "cancel"} waitTentacle(t, func() bool { return len(runtime.resultSlots) == 0 }) runtime.Invoke(t.Context(), shortcut) - selection = next_remote_form(t, forms) + selection = nextRemoteForm(t, forms) } if selection.form.Title != "Remote" { t.Fatal("backend failure retained a connected workflow") @@ -594,11 +594,11 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { } var delivery tentacle.RemoteSpeechDelivery if test.playback { - utterance := server.next_utterance(t) + utterance := server.nextUtterance(t) for utterance.priority == "MESSAGE" { // Returning to desktop produces local status on its ordinary // client. The production Remote voice must stay separate. - utterance = server.next_utterance(t) + utterance = server.nextUtterance(t) } rendered = utterance if utterance.text != remoteText || utterance.language != "fr" || utterance.spelling != "on" || @@ -649,7 +649,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { // peer. Poll status before testing actual output rather than // depending on a scheduling delay or replaying pre-peer output. runtime.Invoke(t.Context(), shortcut) - status = next_remote_form(t, forms) + status = nextRemoteForm(t, forms) deadline := time.Now().Add(5 * time.Second) for { encoded, _ := json.Marshal(status.form) @@ -660,7 +660,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { t.Fatal("peer did not become ready") } status.reply <- internalUIResult{Activated: "refresh"} - status = next_remote_form(t, forms) + status = nextRemoteForm(t, forms) } status.reply <- internalUIResult{Activated: "desktop"} waitTentacle(t, func() bool { return len(runtime.resultSlots) == 0 }) @@ -675,7 +675,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { t.Fatal(err) } } - request := document_observation_request(t, "read-all", review.Result{ + request := documentObservationRequest(t, "read-all", review.Result{ ReadAllContext: t.Context(), ReadAllLines: []atspi.DocumentLine{{Contents: []atspi.DocumentContent{{ Snapshot: atspi.Snapshot{Role: "text"}, Text: "First colour. Second colour.", }}}}, @@ -683,7 +683,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } - request = current_line_observation_request(t, review.Result{CurrentLineBrowse: true, + request = currentLineObservationRequest(t, review.Result{CurrentLineBrowse: true, DocumentCaretText: "Current colour.", DocumentPosition: review.DocumentPosition{Snapshot: atspi.Snapshot{Role: "static"}}, DocumentCaretContext: []atspi.Snapshot{{Role: "static"}, {Role: "paragraph"}, {Role: "document web"}}}) if err := worker.EnqueueAndWait(t.Context(), request); err != nil { @@ -695,7 +695,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { privateLine := atspi.DocumentLine{Contents: []atspi.DocumentContent{{Snapshot: caret, Text: "private joined text"}}, SourceContexts: [][]atspi.Snapshot{{caret}, {{Role: "static"}, {Role: "password text"}}}} for _, kind := range []string{"caret", "read-all", "current-line"} { - request := document_observation_request(t, kind, review.Result{ + request := documentObservationRequest(t, kind, review.Result{ Moved: true, DocumentCaretCommand: review.CaretNextLine, DocumentPosition: review.DocumentPosition{Snapshot: caret}, DocumentCaretText: "private joined text", DocumentCaretContext: []atspi.Snapshot{caret, {Role: "document web"}}, @@ -706,30 +706,30 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { } } for _, private := range []bool{false, true} { - result := native_current_line_result() + result := nativeCurrentLineResult() if private { result.DocumentCaretText = "private native text" result.DocumentCaretContext[1].Role = "password text" } - if err := worker.EnqueueAndWait(t.Context(), current_line_observation_request(t, result)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), currentLineObservationRequest(t, result)); err != nil { t.Fatal(err) } } for _, kind := range []string{"object", "line"} { for _, privacy := range []string{"ordinary", "snapshot-ancestor", "stale"} { - request := review_observation_request(t, kind, review_observation_result(t, kind, privacy)) + request := reviewObservationRequest(t, kind, reviewObservationResult(t, kind, privacy)) if err := worker.EnqueueAndWait(t.Context(), request); err != nil { t.Fatal(err) } } } for _, privacy := range []string{"ordinary", "snapshot-ancestor", "missing", "stale"} { - if err := worker.EnqueueAndWait(t.Context(), where_am_i_observation_request(t, privacy)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), whereAmIObservationRequest(t, privacy)); err != nil { t.Fatal(err) } } for _, privacy := range []string{"ordinary", "ancestor", "changed-text", "failure"} { - if err := worker.EnqueueAndWait(t.Context(), native_where_am_i_request(t, privacy)); err != nil { + if err := worker.EnqueueAndWait(t.Context(), nativeWhereAmIRequest(t, privacy)); err != nil { t.Fatal(err) } } @@ -790,7 +790,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { switch ending { case "disconnect": runtime.Invoke(t.Context(), shortcut) - status = next_remote_form(t, forms) + status = nextRemoteForm(t, forms) if status.form.Title != "Remote status" { t.Fatal("reopening lost the approved connection") } @@ -811,7 +811,7 @@ func TestRemoteConnectionCommandPrivateRelay(t *testing.T) { } waitTentacle(t, func() bool { return len(runtime.resultSlots) == 0 }) if test.playback { - remote_stream_wait(t, voice.closed) + remoteStreamWait(t, voice.closed) server.mutex.Lock() pending := server.connections[rendered.id].pending server.mutex.Unlock() diff --git a/internal/app/tentacle_remote_consent.go b/internal/app/tentacle_remote_consent.go index 2df8478..7b61917 100644 --- a/internal/app/tentacle_remote_consent.go +++ b/internal/app/tentacle_remote_consent.go @@ -8,18 +8,25 @@ import ( "slices" "time" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/tentacle" "git.stormux.org/storm/cthulhu/internal/tentaclewire" + commonui "git.stormux.org/storm/screenreader-common/internalui" ) type localTentacleForms interface { - OpenLocal(context.Context, interaction.Form) (<-chan internalUIResult, error) + OpenLocal(context.Context, tentaclewire.Form) (<-chan internalUIResult, error) } -// authorize_remote reserves a standalone core dialog. Interactive commands use -// authorize_remote_session with their already-reserved slot and exact session. -func (runtime *tentacleRuntime) authorize_remote(ctx context.Context, id, role string, grants []string) (tentaclewire.SessionEvent, error) { +// coreForms opens reader-owned forms; consent passes localOnly. +type coreForms interface { + OpenUI(context.Context, commonui.Form, bool) (<-chan internalUIResult, error) +} + +const consentTab = "consent" + +// authorizeRemote reserves a standalone core dialog. Interactive commands use +// authorizeRemoteSession with their already-reserved slot and exact session. +func (runtime *tentacleRuntime) authorizeRemote(ctx context.Context, id, role string, grants []string) (tentaclewire.SessionEvent, error) { if runtime == nil || runtime.remotePolicy == nil || !tentaclewire.ValidRoleGrants(role, grants) { return tentaclewire.SessionEvent{}, tentacle.ErrPermission } @@ -45,16 +52,16 @@ func (runtime *tentacleRuntime) authorize_remote(ctx context.Context, id, role s return tentaclewire.SessionEvent{}, tentacle.ErrBusy } defer func() { <-runtime.interactionSlots }() - return runtime.authorize_remote_session(ctx, target, role, grants) + return runtime.authorizeRemoteSession(ctx, target, role, grants) } // Caller owns interactionSlots. A child request may open a dialog, but only // local capture and the core-issued ticket can authorize the requesting session. -func (runtime *tentacleRuntime) authorize_remote_session(ctx context.Context, target *tentacle.Session, role string, grants []string) (tentaclewire.SessionEvent, error) { +func (runtime *tentacleRuntime) authorizeRemoteSession(ctx context.Context, target *tentacle.Session, role string, grants []string) (tentaclewire.SessionEvent, error) { if runtime == nil || runtime.remotePolicy == nil || target == nil || !tentaclewire.ValidRoleGrants(role, grants) { return tentaclewire.SessionEvent{}, tentacle.ErrPermission } - forms, ok := runtime.forms.(localTentacleForms) + forms, ok := runtime.forms.(coreForms) if !ok { return tentaclewire.SessionEvent{}, tentacle.ErrUnavailable } @@ -82,8 +89,8 @@ func (runtime *tentacleRuntime) authorize_remote_session(ctx context.Context, ta defer stopPolicy() stopSession := context.AfterFunc(target.OutputContext(), cancel) defer stopSession() - form := remote_consent_form(target.TentacleID(), role, grants) - replies, err := forms.OpenLocal(ctx, form) + form := remoteConsentForm(target.TentacleID(), role, grants) + replies, err := forms.OpenUI(ctx, form, true) if err != nil { return tentaclewire.SessionEvent{}, err } @@ -94,7 +101,7 @@ func (runtime *tentacleRuntime) authorize_remote_session(ctx context.Context, ta } var selected []string for _, grant := range grants { - if reply.Values[grant].Checked { + if reply.Controls[consentTab+"."+grant].Checked { selected = append(selected, grant) } } @@ -107,13 +114,13 @@ func (runtime *tentacleRuntime) authorize_remote_session(ctx context.Context, ta } } -func remote_consent_form(id, role string, grants []string) interaction.Form { +func remoteConsentForm(id, role string, grants []string) commonui.Form { roleText := "control another computer" if role == "controlled" { roleText = "allow a helper to access this computer" } - form := interaction.Form{Title: "Remote access for " + id + ": " + roleText + ". The relay can read session contents. Select access for this session.", - Elements: []interaction.Element{{ID: "cancel", Label: "Cancel", Kind: interaction.Button}}} + title := "Remote access for " + id + ": " + roleText + ". The relay can read session contents. Select access for this session." + controls := []commonui.Control{{ID: "cancel", Label: "Cancel", Kind: commonui.Button, Action: "cancel", SkipValidation: true}} labels := map[string]string{ "output-observe": "Share speech with the helper", "remote-present": "Hear the other computer", @@ -123,13 +130,13 @@ func remote_consent_form(id, role string, grants []string) interaction.Form { "braille-stream": "Braille display and routing", } for _, grant := range grants { - form.Elements = append(form.Elements, interaction.Element{ID: grant, Label: labels[grant], Kind: interaction.CheckBox}) + controls = append(controls, commonui.Control{ID: grant, Label: labels[grant], Kind: commonui.CheckBox}) } - form.Elements = append(form.Elements, interaction.Element{ID: "approve", Label: "Allow selected access and connect", Kind: interaction.Button}) - return form + controls = append(controls, commonui.Control{ID: "approve", Label: "Allow selected access and connect", Kind: commonui.Button, Action: "approve"}) + return commonui.Form{Type: commonui.FlatForm, Title: title, Detailed: true, Tabs: []commonui.Tab{{ID: consentTab, Label: "Remote access", Controls: controls}}} } -func (runtime *tentacleRuntime) authorize_remote_request(ctx context.Context, target *tentacle.Session, request tentaclewire.RemoteRequest) (tentaclewire.SessionEvent, error) { +func (runtime *tentacleRuntime) authorizeRemoteRequest(ctx context.Context, target *tentacle.Session, request tentaclewire.RemoteRequest) (tentaclewire.SessionEvent, error) { if target == nil || !tentaclewire.ValidRemoteRequest(request) { return tentaclewire.SessionEvent{}, tentacle.ErrPermission } @@ -140,5 +147,5 @@ func (runtime *tentacleRuntime) authorize_remote_request(ctx context.Context, ta grants = append(grants, grant) } } - return runtime.authorize_remote_session(ctx, target, request.Role, grants) + return runtime.authorizeRemoteSession(ctx, target, request.Role, grants) } diff --git a/internal/app/tentacle_remote_consent_test.go b/internal/app/tentacle_remote_consent_test.go index f5d1f2f..5dfae88 100644 --- a/internal/app/tentacle_remote_consent_test.go +++ b/internal/app/tentacle_remote_consent_test.go @@ -11,25 +11,39 @@ import ( "testing" "time" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/tentacle" "git.stormux.org/storm/cthulhu/internal/tentaclewire" + commonui "git.stormux.org/storm/screenreader-common/internalui" ) +// consentFormRequest is a Tentacle form, or a reader-owned core form when +// core is set. type consentFormRequest struct { ctx context.Context - form interaction.Form + form tentaclewire.Form + core *commonui.Form reply chan internalUIResult } type consentTestForms struct{ requests chan consentFormRequest } -func (forms *consentTestForms) Open(context.Context, interaction.Form) (<-chan internalUIResult, error) { +func (forms *consentTestForms) Open(context.Context, tentaclewire.Form) (<-chan internalUIResult, error) { return nil, errors.New("ordinary form used for consent") } func (forms *consentTestForms) Notice(context.Context, tentaclewire.Presentation) {} -func (forms *consentTestForms) OpenLocal(ctx context.Context, form interaction.Form) (<-chan internalUIResult, error) { +func (forms *consentTestForms) OpenLocal(ctx context.Context, form tentaclewire.Form) (<-chan internalUIResult, error) { + return forms.open(consentFormRequest{ctx: ctx, form: form}) +} +func (forms *consentTestForms) OpenUI(ctx context.Context, form commonui.Form, localOnly bool) (<-chan internalUIResult, error) { + if !localOnly { + return nil, errors.New("ordinary form used for consent") + } + return forms.open(consentFormRequest{ctx: ctx, core: &form}) +} +func (forms *consentTestForms) open(request consentFormRequest) (<-chan internalUIResult, error) { + ctx := request.ctx reply := make(chan internalUIResult, 1) - forms.requests <- consentFormRequest{ctx, form, reply} + request.reply = reply + forms.requests <- request output := make(chan internalUIResult, 1) go func() { select { @@ -42,7 +56,7 @@ func (forms *consentTestForms) OpenLocal(ctx context.Context, form interaction.F return output, nil } -func consent_runtime_fixture(t *testing.T) (*tentacleRuntime, *tentacle.Session, *consentTestForms, *focusGate) { +func consentRuntimeFixture(t *testing.T) (*tentacleRuntime, *tentacle.Session, *consentTestForms, *focusGate) { t.Helper() executable, err := os.Executable() if err != nil { @@ -83,12 +97,12 @@ func consent_runtime_fixture(t *testing.T) (*tentacleRuntime, *tentacle.Session, func TestRemoteConsentFormDefaultsAndRevocation(t *testing.T) { for _, action := range []string{"approve", "cancel", "empty", "lock", "handoff", "revoke", "disable"} { t.Run(action, func(t *testing.T) { - runtime, session, forms, gate := consent_runtime_fixture(t) + runtime, session, forms, gate := consentRuntimeFixture(t) ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() result := make(chan error, 1) go func() { - _, err := runtime.authorize_remote(ctx, "consent-probe", "controlled", []string{"output-observe", "clipboard-exchange"}) + _, err := runtime.authorizeRemote(ctx, "consent-probe", "controlled", []string{"output-observe", "clipboard-exchange"}) result <- err }() var request consentFormRequest @@ -97,23 +111,21 @@ func TestRemoteConsentFormDefaultsAndRevocation(t *testing.T) { case <-ctx.Done(): t.Fatal("no consent form") } - if _, err := interaction.NewSession(request.form); err != nil { - t.Fatal("invalid consent form", err) - } - if request.form.Elements[0].ID != "cancel" { + controls := consentControls(t, request) + if controls[0].ID != "cancel" { t.Fatal("approval was default action") } - for _, element := range request.form.Elements { - if element.Checked { + for _, control := range controls { + if control.Checked { t.Fatal("permission preselected") } } - reply := internalUIResult{Activated: "approve", Values: map[string]interaction.Value{"output-observe": {Checked: true}}} + reply := consentReply("output-observe") switch action { case "cancel": reply.Activated = "cancel" case "empty": - reply.Values = nil + reply.Controls = nil case "lock": gate.SetLocked(true, nil, nil, nil, nil, &brailleWorker{}) gate.SetLocked(false, nil, nil, nil, nil, &brailleWorker{}) @@ -173,9 +185,9 @@ func TestRemoteConsentFormDefaultsAndRevocation(t *testing.T) { } func TestRemoteGrantedTentacleUsesLocalForms(t *testing.T) { - runtime, session, forms, _ := consent_runtime_fixture(t) - form := interaction.Form{Title: "Certificate review", Elements: []interaction.Element{{ID: "cancel", Label: "Cancel", Kind: interaction.Button}}} - if _, err := runtime.open_tentacle_form(t.Context(), tentacleCommand{session: session}, form); err != nil { + runtime, session, forms, _ := consentRuntimeFixture(t) + form := tentaclewire.Form{Title: "Certificate review", Elements: []tentaclewire.Element{{ID: "cancel", Label: "Cancel", Kind: tentaclewire.Button}}} + if _, err := runtime.openTentacleForm(t.Context(), tentacleCommand{session: session}, form); err != nil { t.Fatal(err) } select { @@ -188,12 +200,13 @@ func TestRemoteGrantedTentacleUsesLocalForms(t *testing.T) { type ordinaryOnlyForms struct{ tentacleForms } func TestRemoteConsentCannotFallBackToOrdinaryForms(t *testing.T) { - runtime, session, _, _ := consent_runtime_fixture(t) + runtime, session, _, _ := consentRuntimeFixture(t) runtime.forms = ordinaryOnlyForms{runtime.forms} - if _, err := runtime.authorize_remote(t.Context(), "consent-probe", "controlled", []string{"output-observe"}); err == nil { + if _, err := runtime.authorizeRemote(t.Context(), "consent-probe", "controlled", []string{"output-observe"}); err == nil { t.Fatal("consent fell back to ordinary input") } - if _, err := runtime.open_tentacle_form(t.Context(), tentacleCommand{session: session}, remote_consent_form("consent-probe", "controlled", []string{"output-observe"})); err == nil { + form := tentaclewire.Form{Title: "Certificate review", Elements: []tentaclewire.Element{{ID: "cancel", Label: "Cancel", Kind: tentaclewire.Button}}} + if _, err := runtime.openTentacleForm(t.Context(), tentacleCommand{session: session}, form); err == nil { t.Fatal("sensitive form fell back to ordinary input") } } @@ -210,22 +223,22 @@ func TestRemotePolicyAttachedToRuntimeManagers(t *testing.T) { } func TestRemoteOptionalGrantsRespectInstallationAndLocalSelection(t *testing.T) { - runtime, session, forms, _ := consent_runtime_fixture(t) + runtime, session, forms, _ := consentRuntimeFixture(t) type result struct { action tentaclewire.SessionEvent err error } completed := make(chan result, 1) go func() { - action, err := runtime.authorize_remote_request(t.Context(), session, tentaclewire.RemoteRequest{Role: "controlled", Grants: []string{"output-observe"}, OptionalGrants: []string{"clipboard-exchange", "keyboard-inject", "braille-stream"}}) + action, err := runtime.authorizeRemoteRequest(t.Context(), session, tentaclewire.RemoteRequest{Role: "controlled", Grants: []string{"output-observe"}, OptionalGrants: []string{"clipboard-exchange", "keyboard-inject", "braille-stream"}}) completed <- result{action, err} }() - request := next_remote_form(t, forms) + request := nextRemoteForm(t, forms) offered := map[string]bool{} - for _, element := range request.form.Elements { - if element.Kind == interaction.CheckBox { - offered[element.ID] = true - if element.Checked { + for _, control := range consentControls(t, request) { + if control.Kind == commonui.CheckBox { + offered[control.ID] = true + if control.Checked { t.Fatal("grant preselected") } } @@ -233,7 +246,7 @@ func TestRemoteOptionalGrantsRespectInstallationAndLocalSelection(t *testing.T) if !offered["output-observe"] || !offered["clipboard-exchange"] || offered["keyboard-inject"] || offered["braille-stream"] { t.Fatal("uninstalled access offered", offered) } - request.reply <- internalUIResult{Activated: "approve", Values: map[string]interaction.Value{"output-observe": {Checked: true}, "keyboard-inject": {Checked: true}}} + request.reply <- consentReply("output-observe", "keyboard-inject") select { case value := <-completed: if value.err != nil || len(value.action.Grants) != 1 || value.action.Grants[0] != "output-observe" { @@ -243,3 +256,37 @@ func TestRemoteOptionalGrantsRespectInstallationAndLocalSelection(t *testing.T) t.Fatal("approval did not finish") } } + +// consentControls returns a validated reader-owned consent form's controls. +func consentControls(t *testing.T, request consentFormRequest) []commonui.Control { + t.Helper() + if request.core == nil { + t.Fatal("consent used a Tentacle form") + } + if _, err := newCoreSession(*request.core); err != nil { + t.Fatal("invalid consent form", err) + } + return request.core.Tabs[0].Controls +} + +// consentReply approves the consent form with the given grants checked. +func consentReply(grants ...string) internalUIResult { + controls := map[string]commonui.Control{} + for _, grant := range grants { + controls[consentTab+"."+grant] = commonui.Control{ID: grant, Kind: commonui.CheckBox, Checked: true} + } + return internalUIResult{Activated: "approve", Controls: controls} +} + +// tentacleReply submits a Tentacle form with the given wire values. +func tentacleReply(activated string, values map[string]tentaclewire.Value) internalUIResult { + controls := map[string]commonui.Control{} + for id, value := range values { + control := commonui.Control{ID: id, Kind: commonui.Entry, Text: value.Text, Checked: value.Checked} + if value.Selected != "" { + control = commonui.Control{ID: id, Kind: commonui.List, Choices: []commonui.Choice{{ID: value.Selected, Label: value.Selected}}} + } + controls[tentaclewire.FormTab+"."+id] = control + } + return internalUIResult{Activated: activated, Controls: controls} +} diff --git a/internal/app/tentacle_remote_keyboard.go b/internal/app/tentacle_remote_keyboard.go index a6ef013..d71e45d 100644 --- a/internal/app/tentacle_remote_keyboard.go +++ b/internal/app/tentacle_remote_keyboard.go @@ -13,14 +13,14 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) -// run_remote_keyboard is the incoming-key mailbox owner. start_remote_keyboard +// runRemoteKeyboard is the incoming-key mailbox owner. startRemoteKeyboard // is its production caller; it retains one supervisor across sessions, // including its permanent uncertainty latch, and provides native focus/security // policy without native I/O. // Policy invalidation must cancel ctx or the lease, including while idle. This // does not establish physical collision safety or trusted command routing. // Ending the owner disables its session, leaving no accepting orphan mailbox. -func run_remote_keyboard(ctx context.Context, session *tentacle.Session, supervisor *remoteinput.Supervisor, +func runRemoteKeyboard(ctx context.Context, session *tentacle.Session, supervisor *remoteinput.Supervisor, allow func(tentacle.RemoteKeyDelivery) bool) (result error) { if ctx == nil || session == nil || supervisor == nil || allow == nil { return remoteinput.ErrUnavailable diff --git a/internal/app/tentacle_remote_keyboard_native_test.go b/internal/app/tentacle_remote_keyboard_native_test.go index 53d9bd6..cde18a0 100644 --- a/internal/app/tentacle_remote_keyboard_native_test.go +++ b/internal/app/tentacle_remote_keyboard_native_test.go @@ -23,7 +23,7 @@ func TestNativeRemoteKeyboardOwnerProcess(t *testing.T) { if os.Getenv("CTHULHU_NATIVE_REMOTE_KEYS") != "1" || ready == "" { t.Skip("requires private native_remote_keys.py crash supervisor") } - f := keyboard_owner_fixture(t, func(f *keyboardOwnerFixture) { + f := newKeyboardOwnerFixture(t, func(f *keyboardOwnerFixture) { var err error f.supervisor, err = remoteinput.NewSupervisor(os.Getenv("CTHULHU_REMOTE_INPUT_HELPER")) if err != nil { @@ -33,7 +33,7 @@ func TestNativeRemoteKeyboardOwnerProcess(t *testing.T) { lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "Shift_L", true) f.key(t, lease, 2, "Control_R", true) - f.wait(t, func() bool { return keyboard_owner_native_state(t) == "110" }) + f.wait(t, func() bool { return keyboardOwnerNativeState(t) == "110" }) if err := os.WriteFile(ready, []byte("ready\n"), 0600); err != nil { t.Fatal(err) } @@ -58,12 +58,12 @@ func TestNativeRemoteKeyboardOwnerProcess(t *testing.T) { if _, err := f.supervisor.Start(t.Context(), lease.Epoch+1); !errors.Is(err, remoteinput.ErrUnavailable) { t.Fatal("resumed owner replaced an unconfirmed helper", err) } - if state := keyboard_owner_native_state(t); state != "000" { + if state := keyboardOwnerNativeState(t); state != "000" { t.Fatal("resumed owner restored retired key state", state) } } -func keyboard_owner_native_state(t *testing.T) string { +func keyboardOwnerNativeState(t *testing.T) string { t.Helper() // Query from a separate connection. No key injection or keymap changes // occur in this probe; the actual source-built helper owns all effects. @@ -101,26 +101,26 @@ func TestNativeRemoteKeyboardOwner(t *testing.T) { } for _, reason := range []string{"policy", "disconnect", "disable", "owner-stop", "replace"} { t.Run(reason, func(t *testing.T) { - f := keyboard_owner_fixture(t, func(f *keyboardOwnerFixture) { + f := newKeyboardOwnerFixture(t, func(f *keyboardOwnerFixture) { var err error f.supervisor, err = remoteinput.NewSupervisor(os.Getenv("CTHULHU_REMOTE_INPUT_HELPER")) if err != nil { t.Fatal(err) } }) - if state := keyboard_owner_native_state(t); state != "000" { + if state := keyboardOwnerNativeState(t); state != "000" { t.Fatal("private server already holds test keys", state) } lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "Shift_L", true) f.key(t, lease, 2, "Control_R", true) - f.wait(t, func() bool { return keyboard_owner_native_state(t) == "110" }) + f.wait(t, func() bool { return keyboardOwnerNativeState(t) == "110" }) switch reason { case "policy": f.policy.SetAvailable(false) f.policy.SetAvailable(true) case "disconnect": - keyboard_owner_invoke(t, f.session, "rpc", map[string]any{"Method": "remote.close", "Params": map[string]any{"lease": lease.Lease, "epoch": lease.Epoch, "sequence": 3}}) + keyboardOwnerInvoke(t, f.session, "rpc", map[string]any{"Method": "remote.close", "Params": map[string]any{"lease": lease.Lease, "epoch": lease.Epoch, "sequence": 3}}) case "disable": f.session.Disable() case "owner-stop": @@ -129,10 +129,10 @@ func TestNativeRemoteKeyboardOwner(t *testing.T) { fresh := f.open(t, "keyboard-inject") f.key(t, fresh, 1, "a", true) // Fresh input cannot overtake old native releases/process exit. - f.wait(t, func() bool { return keyboard_owner_native_state(t) == "001" }) + f.wait(t, func() bool { return keyboardOwnerNativeState(t) == "001" }) f.session.RevokeRemote() } - f.wait(t, func() bool { return keyboard_owner_native_state(t) == "000" }) + f.wait(t, func() bool { return keyboardOwnerNativeState(t) == "000" }) }) } } diff --git a/internal/app/tentacle_remote_keyboard_owner.go b/internal/app/tentacle_remote_keyboard_owner.go index d64c9cb..89f4f44 100644 --- a/internal/app/tentacle_remote_keyboard_owner.go +++ b/internal/app/tentacle_remote_keyboard_owner.go @@ -17,11 +17,11 @@ import ( const remoteInputHelperName = "cthulhu-input-helper" -// remote_input_supervisor returns the one Supervisor retained for the reader +// remoteInputSupervisor returns the one Supervisor retained for the reader // lifetime, so its permanent uncertainty latch survives session replacement. // A missing helper leaves keyboard injection unavailable rather than failing // reader or Tentacle startup. -func (runtime *tentacleRuntime) remote_input_supervisor() *remoteinput.Supervisor { +func (runtime *tentacleRuntime) remoteInputSupervisor() *remoteinput.Supervisor { runtime.mutex.Lock() defer runtime.mutex.Unlock() if runtime.remoteInput != nil || runtime.remoteInputChecked { @@ -49,13 +49,13 @@ func (runtime *tentacleRuntime) remote_input_supervisor() *remoteinput.Superviso return supervisor } -// start_remote_keyboard attaches the production incoming-key owner for a +// startRemoteKeyboard attaches the production incoming-key owner for a // session installed with keyboard-inject. Like speech, the mailbox exists // before the child becomes active; a session without the grant or a reader // without the helper keeps remote.key owner-unavailable. Delivery-time policy // rechecks lock, handoff suspension and internal reader UI, in addition to the // worker's lease, grant and deadline checks. -func (runtime *tentacleRuntime) start_remote_keyboard(ctx context.Context, session *tentacle.Session) <-chan struct{} { +func (runtime *tentacleRuntime) startRemoteKeyboard(ctx context.Context, session *tentacle.Session) <-chan struct{} { done := make(chan struct{}) owner := runtime.output if owner == nil || owner.gate == nil || runtime.remotePolicy == nil || @@ -63,7 +63,7 @@ func (runtime *tentacleRuntime) start_remote_keyboard(ctx context.Context, sessi close(done) return done } - supervisor := runtime.remote_input_supervisor() + supervisor := runtime.remoteInputSupervisor() if supervisor == nil { close(done) return done @@ -75,7 +75,7 @@ func (runtime *tentacleRuntime) start_remote_keyboard(ctx context.Context, sessi } go func() { defer close(done) - err := run_remote_keyboard(ctx, session, supervisor, allow) + err := runRemoteKeyboard(ctx, session, supervisor, allow) if err == nil || ctx.Err() != nil { return } diff --git a/internal/app/tentacle_remote_keyboard_owner_test.go b/internal/app/tentacle_remote_keyboard_owner_test.go index 4b9b4fc..5d94fef 100644 --- a/internal/app/tentacle_remote_keyboard_owner_test.go +++ b/internal/app/tentacle_remote_keyboard_owner_test.go @@ -19,12 +19,12 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) -func keyboard_attach_runtime(policy *tentacle.RemotePolicy, helper string) *tentacleRuntime { +func keyboardAttachRuntime(policy *tentacle.RemotePolicy, helper string) *tentacleRuntime { return &tentacleRuntime{logger: slog.New(slog.DiscardHandler), remotePolicy: policy, remoteInputHelper: helper, output: &tentacleOutput{gate: &focusGate{}}, announcements: make(chan string, 1)} } -func keyboard_attach_key(t *testing.T, session *tentacle.Session, lease tentaclewire.RemoteLease, sequence uint64, name string, pressed bool) error { +func keyboardAttachKey(t *testing.T, session *tentacle.Session, lease tentaclewire.RemoteLease, sequence uint64, name string, pressed bool) error { t.Helper() ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() @@ -43,7 +43,7 @@ func keyboard_attach_key(t *testing.T, session *tentacle.Session, lease tentacle } } -func keyboard_attach_open(t *testing.T, session *tentacle.Session) tentaclewire.RemoteLease { +func keyboardAttachOpen(t *testing.T, session *tentacle.Session) tentaclewire.RemoteLease { t.Helper() approval, err := session.BeginRemoteApproval("controlled", []string{"keyboard-inject"}) if err != nil { @@ -53,7 +53,7 @@ func keyboard_attach_open(t *testing.T, session *tentacle.Session) tentaclewire. t.Fatal(err) } var lease tentaclewire.RemoteLease - if json.Unmarshal(keyboard_owner_invoke(t, session, "open", nil), &lease) != nil || lease.Epoch == 0 { + if json.Unmarshal(keyboardOwnerInvoke(t, session, "open", nil), &lease) != nil || lease.Epoch == 0 { t.Fatal("keyboard peer failed to open lease") } return lease @@ -61,11 +61,11 @@ func keyboard_attach_open(t *testing.T, session *tentacle.Session) tentaclewire. func TestRemoteKeyboardProductionAttachDeliversAndRetires(t *testing.T) { policy := tentacle.NewRemotePolicy() - program, log := keyboard_owner_helper(t) - session := keyboard_owner_session(t, policy, []string{"keyboard-inject", "output-observe"}) - runtime := keyboard_attach_runtime(policy, program) + program, log := keyboardOwnerHelper(t) + session := keyboardOwnerSession(t, policy, []string{"keyboard-inject", "output-observe"}) + runtime := keyboardAttachRuntime(policy, program) ctx, cancel := context.WithCancel(t.Context()) - done := runtime.start_remote_keyboard(ctx, session) + done := runtime.startRemoteKeyboard(ctx, session) t.Cleanup(func() { cancel() select { @@ -74,11 +74,11 @@ func TestRemoteKeyboardProductionAttachDeliversAndRetires(t *testing.T) { t.Error("production keyboard owner did not join") } }) - lease := keyboard_attach_open(t, session) - if err := keyboard_attach_key(t, session, lease, 1, "a", true); err != nil { + lease := keyboardAttachOpen(t, session) + if err := keyboardAttachKey(t, session, lease, 1, "a", true); err != nil { t.Fatal(err) } - if err := keyboard_attach_key(t, session, lease, 2, "a", false); err != nil { + if err := keyboardAttachKey(t, session, lease, 2, "a", false); err != nil { t.Fatal(err) } f := &keyboardOwnerFixture{log: log} @@ -88,22 +88,22 @@ func TestRemoteKeyboardProductionAttachDeliversAndRetires(t *testing.T) { policy.SetAvailable(false) f.wait(t, func() bool { return strings.Contains(f.effects(), prefix+"cleanup\n") }) policy.SetAvailable(true) - if runtime.remote_input_supervisor() != runtime.remoteInput || runtime.remoteInput == nil { + if runtime.remoteInputSupervisor() != runtime.remoteInput || runtime.remoteInput == nil { t.Fatal("supervisor was not retained for the reader lifetime") } } func TestRemoteKeyboardProductionAttachRechecksReaderUI(t *testing.T) { policy := tentacle.NewRemotePolicy() - program, log := keyboard_owner_helper(t) - session := keyboard_owner_session(t, policy, []string{"keyboard-inject"}) - runtime := keyboard_attach_runtime(policy, program) + program, log := keyboardOwnerHelper(t) + session := keyboardOwnerSession(t, policy, []string{"keyboard-inject"}) + runtime := keyboardAttachRuntime(policy, program) runtime.output.gate.suspended.Store(true) // XTerm handoff. ctx, cancel := context.WithCancel(t.Context()) - done := runtime.start_remote_keyboard(ctx, session) + done := runtime.startRemoteKeyboard(ctx, session) defer func() { cancel(); <-done }() - lease := keyboard_attach_open(t, session) - _ = keyboard_attach_key(t, session, lease, 1, "a", true) + lease := keyboardAttachOpen(t, session) + _ = keyboardAttachKey(t, session, lease, 1, "a", true) deadline := time.Now().Add(5 * time.Second) for { if _, err := session.RemoteContext(lease, "keyboard-inject"); err != nil { @@ -122,7 +122,7 @@ func TestRemoteKeyboardProductionAttachRechecksReaderUI(t *testing.T) { func TestRemoteKeyboardProductionAttachRequiresGrantAndHelper(t *testing.T) { policy := tentacle.NewRemotePolicy() - program, _ := keyboard_owner_helper(t) + program, _ := keyboardOwnerHelper(t) for name, test := range map[string]struct { grants []string helper string @@ -131,17 +131,17 @@ func TestRemoteKeyboardProductionAttachRequiresGrantAndHelper(t *testing.T) { "missing helper": {[]string{"keyboard-inject"}, filepath.Join(t.TempDir(), "absent")}, } { t.Run(name, func(t *testing.T) { - session := keyboard_owner_session(t, policy, test.grants) - runtime := keyboard_attach_runtime(policy, test.helper) - done := runtime.start_remote_keyboard(t.Context(), session) + session := keyboardOwnerSession(t, policy, test.grants) + runtime := keyboardAttachRuntime(policy, test.helper) + done := runtime.startRemoteKeyboard(t.Context(), session) select { case <-done: case <-time.After(time.Second): t.Fatal("unavailable keyboard owner did not finish immediately") } if name == "missing helper" { - lease := keyboard_attach_open(t, session) - err := keyboard_attach_key(t, session, lease, 1, "a", true) + lease := keyboardAttachOpen(t, session) + err := keyboardAttachKey(t, session, lease, 1, "a", true) if err == nil || errors.Is(err, context.DeadlineExceeded) { t.Fatalf("missing helper accepted a key: %v", err) } diff --git a/internal/app/tentacle_remote_keyboard_test.go b/internal/app/tentacle_remote_keyboard_test.go index 619e140..cd8d054 100644 --- a/internal/app/tentacle_remote_keyboard_test.go +++ b/internal/app/tentacle_remote_keyboard_test.go @@ -86,7 +86,7 @@ func (target keyboardOwnerTestTarget) record(event string) { } } -func keyboard_owner_test_gate(name string) { +func keyboardOwnerTestGate(name string) { if path := os.Getenv(name); path != "" { for { if _, err := os.Stat(path); err == nil { @@ -99,7 +99,7 @@ func keyboard_owner_test_gate(name string) { func (target keyboardOwnerTestTarget) Apply(name string, pressed bool) error { target.record(name + " " + strconv.FormatBool(pressed)) - keyboard_owner_test_gate("CTHULHU_KEY_OWNER_APPLY_GATE") + keyboardOwnerTestGate("CTHULHU_KEY_OWNER_APPLY_GATE") return nil } @@ -130,7 +130,7 @@ func TestRemoteKeyboardHelper(t *testing.T) { } target := keyboardOwnerTestTarget{epoch} target.record("starting") - keyboard_owner_test_gate("CTHULHU_KEY_OWNER_READY_GATE") + keyboardOwnerTestGate("CTHULHU_KEY_OWNER_READY_GATE") if remoteinput.Run(context.Background(), epoch, control, lifetime, output, target) != nil { os.Exit(1) } @@ -147,10 +147,10 @@ type keyboardOwnerFixture struct { log string } -// keyboard_owner_helper writes the wrapper the real Supervisor launches. The +// keyboardOwnerHelper writes the wrapper the real Supervisor launches. The // wrapper only adapts test-binary arguments; the Supervisor still owns launch, // private pipes, heartbeats, ACK validation and process reaping. -func keyboard_owner_helper(t *testing.T) (program, log string) { +func keyboardOwnerHelper(t *testing.T) (program, log string) { t.Helper() executable, err := os.Executable() if err != nil { @@ -167,7 +167,7 @@ func keyboard_owner_helper(t *testing.T) (program, log string) { return program, log } -func keyboard_owner_session(t *testing.T, policy *tentacle.RemotePolicy, grants []string) *tentacle.Session { +func keyboardOwnerSession(t *testing.T, policy *tentacle.RemotePolicy, grants []string) *tentacle.Session { t.Helper() executable, err := os.Executable() if err != nil { @@ -202,18 +202,18 @@ func keyboard_owner_session(t *testing.T, policy *tentacle.RemotePolicy, grants return session } -func keyboard_owner_fixture(t *testing.T, configure ...func(*keyboardOwnerFixture)) *keyboardOwnerFixture { +func newKeyboardOwnerFixture(t *testing.T, configure ...func(*keyboardOwnerFixture)) *keyboardOwnerFixture { t.Helper() f := &keyboardOwnerFixture{result: make(chan error, 1), policy: tentacle.NewRemotePolicy()} f.allowed.Store(true) - program, log := keyboard_owner_helper(t) + program, log := keyboardOwnerHelper(t) f.log = log var err error f.supervisor, err = remoteinput.NewSupervisor(program) if err != nil { t.Fatal(err) } - f.session = keyboard_owner_session(t, f.policy, []string{"keyboard-inject", "output-observe"}) + f.session = keyboardOwnerSession(t, f.policy, []string{"keyboard-inject", "output-observe"}) for _, setup := range configure { setup(f) } @@ -223,7 +223,7 @@ func keyboard_owner_fixture(t *testing.T, configure ...func(*keyboardOwnerFixtur // keyboard service availability. This call grants no consent. f.session.EnableRemoteKeys() go func() { - f.result <- run_remote_keyboard(ctx, f.session, f.supervisor, func(tentacle.RemoteKeyDelivery) bool { return f.allowed.Load() }) + f.result <- runRemoteKeyboard(ctx, f.session, f.supervisor, func(tentacle.RemoteKeyDelivery) bool { return f.allowed.Load() }) }() t.Cleanup(func() { // Unblock only these synthetic targets if a test fails before releasing @@ -243,7 +243,7 @@ func keyboard_owner_fixture(t *testing.T, configure ...func(*keyboardOwnerFixtur return f } -func keyboard_owner_invoke(t *testing.T, session *tentacle.Session, command string, params any) json.RawMessage { +func keyboardOwnerInvoke(t *testing.T, session *tentacle.Session, command string, params any) json.RawMessage { t.Helper() ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() @@ -274,7 +274,7 @@ func (f *keyboardOwnerFixture) open(t *testing.T, grant string) tentaclewire.Rem t.Fatal(err) } var lease tentaclewire.RemoteLease - if json.Unmarshal(keyboard_owner_invoke(t, f.session, "open", nil), &lease) != nil || lease.Epoch == 0 { + if json.Unmarshal(keyboardOwnerInvoke(t, f.session, "open", nil), &lease) != nil || lease.Epoch == 0 { t.Fatal("keyboard peer failed to open lease") } return lease @@ -283,7 +283,7 @@ func (f *keyboardOwnerFixture) open(t *testing.T, grant string) tentaclewire.Rem func (f *keyboardOwnerFixture) key(t *testing.T, lease tentaclewire.RemoteLease, sequence uint64, name string, pressed bool) { t.Helper() request := tentaclewire.RemoteKeyRequest{RemoteOperation: tentaclewire.RemoteOperation{Lease: lease.Lease, Epoch: lease.Epoch, Sequence: sequence}, Key: tentaclewire.RemoteKey{Name: name, Pressed: pressed}} - keyboard_owner_invoke(t, f.session, "rpc", map[string]any{"Method": "remote.key", "Params": request}) + keyboardOwnerInvoke(t, f.session, "rpc", map[string]any{"Method": "remote.key", "Params": request}) } func (f *keyboardOwnerFixture) effects() string { @@ -307,7 +307,7 @@ func (f *keyboardOwnerFixture) wait(t *testing.T, predicate func() bool) { } func TestRemoteKeyboardOwnerOrdersKeysAndReplacementCleanup(t *testing.T) { - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) first := f.open(t, "keyboard-inject") for index, pressed := range []bool{true, true, false} { f.key(t, first, uint64(index+1), "Shift_L", pressed) @@ -333,7 +333,7 @@ func TestRemoteKeyboardOwnerOrdersKeysAndReplacementCleanup(t *testing.T) { func TestRemoteKeyboardOwnerRechecksPolicyAfterStartup(t *testing.T) { gate := filepath.Join(t.TempDir(), "ready") t.Setenv("CTHULHU_KEY_OWNER_READY_GATE", gate) - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "a", true) f.wait(t, func() bool { return strings.Contains(f.effects(), "starting\n") }) @@ -355,7 +355,7 @@ func TestRemoteKeyboardOwnerRechecksPolicyAfterStartup(t *testing.T) { } func TestRemoteKeyboardOwnerDeniedWorkDoesNotLaunchHelper(t *testing.T) { - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) f.allowed.Store(false) lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "a", true) @@ -368,7 +368,7 @@ func TestRemoteKeyboardOwnerDeniedWorkDoesNotLaunchHelper(t *testing.T) { func TestRemoteKeyboardOwnerCancelledStartupAllowsFreshLease(t *testing.T) { gate := filepath.Join(t.TempDir(), "ready") t.Setenv("CTHULHU_KEY_OWNER_READY_GATE", gate) - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) old := f.open(t, "keyboard-inject") f.key(t, old, 1, "a", true) f.wait(t, func() bool { return strings.Contains(f.effects(), "starting\n") }) @@ -387,7 +387,7 @@ func TestRemoteKeyboardOwnerCancelledStartupAllowsFreshLease(t *testing.T) { } func TestRemoteKeyboardOwnerIdleLeaseExpiryRetiresHelper(t *testing.T) { - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "Control_R", true) f.wait(t, func() bool { return strings.Contains(f.effects(), "Control_R true\n") }) @@ -400,7 +400,7 @@ func TestRemoteKeyboardOwnerIdleLeaseExpiryRetiresHelper(t *testing.T) { } func TestRemoteKeyboardOwnerShutdownJoinsCleanupAndDisablesMailbox(t *testing.T) { - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "Control_R", true) f.wait(t, func() bool { return strings.Contains(f.effects(), "Control_R true\n") }) @@ -422,7 +422,7 @@ func TestRemoteKeyboardOwnerShutdownJoinsCleanupAndDisablesMailbox(t *testing.T) func TestRemoteKeyboardOwnerRevokesBlockedAndQueuedKeys(t *testing.T) { gate := filepath.Join(t.TempDir(), "apply") t.Setenv("CTHULHU_KEY_OWNER_APPLY_GATE", gate) - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "Shift_L", true) f.wait(t, func() bool { return strings.Contains(f.effects(), "Shift_L true\n") }) @@ -440,7 +440,7 @@ func TestRemoteKeyboardOwnerRevokesBlockedAndQueuedKeys(t *testing.T) { func TestRemoteKeyboardOwnerUncertainCleanupStopsSession(t *testing.T) { t.Setenv("CTHULHU_KEY_OWNER_FAIL_CLEANUP", "1") - f := keyboard_owner_fixture(t) + f := newKeyboardOwnerFixture(t) lease := f.open(t, "keyboard-inject") f.key(t, lease, 1, "Control_L", true) f.wait(t, func() bool { return strings.Contains(f.effects(), "Control_L true\n") }) diff --git a/internal/app/tentacle_remote_speech.go b/internal/app/tentacle_remote_speech.go index e356c17..c2c5cf2 100644 --- a/internal/app/tentacle_remote_speech.go +++ b/internal/app/tentacle_remote_speech.go @@ -16,7 +16,7 @@ import ( // Called under the speech mutex. Cancellation performs no backend I/O. A local // announcement or interruption discards all older incoming work, including work // waiting behind an active renderer. Later Remote output needs fresh admission. -func (worker *speechWorker) retire_remote_speech_locked() { +func (worker *speechWorker) retireRemoteSpeechLocked() { worker.remoteAfter = time.Now() if worker.remoteCancel != nil { worker.remoteCancel() @@ -24,7 +24,7 @@ func (worker *speechWorker) retire_remote_speech_locked() { worker.remoteLifetime, worker.remoteCancel = nil, nil } -func (worker *speechWorker) admit_remote_speech(delivery tentacle.RemoteSpeechDelivery) (remoteSpeechPermit, bool) { +func (worker *speechWorker) admitRemoteSpeech(delivery tentacle.RemoteSpeechDelivery) (remoteSpeechPermit, bool) { worker.mutex.Lock() defer worker.mutex.Unlock() if !worker.running || !worker.enabled || worker.secure || worker.mode != speechModeSpeech || @@ -42,17 +42,17 @@ func (worker *speechWorker) admit_remote_speech(delivery tentacle.RemoteSpeechDe release: func() { stop(); cancel() }}, true } -func (worker *speechWorker) remote_speech_available(delivery tentacle.RemoteSpeechDelivery) bool { +func (worker *speechWorker) remoteSpeechAvailable(delivery tentacle.RemoteSpeechDelivery) bool { worker.mutex.Lock() defer worker.mutex.Unlock() return worker.running && worker.enabled && !worker.secure && worker.mode == speechModeSpeech && delivery.Received.After(worker.remoteAfter) } -// start_remote_speech installs the mailbox before the child becomes active. +// startRemoteSpeech installs the mailbox before the child becomes active. // One session worker owns it until output revocation or reader shutdown. The // lifecycle watcher joins cleanup; input/focus callers only cancel contexts. -func (runtime *tentacleRuntime) start_remote_speech(ctx context.Context, session *tentacle.Session) <-chan struct{} { +func (runtime *tentacleRuntime) startRemoteSpeech(ctx context.Context, session *tentacle.Session) <-chan struct{} { done := make(chan struct{}) owner := runtime.output if owner == nil || owner.speech == nil || owner.gate == nil || runtime.remotePolicy == nil || @@ -75,7 +75,7 @@ func (runtime *tentacleRuntime) start_remote_speech(ctx context.Context, session owner.gate.mutex.Lock() defer owner.gate.mutex.Unlock() if owner.gate.Locked() || owner.gate.Suspended() || owner.gate.InternalUIActive() || - !owner.speech.remote_speech_available(delivery) { + !owner.speech.remoteSpeechAvailable(delivery) { return false } lifetime, err := session.RemoteContext(delivery.Lease, "remote-present") @@ -86,7 +86,7 @@ func (runtime *tentacleRuntime) start_remote_speech(ctx context.Context, session defer cancel() defer stop() for ctx.Err() == nil { - err := run_remote_speech_playback(ctx, speaker, incoming, allow, owner.speech.admit_remote_speech, runtime.logger) + err := runRemoteSpeechPlayback(ctx, speaker, incoming, allow, owner.speech.admitRemoteSpeech, runtime.logger) if ctx.Err() != nil || err == nil { return } diff --git a/internal/app/tentacle_remote_speech_test.go b/internal/app/tentacle_remote_speech_test.go index a4f1439..cb3f484 100644 --- a/internal/app/tentacle_remote_speech_test.go +++ b/internal/app/tentacle_remote_speech_test.go @@ -18,7 +18,7 @@ func TestRemoteSpeechLocalPriorityDiscardsActiveAndQueuedWork(t *testing.T) { t.Run(change, func(t *testing.T) { worker := newSpeechWorker(slog.New(slog.DiscardHandler), nil) worker.running, worker.workerContext = true, t.Context() - f := remote_stream_fixture(t, false, worker.admit_remote_speech) + f := newRemoteStreamFixture(t, false, worker.admitRemoteSpeech) activeRelease := f.speak(t, "old active", 2) active := f.next(t, "old active") pendingRelease := f.speak(t, "old pending", 2) @@ -31,16 +31,16 @@ func TestRemoteSpeechLocalPriorityDiscardsActiveAndQueuedWork(t *testing.T) { case "interrupt": worker.InterruptForUser() case "mode": - worker.cycle_speech_mode() + worker.cycleSpeechMode() case "disable": worker.SetEnabled(false) case "secure": worker.SetSecureInputActive(true) } - remote_stream_wait(t, active.stopped) - remote_stream_wait(t, activeRelease) - remote_stream_wait(t, pendingRelease) - remote_stream_wait(t, f.speak(t, "blocked by local policy", 2)) + remoteStreamWait(t, active.stopped) + remoteStreamWait(t, activeRelease) + remoteStreamWait(t, pendingRelease) + remoteStreamWait(t, f.speak(t, "blocked by local policy", 2)) select { case <-f.started: t.Fatal("old or blocked incoming speech reached rendering") @@ -53,7 +53,7 @@ func TestRemoteSpeechLocalPriorityDiscardsActiveAndQueuedWork(t *testing.T) { freshRelease := f.speak(t, "fresh output", 0) fresh := f.next(t, "fresh output") fresh.finish <- nil - remote_stream_wait(t, freshRelease) + remoteStreamWait(t, freshRelease) f.stop(t) }) } @@ -69,11 +69,11 @@ func TestRemoteSpeechLocalPriorityRejectsOldMailboxAndIncompleteAssembly(t *test worker.mutex.Lock() worker.pending = nil // Local queue drained before the old mailbox is read. worker.mutex.Unlock() - if _, ok := worker.admit_remote_speech(old); ok { + if _, ok := worker.admitRemoteSpeech(old); ok { t.Fatal("old mailbox/assembly work followed local output") } fresh := tentacle.RemoteSpeechDelivery{Context: t.Context(), Received: time.Now()} - permit, ok := worker.admit_remote_speech(fresh) + permit, ok := worker.admitRemoteSpeech(fresh) if !ok || permit.context.Err() != nil || !permit.current() { t.Fatal("fresh incoming output was rejected after local reading") } @@ -83,7 +83,7 @@ func TestRemoteSpeechLocalPriorityRejectsOldMailboxAndIncompleteAssembly(t *test func TestRemoteSpeechRejectedLocalRequestPreservesRemoteAndServerCancelContinues(t *testing.T) { worker := newSpeechWorker(slog.New(slog.DiscardHandler), nil) worker.running, worker.workerContext = true, t.Context() - f := remote_stream_fixture(t, false, worker.admit_remote_speech) + f := newRemoteStreamFixture(t, false, worker.admitRemoteSpeech) released := f.speak(t, "active", 0) active := f.next(t, "active") oldGeneration := worker.generation + 1 @@ -96,20 +96,20 @@ func TestRemoteSpeechRejectedLocalRequestPreservesRemoteAndServerCancelContinues // A server priority cancellation discards this assembly. It must not // disable the owner or retire consent, and no suffix is retried. active.finish <- context.Canceled - remote_stream_wait(t, released) + remoteStreamWait(t, released) nextRelease := f.speak(t, "after cancellation", 0) next := f.next(t, "after cancellation") next.finish <- nil - remote_stream_wait(t, nextRelease) + remoteStreamWait(t, nextRelease) f.stop(t) } func TestRemoteSpeechBackgroundPriorityRejectionClosesCandidate(t *testing.T) { - speaker, server := isolated_voice_fixture(t) + speaker, server := isolatedVoiceFixture(t) server.mutex.Lock() server.queryReplies = map[string]string{"SET SELF PRIORITY TEXT": "400 Rejected\r\n"} server.mutex.Unlock() - if _, err := speaker.open_remote_voice(t.Context()); err == nil { + if _, err := speaker.openRemoteVoice(t.Context()); err == nil { t.Fatal("isolated client acquired without lower backend priority") } speaker.mu.RLock() @@ -121,7 +121,7 @@ func TestRemoteSpeechBackgroundPriorityRejectionClosesCandidate(t *testing.T) { server.mutex.Lock() server.queryReplies = nil server.mutex.Unlock() - voice, err := speaker.open_remote_voice(t.Context()) + voice, err := speaker.openRemoteVoice(t.Context()) if err != nil { t.Fatal("failed priority setup prevented a fresh acquisition", err) } diff --git a/internal/app/tentacle_repositories.go b/internal/app/tentacle_repositories.go index 280969e..00ef21d 100644 --- a/internal/app/tentacle_repositories.go +++ b/internal/app/tentacle_repositories.go @@ -10,7 +10,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentacle" ) -func change_tentacle_repositories(repositories []tentacle.Repository, request tentacle.ManagementRequest, repository *tentacle.Repository) ([]tentacle.Repository, error) { +func changeTentacleRepositories(repositories []tentacle.Repository, request tentacle.ManagementRequest, repository *tentacle.Repository) ([]tentacle.Repository, error) { if request.Entry != nil || request.ID != "" { return nil, errors.New("unexpected tentacle entry in repository request") } diff --git a/internal/app/tentacle_repositories_test.go b/internal/app/tentacle_repositories_test.go index 0161522..7e4f461 100644 --- a/internal/app/tentacle_repositories_test.go +++ b/internal/app/tentacle_repositories_test.go @@ -13,7 +13,7 @@ import ( func TestManagedRepositoryDiscoveryRefreshRemoveAndRestart(t *testing.T) { registryPath := filepath.Join(t.TempDir(), "tentacles.toml") - runtime, _ := managed_tentacle_fixture(t, registryPath, false) + runtime, _ := managedTentacleFixture(t, registryPath, false) origin := "https://example.org/team/tentacles" repository := tentacle.Repository{URL: origin, ID: "example.tentacles", Name: "Example", Revision: strings.Repeat("a", 40), Tentacles: []tentacle.Manifest{{FormatVersion: 1, ID: "echo", Name: "Echo", Version: "0.1"}}} fail := false @@ -63,7 +63,7 @@ func TestManagedRepositoryDiscoveryRefreshRemoveAndRestart(t *testing.T) { t.Fatalf("persisted repository: %+v %v", disk.Repositories(), err) } // Cached catalogs load at startup without invoking any fetch function. - restarted, _ := managed_tentacle_fixture(t, registryPath, false) + restarted, _ := managedTentacleFixture(t, registryPath, false) restarted.fetchRepository = func(context.Context, string) (tentacle.Repository, error) { t.Error("startup fetched repository") return repository, nil @@ -87,7 +87,7 @@ func TestRepositoryRemovalRetainsInstalledEntries(t *testing.T) { if _, err := registry.Load(); err != nil { t.Fatal(err) } - entry := probe_entry(t, "installed", "called") + entry := probeEntry(t, "installed", "called") entry.Repository = origin entry.RepositoryID = "example.tentacles" entry.LocalID = "echo" @@ -95,7 +95,7 @@ func TestRepositoryRemovalRetainsInstalledEntries(t *testing.T) { if err := registry.SaveState([]tentacle.Entry{entry}, []tentacle.Repository{repository}); err != nil { t.Fatal(err) } - runtime, _ := managed_tentacle_fixture(t, registryPath, false) + runtime, _ := managedTentacleFixture(t, registryPath, false) if err := runtime.Start(context.Background()); err != nil { t.Fatal(err) } diff --git a/internal/app/tentacle_settings_test.go b/internal/app/tentacle_settings_test.go index d37460f..ae07615 100644 --- a/internal/app/tentacle_settings_test.go +++ b/internal/app/tentacle_settings_test.go @@ -16,7 +16,7 @@ func TestPreferencesTentacleSettingsDispatchAndMissingSettings(t *testing.T) { t.Run(mode, func(t *testing.T) { directory := t.TempDir() path, marker := filepath.Join(directory, "tentacles.toml"), filepath.Join(directory, mode) - runtime, _ := managed_tentacle_fixture(t, path, false) + runtime, _ := managedTentacleFixture(t, path, false) runtime.output = tentacleOutputFixture(t) keys := &uiTestKeys{} output := &ocrTestOutput{speech: make(chan speechRequest, 32)} @@ -30,7 +30,7 @@ func TestPreferencesTentacleSettingsDispatchAndMissingSettings(t *testing.T) { } executable, _ := os.Executable() entry := tentacle.Entry{ID: "probe", Enabled: true, Presentation: true, Interaction: true, Program: []string{executable, "-test.run=^TestTentacleInteractionPeer$", "--", "interaction-peer", marker}} - manage_tentacle(t, runtime, "add", entry.ID, &entry) + manageTentacle(t, runtime, "add", entry.ID, &entry) waitTentacle(t, func() bool { snapshot := runtime.Snapshot() return len(snapshot.Entries) == 1 && snapshot.Entries[0].State == "active" @@ -45,7 +45,7 @@ func TestPreferencesTentacleSettingsDispatchAndMissingSettings(t *testing.T) { t.Fatal("snapshot shared shortcut storage") } worker := &preferencesWorker{tentacles: runtime} - response := worker.manage_tentacle(ctx, preferences.Request{Tentacle: &tentacle.ManagementRequest{Action: "settings", ID: entry.ID}}) + response := worker.manageTentacle(ctx, preferences.Request{Tentacle: &tentacle.ManagementRequest{Action: "settings", ID: entry.ID}}) if mode == "no-settings" { if response.Accepted || response.Message != "No settings for this tentacle." || keys.InternalUISession() != 0 { t.Fatal(response) @@ -64,7 +64,7 @@ func TestPreferencesTentacleSettingsDispatchAndMissingSettings(t *testing.T) { case "settings-cancel": ui.Handle(input.CommandEvent{Command: input.InternalUIKey, UISession: sessionID, Chord: input.CommandChord{Symbol: 0xff1b}}) case "settings-disable": - manage_tentacle(t, runtime, "disable", entry.ID, nil) + manageTentacle(t, runtime, "disable", entry.ID, nil) } waitTentacle(t, func() bool { return len(runtime.resultSlots) == 0 && keys.InternalUISession() == 0 }) if mode != "settings-disable" { diff --git a/internal/app/tentacle_startup.go b/internal/app/tentacle_startup.go index 35d595b..d5117fa 100644 --- a/internal/app/tentacle_startup.go +++ b/internal/app/tentacle_startup.go @@ -135,10 +135,10 @@ func (owner *tentacleLifecycle) startPending() { } }) owner.watchers = append(owner.watchers, done) - speechDone := owner.runtime.start_remote_speech(owner.ctx, session) - keysDone := owner.runtime.start_remote_keyboard(owner.ctx, session) - captureDone := owner.runtime.start_remote_capture(owner.ctx, session) - brailleDone := owner.runtime.start_remote_braille(owner.ctx, session) + speechDone := owner.runtime.startRemoteSpeech(owner.ctx, session) + keysDone := owner.runtime.startRemoteKeyboard(owner.ctx, session) + captureDone := owner.runtime.startRemoteCapture(owner.ctx, session) + brailleDone := owner.runtime.startRemoteBraille(owner.ctx, session) go func() { defer close(done) defer func() { <-speechDone; <-keysDone; <-captureDone; <-brailleDone }() @@ -147,7 +147,7 @@ func (owner *tentacleLifecycle) startPending() { case <-owner.ctx.Done(): } owner.runtime.output.RetireRevoked() - owner.runtime.signal_extensions() + owner.runtime.signalExtensions() owner.notify() <-session.Done() owner.notify() diff --git a/internal/app/tentacle_uninterruptible_test.go b/internal/app/tentacle_uninterruptible_test.go index 07e8aa2..0d43c06 100644 --- a/internal/app/tentacle_uninterruptible_test.go +++ b/internal/app/tentacle_uninterruptible_test.go @@ -14,11 +14,11 @@ import ( type protectedSpeaker struct{ confirmationSpeaker } -func (speaker *protectedSpeaker) speak_uninterruptible(ctx context.Context, text string) error { +func (speaker *protectedSpeaker) speakUninterruptible(ctx context.Context, text string) error { return speaker.call(ctx, text) } -func protected_output_fixture(t *testing.T) (*tentacleOutput, *protectedSpeaker) { +func protectedOutputFixture(t *testing.T) (*tentacleOutput, *protectedSpeaker) { t.Helper() owner := tentacleOutputFixture(t) speaker := &protectedSpeaker{confirmationSpeaker{controlledSpeaker{calls: make(chan speechCall, 20)}}} @@ -32,7 +32,7 @@ func protected_output_fixture(t *testing.T) (*tentacleOutput, *protectedSpeaker) } func TestTentacleUninterruptibleSurvivesInputAndFocusUntilEnd(t *testing.T) { - owner, speaker := protected_output_fixture(t) + owner, speaker := protectedOutputFixture(t) ticket := owner.Capture(t.Context()) owner.Present(ticket, tentaclewire.Presentation{Speech: "Hello world!", Braille: "Hello world!", Uninterruptible: true}, "tentacle/test/hello") // Protection begins on admission, before the backend has accepted SPEAK. @@ -50,7 +50,7 @@ func TestTentacleUninterruptibleSurvivesInputAndFocusUntilEnd(t *testing.T) { } owner.speech.Enqueue(speechRequest{Text: "Focused control"}) owner.speech.mutex.Lock() - if len(owner.speech.pending) != 1 || !owner.speech.pending[0].Append || !owner.speech.has_uninterruptible_locked() { + if len(owner.speech.pending) != 1 || !owner.speech.pending[0].Append || !owner.speech.hasUninterruptibleLocked() { t.Error("core output did not queue behind protected speech") } owner.speech.mutex.Unlock() @@ -71,7 +71,7 @@ func TestTentacleUninterruptibleSurvivesInputAndFocusUntilEnd(t *testing.T) { func TestTentacleUninterruptibleStillRevokes(t *testing.T) { for _, action := range []string{"session", "disable", "lock", "speech off", "mode", "stop", "lifetime"} { t.Run(action, func(t *testing.T) { - owner, speaker := protected_output_fixture(t) + owner, speaker := protectedOutputFixture(t) parent, cancel := context.WithCancel(t.Context()) defer cancel() ticket := owner.Capture(parent) @@ -94,7 +94,7 @@ func TestTentacleUninterruptibleStillRevokes(t *testing.T) { case "speech off": owner.speech.SetEnabled(false) case "mode": - owner.speech.cycle_speech_mode() + owner.speech.cycleSpeechMode() case "stop": if err := owner.speech.Stop(t.Context()); err != nil { t.Fatal(err) @@ -119,7 +119,7 @@ func TestTentacleUninterruptibleStillRevokes(t *testing.T) { owner.speech.mutex.Unlock() owner.speech.Enqueue(speechRequest{Text: "Resumed"}) for { - call := expect_next_speech_call(t, &speaker.controlledSpeaker) + call := expectNextSpeechCall(t, &speaker.controlledSpeaker) close(call.done) if call.text == "Resumed" { return @@ -132,7 +132,7 @@ func TestTentacleUninterruptibleStillRevokes(t *testing.T) { } } -func expect_next_speech_call(t *testing.T, speaker *controlledSpeaker) speechCall { +func expectNextSpeechCall(t *testing.T, speaker *controlledSpeaker) speechCall { t.Helper() select { case call := <-speaker.calls: @@ -175,13 +175,13 @@ func TestTentacleUninterruptibleCannotResurrectStaleReply(t *testing.T) { } func TestTentacleProtectedStopPreservesCoreQueue(t *testing.T) { - owner, speaker := protected_output_fixture(t) + owner, speaker := protectedOutputFixture(t) owner.Present(owner.Capture(t.Context()), tentaclewire.Presentation{Speech: "Greeting", Uninterruptible: true}, "tentacle/test/hello") _ = expectSpeechCall(t, &speaker.controlledSpeaker, "Greeting") owner.speech.Enqueue(speechRequest{Text: "Core output"}) owner.Stop() for { - call := expect_next_speech_call(t, &speaker.controlledSpeaker) + call := expectNextSpeechCall(t, &speaker.controlledSpeaker) close(call.done) if call.text == "Core output" { return @@ -216,7 +216,7 @@ func TestTentacleProtectedModesAndUnsupportedHardware(t *testing.T) { // Hardware SpeakAndWait reports transmission rather than audible END. It // must not be treated as a completion-capable protected-speech backend. configured := &configuredSpeaker{active: &hardwareSpeaker{}} - if err := configured.speak_uninterruptible(t.Context(), "Greeting"); err == nil { + if err := configured.speakUninterruptible(t.Context(), "Greeting"); err == nil { t.Fatal("hardware backend claimed audible completion") } } diff --git a/internal/app/tentacle_upgrade_failure_test.go b/internal/app/tentacle_upgrade_failure_test.go index 602570f..e53eca2 100644 --- a/internal/app/tentacle_upgrade_failure_test.go +++ b/internal/app/tentacle_upgrade_failure_test.go @@ -15,9 +15,9 @@ import ( ) func TestUpgradePreparationFailurePreservesInstallation(t *testing.T) { - repository, data := install_fixture(t) + repository, data := installFixture(t) - set_install_transport(t, func(*http.Request) (*http.Response, error) { + setInstallTransport(t, func(*http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewReader(data)), @@ -26,7 +26,7 @@ func TestUpgradePreparationFailurePreservesInstallation(t *testing.T) { }) registryPath := filepath.Join(t.TempDir(), "tentacles.toml") - owner, _ := managed_tentacle_fixture(t, registryPath, false) + owner, _ := managedTentacleFixture(t, registryPath, false) owner.fetchRepository = func(context.Context, string) (tentacle.Repository, error) { return repository, nil @@ -57,7 +57,7 @@ func TestUpgradePreparationFailurePreservesInstallation(t *testing.T) { } id := tentacle.PackageID(repository, "echo") - wait_managed_state(t, owner, id, "disabled") + waitManagedState(t, owner, id, "disabled") before := owner.Snapshot().Entries[0].Entry diff --git a/internal/app/tentacle_upgrade_lifecycle_test.go b/internal/app/tentacle_upgrade_lifecycle_test.go index c5f8d8a..e32669d 100644 --- a/internal/app/tentacle_upgrade_lifecycle_test.go +++ b/internal/app/tentacle_upgrade_lifecycle_test.go @@ -20,11 +20,11 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentacle" ) -func prepare_upgrade_fixture(t *testing.T, mode string) (*tentacleRuntime, *tentacleBindingRecorder, tentacle.Repository, tentacle.Entry) { +func prepareUpgradeFixture(t *testing.T, mode string) (*tentacleRuntime, *tentacleBindingRecorder, tentacle.Repository, tentacle.Entry) { t.Helper() - repository, data := install_fixture(t) + repository, data := installFixture(t) - set_install_transport(t, func(*http.Request) (*http.Response, error) { + setInstallTransport(t, func(*http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, ContentLength: int64(len(data)), @@ -34,7 +34,7 @@ func prepare_upgrade_fixture(t *testing.T, mode string) (*tentacleRuntime, *tent }) registryPath := filepath.Join(t.TempDir(), "tentacles.toml") - owner, bindings := managed_tentacle_fixture(t, registryPath, false) + owner, bindings := managedTentacleFixture(t, registryPath, false) owner.fetchRepository = func(context.Context, string) (tentacle.Repository, error) { return repository, nil @@ -57,7 +57,7 @@ func prepare_upgrade_fixture(t *testing.T, mode string) (*tentacleRuntime, *tent } id := tentacle.PackageID(repository, "echo") - wait_managed_state(t, owner, id, "active") + waitManagedState(t, owner, id, "active") before := owner.Snapshot().Entries[0].Entry // Rebuild the downloaded archive with a matching version 0.2 manifest. @@ -137,7 +137,7 @@ func prepare_upgrade_fixture(t *testing.T, mode string) (*tentacleRuntime, *tent } func TestUpgradeReplacesRunningPackageAndCleansOldFiles(t *testing.T) { - owner, _, repository, before := prepare_upgrade_fixture(t, "called") + owner, _, repository, before := prepareUpgradeFixture(t, "called") id := before.ID if err := owner.Manage(context.Background(), tentacle.ManagementRequest{ @@ -146,7 +146,7 @@ func TestUpgradeReplacesRunningPackageAndCleansOldFiles(t *testing.T) { t.Fatal(err) } - wait_managed_state(t, owner, id, "active") + waitManagedState(t, owner, id, "active") after := owner.Snapshot().Entries[0].Entry if !after.Enabled { @@ -173,7 +173,7 @@ func TestUpgradeFailureAndCancellationRestorePreviousPackage(t *testing.T) { if operation == "fail" { mode = "fail" } - owner, bindings, repository, before := prepare_upgrade_fixture(t, mode) + owner, bindings, repository, before := prepareUpgradeFixture(t, mode) ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() result := make(chan error, 1) @@ -192,7 +192,7 @@ func TestUpgradeFailureAndCancellationRestorePreviousPackage(t *testing.T) { case "cancel": cancel() case "disable", "remove": - manage_tentacle(t, owner, operation, before.ID, nil) + manageTentacle(t, owner, operation, before.ID, nil) case "shutdown": if err := owner.Stop(ctx); err != nil { t.Fatal(err) @@ -208,19 +208,19 @@ func TestUpgradeFailureAndCancellationRestorePreviousPackage(t *testing.T) { t.Fatal("update did not finish") } if operation == "fail" || operation == "cancel" { - wait_managed_state(t, owner, before.ID, "active") + waitManagedState(t, owner, before.ID, "active") owner.Invoke(context.Background(), bindings.TentacleBindings()[0].Command) waitTentacle(t, func() bool { _, err := os.Stat(before.Program[len(before.Program)-1]); return err == nil }) } if operation == "disable" { - wait_managed_state(t, owner, before.ID, "disabled") + waitManagedState(t, owner, before.ID, "disabled") } if operation == "shutdown" { - restarted, _ := managed_tentacle_fixture(t, owner.registry.Path, false) + restarted, _ := managedTentacleFixture(t, owner.registry.Path, false) if err := restarted.Start(context.Background()); err != nil { t.Fatal(err) } - wait_managed_state(t, restarted, before.ID, "active") + waitManagedState(t, restarted, before.ID, "active") } disk, err := (&tentacle.Registry{Path: owner.registry.Path}).Load() if err != nil { @@ -255,7 +255,7 @@ func TestUpgradeFailureAndCancellationRestorePreviousPackage(t *testing.T) { } func TestUpgradePreparationCancellationLeavesRunningPackage(t *testing.T) { - owner, _, repository, before := prepare_upgrade_fixture(t, "called") + owner, _, repository, before := prepareUpgradeFixture(t, "called") preparing := make(chan struct{}) owner.preparePackage = func(ctx context.Context, _ string, _ tentacle.Repository, _ string) (*tentacle.PreparedPackage, error) { close(preparing) @@ -289,7 +289,7 @@ func TestUpgradePreparationCancellationLeavesRunningPackage(t *testing.T) { } func TestUpgradeUsesEnablementAtCommit(t *testing.T) { - owner, _, repository, before := prepare_upgrade_fixture(t, "called") + owner, _, repository, before := prepareUpgradeFixture(t, "called") preparing, release := make(chan struct{}), make(chan struct{}) owner.preparePackage = func(ctx context.Context, root string, repository tentacle.Repository, id string) (*tentacle.PreparedPackage, error) { close(preparing) @@ -311,7 +311,7 @@ func TestUpgradeUsesEnablementAtCommit(t *testing.T) { case <-ctx.Done(): t.Fatal("preparation did not start") } - manage_tentacle(t, owner, "disable", before.ID, nil) + manageTentacle(t, owner, "disable", before.ID, nil) close(release) select { case err := <-result: @@ -321,7 +321,7 @@ func TestUpgradeUsesEnablementAtCommit(t *testing.T) { case <-ctx.Done(): t.Fatal("upgrade did not finish") } - wait_managed_state(t, owner, before.ID, "disabled") + waitManagedState(t, owner, before.ID, "disabled") status := owner.Snapshot().Entries[0] if status.Entry.Version != "0.2" || status.Entry.Enabled { t.Fatal(status) diff --git a/internal/app/tentacles.go b/internal/app/tentacles.go index e66fe6c..e41c9f8 100644 --- a/internal/app/tentacles.go +++ b/internal/app/tentacles.go @@ -89,7 +89,7 @@ func (runtime *tentacleRuntime) Start(ctx context.Context) error { defer close(runtime.done) run := runtime.run if runtime.registry != nil { - run = runtime.run_managed + run = runtime.runManaged } if err := run(ctx); err != nil { runtime.logger.Warn("tentacle startup failed", "error", err) @@ -108,7 +108,7 @@ func (runtime *tentacleRuntime) Disable() { runtime.disabled = true runtime.output.Stop() clear(runtime.commands) - runtime.signal_extensions() + runtime.signalExtensions() for _, session := range runtime.sessions { session.Disable() } @@ -189,10 +189,10 @@ func (runtime *tentacleRuntime) run(ctx context.Context) error { } runtime.mutex.Unlock() current, ready = session, session.Ready() - speechDone := runtime.start_remote_speech(ctx, session) - keysDone := runtime.start_remote_keyboard(ctx, session) - captureDone := runtime.start_remote_capture(ctx, session) - brailleDone := runtime.start_remote_braille(ctx, session) + speechDone := runtime.startRemoteSpeech(ctx, session) + keysDone := runtime.startRemoteKeyboard(ctx, session) + captureDone := runtime.startRemoteCapture(ctx, session) + brailleDone := runtime.startRemoteBraille(ctx, session) watchers.Add(1) go func() { defer watchers.Done() @@ -202,7 +202,7 @@ func (runtime *tentacleRuntime) run(ctx context.Context) error { case <-ctx.Done(): } runtime.output.RetireRevoked() - runtime.signal_extensions() + runtime.signalExtensions() select { case wake <- struct{}{}: default: @@ -283,7 +283,7 @@ func (runtime *tentacleRuntime) bind(ctx context.Context, sessions []*tentacle.S func (runtime *tentacleRuntime) publishCommands(sessions []*tentacle.Session) { runtime.mutex.Lock() defer runtime.mutex.Unlock() - defer runtime.signal_extensions() + defer runtime.signalExtensions() clear(runtime.commands) if runtime.disabled { return @@ -432,7 +432,7 @@ func (runtime *tentacleRuntime) report(message string) { // makeManager runs on the lifecycle worker, never on input or GTK callbacks. func (runtime *tentacleRuntime) makeManager() (*tentacle.Manager, error) { - manager, err := runtime.make_manager() + manager, err := runtime.buildManager() if err == nil { manager.SetLogger(runtime.logger) } @@ -440,12 +440,12 @@ func (runtime *tentacleRuntime) makeManager() (*tentacle.Manager, error) { err = manager.UseRemotePolicy(runtime.remotePolicy) } if err == nil && runtime.output != nil && runtime.output.speech != nil { - runtime.output.speech.observe_remote_output(manager) + runtime.output.speech.observeRemoteOutput(manager) } return manager, err } -func (runtime *tentacleRuntime) make_manager() (*tentacle.Manager, error) { +func (runtime *tentacleRuntime) buildManager() (*tentacle.Manager, error) { if runtime.newManager != nil { return runtime.newManager() } diff --git a/internal/app/tentacles_test.go b/internal/app/tentacles_test.go index 36ee001..300d02c 100644 --- a/internal/app/tentacles_test.go +++ b/internal/app/tentacles_test.go @@ -20,7 +20,7 @@ import ( ) // Publish complete fixture data before readers can observe the marker. -func write_tentacle_fixture_marker(markerPath string, data []byte) error { +func writeTentacleFixtureMarker(markerPath string, data []byte) error { if err := os.WriteFile(markerPath+".tmp", data, 0600); err != nil { return err } @@ -49,7 +49,7 @@ func TestTentacleReaderPeer(t *testing.T) { os.Exit(3) } group, _ := os.ReadFile("/proc/self/cgroup") - if err := write_tentacle_fixture_marker(marker, group); err != nil { + if err := writeTentacleFixtureMarker(marker, group); err != nil { return nil, err } if filepath.Base(marker) == "present-delay" { diff --git a/internal/app/terminal_events.go b/internal/app/terminal_events.go index da7bb00..6d4abbb 100644 --- a/internal/app/terminal_events.go +++ b/internal/app/terminal_events.go @@ -12,7 +12,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/input" ) -func should_ignore_terminal_scrollback(event atspi.Event) bool { +func shouldIgnoreTerminalScrollback(event atspi.Event) bool { // VTE can remove old lines at the start of its accessible text while // appending output at a different offset. A deletion entirely before // the caret line is not an edit to the prompt. VTE wrapped rows have @@ -25,12 +25,12 @@ func should_ignore_terminal_scrollback(event atspi.Event) bool { event.TextChangeLength <= event.Source.BrailleLineStart } -// is_user_terminal_deletion identifies a deletion the user just caused at +// isUserTerminalDeletion identifies a deletion the user just caused at // the caret on its own line: a Backspace or Delete edit. The deleted text // is the user's confirmation that the edit took, so repaint coalescing // must not swallow it. Program repaints start above the caret line, and // deletions without a preceding delete key are program output churn. -func is_user_terminal_deletion(event atspi.Event, intent input.Intent) bool { +func isUserTerminalDeletion(event atspi.Event, intent input.Intent) bool { return intent == input.DeleteIntent && event.Type == atspi.TextDeletedEvent && event.Source.Role == "terminal" && event.Source.TextCaretKnown && @@ -38,13 +38,13 @@ func is_user_terminal_deletion(event atspi.Event, intent input.Intent) bool { event.Detail1 <= event.Source.BrailleCaret } -// is_latest_wins_terminal_repaint identifies an in-place rewrite: an +// isLatestWinsTerminalRepaint identifies an in-place rewrite: an // insertion that replaced a just-deleted range. Status regions update // this way several times a second and only the newest state is worth // hearing. Editing feedback on the caret line after a typing or delete // key stays immediate; appended output has no preceding deletion and // never qualifies. -func is_latest_wins_terminal_repaint(event atspi.Event, intent input.Intent, replacedDeletion bool) bool { +func isLatestWinsTerminalRepaint(event atspi.Event, intent input.Intent, replacedDeletion bool) bool { if !replacedDeletion || event.Type != atspi.TextInsertedEvent || event.Source.Role != "terminal" { return false } @@ -57,7 +57,7 @@ func is_latest_wins_terminal_repaint(event atspi.Event, intent input.Intent, rep // Blank repaints carry no speech. Short nonblank updates can still be // meaningful ("OK", a count, or one Unicode character) and must survive. -func is_trivial_terminal_repaint(event atspi.Event) bool { +func isTrivialTerminalRepaint(event atspi.Event) bool { return event.Type == atspi.TextInsertedEvent && event.Source.Role == "terminal" && strings.TrimSpace(event.Payload) == "" } @@ -79,7 +79,7 @@ func terminalReplacementOverlap(deletion, insertion atspi.Event) bool { // Preserve the first deadline so a continuously redrawn status still speaks // its latest value. The event loop owns both the event and the timer. -func (pending *pendingPresentation) coalesce_terminal_repaint(event atspi.Event) { +func (pending *pendingPresentation) coalesceTerminalRepaint(event atspi.Event) { if pending.event.Type == "" { pending.schedule(event, input.NoIntent, terminalRepaintDebounce) return diff --git a/internal/app/terminal_events_test.go b/internal/app/terminal_events_test.go index 8e6bc6f..71f3c7b 100644 --- a/internal/app/terminal_events_test.go +++ b/internal/app/terminal_events_test.go @@ -134,7 +134,7 @@ func TestTerminalScrollbackDeletionPreservesEditing(t *testing.T) { t.Run(test.name, func(t *testing.T) { event := base test.modify(&event) - if got := should_ignore_terminal_scrollback(event); got != test.ignore { + if got := shouldIgnoreTerminalScrollback(event); got != test.ignore { t.Fatalf("ignore = %v, want %v", got, test.ignore) } }) @@ -435,7 +435,7 @@ func TestUserTerminalDeletionClassification(t *testing.T) { t.Run(test.name, func(t *testing.T) { event := atspi.NewEventWithPayload(atspi.TextDeletedEvent, terminal, "x") test.modify(&event) - if got := is_user_terminal_deletion(event, test.intent); got != test.want { + if got := isUserTerminalDeletion(event, test.intent); got != test.want { t.Fatalf("is_user_terminal_deletion = %v, want %v", got, test.want) } }) diff --git a/internal/app/test_helpers_test.go b/internal/app/test_helpers_test.go index 03a57c3..0cd0095 100644 --- a/internal/app/test_helpers_test.go +++ b/internal/app/test_helpers_test.go @@ -174,15 +174,6 @@ func (listener *fakeInputListener) Stop(context.Context) error { return nil } -func contains_string(values []string, wanted string) bool { - for _, value := range values { - if value == wanted { - return true - } - } - return false -} - type eventDiagnosticsWriter struct { started chan struct{} startOnce sync.Once diff --git a/internal/app/voice_profiles_test.go b/internal/app/voice_profiles_test.go index e774865..30b9f55 100644 --- a/internal/app/voice_profiles_test.go +++ b/internal/app/voice_profiles_test.go @@ -29,12 +29,12 @@ func TestQuickVoiceProfilesFailurePersistenceAndApplicationInheritance(t *testin t.Fatal("failed profile changed current voice") } failure = nil - saved := config.Primary_voice(settings) + saved := config.PrimaryVoice(settings) // After the last profile, Default restores the saved voice. for _, name := range []string{"Reading", "Presentation", "", "Reading"} { worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting) - primary := config.Primary_voice(worker.settings) - if got := worker.settings.VoiceProfiles.Matching(primary); got != name || name == "" && !voiceprofiles.Same_voice(primary, saved) { + primary := config.PrimaryVoice(worker.settings) + if got := worker.settings.VoiceProfiles.Matching(primary); got != name || name == "" && !voiceprofiles.SameVoice(primary, saved) { t.Fatal(got, name, worker.settings.DefaultVoice) } } @@ -57,7 +57,7 @@ func TestQuickVoiceProfileDefaultRestoresSavedVoiceFromCustom(t *testing.T) { settings := config.DefaultSettings() settings.Path = filepath.Join(t.TempDir(), "settings.toml") settings.VoiceProfiles.Profiles = []voiceprofiles.Profile{{Name: "Reading", Driver: "speech-dispatcher", Rate: 30, Volume: 80}} - saved := config.Primary_voice(settings) + saved := config.PrimaryVoice(settings) worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, settingsUpdateFunc(func(context.Context, speech.Settings) error { return nil })) var messages []string worker.announce = func(text string) { messages = append(messages, text) } @@ -68,7 +68,7 @@ func TestQuickVoiceProfileDefaultRestoresSavedVoiceFromCustom(t *testing.T) { t.Fatal("session voice not reported as Custom", got) } worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting) - if got := messages[len(messages)-1]; got != "Default" || !voiceprofiles.Same_voice(config.Primary_voice(worker.settings), saved) { + if got := messages[len(messages)-1]; got != "Default" || !voiceprofiles.SameVoice(config.PrimaryVoice(worker.settings), saved) { t.Fatal("Default did not restore the saved voice", messages, worker.settings.DefaultVoice) } } @@ -112,7 +112,7 @@ func TestQuickVoiceProfileDefaultIsFocusedApplicationVoice(t *testing.T) { } // An application without its own voice follows the global saved voice. worker.switchApplication(t.Context(), "Plain Application") - if saved := worker.saved_voice(); saved == nil || !voiceprofiles.Same_voice(*saved, config.Primary_voice(global)) { + if saved := worker.savedVoiceProfile(); saved == nil || !voiceprofiles.SameVoice(*saved, config.PrimaryVoice(global)) { t.Fatal("inherited application voice was not the global voice", saved) } } @@ -148,7 +148,7 @@ func TestAppliedNewVoiceProfileIsImmediatelyAvailableAcrossApplications(t *testi worker.switchApplication(t.Context(), application) selectQuickSetting(t, worker, "speech.profile") worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting) - if got := config.Primary_voice(worker.settings); got.Rate != 30 || got.Volume != 80 { + if got := config.PrimaryVoice(worker.settings); got.Rate != 30 || got.Volume != 80 { t.Fatal("new profile unavailable without restart", application, got) } worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting) // Return to Default. @@ -160,14 +160,14 @@ func TestProfileVoicePreviewReachesBackendWithoutCommitting(t *testing.T) { updater := &voiceConfigurationRecorder{} worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, updater) profile := voiceprofiles.Profile{Name: "Reading", Driver: "speech-dispatcher", Module: "fixture", Language: "es", Voice: "Reading voice", Rate: 30, Pitch: -10, Volume: 80} - draft, err := config.Apply_primary_voice(settings, profile) + draft, err := config.ApplyPrimaryVoice(settings, profile) if err != nil { t.Fatal(err) } if response := worker.preview(t.Context(), preferences.Request{Values: preferences.FromSettings(draft), Preview: true}); !response.Accepted { t.Fatal(response.Message) } - if got := config.Primary_voice(updater.settings); !voiceprofiles.Same_voice(got, profile) { + if got := config.PrimaryVoice(updater.settings); !voiceprofiles.SameVoice(got, profile) { t.Fatal("profile preview did not reach the speech backend", got) } if !reflect.DeepEqual(worker.settings, settings) || len(worker.settings.VoiceProfiles.Profiles) != 0 { diff --git a/internal/app/window_switcher.go b/internal/app/window_switcher.go index 39bc16c..b88df43 100644 --- a/internal/app/window_switcher.go +++ b/internal/app/window_switcher.go @@ -13,7 +13,7 @@ import ( // A window-manager switcher can leave the old client as X11 foreground while // Alt is held. Present its selection without replacing that client's focus, // review position, browser mode or native ownership. No session state is kept. -func (handler *accessibilityEventHandler) handle_window_switcher(event atspi.Event) bool { +func (handler *accessibilityEventHandler) handleWindowSwitcher(event atspi.Event) bool { if !atspi.IsWindowSwitcherSelection(event) { return false } diff --git a/internal/app/window_switcher_test.go b/internal/app/window_switcher_test.go index 2b9e7e1..ca7ce55 100644 --- a/internal/app/window_switcher_test.go +++ b/internal/app/window_switcher_test.go @@ -24,7 +24,7 @@ func (display *switcherBrailleRecorder) Flash(text string, _ config.BrailleOptio return true } -func mate_switcher_event(eventType, title string, foreground atspi.ForegroundState) atspi.Event { +func mateSwitcherEvent(eventType, title string, foreground atspi.ForegroundState) atspi.Event { event := ownerEvent(eventType, ":1.43", "/switcher", "/switcher/status") event.Source.ApplicationName, event.Source.ApplicationProcess = "marco", "marco" event.Source.Role, event.Source.Name = "status bar", title @@ -60,7 +60,7 @@ func TestMateWindowSwitcherOutsideForeground(t *testing.T) { // Replay the log's non-focused status insertion, then repeated forward // and reverse selection updates without an X11 foreground change. for _, title := range []string{"Editor", "Terminal", "Editor"} { - adapter.events <- mate_switcher_event(atspi.TextInsertedEvent, title, foreground) + adapter.events <- mateSwitcherEvent(atspi.TextInsertedEvent, title, foreground) expectActivationSpeech(t, queue.spoken, title) request := <-queue.requests if request.Cause != "window-switcher" || request.Role != "system" || !request.BypassFocusGate { @@ -75,12 +75,12 @@ func TestMateWindowSwitcherOutsideForeground(t *testing.T) { t.Fatal("missing switcher Braille message") } } - showing := mate_switcher_event(atspi.ShowingStateEvent, "Browser", foreground) + showing := mateSwitcherEvent(atspi.ShowingStateEvent, "Browser", foreground) showing.Detail1 = 1 adapter.events <- showing expectActivationSpeech(t, queue.spoken, "Browser") <-queue.requests - adapter.events <- mate_switcher_event(atspi.SelectionChangedEvent, "Terminal", foreground) + adapter.events <- mateSwitcherEvent(atspi.SelectionChangedEvent, "Terminal", foreground) expectActivationSpeech(t, queue.spoken, "Terminal") <-queue.requests @@ -100,7 +100,7 @@ func TestMateWindowSwitcherOutsideForeground(t *testing.T) { func(e *atspi.Event) { e.Window.BusName = ":1.44" }, func(e *atspi.Event) { e.Source.Name = " " }, } { - event := mate_switcher_event(atspi.TextInsertedEvent, "Unwanted output", foreground) + event := mateSwitcherEvent(atspi.TextInsertedEvent, "Unwanted output", foreground) change(&event) adapter.events <- event } @@ -117,8 +117,8 @@ func TestMateWindowSwitcherTerminalHandoffAndLock(t *testing.T) { gate := &focusGate{} gate.suspended.Store(true) handler := accessibilityEventHandler{focusGate: gate, speech: gatedSpeech{speech: queue, gate: gate}} - event := mate_switcher_event(atspi.TextInsertedEvent, "Editor", atspi.ForegroundState{}) - if !handler.handle_window_switcher(event) { + event := mateSwitcherEvent(atspi.TextInsertedEvent, "Editor", atspi.ForegroundState{}) + if !handler.handleWindowSwitcher(event) { t.Fatal("switcher selection was not handled") } expectActivationSpeech(t, queue.spoken, "Editor") diff --git a/internal/app/window_titles.go b/internal/app/window_titles.go index 7ec6dd8..54b00e8 100644 --- a/internal/app/window_titles.go +++ b/internal/app/window_titles.go @@ -333,10 +333,10 @@ func (titles *windowTitleController) present() { Window: window, ExcludeFromHistory: titles.state.historyWindow.Valid() && window == titles.state.historyWindow}) } -// repeats_focused_edit recognizes titles whose only changed portion mirrors +// repeatsFocusedEdit recognizes titles whose only changed portion mirrors // the owned entry. Use copied focus and input evidence, never application names // or field labels. Window introductions and unrelated status changes still speak. -func (titles *windowTitleController) repeats_focused_edit(previousTitle, title string) bool { +func (titles *windowTitleController) repeatsFocusedEdit(previousTitle, title string) bool { current := titles.state.current if previousTitle == "" || !current.Editable || current.ReadOnly || !current.Focused || !titles.state.focusedID.Valid() || current.ID() != titles.state.focusedID || @@ -408,7 +408,7 @@ func (titles *windowTitleController) flush() { return } titles.lastTitle = pending.text - if pending.changed && titles.repeats_focused_edit(pending.previousText, pending.text) { + if pending.changed && titles.repeatsFocusedEdit(pending.previousText, pending.text) { return } if pending.inputSequence != recentInput(titles.inputSource).TitleInterruptionSequence { diff --git a/internal/app/wine_events.go b/internal/app/wine_events.go index fbbb446..6a8de3c 100644 --- a/internal/app/wine_events.go +++ b/internal/app/wine_events.go @@ -68,10 +68,10 @@ func wineTypingEchoEnabled(text string, settings config.Settings) bool { } func (owner *wineEventPresenter) Present(event remote.AccessibleEvent) bool { - return owner.present_event(event, nil) + return owner.presentEvent(event, nil) } -func (owner *wineEventPresenter) present_event(event remote.AccessibleEvent, editor func(remote.AccessibleEvent) bool) bool { +func (owner *wineEventPresenter) presentEvent(event remote.AccessibleEvent, editor func(remote.AccessibleEvent) bool) bool { owner.mu.Lock() defer owner.mu.Unlock() kind := strings.ToLower(event.EventType) @@ -114,7 +114,7 @@ func (owner *wineEventPresenter) present_event(event remote.AccessibleEvent, edi } // Establish the queued focus before the action. Neither focus merging // nor duplicate suppression may consume repeated characters/actions. - owner.flush_pending() + owner.flushPending() if owner.logger != nil { owner.logger.Debug("Wine editor feedback", "source", event.SourceID, "native_utf16_selection", event.States, "text", event.Name) @@ -182,7 +182,7 @@ func (owner *wineEventPresenter) present_event(event remote.AccessibleEvent, edi owner.pending = &winePresentation{source: event.SourceID, window: event.WindowTitle, message: message, parts: parts} if owner.timer == nil { generation := owner.timerGeneration - owner.timer = time.AfterFunc(50*time.Millisecond, func() { owner.flush_generation(generation) }) + owner.timer = time.AfterFunc(50*time.Millisecond, func() { owner.flushGeneration(generation) }) } return true } @@ -200,20 +200,20 @@ func (owner *wineEventPresenter) present_event(event remote.AccessibleEvent, edi func (owner *wineEventPresenter) flush() { owner.mu.Lock() defer owner.mu.Unlock() - owner.flush_pending() + owner.flushPending() } -func (owner *wineEventPresenter) flush_generation(generation uint64) { +func (owner *wineEventPresenter) flushGeneration(generation uint64) { owner.mu.Lock() defer owner.mu.Unlock() if generation == owner.timerGeneration { - owner.flush_pending() + owner.flushPending() } } -// flush_pending requires mu to be held, including for immediate editor +// flushPending requires mu to be held, including for immediate editor // actions. Stop the old timer so it cannot flush a later focus burst early. -func (owner *wineEventPresenter) flush_pending() { +func (owner *wineEventPresenter) flushPending() { owner.timerGeneration++ if owner.timer != nil { owner.timer.Stop() diff --git a/internal/app/wine_events_test.go b/internal/app/wine_events_test.go index 61e4c0e..895da11 100644 --- a/internal/app/wine_events_test.go +++ b/internal/app/wine_events_test.go @@ -218,7 +218,7 @@ func TestWineEditorFlushInvalidatesOldTimer(t *testing.T) { owner.timer.Stop() owner.mu.Unlock() // Model a timer that fired before Stop but was waiting for delivery. - owner.flush_generation(oldGeneration) + owner.flushGeneration(oldGeneration) if !slices.Equal(spoken, []string{"edit", "a"}) { t.Fatalf("stale timer delivered new focus: %v", spoken) } diff --git a/internal/atspi/adapter.go b/internal/atspi/adapter.go index a825830..b24d4a0 100644 --- a/internal/atspi/adapter.go +++ b/internal/atspi/adapter.go @@ -409,7 +409,7 @@ func (adapter *Adapter) capture(ctx context.Context, reviewFocus ObjectID, captu } var trace *captureDiagnostics if reviewFocus.Valid() { - ctx, trace = new_capture_diagnostics(ctx, adapter.captureLogger.Load(), reviewFocus) + ctx, trace = newCaptureDiagnostics(ctx, adapter.captureLogger.Load(), reviewFocus) if trace != nil && document { trace.kind = "document" } @@ -435,7 +435,7 @@ func (adapter *Adapter) capture(ctx context.Context, reviewFocus ObjectID, captu documentText: documentText, result: make(chan treeCaptureResult, 1), } - trace.begin_stage("queue-wait", reviewFocus, "") + trace.beginStage("queue-wait", reviewFocus, "") select { case adapter.treeRequests <- request: case <-ctx.Done(): diff --git a/internal/atspi/adapter_actions_native.go b/internal/atspi/adapter_actions_native.go index ca3cccb..ae1f3df 100644 --- a/internal/atspi/adapter_actions_native.go +++ b/internal/atspi/adapter_actions_native.go @@ -36,7 +36,7 @@ func (adapter *Adapter) PerformAccessibleAction(ctx context.Context, target Acti // Native action work stays on the GLib owner, using retained review/document // handles as well as focus. Never redirect a stale action to a new focus. -func (adapter *Adapter) native_action_source(object ObjectID) (*C.AtspiAccessible, ActionTarget, error) { +func (adapter *Adapter) nativeActionSource(object ObjectID) (*C.AtspiAccessible, ActionTarget, error) { var source *C.AtspiAccessible for _, item := range adapter.nativeFocus { if item.id == object { @@ -82,11 +82,11 @@ func (adapter *Adapter) native_action_source(object ObjectID) (*C.AtspiAccessibl return source, target, nil } -func (adapter *Adapter) native_actions(ctx context.Context, object ObjectID, expected *ActionTarget, name string) (ActionSet, error) { +func (adapter *Adapter) nativeActions(ctx context.Context, object ObjectID, expected *ActionTarget, name string) (ActionSet, error) { if err := ctx.Err(); err != nil { return ActionSet{}, err } - source, target, err := adapter.native_action_source(object) + source, target, err := adapter.nativeActionSource(object) if err != nil { return ActionSet{}, err } @@ -125,7 +125,7 @@ func (adapter *Adapter) native_actions(ctx context.Context, object ObjectID, exp return ActionSet{}, ErrStaleObject } // Recheck ownership immediately before the external side effect. - _, current, checkErr := adapter.native_action_source(object) + _, current, checkErr := adapter.nativeActionSource(object) if checkErr != nil || current != target { return ActionSet{}, ErrStaleObject } diff --git a/internal/atspi/adapter_document_native.go b/internal/atspi/adapter_document_native.go index b648011..ac17cec 100644 --- a/internal/atspi/adapter_document_native.go +++ b/internal/atspi/adapter_document_native.go @@ -201,7 +201,7 @@ func (adapter *Adapter) activateNativeDocumentObject(ctx context.Context, positi if len(adapter.nativeFocus) > 0 { latest := adapter.nativeFocus[len(adapter.nativeFocus)-1].id if latest != focus { - if err := document_position_matches_retained_focus(tree, position, adapter.nativeFocus[len(adapter.nativeFocus)-1]); err != nil { + if err := documentPositionMatchesRetainedFocus(tree, position, adapter.nativeFocus[len(adapter.nativeFocus)-1]); err != nil { return err } } @@ -325,13 +325,13 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob var nativeErr *C.GError count := int(C.atspi_text_get_character_count(text, &nativeErr)) if nativeErr != nil { - err := adapter.document_object_error(position.ID(), nativeError("get document text count", nativeErr)) + err := adapter.documentObjectError(position.ID(), nativeError("get document text count", nativeErr)) C.g_error_free(nativeErr) return DocumentCaretText{}, err } if count == 0 && snapshot.CharacterCount > 0 && !snapshot.Editable && (snapshot.Role == "static" || snapshot.Role == "text") { - return DocumentCaretText{}, adapter.document_text_became_empty(position.ID()) + return DocumentCaretText{}, adapter.documentTextBecameEmpty(position.ID()) } if count <= 0 || offset >= count { if unit != DocumentCaretBrailleLine || count <= 0 || offset != count { @@ -345,7 +345,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob end := min(count, start+128) content := C.atspi_text_get_text(text, C.gint(start), C.gint(end), &nativeErr) if nativeErr != nil { - err := adapter.document_object_error(position.ID(), nativeError("read document characters", nativeErr)) + err := adapter.documentObjectError(position.ID(), nativeError("read document characters", nativeErr)) C.g_error_free(nativeErr) C.g_free(C.gpointer(content)) return DocumentCaretText{}, err @@ -366,7 +366,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob line = expandNativeDocumentText(ctx, source, snapshot, line) } if unit == DocumentCaretBrailleLine && adapter.captureTextAttributes.Load() { - line.TextAttributeRuns = native_text_attribute_runs(text, line.Start, line.End, TextAttributeRun{}) + line.TextAttributeRuns = nativeTextAttributeRuns(text, line.Start, line.End, TextAttributeRun{}) } if unit == DocumentCaretBrailleLine && C.atspi_text_get_n_selections(text, nil) > 0 { if selection := C.atspi_text_get_selection(text, 0, nil); selection != nil { @@ -380,7 +380,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob var boundsErr error line.Bounds, boundsErr = (nativeReviewText{text: text}).bounds(ctx, line.Start, line.End) if boundsErr != nil { - if err := adapter.document_object_error(position.ID(), boundsErr); errors.Is(err, ErrDeadObject) { + if err := adapter.documentObjectError(position.ID(), boundsErr); errors.Is(err, ErrDeadObject) { return DocumentCaretText{}, err } } @@ -396,13 +396,13 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob var verifyErr *C.GError remaining := int(C.atspi_text_get_character_count(text, &verifyErr)) if verifyErr != nil { - err := adapter.document_object_error(position.ID(), nativeError("verify document text count", verifyErr)) + err := adapter.documentObjectError(position.ID(), nativeError("verify document text count", verifyErr)) C.g_error_free(verifyErr) if errors.Is(err, ErrDeadObject) { return DocumentCaretText{}, err } } else if remaining == 0 && count > 0 { - return DocumentCaretText{}, adapter.document_text_became_empty(position.ID()) + return DocumentCaretText{}, adapter.documentTextBecameEmpty(position.ID()) } } if unit == DocumentCaretLineRemainder && line.Start < offset && offset < line.End && offset-line.Start <= utf8.RuneCountInString(line.Text) { @@ -410,7 +410,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob line.Start = offset } if unit != DocumentCaretBrailleLine { - line.Misspelled = native_misspelled(text, offset) + line.Misspelled = nativeMisspelled(text, offset) line.Text = sanitizeSnapshotField(line.Text) } return line, nil @@ -424,7 +424,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob } rangeText := C.atspi_text_get_string_at_offset(text, C.gint(offset), granularity, &nativeErr) if nativeErr != nil { - err := adapter.document_object_error(position.ID(), nativeError("read document text", nativeErr)) + err := adapter.documentObjectError(position.ID(), nativeError("read document text", nativeErr)) C.g_error_free(nativeErr) return DocumentCaretText{}, err } @@ -441,7 +441,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob } return DocumentCaretText{ Start: int(rangeText.start_offset), End: int(rangeText.end_offset), - Text: content, CharacterCount: count, Misspelled: native_misspelled(text, offset), + Text: content, CharacterCount: count, Misspelled: nativeMisspelled(text, offset), }, nil } @@ -539,7 +539,7 @@ func (adapter *Adapter) setNativeDocumentPosition(ctx context.Context, position if len(adapter.nativeFocus) > 0 { latest := adapter.nativeFocus[len(adapter.nativeFocus)-1].id if latest != focus { - if err := document_position_matches_retained_focus(tree, position, adapter.nativeFocus[len(adapter.nativeFocus)-1]); err != nil { + if err := documentPositionMatchesRetainedFocus(tree, position, adapter.nativeFocus[len(adapter.nativeFocus)-1]); err != nil { return err } } @@ -587,7 +587,7 @@ func (adapter *Adapter) setNativeDocumentPosition(ctx context.Context, position } else { caretOffset = C.atspi_text_get_caret_offset(text, &nativeErr) if nativeErr != nil { - err := adapter.document_object_error(position.ID(), nativeError("get document caret", nativeErr)) + err := adapter.documentObjectError(position.ID(), nativeError("get document caret", nativeErr)) C.g_error_free(nativeErr) clear(adapter.navigationEcho) return err @@ -615,7 +615,7 @@ func (adapter *Adapter) setNativeDocumentPosition(ctx context.Context, position } moved := C.atspi_text_set_caret_offset(text, caretOffset, &nativeErr) if nativeErr != nil { - err := adapter.document_object_error(position.ID(), nativeError("set document caret", nativeErr)) + err := adapter.documentObjectError(position.ID(), nativeError("set document caret", nativeErr)) C.g_error_free(nativeErr) clear(adapter.navigationEcho) return err @@ -633,7 +633,7 @@ func (adapter *Adapter) setNativeDocumentPosition(ctx context.Context, position // before the next command. That remembered position is not evidence that native // focus left the document. Retain its generation-checked document proof while // continuing to reject actual focus changes to chrome or another document. -func document_position_matches_retained_focus(tree *AccessibleTree, position ObjectReference, focus nativeFocusReference) error { +func documentPositionMatchesRetainedFocus(tree *AccessibleTree, position ObjectReference, focus nativeFocusReference) error { err := documentPositionMatchesFocus(tree, position, focus.id) if !errors.Is(err, ErrObjectNotFound) || !focus.navigationDocument.Valid() { return err diff --git a/internal/atspi/adapter_event_callback_native.go b/internal/atspi/adapter_event_callback_native.go index ef296c2..a610da0 100644 --- a/internal/atspi/adapter_event_callback_native.go +++ b/internal/atspi/adapter_event_callback_native.go @@ -352,7 +352,7 @@ func (adapter *Adapter) enrichNativeWindowEvent(event *C.AtspiEvent, target *C.A } focusEvent.Source = snapshot if eventType == FocusEvent || eventType == FocusedStateEvent && focusEvent.Detail1 != 0 || eventType == CaretEvent || eventType == ActiveDescendantEvent || eventType == SelectionChangedEvent { - snapshot.SpeechContext, snapshot.BrailleContext = native_speech_context(target) + snapshot.SpeechContext, snapshot.BrailleContext = nativeSpeechContext(target) for _, ancestor := range snapshot.SpeechContext { if ancestor.Role == "document spreadsheet" { snapshot.Spreadsheet = true @@ -418,15 +418,15 @@ func (adapter *Adapter) enrichNativeWindowEvent(event *C.AtspiEvent, target *C.A //export cthulhuAtspiEventCallback func cthulhuAtspiEventCallback(event *C.AtspiEvent, userData unsafe.Pointer) { - dispatch_native_event(event, userData, false, 0) + dispatchNativeEvent(event, userData, false, 0) } //export cthulhuAtspiSelectionCallback func cthulhuAtspiSelectionCallback(event *C.AtspiEvent, userData unsafe.Pointer, epoch C.uint64_t) { - dispatch_native_event(event, userData, true, uint64(epoch)) + dispatchNativeEvent(event, userData, true, uint64(epoch)) } -func dispatch_native_event(event *C.AtspiEvent, userData unsafe.Pointer, deferredSelection bool, selectionEpoch uint64) { +func dispatchNativeEvent(event *C.AtspiEvent, userData unsafe.Pointer, deferredSelection bool, selectionEpoch uint64) { if event == nil || userData == nil { return } @@ -495,7 +495,7 @@ func dispatch_native_event(event *C.AtspiEvent, userData unsafe.Pointer, deferre adapter.refreshForeground() if isDocumentLifecycleEvent(eventType) || eventType == DefunctStateEvent && C.cthulhu_event_detail1(event) != 0 { adapter.deferredLiveRegions.take(originID) - adapter.deferredLiveRegions.forget_document(originID) + adapter.deferredLiveRegions.forgetDocument(originID) } if eventType == DefunctStateEvent && C.cthulhu_event_detail1(event) != 0 { adapter.forgetDocumentWindow(originID) @@ -503,14 +503,14 @@ func dispatch_native_event(event *C.AtspiEvent, userData unsafe.Pointer, deferre adapter.forgetWindowDocuments(originID) } invalidated := adapter.applyTreeInvalidation(eventType, event) - returnedTarget := adapter.returned_menu_item(event, eventType, originID) + returnedTarget := adapter.returnedMenuItem(event, eventType, originID) if returnedTarget != nil { defer C.g_object_unref(C.gpointer(returnedTarget)) // Keep the original showing event and popup origin in diagnostics. // Only fresh focus on its parent supplies this normalized focus event. eventType, invalidated = FocusEvent, false } - if selection := adapter.window_switcher_event(event, eventType); selection != nil { + if selection := adapter.windowSwitcherEvent(event, eventType); selection != nil { adapter.enqueueSecureEvent(*selection, secureEpoch) return } @@ -570,7 +570,7 @@ func dispatch_native_event(event *C.AtspiEvent, userData unsafe.Pointer, deferre } var live nativeLiveProperties if eventType == TextInsertedEvent || eventType == ChildrenAddedEvent || eventType == BusyStateEvent { - live = capture_live_properties(event.source) + live = captureLiveProperties(event.source) } if invalidated && webNotification == nil && eventType == ChildrenAddedEvent && (live.politeness == "" || live.politeness == "off") { return @@ -578,7 +578,7 @@ func dispatch_native_event(event *C.AtspiEvent, userData unsafe.Pointer, deferre if !deferredSelection && !selectionBoundary { C.cthulhu_flush_selection(adapter.callbackData) } - deferLive, completeLive := adapter.prepare_live_region(event, eventType, originID, live) + deferLive, completeLive := adapter.prepareLiveRegion(event, eventType, originID, live) if deferLive { return } diff --git a/internal/atspi/adapter_foreground_native.go b/internal/atspi/adapter_foreground_native.go index 378dfe5..e458671 100644 --- a/internal/atspi/adapter_foreground_native.go +++ b/internal/atspi/adapter_foreground_native.go @@ -60,7 +60,7 @@ func cthulhuAtspiForegroundCallback(data unsafe.Pointer) { adapter.foregroundRecovery = 8 } adapter.recoverForeground() - adapter.refresh_entry_name() + adapter.refreshEntryName() } func (adapter *Adapter) matchesForeground(source, window *C.AtspiAccessible, id ObjectID) bool { @@ -86,7 +86,7 @@ func (adapter *Adapter) matchForeground(source, window *C.AtspiAccessible, id Ob // Desktop panel menus can grab the keyboard while X11 still names the // previous application. Orca accepts their active, showing menu window. // Keep the correlated X11 owner so dismissal can return to that client. - if adapter.is_panel_menu(source, window) { + if adapter.isPanelMenu(source, window) { return true } if state.Window == 0 { @@ -139,7 +139,7 @@ func (adapter *Adapter) matchForeground(source, window *C.AtspiAccessible, id Ob // Tiling window managers can report GTK's frame and X11's client at // different origins and sizes. Our own active preferences child is known // by its launched PID; require X11 to confirm that process is foreground. - if preferences_foreground_matches(state, pid, adapter.preferencesPID.Load()) { + if preferencesForegroundMatches(state, pid, adapter.preferencesPID.Load()) { adapter.foregroundWindow = id adapter.foregroundRecovery = 0 return true @@ -195,7 +195,7 @@ func (adapter *Adapter) matchForeground(source, window *C.AtspiAccessible, id Ob // The exception is for a native menu from the panel process, never an // arbitrary panel control or a provider claiming the panel's accessible name. // Query fresh window state on the GLib owner; no popup state is retained. -func (adapter *Adapter) is_panel_menu(source, window *C.AtspiAccessible) bool { +func (adapter *Adapter) isPanelMenu(source, window *C.AtspiAccessible) bool { if adapter.applicationProcess(window) != "mate-panel" { return false } diff --git a/internal/atspi/adapter_menu_states_native.go b/internal/atspi/adapter_menu_states_native.go index d0a3105..cd5d547 100644 --- a/internal/atspi/adapter_menu_states_native.go +++ b/internal/atspi/adapter_menu_states_native.go @@ -12,7 +12,7 @@ import "C" // A hiding submenu can return focus only from its most recently focused // direct item. Queries and the returned reference belong to the GLib owner; // the callback releases the reference after the ordinary foreground gates. -func (adapter *Adapter) returned_menu_item(event *C.AtspiEvent, eventType string, origin ObjectID) *C.AtspiAccessible { +func (adapter *Adapter) returnedMenuItem(event *C.AtspiEvent, eventType string, origin ObjectID) *C.AtspiAccessible { if eventType != ShowingStateEvent || event.detail1 != 0 || len(adapter.nativeFocus) == 0 { return nil } diff --git a/internal/atspi/adapter_native_test.go b/internal/atspi/adapter_native_test.go index 06932d9..cd579ba 100644 --- a/internal/atspi/adapter_native_test.go +++ b/internal/atspi/adapter_native_test.go @@ -446,8 +446,8 @@ func TestNativeTreeCaptureDefunctAndShutdownInvalidation(t *testing.T) { } assertNativeReviewText(t, tree, textRef, "Café 猫Second line") if os.Getenv("CTHULHU_TREE_CONTAINER") == "list" { - assert_native_list_position(t, tree, "Persistent control", 1, 7) - assert_native_list_position(t, tree, "Removable control", 2, 7) + assertNativeListPosition(t, tree, "Persistent control", 1, 7) + assertNativeListPosition(t, tree, "Removable control", 2, 7) } caretRef := findNamedReference(t, tree, "Caret review probe") if captured, err := tree.VisibleText(caretRef); err != nil || !captured.CaretKnown || captured.CaretOffset != 6 { @@ -509,7 +509,7 @@ func TestNativeTreeCaptureDefunctAndShutdownInvalidation(t *testing.T) { t.Fatal("recapture did not contain persistent control") } if os.Getenv("CTHULHU_TREE_CONTAINER") == "list" { - assert_native_list_position(t, tree, "Persistent control", 1, 6) + assertNativeListPosition(t, tree, "Persistent control", 1, 6) } if os.Getenv("CTHULHU_TREE_CONTAINER") == "box" { container := findNamedReference(t, tree, "Dynamic controls") @@ -653,7 +653,7 @@ func waitForSoundGeometry(t *testing.T, ctx context.Context, events <-chan Event } } -func assert_native_list_position(t *testing.T, tree *AccessibleTree, name string, position, size int) { +func assertNativeListPosition(t *testing.T, tree *AccessibleTree, name string, position, size int) { t.Helper() label := findNamedReference(t, tree, name) row, ok, err := tree.Parent(label) diff --git a/internal/atspi/adapter_ocr_native.go b/internal/atspi/adapter_ocr_native.go index 63b9349..a6d00d7 100644 --- a/internal/atspi/adapter_ocr_native.go +++ b/internal/atspi/adapter_ocr_native.go @@ -128,7 +128,7 @@ func (adapter *Adapter) nativeOCRGeometry(ctx context.Context, object ObjectID, } bounds = clipped } - screen, err := ocr_screen_bounds(bounds, windowGeometry.Bounds, before.Client) + screen, err := ocrScreenBounds(bounds, windowGeometry.Bounds, before.Client) adapter.refreshForeground() if err := ctx.Err(); err != nil { return OCRGeometry{}, err diff --git a/internal/atspi/adapter_references_native.go b/internal/atspi/adapter_references_native.go index 8640415..246d945 100644 --- a/internal/atspi/adapter_references_native.go +++ b/internal/atspi/adapter_references_native.go @@ -18,8 +18,8 @@ import ( func (adapter *Adapter) captureDesktop(ctx context.Context, reviewFocus ObjectID, document, documentText bool) (*AccessibleTree, error) { if document { - trace := capture_diagnostics(ctx) - trace.begin_stage("root-selection", reviewFocus, "") + trace := captureDiagnosticsFrom(ctx) + trace.beginStage("root-selection", reviewFocus, "") root, err := adapter.nativeDocumentRoot(ctx, reviewFocus) if errors.Is(err, ErrObjectNotFound) || errors.Is(err, ErrStaleObject) { // A removed focus may still belong to a retained capture. Recover @@ -32,8 +32,8 @@ func (adapter *Adapter) captureDesktop(ctx context.Context, reviewFocus ObjectID if err != nil { return nil, err } - trace.set_root(nativeObjectID(root), "document") - trace.begin_stage("cache-preparation", nativeObjectID(root), "") + trace.setRoot(nativeObjectID(root), "document") + trace.beginStage("cache-preparation", nativeObjectID(root), "") adapter.rotateDocumentSlots(nativeObjectID(root)) adapter.treeMutex.Lock() previousTree := adapter.documentTree @@ -60,8 +60,8 @@ func (adapter *Adapter) captureDesktop(ctx context.Context, reviewFocus ObjectID adapter.nativeDocument = retained return tree, nil } - trace := capture_diagnostics(ctx) - trace.begin_stage("root-selection", reviewFocus, "") + trace := captureDiagnosticsFrom(ctx) + trace.beginStage("root-selection", reviewFocus, "") rootScope := "window" var rootSource *C.AtspiAccessible if reviewFocus.Valid() { @@ -82,8 +82,8 @@ func (adapter *Adapter) captureDesktop(ctx context.Context, reviewFocus ObjectID if rootSource == nil { return nil, errors.New("capture AT-SPI review window: root is unavailable") } - trace.set_root(nativeObjectID(rootSource), rootScope) - trace.begin_stage("cache-preparation", nativeObjectID(rootSource), "") + trace.setRoot(nativeObjectID(rootSource), rootScope) + trace.beginStage("cache-preparation", nativeObjectID(rootSource), "") retained := make(map[ObjectID]*C.AtspiAccessible) cache := nativeTreeCache{} if reviewFocus.BusName != "" { @@ -104,7 +104,7 @@ func (adapter *Adapter) captureDesktop(ctx context.Context, reviewFocus ObjectID } return nil, err } - trace.begin_stage("tree-installation", root, "") + trace.beginStage("tree-installation", root, "") tree, err := adapter.installCapturedTree(root, nodes, document, documentText) if err != nil { for _, source := range retained { @@ -112,11 +112,11 @@ func (adapter *Adapter) captureDesktop(ctx context.Context, reviewFocus ObjectID } return nil, err } - trace.begin_stage("reference-cleanup", root, "") + trace.beginStage("reference-cleanup", root, "") adapter.clearNativeReview() adapter.nativeReview = retained adapter.nativeReviewBus = reviewFocus.BusName - trace.begin_stage("result-delivery", root, "") + trace.beginStage("result-delivery", root, "") return tree, nil } diff --git a/internal/atspi/adapter_snapshot_native.go b/internal/atspi/adapter_snapshot_native.go index 6d3c22e..1b262ad 100644 --- a/internal/atspi/adapter_snapshot_native.go +++ b/internal/atspi/adapter_snapshot_native.go @@ -67,7 +67,7 @@ func snapshotFromNativeWithOptions(source *C.AtspiAccessible, text, caretCharact if text && snapshot.Role != "password text" { switch snapshot.Role { case "button", "push button", "check box", "radio button", "toggle button", "menu item", "check menu item", "radio menu item": - snapshot.Mnemonic = native_mnemonic(source) + snapshot.Mnemonic = nativeMnemonic(source) } } if snapshot.TextCaretKnown { @@ -79,11 +79,11 @@ func snapshotFromNativeWithOptions(source *C.AtspiAccessible, text, caretCharact if caretCharacter && strings.ContainsRune(textContent, '\ufffc') && characterCount <= 0 { characterCount = int(C.atspi_text_get_character_count(text, nil)) } - snapshot.TextAttributeRun = native_text_attribute_run(text, snapshot.BrailleCaret) + snapshot.TextAttributeRun = nativeTextAttributeRun(text, snapshot.BrailleCaret) snapshot.Misspelled = TextAttributesMisspelled(snapshot.TextAttributeRun.Values) if len(captureAttributes) != 0 && captureAttributes[0] { start := snapshot.BrailleLineStart - snapshot.TextAttributeRuns = native_text_attribute_runs(text, start, start+len([]rune(snapshot.BrailleLine)), snapshot.TextAttributeRun) + snapshot.TextAttributeRuns = nativeTextAttributeRuns(text, start, start+len([]rune(snapshot.BrailleLine)), snapshot.TextAttributeRun) } if C.atspi_text_get_n_selections(text, nil) > 0 { if selection := C.atspi_text_get_selection(text, 0, nil); selection != nil { diff --git a/internal/atspi/adapter_tree_native.go b/internal/atspi/adapter_tree_native.go index a66eb4d..2f528bd 100644 --- a/internal/atspi/adapter_tree_native.go +++ b/internal/atspi/adapter_tree_native.go @@ -88,8 +88,8 @@ type nativeTreeCache struct { // focused application's subtree. The latter keeps flat review independent of // unrelated AT-SPI providers that can be slow or transiently unavailable. func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusName string, document, documentText bool, retained map[ObjectID]*C.AtspiAccessible, cache nativeTreeCache) (ObjectID, []TreeNode, error) { - trace := capture_diagnostics(ctx) - trace.begin_stage("tree-setup", ObjectID{}, "") + trace := captureDiagnosticsFrom(ctx) + trace.beginStage("tree-setup", ObjectID{}, "") reviewOnly := !document && reviewBusName != "" rootID := nativeObjectID(root) if !rootID.Valid() { @@ -129,7 +129,7 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa cached, known := cache.nodes[sourceID] refresh := !known || cached.snapshotInvalid || cached.textInvalid || cached.geometryInvalid || cached.childrenInvalid || cached.childrenUnavailable snapshot := cached.snapshot - trace.begin_stage("snapshot", sourceID, snapshot.Role) + trace.beginStage("snapshot", sourceID, snapshot.Role) if refresh { // Only changed/new objects require synchronous provider queries. // Reusing live siblings matches Python's event-driven web cache and @@ -185,7 +185,7 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa retained[snapshot.ID()] = (*C.AtspiAccessible)(C.g_object_ref(C.gpointer(source))) } - trace.begin_stage("geometry", snapshot.ID(), snapshot.Role) + trace.beginStage("geometry", snapshot.ID(), snapshot.Role) geometry := cached.geometry var geometryErr error if refresh { @@ -214,7 +214,7 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa // can be the displayed page below it. Preserve the parent viewport. childClip, childClipped = item.clip, item.clipped } - trace.begin_stage("visible-text", snapshot.ID(), snapshot.Role) + trace.beginStage("visible-text", snapshot.ID(), snapshot.Role) text := VisibleText{Limited: true, Issue: TextTreeLimit} if (!document || documentText) && textBytes < maxTreeTextBytes { if known && !cached.textInvalid && !cached.geometryInvalid && !item.clipChanged { @@ -234,13 +234,13 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa } if textBytes+size > maxTreeTextBytes { text = VisibleText{Limited: true, Issue: TextTreeLimit} - trace.text_issue(TextTreeLimit) + trace.textIssue(TextTreeLimit) } else { textBytes += size } } - trace.begin_stage("table-viewport", snapshot.ID(), snapshot.Role) + trace.beginStage("table-viewport", snapshot.ID(), snapshot.Role) // Visual review cannot use descendants of hidden controls. Inactive // notebook pages and closed GTK combo menus can expose thousands of // children; traversing them can exhaust the entire capture deadline. @@ -271,7 +271,7 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa tableViewport := false if reviewOnly && captureChildren { var tableErr error - tableChildren, tableViewport, tableErr = native_review_table_children(ctx, source, clip) + tableChildren, tableViewport, tableErr = nativeReviewTableChildren(ctx, source, clip) if tableErr != nil { C.g_object_unref(C.gpointer(source)) releasePending() @@ -284,7 +284,7 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa } }(tableChildren) } - trace.begin_stage("child-count", snapshot.ID(), snapshot.Role) + trace.beginStage("child-count", snapshot.ID(), snapshot.Role) if !captureChildren { childCount = 0 } else if tableViewport { @@ -321,7 +321,7 @@ func captureNativeTree(ctx context.Context, root *C.AtspiAccessible, reviewBusNa return ObjectID{}, nil, fmt.Errorf("%w: native tree exceeds limit %d", ErrInvalidTree, maxTreeNodes) } - trace.begin_stage("child-enumeration", snapshot.ID(), snapshot.Role) + trace.beginStage("child-enumeration", snapshot.ID(), snapshot.Role) children := make([]ObjectID, 0, childCount) for index := 0; index < childCount; index++ { if err := ctx.Err(); err != nil { @@ -410,7 +410,7 @@ func cthulhuAtspiTreeCaptureCallback(userData unsafe.Pointer) { return } request := <-adapter.treeRequests - capture_diagnostics(request.ctx).begin_stage("callback-setup", request.reviewFocus, "") + captureDiagnosticsFrom(request.ctx).beginStage("callback-setup", request.reviewFocus, "") adapter.applySecureReset() if request.ctx.Err() != nil { request.result <- treeCaptureResult{err: request.ctx.Err()} @@ -424,14 +424,14 @@ func cthulhuAtspiTreeCaptureCallback(userData unsafe.Pointer) { item, err := adapter.nativeTransferItem(request.ctx, request.reviewFocus, request.positionOffset) request.result <- treeCaptureResult{item: item, err: err} } else if request.typeText { - err := adapter.native_type_text(request.ctx, request.insertionText) + err := adapter.nativeTypeText(request.ctx, request.insertionText) request.result <- treeCaptureResult{err: err} } else if request.listActions || request.actionTarget != nil { object := request.reviewFocus if request.actionTarget != nil { object = request.actionTarget.Object } - actions, err := adapter.native_actions(request.ctx, object, request.actionTarget, request.actionName) + actions, err := adapter.nativeActions(request.ctx, object, request.actionTarget, request.actionName) request.result <- treeCaptureResult{actions: actions, err: err} } else if request.ocrGeometry { geometry, err := adapter.nativeOCRGeometry(request.ctx, request.reviewFocus, request.ocrZone) @@ -446,10 +446,10 @@ func cthulhuAtspiTreeCaptureCallback(userData unsafe.Pointer) { err := adapter.setNativeFocusedTextCaret(request.ctx, request.reviewFocus, request.positionOffset) request.result <- treeCaptureResult{err: err} } else if request.readFocusedSnapshot { - content, err := adapter.read_native_focused_snapshot(request.ctx, request.reviewFocus) + content, err := adapter.readNativeFocusedSnapshot(request.ctx, request.reviewFocus) request.result <- treeCaptureResult{content: content, err: err} } else if request.readFocusedLine { - content, err := adapter.read_native_focused_line(request.ctx, request.reviewFocus) + content, err := adapter.readNativeFocusedLine(request.ctx, request.reviewFocus) request.result <- treeCaptureResult{content: content, err: err} } else if request.readFocusedText { content, err := adapter.readNativeFocusedText(request.ctx, request.reviewFocus) diff --git a/internal/atspi/adapter_tree_test.go b/internal/atspi/adapter_tree_test.go index 6ced675..3ae6ca4 100644 --- a/internal/atspi/adapter_tree_test.go +++ b/internal/atspi/adapter_tree_test.go @@ -477,11 +477,11 @@ func TestRemovedBrowseCaretRetainsOnlyItsDocument(t *testing.T) { if err != nil { t.Fatal(err) } - if err := document_position_matches_retained_focus(tree, position, focus); (err == nil) != test.allowed { + if err := documentPositionMatchesRetainedFocus(tree, position, focus); (err == nil) != test.allowed { t.Fatalf("caret ownership error = %v, allowed = %t", err, test.allowed) } tree.Invalidate(position.ID()) - if err := document_position_matches_retained_focus(tree, position, focus); err == nil { + if err := documentPositionMatchesRetainedFocus(tree, position, focus); err == nil { t.Fatal("removed target accepted") } }) diff --git a/internal/atspi/adapter_window_switcher_native.go b/internal/atspi/adapter_window_switcher_native.go index 47733be..4c0a818 100644 --- a/internal/atspi/adapter_window_switcher_native.go +++ b/internal/atspi/adapter_window_switcher_native.go @@ -12,9 +12,9 @@ import "C" // Capture only the verified window manager's visible status container, before // background filtering or selected-child resolution. All native queries run // on the GLib owner; no native references or mutable switcher state survive. -func (adapter *Adapter) window_switcher_event(event *C.AtspiEvent, eventType string) *Event { +func (adapter *Adapter) windowSwitcherEvent(event *C.AtspiEvent, eventType string) *Event { detail1 := int(C.cthulhu_event_detail1(event)) - if !is_window_switcher_selection_type(eventType, detail1) || + if !isWindowSwitcherSelectionType(eventType, detail1) || C.atspi_accessible_get_role(event.source, nil) != C.ATSPI_ROLE_STATUS_BAR || adapter.applicationProcess(event.source) != "marco" { return nil diff --git a/internal/atspi/braille_native.go b/internal/atspi/braille_native.go index 3a64939..be4776b 100644 --- a/internal/atspi/braille_native.go +++ b/internal/atspi/braille_native.go @@ -43,7 +43,7 @@ func (adapter *Adapter) routeNativeBraille(ctx context.Context, route BrailleRou return err } if route.Position.Valid() { - return adapter.route_document_braille(ctx, route) + return adapter.routeDocumentBraille(ctx, route) } if !adapter.nativeFocusIs(route.Focus) { return ErrStaleObject @@ -76,7 +76,7 @@ func (adapter *Adapter) routeNativeBraille(ctx context.Context, route BrailleRou return nil } -func (adapter *Adapter) route_document_braille(ctx context.Context, route BrailleRoute) error { +func (adapter *Adapter) routeDocumentBraille(ctx context.Context, route BrailleRoute) error { adapter.treeMutex.Lock() tree := adapter.documentTree adapter.treeMutex.Unlock() diff --git a/internal/atspi/capture_diagnostics.go b/internal/atspi/capture_diagnostics.go index 9c04b5b..faf9d26 100644 --- a/internal/atspi/capture_diagnostics.go +++ b/internal/atspi/capture_diagnostics.go @@ -44,7 +44,7 @@ type captureDiagnostics struct { finished bool } -func (trace *captureDiagnostics) text_issue(issue TextCaptureIssue) { +func (trace *captureDiagnostics) textIssue(issue TextCaptureIssue) { if trace == nil { return } @@ -58,7 +58,7 @@ func (trace *captureDiagnostics) text_issue(issue TextCaptureIssue) { } } -func new_capture_diagnostics(ctx context.Context, logger *slog.Logger, focus ObjectID) (context.Context, *captureDiagnostics) { +func newCaptureDiagnostics(ctx context.Context, logger *slog.Logger, focus ObjectID) (context.Context, *captureDiagnostics) { if logger == nil || !logger.Enabled(ctx, slog.LevelDebug) { return ctx, nil } @@ -67,12 +67,12 @@ func new_capture_diagnostics(ctx context.Context, logger *slog.Logger, focus Obj return context.WithValue(ctx, captureDiagnosticKey{}, trace), trace } -func capture_diagnostics(ctx context.Context) *captureDiagnostics { +func captureDiagnosticsFrom(ctx context.Context) *captureDiagnostics { trace, _ := ctx.Value(captureDiagnosticKey{}).(*captureDiagnostics) return trace } -func (trace *captureDiagnostics) record_stage(now time.Time) { +func (trace *captureDiagnostics) recordStage(now time.Time) { duration := now.Sub(trace.stageStarted) index := 0 for index < len(trace.timings) && trace.timings[index].Stage != trace.stage { @@ -90,7 +90,7 @@ func (trace *captureDiagnostics) record_stage(now time.Time) { } } -func (trace *captureDiagnostics) begin_stage(stage string, object ObjectID, role string) { +func (trace *captureDiagnostics) beginStage(stage string, object ObjectID, role string) { if trace == nil { return } @@ -100,11 +100,11 @@ func (trace *captureDiagnostics) begin_stage(stage string, object ObjectID, role return } now := time.Now() - trace.record_stage(now) + trace.recordStage(now) trace.stage, trace.object, trace.role, trace.stageStarted = stage, object, role, now } -func (trace *captureDiagnostics) set_root(root ObjectID, scope string) { +func (trace *captureDiagnostics) setRoot(root ObjectID, scope string) { if trace == nil { return } @@ -137,7 +137,7 @@ func (trace *captureDiagnostics) finish(err error) { return } now := time.Now() - trace.record_stage(now) + trace.recordStage(now) trace.finished = true message := "flat review capture timing" if trace.kind != "" { diff --git a/internal/atspi/capture_diagnostics_test.go b/internal/atspi/capture_diagnostics_test.go index 7819939..a119a4c 100644 --- a/internal/atspi/capture_diagnostics_test.go +++ b/internal/atspi/capture_diagnostics_test.go @@ -17,24 +17,24 @@ import ( func TestCaptureDiagnosticsTimeoutDuringNativeCall(t *testing.T) { var output bytes.Buffer logger := logging.New(&output, logging.Options{Level: slog.LevelDebug}) - ctx, trace := new_capture_diagnostics(context.Background(), logger, NewObjectID(":1.7", "/focus")) - if capture_diagnostics(ctx) != trace { + ctx, trace := newCaptureDiagnostics(context.Background(), logger, NewObjectID(":1.7", "/focus")) + if captureDiagnosticsFrom(ctx) != trace { t.Fatal("capture context lost its diagnostics") } root := NewObjectID(":1.7", "/window") cell := NewObjectID(":1.7", "/cell") - trace.set_root(root, "window") - trace.begin_stage("queue-wait", root, "frame") + trace.setRoot(root, "window") + trace.beginStage("queue-wait", root, "frame") started, resume, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) go func() { defer close(done) - trace.begin_stage("visible-text", cell, "table cell") + trace.beginStage("visible-text", cell, "table cell") trace.progress("table cell", 12, 3, 250) close(started) <-resume // The native operation is still running when its caller times out. - trace.begin_stage("child-count", cell, "table cell") + trace.beginStage("child-count", cell, "table cell") trace.progress("table cell", 13, 2, 400) - trace.set_root(NewObjectID(":1.7", "/late-root"), "desktop") + trace.setRoot(NewObjectID(":1.7", "/late-root"), "desktop") trace.finish(nil) }() <-started @@ -78,13 +78,13 @@ func TestCaptureDiagnosticsTimeoutDuringNativeCall(t *testing.T) { func TestCaptureDiagnosticsRequiresDebugLogging(t *testing.T) { ctx := context.Background() for _, logger := range []*slog.Logger{nil, logging.New(nil, logging.Options{Level: slog.LevelInfo})} { - gotContext, trace := new_capture_diagnostics(ctx, logger, ObjectID{}) + gotContext, trace := newCaptureDiagnostics(ctx, logger, ObjectID{}) if gotContext != ctx || trace != nil { t.Fatal("disabled diagnostics added capture state") } - trace.begin_stage("snapshot", ObjectID{}, "") + trace.beginStage("snapshot", ObjectID{}, "") trace.progress("", 0, 0, 0) - trace.set_root(ObjectID{}, "") + trace.setRoot(ObjectID{}, "") trace.finish(nil) } } diff --git a/internal/atspi/current_line_native.go b/internal/atspi/current_line_native.go index a80b202..8f2ed5b 100644 --- a/internal/atspi/current_line_native.go +++ b/internal/atspi/current_line_native.go @@ -29,7 +29,7 @@ func (adapter *Adapter) ReadFocusedSnapshot(ctx context.Context, focus ObjectID) return result.content, err } -func (adapter *Adapter) read_native_focused_snapshot(ctx context.Context, focus ObjectID) (DocumentContent, error) { +func (adapter *Adapter) readNativeFocusedSnapshot(ctx context.Context, focus ObjectID) (DocumentContent, error) { if err := ctx.Err(); err != nil { return DocumentContent{}, err } @@ -39,10 +39,10 @@ func (adapter *Adapter) read_native_focused_snapshot(ctx context.Context, focus source := adapter.nativeFocus[len(adapter.nativeFocus)-1].source C.atspi_accessible_clear_cache_single(source) snapshot := snapshotFromNativeWithCaret(source, true, false, false, false) - return DocumentContent{Snapshot: snapshot, SourceContext: native_focused_line_context(ctx, source)}, ctx.Err() + return DocumentContent{Snapshot: snapshot, SourceContext: nativeFocusedLineContext(ctx, source)}, ctx.Err() } -func (adapter *Adapter) read_native_focused_line(ctx context.Context, focus ObjectID) (content DocumentContent, err error) { +func (adapter *Adapter) readNativeFocusedLine(ctx context.Context, focus ObjectID) (content DocumentContent, err error) { if err := ctx.Err(); err != nil { return DocumentContent{}, err } @@ -58,7 +58,7 @@ func (adapter *Adapter) read_native_focused_line(ctx context.Context, focus Obje content = DocumentContent{Snapshot: snapshot, Text: snapshot.Name} defer func() { if err == nil { - content.SourceContext = native_focused_line_context(ctx, source) + content.SourceContext = nativeFocusedLineContext(ctx, source) } }() text := C.atspi_accessible_get_text_iface(source) @@ -116,7 +116,7 @@ func (adapter *Adapter) read_native_focused_line(ctx context.Context, focus Obje // even unnamed containers and parents outside the window. Keep it on the GLib // owner and bound the walk without scanning children or retaining native refs. // Failed/truncated capture must not turn a successful local read into an error. -func native_focused_line_context(ctx context.Context, source *C.AtspiAccessible) []Snapshot { +func nativeFocusedLineContext(ctx context.Context, source *C.AtspiAccessible) []Snapshot { deadline, cancel := context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() current := (*C.AtspiAccessible)(C.g_object_ref(C.gpointer(source))) diff --git a/internal/atspi/document.go b/internal/atspi/document.go index a475d7e..0e77663 100644 --- a/internal/atspi/document.go +++ b/internal/atspi/document.go @@ -120,11 +120,11 @@ func (tree *AccessibleTree) Document(ctx context.Context, reference ObjectRefere func (tree *AccessibleTree) DocumentView(ctx context.Context, reference ObjectReference) (DocumentSnapshot, error) { tree.mu.Lock() defer tree.mu.Unlock() - view, err := tree.navigation_document_locked(ctx, reference) + view, err := tree.navigationDocumentLocked(ctx, reference) if err != nil { return DocumentSnapshot{}, err } - if err := tree.validate_document_range_locked(ctx, view, 0, len(view.Nodes)-1); err != nil { + if err := tree.validateDocumentRangeLocked(ctx, view, 0, len(view.Nodes)-1); err != nil { return DocumentSnapshot{}, err } return view, nil @@ -137,10 +137,10 @@ func (tree *AccessibleTree) DocumentView(ctx context.Context, reference ObjectRe func (tree *AccessibleTree) NavigationDocument(ctx context.Context, reference ObjectReference) (DocumentSnapshot, error) { tree.mu.Lock() defer tree.mu.Unlock() - return tree.navigation_document_locked(ctx, reference) + return tree.navigationDocumentLocked(ctx, reference) } -func (tree *AccessibleTree) navigation_document_locked(ctx context.Context, reference ObjectReference) (DocumentSnapshot, error) { +func (tree *AccessibleTree) navigationDocumentLocked(ctx context.Context, reference ObjectReference) (DocumentSnapshot, error) { if err := ctx.Err(); err != nil { return DocumentSnapshot{}, err } @@ -191,8 +191,8 @@ func (tree *AccessibleTree) navigation_document_locked(ctx context.Context, refe pending = append(pending, pendingNode{entry.children[i], hidden}) } } - result.data = new_document_data(result.Nodes) - populate_document_rows(&result) + result.data = newDocumentData(result.Nodes) + populateDocumentRows(&result) if tree.documents == nil { tree.documents = make(map[ObjectID]*documentData) } diff --git a/internal/atspi/document_error.go b/internal/atspi/document_error.go index e0536fe..3298a33 100644 --- a/internal/atspi/document_error.go +++ b/internal/atspi/document_error.go @@ -13,7 +13,7 @@ import ( // its removal event reaches us. Refresh its metadata and parent's child order // rather than silently skipping text from an obsolete snapshot. Empty text // alone does not prove removal, so keep identities and live siblings intact. -func (adapter *Adapter) document_text_became_empty(object ObjectID) error { +func (adapter *Adapter) documentTextBecameEmpty(object ObjectID) error { adapter.treeMutex.Lock() tree := adapter.documentTree adapter.treeMutex.Unlock() @@ -33,7 +33,7 @@ func (adapter *Adapter) document_text_became_empty(object ObjectID) error { // libatspi forwards Chromium's missing-object response as an untyped GError. // Match the queried path exactly; a timeout or unsupported caret is not proof // that the virtual reading position has disappeared. -func (adapter *Adapter) document_object_error(object ObjectID, err error) error { +func (adapter *Adapter) documentObjectError(object ObjectID, err error) error { if err == nil || !object.Valid() || !strings.HasSuffix(strings.TrimSpace(err.Error()), "could not be processed as object "+object.Path+" does not exist") { return err diff --git a/internal/atspi/document_error_test.go b/internal/atspi/document_error_test.go index 0b44cf6..cdc3426 100644 --- a/internal/atspi/document_error_test.go +++ b/internal/atspi/document_error_test.go @@ -16,7 +16,7 @@ func TestDocumentMissingObjectRetiresCachedTarget(t *testing.T) { object := testID("/second") failure := fmt.Errorf("get document caret: Method %q with signature %q on interface %q could not be processed as object %s does not exist\n", "Get", "ss", "org.freedesktop.DBus.Properties", object.Path) - err := adapter.document_object_error(object, failure) + err := adapter.documentObjectError(object, failure) if !errors.Is(err, ErrDeadObject) || !errors.Is(err, failure) { t.Fatalf("missing-object error lost classification or details: %v", err) } @@ -49,7 +49,7 @@ func TestDocumentCaretFailuresDoNotRetireLiveTargets(t *testing.T) { adapter := New() adapter.documentTree = testTree(t) failure := errors.New(message) - if err := adapter.document_object_error(testID("/second"), failure); err != failure { + if err := adapter.documentObjectError(testID("/second"), failure); err != failure { t.Fatalf("ordinary failure reclassified: %v", err) } if _, err := adapter.documentTree.Reference(testID("/second")); err != nil { @@ -66,7 +66,7 @@ func TestDocumentEmptyTextRefreshesMetadataAndParentWithoutRetiringTargets(t *te object := testID("/second") target, _ := tree.Reference(object) sibling, _ := tree.Reference(testID("/first")) - if err := adapter.document_text_became_empty(object); !errors.Is(err, ErrStaleText) { + if err := adapter.documentTextBecameEmpty(object); !errors.Is(err, ErrStaleText) { t.Fatalf("unexpected empty-text classification: %v", err) } if current, err := tree.Reference(object); err != nil || current != target { @@ -89,7 +89,7 @@ func TestDocumentMissingDescendantRefreshesAncestorChildOrder(t *testing.T) { adapter.tree, adapter.documentTree, adapter.documentTextTree = testTree(t), testTree(t), testTree(t) object := testID("/grandchild") failure := fmt.Errorf("get document caret: could not be processed as object %s does not exist", object.Path) - if err := adapter.document_object_error(object, failure); !errors.Is(err, ErrDeadObject) { + if err := adapter.documentObjectError(object, failure); !errors.Is(err, ErrDeadObject) { t.Fatal(err) } for _, tree := range []*AccessibleTree{adapter.tree, adapter.documentTree, adapter.documentTextTree} { diff --git a/internal/atspi/document_rows.go b/internal/atspi/document_rows.go index b63f9a6..9c88fef 100644 --- a/internal/atspi/document_rows.go +++ b/internal/atspi/document_rows.go @@ -11,7 +11,7 @@ import ( // Derive rows from the already captured document. This performs no native // queries and keeps large tables bounded to 32 cells and 4096 bytes per row. -func populate_document_rows(document *DocumentSnapshot) { +func populateDocumentRows(document *DocumentSnapshot) { nodes := document.data.indices type rowKey struct { table ObjectID diff --git a/internal/atspi/document_view.go b/internal/atspi/document_view.go index 8bd1133..e6f46c3 100644 --- a/internal/atspi/document_view.go +++ b/internal/atspi/document_view.go @@ -16,7 +16,7 @@ type documentData struct { rows map[ObjectID][]ObjectReference } -func new_document_data(nodes []DocumentNode) *documentData { +func newDocumentData(nodes []DocumentNode) *documentData { data := &documentData{nodes: nodes, indices: make(map[ObjectID]int, len(nodes)), ends: make([]int, len(nodes))} for index, node := range nodes { data.indices[node.Reference.ID()] = index @@ -71,13 +71,13 @@ func (document DocumentSnapshot) SubtreeEnd(index int) int { return end } -// document_entry_error_tolerating optionally ignores text, geometry, and +// documentEntryErrorTolerating optionally ignores text, geometry, and // child-order staleness. Caret movement reads text and line bounds live // from the provider and generation-checks every endpoint, so captured // staleness of those cannot make its result wrong: at worst a just-inserted // sibling is skipped until the next capture. Identity and semantics are // checked either way. -func document_entry_error_tolerating(entry treeEntry, tolerateText bool) error { +func documentEntryErrorTolerating(entry treeEntry, tolerateText bool) error { switch { case entry.snapshotInvalid: return ErrStaleSnapshot @@ -98,7 +98,7 @@ func document_entry_error_tolerating(entry treeEntry, tolerateText bool) error { func (tree *AccessibleTree) ValidateDocumentRange(ctx context.Context, document DocumentSnapshot, from, to int) error { tree.mu.RLock() defer tree.mu.RUnlock() - return tree.validate_document_range_locked(ctx, document, from, to) + return tree.validateDocumentRangeLocked(ctx, document, from, to) } // ValidateDocumentCaretRange is ValidateDocumentRange for caret movement, @@ -111,7 +111,7 @@ func (tree *AccessibleTree) ValidateDocumentRange(ctx context.Context, document func (tree *AccessibleTree) ValidateDocumentCaretRange(ctx context.Context, document DocumentSnapshot, from, to int) error { tree.mu.RLock() defer tree.mu.RUnlock() - return tree.validate_document_path_locked(ctx, document, from, to, from != to, true) + return tree.validateDocumentPathLocked(ctx, document, from, to, from != to, true) } // ValidateDocumentOrder also checks ancestor child order when a structural @@ -119,14 +119,14 @@ func (tree *AccessibleTree) ValidateDocumentCaretRange(ctx context.Context, docu func (tree *AccessibleTree) ValidateDocumentOrder(ctx context.Context, document DocumentSnapshot, index int) error { tree.mu.RLock() defer tree.mu.RUnlock() - return tree.validate_document_path_locked(ctx, document, index, index, true, false) + return tree.validateDocumentPathLocked(ctx, document, index, index, true, false) } -func (tree *AccessibleTree) validate_document_range_locked(ctx context.Context, document DocumentSnapshot, from, to int) error { - return tree.validate_document_path_locked(ctx, document, from, to, from != to, false) +func (tree *AccessibleTree) validateDocumentRangeLocked(ctx context.Context, document DocumentSnapshot, from, to int) error { + return tree.validateDocumentPathLocked(ctx, document, from, to, from != to, false) } -func (tree *AccessibleTree) validate_document_path_locked(ctx context.Context, document DocumentSnapshot, from, to int, requireOrder, tolerateText bool) error { +func (tree *AccessibleTree) validateDocumentPathLocked(ctx context.Context, document DocumentSnapshot, from, to int, requireOrder, tolerateText bool) error { if err := ctx.Err(); err != nil { return err } @@ -145,10 +145,10 @@ func (tree *AccessibleTree) validate_document_path_locked(ctx context.Context, d if err != nil { return err } - if err := document_entry_error_tolerating(entry, tolerateText); err != nil { + if err := documentEntryErrorTolerating(entry, tolerateText); err != nil { return err } - if err := tree.validate_document_row_locked(document, node.Reference.ID(), tolerateText); err != nil { + if err := tree.validateDocumentRowLocked(document, node.Reference.ID(), tolerateText); err != nil { return err } for entry.hasParent { @@ -172,7 +172,7 @@ func (tree *AccessibleTree) validate_document_path_locked(ctx context.Context, d if requireOrder && entry.textInvalid && len(entry.snapshot.TextChildren) != 0 { return ErrStaleText } - if err := tree.validate_document_row_locked(document, entry.snapshot.ID(), tolerateText); err != nil { + if err := tree.validateDocumentRowLocked(document, entry.snapshot.ID(), tolerateText); err != nil { return err } } @@ -180,13 +180,13 @@ func (tree *AccessibleTree) validate_document_path_locked(ctx context.Context, d return nil } -func (tree *AccessibleTree) validate_document_row_locked(document DocumentSnapshot, id ObjectID, tolerateText bool) error { +func (tree *AccessibleTree) validateDocumentRowLocked(document DocumentSnapshot, id ObjectID, tolerateText bool) error { for _, reference := range document.data.rows[id] { entry, err := tree.resolveLocked(reference) if err != nil { return err } - if err := document_entry_error_tolerating(entry, tolerateText); err != nil { + if err := documentEntryErrorTolerating(entry, tolerateText); err != nil { return err } } diff --git a/internal/atspi/entry_name_native.go b/internal/atspi/entry_name_native.go index 10fc1f7..1231cbd 100644 --- a/internal/atspi/entry_name_native.go +++ b/internal/atspi/entry_name_native.go @@ -13,7 +13,7 @@ import "time" // Called by the existing GLib timer. Never sleep in the event callback or // retain a separate native object; stop on focus, foreground or secure changes. -func (adapter *Adapter) refresh_entry_name() { +func (adapter *Adapter) refreshEntryName() { pending := &adapter.entryNameRefresh if !pending.event.Source.ID().Valid() { return diff --git a/internal/atspi/foreground.go b/internal/atspi/foreground.go index f9dfe0a..e20e3ef 100644 --- a/internal/atspi/foreground.go +++ b/internal/atspi/foreground.go @@ -32,7 +32,7 @@ func (adapter *Adapter) SetPreferencesProcess(pid int) { adapter.preferencesPID.Store(int64(pid)) } -func preferences_foreground_matches(client xorg.Foreground, pid int, preferencesPID int64) bool { +func preferencesForegroundMatches(client xorg.Foreground, pid int, preferencesPID int64) bool { return client.Known && client.Window != 0 && preferencesPID > 0 && int64(pid) == preferencesPID && client.PID == pid } diff --git a/internal/atspi/foreground_test.go b/internal/atspi/foreground_test.go index 530864d..70517bc 100644 --- a/internal/atspi/foreground_test.go +++ b/internal/atspi/foreground_test.go @@ -125,7 +125,7 @@ func TestPreferencesForegroundIdentity(t *testing.T) { {"unknown foreground", xorg.Foreground{Window: 45, PID: 123}, 123, 123, false}, } { t.Run(test.name, func(t *testing.T) { - if got := preferences_foreground_matches(test.client, test.pid, test.owned); got != test.want { + if got := preferencesForegroundMatches(test.client, test.pid, test.owned); got != test.want { t.Fatalf("match = %v, want %v", got, test.want) } }) diff --git a/internal/atspi/live_regions.go b/internal/atspi/live_regions.go index fc584fd..080a9f6 100644 --- a/internal/atspi/live_regions.go +++ b/internal/atspi/live_regions.go @@ -35,7 +35,7 @@ func (store *deferredLiveRegionStore) take(object ObjectID) (ObjectID, bool) { return ObjectID{}, false } -func (store *deferredLiveRegionStore) forget_document(document ObjectID) { +func (store *deferredLiveRegionStore) forgetDocument(document ObjectID) { kept := (*store)[:0] for _, entry := range *store { if entry.document != document { diff --git a/internal/atspi/live_regions_native.go b/internal/atspi/live_regions_native.go index b18c8d5..0378ab8 100644 --- a/internal/atspi/live_regions_native.go +++ b/internal/atspi/live_regions_native.go @@ -14,7 +14,7 @@ type nativeLiveProperties struct { atomic, busy bool } -func capture_live_properties(source *C.AtspiAccessible) nativeLiveProperties { +func captureLiveProperties(source *C.AtspiAccessible) nativeLiveProperties { properties := C.cthulhu_capture_live_properties(source) defer C.g_free(C.gpointer(properties.politeness)) return nativeLiveProperties{sanitizeSnapshotField(C.GoString(properties.politeness)), properties.atomic != 0, properties.busy != 0} @@ -22,7 +22,7 @@ func capture_live_properties(source *C.AtspiAccessible) nativeLiveProperties { // Called after foreground filtering. A completion is transformed into a live // insertion so it cannot acquire focus or enter document-loading policy. -func (adapter *Adapter) prepare_live_region(event *C.AtspiEvent, eventType string, origin ObjectID, properties nativeLiveProperties) (deferEvent, complete bool) { +func (adapter *Adapter) prepareLiveRegion(event *C.AtspiEvent, eventType string, origin ObjectID, properties nativeLiveProperties) (deferEvent, complete bool) { if eventType != TextInsertedEvent && eventType != ChildrenAddedEvent && eventType != BusyStateEvent { return false, false } diff --git a/internal/atspi/live_regions_test.go b/internal/atspi/live_regions_test.go index 6e69184..679afe4 100644 --- a/internal/atspi/live_regions_test.go +++ b/internal/atspi/live_regions_test.go @@ -32,7 +32,7 @@ func TestDeferredLiveRegionLifetime(t *testing.T) { t.Fatal("completed update remained deferred") } store.remember(testID("/other_region"), testID("/other_document")) - store.forget_document(testID("/document")) + store.forgetDocument(testID("/document")) if len(store) != 1 || store[0].document != testID("/other_document") { t.Fatal("document retirement retained old entries or removed another document") } diff --git a/internal/atspi/ocr_geometry.go b/internal/atspi/ocr_geometry.go index 4f41cff..4649789 100644 --- a/internal/atspi/ocr_geometry.go +++ b/internal/atspi/ocr_geometry.go @@ -28,7 +28,7 @@ type OCRGeometry struct { // scaling supported by the capture contract. Origins must match either the // physical or uniformly scaled root. Unknown origins are rejected. Use measured // per-axis ratios, not DPI. -func ocr_screen_bounds(bounds, window Rectangle, client xorg.Foreground) (image.Rectangle, error) { +func ocrScreenBounds(bounds, window Rectangle, client xorg.Foreground) (image.Rectangle, error) { if !bounds.Valid() || !window.Valid() || !client.Known || client.Window == 0 { return image.Rectangle{}, ErrOCRGeometry } @@ -44,7 +44,7 @@ func ocr_screen_bounds(bounds, window Rectangle, client xorg.Foreground) (image. } if !matched.Valid() { for _, candidate := range []Rectangle{inner, outer} { - if ocr_window_matches(window, candidate) { + if ocrWindowMatches(window, candidate) { if matched.Valid() && matched != candidate { return image.Rectangle{}, ErrOCRGeometry } @@ -62,17 +62,17 @@ func ocr_screen_bounds(bounds, window Rectangle, client xorg.Foreground) (image. // Use exact integer edge ratios. Provider windows can exceed the OCR image // pixel cap while the chosen object/zone remains a small valid capture. - map_edge := func(value int64, origin, extent, screenOrigin, screenExtent int32, upper bool) int { + mapEdge := func(value int64, origin, extent, screenOrigin, screenExtent int32, upper bool) int { numerator := (value - int64(origin)) * int64(screenExtent) if upper { numerator += int64(extent) - 1 } return int(int64(screenOrigin) + numerator/int64(extent)) } - mapped := image.Rect(map_edge(int64(clipped.X), window.X, window.Width, matched.X, matched.Width, false), - map_edge(int64(clipped.Y), window.Y, window.Height, matched.Y, matched.Height, false), - map_edge(int64(clipped.X)+int64(clipped.Width), window.X, window.Width, matched.X, matched.Width, true), - map_edge(int64(clipped.Y)+int64(clipped.Height), window.Y, window.Height, matched.Y, matched.Height, true)) + mapped := image.Rect(mapEdge(int64(clipped.X), window.X, window.Width, matched.X, matched.Width, false), + mapEdge(int64(clipped.Y), window.Y, window.Height, matched.Y, matched.Height, false), + mapEdge(int64(clipped.X)+int64(clipped.Width), window.X, window.Width, matched.X, matched.Width, true), + mapEdge(int64(clipped.Y)+int64(clipped.Height), window.Y, window.Height, matched.Y, matched.Height, true)) if mapped.Empty() { return image.Rectangle{}, ErrOCRGeometry } @@ -83,7 +83,7 @@ func ocr_screen_bounds(bounds, window Rectangle, client xorg.Foreground) (image. // GTK can scale the root origin as well as dimensions; Chromium may retain // a physical root origin. Admit these two measured contracts only. Other // monitor-dependent origin conventions need separate evidence. -func ocr_window_matches(provider, native Rectangle) bool { +func ocrWindowMatches(provider, native Rectangle) bool { if !provider.Valid() || !native.Valid() { return false } diff --git a/internal/atspi/ocr_geometry_test.go b/internal/atspi/ocr_geometry_test.go index 082c9e0..fcbf857 100644 --- a/internal/atspi/ocr_geometry_test.go +++ b/internal/atspi/ocr_geometry_test.go @@ -33,7 +33,7 @@ func TestOCRProviderCoordinateConversion(t *testing.T) { {name: "ambiguous decoration scale", window: Rectangle{0, 0, 100, 100}, object: Rectangle{0, 0, 20, 20}, client: xorg.Foreground{Known: true, Window: 1, Width: 200, Height: 200, OuterWidth: 202, OuterHeight: 202}, fail: true}, } { t.Run(test.name, func(t *testing.T) { - got, err := ocr_screen_bounds(test.object, test.window, test.client) + got, err := ocrScreenBounds(test.object, test.window, test.client) if test.fail { if err == nil { t.Fatalf("accepted ambiguous bounds: %v", got) diff --git a/internal/atspi/panel_applet_native_test.go b/internal/atspi/panel_applet_native_test.go index 8735f29..99865d2 100644 --- a/internal/atspi/panel_applet_native_test.go +++ b/internal/atspi/panel_applet_native_test.go @@ -23,11 +23,11 @@ func TestNativeEmbeddedPanelApplet(t *testing.T) { // Embedding belongs to the window ancestry contract, not a process-name // exception. Both MATE and an ordinary GTK host must retain ownership. for _, hostName := range []string{"panel", "other-host"} { - t.Run(hostName, func(t *testing.T) { check_native_embedded_applet(t, hostName) }) + t.Run(hostName, func(t *testing.T) { checkNativeEmbeddedApplet(t, hostName) }) } } -func check_native_embedded_applet(t *testing.T, hostName string) { +func checkNativeEmbeddedApplet(t *testing.T, hostName string) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() diff --git a/internal/atspi/panel_menu_native_test.go b/internal/atspi/panel_menu_native_test.go index aa4bf00..5fbbd14 100644 --- a/internal/atspi/panel_menu_native_test.go +++ b/internal/atspi/panel_menu_native_test.go @@ -35,12 +35,12 @@ func TestNativeMatePanelMenuOutsideForeground(t *testing.T) { {"attached impostor", "impostor", false, true, false}, } { t.Run(test.name, func(t *testing.T) { - check_native_panel_menu(t, test.processName, test.empty, test.attached, test.bottom) + checkNativePanelMenu(t, test.processName, test.empty, test.attached, test.bottom) }) } } -func check_native_panel_menu(t *testing.T, processName string, empty, attached, bottom bool) { +func checkNativePanelMenu(t *testing.T, processName string, empty, attached, bottom bool) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() @@ -82,7 +82,7 @@ func check_native_panel_menu(t *testing.T, processName string, empty, attached, if err != nil { t.Fatal(err) } - check_native_panel_icons(t, tree) + checkNativePanelIcons(t, tree) key := func(args ...string) { t.Helper() if output, err := exec.CommandContext(ctx, "xdotool", args...).CombinedOutput(); err != nil { @@ -194,7 +194,7 @@ func check_native_panel_menu(t *testing.T, processName string, empty, attached, } } -func check_native_panel_icons(t *testing.T, tree *AccessibleTree) { +func checkNativePanelIcons(t *testing.T, tree *AccessibleTree) { t.Helper() tree.mu.RLock() defer tree.mu.RUnlock() diff --git a/internal/atspi/preferences_native_test.go b/internal/atspi/preferences_native_test.go index 5286995..d82683c 100644 --- a/internal/atspi/preferences_native_test.go +++ b/internal/atspi/preferences_native_test.go @@ -112,7 +112,7 @@ func TestNativePreferencesDropdownEscape(t *testing.T) { if err := json.NewEncoder(in).Encode(initial); err != nil { t.Fatal(err) } - wait_event := func(timeout time.Duration, match func(Event) bool) Event { + waitEvent := func(timeout time.Duration, match func(Event) bool) Event { t.Helper() timer := time.NewTimer(timeout) defer timer.Stop() @@ -144,7 +144,7 @@ func TestNativePreferencesDropdownEscape(t *testing.T) { return event.Type == FocusedStateEvent && event.Detail1 == 1 && event.Source.Name == name } } - wait_event(5*time.Second, func(event Event) bool { return event.Type == WindowActivatedEvent }) + waitEvent(5*time.Second, func(event Event) bool { return event.Type == WindowActivatedEvent }) xdotool := func(args ...string) string { t.Helper() output, err := exec.CommandContext(ctx, "xdotool", args...).CombinedOutput() @@ -155,7 +155,7 @@ func TestNativePreferencesDropdownEscape(t *testing.T) { } window := xdotool("search", "--onlyvisible", "--name", "^Cthulhu Preferences$") xdotool("windowfocus", window) - capture_review := func(name, wantName string, focus ObjectID) { + captureReview := func(name, wantName string, focus ObjectID) { t.Helper() captureCtx, stop := context.WithTimeout(ctx, 2*time.Second) defer stop() @@ -185,57 +185,57 @@ func TestNativePreferencesDropdownEscape(t *testing.T) { } // Match the reported workflow: focus the General tab header itself. xdotool("key", "ctrl+Page_Down", "ctrl+Page_Up") - general := wait_event(5*time.Second, focused("General")) - capture_review("General", "Desktop", general.Source.ID()) + general := waitEvent(5*time.Second, focused("General")) + captureReview("General", "Desktop", general.Source.ID()) xdotool("key", "ctrl+Page_Down", "ctrl+Page_Down") - speech := wait_event(5*time.Second, focused("Speech")) - capture_review("Speech", "Enable speech", speech.Source.ID()) + speech := waitEvent(5*time.Second, focused("Speech")) + captureReview("Speech", "Enable speech", speech.Source.ID()) xdotool("key", "Tab", "Tab") - wait_event(5*time.Second, focused("Speech system")) + waitEvent(5*time.Second, focused("Speech system")) xdotool("key", "alt+Down") - popup := wait_event(5*time.Second, focused("Speech Dispatcher")) - capture_review("open dropdown", "Speech Dispatcher", popup.Source.ID()) + popup := waitEvent(5*time.Second, focused("Speech Dispatcher")) + captureReview("open dropdown", "Speech Dispatcher", popup.Source.ID()) xdotool("key", "Escape") - combo := wait_event(1500*time.Millisecond, focused("Speech system")) - capture_review("closed dropdown", "Speech system", combo.Source.ID()) + combo := waitEvent(1500*time.Millisecond, focused("Speech system")) + captureReview("closed dropdown", "Speech system", combo.Source.ID()) xdotool("key", "alt+Down") - popup = wait_event(5*time.Second, focused("Speech Dispatcher")) - capture_review("reopened dropdown", "Speech Dispatcher", popup.Source.ID()) + popup = waitEvent(5*time.Second, focused("Speech Dispatcher")) + captureReview("reopened dropdown", "Speech Dispatcher", popup.Source.ID()) xdotool("key", "Escape") - wait_event(1500*time.Millisecond, focused("Speech system")) + waitEvent(1500*time.Millisecond, focused("Speech system")) xdotool("key", "ctrl+Page_Up", "ctrl+Page_Up") - general = wait_event(5*time.Second, focused("Desktop")) - capture_review("returned General", "Desktop", general.Source.ID()) + general = waitEvent(5*time.Second, focused("Desktop")) + captureReview("returned General", "Desktop", general.Source.ID()) xdotool("key", "shift+Tab") - wait_event(5*time.Second, focused("General")) + waitEvent(5*time.Second, focused("General")) xdotool("key", "--clearmodifiers", "ctrl+Page_Down", "ctrl+Page_Down") - wait_event(5*time.Second, focused("Speech")) + waitEvent(5*time.Second, focused("Speech")) xdotool("key", "Tab", "Tab") - wait_event(5*time.Second, focused("Speech system")) + waitEvent(5*time.Second, focused("Speech system")) xdotool("key", "alt+Down") - wait_event(5*time.Second, focused("Speech Dispatcher")) + waitEvent(5*time.Second, focused("Speech Dispatcher")) started := time.Now() xdotool("key", "Escape") - wait_event(1500*time.Millisecond, focused("Speech system")) + waitEvent(1500*time.Millisecond, focused("Speech system")) t.Logf("dropdown Escape restored focus in %s", time.Since(started)) xdotool("key", "Tab") - wait_event(1500*time.Millisecond, focused("Speech synthesizer")) + waitEvent(1500*time.Millisecond, focused("Speech synthesizer")) xdotool("key", "alt+Down") - wait_event(5*time.Second, focused("Default")) + waitEvent(5*time.Second, focused("Default")) xdotool("key", "Escape") - wait_event(1500*time.Millisecond, focused("Speech synthesizer")) + waitEvent(1500*time.Millisecond, focused("Speech synthesizer")) if largeCatalog { xdotool("key", "Down") } xdotool("key", "Tab") - wait_event(1500*time.Millisecond, focused("Language")) + waitEvent(1500*time.Millisecond, focused("Language")) if largeCatalog { xdotool("key", "Tab") - wait_event(1500*time.Millisecond, focused("Person")) + waitEvent(1500*time.Millisecond, focused("Person")) xdotool("key", "alt+Down") - wait_event(1500*time.Millisecond, focused("Default")) + waitEvent(1500*time.Millisecond, focused("Default")) xdotool("key", "Escape") - wait_event(1500*time.Millisecond, focused("Person")) + waitEvent(1500*time.Millisecond, focused("Person")) } xdotool("key", "Escape") select { diff --git a/internal/atspi/replaced_feed_native_test.go b/internal/atspi/replaced_feed_native_test.go index eda64b7..a041d5a 100644 --- a/internal/atspi/replaced_feed_native_test.go +++ b/internal/atspi/replaced_feed_native_test.go @@ -96,7 +96,7 @@ func TestNativeBrowserMissingFeedRefreshesWholeBranch(t *testing.T) { if restoreErr := tree.Replace(root.ID(), oldNodes); restoreErr != nil { t.Fatal(restoreErr) } - if replayErr := adapter.document_object_error(missing.ID(), err); !errors.Is(replayErr, ErrDeadObject) { + if replayErr := adapter.documentObjectError(missing.ID(), err); !errors.Is(replayErr, ErrDeadObject) { t.Fatal(replayErr) } tree, err = adapter.CaptureDocument(ctx, start.ID()) diff --git a/internal/atspi/review_cache_native_test.go b/internal/atspi/review_cache_native_test.go index 9291a6c..601cc00 100644 --- a/internal/atspi/review_cache_native_test.go +++ b/internal/atspi/review_cache_native_test.go @@ -26,21 +26,21 @@ func TestNativeFlatReviewPreservesProviderCache(t *testing.T) { if os.Getenv("CTHULHU_NATIVE_REVIEW_CACHE") != "1" { t.Skip("requires private Xvfb/AT-SPI session") } - test_native_review_provider(t, "cache") + testNativeReviewProvider(t, "cache") } func TestNativeFlatReviewBoundsSlowLongRanges(t *testing.T) { if os.Getenv("CTHULHU_NATIVE_REVIEW_BOUNDS") != "1" { t.Skip("requires private Xvfb/AT-SPI session") } - test_native_review_provider(t, "bounds") + testNativeReviewProvider(t, "bounds") } func TestNativeFlatReviewClippedViewport(t *testing.T) { if os.Getenv("CTHULHU_NATIVE_REVIEW_CLIPPED") != "1" { t.Skip("requires private Xvfb/AT-SPI session") } - test_native_review_provider(t, "clipped") + testNativeReviewProvider(t, "clipped") } func TestNativeFlatReviewLargeTextViewport(t *testing.T) { @@ -52,24 +52,24 @@ func TestNativeFlatReviewLargeTextViewport(t *testing.T) { if mode != "lines" && mode != "long" { t.Fatal("set viewport mode to lines or long") } - test_native_review_provider(t, mode) + testNativeReviewProvider(t, mode) } func TestNativeFlatReviewUnavailableSubtree(t *testing.T) { if os.Getenv("CTHULHU_NATIVE_REVIEW_SUBTREE") != "1" { t.Skip("requires private Xvfb/AT-SPI session") } - test_native_review_provider(t, "children") + testNativeReviewProvider(t, "children") } func TestNativeFlatReviewZeroAreaGlyph(t *testing.T) { if os.Getenv("CTHULHU_NATIVE_REVIEW_GLYPHS") != "1" { t.Skip("requires private Xvfb/AT-SPI session") } - test_native_review_provider(t, "glyphs") + testNativeReviewProvider(t, "glyphs") } -func test_native_review_provider(t *testing.T, mode string) { +func testNativeReviewProvider(t *testing.T, mode string) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() diff --git a/internal/atspi/review_table_native.go b/internal/atspi/review_table_native.go index 7c49e34..0f9d812 100644 --- a/internal/atspi/review_table_native.go +++ b/internal/atspi/review_table_native.go @@ -14,11 +14,11 @@ import ( "fmt" ) -// native_review_table_children enumerates a selectable table's viewport, as +// nativeReviewTableChildren enumerates a selectable table's viewport, as // Orca's flat review does. GTK exposes every offscreen row as a child; fetching // that list creates thousands of transient cell proxies during timeline refresh. // Returned references belong to the caller. All queries run on the GLib owner. -func native_review_table_children(ctx context.Context, source *C.AtspiAccessible, clip Rectangle) (children []*C.AtspiAccessible, handled bool, err error) { +func nativeReviewTableChildren(ctx context.Context, source *C.AtspiAccessible, clip Rectangle) (children []*C.AtspiAccessible, handled bool, err error) { if !clip.Valid() { return nil, false, nil } diff --git a/internal/atspi/review_table_native_test.go b/internal/atspi/review_table_native_test.go index 9003d18..52f95f6 100644 --- a/internal/atspi/review_table_native_test.go +++ b/internal/atspi/review_table_native_test.go @@ -17,11 +17,11 @@ func TestNativeFlatReviewLargeGTKTable(t *testing.T) { t.Skip("requires private Xvfb/AT-SPI session") } for _, mode := range []string{"large", "small", "empty", "horizontal", "compound"} { - t.Run(mode, func(t *testing.T) { test_native_review_table(t, mode) }) + t.Run(mode, func(t *testing.T) { testNativeReviewTable(t, mode) }) } } -func test_native_review_table(t *testing.T, mode string) { +func testNativeReviewTable(t *testing.T, mode string) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) defer cancel() diff --git a/internal/atspi/speech_metadata_native.go b/internal/atspi/speech_metadata_native.go index a64aa96..577a7bb 100644 --- a/internal/atspi/speech_metadata_native.go +++ b/internal/atspi/speech_metadata_native.go @@ -15,7 +15,7 @@ import ( "unsafe" ) -func native_mnemonic(source *C.AtspiAccessible) string { +func nativeMnemonic(source *C.AtspiAccessible) string { action := C.atspi_accessible_get_action_iface(source) if action == nil { return "" @@ -35,12 +35,12 @@ func native_mnemonic(source *C.AtspiAccessible) string { return sanitizeSnapshotField(parts[0]) } -func native_misspelled(text *C.AtspiText, offset int) bool { - run := native_text_attribute_run(text, offset) +func nativeMisspelled(text *C.AtspiText, offset int) bool { + run := nativeTextAttributeRun(text, offset) return TextAttributesMisspelled(run.Values) } -func native_text_attribute_run(text *C.AtspiText, offset int) TextAttributeRun { +func nativeTextAttributeRun(text *C.AtspiText, offset int) TextAttributeRun { if offset < 0 { return TextAttributeRun{} } @@ -64,7 +64,7 @@ func native_text_attribute_run(text *C.AtspiText, offset int) TextAttributeRun { // Each provider request can block. Stop after a bounded number of runs and a // short deadline; the caret run is still available if a provider is slow. -func native_text_attribute_runs(text *C.AtspiText, start, end int, caret TextAttributeRun) []TextAttributeRun { +func nativeTextAttributeRuns(text *C.AtspiText, start, end int, caret TextAttributeRun) []TextAttributeRun { if start < 0 || end <= start { return nil } @@ -73,7 +73,7 @@ func native_text_attribute_runs(text *C.AtspiText, start, end int, caret TextAtt for offset := start; offset < end && len(runs) < 32 && time.Now().Before(deadline); { run := caret if offset < run.Start || offset >= run.End { - run = native_text_attribute_run(text, offset) + run = nativeTextAttributeRun(text, offset) } if run.End <= offset { break @@ -86,7 +86,7 @@ func native_text_attribute_runs(text *C.AtspiText, start, end int, caret TextAtt // Queries stay on the GLib owner. This copies only container metadata, bounded // by depth and time, and never scans children or retains native references. -func native_speech_context(source *C.AtspiAccessible) ([]Snapshot, []Snapshot) { +func nativeSpeechContext(source *C.AtspiAccessible) ([]Snapshot, []Snapshot) { result := make([]Snapshot, 0) brailleContext := make([]Snapshot, 0) speechOpen := true diff --git a/internal/atspi/tentacle_item_native.go b/internal/atspi/tentacle_item_native.go index c46b937..3c5b22d 100644 --- a/internal/atspi/tentacle_item_native.go +++ b/internal/atspi/tentacle_item_native.go @@ -25,7 +25,7 @@ func (adapter *Adapter) ReadTransferItem(ctx context.Context, object ObjectID, o return result.item, err } func (adapter *Adapter) nativeTransferItem(ctx context.Context, object ObjectID, offset int) (TransferItem, error) { - source, _, err := adapter.native_action_source(object) + source, _, err := adapter.nativeActionSource(object) if err != nil || ctx.Err() != nil { return TransferItem{}, ErrStaleObject } diff --git a/internal/atspi/text.go b/internal/atspi/text.go index 2236979..e1e6bda 100644 --- a/internal/atspi/text.go +++ b/internal/atspi/text.go @@ -147,11 +147,11 @@ type reviewViewportSource interface { viewport(context.Context, int, int, Rectangle) ([]TextRange, error) } -// bounded_review_bounds preserves the full range's bounding rectangle without +// boundedReviewBounds preserves the full range's bounding rectangle without // asking a provider to measure thousands of characters in one synchronous call. // GTK text cells can exceed libatspi's timeout on such requests. Union every // chunk rather than inferring bounds from endpoints, which would lose bidi runs. -func bounded_review_bounds(ctx context.Context, start, end int, query func(context.Context, int, int) (Rectangle, error)) (Rectangle, error) { +func boundedReviewBounds(ctx context.Context, start, end int, query func(context.Context, int, int) (Rectangle, error)) (Rectangle, error) { var bounds Rectangle for offset := start; offset < end; { if err := ctx.Err(); err != nil { @@ -234,14 +234,14 @@ func captureVisibleText(ctx context.Context, source reviewTextSource, clip Recta if ctx.Err() != nil { return unknown, ctx.Err() } - start, end, err = visible_line_offsets(ctx, source, count, clip) + start, end, err = visibleLineOffsets(ctx, source, count, clip) } if err != nil { if ctx.Err() != nil { return unknown, ctx.Err() } if count > maxReviewCharacters { - return capture_review_viewport(ctx, source, count, clip, TextViewportUnavailable) + return captureReviewViewport(ctx, source, count, clip, TextViewportUnavailable) } // Some otherwise usable GTK text providers do not expose per-character // extents. Retain the established bounded line capture for those small @@ -252,7 +252,7 @@ func captureVisibleText(ctx context.Context, source reviewTextSource, clip Recta if spatial, ok := source.(reviewViewportSource); ok { ranges, spatialErr := spatial.viewport(ctx, start, end, clip) if spatialErr == nil && len(ranges) > 0 { - return capture_review_lines(ctx, source, count, 0, count, clip, ranges) + return captureReviewLines(ctx, source, count, 0, count, clip, ranges) } if errors.Is(spatialErr, errReviewViewportScanLimit) { return VisibleText{Limited: true, Issue: TextViewportScanLimit}, ctx.Err() @@ -265,16 +265,16 @@ func captureVisibleText(ctx context.Context, source reviewTextSource, clip Recta if end-start > maxReviewCharacters { return VisibleText{Limited: true, Issue: TextCharacterLimit}, nil } - return capture_review_lines(ctx, source, count, start, end, clip, nil) + return captureReviewLines(ctx, source, count, start, end, clip, nil) } -func capture_review_lines(ctx context.Context, source reviewTextSource, count, start, end int, clip Rectangle, spatial []TextRange) (VisibleText, error) { +func captureReviewLines(ctx context.Context, source reviewTextSource, count, start, end int, clip Rectangle, spatial []TextRange) (VisibleText, error) { unknown := VisibleText{} if spatial != nil { - if err := validate_viewport_ranges(spatial, count); err != nil { + if err := validateViewportRanges(spatial, count); err != nil { return unknown, err } - spatial = split_viewport_lines(spatial) + spatial = splitViewportLines(spatial) } result := VisibleText{Known: true} characters := 0 @@ -300,7 +300,7 @@ func capture_review_lines(ctx context.Context, source reviewTextSource, count, s line, err = source.line(ctx, offset) } if errors.Is(err, errReviewLineTooLong) { - return capture_review_viewport(ctx, source, count, clip, TextCharacterLimit) + return captureReviewViewport(ctx, source, count, clip, TextCharacterLimit) } if err != nil { return unknown, err @@ -404,7 +404,7 @@ func capture_review_lines(ctx context.Context, source reviewTextSource, count, s return unknown, err } charClip, ok := charBounds.Intersection(clip) - if !charBounds.Valid() && spanEnd == i && spanStart >= 0 && review_cluster_continuation(runes[i]) { + if !charBounds.Valid() && spanEnd == i && spanStart >= 0 && reviewClusterContinuation(runes[i]) { // Combining marks and joiners belong to the visible base // even when they have no independent glyph rectangle. charClip, ok = spanBounds, true @@ -440,7 +440,7 @@ func capture_review_lines(ctx context.Context, source reviewTextSource, count, s return result, ctx.Err() } -func review_cluster_continuation(character rune) bool { +func reviewClusterContinuation(character rune) bool { return unicode.IsMark(character) || character == '\u200c' || character == '\u200d' } @@ -500,11 +500,11 @@ func searchTextOffset(ctx context.Context, source reviewTextSource, count int, a return low, nil } -// recover_review_component distinguishes synthetic Text interfaces from failed +// recoverReviewComponent distinguishes synthetic Text interfaces from failed // text-bearing objects. It never invents offsets or uses editable values as names. // A label is usable only when it exactly matches the bounded native text and the // component is fully inside the clip. Embedded-only text belongs to children. -func recover_review_component(ctx context.Context, source interface { +func recoverReviewComponent(ctx context.Context, source interface { reviewTextSource reviewSpanSource }, snapshot Snapshot, geometry Geometry, clip Rectangle) (VisibleText, bool) { @@ -527,7 +527,7 @@ func recover_review_component(ctx context.Context, source interface { var content strings.Builder for start := 0; start < count; { end := start + min(count-start, maxReviewBoundsCharacters) - span, err := source.text_span(ctx, start, end) + span, err := source.textSpan(ctx, start, end) if err != nil || !utf8.ValidString(span) || utf8.RuneCountInString(span) != end-start { return VisibleText{}, false } diff --git a/internal/atspi/text_bounds_test.go b/internal/atspi/text_bounds_test.go index 02591c9..af02394 100644 --- a/internal/atspi/text_bounds_test.go +++ b/internal/atspi/text_bounds_test.go @@ -22,7 +22,7 @@ func (source *longReviewText) line(context.Context, int) (TextRange, error) { return TextRange{Start: 0, End: len(source.runes), Text: string(source.runes)}, nil } func (source *longReviewText) bounds(ctx context.Context, start, end int) (Rectangle, error) { - return bounded_review_bounds(ctx, start, end, func(_ context.Context, first, last int) (Rectangle, error) { + return boundedReviewBounds(ctx, start, end, func(_ context.Context, first, last int) (Rectangle, error) { source.queries++ source.largest = max(source.largest, last-first) if last-first > 128 { @@ -57,7 +57,7 @@ func TestCaptureVisibleTextBoundsLongHorizontalLine(t *testing.T) { func TestBoundedReviewBoundsIncludesInteriorAndEmptyChunks(t *testing.T) { rectangles := []Rectangle{{X: 500, Width: 100, Height: 20}, {X: -50, Width: 300, Height: 20}, {}, {X: 400, Width: 50, Height: 20}} queries := 0 - got, err := bounded_review_bounds(context.Background(), 0, 512, func(_ context.Context, start, end int) (Rectangle, error) { + got, err := boundedReviewBounds(context.Background(), 0, 512, func(_ context.Context, start, end int) (Rectangle, error) { if end-start > 128 { t.Fatalf("oversized query: %d", end-start) } @@ -71,7 +71,7 @@ func TestBoundedReviewBoundsIncludesInteriorAndEmptyChunks(t *testing.T) { func TestBoundedReviewBoundsStopsOnFailureOrCancellation(t *testing.T) { providerError := errors.New("provider unavailable") - if _, err := bounded_review_bounds(context.Background(), 0, 512, func(context.Context, int, int) (Rectangle, error) { + if _, err := boundedReviewBounds(context.Background(), 0, 512, func(context.Context, int, int) (Rectangle, error) { return Rectangle{}, providerError }); !errors.Is(err, providerError) { t.Fatalf("provider error hidden: %v", err) @@ -79,7 +79,7 @@ func TestBoundedReviewBoundsStopsOnFailureOrCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() queries := 0 - _, err := bounded_review_bounds(ctx, 0, 512, func(context.Context, int, int) (Rectangle, error) { + _, err := boundedReviewBounds(ctx, 0, 512, func(context.Context, int, int) (Rectangle, error) { queries++ cancel() return Rectangle{Width: 100, Height: 20}, nil diff --git a/internal/atspi/text_component_test.go b/internal/atspi/text_component_test.go index 86e2f0e..c4104b3 100644 --- a/internal/atspi/text_component_test.go +++ b/internal/atspi/text_component_test.go @@ -40,13 +40,13 @@ func TestReviewComponentRecoveryRequiresVerifiedContent(t *testing.T) { if tc.clipped { geometry.Bounds.Width++ } - got, ok := recover_review_component(context.Background(), source, Snapshot{Role: tc.role, Name: tc.label, Editable: tc.editable}, geometry, clip) + got, ok := recoverReviewComponent(context.Background(), source, Snapshot{Role: tc.role, Name: tc.label, Editable: tc.editable}, geometry, clip) if ok != tc.want || got.Known != tc.known || len(got.Ranges) != 0 || got.CaretKnown { t.Fatalf("recovery = %+v, %v", got, ok) } ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, ok := recover_review_component(ctx, source, Snapshot{Role: tc.role, Name: tc.label}, geometry, clip); ok { + if _, ok := recoverReviewComponent(ctx, source, Snapshot{Role: tc.role, Name: tc.label}, geometry, clip); ok { t.Fatal("recovered canceled request") } }) diff --git a/internal/atspi/text_input_native.go b/internal/atspi/text_input_native.go index b2ca54b..d28dae6 100644 --- a/internal/atspi/text_input_native.go +++ b/internal/atspi/text_input_native.go @@ -29,7 +29,7 @@ func (adapter *Adapter) TypeText(ctx context.Context, text string) error { _, err := adapter.documentOperation(ctx, treeCaptureRequest{typeText: true, insertionText: text}) return err } -func (adapter *Adapter) native_type_text(ctx context.Context, text string) error { +func (adapter *Adapter) nativeTypeText(ctx context.Context, text string) error { if ctx.Err() != nil { return ctx.Err() } diff --git a/internal/atspi/text_native.go b/internal/atspi/text_native.go index 8f6b154..2d62513 100644 --- a/internal/atspi/text_native.go +++ b/internal/atspi/text_native.go @@ -235,10 +235,10 @@ func (source nativeReviewText) line(ctx context.Context, offset int) (TextRange, } func (source nativeReviewText) viewport(ctx context.Context, start, end int, clip Rectangle) ([]TextRange, error) { - return point_review_viewport(ctx, source, start, end, clip) + return pointReviewViewport(ctx, source, start, end, clip) } -func (source nativeReviewText) offset_at_point(ctx context.Context, x, y int32) (int, error) { +func (source nativeReviewText) offsetAtPoint(ctx context.Context, x, y int32) (int, error) { if err := ctx.Err(); err != nil { return 0, err } @@ -251,7 +251,7 @@ func (source nativeReviewText) offset_at_point(ctx context.Context, x, y int32) return int(offset), ctx.Err() } -func (source nativeReviewText) text_span(ctx context.Context, start, end int) (string, error) { +func (source nativeReviewText) textSpan(ctx context.Context, start, end int) (string, error) { if err := ctx.Err(); err != nil { return "", err } @@ -279,14 +279,14 @@ func (source nativeReviewText) text_span(ctx context.Context, start, end int) (s } func (source nativeReviewText) bounds(ctx context.Context, start, end int) (Rectangle, error) { - rect, err := bounded_review_bounds(ctx, start, end, source.range_bounds) + rect, err := boundedReviewBounds(ctx, start, end, source.rangeBounds) if err != nil { return Rectangle{}, err } return rect, ctx.Err() } -func (source nativeReviewText) range_bounds(ctx context.Context, start, end int) (Rectangle, error) { +func (source nativeReviewText) rangeBounds(ctx context.Context, start, end int) (Rectangle, error) { if err := ctx.Err(); err != nil { return Rectangle{}, err } @@ -343,12 +343,12 @@ func textFromNative(ctx context.Context, accessible *C.AtspiAccessible, geometry // Some providers advertise Text on component-only controls and // containers. Verify their bounded content before allowing the // established accessible-name/child-content path to handle them. - if recovered, ok := recover_review_component(ctx, source, snapshot, geometry, clip); ok { + if recovered, ok := recoverReviewComponent(ctx, source, snapshot, geometry, clip); ok { result = recovered } } if result.Issue != "" { - capture_diagnostics(ctx).text_issue(result.Issue) + captureDiagnosticsFrom(ctx).textIssue(result.Issue) } if result.Known && ctx.Err() == nil { var nativeErr *C.GError diff --git a/internal/atspi/text_viewport.go b/internal/atspi/text_viewport.go index 3bfdf5d..afb042e 100644 --- a/internal/atspi/text_viewport.go +++ b/internal/atspi/text_viewport.go @@ -16,27 +16,27 @@ var errReviewViewportScanLimit = errors.New("review viewport scan limit") type reviewSpanSource interface { bounds(context.Context, int, int) (Rectangle, error) - text_span(context.Context, int, int) (string, error) + textSpan(context.Context, int, int) (string, error) } type reviewPointSource interface { reviewSpanSource - offset_at_point(context.Context, int32, int32) (int, error) + offsetAtPoint(context.Context, int32, int32) (int, error) } // Walk visible glyph rectangles rather than logical offsets. Logical offsets // need not increase left-to-right (bidi), and a single line can be enormous. // Check every intervening pixel when a provider cannot identify a glyph. A // finite query budget rejects sparse or defective providers without omissions. -func point_review_viewport(ctx context.Context, source reviewPointSource, start, end int, clip Rectangle) ([]TextRange, error) { +func pointReviewViewport(ctx context.Context, source reviewPointSource, start, end int, clip Rectangle) ([]TextRange, error) { if end <= start { return nil, nil } - first, err := review_endpoint_bounds(ctx, source, start, end, false) + first, err := reviewEndpointBounds(ctx, source, start, end, false) if err != nil { return nil, err } - last, err := review_endpoint_bounds(ctx, source, start, end, true) + last, err := reviewEndpointBounds(ctx, source, start, end, true) if err != nil { return nil, err } @@ -57,7 +57,7 @@ func point_review_viewport(ctx context.Context, source reviewPointSource, start, return nil, errReviewViewportScanLimit } queries++ - offset, err := source.offset_at_point(ctx, int32(x), int32(y)) + offset, err := source.offsetAtPoint(ctx, int32(x), int32(y)) if err != nil { return nil, err } @@ -106,7 +106,7 @@ func point_review_viewport(ctx context.Context, source reviewPointSource, start, next++ } last := ordered[next-1] + 1 - content, err := source.text_span(ctx, first, last) + content, err := source.textSpan(ctx, first, last) if err != nil { return nil, err } @@ -117,12 +117,12 @@ func point_review_viewport(ctx context.Context, source reviewPointSource, start, limit = min(limit, ordered[next]) } if last < limit { - tail, err := source.text_span(ctx, last, limit) + tail, err := source.textSpan(ctx, last, limit) if err != nil { return nil, err } for _, character := range tail { - if !review_cluster_continuation(character) { + if !reviewClusterContinuation(character) { break } bounds, err := source.bounds(ctx, last, last+1) @@ -136,12 +136,12 @@ func point_review_viewport(ctx context.Context, source reviewPointSource, start, last++ } if last == limit && limit < end && (next == len(ordered) || limit < ordered[next]) { - following, err := source.text_span(ctx, last, last+1) + following, err := source.textSpan(ctx, last, last+1) if err != nil { return nil, err } for _, character := range following { - if review_cluster_continuation(character) { + if reviewClusterContinuation(character) { return nil, errReviewViewportScanLimit } } @@ -156,7 +156,7 @@ func point_review_viewport(ctx context.Context, source reviewPointSource, start, // Trailing newlines and formatting characters can have no glyph rectangle. // Look only within a bounded edge block, rather than discarding a long line // or scanning arbitrary offscreen text to find an endpoint. -func review_endpoint_bounds(ctx context.Context, source reviewSpanSource, start, end int, backwards bool) (Rectangle, error) { +func reviewEndpointBounds(ctx context.Context, source reviewSpanSource, start, end int, backwards bool) (Rectangle, error) { for index := 0; index < min(end-start, maxReviewBoundsCharacters); index++ { if err := ctx.Err(); err != nil { return Rectangle{}, err @@ -179,7 +179,7 @@ func review_endpoint_bounds(ctx context.Context, source reviewSpanSource, start, // Line rectangles can be usable when single-character extents are missing. // Move by complete line boundaries on each binary-search step; never scan // scrollback or accept a non-progressing/provider-clamped line as a match. -func visible_line_offsets(ctx context.Context, source reviewTextSource, count int, clip Rectangle) (int, int, error) { +func visibleLineOffsets(ctx context.Context, source reviewTextSource, count int, clip Rectangle) (int, int, error) { if !clip.Valid() { return 0, 0, errors.New("invalid review text clip") } @@ -227,14 +227,14 @@ func visible_line_offsets(ctx context.Context, source reviewTextSource, count in return start, end, err } -func capture_review_viewport(ctx context.Context, source reviewTextSource, count int, clip Rectangle, reason TextCaptureIssue) (VisibleText, error) { +func captureReviewViewport(ctx context.Context, source reviewTextSource, count int, clip Rectangle, reason TextCaptureIssue) (VisibleText, error) { if spatial, ok := source.(reviewViewportSource); ok { ranges, err := spatial.viewport(ctx, 0, count, clip) if ctx.Err() != nil { return VisibleText{}, ctx.Err() } if err == nil && len(ranges) > 0 { - return capture_review_lines(ctx, source, count, 0, count, clip, ranges) + return captureReviewLines(ctx, source, count, 0, count, clip, ranges) } if errors.Is(err, errReviewViewportScanLimit) { reason = TextViewportScanLimit @@ -245,7 +245,7 @@ func capture_review_viewport(ctx context.Context, source reviewTextSource, count // Validate all spatial output before accepting any of it. Native offsets can // be large, but the amount of copied text and the number of spans cannot. -func validate_viewport_ranges(ranges []TextRange, count int) error { +func validateViewportRanges(ranges []TextRange, count int) error { if len(ranges) > maxReviewRanges { return errors.New("review viewport range limit") } @@ -265,7 +265,7 @@ func validate_viewport_ranges(ranges []TextRange, count int) error { // Provider spatial ranges need not stop at line breaks. Split without making // another whole-line native request; wrapping is handled by glyph geometry. -func split_viewport_lines(ranges []TextRange) []TextRange { +func splitViewportLines(ranges []TextRange) []TextRange { var lines []TextRange for _, span := range ranges { start := span.Start diff --git a/internal/atspi/text_viewport_test.go b/internal/atspi/text_viewport_test.go index 3624903..c26cd83 100644 --- a/internal/atspi/text_viewport_test.go +++ b/internal/atspi/text_viewport_test.go @@ -104,7 +104,7 @@ type pointReviewText struct { textByOffset map[int]string } -func (source *pointReviewText) offset_at_point(ctx context.Context, x, y int32) (int, error) { +func (source *pointReviewText) offsetAtPoint(ctx context.Context, x, y int32) (int, error) { source.pointCalls++ for span, bounds := range source.rectangles { if span[1]-span[0] == 1 && int64(x) >= int64(bounds.X) && int64(x) < int64(bounds.X)+int64(bounds.Width) && int64(y) >= int64(bounds.Y) && int64(y) < int64(bounds.Y)+int64(bounds.Height) { @@ -113,7 +113,7 @@ func (source *pointReviewText) offset_at_point(ctx context.Context, x, y int32) } return -1, ctx.Err() } -func (source *pointReviewText) text_span(ctx context.Context, start, end int) (string, error) { +func (source *pointReviewText) textSpan(ctx context.Context, start, end int) (string, error) { var text strings.Builder for offset := start; offset < end; offset++ { character, ok := source.textByOffset[offset] @@ -130,7 +130,7 @@ func TestPointReviewViewportKeepsDisjointBidiOffsets(t *testing.T) { {0, 1}: {-100, 0, 10, 10}, {99999, 100000}: {100, 0, 10, 10}, {10, 11}: {30, 0, 10, 10}, {70000, 70001}: {10, 0, 10, 10}, {80000, 80001}: {20, 0, 10, 10}, }}, textByOffset: map[int]string{10: "א", 70000: "猫", 80000: "é"}} - ranges, err := point_review_viewport(context.Background(), source, 0, 100000, Rectangle{X: 10, Width: 30, Height: 10}) + ranges, err := pointReviewViewport(context.Background(), source, 0, 100000, Rectangle{X: 10, Width: 30, Height: 10}) if err != nil || len(ranges) != 3 || source.pointCalls != 3 { t.Fatalf("point bidi = %+v, %v; calls=%d", ranges, err, source.pointCalls) } @@ -145,7 +145,7 @@ func TestPointReviewViewportDoesNotSkipVerticallyInsetGlyph(t *testing.T) { source := &pointReviewText{fakeReviewText: fakeReviewText{rectangles: map[[2]int]Rectangle{ {0, 1}: {0, 0, 10, 20}, {1, 2}: {10, 5, 10, 10}, {2, 3}: {20, 0, 10, 20}, }}, textByOffset: map[int]string{0: "A", 1: "é", 2: "B"}} - ranges, err := point_review_viewport(context.Background(), source, 0, 3, Rectangle{Width: 30, Height: 20}) + ranges, err := pointReviewViewport(context.Background(), source, 0, 3, Rectangle{Width: 30, Height: 20}) if err != nil || len(ranges) != 3 || ranges[1].Text != "é" { t.Fatalf("inset glyph omitted: %+v %v", ranges, err) } @@ -155,7 +155,7 @@ func TestPointReviewViewportBoundsSparseProviderWork(t *testing.T) { source := &pointReviewText{fakeReviewText: fakeReviewText{rectangles: map[[2]int]Rectangle{ {0, 1}: {-100, 0, 10, 100}, {99999, 100000}: {1000, 0, 10, 100}, }}} - ranges, err := point_review_viewport(context.Background(), source, 0, 100000, Rectangle{Width: 100, Height: 100}) + ranges, err := pointReviewViewport(context.Background(), source, 0, 100000, Rectangle{Width: 100, Height: 100}) if !errors.Is(err, errReviewViewportScanLimit) || len(ranges) != 0 || source.pointCalls != 4096 { t.Fatalf("sparse provider work: ranges=%d calls=%d err=%v", len(ranges), source.pointCalls, err) } @@ -165,7 +165,7 @@ func TestPointReviewViewportRetainsLineWithZeroAreaTrailingNewline(t *testing.T) source := &pointReviewText{fakeReviewText: fakeReviewText{rectangles: map[[2]int]Rectangle{ {0, 1}: {Width: 10, Height: 10}, {1, 2}: {X: 10, Width: 10, Height: 10}, {2, 3}: {}, }}, textByOffset: map[int]string{0: "é", 1: "猫", 2: "\n"}} - ranges, err := point_review_viewport(context.Background(), source, 0, 3, Rectangle{Width: 20, Height: 20}) + ranges, err := pointReviewViewport(context.Background(), source, 0, 3, Rectangle{Width: 20, Height: 20}) if err != nil || len(ranges) != 1 || ranges[0].Text != "é猫" || ranges[0].End != 2 { t.Fatalf("trailing newline discarded visible glyphs: %+v %v", ranges, err) } @@ -207,7 +207,7 @@ func TestPointReviewViewportRetainsZeroAreaCombiningMark(t *testing.T) { source := &pointReviewText{fakeReviewText: fakeReviewText{rectangles: map[[2]int]Rectangle{ {0, 1}: {Width: 10, Height: 10}, {1, 2}: {}, {2, 3}: {X: 10, Width: 10, Height: 10}, }}, textByOffset: map[int]string{0: "a", 1: "\u0301", 2: "b"}} - ranges, err := point_review_viewport(context.Background(), source, 0, 3, Rectangle{Width: 20, Height: 10}) + ranges, err := pointReviewViewport(context.Background(), source, 0, 3, Rectangle{Width: 20, Height: 10}) if err != nil || len(ranges) != 2 || ranges[0].Text != "a\u0301" || ranges[0].End != 2 || ranges[1].Text != "b" { t.Fatalf("point traversal lost accent: %+v %v", ranges, err) } @@ -221,7 +221,7 @@ func TestPointReviewViewportRejectsExcessiveClusterWithoutPartialText(t *testing for offset := 1; offset < finalOffset; offset++ { source.textByOffset[offset] = "\u0301" } - ranges, err := point_review_viewport(context.Background(), source, 0, finalOffset+1, Rectangle{Width: 20, Height: 10}) + ranges, err := pointReviewViewport(context.Background(), source, 0, finalOffset+1, Rectangle{Width: 20, Height: 10}) if !errors.Is(err, errReviewViewportScanLimit) || len(ranges) != 0 { t.Fatalf("cluster limit silently omitted text: %+v %v", ranges, err) } diff --git a/internal/atspi/window_switcher.go b/internal/atspi/window_switcher.go index 4a49290..60ff7bb 100644 --- a/internal/atspi/window_switcher.go +++ b/internal/atspi/window_switcher.go @@ -6,7 +6,7 @@ package atspi import "strings" -func is_window_switcher_selection_type(eventType string, detail1 int) bool { +func isWindowSwitcherSelectionType(eventType string, detail1 int) bool { switch eventType { case TextInsertedEvent, SelectionChangedEvent: return true @@ -24,7 +24,7 @@ func is_window_switcher_selection_type(eventType string, detail1 int) bool { // out of this exception. This does not grant native or application focus. func IsWindowSwitcherSelection(event Event) bool { source := event.Source - return is_window_switcher_selection_type(event.Type, event.Detail1) && + return isWindowSwitcherSelectionType(event.Type, event.Detail1) && source.ApplicationProcess == "marco" && strings.EqualFold(source.ApplicationName, "marco") && source.Role == "status bar" && source.StatesKnown && source.Visible && source.Showing && !source.Defunct && source.ID().Valid() && event.Window.Valid() && event.Window.BusName == source.BusName diff --git a/internal/braille/braille.go b/internal/braille/braille.go index 1176d53..4b8856e 100644 --- a/internal/braille/braille.go +++ b/internal/braille/braille.go @@ -167,7 +167,7 @@ func (v *viewport) setFrame(frame Frame) error { func (v *viewport) route(key Key) (RoutingEvent, bool) { cell := int(key - RouteBase) - if key < RouteBase || cell < 0 || cell >= v.width || v.offset+cell >= v.visible_end() { + if key < RouteBase || cell < 0 || cell >= v.width || v.offset+cell >= v.visibleEnd() { return RoutingEvent{}, false } return RoutingEvent{ID: v.id, Offset: v.inputPositions[v.offset+cell]}, true @@ -184,7 +184,7 @@ func (v *viewport) pan(key Key) bool { v.offset = max(0, v.offset-v.width) } case PanRight: - if next := v.visible_end(); next < len(v.text) { + if next := v.visibleEnd(); next < len(v.text) { v.panHistory = append(v.panHistory, v.offset) v.offset = next } @@ -193,34 +193,34 @@ func (v *viewport) pan(key Key) bool { } func (v *viewport) frame() string { - end := v.visible_end() + end := v.visibleEnd() return string(v.text[v.offset:end]) + strings.Repeat(" ", v.width-(end-v.offset)) } func (v *viewport) displayDots() []byte { result := make([]byte, v.width) - copy(result, v.dots[v.offset:v.visible_end()]) + copy(result, v.dots[v.offset:v.visibleEnd()]) return result } func (v *viewport) displayCursor() int { - if v.cursor < v.offset || v.cursor >= v.visible_end() { + if v.cursor < v.offset || v.cursor >= v.visibleEnd() { return 0 } return v.cursor - v.offset + 1 } -func braille_space(cell rune) bool { return cell == ' ' || cell == '\u2800' } +func brailleSpace(cell rune) bool { return cell == ' ' || cell == '\u2800' } // Pad the remainder of a wrapped page instead of showing half of the next // word. Overlong words still advance by the display width. Do not hide a caret // which the initial viewport was positioned to show. -func (v *viewport) visible_end() int { +func (v *viewport) visibleEnd() int { end := min(len(v.text), v.offset+v.width) - if v.wordWrap && end < len(v.text) && !braille_space(v.text[end]) && - !braille_space(v.text[end-1]) { + if v.wordWrap && end < len(v.text) && !brailleSpace(v.text[end]) && + !brailleSpace(v.text[end-1]) { for boundary := end - 1; boundary > v.offset; boundary-- { - if braille_space(v.text[boundary]) { + if brailleSpace(v.text[boundary]) { if v.cursor >= boundary+1 && v.cursor < end { return end } diff --git a/internal/clipboard/clipboard.go b/internal/clipboard/clipboard.go index 65d7901..9b0534c 100644 --- a/internal/clipboard/clipboard.go +++ b/internal/clipboard/clipboard.go @@ -27,7 +27,7 @@ type Snapshot struct { // WriteMessage is called only by the short lived clipboard helper process. // URI filesystem checks stay here so the parent can enforce a read deadline. func WriteMessage(output io.Writer) error { - snapshot, err := read_native() + snapshot, err := readNative() if err != nil { return err } @@ -41,7 +41,7 @@ func Format(snapshot Snapshot) string { return "The clipboard contains a image" } if len(snapshot.URIs) != 0 { - return format_uris(snapshot.URIs) + return formatUris(snapshot.URIs) } if snapshot.HasText { return "Text in clipboard " + snapshot.Text @@ -49,7 +49,7 @@ func Format(snapshot Snapshot) string { return "The clipboard is empty" } -func format_uris(uris []string) string { +func formatUris(uris []string) string { objects := make([]string, 0, len(uris)) for _, raw := range uris { if raw == "" { @@ -77,7 +77,7 @@ func format_uris(uris []string) string { } else if info.Mode().IsRegular() { parts = append(parts, "File") } - if !link && is_mount(localPath, info) { + if !link && isMount(localPath, info) { parts = append(parts, "Disk") } } @@ -97,7 +97,7 @@ func format_uris(uris []string) string { return strconv.Itoa(len(objects)) + label + strings.Join(objects, " ") } -func is_mount(localPath string, info os.FileInfo) bool { +func isMount(localPath string, info os.FileInfo) bool { parentPath := filepath.Dir(filepath.Clean(localPath)) parent, err := os.Stat(parentPath) if err != nil { diff --git a/internal/clipboard/native.go b/internal/clipboard/native.go index 816a4db..ae3ade9 100644 --- a/internal/clipboard/native.go +++ b/internal/clipboard/native.go @@ -45,7 +45,7 @@ import ( "unsafe" ) -func read_native() (Snapshot, error) { +func readNative() (Snapshot, error) { native := C.read_clipboard() defer C.free_clipboard(&native) if native.initialized == 0 { diff --git a/internal/config/legacy_mapping.go b/internal/config/legacy_mapping.go index a462d0e..6f4012c 100644 --- a/internal/config/legacy_mapping.go +++ b/internal/config/legacy_mapping.go @@ -18,22 +18,22 @@ package config import ( - "git.stormux.org/storm/cthulhu/internal/datetime" + "git.stormux.org/storm/screenreader-common/datetime" ) func apply(settings *Settings, values rawSettings) { // Keep the established patch order; absent fields leave prior values intact. - apply_legacy_sound(settings, values) - apply_legacy_output(settings, values) - apply_legacy_speech_service(settings, values) - apply_legacy_reading(settings, values) - apply_legacy_speech_formats(settings, values) - apply_legacy_keyboard(settings, values) - apply_legacy_echo(settings, values) - apply_legacy_default_voice(settings, values) + applyLegacySound(settings, values) + applyLegacyOutput(settings, values) + applyLegacySpeechService(settings, values) + applyLegacyReading(settings, values) + applyLegacySpeechFormats(settings, values) + applyLegacyKeyboard(settings, values) + applyLegacyEcho(settings, values) + applyLegacyDefaultVoice(settings, values) } -func apply_legacy_sound(settings *Settings, values rawSettings) { +func applyLegacySound(settings *Settings, values rawSettings) { if values.EnableSound != nil { settings.EnableSound = *values.EnableSound } @@ -63,7 +63,7 @@ func apply_legacy_sound(settings *Settings, values rawSettings) { } } -func apply_legacy_output(settings *Settings, values rawSettings) { +func applyLegacyOutput(settings *Settings, values rawSettings) { if values.EnableSpeech != nil { settings.EnableSpeech = *values.EnableSpeech } @@ -108,7 +108,7 @@ func apply_legacy_output(settings *Settings, values rawSettings) { } } -func apply_legacy_speech_service(settings *Settings, values rawSettings) { +func applyLegacySpeechService(settings *Settings, values rawSettings) { if values.HardwareSpeechDevice != nil { settings.HardwareSpeechDevice = *values.HardwareSpeechDevice } @@ -132,7 +132,7 @@ func apply_legacy_speech_service(settings *Settings, values rawSettings) { } } -func apply_legacy_reading(settings *Settings, values rawSettings) { +func applyLegacyReading(settings *Settings, values rawSettings) { if values.Reading.OnlySpeakDisplayedText != nil { settings.Reading.OnlySpeakDisplayedText = *values.Reading.OnlySpeakDisplayedText } @@ -222,7 +222,7 @@ func apply_legacy_reading(settings *Settings, values rawSettings) { } } -func apply_legacy_speech_formats(settings *Settings, values rawSettings) { +func applyLegacySpeechFormats(settings *Settings, values rawSettings) { if values.VerbalizePunctuationStyle != nil { settings.VerbalizePunctuationStyle = *values.VerbalizePunctuationStyle } @@ -237,7 +237,7 @@ func apply_legacy_speech_formats(settings *Settings, values rawSettings) { } } -func apply_legacy_keyboard(settings *Settings, values rawSettings) { +func applyLegacyKeyboard(settings *Settings, values rawSettings) { if values.KeyboardLayout != nil { settings.KeyboardLayout = *values.KeyboardLayout } @@ -246,7 +246,7 @@ func apply_legacy_keyboard(settings *Settings, values rawSettings) { } } -func apply_legacy_echo(settings *Settings, values rawSettings) { +func applyLegacyEcho(settings *Settings, values rawSettings) { if values.UseCustomEchoVoice != nil { settings.UseCustomEchoVoice = *values.UseCustomEchoVoice } @@ -312,7 +312,7 @@ func apply_legacy_echo(settings *Settings, values rawSettings) { } } -func apply_legacy_default_voice(settings *Settings, values rawSettings) { +func applyLegacyDefaultVoice(settings *Settings, values rawSettings) { if voice, exists := values.Voices["default"]; exists { converted := voiceFromLegacy(voice) if settings.SpeechServerFactory == "hardwarefactory" { diff --git a/internal/config/ocr_test.go b/internal/config/ocr_test.go index 2fdcc17..8f37bf8 100644 --- a/internal/config/ocr_test.go +++ b/internal/config/ocr_test.go @@ -37,11 +37,11 @@ func TestOCRAutoReadAllDefaultsAndExplicitFalse(t *testing.T) { t.Fatal("automatic OCR reading must default off") } settings.OCR.AutoReadAll = true - apply_profile_ocr(&settings.OCR, writableOCR{}) + applyProfileOcr(&settings.OCR, writableOCR{}) if !settings.OCR.AutoReadAll { t.Fatal("omitted setting changed inherited value") } - apply_profile_ocr(&settings.OCR, writableOCR{AutoReadAll: boolPointer(false)}) + applyProfileOcr(&settings.OCR, writableOCR{AutoReadAll: boolPointer(false)}) if settings.OCR.AutoReadAll { t.Fatal("explicit false did not override inherited value") } diff --git a/internal/config/profile_mapping.go b/internal/config/profile_mapping.go index cc9708b..5a5d0ff 100644 --- a/internal/config/profile_mapping.go +++ b/internal/config/profile_mapping.go @@ -20,8 +20,8 @@ package config import ( "reflect" - "git.stormux.org/storm/cthulhu/internal/datetime" "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/screenreader-common/datetime" ) // Application profiles store only values that differ from the global profile. @@ -117,7 +117,7 @@ func profileFromSettings(settings Settings) writableProfile { }, }, Speech: writableSpeech{ - Interruption: interruption_pointer(settings.SpeechInterruption), + Interruption: interruptionPointer(settings.SpeechInterruption), HardwareDevice: stringPointer(settings.HardwareSpeechDevice), HardwareBaudRate: intPointer(settings.HardwareSpeechBaudRate), Enabled: boolPointer(settings.EnableSpeech), ServerFactory: stringPointer(settings.SpeechServerFactory), @@ -182,14 +182,14 @@ func applyProfile(settings *Settings, profile writableProfile) { if profile.Wine.ExcludedPrograms != nil { settings.Wine.ExcludedPrograms = append([]string(nil), (*profile.Wine.ExcludedPrograms)...) } - apply_profile_ocr(&settings.OCR, profile.OCR) + applyProfileOcr(&settings.OCR, profile.OCR) // Keep the established patch order; absent fields leave prior values intact. - apply_profile_formats(settings, profile) - apply_profile_echo_voice(settings, profile) - apply_profile_reading(settings, profile) - apply_profile_output(settings, profile) - apply_profile_speech(settings, profile) - apply_profile_sound(settings, profile) + applyProfileFormats(settings, profile) + applyProfileEchoVoice(settings, profile) + applyProfileReading(settings, profile) + applyProfileOutput(settings, profile) + applyProfileSpeech(settings, profile) + applyProfileSound(settings, profile) if value := profile.ProgressBar.OutputMode; value != nil { settings.ProgressBar.OutputMode = *value } @@ -202,11 +202,11 @@ func applyProfile(settings *Settings, profile writableProfile) { if value := profile.ProgressBar.SpeechPercentageInterval; value != nil { settings.ProgressBar.SpeechPercentageInterval = *value } - apply_profile_keyboard(settings, profile) - apply_profile_echo_keys(settings, profile) + applyProfileKeyboard(settings, profile) + applyProfileEchoKeys(settings, profile) } -func apply_profile_ocr(settings *OCRSettings, patch writableOCR) { +func applyProfileOcr(settings *OCRSettings, patch writableOCR) { if patch.Language != nil { settings.Language = *patch.Language } @@ -245,7 +245,7 @@ func apply_profile_ocr(settings *OCRSettings, patch writableOCR) { } } -func apply_profile_formats(settings *Settings, profile writableProfile) { +func applyProfileFormats(settings *Settings, profile writableProfile) { if v := profile.Presentation.TimeFormat; v != nil { settings.TimeFormat = *v } @@ -254,7 +254,7 @@ func apply_profile_formats(settings *Settings, profile writableProfile) { } } -func apply_profile_echo_voice(settings *Settings, profile writableProfile) { +func applyProfileEchoVoice(settings *Settings, profile writableProfile) { if v := profile.KeyEcho.UseCustomEchoVoice; v != nil { settings.UseCustomEchoVoice = *v } @@ -281,7 +281,7 @@ func apply_profile_echo_voice(settings *Settings, profile writableProfile) { } } -func apply_profile_reading(settings *Settings, profile writableProfile) { +func applyProfileReading(settings *Settings, profile writableProfile) { if value := profile.Presentation.Pronunciations; value != nil { settings.Pronunciations = append([]PronunciationEntry(nil), (*value)...) } @@ -422,9 +422,9 @@ func apply_profile_reading(settings *Settings, profile writableProfile) { } } -func apply_profile_output(settings *Settings, profile writableProfile) { +func applyProfileOutput(settings *Settings, profile writableProfile) { if value := profile.Speech.Interruption; value != nil { - settings.SpeechInterruption = *interruption_pointer(*value) + settings.SpeechInterruption = *interruptionPointer(*value) } if value := profile.Speech.Enabled; value != nil { settings.EnableSpeech = *value @@ -473,12 +473,12 @@ func apply_profile_output(settings *Settings, profile writableProfile) { } } -func interruption_pointer(settings input.InterruptionSettings) *input.InterruptionSettings { +func interruptionPointer(settings input.InterruptionSettings) *input.InterruptionSettings { settings.Keys = append([]string(nil), settings.Keys...) return &settings } -func apply_profile_speech(settings *Settings, profile writableProfile) { +func applyProfileSpeech(settings *Settings, profile writableProfile) { if value := profile.Speech.HardwareDevice; value != nil { settings.HardwareSpeechDevice = *value } @@ -520,7 +520,7 @@ func apply_profile_speech(settings *Settings, profile writableProfile) { } } -func apply_profile_sound(settings *Settings, profile writableProfile) { +func applyProfileSound(settings *Settings, profile writableProfile) { if value := profile.Sound.Enabled; value != nil { settings.EnableSound = *value } @@ -550,7 +550,7 @@ func apply_profile_sound(settings *Settings, profile writableProfile) { } } -func apply_profile_keyboard(settings *Settings, profile writableProfile) { +func applyProfileKeyboard(settings *Settings, profile writableProfile) { if value := profile.Keyboard.Bindings; value != nil { settings.KeyBindings = input.CloneBindingOverrides(*value) } @@ -562,7 +562,7 @@ func apply_profile_keyboard(settings *Settings, profile writableProfile) { } } -func apply_profile_echo_keys(settings *Settings, profile writableProfile) { +func applyProfileEchoKeys(settings *Settings, profile writableProfile) { if value := profile.KeyEcho.Enabled; value != nil { settings.EnableKeyEcho = *value } diff --git a/internal/config/validation.go b/internal/config/validation.go index e974ff4..1e3f123 100644 --- a/internal/config/validation.go +++ b/internal/config/validation.go @@ -26,8 +26,8 @@ import ( "unicode" "unicode/utf16" - "git.stormux.org/storm/cthulhu/internal/datetime" "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/screenreader-common/datetime" ) // Validate checks the complete configuration without touching the filesystem. @@ -169,11 +169,12 @@ func validate(settings Settings) error { return errors.New("a separate echo synthesizer requires Speech Dispatcher; disable custom echo voice for hardware speech") } switch settings.SpeechOutputModule { - case "litetalk", "doubletalk", "tripletalk", "dectalk": + case "litetalk", "doubletalk", "tripletalk", "dectalk", "dectalk-usb": default: return errors.New("choose a hardware speech synthesizer") } - if !filepath.IsAbs(settings.HardwareSpeechDevice) { + // DECtalk USB finds its device itself; serial synthesizers need a path. + if settings.SpeechOutputModule != "dectalk-usb" && !filepath.IsAbs(settings.HardwareSpeechDevice) { return errors.New("choose an explicit serial device path for hardware speech") } } diff --git a/internal/config/voice_profiles.go b/internal/config/voice_profiles.go index 3e3ca7b..73b3e02 100644 --- a/internal/config/voice_profiles.go +++ b/internal/config/voice_profiles.go @@ -4,13 +4,12 @@ package config import ( - "fmt" "git.stormux.org/storm/screenreader-common/voiceprofiles" "math" "strings" ) -func Primary_voice(settings Settings) voiceprofiles.Profile { +func PrimaryVoice(settings Settings) voiceprofiles.Profile { p := voiceprofiles.Profile{Driver: "speech-dispatcher", Module: settings.SpeechOutputModule, Volume: 100} number := func(v *float64, fallback int) int { if v != nil { @@ -38,7 +37,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 } @@ -51,13 +50,14 @@ func Apply_primary_voice(settings Settings, p voiceprofiles.Profile) (Settings, voice.AveragePitch = &pitch voice.Gain = &volume if p.Driver != "speech-dispatcher" { - if p.Driver == "dectalk-usb" { - return settings, fmt.Errorf("DECtalk USB is not supported by Cthulhu") - } next.SpeechServerFactory = "hardwarefactory" next.SpeechOutputModule = p.Driver - next.HardwareSpeechDevice = p.Device - next.HardwareSpeechBaudRate = p.BaudRate + // DECtalk USB has no device path or baud rate; keep the saved serial + // settings for when a serial synthesizer is chosen again. + if p.Driver != "dectalk-usb" { + next.HardwareSpeechDevice = p.Device + next.HardwareSpeechBaudRate = p.BaudRate + } } else if p.Voice != "" || p.Language != "" { voice.Family = &VoiceFamily{Name: p.Voice, Lang: p.Language, Variant: p.Variant} } diff --git a/internal/config/voice_profiles_test.go b/internal/config/voice_profiles_test.go index 726d930..0e4485e 100644 --- a/internal/config/voice_profiles_test.go +++ b/internal/config/voice_profiles_test.go @@ -29,7 +29,7 @@ func TestVoiceProfilesPersistencePrimaryScopeAndApplicationSave(t *testing.T) { if err != nil || !reflect.DeepEqual(loaded.VoiceProfiles, settings.VoiceProfiles) { t.Fatal(loaded.VoiceProfiles, err) } - loaded, err = Apply_primary_voice(loaded, p) + loaded, err = ApplyPrimaryVoice(loaded, p) if err != nil || loaded.DefaultVoice.Family.Name != "Reader" || *loaded.DefaultVoice.Rate != 30 { t.Fatal(loaded, err) } @@ -58,3 +58,25 @@ func TestVoiceProfilesPersistencePrimaryScopeAndApplicationSave(t *testing.T) { t.Fatal(global.VoiceProfiles, err) } } + +func TestDECtalkUSBProfileNeedsNoSerialDevice(t *testing.T) { + settings := DefaultSettings() + settings.UseCustomEchoSpeechServer = false + p := voiceprofiles.Profile{Name: "Desk", Driver: "dectalk-usb", Rate: 10} + next, err := ApplyPrimaryVoice(settings, p) + if err != nil { + t.Fatal(err) + } + if next.SpeechServerFactory != "hardwarefactory" || next.SpeechOutputModule != "dectalk-usb" { + t.Fatal(next.SpeechServerFactory, next.SpeechOutputModule) + } + if got := PrimaryVoice(next); got.Driver != "dectalk-usb" { + t.Fatal("round trip", got) + } + serial := next + serial.SpeechOutputModule = "dectalk" + serial.HardwareSpeechDevice = "" + if err := Validate(serial); err == nil { + t.Fatal("serial DECtalk accepted without a device path") + } +} diff --git a/internal/datetime/datetime.go b/internal/datetime/datetime.go deleted file mode 100644 index 2d2a06b..0000000 --- a/internal/datetime/datetime.go +++ /dev/null @@ -1,17 +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 TimeOptions = common.TimeOptions -var DateOptions = common.DateOptions -var FormatTime = common.FormatTime -var FormatDate = common.FormatDate -var ValidTime = common.ValidTime -var ValidDate = common.ValidDate -var NormalizeDate = common.NormalizeDate diff --git a/internal/emoji/catalog.go b/internal/emoji/catalog.go index 0bb1f74..6830c39 100644 --- a/internal/emoji/catalog.go +++ b/internal/emoji/catalog.go @@ -2,33 +2,68 @@ // Authors: Storm Dragon, Angus Kola // SPDX-License-Identifier: GPL-3.0-or-later -// Package emoji adapts the shared catalog to Cthulhu's internal UI form. +// Package emoji builds Cthulhu's picker form from the shared catalog. package emoji import ( - "sort" - - "git.stormux.org/storm/cthulhu/internal/interaction" commonemoji "git.stormux.org/storm/screenreader-common/emoji" + ui "git.stormux.org/storm/screenreader-common/internalui" ) -const MenuTitle = "Emoji Menu" +const ( + MenuTitle = "Emoji Menu" + // SelectAction is the grid's activation; the focused grid holds the choice. + SelectAction = "select-grid-item" + gridID = "grid" + copyID = "copy" +) -// NewSession builds a private picker with independent category searches. -func NewSession(copyChecked bool) (*interaction.Session, error) { - sharedCategories := commonemoji.Categories() - tabs := make([]interaction.GridTab, 1, len(sharedCategories)+1) - tabs[0] = interaction.GridTab{ID: "all", Label: "All"} - var all []interaction.Item - for _, category := range sharedCategories { - items := make([]interaction.Item, len(category.Entries)) - for index, entry := range category.Entries { - items[index] = interaction.Item{ID: entry.ID, Label: entry.Label} +// Form is a private picker with independent category searches. Every tab has +// its own copy checkbox; SyncCopy keeps them in step. +func Form(copyChecked bool) ui.Form { + form := ui.Form{Type: ui.TabForm, Title: MenuTitle, Detailed: true} + for _, tab := range commonemoji.PickerTabs() { + choices := make([]ui.Choice, len(tab.Entries)) + for index, entry := range tab.Entries { + choices[index] = ui.Choice{ID: entry.ID, Label: entry.Label, Literal: true} } - all = append(all, items...) - tabs = append(tabs, interaction.GridTab{ID: category.ID, Label: category.Label, Items: items}) + form.Tabs = append(form.Tabs, ui.Tab{ID: tab.ID, Label: tab.Label, Controls: []ui.Control{ + {ID: gridID, Label: "Grid", Kind: ui.Grid, Choices: choices, Columns: commonemoji.PickerColumns, Action: SelectAction}, + {ID: copyID, Label: "Copy selected emoji to clipboard", Kind: ui.CheckBox, Checked: copyChecked}, + }}) } - sort.SliceStable(all, func(i, j int) bool { return all[i].Label < all[j].Label }) - tabs[0].Items = all - return interaction.NewGridSession(MenuTitle, tabs, 6, interaction.Element{ID: "copy", Label: "Copy selected emoji to clipboard", Kind: interaction.CheckBox, Checked: copyChecked}) + return form +} + +// NewSession opens the picker. Emoji names come from the shared catalog and +// are not translated. +func NewSession(copyChecked bool) (*ui.Session, error) { + return ui.NewSession(Form(copyChecked), ui.Messages{}) +} + +// SyncCopy mirrors a change to the focused copy checkbox onto every tab. +func SyncCopy(session *ui.Session) { + if control, ok := session.FocusedControl(); ok && control.ID == copyID { + session.SetChecked(copyID, control.Checked) + } +} + +// CopyChecked reports the copy choice; ok is false once the session closes. +func CopyChecked(session *ui.Session) (checked, ok bool) { + for _, control := range session.Values() { + if control.ID == copyID { + return control.Checked, true + } + } + return false, false +} + +// Selection returns the focused grid's emoji and its name. +func Selection(session *ui.Session) (id, label string, ok bool) { + control, focused := session.FocusedControl() + if !focused || control.ID != gridID || control.Selected < 0 || control.Selected >= len(control.Choices) { + return "", "", false + } + choice := control.Choices[control.Selected] + return choice.ID, choice.Label, true } diff --git a/internal/emoji/catalog_test.go b/internal/emoji/catalog_test.go index a730cc7..ce50a06 100644 --- a/internal/emoji/catalog_test.go +++ b/internal/emoji/catalog_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" - "git.stormux.org/storm/cthulhu/internal/interaction" commonemoji "git.stormux.org/storm/screenreader-common/emoji" + ui "git.stormux.org/storm/screenreader-common/internalui" ) func TestCatalogUniquenessAndSequences(t *testing.T) { @@ -32,9 +32,9 @@ func TestKissMarkSearch(t *testing.T) { if err != nil { t.Fatal(err) } - session.Handle(interaction.Event{Key: interaction.Tab}) - session.Handle(interaction.Event{Text: "Kiss mark"}) - if got := session.Values()["grid"].Selected; got != "💋" { + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Text: "Kiss mark"}) + if got := selected(session); got != "💋" { t.Fatalf("kiss mark selection = %q", got) } } @@ -43,48 +43,79 @@ func TestPickerSearchSelectionAndIndependentCategories(t *testing.T) { if err != nil { t.Fatal(err) } - if got := session.Opening().Speech; got != "Emoji Menu. All tab" { + if got := session.Open(); got != "Emoji Menu. All tab" { t.Fatal(got) } - session.Handle(interaction.Event{Key: interaction.Tab}) - session.Handle(interaction.Event{Text: "astronaut"}) - if got := session.Values()["grid"].Selected; got != "🧑‍🚀" { + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Text: "astronaut"}) + if got := selected(session); got != "🧑‍🚀" { t.Fatalf("sequence changed: %q", got) } // Empty results must not activate or retain a previous selection. - session.Handle(interaction.Event{Text: "zz"}) - if session.Values()["grid"].Selected != "" || session.Handle(interaction.Event{Key: interaction.Enter}).Activated != "" { + session.Handle(ui.Key{Text: "zz"}) + if selected(session) != "" || session.Handle(ui.Key{Name: "enter"}).Action != "" { t.Fatal("stale selection after empty search") } - session.Handle(interaction.Event{Key: interaction.Backspace, Control: true}) - session.Handle(interaction.Event{Text: "goat"}) - if session.Values()["grid"].Selected != "🐐" { + session.Handle(ui.Key{Name: "backspace", Ctrl: true}) + session.Handle(ui.Key{Text: "goat"}) + if selected(session) != "🐐" { t.Fatal("search not reset") } // Forward and reverse Tab include the checkbox and category strip. - session.Handle(interaction.Event{Key: interaction.Tab}) - session.Handle(interaction.Event{Text: " "}) - if session.Values()["copy"].Checked { + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Name: "space", Text: " "}) + SyncCopy(session) + if copied(session) { t.Fatal("checkbox did not toggle") } - session.Handle(interaction.Event{Key: interaction.Tab}) - session.Handle(interaction.Event{Key: interaction.Right}) - session.Handle(interaction.Event{Key: interaction.Tab}) + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Name: "right"}) + session.Handle(ui.Key{Name: "tab"}) if strings.Contains(session.Presentation().Speech, "Goat") { t.Fatal("category search leaked") } - session.Handle(interaction.Event{Key: interaction.Tab, Shift: true}) - session.Handle(interaction.Event{Key: interaction.Left}) - session.Handle(interaction.Event{Key: interaction.Tab}) - if session.Values()["grid"].Selected != "🐐" { + session.Handle(ui.Key{Name: "tab", Shift: true}) + session.Handle(ui.Key{Name: "left"}) + session.Handle(ui.Key{Name: "tab"}) + if selected(session) != "🐐" { t.Fatal("category search not retained") } - if got := session.Handle(interaction.Event{Key: interaction.Enter}).Activated; got != "select-grid-item" { + if got := session.Handle(ui.Key{Name: "enter"}).Action; got != "select-grid-item" { t.Fatal(got) } other, _ := NewSession(true) - other.Handle(interaction.Event{Key: interaction.Tab}) - if other.Values()["grid"].Selected == "🐐" { + other.Handle(ui.Key{Name: "tab"}) + if selected(other) == "🐐" { t.Fatal("new picker inherited search") } } + +func selected(session *ui.Session) string { + id, _, _ := Selection(session) + return id +} + +func copied(session *ui.Session) bool { + checked, _ := CopyChecked(session) + return checked +} + +func TestCopyChoiceFollowsEveryTab(t *testing.T) { + session, err := NewSession(false) + if err != nil { + t.Fatal(err) + } + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Name: "space", Text: " "}) + SyncCopy(session) + for key, control := range session.Values() { + if control.Kind == ui.CheckBox && !control.Checked { + t.Fatalf("%s kept the old copy choice", key) + } + } + session.Close() + if _, ok := CopyChecked(session); ok { + t.Fatal("closed picker still reported a copy choice") + } +} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..0bfa750 --- /dev/null +++ b/internal/i18n/i18n.go @@ -0,0 +1,49 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package i18n is Cthulhu's setup of the shared gettext loader: the +// "cthulhu" domain, installed catalogs under /usr/share/locale and catalogs +// bundled from locale/. Application text, accessible names and other +// external content must never pass through this package; only Cthulhu's own +// user-facing messages do. See TRANSLATIONS.md in screenreader-common. +package i18n + +import ( + "embed" + "io/fs" + + common "git.stormux.org/storm/screenreader-common/i18n" +) + +const Domain = "cthulhu" +const LocaleDir = common.LocaleDir + +// locale holds cthulhu.pot and, once contributed, /LC_MESSAGES/cthulhu.po. +// +//go:embed locale +var bundled embed.FS + +type Catalog = common.Catalog + +var active common.Active + +// Language follows Python gettext's environment precedence. +func Language() string { return common.Language() } + +// New loads Cthulhu's installed catalogs under root, then its bundled ones. +func New(root, languages string) *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 active.Use(catalog) } + +func T(message string) string { return active.T(message) } + +func N(singular, plural string, count int) string { return active.N(singular, plural, count) } + +// Format substitutes positional fields {0}, {1}, ... after lookup, so +// translators can reorder them. +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 new file mode 100644 index 0000000..05b917d --- /dev/null +++ b/internal/i18n/i18n_test.go @@ -0,0 +1,37 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package i18n + +import ( + "os" + "path/filepath" + "testing" +) + +func TestInstalledCatalogTranslatesAndEnglishIsDefault(t *testing.T) { + if got := T("Close"); got != "Close" { + t.Fatal("translated before setup", got) + } + root := t.TempDir() + dir := filepath.Join(root, "xx", "LC_MESSAGES") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, Domain+".po"), []byte("msgid \"Close\"\nmsgstr \"xx-close\"\n\nmsgid \"{0} of {1}\"\nmsgstr \"{1}: {0}\"\n"), 0o600); err != nil { + t.Fatal(err) + } + previous := Use(New(root, "xx_YY.UTF-8")) + t.Cleanup(func() { Use(previous) }) + if got := T("Close"); got != "xx-close" { + t.Fatal(got) + } + if got := Format("{0} of {1}", "2", "5"); got != "5: 2" { + t.Fatal(got) + } + // The bundled tree holds only the template until a language is added. + if got := New(t.TempDir(), "de").T("Close"); got != "Close" { + t.Fatal(got) + } +} diff --git a/internal/i18n/locale/cthulhu.pot b/internal/i18n/locale/cthulhu.pot new file mode 100644 index 0000000..e8c284f --- /dev/null +++ b/internal/i18n/locale/cthulhu.pot @@ -0,0 +1,150 @@ +# Cthulhu reader messages. Generated by go run ./tools/translations. +msgid "" +msgstr "" +"Project-Id-Version: cthulhu\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: screenreader-common/internalui +msgid " (selected {0} characters)" +msgstr "" + +#: screenreader-common/internalui +msgid "1 character" +msgstr "" + +#: screenreader-common/internalui +msgid "Copy and cut are unavailable for password fields" +msgstr "" + +#: screenreader-common/internalui +msgid "Deleted {0}" +msgstr "" + +#: screenreader-common/internalui +msgid "End of text" +msgstr "" + +#: screenreader-common/internalui +msgid "Hidden character" +msgstr "" + +#: screenreader-common/internalui +msgid "Inserted {0}" +msgstr "" + +#: screenreader-common/internalui +msgid "Invalid text" +msgstr "" + +#: screenreader-common/internalui +msgid "No matches" +msgstr "" + +#: screenreader-common/internalui +msgid "Only single-line text is accepted" +msgstr "" + +#: screenreader-common/quicksettings/menu.go +msgid "Quick menu not available" +msgstr "" + +#: screenreader-common/internalui +msgid "Search cleared" +msgstr "" + +#: screenreader-common/internalui +msgid "Search {0}" +msgstr "" + +#: screenreader-common/internalui +msgid "Selected all" +msgstr "" + +#: screenreader-common/internalui +msgid "Text limit reached" +msgstr "" + +#: screenreader-common/internalui screenreader-common/quicksettings/menu.go +msgid "checked" +msgstr "" + +#: screenreader-common/quicksettings/menu.go +msgid "default" +msgstr "" + +#: screenreader-common/internalui +msgid "unavailable" +msgstr "" + +#: screenreader-common/internalui screenreader-common/quicksettings/menu.go +msgid "unchecked" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} button" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} characters" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} combo box {1}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} entry {1}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} grid. {1}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} is required" +msgstr "" + +#: screenreader-common/quicksettings/menu.go +msgid "{0} not available" +msgstr "" + +#: screenreader-common/internalui +msgid "{0} tab" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}, button" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}, edit: {1}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}, password edit, {1}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}, password edit: {1}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}, selected" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}. row {1}, column {2}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}. row {1}, column {2}. {3} of {4}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}. {1} of {2}" +msgstr "" + +#: screenreader-common/internalui +msgid "{0}: {1}, {2} of {3}" +msgstr "" diff --git a/internal/input/commands.go b/internal/input/commands.go index cf87238..fe3b026 100644 --- a/internal/input/commands.go +++ b/internal/input/commands.go @@ -342,7 +342,7 @@ func (router *CommandRouter) Handle(symbol uint32, code uint16, modifiers uint16 } if command := router.bindings[chord]; command != "" { router.consumed[code] = true - command = router.review_press(command, chord) + command = router.reviewPress(command, chord) if command == ToggleDocumentMode { now := router.now() if !router.lastModePress.IsZero() && now.Sub(router.lastModePress) >= 0 && now.Sub(router.lastModePress) <= 500*time.Millisecond { diff --git a/internal/input/review_presses.go b/internal/input/review_presses.go index f560d1d..3e36201 100644 --- a/internal/input/review_presses.go +++ b/internal/input/review_presses.go @@ -9,7 +9,7 @@ import "time" // The router owns this sequence across fully released chords and browse grab // updates. Another key/chord, timeout, or the final press retires it. Held-key // repeats never reach this helper. Reset only clears held keys, as for time/date. -func (router *CommandRouter) review_press(command Command, chord CommandChord) Command { +func (router *CommandRouter) reviewPress(command Command, chord CommandChord) Command { if command != ReviewCurrentCharacter && command != ReviewCurrentWord && command != ReviewCurrentLine && command != PresentCurrentLine { router.lastReviewPress = time.Time{} return command diff --git a/internal/interaction/grid_test.go b/internal/interaction/grid_test.go deleted file mode 100644 index 5d5db89..0000000 --- a/internal/interaction/grid_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later -package interaction - -import "testing" - -func TestGridRowsBoundsAndDisabledItems(t *testing.T) { - items := []Item{{ID: "1", Label: "One"}, {ID: "2", Label: "Two"}, {ID: "3", Label: "Three"}, {ID: "4", Label: "Four"}, {ID: "5", Label: "Five", Disabled: true}, {ID: "6", Label: "Six"}} - session, err := NewGridSession("Picker", []GridTab{{ID: "all", Label: "All", Items: items}}, 3, Element{ID: "copy", Label: "Copy", Kind: CheckBox}) - if err != nil { - t.Fatal(err) - } - session.Handle(Event{Key: Tab}) - for _, step := range []struct { - key Key - want string - }{{Right, "2"}, {Right, "3"}, {Down, "6"}, {Down, "6"}, {Up, "2"}, {Home, "1"}, {Left, "1"}, {End, "6"}, {Right, "6"}, {PageUp, "1"}, {PageDown, "6"}} { - session.Handle(Event{Key: step.key}) - if got := session.Values()["grid"].Selected; got != step.want { - t.Fatalf("%v selected %q want %q", step.key, got, step.want) - } - } - if result := session.Handle(Event{Key: Escape}); !result.Cancelled { - t.Fatal("escape not cancelled") - } - if session.Handle(Event{Key: Enter}).Activated != "" || session.Presentation().Speech != "" { - t.Fatal("closed grid responded") - } -} diff --git a/internal/interaction/secret_test.go b/internal/interaction/secret_test.go deleted file mode 100644 index a0dc2da..0000000 --- a/internal/interaction/secret_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// Authors: Storm Dragon, Angus Kola -// SPDX-License-Identifier: GPL-3.0-or-later - -package interaction - -import "testing" - -func secretForm(text string) Form { - return Form{Title: "Connection", Elements: []Element{ - {ID: "key", Label: "Channel key", Kind: Entry, Secret: true, Text: text, Required: true, MaxLength: 12}, - {ID: "connect", Label: "Connect", Kind: Button}, - }} -} - -func TestSecretEntryEditingAndPresentation(t *testing.T) { - session, err := NewSession(secretForm("猫é123")) - if err != nil { - t.Fatal(err) - } - if got := session.Opening(); got.Speech != "Connection. Channel key, password edit, 5 characters" || got.Braille != "Channel key, password edit: *****" || got.Cursor != 33 { - t.Fatalf("unexpected masked opening: %+v", got) - } - steps := []struct { - event Event - speech, text, braille string - }{ - {Event{Key: Home}, "Hidden character", "猫é123", "Channel key, password edit: *****"}, - {Event{Key: Right, Shift: true}, "Hidden character, selected", "猫é123", "Channel key, password edit: ***** (selected 1 characters)"}, - {Event{Text: "密"}, "Inserted 1 character", "密é123", "Channel key, password edit: *****"}, - {Event{Key: Delete}, "Deleted 1 character", "密123", "Channel key, password edit: ****"}, - {Event{Key: Backspace}, "Deleted 1 character", "123", "Channel key, password edit: ***"}, - {Event{Key: End}, "End of text", "123", "Channel key, password edit: ***"}, - {Event{Text: "a", Control: true}, "Selected all", "123", "Channel key, password edit: *** (selected 3 characters)"}, - {Event{Text: "c", Control: true}, "Copy and cut are unavailable for password fields", "123", "Channel key, password edit: *** (selected 3 characters)"}, - {Event{Text: "x", Control: true}, "Copy and cut are unavailable for password fields", "123", "Channel key, password edit: *** (selected 3 characters)"}, - {Event{Key: Backspace}, "Deleted 3 characters", "", "Channel key, password edit: "}, - {Event{Key: Enter}, "Channel key is required", "", "Channel key is required"}, - } - for index, step := range steps { - effect := session.Handle(step.event) - if effect.Speech != step.speech || effect.Braille != step.braille || effect.Copy != nil || effect.Activated != "" || session.Values()["key"].Text != step.text { - t.Fatalf("secret editing step %d failed", index) - } - } - if !session.Handle(Event{Text: "v", Control: true}).Paste { - t.Fatal("explicit paste not requested") - } - if effect := session.Insert("pasted猫"); effect.Speech != "Inserted 7 characters" || effect.Braille != "Channel key, password edit: *******" { - t.Fatal("paste was not masked") - } - for _, text := range []string{"oversized content", "bad\ntext", string([]byte{0xff})} { - session.Insert(text) - if session.Values()["key"].Text != "pasted猫" { - t.Fatal("invalid paste modified secret") - } - } - session.Handle(Event{Key: Tab}) - if got := session.Handle(Event{Key: Tab, Shift: true}); got.Speech != "Channel key, password edit, 7 characters" { - t.Fatal("returning to password did not mask it") - } - session.Handle(Event{Key: Tab}) - if effect := session.Handle(Event{Key: Enter}); effect.Activated != "connect" || session.Values()["key"].Text != "pasted猫" { - t.Fatal("submission lost the actual secret") - } -} - -func TestSecretEntryCloseAndValidation(t *testing.T) { - for _, escape := range []bool{false, true} { - session, _ := NewSession(secretForm("fixture")) - if escape { - if !session.Handle(Event{Key: Escape}).Cancelled { - t.Fatal("escape did not cancel") - } - } else { - session.Close() - } - session.Close() - if session.Values() != nil || session.Presentation() != (Presentation{}) || session.Insert("more") != (Effect{}) { - t.Fatal("closed editor retained or accepted a secret") - } - } - for _, kind := range []Kind{List, CheckBox, Button} { - form := secretForm("") - form.Elements[0].Kind = kind - if _, err := NewSession(form); err == nil { - t.Fatal("secret accepted on non-entry") - } - } - if err := ValidatePreferences(secretForm("fixture")); err == nil { - t.Fatal("secret accepted in persistent preferences") - } -} diff --git a/internal/interaction/session_test.go b/internal/interaction/session_test.go deleted file mode 100644 index 5a28cc5..0000000 --- a/internal/interaction/session_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// Authors: Storm Dragon, Angus Kola -// SPDX-License-Identifier: GPL-3.0-or-later - -package interaction - -import ( - "strconv" - "strings" - "testing" -) - -func TestNavigationListsRetainExternalFormLimit(t *testing.T) { - items := make([]Item, 300) - for index := range items { - items[index] = Item{ID: strconv.Itoa(index), Label: "Example item"} - } - if _, err := NewSession(Form{Title: "External form", Elements: []Element{{ID: "items", Label: "Items", Kind: List, Items: items}}}); err == nil { - t.Fatal("external form exceeded its protocol limit") - } - session, err := NewNavigationSession("Links", items, 299) - if err != nil { - t.Fatal(err) - } - if effect := session.Handle(Event{Key: Enter}); effect.Activated != "299" { - t.Fatalf("lost initial selection: %+v", effect) - } -} - -func TestListNavigationAndIndependentSessions(t *testing.T) { - form := Form{Title: "Actions", Elements: []Element{{ID: "actions", Label: "Actions", Kind: List, Items: []Item{{ID: "click", Label: "Click"}, {ID: "skip", Label: "Unavailable", Disabled: true}, {ID: "press", Label: "Press"}, {ID: "ancestor", Label: "Click ancestor"}}}}} - first, err := NewSession(form) - if err != nil { - t.Fatal(err) - } - second, _ := NewSession(form) - if opening := first.Opening().Speech; opening != "Actions. Click" { - t.Fatalf("opening speech = %q", opening) - } - if moved := first.Handle(Event{Key: Down}).Speech; moved != "Press" { - t.Fatalf("option speech = %q", moved) - } - if effect := first.Handle(Event{Key: Enter}); effect.Activated != "press" { - t.Fatalf("selection = %+v", effect) - } - if second.Handle(Event{Key: Enter}).Activated != "click" { - t.Fatal("sessions share state") - } - first.Handle(Event{Key: End}) - first.Handle(Event{Key: Down}) - if first.Handle(Event{Key: Enter}).Activated != "ancestor" { - t.Fatal("boundary moved selection") - } - first.Handle(Event{Key: Home}) - first.Handle(Event{Text: "p"}) - if first.Handle(Event{Key: Enter}).Activated != "press" { - t.Fatal("typeahead failed") - } - if !first.Handle(Event{Key: Escape}).Cancelled || first.Handle(Event{Key: Enter}).Activated != "" { - t.Fatal("cancelled session remained usable") - } - form.Elements[0].Items[0].Label = "Changed" - if !strings.Contains(second.Presentation().Speech, "Click") { - t.Fatal("caller mutation changed session") - } -} - -func TestCallerSuppliedMenuTitleAndFormListLabel(t *testing.T) { - menu, err := NewSession(Form{Title: "Wormhole Menu", Elements: []Element{{ID: "choices", Label: "Options", Kind: List, Items: []Item{{ID: "send", Label: "Send focused item"}, {ID: "receive", Label: "Receive file"}}}}}) - if err != nil { - t.Fatal(err) - } - if opening := menu.Opening().Speech; opening != "Wormhole Menu. Send focused item" { - t.Fatalf("custom title = %q", opening) - } - if moved := menu.Handle(Event{Key: Down}).Speech; moved != "Receive file" { - t.Fatalf("custom menu option = %q", moved) - } - if focus := menu.Handle(Event{Key: Tab}).Speech; focus != "Receive file" { - t.Fatalf("menu repeated title on Tab: %q", focus) - } - form, _ := NewSession(Form{Title: "Example", Elements: []Element{{ID: "code", Label: "Code", Kind: Entry}, {ID: "method", Label: "Method", Kind: List, Items: []Item{{ID: "send", Label: "Send"}}}}}) - if focus := form.Handle(Event{Key: Tab}).Speech; focus != "Method. Send" { - t.Fatalf("form list lost its field label: %q", focus) - } -} - -func TestFormTraversalEditingAndValidation(t *testing.T) { - session, err := NewSession(Form{Title: "Receive", Elements: []Element{{ID: "code", Label: "Code", Kind: Entry, Required: true, MaxLength: 8}, {ID: "disabled", Label: "Disabled", Kind: Button, Disabled: true}, {ID: "keep", Label: "Keep", Kind: CheckBox}, {ID: "submit", Label: "Receive", Kind: Button}}}) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(session.Handle(Event{Key: Enter}).Speech, "required") { - t.Fatal("missing required validation") - } - session.Handle(Event{Text: "ab猫"}) - session.Handle(Event{Key: Left, Shift: true}) - session.Insert("é") - if session.Values()["code"].Text != "abé" { - t.Fatal("Unicode selection replacement") - } - session.Handle(Event{Key: Home}) - session.Handle(Event{Key: Delete}) - if session.Values()["code"].Text != "bé" { - t.Fatal("Unicode deletion") - } - session.Handle(Event{Text: "a", Control: true}) - if effect := session.Handle(Event{Text: "c", Control: true}); effect.Copy == nil || *effect.Copy != "bé" { - t.Fatal("copy selection") - } - if !session.Handle(Event{Text: "v", Control: true}).Paste { - t.Fatal("paste host request missing") - } - before := session.Values()["code"].Text - if !strings.Contains(session.Insert("too long to fit").Speech, "limit") || session.Values()["code"].Text != before { - t.Fatal("oversized insertion changed field") - } - if !strings.Contains(session.Insert("bad\ntext").Speech, "single-line") { - t.Fatal("multiline paste accepted") - } - if session.Insert(string([]byte{0xff})).Speech != "Invalid text" || session.Values()["code"].Text != before { - t.Fatal("invalid UTF-8 paste changed entry") - } - session.Handle(Event{Key: Tab}) - session.Handle(Event{Text: " "}) - if !session.Values()["keep"].Checked { - t.Fatal("checkbox not toggled / disabled control took focus") - } - session.Handle(Event{Key: Tab}) - if session.Handle(Event{Key: Enter}).Activated != "submit" { - t.Fatal("button did not submit") - } - session.Handle(Event{Key: Tab}) - if !strings.Contains(session.Presentation().Speech, "Code") { - t.Fatal("Tab did not wrap") - } - session.Handle(Event{Key: Tab, Shift: true}) - if session.Handle(Event{Key: Enter}).Activated != "submit" { - t.Fatal("Shift Tab did not wrap") - } -} - -func TestWordMovementAndSelection(t *testing.T) { - session, _ := NewSession(Form{Title: "Edit", Elements: []Element{{ID: "text", Label: "Text", Kind: Entry, Text: "one two 猫"}}}) - session.Handle(Event{Key: Left, Control: true, Shift: true}) - if effect := session.Handle(Event{Text: "c", Control: true}); effect.Copy == nil || *effect.Copy != "猫" { - t.Fatal("word selection") - } - session.Handle(Event{Key: Backspace}) - if session.Values()["text"].Text != "one two " { - t.Fatal("word selection deletion") - } - session.Handle(Event{Key: Home}) - session.Handle(Event{Key: Right, Control: true}) - session.Insert("é") - if session.Values()["text"].Text != "one étwo " { - t.Fatalf("word movement = %+v", session.Values()) - } -} - -func TestInvalidForms(t *testing.T) { - for _, form := range []Form{{}, {Title: "Empty", Elements: []Element{{ID: "list", Label: "List", Kind: List}}}, {Title: "Duplicate", Elements: []Element{{ID: "same", Label: "First", Kind: Button}, {ID: "same", Label: "Second", Kind: Entry}}}} { - if _, err := NewSession(form); err == nil { - t.Fatalf("accepted invalid form %+v", form) - } - } -} - -func TestButtonActivationValidatesRequiredEntries(t *testing.T) { - for _, event := range []Event{{Key: Enter}, {Key: Text, Text: " "}} { - t.Run(map[Key]string{Enter: "Enter", Text: "Space"}[event.Key], func(t *testing.T) { - session, err := NewSession(Form{Title: "Receive", Elements: []Element{ - {ID: "code", Label: "Code", Kind: Entry, Required: true}, - {ID: "submit", Label: "Receive", Kind: Button}, - }}) - if err != nil { - t.Fatal(err) - } - session.Handle(Event{Key: Tab}) - if effect := session.Handle(event); effect.Activated != "" || effect.Speech != "Code is required" { - t.Fatalf("empty required field accepted: %+v", effect) - } - session.Handle(Event{Key: Tab, Shift: true}) - session.Insert("1234") - session.Handle(Event{Key: Tab}) - if effect := session.Handle(event); effect.Activated != "submit" { - t.Fatalf("completed form rejected: %+v", effect) - } - }) - } -} diff --git a/internal/interaction/shared.go b/internal/interaction/shared.go deleted file mode 100644 index eba9302..0000000 --- a/internal/interaction/shared.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2026 Storm Dragon -// SPDX-License-Identifier: GPL-3.0-or-later - -// Package interaction preserves the reader API for the shared UI toolkit. -package interaction - -import shared "git.stormux.org/storm/screenreader-common/interaction" -import ui "git.stormux.org/storm/screenreader-common/internalui" - -type Kind = shared.Kind -type Item = shared.Item -type Element = shared.Element -type Form = shared.Form -type Key = shared.Key -type Event = shared.Event -type Presentation = shared.Presentation -type Effect = shared.Effect -type Value = shared.Value -type Session = shared.Session -type GridTab = shared.GridTab - -const ( - List = shared.List - Entry = shared.Entry - CheckBox = shared.CheckBox - Button = shared.Button - Text = shared.Text - Up = shared.Up - Down = shared.Down - Left = shared.Left - Right = shared.Right - Home = shared.Home - End = shared.End - PageUp = shared.PageUp - PageDown = shared.PageDown - Tab = shared.Tab - Enter = shared.Enter - Escape = shared.Escape - Backspace = shared.Backspace - Delete = shared.Delete -) - -func NewSession(form Form) (*Session, error) { return shared.NewSession(form) } -func ValidatePreferences(form Form) error { return shared.ValidatePreferences(form) } -func NewNavigationSession(title string, items []Item, selected int) (*Session, error) { - return shared.NewNavigationSession(title, items, selected) -} -func NewGridSession(title string, tabs []GridTab, columns int, checkbox Element) (*Session, error) { - return shared.NewGridSession(title, tabs, columns, checkbox) -} - -func NewUnifiedSession(form ui.Form, messages ui.Messages) (*Session, error) { - return shared.NewUnifiedSession(form, messages) -} diff --git a/internal/logging/duckdb.go b/internal/logging/duckdb.go index a095664..4b4d5b6 100644 --- a/internal/logging/duckdb.go +++ b/internal/logging/duckdb.go @@ -17,365 +17,9 @@ package logging -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "strings" - "time" -) +import "errors" // ErrDuckDBUnavailable reports that DuckDB debug logging cannot be used in // this build or on this system: either the build was compiled without // -tags duckdb, or libduckdb could not be loaded at runtime. var ErrDuckDBUnavailable = errors.New("duckdb debug logging unavailable (requires a -tags duckdb build and an installed libduckdb)") - -// Debug database schema. The fields Handler.format emits for every record -// become typed columns, and so do the record attributes listed in -// promotedAttrs: keys that real logs show are frequent, scalar, and -// type-stable, which makes them honest filter and aggregate dimensions for -// SQL (real types, column statistics, no JSON extraction). Everything else -// is preserved verbatim in the attrs JSON column, promoted keys included, -// because the full key set is open-ended (over 100 keys, nested objects -// and arrays, occasional type changes), so one column per key is not -// viable. Promoted columns follow attrs so a v1 database upgrades in -// place by appending them. -const ( - duckDBSchemaVersion = "2" - duckDBSchemaVersionV1 = "1" - - duckDBCreateMeta = `CREATE TABLE IF NOT EXISTS meta ( - key VARCHAR PRIMARY KEY, - value VARCHAR NOT NULL - )` - duckDBCreateSessions = `CREATE TABLE IF NOT EXISTS sessions ( - session_id VARCHAR PRIMARY KEY, - started_at TIMESTAMPTZ NOT NULL, - pid BIGINT NOT NULL - )` -) - -// Column order here is the appender order in duckdb_native.go. -var duckDBCreateLogs = buildLogsDDL() - -func buildLogsDDL() string { - var ddl strings.Builder - ddl.WriteString(`CREATE TABLE IF NOT EXISTS logs ( - seq BIGINT NOT NULL, - session_id VARCHAR NOT NULL, - ts TIMESTAMPTZ NOT NULL, - level VARCHAR NOT NULL, - message VARCHAR NOT NULL, - source VARCHAR, - function VARCHAR, - attrs JSON NOT NULL`) - for _, attr := range promotedAttrs { - fmt.Fprintf(&ddl, ",\n\t\t\"%s\" %s", attr.key, attr.sqlType()) - } - ddl.WriteString("\n\t)") - return ddl.String() -} - -type promotedKind int - -const ( - promotedText promotedKind = iota - promotedInt - promotedBool -) - -type promotedAttr struct { - key string - kind promotedKind -} - -func (attr promotedAttr) sqlType() string { - switch attr.kind { - case promotedInt: - return "BIGINT" - case promotedBool: - return "BOOLEAN" - default: - return "VARCHAR" - } -} - -// promotedAttrs was derived by profiling real debug sessions: every key -// here is scalar and single-typed (null aside) at meaningful frequency, or -// carries errors. Free-text payloads (utterance, speech_text) stay in -// attrs only; they are content, not dimensions. -var promotedAttrs = []promotedAttr{ - {key: "role", kind: promotedText}, - {key: "type", kind: promotedText}, - {key: "bus", kind: promotedText}, - {key: "source_path", kind: promotedText}, - {key: "application", kind: promotedText}, - {key: "window_path", kind: promotedText}, - {key: "native_type", kind: promotedText}, - {key: "origin_path", kind: promotedText}, - {key: "window_bus", kind: promotedText}, - {key: "focus_outside_document", kind: promotedText}, - {key: "radio_group_name", kind: promotedText}, - {key: "editable_root", kind: promotedText}, - {key: "read_only_combo", kind: promotedText}, - {key: "key", kind: promotedText}, - {key: "cause", kind: promotedText}, - {key: "reason", kind: promotedText}, - {key: "command", kind: promotedText}, - {key: "object_path", kind: promotedText}, - {key: "capture_reason", kind: promotedText}, - {key: "error", kind: promotedText}, - {key: "component", kind: promotedText}, - {key: "service", kind: promotedText}, - - {key: "window_recovered", kind: promotedBool}, - {key: "focused", kind: promotedBool}, - {key: "browser_tab", kind: promotedBool}, - {key: "selected", kind: promotedBool}, - {key: "checked", kind: promotedBool}, - {key: "prompt_message_present", kind: promotedBool}, - {key: "editable", kind: promotedBool}, - {key: "autocomplete", kind: promotedBool}, - {key: "autocomplete_popup", kind: promotedBool}, - {key: "native_caret_known", kind: promotedBool}, - {key: "input_repeat", kind: promotedBool}, - {key: "append", kind: promotedBool}, - {key: "interrupt_previous", kind: promotedBool}, - {key: "character", kind: promotedBool}, - {key: "custom_echo", kind: promotedBool}, - {key: "moved", kind: promotedBool}, - {key: "has_offset", kind: promotedBool}, - - {key: "snapshot_duration", kind: promotedInt}, - {key: "event_detail1", kind: promotedInt}, - {key: "native_caret_offset", kind: promotedInt}, - {key: "native_line_start", kind: promotedInt}, - {key: "character_count", kind: promotedInt}, - {key: "selection_start", kind: promotedInt}, - {key: "selection_end", kind: promotedInt}, - {key: "input_timestamp", kind: promotedInt}, - {key: "recent", kind: promotedInt}, - {key: "input_keycode", kind: promotedInt}, - {key: "read_all_index", kind: promotedInt}, - {key: "capture_duration", kind: promotedInt}, - {key: "speech_style", kind: promotedInt}, - {key: "unit", kind: promotedInt}, - {key: "offset", kind: promotedInt}, - {key: "elapsed", kind: promotedInt}, - {key: "duration", kind: promotedInt}, - {key: "stage_duration", kind: promotedInt}, - {key: "captured_nodes", kind: promotedInt}, - {key: "pending_nodes", kind: promotedInt}, - {key: "text_bytes", kind: promotedInt}, -} - -// promotedValue is one promotedAttrs entry decoded from a record. valid is -// false when the key is absent, JSON null, or holds a different type than -// the column; the value still survives in attrs in every case. -type promotedValue struct { - text string - integer int64 - boolean bool - valid bool -} - -func decodePromoted(kind promotedKind, raw json.RawMessage) promotedValue { - if string(raw) == "null" { - return promotedValue{} - } - switch kind { - case promotedText: - var value string - if json.Unmarshal(raw, &value) == nil { - return promotedValue{text: value, valid: true} - } - case promotedInt: - var value int64 - if json.Unmarshal(raw, &value) == nil { - return promotedValue{integer: value, valid: true} - } - case promotedBool: - var value bool - if json.Unmarshal(raw, &value) == nil { - return promotedValue{boolean: value, valid: true} - } - } - return promotedValue{} -} - -// parsedRecord is one formatted log line split into typed columns and the -// remaining attributes as JSON object text. -type parsedRecord struct { - timestamp time.Time - level string - message string - source string - function string - attrs string - promoted []promotedValue -} - -// parseLogRecord splits one NDJSON line produced by Handler.format. The -// formatter emits message, level, source and function first, then any -// record attributes, and time last of all. An attribute may reuse one of -// those names (for example an integer "level" attribute), so the leading -// fields are owned by their first occurrence and time by its last; -// superseded duplicates fall through to attrs. ok is false for lines that -// do not match the formatter's shape, in which case the caller stores the -// raw line instead of dropping it. -func parseLogRecord(line []byte) (record parsedRecord, ok bool) { - decoder := json.NewDecoder(bytes.NewReader(line)) - token, err := decoder.Token() - if err != nil { - return parsedRecord{}, false - } - if delim, isDelim := token.(json.Delim); !isDelim || delim != '{' { - return parsedRecord{}, false - } - attrs := map[string]json.RawMessage{} - seen := map[string]bool{} - var timeRaw json.RawMessage - for decoder.More() { - keyToken, err := decoder.Token() - if err != nil { - return parsedRecord{}, false - } - key, isString := keyToken.(string) - if !isString { - return parsedRecord{}, false - } - var raw json.RawMessage - if err := decoder.Decode(&raw); err != nil { - return parsedRecord{}, false - } - if key == "time" { - // The formatter's timestamp comes last; any earlier "time" - // attribute is demoted to attrs when the real one arrives. - if timeRaw != nil { - attrs["time"] = timeRaw - } - timeRaw = raw - continue - } - if isReservedLogKey(key) && !seen[key] { - seen[key] = true - if !record.setReserved(key, raw) { - return parsedRecord{}, false - } - continue - } - attrs[key] = raw - } - if _, err := decoder.Token(); err != nil { // closing brace - return parsedRecord{}, false - } - if _, err := decoder.Token(); err != io.EOF { // trailing newline only - return parsedRecord{}, false - } - if !seen["message"] || !seen["level"] || timeRaw == nil { - return parsedRecord{}, false - } - var timeText string - if err := json.Unmarshal(timeRaw, &timeText); err != nil { - return parsedRecord{}, false - } - parsedTime, err := time.Parse(time.RFC3339Nano, timeText) - if err != nil { - return parsedRecord{}, false - } - record.timestamp = parsedTime - if len(attrs) == 0 { - record.attrs = "{}" - } else { - encoded, err := json.Marshal(attrs) - if err != nil { - return parsedRecord{}, false - } - record.attrs = string(encoded) - } - record.promoted = make([]promotedValue, len(promotedAttrs)) - for i, attr := range promotedAttrs { - if raw, present := attrs[attr.key]; present { - record.promoted[i] = decodePromoted(attr.kind, raw) - } - } - return record, true -} - -func isReservedLogKey(key string) bool { - switch key { - case "message", "level", "source", "function": - return true - } - return false -} - -func (record *parsedRecord) setReserved(key string, raw json.RawMessage) bool { - var text string - if err := json.Unmarshal(raw, &text); err != nil { - return false - } - switch key { - case "message": - record.message = text - case "level": - record.level = text - case "source": - record.source = text - case "function": - record.function = text - } - return true -} - -// multiWriter fans each formatted record out to every sink, for example the -// NDJSON file and the DuckDB database at the same time. A failing sink does -// not starve the others; errors are joined and reported to the diagnostics -// loop, which records them like any other write error. -type multiWriter struct { - writers []DiagnosticsWriter -} - -func NewMultiWriter(writers ...DiagnosticsWriter) DiagnosticsWriter { - live := make([]DiagnosticsWriter, 0, len(writers)) - for _, writer := range writers { - if writer != nil { - live = append(live, writer) - } - } - switch len(live) { - case 0: - return NewPassthroughWriter(nil) - case 1: - return live[0] - } - return &multiWriter{writers: live} -} - -func (writer *multiWriter) Write(data []byte) (int, error) { - var joined error - for _, sink := range writer.writers { - if _, err := sink.Write(data); err != nil { - joined = errors.Join(joined, err) - } - } - return len(data), joined -} - -func (writer *multiWriter) Cancel() error { - var joined error - for _, sink := range writer.writers { - joined = errors.Join(joined, sink.Cancel()) - } - return joined -} - -func (writer *multiWriter) Close() error { - var joined error - for _, sink := range writer.writers { - joined = errors.Join(joined, sink.Close()) - } - return joined -} diff --git a/internal/logging/duckdb_schema.go b/internal/logging/duckdb_schema.go new file mode 100644 index 0000000..c99c93b --- /dev/null +++ b/internal/logging/duckdb_schema.go @@ -0,0 +1,327 @@ +//go:build duckdb && cgo + +// Cthulhu screen reader. +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +package logging + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "strings" + "time" +) + +// Debug database schema. The fields Handler.format emits for every record +// become typed columns, and so do the record attributes listed in +// promotedAttrs: keys that real logs show are frequent, scalar, and +// type-stable, which makes them honest filter and aggregate dimensions for +// SQL (real types, column statistics, no JSON extraction). Everything else +// is preserved verbatim in the attrs JSON column, promoted keys included, +// because the full key set is open-ended (over 100 keys, nested objects +// and arrays, occasional type changes), so one column per key is not +// viable. Promoted columns follow attrs so a v1 database upgrades in +// place by appending them. +const ( + duckDBSchemaVersion = "2" + duckDBSchemaVersionV1 = "1" + + duckDBCreateMeta = `CREATE TABLE IF NOT EXISTS meta ( + key VARCHAR PRIMARY KEY, + value VARCHAR NOT NULL + )` + duckDBCreateSessions = `CREATE TABLE IF NOT EXISTS sessions ( + session_id VARCHAR PRIMARY KEY, + started_at TIMESTAMPTZ NOT NULL, + pid BIGINT NOT NULL + )` +) + +// Column order here is the appender order in duckdb_native.go. +var duckDBCreateLogs = buildLogsDDL() + +func buildLogsDDL() string { + var ddl strings.Builder + ddl.WriteString(`CREATE TABLE IF NOT EXISTS logs ( + seq BIGINT NOT NULL, + session_id VARCHAR NOT NULL, + ts TIMESTAMPTZ NOT NULL, + level VARCHAR NOT NULL, + message VARCHAR NOT NULL, + source VARCHAR, + function VARCHAR, + attrs JSON NOT NULL`) + for _, attr := range promotedAttrs { + fmt.Fprintf(&ddl, ",\n\t\t\"%s\" %s", attr.key, attr.sqlType()) + } + ddl.WriteString("\n\t)") + return ddl.String() +} + +type promotedKind int + +const ( + promotedText promotedKind = iota + promotedInt + promotedBool +) + +type promotedAttr struct { + key string + kind promotedKind +} + +func (attr promotedAttr) sqlType() string { + switch attr.kind { + case promotedInt: + return "BIGINT" + case promotedBool: + return "BOOLEAN" + default: + return "VARCHAR" + } +} + +// promotedAttrs was derived by profiling real debug sessions: every key +// here is scalar and single-typed (null aside) at meaningful frequency, or +// carries errors. Free-text payloads (utterance, speech_text) stay in +// attrs only; they are content, not dimensions. +var promotedAttrs = []promotedAttr{ + {key: "role", kind: promotedText}, + {key: "type", kind: promotedText}, + {key: "bus", kind: promotedText}, + {key: "source_path", kind: promotedText}, + {key: "application", kind: promotedText}, + {key: "window_path", kind: promotedText}, + {key: "native_type", kind: promotedText}, + {key: "origin_path", kind: promotedText}, + {key: "window_bus", kind: promotedText}, + {key: "focus_outside_document", kind: promotedText}, + {key: "radio_group_name", kind: promotedText}, + {key: "editable_root", kind: promotedText}, + {key: "read_only_combo", kind: promotedText}, + {key: "key", kind: promotedText}, + {key: "cause", kind: promotedText}, + {key: "reason", kind: promotedText}, + {key: "command", kind: promotedText}, + {key: "object_path", kind: promotedText}, + {key: "capture_reason", kind: promotedText}, + {key: "error", kind: promotedText}, + {key: "component", kind: promotedText}, + {key: "service", kind: promotedText}, + + {key: "window_recovered", kind: promotedBool}, + {key: "focused", kind: promotedBool}, + {key: "browser_tab", kind: promotedBool}, + {key: "selected", kind: promotedBool}, + {key: "checked", kind: promotedBool}, + {key: "prompt_message_present", kind: promotedBool}, + {key: "editable", kind: promotedBool}, + {key: "autocomplete", kind: promotedBool}, + {key: "autocomplete_popup", kind: promotedBool}, + {key: "native_caret_known", kind: promotedBool}, + {key: "input_repeat", kind: promotedBool}, + {key: "append", kind: promotedBool}, + {key: "interrupt_previous", kind: promotedBool}, + {key: "character", kind: promotedBool}, + {key: "custom_echo", kind: promotedBool}, + {key: "moved", kind: promotedBool}, + {key: "has_offset", kind: promotedBool}, + + {key: "snapshot_duration", kind: promotedInt}, + {key: "event_detail1", kind: promotedInt}, + {key: "native_caret_offset", kind: promotedInt}, + {key: "native_line_start", kind: promotedInt}, + {key: "character_count", kind: promotedInt}, + {key: "selection_start", kind: promotedInt}, + {key: "selection_end", kind: promotedInt}, + {key: "input_timestamp", kind: promotedInt}, + {key: "recent", kind: promotedInt}, + {key: "input_keycode", kind: promotedInt}, + {key: "read_all_index", kind: promotedInt}, + {key: "capture_duration", kind: promotedInt}, + {key: "speech_style", kind: promotedInt}, + {key: "unit", kind: promotedInt}, + {key: "offset", kind: promotedInt}, + {key: "elapsed", kind: promotedInt}, + {key: "duration", kind: promotedInt}, + {key: "stage_duration", kind: promotedInt}, + {key: "captured_nodes", kind: promotedInt}, + {key: "pending_nodes", kind: promotedInt}, + {key: "text_bytes", kind: promotedInt}, +} + +// promotedValue is one promotedAttrs entry decoded from a record. valid is +// false when the key is absent, JSON null, or holds a different type than +// the column; the value still survives in attrs in every case. +type promotedValue struct { + text string + integer int64 + boolean bool + valid bool +} + +func decodePromoted(kind promotedKind, raw json.RawMessage) promotedValue { + if string(raw) == "null" { + return promotedValue{} + } + switch kind { + case promotedText: + var value string + if json.Unmarshal(raw, &value) == nil { + return promotedValue{text: value, valid: true} + } + case promotedInt: + var value int64 + if json.Unmarshal(raw, &value) == nil { + return promotedValue{integer: value, valid: true} + } + case promotedBool: + var value bool + if json.Unmarshal(raw, &value) == nil { + return promotedValue{boolean: value, valid: true} + } + } + return promotedValue{} +} + +// parsedRecord is one formatted log line split into typed columns and the +// remaining attributes as JSON object text. +type parsedRecord struct { + timestamp time.Time + level string + message string + source string + function string + attrs string + promoted []promotedValue +} + +// parseLogRecord splits one NDJSON line produced by Handler.format. The +// formatter emits message, level, source and function first, then any +// record attributes, and time last of all. An attribute may reuse one of +// those names (for example an integer "level" attribute), so the leading +// fields are owned by their first occurrence and time by its last; +// superseded duplicates fall through to attrs. ok is false for lines that +// do not match the formatter's shape, in which case the caller stores the +// raw line instead of dropping it. +func parseLogRecord(line []byte) (record parsedRecord, ok bool) { + decoder := json.NewDecoder(bytes.NewReader(line)) + token, err := decoder.Token() + if err != nil { + return parsedRecord{}, false + } + if delim, isDelim := token.(json.Delim); !isDelim || delim != '{' { + return parsedRecord{}, false + } + attrs := map[string]json.RawMessage{} + seen := map[string]bool{} + var timeRaw json.RawMessage + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return parsedRecord{}, false + } + key, isString := keyToken.(string) + if !isString { + return parsedRecord{}, false + } + var raw json.RawMessage + if err := decoder.Decode(&raw); err != nil { + return parsedRecord{}, false + } + if key == "time" { + // The formatter's timestamp comes last; any earlier "time" + // attribute is demoted to attrs when the real one arrives. + if timeRaw != nil { + attrs["time"] = timeRaw + } + timeRaw = raw + continue + } + if isReservedLogKey(key) && !seen[key] { + seen[key] = true + if !record.setReserved(key, raw) { + return parsedRecord{}, false + } + continue + } + attrs[key] = raw + } + if _, err := decoder.Token(); err != nil { // closing brace + return parsedRecord{}, false + } + if _, err := decoder.Token(); err != io.EOF { // trailing newline only + return parsedRecord{}, false + } + if !seen["message"] || !seen["level"] || timeRaw == nil { + return parsedRecord{}, false + } + var timeText string + if err := json.Unmarshal(timeRaw, &timeText); err != nil { + return parsedRecord{}, false + } + parsedTime, err := time.Parse(time.RFC3339Nano, timeText) + if err != nil { + return parsedRecord{}, false + } + record.timestamp = parsedTime + if len(attrs) == 0 { + record.attrs = "{}" + } else { + encoded, err := json.Marshal(attrs) + if err != nil { + return parsedRecord{}, false + } + record.attrs = string(encoded) + } + record.promoted = make([]promotedValue, len(promotedAttrs)) + for i, attr := range promotedAttrs { + if raw, present := attrs[attr.key]; present { + record.promoted[i] = decodePromoted(attr.kind, raw) + } + } + return record, true +} + +func isReservedLogKey(key string) bool { + switch key { + case "message", "level", "source", "function": + return true + } + return false +} + +func (record *parsedRecord) setReserved(key string, raw json.RawMessage) bool { + var text string + if err := json.Unmarshal(raw, &text); err != nil { + return false + } + switch key { + case "message": + record.message = text + case "level": + record.level = text + case "source": + record.source = text + case "function": + record.function = text + } + return true +} diff --git a/internal/logging/duckdb_test.go b/internal/logging/duckdb_schema_test.go similarity index 83% rename from internal/logging/duckdb_test.go rename to internal/logging/duckdb_schema_test.go index f1b580a..35eb5f3 100644 --- a/internal/logging/duckdb_test.go +++ b/internal/logging/duckdb_schema_test.go @@ -1,3 +1,5 @@ +//go:build duckdb && cgo + // Cthulhu screen reader. // Copyright (c) 2026 Storm Dragon // Authors: Storm Dragon, Angus Kola @@ -19,8 +21,6 @@ package logging import ( "encoding/json" - "errors" - "strings" "testing" "time" ) @@ -181,48 +181,3 @@ func TestParseLogRecordTimeAttrDoesNotStealTimestamp(t *testing.T) { } } } - -type recordingSink struct { - writes [][]byte - writeErr error - cancels int - closes int -} - -func (sink *recordingSink) Write(data []byte) (int, error) { - sink.writes = append(sink.writes, append([]byte(nil), data...)) - return len(data), sink.writeErr -} - -func (sink *recordingSink) Cancel() error { sink.cancels++; return nil } -func (sink *recordingSink) Close() error { sink.closes++; return nil } - -func TestMultiWriterFansOutDespiteFailure(t *testing.T) { - failing := &recordingSink{writeErr: errors.New("sink failed")} - healthy := &recordingSink{} - writer := NewMultiWriter(failing, healthy) - - line := []byte("{\"message\":\"m\"}\n") - if _, err := writer.Write(line); err == nil || !strings.Contains(err.Error(), "sink failed") { - t.Fatalf("Write error = %v", err) - } - if len(failing.writes) != 1 || len(healthy.writes) != 1 { - t.Fatalf("writes = %d/%d, want both sinks served", len(failing.writes), len(healthy.writes)) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - if failing.closes != 1 || healthy.closes != 1 { - t.Fatalf("closes = %d/%d", failing.closes, healthy.closes) - } -} - -func TestMultiWriterPassesThroughSingleSink(t *testing.T) { - sink := &recordingSink{} - if got := NewMultiWriter(sink); got != DiagnosticsWriter(sink) { - t.Fatalf("single sink wrapped: %T", got) - } - if got := NewMultiWriter(); got == nil { - t.Fatal("empty multi writer is nil") - } -} diff --git a/internal/logging/multi_writer.go b/internal/logging/multi_writer.go new file mode 100644 index 0000000..03180ec --- /dev/null +++ b/internal/logging/multi_writer.go @@ -0,0 +1,79 @@ +// Cthulhu screen reader. +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +package logging + +import ( + "errors" + "io" +) + +// multiWriter fans each formatted record out to every sink, for example the +// NDJSON file and the DuckDB database at the same time. A failing sink does +// not starve the others; errors are joined and reported to the diagnostics +// loop, which records them like any other write error. +type multiWriter struct { + writers []DiagnosticsWriter +} + +func NewMultiWriter(writers ...DiagnosticsWriter) DiagnosticsWriter { + live := make([]DiagnosticsWriter, 0, len(writers)) + for _, writer := range writers { + if writer != nil { + live = append(live, writer) + } + } + switch len(live) { + case 0: + return NewPassthroughWriter(nil) + case 1: + return live[0] + } + return &multiWriter{writers: live} +} + +func (writer *multiWriter) Write(data []byte) (int, error) { + var joined error + written := len(data) + for _, sink := range writer.writers { + count, err := sink.Write(data) + written = min(written, count) + if count != len(data) && err == nil { + err = io.ErrShortWrite + } + if err != nil { + joined = errors.Join(joined, err) + } + } + return written, joined +} + +func (writer *multiWriter) Cancel() error { + var joined error + for _, sink := range writer.writers { + joined = errors.Join(joined, sink.Cancel()) + } + return joined +} + +func (writer *multiWriter) Close() error { + var joined error + for _, sink := range writer.writers { + joined = errors.Join(joined, sink.Close()) + } + return joined +} diff --git a/internal/logging/multi_writer_test.go b/internal/logging/multi_writer_test.go new file mode 100644 index 0000000..764a67d --- /dev/null +++ b/internal/logging/multi_writer_test.go @@ -0,0 +1,89 @@ +// Cthulhu screen reader. +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +package logging + +import ( + "errors" + "io" + "strings" + "testing" +) + +type recordingSink struct { + writes [][]byte + writeErr error + cancels int + closes int +} + +func (sink *recordingSink) Write(data []byte) (int, error) { + sink.writes = append(sink.writes, append([]byte(nil), data...)) + return len(data), sink.writeErr +} + +func (sink *recordingSink) Cancel() error { sink.cancels++; return nil } +func (sink *recordingSink) Close() error { sink.closes++; return nil } + +func TestMultiWriterFansOutDespiteFailure(t *testing.T) { + failing := &recordingSink{writeErr: errors.New("sink failed")} + healthy := &recordingSink{} + writer := NewMultiWriter(failing, healthy) + + line := []byte("{\"message\":\"m\"}\n") + if _, err := writer.Write(line); err == nil || !strings.Contains(err.Error(), "sink failed") { + t.Fatalf("Write error = %v", err) + } + if len(failing.writes) != 1 || len(healthy.writes) != 1 { + t.Fatalf("writes = %d/%d, want both sinks served", len(failing.writes), len(healthy.writes)) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if failing.closes != 1 || healthy.closes != 1 { + t.Fatalf("closes = %d/%d", failing.closes, healthy.closes) + } +} + +func TestMultiWriterPassesThroughSingleSink(t *testing.T) { + sink := &recordingSink{} + if got := NewMultiWriter(sink); got != DiagnosticsWriter(sink) { + t.Fatalf("single sink wrapped: %T", got) + } + if got := NewMultiWriter(); got == nil { + t.Fatal("empty multi writer is nil") + } +} + +type shortSink struct{ recordingSink } + +func (sink *shortSink) Write(data []byte) (int, error) { + return len(data) - 1, nil +} + +func TestMultiWriterReportsShortWritesAndContinues(t *testing.T) { + healthy := &recordingSink{} + writer := NewMultiWriter(&shortSink{}, healthy) + line := []byte("record\n") + count, err := writer.Write(line) + if count != len(line)-1 || !errors.Is(err, io.ErrShortWrite) { + t.Fatalf("Write = %d, %v; want short write", count, err) + } + if len(healthy.writes) != 1 || string(healthy.writes[0]) != string(line) { + t.Fatal("short write prevented delivery to the healthy sink") + } +} diff --git a/internal/ocr/capture.go b/internal/ocr/capture.go index 41735b8..cb3d90a 100644 --- a/internal/ocr/capture.go +++ b/internal/ocr/capture.go @@ -53,7 +53,7 @@ func (request CaptureRequest) Validate() error { } switch request.Kind { case ObjectSource: - if !valid_screen_rectangle(request.Bounds) { + if !validScreenRectangle(request.Bounds) { return ErrSource } case WindowSource, DesktopSource, ClipboardSource: @@ -120,14 +120,14 @@ func (capturer *Capturer) Capture(ctx context.Context, request CaptureRequest) ( if err != nil { return Capture{}, ErrSource } - output, _, err := run_process(ctx, capturer.command, input, maxImageBytes+maxCaptureHeader, "--ocr-capture") + output, _, err := runProcess(ctx, capturer.command, input, maxImageBytes+maxCaptureHeader, "--ocr-capture") if err != nil { if errors.Is(err, ErrUnavailable) || errors.Is(err, ErrRecognition) { return Capture{}, ErrCapture } return Capture{}, err } - capture, err := decode_capture(output, request) + capture, err := decodeCapture(output, request) if ctx.Err() != nil { return Capture{}, ctx.Err() } @@ -157,10 +157,10 @@ func WriteCaptureResponse(output io.Writer, header CaptureHeader, pixels image.I if err != nil || len(data)+1 > maxCaptureHeader { return ErrLimit } - buffer := &bounded_buffer{ctx: context.Background(), limit: maxImageBytes + maxCaptureHeader} + buffer := &boundedBuffer{ctx: context.Background(), limit: maxImageBytes + maxCaptureHeader} _, _ = buffer.Write(append(data, '\n')) if header.Status == "" { - if pixels == nil || !valid_dimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) { + if pixels == nil || !validDimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) { return ErrInvalidImage } if err := png.Encode(buffer, pixels); err != nil { @@ -171,7 +171,7 @@ func WriteCaptureResponse(output io.Writer, header CaptureHeader, pixels image.I return err } -func decode_capture(data []byte, request CaptureRequest) (Capture, error) { +func decodeCapture(data []byte, request CaptureRequest) (Capture, error) { separator := bytes.IndexByte(data, '\n') if separator < 0 || separator >= maxCaptureHeader || len(data) > maxImageBytes+maxCaptureHeader { return Capture{}, ErrCapture @@ -204,7 +204,7 @@ func decode_capture(data []byte, request CaptureRequest) (Capture, error) { if err != nil { return Capture{}, ErrCapture } - if !valid_dimensions(config.Width, config.Height) { + if !validDimensions(config.Width, config.Height) { return Capture{}, ErrLimit } transform := Transform{ImageContent: image.Rect(0, 0, config.Width, config.Height)} @@ -213,8 +213,8 @@ func decode_capture(data []byte, request CaptureRequest) (Capture, error) { return Capture{}, ErrCapture } } else { - if !valid_screen_rectangle(header.RootBounds) || !valid_screen_rectangle(header.SourceBounds) || - !valid_screen_rectangle(header.ScreenBounds) || !header.ScreenBounds.In(header.RootBounds) || !header.ScreenBounds.In(header.SourceBounds) || + if !validScreenRectangle(header.RootBounds) || !validScreenRectangle(header.SourceBounds) || + !validScreenRectangle(header.ScreenBounds) || !header.ScreenBounds.In(header.RootBounds) || !header.ScreenBounds.In(header.SourceBounds) || header.ScreenBounds.Dx() != config.Width || header.ScreenBounds.Dy() != config.Height { return Capture{}, ErrCapture } diff --git a/internal/ocr/capture_test.go b/internal/ocr/capture_test.go index 2988337..7577baf 100644 --- a/internal/ocr/capture_test.go +++ b/internal/ocr/capture_test.go @@ -24,11 +24,11 @@ import ( "time" ) -func capture_request() CaptureRequest { +func captureRequest() CaptureRequest { return CaptureRequest{Kind: ObjectSource, Bounds: image.Rect(-20, 10, 30, 50), Foreground: 123, Generation: 7} } -func capture_frame(t *testing.T, header CaptureHeader, pixels image.Image) []byte { +func captureFrame(t *testing.T, header CaptureHeader, pixels image.Image) []byte { t.Helper() var output bytes.Buffer if err := WriteCaptureResponse(&output, header, pixels); err != nil { @@ -38,7 +38,7 @@ func capture_frame(t *testing.T, header CaptureHeader, pixels image.Image) []byt } func TestCaptureRequestRejectsUnownedOrInvalidSources(t *testing.T) { - base := capture_request() + base := captureRequest() if err := base.Validate(); err != nil { t.Fatal(err) } @@ -80,20 +80,20 @@ func TestCaptureRequestRejectsUnownedOrInvalidSources(t *testing.T) { } func TestCaptureFrameClippingAndGeneration(t *testing.T) { - request := capture_request() + request := captureRequest() header := CaptureHeader{Request: request, SourceWindow: request.Foreground, RootBounds: image.Rect(0, 0, 100, 100), SourceBounds: image.Rect(-10, 0, 80, 80), ScreenBounds: image.Rect(0, 10, 30, 50)} pixels := image.NewRGBA(image.Rect(0, 0, 30, 40)) pixels.Set(1, 2, color.RGBA{12, 34, 56, 255}) - frame := capture_frame(t, header, pixels) - result, err := decode_capture(frame, request) + frame := captureFrame(t, header, pixels) + result, err := decodeCapture(frame, request) if err != nil { t.Fatal(err) } if color.RGBAModel.Convert(result.Pixels.At(1, 2)) != pixels.At(1, 2) { t.Fatal("pixels changed") } - if _, err := decode_capture(append(append([]byte(nil), frame...), 'x'), request); !errors.Is(err, ErrCapture) { + if _, err := decodeCapture(append(append([]byte(nil), frame...), 'x'), request); !errors.Is(err, ErrCapture) { t.Fatalf("trailing payload accepted: %v", err) } mapped, ok := result.Transform.ScreenRectangle(image.Rect(1, 2, 3, 4)) @@ -101,7 +101,7 @@ func TestCaptureFrameClippingAndGeneration(t *testing.T) { t.Fatalf("mapping: %v, %v", mapped, ok) } request.Generation++ - if _, err := decode_capture(frame, request); !errors.Is(err, ErrCapture) { + if _, err := decodeCapture(frame, request); !errors.Is(err, ErrCapture) { t.Fatalf("old generation accepted: %v", err) } request.Generation-- @@ -113,7 +113,7 @@ func TestCaptureFrameClippingAndGeneration(t *testing.T) { } { bad := header change(&bad) - if _, err := decode_capture(capture_frame(t, bad, pixels), request); err == nil { + if _, err := decodeCapture(captureFrame(t, bad, pixels), request); err == nil { t.Fatalf("invalid mapping accepted: %+v", bad) } } @@ -123,47 +123,47 @@ func TestCaptureClipboardDoesNotMapToScreen(t *testing.T) { request := CaptureRequest{Kind: ClipboardSource, Foreground: 123, Generation: 1} header := CaptureHeader{Request: request} pixels := image.NewRGBA(image.Rect(0, 0, 10, 10)) - result, err := decode_capture(capture_frame(t, header, pixels), request) + result, err := decodeCapture(captureFrame(t, header, pixels), request) if err != nil || result.Transform.HasScreenMapping { t.Fatalf("clipboard: %+v, %v", result, err) } header.ScreenBounds = image.Rect(0, 0, 10, 10) - if _, err := decode_capture(capture_frame(t, header, pixels), request); err == nil { + if _, err := decodeCapture(captureFrame(t, header, pixels), request); err == nil { t.Fatal("clipboard gained coordinates") } } func TestCaptureProtocolErrorsAndPixelLimit(t *testing.T) { - request := capture_request() + request := captureRequest() for status, want := range map[string]error{"unavailable": ErrCapture, "source": ErrSource, "changed": ErrSourceChanged, "limit": ErrLimit, "Private diagnostics": ErrCapture} { - frame := capture_frame(t, CaptureHeader{Request: request, Status: status}, nil) - _, err := decode_capture(frame, request) + frame := captureFrame(t, CaptureHeader{Request: request, Status: status}, nil) + _, err := decodeCapture(frame, request) if !errors.Is(err, want) || strings.Contains(err.Error(), "Private") { t.Fatalf("status %q: %v", status, err) } - if _, err := decode_capture(append(frame, 'x'), request); !errors.Is(err, ErrCapture) { + if _, err := decodeCapture(append(frame, 'x'), request); !errors.Is(err, ErrCapture) { t.Fatal("failure with payload accepted") } } clipboard := CaptureRequest{Kind: ClipboardSource, Foreground: 123, Generation: 1} - frame := capture_frame(t, CaptureHeader{Request: clipboard}, image.NewRGBA(image.Rect(0, 0, 1, 1))) + frame := captureFrame(t, CaptureHeader{Request: clipboard}, image.NewRGBA(image.Rect(0, 0, 1, 1))) start := bytes.IndexByte(frame, '\n') + 1 // A valid CRC and malicious IHDR are rejected before allocating pixel data. binary.BigEndian.PutUint32(frame[start+16:start+20], 10000) binary.BigEndian.PutUint32(frame[start+20:start+24], 10000) binary.BigEndian.PutUint32(frame[start+29:start+33], crc32.ChecksumIEEE(frame[start+12:start+29])) - if _, err := decode_capture(frame, clipboard); !errors.Is(err, ErrLimit) { + if _, err := decodeCapture(frame, clipboard); !errors.Is(err, ErrLimit) { t.Fatalf("oversize PNG: %v", err) } for _, invalid := range [][]byte{nil, []byte("{}\nnot a png"), bytes.Repeat([]byte{'x'}, maxCaptureHeader+1)} { - if _, err := decode_capture(invalid, request); !errors.Is(err, ErrCapture) { + if _, err := decodeCapture(invalid, request); !errors.Is(err, ErrCapture) { t.Fatalf("invalid response: %v", err) } } } func TestCapturerMissingHelperAndCancellation(t *testing.T) { - request := capture_request() + request := captureRequest() if _, err := NewCapturer("/nonexistent-ocr-capture-helper").Capture(context.Background(), request); !errors.Is(err, ErrCapture) { t.Fatalf("missing helper: %v", err) } diff --git a/internal/ocr/cursor.go b/internal/ocr/cursor.go index 45554d4..c74cab8 100644 --- a/internal/ocr/cursor.go +++ b/internal/ocr/cursor.go @@ -59,12 +59,12 @@ func NewCursor(result Result) *Cursor { return cursor } -func (cursor *Cursor) line_index() int { +func (cursor *Cursor) lineIndex() int { return sort.Search(len(cursor.lines), func(index int) bool { return cursor.lines[index].End >= cursor.offset }) } func (cursor *Cursor) Current(unit Unit) Position { - lineIndex := cursor.line_index() + lineIndex := cursor.lineIndex() line := cursor.lines[lineIndex] position := Position{Offset: cursor.offset, Line: cursor.lineTexts[lineIndex], LineStart: line.Start, Cursor: cursor.offset - line.Start} switch unit { @@ -84,7 +84,7 @@ func (cursor *Cursor) Current(unit Unit) Position { func (cursor *Cursor) Move(unit Unit, step int) Position { previous := cursor.offset - lineIndex := cursor.line_index() + lineIndex := cursor.lineIndex() line := cursor.lines[lineIndex] switch unit { case Character: @@ -119,7 +119,7 @@ func (cursor *Cursor) Move(unit Unit, step int) Position { cursor.offset = len(cursor.text) } if unit != LineUnit && unit != PageUnit { - cursor.column = cursor.offset - cursor.lines[cursor.line_index()].Start + cursor.column = cursor.offset - cursor.lines[cursor.lineIndex()].Start } position := cursor.Current(unit) position.Moved = previous != cursor.offset @@ -133,7 +133,7 @@ func (cursor *Cursor) Set(offset int) (Position, bool) { return Position{}, false } cursor.offset = offset - cursor.column = offset - cursor.lines[cursor.line_index()].Start + cursor.column = offset - cursor.lines[cursor.lineIndex()].Start return cursor.Current(Character), true } @@ -152,7 +152,7 @@ func (cursor *Cursor) Slice(start, end int) (string, bool) { // LinesFrom returns whole lines after the virtual cursor. The first line // begins at the cursor position; following lines retain recognition order. func (cursor *Cursor) LinesFrom() []ReadLine { - index := cursor.line_index() + index := cursor.lineIndex() first := index parts := make([]ReadLine, 0, len(cursor.lines)-index) for ; index < len(cursor.lines); index++ { diff --git a/internal/ocr/engine.go b/internal/ocr/engine.go index 3e21172..31ad8ac 100644 --- a/internal/ocr/engine.go +++ b/internal/ocr/engine.go @@ -103,10 +103,10 @@ func (engine *Engine) discover(ctx context.Context) (Catalog, error) { } return Catalog{}, err } - return parse_catalog(string(output)) + return parseCatalog(string(output)) } -func parse_catalog(output string) (Catalog, error) { +func parseCatalog(output string) (Catalog, error) { lines := strings.Split(strings.TrimSpace(output), "\n") header := strings.TrimSuffix(lines[0], "\r") countStart := strings.LastIndex(header, "(") @@ -121,7 +121,7 @@ func parse_catalog(output string) (Catalog, error) { seen := make(map[string]bool) for _, line := range lines[1:] { language := strings.TrimSuffix(line, "\r") - if !valid_language(language) || seen[language] { + if !validLanguage(language) || seen[language] { return Catalog{}, fmt.Errorf("%w: invalid language catalog", ErrUnavailable) } seen[language] = true @@ -140,9 +140,9 @@ func parse_catalog(output string) (Catalog, error) { return catalog, nil } -// valid_language permits upstream script/Latin-style identifiers, without +// validLanguage permits upstream script/Latin-style identifiers, without // accepting path traversal, options, whitespace or expression delimiters. -func valid_language(language string) bool { +func validLanguage(language string) bool { if language == "" || len(language) > 128 { return false } @@ -163,7 +163,7 @@ func valid_language(language string) bool { return true } -func (catalog Catalog) resolve_language(expression string) (string, error) { +func (catalog Catalog) resolveLanguage(expression string) (string, error) { if expression == "" { return catalog.DefaultLanguage, nil } @@ -172,7 +172,7 @@ func (catalog Catalog) resolve_language(expression string) (string, error) { } seen := make(map[string]bool) for _, language := range strings.Split(expression, "+") { - if !valid_language(language) || language == "osd" || seen[language] { + if !validLanguage(language) || language == "osd" || seen[language] { return "", fmt.Errorf("%w: invalid language selection", ErrUnavailable) } seen[language] = true @@ -190,7 +190,7 @@ func (catalog Catalog) resolve_language(expression string) (string, error) { func (engine *Engine) Recognize(ctx context.Context, pixels image.Image, options Options) (Result, error) { ctx, cancel := context.WithTimeout(ctx, recognitionTimeout) defer cancel() - if pixels == nil || !valid_dimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) { + if pixels == nil || !validDimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) { return Result{}, ErrInvalidImage } if options.Layout == 0 { @@ -212,11 +212,11 @@ func (engine *Engine) Recognize(ctx context.Context, pixels image.Image, options if err != nil { return Result{}, err } - language, err := catalog.resolve_language(options.Language) + language, err := catalog.resolveLanguage(options.Language) if err != nil { return Result{}, err } - encoded := &bounded_buffer{limit: maxImageBytes, ctx: ctx} + encoded := &boundedBuffer{limit: maxImageBytes, ctx: ctx} if err := png.Encode(encoded, pixels); err != nil { if ctx.Err() != nil { return Result{}, ctx.Err() diff --git a/internal/ocr/engine_test.go b/internal/ocr/engine_test.go index 24f845a..64ee19b 100644 --- a/internal/ocr/engine_test.go +++ b/internal/ocr/engine_test.go @@ -24,13 +24,13 @@ import ( ) func TestCatalogAndOrderedLanguages(t *testing.T) { - catalog, err := parse_catalog("List of available languages in \"/data\" (4):\nfra\nosd\nscript/Latin\neng\n") + catalog, err := parseCatalog("List of available languages in \"/data\" (4):\nfra\nosd\nscript/Latin\neng\n") if err != nil || catalog.DefaultLanguage != "eng" || !reflect.DeepEqual(catalog.Languages, []string{"eng", "fra", "script/Latin"}) { t.Fatalf("catalog: %+v, %v", catalog, err) } for _, expression := range []string{"", "fra+eng", "script/Latin"} { - got, err := catalog.resolve_language(expression) + got, err := catalog.resolveLanguage(expression) want := expression if want == "" { want = "eng" @@ -40,11 +40,11 @@ func TestCatalogAndOrderedLanguages(t *testing.T) { } } for _, expression := range []string{"osd", "deu", "fra+missing", "eng+eng", "eng+", "+eng", "../eng", "-l eng", "eng;command", "fra\neng"} { - if _, err := catalog.resolve_language(expression); !errors.Is(err, ErrUnavailable) { + if _, err := catalog.resolveLanguage(expression); !errors.Is(err, ErrUnavailable) { t.Fatalf("invalid/uninstalled expression %q accepted: %v", expression, err) } } - other, err := parse_catalog("List of available languages in \"/data\" (2):\nfra\ndeu\n") + other, err := parseCatalog("List of available languages in \"/data\" (2):\nfra\ndeu\n") if err != nil || other.DefaultLanguage != "deu" { t.Fatalf("default without English: %+v, %v", other, err) } @@ -59,14 +59,14 @@ func TestMissingAndMalformedCatalogs(t *testing.T) { "List of available languages in \"/data\" (1):\neng\nfra\n", "List of available languages in \"/data\" (1):\n../eng\n", } { - _, err := parse_catalog(output) + _, err := parseCatalog(output) if !errors.Is(err, ErrUnavailable) || !strings.HasPrefix(err.Error(), "OCR not available") || strings.Contains(err.Error(), "Private") { t.Fatalf("unavailable message: %v", err) } } } -func test_engine(t *testing.T, mode string) *Engine { +func testEngine(t *testing.T, mode string) *Engine { t.Helper() executable, err := os.Executable() if err != nil { @@ -82,7 +82,7 @@ func test_engine(t *testing.T, mode string) *Engine { } func TestEngineRecognizesOneTSVInvocation(t *testing.T) { - engine := test_engine(t, "success") + engine := testEngine(t, "success") original := engine.command var invocations [][]string engine.command = func(ctx context.Context, args ...string) *exec.Cmd { @@ -118,7 +118,7 @@ func TestEngineMissingExecutableAndUnavailableLanguage(t *testing.T) { if _, err := engine.Recognize(context.Background(), image.NewGray(image.Rect(0, 0, 100, 100)), Options{}); !errors.Is(err, ErrUnavailable) { t.Fatalf("missing executable recognition: %v", err) } - engine = test_engine(t, "success") + engine = testEngine(t, "success") original := engine.command var invocations int engine.command = func(ctx context.Context, args ...string) *exec.Cmd { @@ -158,7 +158,7 @@ func TestEngineFailuresAndOutputBounds(t *testing.T) { {"catalog-limit", ErrLimit}, } { t.Run(test.mode, func(t *testing.T) { - engine := test_engine(t, test.mode) + engine := testEngine(t, test.mode) result, err := engine.Recognize(context.Background(), image.NewGray(image.Rect(0, 0, 100, 100)), Options{}) if !errors.Is(err, test.want) || result.Text != "" || len(result.Words) != 0 { t.Fatalf("result: %+v, error: %v; want %v", result, err, test.want) @@ -176,7 +176,7 @@ func TestEngineRejectsInvalidImageAndLayoutBeforeStartingChild(t *testing.T) { t.Fatal("child invoked for invalid request") return nil } - for _, pixels := range []image.Image{nil, image.NewGray(image.Rectangle{}), oversized_image{}} { + for _, pixels := range []image.Image{nil, image.NewGray(image.Rectangle{}), oversizedImage{}} { if _, err := engine.Recognize(context.Background(), pixels, Options{}); !errors.Is(err, ErrInvalidImage) { t.Fatalf("invalid image: %v", err) } @@ -186,18 +186,18 @@ func TestEngineRejectsInvalidImageAndLayoutBeforeStartingChild(t *testing.T) { } } -type oversized_image struct{ image.Image } +type oversizedImage struct{ image.Image } -func (oversized_image) Bounds() image.Rectangle { return image.Rect(0, 0, MaxPixels, 2) } +func (oversizedImage) Bounds() image.Rectangle { return image.Rect(0, 0, MaxPixels, 2) } func TestEngineCancellationReapsChildAndUnblocksWaitingRequest(t *testing.T) { - t.Run("cancel", func(t *testing.T) { check_child_cancellation(t, false) }) - t.Run("deadline", func(t *testing.T) { check_child_cancellation(t, true) }) + t.Run("cancel", func(t *testing.T) { checkChildCancellation(t, false) }) + t.Run("deadline", func(t *testing.T) { checkChildCancellation(t, true) }) } -func check_child_cancellation(t *testing.T, deadline bool) { +func checkChildCancellation(t *testing.T, deadline bool) { t.Helper() - engine := test_engine(t, "wait") + engine := testEngine(t, "wait") original := engine.command readyRead, readyWrite, err := os.Pipe() if err != nil { @@ -264,7 +264,7 @@ func check_child_cancellation(t *testing.T, deadline bool) { } func TestEngineRetiresDescendantsHoldingPipes(t *testing.T) { - engine := test_engine(t, "orphan") + engine := testEngine(t, "orphan") original := engine.command readyRead, readyWrite, err := os.Pipe() if err != nil { @@ -346,7 +346,7 @@ func TestEngineExpiredDeadlineStartsNoChild(t *testing.T) { } func TestBoundedBufferCannotBypassWriteLimit(t *testing.T) { - buffer := &bounded_buffer{limit: 5, ctx: context.Background()} + buffer := &boundedBuffer{limit: 5, ctx: context.Background()} if _, err := io.Copy(buffer, strings.NewReader("0123456789")); !errors.Is(err, ErrLimit) || buffer.Len() > 5 { t.Fatalf("writer limit bypassed: %d bytes, %v", buffer.Len(), err) } diff --git a/internal/ocr/model.go b/internal/ocr/model.go index 08961ea..cfe1241 100644 --- a/internal/ocr/model.go +++ b/internal/ocr/model.go @@ -116,9 +116,9 @@ type Transform struct { // Invalid, empty and entirely padded rectangles have no screen mapping. func (transform Transform) ScreenRectangle(bounds image.Rectangle) (image.Rectangle, bool) { content, screen := transform.ImageContent, transform.ScreenBounds - if !transform.HasScreenMapping || !valid_dimensions(content.Dx(), content.Dy()) || + if !transform.HasScreenMapping || !validDimensions(content.Dx(), content.Dy()) || content.Min.X < 0 || content.Min.Y < 0 || content.Max.X > MaxPixels || content.Max.Y > MaxPixels || - !valid_screen_rectangle(screen) { + !validScreenRectangle(screen) { return image.Rectangle{}, false } bounds = bounds.Intersect(content) @@ -137,7 +137,7 @@ func (transform Transform) ScreenRectangle(bounds image.Rectangle) (image.Rectan return mapped, !mapped.Empty() } -func valid_screen_rectangle(bounds image.Rectangle) bool { +func validScreenRectangle(bounds image.Rectangle) bool { return bounds.Min.X > math.MinInt32 && bounds.Min.Y > math.MinInt32 && bounds.Max.X <= math.MaxInt32 && bounds.Max.Y <= math.MaxInt32 && bounds.Max.X > bounds.Min.X && bounds.Max.Y > bounds.Min.Y && @@ -145,13 +145,13 @@ func valid_screen_rectangle(bounds image.Rectangle) bool { int64(bounds.Max.Y)-int64(bounds.Min.Y) <= MaxPixels } -func valid_dimensions(width, height int) bool { +func validDimensions(width, height int) bool { return width > 0 && height > 0 && height <= MaxPixels && width <= MaxPixels/height } -func valid_word_bounds(bounds image.Rectangle, width, height int) bool { +func validWordBounds(bounds image.Rectangle, width, height int) bool { return bounds.Min.X >= 0 && bounds.Min.Y >= 0 && !bounds.Empty() && bounds.Max.X <= width && bounds.Max.Y <= height } -func rune_length(text string) int { return utf8.RuneCountInString(text) } +func runeLength(text string) int { return utf8.RuneCountInString(text) } diff --git a/internal/ocr/native_test.go b/internal/ocr/native_test.go index 43e547e..580e8a6 100644 --- a/internal/ocr/native_test.go +++ b/internal/ocr/native_test.go @@ -24,7 +24,7 @@ func TestNativeTesseract(t *testing.T) { if err != nil { t.Fatal(err) } - if language, err := catalog.resolve_language("eng"); err != nil || language != "eng" { + if language, err := catalog.resolveLanguage("eng"); err != nil || language != "eng" { t.Fatal("the native painted-text fixture requires installed English data") } file, err := os.Open("testdata/painted-text.png") @@ -52,7 +52,7 @@ func TestNativeTesseract(t *testing.T) { t.Fatalf("PSM %d lost line/word structure: %+v", layout, result) } for _, word := range result.Words { - if !valid_word_bounds(word.Bounds, result.Width, result.Height) || + if !validWordBounds(word.Bounds, result.Width, result.Height) || word.Bounds.Min.X < 20 || word.Bounds.Min.Y < 15 || word.Bounds.Max.Y > 185 { t.Fatalf("PSM %d word outside painted area: %+v", layout, word) } @@ -67,7 +67,7 @@ func TestNativeTesseract(t *testing.T) { t.Fatalf("scaled recognition did not retain image coordinates: %dx%d, %d words", scaled.Width, scaled.Height, len(scaled.Words)) } for _, word := range scaled.Words { - if !valid_word_bounds(word.Bounds, scaled.Width, scaled.Height) { + if !validWordBounds(word.Bounds, scaled.Width, scaled.Height) { t.Fatalf("invalid scaled word: %+v", word) } } diff --git a/internal/ocr/preprocess.go b/internal/ocr/preprocess.go index cdbd950..3219de5 100644 --- a/internal/ocr/preprocess.go +++ b/internal/ocr/preprocess.go @@ -13,7 +13,7 @@ import ( // Preprocess returns owned pixels in recognition coordinates. Scale uses nearest // neighbor sampling so recognized word boxes map back through the capture transform. func Preprocess(ctx context.Context, source image.Image, options Options) (image.Image, error) { - if source == nil || !valid_dimensions(source.Bounds().Dx(), source.Bounds().Dy()) { + if source == nil || !validDimensions(source.Bounds().Dx(), source.Bounds().Dy()) { return nil, ErrInvalidImage } scale := options.Scale @@ -21,7 +21,7 @@ func Preprocess(ctx context.Context, source image.Image, options Options) (image scale = 1 } width, height := source.Bounds().Dx(), source.Bounds().Dy() - if scale < 1 || scale > 4 || height > MaxPixels/scale || !valid_dimensions(width*scale, height*scale) || + if scale < 1 || scale > 4 || height > MaxPixels/scale || !validDimensions(width*scale, height*scale) || options.Threshold < 0 || options.Threshold > 255 { return nil, ErrLimit } diff --git a/internal/ocr/process.go b/internal/ocr/process.go index 3965aee..5d0a23e 100644 --- a/internal/ocr/process.go +++ b/internal/ocr/process.go @@ -15,9 +15,9 @@ import ( "time" ) -// bounded_buffer never retains more than limit bytes. Child-output overflow +// boundedBuffer never retains more than limit bytes. Child-output overflow // cancels its process immediately instead of leaving a stopped pipe reader. -type bounded_buffer struct { +type boundedBuffer struct { data bytes.Buffer limit int ctx context.Context @@ -25,7 +25,7 @@ type bounded_buffer struct { overflow bool } -func (buffer *bounded_buffer) Write(data []byte) (int, error) { +func (buffer *boundedBuffer) Write(data []byte) (int, error) { if err := buffer.ctx.Err(); err != nil { return 0, err } @@ -39,14 +39,14 @@ func (buffer *bounded_buffer) Write(data []byte) (int, error) { return buffer.data.Write(data) } -func (buffer *bounded_buffer) Bytes() []byte { return buffer.data.Bytes() } -func (buffer *bounded_buffer) Len() int { return buffer.data.Len() } +func (buffer *boundedBuffer) Bytes() []byte { return buffer.data.Bytes() } +func (buffer *boundedBuffer) Len() int { return buffer.data.Len() } func (engine *Engine) run(parent context.Context, input []byte, limit int, args ...string) ([]byte, []byte, error) { - return run_process(parent, engine.command, input, limit, args...) + return runProcess(parent, engine.command, input, limit, args...) } -func run_process(parent context.Context, factory func(context.Context, ...string) *exec.Cmd, input []byte, limit int, args ...string) ([]byte, []byte, error) { +func runProcess(parent context.Context, factory func(context.Context, ...string) *exec.Cmd, input []byte, limit int, args ...string) ([]byte, []byte, error) { ctx, cancel := context.WithCancel(parent) defer cancel() command := factory(ctx, args...) @@ -65,10 +65,10 @@ func run_process(parent context.Context, factory func(context.Context, ...string } command.Cancel = kill command.WaitDelay = time.Second - command.Env = process_environment(command.Env) + command.Env = processEnvironment(command.Env) command.Stdin = bytes.NewReader(input) - output := &bounded_buffer{limit: limit, ctx: ctx, cancel: cancel} - diagnostics := &bounded_buffer{limit: maxStderrBytes, ctx: ctx, cancel: cancel} + output := &boundedBuffer{limit: limit, ctx: ctx, cancel: cancel} + diagnostics := &boundedBuffer{limit: maxStderrBytes, ctx: ctx, cancel: cancel} command.Stdout, command.Stderr = output, diagnostics err := command.Run() // WaitDelay closes inherited pipes after a bound, but os/exec only kills the @@ -92,7 +92,7 @@ func run_process(parent context.Context, factory func(context.Context, ...string return output.Bytes(), diagnostics.Bytes(), nil } -func process_environment(environment []string) []string { +func processEnvironment(environment []string) []string { if environment == nil { environment = os.Environ() } diff --git a/internal/ocr/tsv.go b/internal/ocr/tsv.go index 453aa8c..fd98d93 100644 --- a/internal/ocr/tsv.go +++ b/internal/ocr/tsv.go @@ -23,7 +23,7 @@ const tsvHeader = "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft // Malformed output is rejected atomically, with no recognized text in errors. // The supplied dimensions must describe the actual recognition image. func ParseTSV(input io.Reader, width, height int) (Result, error) { - if !valid_dimensions(width, height) { + if !validDimensions(width, height) { return Result{}, ErrInvalidImage } limited := &io.LimitedReader{R: input, N: maxTSVBytes + 1} @@ -46,41 +46,41 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) { } fields := strings.SplitN(scanner.Text(), "\t", 12) if len(fields) != 12 { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } var numbers [10]int for index := range numbers { number, err := strconv.ParseInt(fields[index], 10, 32) if err != nil || number < 0 { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } numbers[index] = int(number) } level := numbers[0] if level < 1 || level > 5 || numbers[1] < 1 { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } for index := 2; index <= 5; index++ { if (index <= level && numbers[index] < 1) || (index > level && numbers[index] != 0) { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } } confidence, err := strconv.ParseFloat(fields[10], 64) if err != nil || math.IsNaN(confidence) || math.IsInf(confidence, 0) || confidence < -1 || confidence > 100 { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } // Subtraction avoids overflowing 32-bit additions on ARM builds. left, top, boxWidth, boxHeight := numbers[6], numbers[7], numbers[8], numbers[9] if left > width || top > height || boxWidth > width-left || boxHeight > height-top { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } wordText := fields[11] if !utf8.ValidString(wordText) || strings.ContainsFunc(wordText, unicode.IsControl) { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } if level != 5 { if wordText != "" || confidence != -1 { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } continue } @@ -88,8 +88,8 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) { continue } bounds := image.Rect(left, top, left+boxWidth, top+boxHeight) - if !valid_word_bounds(bounds, width, height) || strings.TrimSpace(wordText) != wordText { - return Result{}, invalid_row(rows) + if !validWordBounds(bounds, width, height) || strings.TrimSpace(wordText) != wordText { + return Result{}, invalidRow(rows) } separatorBytes := 0 if len(result.Words) != 0 { @@ -101,7 +101,7 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) { id := LineID{numbers[1], numbers[2], numbers[3], numbers[4]} if len(result.Lines) == 0 || result.Lines[len(result.Lines)-1].ID != id { if closedLines[id] { - return Result{}, invalid_row(rows) + return Result{}, invalidRow(rows) } if len(result.Lines) != 0 { closedLines[result.Lines[len(result.Lines)-1].ID] = true @@ -115,7 +115,7 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) { } start := offset text.WriteString(wordText) - offset += rune_length(wordText) + offset += runeLength(wordText) result.Words = append(result.Words, Word{wordText, confidence, bounds, Span{start, offset}}) line := &result.Lines[len(result.Lines)-1] line.End, line.WordEnd = offset, len(result.Words) @@ -133,6 +133,6 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) { return result, nil } -func invalid_row(row int) error { +func invalidRow(row int) error { return fmt.Errorf("%w: TSV row %d", ErrInvalidOutput, row) } diff --git a/internal/ocr/tsv_test.go b/internal/ocr/tsv_test.go index 04940d5..9859aec 100644 --- a/internal/ocr/tsv_test.go +++ b/internal/ocr/tsv_test.go @@ -126,7 +126,7 @@ func FuzzParseTSV(f *testing.F) { start, startOK := result.ByteOffset(word.Start) end, endOK := result.ByteOffset(word.End) if !startOK || !endOK || word.Start < lastEnd || word.End <= word.Start || - result.Text[start:end] != word.Text || !valid_word_bounds(word.Bounds, result.Width, result.Height) { + result.Text[start:end] != word.Text || !validWordBounds(word.Bounds, result.Width, result.Height) { t.Fatal("invalid word map") } lastEnd = word.End diff --git a/internal/platform/wayland/keyboard.go b/internal/platform/wayland/keyboard.go index 3fdd4fc..bde7522 100644 --- a/internal/platform/wayland/keyboard.go +++ b/internal/platform/wayland/keyboard.go @@ -108,7 +108,7 @@ func (keyboard *Keyboard) Start(ctx context.Context) error { if err := ctx.Err(); err != nil { return err } - if err := validate_configuration(keyboard.configuration); err != nil { + if err := validateConfiguration(keyboard.configuration); err != nil { return err } keyboard.started = true @@ -199,11 +199,11 @@ func (keyboard *Keyboard) SetSecureInputActive(active bool) { } } -func validate_configuration(configuration keyboardConfiguration) error { +func validateConfiguration(configuration keyboardConfiguration) error { if configuration.layout != input.DesktopKeyboardLayout && configuration.layout != input.LaptopKeyboardLayout { return fmt.Errorf("invalid keyboard layout %d", configuration.layout) } - if _, err := modifier_symbols(configuration.modifiers); err != nil { + if _, err := modifierSymbols(configuration.modifiers); err != nil { return err } return input.ValidateBindingOverrides(configuration.bindings) @@ -221,7 +221,7 @@ func (keyboard *Keyboard) SetKeyboardConfiguration(ctx context.Context, layout i if err := ctx.Err(); err != nil { return err } - if err := validate_configuration(configuration); err != nil { + if err := validateConfiguration(configuration); err != nil { return err } keyboard.mutex.Lock() diff --git a/internal/platform/wayland/protocol.go b/internal/platform/wayland/protocol.go index 661b3cb..39fd1a7 100644 --- a/internal/platform/wayland/protocol.go +++ b/internal/platform/wayland/protocol.go @@ -78,14 +78,14 @@ func (owner *keyboardOwner) call(ctx context.Context, method string, arguments . return owner.connection.Object(owner.owner, managerPath).CallWithContext(deadline, monitorInterface+"."+method, 0, arguments...).Err } -func (owner *keyboardOwner) requested_policy() keyboardPolicy { +func (owner *keyboardOwner) requestedPolicy() keyboardPolicy { keyboard := owner.keyboard if !keyboard.enabled.Load() || keyboard.secure.Load() { owner.learning = false keyboard.learn.Store(false) if owner.uiSession != 0 { session := owner.uiSession - owner.dismiss_internal_ui() + owner.dismissInternalUi() select { case keyboard.commands <- input.CommandEvent{Command: input.InternalUIDismiss, UISession: session}: default: @@ -95,7 +95,7 @@ func (owner *keyboardOwner) requested_policy() keyboardPolicy { return keyboardPolicy{enabled: keyboard.enabled.Load(), browse: keyboard.browse.Load(), button: keyboard.nativeButton.Load(), secure: keyboard.secure.Load(), learn: owner.learning, bypass: keyboard.bypass.Load(), ui: owner.uiSession != 0} } -func (owner *keyboardOwner) retire_secure_generation() { +func (owner *keyboardOwner) retireSecureGeneration() { generation := owner.keyboard.secureGeneration.Load() if generation == owner.generation { return @@ -110,7 +110,7 @@ func (owner *keyboardOwner) retire_secure_generation() { owner.keyboard.learn.Store(false) if owner.uiSession != 0 { session := owner.uiSession - owner.dismiss_internal_ui() + owner.dismissInternalUi() select { case owner.keyboard.commands <- input.CommandEvent{Command: input.InternalUIDismiss, UISession: session}: default: @@ -120,7 +120,7 @@ func (owner *keyboardOwner) retire_secure_generation() { } func (owner *keyboardOwner) configure(ctx context.Context, configuration keyboardConfiguration, policy keyboardPolicy) error { - symbols, grabs, bindings := make_grabs(configuration, policy) + symbols, grabs, bindings := makeGrabs(configuration, policy) if err := owner.call(ctx, "SetKeyGrabs", symbols, grabs); err != nil { return err } @@ -198,7 +198,7 @@ func (keyboard *Keyboard) run(ctx context.Context, configuration keyboardConfigu setup <- err return } - policy := owner.requested_policy() + policy := owner.requestedPolicy() if !policy.secure { if err := owner.call(ctx, "WatchKeyboard"); err != nil { setup <- err @@ -245,8 +245,8 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error return nil } } - owner.retire_secure_generation() - policy := owner.requested_policy() + owner.retireSecureGeneration() + policy := owner.requestedPolicy() if policy.secure != owner.policy.secure { owner.learning, policy.learn = false, false keyboard.learn.Store(false) @@ -269,8 +269,8 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error // sync below retains the compositor grab until those releases // arrive, mirroring the Escape path and the Xorg owner. if owner.uiSession != 0 && keyboard.uiClose.Load() >= owner.uiSession { - owner.dismiss_internal_ui() - policy = owner.requested_policy() + owner.dismissInternalUi() + policy = owner.requestedPolicy() } if !stopping && len(owner.held) == 0 { if pendingUI != nil { @@ -280,13 +280,13 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error if reply.err == nil { if update.closeSession != 0 { if update.closeSession == owner.uiSession { - owner.dismiss_internal_ui() + owner.dismissInternalUi() } if owner.policy.ui { - reply.err = owner.configure(update.ctx, owner.configuration, owner.requested_policy()) + reply.err = owner.configure(update.ctx, owner.configuration, owner.requestedPolicy()) } } else { - reply.session, reply.err = owner.begin_internal_ui(update.ctx) + reply.session, reply.err = owner.beginInternalUi(update.ctx) } } update.result <- reply @@ -374,7 +374,7 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error } continue } - if err := owner.handle_key(key); err != nil { + if err := owner.handleKey(key); err != nil { return err } } diff --git a/internal/platform/wayland/protocol_test.go b/internal/platform/wayland/protocol_test.go index cd95e21..f051f98 100644 --- a/internal/platform/wayland/protocol_test.go +++ b/internal/platform/wayland/protocol_test.go @@ -109,19 +109,19 @@ func (monitor *FakeKeyboardMonitor) SetKeyGrabs(modifiers []uint32, grabs []keyG return nil } -func (monitor *FakeKeyboardMonitor) grab_state() (grabbed bool, grabCalls, ungrabCalls, keyGrabs int) { +func (monitor *FakeKeyboardMonitor) grabState() (grabbed bool, grabCalls, ungrabCalls, keyGrabs int) { monitor.mutex.Lock() defer monitor.mutex.Unlock() return monitor.state.grabbed, monitor.grabCalls, monitor.ungrabCalls, len(monitor.state.grabs) } -func (monitor *FakeKeyboardMonitor) fail_next_grab() { +func (monitor *FakeKeyboardMonitor) failNextGrab() { monitor.mutex.Lock() defer monitor.mutex.Unlock() monitor.failGrabNext = true } -func (monitor *FakeKeyboardMonitor) delay_next_grab(delay time.Duration) <-chan struct{} { +func (monitor *FakeKeyboardMonitor) delayNextGrab(delay time.Duration) <-chan struct{} { started := make(chan struct{}, 1) monitor.mutex.Lock() defer monitor.mutex.Unlock() @@ -129,7 +129,7 @@ func (monitor *FakeKeyboardMonitor) delay_next_grab(delay time.Duration) <-chan return started } -func wait_for(t *testing.T, check func() bool, message string) { +func waitFor(t *testing.T, check func() bool, message string) { t.Helper() deadline := time.Now().Add(3 * time.Second) for !check() { @@ -140,7 +140,7 @@ func wait_for(t *testing.T, check func() bool, message string) { } } -func start_monitor(t *testing.T) *FakeKeyboardMonitor { +func startMonitor(t *testing.T) *FakeKeyboardMonitor { t.Helper() if os.Getenv("CTHULHU_NATIVE_DBUS_TEST") != "1" { t.Skip("requires CTHULHU_NATIVE_DBUS_TEST=1 and a private dbus-run-session") @@ -163,7 +163,7 @@ func start_monitor(t *testing.T) *FakeKeyboardMonitor { return monitor } -func start_keyboard(t *testing.T, monitor *FakeKeyboardMonitor) *Keyboard { +func startKeyboard(t *testing.T, monitor *FakeKeyboardMonitor) *Keyboard { t.Helper() keyboard := New([]string{"Insert", "KP_Insert"}, input.DesktopKeyboardLayout, nil) if err := keyboard.Start(context.Background()); err != nil { @@ -176,11 +176,11 @@ func start_keyboard(t *testing.T, monitor *FakeKeyboardMonitor) *Keyboard { t.Error(err) } }) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.modifiers) == 3 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.modifiers) == 3 }) return keyboard } -func wait_snapshot(t *testing.T, monitor *FakeKeyboardMonitor, check func(MonitorSnapshot) bool) MonitorSnapshot { +func waitSnapshot(t *testing.T, monitor *FakeKeyboardMonitor, check func(MonitorSnapshot) bool) MonitorSnapshot { t.Helper() for { select { @@ -194,7 +194,7 @@ func wait_snapshot(t *testing.T, monitor *FakeKeyboardMonitor, check func(Monito } } -func emit_key(t *testing.T, connection *dbus.Conn, client string, symbol uint32, code uint16, state uint32, released bool) { +func emitKey(t *testing.T, connection *dbus.Conn, client string, symbol uint32, code uint16, state uint32, released bool) { t.Helper() message := &dbus.Message{Type: dbus.TypeSignal, Headers: map[dbus.HeaderField]dbus.Variant{ dbus.FieldDestination: dbus.MakeVariant(client), dbus.FieldPath: dbus.MakeVariant(managerPath), @@ -210,10 +210,10 @@ func (monitor *FakeKeyboardMonitor) key(t *testing.T, symbol uint32, code uint16 monitor.mutex.Lock() client := monitor.state.client monitor.mutex.Unlock() - emit_key(t, monitor.connection, client, symbol, code, state, released) + emitKey(t, monitor.connection, client, symbol, code, state, released) } -func await_command(t *testing.T, keyboard *Keyboard, command input.Command) input.CommandEvent { +func awaitCommand(t *testing.T, keyboard *Keyboard, command input.Command) input.CommandEvent { t.Helper() select { case event := <-keyboard.commands: @@ -227,7 +227,7 @@ func await_command(t *testing.T, keyboard *Keyboard, command input.Command) inpu return input.CommandEvent{} } -func await_input(t *testing.T, keyboard *Keyboard, name string) input.Event { +func awaitInput(t *testing.T, keyboard *Keyboard, name string) input.Event { t.Helper() select { case event := <-keyboard.events: @@ -242,12 +242,12 @@ func await_input(t *testing.T, keyboard *Keyboard, name string) input.Event { } func TestNativeKeyboardProtocolCommandsMonitoringAndCleanup(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) monitor.key(t, 'x', 53, 0, false) monitor.key(t, 'x', 53, 0, true) - press := await_input(t, keyboard, "x") - release := await_input(t, keyboard, "x") + press := awaitInput(t, keyboard, "x") + release := awaitInput(t, keyboard, "x") if !press.Pressed || release.Pressed || release.Timestamp <= press.Timestamp { t.Fatal("input transition order lost") } @@ -255,7 +255,7 @@ func TestNativeKeyboardProtocolCommandsMonitoringAndCleanup(t *testing.T) { monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 's', 39, 0, false) monitor.key(t, 's', 39, 0, false) - await_command(t, keyboard, input.CycleSpeechMode) + awaitCommand(t, keyboard, input.CycleSpeechMode) if modifierFirst { monitor.key(t, 0xff63, 118, 0, true) } @@ -265,8 +265,8 @@ func TestNativeKeyboardProtocolCommandsMonitoringAndCleanup(t *testing.T) { } monitor.key(t, 'x', 53, 0, false) monitor.key(t, 'x', 53, 0, true) - await_input(t, keyboard, "x") - await_input(t, keyboard, "x") + awaitInput(t, keyboard, "x") + awaitInput(t, keyboard, "x") if len(keyboard.commands) != 0 || keyboard.CommandGrabActive() { t.Fatal("repeat command or sticky reader modifier") } @@ -284,10 +284,10 @@ func TestNativeKeyboardProtocolCommandsMonitoringAndCleanup(t *testing.T) { } func TestNativeKeyboardBrowseSecureAndLearnTransitions(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) keyboard.SetBrowseNavigation(true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { for _, grab := range state.grabs { if grab.Symbol == 'h' { return true @@ -297,14 +297,14 @@ func TestNativeKeyboardBrowseSecureAndLearnTransitions(t *testing.T) { }) monitor.key(t, 'h', 43, 0, false) monitor.key(t, 'h', 43, 0, true) - await_command(t, keyboard, input.DocumentNextHeading) + awaitCommand(t, keyboard, input.DocumentNextHeading) if loadShiftPairs().unshifted['#'] == '3' { monitor.key(t, '#', 12, 1, false) monitor.key(t, '3', 12, 0, true) - await_command(t, keyboard, input.DocumentPreviousHeadingAtLevel3) + awaitCommand(t, keyboard, input.DocumentPreviousHeadingAtLevel3) } keyboard.SetNativeButtonFocus(true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { for _, grab := range state.grabs { if grab.Symbol == 0xff0d { return false @@ -313,44 +313,44 @@ func TestNativeKeyboardBrowseSecureAndLearnTransitions(t *testing.T) { return true }) keyboard.SetSecureInputActive(true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.watching && len(state.modifiers) == 0 && len(state.grabs) == 0 }) keyboard.SetSecureInputActive(false) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.watching && len(state.modifiers) == 3 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.watching && len(state.modifiers) == 3 }) monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 'h', 43, 0, false) - if !await_command(t, keyboard, input.ToggleLearnMode).LearnModeStarted { + if !awaitCommand(t, keyboard, input.ToggleLearnMode).LearnModeStarted { t.Fatal("learn did not begin") } monitor.key(t, 'h', 43, 0, true) monitor.key(t, 0xff63, 118, 0, true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) monitor.key(t, 'q', 24, 0, false) monitor.key(t, 'q', 24, 0, true) - await_command(t, keyboard, input.LearnKey) + awaitCommand(t, keyboard, input.LearnKey) monitor.key(t, 0xff1b, 9, 0, false) monitor.key(t, 0xff1b, 9, 0, true) - if await_command(t, keyboard, input.ToggleLearnMode).LearnModeStarted { + if awaitCommand(t, keyboard, input.ToggleLearnMode).LearnModeStarted { t.Fatal("Escape entered learn mode") } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) keyboard.SetCommandGrabs(false) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.modifiers) == 0 && len(state.grabs) == 0 && !state.grabbed }) monitor.key(t, 'q', 24, 0, false) monitor.key(t, 'q', 24, 0, true) - await_input(t, keyboard, "q") - await_input(t, keyboard, "q") + awaitInput(t, keyboard, "q") + awaitInput(t, keyboard, "q") } func TestNativeKeyboardBindingUpdateRollbackAndHeldCancellation(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 's', 39, 0, false) - await_command(t, keyboard, input.CycleSpeechMode) + awaitCommand(t, keyboard, input.CycleSpeechMode) ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() if err := keyboard.SetKeyboardConfiguration(ctx, input.LaptopKeyboardLayout, []string{"Caps_Lock"}, nil); !errors.Is(err, context.DeadlineExceeded) { @@ -366,7 +366,7 @@ func TestNativeKeyboardBindingUpdateRollbackAndHeldCancellation(t *testing.T) { } monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, ' ', 65, 0, false) - await_command(t, keyboard, input.Preferences) + awaitCommand(t, keyboard, input.Preferences) monitor.key(t, ' ', 65, 0, true) monitor.key(t, 0xff63, 118, 0, true) bindings := []input.BindingOverride{{Layout: input.LaptopKeyboardLayout, Scope: "global", Command: input.Preferences, Keys: []string{"Cthulhu+p"}}} @@ -375,14 +375,14 @@ func TestNativeKeyboardBindingUpdateRollbackAndHeldCancellation(t *testing.T) { } monitor.key(t, 0xffe5, 66, 0, false) monitor.key(t, 'p', 33, 0, false) - await_command(t, keyboard, input.Preferences) + awaitCommand(t, keyboard, input.Preferences) monitor.key(t, 'p', 33, 0, true) monitor.key(t, 0xffe5, 66, 0, true) } func TestNativeKeyboardRejectsSpoofedSignalsAndServiceLoss(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) impostor, err := dbus.ConnectSessionBus() if err != nil { t.Fatal(err) @@ -391,14 +391,14 @@ func TestNativeKeyboardRejectsSpoofedSignalsAndServiceLoss(t *testing.T) { monitor.mutex.Lock() client := monitor.state.client monitor.mutex.Unlock() - emit_key(t, impostor, client, 0xff63, 118, 0, false) + emitKey(t, impostor, client, 0xff63, 118, 0, false) if err := impostor.BusObject().Call("org.freedesktop.DBus.GetId", 0).Err; err != nil { t.Fatal(err) } monitor.key(t, 's', 39, 0, false) monitor.key(t, 's', 39, 0, true) - await_input(t, keyboard, "s") - await_input(t, keyboard, "s") + awaitInput(t, keyboard, "s") + awaitInput(t, keyboard, "s") if len(keyboard.commands) != 0 { t.Fatal("untrusted signal created reader modifier") } @@ -416,7 +416,7 @@ func TestNativeKeyboardRejectsSpoofedSignalsAndServiceLoss(t *testing.T) { } func TestNativeKeyboardDeniedWatchCleansUp(t *testing.T) { - monitor := start_monitor(t) + monitor := startMonitor(t) monitor.mutex.Lock() monitor.rejectWatch = true monitor.mutex.Unlock() @@ -434,58 +434,58 @@ func TestNativeKeyboardDeniedWatchCleansUp(t *testing.T) { } func TestNativeKeyboardRapidSecureCycleRetiresHeldModifier(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 't', 28, 0, false) - await_command(t, keyboard, input.PresentTime) + awaitCommand(t, keyboard, input.PresentTime) keyboard.SetSecureInputActive(true) keyboard.SetSecureInputActive(false) // The old physical releases may have been discarded while secure. Plain Q // must reach monitoring rather than becoming a stale Cthulhu+Q command. monitor.key(t, 'q', 24, 0, false) monitor.key(t, 'q', 24, 0, true) - await_input(t, keyboard, "q") - await_input(t, keyboard, "q") + awaitInput(t, keyboard, "q") + awaitInput(t, keyboard, "q") if len(keyboard.commands) != 0 || keyboard.CommandGrabActive() { t.Fatal("secure cycle retained reader chord") } } func TestNativeKeyboardStartsSecureWithoutMonitoringOrGrabs(t *testing.T) { - monitor := start_monitor(t) + monitor := startMonitor(t) keyboard := New([]string{"Insert"}, input.DesktopKeyboardLayout, nil) keyboard.SetSecureInputActive(true) if err := keyboard.Start(context.Background()); err != nil { t.Fatal(err) } defer keyboard.Stop(context.Background()) - state := wait_snapshot(t, monitor, func(MonitorSnapshot) bool { return true }) + state := waitSnapshot(t, monitor, func(MonitorSnapshot) bool { return true }) if state.watching || state.grabbed || len(state.modifiers) != 0 || len(state.grabs) != 0 { t.Fatal("secure startup acquired keyboard access") } keyboard.SetSecureInputActive(false) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.watching && len(state.modifiers) == 1 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.watching && len(state.modifiers) == 1 }) } func TestNativeBypassAndInternalUIGrabLifecycle(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) keyboard.SetBrowseNavigation(true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.grabs) != 0 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.grabs) != 0 }) monitor.key(t, 'h', 43, 0, false) - await_command(t, keyboard, input.DocumentNextHeading) + awaitCommand(t, keyboard, input.DocumentNextHeading) keyboard.SetCommandBypass(true) heldDeadline := time.Now().Add(75 * time.Millisecond) for time.Now().Before(heldDeadline) { - if _, _, _, keyGrabs := monitor.grab_state(); keyGrabs == 0 { + if _, _, _, keyGrabs := monitor.grabState(); keyGrabs == 0 { t.Fatal("bypass was applied while a key was held") } time.Sleep(time.Millisecond) } monitor.key(t, 'h', 43, 0, true) keyboard.SetCommandBypass(true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.grabs) == 0 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.grabs) == 0 }) deadline := time.Now().Add(3 * time.Second) for !keyboard.CommandBypassEnabled() { if time.Now().After(deadline) { @@ -496,11 +496,11 @@ func TestNativeBypassAndInternalUIGrabLifecycle(t *testing.T) { // The retained toggle chord still dispatches through the modifier watch. monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 'z', 52, 0, false) - await_command(t, keyboard, input.ToggleCommandBypass) + awaitCommand(t, keyboard, input.ToggleCommandBypass) monitor.key(t, 'z', 52, 0, true) monitor.key(t, 0xff63, 118, 0, true) keyboard.SetCommandBypass(false) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.grabs) != 0 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return len(state.grabs) != 0 }) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() @@ -511,9 +511,9 @@ func TestNativeBypassAndInternalUIGrabLifecycle(t *testing.T) { if !keyboard.InternalUIActive() || keyboard.InternalUISession() != session { t.Fatal("internal UI session not published") } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) monitor.key(t, 'a', 38, 0, false) - event := await_command(t, keyboard, input.InternalUIKey) + event := awaitCommand(t, keyboard, input.InternalUIKey) if event.UISession != session || event.Text != "a" { t.Fatalf("internal UI key = %+v", event) } @@ -521,75 +521,75 @@ func TestNativeBypassAndInternalUIGrabLifecycle(t *testing.T) { if err := keyboard.EndInternalUI(ctx, session); err != nil { t.Fatal(err) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) if keyboard.InternalUIActive() || keyboard.InternalUISession() != 0 { t.Fatal("internal UI session survived end") } } func TestNativeInternalUISecureTransitionRevokesSession(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() session, err := keyboard.BeginInternalUI(ctx) if err != nil || session == 0 { t.Fatalf("begin internal UI: session %d, %v", session, err) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) keyboard.SetSecureInputActive(true) - if event := await_command(t, keyboard, input.InternalUIDismiss); event.UISession != session { + if event := awaitCommand(t, keyboard, input.InternalUIDismiss); event.UISession != session { t.Fatalf("secure dismiss session = %d, want %d", event.UISession, session) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.watching && !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.watching && !state.grabbed }) if keyboard.InternalUIActive() || keyboard.InternalUISession() != 0 { t.Fatal("internal UI session survived secure transition") } - _, grabCalls, _, _ := monitor.grab_state() + _, grabCalls, _, _ := monitor.grabState() if _, err := keyboard.BeginInternalUI(ctx); err == nil { t.Fatal("internal UI began while secure") } - if _, afterCalls, _, _ := monitor.grab_state(); afterCalls != grabCalls { + if _, afterCalls, _, _ := monitor.grabState(); afterCalls != grabCalls { t.Fatal("rejected secure begin still grabbed the keyboard") } keyboard.SetSecureInputActive(false) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.watching && !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.watching && !state.grabbed }) session, err = keyboard.BeginInternalUI(ctx) if err != nil || session == 0 { t.Fatalf("begin internal UI after unlock: session %d, %v", session, err) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) monitor.key(t, 0xff1b, 9, 0, false) - event := await_command(t, keyboard, input.InternalUIKey) + event := awaitCommand(t, keyboard, input.InternalUIKey) if event.UISession != session || event.Chord.Symbol != 0xff1b { t.Fatalf("internal UI Escape = %+v", event) } monitor.key(t, 0xff1b, 9, 0, true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) if err := keyboard.EndInternalUI(ctx, session); err != nil { t.Fatal(err) } } func TestNativeInternalUIEndWaitsForHeldKeyRelease(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() session, err := keyboard.BeginInternalUI(ctx) if err != nil || session == 0 { t.Fatalf("begin internal UI: session %d, %v", session, err) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) monitor.key(t, 0xff0d, 36, 0, false) - await_command(t, keyboard, input.InternalUIKey) + awaitCommand(t, keyboard, input.InternalUIKey) closed := make(chan error, 1) go func() { closed <- keyboard.EndInternalUI(ctx, session) }() - wait_for(t, func() bool { return !keyboard.InternalUIActive() }, "session identity was not revoked promptly") - if grabbed, _, _, _ := monitor.grab_state(); !grabbed { + waitFor(t, func() bool { return !keyboard.InternalUIActive() }, "session identity was not revoked promptly") + if grabbed, _, _, _ := monitor.grabState(); !grabbed { t.Fatal("keyboard was ungrabbed while Enter was held") } if !keyboard.InternalUIEchoActive() { @@ -609,15 +609,15 @@ func TestNativeInternalUIEndWaitsForHeldKeyRelease(t *testing.T) { case <-time.After(3 * time.Second): t.Fatal("EndInternalUI did not return after key release") } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) if keyboard.InternalUIEchoActive() { t.Fatal("UI echo suppression survived ungrab") } } func TestNativeInternalUIRepeatsKeys(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() session, err := keyboard.BeginInternalUI(ctx) @@ -627,7 +627,7 @@ func TestNativeInternalUIRepeatsKeys(t *testing.T) { monitor.key(t, 0xff08, 22, 0, false) monitor.key(t, 0xff08, 22, 0, false) for i := 0; i < 2; i++ { - if event := await_command(t, keyboard, input.InternalUIKey); event.UISession != session || event.Chord.Symbol != 0xff08 { + if event := awaitCommand(t, keyboard, input.InternalUIKey); event.UISession != session || event.Chord.Symbol != 0xff08 { t.Fatalf("Backspace repeat %d = %+v", i, event) } } @@ -638,8 +638,8 @@ func TestNativeInternalUIRepeatsKeys(t *testing.T) { } func TestNativeInternalUISuspensionDismissesBeforeHeldRelease(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() session, err := keyboard.BeginInternalUI(ctx) @@ -647,21 +647,21 @@ func TestNativeInternalUISuspensionDismissesBeforeHeldRelease(t *testing.T) { t.Fatal(err) } monitor.key(t, 0xff0d, 36, 0, false) - await_command(t, keyboard, input.InternalUIKey) + awaitCommand(t, keyboard, input.InternalUIKey) keyboard.SetCommandGrabs(false) - if event := await_command(t, keyboard, input.InternalUIDismiss); event.UISession != session { + if event := awaitCommand(t, keyboard, input.InternalUIDismiss); event.UISession != session { t.Fatalf("suspension dismiss = %+v", event) } if keyboard.InternalUIActive() { t.Fatal("internal UI stayed active after command grabs were suspended") } - if grabbed, _, _, _ := monitor.grab_state(); !grabbed { + if grabbed, _, _, _ := monitor.grabState(); !grabbed { t.Fatal("keyboard ungrabbed while Enter was held") } monitor.key(t, 'a', 38, 0, false) monitor.key(t, 'a', 38, 0, true) monitor.key(t, 0xff0d, 36, 0, true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed && len(state.grabs) == 0 }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed && len(state.grabs) == 0 }) if len(keyboard.commands) != 0 || len(keyboard.events) != 0 { t.Fatal("keys from the closing UI reached command routing or monitoring") } @@ -671,16 +671,16 @@ func TestNativeInternalUISuspensionDismissesBeforeHeldRelease(t *testing.T) { } func TestNativeShowActionsCapturePreservesHeldReaderModifier(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 0xffe1, 50, 1, false) monitor.key(t, 'A', 38, 1, false) - opened := await_command(t, keyboard, input.ShowActions) + opened := awaitCommand(t, keyboard, input.ShowActions) if opened.UISession == 0 || opened.UISession != keyboard.InternalUISession() { t.Fatalf("ShowActions did not capture atomically: %+v", opened) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) // Insert is still held from the opening chord. Its router state must // survive the synchronous capture so this cannot become field text. monitor.key(t, 'x', 53, 1, false) @@ -689,21 +689,21 @@ func TestNativeShowActionsCapturePreservesHeldReaderModifier(t *testing.T) { monitor.key(t, 0xffe1, 50, 0, true) monitor.key(t, 0xff63, 118, 0, true) monitor.key(t, 'a', 38, 0, false) - event := await_command(t, keyboard, input.InternalUIKey) + event := awaitCommand(t, keyboard, input.InternalUIKey) if event.UISession != opened.UISession || event.Text != "a" { t.Fatalf("first internal UI key = %+v", event) } monitor.key(t, 'a', 38, 0, true) monitor.key(t, 0xff1b, 9, 0, false) - await_command(t, keyboard, input.InternalUIKey) + awaitCommand(t, keyboard, input.InternalUIKey) monitor.key(t, 0xff1b, 9, 0, true) - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.grabbed }) } func TestNativeShowActionsSecureTransitionDoesNotBlockLock(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) - started := monitor.delay_next_grab(300 * time.Millisecond) + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) + started := monitor.delayNextGrab(300 * time.Millisecond) monitor.key(t, 0xff63, 118, 0, false) monitor.key(t, 0xffe1, 50, 1, false) monitor.key(t, 'A', 38, 1, false) @@ -722,10 +722,10 @@ func TestNativeShowActionsSecureTransitionDoesNotBlockLock(t *testing.T) { case <-time.After(100 * time.Millisecond): t.Fatal("secure transition blocked behind ShowActions capture") } - if event := await_command(t, keyboard, input.InternalUIDismiss); event.UISession == 0 { + if event := awaitCommand(t, keyboard, input.InternalUIDismiss); event.UISession == 0 { t.Fatalf("secure dismiss event = %+v", event) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.watching && !state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return !state.watching && !state.grabbed }) keyboard.SetSecureInputActive(false) deadline := time.Now().Add(3 * time.Second) for { @@ -749,23 +749,23 @@ func TestNativeShowActionsSecureTransitionDoesNotBlockLock(t *testing.T) { } func TestNativeInternalUIRecoversAmbiguousGrabFailure(t *testing.T) { - monitor := start_monitor(t) - keyboard := start_keyboard(t, monitor) - monitor.fail_next_grab() + monitor := startMonitor(t) + keyboard := startKeyboard(t, monitor) + monitor.failNextGrab() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() if session, err := keyboard.BeginInternalUI(ctx); err == nil || session != 0 { t.Fatalf("ambiguous grab begin = session %d, %v", session, err) } - wait_for(t, func() bool { - grabbed, _, ungrabCalls, _ := monitor.grab_state() + waitFor(t, func() bool { + grabbed, _, ungrabCalls, _ := monitor.grabState() return !grabbed && ungrabCalls != 0 }, "ambiguous grab was not reconciled with UngrabKeyboard") session, err := keyboard.BeginInternalUI(ctx) if err != nil || session == 0 { t.Fatalf("begin after grab recovery: session %d, %v", session, err) } - wait_snapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) + waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed }) if err := keyboard.EndInternalUI(ctx, session); err != nil { t.Fatal(err) } diff --git a/internal/platform/wayland/routing.go b/internal/platform/wayland/routing.go index 3a6e8c2..5018d1d 100644 --- a/internal/platform/wayland/routing.go +++ b/internal/platform/wayland/routing.go @@ -25,7 +25,7 @@ import ( type keyGrab struct{ Symbol, Modifiers uint32 } type keyboardPolicy struct{ enabled, browse, button, secure, learn, bypass, ui bool } -func modifier_symbols(names []string) ([]uint32, error) { +func modifierSymbols(names []string) ([]uint32, error) { var symbols []uint32 for _, name := range names { switch name { @@ -42,7 +42,7 @@ func modifier_symbols(names []string) ([]uint32, error) { return symbols, nil } -func key_name(symbol uint32) string { +func keyName(symbol uint32) string { var buffer [128]C.char length := C.xkb_keysym_get_name(C.xkb_keysym_t(symbol), &buffer[0], C.size_t(len(buffer))) if length <= 0 || int(length) >= len(buffer) { @@ -51,9 +51,9 @@ func key_name(symbol uint32) string { return C.GoString((*C.char)(unsafe.Pointer(&buffer[0]))) } -func lower_symbol(symbol uint32) uint32 { return uint32(C.xkb_keysym_to_lower(C.xkb_keysym_t(symbol))) } +func lowerSymbol(symbol uint32) uint32 { return uint32(C.xkb_keysym_to_lower(C.xkb_keysym_t(symbol))) } -func symbol_utf32(symbol uint32) uint32 { +func symbolUtf32(symbol uint32) uint32 { return uint32(C.xkb_keysym_to_utf32(C.xkb_keysym_t(symbol))) } @@ -67,7 +67,7 @@ func symbol_utf32(symbol uint32) uint32 { // defaults). The monitor interface does not expose the compositor's keymap; // shifted digit and punctuation chords therefore require these defaults to // match the compositor's layout. The protocol cannot verify that match. -func shifted_symbol(symbol uint32) uint32 { +func shiftedSymbol(symbol uint32) uint32 { return uint32(C.xkb_keysym_to_upper(C.xkb_keysym_t(symbol))) } @@ -76,16 +76,16 @@ type shiftPairs struct { unshifted map[uint32]uint32 // Shifted symbol to its one unshifted partner. } -var loadShiftPairs = sync.OnceValue(func() shiftPairs { return build_shift_pairs("") }) +var loadShiftPairs = sync.OnceValue(func() shiftPairs { return buildShiftPairs("") }) -func shift_pair_base(symbol uint32) bool { +func shiftPairBase(symbol uint32) bool { if symbol < '!' || symbol > '~' { return false } return (symbol < 'A' || symbol > 'Z') && (symbol < 'a' || symbol > 'z') } -func shift_pair_partner(symbol, base uint32) bool { +func shiftPairPartner(symbol, base uint32) bool { if symbol == 0 || symbol == base || symbol >= 0xfe00 { return false // NoSymbol, unchanged, or dead/function/modifier ranges. } @@ -93,7 +93,7 @@ func shift_pair_partner(symbol, base uint32) bool { } // An empty layout selects the default keymap; tests name layouts explicitly. -func build_shift_pairs(layout string) shiftPairs { +func buildShiftPairs(layout string) shiftPairs { pairs := shiftPairs{shifted: make(map[uint32][]uint32), unshifted: make(map[uint32]uint32)} context := C.xkb_context_new(C.XKB_CONTEXT_NO_FLAGS) if context == nil { @@ -131,7 +131,7 @@ func build_shift_pairs(layout string) shiftPairs { base := uint32(C.xkb_state_key_get_one_sym(state, code)) C.xkb_state_update_mask(state, 1<= 0x20 && candidate != 0x7f && candidate <= 0x10ffff { return string(rune(candidate)) } diff --git a/internal/platform/wayland/ui_test.go b/internal/platform/wayland/ui_test.go index e631934..55f2aa7 100644 --- a/internal/platform/wayland/ui_test.go +++ b/internal/platform/wayland/ui_test.go @@ -21,7 +21,7 @@ func TestUpdateInternalUIWaitsForSentUpdateResult(t *testing.T) { } outcomes := make(chan outcome, 1) go func() { - session, err := keyboard.update_internal_ui(ctx, 0) + session, err := keyboard.updateInternalUi(ctx, 0) outcomes <- outcome{session: session, err: err} }() diff --git a/internal/platform/xorg/commands_bindings.go b/internal/platform/xorg/commands_bindings.go index c0245f3..295f422 100644 --- a/internal/platform/xorg/commands_bindings.go +++ b/internal/platform/xorg/commands_bindings.go @@ -31,7 +31,7 @@ type bindingUpdate struct { // SetKeyBindings validates and acknowledges a native update after the current // chord releases. Before Start it sets the configuration used at startup. func (listener *CommandListener) SetKeyBindings(ctx context.Context, overrides []input.BindingOverride) error { - return listener.update_keyboard(ctx, bindingUpdate{overrides: overrides}) + return listener.updateKeyboard(ctx, bindingUpdate{overrides: overrides}) } // SetKeyboardConfiguration applies layout, modifier keys, and shortcuts together @@ -40,13 +40,13 @@ func (listener *CommandListener) SetKeyboardConfiguration(ctx context.Context, l if layout != input.DesktopKeyboardLayout && layout != input.LaptopKeyboardLayout { return fmt.Errorf("invalid keyboard layout %d", layout) } - if _, err := command_modifier_symbols(modifiers); err != nil { + if _, err := commandModifierSymbols(modifiers); err != nil { return err } - return listener.update_keyboard(ctx, bindingUpdate{layout: layout, modifiers: append([]string(nil), modifiers...), overrides: overrides, replaceKeyboard: true}) + return listener.updateKeyboard(ctx, bindingUpdate{layout: layout, modifiers: append([]string(nil), modifiers...), overrides: overrides, replaceKeyboard: true}) } -func (listener *CommandListener) update_keyboard(ctx context.Context, update bindingUpdate) error { +func (listener *CommandListener) updateKeyboard(ctx context.Context, update bindingUpdate) error { if err := ctx.Err(); err != nil { return err } @@ -91,7 +91,7 @@ func (listener *CommandListener) SetTentacleBindings(ctx context.Context, bindin if err := input.ValidateTentacleBindings(bindings); err != nil { return err } - return listener.update_keyboard(ctx, bindingUpdate{replaceTentacles: true, tentacles: input.CloneBindingOverrides(bindings)}) + return listener.updateKeyboard(ctx, bindingUpdate{replaceTentacles: true, tentacles: input.CloneBindingOverrides(bindings)}) } func (listener *CommandListener) TentacleBindings() []input.BindingOverride { @@ -111,7 +111,7 @@ func (listener *CommandListener) publishTentacleBindings(merged []input.BindingO } } -func command_modifier_symbols(modifiers []string) ([]uint32, error) { +func commandModifierSymbols(modifiers []string) ([]uint32, error) { var symbols []uint32 for _, name := range modifiers { switch name { @@ -134,11 +134,11 @@ func resolvedBindings(layout input.KeyboardLayout, browse bool, overrides []inpu } func configureNativeBindings(device *C.CommandDevice, layout input.KeyboardLayout, modifiers []string, overrides []input.BindingOverride) error { - return configure_native_bindings(device, layout, modifiers, overrides, false) + return configureNativeBindingsWithOCR(device, layout, modifiers, overrides, false) } -func configure_native_bindings(device *C.CommandDevice, layout input.KeyboardLayout, modifiers []string, overrides []input.BindingOverride, ocrReview bool, pending ...bool) error { - symbols, err := command_modifier_symbols(modifiers) +func configureNativeBindingsWithOCR(device *C.CommandDevice, layout input.KeyboardLayout, modifiers []string, overrides []input.BindingOverride, ocrReview bool, pending ...bool) error { + symbols, err := commandModifierSymbols(modifiers) if err != nil { return err } diff --git a/internal/platform/xorg/commands_chord.go b/internal/platform/xorg/commands_chord.go index 8b1cc0c..bc15e93 100644 --- a/internal/platform/xorg/commands_chord.go +++ b/internal/platform/xorg/commands_chord.go @@ -14,7 +14,7 @@ import ( ) // Wait for the complete chord: Shift+CapsLock+V remains a version command. -func is_caps_lock_toggle(keys []C.CommandKey) bool { +func isCapsLockToggle(keys []C.CommandKey) bool { caps, shift := false, false for _, key := range keys { if key.modifiers & ^C.int(1) != 0 { @@ -49,9 +49,9 @@ func (owner *commandOwner) handleKey(key C.CommandKey) bool { } owner.buffered = append(owner.buffered, key) if owner.remote != nil { - owner.handle_remote_key(key) + owner.handleRemoteKey(key) } else if owner.uiSession != 0 { - if !owner.handle_internal_key(key) { + if !owner.handleInternalKey(key) { return false } } else if owner.learnMode { @@ -128,11 +128,11 @@ func (owner *commandOwner) handleRoutedKey(key C.CommandKey) bool { } uiSession := uint64(0) if command == input.ShowActions { - if owner.ocrReview && !owner.leave_ocr_review() { + if owner.ocrReview && !owner.leaveOcrReview() { return false } var err error - uiSession, err = owner.begin_internal_ui() + uiSession, err = owner.beginInternalUi() if err != nil { // An unavailable modal grab is a failed command, not a failed reader. uiSession = 0 @@ -147,7 +147,7 @@ func (owner *commandOwner) handleRoutedKey(key C.CommandKey) bool { } func (owner *commandOwner) finishChord() bool { - if owner.device.bypass == 0 && !owner.bound && owner.device.capsCode != 0 && is_caps_lock_toggle(owner.buffered) { + if owner.device.bypass == 0 && !owner.bound && owner.device.capsCode != 0 && isCapsLockToggle(owner.buffered) { C.toggle_command_caps_lock(owner.device) if result := C.replay_command_keys(owner.device, &owner.buffered[0], C.int(len(owner.buffered))); result != 0 { owner.listener.failures <- fmt.Errorf("release Caps Lock toggle chord: native error %d", int(result)) @@ -168,7 +168,7 @@ func (owner *commandOwner) finishChord() bool { owner.passThrough = false if owner.dismissOCR { owner.dismissOCR = false - if !owner.leave_ocr_review() { + if !owner.leaveOcrReview() { return false } } diff --git a/internal/platform/xorg/commands_ocr.go b/internal/platform/xorg/commands_ocr.go index 17e286d..ec1e050 100644 --- a/internal/platform/xorg/commands_ocr.go +++ b/internal/platform/xorg/commands_ocr.go @@ -22,12 +22,12 @@ import ( // consumer. Failure retains the old context. Secure/terminal policy still wins. // The session must dismiss on real focus changes and ordinary XRecord input. func (listener *CommandListener) SetOCRReview(ctx context.Context, enabled bool) error { - return listener.set_ocr_context(ctx, enabled, false, 0) + return listener.setOcrContext(ctx, enabled, false, 0) } // SetOCRPending owns Escape only; recognition never claims document navigation. func (listener *CommandListener) SetOCRPending(ctx context.Context, enabled bool) error { - return listener.set_ocr_context(ctx, enabled, enabled, 0) + return listener.setOcrContext(ctx, enabled, enabled, 0) } // SetOCRContext admits a live session only in its expected foreground client. @@ -35,10 +35,10 @@ func (listener *CommandListener) SetOCRContext(ctx context.Context, foreground u if foreground == 0 { return errors.New("OCR foreground unavailable") } - return listener.set_ocr_context(ctx, true, pending, foreground) + return listener.setOcrContext(ctx, true, pending, foreground) } -func (listener *CommandListener) set_ocr_context(ctx context.Context, enabled, pending bool, foreground uint64) error { +func (listener *CommandListener) setOcrContext(ctx context.Context, enabled, pending bool, foreground uint64) error { if err := ctx.Err(); err != nil { return err } @@ -70,7 +70,7 @@ func (listener *CommandListener) OCRReviewEnabled() bool { return !listener.bypass.Load() && !listener.ocrPending.Load() && !listener.secure.Load() && listener.commandsEnabled.Load() && listener.commandsApplied.Load() && listener.ocrApplied.Load() } -func (owner *commandOwner) context_bindings() input.CommandBindings { +func (owner *commandOwner) contextBindings() input.CommandBindings { if owner.device.bypass != 0 { return input.BypassCommandBindings(owner.globalBindings) } @@ -85,13 +85,13 @@ func (owner *commandOwner) context_bindings() input.CommandBindings { // Configure grabs and routing together. Native replacement restores old // bindings on error; restore its old mode too before reporting a failed entry. -func configure_context_bindings(device *C.CommandDevice, layout input.KeyboardLayout, modifiers []string, overrides []input.BindingOverride, browse, ocrReview bool, pending ...bool) error { +func configureContextBindings(device *C.CommandDevice, layout input.KeyboardLayout, modifiers []string, overrides []input.BindingOverride, browse, ocrReview bool, pending ...bool) error { previous, enabled := device.browse, device.commands device.browse = 0 if device.bypass == 0 && (browse || ocrReview) { device.browse = 1 } - err := configure_native_bindings(device, layout, modifiers, overrides, ocrReview, pending...) + err := configureNativeBindingsWithOCR(device, layout, modifiers, overrides, ocrReview, pending...) if err != nil { device.browse = previous if result := C.set_command_keys(device, enabled); result != 0 { @@ -103,11 +103,11 @@ func configure_context_bindings(device *C.CommandDevice, layout input.KeyboardLa return nil } -func (owner *commandOwner) leave_ocr_review() bool { +func (owner *commandOwner) leaveOcrReview() bool { if !owner.ocrReview { return true } - if err := configure_context_bindings(owner.device, owner.layout, owner.modifiers, owner.overrides, owner.listener.browse.Load(), false); err != nil { + if err := configureContextBindings(owner.device, owner.layout, owner.modifiers, owner.overrides, owner.listener.browse.Load(), false); err != nil { owner.listener.failures <- err return false } @@ -115,6 +115,6 @@ func (owner *commandOwner) leave_ocr_review() bool { owner.listener.ocrPending.Store(false) owner.listener.ocrApplied.Store(false) owner.listener.browseApplied.Store(owner.device.browse != 0) - owner.router.ReplaceBindings(owner.context_bindings()) + owner.router.ReplaceBindings(owner.contextBindings()) return true } diff --git a/internal/platform/xorg/commands_owner.go b/internal/platform/xorg/commands_owner.go index 20a94be..c1619dc 100644 --- a/internal/platform/xorg/commands_owner.go +++ b/internal/platform/xorg/commands_owner.go @@ -28,7 +28,7 @@ func (listener *CommandListener) Start(ctx context.Context) error { if listener.done != nil { return errors.New("command listener already started") } - symbols, err := command_modifier_symbols(listener.modifiers) + symbols, err := commandModifierSymbols(listener.modifiers) if err != nil { return err } diff --git a/internal/platform/xorg/commands_owner_loop.go b/internal/platform/xorg/commands_owner_loop.go index 2d12291..03d088c 100644 --- a/internal/platform/xorg/commands_owner_loop.go +++ b/internal/platform/xorg/commands_owner_loop.go @@ -66,15 +66,15 @@ func (owner *commandOwner) run() { break } } - if !owner.sync_internal_ui() { + if !owner.syncInternalUi() { return } - owner.sync_remote_capture() + owner.syncRemoteCapture() if !owner.applyBindingUpdate() { return } if time.Since(owner.lastFocusCheck) >= xtermFocusCheckInterval { - owner.check_steam_focus(owner.publishFocus()) + owner.checkSteamFocus(owner.publishFocus()) } owner.resetForSecureInput() if !owner.syncGrabs() { @@ -97,14 +97,14 @@ func (owner *commandOwner) run() { // A changed XI2 hierarchy invalidates the local source set. A // removed device may never release its held keys; retire that chord. session := owner.uiSession - owner.end_remote_capture("local") + owner.endRemoteCapture("local") clear(owner.held) owner.buffered = nil owner.router.Reset() owner.bound, owner.passThrough = false, false - owner.dismiss_internal_ui() + owner.dismissInternalUi() if session != 0 && !owner.listener.enqueueSecureCommand(input.CommandEvent{Command: input.InternalUIDismiss, UISession: session}) { - owner.report_ui_failure(errors.New("internal UI queue overflow")) + owner.reportUiFailure(errors.New("internal UI queue overflow")) return } continue @@ -122,7 +122,7 @@ func (owner *commandOwner) run() { } func (owner *commandOwner) publishFocus() steamFocusSample { - match, steam := read_command_focus(owner.device.display, !owner.listener.secure.Load() && owner.workerContext.Err() == nil) + match, steam := readCommandFocus(owner.device.display, !owner.listener.secure.Load() && owner.workerContext.Err() == nil) owner.lastFocusCheck = time.Now() if match == 0 || C.int(match) == owner.lastFocusMatch { return steam @@ -174,7 +174,7 @@ func (owner *commandOwner) applyBindingUpdate() bool { } } if err == nil { - err = configure_context_bindings(owner.device, nextLayout, nextModifiers, nextOverrides, owner.listener.browse.Load(), nextOCR, nextPending) + err = configureContextBindings(owner.device, nextLayout, nextModifiers, nextOverrides, owner.listener.browse.Load(), nextOCR, nextPending) } if err == nil { owner.layout, owner.modifiers, owner.overrides = nextLayout, nextModifiers, nextOverrides @@ -184,9 +184,9 @@ func (owner *commandOwner) applyBindingUpdate() bool { owner.listener.ocrPending.Store(nextPending) owner.listener.ocrApplied.Store(nextOCR) owner.listener.browseApplied.Store(owner.device.browse != 0 && !nextOCR) - owner.symbols, _ = command_modifier_symbols(owner.modifiers) + owner.symbols, _ = commandModifierSymbols(owner.modifiers) owner.globalBindings = resolvedBindings(owner.layout, false, owner.overrides) - owner.router = input.NewCommandRouter(owner.symbols, owner.context_bindings()) + owner.router = input.NewCommandRouter(owner.symbols, owner.contextBindings()) } update.result <- err @@ -202,7 +202,7 @@ func (owner *commandOwner) applyBindingUpdate() bool { func (owner *commandOwner) resetForSecureInput() { if owner.listener.secure.Load() && (owner.ocrReview || owner.device.commands != 0 || owner.device.active != 0 || len(owner.held) != 0 || owner.remote != nil) { - owner.end_remote_capture("local") + owner.endRemoteCapture("local") C.release_command_keyboard(owner.device) C.set_command_keys(owner.device, 0) owner.listener.commandsApplied.Store(false) @@ -210,7 +210,7 @@ func (owner *commandOwner) resetForSecureInput() { owner.learnMode = false owner.listener.learnMode.Store(false) owner.listener.learnEcho.Store(false) - owner.dismiss_internal_ui() + owner.dismissInternalUi() owner.listener.uiEcho.Store(false) clear(owner.held) owner.buffered = nil @@ -218,7 +218,7 @@ func (owner *commandOwner) resetForSecureInput() { owner.ocrReview, owner.ocrPending = false, false owner.listener.ocrPending.Store(false) owner.listener.ocrApplied.Store(false) - if err := configure_context_bindings(owner.device, owner.layout, owner.modifiers, owner.overrides, false, false); err != nil { + if err := configureContextBindings(owner.device, owner.layout, owner.modifiers, owner.overrides, false, false); err != nil { owner.listener.failures <- err } owner.router = input.NewCommandRouter(owner.symbols, resolvedBindings(owner.layout, false, owner.overrides)) @@ -228,7 +228,7 @@ func (owner *commandOwner) resetForSecureInput() { func (owner *commandOwner) syncGrabs() bool { if len(owner.held) == 0 && (owner.device.bypass != 0) != owner.listener.bypass.Load() { if owner.ocrReview { - if !owner.leave_ocr_review() || !owner.listener.enqueueSecureCommand(input.CommandEvent{Command: input.OCRDismiss}) { + if !owner.leaveOcrReview() || !owner.listener.enqueueSecureCommand(input.CommandEvent{Command: input.OCRDismiss}) { return false } } @@ -237,19 +237,19 @@ func (owner *commandOwner) syncGrabs() bool { if owner.listener.bypass.Load() { owner.device.bypass = 1 } - if err := configure_context_bindings(owner.device, owner.layout, owner.modifiers, owner.overrides, owner.listener.browse.Load(), false); err != nil { + if err := configureContextBindings(owner.device, owner.layout, owner.modifiers, owner.overrides, owner.listener.browse.Load(), false); err != nil { owner.device.bypass = previous owner.listener.failures <- err return false } - owner.router.ReplaceBindings(owner.context_bindings()) + owner.router.ReplaceBindings(owner.contextBindings()) owner.listener.bypassApplied.Store(owner.device.bypass != 0) owner.listener.browseApplied.Store(owner.device.browse != 0) } if owner.ocrReview && len(owner.held) == 0 { foreground := C.read_foreground(owner.device.display) if foreground.known == 0 || foreground.window == 0 || foreground.window != owner.device.browseWindow { - if !owner.leave_ocr_review() { + if !owner.leaveOcrReview() { return false } if !owner.listener.enqueueSecureCommand(input.CommandEvent{Command: input.OCRDismiss}) { @@ -259,7 +259,7 @@ func (owner *commandOwner) syncGrabs() bool { } enabled := owner.commandGrabsAllowed() if owner.ocrReview && !enabled && len(owner.held) == 0 { - if !owner.leave_ocr_review() { + if !owner.leaveOcrReview() { return false } } @@ -295,7 +295,7 @@ func (owner *commandOwner) syncGrabs() bool { owner.listener.failures <- fmt.Errorf("change X11 browse grabs: native error %d", int(err)) return false } - owner.router.ReplaceBindings(owner.context_bindings()) + owner.router.ReplaceBindings(owner.contextBindings()) owner.listener.browseApplied.Store(enabled) } owner.device.nativeButtonFocus = 0 @@ -312,7 +312,7 @@ func (owner *commandOwner) publishLocks(key C.CommandKey) { // Remote's lock keys belong to the peer, including its feedback. Local // announcements would cancel incoming speech and repeat the peer's echo. if owner.remote == nil && (key.locks^owner.lastLocks)&mask != 0 { - owner.listener.publish_lock_state(input.LockState{Name: name, Locked: key.locks&mask != 0, Timestamp: uint32(key.timestamp)}) + owner.listener.publishLockState(input.LockState{Name: name, Locked: key.locks&mask != 0, Timestamp: uint32(key.timestamp)}) } } owner.lastLocks = key.locks diff --git a/internal/platform/xorg/commands_remote.go b/internal/platform/xorg/commands_remote.go index 6b33942..2262ac1 100644 --- a/internal/platform/xorg/commands_remote.go +++ b/internal/platform/xorg/commands_remote.go @@ -67,7 +67,7 @@ func (listener *CommandListener) BeginRemoteCapture(ctx context.Context, localPr if !strings.HasPrefix(localPrefix, "tentacle/") || !strings.HasSuffix(localPrefix, "/") { return 0, nil, errors.New("invalid remote capture command prefix") } - reply, err := listener.update_remote_capture(ctx, 0, localPrefix) + reply, err := listener.updateRemoteCapture(ctx, 0, localPrefix) return reply.session, reply.events, err } @@ -78,11 +78,11 @@ func (listener *CommandListener) EndRemoteCapture(ctx context.Context, session u if session == 0 { return errors.New("missing remote capture session") } - _, err := listener.update_remote_capture(ctx, session, "") + _, err := listener.updateRemoteCapture(ctx, session, "") return err } -func (listener *CommandListener) update_remote_capture(ctx context.Context, session uint64, prefix string) (remoteCaptureReply, error) { +func (listener *CommandListener) updateRemoteCapture(ctx context.Context, session uint64, prefix string) (remoteCaptureReply, error) { listener.mutex.Lock() done := listener.done listener.mutex.Unlock() @@ -105,14 +105,14 @@ func (listener *CommandListener) update_remote_capture(ctx context.Context, sess } } -// sync_remote_capture ends capture on reader policy and services begin/end +// syncRemoteCapture ends capture on reader policy and services begin/end // requests between chords. The core escape never passes through here. -func (owner *commandOwner) sync_remote_capture() { +func (owner *commandOwner) syncRemoteCapture() { if owner.remote != nil && (!owner.commandGrabsAllowed() || owner.learnMode || owner.ocrReview) { - owner.end_remote_capture("local") + owner.endRemoteCapture("local") } if owner.remote != nil { - owner.flush_remote(time.Now()) + owner.flushRemote(time.Now()) } if len(owner.held) != 0 { return @@ -123,10 +123,10 @@ func (owner *commandOwner) sync_remote_capture() { if reply.err == nil { if update.session != 0 { if owner.remote != nil && owner.remote.session == update.session { - owner.end_remote_capture("requested") + owner.endRemoteCapture("requested") } } else { - reply.session, reply.events, reply.err = owner.begin_remote_capture(update.prefix) + reply.session, reply.events, reply.err = owner.beginRemoteCapture(update.prefix) } } update.result <- reply @@ -134,7 +134,7 @@ func (owner *commandOwner) sync_remote_capture() { } } -func (owner *commandOwner) begin_remote_capture(prefix string) (uint64, <-chan input.RemoteCaptureEvent, error) { +func (owner *commandOwner) beginRemoteCapture(prefix string) (uint64, <-chan input.RemoteCaptureEvent, error) { if !owner.commandGrabsAllowed() || owner.learnMode || owner.ocrReview || owner.uiSession != 0 || owner.remote != nil { return 0, nil, errors.New("remote capture unavailable") } @@ -163,21 +163,21 @@ func (owner *commandOwner) begin_remote_capture(prefix string) (uint64, <-chan i return session, owner.remote.events, nil } -// end_remote_capture releases every owned remote key through the event +// endRemoteCapture releases every owned remote key through the event // stream, then the end marker, and closes the stream. Physically held keys // keep the grab until their releases arrive, so none leak to an application // that never received the press. -func (owner *commandOwner) end_remote_capture(reason string) { +func (owner *commandOwner) endRemoteCapture(reason string) { capture := owner.remote if capture == nil || capture.ending { return } capture.ending = true for _, transition := range capture.normalizer.Retire() { - owner.route_remote(input.RemoteCaptureKey{Keycode: transition.Keycode}) + owner.routeRemote(input.RemoteCaptureKey{Keycode: transition.Keycode}) } for _, transition := range capture.router.Retire().Remote { - owner.send_remote(input.RemoteCaptureEvent{Key: &input.RemoteCaptureTransition{Code: transition.Keycode}}) + owner.sendRemote(input.RemoteCaptureEvent{Key: &input.RemoteCaptureTransition{Code: transition.Keycode}}) } capture.events <- input.RemoteCaptureEvent{Ended: reason} // Reserved capacity. close(capture.events) @@ -191,28 +191,28 @@ func (owner *commandOwner) end_remote_capture(reason string) { } } -// send_remote never blocks the X thread. Running into the reserve ends +// sendRemote never blocks the X thread. Running into the reserve ends // capture; the reserve still holds the release plan and end marker. -func (owner *commandOwner) send_remote(event input.RemoteCaptureEvent) bool { +func (owner *commandOwner) sendRemote(event input.RemoteCaptureEvent) bool { capture := owner.remote if capture == nil { return false } if !capture.ending && len(capture.events) >= cap(capture.events)-remoteCaptureReserve && event.Key != nil && event.Key.Pressed { - owner.end_remote_capture("local") + owner.endRemoteCapture("local") return false } capture.events <- event return true } -func (owner *commandOwner) flush_remote(now time.Time) { +func (owner *commandOwner) flushRemote(now time.Time) { for _, transition := range owner.remote.normalizer.Flush(now) { - owner.route_remote(input.RemoteCaptureKey{Keycode: transition.Keycode}) + owner.routeRemote(input.RemoteCaptureKey{Keycode: transition.Keycode}) } } -func (owner *commandOwner) handle_remote_key(key C.CommandKey) { +func (owner *commandOwner) handleRemoteKey(key C.CommandKey) { owner.bound = true capture := owner.remote event := input.Event{Keycode: uint8(key.code), Pressed: key.pressed != 0, Timestamp: uint32(key.timestamp)} @@ -231,21 +231,21 @@ func (owner *commandOwner) handle_remote_key(key C.CommandKey) { capture.names[transition.Keycode] = name routed.Unsupported = name == "" } - owner.route_remote(routed) + owner.routeRemote(routed) } if err != nil && owner.remote != nil { - owner.end_remote_capture("local") + owner.endRemoteCapture("local") } } -func (owner *commandOwner) route_remote(key input.RemoteCaptureKey) { +func (owner *commandOwner) routeRemote(key input.RemoteCaptureKey) { capture := owner.remote if capture == nil { return } result, err := capture.router.Route(key) if err != nil { - owner.end_remote_capture("local") // No-op while already ending. + owner.endRemoteCapture("local") // No-op while already ending. return } for _, transition := range result.Remote { @@ -253,7 +253,7 @@ func (owner *commandOwner) route_remote(key input.RemoteCaptureKey) { if transition.Pressed && !transition.Repeat { forwarded.Name = capture.names[transition.Keycode] } - if !owner.send_remote(input.RemoteCaptureEvent{Key: forwarded}) { + if !owner.sendRemote(input.RemoteCaptureEvent{Key: forwarded}) { return } } @@ -261,12 +261,12 @@ func (owner *commandOwner) route_remote(key input.RemoteCaptureKey) { return } if result.Escape { - owner.end_remote_capture("escape") + owner.endRemoteCapture("escape") return } // A Remote shortcut returns the keyboard here instead of running: running it // would race with the focus change. Press it again under local focus. if result.Local != "" { - owner.end_remote_capture("requested") + owner.endRemoteCapture("requested") } } diff --git a/internal/platform/xorg/commands_security.go b/internal/platform/xorg/commands_security.go index 173b92d..a442f8e 100644 --- a/internal/platform/xorg/commands_security.go +++ b/internal/platform/xorg/commands_security.go @@ -23,7 +23,7 @@ func (listener *CommandListener) SetSecureInputActive(active bool) { } } -func (listener *CommandListener) publish_lock_state(state input.LockState) { +func (listener *CommandListener) publishLockState(state input.LockState) { listener.secureMutex.Lock() defer listener.secureMutex.Unlock() if listener.secure.Load() { diff --git a/internal/platform/xorg/commands_ui.go b/internal/platform/xorg/commands_ui.go index f0ef377..0147a35 100644 --- a/internal/platform/xorg/commands_ui.go +++ b/internal/platform/xorg/commands_ui.go @@ -37,14 +37,14 @@ func (listener *CommandListener) InternalUIEchoActive() bool { return listener.u // BeginInternalUI acknowledges exclusive capture without changing X input // focus. EndInternalUI waits for physical releases, and cannot close a newer UI. func (listener *CommandListener) BeginInternalUI(ctx context.Context) (uint64, error) { - return listener.update_internal_ui(ctx, 0, false) + return listener.updateInternalUi(ctx, 0, false) } // BeginLocalUI admits only device-backed XI2 events and excludes XTEST. This // is a core API, never a Tentacle-controlled form flag. It fails on unsupported // servers; ordinary forms keep their existing input path. func (listener *CommandListener) BeginLocalUI(ctx context.Context) (uint64, error) { - return listener.update_internal_ui(ctx, 0, true) + return listener.updateInternalUi(ctx, 0, true) } func (listener *CommandListener) EndInternalUI(ctx context.Context, session uint64) error { if session == 0 { @@ -59,10 +59,10 @@ func (listener *CommandListener) EndInternalUI(ctx context.Context, session uint break } } - _, err := listener.update_internal_ui(ctx, session, false) + _, err := listener.updateInternalUi(ctx, session, false) return err } -func (listener *CommandListener) update_internal_ui(ctx context.Context, closeSession uint64, localOnly bool) (uint64, error) { +func (listener *CommandListener) updateInternalUi(ctx context.Context, closeSession uint64, localOnly bool) (uint64, error) { listener.mutex.Lock() done := listener.done listener.mutex.Unlock() @@ -85,7 +85,7 @@ func (listener *CommandListener) update_internal_ui(ctx context.Context, closeSe } } -func (owner *commandOwner) begin_internal_ui_mode(localOnly bool) (uint64, error) { +func (owner *commandOwner) beginInternalUiMode(localOnly bool) (uint64, error) { if !owner.commandGrabsAllowed() || owner.learnMode || owner.ocrReview || owner.uiSession != 0 || owner.remote != nil { return 0, errors.New("internal UI input unavailable") } @@ -111,11 +111,11 @@ func (owner *commandOwner) begin_internal_ui_mode(localOnly bool) (uint64, error return owner.uiSession, nil } -func (owner *commandOwner) begin_internal_ui() (uint64, error) { - return owner.begin_internal_ui_mode(false) +func (owner *commandOwner) beginInternalUi() (uint64, error) { + return owner.beginInternalUiMode(false) } -func (owner *commandOwner) dismiss_internal_ui() { +func (owner *commandOwner) dismissInternalUi() { owner.uiSession = 0 owner.listener.uiSession.Store(0) C.reset_internal_compose(owner.device) @@ -125,11 +125,11 @@ func (owner *commandOwner) dismiss_internal_ui() { owner.listener.grabActive.Store(false) } } -func (owner *commandOwner) report_ui_failure(err error) bool { +func (owner *commandOwner) reportUiFailure(err error) bool { owner.listener.failures <- err return false } -func (owner *commandOwner) sync_internal_ui() bool { +func (owner *commandOwner) syncInternalUi() bool { if owner.uiSession != 0 { var focus C.Window var revert C.int @@ -137,11 +137,11 @@ func (owner *commandOwner) sync_internal_ui() bool { requestedClose := owner.listener.uiClose.Load() == owner.uiSession if requestedClose || !owner.commandGrabsAllowed() || focus != owner.uiFocus || C.read_foreground(owner.device.display).window != owner.uiWindow { session := owner.uiSession - owner.dismiss_internal_ui() + owner.dismissInternalUi() // Retain ownership of the current chord until its releases arrive. owner.bound = len(owner.held) != 0 if !requestedClose && !owner.listener.enqueueSecureCommand(input.CommandEvent{Command: input.InternalUIDismiss, UISession: session}) { - return owner.report_ui_failure(errors.New("internal UI queue overflow")) + return owner.reportUiFailure(errors.New("internal UI queue overflow")) } } } @@ -152,10 +152,10 @@ func (owner *commandOwner) sync_internal_ui() bool { if result.err == nil { if update.closeSession != 0 { if update.closeSession == owner.uiSession { - owner.dismiss_internal_ui() + owner.dismissInternalUi() } } else { - result.session, result.err = owner.begin_internal_ui_mode(update.localOnly) + result.session, result.err = owner.beginInternalUiMode(update.localOnly) } } update.result <- result @@ -165,7 +165,7 @@ func (owner *commandOwner) sync_internal_ui() bool { return true } -func (owner *commandOwner) handle_internal_key(key C.CommandKey) bool { +func (owner *commandOwner) handleInternalKey(key C.CommandKey) bool { owner.bound = true owner.router.Handle(uint32(key.symbol), uint16(key.code), uint16(key.modifiers), key.pressed != 0) if key.pressed == 0 { @@ -185,10 +185,10 @@ func (owner *commandOwner) handle_internal_key(key C.CommandKey) bool { } event := input.CommandEvent{Command: input.InternalUIKey, UISession: owner.uiSession, Timestamp: uint32(key.timestamp), Chord: chord, Text: C.GoString(&key.text[0])} if uint32(key.symbol) == 0xff1b { - owner.dismiss_internal_ui() + owner.dismissInternalUi() } if !owner.listener.enqueueSecureCommand(event) { - return owner.report_ui_failure(errors.New("internal UI queue overflow")) + return owner.reportUiFailure(errors.New("internal UI queue overflow")) } return true } diff --git a/internal/platform/xorg/steam_focus.go b/internal/platform/xorg/steam_focus.go index a9c7c82..8b7b3d8 100644 --- a/internal/platform/xorg/steam_focus.go +++ b/internal/platform/xorg/steam_focus.go @@ -56,7 +56,7 @@ func (repair *steamFocusRepair) observe(sample steamFocusSample) uint64 { return repair.target } -func read_command_focus(display *C.Display, steamEnabled bool) (int, steamFocusSample) { +func readCommandFocus(display *C.Display, steamEnabled bool) (int, steamFocusSample) { var enabled C.int if steamEnabled { enabled = 1 @@ -67,11 +67,11 @@ func read_command_focus(display *C.Display, steamEnabled bool) (int, steamFocusS known: value.known != 0, steam: value.steam != 0, innerFocus: value.innerFocus != 0} } -func restore_steam_focus(display *C.Display, window uint64, pid int, target uint64) bool { +func restoreSteamFocus(display *C.Display, window uint64, pid int, target uint64) bool { return C.cthulhu_restore_steam_focus(display, C.Window(window), C.int(pid), C.Window(target)) != 0 } -func (owner *commandOwner) check_steam_focus(sample steamFocusSample) { +func (owner *commandOwner) checkSteamFocus(sample steamFocusSample) { if owner.listener.secure.Load() || owner.workerContext.Err() != nil { owner.steamFocus.checksLeft = 0 return @@ -81,7 +81,7 @@ func (owner *commandOwner) check_steam_focus(sample steamFocusSample) { owner.learnMode || owner.uiSession != 0 || owner.ocrReview || owner.ocrPending { return } - if restore_steam_focus(owner.device.display, sample.window, sample.pid, target) { + if restoreSteamFocus(owner.device.display, sample.window, sample.pid, target) { owner.steamFocus.checksLeft = 0 } } diff --git a/internal/platform/xorg/steam_focus_native_test.go b/internal/platform/xorg/steam_focus_native_test.go index fd53865..f3f00de 100644 --- a/internal/platform/xorg/steam_focus_native_test.go +++ b/internal/platform/xorg/steam_focus_native_test.go @@ -68,13 +68,13 @@ func TestNativeSteamFocusRepair(t *testing.T) { defer reader.Close() readSteam := func() steamFocusSample { t.Helper() - match, sample := read_command_focus(reader.display, true) + match, sample := readCommandFocus(reader.display, true) if match != 2 { t.Fatalf("Steam/ordinary window XTerm match = %d", match) } return sample } - match, disabled := read_command_focus(reader.display, false) + match, disabled := readCommandFocus(reader.display, false) if match != 2 || disabled != (steamFocusSample{}) { t.Fatalf("disabled Steam sampling = %d, %+v", match, disabled) } @@ -99,7 +99,7 @@ func TestNativeSteamFocusRepair(t *testing.T) { return repair.observe(readSteam()) } target := roundTrip() - if target != windows["browser"] || !restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if target != windows["browser"] || !restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("main browser keyboard focus was not repaired") } key("key", "Escape") @@ -127,52 +127,52 @@ func TestNativeSteamFocusRepair(t *testing.T) { t.Fatal("valid popup focus was overridden") } target = roundTrip() - if target != windows["popup"] || !restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if target != windows["popup"] || !restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("popup keyboard focus was not repaired") } command("focus", "browser") - if restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("valid search/control browser focus was overridden") } command("activate", "steam") key("keydown", "Control_L") - blocked := restore_steam_focus(reader.display, sample.window, sample.pid, target) + blocked := restoreSteamFocus(reader.display, sample.window, sample.pid, target) key("keyup", "Control_L") if blocked { t.Fatal("focus moved while a physical modifier was held") } command("activate", "other") - if restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("repair stole focus from another application") } command("activate", "steam") - if restore_steam_focus(reader.display, sample.window, sample.pid, windows["otherChild"]) { + if restoreSteamFocus(reader.display, sample.window, sample.pid, windows["otherChild"]) { t.Fatal("repair targeted an unrelated child") } command("unmap", "popupHost") - if restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("repair focused a hidden popup") } command("map", "popupHost") command("pid", "popup") - if restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("repair focused a child from a different process") } command("destroy", "popup") - if restore_steam_focus(reader.display, sample.window, sample.pid, target) { + if restoreSteamFocus(reader.display, sample.window, sample.pid, target) { t.Fatal("repair focused a destroyed popup") } command("class", "steam") - if readSteam().steam || restore_steam_focus(reader.display, sample.window, sample.pid, windows["browser"]) { + if readSteam().steam || restoreSteamFocus(reader.display, sample.window, sample.pid, windows["browser"]) { t.Fatal("repair changed focus in an ordinary application") } command("xterm", "steam") - match, terminal := read_command_focus(reader.display, true) + match, terminal := readCommandFocus(reader.display, true) if match != 1 || !terminal.known || terminal.steam || terminal.focus != 0 { t.Fatalf("XTerm class change = %d, %+v", match, terminal) } command("unknown", "steam") - match, unknown := read_command_focus(reader.display, true) + match, unknown := readCommandFocus(reader.display, true) if match != 0 || unknown != (steamFocusSample{}) { t.Fatalf("unknown foreground = %d, %+v", match, unknown) } diff --git a/internal/preferences/applications.go b/internal/preferences/applications.go index 6fa3c61..38e2b89 100644 --- a/internal/preferences/applications.go +++ b/internal/preferences/applications.go @@ -31,7 +31,7 @@ type applicationIdentity struct { pid int } -func application_choices(accessible []applicationIdentity, windows []xorg.ApplicationWindow) []string { +func applicationChoices(accessible []applicationIdentity, windows []xorg.ApplicationWindow) []string { names := make(map[string]bool) byPID := make(map[int]string) add := func(name string) { @@ -61,7 +61,7 @@ func application_choices(accessible []applicationIdentity, windows []xorg.Applic return choices } -func running_applications() []string { +func runningApplications() []string { var count C.int native := C.prefs_application_names(&count) defer C.prefs_free_application_names(native, count) @@ -78,13 +78,13 @@ func running_applications() []string { } reader := xorg.OpenForegroundReader() defer reader.Close() - return application_choices(accessible, reader.ApplicationWindows()) + return applicationChoices(accessible, reader.ApplicationWindows()) } // The chooser shares the preferences child and bounded pipe protocol. Cancel // emits no request, so it cannot open a profile or submit settings. -func choose_application(ctx context.Context, updates <-chan Response, errorsIn <-chan error, output io.Writer) (Response, bool, error) { - choices := running_applications() +func chooseApplication(ctx context.Context, updates <-chan Response, errorsIn <-chan error, output io.Writer) (Response, bool, error) { + choices := runningApplications() if C.prefs_application_chooser_init() == 0 { return Response{}, false, errors.New("cannot open application chooser on this display") } diff --git a/internal/preferences/applications_test.go b/internal/preferences/applications_test.go index 7e617af..38ef444 100644 --- a/internal/preferences/applications_test.go +++ b/internal/preferences/applications_test.go @@ -17,7 +17,7 @@ func TestApplicationChoicesUseProfileIdentityAndWineChildren(t *testing.T) { {Application: "Example Editor", PID: 4}, } want := []string{"Example Browser", "Example Editor", "Example Terminal", "Game.exe", "Other Unknown PID Application", "Unknown PID Application"} - if got := application_choices(accessible, windows); !reflect.DeepEqual(got, want) { + if got := applicationChoices(accessible, windows); !reflect.DeepEqual(got, want) { t.Fatalf("applications = %v, want %v", got, want) } } diff --git a/internal/preferences/braille.go b/internal/preferences/braille.go index e2f25f3..622fb70 100644 --- a/internal/preferences/braille.go +++ b/internal/preferences/braille.go @@ -42,7 +42,7 @@ func getBrailleIndicator(prefix string) int { return 0 } -func (session *uiSession) set_braille_values(values Values) { +func (session *uiSession) setBrailleValues(values Values) { setCheck("enableBrailleCheckButton", values.EnableBraille) setCheck("contractedBrailleCheckButton", values.EnableContractedBraille) setCheck("abbrevRolenames", values.Braille.AbbreviateRoles) @@ -85,7 +85,7 @@ func (session *uiSession) set_braille_values(values Values) { C.free(unsafe.Pointer(comboID)) } -func (session *uiSession) get_braille_values(values *Values) error { +func (session *uiSession) getBrailleValues(values *Values) error { values.EnableBraille = getCheck("enableBrailleCheckButton") values.EnableContractedBraille = getCheck("contractedBrailleCheckButton") values.Braille.AbbreviateRoles = getCheck("abbrevRolenames") diff --git a/internal/preferences/catalog_protocol.go b/internal/preferences/catalog_protocol.go index cad03fd..5cc6f30 100644 --- a/internal/preferences/catalog_protocol.go +++ b/internal/preferences/catalog_protocol.go @@ -81,9 +81,9 @@ func EncodeInitial(encoder *json.Encoder, response Response) error { return encoder.Encode(catalogPart{}) } -// read_responses owns catalog assembly for the lifetime of the helper pipe. +// readResponses owns catalog assembly for the lifetime of the helper pipe. // Only complete responses reach GTK, including after application selection. -func read_responses(ctx context.Context, input io.Reader, updates chan<- Response, errorsIn chan<- error) { +func readResponses(ctx context.Context, input io.Reader, updates chan<- Response, errorsIn chan<- error) { scanner := bufio.NewScanner(input) scanner.Buffer(make([]byte, 4096), 1024*1024) var initial *Response diff --git a/internal/preferences/catalog_protocol_test.go b/internal/preferences/catalog_protocol_test.go index fb2ca31..1e78215 100644 --- a/internal/preferences/catalog_protocol_test.go +++ b/internal/preferences/catalog_protocol_test.go @@ -51,7 +51,7 @@ func TestInitialCatalogRoundTrip(t *testing.T) { } updates := make(chan Response, 3) errorsIn := make(chan error, 1) - read_responses(t.Context(), &wire, updates, errorsIn) + readResponses(t.Context(), &wire, updates, errorsIn) if err := <-errorsIn; err != nil { t.Fatal(err) } @@ -82,13 +82,13 @@ func TestInitialCatalogRejectsOversizedEntry(t *testing.T) { func TestInitialCatalogIncompleteAndCancellation(t *testing.T) { updates := make(chan Response, 1) errorsIn := make(chan error, 1) - read_responses(t.Context(), strings.NewReader(`{"CatalogPending":true}`+"\n"), updates, errorsIn) + readResponses(t.Context(), strings.NewReader(`{"CatalogPending":true}`+"\n"), updates, errorsIn) if err := <-errorsIn; !errors.Is(err, io.ErrUnexpectedEOF) || len(updates) != 0 { t.Fatalf("incomplete catalog reached the UI: %v", err) } ctx, cancel := context.WithCancel(t.Context()) cancel() - read_responses(ctx, strings.NewReader("{}\n"), make(chan Response), errorsIn) + readResponses(ctx, strings.NewReader("{}\n"), make(chan Response), errorsIn) } func TestDefaultVoicesFiltersESpeakAndDefaultAlias(t *testing.T) { @@ -96,18 +96,18 @@ func TestDefaultVoicesFiltersESpeakAndDefaultAlias(t *testing.T) { voices := []speech.Voice{{Name: "German", Language: "de"}, {Name: "English", Language: "en-US"}} session := &uiSession{catalog: speech.Catalog{"": voices, "espeak-ng": voices, "other": voices}} for _, module := range []string{"", "espeak-ng"} { - if got := session.default_voices(module); !reflect.DeepEqual(got, voices[1:]) { + if got := session.defaultVoices(module); !reflect.DeepEqual(got, voices[1:]) { t.Fatalf("module %q: %v", module, got) } } - if got := session.default_voices("other"); !reflect.DeepEqual(got, voices) { + if got := session.defaultVoices("other"); !reflect.DeepEqual(got, voices) { t.Fatal("other synthesizer was filtered") } if !reflect.DeepEqual(session.catalog["espeak-ng"], voices) { t.Fatal("language selection lost the full catalog") } session.catalog[""] = voices[:1] - if got := session.default_voices(""); !reflect.DeepEqual(got, voices[:1]) { + if got := session.defaultVoices(""); !reflect.DeepEqual(got, voices[:1]) { t.Fatal("unidentified default synthesizer was filtered") } } diff --git a/internal/preferences/catalog_voices.go b/internal/preferences/catalog_voices.go index 53179ce..6cdbc37 100644 --- a/internal/preferences/catalog_voices.go +++ b/internal/preferences/catalog_voices.go @@ -11,10 +11,10 @@ import ( "git.stormux.org/storm/cthulhu/internal/speech" ) -// default_voices filters eSpeak's language/variant combinations for controls +// defaultVoices filters eSpeak's language/variant combinations for controls // without an explicit language selection. Saved voices remain available through // the caller's selected-family entry, and the full language catalog is retained. -func (session *uiSession) default_voices(module string) []speech.Voice { +func (session *uiSession) defaultVoices(module string) []speech.Voice { voices := session.catalog[module] if strings.Contains(strings.ToLower(module), "espeak") { return speech.LocaleVoices(voices) diff --git a/internal/preferences/echo.go b/internal/preferences/echo.go index d51945c..40028d7 100644 --- a/internal/preferences/echo.go +++ b/internal/preferences/echo.go @@ -103,7 +103,7 @@ func (session *uiSession) populateEchoFamilies(module string, selected *config.V session.echoFamilies = []*config.VoiceFamily{nil} labels := []string{"Default"} index := 0 - for _, voice := range session.default_voices(module) { + for _, voice := range session.defaultVoices(module) { family := &config.VoiceFamily{Name: voice.Name, Lang: voice.Language, Variant: voice.Variant} session.echoFamilies = append(session.echoFamilies, family) labels = append(labels, voice.Name+" ("+voice.Language+")") @@ -154,7 +154,7 @@ func (session *uiSession) getEchoVoice() (config.Voice, string) { return voice, session.selectedEchoModule() } -func set_echo_checks(values Values) { +func setEchoChecks(values Values) { setCheck("keyEchoDisabledRadio", !values.EnableKeyEcho) setCheck("keyEchoEnabledRadio", values.EnableKeyEcho && !values.KeyEchoInEditFieldsOnly) setCheck("keyEchoEditFieldsRadio", values.EnableKeyEcho && values.KeyEchoInEditFieldsOnly) @@ -163,7 +163,7 @@ func set_echo_checks(values Values) { } } -func get_echo_checks(values *Values) { +func getEchoChecks(values *Values) { values.EnableKeyEcho = !getCheck("keyEchoDisabledRadio") values.KeyEchoInEditFieldsOnly = getCheck("keyEchoEditFieldsRadio") for _, check := range echoChecks(values) { diff --git a/internal/preferences/extensions.go b/internal/preferences/extensions.go index 80c50b6..2bc964b 100644 --- a/internal/preferences/extensions.go +++ b/internal/preferences/extensions.go @@ -11,20 +11,19 @@ import "C" import ( "fmt" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/tentaclewire" "unsafe" ) -func extension_page_key(page ExtensionPage) string { return page.Session + "/" + page.ID } +func extensionPageKey(page ExtensionPage) string { return page.Session + "/" + page.ID } // GTK owns native focus. Refreshes keep unchanged widgets and their unapplied // drafts, and move focus to the notebook before removing a revoked page. -func (session *uiSession) set_extension_pages(pages []ExtensionPage) error { +func (session *uiSession) setExtensionPages(pages []ExtensionPage) error { selected := C.GoString(C.prefs_extension_selected()) ids := map[string]bool{} for _, page := range pages { - key := extension_page_key(page) + key := extensionPageKey(page) if page.Session == "" || ids[key] { return fmt.Errorf("invalid extension page identity") } @@ -35,9 +34,9 @@ func (session *uiSession) set_extension_pages(pages []ExtensionPage) error { } keep := map[string]bool{} for _, previous := range session.extensionPages { - key := extension_page_key(previous) + key := extensionPageKey(previous) for _, page := range pages { - if extension_page_key(page) == key && page.Revision == previous.Revision { + if extensionPageKey(page) == key && page.Revision == previous.Revision { keep[key] = true break } @@ -49,7 +48,7 @@ func (session *uiSession) set_extension_pages(pages []ExtensionPage) error { } } for _, page := range pages { - key := extension_page_key(page) + key := extensionPageKey(page) if keep[key] { continue } @@ -68,7 +67,7 @@ func (session *uiSession) set_extension_pages(pages []ExtensionPage) error { } value := page.Values[element.ID] text := value.Text - if element.Kind == interaction.List { + if element.Kind == tentaclewire.List { text = value.Selected } cText := C.CString(text) @@ -86,20 +85,20 @@ func (session *uiSession) set_extension_pages(pages []ExtensionPage) error { } return nil } -func (session *uiSession) extension_drafts() ([]PageDraft, error) { +func (session *uiSession) extensionDrafts() ([]PageDraft, error) { var drafts []PageDraft for _, page := range session.extensionPages { - values := map[string]interaction.Value{} - key := C.CString(extension_page_key(page)) + values := map[string]tentaclewire.Value{} + key := C.CString(extensionPageKey(page)) for _, element := range page.Elements { id := C.CString(element.ID) - value := interaction.Value{} + value := tentaclewire.Value{} switch element.Kind { - case interaction.List: + case tentaclewire.List: value.Selected = C.GoString(C.prefs_extension_text(key, id, C.int(element.Kind))) - case interaction.Entry: + case tentaclewire.Entry: value.Text = C.GoString(C.prefs_extension_text(key, id, C.int(element.Kind))) - case interaction.CheckBox: + case tentaclewire.CheckBox: value.Checked = C.prefs_extension_checked(key, id) != 0 } C.free(unsafe.Pointer(id)) diff --git a/internal/preferences/general.go b/internal/preferences/general.go index d325312..f73db8d 100644 --- a/internal/preferences/general.go +++ b/internal/preferences/general.go @@ -15,8 +15,8 @@ import ( "time" "unsafe" - "git.stormux.org/storm/cthulhu/internal/datetime" "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/screenreader-common/datetime" ) func setFormatCombo(name string, options []datetime.Option, value string) { @@ -40,7 +40,7 @@ func formatIndex(options []datetime.Option, value string) int { return 0 } -func (session *uiSession) set_general_values(values Values) { +func (session *uiSession) setGeneralValues(values Values) { setCheck("structuralNavigationFocusCheckButton", values.StructuralNavigationTriggersFocusMode) session.progressBar = values.ProgressBar session.setKeyBindings(values) @@ -51,7 +51,7 @@ func (session *uiSession) set_general_values(values Values) { setFormatCombo("dateFormatCombo", datetime.DateOptions(now), values.DateFormat) } -func (session *uiSession) get_general_values(values *Values) error { +func (session *uiSession) getGeneralValues(values *Values) error { values.StructuralNavigationTriggersFocusMode = getCheck("structuralNavigationFocusCheckButton") values.KeyBindings = input.CloneBindingOverrides(session.bindingDraft) values.KeyboardLayout = 1 diff --git a/internal/preferences/native.h b/internal/preferences/native.h index 2a48332..cc489b0 100644 --- a/internal/preferences/native.h +++ b/internal/preferences/native.h @@ -37,7 +37,7 @@ void prefs_hardware_devices_clear(void); void prefs_hardware_device_append(const char *text); void prefs_hardware_device_set(const char *text); const char *prefs_hardware_device_get(void); -void prefs_hardware_sensitivity(int enabled); +void prefs_hardware_sensitivity(int enabled, int serial); void prefs_combo_set(const char *id, int value); int prefs_combo_get(const char *id); diff --git a/internal/preferences/native_widgets.c b/internal/preferences/native_widgets.c index 0fa22dd..191cad2 100644 --- a/internal/preferences/native_widgets.c +++ b/internal/preferences/native_widgets.c @@ -59,9 +59,9 @@ void prefs_hardware_device_set(const char *text) { const char *prefs_hardware_device_get(void) { return gtk_entry_get_text(GTK_ENTRY(prefs_widget("hardwareDeviceEntry"))); } -void prefs_hardware_sensitivity(int enabled) { - gtk_widget_set_sensitive(prefs_widget("hardwareDeviceEntry"), enabled); - gtk_widget_set_sensitive(prefs_widget("hardwareBaudCombo"), enabled); +void prefs_hardware_sensitivity(int enabled, int serial) { + gtk_widget_set_sensitive(prefs_widget("hardwareDeviceEntry"), enabled && serial); + gtk_widget_set_sensitive(prefs_widget("hardwareBaudCombo"), enabled && serial); gtk_widget_set_sensitive(prefs_widget("speechLanguages"), !enabled); gtk_widget_set_sensitive(prefs_widget("speechFamilies"), !enabled); } diff --git a/internal/preferences/protocol.go b/internal/preferences/protocol.go index 9b71c8f..4054218 100644 --- a/internal/preferences/protocol.go +++ b/internal/preferences/protocol.go @@ -9,7 +9,6 @@ package preferences import ( "git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/input" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/speech" "git.stormux.org/storm/cthulhu/internal/tentacle" "git.stormux.org/storm/cthulhu/internal/tentaclewire" @@ -103,7 +102,7 @@ type PageDraft struct { Session string ID string Revision uint64 - Values map[string]interaction.Value + Values map[string]tentaclewire.Value } type Request struct { diff --git a/internal/preferences/sound.go b/internal/preferences/sound.go index e95dec0..9cdf43b 100644 --- a/internal/preferences/sound.go +++ b/internal/preferences/sound.go @@ -46,26 +46,26 @@ func (session *uiSession) setSoundTheme(theme string) { comboItems("soundThemeCombo", labels, selected) } -func set_sound_checks(values Values) { +func setSoundChecks(values Values) { for _, check := range soundChecks(&values) { setCheck(check.id, *check.value) } } -func (session *uiSession) set_sound_values(values Values) { +func (session *uiSession) setSoundValues(values Values) { setRange("soundVolumeScale", values.SoundVolume) setCombo("soundSinkCombo", map[string]int{"auto": 0, "pipewire": 1, "pulse": 2, "alsa": 3}[values.SoundSink]) session.setSoundTheme(values.SoundTheme) setCombo("roleSoundPresentationCombo", map[string]int{"sound_and_speech": 0, "speech_only": 1, "sound_only": 2}[values.RoleSoundPresentation]) } -func get_sound_checks(values *Values) { +func getSoundChecks(values *Values) { for _, check := range soundChecks(values) { *check.value = getCheck(check.id) } } -func (session *uiSession) get_sound_values(values *Values) error { +func (session *uiSession) getSoundValues(values *Values) error { values.SoundVolume = getRange("soundVolumeScale") sink, theme, presentation := getCombo("soundSinkCombo"), getCombo("soundThemeCombo"), getCombo("roleSoundPresentationCombo") if sink < 0 || sink > 3 || theme < 0 || theme >= len(session.soundThemes) || presentation < 0 || presentation > 2 { diff --git a/internal/preferences/speech.go b/internal/preferences/speech.go index cb99281..5de1ac2 100644 --- a/internal/preferences/speech.go +++ b/internal/preferences/speech.go @@ -57,23 +57,23 @@ func (session *uiSession) setSpeechVoice(values Values) { } } setCombo("hardwareBaudCombo", baudIndex) - C.prefs_hardware_sensitivity(C.int(session.activeSpeechSystem)) session.populateSpeechModules(values) - session.load_voice_editor() + session.updateHardwareSensitivity() + session.loadVoiceEditor() } var hardwareBaudRates = []int{1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200} func (session *uiSession) populateSpeechModules(values Values) { if session.activeSpeechSystem == 1 { - session.speechModules = []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} + session.speechModules = []string{"litetalk", "doubletalk", "tripletalk", "dectalk", "dectalk-usb"} selected := 0 for index, module := range session.speechModules { if module == values.SpeechOutputModule { selected = index } } - comboItems("speechServers", []string{"LiteTalk", "DoubleTalk", "TripleTalk", "DECtalk"}, selected) + comboItems("speechServers", []string{"LiteTalk", "DoubleTalk", "TripleTalk", "DECtalk", "DECtalk USB"}, selected) session.activeSpeechModule = session.speechModules[selected] comboItems("speechLanguages", []string{"Default"}, 0) comboItems("speechFamilies", []string{"Default"}, 0) @@ -143,7 +143,7 @@ func (session *uiSession) populateSpeechFamilies(module, language string, select index := 0 voices := session.catalog[module] if language == "" { - voices = session.default_voices(module) + voices = session.defaultVoices(module) } for _, voice := range voices { if language != "" && !strings.EqualFold(voice.Language, language) { @@ -165,6 +165,14 @@ func (session *uiSession) populateSpeechFamilies(module, language string, select comboItems("speechFamilies", labels, index) } +// updateHardwareSensitivity enables the serial device and baud rate only for +// hardware synthesizers that use them; DECtalk USB finds its own device. +func (session *uiSession) updateHardwareSensitivity() { + hardware := session.activeSpeechSystem == 1 + serial := !hardware || session.selectedSpeechModule() != "dectalk-usb" + C.prefs_hardware_sensitivity(C.int(session.activeSpeechSystem), boolean(serial)) +} + func (session *uiSession) selectedSpeechModule() string { i := getCombo("speechServers") if i >= 0 && i < len(session.speechModules) { @@ -190,7 +198,7 @@ func (session *uiSession) selectedSpeechFamily() *config.VoiceFamily { func (session *uiSession) refreshSpeechVoices() { voiceType := getCombo("voiceTypesCombo") if voiceType >= 0 && voiceType < len(session.voiceDrafts) && voiceType != session.activeVoiceType { - voice, err := session.read_voice_editor() + voice, err := session.readVoiceEditor() if err != nil { status(err.Error(), true) setCombo("voiceTypesCombo", session.activeVoiceType) @@ -198,12 +206,12 @@ func (session *uiSession) refreshSpeechVoices() { } session.voiceDrafts[session.activeVoiceType] = voice session.activeVoiceType = voiceType - session.load_voice_editor() + session.loadVoiceEditor() return } system := getCombo("speechSystems") if system != session.activeSpeechSystem { - if voice, err := session.read_voice_editor(); err == nil { + if voice, err := session.readVoiceEditor(); err == nil { session.voiceDrafts[session.activeVoiceType] = voice } if session.activeSpeechSystem == 0 { @@ -217,21 +225,22 @@ func (session *uiSession) refreshSpeechVoices() { module = session.hardwareModule } session.populateSpeechModules(Values{SpeechOutputModule: module}) - C.prefs_hardware_sensitivity(C.int(system)) + session.updateHardwareSensitivity() if system == 0 { - session.reconcile_voice_families(session.selectedSpeechModule()) + session.reconcileVoiceFamilies(session.selectedSpeechModule()) } - session.load_voice_editor() + session.loadVoiceEditor() } if system == 1 { + session.updateHardwareSensitivity() return } module := session.selectedSpeechModule() if module != session.activeSpeechModule { - if voice, err := session.read_voice_editor(); err == nil { + if voice, err := session.readVoiceEditor(); err == nil { session.voiceDrafts[session.activeVoiceType] = voice } - session.reconcile_voice_families(module) + session.reconcileVoiceFamilies(module) session.populateSpeechLanguages(module, session.activeSpeechLanguage, session.voiceDrafts[session.activeVoiceType].Family) return } @@ -245,7 +254,7 @@ func (session *uiSession) refreshSpeechVoices() { } } -func (session *uiSession) reconcile_voice_families(module string) { +func (session *uiSession) reconcileVoiceFamilies(module string) { for index, voice := range session.voiceDrafts { family := voice.Family if family == nil { @@ -273,7 +282,7 @@ func (session *uiSession) reconcile_voice_families(module string) { } } -func set_speech_support(values Values) { +func setSpeechSupport(values Values) { setCheck("interruptAllKeysRadio", values.SpeechInterruption.Mode != input.InterruptCommonKeys && values.SpeechInterruption.Mode != input.InterruptCustomKeys) setCheck("interruptCommonKeysRadio", values.SpeechInterruption.Mode == input.InterruptCommonKeys) setCheck("interruptCustomKeysRadio", values.SpeechInterruption.Mode == input.InterruptCustomKeys) @@ -294,7 +303,7 @@ func set_speech_support(values Values) { setCheck("indentationSpeechAndBeepsButton", mode == "both") } -func set_speech_numbers(values Values, inherited config.Voice, defaults speech.Settings) { +func setSpeechNumbers(values Values, inherited config.Voice, defaults speech.Settings) { for _, item := range []struct { id string value *float64 @@ -322,7 +331,7 @@ func set_speech_numbers(values Values, inherited config.Voice, defaults speech.S } } -func set_speech_presentation(values Values) { +func setSpeechPresentation(values Values) { setChoice("punctuation", values.Punctuation) setCheck("raisePitchForCapitals", values.RaisePitchForCapitals) setCheck("beepForCapitals", values.BeepForCapitals) @@ -330,7 +339,7 @@ func set_speech_presentation(values Values) { setReading(values) } -func get_speech_support(values *Values) { +func getSpeechSupport(values *Values) { values.SpeechInterruption.Mode = input.InterruptAllKeys if getCheck("interruptCommonKeysRadio") { values.SpeechInterruption.Mode = input.InterruptCommonKeys @@ -359,8 +368,8 @@ func get_speech_support(values *Values) { } } -func (session *uiSession) get_speech_values(values *Values) error { - voice, err := session.read_voice_editor() +func (session *uiSession) getSpeechValues(values *Values) error { + voice, err := session.readVoiceEditor() if err != nil { return err } @@ -392,7 +401,7 @@ func (session *uiSession) get_speech_values(values *Values) error { return nil } -func (session *uiSession) load_voice_editor() { +func (session *uiSession) loadVoiceEditor() { voice := session.voiceDrafts[session.activeVoiceType] settings := config.Settings{RaisePitchForCapitals: true, DefaultVoice: session.voiceDrafts[0], UppercaseVoice: session.voiceDrafts[1], HyperlinkVoice: session.voiceDrafts[2], SystemVoice: session.voiceDrafts[3]} kind := []string{"default", "uppercase", "hyperlink", "system"}[session.activeVoiceType] @@ -400,13 +409,13 @@ func (session *uiSession) load_voice_editor() { if session.activeSpeechSystem == 1 { defaults = speech.Settings{} } - set_speech_numbers(Values{Rate: voice.Rate, Pitch: voice.AveragePitch, Volume: voice.Gain}, config.EffectiveVoice(settings, kind), defaults) + setSpeechNumbers(Values{Rate: voice.Rate, Pitch: voice.AveragePitch, Volume: voice.Gain}, config.EffectiveVoice(settings, kind), defaults) if session.activeSpeechSystem != 1 { session.populateSpeechLanguages(session.selectedSpeechModule(), "", voice.Family) } } -func (session *uiSession) read_voice_editor() (config.Voice, error) { +func (session *uiSession) readVoiceEditor() (config.Voice, error) { voice := session.voiceDrafts[session.activeVoiceType] for _, item := range []struct { id string diff --git a/internal/preferences/tentacles.go b/internal/preferences/tentacles.go index 30a4a1a..c23267d 100644 --- a/internal/preferences/tentacles.go +++ b/internal/preferences/tentacles.go @@ -30,7 +30,7 @@ type tentaclePage struct { selectedKey string } -func tentacle_rows(snapshot *tentacle.Snapshot, origin string) []tentacleRow { +func tentacleRows(snapshot *tentacle.Snapshot, origin string) []tentacleRow { if snapshot == nil { return nil } @@ -99,7 +99,7 @@ func (page *tentaclePage) controls() { } func (page *tentaclePage) render() { - page.rows = tentacle_rows(page.snapshot, page.origin()) + page.rows = tentacleRows(page.snapshot, page.origin()) C.prefs_tentacles_clear() selectedRow := -1 for index, row := range page.rows { diff --git a/internal/preferences/tentacles_test.go b/internal/preferences/tentacles_test.go index 909db52..9cb1359 100644 --- a/internal/preferences/tentacles_test.go +++ b/internal/preferences/tentacles_test.go @@ -17,24 +17,24 @@ func TestTentacleRepositoryViewsAndRemovedSource(t *testing.T) { {URL: second, ID: "example.second", Tentacles: []tentacle.Manifest{{ID: "echo"}}}, }, } - all := tentacle_rows(snapshot, "") + all := tentacleRows(snapshot, "") if len(all) != 4 || !all[0].installed || !all[0].status.Entry.Enabled || all[2].installed || all[0].key == all[3].key { t.Fatalf("All view: %+v", all) } - filtered := tentacle_rows(snapshot, first) + filtered := tentacleRows(snapshot, first) if len(filtered) != 2 || filtered[0].status.Entry.ID != "installed" || filtered[1].status.Entry.ID != "other" { t.Fatalf("repository view: %+v", filtered) } snapshot.Repositories[0].ID = "example.replacement" - if replacement := tentacle_rows(snapshot, first); len(replacement) != 2 || replacement[0].installed { + if replacement := tentacleRows(snapshot, first); len(replacement) != 2 || replacement[0].installed { t.Fatalf("replacement source claimed old installation: %+v", replacement) } snapshot.Repositories = snapshot.Repositories[1:] - remaining := tentacle_rows(snapshot, "") + remaining := tentacleRows(snapshot, "") if len(remaining) != 3 || remaining[0].status.Entry.ID != "installed" { t.Fatalf("removed source lost installed entry: %+v", remaining) } - if rows := tentacle_rows(nil, ""); len(rows) != 0 { + if rows := tentacleRows(nil, ""); len(rows) != 0 { t.Fatal(rows) } } diff --git a/internal/preferences/ui.go b/internal/preferences/ui.go index 2e27849..d70971c 100644 --- a/internal/preferences/ui.go +++ b/internal/preferences/ui.go @@ -37,7 +37,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { defer cancel() updates := make(chan Response, 1) errorsIn := make(chan error, 1) - go read_responses(ctx, input, updates, errorsIn) + go readResponses(ctx, input, updates, errorsIn) var initial Response select { case initial = <-updates: @@ -47,7 +47,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { return ctx.Err() } if initial.ChooseApplication { - response, chosen, err := choose_application(ctx, updates, errorsIn, output) + response, chosen, err := chooseApplication(ctx, updates, errorsIn, output) if err != nil || !chosen { return err } @@ -70,7 +70,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { C.prefs_profiles_init() } session.setValues(initial.Values) - if err := session.set_extension_pages(initial.ExtensionPages); err != nil { + if err := session.setExtensionPages(initial.ExtensionPages); err != nil { return err } tentacles := &tentaclePage{} @@ -96,7 +96,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { return err case response := <-updates: if response.ExtensionsOnly { - if err := session.set_extension_pages(response.ExtensionPages); err != nil { + if err := session.setExtensionPages(response.ExtensionPages); err != nil { return err } continue @@ -141,7 +141,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { busy, canSave = false, response.CanSave if response.Accepted { session.setValues(response.Values) - if err := session.set_extension_pages(response.ExtensionPages); err != nil { + if err := session.setExtensionPages(response.ExtensionPages); err != nil { return err } C.prefs_voice_changed() @@ -151,7 +151,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { status(response.Message, !response.Accepted) case <-ticker.C: C.prefs_iterate() - profileActive := session.profile_tick() + profileActive := session.profileTick() if session.profilePreview != nil && !previewPending && !busy { if err := encoder.Encode(Request{Values: *session.profilePreview, Preview: true}); err != nil { return err @@ -167,7 +167,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { session.refreshKeyBindingLayout() action := C.prefs_action() if action >= 30 && action <= 33 && !busy && session.wineEditable { - session.profile_action(int(action)) + session.profileAction(int(action)) continue } if action >= C.PREFS_TENTACLE_REPOSITORY_ADD && action <= C.PREFS_TENTACLE_UPDATE && !busy { @@ -219,7 +219,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error { status(err.Error(), true) continue } - drafts, err := session.extension_drafts() + drafts, err := session.extensionDrafts() if err != nil { status(err.Error(), true) continue diff --git a/internal/preferences/ui_values.go b/internal/preferences/ui_values.go index c9fed5b..e1adebb 100644 --- a/internal/preferences/ui_values.go +++ b/internal/preferences/ui_values.go @@ -6,7 +6,7 @@ package preferences func (session *uiSession) setValues(values Values) { session.profiles = values.VoiceProfiles.Clone() - session.populate_profiles(0) + session.populateProfiles(0) // The Wine page exists only in global preferences. Application // preferences retain the values their base carries and submit them // unchanged, so they are never a Wine editing surface. @@ -17,15 +17,15 @@ func (session *uiSession) setValues(values Values) { setPronunciations(values.Pronunciations) setTextAttributes(values.TextAttributes) setOCRValues(values.OCR) - session.set_general_values(values) - set_sound_checks(values) - set_speech_support(values) - session.set_braille_values(values) - session.set_sound_values(values) + session.setGeneralValues(values) + setSoundChecks(values) + setSpeechSupport(values) + session.setBrailleValues(values) + session.setSoundValues(values) session.setEchoVoice(values) session.setSpeechVoice(values) - set_echo_checks(values) - set_speech_presentation(values) + setEchoChecks(values) + setSpeechPresentation(values) } func (session *uiSession) getValues() (Values, error) { @@ -44,20 +44,20 @@ func (session *uiSession) getValues() (Values, error) { } values.TextAttributes = getTextAttributes() values.OCR = getOCRValues() - if err := session.get_general_values(&values); err != nil { + if err := session.getGeneralValues(&values); err != nil { return values, err } - get_sound_checks(&values) - get_speech_support(&values) - if err := session.get_braille_values(&values); err != nil { + getSoundChecks(&values) + getSpeechSupport(&values) + if err := session.getBrailleValues(&values); err != nil { return values, err } - if err := session.get_sound_values(&values); err != nil { + if err := session.getSoundValues(&values); err != nil { return values, err } - get_echo_checks(&values) + getEchoChecks(&values) getReading(&values) - if err := session.get_speech_values(&values); err != nil { + if err := session.getSpeechValues(&values); err != nil { return values, err } return values, nil diff --git a/internal/preferences/voice_profiles.go b/internal/preferences/voice_profiles.go index 332f1ed..36513c6 100644 --- a/internal/preferences/voice_profiles.go +++ b/internal/preferences/voice_profiles.go @@ -16,7 +16,7 @@ import ( "unsafe" ) -func (session *uiSession) populate_profiles(index int) { +func (session *uiSession) populateProfiles(index int) { if !session.wineEditable { return } @@ -29,11 +29,11 @@ func (session *uiSession) populate_profiles(index int) { C.prefs_profiles_select(C.int(index), C.int(len(session.profiles.Profiles))) } -func (session *uiSession) profile_action(action int) { +func (session *uiSession) profileAction(action int) { index := int(C.prefs_profiles_selected()) if action == 32 { session.profiles = session.profiles.Remove(index) - session.populate_profiles(index) + session.populateProfiles(index) return } if action == 33 { @@ -45,15 +45,15 @@ func (session *uiSession) profile_action(action int) { status(err.Error(), true) return } - settings := primary_settings(values) - next, err := config.Apply_primary_voice(settings, session.profiles.Profiles[index]) + settings := primarySettings(values) + next, err := config.ApplyPrimaryVoice(settings, session.profiles.Profiles[index]) if err != nil { status(err.Error(), true) return } session.activeVoiceType = 0 session.setSpeechVoice(FromSettings(next)) - preview := profile_preview_values(values, next) + preview := profilePreviewValues(values, next) session.profilePreview = &preview return } @@ -62,8 +62,8 @@ func (session *uiSession) profile_action(action int) { status(err.Error(), true) return } - settings := primary_settings(values) - p := config.Primary_voice(settings) + settings := primarySettings(values) + p := config.PrimaryVoice(settings) p.Name = "" if p.Device == "" { p.Device = "/dev/ttyUSB0" @@ -79,13 +79,7 @@ func (session *uiSession) profile_action(action int) { } else { index = -1 } - drivers := []voiceprofiles.Driver{} - for _, d := range voiceprofiles.Drivers() { - if d.ID != "dectalk-usb" { - drivers = append(drivers, d) - } - } - session.profileEditor = voiceprofiles.New_editor(p, drivers, session.catalog) + session.profileEditor = voiceprofiles.NewEditor(p, voiceprofiles.Drivers(), session.catalog) session.profileBase = values session.profileVoice = nil session.profileIndex = index @@ -96,12 +90,12 @@ func (session *uiSession) profile_action(action int) { C.prefs_profile_control(id, label, C.int(c.Kind), C.int(row), C.int(c.MaxLength), C.double(c.Min), C.double(c.Max), C.double(c.Step)) C.free(unsafe.Pointer(id)) C.free(unsafe.Pointer(label)) - set_profile_control(c) + setProfileControl(c) } C.prefs_profile_show() } -func set_profile_control(c ui.Control) { +func setProfileControl(c ui.Control) { id, text := C.CString(c.ID), C.CString(c.Text) defer C.free(unsafe.Pointer(id)) defer C.free(unsafe.Pointer(text)) @@ -116,15 +110,15 @@ func set_profile_control(c ui.Control) { C.prefs_profile_set(id, C.int(c.Kind), text, C.double(c.Number), C.int(c.Selected), boolean(c.Hidden)) } -// set_profile_state updates a combo's selection and visibility in place. -func set_profile_state(c ui.Control) { +// setProfileState updates a combo's selection and visibility in place. +func setProfileState(c ui.Control) { id, text := C.CString(c.ID), C.CString(c.Text) defer C.free(unsafe.Pointer(id)) defer C.free(unsafe.Pointer(text)) C.prefs_profile_set(id, C.int(c.Kind), text, C.double(c.Number), C.int(c.Selected), boolean(c.Hidden)) } -func same_choices(a, b []ui.Choice) bool { +func sameChoices(a, b []ui.Choice) bool { if len(a) != len(b) { return false } @@ -136,7 +130,7 @@ func same_choices(a, b []ui.Choice) bool { return true } -func (session *uiSession) profile_tick() bool { +func (session *uiSession) profileTick() bool { if session.profileEditor == nil { return false } @@ -161,10 +155,10 @@ func (session *uiSession) profile_tick() bool { } // Rebuilding the combo the user is changing moves GTK focus out of // it. Like the main speech page, refill only lists that changed. - if old := values[voiceprofiles.PageID+"."+c.ID]; c.Kind != ui.ComboBox || !same_choices(old.Choices, c.Choices) { - set_profile_control(c) + if old := values[voiceprofiles.PageID+"."+c.ID]; c.Kind != ui.ComboBox || !sameChoices(old.Choices, c.Choices) { + setProfileControl(c) } else if old.Selected != c.Selected || old.Hidden != c.Hidden { - set_profile_state(c) + setProfileState(c) } values[voiceprofiles.PageID+"."+c.ID] = c for index, old := range session.profileControls { @@ -174,7 +168,7 @@ func (session *uiSession) profile_tick() bool { } } } - session.preview_profile(values) + session.previewProfile(values) response := int(C.prefs_profile_response()) if response == 0 { return true @@ -200,27 +194,27 @@ func (session *uiSession) profile_tick() bool { // Both Save and Cancel return to the unchanged parent speech draft. preview := session.profileBase session.profilePreview = &preview - session.populate_profiles(max(0, session.profileIndex)) + session.populateProfiles(max(0, session.profileIndex)) return true } -func (session *uiSession) preview_profile(values map[string]ui.Control) { +func (session *uiSession) previewProfile(values map[string]ui.Control) { profile, err := session.profileEditor.Read(values) - if err != nil || session.profileVoice != nil && voiceprofiles.Same_voice(*session.profileVoice, profile) { + if err != nil || session.profileVoice != nil && voiceprofiles.SameVoice(*session.profileVoice, profile) { return } - next, err := config.Apply_primary_voice(primary_settings(session.profileBase), profile) + next, err := config.ApplyPrimaryVoice(primarySettings(session.profileBase), profile) if err != nil { return // Incomplete or unsupported edits retain the working voice. } - preview := profile_preview_values(session.profileBase, next) + preview := profilePreviewValues(session.profileBase, next) session.profileVoice = &profile session.profilePreview = &preview } // Profile previews change only primary speech. The parent form and its other // voice drafts remain intact and are restored when the child editor closes. -func profile_preview_values(base Values, settings config.Settings) Values { +func profilePreviewValues(base Values, settings config.Settings) Values { voice := FromSettings(settings) base.Rate, base.Pitch, base.Volume = voice.Rate, voice.Pitch, voice.Volume base.SpeechServerFactory = voice.SpeechServerFactory @@ -232,7 +226,7 @@ func profile_preview_values(base Values, settings config.Settings) Values { return base } -func primary_settings(values Values) config.Settings { +func primarySettings(values Values) config.Settings { settings := config.DefaultSettings() settings.SpeechServerFactory = values.SpeechServerFactory settings.SpeechOutputModule = values.SpeechOutputModule diff --git a/internal/presentation/control_values_test.go b/internal/presentation/control_values_test.go index 91a17ee..8e51ead 100644 --- a/internal/presentation/control_values_test.go +++ b/internal/presentation/control_values_test.go @@ -196,7 +196,7 @@ func TestSliderFocusUsesCurrentValueInsteadOfStaleText(t *testing.T) { t.Fatalf("focus speech = %q", got) } options := DefaultOptions() - reading := reading_options(options) + reading := readingOptions(options) reading.OnlySpeakDisplayedText = true options.Reading = &reading want := tc.want diff --git a/internal/presentation/document_line.go b/internal/presentation/document_line.go index 11220a4..137d370 100644 --- a/internal/presentation/document_line.go +++ b/internal/presentation/document_line.go @@ -19,7 +19,7 @@ func DocumentLineTextWithOptions(line atspi.DocumentLine, options Options) strin } func DocumentLineSpeechWithOptions(line atspi.DocumentLine, options Options) Speech { - reading := reading_options(options) + reading := readingOptions(options) var parts []string seen := make(map[atspi.ObjectID]bool) type rowKey struct { diff --git a/internal/presentation/libreoffice.go b/internal/presentation/libreoffice.go index dcbb68d..e2da7b3 100644 --- a/internal/presentation/libreoffice.go +++ b/internal/presentation/libreoffice.go @@ -40,7 +40,7 @@ func libreOfficeFocusSnapshot(snapshot atspi.Snapshot, options Options) atspi.Sn // and insensitive-state chatter; these bits are not cell availability. snapshot.Multiselectable = false snapshot.SensitiveKnown = false - if reading_options(options).OnlySpeakDisplayedText { + if readingOptions(options).OnlySpeakDisplayedText { snapshot.Text = "" return snapshot } diff --git a/internal/presentation/presentation.go b/internal/presentation/presentation.go index 1890f94..c24570a 100644 --- a/internal/presentation/presentation.go +++ b/internal/presentation/presentation.go @@ -84,7 +84,7 @@ func FocusSpeechWithOptions(snapshot atspi.Snapshot, options Options) Speech { if snapshot.Role == "slider" && controlValue(snapshot) != "" { snapshot.Text = "" } - reading := reading_options(options) + reading := readingOptions(options) var parts []string role := snapshot.ControlRole() if role == "entry" && snapshot.Autocomplete { @@ -106,7 +106,7 @@ func FocusSpeechWithOptions(snapshot atspi.Snapshot, options Options) Speech { } } if reading.OnlySpeakDisplayedText { - return SpeechWithOptions([]string{displayed_focus_text(snapshot)}, options) + return SpeechWithOptions([]string{displayedFocusText(snapshot)}, options) } if role == "table" && snapshot.TableRowCount > 0 && snapshot.TableColumnCount > 0 { if options.SpeechVerbosityLevel == 0 { @@ -171,7 +171,7 @@ func FocusSpeechWithOptions(snapshot atspi.Snapshot, options Options) Speech { fields = append(fields, spokenMnemonic(snapshot.Mnemonic)) } if reading.EnableTutorialMessages { - fields = append(fields, control_tutorial(snapshot)) + fields = append(fields, controlTutorial(snapshot)) } if reading.SpeakMisspelledIndicator && snapshot.Misspelled { fields = append(fields, "misspelled") @@ -285,7 +285,7 @@ func EventSpeechWithOptions(event atspi.Event, options Options) Speech { "object:state-changed:required", "object:state-changed:selected", "object:state-changed:sensitive": - if reading_options(options).OnlySpeakDisplayedText { + if readingOptions(options).OnlySpeakDisplayedText { return Speech{} } text := stateChangeText(event.Source, event.Type) diff --git a/internal/presentation/reading.go b/internal/presentation/reading.go index 893769a..5a30d54 100644 --- a/internal/presentation/reading.go +++ b/internal/presentation/reading.go @@ -12,19 +12,19 @@ import ( "git.stormux.org/storm/cthulhu/internal/config" ) -func reading_options(options Options) config.ReadingSettings { +func readingOptions(options Options) config.ReadingSettings { if options.Reading != nil { return *options.Reading } return config.DefaultSettings().Reading } -func join_speech_parts(parts []string, options Options) string { - if !reading_options(options).EnablePauseBreaks { +func joinSpeechParts(parts []string, options Options) string { + if !readingOptions(options).EnablePauseBreaks { return strings.Join(parts, " ") } return strings.Join(parts, ", ") } -func displayed_focus_text(snapshot atspi.Snapshot) string { +func displayedFocusText(snapshot atspi.Snapshot) string { var parts []string for _, text := range []string{snapshot.Name, snapshot.Text, controlValue(snapshot)} { if text != "" && !contains(parts, text) { @@ -33,7 +33,7 @@ func displayed_focus_text(snapshot atspi.Snapshot) string { } return strings.Join(parts, " ") } -func control_tutorial(snapshot atspi.Snapshot) string { +func controlTutorial(snapshot atspi.Snapshot) string { switch snapshot.Role { case "push button", "button": return "Press Space to activate." @@ -56,7 +56,7 @@ func control_tutorial(snapshot atspi.Snapshot) string { } func FullRowEnabled(snapshot atspi.Snapshot, options Options) bool { - reading := reading_options(options) + reading := readingOptions(options) if snapshot.Spreadsheet { return reading.ReadFullRowInSpreadSheet } diff --git a/internal/presentation/sound_cues.go b/internal/presentation/sound_cues.go index 6e09762..66b8fd8 100644 --- a/internal/presentation/sound_cues.go +++ b/internal/presentation/sound_cues.go @@ -83,13 +83,13 @@ func SoundCues(snapshot atspi.Snapshot, options Options) []sound.Cue { if hasStateCue { cues = append(cues, stateCue) } - if cue, ok := position_sound_cue(snapshot, options); ok { + if cue, ok := positionSoundCue(snapshot, options); ok { cues = append(cues, cue) } return cues } -func position_sound_cue(snapshot atspi.Snapshot, options Options) (sound.Cue, bool) { +func positionSoundCue(snapshot atspi.Snapshot, options Options) (sound.Cue, bool) { if !options.EnableSound || !options.PlaySoundForPositionInSet || options.RoleSoundPresentation == "speech_only" || snapshot.Defunct || snapshot.SetSize <= 1 || snapshot.PositionInSet < 1 || snapshot.PositionInSet > snapshot.SetSize { return sound.Cue{}, false diff --git a/internal/presentation/speech.go b/internal/presentation/speech.go index 114c1c2..0e3db0d 100644 --- a/internal/presentation/speech.go +++ b/internal/presentation/speech.go @@ -19,8 +19,8 @@ func SpeechWithOptions(parts []string, options Options) Speech { } } parts = nonempty - result := Speech{Text: join_speech_parts(parts, options)} - if reading_options(options).EnablePauseBreaks { + result := Speech{Text: joinSpeechParts(parts, options)} + if readingOptions(options).EnablePauseBreaks { result.Chunks = parts } return result diff --git a/internal/remote/registrations.go b/internal/remote/registrations.go index d0af0ed..b6788ef 100644 --- a/internal/remote/registrations.go +++ b/internal/remote/registrations.go @@ -7,9 +7,9 @@ package remote import "github.com/godbus/dbus/v5/introspect" -// service_bindings builds exports in their existing registration order. Start +// serviceBindings builds exports in their existing registration order. Start // performs exports and rollback; Stop reverses this list before releasing names. -func service_bindings(endpoint *endpoint, orca bool, handler Handler) []serviceBinding { +func serviceBindings(endpoint *endpoint, orca bool, handler Handler) []serviceBinding { path, iface := ObjectPath, InterfaceName if orca { path, iface = OrcaObjectPath, OrcaInterfaceName diff --git a/internal/remote/service.go b/internal/remote/service.go index b0197c1..434468e 100644 --- a/internal/remote/service.go +++ b/internal/remote/service.go @@ -180,7 +180,7 @@ func (service *Service) Start(ctx context.Context) error { if service.orca { name = OrcaBusName } - registrations := service_bindings(endpoint, service.orca, service.handler) + registrations := serviceBindings(endpoint, service.orca, service.handler) started := false exported := 0 defer func() { diff --git a/internal/review/current_line.go b/internal/review/current_line.go index 12ac557..5804484 100644 --- a/internal/review/current_line.go +++ b/internal/review/current_line.go @@ -24,7 +24,7 @@ func (worker *Worker) ReadCurrentLine(browse bool, style FlatSpeech) error { } } -func (worker *Worker) read_current_line(ctx context.Context, cursor *DocumentCursor, browse bool) Result { +func (worker *Worker) readCurrentLine(ctx context.Context, cursor *DocumentCursor, browse bool) Result { result := Result{CurrentLine: true, CurrentLineBrowse: browse, DocumentFocus: worker.focus()} if !result.DocumentFocus.Valid() { result.Err = ErrNoCurrent diff --git a/internal/review/current_line_test.go b/internal/review/current_line_test.go index 9e9af8f..55eb1f6 100644 --- a/internal/review/current_line_test.go +++ b/internal/review/current_line_test.go @@ -49,7 +49,7 @@ func TestCurrentLineNativeMissingContextPreservesLocalText(t *testing.T) { capturer := ¤tLineCapturer{content: atspi.DocumentContent{Text: "Local line"}} worker, _ := NewWorker(capturer, time.Second) worker.SyncFocus(webID("/entry")) - result := worker.read_current_line(t.Context(), nil, false) + result := worker.readCurrentLine(t.Context(), nil, false) if result.Err != nil || result.DocumentCaretText != "Local line" || len(result.DocumentCaretContext) != 0 { t.Fatalf("missing privacy metadata changed local reading: %+v", result) } @@ -67,7 +67,7 @@ func TestCurrentLineReadsWholeBrowseLineWithoutMoving(t *testing.T) { } } before := append([]documentPlace(nil), cursor.places...) - result := worker.read_current_line(context.Background(), cursor, true) + result := worker.readCurrentLine(context.Background(), cursor, true) if result.Err != nil || strings.TrimSpace(result.DocumentCaretText) != "Second café 猫" { t.Fatalf("whole browse line from middle: %+v", result) } @@ -81,7 +81,7 @@ func TestCurrentLineReadsWholeBrowseLineWithoutMoving(t *testing.T) { } func TestCurrentLineJoinsBrowseFragmentsWithoutMoving(t *testing.T) { - cursor, reader := fragment_cursor(t, "paragraph") + cursor, reader := fragmentCursor(t, "paragraph") if _, err := cursor.MoveCaret(context.Background(), reader, CaretNextWord); err != nil { t.Fatal(err) } @@ -91,7 +91,7 @@ func TestCurrentLineJoinsBrowseFragmentsWithoutMoving(t *testing.T) { worker, _ := NewWorker(source, time.Second) worker.SyncFocus(webID("/one")) before := append([]documentPlace(nil), cursor.places...) - result := worker.read_current_line(context.Background(), cursor, true) + result := worker.readCurrentLine(context.Background(), cursor, true) if result.Err != nil || result.DocumentCaretText != "One two." || !reflect.DeepEqual(cursor.places, before) { t.Fatalf("fragmented current line: %+v", result) } @@ -115,7 +115,7 @@ func TestCurrentLineReadsBrowseControlLabel(t *testing.T) { } worker, _ := NewWorker(&readAllCapturer{tree: tree, caretTextReader: caretTextReader{}}, time.Second) worker.SyncFocus(button.ID()) - result := worker.read_current_line(context.Background(), cursor, true) + result := worker.readCurrentLine(context.Background(), cursor, true) if result.Err != nil || result.DocumentCaretText != "Example button" { t.Fatalf("browse control label: %+v", result) } @@ -129,7 +129,7 @@ func TestCurrentLineUsesRecapturedSourceContext(t *testing.T) { invalidateTree: cursor.tree, staleAt: 2} worker, _ := NewWorker(capturer, time.Second) worker.SyncFocus(webID("/text")) - result := worker.read_current_line(t.Context(), cursor, true) + result := worker.readCurrentLine(t.Context(), cursor, true) if result.Err != nil || strings.TrimSpace(result.DocumentCaretText) != "First" || capturer.index != 1 { t.Fatalf("current line did not recover capture: %+v", result) } @@ -155,7 +155,7 @@ func TestCurrentLinePreservesLocalTextWithStaleContext(t *testing.T) { capturer := ¤tLineStaleContextCapturer{&readAllCapturer{caretTextReader: text, tree: cursor.tree}} worker, _ := NewWorker(capturer, time.Second) worker.SyncFocus(webID("/text")) - result := worker.read_current_line(t.Context(), cursor, true) + result := worker.readCurrentLine(t.Context(), cursor, true) if result.Err != nil || result.DocumentCaretText != "Local line" || len(result.DocumentCaretContext) != 0 { t.Fatalf("stale ancestry must leave local reading available without export metadata: %+v", result) } diff --git a/internal/review/document.go b/internal/review/document.go index be37c1c..a00fdc7 100644 --- a/internal/review/document.go +++ b/internal/review/document.go @@ -119,10 +119,10 @@ func (cursor *DocumentCursor) rebindPlace(tree *atspi.AccessibleTree, oldPositio cursor.active = newPosition.Document } -// capture_anchor returns the saved document identity for a recapture when +// captureAnchor returns the saved document identity for a recapture when // the page destroyed the focused anchor itself. The anchor only locates the // document to capture; position recovery still runs against the fresh tree. -func (cursor *DocumentCursor) capture_anchor(focus atspi.ObjectID) (atspi.ObjectID, bool) { +func (cursor *DocumentCursor) captureAnchor(focus atspi.ObjectID) (atspi.ObjectID, bool) { if cursor == nil { return atspi.ObjectID{}, false } @@ -207,13 +207,13 @@ func (cursor *DocumentCursor) ActivationTarget() (atspi.ObjectReference, error) } func (cursor *DocumentCursor) SyncFocus(ctx context.Context, focus atspi.ObjectID) (DocumentPosition, error) { - position, _, err := cursor.sync_focus(ctx, focus) + position, _, err := cursor.syncFocus(ctx, focus) return position, err } // The outcome explains whether focus synchronization retained the reading // position, recovered a replacement text child, or fell back to native focus. -func (cursor *DocumentCursor) sync_focus(ctx context.Context, focus atspi.ObjectID) (DocumentPosition, string, error) { +func (cursor *DocumentCursor) syncFocus(ctx context.Context, focus atspi.ObjectID) (DocumentPosition, string, error) { cursor.mu.Lock() defer cursor.mu.Unlock() // Failed ownership resolution must never leave web navigation active for @@ -244,12 +244,12 @@ func (cursor *DocumentCursor) sync_focus(ctx context.Context, focus atspi.Object recovery = "preserved" place = saved place.focus = ref - } else if replacement, kind, ok := replacement_text_node(doc, saved); ok { + } else if replacement, kind, ok := replacementTextNode(doc, saved); ok { recovery = kind place = saved place.focus, place.object = ref, replacement.Reference place.offset = min(saved.offset, max(0, replacement.Snapshot.CharacterCount-1)) - } else if replacement, kind, ok := replacement_child_node(doc, saved); ok { + } else if replacement, kind, ok := replacementChildNode(doc, saved); ok { recovery = kind place = saved place.focus, place.object = ref, replacement.Reference @@ -278,7 +278,7 @@ func (cursor *DocumentCursor) sync_focus(ctx context.Context, focus atspi.Object if removeIndex >= 0 { cursor.places = append(cursor.places[:removeIndex], cursor.places[removeIndex+1:]...) } - remember_text_parent(doc, &place) + rememberTextParent(doc, &place) if len(cursor.places) == 16 { cursor.places = cursor.places[1:] } @@ -423,7 +423,7 @@ func (cursor *DocumentCursor) Move(ctx context.Context, target DocumentTarget, l } place.tableCell = atspi.ObjectID{} place.object, place.origin, place.offset = doc.Nodes[targetIndex].Reference, StructuralNavigation, 0 - remember_text_parent(doc, place) + rememberTextParent(doc, place) return DocumentMoveResult{Position: documentPosition(doc, *place), Moved: true, Wrapped: wrapped}, nil } step := 1 diff --git a/internal/review/document_benchmark_test.go b/internal/review/document_benchmark_test.go index 25267de..00b884e 100644 --- a/internal/review/document_benchmark_test.go +++ b/internal/review/document_benchmark_test.go @@ -19,7 +19,7 @@ import ( func BenchmarkDocumentWorkerHeadingNavigation(b *testing.B) { for _, contentNodes := range []int{100, 1000, 10000} { b.Run(fmt.Sprintf("nodes-%d", contentNodes), func(b *testing.B) { - tree, ids := benchmark_document_tree(b, contentNodes) + tree, ids := benchmarkDocumentTree(b, contentNodes) cursor, err := NewDocumentCursor(tree) if err != nil { b.Fatal(err) @@ -55,7 +55,7 @@ func BenchmarkDocumentWorkerHeadingNavigation(b *testing.B) { func BenchmarkDocumentCaretNavigation(b *testing.B) { for _, contentNodes := range []int{100, 1000, 10000} { b.Run(fmt.Sprintf("nodes-%d", contentNodes), func(b *testing.B) { - tree, ids := benchmark_document_tree(b, contentNodes) + tree, ids := benchmarkDocumentTree(b, contentNodes) cursor, err := NewDocumentCursor(tree) if err != nil { b.Fatal(err) @@ -89,10 +89,10 @@ func BenchmarkDocumentCaretNavigation(b *testing.B) { } } -// benchmark_document_tree models an already captured page, not native AT-SPI +// benchmarkDocumentTree models an already captured page, not native AT-SPI // capture. Each section has twenty content objects: a heading, a link, and // ordinary text. Pairs of objects share a visual row, including Unicode text. -func benchmark_document_tree(b *testing.B, contentNodes int) (*atspi.AccessibleTree, []atspi.ObjectID) { +func benchmarkDocumentTree(b *testing.B, contentNodes int) (*atspi.AccessibleTree, []atspi.ObjectID) { b.Helper() rootID := webID("/benchmark/document") root := atspi.NewSnapshot(rootID.Path, "Benchmark page", "document web", "", "") @@ -144,7 +144,7 @@ func benchmark_document_tree(b *testing.B, contentNodes int) (*atspi.AccessibleT func BenchmarkDocumentSnapshot(b *testing.B) { for _, contentNodes := range []int{100, 1000, 10000} { b.Run(fmt.Sprintf("nodes-%d", contentNodes), func(b *testing.B) { - tree, _ := benchmark_document_tree(b, contentNodes) + tree, _ := benchmarkDocumentTree(b, contentNodes) root, err := tree.Root() if err != nil { b.Fatal(err) @@ -166,7 +166,7 @@ func BenchmarkDocumentHeadingNavigation(b *testing.B) { for _, contentNodes := range []int{100, 1000, 10000} { for _, scenario := range []string{"adjacent", "wrap"} { b.Run(fmt.Sprintf("nodes-%d/%s", contentNodes, scenario), func(b *testing.B) { - tree, contentIDs := benchmark_document_tree(b, contentNodes) + tree, contentIDs := benchmarkDocumentTree(b, contentNodes) cursor, err := NewDocumentCursor(tree) if err != nil { b.Fatal(err) @@ -202,7 +202,7 @@ func BenchmarkDocumentHeadingNavigation(b *testing.B) { func BenchmarkDocumentLineAssembly(b *testing.B) { for _, contentNodes := range []int{100, 1000, 10000} { b.Run(fmt.Sprintf("nodes-%d", contentNodes), func(b *testing.B) { - tree, contentIDs := benchmark_document_tree(b, contentNodes) + tree, contentIDs := benchmarkDocumentTree(b, contentNodes) middle := contentNodes / 2 reference, err := tree.Reference(contentIDs[middle]) if err != nil { diff --git a/internal/review/document_braille_routing.go b/internal/review/document_braille_routing.go index e69ccc0..c4d5c67 100644 --- a/internal/review/document_braille_routing.go +++ b/internal/review/document_braille_routing.go @@ -35,7 +35,7 @@ func (worker *Worker) RouteDocumentBraille(ctx context.Context, epoch uint64, fo } } -func (worker *Worker) route_document_braille(ctx context.Context, cursor *DocumentCursor, request request) (result Result) { +func (worker *Worker) routeDocumentBraille(ctx context.Context, cursor *DocumentCursor, request request) (result Result) { route := request.brailleRoute result = Result{DocumentBrailleRoute: true, DocumentCaretCommand: CaretReadLine, DocumentFocus: route.focus, DocumentEpoch: request.documentEpoch} defer func() { route.done <- result.Err }() @@ -77,7 +77,7 @@ func (worker *Worker) route_document_braille(ctx context.Context, cursor *Docume result.Err = err return } - node, caretOffset, err := native_caret_node(ctx, reader, doc, route.target, route.offset) + node, caretOffset, err := nativeCaretNode(ctx, reader, doc, route.target, route.offset) if err != nil { result.Err = err return @@ -103,7 +103,7 @@ func (worker *Worker) route_document_braille(ctx context.Context, cursor *Docume place := &cursor.places[len(cursor.places)-1] place.object, place.offset, place.origin = node.Reference, caretOffset, CaretNavigation place.tableCell = atspi.ObjectID{} - remember_text_parent(doc, place) + rememberTextParent(doc, place) snapshot, err := cursor.tree.Resolve(node.Reference) result.DocumentPosition = DocumentPosition{Document: owner.TopLevel, Object: node.Reference, Snapshot: snapshot, Offset: caretOffset, Origin: CaretNavigation} cursor.mu.Unlock() @@ -123,9 +123,9 @@ func (worker *Worker) route_document_braille(ctx context.Context, cursor *Docume } } if position >= 0 { - parts, err := collect_visual_line(deadline, reader, doc, indices, visual_line_owners(doc.Nodes), position, caretOffset, true) + parts, err := collectVisualLine(deadline, reader, doc, indices, visualLineOwners(doc.Nodes), position, caretOffset, true) if err == nil && len(parts) > 1 { - line, _, _ := assemble_visual_line(cursor.tree, doc, parts) + line, _, _ := assembleVisualLine(cursor.tree, doc, parts) result.DocumentCaretLine = &line } } diff --git a/internal/review/document_caret.go b/internal/review/document_caret.go index cfeb0c5..f5afd68 100644 --- a/internal/review/document_caret.go +++ b/internal/review/document_caret.go @@ -115,8 +115,8 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare if !doc.SameContent(cursor.caretDocument) { cursor.caretDocument = doc cursor.caretRanges = caretNodeRanges(doc.Nodes) - cursor.caretLookup = new_caret_range_lookup(cursor.caretRanges, len(doc.Nodes)) - cursor.lineOwners = visual_line_owners(doc.Nodes) + cursor.caretLookup = newCaretRangeLookup(cursor.caretRanges, len(doc.Nodes)) + cursor.lineOwners = visualLineOwners(doc.Nodes) } indices := cursor.caretRanges if len(indices) == 0 { @@ -137,7 +137,7 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare command == CaretPreviousWord || command == CaretPreviousCharacter, command == CaretNextWord || command == CaretPreviousWord) default: - movement, err = move_caret_line(ctx, reader, cursor.tree, doc, place, indices, cursor.caretLookup, current, command, cursor.lineOwners) + movement, err = moveCaretLine(ctx, reader, cursor.tree, doc, place, indices, cursor.caretLookup, current, command, cursor.lineOwners) } if err == nil && movement.Moved { target, found := doc.Index(place.object.ID()) @@ -148,12 +148,12 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare // removes its ancestor immediately afterwards. Repeating that move // during recovery would skip the line. Synthetic whole-object stops // still need validation because they bypass the native text reader. - if !navigationReader.did_read(place.object) { + if !navigationReader.didRead(place.object) { if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, current, target); err != nil { return DocumentCaretMove{}, err } } - remember_text_parent(doc, place) + rememberTextParent(doc, place) *saved = next } else if err == nil { // Reaching a boundary must not silently skip newly readable text in a diff --git a/internal/review/document_caret_editable_test.go b/internal/review/document_caret_editable_test.go index 6623b22..b5e66ad 100644 --- a/internal/review/document_caret_editable_test.go +++ b/internal/review/document_caret_editable_test.go @@ -14,7 +14,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" ) -func editable_caret_cursor(t *testing.T) (*DocumentCursor, caretTextReader) { +func editableCaretCursor(t *testing.T) (*DocumentCursor, caretTextReader) { t.Helper() reader := caretTextReader{ webID("/before"): "Suggested wording", @@ -63,7 +63,7 @@ func editable_caret_cursor(t *testing.T) (*DocumentCursor, caretTextReader) { func TestDocumentCaretReadsEditableDescendants(t *testing.T) { ctx := context.Background() - cursor, reader := editable_caret_cursor(t) + cursor, reader := editableCaretCursor(t) for _, step := range []struct { command DocumentCaretCommand want string @@ -89,7 +89,7 @@ func TestDocumentCaretReadsEditableDescendants(t *testing.T) { } func TestReadAllIncludesEditableDescendants(t *testing.T) { - cursor, reader := editable_caret_cursor(t) + cursor, reader := editableCaretCursor(t) capturer := &readAllCapturer{tree: cursor.tree, caretTextReader: reader} worker, err := NewWorker(capturer, time.Second) if err != nil { diff --git a/internal/review/document_caret_glyph_test.go b/internal/review/document_caret_glyph_test.go index b828bfe..1cc647c 100644 --- a/internal/review/document_caret_glyph_test.go +++ b/internal/review/document_caret_glyph_test.go @@ -13,7 +13,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" ) -func glyph_cursor(t *testing.T, parentRole string, modify func(*atspi.Snapshot)) (*DocumentCursor, caretTextReader) { +func glyphCursor(t *testing.T, parentRole string, modify func(*atspi.Snapshot)) (*DocumentCursor, caretTextReader) { t.Helper() reader := caretTextReader{webID("/before"): "Member", webID("/icon"): "\uf005", webID("/after"): "Join Date"} node := func(path, role string, children ...string) atspi.TreeNode { @@ -57,7 +57,7 @@ func TestDocumentCaretSkipsDecorativeGlyph(t *testing.T) { ctx := context.Background() for _, command := range []DocumentCaretCommand{CaretNextLine, CaretNextCharacter, CaretNextWord} { t.Run(command.String(), func(t *testing.T) { - cursor, reader := glyph_cursor(t, "section", nil) + cursor, reader := glyphCursor(t, "section", nil) if command != CaretNextLine { cursor.places[0].offset = len("Member") - 1 } @@ -74,7 +74,7 @@ func TestDocumentCaretSkipsDecorativeGlyph(t *testing.T) { // Focus/routing may leave the cursor on an omitted icon. Both directions // must still reach surrounding text rather than report a stale position. for _, command := range []DocumentCaretCommand{CaretNextLine, CaretPreviousLine} { - cursor, reader := glyph_cursor(t, "section", nil) + cursor, reader := glyphCursor(t, "section", nil) if _, err := cursor.SyncFocus(ctx, webID("/icon")); err != nil { t.Fatal(err) } @@ -108,7 +108,7 @@ func TestDocumentCaretPreservesMeaningfulGlyphs(t *testing.T) { {"different text", "section", func(s *atspi.Snapshot) { s.Text = "X" }}, } { t.Run(test.name, func(t *testing.T) { - cursor, reader := glyph_cursor(t, test.parentRole, test.modify) + cursor, reader := glyphCursor(t, test.parentRole, test.modify) move, err := cursor.MoveCaret(context.Background(), reader, CaretNextLine) if err != nil || !move.Moved || move.Position.Object.ID() != webID("/icon") { t.Fatalf("meaningful glyph omitted: %+v, %v", move, err) @@ -118,7 +118,7 @@ func TestDocumentCaretPreservesMeaningfulGlyphs(t *testing.T) { } func TestReadAllSkipsDecorativeGlyph(t *testing.T) { - cursor, reader := glyph_cursor(t, "section", nil) + cursor, reader := glyphCursor(t, "section", nil) capturer := &readAllCapturer{tree: cursor.tree, caretTextReader: reader} worker, err := NewWorker(capturer, time.Second) if err != nil { diff --git a/internal/review/document_caret_line.go b/internal/review/document_caret_line.go index 4233b7a..b8a33e4 100644 --- a/internal/review/document_caret_line.go +++ b/internal/review/document_caret_line.go @@ -13,9 +13,9 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" ) -// move_caret_line handles line and document boundaries under the cursor lock +// moveCaretLine handles line and document boundaries under the cursor lock // held by MoveCaret. Text-unit movement has its separate traversal helper. -func move_caret_object_line(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, place *documentPlace, indices []caretRange, lookup *caretRangeLookup, current int, command DocumentCaretCommand) (DocumentCaretMove, error) { +func moveCaretObjectLine(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, place *documentPlace, indices []caretRange, lookup *caretRangeLookup, current int, command DocumentCaretCommand) (DocumentCaretMove, error) { unit := atspi.DocumentCaretLine if command == CaretReadLine { unit = atspi.DocumentCaretLineRemainder @@ -64,12 +64,12 @@ func move_caret_object_line(ctx context.Context, reader DocumentCaretReader, doc continue } node := doc.Nodes[indices[position].index] - if named_link_label(node.Snapshot) != "" && (command == CaretLineStart || command == CaretLineEnd) { + if namedLinkLabel(node.Snapshot) != "" && (command == CaretLineStart || command == CaretLineEnd) { offset = 0 if command == CaretLineEnd { - offset = caret_text_count(node.Snapshot) - 1 + offset = caretTextCount(node.Snapshot) - 1 } - character, err := read_caret_text(ctx, reader, node, offset, atspi.DocumentCaretCharacter) + character, err := readCaretText(ctx, reader, node, offset, atspi.DocumentCaretCharacter) if err != nil { return DocumentCaretMove{}, err } diff --git a/internal/review/document_caret_nodes.go b/internal/review/document_caret_nodes.go index 7b0f7f0..fe98d92 100644 --- a/internal/review/document_caret_nodes.go +++ b/internal/review/document_caret_nodes.go @@ -42,13 +42,13 @@ func wholeCaretControl(snapshot atspi.Snapshot) bool { // caret placement moves focus away. Entering their text can strand navigation // on a removed object and repeatedly recover to the owner's container. Match // Orca's web caret policy while retaining focusable/editable tooltip content. -func passive_caret_tooltip(snapshot atspi.Snapshot) bool { +func passiveCaretTooltip(snapshot atspi.Snapshot) bool { return snapshot.Role == "tool tip" && !snapshot.Focusable && !snapshot.Editable } -// caret_node_indices preserves provider order and treats whole controls as one +// caretNodeIndices preserves provider order and treats whole controls as one // stop. MoveCaret holds the document cursor lock while using these indices. -func caret_node_indices(nodes []atspi.DocumentNode, object atspi.ObjectReference) ([]int, int, map[atspi.ObjectID]bool) { +func caretNodeIndices(nodes []atspi.DocumentNode, object atspi.ObjectReference) ([]int, int, map[atspi.ObjectID]bool) { // Container text normally embeds its child text. Whole controls are one // caret stop even when their label is a child or they have no text interface. // Python's web _treatObjectAsWhole makes the same distinction. @@ -104,11 +104,11 @@ func caret_node_indices(nodes []atspi.DocumentNode, object atspi.ObjectReference if node.Hidden || skipped[node.Reference.ID()] { continue } - if snapshot.Role == "password text" || passive_caret_tooltip(snapshot) { + if snapshot.Role == "password text" || passiveCaretTooltip(snapshot) { skipChildren(node.Children) continue } - if !protected[node.Reference.ID()] && decorative_caret_glyph(node) { + if !protected[node.Reference.ID()] && decorativeCaretGlyph(node) { continue } if wholeCaretNode(node.Snapshot) { @@ -133,7 +133,7 @@ func caret_node_indices(nodes []atspi.DocumentNode, object atspi.ObjectReference // Python's web hasValidName/isUselessEmptyElement rejects standalone unnamed // private-use icons. Keep this narrower: only a known non-interactive static // leaf with one matching name/text character is omitted from browse reading. -func decorative_caret_glyph(node atspi.DocumentNode) bool { +func decorativeCaretGlyph(node atspi.DocumentNode) bool { snapshot := node.Snapshot if snapshot.Role != "static" || !snapshot.StatesKnown || snapshot.Focusable || snapshot.Editable || node.ParentEditable || snapshot.SupportsClick || snapshot.ExplicitName || diff --git a/internal/review/document_caret_ranges.go b/internal/review/document_caret_ranges.go index c3566c7..df6d79d 100644 --- a/internal/review/document_caret_ranges.go +++ b/internal/review/document_caret_ranges.go @@ -18,7 +18,7 @@ import ( type caretRange struct{ index, start, end int } func caretNodeRanges(nodes []atspi.DocumentNode) []caretRange { - indices, _, expanded := caret_node_indices(nodes, atspi.ObjectReference{}) + indices, _, expanded := caretNodeIndices(nodes, atspi.ObjectReference{}) eligible := make(map[int]bool, len(indices)) byID := make(map[atspi.ObjectID]int, len(nodes)) for _, index := range indices { @@ -31,7 +31,7 @@ func caretNodeRanges(nodes []atspi.DocumentNode) []caretRange { var visit func(int) visit = func(index int) { node := nodes[index] - if node.Hidden || node.Snapshot.Role == "password text" || passive_caret_tooltip(node.Snapshot) { + if node.Hidden || node.Snapshot.Role == "password text" || passiveCaretTooltip(node.Snapshot) { return } children := node.Snapshot.TextChildren @@ -73,7 +73,7 @@ func caretNodeRanges(nodes []atspi.DocumentNode) []caretRange { return } if eligible[index] { - result = append(result, caretRange{index, 0, caret_text_count(node.Snapshot)}) + result = append(result, caretRange{index, 0, caretTextCount(node.Snapshot)}) if wholeCaretNode(node.Snapshot) && !expanded[node.Reference.ID()] { return } @@ -98,7 +98,7 @@ type caretRangeLookup struct { after []int } -func new_caret_range_lookup(ranges []caretRange, nodeCount int) *caretRangeLookup { +func newCaretRangeLookup(ranges []caretRange, nodeCount int) *caretRangeLookup { lookup := &caretRangeLookup{objects: make([][]int, nodeCount), after: make([]int, nodeCount)} for position, item := range ranges { lookup.objects[item.index] = append(lookup.objects[item.index], position) @@ -139,11 +139,11 @@ func (lookup *caretRangeLookup) position(ranges []caretRange, current, offset in func readCaretRange(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, item caretRange, offset int, unit atspi.DocumentCaretUnit) (atspi.DocumentCaretText, error) { offset = max(item.start, min(offset, item.end-1)) node := doc.Nodes[item.index] - text, err := read_caret_text(ctx, reader, node, offset, unit) + text, err := readCaretText(ctx, reader, node, offset, unit) if err != nil || text.End <= text.Start { return text, err } - if item.start == 0 && item.end == caret_text_count(node.Snapshot) { + if item.start == 0 && item.end == caretTextCount(node.Snapshot) { return text, nil } if text.Start < 0 || text.Start > offset || text.End <= offset || text.End > text.CharacterCount { diff --git a/internal/review/document_caret_text.go b/internal/review/document_caret_text.go index b3750eb..5143329 100644 --- a/internal/review/document_caret_text.go +++ b/internal/review/document_caret_text.go @@ -39,7 +39,7 @@ func moveCaretText(ctx context.Context, reader DocumentCaretReader, doc atspi.Do return DocumentCaretMove{}, err } node := doc.Nodes[indices[position].index] - if caret_text_count(node.Snapshot) == 0 || wholeCaretNode(node.Snapshot) && named_link_label(node.Snapshot) == "" { + if caretTextCount(node.Snapshot) == 0 || wholeCaretNode(node.Snapshot) && namedLinkLabel(node.Snapshot) == "" { if node.Reference != place.object { place.object, place.offset, place.origin = node.Reference, 0, CaretNavigation return DocumentCaretMove{Position: documentPosition(doc, *place), Moved: true}, nil @@ -62,8 +62,8 @@ func moveCaretText(ctx context.Context, reader DocumentCaretReader, doc atspi.Do if err == nil && character.End > character.Start { value, _ := utf8.DecodeRuneInString(character.Text) if character.Text == "" || byWord && unicode.IsSpace(value) || value == '\ufffc' || value == '\ufeff' { - if blocks, ok := reader.(DocumentCharacterReader); byWord && unicode.IsSpace(value) && ok && named_link_label(node.Snapshot) == "" { - nextOffset, err := skip_word_spaces(ctx, blocks, node.Reference, indices[position], offset, step) + if blocks, ok := reader.(DocumentCharacterReader); byWord && unicode.IsSpace(value) && ok && namedLinkLabel(node.Snapshot) == "" { + nextOffset, err := skipWordSpaces(ctx, blocks, node.Reference, indices[position], offset, step) if err != nil { return DocumentCaretMove{}, err } @@ -123,7 +123,7 @@ func moveCaretText(ctx context.Context, reader DocumentCaretReader, doc atspi.Do // Keep native Unicode offsets and stop at embedded-object range boundaries. // A broken optional block cannot advance the cursor; ordinary unit reads then // retain their existing provider-error handling. -func skip_word_spaces(ctx context.Context, reader DocumentCharacterReader, object atspi.ObjectReference, item caretRange, offset, step int) (int, error) { +func skipWordSpaces(ctx context.Context, reader DocumentCharacterReader, object atspi.ObjectReference, item caretRange, offset, step int) (int, error) { block, err := reader.ReadDocumentCharacters(ctx, object, offset) if err != nil { return offset, err diff --git a/internal/review/document_diagnostics.go b/internal/review/document_diagnostics.go index 16b2f73..b5d0287 100644 --- a/internal/review/document_diagnostics.go +++ b/internal/review/document_diagnostics.go @@ -35,7 +35,7 @@ type DocumentState struct { Active bool `json:"active"` } -func (cursor *DocumentCursor) diagnostic_state() DocumentState { +func (cursor *DocumentCursor) diagnosticState() DocumentState { if cursor == nil { return DocumentState{} } @@ -57,8 +57,8 @@ func (cursor *DocumentCursor) diagnostic_state() DocumentState { Origin: origin, Active: cursor.active == place.document} } -func (result *Result) record_document_attempt(cursor *DocumentCursor, attempt DocumentAttempt, err error) { - attempt.After = cursor.diagnostic_state() +func (result *Result) recordDocumentAttempt(cursor *DocumentCursor, attempt DocumentAttempt, err error) { + attempt.After = cursor.diagnosticState() if err != nil { attempt.Error = err.Error() } diff --git a/internal/review/document_inline_replacement_test.go b/internal/review/document_inline_replacement_test.go index 5d6b98f..3836bee 100644 --- a/internal/review/document_inline_replacement_test.go +++ b/internal/review/document_inline_replacement_test.go @@ -14,7 +14,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" ) -func inline_replacement_cursor(t *testing.T, role string, slot int) (*DocumentCursor, caretTextReader, []atspi.TreeNode) { +func inlineReplacementCursor(t *testing.T, role string, slot int) (*DocumentCursor, caretTextReader, []atspi.TreeNode) { t.Helper() reader := caretTextReader{webID("/before"): "Published", webID("/old"): "↺ by Publisher", webID("/after"): "Article continues"} paths := []string{"/before", "/after"} @@ -57,7 +57,7 @@ func TestDocumentCaretRecoversReplacedInlineText(t *testing.T) { for _, role := range []string{"paragraph", "heading", "section", "link"} { for slot := 0; slot < 3; slot++ { t.Run(fmt.Sprintf("%s/%d", role, slot), func(t *testing.T) { - cursor, reader, nodes := inline_replacement_cursor(t, role, slot) + cursor, reader, nodes := inlineReplacementCursor(t, role, slot) ctx := context.Background() for generation := 0; generation < 4; generation++ { path := fmt.Sprintf("/replacement%d", generation) @@ -67,7 +67,7 @@ func TestDocumentCaretRecoversReplacedInlineText(t *testing.T) { if err := cursor.tree.Replace(webID("/doc"), nodes); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(ctx, webID("/paragraph")) + position, recovery, err := cursor.syncFocus(ctx, webID("/paragraph")) if err != nil || recovery != "replaced-text-child" || position.Object.ID() != webID(path) { t.Fatalf("replacement %d: %+v, %s, %v", generation, position, recovery, err) } @@ -100,7 +100,7 @@ func TestDocumentCaretRecoversReplacedInlineText(t *testing.T) { func TestDocumentLinkReplacementPreservesActivationOwnership(t *testing.T) { for _, kind := range []string{"same link", "replaced link", "named link", "editable link"} { t.Run(kind, func(t *testing.T) { - cursor, _, nodes := inline_replacement_cursor(t, "link", 1) + cursor, _, nodes := inlineReplacementCursor(t, "link", 1) ctx := context.Background() originalTarget, err := cursor.ActivationTarget() if err != nil || originalTarget.ID() != webID("/paragraph") { @@ -122,7 +122,7 @@ func TestDocumentLinkReplacementPreservesActivationOwnership(t *testing.T) { if _, err := cursor.syncActionFocus(ctx, webID("/paragraph")); err == nil { t.Fatal("activation silently recovered a missing text target") } - position, recovery, err := cursor.sync_focus(ctx, webID("/paragraph")) + position, recovery, err := cursor.syncFocus(ctx, webID("/paragraph")) if err != nil { t.Fatal(err) } @@ -141,7 +141,7 @@ func TestDocumentLinkReplacementPreservesActivationOwnership(t *testing.T) { } func TestReadAllAfterInlineReplacementRecovery(t *testing.T) { - cursor, reader, nodes := inline_replacement_cursor(t, "paragraph", 1) + cursor, reader, nodes := inlineReplacementCursor(t, "paragraph", 1) nodes[1].Children[1] = webID("/new") nodes[3].Snapshot.Path = "/new" reader[webID("/new")] = reader[webID("/old")] @@ -164,7 +164,7 @@ func TestReadAllAfterInlineReplacementRecovery(t *testing.T) { func TestReadAllRecoveryRejectsReplacedDocument(t *testing.T) { for _, refresh := range []bool{false, true} { t.Run(fmt.Sprint(refresh), func(t *testing.T) { - cursor, reader, nodes := inline_replacement_cursor(t, "link", 1) + cursor, reader, nodes := inlineReplacementCursor(t, "link", 1) cursor.tree.Invalidate(webID("/doc")) if err := cursor.tree.Replace(webID("/doc"), nodes); err != nil { t.Fatal(err) @@ -172,7 +172,7 @@ func TestReadAllRecoveryRejectsReplacedDocument(t *testing.T) { worker, _ := NewWorker(&readAllCapturer{tree: cursor.tree, caretTextReader: reader}, time.Second) worker.SyncFocus(webID("/paragraph")) if refresh { - if _, err := worker.refresh_read_all_cursor(context.Background(), cursor, webID("/paragraph")); err == nil { + if _, err := worker.refreshReadAllCursor(context.Background(), cursor, webID("/paragraph")); err == nil { t.Fatal("Read All refresh crossed a document generation") } return @@ -188,7 +188,7 @@ func TestReadAllRecoveryRejectsReplacedDocument(t *testing.T) { func TestDocumentInlineReplacementRetainsAndClampsUnicodeOffset(t *testing.T) { for _, replacement := range []string{"↺ by Another publisher", "↺"} { t.Run(replacement, func(t *testing.T) { - cursor, reader, nodes := inline_replacement_cursor(t, "paragraph", 1) + cursor, reader, nodes := inlineReplacementCursor(t, "paragraph", 1) ctx := context.Background() move, err := cursor.MoveCaret(ctx, reader, CaretNextWord) if err != nil || move.Position.Offset != 4 { @@ -201,7 +201,7 @@ func TestDocumentInlineReplacementRetainsAndClampsUnicodeOffset(t *testing.T) { if err := cursor.tree.Replace(webID("/doc"), nodes); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(ctx, webID("/paragraph")) + position, recovery, err := cursor.syncFocus(ctx, webID("/paragraph")) wantOffset := min(move.Position.Offset, utf8.RuneCountInString(replacement)-1) if err != nil || recovery != "replaced-text-child" || position.Offset != wantOffset { t.Fatalf("replacement: offset=%d want=%d recovery=%s err=%v", position.Offset, wantOffset, recovery, err) @@ -215,7 +215,7 @@ func TestDocumentInlineReplacementRejectsAmbiguousOrInteractiveChanges(t *testin "replaced parent", "replaced document", "hidden parent", "editable parent", "clickable parent", "focusable parent", "hidden child", "editable child", "clickable child", "focusable child", "named child", "password child", "native origin"} { t.Run(kind, func(t *testing.T) { - cursor, reader, nodes := inline_replacement_cursor(t, "paragraph", 1) + cursor, reader, nodes := inlineReplacementCursor(t, "paragraph", 1) nodes[1].Children[1] = webID("/new") nodes[3].Snapshot.Path = "/new" reader[webID("/new")] = reader[webID("/old")] @@ -260,7 +260,7 @@ func TestDocumentInlineReplacementRejectsAmbiguousOrInteractiveChanges(t *testin if err := cursor.tree.Replace(webID("/doc"), nodes); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(context.Background(), webID("/paragraph")) + position, recovery, err := cursor.syncFocus(context.Background(), webID("/paragraph")) if err != nil || recovery == "replaced-text-child" || position.Object.ID() == webID("/new") { t.Fatalf("unsafe replacement accepted: object=%+v recovery=%s err=%v", position.Object.ID(), recovery, err) } diff --git a/internal/review/document_lists.go b/internal/review/document_lists.go index ce74720..b05b680 100644 --- a/internal/review/document_lists.go +++ b/internal/review/document_lists.go @@ -259,7 +259,7 @@ func (worker *Worker) selectDocumentList(ctx context.Context, cursor *DocumentCu place := &cursor.places[len(cursor.places)-1] place.object, place.offset, place.origin = position.Object, 0, StructuralNavigation place.tableCell = atspi.ObjectID{} - remember_text_parent(doc, place) + rememberTextParent(doc, place) result.DocumentPosition = documentPosition(doc, *place) cursor.mu.Unlock() result.Moved = true diff --git a/internal/review/document_lists_test.go b/internal/review/document_lists_test.go index 11b4f8c..8e8bd79 100644 --- a/internal/review/document_lists_test.go +++ b/internal/review/document_lists_test.go @@ -22,12 +22,12 @@ func TestDocumentListPreservesCursorAndSelectsExactTarget(t *testing.T) { capturer := &readAllCapturer{tree: tree} worker, _ := NewWorker(capturer, time.Second) worker.SyncFocus(webID("/doc")) - before := cursor.diagnostic_state() + before := cursor.diagnosticState() list, err := worker.listDocument(ctx, cursor, &documentListRequest{ctx: ctx, target: DocumentHeading}) if err != nil || len(list.Entries) != 2 { t.Fatalf("heading list: %+v %v", list, err) } - if after := cursor.diagnostic_state(); after != before { + if after := cursor.diagnosticState(); after != before { t.Fatalf("opening moved cursor: %+v -> %+v", before, after) } result, cursor := worker.selectDocumentList(ctx, cursor, &documentListSelection{list: list, index: 1}) diff --git a/internal/review/document_named_link.go b/internal/review/document_named_link.go index b089f0f..7dbbcca 100644 --- a/internal/review/document_named_link.go +++ b/internal/review/document_named_link.go @@ -13,15 +13,15 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" ) -func named_link_label(snapshot atspi.Snapshot) string { +func namedLinkLabel(snapshot atspi.Snapshot) string { if snapshot.Role == "link" && snapshot.ExplicitName && !snapshot.Editable { return strings.TrimSpace(snapshot.Name) } return "" } -func caret_text_count(snapshot atspi.Snapshot) int { - if label := named_link_label(snapshot); label != "" { +func caretTextCount(snapshot atspi.Snapshot) int { + if label := namedLinkLabel(snapshot); label != "" { return utf8.RuneCountInString(label) } return snapshot.CharacterCount @@ -30,11 +30,11 @@ func caret_text_count(snapshot atspi.Snapshot) int { // Named links can expose no Text interface, or only a badge/embedded object. // Review the label used by line speech, retaining the link for activation. // These offsets belong to the label and must never become native text offsets. -func read_caret_text(ctx context.Context, reader DocumentCaretReader, node atspi.DocumentNode, offset int, unit atspi.DocumentCaretUnit) (atspi.DocumentCaretText, error) { +func readCaretText(ctx context.Context, reader DocumentCaretReader, node atspi.DocumentNode, offset int, unit atspi.DocumentCaretUnit) (atspi.DocumentCaretText, error) { if err := ctx.Err(); err != nil { return atspi.DocumentCaretText{}, err } - label := named_link_label(node.Snapshot) + label := namedLinkLabel(node.Snapshot) if label == "" { return reader.ReadDocumentCaret(ctx, node.Reference, offset, unit) } diff --git a/internal/review/document_native_caret.go b/internal/review/document_native_caret.go index 71286e9..247c998 100644 --- a/internal/review/document_native_caret.go +++ b/internal/review/document_native_caret.go @@ -28,18 +28,18 @@ func (cursor *DocumentCursor) syncNativeCaret(ctx context.Context, reader Docume if err != nil { return err } - node, offset, err := native_caret_node(ctx, reader, doc, focus, offset) + node, offset, err := nativeCaretNode(ctx, reader, doc, focus, offset) if err != nil { return err } place.object, place.offset, place.origin = node.Reference, offset, CaretNavigation place.tableCell = atspi.ObjectID{} - remember_text_parent(doc, place) + rememberTextParent(doc, place) return nil } -func native_caret_node(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, focus atspi.ObjectID, offset int) (atspi.DocumentNode, int, error) { +func nativeCaretNode(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, focus atspi.ObjectID, offset int) (atspi.DocumentNode, int, error) { node, _ := doc.Node(focus) if !node.Reference.Valid() || offset < 0 || offset > node.Snapshot.CharacterCount || node.Snapshot.Editable || node.Snapshot.Role == "password text" { return atspi.DocumentNode{}, 0, atspi.ErrNoDocumentCaret diff --git a/internal/review/document_navigation_reader.go b/internal/review/document_navigation_reader.go index 08a3ee4..7763eb5 100644 --- a/internal/review/document_navigation_reader.go +++ b/internal/review/document_navigation_reader.go @@ -36,7 +36,7 @@ func (reader *navigationTextReader) ReadDocumentCaret(ctx context.Context, objec return text, err } -func (reader *navigationTextReader) did_read(object atspi.ObjectReference) bool { +func (reader *navigationTextReader) didRead(object atspi.ObjectReference) bool { for _, read := range reader.readObjects { if read == object { return true diff --git a/internal/review/document_replacement.go b/internal/review/document_replacement.go index 1d35323..0ef71aa 100644 --- a/internal/review/document_replacement.go +++ b/internal/review/document_replacement.go @@ -14,7 +14,7 @@ import "git.stormux.org/storm/cthulhu/internal/atspi" // generation-checked parent, then distinguish recreation from insertion. // Labels alone still cannot establish the old reading position, and neither // recovery is ever used for activation. -func remember_text_parent(doc atspi.DocumentSnapshot, place *documentPlace) { +func rememberTextParent(doc atspi.DocumentSnapshot, place *documentPlace) { place.textParent = atspi.ObjectReference{} place.textPrevious, place.textNext = atspi.ObjectReference{}, atspi.ObjectReference{} place.textChildIndex, place.textChildCount = 0, 0 @@ -26,7 +26,7 @@ func remember_text_parent(doc atspi.DocumentSnapshot, place *documentPlace) { if !ok || node.Reference != place.object { return } - plainText := replacement_text_leaf(node) + plainText := replacementTextLeaf(node) firstParent := true for parentID := node.Parent; parentID.Valid(); { parent, ok := doc.Node(parentID) @@ -35,10 +35,10 @@ func remember_text_parent(doc atspi.DocumentSnapshot, place *documentPlace) { } if firstParent { firstParent = false - remember_child_slot(doc, place, parent, &place.parent, &place.parentPrevious, &place.parentNext, + rememberChildSlot(doc, place, parent, &place.parent, &place.parentPrevious, &place.parentNext, &place.parentChildIndex, &place.parentChildCount) } - if len(place.recoveryParents) == 0 && plainText && replacement_text_parent(parent) { + if len(place.recoveryParents) == 0 && plainText && replacementTextParent(parent) { place.textParent = parent.Reference for childIndex, id := range parent.Children { if id != place.object.ID() { @@ -89,7 +89,7 @@ func survivingDocumentParent(doc atspi.DocumentSnapshot, saved documentPlace) (a return atspi.DocumentNode{}, false } -func replacement_text_node(doc atspi.DocumentSnapshot, saved documentPlace) (atspi.DocumentNode, string, bool) { +func replacementTextNode(doc atspi.DocumentSnapshot, saved documentPlace) (atspi.DocumentNode, string, bool) { if saved.document != doc.Context.TopLevel || !saved.textParent.Valid() || saved.origin != CaretNavigation { return atspi.DocumentNode{}, "", false } @@ -99,7 +99,7 @@ func replacement_text_node(doc atspi.DocumentSnapshot, saved documentPlace) (ats byID[node.Reference.ID()] = node } for _, parent := range doc.Nodes { - if parent.Reference != saved.textParent || !replacement_text_parent(parent) { + if parent.Reference != saved.textParent || !replacementTextParent(parent) { continue } for index, id := range parent.Children { @@ -119,7 +119,7 @@ func replacement_text_node(doc atspi.DocumentSnapshot, saved documentPlace) (ats next = sibling.Reference } child := byID[id] - if previous == saved.textPrevious && next == saved.textNext && child != nil && replacement_text_leaf(*child) { + if previous == saved.textPrevious && next == saved.textNext && child != nil && replacementTextLeaf(*child) { return *child, "replaced-text-child", true } } @@ -140,7 +140,7 @@ func replacement_text_node(doc atspi.DocumentSnapshot, saved documentPlace) (ats } if siblingsRetired && saved.textChildCount > 0 && len(parent.Children) == saved.textChildCount && saved.textChildIndex >= 0 && saved.textChildIndex < len(parent.Children) { - if child := byID[parent.Children[saved.textChildIndex]]; child != nil && replacement_text_leaf(*child) { + if child := byID[parent.Children[saved.textChildIndex]]; child != nil && replacementTextLeaf(*child) { return *child, "replaced-text-child-index", true } } @@ -149,11 +149,11 @@ func replacement_text_node(doc atspi.DocumentSnapshot, saved documentPlace) (ats return atspi.DocumentNode{}, "", false } -// remember_child_slot records a child's slot under its immediate parent: +// rememberChildSlot records a child's slot under its immediate parent: // the generation-checked parent, adjacent sibling references, and index // and count. Any unresolved boundary clears the slot; indices alone are // never enough evidence on their own. -func remember_child_slot(doc atspi.DocumentSnapshot, place *documentPlace, parent atspi.DocumentNode, +func rememberChildSlot(doc atspi.DocumentSnapshot, place *documentPlace, parent atspi.DocumentNode, slotParent, slotPrevious, slotNext *atspi.ObjectReference, slotIndex, slotCount *int) { for childIndex, id := range parent.Children { if id != place.object.ID() { @@ -179,14 +179,14 @@ func remember_child_slot(doc atspi.DocumentSnapshot, place *documentPlace, paren } } -// replacement_child_node generalizes the replaced-text-child recovery to +// replacementChildNode generalizes the replaced-text-child recovery to // any child (recreated button rows, containers) under the same bounded // evidence: either the generation-checked sibling boundaries still match, // or every sibling retired together with the child count unchanged, so // the same index under the same surviving parent is the recreation. Orca // recovers removed children the same way (parent plus removed index); // activation never uses this fallback. -func replacement_child_node(doc atspi.DocumentSnapshot, saved documentPlace) (atspi.DocumentNode, string, bool) { +func replacementChildNode(doc atspi.DocumentSnapshot, saved documentPlace) (atspi.DocumentNode, string, bool) { if saved.document != doc.Context.TopLevel || !saved.parent.Valid() || saved.origin == NativeNavigation { return atspi.DocumentNode{}, "", false } @@ -248,7 +248,7 @@ func replacement_child_node(doc atspi.DocumentSnapshot, saved documentPlace) (at return atspi.DocumentNode{}, "", false } -func replacement_text_parent(node atspi.DocumentNode) bool { +func replacementTextParent(node atspi.DocumentNode) bool { if len(node.Children) == 0 || node.Hidden || node.ParentEditable || node.Snapshot.Editable { return false } @@ -263,7 +263,7 @@ func replacement_text_parent(node atspi.DocumentNode) bool { (node.Snapshot.Role == "paragraph" || node.Snapshot.Role == "heading" || node.Snapshot.Role == "section") } -func replacement_text_leaf(node atspi.DocumentNode) bool { +func replacementTextLeaf(node atspi.DocumentNode) bool { return len(node.Children) == 0 && !node.Hidden && !node.ParentEditable && !node.Snapshot.Editable && !node.Snapshot.Focusable && !node.Snapshot.SupportsClick && !node.Snapshot.ExplicitName && node.Snapshot.CharacterCount > 0 && diff --git a/internal/review/document_replacement_test.go b/internal/review/document_replacement_test.go index e0b2938..79a3373 100644 --- a/internal/review/document_replacement_test.go +++ b/internal/review/document_replacement_test.go @@ -52,7 +52,7 @@ func TestDocumentCaretRecoversSingleReplacedTextChild(t *testing.T) { if err := tree.Replace(webID("/doc"), nodes); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(ctx, webID("/doc")) + position, recovery, err := cursor.syncFocus(ctx, webID("/doc")) if err != nil { t.Fatal(err) } @@ -122,7 +122,7 @@ func TestDocumentCaretRecoversRecreatedTextSiblings(t *testing.T) { if err := tree.Replace(webID("/doc"), generation("b")); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(ctx, webID("/doc")) + position, recovery, err := cursor.syncFocus(ctx, webID("/doc")) if err != nil { t.Fatal(err) } @@ -135,7 +135,7 @@ func TestDocumentCaretRecoversRecreatedTextSiblings(t *testing.T) { if err := tree.Replace(webID("/doc"), generation("c")); err != nil { t.Fatal(err) } - if _, _, err := cursor.sync_focus(ctx, webID("/doc")); err != nil { + if _, _, err := cursor.syncFocus(ctx, webID("/doc")); err != nil { t.Fatal(err) } if move, err := cursor.MoveCaret(ctx, reader, CaretNextLine); err != nil || move.Moved { @@ -186,7 +186,7 @@ func TestDocumentCaretRecoversRecreatedChildByIndex(t *testing.T) { if err := tree.Replace(webID("/doc"), generation("b")); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(ctx, webID("/doc")) + position, recovery, err := cursor.syncFocus(ctx, webID("/doc")) if err != nil { t.Fatal(err) } @@ -225,7 +225,7 @@ func TestDocumentCaretMoveCrossesTextInvalidatedLines(t *testing.T) { } tree.InvalidateText(webID("/first")) tree.InvalidateText(webID("/second")) - if _, _, err := cursor.sync_focus(ctx, webID("/doc")); err != nil { + if _, _, err := cursor.syncFocus(ctx, webID("/doc")); err != nil { t.Fatalf("sync across ticking text: %v", err) } move, err := cursor.MoveCaret(ctx, reader, CaretNextLine) @@ -290,7 +290,7 @@ func TestDocumentRecoveryUsesSurvivingContainerWithoutTransferringOffset(t *test if err := tree.Replace(webID("/doc"), nodes); err != nil { t.Fatal(err) } - position, recovery, err := cursor.sync_focus(ctx, webID("/doc")) + position, recovery, err := cursor.syncFocus(ctx, webID("/doc")) if err != nil || recovery != "surviving-parent" || position.Object.ID() != webID("/section") || position.Offset != 0 { t.Fatalf("container recovery: %+v, %s, %v", position, recovery, err) } diff --git a/internal/review/document_table.go b/internal/review/document_table.go index 9862964..6eb9b3a 100644 --- a/internal/review/document_table.go +++ b/internal/review/document_table.go @@ -16,7 +16,7 @@ import ( // The virtual coordinate survives a spanning cell so reversing direction keeps // the user's column/row. Nested tables have independent coordinate spaces. func (cursor *DocumentCursor) moveTable(ctx context.Context, doc atspi.DocumentSnapshot, place *documentPlace, command DocumentCaretCommand) (DocumentCaretMove, error) { - tableIndex, found := document_table_index(doc, place.object.ID()) + tableIndex, found := documentTableIndex(doc, place.object.ID()) message := func(text string) (DocumentCaretMove, error) { return DocumentCaretMove{Position: documentPosition(doc, *place), Text: text}, nil } @@ -110,7 +110,7 @@ func (cursor *DocumentCursor) moveTable(ctx context.Context, doc atspi.DocumentS } } if !target.Reference.Valid() && (dr != 0 || dc != 0) { - target, row, col = next_available_table_cell(cells, current, row, col, dr, dc) + target, row, col = nextAvailableTableCell(cells, current, row, col, dr, dc) } if !target.Reference.Valid() { return message("Table cell unavailable.") @@ -168,7 +168,7 @@ func (cursor *DocumentCursor) moveTable(ctx context.Context, doc atspi.DocumentS } // Use the immutable document index and avoid rebuilding whole-page parent maps. -func document_table_index(doc atspi.DocumentSnapshot, id atspi.ObjectID) (int, bool) { +func documentTableIndex(doc atspi.DocumentSnapshot, id atspi.ObjectID) (int, bool) { for depth := 0; id.Valid() && depth < 128; depth++ { index, ok := doc.Index(id) if !ok { @@ -185,7 +185,7 @@ func document_table_index(doc atspi.DocumentSnapshot, id atspi.ObjectID) (int, b // Search captured cells rather than iterating potentially enormous sparse // dimensions. Horizontal neighbors can occupy a lower row of a spanning cell. -func next_available_table_cell(cells []atspi.DocumentNode, current atspi.DocumentNode, row, col, dr, dc int) (atspi.DocumentNode, int, int) { +func nextAvailableTableCell(cells []atspi.DocumentNode, current atspi.DocumentNode, row, col, dr, dc int) (atspi.DocumentNode, int, int) { var target atspi.DocumentNode bestRow, bestCol := row, col for _, node := range cells { diff --git a/internal/review/document_tooltip_test.go b/internal/review/document_tooltip_test.go index 179d34d..6f9b48e 100644 --- a/internal/review/document_tooltip_test.go +++ b/internal/review/document_tooltip_test.go @@ -12,7 +12,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/atspi" ) -func tooltip_cursor(t *testing.T, focusable, editable, hypertext bool) (*DocumentCursor, caretTextReader) { +func tooltipCursor(t *testing.T, focusable, editable, hypertext bool) (*DocumentCursor, caretTextReader) { t.Helper() reader := caretTextReader{webID("/before"): "Project", webID("/tiptext"): "Project", webID("/after"): "After"} node := func(path, role string, children ...atspi.ObjectID) atspi.TreeNode { @@ -48,7 +48,7 @@ func TestDocumentCaretSkipsPassiveTooltip(t *testing.T) { for _, hypertext := range []bool{false, true} { for _, command := range []DocumentCaretCommand{CaretNextLine, CaretNextCharacter, CaretNextWord} { t.Run(command.String(), func(t *testing.T) { - cursor, reader := tooltip_cursor(t, false, false, hypertext) + cursor, reader := tooltipCursor(t, false, false, hypertext) if command != CaretNextLine { cursor.places[0].offset = len("Project") - 1 } @@ -74,7 +74,7 @@ func TestDocumentCaretSkipsPassiveTooltip(t *testing.T) { func TestDocumentCaretPreservesInteractiveTooltip(t *testing.T) { for _, focusable := range []bool{false, true} { - cursor, reader := tooltip_cursor(t, focusable, !focusable, false) + cursor, reader := tooltipCursor(t, focusable, !focusable, false) move, err := cursor.MoveCaret(context.Background(), reader, CaretNextLine) if err != nil || !move.Moved || move.Position.Object.ID() != webID("/tiptext") { t.Fatalf("interactive tooltip: %+v, %v", move, err) @@ -83,7 +83,7 @@ func TestDocumentCaretPreservesInteractiveTooltip(t *testing.T) { } func TestReadAllSkipsPassiveTooltip(t *testing.T) { - cursor, reader := tooltip_cursor(t, false, false, true) + cursor, reader := tooltipCursor(t, false, false, true) worker, err := NewWorker(&readAllCapturer{tree: cursor.tree, caretTextReader: reader}, time.Second) if err != nil { t.Fatal(err) diff --git a/internal/review/document_visual_line.go b/internal/review/document_visual_line.go index 94afd25..3665ca4 100644 --- a/internal/review/document_visual_line.go +++ b/internal/review/document_visual_line.go @@ -48,7 +48,7 @@ func (reader *visualLineReader) ReadDocumentCaret(ctx context.Context, object at return text, err } -func move_caret_line(ctx context.Context, source DocumentCaretReader, tree *atspi.AccessibleTree, doc atspi.DocumentSnapshot, place *documentPlace, indices []caretRange, lookup *caretRangeLookup, current int, command DocumentCaretCommand, owners map[int]atspi.ObjectID) (DocumentCaretMove, error) { +func moveCaretLine(ctx context.Context, source DocumentCaretReader, tree *atspi.AccessibleTree, doc atspi.DocumentSnapshot, place *documentPlace, indices []caretRange, lookup *caretRangeLookup, current int, command DocumentCaretCommand, owners map[int]atspi.ObjectID) (DocumentCaretMove, error) { reader := &visualLineReader{DocumentCaretReader: source, cache: make(map[visualLineKey]atspi.DocumentCaretText)} next := *place // Move beyond the entire current line, even when character/word movement @@ -60,7 +60,7 @@ func move_caret_line(ctx context.Context, source DocumentCaretReader, tree *atsp position = lookup.after[current] } if position >= 0 { - parts, err := collect_visual_line(ctx, reader, doc, indices, owners, position, place.offset, true) + parts, err := collectVisualLine(ctx, reader, doc, indices, owners, position, place.offset, true) if err != nil { return DocumentCaretMove{}, err } @@ -74,7 +74,7 @@ func move_caret_line(ctx context.Context, source DocumentCaretReader, tree *atsp } } } - movement, err := move_caret_object_line(ctx, reader, doc, &next, indices, lookup, current, command) + movement, err := moveCaretObjectLine(ctx, reader, doc, &next, indices, lookup, current, command) if err != nil || !movement.Moved { if err == nil { movement.Position = documentPosition(doc, *place) @@ -84,7 +84,7 @@ func move_caret_line(ctx context.Context, source DocumentCaretReader, tree *atsp nextIndex, _ := doc.Index(next.object.ID()) position := lookup.containing(indices, nextIndex, next.offset) if position >= 0 { - parts, err := collect_visual_line(ctx, reader, doc, indices, owners, position, next.offset, command != CaretReadLine) + parts, err := collectVisualLine(ctx, reader, doc, indices, owners, position, next.offset, command != CaretReadLine) if err != nil { return DocumentCaretMove{}, err } @@ -98,7 +98,7 @@ func move_caret_line(ctx context.Context, source DocumentCaretReader, tree *atsp next.offset = part.text.End - 1 } movement.Start, movement.End = part.text.Start, part.text.End - line, raw, misspelled := assemble_visual_line(tree, doc, parts) + line, raw, misspelled := assembleVisualLine(tree, doc, parts) movement.Line, movement.RawText, movement.Misspelled = &line, raw, movement.Misspelled || misspelled movement.Text = strings.Join(strings.Fields(movement.RawText), " ") if command == CaretLineStart || command == CaretLineEnd { @@ -118,7 +118,7 @@ func move_caret_line(ctx context.Context, source DocumentCaretReader, tree *atsp // Retain semantic boundaries even if unrelated blocks have matching y values. // Links and same-row list items inherit their surrounding block. Headings, // paragraphs and table cells remain separate; grid items retain their boundaries. -func visual_line_owners(nodes []atspi.DocumentNode) map[int]atspi.ObjectID { +func visualLineOwners(nodes []atspi.DocumentNode) map[int]atspi.ObjectID { owners := make(map[int]atspi.ObjectID, len(nodes)) byID := make(map[atspi.ObjectID]atspi.ObjectID, len(nodes)) displays := make(map[atspi.ObjectID]string, len(nodes)) @@ -156,7 +156,7 @@ func visual_line_owners(nodes []atspi.DocumentNode) map[int]atspi.ObjectID { return owners } -func collect_visual_line(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, indices []caretRange, owners map[int]atspi.ObjectID, position, offset int, left bool) ([]visualLinePart, error) { +func collectVisualLine(ctx context.Context, reader DocumentCaretReader, doc atspi.DocumentSnapshot, indices []caretRange, owners map[int]atspi.ObjectID, position, offset int, left bool) ([]visualLinePart, error) { index := indices[position].index node := doc.Nodes[index] if !owners[index].Valid() || node.Snapshot.Editable || wholeCaretNode(node.Snapshot) || node.Snapshot.CharacterCount <= 0 { @@ -173,7 +173,7 @@ func collect_visual_line(ctx context.Context, reader DocumentCaretReader, doc at if err != nil { return nil, err } - if !visual_line_text(text) { + if !visualLineText(text) { return nil, nil } if !left && text.RawText != "" { @@ -206,7 +206,7 @@ func collect_visual_line(ctx context.Context, reader DocumentCaretReader, doc at if err != nil { return nil, err } - if !visual_line_text(piece) || !visual_line_bounds(text.Bounds, piece.Bounds) { + if !visualLineText(piece) || !visualLineBounds(text.Bounds, piece.Bounds) { break } // A fragment containing a hard newline ends the line, even when @@ -233,12 +233,12 @@ func collect_visual_line(ctx context.Context, reader DocumentCaretReader, doc at return parts, nil } -func visual_line_text(text atspi.DocumentCaretText) bool { +func visualLineText(text atspi.DocumentCaretText) bool { return text.Bounds.Valid() && text.Start >= 0 && text.End > text.Start && text.End <= text.CharacterCount && !strings.ContainsRune(text.Text, '\ufffc') && (text.Text != "" || text.RawText != "") } -func visual_line_bounds(first, second atspi.Rectangle) bool { +func visualLineBounds(first, second atspi.Rectangle) bool { if !first.Valid() || !second.Valid() { return false } @@ -247,7 +247,7 @@ func visual_line_bounds(first, second atspi.Rectangle) bool { return bottom > top && math.Abs(float64(first.Y)+float64(first.Height)/2-float64(second.Y)-float64(second.Height)/2) <= 5 } -func visual_line_space(first, second atspi.DocumentCaretText) bool { +func visualLineSpace(first, second atspi.DocumentCaretText) bool { left, right := first.RawText, second.RawText if left == "" { left = first.Text @@ -261,7 +261,7 @@ func visual_line_space(first, second atspi.DocumentCaretText) bool { return gap > 1 && !unicode.IsSpace(last) && !unicode.IsSpace(start) } -func assemble_visual_line(tree *atspi.AccessibleTree, doc atspi.DocumentSnapshot, parts []visualLinePart) (atspi.DocumentLine, string, bool) { +func assembleVisualLine(tree *atspi.AccessibleTree, doc atspi.DocumentSnapshot, parts []visualLinePart) (atspi.DocumentLine, string, bool) { misspelled := false line := atspi.DocumentLine{Document: doc.Context.TopLevel} var raw strings.Builder @@ -272,7 +272,7 @@ func assemble_visual_line(tree *atspi.AccessibleTree, doc atspi.DocumentSnapshot } // Preserve native spacing and punctuation across span boundaries. separator := "" - if i > 0 && visual_line_space(parts[i-1].text, part.text) { + if i > 0 && visualLineSpace(parts[i-1].text, part.text) { separator = " " } raw.WriteString(separator) diff --git a/internal/review/document_visual_line_native_test.go b/internal/review/document_visual_line_native_test.go index 6b4c39b..2cd3c31 100644 --- a/internal/review/document_visual_line_native_test.go +++ b/internal/review/document_visual_line_native_test.go @@ -124,7 +124,7 @@ func TestNativeBrowserFragmentLines(t *testing.T) { content := inline.Line.Contents[1] displayRoute := &documentBrailleRequest{ctx: ctx, focus: focus, document: inline.Position.Document.ID(), target: content.Snapshot.ID(), line: content.RawText, start: content.Start, offset: content.Start + 1, done: make(chan error, 1)} - routed := worker.route_document_braille(ctx, cursor, request{brailleRoute: displayRoute}) + routed := worker.routeDocumentBraille(ctx, cursor, request{brailleRoute: displayRoute}) if routed.Err != nil || !routed.Moved || routed.DocumentPosition.Offset != content.Start+1 || routed.DocumentCaretLine == nil || len(routed.DocumentCaretLine.Contents) < 2 { t.Fatalf("native inline braille route = %+v", routed) } @@ -148,7 +148,7 @@ func TestNativeBrowserFragmentLines(t *testing.T) { t.Fatalf("Read All: %+v", result) } for index, want := range []string{"One two three.", "Four five six.", "Next paragraph."} { - if got := visual_line_test_text(result.ReadAllLines[index]); got != want { + if got := visualLineTestText(result.ReadAllLines[index]); got != want { t.Fatalf("Read All line %d: %q, want %q", index, got, want) } } diff --git a/internal/review/document_visual_line_test.go b/internal/review/document_visual_line_test.go index 47219a4..b4b38da 100644 --- a/internal/review/document_visual_line_test.go +++ b/internal/review/document_visual_line_test.go @@ -31,7 +31,7 @@ func (reader fragmentTextReader) ReadDocumentCaret(ctx context.Context, ref atsp return text, err } -func fragment_cursor(t *testing.T, boundary string) (*DocumentCursor, fragmentTextReader) { +func fragmentCursor(t *testing.T, boundary string) (*DocumentCursor, fragmentTextReader) { t.Helper() reader := fragmentTextReader{caretTextReader: caretTextReader{ webID("/one"): "One ", webID("/two"): "two.", webID("/three"): "Three ", webID("/four"): "four.", webID("/after"): "Next paragraph", @@ -79,7 +79,7 @@ func fragment_cursor(t *testing.T, boundary string) (*DocumentCursor, fragmentTe } func TestDocumentFragmentLines(t *testing.T) { - cursor, reader := fragment_cursor(t, "paragraph") + cursor, reader := fragmentCursor(t, "paragraph") ctx := context.Background() for _, step := range []struct { command DocumentCaretCommand @@ -115,7 +115,7 @@ func TestDocumentFragmentSpacingAndPunctuation(t *testing.T) { {"One", "two.", "One two.", 40}, {"Hello", ",", "Hello,", 30}, } { - cursor, reader := fragment_cursor(t, "paragraph") + cursor, reader := fragmentCursor(t, "paragraph") reader.caretTextReader[webID("/one")] = test.first reader.caretTextReader[webID("/two")] = test.second bounds := reader.bounds[webID("/two")] @@ -150,7 +150,7 @@ func (capturer *fragmentReadAllCapturer) ReadDocumentCaret(ctx context.Context, } func TestReadAllFragmentLinesAndRemainder(t *testing.T) { - cursor, reader := fragment_cursor(t, "paragraph") + cursor, reader := fragmentCursor(t, "paragraph") ctx := context.Background() if _, err := cursor.MoveCaret(ctx, reader, CaretNextCharacter); err != nil { t.Fatal(err) @@ -163,7 +163,7 @@ func TestReadAllFragmentLinesAndRemainder(t *testing.T) { t.Fatalf("read all: %+v", result) } for index, want := range []string{"ne two.", "Three four.", "Next paragraph"} { - if got := visual_line_test_text(result.ReadAllLines[index]); got != want { + if got := visualLineTestText(result.ReadAllLines[index]); got != want { t.Fatalf("line %d: %q, want %q", index, got, want) } } @@ -190,7 +190,7 @@ func TestReadAllFragmentLinesAndRemainder(t *testing.T) { } func TestDocumentFragmentSourceLookupFailureKeepsLocalText(t *testing.T) { - cursor, reader := fragment_cursor(t, "paragraph") + cursor, reader := fragmentCursor(t, "paragraph") doc, err := cursor.tree.Document(t.Context(), cursor.places[0].object) if err != nil { t.Fatal(err) @@ -208,7 +208,7 @@ func TestDocumentFragmentSourceLookupFailureKeepsLocalText(t *testing.T) { // Metadata can become stale after the successful text read. The local // text stays usable; missing source evidence must remain explicit. cursor.tree.InvalidateSnapshot(webID("/span")) - line, raw, _ := assemble_visual_line(cursor.tree, doc, parts) + line, raw, _ := assembleVisualLine(cursor.tree, doc, parts) if raw != "One two." || len(line.SourceContexts) != 2 || len(line.SourceContexts[0]) == 0 || line.SourceContexts[1] != nil { t.Fatal("stale source context changed local text or looked classified") } @@ -217,7 +217,7 @@ func TestDocumentFragmentSourceLookupFailureKeepsLocalText(t *testing.T) { func TestDocumentFragmentBoundaries(t *testing.T) { for _, boundary := range []string{"heading", "link", "table cell", "pre", "code", "entry"} { t.Run(boundary, func(t *testing.T) { - cursor, reader := fragment_cursor(t, boundary) + cursor, reader := fragmentCursor(t, boundary) move, err := cursor.MoveCaret(context.Background(), reader, CaretDocumentStart) want := "One two." if boundary == "pre" || boundary == "code" || boundary == "entry" { @@ -235,7 +235,7 @@ func TestDocumentFragmentBoundaries(t *testing.T) { func TestDocumentFragmentErrorsDoNotMoveCursor(t *testing.T) { for _, failure := range []error{context.Canceled, atspi.ErrStaleObject} { - cursor, reader := fragment_cursor(t, "paragraph") + cursor, reader := fragmentCursor(t, "paragraph") reader.err = failure before := cursor.places[0] _, err := cursor.MoveCaret(context.Background(), reader, CaretNextLine) @@ -256,7 +256,7 @@ func (reader wrappedFragmentReader) ReadDocumentCaret(ctx context.Context, ref a } func TestDocumentFragmentLineAcrossWrappedObject(t *testing.T) { - cursor, base := fragment_cursor(t, "paragraph") + cursor, base := fragmentCursor(t, "paragraph") base.caretTextReader[webID("/one")] = "First\nSecond " base.bounds[webID("/two")] = atspi.Rectangle{X: 60, Y: 30, Width: 30, Height: 18} base.bounds[webID("/three")] = atspi.Rectangle{X: 0, Y: 50, Width: 30, Height: 18} @@ -291,7 +291,7 @@ func TestDocumentFragmentLineAcrossWrappedObject(t *testing.T) { } } -func visual_line_test_text(line atspi.DocumentLine) string { +func visualLineTestText(line atspi.DocumentLine) string { var text strings.Builder for _, part := range line.Contents { text.WriteString(part.Separator) @@ -303,7 +303,7 @@ func visual_line_test_text(line atspi.DocumentLine) string { func TestDocumentSameRowLinksAndListItems(t *testing.T) { for _, role := range []string{"link", "list item"} { t.Run(role, func(t *testing.T) { - cursor, reader := fragment_cursor(t, "list") + cursor, reader := fragmentCursor(t, "list") doc, _ := cursor.tree.Document(t.Context(), cursor.places[0].object) var nodes []atspi.TreeNode for _, node := range doc.Nodes { @@ -332,7 +332,7 @@ func TestDocumentSameRowLinksAndListItems(t *testing.T) { } func TestDocumentGridListItemsStaySeparate(t *testing.T) { - cursor, reader := fragment_cursor(t, "list") + cursor, reader := fragmentCursor(t, "list") doc, _ := cursor.tree.Document(t.Context(), cursor.places[0].object) var nodes []atspi.TreeNode for _, node := range doc.Nodes { diff --git a/internal/review/document_worker.go b/internal/review/document_worker.go index 6790176..ceef795 100644 --- a/internal/review/document_worker.go +++ b/internal/review/document_worker.go @@ -187,7 +187,7 @@ func (worker *Worker) captureDocumentForMove(ctx context.Context, cursor *Docume if err == nil || !errors.Is(err, atspi.ErrObjectNotFound) { return tree, duration, err } - anchor, ok := cursor.capture_anchor(focus) + anchor, ok := cursor.captureAnchor(focus) if !ok { return tree, duration, err } @@ -212,14 +212,14 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document return result, cursor } move := func() (moveErr error) { - attempt := DocumentAttempt{Focus: result.DocumentFocus, Before: cursor.diagnostic_state(), Stage: "focus"} - defer func() { result.record_document_attempt(cursor, attempt, moveErr) }() + attempt := DocumentAttempt{Focus: result.DocumentFocus, Before: cursor.diagnosticState(), Stage: "focus"} + defer func() { result.recordDocumentAttempt(cursor, attempt, moveErr) }() if cursor == nil { attempt.Recovery = "no-cursor" return ErrNoCurrent } - _, recovery, err := cursor.sync_focus(ctx, result.DocumentFocus) - attempt.Recovery, attempt.Synced = recovery, cursor.diagnostic_state() + _, recovery, err := cursor.syncFocus(ctx, result.DocumentFocus) + attempt.Recovery, attempt.Synced = recovery, cursor.diagnosticState() if err != nil { return err } @@ -398,14 +398,14 @@ func (worker *Worker) moveDocumentCaret(ctx context.Context, cursor *DocumentCur return result, cursor } move := func() (moveErr error) { - attempt := DocumentAttempt{Focus: result.DocumentFocus, Before: cursor.diagnostic_state(), Stage: "focus"} - defer func() { result.record_document_attempt(cursor, attempt, moveErr) }() + attempt := DocumentAttempt{Focus: result.DocumentFocus, Before: cursor.diagnosticState(), Stage: "focus"} + defer func() { result.recordDocumentAttempt(cursor, attempt, moveErr) }() if cursor == nil { attempt.Recovery = "no-cursor" return ErrNoCurrent } - _, recovery, err := cursor.sync_focus(ctx, result.DocumentFocus) - attempt.Recovery, attempt.Synced = recovery, cursor.diagnostic_state() + _, recovery, err := cursor.syncFocus(ctx, result.DocumentFocus) + attempt.Recovery, attempt.Synced = recovery, cursor.diagnosticState() if err != nil { return err } @@ -506,7 +506,7 @@ func (worker *Worker) placeDocumentCaret(ctx context.Context, cursor *DocumentCu deadline, cancel := context.WithTimeout(ctx, worker.captureTimeout) defer cancel() nativeOffset := result.DocumentPosition.Offset - if named_link_label(result.DocumentPosition.Snapshot) != "" { + if namedLinkLabel(result.DocumentPosition.Snapshot) != "" { // The label's review offset has no relationship to the native badge // or embedded-object text. Place only the link's native anchor. nativeOffset = 0 @@ -600,17 +600,17 @@ func (cursor *DocumentCursor) syncActionFocus(ctx context.Context, focus atspi.O // Refresh before an action, retaining the virtual position only within the same // document and focus. Never substitute another link if the selected one vanished. func (worker *Worker) refreshDocumentCursor(ctx context.Context, cursor *DocumentCursor, focus atspi.ObjectID) (*DocumentCursor, error) { - return worker.refresh_document_cursor(ctx, cursor, focus, false) + return worker.refreshDocumentCursorWithRecovery(ctx, cursor, focus, false) } // Read All is navigation: a missing text child can recover within the same // captured tree using its generation-checked parent and sibling boundaries. // Activation keeps the stricter refreshDocumentCursor path above. -func (worker *Worker) refresh_read_all_cursor(ctx context.Context, cursor *DocumentCursor, focus atspi.ObjectID) (*DocumentCursor, error) { - return worker.refresh_document_cursor(ctx, cursor, focus, true) +func (worker *Worker) refreshReadAllCursor(ctx context.Context, cursor *DocumentCursor, focus atspi.ObjectID) (*DocumentCursor, error) { + return worker.refreshDocumentCursorWithRecovery(ctx, cursor, focus, true) } -func (worker *Worker) refresh_document_cursor(ctx context.Context, cursor *DocumentCursor, focus atspi.ObjectID, recoverNavigation bool) (*DocumentCursor, error) { +func (worker *Worker) refreshDocumentCursorWithRecovery(ctx context.Context, cursor *DocumentCursor, focus atspi.ObjectID, recoverNavigation bool) (*DocumentCursor, error) { var saved documentPlace if cursor != nil && len(cursor.places) > 0 { saved = cursor.places[len(cursor.places)-1] diff --git a/internal/review/flat.go b/internal/review/flat.go index db761d6..9dd3a6f 100644 --- a/internal/review/flat.go +++ b/internal/review/flat.go @@ -85,7 +85,7 @@ func (cursor *FlatCursor) Refresh(ctx context.Context, tree *atspi.AccessibleTre return err } nodes := snapshot.Nodes - lines, completeness, err := build_flat_layout(ctx, nodes) + lines, completeness, err := buildFlatLayout(ctx, nodes) if err != nil { return err } @@ -101,7 +101,7 @@ func (cursor *FlatCursor) Refresh(ctx context.Context, tree *atspi.AccessibleTre // Exact identity takes priority over a displayed descendant of focus. if !next.seek(focus, 0, false) { if !next.seekDescendant(focus) { - next.seek_ancestor(focus) + next.seekAncestor(focus) } } for _, n := range nodes { @@ -127,7 +127,7 @@ func (cursor *FlatCursor) Refresh(ctx context.Context, tree *atspi.AccessibleTre // A focused leaf can have no displayed zone while its parent supplies the // text. Choose only an actual ancestor zone, never a sibling or window title. -func (cursor *FlatCursor) seek_ancestor(object atspi.ObjectID) bool { +func (cursor *FlatCursor) seekAncestor(object atspi.ObjectID) bool { for id := cursor.parents[object]; id.Valid(); id = cursor.parents[id] { if !cursor.parents[id].Valid() { return false diff --git a/internal/review/flat_browser_native_test.go b/internal/review/flat_browser_native_test.go index c5503b8..9d26a55 100644 --- a/internal/review/flat_browser_native_test.go +++ b/internal/review/flat_browser_native_test.go @@ -56,7 +56,7 @@ func TestNativeBrowserChromeFlatReview(t *testing.T) { if err != nil { t.Fatal(err) } - lines, status, err := build_flat_layout(ctx, snapshot.Nodes) + lines, status, err := buildFlatLayout(ctx, snapshot.Nodes) if err != nil { t.Fatal(err) } diff --git a/internal/review/flat_layout.go b/internal/review/flat_layout.go index 5a31d5f..7696372 100644 --- a/internal/review/flat_layout.go +++ b/internal/review/flat_layout.go @@ -68,14 +68,14 @@ type flatLine struct{ zones []flatZone } // vertical extents and centres within five pixels. Compare to the first zone // so a staircase of overlapping objects cannot merge separate text rows. func buildFlatLines(ctx context.Context, nodes []atspi.TreeNode) ([]flatLine, error) { - lines, _, err := build_flat_layout(ctx, nodes) + lines, _, err := buildFlatLayout(ctx, nodes) return lines, err } -func build_flat_layout(ctx context.Context, nodes []atspi.TreeNode) ([]flatLine, FlatCompleteness, error) { +func buildFlatLayout(ctx context.Context, nodes []atspi.TreeNode) ([]flatLine, FlatCompleteness, error) { var status FlatCompleteness - parents, nodeClips, hidden := flat_node_visibility(nodes) - zones, err := collect_flat_zones(ctx, nodes, parents, nodeClips, hidden, &status) + parents, nodeClips, hidden := flatNodeVisibility(nodes) + zones, err := collectFlatZones(ctx, nodes, parents, nodeClips, hidden, &status) if err != nil { return nil, status, err } @@ -87,7 +87,7 @@ func build_flat_layout(ctx context.Context, nodes []atspi.TreeNode) ([]flatLine, } return nil, status, ErrUnavailableReview } - lines, err := arrange_flat_lines(ctx, nodes, zones) + lines, err := arrangeFlatLines(ctx, nodes, zones) return lines, status, err } @@ -107,8 +107,8 @@ func sameFlatLine(a, b flatZone) bool { return delta >= -10 && delta <= 10 } -// flat_node_visibility follows parent clipping before collecting any text. -func flat_node_visibility(nodes []atspi.TreeNode) (map[atspi.ObjectID]atspi.Snapshot, map[atspi.ObjectID]atspi.Rectangle, map[atspi.ObjectID]bool) { +// flatNodeVisibility follows parent clipping before collecting any text. +func flatNodeVisibility(nodes []atspi.TreeNode) (map[atspi.ObjectID]atspi.Snapshot, map[atspi.ObjectID]atspi.Rectangle, map[atspi.ObjectID]bool) { parents := make(map[atspi.ObjectID]atspi.Snapshot, len(nodes)) clips := make(map[atspi.ObjectID]atspi.Rectangle, len(nodes)) nodeClips := make(map[atspi.ObjectID]atspi.Rectangle, len(nodes)) @@ -144,9 +144,9 @@ func flat_node_visibility(nodes []atspi.TreeNode) (map[atspi.ObjectID]atspi.Snap return parents, nodeClips, hidden } -// collect_flat_zones walks children before parents to avoid repeating container +// collectFlatZones walks children before parents to avoid repeating container // names and text. Password contents and partly clipped native runs stay excluded. -func collect_flat_zones(ctx context.Context, nodes []atspi.TreeNode, parents map[atspi.ObjectID]atspi.Snapshot, nodeClips map[atspi.ObjectID]atspi.Rectangle, hidden map[atspi.ObjectID]bool, status *FlatCompleteness) ([]flatZone, error) { +func collectFlatZones(ctx context.Context, nodes []atspi.TreeNode, parents map[atspi.ObjectID]atspi.Snapshot, nodeClips map[atspi.ObjectID]atspi.Rectangle, hidden map[atspi.ObjectID]bool, status *FlatCompleteness) ([]flatZone, error) { var zones []flatZone textBytes := 0 hasContent := make(map[atspi.ObjectID]bool, len(nodes)) @@ -163,7 +163,7 @@ func collect_flat_zones(ctx context.Context, nodes []atspi.TreeNode, parents map if hasContent[id] { hasContent[parent.ID()] = true } - if labelContent[id] && !flat_label_control(n.Snapshot.Role) { + if labelContent[id] && !flatLabelControl(n.Snapshot.Role) { labelContent[parent.ID()] = true } if hidden[id] { @@ -264,7 +264,7 @@ func collect_flat_zones(ctx context.Context, nodes []atspi.TreeNode, parents map if len(zones) > before || hasContent[id] { hasContent[parent.ID()] = true } - if !flat_label_control(n.Snapshot.Role) && (len(zones) > before || labelContent[id]) { + if !flatLabelControl(n.Snapshot.Role) && (len(zones) > before || labelContent[id]) { labelContent[parent.ID()] = true } } @@ -273,7 +273,7 @@ func collect_flat_zones(ctx context.Context, nodes []atspi.TreeNode, parents map // Named child controls represent independent actions rather than their // enclosing control's label. Text/label descendants retain normal deduplication. -func flat_label_control(role string) bool { +func flatLabelControl(role string) bool { switch role { case "button", "push button", "toggle button", "check box", "radio button", "page tab", "menu item", "check menu item", "radio menu item": @@ -282,9 +282,9 @@ func flat_label_control(role string) bool { return false } -// arrange_flat_lines keeps stable provider order for geometry ties and computes +// arrangeFlatLines keeps stable provider order for geometry ties and computes // Unicode word spans only after all bounded content has been collected. -func arrange_flat_lines(ctx context.Context, nodes []atspi.TreeNode, zones []flatZone) ([]flatLine, error) { +func arrangeFlatLines(ctx context.Context, nodes []atspi.TreeNode, zones []flatZone) ([]flatLine, error) { if len(zones) == 0 { return nil, ErrNoReviewContent } diff --git a/internal/review/flat_robustness_test.go b/internal/review/flat_robustness_test.go index 66b5a9c..2db7be3 100644 --- a/internal/review/flat_robustness_test.go +++ b/internal/review/flat_robustness_test.go @@ -146,7 +146,7 @@ func TestFlatReviewCompositeControlKeepsLabelBesideChildAction(t *testing.T) { nodes[0] = parent nodes = append(nodes, label) } - lines, status, err := build_flat_layout(context.Background(), nodes) + lines, status, err := buildFlatLayout(context.Background(), nodes) if err != nil || status.Incomplete() { t.Fatalf("layout: %+v %v", status, err) } diff --git a/internal/review/flat_worker.go b/internal/review/flat_worker.go index fc67a71..cd201a5 100644 --- a/internal/review/flat_worker.go +++ b/internal/review/flat_worker.go @@ -122,7 +122,7 @@ func (worker *Worker) readFlat(ctx context.Context, cursor *FlatCursor, tree *at if !cursor.seek(origin, offset, true) { if !cursor.seek(origin, 0, false) { if !cursor.seekDescendant(origin) { - cursor.seek_ancestor(origin) + cursor.seekAncestor(origin) } } } diff --git a/internal/review/interest.go b/internal/review/interest.go index dbcf025..09724a6 100644 --- a/internal/review/interest.go +++ b/internal/review/interest.go @@ -74,7 +74,7 @@ func (worker *Worker) ObjectOfInterest(ctx context.Context) (Interest, error) { } } -func resolve_interest(ctx context.Context, focus atspi.ObjectID, explicit interestMode, cursor *Cursor, flat *FlatCursor, flatTree *atspi.AccessibleTree, document *DocumentCursor) (Interest, error) { +func resolveInterest(ctx context.Context, focus atspi.ObjectID, explicit interestMode, cursor *Cursor, flat *FlatCursor, flatTree *atspi.AccessibleTree, document *DocumentCursor) (Interest, error) { if err := ctx.Err(); err != nil { return Interest{}, err } diff --git a/internal/review/interest_test.go b/internal/review/interest_test.go index 559ff0f..381bf25 100644 --- a/internal/review/interest_test.go +++ b/internal/review/interest_test.go @@ -103,14 +103,14 @@ func TestInterestPrefersVirtualCaretThenExplicitReview(t *testing.T) { if _, err := document.MoveCaret(ctx, reader, CaretNextLine); err != nil { t.Fatal(err) } - got, err := resolve_interest(ctx, webID("/text"), 0, nil, nil, nil, document) + got, err := resolveInterest(ctx, webID("/text"), 0, nil, nil, nil, document) if err != nil || got.Object != webID("/next") { t.Fatalf("virtual caret: %+v %v", got, err) } cursor, _ := NewCursor(newTree(t)) cursor.SyncFocus(objectID("/first")) cursor.Move(NextSibling) - got, err = resolve_interest(ctx, webID("/text"), 1, cursor, nil, nil, document) + got, err = resolveInterest(ctx, webID("/text"), 1, cursor, nil, nil, document) if err != nil || got.Object != objectID("/second") { t.Fatalf("explicit precedence: %+v %v", got, err) } diff --git a/internal/review/read_all.go b/internal/review/read_all.go index 77c0fea..2f5ee4d 100644 --- a/internal/review/read_all.go +++ b/internal/review/read_all.go @@ -37,10 +37,10 @@ func (worker *Worker) readAll(ctx context.Context, cursor *DocumentCursor) Resul result.Err = ErrNoCurrent } if documentNeedsCapture(result.Err) { - cursor, result.Err = worker.refresh_read_all_cursor(ctx, cursor, result.DocumentFocus) + cursor, result.Err = worker.refreshReadAllCursor(ctx, cursor, result.DocumentFocus) } if documentNeedsCapture(result.Err) { - cursor, result.Err = worker.refresh_read_all_cursor(ctx, cursor, result.DocumentFocus) + cursor, result.Err = worker.refreshReadAllCursor(ctx, cursor, result.DocumentFocus) } if errors.Is(result.Err, atspi.ErrNotInDocument) { if reader, ok := worker.nativeCapturerFor(result.DocumentFocus).(interface { @@ -123,7 +123,7 @@ func (worker *Worker) readAll(ctx context.Context, cursor *DocumentCursor) Resul result.Err = err return result } - refreshed, refreshErr := worker.refresh_read_all_cursor(ctx, cursor, result.DocumentFocus) + refreshed, refreshErr := worker.refreshReadAllCursor(ctx, cursor, result.DocumentFocus) if refreshErr != nil { result.Err = refreshErr return result @@ -164,7 +164,7 @@ func (worker *Worker) readAllMove(ctx context.Context, cursor *DocumentCursor, r if err == nil || !documentNeedsCapture(err) { return movement, cursor, err } - cursor, refreshErr := worker.refresh_read_all_cursor(ctx, cursor, focus) + cursor, refreshErr := worker.refreshReadAllCursor(ctx, cursor, focus) if refreshErr != nil { return movement, cursor, refreshErr } diff --git a/internal/review/where_am_i.go b/internal/review/where_am_i.go index f6b5209..5d29fc6 100644 --- a/internal/review/where_am_i.go +++ b/internal/review/where_am_i.go @@ -34,7 +34,7 @@ func (worker *Worker) ReadWhereAmI(revision uint64) error { } } -func (worker *Worker) read_where_am_i(ctx context.Context, request request) Result { +func (worker *Worker) readWhereAmI(ctx context.Context, request request) Result { result := Result{WhereAmI: true, WhereAmIRevision: request.whereAmIRevision, DocumentFocus: request.readFocus} if !result.DocumentFocus.Valid() || result.DocumentFocus != worker.Focus() { result.Err = ErrNoCurrent diff --git a/internal/review/where_am_i_test.go b/internal/review/where_am_i_test.go index 3e87d98..808e08c 100644 --- a/internal/review/where_am_i_test.go +++ b/internal/review/where_am_i_test.go @@ -56,7 +56,7 @@ func TestWhereAmIRejectsChangedFocusBeforeCapture(t *testing.T) { t.Fatal("missing focus queued a native request") } worker.SyncFocus(webID("/new")) - result := worker.read_where_am_i(t.Context(), request{readFocus: webID("/old")}) + result := worker.readWhereAmI(t.Context(), request{readFocus: webID("/old")}) if result.Err == nil || capturer.reads != 0 { t.Fatal("retired focus started a native capture") } diff --git a/internal/review/worker.go b/internal/review/worker.go index ef49c27..106ef34 100644 --- a/internal/review/worker.go +++ b/internal/review/worker.go @@ -345,7 +345,7 @@ func (worker *Worker) run(ctx context.Context, done chan<- struct{}) { continue } if request.interest != nil { - interest, err := resolve_interest(request.interest.ctx, interestFocus, explicitInterest, cursor, flat, flatTree, document) + interest, err := resolveInterest(request.interest.ctx, interestFocus, explicitInterest, cursor, flat, flatTree, document) worker.stateMutex.Lock() currentFocus, currentRevision := worker.latestFocus, worker.focusRevision worker.stateMutex.Unlock() @@ -370,14 +370,14 @@ func (worker *Worker) run(ctx context.Context, done chan<- struct{}) { } var result Result if request.whereAmI { - result = worker.read_where_am_i(ctx, request) + result = worker.readWhereAmI(ctx, request) } else if request.currentLine { - result = worker.read_current_line(ctx, document, request.currentLineBrowse) + result = worker.readCurrentLine(ctx, document, request.currentLineBrowse) result.FlatSpeech = request.flatSpeech } else if request.listSelection != nil { result, document = worker.selectDocumentList(ctx, document, request.listSelection) } else if request.brailleRoute != nil { - result = worker.route_document_braille(ctx, document, request) + result = worker.routeDocumentBraille(ctx, document, request) } else if request.nativeCaret { result, document = worker.syncDocumentCaret(ctx, document, request) } else if request.readPosition != nil { diff --git a/internal/sound/indentation.go b/internal/sound/indentation.go index eed0991..86b5bef 100644 --- a/internal/sound/indentation.go +++ b/internal/sound/indentation.go @@ -13,13 +13,13 @@ import ( const indentationCuePrefix = "generated-indentation-tone:" func IndentationCueName(frequency int) string { return indentationCuePrefix + strconv.Itoa(frequency) } -func indentation_frequency(name string) (int, bool) { +func indentationFrequency(name string) (int, bool) { if !strings.HasPrefix(name, indentationCuePrefix) { return 0, false } frequency, err := strconv.Atoi(strings.TrimPrefix(name, indentationCuePrefix)) return frequency, err == nil && frequency >= 100 && frequency <= 2750 } -func indentation_tone_wav(frequency int) []byte { - return tone_wav(float64(frequency), 150*time.Millisecond, .7, 5*time.Millisecond) +func indentationToneWav(frequency int) []byte { + return toneWav(float64(frequency), 150*time.Millisecond, .7, 5*time.Millisecond) } diff --git a/internal/sound/indentation_test.go b/internal/sound/indentation_test.go index d715545..ad12a56 100644 --- a/internal/sound/indentation_test.go +++ b/internal/sound/indentation_test.go @@ -18,7 +18,7 @@ func TestIndentationToneIsBoundedAndHonorsSoundPolicy(t *testing.T) { if err != nil || len(data) != 44+3307*2 || binary.LittleEndian.Uint32(data[24:]) != 22050 { t.Fatalf("indentation WAV: bytes %d, error %v", len(data), err) } - if !service.cue_available(name) || !generated_tone(name) { + if !service.cueAvailable(name) || !generatedTone(name) { t.Fatal("generated indentation unavailable") } } @@ -26,11 +26,11 @@ func TestIndentationToneIsBoundedAndHonorsSoundPolicy(t *testing.T) { t.Fatal("unbounded pitch accepted") } service.Configure(Configuration{Enabled: false, Theme: "default", Volume: .5}) - if service.cue_available(IndentationCueName(200)) { + if service.cueAvailable(IndentationCueName(200)) { t.Fatal("disabled sound played indentation") } service.Configure(Configuration{Enabled: true, Theme: "none", Volume: .5}) - if service.cue_available(IndentationCueName(200)) { + if service.cueAvailable(IndentationCueName(200)) { t.Fatal("None theme played indentation") } } diff --git a/internal/sound/position.go b/internal/sound/position.go index c19b8de..12d5964 100644 --- a/internal/sound/position.go +++ b/internal/sound/position.go @@ -18,7 +18,7 @@ func PositionCueName(position float64) string { return positionCuePrefix + strconv.FormatFloat(position, 'g', -1, 64) } -func set_position(cue string) (float64, bool) { +func setPosition(cue string) (float64, bool) { if !strings.HasPrefix(cue, positionCuePrefix) { return 0, false } @@ -26,8 +26,8 @@ func set_position(cue string) (float64, bool) { return position, err == nil && !math.IsNaN(position) && !math.IsInf(position, 0) && position >= 0 && position <= 1 } -func position_tone_wav(position float64) []byte { +func positionToneWav(position float64) []byte { // Two octaves distinguish the ends of a set. Smooth the edges of this // short cue; the service supplies the user's volume and stereo position. - return tone_wav(220*math.Pow(4, position), 60*time.Millisecond, 0.5, 5*time.Millisecond) + return toneWav(220*math.Pow(4, position), 60*time.Millisecond, 0.5, 5*time.Millisecond) } diff --git a/internal/sound/progress.go b/internal/sound/progress.go index 55878af..5038c6b 100644 --- a/internal/sound/progress.go +++ b/internal/sound/progress.go @@ -18,7 +18,7 @@ func ProgressCueName(percentage float64) string { return progressCuePrefix + strconv.FormatFloat(percentage, 'g', -1, 64) } -func progress_percentage(cue string) (float64, bool) { +func progressPercentage(cue string) (float64, bool) { if !strings.HasPrefix(cue, progressCuePrefix) { return 0, false } @@ -26,5 +26,5 @@ func progress_percentage(cue string) (float64, bool) { return percentage, err == nil && !math.IsNaN(percentage) && !math.IsInf(percentage, 0) && percentage >= 0 && percentage <= 100 } -func progress_tone_wav(percentage float64) []byte { return tones.ProgressWAV(percentage) } -func nvda_tone_wav(hz float64, milliseconds int) []byte { return tones.NVDAWAV(hz, milliseconds) } +func progressToneWav(percentage float64) []byte { return tones.ProgressWAV(percentage) } +func nvdaToneWav(hz float64, milliseconds int) []byte { return tones.NVDAWAV(hz, milliseconds) } diff --git a/internal/sound/progress_test.go b/internal/sound/progress_test.go index dc94bef..ecf456f 100644 --- a/internal/sound/progress_test.go +++ b/internal/sound/progress_test.go @@ -32,7 +32,7 @@ func (player *progressTestPlayer) Play(ctx context.Context, data []byte, _, _ fl } } -func new_progress_test_service(t *testing.T) (*Service, *progressTestPlayer) { +func newProgressTestService(t *testing.T) (*Service, *progressTestPlayer) { t.Helper() player := &progressTestPlayer{started: make(chan progressPlayback, 16), release: make(chan struct{}, 16)} service := New(slog.New(slog.DiscardHandler), player, "none", 0) @@ -49,7 +49,7 @@ func new_progress_test_service(t *testing.T) (*Service, *progressTestPlayer) { return service, player } -func next_progress_playback(t *testing.T, player *progressTestPlayer) progressPlayback { +func nextProgressPlayback(t *testing.T, player *progressTestPlayer) progressPlayback { t.Helper() select { case playback := <-player.started: @@ -61,9 +61,9 @@ func next_progress_playback(t *testing.T, player *progressTestPlayer) progressPl } func TestRapidProgressFinishesActiveToneAndPlaysLatestValue(t *testing.T) { - service, player := new_progress_test_service(t) + service, player := newProgressTestService(t) service.Enqueue(Cue{Name: ProgressCueName(0)}) - first := next_progress_playback(t, player) + first := nextProgressPlayback(t, player) for percentage := 1; percentage <= 100; percentage++ { if !service.EnqueueBatch([]Cue{{Name: ProgressCueName(float64(percentage))}}) { t.Fatal("rapid progress update rejected") @@ -73,32 +73,32 @@ func TestRapidProgressFinishesActiveToneAndPlaysLatestValue(t *testing.T) { t.Fatalf("rapid updates canceled the active progress tone: %v", err) } player.release <- struct{}{} - latest := next_progress_playback(t, player) - if !bytes.Equal(latest.data, progress_tone_wav(100)) { + latest := nextProgressPlayback(t, player) + if !bytes.Equal(latest.data, progressToneWav(100)) { t.Fatal("played an obsolete percentage instead of the latest value") } } func TestProgressPreservesActiveAndPendingRoleSounds(t *testing.T) { - service, player := new_progress_test_service(t) + service, player := newProgressTestService(t) service.mutex.Lock() service.enabled, service.theme, service.volume = true, "default", 0.5 service.available = map[string]bool{"button": true, "link": true} service.mutex.Unlock() service.EnqueueBatch([]Cue{{Name: "button"}, {Name: "link"}}) - first := next_progress_playback(t, player) + first := nextProgressPlayback(t, player) service.Enqueue(Cue{Name: ProgressCueName(100)}) if err := first.context.Err(); err != nil { t.Fatalf("progress interrupted a role sound: %v", err) } player.release <- struct{}{} - second := next_progress_playback(t, player) - want, err := load_sound("default", "link") + second := nextProgressPlayback(t, player) + want, err := loadSound("default", "link") if err != nil || !bytes.Equal(second.data, want) { t.Fatal("progress displaced a pending role sound") } player.release <- struct{}{} - if got := next_progress_playback(t, player); !bytes.Equal(got.data, progress_tone_wav(100)) { + if got := nextProgressPlayback(t, player); !bytes.Equal(got.data, progressToneWav(100)) { t.Fatal("latest progress did not follow the role sounds") } } @@ -106,9 +106,9 @@ func TestProgressPreservesActiveAndPendingRoleSounds(t *testing.T) { func TestProgressCancellationDiscardsPendingValue(t *testing.T) { for _, action := range []string{"presentation", "configure", "stop"} { t.Run(action, func(t *testing.T) { - service, player := new_progress_test_service(t) + service, player := newProgressTestService(t) service.Enqueue(Cue{Name: ProgressCueName(0)}) - first := next_progress_playback(t, player) + first := nextProgressPlayback(t, player) service.Enqueue(Cue{Name: ProgressCueName(100)}) switch action { case "presentation": diff --git a/internal/sound/service.go b/internal/sound/service.go index 39f18d3..130b88e 100644 --- a/internal/sound/service.go +++ b/internal/sound/service.go @@ -99,7 +99,7 @@ func (service *Service) Configure(configuration Configuration) { func (service *Service) Available(name string) bool { service.mutex.Lock() defer service.mutex.Unlock() - return service.running && service.cue_available(name) + return service.running && service.cueAvailable(name) } func (service *Service) Start(ctx context.Context) error { @@ -140,12 +140,12 @@ func (service *Service) EnqueueBatch(cues []Cue) bool { return false } for _, cue := range cues { - if !service.cue_available(cue.Name) { + if !service.cueAvailable(cue.Name) { return false } } if len(cues) == 1 { - if _, progress := progress_percentage(cues[0].Name); progress { + if _, progress := progressPercentage(cues[0].Name); progress { cue := cues[0] cue.Pan = normalizedPan(cue.Pan) service.pendingProgress = &queuedCue{Cue: cue, generation: service.generation} @@ -184,7 +184,7 @@ func (service *Service) discardPending() { func (service *Service) run(ctx context.Context, done chan struct{}) { defer close(done) for { - cue, ok := service.next_cue(ctx) + cue, ok := service.nextCue(ctx) if !ok { return } @@ -199,7 +199,7 @@ func (service *Service) run(ctx context.Context, done chan struct{}) { // Preserve the order of ordinary presentation cues before taking the newest // progress value. progressWake is only a notification; mutex owns the slot. -func (service *Service) next_cue(ctx context.Context) (queuedCue, bool) { +func (service *Service) nextCue(ctx context.Context) (queuedCue, bool) { for { if ctx.Err() != nil { return queuedCue{}, false @@ -229,12 +229,12 @@ func (service *Service) next_cue(ctx context.Context) (queuedCue, bool) { func (service *Service) playQueued(ctx context.Context, cue queuedCue) error { service.mutex.Lock() - if cue.generation != service.generation || !service.running || !service.cue_available(cue.Name) { + if cue.generation != service.generation || !service.running || !service.cueAvailable(cue.Name) { service.mutex.Unlock() return nil } player, theme, volume := service.player, service.theme, service.volume - if _, valid := progress_percentage(cue.Name); valid { + if _, valid := progressPercentage(cue.Name); valid { volume = 1 } cacheKey := theme + "\x00" + cue.Name @@ -259,7 +259,7 @@ func (service *Service) playQueued(ctx context.Context, cue queuedCue) error { return err } service.mutex.Lock() - if !generated_tone(cue.Name) { + if !generatedTone(cue.Name) { service.cache[cacheKey] = data } service.mutex.Unlock() @@ -274,7 +274,7 @@ func (service *Service) playQueued(ctx context.Context, cue queuedCue) error { func (service *Service) play(ctx context.Context, cue Cue) error { service.mutex.Lock() player, theme, volume := service.player, service.theme, service.volume - if _, valid := progress_percentage(cue.Name); valid { + if _, valid := progressPercentage(cue.Name); valid { volume = 1 } cacheKey := theme + "\x00" + cue.Name @@ -287,7 +287,7 @@ func (service *Service) play(ctx context.Context, cue Cue) error { return err } service.mutex.Lock() - if !generated_tone(cue.Name) { + if !generatedTone(cue.Name) { service.cache[cacheKey] = data } service.mutex.Unlock() @@ -313,7 +313,7 @@ var namedCues = []string{ func cueAvailability(theme string) map[string]bool { available := make(map[string]bool, len(namedCues)) for _, name := range namedCues { - if data, err := load_sound(theme, name); err == nil && len(data) <= maxSoundBytes { + if data, err := loadSound(theme, name); err == nil && len(data) <= maxSoundBytes { available[name] = true } } @@ -322,49 +322,49 @@ func cueAvailability(theme string) map[string]bool { // Called under the service mutex. Progress output is controlled by its own // output mode, independent of role-sound enablement, theme and volume. -func (service *Service) cue_available(name string) bool { - if _, valid := indentation_frequency(name); valid { +func (service *Service) cueAvailable(name string) bool { + if _, valid := indentationFrequency(name); valid { return service.enabled && service.theme != "none" && service.volume > 0 } - if _, valid := progress_percentage(name); valid { + if _, valid := progressPercentage(name); valid { return true } - if _, valid := set_position(name); valid { + if _, valid := setPosition(name); valid { return service.enabled && service.theme != "none" && service.volume > 0 } return service.enabled && service.available[name] } -func generated_tone(name string) bool { - _, indentation := indentation_frequency(name) - _, progress := progress_percentage(name) - _, position := set_position(name) +func generatedTone(name string) bool { + _, indentation := indentationFrequency(name) + _, progress := progressPercentage(name) + _, position := setPosition(name) return progress || position || indentation } func soundData(theme, cue string) ([]byte, error) { if strings.HasPrefix(cue, indentationCuePrefix) { - frequency, valid := indentation_frequency(cue) + frequency, valid := indentationFrequency(cue) if !valid { return nil, errors.New("invalid generated indentation tone") } - return indentation_tone_wav(frequency), nil + return indentationToneWav(frequency), nil } if strings.HasPrefix(cue, positionCuePrefix) { - position, valid := set_position(cue) + position, valid := setPosition(cue) if !valid { return nil, errors.New("invalid generated position tone") } - return position_tone_wav(position), nil + return positionToneWav(position), nil } if strings.HasPrefix(cue, progressCuePrefix) { - percentage, valid := progress_percentage(cue) + percentage, valid := progressPercentage(cue) if !valid { return nil, errors.New("invalid generated progress tone") } - return progress_tone_wav(percentage), nil + return progressToneWav(percentage), nil } - return load_sound(theme, cue) + return loadSound(theme, cue) } // Stop cancels any active cue, discards pending cues, and plays the stop cue @@ -405,7 +405,7 @@ func (service *Service) Stop(ctx context.Context) error { return nil } -func load_sound(theme, cue string) ([]byte, error) { +func loadSound(theme, cue string) ([]byte, error) { if filepath.Base(theme) != theme || theme == "." || theme == ".." || filepath.Base(cue) != cue || cue == "." || cue == ".." { return nil, errors.New("invalid sound theme or cue name") } diff --git a/internal/sound/service_test.go b/internal/sound/service_test.go index b22607a..b0f6320 100644 --- a/internal/sound/service_test.go +++ b/internal/sound/service_test.go @@ -19,7 +19,7 @@ func TestBundledSoundsDecodeInProcess(t *testing.T) { } for _, cue := range []string{"start", "stop", "autocomplete", "button", "checkbox_checked", "checkbox_mixed", "checkbox_unchecked", "combobox", "link", "link_visited", "radiobutton_checked", "radiobutton_unchecked", "togglebutton_checked", "togglebutton_unchecked", "switch_on", "switch_off", "browse_mode", "focus_mode"} { t.Run(cue, func(t *testing.T) { - data, err := load_sound("default", cue) + data, err := loadSound("default", cue) if err != nil { t.Fatal(err) } @@ -53,7 +53,7 @@ func TestGeneratedProgressSoundsDecodeInProcess(t *testing.T) { } func TestBundledSoundPanDecodes(t *testing.T) { - data, err := load_sound("default", "button") + data, err := loadSound("default", "button") if err != nil { t.Fatal(err) } @@ -70,10 +70,10 @@ func TestBundledSoundPanDecodes(t *testing.T) { func TestThemePathsAndSizeAreBounded(t *testing.T) { t.Setenv("XDG_DATA_HOME", t.TempDir()) for _, name := range []string{"..", "../other", "/tmp/other"} { - if _, err := load_sound(name, "start"); err == nil { + if _, err := loadSound(name, "start"); err == nil { t.Fatalf("accepted theme %q", name) } - if _, err := load_sound("default", name); err == nil { + if _, err := loadSound("default", name); err == nil { t.Fatalf("accepted cue %q", name) } } @@ -84,14 +84,14 @@ func TestThemePathsAndSizeAreBounded(t *testing.T) { if err := os.WriteFile(filepath.Join(path, "start.wav"), []byte("custom"), 0o600); err != nil { t.Fatal(err) } - data, err := load_sound("custom", "start") + data, err := loadSound("custom", "start") if err != nil || string(data) != "custom" { t.Fatalf("custom theme = %q, %v", data, err) } if err := os.WriteFile(filepath.Join(path, "start.wav"), make([]byte, maxSoundBytes+1), 0o600); err != nil { t.Fatal(err) } - if _, err := load_sound("custom", "start"); err == nil { + if _, err := loadSound("custom", "start"); err == nil { t.Fatal("accepted oversized sound") } } @@ -191,7 +191,7 @@ func TestNewPresentationInterruptsOldCueAndDiscardsPendingCues(t *testing.T) { case <-time.After(time.Second): t.Fatal("initial cue was not interrupted") } - want, err := load_sound("default", "link") + want, err := loadSound("default", "link") if err != nil { t.Fatal(err) } @@ -481,7 +481,7 @@ func TestSoundWorkerBoundsQueueAndStopsActiveCue(t *testing.T) { } func TestStopPlaysShutdownCueAfterOversizedPresentation(t *testing.T) { - stopData, err := load_sound("default", "stop") + stopData, err := loadSound("default", "stop") if err != nil { t.Fatal(err) } @@ -522,7 +522,7 @@ func TestStopPlaysShutdownCueAfterOversizedPresentation(t *testing.T) { } func TestStopTimeoutPreservesShutdownCueForRetry(t *testing.T) { - stopData, err := load_sound("default", "stop") + stopData, err := loadSound("default", "stop") if err != nil { t.Fatal(err) } @@ -602,7 +602,7 @@ func TestLiveSound(t *testing.T) { t.Skip("explicit live audio test") } for _, cue := range []string{"start", "stop"} { - data, err := load_sound("default", cue) + data, err := loadSound("default", cue) if err != nil { t.Fatal(err) } diff --git a/internal/sound/speech_beep.go b/internal/sound/speech_beep.go index a549d13..28ea2ed 100644 --- a/internal/sound/speech_beep.go +++ b/internal/sound/speech_beep.go @@ -9,23 +9,23 @@ import ( "time" ) -var speechBeepWAV = tone_wav(440, 40*time.Millisecond, 0.35, 5*time.Millisecond) -var capitalBeepWAV = nvda_tone_wav(2000, 50) +var speechBeepWAV = toneWav(440, 40*time.Millisecond, 0.35, 5*time.Millisecond) +var capitalBeepWAV = nvdaToneWav(2000, 50) // SpeechBeep replaces an utterance, independently of role-sound enablement or // theme availability. The speech worker owns its ordering and cancellation; // sound preferences still supply the output sink and volume. func (service *Service) SpeechBeep(ctx context.Context) error { - return service.play_speech_beep(ctx, speechBeepWAV) + return service.playSpeechBeep(ctx, speechBeepWAV) } // CapitalBeep is ordered and canceled by the speech worker, just like speech. // It uses sound volume and sink, independently of the role sound theme. func (service *Service) CapitalBeep(ctx context.Context) error { - return service.play_speech_beep(ctx, capitalBeepWAV) + return service.playSpeechBeep(ctx, capitalBeepWAV) } -func (service *Service) play_speech_beep(ctx context.Context, data []byte) error { +func (service *Service) playSpeechBeep(ctx context.Context, data []byte) error { service.mutex.Lock() player, volume := service.player, service.volume service.mutex.Unlock() diff --git a/internal/sound/tone.go b/internal/sound/tone.go index 1fd856c..1abea13 100644 --- a/internal/sound/tone.go +++ b/internal/sound/tone.go @@ -10,6 +10,6 @@ import ( "git.stormux.org/storm/screenreader-common/tones" ) -func tone_wav(frequency float64, duration time.Duration, amplitude float64, ramp time.Duration) []byte { +func toneWav(frequency float64, duration time.Duration, amplitude float64, ramp time.Duration) []byte { return tones.SineWAV(frequency, duration, amplitude, ramp) } diff --git a/internal/speech/hardware.go b/internal/speech/hardware.go index 3cf8216..fd2895c 100644 --- a/internal/speech/hardware.go +++ b/internal/speech/hardware.go @@ -7,46 +7,53 @@ package speech import ( "context" "errors" - "fmt" - "path/filepath" - "strings" "sync" - "syscall" "time" "git.stormux.org/storm/screenreader-common/hardware" + "git.stormux.org/storm/screenreader-common/hardware/transport" ) -// Hardware ports Python Cthulhu's serial protocols. One owner serializes text -// and settings; cancellation retires a blocked write before sending Ctrl+X. +// unpacedWriteTimeout bounds one utterance on serial synthesizers without +// flow control, where a write that cannot drain means the device is gone. +// DECtalk serial uses XON/XOFF and may pause output for as long as its +// buffer takes to speak, so it, like DECtalk USB, relies on cancellation. +const unpacedWriteTimeout = 5 * time.Second + +// Hardware drives one hardware synthesizer through the shared transport. +// One owner serializes text; cancellation retires a blocked write without +// waiting for it and sends the synthesizer's immediate stop command. type Hardware struct { - mu sync.Mutex - ioMu sync.Mutex - fd int + mu sync.Mutex // Guards generation and closed; never held during I/O. + ioMu sync.Mutex // Serializes utterances. + port transport.Port synth string + protocol hardware.Protocol + paced bool generation uint64 + closed bool } type HardwareVoice struct{ Rate, Pitch, Volume *float64 } +// NewHardware opens synth on device. DECtalk USB ignores device and baud. func NewHardware(device, synth string, baud int) (*Hardware, error) { - if !filepath.IsAbs(device) || strings.ContainsAny(device, "\x00\r\n") { - return nil, errors.New("hardware speech requires an explicit serial device path") - } - switch synth { - case "litetalk", "doubletalk", "tripletalk", "dectalk": - default: - return nil, errors.New("unsupported hardware speech synthesizer") - } - fd, err := open_serial(device, baud) + port, err := transport.Open(synth, device, baud) if err != nil { return nil, err } - return &Hardware{fd: fd, synth: synth}, nil + return &Hardware{port: port, synth: synth, protocol: hardwareProtocol(synth), paced: synth == "dectalk" || synth == "dectalk-usb"}, nil } -func hardware_bytes(synth, text string, voice HardwareVoice) []byte { - profile := hardware.Serial(synth == "dectalk") +func hardwareProtocol(synth string) hardware.Protocol { + if synth == "dectalk-usb" { + return hardware.DECtalkUSB() + } + return hardware.Serial(synth == "dectalk") +} + +func hardwareBytes(synth, text string, voice HardwareVoice) []byte { + profile := hardwareProtocol(synth) var data []byte for _, command := range profile.Commands(hardware.Parameters{Rate: voice.Rate, Pitch: voice.Pitch, Volume: voice.Volume}) { data = append(data, command...) @@ -59,79 +66,61 @@ func (client *Hardware) Speak(ctx context.Context, text string, voice HardwareVo return errors.New("speech text is empty") } client.mu.Lock() - generation := client.generation + generation, closed := client.generation, client.closed client.mu.Unlock() + if closed { + return errors.New("hardware speech is closed") + } + data := hardwareBytes(client.synth, text, voice) + if !client.paced { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, unpacedWriteTimeout) + defer cancel() + } client.ioMu.Lock() defer client.ioMu.Unlock() - return client.write_serial(ctx, hardware_bytes(client.synth, text, voice), generation) -} - -func (client *Hardware) write_serial(ctx context.Context, data []byte, generation uint64) error { - ctx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - for len(data) > 0 { - if err := ctx.Err(); err != nil { - return err + err := client.port.Write(data, func() bool { + if ctx.Err() != nil { + return true } client.mu.Lock() - current := client.generation - client.mu.Unlock() - if generation != current { - return context.Canceled - } - if client.fd < 0 { - return errors.New("hardware speech is closed") - } - written, err := syscall.Write(client.fd, data[:min(256, len(data))]) - if written > 0 { - data = data[written:] - } - if err == syscall.EINTR { - continue - } - if err == syscall.EAGAIN || err == syscall.EWOULDBLOCK { - timer := time.NewTimer(5 * time.Millisecond) - select { - case <-ctx.Done(): - timer.Stop() - return ctx.Err() - case <-timer.C: - } - continue - } - if err != nil { - return fmt.Errorf("write hardware speech: %w", err) - } - if written == 0 { - return errors.New("serial write returned zero bytes") + defer client.mu.Unlock() + return client.closed || client.generation != generation + }) + if errors.Is(err, transport.ErrCanceled) { + if ctx.Err() != nil { + return ctx.Err() } + return context.Canceled } - return nil + return err } +// Cancel retires the current utterance and sends the stop command. It does +// not wait for a blocked write; the transport discards its remaining text. func (client *Hardware) Cancel(ctx context.Context) error { - client.mu.Lock() - client.generation++ - generation := client.generation - client.mu.Unlock() - client.ioMu.Lock() - defer client.ioMu.Unlock() - if client.fd < 0 { - return nil - } - if err := flush_serial(client.fd); err != nil { + if err := ctx.Err(); err != nil { return err } - return client.write_serial(ctx, hardware.Serial(client.synth == "dectalk").Cancel(), generation) + client.mu.Lock() + client.generation++ + closed := client.closed + client.mu.Unlock() + if closed { + return nil + } + return client.port.Cancel(client.protocol.Cancel()) } func (client *Hardware) Close(ctx context.Context) error { result := client.Cancel(ctx) - client.ioMu.Lock() - defer client.ioMu.Unlock() - if client.fd >= 0 { - result = errors.Join(result, syscall.Close(client.fd)) - client.fd = -1 + client.mu.Lock() + if client.closed { + client.mu.Unlock() + return nil } + client.closed = true + client.mu.Unlock() + client.port.Close() return result } diff --git a/internal/speech/hardware_test.go b/internal/speech/hardware_test.go index 1a07b0d..a8fbf60 100644 --- a/internal/speech/hardware_test.go +++ b/internal/speech/hardware_test.go @@ -15,16 +15,16 @@ func TestHardwareProtocolsUseCommonEncoding(t *testing.T) { if synth == "dectalk" { want = "[:ra 650][:dv ap 350][:dv g5 86]Hello !\x0b" } - if got := string(hardware_bytes(synth, "Hello\n\x01é猫!", voice)); got != want { + if got := string(hardwareBytes(synth, "Hello\n\x01é猫!", voice)); got != want { t.Fatalf("%s: got %q, want %q", synth, got, want) } } rate, pitch, volume = -100, -100, -100 - if got := string(hardware_bytes("dectalk", "Low", voice)); got != "[:ra 75][:dv ap 50][:dv g5 60]Low\x0b" { + if got := string(hardwareBytes("dectalk", "Low", voice)); got != "[:ra 75][:dv ap 50][:dv g5 60]Low\x0b" { t.Fatal(got) } rate, pitch, volume = 0, 0, 0 - if got := string(hardware_bytes("litetalk", "Middle", voice)); got != "\x014S\x0150P\x014VMiddle\r" { + if got := string(hardwareBytes("litetalk", "Middle", voice)); got != "\x014S\x0150P\x014VMiddle\r" { t.Fatal(got) } } @@ -33,7 +33,7 @@ func TestDECtalkUsesCommonMidpointAndFiltersCommands(t *testing.T) { rate, pitch, volume := 0.0, 0.0, 0.0 voice := HardwareVoice{Rate: &rate, Pitch: &pitch, Volume: &volume} want := "[:ra 180][:dv ap 122][:dv g5 73]Say [ :dv g5 10]\x0b" - if got := string(hardware_bytes("dectalk", "Say [:dv g5 10]", voice)); got != want { + if got := string(hardwareBytes("dectalk", "Say [:dv g5 10]", voice)); got != want { t.Fatalf("%q, want %q", got, want) } } diff --git a/internal/speech/serial_native.go b/internal/speech/serial_native.go deleted file mode 100644 index 8c24a4e..0000000 --- a/internal/speech/serial_native.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build linux && cgo - -// Copyright (c) 2026 Storm Dragon -// Authors: Storm Dragon, Angus Kola -// SPDX-License-Identifier: GPL-3.0-or-later - -package speech - -/* -#include -#include -#include -#include -#include - -static int cth_serial_open(const char *device, int baud) { - 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: return -EINVAL; - } - int fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC); - if (fd < 0) return -errno; - struct termios attrs; - if (tcgetattr(fd, &attrs) < 0) { int error = errno; close(fd); return -error; } - cfmakeraw(&attrs); - attrs.c_cflag |= CLOCAL | CREAD; - attrs.c_cc[VMIN] = attrs.c_cc[VTIME] = 0; - if (cfsetispeed(&attrs, speed) < 0 || cfsetospeed(&attrs, speed) < 0 || - tcsetattr(fd, TCSANOW, &attrs) < 0) { int error = errno; close(fd); return -error; } - return fd; -} -static int cth_serial_flush(int fd) { return tcflush(fd, TCOFLUSH) < 0 ? errno : 0; } -*/ -import "C" - -import ( - "fmt" - "syscall" - "unsafe" -) - -func open_serial(device string, baud int) (int, error) { - value := C.CString(device) - defer C.free(unsafe.Pointer(value)) - fd := int(C.cth_serial_open(value, C.int(baud))) - if fd < 0 { - return -1, fmt.Errorf("open hardware speech device: %w", syscall.Errno(-fd)) - } - return fd, nil -} - -func flush_serial(fd int) error { - if code := C.cth_serial_flush(C.int(fd)); code != 0 { - return fmt.Errorf("flush hardware speech: %w", syscall.Errno(code)) - } - return nil -} diff --git a/internal/speech/serial_native_test.go b/internal/speech/serial_native_test.go index d421885..49e5993 100644 --- a/internal/speech/serial_native_test.go +++ b/internal/speech/serial_native_test.go @@ -9,6 +9,7 @@ package speech import ( "bytes" "context" + "errors" "fmt" "os" "strings" @@ -18,7 +19,7 @@ import ( "unsafe" ) -func serial_fixture(t *testing.T) (*os.File, string) { +func serialFixture(t *testing.T) (*os.File, string) { t.Helper() fd, err := syscall.Open("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK, 0600) if err != nil { @@ -40,7 +41,7 @@ func serial_fixture(t *testing.T) (*os.File, string) { func TestHardwareSerialWritesCancelsAndCloses(t *testing.T) { for _, synth := range []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} { t.Run(synth, func(t *testing.T) { - master, device := serial_fixture(t) + master, device := serialFixture(t) client, err := NewHardware(device, synth, 9600) if err != nil { t.Fatal(err) @@ -49,7 +50,7 @@ func TestHardwareSerialWritesCancelsAndCloses(t *testing.T) { if err := client.Speak(context.Background(), "Serial test", HardwareVoice{}); err != nil { t.Fatal(err) } - want := hardware_bytes(synth, "Serial test", HardwareVoice{}) + want := hardwareBytes(synth, "Serial test", HardwareVoice{}) master.SetReadDeadline(time.Now().Add(time.Second)) buffer := make([]byte, 256) n, err := master.Read(buffer) @@ -82,7 +83,7 @@ func TestHardwareSerialWritesCancelsAndCloses(t *testing.T) { } func TestHardwareCancellationRetiresBlockedSerialWrite(t *testing.T) { - _, device := serial_fixture(t) + master, device := serialFixture(t) client, err := NewHardware(device, "litetalk", 9600) if err != nil { t.Fatal(err) @@ -90,23 +91,11 @@ func TestHardwareCancellationRetiresBlockedSerialWrite(t *testing.T) { defer client.Close(context.Background()) done := make(chan error, 1) go func() { done <- client.Speak(context.Background(), strings.Repeat("x", 1024*1024), HardwareVoice{}) }() - // Wait until the PTY output queue fills, then use the same cancellation - // path used by keyboard input. No reader drains that queue. - deadline := time.Now().Add(time.Second) - for { - client.mu.Lock() - locked := !client.ioMu.TryLock() - if !locked { - client.ioMu.Unlock() - } - client.mu.Unlock() - if locked { - break - } - if time.Now().After(deadline) { - t.Fatal("serial write did not start") - } - time.Sleep(time.Millisecond) + // One byte proves the write started; nothing drains the rest, so the + // PTY output queue fills and the write blocks. + _ = master.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := master.Read(make([]byte, 1)); err != nil { + t.Fatal("serial write did not start", err) } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() @@ -115,10 +104,30 @@ func TestHardwareCancellationRetiresBlockedSerialWrite(t *testing.T) { } select { case err := <-done: - if err != context.Canceled { + if !errors.Is(err, context.Canceled) { t.Fatalf("blocked write: %v", err) } case <-ctx.Done(): t.Fatal("cancellation did not release serial writer") } } + +func TestHardwareSerialDeviceIsExclusive(t *testing.T) { + _, device := serialFixture(t) + client, err := NewHardware(device, "dectalk", 9600) + if err != nil { + t.Fatal(err) + } + if other, err := NewHardware(device, "dectalk", 9600); err == nil { + other.Close(context.Background()) + t.Fatal("second owner opened a locked device") + } + if err := client.Close(context.Background()); err != nil { + t.Fatal(err) + } + reopened, err := NewHardware(device, "dectalk", 19200) + if err != nil { + t.Fatal("lock survived close", err) + } + reopened.Close(context.Background()) +} diff --git a/internal/speech/serial_unavailable.go b/internal/speech/serial_unavailable.go deleted file mode 100644 index f52e167..0000000 --- a/internal/speech/serial_unavailable.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !linux || !cgo - -// Copyright (c) 2026 Storm Dragon -// Authors: Storm Dragon, Angus Kola -// SPDX-License-Identifier: GPL-3.0-or-later - -package speech - -import "errors" - -func open_serial(string, int) (int, error) { - return -1, errors.New("hardware speech requires Linux and cgo") -} -func flush_serial(int) error { return errors.New("hardware speech requires Linux and cgo") } diff --git a/internal/tentacle/bindings.go b/internal/tentacle/bindings.go index 7d8678d..76e1aa6 100644 --- a/internal/tentacle/bindings.go +++ b/internal/tentacle/bindings.go @@ -20,14 +20,14 @@ type BindingStatus struct { Conflict string // Existing command ID; empty when there is no conflict. } -func binding_layout(name string) input.KeyboardLayout { +func bindingLayout(name string) input.KeyboardLayout { if name == "desktop" { return input.DesktopKeyboardLayout } return input.LaptopKeyboardLayout } -func validate_binding(binding Binding) error { +func validateBinding(binding Binding) error { if (binding.Layout != "desktop" && binding.Layout != "laptop") || (binding.Scope != "global" && binding.Scope != "browse") || len(binding.Key) > 128 { return ErrProtocol @@ -46,7 +46,7 @@ func (session *Session) Bindings() []BindingStatus { // Caller holds manager.mutex, but no session lock. Revoked sessions immediately // stop reserving chords even while their processes are still shutting down. -func (manager *Manager) occupied_bindings() map[input.KeyboardLayout]input.CommandBindings { +func (manager *Manager) occupiedBindings() map[input.KeyboardLayout]input.CommandBindings { occupied := make(map[input.KeyboardLayout]input.CommandBindings) for layout, bindings := range manager.coreBindings { occupied[layout] = make(input.CommandBindings) @@ -60,7 +60,7 @@ func (manager *Manager) occupied_bindings() map[input.KeyboardLayout]input.Comma for _, binding := range session.bindings { if binding.Bound { chord, _ := input.ParseCommandChord(binding.Suggested.Key) - occupied[binding_layout(binding.Suggested.Layout)][chord] = input.Command(binding.Command) + occupied[bindingLayout(binding.Suggested.Layout)][chord] = input.Command(binding.Command) } } } @@ -69,13 +69,13 @@ func (manager *Manager) occupied_bindings() map[input.KeyboardLayout]input.Comma return occupied } -func resolve_bindings(identity string, commands []Command, occupied map[input.KeyboardLayout]input.CommandBindings) []BindingStatus { +func resolveBindings(identity string, commands []Command, occupied map[input.KeyboardLayout]input.CommandBindings) []BindingStatus { var result []BindingStatus for _, command := range commands { commandID := "tentacle/" + identity + "/" + command.ID for _, binding := range command.Bindings { chord, _ := input.ParseCommandChord(binding.Key) - bindings := occupied[binding_layout(binding.Layout)] + bindings := occupied[bindingLayout(binding.Layout)] previous := bindings[chord] result = append(result, BindingStatus{Command: commandID, Suggested: binding, Bound: previous == "", Conflict: string(previous)}) diff --git a/internal/tentacle/containment.go b/internal/tentacle/containment.go index 89935cc..2f92b87 100644 --- a/internal/tentacle/containment.go +++ b/internal/tentacle/containment.go @@ -83,11 +83,11 @@ func NewContainedManager(limits Limits, overrides []input.BindingOverride, paren if _, err := rand.Read(identity[:]); err != nil { return nil, err } - group, err := create_cgroup(filepath.Join(parent, fmt.Sprintf("cthulhu-tentacles-%x", identity)), resources.Total, limits.Processes) + group, err := createCgroup(filepath.Join(parent, fmt.Sprintf("cthulhu-tentacles-%x", identity)), resources.Total, limits.Processes) if err != nil { return nil, err } - if err := write_control(group.path, "cgroup.subtree_control", "+cpu +memory +pids"); err != nil { + if err := writeControl(group.path, "cgroup.subtree_control", "+cpu +memory +pids"); err != nil { return nil, errors.Join(err, group.remove()) } manager.containment = &containment{group: group, limits: resources} @@ -104,24 +104,24 @@ type cgroup struct { file *os.File } -func write_control(path, name, value string) error { +func writeControl(path, name, value string) error { // Do not create ordinary files if the kernel lacks a required controller. file, err := os.OpenFile(filepath.Join(path, name), os.O_WRONLY, 0) if err != nil { return fmt.Errorf("%w: open %s: %w", ErrContainment, name, err) } _, writeError := file.WriteString(value) - return errors.Join(wrap_control_error(name, writeError), wrap_control_error(name, file.Close())) + return errors.Join(wrapControlError(name, writeError), wrapControlError(name, file.Close())) } -func wrap_control_error(name string, err error) error { +func wrapControlError(name string, err error) error { if err == nil { return nil } return fmt.Errorf("%w: %s: %w", ErrContainment, name, err) } -func create_cgroup(path string, budget ResourceBudget, children int) (*cgroup, error) { +func createCgroup(path string, budget ResourceBudget, children int) (*cgroup, error) { if err := os.Mkdir(path, 0700); err != nil { return nil, fmt.Errorf("%w: create group: %w", ErrContainment, err) } @@ -139,7 +139,7 @@ func create_cgroup(path string, budget ResourceBudget, children int) (*cgroup, e settings = append(settings, struct{ name, value string }{"memory.oom.group", "1"}) } for _, setting := range settings { - if err := write_control(path, setting.name, setting.value); err != nil { + if err := writeControl(path, setting.name, setting.value); err != nil { return nil, errors.Join(err, group.remove()) } } @@ -147,14 +147,14 @@ func create_cgroup(path string, budget ResourceBudget, children int) (*cgroup, e // SIGKILL CLONE_INTO_CGROUP children entering a previously killed group. killFile, err := os.OpenFile(filepath.Join(path, "cgroup.kill"), os.O_WRONLY, 0) if err != nil { - return nil, errors.Join(wrap_control_error("open cgroup.kill", err), group.remove()) + return nil, errors.Join(wrapControlError("open cgroup.kill", err), group.remove()) } if err := killFile.Close(); err != nil { - return nil, errors.Join(wrap_control_error("close cgroup.kill", err), group.remove()) + return nil, errors.Join(wrapControlError("close cgroup.kill", err), group.remove()) } file, err := os.Open(path) if err != nil { - return nil, errors.Join(wrap_control_error("open group", err), group.remove()) + return nil, errors.Join(wrapControlError("open group", err), group.remove()) } group.file = file return group, nil @@ -165,19 +165,19 @@ func (group *cgroup) remove() error { _ = group.file.Close() group.file = nil } - return wrap_control_error("remove group", os.Remove(group.path)) + return wrapControlError("remove group", os.Remove(group.path)) } -// kill_and_remove waits only during teardown. Successful removal proves the +// killAndRemove waits only during teardown. Successful removal proves the // kernel no longer has live tasks in the group, including setsid descendants. -func (group *cgroup) kill_and_remove(timeout time.Duration) error { +func (group *cgroup) killAndRemove(timeout time.Duration) error { defer func() { if group.file != nil { _ = group.file.Close() group.file = nil } }() - if err := write_control(group.path, "cgroup.kill", "1"); err != nil { + if err := writeControl(group.path, "cgroup.kill", "1"); err != nil { return err } deadline := time.NewTimer(timeout) diff --git a/internal/tentacle/containment_test.go b/internal/tentacle/containment_test.go index 0b9a06e..6960561 100644 --- a/internal/tentacle/containment_test.go +++ b/internal/tentacle/containment_test.go @@ -42,7 +42,7 @@ func TestContainmentRejectsInvalidConfiguration(t *testing.T) { } } -func contained_manager(t *testing.T, resources ResourceLimits) *Manager { +func containedManager(t *testing.T, resources ResourceLimits) *Manager { t.Helper() parent := os.Getenv("CTHULHU_TENTACLE_CGROUP_PARENT") if parent == "" { @@ -74,7 +74,7 @@ func contained_manager(t *testing.T, resources ResourceLimits) *Manager { return manager } -func resource_peer(t *testing.T, manager *Manager, id string) *Session { +func resourcePeer(t *testing.T, manager *Manager, id string) *Session { t.Helper() python, err := exec.LookPath("python3") if err != nil { @@ -88,7 +88,7 @@ func resource_peer(t *testing.T, manager *Manager, id string) *Session { if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if state, err := session.Status(); state != Ready || err != nil { t.Fatalf("resource peer %s: %v", state, err) } @@ -98,16 +98,16 @@ func resource_peer(t *testing.T, manager *Manager, id string) *Session { return session } -func resource_call(t *testing.T, session *Session, arguments string) Result { +func resourceCall(t *testing.T, session *Session, arguments string) Result { t.Helper() pending, err := session.Invoke(context.Background(), "echo", json.RawMessage(arguments)) if err != nil { t.Fatal(err) } - return wait_result(t, pending) + return waitResult(t, pending) } -func read_control(t *testing.T, path, name string) string { +func readControl(t *testing.T, path, name string) string { t.Helper() data, err := os.ReadFile(filepath.Join(path, name)) if err != nil { @@ -116,9 +116,9 @@ func read_control(t *testing.T, path, name string) string { return strings.TrimSpace(string(data)) } -func control_counter(t *testing.T, path, name, key string) int64 { +func controlCounter(t *testing.T, path, name, key string) int64 { t.Helper() - for _, line := range strings.Split(read_control(t, path, name), "\n") { + for _, line := range strings.Split(readControl(t, path, name), "\n") { fields := strings.Fields(line) if len(fields) == 2 && fields[0] == key { value, err := strconv.ParseInt(fields[1], 10, 64) @@ -132,7 +132,7 @@ func control_counter(t *testing.T, path, name, key string) int64 { return 0 } -func wait_control(t *testing.T, check func() bool) { +func waitControl(t *testing.T, check func() bool) { t.Helper() deadline := time.NewTimer(4 * time.Second) defer deadline.Stop() @@ -148,32 +148,32 @@ func wait_control(t *testing.T, check func() bool) { } func TestNativeContainmentPlacementAndDetachedCleanup(t *testing.T) { - manager := contained_manager(t, DefaultResourceLimits()) - session := resource_peer(t, manager, "detaching") + manager := containedManager(t, DefaultResourceLimits()) + session := resourcePeer(t, manager, "detaching") groupPath := filepath.Join(manager.containment.group.path, session.Identity()) for name, expected := range map[string]string{ "cpu.max": "25000 100000", "memory.max": "268435456", "memory.swap.max": "0", "pids.max": "64", "memory.oom.group": "1", "cgroup.max.descendants": "0", } { - if actual := read_control(t, groupPath, name); actual != expected { + if actual := readControl(t, groupPath, name); actual != expected { t.Fatalf("%s = %s, want %s", name, actual, expected) } } - result := resource_call(t, session, `{}`) + result := resourceCall(t, session, `{}`) var location string if result.Err != nil || json.Unmarshal(result.Value, &location) != nil || !strings.HasSuffix(location, "/"+session.Identity()) { t.Fatalf("child ran outside its group: %+v", result) } - result = resource_call(t, session, `{"action":"detach"}`) + result = resourceCall(t, session, `{"action":"detach"}`) var pid int if result.Err != nil || json.Unmarshal(result.Value, &pid) != nil || pid <= 1 { t.Fatalf("missing detached child: %+v", result) } - if actual := read_control(t, fmt.Sprintf("/proc/%d", pid), "cgroup"); actual != location { + if actual := readControl(t, fmt.Sprintf("/proc/%d", pid), "cgroup"); actual != location { t.Fatalf("detached descendant escaped: %s", actual) } session.Disable() - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Stopped || err != nil { t.Fatalf("cleanup %s: %v", state, err) } @@ -181,7 +181,7 @@ func TestNativeContainmentPlacementAndDetachedCleanup(t *testing.T) { t.Fatalf("session group survived Done: %v", err) } // Kernel exit can remove a task from its cgroup just before /proc shows Z. - wait_control(t, func() bool { + waitControl(t, func() bool { data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) if os.IsNotExist(err) { return true @@ -193,17 +193,17 @@ func TestNativeContainmentPlacementAndDetachedCleanup(t *testing.T) { return found && strings.HasPrefix(tail, "Z ") }) // A new identity can reuse capacity after all descendants are gone. - resource_peer(t, manager, "detaching") + resourcePeer(t, manager, "detaching") } func TestNativeContainmentExec(t *testing.T) { - manager := contained_manager(t, DefaultResourceLimits()) - group, err := create_cgroup(filepath.Join(manager.containment.group.path, "exec-proof"), DefaultResourceLimits().PerSession, 0) + manager := containedManager(t, DefaultResourceLimits()) + group, err := createCgroup(filepath.Join(manager.containment.group.path, "exec-proof"), DefaultResourceLimits().PerSession, 0) if err != nil { t.Fatal(err) } defer func() { - if err := group.kill_and_remove(time.Second); err != nil { + if err := group.killAndRemove(time.Second); err != nil { t.Error(err) } }() @@ -227,22 +227,22 @@ func TestNativeContainmentExec(t *testing.T) { func TestNativeContainmentTaskLimits(t *testing.T) { resources := DefaultResourceLimits() resources.PerSession.Tasks, resources.Total.Tasks = 8, 12 - manager := contained_manager(t, resources) - first := resource_peer(t, manager, "first") - second := resource_peer(t, manager, "second") + manager := containedManager(t, resources) + first := resourcePeer(t, manager, "first") + second := resourcePeer(t, manager, "second") for _, session := range []*Session{first, second} { - if result := resource_call(t, session, `{"action":"tasks"}`); result.Err != nil { + if result := resourceCall(t, session, `{"action":"tasks"}`); result.Err != nil { t.Fatal(result.Err) } } parent := manager.containment.group.path - if count := read_control(t, parent, "pids.current"); count != "12" { + if count := readControl(t, parent, "pids.current"); count != "12" { t.Fatalf("aggregate task limit was not reached: %s", count) } - if count := read_control(t, filepath.Join(parent, first.Identity()), "pids.current"); count != "8" { + if count := readControl(t, filepath.Join(parent, first.Identity()), "pids.current"); count != "8" { t.Fatalf("session task limit was not reached: %s", count) } - if control_counter(t, parent, "pids.events", "max") == 0 { + if controlCounter(t, parent, "pids.events", "max") == 0 { t.Fatal("kernel did not report task limit enforcement") } } @@ -252,23 +252,23 @@ func TestNativeContainmentMemoryLimits(t *testing.T) { t.Run(fmt.Sprintf("aggregate-%t", aggregate), func(t *testing.T) { resources := DefaultResourceLimits() resources.PerSession.MemoryBytes, resources.Total.MemoryBytes = 64<<20, 96<<20 - manager := contained_manager(t, resources) - first := resource_peer(t, manager, "first") + manager := containedManager(t, resources) + first := resourcePeer(t, manager, "first") if aggregate { - second := resource_peer(t, manager, "second") - if result := resource_call(t, first, `{"action":"memory","bytes":50331648}`); result.Err != nil { + second := resourcePeer(t, manager, "second") + if result := resourceCall(t, first, `{"action":"memory","bytes":50331648}`); result.Err != nil { t.Fatal(result.Err) } // The kernel may select either session as the aggregate OOM victim. - resource_call(t, second, `{"action":"memory","bytes":50331648}`) + resourceCall(t, second, `{"action":"memory","bytes":50331648}`) } else { - if result := resource_call(t, first, `{"action":"memory","bytes":100663296}`); result.Err == nil { + if result := resourceCall(t, first, `{"action":"memory","bytes":100663296}`); result.Err == nil { t.Fatal("allocation above session limit succeeded") } - wait_signal(t, first.Done()) + waitSignal(t, first.Done()) } - wait_control(t, func() bool { - return control_counter(t, manager.containment.group.path, "memory.events", "oom_kill") > 0 + waitControl(t, func() bool { + return controlCounter(t, manager.containment.group.path, "memory.events", "oom_kill") > 0 }) }) } @@ -281,50 +281,50 @@ func TestNativeContainmentCPUThrottling(t *testing.T) { if aggregate { resources.PerSession.CPUQuota, resources.Total.CPUQuota = 50000, 50000 } - manager := contained_manager(t, resources) - first := resource_peer(t, manager, "first") + manager := containedManager(t, resources) + first := resourcePeer(t, manager, "first") path := filepath.Join(manager.containment.group.path, first.Identity()) if aggregate { - second := resource_peer(t, manager, "second") - if result := resource_call(t, second, `{"action":"cpu"}`); result.Err != nil { + second := resourcePeer(t, manager, "second") + if result := resourceCall(t, second, `{"action":"cpu"}`); result.Err != nil { t.Fatal(result.Err) } path = manager.containment.group.path } - if result := resource_call(t, first, `{"action":"cpu"}`); result.Err != nil { + if result := resourceCall(t, first, `{"action":"cpu"}`); result.Err != nil { t.Fatal(result.Err) } - wait_control(t, func() bool { return control_counter(t, path, "cpu.stat", "nr_throttled") > 0 }) + waitControl(t, func() bool { return controlCounter(t, path, "cpu.stat", "nr_throttled") > 0 }) }) } } func TestNativeContainmentFailedLaunchReleasesGroups(t *testing.T) { - manager := contained_manager(t, DefaultResourceLimits()) + manager := containedManager(t, DefaultResourceLimits()) session, err := manager.Start(context.Background(), Spec{ID: "missing", Program: []string{"/nonexistent/tentacle-fixture"}}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Failed || err == nil { t.Fatalf("missing executable %s: %v", state, err) } if _, err := os.Stat(filepath.Join(manager.containment.group.path, session.Identity())); !os.IsNotExist(err) { t.Fatalf("failed launch leaked a group: %v", err) } - resource_peer(t, manager, "missing") + resourcePeer(t, manager, "missing") } func TestNativeContainmentSDKRoundTrip(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := contained_manager(t, DefaultResourceLimits()) - program := sdk_program(t, language, filepath.Join(t.TempDir(), "cancelled")) + manager := containedManager(t, DefaultResourceLimits()) + program := sdkProgram(t, language, filepath.Join(t.TempDir(), "cancelled")) session, err := manager.Start(context.Background(), Spec{ID: "sdk", Program: program}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if state, err := session.Status(); state != Ready || err != nil { t.Fatalf("contained SDK startup %s: %v", state, err) } @@ -332,7 +332,7 @@ func TestNativeContainmentSDKRoundTrip(t *testing.T) { t.Fatal(err) } const arguments = `{"text":"é猫😀é"}` - if result := resource_call(t, session, arguments); result.Err != nil || string(result.Value) != arguments { + if result := resourceCall(t, session, arguments); result.Err != nil || string(result.Value) != arguments { t.Fatalf("contained SDK round trip: %+v", result) } }) @@ -340,8 +340,8 @@ func TestNativeContainmentSDKRoundTrip(t *testing.T) { } func TestNativeContainmentCleanupFailure(t *testing.T) { - manager := contained_manager(t, DefaultResourceLimits()) - session := resource_peer(t, manager, "cleanup-failure") + manager := containedManager(t, DefaultResourceLimits()) + session := resourcePeer(t, manager, "cleanup-failure") groupPath := filepath.Join(manager.containment.group.path, session.Identity()) killPath := filepath.Join(groupPath, "cgroup.kill") info, err := os.Stat(killPath) @@ -358,7 +358,7 @@ func TestNativeContainmentCleanupFailure(t *testing.T) { t.Error(err) return } - if err := (&cgroup{path: groupPath}).kill_and_remove(time.Second); err != nil { + if err := (&cgroup{path: groupPath}).killAndRemove(time.Second); err != nil { t.Error(err) return } @@ -370,14 +370,14 @@ func TestNativeContainmentCleanupFailure(t *testing.T) { manager.mutex.Unlock() }() session.Disable() - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Failed || !errors.Is(err, ErrContainment) { t.Fatalf("failed cleanup reported %s: %v", state, err) } if manager.Stats().Processes != 1 { t.Fatal("failed cleanup released admission capacity") } - if _, err := manager.Start(context.Background(), child_spec(t, "blocked", "echo")); !errors.Is(err, ErrContainment) { + if _, err := manager.Start(context.Background(), childSpec(t, "blocked", "echo")); !errors.Is(err, ErrContainment) { t.Fatalf("cleanup failure admitted a child: %v", err) } if err := manager.Shutdown(context.Background()); !errors.Is(err, ErrContainment) { diff --git a/internal/tentacle/diagnostics.go b/internal/tentacle/diagnostics.go index 6ad3cfe..54e55ef 100644 --- a/internal/tentacle/diagnostics.go +++ b/internal/tentacle/diagnostics.go @@ -96,7 +96,7 @@ func (writer *diagnosticWriter) Write(data []byte) (int, error) { func (writer *diagnosticWriter) record() { var d childDiagnostic - if decode_strict(json.RawMessage(writer.line), &d) != nil || d.Version != 1 || d.ElapsedMS < 0 { + if decodeStrict(json.RawMessage(writer.line), &d) != nil || d.Version != 1 || d.ElapsedMS < 0 { return } if d.Operation != "" && diagnosticOperation(d.Operation) == "other" { diff --git a/internal/tentacle/diagnostics_test.go b/internal/tentacle/diagnostics_test.go index a770633..f4788f0 100644 --- a/internal/tentacle/diagnostics_test.go +++ b/internal/tentacle/diagnostics_test.go @@ -36,7 +36,7 @@ func TestDiagnosticStreamBoundsAndPrivacy(t *testing.T) { func TestRemoteLifecycleDiagnosticsOmitAuthorityTokens(t *testing.T) { var output bytes.Buffer - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) manager.SetLogger(slog.New(slog.NewJSONHandler(&output, &slog.HandlerOptions{Level: slog.LevelDebug}))) // Exercise the real lease lifecycle with a logger attached, without a child. ctx, cancel := context.WithCancel(context.Background()) @@ -50,7 +50,7 @@ func TestRemoteLifecycleDiagnosticsOmitAuthorityTokens(t *testing.T) { params := tentaclewire.RemoteOpen{Action: action.Action, Epoch: action.Epoch, Role: action.Role, Grants: action.Grants} session.mutex.Lock() raw, _ := json.Marshal(params) - value, failure := session.remote_call_locked("remote.open", raw) + value, failure := session.remoteCallLocked("remote.open", raw) session.mutex.Unlock() if failure != nil { t.Fatal(failure) diff --git a/internal/tentacle/install.go b/internal/tentacle/install.go index 58d1607..1c4acb6 100644 --- a/internal/tentacle/install.go +++ b/internal/tentacle/install.go @@ -31,29 +31,29 @@ import ( const maxPackageBytes = 32 << 20 const maxExpandedBytes = 64 << 20 -func valid_digest(value string) bool { +func validDigest(value string) bool { decoded, err := hex.DecodeString(value) return err == nil && len(decoded) == sha256.Size && value == strings.ToLower(value) } -func valid_revision(value string) bool { +func validRevision(value string) bool { decoded, err := hex.DecodeString(value) return err == nil && (len(decoded) == 20 || len(decoded) == 32) && value == strings.ToLower(value) } -func artifact_url(value string) bool { +func artifactUrl(value string) bool { parsed, err := url.Parse(value) - return err == nil && parsed.Scheme == "https" && parsed.Hostname() != "" && parsed.User == nil && parsed.Opaque == "" && parsed.Fragment == "" && !strings.Contains(value, "#") && len(value) <= 2048 && metadata_text(value, true) + return err == nil && parsed.Scheme == "https" && parsed.Hostname() != "" && parsed.User == nil && parsed.Opaque == "" && parsed.Fragment == "" && !strings.Contains(value, "#") && len(value) <= 2048 && metadataText(value, true) } -func validate_releases(releases []Release) error { +func validateReleases(releases []Release) error { if len(releases) > 16 { return ErrLimit } seen := make(map[string]bool) for _, release := range releases { key := release.Platform + "/" + release.Architecture - if !metadata_id(release.Platform) || !metadata_id(release.Architecture) || !artifact_url(release.URL) || !valid_digest(release.SHA256) || seen[key] { + if !metadataId(release.Platform) || !metadataId(release.Architecture) || !artifactUrl(release.URL) || !validDigest(release.SHA256) || seen[key] { return errors.New("Invalid or duplicate package release metadata.") } seen[key] = true @@ -92,19 +92,19 @@ func (prepared *PreparedPackage) Discard() error { func (prepared *PreparedPackage) Retain() { prepared.directory = "" } func PreparePackage(ctx context.Context, root string, repository Repository, localID string) (*PreparedPackage, error) { - return prepare_package(ctx, root, repository, localID, new_package_client()) + return preparePackage(ctx, root, repository, localID, newPackageClient()) } -func new_package_client() *http.Client { +func newPackageClient() *http.Client { return &http.Client{Timeout: 45 * time.Second, CheckRedirect: func(request *http.Request, via []*http.Request) error { - if len(via) >= 5 || !artifact_url(request.URL.String()) { + if len(via) >= 5 || !artifactUrl(request.URL.String()) { return errors.New("Package redirect must use HTTPS without credentials.") } return nil }} } -func prepare_package(ctx context.Context, root string, repository Repository, localID string, client *http.Client) (_ *PreparedPackage, resultError error) { +func preparePackage(ctx context.Context, root string, repository Repository, localID string, client *http.Client) (_ *PreparedPackage, resultError error) { if err := ValidateRepositories([]Repository{repository}); err != nil { return nil, err } @@ -175,10 +175,10 @@ func prepare_package(ctx context.Context, root string, repository Repository, lo if _, err := archive.Seek(0, io.SeekStart); err != nil { return nil, err } - if err := extract_package(ctx, archive, stage); err != nil { + if err := extractPackage(ctx, archive, stage); err != nil { return nil, err } - data, err := read_registry(filepath.Join(stage, "tentacle.toml")) + data, err := readRegistry(filepath.Join(stage, "tentacle.toml")) if err != nil || data == nil { return nil, errors.New("Package must contain a regular tentacle.toml.") } @@ -224,11 +224,11 @@ func prepare_package(ctx context.Context, root string, repository Repository, lo if !valid { return nil, errors.New("Package requires unsupported APIs or permissions.") } - if len(packageManifest.EntryPoint) == 0 || len(packageManifest.EntryPoint) > 32 || !package_path(packageManifest.EntryPoint[0]) { + if len(packageManifest.EntryPoint) == 0 || len(packageManifest.EntryPoint) > 32 || !packagePath(packageManifest.EntryPoint[0]) { return nil, errors.New("Package entry point must be a relative file path inside the package.") } executable := filepath.Join(stage, filepath.FromSlash(packageManifest.EntryPoint[0])) - if err := validate_native_program(executable); err != nil { + if err := validateNativeProgram(executable); err != nil { return nil, err } if err := ctx.Err(); err != nil { @@ -239,7 +239,7 @@ func prepare_package(ctx context.Context, root string, repository Repository, lo return walkError } if entry.IsDir() { - return sync_directory(filename) + return syncDirectory(filename) } return nil }); err != nil { @@ -266,20 +266,20 @@ func prepare_package(ctx context.Context, root string, repository Repository, lo if err := ValidateEntries([]Entry{prepared.Entry}); err != nil { return nil, err } - if err := sync_directory(final); err != nil { + if err := syncDirectory(final); err != nil { return nil, err } - if err := sync_directory(root); err != nil { + if err := syncDirectory(root); err != nil { return nil, err } return prepared, nil } -func package_path(filename string) bool { +func packagePath(filename string) bool { return filename != "" && filename != "." && !strings.HasPrefix(filename, "/") && path.Clean(filename) == filename && filename != ".." && !strings.HasPrefix(filename, "../") && !strings.ContainsAny(filename, "\\\x00\r\n:") && len(filename) <= 4096 } -func extract_package(ctx context.Context, archive io.Reader, directory string) error { +func extractPackage(ctx context.Context, archive io.Reader, directory string) error { compressed, err := gzip.NewReader(archive) if err != nil { return errors.New("Package must be a gzip tar archive.") @@ -303,7 +303,7 @@ func extract_package(ctx context.Context, archive io.Reader, directory string) e return ErrLimit } filename := strings.TrimSuffix(header.Name, "/") - if !package_path(filename) || seen[filename] { + if !packagePath(filename) || seen[filename] { return errors.New("Package contains unsafe or duplicate paths.") } seen[filename] = true @@ -348,7 +348,7 @@ func extract_package(ctx context.Context, archive io.Reader, directory string) e return nil } -func validate_native_program(filename string) error { +func validateNativeProgram(filename string) error { info, err := os.Stat(filename) if err != nil || !info.Mode().IsRegular() || info.Mode()&0100 == 0 { return errors.New("Package entry point is missing or not executable.") @@ -366,7 +366,7 @@ func validate_native_program(filename string) error { return nil } -func sync_directory(directory string) error { +func syncDirectory(directory string) error { file, err := os.Open(directory) if err != nil { return err @@ -399,7 +399,7 @@ func RemovePackage(root string, entry Entry) error { if err := os.RemoveAll(directory); err != nil { return err } - return sync_directory(root) + return syncDirectory(root) } // RecoverPackages runs once, after a successful registry load, before accepting @@ -417,7 +417,7 @@ func RecoverPackages(root string, entries []Entry) error { for _, entry := range entries { for _, filename := range append([]string{entry.PackageDirectory, entry.Directory}, entry.Program...) { relative, err := filepath.Rel(root, filename) - if err == nil && package_path(filepath.ToSlash(relative)) { + if err == nil && packagePath(filepath.ToSlash(relative)) { retained[strings.Split(filepath.ToSlash(relative), "/")[0]] = true } } @@ -441,5 +441,5 @@ func RecoverPackages(root string, entries []Entry) error { return err } } - return sync_directory(root) + return syncDirectory(root) } diff --git a/internal/tentacle/install_test.go b/internal/tentacle/install_test.go index 766b848..e510830 100644 --- a/internal/tentacle/install_test.go +++ b/internal/tentacle/install_test.go @@ -33,7 +33,7 @@ type archiveMember struct { mode int64 } -func package_archive(t *testing.T, members []archiveMember) []byte { +func packageArchive(t *testing.T, members []archiveMember) []byte { t.Helper() var output bytes.Buffer compressed := gzip.NewWriter(&output) @@ -62,11 +62,11 @@ func package_archive(t *testing.T, members []archiveMember) []byte { return output.Bytes() } -func package_manifest() string { +func packageManifest() string { return "format-version=1\nid='echo'\nname='Echo'\nversion='0.1'\nruntime='native'\nplatforms=['linux']\nentry-point=['bin/echo']\napis=['commands','presentation']\ncapabilities=['presentation']\n[protocol]\nmajor=1\nminor=0\n" } -func package_fixture(t *testing.T, data []byte) (Repository, *http.Client) { +func packageFixture(t *testing.T, data []byte) (Repository, *http.Client) { t.Helper() digest := sha256.Sum256(data) repository := Repository{URL: "https://example.org/team/tentacles", ID: "example.tentacles", Name: "Example", Revision: strings.Repeat("a", 40), @@ -81,7 +81,7 @@ func package_fixture(t *testing.T, data []byte) (Repository, *http.Client) { return repository, client } -func native_members(t *testing.T) []archiveMember { +func nativeMembers(t *testing.T) []archiveMember { t.Helper() filename, err := os.Executable() if err != nil { @@ -91,14 +91,14 @@ func native_members(t *testing.T) []archiveMember { if err != nil { t.Fatal(err) } - return []archiveMember{{name: "tentacle.toml", data: []byte(package_manifest()), mode: 0644}, {name: "bin/echo", data: data, mode: 0755}} + return []archiveMember{{name: "tentacle.toml", data: []byte(packageManifest()), mode: 0644}, {name: "bin/echo", data: data, mode: 0755}} } func TestPackageInstallPinsIdentityPermissionsAndSurvivesRestart(t *testing.T) { - data := package_archive(t, native_members(t)) - repository, client := package_fixture(t, data) + data := packageArchive(t, nativeMembers(t)) + repository, client := packageFixture(t, data) root := filepath.Join(t.TempDir(), "packages") - prepared, err := prepare_package(context.Background(), root, repository, "echo", client) + prepared, err := preparePackage(context.Background(), root, repository, "echo", client) if err != nil { t.Fatal(err) } @@ -136,20 +136,20 @@ func TestPackageInstallPinsIdentityPermissionsAndSurvivesRestart(t *testing.T) { func TestPackageRejectsBadDownloadsAndManifestsWithoutFiles(t *testing.T) { for _, problem := range []string{"digest", "status", "unsupported architecture", "version", "grant", "runtime", "protocol", "api", "entry traversal", "missing executable", "not executable", "not ELF", "cancelled", "corrupt gzip"} { t.Run(problem, func(t *testing.T) { - members := native_members(t) + members := nativeMembers(t) switch problem { case "version": - members[0].data = []byte(strings.Replace(package_manifest(), "version='0.1'", "version='0.2'", 1)) + members[0].data = []byte(strings.Replace(packageManifest(), "version='0.1'", "version='0.2'", 1)) case "grant": - members[0].data = []byte(strings.Replace(package_manifest(), "capabilities=['presentation']", "capabilities=[]", 1)) + members[0].data = []byte(strings.Replace(packageManifest(), "capabilities=['presentation']", "capabilities=[]", 1)) case "runtime": - members[0].data = []byte(strings.Replace(package_manifest(), "runtime='native'", "runtime='python'", 1)) + members[0].data = []byte(strings.Replace(packageManifest(), "runtime='native'", "runtime='python'", 1)) case "protocol": - members[0].data = []byte(strings.Replace(package_manifest(), "major=1", "major=2", 1)) + members[0].data = []byte(strings.Replace(packageManifest(), "major=1", "major=2", 1)) case "api": - members[0].data = []byte(strings.Replace(package_manifest(), "'commands','presentation'", "'commands','focused-text'", 1)) + members[0].data = []byte(strings.Replace(packageManifest(), "'commands','presentation'", "'commands','focused-text'", 1)) case "entry traversal": - members[0].data = []byte(strings.Replace(package_manifest(), "bin/echo", "../echo", 1)) + members[0].data = []byte(strings.Replace(packageManifest(), "bin/echo", "../echo", 1)) case "missing executable": members = members[:1] case "not executable": @@ -157,11 +157,11 @@ func TestPackageRejectsBadDownloadsAndManifestsWithoutFiles(t *testing.T) { case "not ELF": members[1].data = []byte("#!/bin/sh\nexit 0\n") } - data := package_archive(t, members) + data := packageArchive(t, members) if problem == "corrupt gzip" { data[len(data)-8] ^= 0xff } - repository, client := package_fixture(t, data) + repository, client := packageFixture(t, data) if problem == "digest" { repository.Tentacles[0].Releases[0].SHA256 = strings.Repeat("0", 64) } @@ -179,7 +179,7 @@ func TestPackageRejectsBadDownloadsAndManifestsWithoutFiles(t *testing.T) { cancel() } root := filepath.Join(t.TempDir(), "packages") - if prepared, err := prepare_package(ctx, root, repository, "echo", client); err == nil { + if prepared, err := preparePackage(ctx, root, repository, "echo", client); err == nil { prepared.Discard() t.Fatal("accepted", problem) } @@ -205,7 +205,7 @@ func TestPackageExtractionRejectsEscapesLinksConflictsAndExpansion(t *testing.T) } for index, members := range cases { t.Run(fmt.Sprint(index), func(t *testing.T) { - if err := extract_package(context.Background(), bytes.NewReader(package_archive(t, members)), t.TempDir()); err == nil { + if err := extractPackage(context.Background(), bytes.NewReader(packageArchive(t, members)), t.TempDir()); err == nil { t.Fatal("unsafe archive accepted") } }) @@ -234,9 +234,9 @@ func TestPackageRemovalPreservesLocalFilesAndRejectsForeignDirectories(t *testin } func TestReleaseCatalogValidationAndDeepClone(t *testing.T) { - files := repository_files() + files := repositoryFiles() files["catalog.toml"] += "[[tentacles.releases]]\nplatform='linux'\narchitecture='amd64'\nurl='https://example.org/release.tar.gz'\nsha256='" + strings.Repeat("a", 64) + "'\n" - repository, err := read_repository_fixture(files) + repository, err := readRepositoryFixture(files) if err != nil { t.Fatal(err) } @@ -283,7 +283,7 @@ func TestPackageRecoveryKeepsSelectedFilesAndLocalReferences(t *testing.T) { func TestPackageRedirectsRejectHTTPAndCredentials(t *testing.T) { for _, location := range []string{"http://example.org/archive", "https://Username@example.org/archive"} { t.Run(location, func(t *testing.T) { - client := new_package_client() + client := newPackageClient() calls := 0 client.Transport = packageTransport(func(request *http.Request) (*http.Response, error) { calls++ @@ -305,7 +305,7 @@ func TestBuiltHelloWorldPackageThroughHost(t *testing.T) { if root == "" { t.Skip("set CTHULHU_TENTACLE_RELEASE_ROOT to validate prepared release artifacts") } - repository, err := read_repository("https://example.org/team/tentacles", strings.Repeat("a", 40), func(filename string) ([]byte, error) { return os.ReadFile(filepath.Join(root, filename)) }) + repository, err := readRepository("https://example.org/team/tentacles", strings.Repeat("a", 40), func(filename string) ([]byte, error) { return os.ReadFile(filepath.Join(root, filename)) }) if err != nil { t.Fatal(err) } @@ -328,11 +328,11 @@ func TestBuiltHelloWorldPackageThroughHost(t *testing.T) { if err != nil { t.Fatal(err) } - client := new_package_client() + client := newPackageClient() client.Transport = packageTransport(func(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(data)), Header: make(http.Header)}, nil }) - prepared, err := prepare_package(context.Background(), filepath.Join(t.TempDir(), "packages"), repository, "hello-world", client) + prepared, err := preparePackage(context.Background(), filepath.Join(t.TempDir(), "packages"), repository, "hello-world", client) if err != nil { t.Fatal(err) } @@ -375,16 +375,16 @@ func TestBuiltHelloWorldPackageThroughHost(t *testing.T) { } func TestInstallInteractivePackageGrant(t *testing.T) { - members := native_members(t) + members := nativeMembers(t) for index := range members { if members[index].name == "tentacle.toml" { - members[index].data = []byte(strings.ReplaceAll(strings.ReplaceAll(package_manifest(), "apis=['commands','presentation']", "apis=['commands','presentation','interaction']"), "capabilities=['presentation']", "capabilities=['presentation','interaction']")) + members[index].data = []byte(strings.ReplaceAll(strings.ReplaceAll(packageManifest(), "apis=['commands','presentation']", "apis=['commands','presentation','interaction']"), "capabilities=['presentation']", "capabilities=['presentation','interaction']")) } } - data := package_archive(t, members) - repository, client := package_fixture(t, data) + data := packageArchive(t, members) + repository, client := packageFixture(t, data) repository.Tentacles[0].Capabilities = []string{"presentation", "interaction"} - prepared, err := prepare_package(context.Background(), t.TempDir(), repository, "echo", client) + prepared, err := preparePackage(context.Background(), t.TempDir(), repository, "echo", client) if err != nil { t.Fatal(err) } @@ -405,13 +405,13 @@ func TestInstallReaderSettingsPackageGrantAndDependencies(t *testing.T) { apis = "'commands','presentation','interaction','reader-settings'" granted = []string{"presentation", "interaction", "reader-settings"} } - members := native_members(t) - manifest := strings.ReplaceAll(package_manifest(), "apis=['commands','presentation']", "apis=["+apis+"]") + members := nativeMembers(t) + manifest := strings.ReplaceAll(packageManifest(), "apis=['commands','presentation']", "apis=["+apis+"]") manifest = strings.ReplaceAll(manifest, "capabilities=['presentation']", "capabilities=["+capabilities+"]") members[0].data = []byte(manifest) - repository, client := package_fixture(t, package_archive(t, members)) + repository, client := packageFixture(t, packageArchive(t, members)) repository.Tentacles[0].Capabilities = granted - prepared, err := prepare_package(t.Context(), t.TempDir(), repository, "echo", client) + prepared, err := preparePackage(t.Context(), t.TempDir(), repository, "echo", client) if !interactive { if err == nil { prepared.Discard() @@ -444,8 +444,8 @@ func TestInstallReaderSettingsPackageGrantAndDependencies(t *testing.T) { func TestSessionPackageGrantsPersistAndRejectMismatch(t *testing.T) { for _, variant := range []string{"valid", "missing API", "unknown grant", "duplicate grant", "old version"} { t.Run(variant, func(t *testing.T) { - members := native_members(t) - manifest := strings.Replace(package_manifest(), "minor=0", "minor=1", 1) + members := nativeMembers(t) + manifest := strings.Replace(packageManifest(), "minor=0", "minor=1", 1) manifest = strings.Replace(manifest, "apis=['commands','presentation']", "apis=['remote-access','session-events','presentation','commands']", 1) capabilities := []string{"presentation", "output-observe"} grantText := "capabilities=['presentation','output-observe']" @@ -463,9 +463,9 @@ func TestSessionPackageGrantsPersistAndRejectMismatch(t *testing.T) { } manifest = strings.Replace(manifest, "capabilities=['presentation']", grantText, 1) members[0].data = []byte(manifest) - repository, client := package_fixture(t, package_archive(t, members)) + repository, client := packageFixture(t, packageArchive(t, members)) repository.Tentacles[0].Capabilities = capabilities - prepared, err := prepare_package(t.Context(), filepath.Join(t.TempDir(), "packages"), repository, "echo", client) + prepared, err := preparePackage(t.Context(), filepath.Join(t.TempDir(), "packages"), repository, "echo", client) if variant != "valid" { if err == nil { prepared.Discard() diff --git a/internal/tentacle/load_test.go b/internal/tentacle/load_test.go index b24be7e..6a872aa 100644 --- a/internal/tentacle/load_test.go +++ b/internal/tentacle/load_test.go @@ -19,12 +19,12 @@ func TestPythonPeerUsesSameContract(t *testing.T) { if err != nil { t.Fatal(err) } - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session, err := manager.Start(context.Background(), Spec{ID: "python", Program: []string{python, "-I", "-u", fixture}}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if err := session.Activate(); err != nil { t.Fatal(err) } @@ -33,7 +33,7 @@ func TestPythonPeerUsesSameContract(t *testing.T) { if err != nil { t.Fatal(err) } - result := wait_result(t, pending) + result := waitResult(t, pending) var value struct { Text string Enabled bool @@ -48,12 +48,12 @@ func TestPythonPeerUsesSameContract(t *testing.T) { } func TestManyTentaclesHaveAggregateBoundAndIndependentProgress(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) sessions := make([]*Session, 0, 16) // Keep one healthy peer alongside fifteen peers that never reply. - healthy := start_active(t, manager, "healthy", "echo") + healthy := startActive(t, manager, "healthy", "echo") for index := range 15 { - sessions = append(sessions, start_active(t, manager, fmt.Sprintf("blocked-%d", index), "timeout")) + sessions = append(sessions, startActive(t, manager, fmt.Sprintf("blocked-%d", index), "timeout")) } for index := range 63 { if _, err := sessions[index%len(sessions)].Invoke(context.Background(), "echo", nil); err != nil { @@ -64,7 +64,7 @@ func TestManyTentaclesHaveAggregateBoundAndIndependentProgress(t *testing.T) { if err != nil { t.Fatal(err) } - if reply := wait_result(t, result); reply.Err != nil || string(reply.Value) != `{"healthy":true}` { + if reply := waitResult(t, result); reply.Err != nil || string(reply.Value) != `{"healthy":true}` { t.Fatalf("healthy peer stalled: %+v", reply) } if _, err := sessions[0].Invoke(context.Background(), "echo", nil); err != nil { @@ -83,7 +83,7 @@ func TestManyTentaclesHaveAggregateBoundAndIndependentProgress(t *testing.T) { if err != nil { t.Fatal(err) } - if reply := wait_result(t, result); reply.Err != nil { + if reply := waitResult(t, result); reply.Err != nil { t.Fatal(reply.Err) } } @@ -91,10 +91,10 @@ func TestManyTentaclesHaveAggregateBoundAndIndependentProgress(t *testing.T) { func BenchmarkCommandRoundTrip(b *testing.B) { for _, count := range []int{1, 8, 16} { b.Run(fmt.Sprintf("processes-%d", count), func(b *testing.B) { - manager := test_manager(b, DefaultLimits(), nil) + manager := testManager(b, DefaultLimits(), nil) sessions := make([]*Session, count) for index := range count { - sessions[index] = start_active(b, manager, fmt.Sprintf("peer-%d", index), "echo") + sessions[index] = startActive(b, manager, fmt.Sprintf("peer-%d", index), "echo") } arguments := json.RawMessage(`{"text":"sample"}`) b.ReportAllocs() diff --git a/internal/tentacle/local.go b/internal/tentacle/local.go index cb625a6..b81606c 100644 --- a/internal/tentacle/local.go +++ b/internal/tentacle/local.go @@ -32,7 +32,7 @@ func LoadLocalSpecs(path string) ([]Spec, error) { if len(data) > MaxFrameBytes { return nil, ErrLimit } - if err := validate_json(data); err != nil { + if err := validateJson(data); err != nil { return nil, err } var specs []Spec @@ -46,7 +46,7 @@ func LoadLocalSpecs(path string) ([]Spec, error) { } seen := make(map[string]bool) for _, spec := range specs { - if err := validate_spec(spec); err != nil { + if err := validateSpec(spec); err != nil { return nil, err } if seen[spec.ID] { diff --git a/internal/tentacle/manager.go b/internal/tentacle/manager.go index c0f1d94..2aa24a3 100644 --- a/internal/tentacle/manager.go +++ b/internal/tentacle/manager.go @@ -127,7 +127,7 @@ func (manager *Manager) Start(ctx context.Context, spec Spec) (*Session, error) if err := ctx.Err(); err != nil { return nil, err } - if err := validate_spec(spec); err != nil { + if err := validateSpec(spec); err != nil { return nil, err } manager.mutex.Lock() @@ -208,11 +208,11 @@ func (manager *Manager) Shutdown(ctx context.Context) error { return nil } -func validate_spec(spec Spec) error { +func validateSpec(spec Spec) error { if !tentaclewire.ValidRemoteGrants(spec.RemoteGrants) || len(spec.RemoteGrants) > 0 && !spec.SessionEvents { return errors.New("invalid remote grants") } - if spec.ReaderSettings && !spec.Interaction || spec.Interaction && !spec.Presentation || !valid_id(spec.ID) || len(spec.Program) == 0 || len(spec.Program) > 32 || + if spec.ReaderSettings && !spec.Interaction || spec.Interaction && !spec.Presentation || !validId(spec.ID) || len(spec.Program) == 0 || len(spec.Program) > 32 || !filepath.IsAbs(spec.Program[0]) || (spec.Directory != "" && !filepath.IsAbs(spec.Directory)) { return errors.New("invalid local tentacle launch") } diff --git a/internal/tentacle/page_store.go b/internal/tentacle/page_store.go index 5f914fa..c345faa 100644 --- a/internal/tentacle/page_store.go +++ b/internal/tentacle/page_store.go @@ -11,12 +11,12 @@ import ( "path/filepath" "syscall" - "git.stormux.org/storm/cthulhu/internal/interaction" + "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) // PageValues contains only host-validated declarative preferences. Active speech // overrides and quick-setting selections are deliberately never restored here. -type PageValues map[string]map[string]map[string]interaction.Value +type PageValues map[string]map[string]map[string]tentaclewire.Value type PageStore struct { Path string @@ -26,13 +26,13 @@ type PageStore struct { func (store *PageStore) Load() (PageValues, error) { store.loaded = false - data, err := read_registry(store.Path) + data, err := readRegistry(store.Path) if err != nil { return nil, err } values := PageValues{} if data != nil { - if validate_json(data) != nil { + if validateJson(data) != nil { return nil, ErrProtocol } if err := json.Unmarshal(data, &values); err != nil || values == nil { @@ -70,7 +70,7 @@ func (store *PageStore) Save(values PageValues) error { return errors.New("tentacle preferences are being edited") } defer func() { _ = syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) }() - current, err := read_registry(store.Path) + current, err := readRegistry(store.Path) if err != nil { return err } diff --git a/internal/tentacle/page_store_test.go b/internal/tentacle/page_store_test.go index 2298d05..a03a2f4 100644 --- a/internal/tentacle/page_store_test.go +++ b/internal/tentacle/page_store_test.go @@ -3,7 +3,7 @@ package tentacle import ( - "git.stormux.org/storm/cthulhu/internal/interaction" + "git.stormux.org/storm/cthulhu/internal/tentaclewire" "os" "path/filepath" "reflect" @@ -20,7 +20,7 @@ func TestPageStoreAtomicPersistenceAndExternalEdits(t *testing.T) { if _, err := os.Stat(path); !os.IsNotExist(err) { t.Fatal("load created a file") } - values["probe"] = map[string]map[string]interaction.Value{"page": {"name": {Text: "Example"}}} + values["probe"] = map[string]map[string]tentaclewire.Value{"page": {"name": {Text: "Example"}}} if err := store.Save(values); err != nil { t.Fatal(err) } @@ -33,7 +33,7 @@ func TestPageStoreAtomicPersistenceAndExternalEdits(t *testing.T) { if err != nil || !reflect.DeepEqual(loaded, values) { t.Fatal(loaded, err) } - loaded["probe"]["page"]["name"] = interaction.Value{Text: "Changed"} + loaded["probe"]["page"]["name"] = tentaclewire.Value{Text: "Changed"} if err := other.Save(loaded); err != nil { t.Fatal(err) } diff --git a/internal/tentacle/process.go b/internal/tentacle/process.go index 09ce95f..2a2f8fe 100644 --- a/internal/tentacle/process.go +++ b/internal/tentacle/process.go @@ -32,13 +32,13 @@ func (session *Session) run() { session.cancel() session.mutex.Lock() if cleanupError != nil { - session.fail_locked(cleanupError) + session.failLocked(cleanupError) // Even a requested disable must report incomplete containment. session.state, session.failure = Failed, cleanupError } else if session.state == Stopping { session.state = Stopped } else if session.state != Failed { - session.fail_locked(ErrExited) + session.failLocked(ErrExited) } session.log("tentacle stopped", "state", session.state, "cleanup_reason", diagnosticError(cleanupError)) session.mutex.Unlock() @@ -122,12 +122,12 @@ func (session *Session) run() { command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} var group *cgroup if containment := session.manager.containment; containment != nil { - group, err = create_cgroup(filepath.Join(containment.group.path, session.identity), containment.limits.PerSession, 0) + group, err = createCgroup(filepath.Join(containment.group.path, session.identity), containment.limits.PerSession, 0) if err != nil { session.fail(err) return } - defer func() { cleanupError = group.kill_and_remove(containment.limits.CleanupTimeout) }() + defer func() { cleanupError = group.killAndRemove(containment.limits.CleanupTimeout) }() // clone3(CLONE_INTO_CGROUP) applies limits before the child executes. // Moving an already-running PID would leave a fork/allocation race. command.SysProcAttr.UseCgroupFD = true @@ -169,9 +169,9 @@ func (session *Session) run() { }() } workers.Add(3) - go func() { defer workers.Done(); session.write_requests(input) }() - go func() { defer workers.Done(); session.read_replies(output) }() - go func() { defer workers.Done(); session.drain_diagnostics(diagnostics) }() + go func() { defer workers.Done(); session.writeRequests(input) }() + go func() { defer workers.Done(); session.readReplies(output) }() + go func() { defer workers.Done(); session.drainDiagnostics(diagnostics) }() defer func() { session.cancel() if supervised { @@ -179,7 +179,7 @@ func (session *Session) run() { configuration.Close() } if group != nil { - _ = write_control(group.path, "cgroup.kill", "1") + _ = writeControl(group.path, "cgroup.kill", "1") if command.Process != nil { _ = command.Process.Kill() } @@ -221,7 +221,7 @@ func (session *Session) run() { if session.spec.ReaderSettings { apis = append(apis, "reader-settings") } - initialized, err = session.request_locked(session.ctx, "initialize", Initialization{ + initialized, err = session.requestLocked(session.ctx, "initialize", Initialization{ Protocol: session.spec.protocol(), Session: session.identity, APIs: session.spec.apis(apis), Capabilities: session.spec.capabilities(apis), }, session.manager.limits.StartupTimeout) @@ -240,7 +240,7 @@ func (session *Session) run() { return } var registration Registration - if decode_strict(result.Value, ®istration) != nil || validate_registration_version(registration, session.identity, session.spec.protocol()) != nil { + if decodeStrict(result.Value, ®istration) != nil || validateRegistrationVersion(registration, session.identity, session.spec.protocol()) != nil { session.fail(ErrProtocol) return } @@ -271,7 +271,7 @@ func (session *Session) run() { session.fail(ErrExited) return case <-session.stop: - session.wait_shutdown(exited) + session.waitShutdown(exited) return } select { @@ -280,11 +280,11 @@ func (session *Session) run() { case <-exited: session.fail(ErrExited) case <-session.stop: - session.wait_shutdown(exited) + session.waitShutdown(exited) } } -func (session *Session) wait_shutdown(exited <-chan struct{}) { +func (session *Session) waitShutdown(exited <-chan struct{}) { timer := time.NewTimer(session.manager.limits.ShutdownTimeout) defer timer.Stop() select { @@ -294,7 +294,7 @@ func (session *Session) wait_shutdown(exited <-chan struct{}) { } } -func (session *Session) write_requests(writer io.Writer) { +func (session *Session) writeRequests(writer io.Writer) { for { select { case <-session.ctx.Done(): @@ -327,10 +327,10 @@ func (session *Session) write_requests(writer io.Writer) { } } -func (session *Session) read_replies(reader io.Reader) { +func (session *Session) readReplies(reader io.Reader) { buffer := bufio.NewReaderSize(reader, 4096) for session.ctx.Err() == nil { - frame, err := read_frame(buffer) + frame, err := readFrame(buffer) if err != nil { if errors.Is(err, io.EOF) { err = ErrExited @@ -339,27 +339,27 @@ func (session *Session) read_replies(reader io.Reader) { return } var fields map[string]json.RawMessage - if validate_json(frame) != nil || json.Unmarshal(frame, &fields) != nil { + if validateJson(frame) != nil || json.Unmarshal(frame, &fields) != nil { session.fail(ErrProtocol) return } if _, request := fields["method"]; request { - if err := session.accept_child_request(frame); err != nil { + if err := session.acceptChildRequest(frame); err != nil { session.fail(err) return } continue } - reply, err := decode_response(frame) + reply, err := decodeResponse(frame) if err != nil { session.fail(err) return } - session.accept_reply(reply) + session.acceptReply(reply) } } -func (session *Session) drain_diagnostics(reader io.Reader) { +func (session *Session) drainDiagnostics(reader io.Reader) { count, err := io.Copy(&diagnosticWriter{session: session}, io.LimitReader(reader, MaxDiagnosticBytes+1)) if count > MaxDiagnosticBytes { session.log("tentacle diagnostic budget exceeded", "bytes", count) diff --git a/internal/tentacle/protocol.go b/internal/tentacle/protocol.go index 128dfae..fbfa73f 100644 --- a/internal/tentacle/protocol.go +++ b/internal/tentacle/protocol.go @@ -87,7 +87,7 @@ type request struct { Params any `json:"params,omitempty"` } -func encode_request(id, method string, params any) ([]byte, error) { +func encodeRequest(id, method string, params any) ([]byte, error) { data, err := json.Marshal(request{JSONRPC: "2.0", ID: id, Method: method, Params: params}) if err != nil { return nil, ErrProtocol @@ -98,13 +98,13 @@ func encode_request(id, method string, params any) ([]byte, error) { return append(data, '\n'), nil } -func read_frame(reader *bufio.Reader) ([]byte, error) { return tentaclewire.ReadFrame(reader) } -func validate_json(data []byte) error { return tentaclewire.ValidateJSON(data) } -func decode_strict(data []byte, target any) error { return tentaclewire.DecodeStrict(data, target) } +func readFrame(reader *bufio.Reader) ([]byte, error) { return tentaclewire.ReadFrame(reader) } +func validateJson(data []byte) error { return tentaclewire.ValidateJSON(data) } +func decodeStrict(data []byte, target any) error { return tentaclewire.DecodeStrict(data, target) } -func decode_response(data []byte) (response, error) { +func decodeResponse(data []byte) (response, error) { var reply response - if err := decode_strict(data, &reply); err != nil { + if err := decodeStrict(data, &reply); err != nil { return reply, err } // Presence matters: a null result is valid; a null error is not. @@ -132,7 +132,7 @@ func decode_response(data []byte) (response, error) { return reply, nil } -func valid_id(value string) bool { +func validId(value string) bool { if len(value) == 0 || len(value) > 128 || value[0] < 'a' || value[0] > 'z' { return false } @@ -144,11 +144,11 @@ func valid_id(value string) bool { return true } -func validate_registration(registration Registration, session string) error { - return validate_registration_version(registration, session, Version{Major: 1, Minor: 0}) +func validateRegistration(registration Registration, session string) error { + return validateRegistrationVersion(registration, session, Version{Major: 1, Minor: 0}) } -func validate_registration_version(registration Registration, session string, version Version) error { +func validateRegistrationVersion(registration Registration, session string, version Version) error { if registration.Protocol != version || registration.Session != session || len(registration.Commands) == 0 || len(registration.Commands) > MaxCommands { return ErrProtocol @@ -156,7 +156,7 @@ func validate_registration_version(registration Registration, session string, ve seen := make(map[string]bool) settings := false for _, command := range registration.Commands { - if command.Reader && !command.Interaction || command.Settings && (!command.Interaction || settings) || command.Interaction && !command.Presentation || !valid_id(command.ID) || seen[command.ID] || strings.TrimSpace(command.Title) == "" || + if command.Reader && !command.Interaction || command.Settings && (!command.Interaction || settings) || command.Interaction && !command.Presentation || !validId(command.ID) || seen[command.ID] || strings.TrimSpace(command.Title) == "" || len(command.Title) > 256 || len(command.Description) > 1024 { return ErrProtocol } @@ -166,7 +166,7 @@ func validate_registration_version(registration Registration, session string, ve return ErrLimit } for _, binding := range command.Bindings { - if err := validate_binding(binding); err != nil { + if err := validateBinding(binding); err != nil { return err } } @@ -176,12 +176,12 @@ func validate_registration_version(registration Registration, session string, ve return err } for _, page := range registration.Extensions.Pages { - if !reader_command(registration.Commands, page.Command) { + if !readerCommand(registration.Commands, page.Command) { return ErrProtocol } } for _, setting := range registration.Extensions.QuickSettings { - if !reader_command(registration.Commands, setting.Command) { + if !readerCommand(registration.Commands, setting.Command) { return ErrProtocol } } @@ -189,7 +189,7 @@ func validate_registration_version(registration Registration, session string, ve return nil } -func reader_command(commands []Command, id string) bool { +func readerCommand(commands []Command, id string) bool { for _, command := range commands { if command.ID == id { return command.Reader && !command.Settings @@ -198,7 +198,7 @@ func reader_command(commands []Command, id string) bool { return false } -func clone_commands(commands []Command) []Command { +func cloneCommands(commands []Command) []Command { result := append([]Command(nil), commands...) for index := range result { result[index].Bindings = append([]Binding(nil), result[index].Bindings...) diff --git a/internal/tentacle/protocol_test.go b/internal/tentacle/protocol_test.go index aacae74..abc59d7 100644 --- a/internal/tentacle/protocol_test.go +++ b/internal/tentacle/protocol_test.go @@ -21,7 +21,7 @@ func TestFramingBoundsAndRequiresNewline(t *testing.T) { {"empty", "", io.EOF}, } { t.Run(testCase.name, func(t *testing.T) { - _, err := read_frame(bufio.NewReaderSize(strings.NewReader(testCase.input), 32)) + _, err := readFrame(bufio.NewReaderSize(strings.NewReader(testCase.input), 32)) if !errors.Is(err, testCase.want) { t.Fatalf("got %v, want %v", err, testCase.want) } @@ -35,7 +35,7 @@ func TestResponseValidation(t *testing.T) { `{"jsonrpc":"2.0","id":"1","result":{"text":"é猫😀é"}}`, `{"jsonrpc":"2.0","id":"1","error":{"code":-32601,"message":"Unknown method"}}`, } { - if _, err := decode_response([]byte(valid)); err != nil { + if _, err := decodeResponse([]byte(valid)); err != nil { t.Errorf("valid response rejected: %v", err) } } @@ -55,7 +55,7 @@ func TestResponseValidation(t *testing.T) { `{"jsonrpc":"2.0","id":"1","result":` + strings.Repeat("[", 40) + "0" + strings.Repeat("]", 40) + `}`, `{"jsonrpc":"2.0","id":"1","result":null} {}`, } { - if _, err := decode_response([]byte(invalid)); err == nil { + if _, err := decodeResponse([]byte(invalid)); err == nil { t.Errorf("invalid response accepted: %q", invalid) } } @@ -71,25 +71,25 @@ func FuzzResponseDecoder(f *testing.F) { if len(data) > MaxFrameBytes { t.Skip() } - _, _ = decode_response(data) - _, _ = read_frame(bufio.NewReader(bytes.NewReader(data))) + _, _ = decodeResponse(data) + _, _ = readFrame(bufio.NewReader(bytes.NewReader(data))) }) } func TestSettingsRegistrationRequiresOneInteractiveCommand(t *testing.T) { command := Command{ID: "settings", Title: "Settings", Settings: true, Interaction: true, Presentation: true} registration := Registration{Protocol: Version{Major: 1}, Session: "test", Commands: []Command{command}} - if err := validate_registration(registration, "test"); err != nil { + if err := validateRegistration(registration, "test"); err != nil { t.Fatal(err) } registration.Commands[0].Interaction = false - if err := validate_registration(registration, "test"); err == nil { + if err := validateRegistration(registration, "test"); err == nil { t.Fatal("accepted a settings handler without interaction") } registration.Commands[0] = command command.ID = "other-settings" registration.Commands = append(registration.Commands, command) - if err := validate_registration(registration, "test"); err == nil { + if err := validateRegistration(registration, "test"); err == nil { t.Fatal("accepted two settings entry points") } } diff --git a/internal/tentacle/reader_test.go b/internal/tentacle/reader_test.go index 6becc80..304a868 100644 --- a/internal/tentacle/reader_test.go +++ b/internal/tentacle/reader_test.go @@ -46,12 +46,12 @@ func TestReaderSDKGrantsCopiesAndArgumentBounds(t *testing.T) { } program = []string{python, "-B", peer} } - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session, err := manager.Start(t.Context(), Spec{ID: "probe", Program: program, Presentation: true, Interaction: true, ReaderSettings: grant}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) state, reason := session.Status() if !grant { if state == Ready { @@ -79,7 +79,7 @@ func TestReaderSDKGrantsCopiesAndArgumentBounds(t *testing.T) { if err != nil { t.Fatal(err) } - result := wait_result(t, replies) + result := waitResult(t, replies) if result.Err != nil || string(result.Value) != string(argument) { t.Fatal("reader continuation did not round trip", result.Err) } @@ -96,16 +96,16 @@ func TestReaderSDKGrantsCopiesAndArgumentBounds(t *testing.T) { func TestReaderRegistrationRequiresDeclaredReaderCallbacks(t *testing.T) { extension := tentaclewire.Extensions{QuickSettings: []tentaclewire.QuickSetting{{ID: "probe", Label: "Probe", Command: "apply", Selected: "default", Options: []sdk.ListItem{{ID: "default", Label: "Default"}}}}} registration := Registration{Protocol: Version{Major: 1}, Session: "session", Commands: []Command{{ID: "apply", Title: "Apply", Presentation: true, Interaction: true, Reader: true}}, Extensions: &extension} - if err := validate_registration(registration, "session"); err != nil { + if err := validateRegistration(registration, "session"); err != nil { t.Fatal(err) } registration.Commands[0].Reader = false - if validate_registration(registration, "session") == nil { + if validateRegistration(registration, "session") == nil { t.Fatal("accepted an unprivileged extension callback") } registration.Commands[0].Reader = true registration.Commands[0].Settings = true - if validate_registration(registration, "session") == nil { + if validateRegistration(registration, "session") == nil { t.Fatal("accepted a settings-form handler as a page callback") } } diff --git a/internal/tentacle/registry.go b/internal/tentacle/registry.go index 7ee62ed..c485da7 100644 --- a/internal/tentacle/registry.go +++ b/internal/tentacle/registry.go @@ -78,18 +78,18 @@ func ValidateEntries(entries []Entry) error { seen := make(map[string]bool) packageDirectories := make(map[string]bool) for _, entry := range entries { - if err := validate_spec(entry.Spec()); err != nil { + if err := validateSpec(entry.Spec()); err != nil { return err } if entry.Repository != "" { origin, err := RepositoryURL(entry.Repository) - if err != nil || origin != entry.Repository || !metadata_id(entry.RepositoryID) || !metadata_id(entry.LocalID) { + if err != nil || origin != entry.Repository || !metadataId(entry.RepositoryID) || !metadataId(entry.LocalID) { return errors.New("invalid installed tentacle source identity") } } else if entry.RepositoryID != "" || entry.LocalID != "" { return errors.New("tentacle source identity requires a repository origin") } - if !metadata_text(entry.Name, false) || !metadata_text(entry.Version, false) { + if !metadataText(entry.Name, false) || !metadataText(entry.Version, false) { return errors.New("invalid installed tentacle display metadata") } if seen[entry.ID] { @@ -99,9 +99,9 @@ func ValidateEntries(entries []Entry) error { relativeProgram, err := filepath.Rel(entry.PackageDirectory, entry.Program[0]) if entry.Repository == "" || !filepath.IsAbs(entry.PackageDirectory) || filepath.Clean(entry.PackageDirectory) != entry.PackageDirectory || entry.Directory != entry.PackageDirectory || - !valid_digest(entry.PackageSHA256) || !valid_revision(entry.RepositoryRevision) || + !validDigest(entry.PackageSHA256) || !validRevision(entry.RepositoryRevision) || entry.ID != PackageID(Repository{URL: entry.Repository, ID: entry.RepositoryID}, entry.LocalID) || - err != nil || !package_path(filepath.ToSlash(relativeProgram)) || packageDirectories[entry.PackageDirectory] { + err != nil || !packagePath(filepath.ToSlash(relativeProgram)) || packageDirectories[entry.PackageDirectory] { return errors.New("invalid installed package lock") } packageDirectories[entry.PackageDirectory] = true @@ -117,7 +117,7 @@ func ValidateEntries(entries []Entry) error { return err } -func read_registry(path string) ([]byte, error) { +func readRegistry(path string) ([]byte, error) { file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0) if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -142,7 +142,7 @@ func read_registry(path string) ([]byte, error) { func (registry *Registry) Load() ([]Entry, error) { registry.loaded = false - data, err := read_registry(registry.Path) + data, err := readRegistry(registry.Path) if err != nil { return nil, err } @@ -210,7 +210,7 @@ func (registry *Registry) SaveState(entries []Entry, repositories []Repository) return errors.New("tentacle registry is being edited") } defer func() { _ = syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) }() - current, err := read_registry(registry.Path) + current, err := readRegistry(registry.Path) if err != nil { return err } diff --git a/internal/tentacle/remote.go b/internal/tentacle/remote.go index aefd960..f8099d5 100644 --- a/internal/tentacle/remote.go +++ b/internal/tentacle/remote.go @@ -54,10 +54,10 @@ func (session *Session) AuthorizeRemote(role string, grants []string) (tentaclew if session.manager.remotePolicy != nil { return tentaclewire.SessionEvent{}, ErrPermission } - return session.authorize_remote_locked(role, grants, session.outputContext) + return session.authorizeRemoteLocked(role, grants, session.outputContext) } -func (session *Session) authorize_remote_locked(role string, grants []string, parent context.Context) (tentaclewire.SessionEvent, error) { +func (session *Session) authorizeRemoteLocked(role string, grants []string, parent context.Context) (tentaclewire.SessionEvent, error) { if session.state != Active || session.ctx.Err() != nil || !session.spec.SessionEvents { return tentaclewire.SessionEvent{}, ErrUnavailable } @@ -79,7 +79,7 @@ func (session *Session) authorize_remote_locked(role string, grants []string, pa return tentaclewire.SessionEvent{}, ErrBusy } session.manager.remoteMutex.Unlock() - session.revoke_remote_locked("replaced", true) + session.revokeRemoteLocked("replaced", true) // Claim and check atomically: a different session may have acquired the slot // while the old lease was being revoked. session.manager.remoteMutex.Lock() @@ -90,7 +90,7 @@ func (session *Session) authorize_remote_locked(role string, grants []string, pa session.manager.remoteOwner = session session.manager.remoteMutex.Unlock() if session.state != Active { - session.release_remote_owner() + session.releaseRemoteOwner() return tentaclewire.SessionEvent{}, ErrUnavailable } session.remoteEpoch++ @@ -106,13 +106,13 @@ func (session *Session) authorize_remote_locked(role string, grants []string, pa defer session.mutex.Unlock() if session.remote == access { session.log("tentacle remote policy cancelled", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) } }) - session.refresh_remote_locked(remoteApprovalTimeout) + session.refreshRemoteLocked(remoteApprovalTimeout) event := tentaclewire.SessionEvent{Kind: "remote.action", Action: access.action, Epoch: access.epoch, Role: role, Grants: slices.Clone(grants)} - if !session.remote_event_locked(&event) { - session.fail_locked(ErrLimit) + if !session.remoteEventLocked(&event) { + session.failLocked(ErrLimit) return tentaclewire.SessionEvent{}, ErrLimit } return event, nil @@ -123,7 +123,7 @@ func (session *Session) authorize_remote_locked(role string, grants []string, pa func (session *Session) RevokeRemote() { session.mutex.Lock() defer session.mutex.Unlock() - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) } // RevokeRemoteEpoch retires only the action/lease owned by a completed core @@ -132,7 +132,7 @@ func (session *Session) RevokeRemoteEpoch(epoch uint64) { session.mutex.Lock() defer session.mutex.Unlock() if session.remote != nil && session.remote.epoch == epoch { - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) } } @@ -141,7 +141,7 @@ func (session *Session) RevokeRemoteEpoch(epoch uint64) { func (session *Session) RemoteContext(lease tentaclewire.RemoteLease, grant string) (context.Context, error) { session.mutex.Lock() defer session.mutex.Unlock() - access := session.remote_access_locked(lease, grant) + access := session.remoteAccessLocked(lease, grant) if access == nil { return nil, ErrPermission } @@ -154,14 +154,14 @@ func (session *Session) RemoteContext(lease tentaclewire.RemoteLease, grant stri func (session *Session) RemoteLeaseContext(lease tentaclewire.RemoteLease) (context.Context, error) { session.mutex.Lock() defer session.mutex.Unlock() - access := session.remote_lease_locked(lease) + access := session.remoteLeaseLocked(lease) if access == nil { return nil, ErrPermission } return access.ctx, nil } -func (session *Session) release_remote_owner() { +func (session *Session) releaseRemoteOwner() { session.manager.remoteMutex.Lock() if session.manager.remoteOwner == session { session.manager.remoteOwner = nil @@ -169,7 +169,7 @@ func (session *Session) release_remote_owner() { session.manager.remoteMutex.Unlock() } -func (session *Session) revoke_remote_locked(reason string, notify bool) { +func (session *Session) revokeRemoteLocked(reason string, notify bool) { if session.remoteApproval != nil { session.remoteApproval.cancel() session.remoteApproval = nil @@ -230,16 +230,16 @@ func (session *Session) revoke_remote_locked(reason string, notify bool) { if access.timer != nil { access.timer.Stop() } - session.release_remote_owner() + session.releaseRemoteOwner() if notify { event := tentaclewire.SessionEvent{Kind: "remote.revoked", Action: access.action, Lease: access.lease, Epoch: access.epoch, Reason: reason} - if !session.remote_event_locked(&event) { - session.fail_locked(ErrLimit) + if !session.remoteEventLocked(&event) { + session.failLocked(ErrLimit) } } } -func (session *Session) refresh_remote_locked(duration time.Duration) { +func (session *Session) refreshRemoteLocked(duration time.Duration) { access := session.remote access.deadline = time.Now().Add(duration) if access.timer != nil { @@ -250,25 +250,25 @@ func (session *Session) refresh_remote_locked(duration time.Duration) { defer session.mutex.Unlock() // An old timer may already be running when heartbeat resets it. if session.remote == access && !time.Now().Before(access.deadline) { - session.revoke_remote_locked("expired", true) + session.revokeRemoteLocked("expired", true) } }) } -func (session *Session) remote_event_locked(event *tentaclewire.SessionEvent) bool { +func (session *Session) remoteEventLocked(event *tentaclewire.SessionEvent) bool { session.eventSequence++ event.Sequence = session.eventSequence - return session.notify_locked("session.event", event) + return session.notifyLocked("session.event", event) } -func (session *Session) accept_child_request(frame []byte) error { +func (session *Session) acceptChildRequest(frame []byte) error { var message struct { JSONRPC string `json:"jsonrpc"` ID string `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` } - if decode_strict(frame, &message) != nil || message.JSONRPC != "2.0" || !strings.HasPrefix(message.ID, "c:") || message.Method == "" || len(message.Method) > 128 || len(message.Params) == 0 || len(message.Params) > 8192 { + if decodeStrict(frame, &message) != nil || message.JSONRPC != "2.0" || !strings.HasPrefix(message.ID, "c:") || message.Method == "" || len(message.Method) > 128 || len(message.Params) == 0 || len(message.Params) > 8192 { return ErrProtocol } number, err := strconv.ParseUint(strings.TrimPrefix(message.ID, "c:"), 10, 64) @@ -281,7 +281,7 @@ func (session *Session) accept_child_request(frame []byte) error { return ErrProtocol } session.childSequence = number - value, failure := session.remote_call_locked(message.Method, message.Params) + value, failure := session.remoteCallLocked(message.Method, message.Params) reply := map[string]any{"jsonrpc": "2.0", "id": message.ID} if failure != nil { session.log("tentacle session operation rejected", "operation", diagnosticOperation(message.Method), "code", failure.Code, "epoch", session.remoteEpoch) @@ -290,27 +290,27 @@ func (session *Session) accept_child_request(frame []byte) error { reply["result"] = value } data, err := json.Marshal(reply) - if err != nil || !session.enqueue_locked(outgoing{frame: append(data, '\n')}) { + if err != nil || !session.enqueueLocked(outgoing{frame: append(data, '\n')}) { return ErrLimit } return nil } -func (session *Session) remote_call_locked(method string, params json.RawMessage) (any, *RPCError) { +func (session *Session) remoteCallLocked(method string, params json.RawMessage) (any, *RPCError) { denied := &RPCError{Code: -32001, Message: "Session permission denied"} invalid := &RPCError{Code: -32602, Message: "Invalid session parameters"} switch method { case "remote.present": - return session.remote_present_locked(params) + return session.remotePresentLocked(params) case "remote.key": - return session.remote_key_locked(params) + return session.remoteKeyLocked(params) case "remote.focus": - return session.remote_focus_locked(params) + return session.remoteFocusLocked(params) case "remote.braille": - return session.remote_braille_locked(params) + return session.remoteBrailleLocked(params) case "remote.open": var request tentaclewire.RemoteOpen - if decode_strict(params, &request) != nil || len(request.Action) != 32 || request.Epoch == 0 || !tentaclewire.ValidRoleGrants(request.Role, request.Grants) { + if decodeStrict(params, &request) != nil || len(request.Action) != 32 || request.Epoch == 0 || !tentaclewire.ValidRoleGrants(request.Role, request.Grants) { return nil, invalid } access := session.remote @@ -327,12 +327,12 @@ func (session *Session) remote_call_locked(method string, params json.RawMessage return nil, &RPCError{Code: -32603, Message: "Session unavailable"} } access.lease, access.action, access.grants = hex.EncodeToString(token[:]), "", slices.Clone(request.Grants) - session.refresh_remote_locked(RemoteHeartbeatTimeout) + session.refreshRemoteLocked(RemoteHeartbeatTimeout) session.log("tentacle remote lease opened", "epoch", access.epoch, "role", access.role, "heartbeat_timeout_ms", RemoteHeartbeatTimeout.Milliseconds()) return tentaclewire.RemoteLease{Lease: access.lease, Epoch: access.epoch}, nil case "remote.close", "remote.heartbeat": var request tentaclewire.RemoteOperation - if decode_strict(params, &request) != nil || len(request.Lease) != 32 || request.Epoch == 0 || request.Sequence == 0 { + if decodeStrict(params, &request) != nil || len(request.Lease) != 32 || request.Epoch == 0 || request.Sequence == 0 { return nil, invalid } access := session.remote @@ -352,9 +352,9 @@ func (session *Session) remote_call_locked(method string, params json.RawMessage } access.sequence = request.Sequence if method == "remote.close" { - session.revoke_remote_locked("closed", true) + session.revokeRemoteLocked("closed", true) } else { - session.refresh_remote_locked(RemoteHeartbeatTimeout) + session.refreshRemoteLocked(RemoteHeartbeatTimeout) } return struct{}{}, nil default: diff --git a/internal/tentacle/remote_background_test.go b/internal/tentacle/remote_background_test.go index 8b48d5c..dffa141 100644 --- a/internal/tentacle/remote_background_test.go +++ b/internal/tentacle/remote_background_test.go @@ -14,13 +14,13 @@ import ( func TestRemoteBackgroundLeaseOwnershipAndLifetime(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) policy := NewRemotePolicy() if err := manager.UseRemotePolicy(policy); err != nil { t.Fatal(err) } session := startSessionSDK(t, manager, language, "speech") - lease := speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + lease := speechFixtureLease(t, session, "controlled", []string{"output-observe"}) lifetime, err := session.RemoteLeaseContext(lease) if err != nil || lifetime.Err() != nil { t.Fatal("live owned lease unavailable", err) @@ -48,7 +48,7 @@ func TestRemoteBackgroundLeaseOwnershipAndLifetime(t *testing.T) { // A replacement remains distinct, even while old forms finish. session.RevokeRemote() invokeSessionSDK(t, session, "event", nil) - replacement := speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + replacement := speechFixtureLease(t, session, "controlled", []string{"output-observe"}) if _, err := session.RemoteLeaseContext(lease); err == nil { t.Fatal("old controls followed replacement consent") } diff --git a/internal/tentacle/remote_braille.go b/internal/tentacle/remote_braille.go index a9248f8..79376b6 100644 --- a/internal/tentacle/remote_braille.go +++ b/internal/tentacle/remote_braille.go @@ -33,13 +33,13 @@ func (session *Session) EnableRemoteBraille() <-chan RemoteBrailleDelivery { return session.remoteBraille } -func (session *Session) remote_braille_locked(params json.RawMessage) (any, *RPCError) { +func (session *Session) remoteBrailleLocked(params json.RawMessage) (any, *RPCError) { var request tentaclewire.RemoteBrailleRequest - if decode_strict(params, &request) != nil { + if decodeStrict(params, &request) != nil { return nil, &RPCError{Code: -32602, Message: "Invalid session parameters"} } lease := tentaclewire.RemoteLease{Lease: request.Lease, Epoch: request.Epoch} - access := session.remote_access_locked(lease, "braille-stream") + access := session.remoteAccessLocked(lease, "braille-stream") if access == nil || request.Sequence <= access.sequence || !tentaclewire.ValidRemoteBrailleFor(access.role, true, request.Braille) { return nil, &RPCError{Code: -32001, Message: "Session permission denied"} } @@ -52,7 +52,7 @@ func (session *Session) remote_braille_locked(params json.RawMessage) (any, *RPC return struct{}{}, nil default: session.log("tentacle remote queue full", "queue", "braille", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) return nil, &RPCError{Code: -32002, Message: "Remote Braille queue full"} } } @@ -63,7 +63,7 @@ func (session *Session) remote_braille_locked(params json.RawMessage) (any, *RPC func (session *Session) PublishRemoteBraille(lease tentaclewire.RemoteLease, value tentaclewire.RemoteBraille) error { session.mutex.Lock() defer session.mutex.Unlock() - access := session.remote_access_locked(lease, "braille-stream") + access := session.remoteAccessLocked(lease, "braille-stream") if access == nil || !tentaclewire.ValidRemoteBrailleFor(access.role, false, value) { return ErrPermission } @@ -72,8 +72,8 @@ func (session *Session) PublishRemoteBraille(lease tentaclewire.RemoteLease, val value.Cells = nil } event := tentaclewire.SessionEvent{Kind: "remote.braille", Lease: lease.Lease, Epoch: lease.Epoch, Braille: &value} - if !session.remote_event_locked(&event) { - session.fail_locked(ErrLimit) + if !session.remoteEventLocked(&event) { + session.failLocked(ErrLimit) return ErrLimit } return nil diff --git a/internal/tentacle/remote_braille_test.go b/internal/tentacle/remote_braille_test.go index 3712959..fe85d5b 100644 --- a/internal/tentacle/remote_braille_test.go +++ b/internal/tentacle/remote_braille_test.go @@ -21,9 +21,9 @@ func brailleRequest(lease tentaclewire.RemoteLease, sequence uint64, value tenta func TestRemoteBrailleSDKDirectionsAndEvents(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "braille", "braille-stream") - lease := speech_fixture_lease(t, session, "controlled", []string{"output-observe", "braille-stream"}) + lease := speechFixtureLease(t, session, "controlled", []string{"output-observe", "braille-stream"}) size := tentaclewire.RemoteBraille{Op: "size", Width: 40} if _, code := remoteCall(t, session, "remote.braille", brailleRequest(lease, 1, size)); code != -32601 { t.Fatal("Braille admitted without owner", code) @@ -55,7 +55,7 @@ func TestRemoteBrailleSDKDirectionsAndEvents(t *testing.T) { } session.RevokeRemote() nextSDKEvent(t, session) - lease = speech_fixture_lease(t, session, "controller", []string{"remote-present", "braille-stream"}) + lease = speechFixtureLease(t, session, "controller", []string{"remote-present", "braille-stream"}) if _, code := remoteCall(t, session, "remote.braille", brailleRequest(lease, 1, cells)); code != 0 { t.Fatal("controller cells refused", code) } @@ -94,17 +94,17 @@ func TestRemoteBrailleSDKDirectionsAndEvents(t *testing.T) { } func TestRemoteBrailleSDKGrantAndSaturation(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, "go", "braille", "braille-stream") deliveries := session.EnableRemoteBraille() - lease := speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + lease := speechFixtureLease(t, session, "controlled", []string{"output-observe"}) size := tentaclewire.RemoteBraille{Op: "size", Width: 40} if _, code := remoteCall(t, session, "remote.braille", brailleRequest(lease, 1, size)); code != -32001 { t.Fatal("Braille admitted without grant", code) } session.RevokeRemote() invokeSessionSDK(t, session, "event", nil) - lease = speech_fixture_lease(t, session, "controlled", []string{"braille-stream"}) + lease = speechFixtureLease(t, session, "controlled", []string{"braille-stream"}) for sequence := uint64(1); sequence <= tentaclewire.RemoteBrailleQueueSize; sequence++ { if _, code := remoteCall(t, session, "remote.braille", brailleRequest(lease, sequence, size)); code != 0 { t.Fatal("refused before saturation", code) diff --git a/internal/tentacle/remote_capture.go b/internal/tentacle/remote_capture.go index 8c0bf2d..f1641e5 100644 --- a/internal/tentacle/remote_capture.go +++ b/internal/tentacle/remote_capture.go @@ -34,13 +34,13 @@ func (session *Session) EnableRemoteCapture() <-chan RemoteFocusDelivery { return session.remoteCapture } -func (session *Session) remote_focus_locked(params json.RawMessage) (any, *RPCError) { +func (session *Session) remoteFocusLocked(params json.RawMessage) (any, *RPCError) { var request tentaclewire.RemoteFocusRequest - if decode_strict(params, &request) != nil { + if decodeStrict(params, &request) != nil { return nil, &RPCError{Code: -32602, Message: "Invalid session parameters"} } lease := tentaclewire.RemoteLease{Lease: request.Lease, Epoch: request.Epoch} - access := session.remote_access_locked(lease, "keyboard-capture") + access := session.remoteAccessLocked(lease, "keyboard-capture") if access == nil || access.role != "controller" || request.Sequence <= access.sequence { return nil, &RPCError{Code: -32001, Message: "Session permission denied"} } @@ -54,13 +54,13 @@ func (session *Session) remote_focus_locked(params json.RawMessage) (any, *RPCEr default: // A lost "local" request must never leave capture active. session.log("tentacle remote queue full", "queue", "focus", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) return nil, &RPCError{Code: -32002, Message: "Remote focus queue full"} } } -func (session *Session) capture_access_locked(lease tentaclewire.RemoteLease) *remoteAccess { - access := session.remote_access_locked(lease, "keyboard-capture") +func (session *Session) captureAccessLocked(lease tentaclewire.RemoteLease) *remoteAccess { + access := session.remoteAccessLocked(lease, "keyboard-capture") if access == nil || access.role != "controller" { return nil } @@ -76,12 +76,12 @@ func (session *Session) PublishRemoteInput(lease tentaclewire.RemoteLease, key t } session.mutex.Lock() defer session.mutex.Unlock() - if session.capture_access_locked(lease) == nil { + if session.captureAccessLocked(lease) == nil { return ErrPermission } event := tentaclewire.SessionEvent{Kind: "remote.input", Lease: lease.Lease, Epoch: lease.Epoch, Input: &key} - if !session.remote_event_locked(&event) { - session.fail_locked(ErrLimit) + if !session.remoteEventLocked(&event) { + session.failLocked(ErrLimit) return ErrLimit } return nil @@ -96,12 +96,12 @@ func (session *Session) PublishRemoteFocus(lease tentaclewire.RemoteLease, focus } session.mutex.Lock() defer session.mutex.Unlock() - if session.capture_access_locked(lease) == nil { + if session.captureAccessLocked(lease) == nil { return ErrPermission } event := tentaclewire.SessionEvent{Kind: "remote.focus", Lease: lease.Lease, Epoch: lease.Epoch, Focus: focus, Reason: reason} - if !session.remote_event_locked(&event) { - session.fail_locked(ErrLimit) + if !session.remoteEventLocked(&event) { + session.failLocked(ErrLimit) return ErrLimit } return nil diff --git a/internal/tentacle/remote_capture_test.go b/internal/tentacle/remote_capture_test.go index c78e386..c87399f 100644 --- a/internal/tentacle/remote_capture_test.go +++ b/internal/tentacle/remote_capture_test.go @@ -29,9 +29,9 @@ func nextSDKEvent(t *testing.T, session *Session) tentaclewire.SessionEvent { func TestRemoteCaptureSDKFocusAndInputEvents(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "capture", "keyboard-capture") - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present", "keyboard-capture"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present", "keyboard-capture"}) if _, code := remoteCall(t, session, "remote.focus", focusRequest(lease, 1, true)); code != -32601 { t.Fatal("focus admitted without capture owner", code) } @@ -100,21 +100,21 @@ func TestRemoteCaptureSDKFocusAndInputEvents(t *testing.T) { func TestRemoteCaptureSDKPermissionAndParameters(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "capture", "keyboard-capture", "keyboard-inject") deliveries := session.EnableRemoteCapture() - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) if _, code := remoteCall(t, session, "remote.focus", focusRequest(lease, 1, true)); code != -32001 { t.Fatal("speech-only controller requested capture", code) } if !errors.Is(session.PublishRemoteInput(lease, tentaclewire.RemoteCapturedKey{Code: 38, Name: "a", Pressed: true}), ErrPermission) { t.Fatal("input published without keyboard-capture") } - lease = speech_fixture_lease(t, session, "controlled", []string{"keyboard-inject"}) + lease = speechFixtureLease(t, session, "controlled", []string{"keyboard-inject"}) if _, code := remoteCall(t, session, "remote.focus", focusRequest(lease, 1, true)); code != -32001 { t.Fatal("controlled role requested capture", code) } - lease = speech_fixture_lease(t, session, "controller", []string{"keyboard-capture"}) + lease = speechFixtureLease(t, session, "controller", []string{"keyboard-capture"}) data, _ := json.Marshal(focusRequest(lease, 1, true)) for _, raw := range []string{ strings.Replace(string(data), `"remote":true`, `"remote":null`, 1), diff --git a/internal/tentacle/remote_key.go b/internal/tentacle/remote_key.go index 397aa12..86ab9d0 100644 --- a/internal/tentacle/remote_key.go +++ b/internal/tentacle/remote_key.go @@ -39,13 +39,13 @@ func (session *Session) EnableRemoteKeys() <-chan RemoteKeyDelivery { return session.remoteKeys } -func (session *Session) remote_key_locked(params json.RawMessage) (any, *RPCError) { +func (session *Session) remoteKeyLocked(params json.RawMessage) (any, *RPCError) { var request tentaclewire.RemoteKeyRequest - if decode_strict(params, &request) != nil { + if decodeStrict(params, &request) != nil { return nil, &RPCError{Code: -32602, Message: "Invalid session parameters"} } lease := tentaclewire.RemoteLease{Lease: request.Lease, Epoch: request.Epoch} - access := session.remote_access_locked(lease, "keyboard-inject") + access := session.remoteAccessLocked(lease, "keyboard-inject") if access == nil || access.role != "controlled" || request.Sequence <= access.sequence { return nil, &RPCError{Code: -32001, Message: "Session permission denied"} } @@ -58,7 +58,7 @@ func (session *Session) remote_key_locked(params json.RawMessage) (any, *RPCErro bytes := len(data) if access.keyItems == tentaclewire.RemoteKeyQueueSize || access.keyBytes+bytes > tentaclewire.RemoteKeyQueueBytes { session.log("tentacle remote queue full", "queue", "keyboard", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) return nil, &RPCError{Code: -32002, Message: "Remote keyboard queue full"} } access.keyItems++ @@ -81,7 +81,7 @@ func (session *Session) remote_key_locked(params json.RawMessage) (any, *RPCErro default: // Losing a release must never leave the input lease active. session.log("tentacle remote queue full", "queue", "keyboard", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) return nil, &RPCError{Code: -32002, Message: "Remote keyboard queue full"} } } diff --git a/internal/tentacle/remote_key_test.go b/internal/tentacle/remote_key_test.go index 30d9030..49cf15e 100644 --- a/internal/tentacle/remote_key_test.go +++ b/internal/tentacle/remote_key_test.go @@ -24,9 +24,9 @@ func keyRequest(lease tentaclewire.RemoteLease, sequence uint64, pressed bool) t func TestRemoteKeySDKMailboxAndSequence(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "keys", "keyboard-inject") - lease := speech_fixture_lease(t, session, "controlled", []string{"keyboard-inject"}) + lease := speechFixtureLease(t, session, "controlled", []string{"keyboard-inject"}) request := keyRequest(lease, 1, true) if _, code := remoteCall(t, session, "remote.key", request); code != -32601 { t.Fatal("accepted keys without reader input owner", code) @@ -91,18 +91,18 @@ func TestRemoteKeySDKMailboxAndSequence(t *testing.T) { func TestRemoteKeySDKPermissionAndParameters(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "keys", "keyboard-inject") deliveries := session.EnableRemoteKeys() - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) if _, code := remoteCall(t, session, "remote.key", keyRequest(lease, 1, true)); code != -32001 { t.Fatal("controller role injected input", code) } - lease = speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + lease = speechFixtureLease(t, session, "controlled", []string{"output-observe"}) if _, code := remoteCall(t, session, "remote.key", keyRequest(lease, 1, true)); code != -32001 { t.Fatal("output grant allowed input", code) } - lease = speech_fixture_lease(t, session, "controlled", []string{"keyboard-inject"}) + lease = speechFixtureLease(t, session, "controlled", []string{"keyboard-inject"}) request := keyRequest(lease, 1, true) for _, foreign := range []tentaclewire.RemoteKeyRequest{ keyRequest(tentaclewire.RemoteLease{Lease: strings.Repeat("f", 32), Epoch: lease.Epoch}, 1, true), @@ -142,8 +142,8 @@ func TestRemoteKeySDKPermissionAndParameters(t *testing.T) { func TestRemoteKeySDKOverflowRetiresInFlightWork(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - session := startSessionSDK(t, test_manager(t, DefaultLimits(), nil), language, "keys", "keyboard-inject") - lease := speech_fixture_lease(t, session, "controlled", []string{"keyboard-inject"}) + session := startSessionSDK(t, testManager(t, DefaultLimits(), nil), language, "keys", "keyboard-inject") + lease := speechFixtureLease(t, session, "controlled", []string{"keyboard-inject"}) deliveries := session.EnableRemoteKeys() request := keyRequest(lease, 1, true) if _, code := remoteCall(t, session, "remote.key", request); code != 0 { @@ -191,13 +191,13 @@ func TestRemoteKeySDKRetirementAndReplacement(t *testing.T) { for _, language := range []string{"go", "python"} { for _, reason := range []string{"local", "close", "replace", "expire", "disable", "failure", "policy"} { t.Run(language+"/"+reason, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) policy := NewRemotePolicy() if err := manager.UseRemotePolicy(policy); err != nil { t.Fatal(err) } session := startSessionSDK(t, manager, language, "keys", "keyboard-inject") - lease := speech_fixture_lease(t, session, "controlled", []string{"keyboard-inject"}) + lease := speechFixtureLease(t, session, "controlled", []string{"keyboard-inject"}) deliveries := session.EnableRemoteKeys() for sequence := uint64(1); sequence <= 2; sequence++ { if _, code := remoteCall(t, session, "remote.key", keyRequest(lease, sequence, true)); code != 0 { @@ -216,7 +216,7 @@ func TestRemoteKeySDKRetirementAndReplacement(t *testing.T) { t.Fatal(code) } case "replace": - fresh := speech_fixture_lease(t, session, "controlled", []string{"keyboard-inject"}) + fresh := speechFixtureLease(t, session, "controlled", []string{"keyboard-inject"}) if _, code := remoteCall(t, session, "remote.key", keyRequest(fresh, 1, true)); code != 0 { t.Fatal(code) } @@ -232,7 +232,7 @@ func TestRemoteKeySDKRetirementAndReplacement(t *testing.T) { case "expire", "policy": session.mutex.Lock() if reason == "expire" { - session.refresh_remote_locked(time.Millisecond) + session.refreshRemoteLocked(time.Millisecond) } else { policy.SetAvailable(false) if inFlight.Context.Err() == nil { diff --git a/internal/tentacle/remote_output.go b/internal/tentacle/remote_output.go index a461b42..1541f53 100644 --- a/internal/tentacle/remote_output.go +++ b/internal/tentacle/remote_output.go @@ -33,7 +33,7 @@ func (manager *Manager) CaptureRemoteSpeechOutput() *RemoteSpeechOutput { return nil } lease := tentaclewire.RemoteLease{Lease: access.lease, Epoch: access.epoch} - if session.remote_access_locked(lease, "output-observe") == nil || access.role != "controlled" { + if session.remoteAccessLocked(lease, "output-observe") == nil || access.role != "controlled" { return nil } return &RemoteSpeechOutput{session: session, lease: lease, ctx: access.ctx} @@ -90,7 +90,7 @@ func (output *RemoteSpeechOutput) publish(speeches []tentaclewire.RemoteSpeech, policy.mutex.Lock() defer policy.mutex.Unlock() } - access := session.remote_access_locked(output.lease, "output-observe") + access := session.remoteAccessLocked(output.lease, "output-observe") if access == nil || access.role != "controlled" || output.ctx.Err() != nil { return ErrPermission } @@ -99,7 +99,7 @@ func (output *RemoteSpeechOutput) publish(speeches []tentaclewire.RemoteSpeech, for index, speech := range speeches { event := tentaclewire.SessionEvent{Sequence: session.eventSequence + uint64(index) + 1, Kind: "remote.output", Lease: output.lease.Lease, Epoch: output.lease.Epoch, Speech: &speech} - frame, err := encode_request("", "session.event", event) + frame, err := encodeRequest("", "session.event", event) if err != nil || !tentaclewire.ValidRemoteSpeech(speech) { overflow = true break @@ -111,7 +111,7 @@ func (output *RemoteSpeechOutput) publish(speeches []tentaclewire.RemoteSpeech, session.queuedBytes+bytes > tentaclewire.SessionQueueBytes { // Losing a cancel or a suffix must never leave an apparently healthy // speech stream. Match the existing observed-output overflow policy. - session.fail_locked(ErrLimit) + session.failLocked(ErrLimit) return ErrLimit } for _, frame := range frames { diff --git a/internal/tentacle/remote_output_test.go b/internal/tentacle/remote_output_test.go index 626346d..d661195 100644 --- a/internal/tentacle/remote_output_test.go +++ b/internal/tentacle/remote_output_test.go @@ -17,18 +17,18 @@ import ( func TestRemoteSpeechOutputSDKTicket(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "speech") if manager.CaptureRemoteSpeechOutput() != nil { t.Fatal("captured output without consent") } - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) if manager.CaptureRemoteSpeechOutput() != nil { t.Fatal("controller acquired observation") } session.RevokeRemote() invokeSessionSDK(t, session, "event", nil) // Revocation. - lease = speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + lease = speechFixtureLease(t, session, "controlled", []string{"output-observe"}) output := manager.CaptureRemoteSpeechOutput() if output == nil { t.Fatal("live controlled output unavailable") @@ -72,7 +72,7 @@ func TestRemoteSpeechOutputSDKTicket(t *testing.T) { } session.RevokeRemote() invokeSessionSDK(t, session, "event", nil) - _ = speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + _ = speechFixtureLease(t, session, "controlled", []string{"output-observe"}) if !errors.Is(output.PublishText("old", false), ErrPermission) || !errors.Is(output.Cancel(), ErrPermission) { t.Fatal("old ticket followed replacement lease") } @@ -85,7 +85,7 @@ func TestRemoteSpeechOutputSDKTicket(t *testing.T) { func TestRemoteSpeechOutputAdmissionAndPolicy(t *testing.T) { for _, mode := range []string{"slots", "bytes", "frames", "invalid", "policy", "expired", "pending"} { t.Run(mode, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) ctx, cancel := context.WithCancel(t.Context()) defer cancel() outputContext, revoke := context.WithCancel(ctx) diff --git a/internal/tentacle/remote_policy.go b/internal/tentacle/remote_policy.go index 4224054..df894b6 100644 --- a/internal/tentacle/remote_policy.go +++ b/internal/tentacle/remote_policy.go @@ -77,7 +77,7 @@ func (session *Session) BeginRemoteApproval(role string, grants []string) (*Remo if !policy.available { return nil, ErrPermission } - session.revoke_remote_locked("replaced", true) + session.revokeRemoteLocked("replaced", true) if session.state != Active { return nil, ErrUnavailable } @@ -131,5 +131,5 @@ func (session *Session) AuthorizeRemoteWithApproval(approval *RemoteApproval, ro } session.remoteApproval = nil defer approval.cancel() - return session.authorize_remote_locked(role, grants, approval.lifetime) + return session.authorizeRemoteLocked(role, grants, approval.lifetime) } diff --git a/internal/tentacle/remote_policy_test.go b/internal/tentacle/remote_policy_test.go index fb495cc..6a45739 100644 --- a/internal/tentacle/remote_policy_test.go +++ b/internal/tentacle/remote_policy_test.go @@ -32,22 +32,22 @@ func TestRemoteCloseBeforeRetirementCallback(t *testing.T) { manager.remoteOwner = session operation := tentaclewire.RemoteOperation{Lease: access.lease, Epoch: 1, Sequence: 1} data, _ := json.Marshal(operation) - if _, failure := session.remote_call_locked("remote.heartbeat", data); failure == nil { + if _, failure := session.remoteCallLocked("remote.heartbeat", data); failure == nil { t.Fatal("heartbeat revived retired authority") } wrong := operation wrong.Lease = strings.Repeat("b", 32) invalid, _ := json.Marshal(wrong) - if _, failure := session.remote_call_locked("remote.close", invalid); failure == nil { + if _, failure := session.remoteCallLocked("remote.close", invalid); failure == nil { t.Fatal("foreign token closed pending retirement") } - if _, failure := session.remote_call_locked("remote.close", data); failure != nil { + if _, failure := session.remoteCallLocked("remote.close", data); failure != nil { t.Fatal("cleanup rejected before retirement callback", failure) } if session.remote != nil || manager.remoteOwner != nil { t.Fatal("close retained remote ownership") } - if _, failure := session.remote_call_locked("remote.close", data); failure != nil { + if _, failure := session.remoteCallLocked("remote.close", data); failure != nil { t.Fatal("repeated cleanup failed", failure) } }) @@ -57,7 +57,7 @@ func TestRemoteCloseBeforeRetirementCallback(t *testing.T) { func TestRemotePolicyRevokesPendingAndLiveSDKAccess(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) policy := NewRemotePolicy() if err := manager.UseRemotePolicy(policy); err != nil { t.Fatal(err) diff --git a/internal/tentacle/remote_speech.go b/internal/tentacle/remote_speech.go index b8ea9cd..306b848 100644 --- a/internal/tentacle/remote_speech.go +++ b/internal/tentacle/remote_speech.go @@ -50,15 +50,15 @@ func (session *Session) EnableRemoteSpeech() <-chan RemoteSpeechDelivery { return session.remoteSpeech } -func (session *Session) remote_access_locked(lease tentaclewire.RemoteLease, grant string) *remoteAccess { - access := session.remote_lease_locked(lease) +func (session *Session) remoteAccessLocked(lease tentaclewire.RemoteLease, grant string) *remoteAccess { + access := session.remoteLeaseLocked(lease) if access == nil || !slices.Contains(access.grants, grant) { return nil } return access } -func (session *Session) remote_lease_locked(lease tentaclewire.RemoteLease) *remoteAccess { +func (session *Session) remoteLeaseLocked(lease tentaclewire.RemoteLease) *remoteAccess { access := session.remote if session.state != Active || access == nil || access.lease == "" || access.lease != lease.Lease || access.epoch != lease.Epoch || !time.Now().Before(access.deadline) || access.ctx.Err() != nil { return nil @@ -76,26 +76,26 @@ func (session *Session) PublishRemoteSpeech(lease tentaclewire.RemoteLease, orig } session.mutex.Lock() defer session.mutex.Unlock() - access := session.remote_access_locked(lease, "output-observe") + access := session.remoteAccessLocked(lease, "output-observe") if access == nil || access.role != "controlled" { return ErrPermission } event := tentaclewire.SessionEvent{Kind: "remote.output", Lease: lease.Lease, Epoch: lease.Epoch, Speech: &speech} - if !session.remote_event_locked(&event) { + if !session.remoteEventLocked(&event) { // Shared lifecycle IPC cannot lose revocation or cancel order. - session.fail_locked(ErrLimit) + session.failLocked(ErrLimit) return ErrLimit } return nil } -func (session *Session) remote_present_locked(params json.RawMessage) (any, *RPCError) { +func (session *Session) remotePresentLocked(params json.RawMessage) (any, *RPCError) { var request tentaclewire.RemotePresentation - if decode_strict(params, &request) != nil { + if decodeStrict(params, &request) != nil { return nil, &RPCError{Code: -32602, Message: "Invalid session parameters"} } lease := tentaclewire.RemoteLease{Lease: request.Lease, Epoch: request.Epoch} - access := session.remote_access_locked(lease, "remote-present") + access := session.remoteAccessLocked(lease, "remote-present") if access == nil || access.role != "controller" || request.Sequence <= access.sequence { return nil, &RPCError{Code: -32001, Message: "Session permission denied"} } @@ -116,7 +116,7 @@ func (session *Session) remote_present_locked(params json.RawMessage) (any, *RPC data, _ := json.Marshal(request.Speech) if access.speechItems == tentaclewire.RemoteSpeechQueueSize || access.speechBytes+len(data) > tentaclewire.RemoteSpeechQueueBytes { session.log("tentacle remote queue full", "queue", "speech", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) return nil, &RPCError{Code: -32002, Message: "Remote speech queue full"} } access.speechItems++ @@ -146,7 +146,7 @@ func (session *Session) remote_present_locked(params json.RawMessage) (any, *RPC default: // A dropped cancel would let stale speech outlive the intended stream. session.log("tentacle remote queue full", "queue", "speech", "epoch", access.epoch) - session.revoke_remote_locked("local", true) + session.revokeRemoteLocked("local", true) return nil, &RPCError{Code: -32002, Message: "Remote speech queue full"} } } diff --git a/internal/tentacle/remote_speech_test.go b/internal/tentacle/remote_speech_test.go index f52c66a..d8caaa1 100644 --- a/internal/tentacle/remote_speech_test.go +++ b/internal/tentacle/remote_speech_test.go @@ -13,7 +13,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) -func speech_fixture_lease(t *testing.T, session *Session, role string, grants []string) tentaclewire.RemoteLease { +func speechFixtureLease(t *testing.T, session *Session, role string, grants []string) tentaclewire.RemoteLease { t.Helper() var action tentaclewire.SessionEvent var err error @@ -44,9 +44,9 @@ func speech_fixture_lease(t *testing.T, session *Session, role string, grants [] func TestRemoteSpeechSDKDeliveryAndRevocation(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "speech") - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) request := tentaclewire.RemotePresentation{RemoteOperation: tentaclewire.RemoteOperation{Lease: lease.Lease, Epoch: lease.Epoch, Sequence: 1}, Speech: tentaclewire.RemoteSpeech{Kind: "speak", Parts: []tentaclewire.RemoteSpeechPart{{Text: " text\t世界 ", Characters: true, Language: "en_US"}}}} if _, code := remoteCall(t, session, "remote.present", request); code != -32601 { t.Fatal("accepted without reader owner", code) @@ -107,9 +107,9 @@ func TestRemoteSpeechSDKDeliveryAndRevocation(t *testing.T) { func TestRemoteSpeechSDKOutputAndOrigins(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, language, "speech") - lease := speech_fixture_lease(t, session, "controlled", []string{"output-observe"}) + lease := speechFixtureLease(t, session, "controlled", []string{"output-observe"}) value := tentaclewire.RemoteSpeech{Kind: "speak", Priority: 2, Parts: []tentaclewire.RemoteSpeechPart{{Text: " whitespace \n "}}} for _, origin := range []string{"remote", "status", "secret", ""} { if err := session.PublishRemoteSpeech(lease, origin, value); err == nil { @@ -138,9 +138,9 @@ func TestRemoteSpeechSDKOutputAndOrigins(t *testing.T) { } func TestRemoteSpeechQueueOverflowRetiresLease(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) session := startSessionSDK(t, manager, "go", "speech") - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) deliveries := session.EnableRemoteSpeech() request := tentaclewire.RemotePresentation{RemoteOperation: tentaclewire.RemoteOperation{Lease: lease.Lease, Epoch: lease.Epoch}, Speech: tentaclewire.RemoteSpeech{Kind: "cancel"}} for index := 1; index <= tentaclewire.RemoteSpeechQueueSize; index++ { @@ -166,8 +166,8 @@ func TestRemoteSpeechQueueOverflowRetiresLease(t *testing.T) { func TestRemoteSpeechSDKAtomicUtterance(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - session := startSessionSDK(t, test_manager(t, DefaultLimits(), nil), language, "speech") - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + session := startSessionSDK(t, testManager(t, DefaultLimits(), nil), language, "speech") + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) deliveries := session.EnableRemoteSpeech() frames := []tentaclewire.RemoteSpeech{ {Kind: "speak", Priority: 2, Parts: []tentaclewire.RemoteSpeechPart{{Text: " prefix\t", Characters: true, Language: "fr"}}}, @@ -246,7 +246,7 @@ func TestRemoteSpeechSDKAtomicUtterance(t *testing.T) { func TestRemoteSpeechSDKAssemblyRetirement(t *testing.T) { for _, mode := range []string{"revoke", "replace", "close", "expiry", "policy"} { t.Run(mode, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) policy := NewRemotePolicy() if mode == "policy" { if err := manager.UseRemotePolicy(policy); err != nil { @@ -254,7 +254,7 @@ func TestRemoteSpeechSDKAssemblyRetirement(t *testing.T) { } } session := startSessionSDK(t, manager, "go", "speech") - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) deliveries := session.EnableRemoteSpeech() request := tentaclewire.RemotePresentation{RemoteOperation: tentaclewire.RemoteOperation{Lease: lease.Lease, Epoch: lease.Epoch, Sequence: 1}, Speech: tentaclewire.RemoteSpeech{Kind: "cancel"}} if _, code := remoteCall(t, session, "remote.present", request); code != 0 { @@ -273,7 +273,7 @@ func TestRemoteSpeechSDKAssemblyRetirement(t *testing.T) { case "revoke": session.RevokeRemote() case "replace": - speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + speechFixtureLease(t, session, "controller", []string{"remote-present"}) case "close": request.Sequence++ if _, code := remoteCall(t, session, "remote.close", request.RemoteOperation); code != 0 { @@ -281,9 +281,9 @@ func TestRemoteSpeechSDKAssemblyRetirement(t *testing.T) { } case "expiry": session.mutex.Lock() - session.refresh_remote_locked(time.Millisecond) + session.refreshRemoteLocked(time.Millisecond) session.mutex.Unlock() - wait_signal(t, old.ctx.Done()) + waitSignal(t, old.ctx.Done()) case "policy": // Cancellation cannot wait for the session mutex; lock/handoff // invalidates work before asynchronous mailbox cleanup. @@ -320,8 +320,8 @@ func TestRemoteSpeechSDKAssemblyRetirement(t *testing.T) { func TestRemoteSpeechSDKAssemblyBudget(t *testing.T) { for _, limit := range []string{"items", "bytes"} { t.Run(limit, func(t *testing.T) { - session := startSessionSDK(t, test_manager(t, DefaultLimits(), nil), "python", "speech") - lease := speech_fixture_lease(t, session, "controller", []string{"remote-present"}) + session := startSessionSDK(t, testManager(t, DefaultLimits(), nil), "python", "speech") + lease := speechFixtureLease(t, session, "controller", []string{"remote-present"}) deliveries := session.EnableRemoteSpeech() text := "x" if limit == "bytes" { diff --git a/internal/tentacle/remote_test.go b/internal/tentacle/remote_test.go index d55f1c4..7eb1534 100644 --- a/internal/tentacle/remote_test.go +++ b/internal/tentacle/remote_test.go @@ -86,7 +86,7 @@ func startSessionSDK(t *testing.T, manager *Manager, language, id string, extraG if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if err := session.Activate(); err != nil { state, reason := session.Status() t.Fatalf("activate: %v, %s %v", err, state, reason) @@ -104,7 +104,7 @@ func invokeSessionSDK(t *testing.T, session *Session, command string, params any if err != nil { t.Fatal(err) } - result := wait_result(t, pending) + result := waitResult(t, pending) if result.Err != nil { t.Fatal(result.Err) } @@ -196,7 +196,7 @@ func TestSessionSDKLifecycleConformance(t *testing.T) { t.Run(language, func(t *testing.T) { limits := DefaultLimits() limits.RequestTimeout = 5 * time.Second - manager := test_manager(t, limits, nil) + manager := testManager(t, limits, nil) session := startSessionSDK(t, manager, language, "session-sdk") if _, code := remoteCall(t, session, "remote.open", tentaclewire.RemoteOpen{Action: strings.Repeat("a", 32), Epoch: 1, Role: "controlled", Grants: []string{"output-observe"}}); code != -32001 { t.Fatal("child minted consent", code) @@ -269,10 +269,10 @@ func TestSessionSDKLifecycleConformance(t *testing.T) { if current.Err() == nil { t.Fatal("disable left lease live") } - if result := wait_result(t, waiting); result.Err == nil { + if result := waitResult(t, waiting); result.Err == nil { t.Fatal("blocked handler survived disable") } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) }) } } @@ -280,7 +280,7 @@ func TestSessionSDKLifecycleConformance(t *testing.T) { func TestSessionLeaseExpiryAndExclusiveOwner(t *testing.T) { limits := DefaultLimits() limits.RequestTimeout = 5 * time.Second - manager := test_manager(t, limits, nil) + manager := testManager(t, limits, nil) first := startSessionSDK(t, manager, "go", "first") second := startSessionSDK(t, manager, "python", "second") lease := openRemote(t, first) @@ -325,7 +325,7 @@ func TestSessionSDKCallTimeout(t *testing.T) { writer := json.NewEncoder(input) reader := bufio.NewReader(output) writer.Encode(map[string]any{"jsonrpc": "2.0", "id": "1", "method": "initialize", "params": Initialization{Protocol: Version{1, 1}, Session: "test", APIs: []string{"commands", "session-events"}, Capabilities: []string{}}}) - if _, err := read_frame(reader); err != nil { + if _, err := readFrame(reader); err != nil { t.Fatal(err) } writer.Encode(map[string]any{"jsonrpc": "2.0", "method": "initialized", "params": map[string]string{"session": "test"}}) @@ -336,7 +336,7 @@ func TestSessionSDKCallTimeout(t *testing.T) { } writer.Encode(map[string]any{"jsonrpc": "2.0", "id": requestID, "method": "command.invoke", "params": map[string]any{"command": "request", "arguments": map[string]any{"method": "remote.heartbeat", "params": map[string]any{}}}}) if !blockedWriter { - frame, err := read_frame(reader) + frame, err := readFrame(reader) if err != nil || !strings.Contains(string(frame), `"id":"c:1"`) { t.Fatal("missing child request", string(frame), err) } @@ -353,7 +353,7 @@ func TestSessionSDKCallTimeout(t *testing.T) { } func TestSessionQueueOverflowRevokesLease(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) ctx, cancel := context.WithCancel(t.Context()) defer cancel() output, revoke := context.WithCancel(ctx) @@ -364,7 +364,7 @@ func TestSessionQueueOverflowRevokesLease(t *testing.T) { } params, _ := json.Marshal(tentaclewire.RemoteOpen{Action: action.Action, Epoch: action.Epoch, Role: action.Role, Grants: action.Grants}) session.mutex.Lock() - value, failure := session.remote_call_locked("remote.open", params) + value, failure := session.remoteCallLocked("remote.open", params) session.mutex.Unlock() if failure != nil { t.Fatal(failure) @@ -394,25 +394,25 @@ func TestSessionHostRejectsMalformedChildRequests(t *testing.T) { } { t.Run(frame, func(t *testing.T) { session := &Session{spec: Spec{SessionEvents: true}, ctx: t.Context(), state: Active, outbound: make(chan outgoing, 32)} - if err := session.accept_child_request([]byte(frame)); err == nil { + if err := session.acceptChildRequest([]byte(frame)); err == nil { t.Fatal("malformed request accepted") } }) } session := &Session{spec: Spec{SessionEvents: true}, ctx: t.Context(), state: Active, outbound: make(chan outgoing, 32)} frame := []byte(`{"jsonrpc":"2.0","id":"c:1","method":"remote.unknown","params":{}}`) - if err := session.accept_child_request(frame); err != nil { + if err := session.acceptChildRequest(frame); err != nil { t.Fatal(err) } - reply, err := decode_response((<-session.outbound).frame) + reply, err := decodeResponse((<-session.outbound).frame) if err != nil || reply.Error == nil || reply.Error.Code != -32601 { t.Fatal("unknown method response", reply, err) } - if err := session.accept_child_request(frame); err == nil { + if err := session.acceptChildRequest(frame); err == nil { t.Fatal("duplicate child ID accepted") } session.spec.SessionEvents = false - if err := session.accept_child_request([]byte(`{"jsonrpc":"2.0","id":"c:2","method":"remote.close","params":{}}`)); err == nil { + if err := session.acceptChildRequest([]byte(`{"jsonrpc":"2.0","id":"c:2","method":"remote.close","params":{}}`)); err == nil { t.Fatal("1.0 accepted child request") } } @@ -469,11 +469,11 @@ func TestSessionAggregateQueueBound(t *testing.T) { session := &Session{spec: Spec{SessionEvents: true}, outbound: make(chan outgoing, 32)} frame := make([]byte, MaxFrameBytes) for range 4 { - if !session.enqueue_locked(outgoing{frame: frame}) { + if !session.enqueueLocked(outgoing{frame: frame}) { t.Fatal("queue rejected boundary") } } - if session.enqueue_locked(outgoing{frame: []byte{1}}) { + if session.enqueueLocked(outgoing{frame: []byte{1}}) { t.Fatal("aggregate byte ceiling exceeded") } } @@ -482,7 +482,7 @@ func TestPendingRemoteRevocationReachesBothSDKs(t *testing.T) { for _, language := range []string{"go", "python"} { for _, reason := range []string{"local", "expired", "replaced"} { t.Run(language+"/"+reason, func(t *testing.T) { - session := startSessionSDK(t, test_manager(t, DefaultLimits(), nil), language, "pending-revoke") + session := startSessionSDK(t, testManager(t, DefaultLimits(), nil), language, "pending-revoke") action, err := session.AuthorizeRemote("controller", []string{"remote-present"}) if err != nil { t.Fatal(err) @@ -490,9 +490,9 @@ func TestPendingRemoteRevocationReachesBothSDKs(t *testing.T) { invokeSessionSDK(t, session, "event", nil) session.mutex.Lock() if reason == "expired" { - session.refresh_remote_locked(time.Millisecond) + session.refreshRemoteLocked(time.Millisecond) } else { - session.revoke_remote_locked(reason, true) + session.revokeRemoteLocked(reason, true) } session.mutex.Unlock() var event tentaclewire.SessionEvent diff --git a/internal/tentacle/repository.go b/internal/tentacle/repository.go index 1405963..cbc79e5 100644 --- a/internal/tentacle/repository.go +++ b/internal/tentacle/repository.go @@ -87,11 +87,11 @@ func CloneRepositories(repositories []Repository) []Repository { return result } -func metadata_text(value string, required bool) bool { +func metadataText(value string, required bool) bool { return (!required || strings.TrimSpace(value) != "") && len(value) <= 4096 && !strings.ContainsFunc(value, func(character rune) bool { return unicode.IsControl(character) }) } -func metadata_id(value string) bool { +func metadataId(value string) bool { if len(value) == 0 || len(value) > 128 || value[0] < 'a' || value[0] > 'z' { return false } @@ -111,7 +111,7 @@ func ValidateRepositories(repositories []Repository) error { count := 0 for _, repository := range repositories { origin, err := RepositoryURL(repository.URL) - if err != nil || origin != repository.URL || seen[origin] || !metadata_id(repository.ID) || !metadata_text(repository.Name, true) || !metadata_text(repository.Description, false) || len(repository.Revision) != 40 && len(repository.Revision) != 64 { + if err != nil || origin != repository.URL || seen[origin] || !metadataId(repository.ID) || !metadataText(repository.Name, true) || !metadataText(repository.Description, false) || len(repository.Revision) != 40 && len(repository.Revision) != 64 { return errors.New("invalid or duplicate tentacle repository metadata") } for _, character := range repository.Revision { @@ -126,7 +126,7 @@ func ValidateRepositories(repositories []Repository) error { if count > 256 { return ErrLimit } - if manifest.FormatVersion != 1 || !metadata_id(manifest.ID) || ids[manifest.ID] || !metadata_text(manifest.Name, true) || !metadata_text(manifest.Description, false) || !metadata_text(manifest.Version, true) { + if manifest.FormatVersion != 1 || !metadataId(manifest.ID) || ids[manifest.ID] || !metadataText(manifest.Name, true) || !metadataText(manifest.Description, false) || !metadataText(manifest.Version, true) { return errors.New("invalid or duplicate tentacle manifest metadata") } ids[manifest.ID] = true @@ -135,12 +135,12 @@ func ValidateRepositories(repositories []Repository) error { } capabilities := make(map[string]bool) for _, capability := range manifest.Capabilities { - if !metadata_id(capability) || capabilities[capability] { + if !metadataId(capability) || capabilities[capability] { return errors.New("invalid or duplicate tentacle capability metadata") } capabilities[capability] = true } - if err := validate_releases(manifest.Releases); err != nil { + if err := validateReleases(manifest.Releases); err != nil { return err } } @@ -148,9 +148,9 @@ func ValidateRepositories(repositories []Repository) error { return nil } -// read_repository uses regular blobs from one immutable revision. Tests supply +// readRepository uses regular blobs from one immutable revision. Tests supply // this reader directly; the public fetch path only permits HTTPS origins. -func read_repository(origin, revision string, read func(string) ([]byte, error)) (Repository, error) { +func readRepository(origin, revision string, read func(string) ([]byte, error)) (Repository, error) { repository := Repository{URL: origin, Revision: revision} var metadata struct { FormatVersion int `toml:"format-version"` @@ -199,7 +199,7 @@ func read_repository(origin, revision string, read func(string) ([]byte, error)) } for _, item := range catalog.Tentacles { parts := strings.Split(item.Manifest, "/") - if len(parts) != 2 || parts[0] == "" || parts[0] == "." || parts[0] == ".." || parts[1] != "tentacle.toml" || strings.ContainsAny(item.Manifest, "\\\x00\r\n:") || !metadata_text(item.Manifest, true) { + if len(parts) != 2 || parts[0] == "" || parts[0] == "." || parts[0] == ".." || parts[1] != "tentacle.toml" || strings.ContainsAny(item.Manifest, "\\\x00\r\n:") || !metadataText(item.Manifest, true) { return repository, errors.New("Catalog manifests must be inside direct top-level tentacle folders.") } var manifest Manifest @@ -225,7 +225,7 @@ func (output *boundedGitOutput) Write(data []byte) (int, error) { return output.Buffer.Write(data) } -func repository_git(ctx context.Context, directory string, arguments ...string) ([]byte, error) { +func repositoryGit(ctx context.Context, directory string, arguments ...string) ([]byte, error) { command := exec.CommandContext(ctx, "git", append([]string{"--literal-pathspecs", "-c", "core.hooksPath=/dev/null", "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "http.followRedirects=false", "-c", "credential.helper=", "-c", "gc.auto=0"}, arguments...)...) command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} command.Cancel = func() error { return syscall.Kill(-command.Process.Pid, syscall.SIGKILL) } @@ -259,27 +259,27 @@ func FetchRepository(ctx context.Context, origin string) (Repository, error) { return Repository{}, err } defer func() { _ = os.RemoveAll(directory) }() - if _, err := repository_git(ctx, directory, "init", "--bare", "--template="); err != nil { + if _, err := repositoryGit(ctx, directory, "init", "--bare", "--template="); err != nil { return Repository{}, err } - if _, err := repository_git(ctx, directory, "fetch", "--depth=1", "--no-tags", "--no-recurse-submodules", "--", origin, "HEAD"); err != nil { + if _, err := repositoryGit(ctx, directory, "fetch", "--depth=1", "--no-tags", "--no-recurse-submodules", "--", origin, "HEAD"); err != nil { return Repository{}, err } - return read_git_repository(ctx, directory, origin) + return readGitRepository(ctx, directory, origin) } -func read_git_repository(ctx context.Context, directory, origin string) (Repository, error) { - revision, err := repository_git(ctx, directory, "rev-parse", "--verify", "FETCH_HEAD^{commit}") +func readGitRepository(ctx context.Context, directory, origin string) (Repository, error) { + revision, err := repositoryGit(ctx, directory, "rev-parse", "--verify", "FETCH_HEAD^{commit}") if err != nil { return Repository{}, err } commit := strings.TrimSpace(string(revision)) - return read_repository(origin, commit, func(filename string) ([]byte, error) { + return readRepository(origin, commit, func(filename string) ([]byte, error) { // Reject symlinks, trees and submodules before reading any metadata. - mode, err := repository_git(ctx, directory, "ls-tree", commit, "--", filename) + mode, err := repositoryGit(ctx, directory, "ls-tree", commit, "--", filename) if err != nil || !(bytes.HasPrefix(mode, []byte("100644 blob ")) || bytes.HasPrefix(mode, []byte("100755 blob "))) { return nil, errors.New("metadata must be a regular blob") } - return repository_git(ctx, directory, "show", commit+":"+filename) + return repositoryGit(ctx, directory, "show", commit+":"+filename) }) } diff --git a/internal/tentacle/repository_test.go b/internal/tentacle/repository_test.go index 764a747..7499ec8 100644 --- a/internal/tentacle/repository_test.go +++ b/internal/tentacle/repository_test.go @@ -11,15 +11,15 @@ import ( "testing" ) -func repository_files() map[string]string { +func repositoryFiles() map[string]string { return map[string]string{ "repository.toml": "format-version = 1\nid = 'example.tentacles'\nname = 'Example tentacles'\ndescription = 'Test catalog'\nmaintainer = 'Maintainer'\n", "catalog.toml": "format-version = 1\n[[tentacles]]\nid = 'echo'\nmanifest = 'echo/tentacle.toml'\n", "echo/tentacle.toml": "format-version = 1\nid = 'echo'\nname = 'Echo'\nversion = '0.1'\ndescription = 'An example'\ncapabilities = ['presentation']\n", } } -func read_repository_fixture(files map[string]string) (Repository, error) { - return read_repository("https://example.org/team/tentacles", strings.Repeat("a", 40), func(filename string) ([]byte, error) { +func readRepositoryFixture(files map[string]string) (Repository, error) { + return readRepository("https://example.org/team/tentacles", strings.Repeat("a", 40), func(filename string) ([]byte, error) { data, found := files[filename] if !found { return nil, os.ErrNotExist @@ -28,13 +28,13 @@ func read_repository_fixture(files map[string]string) (Repository, error) { }) } func TestRepositoryMetadataDiscoveryValidation(t *testing.T) { - repository, err := read_repository_fixture(repository_files()) + repository, err := readRepositoryFixture(repositoryFiles()) if err != nil || repository.ID != "example.tentacles" || len(repository.Tentacles) != 1 || repository.Tentacles[0].Name != "Echo" { t.Fatalf("discovery: %+v %v", repository, err) } for _, problem := range []string{"missing root", "version", "missing manifest", "traversal", "nested", "mismatch", "duplicate", "oversized", "invalid id"} { t.Run(problem, func(t *testing.T) { - files := repository_files() + files := repositoryFiles() switch problem { case "missing root": delete(files, "repository.toml") @@ -55,7 +55,7 @@ func TestRepositoryMetadataDiscoveryValidation(t *testing.T) { case "invalid id": files["echo/tentacle.toml"] = strings.Replace(files["echo/tentacle.toml"], "id = 'echo'", "id = 'Echo!'", 1) } - if _, err := read_repository_fixture(files); err == nil { + if _, err := readRepositoryFixture(files); err == nil { t.Fatal("accepted invalid metadata") } }) @@ -73,7 +73,7 @@ func TestRepositoryURLAndLabel(t *testing.T) { } } func TestRepositorySnapshotPersistenceAndIsolation(t *testing.T) { - repository, err := read_repository_fixture(repository_files()) + repository, err := readRepositoryFixture(repositoryFiles()) if err != nil { t.Fatal(err) } @@ -111,11 +111,11 @@ func TestRepositoryGitIgnoresInheritedConfigAndReadsBlobs(t *testing.T) { t.Setenv("GIT_CONFIG_KEY_0", "core.bare") t.Setenv("GIT_CONFIG_VALUE_0", "invalid") ctx := context.Background() - if _, err := repository_git(ctx, directory, "init", "--bare", "--template="); err != nil { + if _, err := repositoryGit(ctx, directory, "init", "--bare", "--template="); err != nil { t.Fatal(err) } source := t.TempDir() - for name, data := range repository_files() { + for name, data := range repositoryFiles() { filename := filepath.Join(source, name) if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil { t.Fatal(err) @@ -146,12 +146,12 @@ func TestRepositoryGitIgnoresInheritedConfigAndReadsBlobs(t *testing.T) { } } setHead() - repository, err := read_git_repository(ctx, source, "https://example.org/team/tentacles") + repository, err := readGitRepository(ctx, source, "https://example.org/team/tentacles") if err != nil || len(repository.Tentacles) != 1 { t.Fatalf("Git discovery: %+v %v", repository, err) } revision := run("rev-parse", "HEAD") - data, err := repository_git(ctx, source, "show", revision+":repository.toml") + data, err := repositoryGit(ctx, source, "show", revision+":repository.toml") if err != nil || !strings.Contains(string(data), "example.tentacles") { t.Fatalf("read blob: %s %v", data, err) } @@ -166,12 +166,12 @@ func TestRepositoryGitIgnoresInheritedConfigAndReadsBlobs(t *testing.T) { run("add", ".") run("commit", "-m", "Symlink fixture") setHead() - if _, err := read_git_repository(ctx, source, "https://example.org/team/tentacles"); err == nil { + if _, err := readGitRepository(ctx, source, "https://example.org/team/tentacles"); err == nil { t.Fatal("accepted symlink metadata") } cancelled, cancel := context.WithCancel(ctx) cancel() - if _, err := repository_git(cancelled, source, "status"); err == nil { + if _, err := repositoryGit(cancelled, source, "status"); err == nil { t.Fatal("ignored cancellation") } } diff --git a/internal/tentacle/sdk_test.go b/internal/tentacle/sdk_test.go index b329731..1a252cc 100644 --- a/internal/tentacle/sdk_test.go +++ b/internal/tentacle/sdk_test.go @@ -72,7 +72,7 @@ func TestSDKChild(t *testing.T) { os.Exit(0) } -func sdk_program(t *testing.T, language, cancelFile string) []string { +func sdkProgram(t *testing.T, language, cancelFile string) []string { t.Helper() if language == "go" { executable, err := os.Executable() @@ -99,12 +99,12 @@ func TestSDKHostConformance(t *testing.T) { cancelFile := filepath.Join(t.TempDir(), "cancelled") limits := DefaultLimits() limits.RequestTimeout = 5 * time.Second - manager := test_manager(t, limits, nil) - session, err := manager.Start(context.Background(), Spec{ID: "sdk", Program: sdk_program(t, language, cancelFile)}) + manager := testManager(t, limits, nil) + session, err := manager.Start(context.Background(), Spec{ID: "sdk", Program: sdkProgram(t, language, cancelFile)}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if state, err := session.Status(); state != Ready || err != nil { t.Fatalf("%s: %v", state, err) } @@ -120,7 +120,7 @@ func TestSDKHostConformance(t *testing.T) { if err != nil { t.Fatal(err) } - return wait_result(t, pending) + return waitResult(t, pending) } for _, raw := range []string{`{"text":"é猫😀é","nested":[true,null,42]}`, `null`, `[1,"two"]`} { result := invoke("echo", json.RawMessage(raw)) @@ -140,7 +140,7 @@ func TestSDKHostConformance(t *testing.T) { } } for index, reply := range replies { - result := wait_result(t, reply) + result := waitResult(t, reply) var value struct { Index int `json:"index"` } @@ -173,10 +173,10 @@ func TestSDKHostConformance(t *testing.T) { } else { cancel() } - if result := wait_result(t, pending); result.Err == nil { + if result := waitResult(t, pending); result.Err == nil { t.Fatal("late success", result) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if ending == "disable" { if data, err := os.ReadFile(cancelFile); err != nil || string(data) != "cancelled" { t.Fatalf("SDK did not cancel handler: %q, %v", data, err) @@ -191,13 +191,13 @@ func TestSDKPresentationGrantAndRevocation(t *testing.T) { for _, language := range []string{"go", "python"} { for _, grant := range []bool{false, true} { t.Run(language+"/grant="+strconv.FormatBool(grant), func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - program := sdk_program(t, language, filepath.Join(t.TempDir(), "presentation")) + manager := testManager(t, DefaultLimits(), nil) + program := sdkProgram(t, language, filepath.Join(t.TempDir(), "presentation")) session, err := manager.Start(context.Background(), Spec{ID: "sdk", Program: program, Presentation: grant}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) state, err := session.Status() if !grant { if state != Failed || err == nil { @@ -215,7 +215,7 @@ func TestSDKPresentationGrantAndRevocation(t *testing.T) { if err != nil { t.Fatal(err) } - result := wait_result(t, pending) + result := waitResult(t, pending) value, err := tentaclewire.DecodePresentation(result.Value) if result.Err != nil || err != nil || value.Speech != "Hello, é猫😀é" || value.Braille != "Display é猫😀é" || !value.Uninterruptible { t.Fatalf("presentation: %+v, %v", result, err) @@ -251,7 +251,7 @@ func TestSDKRejectsInvalidHostMessages(t *testing.T) { for _, language := range []string{"go", "python"} { for name, input := range cases { t.Run(language+"/"+name, func(t *testing.T) { - program := sdk_program(t, language, filepath.Join(t.TempDir(), "cancelled")) + program := sdkProgram(t, language, filepath.Join(t.TempDir(), "cancelled")) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() command := exec.CommandContext(ctx, program[0], program[1:]...) @@ -270,12 +270,12 @@ func TestSDKRejectsInvalidHostMessages(t *testing.T) { func TestSDKSecretFormConformance(t *testing.T) { for _, language := range []string{"go", "python"} { t.Run(language, func(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - session, err := manager.Start(context.Background(), Spec{ID: "sdk", Program: sdk_program(t, language, filepath.Join(t.TempDir(), "secret")), Presentation: true, Interaction: true}) + manager := testManager(t, DefaultLimits(), nil) + session, err := manager.Start(context.Background(), Spec{ID: "sdk", Program: sdkProgram(t, language, filepath.Join(t.TempDir(), "secret")), Presentation: true, Interaction: true}) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if err := session.Activate(); err != nil { t.Fatal(err) } @@ -285,7 +285,7 @@ func TestSDKSecretFormConformance(t *testing.T) { if err != nil { t.Fatal(err) } - return wait_result(t, pending) + return waitResult(t, pending) } result := invoke("secret", nil) value, err := tentaclewire.DecodeInteraction(result.Value) diff --git a/internal/tentacle/session.go b/internal/tentacle/session.go index 2fffefc..5b22d12 100644 --- a/internal/tentacle/session.go +++ b/internal/tentacle/session.go @@ -117,7 +117,7 @@ func (session *Session) Extensions() tentaclewire.Extensions { func (session *Session) Commands() []Command { session.mutex.Lock() defer session.mutex.Unlock() - return clone_commands(session.commands) + return cloneCommands(session.commands) } // Activate is the host publication barrier. The reader stages acknowledged @@ -125,18 +125,18 @@ func (session *Session) Commands() []Command { func (session *Session) Activate() error { session.manager.mutex.Lock() defer session.manager.mutex.Unlock() - occupied := session.manager.occupied_bindings() + occupied := session.manager.occupiedBindings() session.mutex.Lock() defer session.mutex.Unlock() if session.state != Ready || session.ctx.Err() != nil { return ErrUnavailable } - if !session.notify_locked("initialized", struct { + if !session.notifyLocked("initialized", struct { Session string `json:"session"` }{session.identity}) { return ErrBusy } - session.bindings = resolve_bindings(session.spec.ID, session.commands, occupied) + session.bindings = resolveBindings(session.spec.ID, session.commands, occupied) session.state = Active session.log("tentacle activated") return nil @@ -155,7 +155,7 @@ func (session *Session) Invoke(ctx context.Context, command string, arguments js if len(arguments) == 0 { arguments = json.RawMessage(`{}`) } - if err := validate_json(arguments); err != nil { + if err := validateJson(arguments); err != nil { return nil, err } session.mutex.Lock() @@ -179,13 +179,13 @@ func (session *Session) Invoke(ctx context.Context, command string, arguments js if !known { return nil, ErrUnavailable } - return session.request_locked(ctx, "command.invoke", struct { + return session.requestLocked(ctx, "command.invoke", struct { Command string `json:"command"` Arguments json.RawMessage `json:"arguments"` }{command, arguments}, session.manager.limits.RequestTimeout) } -func (session *Session) request_locked(parent context.Context, method string, params any, timeout time.Duration) (<-chan Result, error) { +func (session *Session) requestLocked(parent context.Context, method string, params any, timeout time.Duration) (<-chan Result, error) { if len(session.pending) >= session.manager.limits.PendingPerProcess { return nil, ErrBusy } @@ -196,7 +196,7 @@ func (session *Session) request_locked(parent context.Context, method string, pa } session.sequence++ id := strconv.FormatUint(session.sequence, 10) - frame, err := encode_request(id, method, params) + frame, err := encodeRequest(id, method, params) if err != nil { <-session.manager.pending return nil, err @@ -207,28 +207,28 @@ func (session *Session) request_locked(parent context.Context, method string, pa session.callbacks.Add(1) call.stopWatch = context.AfterFunc(ctx, func() { defer session.callbacks.Done() - session.cancel_call(id) + session.cancelCall(id) }) - if session.enqueue_locked(outgoing{id: id, frame: frame}) { + if session.enqueueLocked(outgoing{id: id, frame: frame}) { return call.result, nil } - session.finish_locked(id, nil, ErrBusy) + session.finishLocked(id, nil, ErrBusy) if session.spec.SessionEvents { - session.fail_locked(ErrLimit) + session.failLocked(ErrLimit) } return nil, ErrBusy } -func (session *Session) notify_locked(method string, params any) bool { - frame, err := encode_request("", method, params) +func (session *Session) notifyLocked(method string, params any) bool { + frame, err := encodeRequest("", method, params) if err != nil { return false } - return session.enqueue_locked(outgoing{frame: frame}) + return session.enqueueLocked(outgoing{frame: frame}) } // Session.mutex owns byte accounting, including the in-flight write. -func (session *Session) enqueue_locked(item outgoing) bool { +func (session *Session) enqueueLocked(item outgoing) bool { if session.spec.SessionEvents && session.queuedBytes+len(item.frame) > tentaclewire.SessionQueueBytes { return false } @@ -241,7 +241,7 @@ func (session *Session) enqueue_locked(item outgoing) bool { } } -func (session *Session) finish_locked(id string, value json.RawMessage, err error) { +func (session *Session) finishLocked(id string, value json.RawMessage, err error) { call := session.pending[id] if call == nil { return @@ -263,7 +263,7 @@ func (session *Session) finish_locked(id string, value json.RawMessage, err erro close(call.result) } -func (session *Session) cancel_call(id string) { +func (session *Session) cancelCall(id string) { session.mutex.Lock() defer session.mutex.Unlock() call := session.pending[id] @@ -271,14 +271,14 @@ func (session *Session) cancel_call(id string) { return } err := call.ctx.Err() - session.finish_locked(id, nil, err) + session.finishLocked(id, nil, err) // Without a cancellation acknowledgment contract, a timed-out child could // accumulate unlimited still-running work. Retire the whole session instead. // Explicit cancellation follows the same conservative rule in this slice. - session.fail_locked(err) + session.failLocked(err) } -func (session *Session) accept_reply(reply response) { +func (session *Session) acceptReply(reply response) { session.mutex.Lock() defer session.mutex.Unlock() if session.state == Stopping || session.state == Stopped || session.state == Failed { @@ -286,17 +286,17 @@ func (session *Session) accept_reply(reply response) { } if session.pending[reply.ID] == nil { // Unknown/duplicate responses are not allowed to keep a flood alive. - session.fail_locked(ErrProtocol) + session.failLocked(ErrProtocol) return } var err error if reply.Error != nil { err = reply.Error } - session.finish_locked(reply.ID, reply.Result, err) + session.finishLocked(reply.ID, reply.Result, err) } -func (session *Session) fail_locked(err error) { +func (session *Session) failLocked(err error) { if session.state == Stopping || session.state == Stopped || session.state == Failed { return } @@ -304,12 +304,12 @@ func (session *Session) fail_locked(err error) { session.state, session.failure = Failed, err close(session.revoked) session.revokeOutput() - session.revoke_remote_locked("local", false) + session.revokeRemoteLocked("local", false) session.commands = nil session.extensions = tentaclewire.Extensions{} session.bindings = nil for id := range session.pending { - session.finish_locked(id, nil, err) + session.finishLocked(id, nil, err) } session.cancel() } @@ -317,7 +317,7 @@ func (session *Session) fail_locked(err error) { func (session *Session) fail(err error) { session.mutex.Lock() defer session.mutex.Unlock() - session.fail_locked(err) + session.failLocked(err) } // Disable revokes commands and retires replies synchronously; pipe shutdown and @@ -332,13 +332,13 @@ func (session *Session) Disable() { session.state = Stopping close(session.revoked) session.revokeOutput() - session.revoke_remote_locked("local", false) + session.revokeRemoteLocked("local", false) session.commands = nil session.extensions = tentaclewire.Extensions{} session.bindings = nil for id := range session.pending { - session.finish_locked(id, nil, ErrDisabled) + session.finishLocked(id, nil, ErrDisabled) } - session.notify_locked("shutdown", nil) + session.notifyLocked("shutdown", nil) close(session.stop) } diff --git a/internal/tentacle/session_test.go b/internal/tentacle/session_test.go index 85ad122..e3c56b7 100644 --- a/internal/tentacle/session_test.go +++ b/internal/tentacle/session_test.go @@ -18,7 +18,7 @@ import ( "git.stormux.org/storm/cthulhu/internal/input" ) -func test_manager(t testing.TB, limits Limits, overrides []input.BindingOverride) *Manager { +func testManager(t testing.TB, limits Limits, overrides []input.BindingOverride) *Manager { t.Helper() manager, err := NewManager(limits, overrides) if err != nil { @@ -37,7 +37,7 @@ func test_manager(t testing.TB, limits Limits, overrides []input.BindingOverride return manager } -func child_spec(t testing.TB, id, mode string) Spec { +func childSpec(t testing.TB, id, mode string) Spec { t.Helper() executable, err := os.Executable() if err != nil { @@ -46,7 +46,7 @@ func child_spec(t testing.TB, id, mode string) Spec { return Spec{ID: id, Program: []string{executable, "-test.run=^TestTentacleChild$", "--", "tentacle-child:" + mode}} } -func wait_signal(t testing.TB, signal <-chan struct{}) { +func waitSignal(t testing.TB, signal <-chan struct{}) { t.Helper() select { case <-signal: @@ -55,29 +55,29 @@ func wait_signal(t testing.TB, signal <-chan struct{}) { } } -func start_ready(t testing.TB, manager *Manager, id, mode string) *Session { +func startReady(t testing.TB, manager *Manager, id, mode string) *Session { t.Helper() - session, err := manager.Start(context.Background(), child_spec(t, id, mode)) + session, err := manager.Start(context.Background(), childSpec(t, id, mode)) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if state, err := session.Status(); state != Ready || err != nil { t.Fatalf("state %s: %v", state, err) } return session } -func start_active(t testing.TB, manager *Manager, id, mode string) *Session { +func startActive(t testing.TB, manager *Manager, id, mode string) *Session { t.Helper() - session := start_ready(t, manager, id, mode) + session := startReady(t, manager, id, mode) if err := session.Activate(); err != nil { t.Fatal(err) } return session } -func wait_result(t testing.TB, result <-chan Result) Result { +func waitResult(t testing.TB, result <-chan Result) Result { t.Helper() select { case reply, ok := <-result: @@ -92,8 +92,8 @@ func wait_result(t testing.TB, result <-chan Result) Result { } func TestActivationAndUnicodeRoundTrip(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - session := start_ready(t, manager, "sample", "echo") + manager := testManager(t, DefaultLimits(), nil) + session := startReady(t, manager, "sample", "echo") if _, err := session.Invoke(context.Background(), "echo", nil); !errors.Is(err, ErrUnavailable) { t.Fatal(err) } @@ -117,7 +117,7 @@ func TestActivationAndUnicodeRoundTrip(t *testing.T) { if err != nil { t.Fatal(err) } - result := wait_result(t, pending) + result := waitResult(t, pending) if result.Err != nil || string(result.Value) != string(arguments) || result.Session != session.Identity() { t.Fatalf("%+v", result) } @@ -131,19 +131,19 @@ func TestActivationAndUnicodeRoundTrip(t *testing.T) { if _, err := session.Invoke(context.Background(), "echo", nil); !errors.Is(err, ErrUnavailable) { t.Fatal(err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Stopped || err != nil { t.Fatalf("state %s: %v", state, err) } - replacement := start_active(t, manager, "sample", "echo") + replacement := startActive(t, manager, "sample", "echo") if replacement.Identity() == session.Identity() { t.Fatal("session identity reused") } } func TestRepliesCorrelateOutOfOrder(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - session := start_active(t, manager, "sample", "reverse") + manager := testManager(t, DefaultLimits(), nil) + session := startActive(t, manager, "sample", "reverse") first, err := session.Invoke(context.Background(), "echo", json.RawMessage(`1`)) if err != nil { t.Fatal(err) @@ -153,7 +153,7 @@ func TestRepliesCorrelateOutOfOrder(t *testing.T) { t.Fatal(err) } for index, pending := range []<-chan Result{first, second} { - result := wait_result(t, pending) + result := waitResult(t, pending) if result.Err != nil || string(result.Value) != strconv.Itoa(index+1) { t.Fatalf("misrouted response: %+v", result) } @@ -161,13 +161,13 @@ func TestRepliesCorrelateOutOfOrder(t *testing.T) { } func TestDisabledStagingCannotPublish(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - session := start_ready(t, manager, "sample", "echo") + manager := testManager(t, DefaultLimits(), nil) + session := startReady(t, manager, "sample", "echo") session.Disable() if err := session.Activate(); !errors.Is(err, ErrUnavailable) { t.Fatal("disabled staging published", err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if len(session.outbound) != 0 { t.Fatal("cleanup retained unsent frames") } @@ -178,17 +178,17 @@ func TestBadChildrenAreContained(t *testing.T) { t.Run(mode, func(t *testing.T) { limits := DefaultLimits() limits.StartupTimeout = 500 * time.Millisecond - manager := test_manager(t, limits, nil) - session, err := manager.Start(context.Background(), child_spec(t, "broken", mode)) + manager := testManager(t, limits, nil) + session, err := manager.Start(context.Background(), childSpec(t, "broken", mode)) if err != nil { t.Fatal(err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Failed || err == nil || len(session.Commands()) != 0 { t.Fatalf("state %s: %v", state, err) } // Failure releases capacity for a healthy tentacle. - start_active(t, manager, "healthy", "echo") + startActive(t, manager, "healthy", "echo") }) } } @@ -198,8 +198,8 @@ func TestRequestFailureCancellationAndDisable(t *testing.T) { t.Run(mode, func(t *testing.T) { limits := DefaultLimits() limits.RequestTimeout = 150 * time.Millisecond - manager := test_manager(t, limits, nil) - session := start_active(t, manager, "sample", mode) + manager := testManager(t, limits, nil) + session := startActive(t, manager, "sample", mode) ctx, cancel := context.WithCancel(context.Background()) defer cancel() pending, err := session.Invoke(ctx, "echo", json.RawMessage(`{"text":"sample"}`)) @@ -212,7 +212,7 @@ func TestRequestFailureCancellationAndDisable(t *testing.T) { if mode == "disable" { session.Disable() } - result := wait_result(t, pending) + result := waitResult(t, pending) if mode != "duplicate-reply" && result.Err == nil { t.Fatal("failed call succeeded") } @@ -225,7 +225,7 @@ func TestRequestFailureCancellationAndDisable(t *testing.T) { if mode == "disable" && !errors.Is(result.Err, ErrDisabled) { t.Fatal(result.Err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if len(session.Commands()) != 0 { t.Fatal("failure retained commands") } @@ -236,19 +236,19 @@ func TestRequestFailureCancellationAndDisable(t *testing.T) { func TestAdmissionAndAggregatePendingLimits(t *testing.T) { limits := DefaultLimits() limits.Processes, limits.Starting, limits.PendingPerProcess, limits.PendingTotal = 2, 1, 2, 3 - manager := test_manager(t, limits, nil) - blocked, err := manager.Start(context.Background(), child_spec(t, "blocked", "hang-start")) + manager := testManager(t, limits, nil) + blocked, err := manager.Start(context.Background(), childSpec(t, "blocked", "hang-start")) if err != nil { t.Fatal(err) } - if _, err := manager.Start(context.Background(), child_spec(t, "second", "echo")); !errors.Is(err, ErrBusy) { + if _, err := manager.Start(context.Background(), childSpec(t, "second", "echo")); !errors.Is(err, ErrBusy) { t.Fatal("startup limit", err) } blocked.Disable() - wait_signal(t, blocked.Done()) - first := start_active(t, manager, "first", "timeout") - second := start_active(t, manager, "second", "timeout") - if _, err := manager.Start(context.Background(), child_spec(t, "third", "echo")); !errors.Is(err, ErrBusy) { + waitSignal(t, blocked.Done()) + first := startActive(t, manager, "first", "timeout") + second := startActive(t, manager, "second", "timeout") + if _, err := manager.Start(context.Background(), childSpec(t, "third", "echo")); !errors.Is(err, ErrBusy) { t.Fatal("process limit", err) } for range 2 { @@ -275,13 +275,13 @@ func TestAdmissionAndAggregatePendingLimits(t *testing.T) { } func TestParentCancellationAndConcurrentShutdown(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) + manager := testManager(t, DefaultLimits(), nil) ctx, cancel := context.WithCancel(context.Background()) - session, err := manager.Start(ctx, child_spec(t, "sample", "echo")) + session, err := manager.Start(ctx, childSpec(t, "sample", "echo")) if err != nil { t.Fatal(err) } - wait_signal(t, session.Ready()) + waitSignal(t, session.Ready()) if err := session.Activate(); err != nil { t.Fatal(err) } @@ -296,11 +296,11 @@ func TestParentCancellationAndConcurrentShutdown(t *testing.T) { } cancel() workers.Wait() - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if err := manager.Shutdown(context.Background()); err != nil { t.Fatal(err) } - if _, err := manager.Start(context.Background(), child_spec(t, "after-shutdown", "echo")); !errors.Is(err, ErrUnavailable) { + if _, err := manager.Start(context.Background(), childSpec(t, "after-shutdown", "echo")); !errors.Is(err, ErrUnavailable) { t.Fatal(err) } } @@ -308,8 +308,8 @@ func TestParentCancellationAndConcurrentShutdown(t *testing.T) { func TestBlockedPipeCannotBlockSubmissionOrDisable(t *testing.T) { limits := DefaultLimits() limits.RequestTimeout = 10 * time.Second - manager := test_manager(t, limits, nil) - session := start_active(t, manager, "sample", "blocked-input") + manager := testManager(t, limits, nil) + session := startActive(t, manager, "sample", "blocked-input") arguments, err := json.Marshal(strings.Repeat("x", MaxArgumentBytes-2)) if err != nil { t.Fatal(err) @@ -333,17 +333,17 @@ func TestBlockedPipeCannotBlockSubmissionOrDisable(t *testing.T) { case <-time.After(2 * time.Second): t.Fatal("pipe backpressure blocked host submission or disable") } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) } func TestLaunchValidationAndMissingExecutable(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - if _, err := manager.Start(nil, child_spec(t, "sample", "echo")); err == nil { //nolint:staticcheck // SA1012: verifies nil contexts are rejected + manager := testManager(t, DefaultLimits(), nil) + if _, err := manager.Start(nil, childSpec(t, "sample", "echo")); err == nil { //nolint:staticcheck // SA1012: verifies nil contexts are rejected t.Fatal("nil context accepted") } ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, err := manager.Start(ctx, child_spec(t, "sample", "echo")); !errors.Is(err, context.Canceled) { + if _, err := manager.Start(ctx, childSpec(t, "sample", "echo")); !errors.Is(err, context.Canceled) { t.Fatal(err) } for _, spec := range []Spec{ @@ -360,7 +360,7 @@ func TestLaunchValidationAndMissingExecutable(t *testing.T) { if err != nil { t.Fatal(err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Failed || !errors.Is(err, ErrExited) { t.Fatalf("%s: %v", state, err) } @@ -370,13 +370,13 @@ func TestLaunchValidationAndMissingExecutable(t *testing.T) { } func TestBindingConflictsLeaveCommandsAvailable(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - first := start_active(t, manager, "first", "echo") + manager := testManager(t, DefaultLimits(), nil) + first := startActive(t, manager, "first", "echo") bindings := first.Bindings() if len(bindings) != 2 || bindings[0].Bound || bindings[0].Conflict != string(input.CycleSpeechMode) || !bindings[1].Bound { t.Fatalf("core conflict: %+v", bindings) } - second := start_active(t, manager, "second", "echo") + second := startActive(t, manager, "second", "echo") if bindings := second.Bindings(); bindings[1].Bound || bindings[1].Conflict != "tentacle/first/echo" { t.Fatalf("tentacle conflict: %+v", bindings) } @@ -388,27 +388,27 @@ func TestBindingConflictsLeaveCommandsAvailable(t *testing.T) { if second.Bindings()[1].Bound { t.Fatal("silently rebound") } - third := start_active(t, manager, "third", "echo") + third := startActive(t, manager, "third", "echo") if !third.Bindings()[1].Bound { t.Fatal("revoked shortcut remains reserved") } } func TestBindingsRespectUserOverridesAndScopes(t *testing.T) { - manager := test_manager(t, DefaultLimits(), []input.BindingOverride{{ + manager := testManager(t, DefaultLimits(), []input.BindingOverride{{ Layout: input.DesktopKeyboardLayout, Scope: "global", Command: input.PresentTime, Keys: []string{"Cthulhu+Ctrl+F12"}, }}) - session := start_active(t, manager, "sample", "echo") + session := startActive(t, manager, "sample", "echo") if bindings := session.Bindings(); bindings[1].Bound || bindings[1].Conflict != string(input.PresentTime) { t.Fatalf("user override conflict: %+v", bindings) } - occupied := manager.occupied_bindings() + occupied := manager.occupiedBindings() commands := []Command{{ID: "scoped", Bindings: []Binding{ {Layout: "desktop", Scope: "global", Key: "h"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+F12"}, {Layout: "laptop", Scope: "browse", Key: "Ctrl+Cthulhu+F12"}, }}} - bindings := resolve_bindings("scope", commands, occupied) + bindings := resolveBindings("scope", commands, occupied) if bindings[0].Bound || !bindings[1].Bound || bindings[2].Bound { t.Fatalf("scope/alias conflicts: %+v", bindings) } @@ -439,7 +439,7 @@ func TestTentacleChild(t *testing.T) { var heldID string var heldValue json.RawMessage for { - frame, err := read_frame(reader) + frame, err := readFrame(reader) if err != nil { os.Exit(0) } @@ -558,19 +558,19 @@ func TestTentacleChild(t *testing.T) { } func TestDisableKillsGroupDescendantsAndJoinsPipes(t *testing.T) { - manager := test_manager(t, DefaultLimits(), nil) - session := start_active(t, manager, "sample", "spawn") + manager := testManager(t, DefaultLimits(), nil) + session := startActive(t, manager, "sample", "spawn") pending, err := session.Invoke(context.Background(), "echo", nil) if err != nil { t.Fatal(err) } - result := wait_result(t, pending) + result := waitResult(t, pending) var pid int if result.Err != nil || json.Unmarshal(result.Value, &pid) != nil || pid <= 1 { t.Fatalf("bad descendant result: %+v", result) } session.Disable() - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) // SIGKILL delivery/reaping is scheduled by the kernel; wait for /proc to // report disappearance or zombie state, not an arbitrary sleep duration. // A task that exits during ReadFile can return ESRCH rather than ENOENT. diff --git a/internal/tentacle/supervisor.go b/internal/tentacle/supervisor.go index ec2cf78..6409611 100644 --- a/internal/tentacle/supervisor.go +++ b/internal/tentacle/supervisor.go @@ -67,7 +67,7 @@ func RunSupervisor(ctx context.Context) error { } configuration.Close() var spec Spec - if decode_strict(data, &spec) != nil || validate_spec(spec) != nil { + if decodeStrict(data, &spec) != nil || validateSpec(spec) != nil { return nil } if ctx.Err() != nil { @@ -101,7 +101,7 @@ running: case <-childSignals: // The subreaper owns orphaned descendants for the entire session, // not just teardown. Only command.Wait may reap the main child. - supervisionError = reap_exited_supervised_children(command.Process.Pid) + supervisionError = reapExitedSupervisedChildren(command.Process.Pid) if supervisionError != nil { break running } @@ -109,10 +109,10 @@ running: } _ = command.Process.Kill() <-exited - return errors.Join(supervisionError, reap_supervised_children(DefaultResourceLimits().CleanupTimeout)) + return errors.Join(supervisionError, reapSupervisedChildren(DefaultResourceLimits().CleanupTimeout)) } -func supervised_children() ([]int, error) { +func supervisedChildren() ([]int, error) { paths, err := filepath.Glob("/proc/self/task/*/children") if err != nil || len(paths) == 0 { return nil, ErrSupervision @@ -137,8 +137,8 @@ func supervised_children() ([]int, error) { return children, nil } -func reap_exited_supervised_children(mainPID int) error { - children, err := supervised_children() +func reapExitedSupervisedChildren(mainPID int) error { + children, err := supervisedChildren() if err != nil { return err } @@ -163,13 +163,13 @@ func reap_exited_supervised_children(mainPID int) error { // Only this helper's children are killed. A child PID cannot be reused until // it has been reaped, and no other goroutine calls Wait after command.Wait joins. // Killing direct children adopts the next generation, including detached ones. -func reap_supervised_children(timeout time.Duration) error { +func reapSupervisedChildren(timeout time.Duration) error { deadline := time.NewTimer(timeout) defer deadline.Stop() tick := time.NewTicker(5 * time.Millisecond) defer tick.Stop() for { - children, err := supervised_children() + children, err := supervisedChildren() if err != nil { return err } diff --git a/internal/tentacle/supervisor_test.go b/internal/tentacle/supervisor_test.go index ab0f5d9..b803170 100644 --- a/internal/tentacle/supervisor_test.go +++ b/internal/tentacle/supervisor_test.go @@ -16,7 +16,7 @@ import ( "time" ) -func supervisor_program(t testing.TB) []string { +func supervisorProgram(t testing.TB) []string { t.Helper() executable, err := os.Executable() if err != nil { @@ -25,9 +25,9 @@ func supervisor_program(t testing.TB) []string { return []string{executable, "-test.run=^TestSupervisorHelper$", "--", "supervisor"} } -func supervised_manager(t testing.TB) *Manager { +func supervisedManager(t testing.TB) *Manager { t.Helper() - manager, err := NewSupervisedManager(supervisor_program(t), "auto") + manager, err := NewSupervisedManager(supervisorProgram(t), "auto") if err != nil { t.Fatal(err) } @@ -44,13 +44,13 @@ func supervised_manager(t testing.TB) *Manager { return manager } -func supervised_descendant(t testing.TB, session *Session) int { +func supervisedDescendant(t testing.TB, session *Session) int { t.Helper() result, err := session.Invoke(context.Background(), "echo", nil) if err != nil { t.Fatal(err) } - value := wait_result(t, result) + value := waitResult(t, result) var pid int if value.Err != nil || json.Unmarshal(value.Value, &pid) != nil || pid <= 1 { t.Fatalf("descendant: %+v", value) @@ -58,7 +58,7 @@ func supervised_descendant(t testing.TB, session *Session) int { return pid } -func wait_supervised_reap(t *testing.T, pid int) { +func waitSupervisedReap(t *testing.T, pid int) { t.Helper() deadline := time.NewTimer(6 * time.Second) defer deadline.Stop() @@ -87,12 +87,12 @@ func TestSupervisorHelper(t *testing.T) { return } marker := os.Args[len(os.Args)-1] - manager, err := NewSupervisedManager(supervisor_program(t), "auto") + manager, err := NewSupervisedManager(supervisorProgram(t), "auto") if err != nil { t.Fatal(err) } - session := start_active(t, manager, "sample", "spawn-chain") - pid := supervised_descendant(t, session) + session := startActive(t, manager, "sample", "spawn-chain") + pid := supervisedDescendant(t, session) if err := os.WriteFile(marker, []byte(strconv.Itoa(pid)), 0600); err != nil { t.Fatal(err) } @@ -105,23 +105,23 @@ func TestSupervisionWithoutInitToolsCleansDetachedDescendants(t *testing.T) { t.Setenv("CTHULHU_TENTACLE_CGROUP_PARENT", "") for _, mode := range []string{"spawn", "spawn-detached", "spawn-chain"} { t.Run(mode, func(t *testing.T) { - manager := supervised_manager(t) - first := start_active(t, manager, "first", mode) - second := start_active(t, manager, "second", "spawn-detached") - pid := supervised_descendant(t, first) - other := supervised_descendant(t, second) + manager := supervisedManager(t) + first := startActive(t, manager, "first", mode) + second := startActive(t, manager, "second", "spawn-detached") + pid := supervisedDescendant(t, first) + other := supervisedDescendant(t, second) first.Disable() - wait_signal(t, first.Done()) + waitSignal(t, first.Done()) if state, err := first.Status(); state != Stopped || err != nil { t.Fatalf("disable: %s %v", state, err) } - wait_supervised_reap(t, pid) + waitSupervisedReap(t, pid) if _, err := os.Stat("/proc/" + strconv.Itoa(other)); err != nil { t.Fatal("another session was terminated", err) } second.Disable() - wait_signal(t, second.Done()) - wait_supervised_reap(t, other) + waitSignal(t, second.Done()) + waitSupervisedReap(t, other) }) } } @@ -145,81 +145,81 @@ func TestSupervisionCleansDescendantsAfterReaderDeath(t *testing.T) { if err != nil || pid <= 1 { t.Fatal("invalid descendant marker") } - wait_supervised_reap(t, pid) + waitSupervisedReap(t, pid) } func TestSupervisionReapsExitedDescendantWhileSessionActive(t *testing.T) { t.Setenv("CTHULHU_TENTACLE_CGROUP_PARENT", "") - manager := supervised_manager(t) - session := start_active(t, manager, "sample", "spawn-chain") - pid := supervised_descendant(t, session) + manager := supervisedManager(t) + session := startActive(t, manager, "sample", "spawn-chain") + pid := supervisedDescendant(t, session) if err := syscall.Kill(pid, syscall.SIGKILL); err != nil { t.Fatal(err) } - wait_supervised_reap(t, pid) + waitSupervisedReap(t, pid) if state, err := session.Status(); state != Active || err != nil { t.Fatalf("descendant exit retired the live session: %s %v", state, err) } // A status flag alone does not prove the main child's protocol still works. - _ = supervised_descendant(t, session) + _ = supervisedDescendant(t, session) } func TestSupervisionMissingProgramReleasesCapacity(t *testing.T) { t.Setenv("CTHULHU_TENTACLE_CGROUP_PARENT", "") - manager := supervised_manager(t) + manager := supervisedManager(t) spec := Spec{ID: "sample", Program: []string{filepath.Join(t.TempDir(), "missing")}} session, err := manager.Start(context.Background(), spec) if err != nil { t.Fatal(err) } - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, failure := session.Status(); state != Failed || failure == nil { t.Fatal(state, failure) } - healthy := start_active(t, manager, "sample", "echo") + healthy := startActive(t, manager, "sample", "echo") healthy.Disable() - wait_signal(t, healthy.Done()) + waitSignal(t, healthy.Done()) } func TestSupervisionRejectsInvalidExplicitCgroupParent(t *testing.T) { for _, parent := range []string{"relative", t.TempDir()} { - if _, err := NewSupervisedManager(supervisor_program(t), parent); !errors.Is(err, ErrContainment) { + if _, err := NewSupervisedManager(supervisorProgram(t), parent); !errors.Is(err, ErrContainment) { t.Fatalf("silently ignored explicit parent %q: %v", parent, err) } } t.Setenv("CTHULHU_TENTACLE_CGROUP_PARENT", t.TempDir()) - if _, err := NewSupervisedManager(supervisor_program(t), "auto"); !errors.Is(err, ErrContainment) { + if _, err := NewSupervisedManager(supervisorProgram(t), "auto"); !errors.Is(err, ErrContainment) { t.Fatalf("silently ignored configured parent: %v", err) } } func TestSupervisionCancelledStartupReleasesCapacity(t *testing.T) { t.Setenv("CTHULHU_TENTACLE_CGROUP_PARENT", "") - manager := supervised_manager(t) - session, err := manager.Start(context.Background(), child_spec(t, "sample", "hang-start")) + manager := supervisedManager(t) + session, err := manager.Start(context.Background(), childSpec(t, "sample", "hang-start")) if err != nil { t.Fatal(err) } - wait_control(t, func() bool { + waitControl(t, func() bool { session.mutex.Lock() defer session.mutex.Unlock() return len(session.pending) > 0 }) session.Disable() - wait_signal(t, session.Done()) + waitSignal(t, session.Done()) if state, err := session.Status(); state != Stopped || err != nil { t.Fatal(state, err) } - healthy := start_active(t, manager, "sample", "echo") + healthy := startActive(t, manager, "sample", "echo") healthy.Disable() - wait_signal(t, healthy.Done()) + waitSignal(t, healthy.Done()) } func TestSupervisionDetectsChildExitAfterActivation(t *testing.T) { t.Setenv("CTHULHU_TENTACLE_CGROUP_PARENT", "") - manager := supervised_manager(t) - session := start_active(t, manager, "sample", "exit-active") - wait_signal(t, session.Done()) + manager := supervisedManager(t) + session := startActive(t, manager, "sample", "exit-active") + waitSignal(t, session.Done()) if state, err := session.Status(); state != Failed || !errors.Is(err, ErrExited) { t.Fatal(state, err) } diff --git a/internal/tentacle/updates.go b/internal/tentacle/updates.go index f0262a4..3013a27 100644 --- a/internal/tentacle/updates.go +++ b/internal/tentacle/updates.go @@ -26,7 +26,7 @@ type packageVersion struct { prerelease []string } -func numeric_identifier(value string) bool { +func numericIdentifier(value string) bool { if value == "" { return false } @@ -38,7 +38,7 @@ func numeric_identifier(value string) bool { return true } -func version_identifiers(value string, prerelease bool) ([]string, error) { +func versionIdentifiers(value string, prerelease bool) ([]string, error) { identifiers := strings.Split(value, ".") for _, identifier := range identifiers { if identifier == "" { @@ -49,25 +49,25 @@ func version_identifiers(value string, prerelease bool) ([]string, error) { return nil, fmt.Errorf("invalid version identifier %q", identifier) } } - if prerelease && numeric_identifier(identifier) && len(identifier) > 1 && identifier[0] == '0' { + if prerelease && numericIdentifier(identifier) && len(identifier) > 1 && identifier[0] == '0' { return nil, fmt.Errorf("prerelease number has a leading zero") } } return identifiers, nil } -func parse_package_version(value string) (packageVersion, error) { +func parsePackageVersion(value string) (packageVersion, error) { var result packageVersion core := strings.TrimPrefix(strings.TrimSpace(value), "v") if before, build, found := strings.Cut(core, "+"); found { - if _, err := version_identifiers(build, false); err != nil { + if _, err := versionIdentifiers(build, false); err != nil { return result, err } core = before } if before, prerelease, found := strings.Cut(core, "-"); found { var err error - result.prerelease, err = version_identifiers(prerelease, true) + result.prerelease, err = versionIdentifiers(prerelease, true) if err != nil { return result, err } @@ -75,7 +75,7 @@ func parse_package_version(value string) (packageVersion, error) { } result.numbers = strings.Split(core, ".") for _, number := range result.numbers { - if !numeric_identifier(number) { + if !numericIdentifier(number) { return result, fmt.Errorf("invalid numeric version %q", value) } } @@ -83,7 +83,7 @@ func parse_package_version(value string) (packageVersion, error) { } // Compare decimal strings without an integer-size limit. -func compare_version_number(first, second string) int { +func compareVersionNumber(first, second string) int { first, second = strings.TrimLeft(first, "0"), strings.TrimLeft(second, "0") if len(first) < len(second) { return -1 @@ -97,11 +97,11 @@ func compare_version_number(first, second string) int { // IsNewerVersion compares release and prerelease precedence. Build metadata // does not change precedence; missing numeric components are treated as zero. func IsNewerVersion(available, installed string) (bool, error) { - first, err := parse_package_version(available) + first, err := parsePackageVersion(available) if err != nil { return false, err } - second, err := parse_package_version(installed) + second, err := parsePackageVersion(installed) if err != nil { return false, err } @@ -113,7 +113,7 @@ func IsNewerVersion(available, installed string) (bool, error) { if index < len(second.numbers) { secondNumber = second.numbers[index] } - if compared := compare_version_number(firstNumber, secondNumber); compared != 0 { + if compared := compareVersionNumber(firstNumber, secondNumber); compared != 0 { return compared > 0, nil } } @@ -122,10 +122,10 @@ func IsNewerVersion(available, installed string) (bool, error) { } for index := 0; index < len(first.prerelease) && index < len(second.prerelease); index++ { firstID, secondID := first.prerelease[index], second.prerelease[index] - firstNumeric, secondNumeric := numeric_identifier(firstID), numeric_identifier(secondID) + firstNumeric, secondNumeric := numericIdentifier(firstID), numericIdentifier(secondID) compared := strings.Compare(firstID, secondID) if firstNumeric && secondNumeric { - compared = compare_version_number(firstID, secondID) + compared = compareVersionNumber(firstID, secondID) } if firstNumeric != secondNumeric { return !firstNumeric, nil diff --git a/internal/tentaclewire/form.go b/internal/tentaclewire/form.go new file mode 100644 index 0000000..6998311 --- /dev/null +++ b/internal/tentaclewire/form.go @@ -0,0 +1,199 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package tentaclewire + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "strings" + "unicode" + "unicode/utf8" + + ui "git.stormux.org/storm/screenreader-common/internalui" +) + +// Kind is a Tentacle form control. Its numeric JSON values are wire format. +type Kind uint8 + +const ( + List Kind = iota + 1 + Entry + CheckBox + Button +) + +type FormItem struct { + ID string `json:"id"` + Label string `json:"label"` + Disabled bool `json:"disabled,omitempty"` +} + +type Element struct { + ID string `json:"id"` + Label string `json:"label"` + Kind Kind `json:"kind"` + Items []FormItem `json:"items,omitempty"` + Text string `json:"text,omitempty"` + Checked bool `json:"checked,omitempty"` + Disabled bool `json:"disabled,omitempty"` + Required bool `json:"required,omitempty"` + MaxLength int `json:"max_length,omitempty"` + // Secret is supported only on transient entries, never preference pages. + Secret bool `json:"secret,omitempty"` +} + +// Form is the flat form a Tentacle sends. The reader runs it as an +// internalui flat form whose single page is FormTab. +type Form struct { + Title string `json:"title"` + Elements []Element `json:"elements"` +} + +type Value struct { + Text string `json:"text,omitempty"` + Selected string `json:"selected,omitempty"` + Checked bool `json:"checked,omitempty"` +} + +// FormTab is the page ID of every converted Tentacle form; submitted +// internalui values are keyed FormTab + "." + element ID. +const FormTab = "form" + +const maxFormText = 8192 + +// UnmarshalJSON keeps a malformed secret flag from silently becoming an +// ordinary entry (encoding/json otherwise accepts null for a boolean). The +// wire decoder separately rejects duplicate keys and bounds nesting/framing. +func (element *Element) UnmarshalJSON(data []byte) error { + type plain Element + var value plain + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&value); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + for name, raw := range fields { + if strings.EqualFold(name, "secret") { + flag := string(bytes.TrimSpace(raw)) + if name != "secret" || flag != "true" && flag != "false" { + return errors.New("secret must be a boolean") + } + } + } + *element = Element(value) + return nil +} + +// NewSession validates a Tentacle form against the external protocol limits +// and opens it. Its text is Tentacle-owned, so it is never translated. +func NewSession(form Form) (*ui.Session, error) { + converted, err := uiForm(form, 256, 64) + if err != nil { + return nil, err + } + return ui.NewSession(converted, ui.Messages{}) +} + +// ValidatePreferences shares control validation with Tentacle forms, while +// allowing a native, scrolling page to contain several full voice editors. +func ValidatePreferences(form Form) error { + for _, element := range form.Elements { + if element.Secret { + return errors.New("secret entries are not supported in preferences") + } + } + converted, err := uiForm(form, 256, 256) + if err == nil { + _, err = ui.NewSession(converted, ui.Messages{}) + } + return err +} + +func uiForm(form Form, maxItems, maxElements int) (ui.Form, error) { + if form.Title == "" || len(form.Title) > 1024 || len(form.Elements) == 0 || len(form.Elements) > maxElements { + return ui.Form{}, fmt.Errorf("a titled form with 1 to %d controls is required", maxElements) + } + controls := make([]ui.Control, 0, len(form.Elements)) + ids := map[string]bool{} + for _, element := range form.Elements { + if element.ID == "" || len(element.ID) > 1024 || element.Label == "" || len(element.Label) > 1024 || ids[element.ID] || element.Kind < List || element.Kind > Button { + return ui.Form{}, errors.New("controls need unique IDs, labels and supported kinds") + } + ids[element.ID] = true + if element.Secret && element.Kind != Entry { + return ui.Form{}, errors.New("only entries may be secret") + } + if element.MaxLength == 0 { + element.MaxLength = maxFormText + } + if element.MaxLength < 1 || element.MaxLength > maxFormText || len([]rune(element.Text)) > element.MaxLength { + return ui.Form{}, errors.New("invalid entry length") + } + if !utf8.ValidString(element.Text) || strings.ContainsFunc(element.Text, unicode.IsControl) { + return ui.Form{}, errors.New("entries must contain single-line text") + } + if len(element.Items) > maxItems { + return ui.Form{}, errors.New("too many list items") + } + control := ui.Control{ID: element.ID, Label: element.Label, Text: element.Text, Checked: element.Checked, Disabled: element.Disabled, Required: element.Required, Secret: element.Secret, MaxLength: element.MaxLength, Selected: -1, Action: element.ID} + itemIDs := map[string]bool{} + var choices []ui.Choice + for index, item := range element.Items { + if item.ID == "" || len(item.ID) > 1024 || item.Label == "" || len(item.Label) > 1024 || itemIDs[item.ID] { + return ui.Form{}, errors.New("list items need unique IDs and labels") + } + itemIDs[item.ID] = true + if control.Selected < 0 && !item.Disabled { + control.Selected = index + } + choices = append(choices, ui.Choice{ID: item.ID, Label: item.Label, Literal: true, Disabled: item.Disabled}) + } + switch element.Kind { + case List: + control.Kind, control.SelectAction, control.Choices = ui.List, true, choices + if control.Selected < 0 { + control.Disabled = true + } + case Entry: + control.Kind = ui.Entry + case CheckBox: + control.Kind = ui.CheckBox + case Button: + control.Kind = ui.Button + } + controls = append(controls, control) + } + return ui.Form{Type: ui.FlatForm, Title: form.Title, Detailed: true, Tabs: []ui.Tab{{ID: FormTab, Label: form.Title, Controls: controls}}}, nil +} + +// SubmissionValues converts a converted form's internalui values back to the +// Tentacle wire values, keyed by element ID. Entry values may hold secrets. +func SubmissionValues(controls map[string]ui.Control) map[string]Value { + if controls == nil { + return nil + } + values := make(map[string]Value, len(controls)) + for key, control := range controls { + id, found := strings.CutPrefix(key, FormTab+".") + if !found { + continue + } + value := Value{Text: control.Text, Checked: control.Checked} + if control.Kind == ui.List { + value.Text = "" + if control.Selected >= 0 && control.Selected < len(control.Choices) { + value.Selected = control.Choices[control.Selected].ID + } + } + values[id] = value + } + return values +} diff --git a/internal/tentaclewire/form_test.go b/internal/tentaclewire/form_test.go new file mode 100644 index 0000000..de74084 --- /dev/null +++ b/internal/tentaclewire/form_test.go @@ -0,0 +1,142 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package tentaclewire + +import ( + "strconv" + "strings" + "testing" + + ui "git.stormux.org/storm/screenreader-common/internalui" +) + +func TestFormKeepsExternalListLimit(t *testing.T) { + items := make([]FormItem, 300) + for index := range items { + items[index] = FormItem{ID: strconv.Itoa(index), Label: "Example item"} + } + if _, err := NewSession(Form{Title: "External form", Elements: []Element{{ID: "items", Label: "Items", Kind: List, Items: items}}}); err == nil { + t.Fatal("external form exceeded its protocol limit") + } + if _, err := NewSession(Form{Title: "External form", Elements: []Element{{ID: "items", Label: "Items", Kind: List, Items: items[:256]}}}); err != nil { + t.Fatal(err) + } +} + +func TestFormListSelectionAndIndependentSessions(t *testing.T) { + form := Form{Title: "Actions", Elements: []Element{{ID: "actions", Label: "Actions", Kind: List, Items: []FormItem{{ID: "skip", Label: "Unavailable", Disabled: true}, {ID: "click", Label: "Click"}, {ID: "press", Label: "Press"}}}}} + first, err := NewSession(form) + if err != nil { + t.Fatal(err) + } + second, _ := NewSession(form) + if opening := first.Open(); opening != "Actions. Click" { + t.Fatalf("opening speech = %q", opening) + } + if moved := first.Handle(ui.Key{Name: "down"}).Speech; moved != "Press" { + t.Fatalf("option speech = %q", moved) + } + if effect := first.Handle(ui.Key{Name: "enter"}); effect.Action != "press" { + t.Fatalf("selection = %+v", effect) + } + if second.Handle(ui.Key{Name: "enter"}).Action != "click" { + t.Fatal("sessions share state") + } + form.Elements[0].Items[1].Label = "Changed" + if !strings.Contains(second.Presentation().Speech, "Click") { + t.Fatal("caller mutation changed session") + } +} + +func TestFormListLabelOnlyBesideOtherControls(t *testing.T) { + menu, err := NewSession(Form{Title: "Wormhole Menu", Elements: []Element{{ID: "choices", Label: "Options", Kind: List, Items: []FormItem{{ID: "send", Label: "Send focused item"}, {ID: "receive", Label: "Receive file"}}}}}) + if err != nil { + t.Fatal(err) + } + if opening := menu.Open(); opening != "Wormhole Menu. Send focused item" { + t.Fatalf("custom title = %q", opening) + } + menu.Handle(ui.Key{Name: "down"}) + if focus := menu.Handle(ui.Key{Name: "tab"}).Speech; focus != "Receive file" { + t.Fatalf("menu repeated its label on Tab: %q", focus) + } + form, _ := NewSession(Form{Title: "Example", Elements: []Element{{ID: "code", Label: "Code", Kind: Entry}, {ID: "method", Label: "Method", Kind: List, Items: []FormItem{{ID: "send", Label: "Send"}}}}}) + if focus := form.Handle(ui.Key{Name: "tab"}).Speech; focus != "Method. Send" { + t.Fatalf("form list lost its field label: %q", focus) + } +} + +func TestInvalidForms(t *testing.T) { + for name, form := range map[string]Form{ + "empty": {}, + "list of nothing": {Title: "Empty", Elements: []Element{{ID: "list", Label: "List", Kind: List}}}, + "duplicate IDs": {Title: "Duplicate", Elements: []Element{{ID: "same", Label: "First", Kind: Button}, {ID: "same", Label: "Second", Kind: Entry}}}, + "unknown kind": {Title: "Kind", Elements: []Element{{ID: "x", Label: "X", Kind: Button + 1}}}, + "multiline text": {Title: "Text", Elements: []Element{{ID: "x", Label: "X", Kind: Entry, Text: "a\nb"}}}, + "text over limit": {Title: "Text", Elements: []Element{{ID: "x", Label: "X", Kind: Entry, Text: "toolong", MaxLength: 3}}}, + "duplicate items": {Title: "Items", Elements: []Element{{ID: "x", Label: "X", Kind: List, Items: []FormItem{{ID: "a", Label: "A"}, {ID: "a", Label: "B"}}}}}, + "secret checkbox": {Title: "Secret", Elements: []Element{{ID: "x", Label: "X", Kind: CheckBox, Secret: true}}}, + "nothing enabled": {Title: "Disabled", Elements: []Element{{ID: "x", Label: "X", Kind: Button, Disabled: true}}}, + "too many controls": func() Form { + form := Form{Title: "Many"} + for index := range 65 { + form.Elements = append(form.Elements, Element{ID: strconv.Itoa(index), Label: "Button", Kind: Button}) + } + return form + }(), + } { + if _, err := NewSession(form); err == nil { + t.Fatalf("accepted invalid form: %s", name) + } + } +} + +func TestPreferencesRejectSecretsAndAllowLargerPages(t *testing.T) { + secret := Form{Title: "Connection", Elements: []Element{{ID: "key", Label: "Channel key", Kind: Entry, Secret: true}}} + if _, err := NewSession(secret); err != nil { + t.Fatal(err) + } + if err := ValidatePreferences(secret); err == nil { + t.Fatal("secret accepted in persistent preferences") + } +} + +func TestSubmissionValuesFollowWireShape(t *testing.T) { + session, err := NewSession(Form{Title: "Receive", Elements: []Element{ + {ID: "code", Label: "Code", Kind: Entry, Required: true}, + {ID: "method", Label: "Method", Kind: List, Items: []FormItem{{ID: "send", Label: "Send"}, {ID: "receive", Label: "Receive"}}}, + {ID: "keep", Label: "Keep", Kind: CheckBox}, + {ID: "submit", Label: "Receive", Kind: Button}, + }}) + if err != nil { + t.Fatal(err) + } + if effect := session.Handle(ui.Key{Name: "tab"}); effect.Speech != "Method. Send" { + t.Fatalf("list arrival = %q", effect.Speech) + } + session.Handle(ui.Key{Name: "tab", Shift: true}) + session.Insert("7-alpha") + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Text: "r"}) + session.Handle(ui.Key{Name: "tab"}) + session.Handle(ui.Key{Name: "space", Text: " "}) + session.Handle(ui.Key{Name: "tab"}) + if effect := session.Handle(ui.Key{Name: "enter"}); effect.Action != "submit" { + t.Fatalf("submit = %+v", effect) + } + got := SubmissionValues(session.Values()) + want := map[string]Value{"code": {Text: "7-alpha"}, "method": {Selected: "receive"}, "keep": {Checked: true}, "submit": {}} + if len(got) != len(want) { + t.Fatalf("values = %+v", got) + } + for id, value := range want { + if got[id] != value { + t.Fatalf("%s = %+v, want %+v", id, got[id], value) + } + } + if SubmissionValues(nil) != nil { + t.Fatal("missing controls became an empty submission") + } +} diff --git a/internal/tentaclewire/interaction.go b/internal/tentaclewire/interaction.go index ac82251..84a8e14 100644 --- a/internal/tentaclewire/interaction.go +++ b/internal/tentaclewire/interaction.go @@ -9,8 +9,6 @@ import ( "slices" "unicode" "unicode/utf8" - - "git.stormux.org/storm/cthulhu/internal/interaction" ) // Interaction is an opt-in command result. The host runs forms outside the @@ -20,14 +18,14 @@ import ( // reader-owned consent, or finish with a verified background lease. type Interaction struct { Presentation - Form *interaction.Form `json:"form,omitempty"` - Next string `json:"next,omitempty"` - Poll string `json:"poll,omitempty"` - Source string `json:"source,omitempty"` // "focus" or "clipboard", supplied to Next. - Clipboard *string `json:"clipboard,omitempty"` - Done bool `json:"done,omitempty"` - Reader *ReaderRequest `json:"reader,omitempty"` - Remote *RemoteRequest `json:"remote,omitempty"` + Form *Form `json:"form,omitempty"` + Next string `json:"next,omitempty"` + Poll string `json:"poll,omitempty"` + Source string `json:"source,omitempty"` // "focus" or "clipboard", supplied to Next. + Clipboard *string `json:"clipboard,omitempty"` + Done bool `json:"done,omitempty"` + Reader *ReaderRequest `json:"reader,omitempty"` + Remote *RemoteRequest `json:"remote,omitempty"` // RemoteBackground ends this interaction while retaining an already-open // lease owned by this process session. It grants no new access or lifetime. RemoteBackground *RemoteLease `json:"remote_background,omitempty"` @@ -42,13 +40,13 @@ type RemoteRequest struct { } type Submission struct { - Activated string `json:"activated,omitempty"` - Values map[string]interaction.Value `json:"values,omitempty"` - Cancelled bool `json:"cancelled,omitempty"` - Item *Item `json:"item,omitempty"` - Error string `json:"error,omitempty"` - Reader *ReaderState `json:"reader,omitempty"` - Remote *SessionEvent `json:"remote,omitempty"` + Activated string `json:"activated,omitempty"` + Values map[string]Value `json:"values,omitempty"` + Cancelled bool `json:"cancelled,omitempty"` + Item *Item `json:"item,omitempty"` + Error string `json:"error,omitempty"` + Reader *ReaderState `json:"reader,omitempty"` + Remote *SessionEvent `json:"remote,omitempty"` } // Item is a single copied value, without accessible identities or native handles. @@ -112,7 +110,7 @@ func DecodeInteraction(data []byte) (Interaction, error) { if !validFormText(value.Form.Title) { return value, ErrProtocol } - if _, err := interaction.NewSession(*value.Form); err != nil { + if _, err := NewSession(*value.Form); err != nil { return value, ErrProtocol } if value.Next == "" || value.Done || value.Source != "" { diff --git a/internal/tentaclewire/interaction_test.go b/internal/tentaclewire/interaction_test.go index d4db7e8..a6fd12d 100644 --- a/internal/tentaclewire/interaction_test.go +++ b/internal/tentaclewire/interaction_test.go @@ -2,13 +2,12 @@ package tentaclewire import ( "encoding/json" - "git.stormux.org/storm/cthulhu/internal/interaction" "strings" "testing" ) func TestInteractionContract(t *testing.T) { - form := &interaction.Form{Title: "Wormhole menu", Elements: []interaction.Element{{ID: "choices", Label: "Options", Kind: interaction.List, Items: []interaction.Item{{ID: "send", Label: "Send focused item"}}}}} + form := &Form{Title: "Wormhole menu", Elements: []Element{{ID: "choices", Label: "Options", Kind: List, Items: []FormItem{{ID: "send", Label: "Send focused item"}}}}} for _, value := range []Interaction{ {Form: form, Next: "choice"}, {Form: form, Next: "choice", Poll: "status"}, {Source: "focus", Next: "send"}, {Source: "clipboard", Next: "send"}, {Presentation: Presentation{Speech: "Ready"}, Done: true}, {Done: true}, {}, @@ -70,8 +69,8 @@ func TestSecretInteractionContract(t *testing.T) { } } page := PreferencePage{ID: "connection", Title: "Connection", Command: "connect", - Elements: []interaction.Element{{ID: "key", Label: "Channel key", Kind: interaction.Entry, Secret: true}}, - Values: map[string]interaction.Value{"key": {Text: "fixture"}}} + Elements: []Element{{ID: "key", Label: "Channel key", Kind: Entry, Secret: true}}, + Values: map[string]Value{"key": {Text: "fixture"}}} if ValidateExtensions(Extensions{Pages: []PreferencePage{page}}) == nil || ValidatePageValues(page, page.Values) == nil { t.Fatal("secret permitted in persistent page values") } diff --git a/internal/tentaclewire/reader.go b/internal/tentaclewire/reader.go index 99e8f91..1b89180 100644 --- a/internal/tentaclewire/reader.go +++ b/internal/tentaclewire/reader.go @@ -9,7 +9,6 @@ import ( "strings" "git.stormux.org/storm/cthulhu/internal/config" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/speech" ) @@ -70,20 +69,20 @@ func (value SpeechConfiguration) Apply(settings config.Settings) config.Settings } type PreferencePage struct { - ID string `json:"id"` - Title string `json:"title"` - Command string `json:"command"` - Load bool `json:"load,omitempty"` - Elements []interaction.Element `json:"elements"` - Values map[string]interaction.Value `json:"values"` + ID string `json:"id"` + Title string `json:"title"` + Command string `json:"command"` + Load bool `json:"load,omitempty"` + Elements []Element `json:"elements"` + Values map[string]Value `json:"values"` } type QuickSetting struct { - ID string `json:"id"` - Label string `json:"label"` - Command string `json:"command"` - Options []interaction.Item `json:"options"` - Selected string `json:"selected"` + ID string `json:"id"` + Label string `json:"label"` + Command string `json:"command"` + Options []FormItem `json:"options"` + Selected string `json:"selected"` } // Extensions are copied at registration/update. IDs are local to one session. @@ -115,14 +114,14 @@ type ReaderState struct { // ExtensionEvent handlers propose effects only. The host commits page values // and quick selections after validating all proposals and applying core settings. type ExtensionEvent struct { - Event string `json:"event"` - ID string `json:"id"` - Values map[string]interaction.Value `json:"values,omitempty"` - Selected string `json:"selected,omitempty"` - Reader ReaderState `json:"reader"` + Event string `json:"event"` + ID string `json:"id"` + Values map[string]Value `json:"values,omitempty"` + Selected string `json:"selected,omitempty"` + Reader ReaderState `json:"reader"` } -func valid_label(value string) bool { +func validLabel(value string) bool { return strings.TrimSpace(value) != "" && len(value) <= 256 && validFormText(value) } @@ -144,19 +143,19 @@ func ValidateExtensions(value Extensions) error { } ids := map[string]bool{} for _, page := range value.Pages { - if !ValidExtensionID(page.ID) || ids[page.ID] || !valid_label(page.Title) || !ValidExtensionID(page.Command) { + if !ValidExtensionID(page.ID) || ids[page.ID] || !validLabel(page.Title) || !ValidExtensionID(page.Command) { return ErrProtocol } ids[page.ID] = true - if err := interaction.ValidatePreferences(interaction.Form{Title: page.Title, Elements: page.Elements}); err != nil { + if err := ValidatePreferences(Form{Title: page.Title, Elements: page.Elements}); err != nil { return ErrProtocol } for _, element := range page.Elements { - if !ValidExtensionID(element.ID) || !valid_label(element.Label) || element.Kind == interaction.Button { + if !ValidExtensionID(element.ID) || !validLabel(element.Label) || element.Kind == Button { return ErrProtocol } for _, item := range element.Items { - if !ValidExtensionID(item.ID) || !valid_label(item.Label) { + if !ValidExtensionID(item.ID) || !validLabel(item.Label) { return ErrProtocol } } @@ -167,14 +166,14 @@ func ValidateExtensions(value Extensions) error { } clear(ids) for _, setting := range value.QuickSettings { - if !ValidExtensionID(setting.ID) || ids[setting.ID] || !valid_label(setting.Label) || !ValidExtensionID(setting.Command) || len(setting.Options) == 0 || len(setting.Options) > 64 { + if !ValidExtensionID(setting.ID) || ids[setting.ID] || !validLabel(setting.Label) || !ValidExtensionID(setting.Command) || len(setting.Options) == 0 || len(setting.Options) > 64 { return ErrProtocol } ids[setting.ID] = true options := map[string]bool{} selected := false for _, option := range setting.Options { - if !ValidExtensionID(option.ID) || options[option.ID] || !valid_label(option.Label) { + if !ValidExtensionID(option.ID) || options[option.ID] || !validLabel(option.Label) { return ErrProtocol } options[option.ID] = true @@ -191,7 +190,7 @@ func ValidateExtensions(value Extensions) error { return nil } -func ValidatePageValues(page PreferencePage, values map[string]interaction.Value) error { +func ValidatePageValues(page PreferencePage, values map[string]Value) error { if len(values) != len(page.Elements) { return errors.New("page values do not match its controls") } @@ -204,7 +203,7 @@ func ValidatePageValues(page PreferencePage, values map[string]interaction.Value return ErrProtocol } switch element.Kind { - case interaction.Entry: + case Entry: limit := element.MaxLength if limit == 0 { limit = 8192 @@ -212,11 +211,11 @@ func ValidatePageValues(page PreferencePage, values map[string]interaction.Value if !validFormText(value.Text) || len([]rune(value.Text)) > limit || value.Selected != "" || value.Checked || element.Required && strings.TrimSpace(value.Text) == "" { return ErrProtocol } - case interaction.CheckBox: + case CheckBox: if value.Text != "" || value.Selected != "" { return ErrProtocol } - case interaction.List: + case List: valid := false for _, item := range element.Items { valid = valid || item.ID == value.Selected && !item.Disabled diff --git a/internal/tentaclewire/reader_test.go b/internal/tentaclewire/reader_test.go index 41f668d..70e5e0d 100644 --- a/internal/tentaclewire/reader_test.go +++ b/internal/tentaclewire/reader_test.go @@ -6,36 +6,35 @@ import ( "encoding/json" "fmt" "git.stormux.org/storm/cthulhu/internal/config" - "git.stormux.org/storm/cthulhu/internal/interaction" "math" "reflect" "testing" ) -func reader_test_extensions() Extensions { +func readerTestExtensions() Extensions { return Extensions{ - Pages: []PreferencePage{{ID: "options", Title: "Reader probe", Command: "apply", Elements: []interaction.Element{ - {ID: "text", Label: "Text", Kind: interaction.Entry, Required: true, MaxLength: 32}, - {ID: "enabled", Label: "Enabled", Kind: interaction.CheckBox}, - {ID: "choice", Label: "Choice", Kind: interaction.List, Items: []interaction.Item{{ID: "first", Label: "First"}, {ID: "second", Label: "Second", Disabled: true}}}, - }, Values: map[string]interaction.Value{"text": {Text: "Initial"}, "enabled": {}, "choice": {Selected: "first"}}}}, - QuickSettings: []QuickSetting{{ID: "choice", Label: "Probe choice", Command: "apply", Options: []interaction.Item{{ID: "default", Label: "Default"}, {ID: "custom", Label: "Custom"}}, Selected: "default"}}, + Pages: []PreferencePage{{ID: "options", Title: "Reader probe", Command: "apply", Elements: []Element{ + {ID: "text", Label: "Text", Kind: Entry, Required: true, MaxLength: 32}, + {ID: "enabled", Label: "Enabled", Kind: CheckBox}, + {ID: "choice", Label: "Choice", Kind: List, Items: []FormItem{{ID: "first", Label: "First"}, {ID: "second", Label: "Second", Disabled: true}}}, + }, Values: map[string]Value{"text": {Text: "Initial"}, "enabled": {}, "choice": {Selected: "first"}}}}, + QuickSettings: []QuickSetting{{ID: "choice", Label: "Probe choice", Command: "apply", Options: []FormItem{{ID: "default", Label: "Default"}, {ID: "custom", Label: "Custom"}}, Selected: "default"}}, } } func TestReaderPageCanDescribeSixCompleteVoiceConfigurations(t *testing.T) { - page := PreferencePage{ID: "voices", Title: "Voice configurations", Command: "apply", Values: map[string]interaction.Value{}} + page := PreferencePage{ID: "voices", Title: "Voice configurations", Command: "apply", Values: map[string]Value{}} for profile := 1; profile <= 6; profile++ { for field := 1; field <= 24; field++ { id := fmt.Sprintf("profile%d.field%d", profile, field) - page.Elements = append(page.Elements, interaction.Element{ID: id, Label: fmt.Sprintf("Profile %d setting %d", profile, field), Kind: interaction.Entry, MaxLength: 64}) - page.Values[id] = interaction.Value{Text: "Example"} + page.Elements = append(page.Elements, Element{ID: id, Label: fmt.Sprintf("Profile %d setting %d", profile, field), Kind: Entry, MaxLength: 64}) + page.Values[id] = Value{Text: "Example"} } } if err := ValidateExtensions(Extensions{Pages: []PreferencePage{page}}); err != nil { t.Fatal(err) } - if _, err := interaction.NewSession(interaction.Form{Title: page.Title, Elements: page.Elements}); err == nil { + if _, err := NewSession(Form{Title: page.Title, Elements: page.Elements}); err == nil { t.Fatal("native page limit leaked into internal forms") } state := ReaderState{Extensions: Extensions{Pages: []PreferencePage{page}}, Speech: SpeechFromSettings(config.DefaultSettings()), DefaultSpeech: SpeechFromSettings(config.DefaultSettings())} @@ -49,27 +48,27 @@ func TestReaderExtensionsRejectInvalidSchemasAndValues(t *testing.T) { "duplicate page": func(v *Extensions) { v.Pages = append(v.Pages, v.Pages[0]) }, "duplicate setting": func(v *Extensions) { v.QuickSettings = append(v.QuickSettings, v.QuickSettings[0]) }, "duplicate control": func(v *Extensions) { v.Pages[0].Elements = append(v.Pages[0].Elements, v.Pages[0].Elements[0]) }, - "button": func(v *Extensions) { v.Pages[0].Elements[0].Kind = interaction.Button }, + "button": func(v *Extensions) { v.Pages[0].Elements[0].Kind = Button }, "bad label": func(v *Extensions) { v.Pages[0].Title = "Probe\npage" }, "bad identifier": func(v *Extensions) { v.Pages[0].ID = "../page" }, "missing value": func(v *Extensions) { delete(v.Pages[0].Values, "text") }, - "extra value": func(v *Extensions) { v.Pages[0].Values["other"] = interaction.Value{} }, - "wrong value type": func(v *Extensions) { v.Pages[0].Values["enabled"] = interaction.Value{Text: "yes"} }, - "required": func(v *Extensions) { v.Pages[0].Values["text"] = interaction.Value{} }, + "extra value": func(v *Extensions) { v.Pages[0].Values["other"] = Value{} }, + "wrong value type": func(v *Extensions) { v.Pages[0].Values["enabled"] = Value{Text: "yes"} }, + "required": func(v *Extensions) { v.Pages[0].Values["text"] = Value{} }, "oversized": func(v *Extensions) { - v.Pages[0].Values["text"] = interaction.Value{Text: "This string is longer than thirty-two characters"} + v.Pages[0].Values["text"] = Value{Text: "This string is longer than thirty-two characters"} }, - "control character": func(v *Extensions) { v.Pages[0].Values["text"] = interaction.Value{Text: "bad\x1bvalue"} }, - "disabled choice": func(v *Extensions) { v.Pages[0].Values["choice"] = interaction.Value{Selected: "second"} }, + "control character": func(v *Extensions) { v.Pages[0].Values["text"] = Value{Text: "bad\x1bvalue"} }, + "disabled choice": func(v *Extensions) { v.Pages[0].Values["choice"] = Value{Selected: "second"} }, "unknown quick choice": func(v *Extensions) { v.QuickSettings[0].Selected = "missing" }, "disabled quick choice": func(v *Extensions) { v.QuickSettings[0].Options[0].Disabled = true }, } - if err := ValidateExtensions(reader_test_extensions()); err != nil { + if err := ValidateExtensions(readerTestExtensions()); err != nil { t.Fatal(err) } for name, mutate := range mutations { t.Run(name, func(t *testing.T) { - value := reader_test_extensions() + value := readerTestExtensions() mutate(&value) if ValidateExtensions(value) == nil { t.Fatal("accepted invalid extension") @@ -126,7 +125,7 @@ func TestReaderInteractionValidation(t *testing.T) { t.Fatal("accepted", raw) } } - value := reader_test_extensions() + value := readerTestExtensions() data, _ := json.Marshal(Interaction{Reader: &ReaderRequest{Extensions: &value}}) if _, err := DecodeInteraction(data); err != nil { t.Fatal(err) diff --git a/internal/tentaclewire/remote_speech.go b/internal/tentaclewire/remote_speech.go index bc07d1f..395e2ce 100644 --- a/internal/tentaclewire/remote_speech.go +++ b/internal/tentaclewire/remote_speech.go @@ -49,14 +49,14 @@ func ValidRemotePresentation(request RemotePresentation) bool { func (request *RemotePresentation) UnmarshalJSON(data []byte) error { type plain RemotePresentation var value plain - if reject_speech_nulls(data) != nil || DecodeStrict(data, &value) != nil || !ValidRemotePresentation(RemotePresentation(value)) { + if rejectSpeechNulls(data) != nil || DecodeStrict(data, &value) != nil || !ValidRemotePresentation(RemotePresentation(value)) { return ErrProtocol } *request = RemotePresentation(value) return nil } -func reject_speech_nulls(data []byte) error { +func rejectSpeechNulls(data []byte) error { var fields map[string]json.RawMessage if json.Unmarshal(data, &fields) != nil || fields == nil { return ErrProtocol @@ -72,7 +72,7 @@ func reject_speech_nulls(data []byte) error { func (part *RemoteSpeechPart) UnmarshalJSON(data []byte) error { type plain RemoteSpeechPart var value plain - if reject_speech_nulls(data) != nil || DecodeStrict(data, &value) != nil { + if rejectSpeechNulls(data) != nil || DecodeStrict(data, &value) != nil { return ErrProtocol } *part = RemoteSpeechPart(value) @@ -82,7 +82,7 @@ func (part *RemoteSpeechPart) UnmarshalJSON(data []byte) error { func (speech *RemoteSpeech) UnmarshalJSON(data []byte) error { type plain RemoteSpeech var value plain - if reject_speech_nulls(data) != nil || DecodeStrict(data, &value) != nil || !ValidRemoteSpeech(RemoteSpeech(value)) { + if rejectSpeechNulls(data) != nil || DecodeStrict(data, &value) != nil || !ValidRemoteSpeech(RemoteSpeech(value)) { return ErrProtocol } *speech = RemoteSpeech(value) diff --git a/internal/tentaclewire/wire.go b/internal/tentaclewire/wire.go index 7e2a186..aa87d87 100644 --- a/internal/tentaclewire/wire.go +++ b/internal/tentaclewire/wire.go @@ -48,7 +48,7 @@ func ValidateJSON(data []byte) error { } decoder := json.NewDecoder(bytes.NewReader(data)) decoder.UseNumber() - if err := validate_value(decoder, 0); err != nil { + if err := validateValue(decoder, 0); err != nil { return ErrProtocol } if _, err := decoder.Token(); err != io.EOF { @@ -57,7 +57,7 @@ func ValidateJSON(data []byte) error { return nil } -func validate_value(decoder *json.Decoder, depth int) error { +func validateValue(decoder *json.Decoder, depth int) error { if depth > 32 { return ErrLimit } @@ -85,7 +85,7 @@ func validate_value(decoder *json.Decoder, depth int) error { } keys[key] = true } - if err := validate_value(decoder, depth+1); err != nil { + if err := validateValue(decoder, depth+1); err != nil { return err } } diff --git a/internal/version/build.go b/internal/version/build.go index 9434cc6..e8d9d08 100644 --- a/internal/version/build.go +++ b/internal/version/build.go @@ -20,10 +20,10 @@ type Identity struct { func RuntimeIdentity() Identity { info, _ := debug.ReadBuildInfo() - return build_identity(info) + return buildIdentity(info) } -func build_identity(info *debug.BuildInfo) Identity { +func buildIdentity(info *debug.BuildInfo) Identity { identity := Identity{GoVersion: runtime.Version(), Revision: "unknown", Time: "unknown", Modified: "unknown"} if info == nil { return identity diff --git a/internal/version/build_test.go b/internal/version/build_test.go index 4531f7d..9923e07 100644 --- a/internal/version/build_test.go +++ b/internal/version/build_test.go @@ -15,12 +15,12 @@ func TestBuildIdentityUsesEmbeddedSettings(t *testing.T) { {Key: "vcs.time", Value: "2026-10-16T12:00:00Z"}, {Key: "vcs.modified", Value: "true"}, }} - identity := build_identity(info) + identity := buildIdentity(info) if identity != (Identity{"go1.24.0", "0123456789abcdef", "2026-10-16T12:00:00Z", "true"}) { t.Fatalf("embedded build identity = %+v", identity) } for _, info := range []*debug.BuildInfo{nil, {GoVersion: "go1.24.0"}} { - identity := build_identity(info) + identity := buildIdentity(info) if identity.GoVersion == "" || identity.Revision != "unknown" || identity.Time != "unknown" || identity.Modified != "unknown" { t.Fatalf("unstamped build falsely identified: %+v", identity) } diff --git a/internal/version/version.go b/internal/version/version.go index ad208d9..b00f5a6 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -21,7 +21,7 @@ import "strings" const Name = "Cthulhu" -const Version = "2026.11.15" +const Version = "2026.11.16" const Channel = "testing" var Build = Version diff --git a/internal/wine/diagnostics_test.go b/internal/wine/diagnostics_test.go index fc7142f..cc10c36 100644 --- a/internal/wine/diagnostics_test.go +++ b/internal/wine/diagnostics_test.go @@ -126,7 +126,7 @@ func TestHelperReadinessBypassesDiagnosticBackpressure(t *testing.T) { t.Fatalf("readiness publications before logging = %d, want 1", readyCount) } manager := New(nil) - if !manager.restart_running_helper(child, prefix{}, Settings{}) || !manager.helper_unconfirmed("helper") { + if !manager.restartRunningHelper(child, prefix{}, Settings{}) || !manager.helperUnconfirmed("helper") { t.Fatal("lost exclusion mismatch fallback under diagnostic backpressure") } output.finish() diff --git a/internal/wine/helper_staging.go b/internal/wine/helper_staging.go index bffc003..5383d82 100644 --- a/internal/wine/helper_staging.go +++ b/internal/wine/helper_staging.go @@ -28,7 +28,7 @@ type helperFile struct { // A pressure-vessel wineserver cannot see the host's /usr. Publish complete, // immutable helper sets in the home-mounted state directory. Never overwrite // an older set: running processes may still have its sidecar mapped. -func stage_helper(helper string, environment map[string]string) (string, error) { +func stageHelper(helper string, environment map[string]string) (string, error) { if _, present := environment["PRESSURE_VESSEL_RUNTIME"]; !present { return helper, nil } diff --git a/internal/wine/live_settings_test.go b/internal/wine/live_settings_test.go index 6dff32a..ca349dc 100644 --- a/internal/wine/live_settings_test.go +++ b/internal/wine/live_settings_test.go @@ -19,15 +19,15 @@ func TestManagerReadsSettingsSourceAtEachPoll(t *testing.T) { root := t.TempDir() procRoot := filepath.Join(root, "proc") loader := filepath.Join(root, "wine") - write_helper_file(t, loader, "loader") + writeHelperFile(t, loader, "loader") base := filepath.Join(procRoot, "101") - write_helper_file(t, filepath.Join(base, "cmdline"), "launcher.exe\x00") - write_helper_file(t, filepath.Join(base, "environ"), "WINEPREFIX="+root+"\x00") + writeHelperFile(t, filepath.Join(base, "cmdline"), "launcher.exe\x00") + writeHelperFile(t, filepath.Join(base, "environ"), "WINEPREFIX="+root+"\x00") if err := os.Symlink(loader, filepath.Join(base, "exe")); err != nil { t.Fatal(err) } helper := filepath.Join(root, "helper") - write_helper_file(t, helper, "#!/bin/sh\nexec sleep 30\n") + writeHelperFile(t, helper, "#!/bin/sh\nexec sleep 30\n") current := Settings{} reads := 0 diff --git a/internal/wine/manager.go b/internal/wine/manager.go index 2354bac..807745d 100644 --- a/internal/wine/manager.go +++ b/internal/wine/manager.go @@ -73,13 +73,13 @@ type Manager struct { unconfirmed map[string]bool } -func (manager *Manager) helper_unconfirmed(helper string) bool { +func (manager *Manager) helperUnconfirmed(helper string) bool { manager.unconfirmedMu.Lock() defer manager.unconfirmedMu.Unlock() return manager.unconfirmed[helper] } -func (manager *Manager) mark_unconfirmed(helper string) { +func (manager *Manager) markUnconfirmed(helper string) { manager.unconfirmedMu.Lock() defer manager.unconfirmedMu.Unlock() if manager.unconfirmed == nil { @@ -177,7 +177,7 @@ func (manager *Manager) run(ctx context.Context) { } } -func (manager *Manager) current_settings() Settings { +func (manager *Manager) currentSettings() Settings { if manager.SettingsSource == nil { return Settings{} } @@ -189,7 +189,7 @@ func (manager *Manager) poll(active map[string]*process) { // Read the live settings once per poll. Restart decisions and every // spawn in this poll use this snapshot, so a value applied between // polls governs the next poll and spawn without a reader restart. - settings := manager.current_settings() + settings := manager.currentSettings() discovered := discover(manager.procRoot, uint32(os.Getuid())) for path, source := range discovered { child := active[path] @@ -209,7 +209,7 @@ func (manager *Manager) poll(active map[string]*process) { child.next = now.Add(backoff(child.failures)) child.cmd = nil default: - if manager.restart_running_helper(child, source, settings) { + if manager.restartRunningHelper(child, source, settings) { stop(child) } else { continue @@ -233,19 +233,19 @@ func (manager *Manager) poll(active map[string]*process) { } } -// restart_running_helper decides whether a running helper must restart to +// restartRunningHelper decides whether a running helper must restart to // gain protection it lacks. Restarts only ever add protection: a wholesale // helper never restarts here, and removing a listing or clearing the // global switch never downgrades a running helper. -func (manager *Manager) restart_running_helper(child *process, source prefix, settings Settings) bool { +func (manager *Manager) restartRunningHelper(child *process, source prefix, settings Settings) bool { if child.controllerOnly { return false } - if wholesale_controller_only(settings) || manager.helper_unconfirmed(child.launchedHelper) { + if wholesaleControllerOnly(settings) || manager.helperUnconfirmed(child.launchedHelper) { return true } if child.readySeen.Load() && int(child.readyExclusions.Load()) != len(child.exclusions) { - manager.mark_unconfirmed(child.launchedHelper) + manager.markUnconfirmed(child.launchedHelper) manager.logger.Warn("Wine accessibility helper did not confirm hook exclusions; restarting without dialog reading", "sent", len(child.exclusions), "reported", child.readyExclusions.Load()) return true @@ -253,7 +253,7 @@ func (manager *Manager) restart_running_helper(child *process, source prefix, se // A newly listed program that is currently discovered but lacks its // flag restarts the helper once, in the same mode, now carrying it. // Listings for programs that are not running wait for the next spawn. - for _, name := range exclusion_names(settings) { + for _, name := range exclusionNames(settings) { if source.programs[name] && !child.exclusions[name] { return true } @@ -269,13 +269,13 @@ func backoff(failures int) time.Duration { } func (manager *Manager) launch(child *process, source prefix, now time.Time, settings Settings) error { - helper, err := stage_helper(manager.helper, source.environment) + helper, err := stageHelper(manager.helper, source.environment) if err != nil { return err } - controllerOnly := child.controllerOnly || wholesale_controller_only(settings) || - manager.helper_unconfirmed(helper) - arguments := helper_arguments(controllerOnly, settings) + controllerOnly := child.controllerOnly || wholesaleControllerOnly(settings) || + manager.helperUnconfirmed(helper) + arguments := helperArguments(controllerOnly, settings) cmd := exec.Command(helper, arguments...) diagnostics := newHelperDiagnostics() generation := child.generation.Add(1) @@ -322,7 +322,7 @@ func (manager *Manager) launch(child *process, source prefix, now time.Time, set child.controllerOnly = controllerOnly child.launchedHelper = helper child.exclusions = make(map[string]bool) - for _, name := range exclusion_names(settings) { + for _, name := range exclusionNames(settings) { child.exclusions[name] = true } logger := manager.logger.With("helper_pid", cmd.Process.Pid) @@ -472,10 +472,10 @@ func discover(root string, uid uint32) map[string]prefix { if !filepath.IsAbs(path) { continue } - loader := wine_loader(exe, environment["WINELOADER"]) - programs := map[string]bool{program_name(string(commandLine)): true} + loader := wineLoader(exe, environment["WINELOADER"]) + programs := map[string]bool{programName(string(commandLine)): true} if previous, ok := result[path]; ok { - previous.programs[program_name(string(commandLine))] = true + previous.programs[programName(string(commandLine))] = true continue } result[path] = prefix{path: path, loader: loader, environment: environment, programs: programs} diff --git a/internal/wine/proton.go b/internal/wine/proton.go index e325fce..d786f42 100644 --- a/internal/wine/proton.go +++ b/internal/wine/proton.go @@ -13,12 +13,12 @@ import ( "git.stormux.org/storm/cthulhu/internal/config" ) -func program_name(commandLine string) string { +func programName(commandLine string) string { name := strings.SplitN(commandLine, "\x00", 2)[0] return filepath.Base(strings.ReplaceAll(strings.ToLower(strings.TrimSpace(name)), "\\", "/")) } -func wine_loader(exe, configured string) string { +func wineLoader(exe, configured string) string { if executable(configured) { // Protontricks' proxy requires its own runtime environment. Join the // existing server with the actual Proton loader instead. @@ -55,13 +55,13 @@ func wine_loader(exe, configured string) string { return "" } -// wholesale_controller_only reports whether the whole helper must run +// wholesaleControllerOnly reports whether the whole helper must run // without dialog reading. Only the global controller-only switch and the // environment override select it here; a helper binary remembered as -// unconfirmed (see Manager.helper_unconfirmed) is the third trigger. A +// unconfirmed (see Manager.helperUnconfirmed) is the third trigger. A // listed program by itself never selects wholesale mode: the helper gates // it natively while other programs in the prefix keep dialog reading. -func wholesale_controller_only(settings Settings) bool { +func wholesaleControllerOnly(settings Settings) bool { if settings.ControllerOnly { return true } @@ -69,12 +69,12 @@ func wholesale_controller_only(settings Settings) bool { return override != "" && override != "0" } -// exclusion_names returns the hook-exclusion program names exactly as the +// exclusionNames returns the hook-exclusion program names exactly as the // helper will store them: validated at the process boundary, lowercased, // deduplicated case-insensitively, and sorted. The validation mirrors the // helper's own rules so the count sent here matches the count its ready // record reports. -func exclusion_names(settings Settings) []string { +func exclusionNames(settings Settings) []string { seen := make(map[string]bool, len(settings.ExcludedPrograms)) var names []string for _, name := range settings.ExcludedPrograms { @@ -92,9 +92,9 @@ func exclusion_names(settings Settings) []string { return names } -func helper_arguments(controllerOnly bool, settings Settings) []string { +func helperArguments(controllerOnly bool, settings Settings) []string { var arguments []string - for _, name := range exclusion_names(settings) { + for _, name := range exclusionNames(settings) { arguments = append(arguments, "--exclude-hook-program", name) } if controllerOnly { diff --git a/internal/wine/proton_test.go b/internal/wine/proton_test.go index 5f2de64..efd8c1d 100644 --- a/internal/wine/proton_test.go +++ b/internal/wine/proton_test.go @@ -13,7 +13,7 @@ import ( "time" ) -func write_helper_file(t *testing.T, path, data string) { +func writeHelperFile(t *testing.T, path, data string) { t.Helper() if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { t.Fatal(err) @@ -28,11 +28,11 @@ func TestProtonLoaderBypassesProxy(t *testing.T) { loader := filepath.Join(root, "Proton", "files", "bin", "wine") preloader := filepath.Join(root, "Proton", "files", "lib", "wine", "i386-unix", "wine64-preloader") proxy := filepath.Join(root, "proxy", "wine") - write_helper_file(t, loader, "loader") - write_helper_file(t, preloader, "preloader") - write_helper_file(t, proxy, "#!/bin/sh\n# PROTONTRICKS_STEAM_RUNTIME\n") + writeHelperFile(t, loader, "loader") + writeHelperFile(t, preloader, "preloader") + writeHelperFile(t, proxy, "#!/bin/sh\n# PROTONTRICKS_STEAM_RUNTIME\n") for _, configured := range []string{"", proxy, loader} { - if got := wine_loader(preloader, configured); got != loader { + if got := wineLoader(preloader, configured); got != loader { t.Fatalf("loader = %q, want %q", got, loader) } } @@ -44,10 +44,10 @@ func TestContainerHelperPublishesImmutableCompleteSets(t *testing.T) { helper := filepath.Join(root, "installed", "wine-access.exe") names := []string{"wine-access.exe", "wine-access.exe.so", "wine-access-menu.dll", "wine-access-menu32.dll", "wine-access-menu-host32.exe"} for _, name := range names { - write_helper_file(t, filepath.Join(filepath.Dir(helper), name), name) + writeHelperFile(t, filepath.Join(filepath.Dir(helper), name), name) } environment := map[string]string{"PRESSURE_VESSEL_RUNTIME": "runtime"} - original, err := stage_helper(helper, environment) + original, err := stageHelper(helper, environment) if err != nil { t.Fatal(err) } @@ -60,8 +60,8 @@ func TestContainerHelperPublishesImmutableCompleteSets(t *testing.T) { t.Fatalf("incomplete set: %s: %v", name, err) } } - write_helper_file(t, helper+".so", "new sidecar") - updated, err := stage_helper(helper, environment) + writeHelperFile(t, helper+".so", "new sidecar") + updated, err := stageHelper(helper, environment) if err != nil || updated == original { t.Fatalf("updated set = %q, %v", updated, err) } @@ -69,17 +69,17 @@ func TestContainerHelperPublishesImmutableCompleteSets(t *testing.T) { if string(data) != "wine-access.exe.so" { t.Fatal("old sidecar overwritten") } - write_helper_file(t, updated+".so", "tampered") - if _, err := stage_helper(helper, environment); err == nil { + writeHelperFile(t, updated+".so", "tampered") + if _, err := stageHelper(helper, environment); err == nil { t.Fatal("accepted modified staging") } if err := os.Remove(helper + ".so"); err != nil { t.Fatal(err) } - if _, err := stage_helper(helper, environment); err == nil { + if _, err := stageHelper(helper, environment); err == nil { t.Fatal("accepted incomplete source set") } - if got, err := stage_helper(helper, nil); err != nil || got != helper { + if got, err := stageHelper(helper, nil); err != nil || got != helper { t.Fatalf("ordinary Wine = %q, %v", got, err) } } @@ -90,23 +90,23 @@ func TestListedProgramDoesNotForceWholesaleMode(t *testing.T) { // never add the prefix-wide --no-dialog-reader, or ordinary programs in // the same prefix lose dialog reading. listed := Settings{ExcludedPrograms: []string{"Game.EXE", "game.exe"}} - if wholesale_controller_only(listed) { + if wholesaleControllerOnly(listed) { t.Fatal("listed programs selected wholesale mode") } - arguments := helper_arguments(wholesale_controller_only(listed), listed) + arguments := helperArguments(wholesaleControllerOnly(listed), listed) if len(arguments) != 2 || arguments[0] != "--exclude-hook-program" || arguments[1] != "game.exe" { t.Fatalf("mixed-prefix arguments = %v", arguments) } global := Settings{ControllerOnly: true, ExcludedPrograms: []string{"Game.exe"}} - if !wholesale_controller_only(global) { + if !wholesaleControllerOnly(global) { t.Fatal("global controller-only switch ignored") } - arguments = helper_arguments(true, global) + arguments = helperArguments(true, global) if arguments[len(arguments)-1] != "--no-dialog-reader" { t.Fatalf("global arguments = %v", arguments) } t.Setenv("WINE_ACCESS_NO_DIALOG_READER", "1") - if !wholesale_controller_only(Settings{}) { + if !wholesaleControllerOnly(Settings{}) { t.Fatal("environment override ignored") } } @@ -122,7 +122,7 @@ func TestHelperArgumentsValidateProgramNames(t *testing.T) { "--exclude-hook-program", "café.exe", "--exclude-hook-program", "game.exe", } - if got := helper_arguments(false, settings); !reflect.DeepEqual(got, want) { + if got := helperArguments(false, settings); !reflect.DeepEqual(got, want) { t.Fatalf("validated helper arguments = %q, want %q", got, want) } } @@ -144,7 +144,7 @@ func TestLaunchForwardsProtonSyncAndKeepsReaderBus(t *testing.T) { root := t.TempDir() output := filepath.Join(root, "environment") helper := filepath.Join(root, "helper") - write_helper_file(t, helper, "#!/bin/sh\nenv > \"$TEST_WINE_ENV\"\n") + writeHelperFile(t, helper, "#!/bin/sh\nenv > \"$TEST_WINE_ENV\"\n") t.Setenv("TEST_WINE_ENV", output) t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/reader/bus") manager := New(nil) @@ -176,19 +176,19 @@ func TestDiscoverMixedPrefixKeepsOrdinaryProgramsReadable(t *testing.T) { root := t.TempDir() procRoot := filepath.Join(root, "proc") loader := filepath.Join(root, "wine") - write_helper_file(t, loader, "loader") + writeHelperFile(t, loader, "loader") makeProcess := func(pid, program string) { t.Helper() base := filepath.Join(procRoot, pid) - write_helper_file(t, filepath.Join(base, "cmdline"), program+"\x00") - write_helper_file(t, filepath.Join(base, "environ"), "WINEPREFIX="+root+"\x00") + writeHelperFile(t, filepath.Join(base, "cmdline"), program+"\x00") + writeHelperFile(t, filepath.Join(base, "environ"), "WINEPREFIX="+root+"\x00") if err := os.Symlink(loader, filepath.Join(base, "exe")); err != nil { t.Fatal(err) } } makeProcess("101", "launcher.exe") helper := filepath.Join(root, "helper") - write_helper_file(t, helper, "#!/bin/sh\nexec sleep 30\n") + writeHelperFile(t, helper, "#!/bin/sh\nexec sleep 30\n") current := Settings{ExcludedPrograms: []string{"GAME.exe"}} manager := New(nil) manager.helper, manager.procRoot = helper, procRoot @@ -279,10 +279,10 @@ func TestUnconfirmedHelperRestartsWholesaleOnceAndIsRemembered(t *testing.T) { root := t.TempDir() procRoot := filepath.Join(root, "proc") loader := filepath.Join(root, "wine") - write_helper_file(t, loader, "loader") + writeHelperFile(t, loader, "loader") base := filepath.Join(procRoot, "101") - write_helper_file(t, filepath.Join(base, "cmdline"), "launcher.exe\x00") - write_helper_file(t, filepath.Join(base, "environ"), "WINEPREFIX="+root+"\x00") + writeHelperFile(t, filepath.Join(base, "cmdline"), "launcher.exe\x00") + writeHelperFile(t, filepath.Join(base, "environ"), "WINEPREFIX="+root+"\x00") if err := os.Symlink(loader, filepath.Join(base, "exe")); err != nil { t.Fatal(err) } @@ -291,7 +291,7 @@ func TestUnconfirmedHelperRestartsWholesaleOnceAndIsRemembered(t *testing.T) { script := "#!/bin/sh\n" + "echo 'wine-access: ready {\"reader\":\"org.example.Reader\",\"controls_enabled\":true,\"hook_exclusions\":0}' >&2\n" + "exec sleep 30\n" - write_helper_file(t, helper, script) + writeHelperFile(t, helper, script) manager := New(nil) manager.helper, manager.procRoot = helper, procRoot manager.SettingsSource = func() Settings { diff --git a/sdk/go/tentacle/tentacle.go b/sdk/go/tentacle/tentacle.go index 5d8959b..243c935 100644 --- a/sdk/go/tentacle/tentacle.go +++ b/sdk/go/tentacle/tentacle.go @@ -16,7 +16,6 @@ import ( "strconv" "sync" - "git.stormux.org/storm/cthulhu/internal/interaction" "git.stormux.org/storm/cthulhu/internal/tentaclewire" ) @@ -47,19 +46,19 @@ type Presentation = tentaclewire.Presentation type Interaction = tentaclewire.Interaction type Submission = tentaclewire.Submission type Item = tentaclewire.Item -type Form = interaction.Form +type Form = tentaclewire.Form // Element.Secret masks transient Entry controls; it is not supported in // persistent PreferencePage controls. Submitted Value.Text remains sensitive. -type Element = interaction.Element -type ListItem = interaction.Item -type Value = interaction.Value +type Element = tentaclewire.Element +type ListItem = tentaclewire.FormItem +type Value = tentaclewire.Value const ( - List = interaction.List - Entry = interaction.Entry - CheckBox = interaction.CheckBox - Button = interaction.Button + List = tentaclewire.List + Entry = tentaclewire.Entry + CheckBox = tentaclewire.CheckBox + Button = tentaclewire.Button ) // Handlers may run concurrently. Cancellation applies to the entire session; @@ -284,7 +283,7 @@ func serve(input io.ReadCloser, output io.WriteCloser, commands []Command, exten Command string `json:"command"` Arguments json.RawMessage `json:"arguments"` } - if !active || message.ID == "" || tentaclewire.DecodeStrict(message.Params, ¶ms) != nil || len(params.Arguments) == 0 || len(params.Arguments) > command_argument_limit(readerCommands[params.Command]) || handlers[params.Command] == nil { + if !active || message.ID == "" || tentaclewire.DecodeStrict(message.Params, ¶ms) != nil || len(params.Arguments) == 0 || len(params.Arguments) > commandArgumentLimit(readerCommands[params.Command]) || handlers[params.Command] == nil { return ErrProtocol } select { @@ -303,7 +302,7 @@ func serve(input io.ReadCloser, output io.WriteCloser, commands []Command, exten } } defer release() - value, err := call_handler(ctx, handler, arguments) + value, err := callHandler(ctx, handler, arguments) if writeReply(id, value, err != nil, release) != nil { cancel() input.Close() @@ -320,7 +319,7 @@ func serve(input io.ReadCloser, output io.WriteCloser, commands []Command, exten } } -func call_handler(ctx context.Context, handler Handler, arguments json.RawMessage) (value any, err error) { +func callHandler(ctx context.Context, handler Handler, arguments json.RawMessage) (value any, err error) { defer func() { if recover() != nil { value = nil @@ -330,7 +329,7 @@ func call_handler(ctx context.Context, handler Handler, arguments json.RawMessag return handler(ctx, arguments) } -func command_argument_limit(reader bool) int { +func commandArgumentLimit(reader bool) int { if reader { return 48 * 1024 } diff --git a/tools/translations/main.go b/tools/translations/main.go new file mode 100644 index 0000000..3c5f635 --- /dev/null +++ b/tools/translations/main.go @@ -0,0 +1,46 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// 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 Fenrir through +// screenreader-common's catalogtool; this file holds Cthulhu's rules. +// See TRANSLATIONS.md in screenreader-common. +package main + +import ( + "fmt" + "os" + + "git.stormux.org/storm/screenreader-common/i18n/catalogtool" +) + +// Cthulhu wraps its messages explicitly with i18n.T and i18n.Format. Labels +// are not extracted by field name yet: many Cthulhu Label fields hold +// application or Tentacle text, which must not be translated. +var config = catalogtool.Config{ + Domain: "cthulhu", + Project: "Cthulhu", + Command: "go run ./tools/translations", + CatalogDir: "internal/i18n/locale", + SourceRoot: "internal", + Rules: catalogtool.Rules{ + Calls: []string{"i18n.T", "i18n.Format"}, + Plural: []string{"i18n.N"}, + }, + // Cthulhu shows quick settings and core internal UI forms through the + // translator. Its emoji picker uses literal labels and its profile editor + // is rendered by GTK, so those IDs are not included. + Shared: catalogtool.Shared{QuickSettings: true, InternalUI: true}, +} + +func main() { + 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) + } +}