Use shared quick settings and migrate speech values to the SSIP scale
This commit is contained in:
1 parent
679d81a804
commit
09e9570c66
46 files changed
+1053
-554
No files matched your search
@@ -124,16 +124,26 @@ Native X11 grab-window regression:
|
||||
|
||||
## Speech preferences
|
||||
|
||||
Use Cthulhu+Left/Right to select a quick speech setting and Cthulhu+Up/Down
|
||||
to adjust it. These changes follow you across windows, including application
|
||||
profiles, for the current session. Cthulhu+Control+Shift+S saves the choices to
|
||||
Quick settings work as in Fenrir and share their behavior through
|
||||
`screenreader-common/quicksettings`. Cthulhu+Left/Right selects a setting and
|
||||
Cthulhu+Up/Down changes it; Cthulhu+Control+Left/Right moves between the
|
||||
Speech, Reading, Keyboard and Tentacles categories. Settings and categories wrap
|
||||
at both ends; rate, pitch and volume move in steps of 10 and stop at -100 and
|
||||
100. Reading and Keyboard settings toggle between checked and unchecked, and
|
||||
Punctuation level and Indentation cycle through their choices. Object
|
||||
navigation between siblings is Cthulhu+Alt+Left/Right. These changes follow
|
||||
you across windows, including application profiles, for the current session. Cthulhu+Control+Shift+S saves the choices to
|
||||
the global profile. Switching windows does not save or discard them. Applying
|
||||
preferences replaces the temporary quick speech choices; restarting discards
|
||||
unsaved changes. Saved application overrides still apply on the next startup.
|
||||
|
||||
Speech preferences let you adjust rate, pitch and volume directly, without
|
||||
first disabling a default checkbox. Unconfigured values display Speech
|
||||
Dispatcher's defaults when available, or rate 50, pitch 5 and volume 5.
|
||||
first disabling a default checkbox. Rate, pitch and volume use Speech
|
||||
Dispatcher's own -100 through 100 scale, like Fenrir. Settings saved as schema
|
||||
2 or imported from Orca and Python Cthulhu are converted when loaded, keeping
|
||||
the same voice; the D-Bus remote API still reports and accepts Orca's 0-100
|
||||
rate and 0-10 pitch and volume. Unconfigured values display Speech
|
||||
Dispatcher's defaults when available, or rate 0, pitch 0 and volume 100.
|
||||
Adjusting a slider creates an explicit setting; untouched values retain their
|
||||
inheritance, including automatic Uppercase pitch. Apply saves the changes;
|
||||
Cancel restores the last applied voice. See
|
||||
|
||||
@@ -164,8 +164,9 @@ func TestCheckVersionedConfig(t *testing.T) {
|
||||
contents string
|
||||
wantError bool
|
||||
}{
|
||||
{"current", "schema-version = 2\nactive-profile = 'default'\n[profiles.default.speech]\nenabled = false\n", false},
|
||||
{"future", "schema-version = 3\nactive-profile = 'default'\n[profiles.default]\n", true},
|
||||
{"current", "schema-version = 3\nactive-profile = 'default'\n[profiles.default.speech]\nenabled = false\n", false},
|
||||
{"previous", "schema-version = 2\nactive-profile = 'default'\n[profiles.default.speech.default-voice]\nrate = 50.0\n", false},
|
||||
{"future", "schema-version = 4\nactive-profile = 'default'\n[profiles.default]\n", true},
|
||||
{"invalid", "schema-version = 2\nactive-profile = 'default'\n[profiles.default.sound]\nvolume = 2.0\n", true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
@@ -8,9 +8,10 @@ automatic pitch until its pitch slider is changed.
|
||||
|
||||
The preferences worker queries Speech Dispatcher over a separate connection,
|
||||
with a 500 ms overall deadline. Unsupported, invalid or unavailable values use
|
||||
display defaults of rate 50, pitch 5 and volume 5. Server values are converted
|
||||
to the reader's existing scales, rounded to one decimal place and constrained
|
||||
by the sliders' existing ranges. Hardware speech uses the display defaults.
|
||||
display defaults of rate 0, pitch 0 and volume 100. Sliders use Speech
|
||||
Dispatcher's own -100 through 100 scale, so server values are shown without
|
||||
conversion, as whole numbers. Left and Right change a slider by 1; Up and Down
|
||||
change it by 10. Hardware speech uses the display defaults.
|
||||
Merely opening preferences or applying unrelated changes does not save these
|
||||
display values as speech overrides.
|
||||
|
||||
|
||||
@@ -8,4 +8,4 @@ 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.4.0
|
||||
require git.stormux.org/storm/screenreader-common v0.5.0
|
||||
@@ -6,6 +6,8 @@ git.stormux.org/storm/screenreader-common v0.3.0 h1:eWuSMf3lM8fB5RyegnsyHmdz1uP0
|
||||
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=
|
||||
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=
|
||||
|
||||
@@ -45,7 +45,7 @@ func test_hardware_switch(t *testing.T, speaker *configuredSpeaker, software con
|
||||
hardware.SpeechOutputModule = "litetalk"
|
||||
hardware.HardwareSpeechDevice = fmt.Sprintf("/dev/pts/%d", number)
|
||||
hardware.HardwareSpeechBaudRate = 9600
|
||||
rate, pitch, volume := 99.0, 9.0, 9.0
|
||||
rate, pitch, volume := 100.0, 100.0, 100.0
|
||||
hardware.DefaultVoice = config.Voice{Rate: &rate, AveragePitch: &pitch, Gain: &volume}
|
||||
if err := speaker.UpdateConfiguration(ctx, hardware); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -67,7 +67,7 @@ func test_hardware_switch(t *testing.T, speaker *configuredSpeaker, software con
|
||||
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), hardware, speaker)
|
||||
values := preferences.FromSettings(hardware)
|
||||
rateLow := 0.0
|
||||
rateLow := -100.0
|
||||
values.Rate = &rateLow
|
||||
if response := worker.apply(ctx, preferences.Request{Values: values}); !response.Accepted {
|
||||
t.Fatal(response.Message)
|
||||
|
||||
@@ -142,7 +142,7 @@ func TestCustomEchoVoiceInheritanceAndRouting(t *testing.T) {
|
||||
settings.UseCustomEchoSpeechServer = true
|
||||
settings.EchoSpeechServer = "echo-module"
|
||||
got := echoSpeechSettings(settings)
|
||||
if *got.Rate != 32 || *got.Pitch != 90 || *got.Volume != 100 || got.OutputModule != "echo-module" || got.SynthesisVoice != "base" {
|
||||
if *got.Rate != 65 || *got.Pitch != 10 || *got.Volume != 10 || got.OutputModule != "echo-module" || got.SynthesisVoice != "base" {
|
||||
t.Fatalf("echo settings = %+v", got)
|
||||
}
|
||||
if !customEcho(settings, "key") || !customEcho(settings, "character") || customEcho(settings, "word") || customEcho(settings, "sentence") || customEcho(settings, "") {
|
||||
|
||||
@@ -215,16 +215,6 @@ func echoSpeechSettings(settings config.Settings) speech.Settings {
|
||||
if v := settings.EchoVoice.Family; v != nil {
|
||||
voice.Family = v
|
||||
}
|
||||
// Cthulhu accepts UI endpoints 100/10/10 and clamps for SSIP.
|
||||
for _, field := range []struct {
|
||||
value **float64
|
||||
max float64
|
||||
}{{&voice.Rate, 99}, {&voice.AveragePitch, 9}, {&voice.Gain, 9}} {
|
||||
if *field.value != nil {
|
||||
value := min(**field.value, field.max)
|
||||
*field.value = &value
|
||||
}
|
||||
}
|
||||
settings.DefaultVoice = voice
|
||||
result := speechSettingsFromConfig(settings)
|
||||
if settings.UseCustomEchoSpeechServer {
|
||||
|
||||
@@ -160,7 +160,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
}
|
||||
}
|
||||
check(false, "", "")
|
||||
check(true, "echo-module", "62")
|
||||
check(true, "echo-module", "80")
|
||||
if wrapped {
|
||||
// Exercise the new request path through the actual configured backend
|
||||
// and private SSIP connections, including a failure in the echo client
|
||||
@@ -178,19 +178,19 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
if _, err := readerWorker.apply_reader_request(ctx, session, tentaclewire.ReaderRequest{Speech: &configuration}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(false, "tentacle-module", "32")
|
||||
check(true, "echo-module", "62")
|
||||
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 {
|
||||
t.Fatal("failed echo client accepted through reader API")
|
||||
}
|
||||
check(false, "tentacle-module", "32")
|
||||
check(true, "echo-module", "62")
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(false, "", "")
|
||||
check(true, "echo-module", "62")
|
||||
check(true, "echo-module", "80")
|
||||
}
|
||||
// Key names use completion notifications on the selected voice's real
|
||||
// SSIP connection, so following navigation cannot cancel an active echo.
|
||||
@@ -202,7 +202,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
got := <-spoken
|
||||
wantModule, wantRate := "", ""
|
||||
if custom {
|
||||
wantModule, wantRate = "echo-module", "62"
|
||||
wantModule, wantRate = "echo-module", "80"
|
||||
}
|
||||
if got.text != "right" || got.module != wantModule || got.rate != wantRate {
|
||||
t.Fatalf("key echo custom=%v: %+v", custom, got)
|
||||
@@ -241,7 +241,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
got := <-spoken
|
||||
wantModule, wantRate := "", ""
|
||||
if selected {
|
||||
wantModule, wantRate = "echo-module", "62"
|
||||
wantModule, wantRate = "echo-module", "80"
|
||||
}
|
||||
if got.text != want || got.module != wantModule || got.rate != wantRate {
|
||||
t.Fatalf("%s custom=%v: %+v", kind, selected, got)
|
||||
@@ -262,7 +262,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, test := range []struct{ slider, text string }{{"rate", "70.0"}, {"pitch", "6.0"}, {"volume", "10.0"}, {"synthesizer", "preview-module"}, {"person", "Preview voice (en)"}} {
|
||||
for _, test := range []struct{ slider, text string }{{"rate", "70"}, {"pitch", "6"}, {"volume", "10"}, {"synthesizer", "preview-module"}, {"person", "Preview voice (en)"}} {
|
||||
if response := previewWorker.preview(ctx, preferences.Request{Values: previewValues, Preview: true, EchoPreview: test.slider, EchoPreviewFocus: true}); !response.Accepted {
|
||||
t.Fatalf("echo preview rejected: %+v", response)
|
||||
}
|
||||
@@ -277,7 +277,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
select {
|
||||
case got := <-spoken:
|
||||
if got.text != test.text || got.module != "preview-module" || got.voice != "Preview voice" ||
|
||||
got.rate != "42" || got.pitch != "30" || got.volume != "100" {
|
||||
got.rate != "70" || got.pitch != "6" || got.volume != "10" {
|
||||
t.Fatalf("echo slider SSIP request = %+v", got)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
@@ -288,7 +288,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
if response := previewWorker.restorePreview(ctx); !response.Accepted {
|
||||
t.Fatalf("restore echo preview: %+v", response)
|
||||
}
|
||||
check(true, "echo-module", "62")
|
||||
check(true, "echo-module", "80")
|
||||
checkCharacters := func(wantNormal string) {
|
||||
t.Helper()
|
||||
worker := newSpeechWorker(slog.New(slog.DiscardHandler), speaker)
|
||||
@@ -340,7 +340,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
wantPitch = "50"
|
||||
}
|
||||
if custom {
|
||||
wantModule, wantRate = "echo-module", "62"
|
||||
wantModule, wantRate = "echo-module", "80"
|
||||
}
|
||||
if got.text != text || got.pitch != wantPitch || got.module != wantModule || got.rate != wantRate {
|
||||
t.Fatalf("deleted %q, custom=%v: %+v", text, custom, got)
|
||||
@@ -379,7 +379,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
wantPitch = "50"
|
||||
}
|
||||
if custom {
|
||||
wantModule, wantRate = "echo-module", "62"
|
||||
wantModule, wantRate = "echo-module", "80"
|
||||
}
|
||||
if got.text != text || got.pitch != wantPitch || got.module != wantModule || got.rate != wantRate {
|
||||
t.Fatalf("Wine insertion %q, custom=%v: %+v; want pitch %q module %q rate %q", text, custom, got, wantPitch, wantModule, wantRate)
|
||||
@@ -399,7 +399,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
if text == "a" {
|
||||
wantPitch = ""
|
||||
}
|
||||
if got.module != "echo-module" || got.rate != "62" || got.pitch != wantPitch {
|
||||
if got.module != "echo-module" || got.rate != "80" || got.pitch != wantPitch {
|
||||
t.Fatalf("custom character echo = %+v; want pitch %s", got, wantPitch)
|
||||
}
|
||||
}
|
||||
@@ -410,7 +410,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
capitalPreferences.live = capitalLive
|
||||
for mask := 0; mask < 8; mask++ {
|
||||
choices := settings
|
||||
echoPitch := 6.0
|
||||
echoPitch := 30.0
|
||||
choices.EchoVoice.AveragePitch = &echoPitch
|
||||
choices.RaisePitchForCapitals = mask&1 != 0
|
||||
choices.BeepForCapitals = mask&2 != 0
|
||||
@@ -540,7 +540,7 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
if err := speaker.UpdateConfiguration(ctx, settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upperPitch, linkPitch, systemPitch := 8.0, 1.0, 2.0
|
||||
upperPitch, linkPitch, systemPitch := 70.0, -70.0, -50.0
|
||||
settings.UppercaseVoice.AveragePitch = &upperPitch
|
||||
settings.HyperlinkVoice.AveragePitch = &linkPitch
|
||||
settings.SystemVoice.AveragePitch = &systemPitch
|
||||
@@ -612,13 +612,13 @@ func test_echo_speaker(t *testing.T, wrapped bool) {
|
||||
t.Fatal("invalid module accepted")
|
||||
}
|
||||
check(false, "", "")
|
||||
check(true, "echo-module", "62")
|
||||
check(true, "echo-module", "80")
|
||||
settings.UseCustomEchoVoice = false
|
||||
if err := speaker.UpdateConfiguration(ctx, settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(true, "", "")
|
||||
pitch := 3.0
|
||||
pitch := -30.0
|
||||
settings.DefaultVoice.AveragePitch = &pitch
|
||||
if err := speaker.UpdateConfiguration(ctx, settings); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"git.stormux.org/storm/cthulhu/internal/speech"
|
||||
"git.stormux.org/storm/cthulhu/internal/tentacle"
|
||||
"git.stormux.org/storm/cthulhu/internal/tentaclewire"
|
||||
"git.stormux.org/storm/screenreader-common/quicksettings"
|
||||
)
|
||||
|
||||
type speechSettingsUpdater interface {
|
||||
@@ -42,7 +43,7 @@ type preferencesWorker struct {
|
||||
speechOverride *tentaclewire.SpeechConfiguration
|
||||
speechOverrideOwner string
|
||||
extensionRevision uint64
|
||||
quickSettingKey string
|
||||
quickMenu *quicksettings.Menu
|
||||
settings config.Settings
|
||||
globalSettings config.Settings
|
||||
appSettings map[string]config.Settings
|
||||
@@ -75,7 +76,6 @@ type preferencesWorker struct {
|
||||
socket string
|
||||
speechCommands chan input.Command
|
||||
remoteChanges chan remoteSettingsChange
|
||||
speechSetting int
|
||||
announce func(string)
|
||||
announceApply func(string)
|
||||
announceEchoPreview func(string, string)
|
||||
|
||||
@@ -70,7 +70,7 @@ func TestApplicationPreferencesSwitchAndPersistIndependently(t *testing.T) {
|
||||
if err != nil || !mapped || appLoaded.TimeFormat != "24-hour" || appLoaded.DateFormat != "numbers-mdy" || appLoaded.DefaultVoice.Rate == nil || !appLoaded.Reading.AutomaticallyReadClipboardChanges {
|
||||
t.Fatalf("application profile not saved: %+v, %t, %v", appLoaded, mapped, err)
|
||||
}
|
||||
if loaded.DefaultVoice.Rate == nil || *loaded.DefaultVoice.Rate != 51 || loaded.Reading.AutomaticallyReadClipboardChanges {
|
||||
if loaded.DefaultVoice.Rate == nil || *loaded.DefaultVoice.Rate != 10 || loaded.Reading.AutomaticallyReadClipboardChanges {
|
||||
t.Fatal("speech shortcut did not save globally or leaked unrelated application settings")
|
||||
}
|
||||
restarted := newPreferencesWorker(slog.New(slog.DiscardHandler), loaded,
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestPreferencesEchoSliderPreviewsDraftWithoutChangingMainVoice(t *testing.T
|
||||
values.SpeechOutputModule = "unapplied-module"
|
||||
values.VoiceType = "uppercase"
|
||||
values.Rate = &rate
|
||||
for _, test := range []struct{ slider, want string }{{"rate", "78.2"}, {"pitch", "6.3"}, {"volume", "10.0"}, {"synthesizer", "echo-module"}, {"person", "Echo voice (en)"}} {
|
||||
for _, test := range []struct{ slider, want string }{{"rate", "78"}, {"pitch", "6"}, {"volume", "10"}, {"synthesizer", "echo-module"}, {"person", "Echo voice (en)"}} {
|
||||
announced := ""
|
||||
worker.announceEchoPreview = func(_ string, value string) {
|
||||
if updater.calls == 0 || !reflect.DeepEqual(updater.settings.EchoVoice, values.EchoVoice) {
|
||||
@@ -95,7 +95,7 @@ func TestPreferencesEchoPreviewRejectsInvalidDraftAndBackendFailure(t *testing.T
|
||||
case "missing value":
|
||||
request.Values.EchoVoice.Gain = nil
|
||||
case "out of range":
|
||||
volume = 11
|
||||
volume = 101
|
||||
}
|
||||
if response := worker.preview(t.Context(), request); response.Accepted || !response.Preview {
|
||||
t.Fatalf("invalid preview response: %+v", response)
|
||||
|
||||
@@ -86,7 +86,7 @@ func (worker *preferencesWorker) preview_echo_voice(ctx context.Context, request
|
||||
}
|
||||
}
|
||||
if value != nil {
|
||||
text = fmt.Sprintf("%.1f", *value)
|
||||
text = fmt.Sprintf("%.0f", *value)
|
||||
}
|
||||
if !request.Values.UseCustomEchoVoice || text == "" {
|
||||
response.Message = "Choose a custom echo voice and a valid echo control value."
|
||||
|
||||
@@ -192,13 +192,13 @@ func TestPreferencesApplySaveAndRejectedDraft(t *testing.T) {
|
||||
rate := 75.0
|
||||
values.Rate = &rate
|
||||
response := worker.apply(context.Background(), preferences.Request{Values: values, Save: true})
|
||||
if !response.Accepted || len(updates) != 1 || *updates[0].Rate != 52 {
|
||||
if !response.Accepted || len(updates) != 1 || *updates[0].Rate != 75 {
|
||||
t.Fatalf("apply = %+v; updates = %+v", response, updates)
|
||||
}
|
||||
if _, err := os.Stat(settings.Path); err != nil || response.Close {
|
||||
t.Fatalf("Apply did not save and stay open: %v", err)
|
||||
}
|
||||
badRate := 100.0
|
||||
badRate := 101.0
|
||||
bad := values
|
||||
bad.Rate = &badRate
|
||||
response = worker.apply(context.Background(), preferences.Request{Values: bad, Save: true})
|
||||
@@ -305,9 +305,9 @@ func TestPreferencesVoicePreviewDoesNotCommitAndCancelRestores(t *testing.T) {
|
||||
values.Volume = &previewVolume
|
||||
response := worker.preview(context.Background(), preferences.Request{Values: values, Preview: true})
|
||||
if !response.Accepted || !response.Preview || len(updates) != 1 ||
|
||||
updates[0].Rate == nil || *updates[0].Rate != 52 ||
|
||||
updates[0].Pitch == nil || *updates[0].Pitch != 60 ||
|
||||
updates[0].Volume == nil || *updates[0].Volume != 85 {
|
||||
updates[0].Rate == nil || *updates[0].Rate != 75 ||
|
||||
updates[0].Pitch == nil || *updates[0].Pitch != 8 ||
|
||||
updates[0].Volume == nil || *updates[0].Volume != 8 {
|
||||
t.Fatalf("preview = %+v; updates = %+v", response, updates)
|
||||
}
|
||||
if worker.settings.DefaultVoice.Rate == nil || *worker.settings.DefaultVoice.Rate != originalRate ||
|
||||
@@ -317,9 +317,9 @@ func TestPreferencesVoicePreviewDoesNotCommitAndCancelRestores(t *testing.T) {
|
||||
}
|
||||
response = worker.restorePreview(context.Background())
|
||||
if !response.Accepted || !response.Close || len(updates) != 2 ||
|
||||
updates[1].Rate == nil || *updates[1].Rate != -18 ||
|
||||
updates[1].Pitch == nil || *updates[1].Pitch != -10 ||
|
||||
updates[1].Volume == nil || *updates[1].Volume != 55 {
|
||||
updates[1].Rate == nil || *updates[1].Rate != 40 ||
|
||||
updates[1].Pitch == nil || *updates[1].Pitch != 4 ||
|
||||
updates[1].Volume == nil || *updates[1].Volume != 6 {
|
||||
t.Fatalf("restore = %+v; updates = %+v", response, updates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,19 +68,20 @@ func remoteValue(settings config.Settings, module, property string) (dbus.Varian
|
||||
return dbus.MakeVariant(settings.DefaultVoice.Family.Name), true
|
||||
}
|
||||
return dbus.MakeVariant(""), true
|
||||
// The Orca-compatible API keeps its 0..100 rate and 0..10 pitch/volume.
|
||||
case "Rate":
|
||||
if settings.DefaultVoice.Rate != nil {
|
||||
return dbus.MakeVariant(int32(*settings.DefaultVoice.Rate)), true
|
||||
return dbus.MakeVariant(int32(math.Round(config.LegacyFromSpeech(config.VoiceRate, *settings.DefaultVoice.Rate)))), true
|
||||
}
|
||||
return dbus.MakeVariant(int32(50)), true
|
||||
case "Pitch":
|
||||
if settings.DefaultVoice.AveragePitch != nil {
|
||||
return dbus.MakeVariant(*settings.DefaultVoice.AveragePitch), true
|
||||
return dbus.MakeVariant(config.LegacyFromSpeech(config.VoicePitch, *settings.DefaultVoice.AveragePitch)), true
|
||||
}
|
||||
return dbus.MakeVariant(float64(5)), true
|
||||
case "Volume":
|
||||
if settings.DefaultVoice.Gain != nil {
|
||||
return dbus.MakeVariant(*settings.DefaultVoice.Gain), true
|
||||
return dbus.MakeVariant(config.LegacyFromSpeech(config.VoiceGain, *settings.DefaultVoice.Gain)), true
|
||||
}
|
||||
return dbus.MakeVariant(float64(10)), true
|
||||
case "SpeechIsEnabled":
|
||||
@@ -171,32 +172,29 @@ func (worker *preferencesWorker) applyRemoteChange(ctx context.Context, change r
|
||||
return worker.applyNext(applyCtx, next, false, false).Accepted
|
||||
}
|
||||
|
||||
// Remote steps match the quick settings menu on the stored -100..100 scale.
|
||||
func adjustRemoteSpeech(settings *config.Settings, command string) bool {
|
||||
var field **float64
|
||||
var defaultValue, step, upper float64
|
||||
delta := float64(1)
|
||||
defaultValue := 0.0
|
||||
switch command {
|
||||
case "DecreaseRate", "IncreaseRate":
|
||||
field = &settings.DefaultVoice.Rate
|
||||
defaultValue, step, upper = 50, 1, 99
|
||||
case "DecreasePitch", "IncreasePitch":
|
||||
field = &settings.DefaultVoice.AveragePitch
|
||||
defaultValue, step, upper = 5, 0.1, 9
|
||||
case "DecreaseVolume", "IncreaseVolume":
|
||||
field = &settings.DefaultVoice.Gain
|
||||
defaultValue, step, upper = 9, 0.1, 9
|
||||
field, defaultValue = &settings.DefaultVoice.Gain, 100
|
||||
default:
|
||||
return false
|
||||
}
|
||||
delta := float64(quickVoiceStep)
|
||||
if strings.HasPrefix(command, "Decrease") {
|
||||
delta = -1
|
||||
delta = -delta
|
||||
}
|
||||
value := defaultValue
|
||||
if *field != nil {
|
||||
value = **field
|
||||
}
|
||||
value = math.Round((value+delta*step)*10) / 10
|
||||
value = math.Max(0, math.Min(upper, value))
|
||||
value = math.Max(-100, math.Min(100, math.Round(value+delta)))
|
||||
*field = &value
|
||||
return true
|
||||
}
|
||||
@@ -209,16 +207,20 @@ func setRemoteValue(settings *config.Settings, module, property string, value db
|
||||
var number float64
|
||||
if property == "Rate" {
|
||||
v, ok := value.Value().(int32)
|
||||
if !ok || v < 0 || v > 99 {
|
||||
if !ok || v < 0 || v > 100 {
|
||||
return false
|
||||
}
|
||||
number = float64(v)
|
||||
number = config.SpeechFromLegacy(config.VoiceRate, float64(v))
|
||||
} else {
|
||||
v, ok := value.Value().(float64)
|
||||
if !ok {
|
||||
if !ok || !(v >= 0 && v <= 10) {
|
||||
return false
|
||||
}
|
||||
number = v
|
||||
field := config.VoicePitch
|
||||
if property == "Volume" {
|
||||
field = config.VoiceGain
|
||||
}
|
||||
number = config.SpeechFromLegacy(field, v)
|
||||
}
|
||||
switch property {
|
||||
case "Rate":
|
||||
|
||||
@@ -58,7 +58,8 @@ func TestRemoteSettingsUseWorkerWithoutSaving(t *testing.T) {
|
||||
t.Fatal("rate command rejected")
|
||||
}
|
||||
value, ok = presenter.RemoteGet("SpeechManager", "Rate")
|
||||
if !ok || value.Value() != int32(51) {
|
||||
// Unset rate 0 steps to 10, which the Orca-compatible API reports as 54.
|
||||
if !ok || value.Value() != int32(54) {
|
||||
t.Fatalf("rate after command = %v, %v", value, ok)
|
||||
}
|
||||
if presenter.RemoteCommand("SpeechManager", "Unknown", false) {
|
||||
@@ -92,3 +93,16 @@ func TestLegacyRemoteCapitalStyleControlsIndependentCues(t *testing.T) {
|
||||
t.Fatal("invalid style accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteRateMaximumRoundTrip(t *testing.T) {
|
||||
settings := config.DefaultSettings()
|
||||
maximum := 100.0
|
||||
settings.DefaultVoice.Rate = &maximum
|
||||
value, ok := remoteValue(settings, "SpeechManager", "Rate")
|
||||
if !ok || !setRemoteValue(&settings, "SpeechManager", "Rate", value) || *settings.DefaultVoice.Rate != 100 {
|
||||
t.Fatal("remote maximum cannot be written back", value)
|
||||
}
|
||||
if setRemoteValue(&settings, "SpeechManager", "Rate", dbus.MakeVariant(int32(101))) {
|
||||
t.Fatal("accepted out of range rate")
|
||||
}
|
||||
}
|
||||
@@ -205,7 +205,7 @@ func (worker commandRuntime) run(ctx context.Context) error {
|
||||
default:
|
||||
}
|
||||
}
|
||||
case input.SelectPreviousSpeechSetting, input.SelectNextSpeechSetting, input.DecreaseSpeechSetting, input.IncreaseSpeechSetting, input.SaveSpeechSettings, input.CycleProgressBarOutput:
|
||||
case input.SelectPreviousSpeechSetting, input.SelectNextSpeechSetting, input.DecreaseSpeechSetting, input.IncreaseSpeechSetting, input.SelectPreviousSpeechCategory, input.SelectNextSpeechCategory, input.SaveSpeechSettings, input.CycleProgressBarOutput:
|
||||
logger.Debug("speech setting command received", "command", command)
|
||||
preferences.SpeechCommand(command)
|
||||
case input.Preferences:
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/config"
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
"git.stormux.org/storm/cthulhu/internal/presentation"
|
||||
@@ -31,17 +33,15 @@ func speechSettingsFromConfig(settings config.Settings) speech.Settings {
|
||||
Punctuation: map[int]string{0: "all", 1: "most", 2: "some", 3: "none"}[settings.VerbalizePunctuationStyle],
|
||||
Capitalization: "none",
|
||||
}
|
||||
if settings.DefaultVoice.Rate != nil {
|
||||
value := int(2*(*settings.DefaultVoice.Rate) - 98)
|
||||
speechSettings.Rate = &value
|
||||
}
|
||||
if settings.DefaultVoice.AveragePitch != nil {
|
||||
value := int(20*(*settings.DefaultVoice.AveragePitch) - 90)
|
||||
speechSettings.Pitch = &value
|
||||
}
|
||||
if settings.DefaultVoice.Gain != nil {
|
||||
value := int(15*(*settings.DefaultVoice.Gain) - 35)
|
||||
speechSettings.Volume = &value
|
||||
// Voices are stored on Speech Dispatcher's own -100..100 scale.
|
||||
for _, field := range []struct {
|
||||
value *float64
|
||||
target **int
|
||||
}{{settings.DefaultVoice.Rate, &speechSettings.Rate}, {settings.DefaultVoice.AveragePitch, &speechSettings.Pitch}, {settings.DefaultVoice.Gain, &speechSettings.Volume}} {
|
||||
if field.value != nil {
|
||||
value := int(math.Round(*field.value))
|
||||
*field.target = &value
|
||||
}
|
||||
}
|
||||
if family := settings.DefaultVoice.Family; family != nil {
|
||||
speechSettings.Language = family.Lang
|
||||
|
||||
@@ -36,8 +36,9 @@ func TestSpeechSettingsFromConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
got := speechSettingsFromConfig(settings)
|
||||
if got.Rate == nil || *got.Rate != 52 || got.Pitch == nil || *got.Pitch != 0 ||
|
||||
got.Volume == nil || *got.Volume != 40 {
|
||||
// Stored voices already use Speech Dispatcher's scale; 4.5 rounds to 5.
|
||||
if got.Rate == nil || *got.Rate != 75 || got.Pitch == nil || *got.Pitch != 5 ||
|
||||
got.Volume == nil || *got.Volume != 5 {
|
||||
t.Fatalf("converted voice values = rate %v pitch %v volume %v", got.Rate, got.Pitch, got.Volume)
|
||||
}
|
||||
if got.Punctuation != "some" || got.Capitalization != "none" ||
|
||||
|
||||
+340
-186
@@ -6,9 +6,9 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
"git.stormux.org/storm/cthulhu/internal/speech"
|
||||
"git.stormux.org/storm/cthulhu/internal/tentaclewire"
|
||||
"git.stormux.org/storm/screenreader-common/quicksettings"
|
||||
)
|
||||
|
||||
// Use the settings worker's bounded mailbox, keeping discovery, disk writes,
|
||||
@@ -60,183 +61,333 @@ func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, comman
|
||||
return
|
||||
}
|
||||
worker.sync_extensions(ctx)
|
||||
quickSettings := worker.quick_settings()
|
||||
settingIndex := worker.speechSetting
|
||||
if worker.quickSettingKey != "" {
|
||||
settingIndex = 4
|
||||
found := false
|
||||
for index, setting := range quickSettings {
|
||||
if setting.key == worker.quickSettingKey {
|
||||
settingIndex = 5 + index
|
||||
found = true
|
||||
quickCommand, ok := quickSettingCommands[command]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
host := &quickSettingsHost{worker: worker, ctx: ctx, settings: worker.effective_settings(worker.settings)}
|
||||
if worker.quickMenu == nil {
|
||||
worker.quickMenu = quicksettings.New(nil, quicksettings.Messages{})
|
||||
}
|
||||
if !worker.quickMenu.Replace(host.categories()) && quicksettings.IsValueChange(quickCommand) {
|
||||
worker.announceSpeechSetting("The selected setting is no longer available")
|
||||
return
|
||||
}
|
||||
result := worker.quickMenu.Handle(quickCommand, host)
|
||||
if host.unavailable != "" {
|
||||
worker.announceSpeechSetting(host.unavailable)
|
||||
return
|
||||
}
|
||||
if result.Changed {
|
||||
if !worker.apply_quick_setting(ctx, host, result) {
|
||||
return
|
||||
}
|
||||
}
|
||||
worker.announceSpeechSetting(result.Text)
|
||||
}
|
||||
|
||||
// quickVoiceStep matches Fenrir: 5% of Speech Dispatcher's -100..100 scale.
|
||||
const quickVoiceStep = 10
|
||||
|
||||
var quickSettingCommands = map[input.Command]quicksettings.Command{
|
||||
input.SelectPreviousSpeechSetting: quicksettings.PreviousEntry,
|
||||
input.SelectNextSpeechSetting: quicksettings.NextEntry,
|
||||
input.DecreaseSpeechSetting: quicksettings.PreviousValue,
|
||||
input.IncreaseSpeechSetting: quicksettings.NextValue,
|
||||
input.SelectPreviousSpeechCategory: quicksettings.PreviousCategory,
|
||||
input.SelectNextSpeechCategory: quicksettings.NextCategory,
|
||||
}
|
||||
|
||||
var hardwareSynthesizers = []string{"litetalk", "doubletalk", "tripletalk", "dectalk"}
|
||||
|
||||
// quickToggle is one boolean setting in the Reading or Keyboard category.
|
||||
type quickToggle struct {
|
||||
id, label string
|
||||
field func(*config.Settings) *bool
|
||||
}
|
||||
|
||||
var quickReadingToggles = []quickToggle{
|
||||
{"reading.raise-pitch-for-capitals", "Raise pitch for capital letters", func(s *config.Settings) *bool { return &s.RaisePitchForCapitals }},
|
||||
{"reading.numbers-as-digits", "Speak numbers as digits", func(s *config.Settings) *bool { return &s.Reading.SpeakNumbersAsDigits }},
|
||||
{"reading.blank-lines", "Speak blank lines", func(s *config.Settings) *bool { return &s.Reading.SpeakBlankLines }},
|
||||
{"reading.only-displayed-text", "Only speak displayed text", func(s *config.Settings) *bool { return &s.Reading.OnlySpeakDisplayedText }},
|
||||
{"reading.misspelled-indicator", "Speak misspelled indicator", func(s *config.Settings) *bool { return &s.Reading.SpeakMisspelledIndicator }},
|
||||
{"reading.color-names", "Use color names", func(s *config.Settings) *bool { return &s.Reading.UseColorNames }},
|
||||
{"reading.tooltips", "Present tooltips", func(s *config.Settings) *bool { return &s.Reading.PresentTooltips }},
|
||||
{"reading.mouse-review", "Mouse review", func(s *config.Settings) *bool { return &s.Reading.EnableMouseReview }},
|
||||
{"reading.clipboard-changes", "Automatically read clipboard changes", func(s *config.Settings) *bool { return &s.Reading.AutomaticallyReadClipboardChanges }},
|
||||
{"reading.title-changes", "Automatically read title changes", func(s *config.Settings) *bool { return &s.Reading.AutomaticallyReadTitleChanges }},
|
||||
{"reading.tutorial-messages", "Tutorial messages", func(s *config.Settings) *bool { return &s.Reading.EnableTutorialMessages }},
|
||||
{"reading.full-row-document-table", "Read full row in document tables", func(s *config.Settings) *bool { return &s.Reading.ReadFullRowInDocumentTable }},
|
||||
}
|
||||
|
||||
var quickKeyboardToggles = []quickToggle{
|
||||
{"keyboard.key-echo", "Key echo", func(s *config.Settings) *bool { return &s.EnableKeyEcho }},
|
||||
{"keyboard.character-echo", "Character echo", func(s *config.Settings) *bool { return &s.EnableEchoByCharacter }},
|
||||
{"keyboard.word-echo", "Word echo", func(s *config.Settings) *bool { return &s.EnableEchoByWord }},
|
||||
{"keyboard.sentence-echo", "Sentence echo", func(s *config.Settings) *bool { return &s.EnableEchoBySentence }},
|
||||
}
|
||||
|
||||
var quickPunctuation = []quicksettings.Option{{ID: "0", Label: "all"}, {ID: "1", Label: "most"}, {ID: "2", Label: "some"}, {ID: "3", Label: "none"}}
|
||||
var quickIndentation = []quicksettings.Option{{ID: "none", Label: "none"}, {ID: "speech", Label: "speech"}, {ID: "beeps", Label: "beeps"}, {ID: "both", Label: "speech and beeps"}}
|
||||
|
||||
func quickToggleByID(id string) (quickToggle, bool) {
|
||||
for _, toggle := range append(append([]quickToggle(nil), quickReadingToggles...), quickKeyboardToggles...) {
|
||||
if toggle.id == id {
|
||||
return toggle, true
|
||||
}
|
||||
}
|
||||
return quickToggle{}, false
|
||||
}
|
||||
|
||||
// quickSettingsHost describes Cthulhu's settings to the shared menu for one
|
||||
// command. Discovery failures are reported once instead of an option list.
|
||||
type quickSettingsHost struct {
|
||||
worker *preferencesWorker
|
||||
ctx context.Context
|
||||
settings config.Settings
|
||||
extensions map[string]readerQuickSetting
|
||||
unavailable string
|
||||
}
|
||||
|
||||
func (host *quickSettingsHost) hardware() bool {
|
||||
return host.settings.SpeechServerFactory == "hardwarefactory"
|
||||
}
|
||||
|
||||
func (host *quickSettingsHost) categories() []quicksettings.Category {
|
||||
voice := []quicksettings.Entry{
|
||||
{ID: "speech.rate", Label: "Rate", Kind: quicksettings.Range, Min: -100, Max: 100, Step: quickVoiceStep},
|
||||
{ID: "speech.pitch", Label: "Pitch", Kind: quicksettings.Range, Min: -100, Max: 100, Step: quickVoiceStep},
|
||||
{ID: "speech.volume", Label: "Volume", Kind: quicksettings.Range, Min: -100, Max: 100, Step: quickVoiceStep},
|
||||
}
|
||||
if host.hardware() {
|
||||
voice = append(voice, quicksettings.Entry{ID: "speech.module", Label: "Hardware synthesizer", Kind: quicksettings.Choice})
|
||||
} else {
|
||||
voice = append(voice,
|
||||
quicksettings.Entry{ID: "speech.module", Label: "Speech-dispatcher module", Kind: quicksettings.Choice, EmptyIsDefault: true},
|
||||
quicksettings.Entry{ID: "speech.voice", Label: "Speech-dispatcher voice", Kind: quicksettings.Choice, EmptyIsDefault: true})
|
||||
}
|
||||
reading := []quicksettings.Entry{
|
||||
{ID: "reading.punctuation", Label: "Punctuation level", Kind: quicksettings.Choice},
|
||||
{ID: "reading.indentation", Label: "Indentation", Kind: quicksettings.Choice},
|
||||
}
|
||||
for _, toggle := range quickReadingToggles {
|
||||
reading = append(reading, quicksettings.Entry{ID: toggle.id, Label: toggle.label, Kind: quicksettings.Toggle})
|
||||
}
|
||||
var keyboard []quicksettings.Entry
|
||||
for _, toggle := range quickKeyboardToggles {
|
||||
keyboard = append(keyboard, quicksettings.Entry{ID: toggle.id, Label: toggle.label, Kind: quicksettings.Toggle})
|
||||
}
|
||||
var tentacles []quicksettings.Entry
|
||||
host.extensions = make(map[string]readerQuickSetting)
|
||||
for _, setting := range host.worker.quick_settings() {
|
||||
id := "tentacle." + setting.key
|
||||
host.extensions[id] = setting
|
||||
tentacles = append(tentacles, quicksettings.Entry{ID: id, Label: setting.setting.Label, Kind: quicksettings.Choice})
|
||||
}
|
||||
return []quicksettings.Category{
|
||||
{ID: "speech", Label: "Speech", Entries: voice},
|
||||
{ID: "reading", Label: "Reading", Entries: reading},
|
||||
{ID: "keyboard", Label: "Keyboard", Entries: keyboard},
|
||||
{ID: "tentacles", Label: "Tentacles", Entries: tentacles},
|
||||
}
|
||||
}
|
||||
|
||||
func voiceOptionID(family *config.VoiceFamily) string {
|
||||
if family == nil || family.Name == "" {
|
||||
return ""
|
||||
}
|
||||
return family.Name + "\x00" + family.Lang + "\x00" + family.Variant
|
||||
}
|
||||
|
||||
func (host *quickSettingsHost) Value(entry quicksettings.Entry) quicksettings.Value {
|
||||
settings := host.settings
|
||||
number := func(value *float64, fallback int) quicksettings.Value {
|
||||
if value == nil {
|
||||
return quicksettings.Value{Number: fallback}
|
||||
}
|
||||
return quicksettings.Value{Number: int(math.Round(*value))}
|
||||
}
|
||||
switch entry.ID {
|
||||
case "speech.rate":
|
||||
return number(settings.DefaultVoice.Rate, 0)
|
||||
case "speech.pitch":
|
||||
return number(settings.DefaultVoice.AveragePitch, 0)
|
||||
case "speech.volume":
|
||||
return number(settings.DefaultVoice.Gain, 100)
|
||||
case "speech.module":
|
||||
return quicksettings.Value{Choice: settings.SpeechOutputModule}
|
||||
case "speech.voice":
|
||||
return quicksettings.Value{Choice: voiceOptionID(settings.DefaultVoice.Family)}
|
||||
case "reading.punctuation":
|
||||
return quicksettings.Value{Choice: strconv.Itoa(settings.VerbalizePunctuationStyle)}
|
||||
case "reading.indentation":
|
||||
mode := settings.Reading.IndentationPresentationMode
|
||||
if mode == "" {
|
||||
mode = "speech"
|
||||
}
|
||||
if !settings.Reading.EnableIndentation {
|
||||
mode = "none"
|
||||
}
|
||||
return quicksettings.Value{Choice: mode}
|
||||
}
|
||||
if toggle, ok := quickToggleByID(entry.ID); ok {
|
||||
return quicksettings.Value{Checked: *toggle.field(&settings)}
|
||||
}
|
||||
if setting, ok := host.extensions[entry.ID]; ok {
|
||||
return quicksettings.Value{Choice: setting.setting.Selected}
|
||||
}
|
||||
return quicksettings.Value{}
|
||||
}
|
||||
|
||||
func (host *quickSettingsHost) catalog() bool {
|
||||
if host.worker.catalog != nil {
|
||||
return true
|
||||
}
|
||||
catalog, err := host.worker.discover(host.ctx, host.worker.socket)
|
||||
if err != nil && len(catalog) == 0 {
|
||||
host.unavailable = "Speech settings unavailable"
|
||||
return false
|
||||
}
|
||||
host.worker.catalog = catalog
|
||||
return true
|
||||
}
|
||||
|
||||
func (host *quickSettingsHost) Options(entry quicksettings.Entry) []quicksettings.Option {
|
||||
switch entry.ID {
|
||||
case "speech.module":
|
||||
var options []quicksettings.Option
|
||||
if host.hardware() {
|
||||
for _, module := range hardwareSynthesizers {
|
||||
options = append(options, quicksettings.Option{ID: module, Label: module})
|
||||
}
|
||||
return options
|
||||
}
|
||||
if !host.catalog() {
|
||||
return nil
|
||||
}
|
||||
options = []quicksettings.Option{{ID: "", Label: "default"}}
|
||||
for module := range host.worker.catalog {
|
||||
if module != "" {
|
||||
options = append(options, quicksettings.Option{ID: module, Label: module})
|
||||
}
|
||||
}
|
||||
sort.Slice(options[1:], func(i, j int) bool { return options[1+i].ID < options[1+j].ID })
|
||||
return options
|
||||
case "speech.voice":
|
||||
if !host.catalog() {
|
||||
return nil
|
||||
}
|
||||
options := []quicksettings.Option{{ID: "", Label: "default"}}
|
||||
for _, voice := range quickSpeechVoices(host.settings.SpeechOutputModule, host.worker.catalog[host.settings.SpeechOutputModule]) {
|
||||
options = append(options, quicksettings.Option{ID: voiceOptionID(&config.VoiceFamily{Name: voice.Name, Lang: voice.Language, Variant: voice.Variant}), Label: voice.Name})
|
||||
}
|
||||
return options
|
||||
case "reading.punctuation":
|
||||
return quickPunctuation
|
||||
case "reading.indentation":
|
||||
return quickIndentation
|
||||
}
|
||||
if setting, ok := host.extensions[entry.ID]; ok {
|
||||
var options []quicksettings.Option
|
||||
for _, option := range setting.setting.Options {
|
||||
if !option.Disabled {
|
||||
options = append(options, quicksettings.Option{ID: option.ID, Label: option.Label})
|
||||
}
|
||||
}
|
||||
return options
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// set writes one quick value into settings and reports whether speech must be
|
||||
// reconfigured for it.
|
||||
func (host *quickSettingsHost) set(settings *config.Settings, entry quicksettings.Entry, value quicksettings.Value) bool {
|
||||
number := float64(value.Number)
|
||||
switch entry.ID {
|
||||
case "speech.rate":
|
||||
settings.DefaultVoice.Rate = &number
|
||||
case "speech.pitch":
|
||||
settings.DefaultVoice.AveragePitch = &number
|
||||
case "speech.volume":
|
||||
settings.DefaultVoice.Gain = &number
|
||||
case "speech.module":
|
||||
// A voice belongs to its module. Start with the first voice for the
|
||||
// user's locale so eSpeak NG keeps the expected dialect.
|
||||
settings.SpeechOutputModule = value.Choice
|
||||
if !host.hardware() {
|
||||
settings.DefaultVoice.Family = nil
|
||||
if voices := quickSpeechVoices(value.Choice, host.worker.catalog[value.Choice]); len(voices) > 0 {
|
||||
settings.DefaultVoice.Family = &config.VoiceFamily{Name: voices[0].Name, Lang: voices[0].Language, Variant: voices[0].Variant}
|
||||
}
|
||||
}
|
||||
case "speech.voice":
|
||||
settings.DefaultVoice.Family = nil
|
||||
for _, voice := range host.worker.catalog[settings.SpeechOutputModule] {
|
||||
family := &config.VoiceFamily{Name: voice.Name, Lang: voice.Language, Variant: voice.Variant}
|
||||
if voiceOptionID(family) == value.Choice {
|
||||
settings.DefaultVoice.Family = family
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found && (command == input.IncreaseSpeechSetting || command == input.DecreaseSpeechSetting) {
|
||||
worker.quickSettingKey, worker.speechSetting = "", 4
|
||||
worker.announceSpeechSetting("The selected speech setting is no longer available")
|
||||
return
|
||||
case "reading.punctuation":
|
||||
settings.VerbalizePunctuationStyle, _ = strconv.Atoi(value.Choice)
|
||||
case "reading.indentation":
|
||||
settings.Reading.EnableIndentation = value.Choice != "none"
|
||||
if value.Choice != "none" {
|
||||
settings.Reading.IndentationPresentationMode = value.Choice
|
||||
}
|
||||
return false
|
||||
default:
|
||||
if toggle, ok := quickToggleByID(entry.ID); ok {
|
||||
*toggle.field(settings) = value.Checked
|
||||
return entry.ID == "reading.raise-pitch-for-capitals"
|
||||
}
|
||||
return false
|
||||
}
|
||||
switch command {
|
||||
case input.SelectPreviousSpeechSetting:
|
||||
settingIndex = max(0, settingIndex-1)
|
||||
case input.SelectNextSpeechSetting:
|
||||
settingIndex = min(4+len(quickSettings), settingIndex+1)
|
||||
return true
|
||||
}
|
||||
|
||||
// apply_quick_setting 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 {
|
||||
if setting, ok := host.extensions[result.Entry.ID]; ok {
|
||||
return worker.handle_extension_quick(ctx, setting, result.Value.Choice)
|
||||
}
|
||||
worker.quickSettingKey = ""
|
||||
if settingIndex >= 5 {
|
||||
worker.quickSettingKey = quickSettings[settingIndex-5].key
|
||||
} else {
|
||||
worker.speechSetting = settingIndex
|
||||
next := host.settings
|
||||
speechChanged := host.set(&next, result.Entry, result.Value)
|
||||
err := config.Validate(next)
|
||||
if err == nil && speechChanged {
|
||||
err = worker.updateSpeech(ctx, next)
|
||||
}
|
||||
next := worker.effective_settings(worker.settings)
|
||||
adjust := command == input.IncreaseSpeechSetting || command == input.DecreaseSpeechSetting
|
||||
delta := 1
|
||||
if command == input.DecreaseSpeechSetting {
|
||||
delta = -1
|
||||
if err != nil {
|
||||
worker.logger.Warn("adjust quick setting", "setting", result.Entry.ID, "error", err)
|
||||
worker.catalog = nil
|
||||
worker.announceSpeechSetting(result.Entry.Label + " was not changed")
|
||||
return false
|
||||
}
|
||||
if settingIndex >= 5 {
|
||||
worker.handle_extension_quick(ctx, quickSettings[settingIndex-5], adjust, delta)
|
||||
return
|
||||
if worker.speechOverride != nil && speechChanged {
|
||||
value := tentaclewire.SpeechFromSettings(next)
|
||||
worker.speechOverride = &value
|
||||
}
|
||||
message := ""
|
||||
switch worker.speechSetting {
|
||||
case 0, 1, 2:
|
||||
names := []string{"Rate", "Pitch", "Volume"}
|
||||
fields := []**float64{&next.DefaultVoice.Rate, &next.DefaultVoice.AveragePitch, &next.DefaultVoice.Gain}
|
||||
defaults := []float64{50, 5, 9}
|
||||
limits := []float64{99, 9, 9}
|
||||
steps := []float64{1, 0.1, 0.1}
|
||||
field := fields[worker.speechSetting]
|
||||
value := defaults[worker.speechSetting]
|
||||
if *field != nil {
|
||||
value = math.Round(**field*10) / 10
|
||||
if worker.speechOverride == nil || !speechChanged {
|
||||
if worker.quickSpeech.adjusted == nil {
|
||||
worker.quickSpeech.adjusted = make(map[string]bool)
|
||||
}
|
||||
if adjust {
|
||||
value = math.Round((value+float64(delta)*steps[worker.speechSetting])*10) / 10
|
||||
value = math.Max(0, math.Min(limits[worker.speechSetting], value))
|
||||
*field = &value
|
||||
}
|
||||
message = fmt.Sprintf("%s %g", names[worker.speechSetting], value)
|
||||
if *field == nil {
|
||||
message = names[worker.speechSetting] + " server default"
|
||||
}
|
||||
case 3, 4:
|
||||
if next.SpeechServerFactory == "hardwarefactory" {
|
||||
if worker.speechSetting == 4 {
|
||||
worker.announceSpeechSetting("Hardware speech has no selectable voices")
|
||||
return
|
||||
}
|
||||
modules := []string{"litetalk", "doubletalk", "tripletalk", "dectalk"}
|
||||
if adjust {
|
||||
for index, module := range modules {
|
||||
if module == next.SpeechOutputModule {
|
||||
next.SpeechOutputModule = modules[max(0, min(len(modules)-1, index+delta))]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
message = "Hardware synthesizer " + next.SpeechOutputModule
|
||||
break
|
||||
}
|
||||
if worker.catalog == nil {
|
||||
catalog, err := worker.discover(ctx, worker.socket)
|
||||
if err != nil {
|
||||
worker.announceSpeechSetting("Speech settings unavailable")
|
||||
return
|
||||
}
|
||||
worker.catalog = catalog
|
||||
}
|
||||
if worker.speechSetting == 3 {
|
||||
modules := []string{}
|
||||
for module := range worker.catalog {
|
||||
if module != "" {
|
||||
modules = append(modules, module)
|
||||
}
|
||||
}
|
||||
sort.Strings(modules)
|
||||
if len(modules) == 0 {
|
||||
worker.announceSpeechSetting("No speech-dispatcher modules available")
|
||||
return
|
||||
}
|
||||
if adjust {
|
||||
index := 0
|
||||
for i, module := range modules {
|
||||
if module == next.SpeechOutputModule {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
// An unspecified module is a server default, not a known list position.
|
||||
if next.SpeechOutputModule != "" {
|
||||
index = max(0, min(len(modules)-1, index+delta))
|
||||
}
|
||||
next.SpeechOutputModule = modules[index]
|
||||
next.DefaultVoice.Family = nil
|
||||
if voices := quickSpeechVoices(next.SpeechOutputModule, worker.catalog[next.SpeechOutputModule]); len(voices) > 0 {
|
||||
next.DefaultVoice.Family = &config.VoiceFamily{Name: voices[0].Name, Lang: voices[0].Language, Variant: voices[0].Variant}
|
||||
}
|
||||
}
|
||||
name := next.SpeechOutputModule
|
||||
if name == "" {
|
||||
name = "server default"
|
||||
}
|
||||
message = "Speech-dispatcher module " + name
|
||||
} else {
|
||||
voices := quickSpeechVoices(next.SpeechOutputModule, worker.catalog[next.SpeechOutputModule])
|
||||
if len(voices) == 0 {
|
||||
worker.announceSpeechSetting("No speech-dispatcher voices available")
|
||||
return
|
||||
}
|
||||
name := "server default"
|
||||
if family := next.DefaultVoice.Family; family != nil && family.Name != "" {
|
||||
name = family.Name
|
||||
}
|
||||
if adjust {
|
||||
index := 0
|
||||
for i, voice := range voices {
|
||||
if voice.Name == name {
|
||||
index = max(0, min(len(voices)-1, i+delta))
|
||||
break
|
||||
}
|
||||
}
|
||||
voice := voices[index]
|
||||
next.DefaultVoice.Family = &config.VoiceFamily{Name: voice.Name, Lang: voice.Language, Variant: voice.Variant}
|
||||
name = voice.Name
|
||||
}
|
||||
message = "Speech-dispatcher voice " + name
|
||||
worker.quickSpeech.settings = next
|
||||
worker.quickSpeech.adjusted[result.Entry.ID] = true
|
||||
change := quickSpeechSettings{settings: next, adjusted: map[string]bool{result.Entry.ID: true}}
|
||||
global := change.apply(worker.globalSettings)
|
||||
for application, settings := range worker.appSettings {
|
||||
worker.appSettings[application] = config.RebaseApplicationSettings(worker.globalSettings, global, settings)
|
||||
}
|
||||
worker.setGlobalSettings(global)
|
||||
worker.settings = change.apply(worker.settings)
|
||||
}
|
||||
if adjust {
|
||||
err := config.Validate(next)
|
||||
if err == nil {
|
||||
err = worker.updateSpeech(ctx, next)
|
||||
}
|
||||
if err != nil {
|
||||
worker.logger.Warn("adjust speech setting", "error", err)
|
||||
worker.catalog = nil
|
||||
worker.announceSpeechSetting("Speech settings were not applied")
|
||||
return
|
||||
}
|
||||
if worker.speechOverride != nil {
|
||||
value := tentaclewire.SpeechFromSettings(next)
|
||||
worker.speechOverride = &value
|
||||
} else {
|
||||
worker.quickSpeech.settings = next
|
||||
worker.quickSpeech.adjusted[worker.speechSetting] = true
|
||||
global := copyQuickSpeechSetting(worker.globalSettings, next, worker.speechSetting)
|
||||
for application, settings := range worker.appSettings {
|
||||
worker.appSettings[application] = config.RebaseApplicationSettings(worker.globalSettings, global, settings)
|
||||
}
|
||||
worker.setGlobalSettings(global)
|
||||
worker.settings = next
|
||||
}
|
||||
if worker.live != nil {
|
||||
worker.live.Store(next)
|
||||
}
|
||||
if worker.live != nil {
|
||||
worker.live.Store(next)
|
||||
}
|
||||
worker.announceSpeechSetting(message)
|
||||
return true
|
||||
}
|
||||
|
||||
// The preferences worker owns these session-only choices. Apply them after
|
||||
@@ -244,36 +395,39 @@ func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, comman
|
||||
// Explicit preferences Apply or reader exit ends this override; saving does not.
|
||||
type quickSpeechSettings struct {
|
||||
settings config.Settings
|
||||
adjusted [5]bool
|
||||
adjusted map[string]bool
|
||||
}
|
||||
|
||||
func (quick quickSpeechSettings) apply(settings config.Settings) config.Settings {
|
||||
for index, adjusted := range quick.adjusted {
|
||||
if adjusted {
|
||||
settings = copyQuickSpeechSetting(settings, quick.settings, index)
|
||||
host := &quickSettingsHost{settings: quick.settings}
|
||||
for _, id := range sortedQuickIDs(quick.adjusted) {
|
||||
entry := quicksettings.Entry{ID: id}
|
||||
if _, ok := quickToggleByID(id); ok {
|
||||
entry.Kind = quicksettings.Toggle
|
||||
}
|
||||
value := host.Value(entry)
|
||||
if id == "speech.module" || id == "speech.voice" {
|
||||
// A voice belongs to its synthesizer, and a hardware synthesizer also
|
||||
// needs its transport. Keep this selection valid across app profiles.
|
||||
settings.SpeechServerFactory = quick.settings.SpeechServerFactory
|
||||
settings.SpeechOutputModule = quick.settings.SpeechOutputModule
|
||||
settings.HardwareSpeechDevice = quick.settings.HardwareSpeechDevice
|
||||
settings.HardwareSpeechBaudRate = quick.settings.HardwareSpeechBaudRate
|
||||
settings.DefaultVoice.Family = quick.settings.DefaultVoice.Family
|
||||
continue
|
||||
}
|
||||
host.set(&settings, entry, value)
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
func copyQuickSpeechSetting(target, source config.Settings, index int) config.Settings {
|
||||
switch index {
|
||||
case 0:
|
||||
target.DefaultVoice.Rate = source.DefaultVoice.Rate
|
||||
case 1:
|
||||
target.DefaultVoice.AveragePitch = source.DefaultVoice.AveragePitch
|
||||
case 2:
|
||||
target.DefaultVoice.Gain = source.DefaultVoice.Gain
|
||||
case 3, 4:
|
||||
// A voice belongs to its synthesizer, and a hardware synthesizer also
|
||||
// needs its transport. Keep this selection valid across app profiles.
|
||||
target.SpeechServerFactory = source.SpeechServerFactory
|
||||
target.SpeechOutputModule = source.SpeechOutputModule
|
||||
target.HardwareSpeechDevice = source.HardwareSpeechDevice
|
||||
target.HardwareSpeechBaudRate = source.HardwareSpeechBaudRate
|
||||
target.DefaultVoice.Family = source.DefaultVoice.Family
|
||||
func sortedQuickIDs(ids map[string]bool) []string {
|
||||
result := make([]string, 0, len(ids))
|
||||
for id := range ids {
|
||||
result = append(result, id)
|
||||
}
|
||||
return target
|
||||
sort.Strings(result)
|
||||
return result
|
||||
}
|
||||
|
||||
// Keep eSpeak NG's language/variant cross product manageable in quick settings.
|
||||
|
||||
@@ -16,8 +16,27 @@ import (
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
"git.stormux.org/storm/cthulhu/internal/preferences"
|
||||
"git.stormux.org/storm/cthulhu/internal/speech"
|
||||
"git.stormux.org/storm/screenreader-common/quicksettings"
|
||||
)
|
||||
|
||||
// selectQuickSetting moves the quick menu to id with ordinary commands.
|
||||
func selectQuickSetting(t *testing.T, worker *preferencesWorker, id string) {
|
||||
t.Helper()
|
||||
for range 4 {
|
||||
for range 32 {
|
||||
worker.handleSpeechCommand(t.Context(), input.SelectNextSpeechSetting)
|
||||
if entry, ok := worker.quickMenu.Selected(); ok && entry.ID == id {
|
||||
return
|
||||
}
|
||||
}
|
||||
worker.handleSpeechCommand(t.Context(), input.SelectNextSpeechCategory)
|
||||
if entry, ok := worker.quickMenu.Selected(); ok && entry.ID == id {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("quick setting %s not found", id)
|
||||
}
|
||||
|
||||
func TestSpeechShortcutsApplySaveAndFailure(t *testing.T) {
|
||||
settings := config.DefaultSettings()
|
||||
settings.Path = filepath.Join(t.TempDir(), "settings.toml")
|
||||
@@ -38,34 +57,37 @@ func TestSpeechShortcutsApplySaveAndFailure(t *testing.T) {
|
||||
worker.announce = func(text string) { message = text }
|
||||
command := func(c input.Command) { t.Helper(); worker.handleSpeechCommand(context.Background(), c) }
|
||||
command(input.IncreaseSpeechSetting)
|
||||
if message != "Rate 51" || applied.Rate == nil || *applied.Rate != 4 || *worker.live.Load().DefaultVoice.Rate != 51 || rate != 50 {
|
||||
if message != "60" || applied.Rate == nil || *applied.Rate != 60 || *worker.live.Load().DefaultVoice.Rate != 60 || rate != 50 {
|
||||
t.Fatalf("rate: message %q, applied %+v, original %g", message, applied, rate)
|
||||
}
|
||||
updateError = errors.New("backend unavailable")
|
||||
command(input.IncreaseSpeechSetting)
|
||||
if message != "Speech settings were not applied" || *worker.live.Load().DefaultVoice.Rate != 51 {
|
||||
t.Fatal("failed update changed session")
|
||||
if message != "Rate was not changed" || *worker.live.Load().DefaultVoice.Rate != 60 {
|
||||
t.Fatal("failed update changed session", message)
|
||||
}
|
||||
updateError = nil
|
||||
worker.catalog = speech.Catalog{"": {{Name: "default", Language: "en"}}, "alpha": {{Name: "one", Language: "en"}, {Name: "two", Language: "en"}}, "beta": {{Name: "three", Language: "en"}}}
|
||||
for _, want := range []string{"Pitch server default", "Volume server default", "Speech-dispatcher module server default"} {
|
||||
for _, want := range []string{"Pitch 0", "Volume 100", "Speech-dispatcher module default"} {
|
||||
command(input.SelectNextSpeechSetting)
|
||||
if message != want {
|
||||
t.Fatalf("got %q, want %q", message, want)
|
||||
}
|
||||
}
|
||||
command(input.IncreaseSpeechSetting)
|
||||
if applied.OutputModule != "alpha" || applied.SynthesisVoice != "one" {
|
||||
t.Fatalf("module: %+v", applied)
|
||||
if message != "alpha" || applied.OutputModule != "alpha" || applied.SynthesisVoice != "one" {
|
||||
t.Fatalf("module: %q %+v", message, applied)
|
||||
}
|
||||
command(input.SelectNextSpeechSetting)
|
||||
if message != "Speech-dispatcher voice one" {
|
||||
t.Fatal(message)
|
||||
}
|
||||
command(input.IncreaseSpeechSetting)
|
||||
if applied.SynthesisVoice != "two" {
|
||||
t.Fatalf("voice: %+v", applied)
|
||||
}
|
||||
command(input.SelectNextSpeechSetting)
|
||||
if worker.speechSetting != 4 {
|
||||
t.Fatal("selector wrapped")
|
||||
if message != "Rate 60" {
|
||||
t.Fatal("selector did not wrap to the first setting", message)
|
||||
}
|
||||
command(input.SaveSpeechSettings)
|
||||
if message != "Speech settings saved" {
|
||||
@@ -79,7 +101,7 @@ func TestSpeechShortcutsApplySaveAndFailure(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.SpeechOutputModule != "alpha" || saved.DefaultVoice.Family.Name != "two" || *saved.DefaultVoice.Rate != 51 {
|
||||
if saved.SpeechOutputModule != "alpha" || saved.DefaultVoice.Family.Name != "two" || *saved.DefaultVoice.Rate != 60 {
|
||||
t.Fatalf("saved settings did not retain speech choices: %+v", saved.DefaultVoice)
|
||||
}
|
||||
worker.settings.Path = t.TempDir()
|
||||
@@ -90,22 +112,79 @@ func TestSpeechShortcutsApplySaveAndFailure(t *testing.T) {
|
||||
}
|
||||
// A backend failure must not affect later selection or saving.
|
||||
command(input.SelectPreviousSpeechSetting)
|
||||
if worker.speechSetting != 3 {
|
||||
t.Fatal("selector did not recover")
|
||||
if message != "Speech-dispatcher voice two" {
|
||||
t.Fatal("selector did not recover", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuickSettingsCategoriesReadingAndKeyboard(t *testing.T) {
|
||||
settings := config.DefaultSettings()
|
||||
settings.VerbalizePunctuationStyle = 2
|
||||
settings.Reading.EnableIndentation = false
|
||||
settings.Reading.SpeakBlankLines = false
|
||||
settings.EnableEchoByWord = false
|
||||
var applied []speech.Settings
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, settingsUpdateFunc(func(_ context.Context, next speech.Settings) error {
|
||||
applied = append(applied, next)
|
||||
return nil
|
||||
}))
|
||||
worker.live = &liveSettings{}
|
||||
worker.live.Store(settings)
|
||||
var messages []string
|
||||
worker.announce = func(text string) { messages = append(messages, text) }
|
||||
steps := []struct {
|
||||
command input.Command
|
||||
want string
|
||||
}{
|
||||
{input.SelectNextSpeechCategory, "Reading. Punctuation level some"},
|
||||
{input.IncreaseSpeechSetting, "none"},
|
||||
{input.IncreaseSpeechSetting, "all"},
|
||||
{input.SelectNextSpeechSetting, "Indentation none"},
|
||||
{input.IncreaseSpeechSetting, "speech"},
|
||||
{input.IncreaseSpeechSetting, "beeps"},
|
||||
{input.SelectPreviousSpeechSetting, "Punctuation level all"},
|
||||
{input.SelectNextSpeechCategory, "Keyboard. Key echo checked"},
|
||||
{input.SelectNextSpeechSetting, "Character echo unchecked"},
|
||||
{input.SelectNextSpeechSetting, "Word echo unchecked"},
|
||||
{input.IncreaseSpeechSetting, "checked"},
|
||||
{input.SelectNextSpeechCategory, "Speech. Rate 0"},
|
||||
{input.SelectPreviousSpeechCategory, "Keyboard. Word echo checked"},
|
||||
}
|
||||
for _, step := range steps {
|
||||
worker.handleSpeechCommand(t.Context(), step.command)
|
||||
if got := messages[len(messages)-1]; got != step.want {
|
||||
t.Fatalf("got %q, want %q", got, step.want)
|
||||
}
|
||||
}
|
||||
live := worker.live.Load()
|
||||
if live.VerbalizePunctuationStyle != 0 || !live.Reading.EnableIndentation || live.Reading.IndentationPresentationMode != "beeps" || !live.EnableEchoByWord {
|
||||
t.Fatalf("quick changes were not published: %+v", live.Reading)
|
||||
}
|
||||
if worker.globalSettings.VerbalizePunctuationStyle != 0 || !worker.globalSettings.EnableEchoByWord {
|
||||
t.Fatal("quick changes did not reach the session's global settings")
|
||||
}
|
||||
// Punctuation reaches speech; indentation and key echo do not reconfigure it.
|
||||
if len(applied) != 2 || applied[len(applied)-1].Punctuation != "all" {
|
||||
t.Fatalf("speech updates = %+v", applied)
|
||||
}
|
||||
selectQuickSetting(t, worker, "reading.blank-lines")
|
||||
worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting)
|
||||
if !worker.live.Load().Reading.SpeakBlankLines || messages[len(messages)-1] != "checked" {
|
||||
t.Fatal("reading toggle", messages[len(messages)-1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuickSpeechFollowsWindowSwitchesAndSavesGlobally(t *testing.T) {
|
||||
for index, name := range []string{"rate", "pitch", "volume", "synthesizer", "voice"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for _, id := range []string{"speech.rate", "speech.pitch", "speech.volume", "speech.module", "speech.voice", "keyboard.word-echo"} {
|
||||
t.Run(id, func(t *testing.T) {
|
||||
global := config.DefaultSettings()
|
||||
global.Path = filepath.Join(t.TempDir(), "settings.toml")
|
||||
rate, pitch, gain := 50.0, 5.0, 5.0
|
||||
rate, pitch, gain := 50.0, 50.0, 50.0
|
||||
global.DefaultVoice = config.Voice{Rate: &rate, AveragePitch: &pitch, Gain: &gain,
|
||||
Family: &config.VoiceFamily{Name: "one", Lang: "en"}}
|
||||
global.SpeechOutputModule = "alpha"
|
||||
application := global
|
||||
appRate, appPitch, appGain := 25.0, 2.0, 2.0
|
||||
appRate, appPitch, appGain := 25.0, 20.0, 20.0
|
||||
application.DefaultVoice = config.Voice{Rate: &appRate, AveragePitch: &appPitch, Gain: &appGain,
|
||||
Family: &config.VoiceFamily{Name: "three", Lang: "en"}}
|
||||
application.SpeechOutputModule = "beta"
|
||||
@@ -136,35 +215,45 @@ func TestQuickSpeechFollowsWindowSwitchesAndSavesGlobally(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
worker.switchApplication(ctx, "Cached Application")
|
||||
worker.switchApplication(ctx, "Presentation")
|
||||
worker.speechSetting = index
|
||||
selectQuickSetting(t, worker, id)
|
||||
applied = speechSettingsFromConfig(worker.settings)
|
||||
worker.handleSpeechCommand(ctx, input.IncreaseSpeechSetting)
|
||||
adjusted := worker.settings
|
||||
check := func(base config.Settings) {
|
||||
t.Helper()
|
||||
switch index {
|
||||
case 0:
|
||||
value := 51.0
|
||||
change := func(base config.Settings) config.Settings {
|
||||
switch id {
|
||||
case "speech.rate":
|
||||
value := 60.0
|
||||
base.DefaultVoice.Rate = &value
|
||||
case 1:
|
||||
value := 5.1
|
||||
case "speech.pitch":
|
||||
value := 60.0
|
||||
base.DefaultVoice.AveragePitch = &value
|
||||
case 2:
|
||||
value := 5.1
|
||||
case "speech.volume":
|
||||
value := 60.0
|
||||
base.DefaultVoice.Gain = &value
|
||||
case 3:
|
||||
case "speech.module":
|
||||
base.SpeechOutputModule = "beta"
|
||||
base.DefaultVoice.Family = &config.VoiceFamily{Name: "three", Lang: "en"}
|
||||
case 4:
|
||||
case "speech.voice":
|
||||
base.SpeechOutputModule = "alpha"
|
||||
base.DefaultVoice.Family = &config.VoiceFamily{Name: "two", Lang: "en"}
|
||||
case "keyboard.word-echo":
|
||||
base.EnableEchoByWord = !global.EnableEchoByWord
|
||||
}
|
||||
return base
|
||||
}
|
||||
check := func(base config.Settings) {
|
||||
t.Helper()
|
||||
base = change(base)
|
||||
if !reflect.DeepEqual(speechSettingsFromConfig(worker.settings), speechSettingsFromConfig(base)) ||
|
||||
!reflect.DeepEqual(speechSettingsFromConfig(worker.live.Load()), speechSettingsFromConfig(base)) ||
|
||||
!reflect.DeepEqual(applied, speechSettingsFromConfig(base)) {
|
||||
t.Fatalf("speech choice lost in %q: got %+v, want %+v", worker.activeApp, worker.settings.DefaultVoice, base.DefaultVoice)
|
||||
}
|
||||
if worker.settings.EnableEchoByWord != base.EnableEchoByWord || worker.live.Load().EnableEchoByWord != base.EnableEchoByWord {
|
||||
t.Fatalf("word echo lost in %q", worker.activeApp)
|
||||
}
|
||||
if worker.settings.TimeFormat != base.TimeFormat {
|
||||
t.Fatal("quick speech changed unrelated application preferences")
|
||||
t.Fatal("quick settings changed unrelated application preferences")
|
||||
}
|
||||
}
|
||||
check(global)
|
||||
@@ -181,19 +270,19 @@ func TestQuickSpeechFollowsWindowSwitchesAndSavesGlobally(t *testing.T) {
|
||||
t.Fatalf("unsaved shortcuts wrote settings: %v", err)
|
||||
}
|
||||
// Saving while an application profile is active must update the global
|
||||
// speech choice without copying its other preferences into the default.
|
||||
// choice without copying its other preferences into the default.
|
||||
worker.switchApplication(ctx, "Cached Application")
|
||||
worker.handleSpeechCommand(ctx, input.SaveSpeechSettings)
|
||||
loaded, err := store.Load()
|
||||
if err != nil || !reflect.DeepEqual(speechSettingsFromConfig(loaded), speechSettingsFromConfig(adjusted)) || loaded.TimeFormat != global.TimeFormat {
|
||||
t.Fatalf("global speech settings were not saved: %+v, %v", loaded, err)
|
||||
if err != nil || !reflect.DeepEqual(speechSettingsFromConfig(loaded), speechSettingsFromConfig(adjusted)) || loaded.TimeFormat != global.TimeFormat || loaded.EnableEchoByWord != adjusted.EnableEchoByWord {
|
||||
t.Fatalf("global settings were not saved: %+v, %v", loaded, err)
|
||||
}
|
||||
appLoaded, mapped, err := store.LoadForApplication("Cached Application")
|
||||
if err != nil || !mapped || !reflect.DeepEqual(speechSettingsFromConfig(appLoaded), speechSettingsFromConfig(application)) {
|
||||
t.Fatalf("save shortcut overwrote application profile: %+v, %v", appLoaded, err)
|
||||
}
|
||||
if _, mapped, err := store.LoadForApplication("Presentation"); err != nil || mapped {
|
||||
t.Fatalf("quick speech created an application profile: %t, %v", mapped, err)
|
||||
t.Fatalf("quick settings created an application profile: %t, %v", mapped, err)
|
||||
}
|
||||
worker.switchApplication(ctx, "Presentation")
|
||||
check(global)
|
||||
@@ -239,32 +328,32 @@ func TestQuickSpeechFailureAndPreferencesReplacement(t *testing.T) {
|
||||
}
|
||||
worker.globalSettings.Path = path
|
||||
worker.switchApplication(ctx, "Example Editor")
|
||||
if *worker.settings.DefaultVoice.Rate != 51 || *worker.settings.DefaultVoice.AveragePitch != 5.1 {
|
||||
if *worker.settings.DefaultVoice.Rate != 60 || *worker.settings.DefaultVoice.AveragePitch != 10 {
|
||||
t.Fatal("failed adjustment or save lost prior session choices")
|
||||
}
|
||||
if !worker.beginEdit(ctx, "") {
|
||||
t.Fatal("could not open global preferences")
|
||||
}
|
||||
values := preferences.FromSettings(worker.editing)
|
||||
appliedRate := 60.0
|
||||
appliedRate := 70.0
|
||||
values.Rate = &appliedRate
|
||||
updateError = errors.New("backend unavailable")
|
||||
if response := worker.apply(ctx, preferences.Request{Values: values}); response.Accepted {
|
||||
t.Fatal("failed preferences apply was accepted")
|
||||
}
|
||||
if settings, err := worker.applicationSettings("Example Editor"); err != nil || *settings.DefaultVoice.Rate != 51 {
|
||||
if settings, err := worker.applicationSettings("Example Editor"); err != nil || *settings.DefaultVoice.Rate != 60 {
|
||||
t.Fatalf("failed preferences apply discarded quick speech: %v", err)
|
||||
}
|
||||
updateError = nil
|
||||
if response := worker.apply(ctx, preferences.Request{Values: values}); !response.Accepted {
|
||||
t.Fatal(response.Message)
|
||||
}
|
||||
if *worker.settings.DefaultVoice.Rate != 25 || *worker.globalSettings.DefaultVoice.Rate != 60 {
|
||||
if *worker.settings.DefaultVoice.Rate != 25 || *worker.globalSettings.DefaultVoice.Rate != 70 {
|
||||
t.Fatal("explicit preferences apply did not restore application profile ownership")
|
||||
}
|
||||
worker.editingActive = false
|
||||
worker.switchApplication(ctx, "Presentation")
|
||||
if *worker.settings.DefaultVoice.Rate != 60 {
|
||||
if *worker.settings.DefaultVoice.Rate != 70 {
|
||||
t.Fatal("old quick speech choice replaced applied preferences")
|
||||
}
|
||||
}
|
||||
@@ -277,14 +366,18 @@ func TestSpeechShortcutReadsAndSavesRoundedNumbers(t *testing.T) {
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, nil)
|
||||
message := ""
|
||||
worker.announce = func(text string) { message = text }
|
||||
for index, want := range []string{"Rate 90", "Pitch 4.5", "Volume 5"} {
|
||||
command := input.SelectNextSpeechSetting
|
||||
if index == 0 {
|
||||
command = input.SelectPreviousSpeechSetting
|
||||
}
|
||||
worker.handleSpeechCommand(t.Context(), command)
|
||||
if message != want {
|
||||
t.Fatalf("got %q, want %q", message, want)
|
||||
for _, step := range []struct {
|
||||
command input.Command
|
||||
want string
|
||||
}{
|
||||
{input.SelectNextSpeechSetting, "Pitch 4"},
|
||||
{input.SelectNextSpeechSetting, "Volume 5"},
|
||||
{input.SelectPreviousSpeechSetting, "Pitch 4"},
|
||||
{input.SelectPreviousSpeechSetting, "Rate 90"},
|
||||
} {
|
||||
worker.handleSpeechCommand(t.Context(), step.command)
|
||||
if message != step.want {
|
||||
t.Fatalf("got %q, want %q", message, step.want)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(settings.Path); !errors.Is(err, os.ErrNotExist) {
|
||||
@@ -296,51 +389,68 @@ func TestSpeechShortcutReadsAndSavesRoundedNumbers(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := store.Load()
|
||||
if err != nil || *saved.DefaultVoice.Rate != 90 || *saved.DefaultVoice.AveragePitch != 4.5 || *saved.DefaultVoice.Gain != 5 {
|
||||
if err != nil || *saved.DefaultVoice.Rate != 90 || *saved.DefaultVoice.AveragePitch != 4 || *saved.DefaultVoice.Gain != 5 {
|
||||
t.Fatalf("speech numbers were not saved rounded: %+v, %v", saved.DefaultVoice, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpeechShortcutNumericBounds(t *testing.T) {
|
||||
for index, maximum := range []float64{99, 9, 9} {
|
||||
for index, id := range []string{"speech.rate", "speech.pitch", "speech.volume"} {
|
||||
settings := config.DefaultSettings()
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, settingsUpdateFunc(func(context.Context, speech.Settings) error { return nil }))
|
||||
worker.speechSetting = index
|
||||
selectQuickSetting(t, worker, id)
|
||||
fields := []**float64{&worker.settings.DefaultVoice.Rate, &worker.settings.DefaultVoice.AveragePitch, &worker.settings.DefaultVoice.Gain}
|
||||
maximum := 100.0
|
||||
*fields[index] = &maximum
|
||||
worker.handleSpeechCommand(context.Background(), input.IncreaseSpeechSetting)
|
||||
if **fields[index] != maximum {
|
||||
if **fields[index] != 100 {
|
||||
t.Fatal("upper bound exceeded")
|
||||
}
|
||||
zero := 0.0
|
||||
*fields[index] = &zero
|
||||
minimum := -100.0
|
||||
*fields[index] = &minimum
|
||||
worker.handleSpeechCommand(context.Background(), input.DecreaseSpeechSetting)
|
||||
if **fields[index] != 0 {
|
||||
if **fields[index] != -100 {
|
||||
t.Fatal("lower bound exceeded")
|
||||
}
|
||||
worker.handleSpeechCommand(context.Background(), input.IncreaseSpeechSetting)
|
||||
want := 0.1
|
||||
if index == 0 {
|
||||
want = 1
|
||||
}
|
||||
if **fields[index] != want {
|
||||
t.Fatalf("step %g, want %g", **fields[index], want)
|
||||
if **fields[index] != -90 {
|
||||
t.Fatalf("step %g, want -90", **fields[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpeechShortcutUnavailableDiscovery(t *testing.T) {
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), config.DefaultSettings(), nil)
|
||||
worker.speechSetting = 3
|
||||
worker.discover = func(context.Context, string) (speech.Catalog, error) { return nil, errors.New("offline") }
|
||||
message := ""
|
||||
worker.announce = func(text string) { message = text }
|
||||
selectQuickSetting(t, worker, "speech.module")
|
||||
worker.handleSpeechCommand(context.Background(), input.IncreaseSpeechSetting)
|
||||
if message != "Speech settings unavailable" || worker.settings.SpeechOutputModule != "" {
|
||||
t.Fatal(message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHardwareQuickSettingsOfferSynthesizersWithoutVoices(t *testing.T) {
|
||||
settings := config.DefaultSettings()
|
||||
settings.SpeechServerFactory = "hardwarefactory"
|
||||
settings.SpeechOutputModule = "doubletalk"
|
||||
settings.HardwareSpeechDevice = "/dev/fixture-synth"
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, nil)
|
||||
worker.discover = func(context.Context, string) (speech.Catalog, error) {
|
||||
t.Fatal("hardware speech discovered Speech Dispatcher voices")
|
||||
return nil, nil
|
||||
}
|
||||
var messages []string
|
||||
worker.announce = func(text string) { messages = append(messages, text) }
|
||||
for _, want := range []string{"Pitch 0", "Volume 100", "Hardware synthesizer doubletalk", "Rate 0"} {
|
||||
worker.handleSpeechCommand(t.Context(), input.SelectNextSpeechSetting)
|
||||
if got := messages[len(messages)-1]; got != want {
|
||||
t.Fatalf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuickSpeechESpeakLocale(t *testing.T) {
|
||||
voices := []speech.Voice{
|
||||
{Name: "de+max", Language: "de"},
|
||||
@@ -396,19 +506,20 @@ func TestSpeechShortcutESpeakDefaultAndVariants(t *testing.T) {
|
||||
{Name: "en-us", Language: "en-us"},
|
||||
{Name: "fr", Language: "fr"},
|
||||
}}
|
||||
worker.speechSetting = 3
|
||||
selectQuickSetting(t, worker, "speech.module")
|
||||
worker.handleSpeechCommand(context.Background(), input.IncreaseSpeechSetting)
|
||||
if applied.OutputModule != "espeak-ng" || applied.SynthesisVoice != "en-us" || applied.Language != "en-us" {
|
||||
t.Fatalf("module switch: %+v", applied)
|
||||
}
|
||||
worker.handleSpeechCommand(context.Background(), input.SelectNextSpeechSetting)
|
||||
// Voices wrap through the module default, as in Fenrir.
|
||||
for _, tc := range []struct {
|
||||
command input.Command
|
||||
want string
|
||||
}{
|
||||
{input.IncreaseSpeechSetting, "en-us+max"},
|
||||
{input.IncreaseSpeechSetting, "en-us+max"},
|
||||
{input.DecreaseSpeechSetting, "en-us"},
|
||||
{input.IncreaseSpeechSetting, ""},
|
||||
{input.DecreaseSpeechSetting, "en-us+max"},
|
||||
{input.DecreaseSpeechSetting, "en-us"},
|
||||
} {
|
||||
worker.handleSpeechCommand(context.Background(), tc.command)
|
||||
@@ -417,3 +528,15 @@ func TestSpeechShortcutESpeakDefaultAndVariants(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuickSettingsRetainPartialDiscovery(t *testing.T) {
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), config.DefaultSettings(), nil)
|
||||
worker.discover = func(context.Context, string) (speech.Catalog, error) {
|
||||
return speech.Catalog{"working": {{Name: "Voice", Language: "en"}}}, errors.New("another module failed")
|
||||
}
|
||||
host := &quickSettingsHost{worker: worker, ctx: t.Context(), settings: worker.settings}
|
||||
options := host.Options(quicksettings.Entry{ID: "speech.module"})
|
||||
if host.unavailable != "" || len(options) != 2 || options[1].ID != "working" {
|
||||
t.Fatal(options, host.unavailable)
|
||||
}
|
||||
}
|
||||
@@ -576,61 +576,57 @@ func (worker *preferencesWorker) quick_settings() []readerQuickSetting {
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (worker *preferencesWorker) handle_extension_quick(ctx context.Context, setting readerQuickSetting, adjust bool, delta int) {
|
||||
selected := 0
|
||||
for index, option := range setting.setting.Options {
|
||||
if option.ID == setting.setting.Selected {
|
||||
selected = index
|
||||
|
||||
// handle_extension_quick 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
|
||||
found := false
|
||||
for _, candidate := range setting.setting.Options {
|
||||
if candidate.ID == selected && !candidate.Disabled {
|
||||
option, found = candidate, true
|
||||
break
|
||||
}
|
||||
}
|
||||
candidate := selected
|
||||
if adjust {
|
||||
for index := selected + delta; index >= 0 && index < len(setting.setting.Options); index += delta {
|
||||
if !setting.setting.Options[index].Disabled {
|
||||
candidate = index
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
worker.announceSpeechSetting(setting.setting.Label + " was not changed")
|
||||
return false
|
||||
}
|
||||
option := setting.setting.Options[candidate]
|
||||
if candidate != selected {
|
||||
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()
|
||||
if err == nil {
|
||||
err = worker.stage_reader_request(ctx, &transaction, setting.extension.session, request)
|
||||
}
|
||||
if err == nil {
|
||||
found := false
|
||||
extension := transaction.extensions[setting.extension.session.Identity()]
|
||||
for index := range extension.value.QuickSettings {
|
||||
current := &extension.value.QuickSettings[index]
|
||||
if current.ID != setting.setting.ID {
|
||||
continue
|
||||
}
|
||||
for _, choice := range current.Options {
|
||||
if choice.ID == option.ID && !choice.Disabled {
|
||||
current.Selected = option.ID
|
||||
found = true
|
||||
break
|
||||
}
|
||||
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()
|
||||
if err == nil {
|
||||
err = worker.stage_reader_request(ctx, &transaction, setting.extension.session, request)
|
||||
}
|
||||
if err == nil {
|
||||
found := false
|
||||
extension := transaction.extensions[setting.extension.session.Identity()]
|
||||
for index := range extension.value.QuickSettings {
|
||||
current := &extension.value.QuickSettings[index]
|
||||
if current.ID != setting.setting.ID {
|
||||
continue
|
||||
}
|
||||
for _, choice := range current.Options {
|
||||
if choice.ID == option.ID && !choice.Disabled {
|
||||
current.Selected = option.ID
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
err = errors.New("selected quick setting was removed by its callback")
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = worker.commit_reader_transaction(ctx, setting.extension.session, transaction)
|
||||
}
|
||||
if err != nil {
|
||||
worker.logger.Warn("apply tentacle quick setting", "error", err)
|
||||
worker.announceSpeechSetting(setting.setting.Label + " was not changed")
|
||||
return
|
||||
if !found {
|
||||
err = errors.New("selected quick setting was removed by its callback")
|
||||
}
|
||||
}
|
||||
worker.announceSpeechSetting(setting.setting.Label + " " + option.Label)
|
||||
if err == nil {
|
||||
err = worker.commit_reader_transaction(ctx, setting.extension.session, transaction)
|
||||
}
|
||||
if err != nil {
|
||||
worker.logger.Warn("apply tentacle quick setting", "error", err)
|
||||
worker.announceSpeechSetting(setting.setting.Label + " was not changed")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (runtime *tentacleRuntime) reader_continuation(command tentacleCommand, id string) bool {
|
||||
|
||||
@@ -253,9 +253,9 @@ func TestReaderExtensionQuickNavigationRollbackDefaultAndBaseEdits(t *testing.T)
|
||||
worker, _, recorder := reader_extension_fixture(t, "normal")
|
||||
var messages []string
|
||||
worker.announce = func(message string) { messages = append(messages, message) }
|
||||
worker.speechSetting = 4
|
||||
worker.handleSpeechCommand(t.Context(), input.SelectNextSpeechSetting)
|
||||
if messages[len(messages)-1] != "Probe mode Default" {
|
||||
probe := "tentacle." + worker.quick_settings()[0].key
|
||||
selectQuickSetting(t, worker, probe)
|
||||
if messages[len(messages)-1] != "Tentacles. Probe mode Default" {
|
||||
t.Fatal(messages)
|
||||
}
|
||||
worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting)
|
||||
@@ -267,10 +267,9 @@ func TestReaderExtensionQuickNavigationRollbackDefaultAndBaseEdits(t *testing.T)
|
||||
t.Fatal("failed switch committed")
|
||||
}
|
||||
// Built-in changes edit the active temporary override, not the normal voice.
|
||||
worker.quickSettingKey = ""
|
||||
worker.speechSetting = 0
|
||||
selectQuickSetting(t, worker, "speech.rate")
|
||||
worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting)
|
||||
if *worker.live.Load().DefaultVoice.Rate != 81 || *worker.settings.DefaultVoice.Rate != 50 {
|
||||
if *worker.live.Load().DefaultVoice.Rate != 90 || *worker.settings.DefaultVoice.Rate != 50 {
|
||||
t.Fatal("built-in adjustment changed base")
|
||||
}
|
||||
// A core preference edit still targets and saves the ordinary settings.
|
||||
@@ -278,10 +277,10 @@ func TestReaderExtensionQuickNavigationRollbackDefaultAndBaseEdits(t *testing.T)
|
||||
pitch := 6.0
|
||||
next.DefaultVoice.AveragePitch = &pitch
|
||||
response := worker.applyNext(t.Context(), next, false, false)
|
||||
if !response.Accepted || *worker.live.Load().DefaultVoice.Rate != 81 {
|
||||
if !response.Accepted || *worker.live.Load().DefaultVoice.Rate != 90 {
|
||||
t.Fatal(response.Message)
|
||||
}
|
||||
worker.quickSettingKey = worker.quick_settings()[0].key
|
||||
selectQuickSetting(t, worker, probe)
|
||||
worker.handleSpeechCommand(t.Context(), input.DecreaseSpeechSetting)
|
||||
if worker.speechOverride != nil || *worker.live.Load().DefaultVoice.Rate != 50 || *worker.live.Load().DefaultVoice.AveragePitch != 6 {
|
||||
t.Fatal("default did not restore edited base")
|
||||
@@ -316,7 +315,7 @@ func TestReaderExtensionRejectionCrashAndFailedApplyLeaveDraftUncommitted(t *tes
|
||||
}
|
||||
func TestReaderExtensionRevocationRestoresAndRemovesContributions(t *testing.T) {
|
||||
worker, session, _ := reader_extension_fixture(t, "normal")
|
||||
worker.quickSettingKey = worker.quick_settings()[0].key
|
||||
selectQuickSetting(t, worker, "tentacle."+worker.quick_settings()[0].key)
|
||||
value := tentaclewire.SpeechFromSettings(worker.settings)
|
||||
rate := 82.0
|
||||
value.DefaultVoice.Rate = &rate
|
||||
@@ -334,7 +333,7 @@ func TestReaderExtensionRevocationRestoresAndRemovesContributions(t *testing.T)
|
||||
message := ""
|
||||
worker.announce = func(text string) { message = text }
|
||||
worker.handleSpeechCommand(t.Context(), input.IncreaseSpeechSetting)
|
||||
if message != "The selected speech setting is no longer available" || worker.settings.DefaultVoice.Family != nil {
|
||||
if message != "The selected setting is no longer available" || worker.settings.DefaultVoice.Family != nil {
|
||||
t.Fatal("a removed quick setting silently adjusted a different setting", message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func decodeDocument(contents []byte) (writableDocument, Settings, error) {
|
||||
if err := toml.Unmarshal(contents, &envelope); err != nil {
|
||||
return writableDocument{}, Settings{}, fmt.Errorf("parse settings: %w", err)
|
||||
}
|
||||
if envelope.SchemaVersion != CurrentSchemaVersion {
|
||||
if envelope.SchemaVersion != CurrentSchemaVersion && envelope.SchemaVersion != speechScaleSchemaVersion-1 {
|
||||
return writableDocument{}, Settings{}, fmt.Errorf("unsupported settings schema version %d; expected %d", envelope.SchemaVersion, CurrentSchemaVersion)
|
||||
}
|
||||
var document writableDocument
|
||||
@@ -63,6 +63,9 @@ func decodeDocument(contents []byte) (writableDocument, Settings, error) {
|
||||
}
|
||||
return writableDocument{}, Settings{}, fmt.Errorf("parse settings schema %d: %w", CurrentSchemaVersion, err)
|
||||
}
|
||||
if document.SchemaVersion < speechScaleSchemaVersion {
|
||||
migrateSpeechScale(&document)
|
||||
}
|
||||
settings, err := effectiveSettings(document)
|
||||
if err != nil {
|
||||
return writableDocument{}, Settings{}, err
|
||||
@@ -70,6 +73,34 @@ func decodeDocument(contents []byte) (writableDocument, Settings, error) {
|
||||
return document, settings, nil
|
||||
}
|
||||
|
||||
// Schema 2 differs only in its legacy voice scale. The migrated document is
|
||||
// written as the current schema on the next save.
|
||||
func migrateSpeechScale(document *writableDocument) {
|
||||
applicationProfiles := make(map[string]bool)
|
||||
for _, name := range document.Applications {
|
||||
applicationProfiles[name] = true
|
||||
}
|
||||
globalFactory := document.Profiles[document.ActiveProfile].Speech.ServerFactory
|
||||
for name, profile := range document.Profiles {
|
||||
factory := profile.Speech.ServerFactory
|
||||
if factory == nil && applicationProfiles[name] {
|
||||
factory = globalFactory
|
||||
}
|
||||
for _, voice := range []**Voice{&profile.Speech.DefaultVoice, &profile.Speech.UppercaseVoice, &profile.Speech.HyperlinkVoice, &profile.Speech.SystemVoice, &profile.KeyEcho.EchoVoice} {
|
||||
if *voice != nil {
|
||||
converted := voiceFromLegacy(**voice)
|
||||
// Echo always uses Speech Dispatcher, including with serial output.
|
||||
if voice != &profile.KeyEcho.EchoVoice && factory != nil && *factory == "hardwarefactory" {
|
||||
converted = hardwareVoiceFromLegacy(**voice)
|
||||
}
|
||||
*voice = &converted
|
||||
}
|
||||
}
|
||||
document.Profiles[name] = profile
|
||||
}
|
||||
document.SchemaVersion = CurrentSchemaVersion
|
||||
}
|
||||
|
||||
func effectiveSettings(document writableDocument) (Settings, error) {
|
||||
if strings.TrimSpace(document.ActiveProfile) == "" {
|
||||
return Settings{}, errors.New("validate configuration: active-profile is empty")
|
||||
|
||||
@@ -59,7 +59,7 @@ func TestLegacySayAllStyleMapsToRuntimeChoice(t *testing.T) {
|
||||
func TestLoadRejectsInvalidVersionedSettingsWithoutWriting(t *testing.T) {
|
||||
for name, contents := range map[string]string{
|
||||
"old": "schema-version = 1\n[general]\n",
|
||||
"future": "schema-version = 3\nactive-profile = 'default'\n[profiles.default]\n",
|
||||
"future": "schema-version = 4\nactive-profile = 'default'\n[profiles.default]\n",
|
||||
"zero": "schema-version = 0\n[general]\n",
|
||||
"negative": "schema-version = -1\n[general]\n",
|
||||
"wrong type": "schema-version = '1'\n[general]\n",
|
||||
@@ -153,11 +153,12 @@ dialect = "US"
|
||||
if settings.SpeechServerFactory != "cthulhu.speechdispatcherfactory" {
|
||||
t.Fatalf("speech server factory = %q", settings.SpeechServerFactory)
|
||||
}
|
||||
if settings.DefaultVoice.Rate == nil || *settings.DefaultVoice.Rate != 75 {
|
||||
t.Fatalf("voice rate = %v, want 75", settings.DefaultVoice.Rate)
|
||||
// Legacy 0..100 rate 75 and 0..10 gain 8 migrate to Speech Dispatcher's scale.
|
||||
if settings.DefaultVoice.Rate == nil || *settings.DefaultVoice.Rate != 52 {
|
||||
t.Fatalf("voice rate = %v, want 52", settings.DefaultVoice.Rate)
|
||||
}
|
||||
if settings.DefaultVoice.Gain == nil || *settings.DefaultVoice.Gain != 8 {
|
||||
t.Fatalf("voice gain = %v, want inherited value 8", settings.DefaultVoice.Gain)
|
||||
if settings.DefaultVoice.Gain == nil || *settings.DefaultVoice.Gain != 85 {
|
||||
t.Fatalf("voice gain = %v, want inherited value 85", settings.DefaultVoice.Gain)
|
||||
}
|
||||
if settings.DefaultVoice.Family == nil || settings.DefaultVoice.Family.Name != "Generic Voice" {
|
||||
t.Fatalf("voice family = %#v", settings.DefaultVoice.Family)
|
||||
@@ -277,7 +278,7 @@ roleSoundPresentation = "sound_only"
|
||||
func TestLoadRejectsNonFiniteVoiceValues(t *testing.T) {
|
||||
for _, value := range []string{"nan", "+inf", "-inf"} {
|
||||
path := writeConfig(t, "[general.voices.default]\nrate = "+value+"\n")
|
||||
if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "default voice rate") {
|
||||
if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "voice rate") {
|
||||
t.Fatalf("Load rate %s error = %v", value, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,7 +266,7 @@ func apply_legacy_echo(settings *Settings, values rawSettings) {
|
||||
settings.UseCustomEchoForSentence = *values.UseCustomEchoForSentence
|
||||
}
|
||||
if values.EchoVoice != nil {
|
||||
mergeVoice(&settings.EchoVoice, *values.EchoVoice)
|
||||
mergeVoice(&settings.EchoVoice, voiceFromLegacy(*values.EchoVoice))
|
||||
}
|
||||
if len(values.EchoSpeechServerInfo) > 1 {
|
||||
settings.EchoSpeechServer = values.EchoSpeechServerInfo[1]
|
||||
@@ -314,7 +314,11 @@ func apply_legacy_echo(settings *Settings, values rawSettings) {
|
||||
|
||||
func apply_legacy_default_voice(settings *Settings, values rawSettings) {
|
||||
if voice, exists := values.Voices["default"]; exists {
|
||||
mergeVoice(&settings.DefaultVoice, voice)
|
||||
converted := voiceFromLegacy(voice)
|
||||
if settings.SpeechServerFactory == "hardwarefactory" {
|
||||
converted = hardwareVoiceFromLegacy(voice)
|
||||
}
|
||||
mergeVoice(&settings.DefaultVoice, converted)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,8 @@ speak-blank-lines = false
|
||||
if settings.EnableSpeech || settings.EnableBraille || settings.SoundVolume != 0 ||
|
||||
settings.PlaySoundForRole || settings.Reading.SpeakBlankLines ||
|
||||
len(settings.CthulhuModifierKeys) != 0 || settings.EchoSpeechServer != "" ||
|
||||
settings.DefaultVoice.Rate == nil || *settings.DefaultVoice.Rate != 0 {
|
||||
// Both inputs use the legacy scale, where rate 0 is the slowest.
|
||||
settings.DefaultVoice.Rate == nil || *settings.DefaultVoice.Rate != -98 {
|
||||
t.Fatalf("explicit false/zero/empty values were lost: %+v", settings)
|
||||
}
|
||||
if !settings.EnableSound || !settings.PlaySoundForState || !settings.EnableKeyEcho ||
|
||||
|
||||
@@ -21,7 +21,10 @@ import (
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
)
|
||||
|
||||
const CurrentSchemaVersion = 2
|
||||
const CurrentSchemaVersion = 3
|
||||
|
||||
// speechScaleSchemaVersion moved voices to Speech Dispatcher's -100..100 scale.
|
||||
const speechScaleSchemaVersion = 3
|
||||
|
||||
type writableDocument struct {
|
||||
SchemaVersion int `toml:"schema-version"`
|
||||
|
||||
@@ -58,7 +58,7 @@ func TestStoreSaveAndLoadRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(contents), "schema-version = 2") ||
|
||||
if !strings.Contains(string(contents), "schema-version = 3") ||
|
||||
!strings.Contains(string(contents), "[profiles.default.speech]") ||
|
||||
!strings.Contains(string(contents), "history-limit = 1000") {
|
||||
t.Fatalf("settings do not contain schema version:\n%s", contents)
|
||||
@@ -119,7 +119,7 @@ func TestStoreMissingFileUsesDefaults(t *testing.T) {
|
||||
func TestStoreRejectsSchemaVersionsAndUnknownFields(t *testing.T) {
|
||||
for name, contents := range map[string]string{
|
||||
"missing": `[general]`,
|
||||
"future": "schema-version = 3\nactive-profile = 'default'\n[profiles.default]\n",
|
||||
"future": "schema-version = 4\nactive-profile = 'default'\n[profiles.default]\n",
|
||||
"unknown": "schema-version = 2\nactive-profile = 'default'\n[profiles.default]\nfuture-setting = true\n",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
@@ -151,15 +151,16 @@ func TestStoreVersionFixtures(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("decode current fixture: %v", err)
|
||||
}
|
||||
if settings.SpeakDescription || settings.VerbalizePunctuationStyle != 2 || settings.DefaultVoice.Rate == nil || *settings.DefaultVoice.Rate != 65 {
|
||||
// Schema 2's legacy rate 65 migrates to 32 on Speech Dispatcher's scale.
|
||||
if settings.SpeakDescription || settings.VerbalizePunctuationStyle != 2 || settings.DefaultVoice.Rate == nil || *settings.DefaultVoice.Rate != 32 {
|
||||
t.Fatalf("current fixture settings = %#v", settings)
|
||||
}
|
||||
|
||||
future, err := os.ReadFile(filepath.Join("testdata", "settings-v3.toml"))
|
||||
future, err := os.ReadFile(filepath.Join("testdata", "settings-v4.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := decodeWritable(future); err == nil || !strings.Contains(err.Error(), "schema version 3") {
|
||||
if _, err := decodeWritable(future); err == nil || !strings.Contains(err.Error(), "schema version 4") {
|
||||
t.Fatalf("future fixture error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
schema-version = 3
|
||||
schema-version = 4
|
||||
active-profile = "default"
|
||||
|
||||
[profiles.default]
|
||||
@@ -214,7 +214,7 @@ func validate(settings Settings) error {
|
||||
if strings.ContainsAny(settings.EchoSpeechServer, "\r\n\x00") {
|
||||
return fmt.Errorf("invalid echo speech synthesizer")
|
||||
}
|
||||
if err := validateVoice(settings.EchoVoice, true); err != nil {
|
||||
if err := validateVoice(settings.EchoVoice); err != nil {
|
||||
return fmt.Errorf("echo voice: %w", err)
|
||||
}
|
||||
if err := validateVoice(settings.DefaultVoice); err != nil {
|
||||
@@ -233,28 +233,13 @@ func validate(settings Settings) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateVoice(voice Voice, echo ...bool) error {
|
||||
values := []struct {
|
||||
name string
|
||||
value *float64
|
||||
maximum float64
|
||||
}{
|
||||
{name: "rate", value: voice.Rate, maximum: 99},
|
||||
{name: "average-pitch", value: voice.AveragePitch, maximum: 9},
|
||||
{name: "gain", value: voice.Gain, maximum: 9},
|
||||
}
|
||||
if len(echo) != 0 && echo[0] {
|
||||
values[0].maximum = 100
|
||||
values[1].maximum = 10
|
||||
values[2].maximum = 10
|
||||
}
|
||||
for _, field := range values {
|
||||
name, value, maximum := field.name, field.value, field.maximum
|
||||
if value == nil {
|
||||
func validateVoice(voice Voice) error {
|
||||
for field, value := range voiceFields(&voice) {
|
||||
if *value == nil {
|
||||
continue
|
||||
}
|
||||
if *value < 0 || *value > maximum || math.IsNaN(*value) || math.IsInf(*value, 0) {
|
||||
return fmt.Errorf("validate configuration: default voice %s %.2f is outside 0 through %.0f", name, *value, maximum)
|
||||
if **value < -100 || **value > 100 || math.IsNaN(**value) || math.IsInf(**value, 0) {
|
||||
return fmt.Errorf("validate configuration: voice %s %.2f is outside -100 through 100", []string{"rate", "average-pitch", "gain"}[field], **value)
|
||||
}
|
||||
}
|
||||
if voice.Family == nil {
|
||||
|
||||
@@ -4,15 +4,74 @@
|
||||
|
||||
package config
|
||||
|
||||
import "math"
|
||||
import (
|
||||
"math"
|
||||
|
||||
// RoundSpeechValues keeps speech controls and persisted voices at one decimal
|
||||
// place without changing the caller's values or turning inheritance into values.
|
||||
"git.stormux.org/storm/screenreader-common/hardware"
|
||||
)
|
||||
|
||||
// Voice rate, average pitch and gain use Speech Dispatcher's -100..100 scale
|
||||
// from schema 3. Earlier schemas, Orca/Python settings and the Orca-compatible
|
||||
// D-Bus API use rate 0..100 and pitch/gain 0..10.
|
||||
const (
|
||||
VoiceRate = iota
|
||||
VoicePitch
|
||||
VoiceGain
|
||||
)
|
||||
|
||||
// These are the formulas Cthulhu used to send legacy values to Speech
|
||||
// Dispatcher, so migrated voices keep sounding the same.
|
||||
var legacyVoiceScales = [3]struct{ scale, offset, maximum float64 }{{2, 98, 100}, {20, 90, 10}, {15, 35, 10}}
|
||||
|
||||
func SpeechFromLegacy(field int, value float64) float64 {
|
||||
scale := legacyVoiceScales[field]
|
||||
return max(-100, min(100, math.Round(value*scale.scale-scale.offset)))
|
||||
}
|
||||
|
||||
func LegacyFromSpeech(field int, value float64) float64 {
|
||||
scale := legacyVoiceScales[field]
|
||||
return max(0, min(scale.maximum, math.Round((value+scale.offset)/scale.scale*10)/10))
|
||||
}
|
||||
|
||||
func voiceFields(voice *Voice) [3]**float64 {
|
||||
return [3]**float64{&voice.Rate, &voice.AveragePitch, &voice.Gain}
|
||||
}
|
||||
|
||||
func voiceFromLegacy(voice Voice) Voice {
|
||||
voice = cloneVoice(voice)
|
||||
for field, value := range voiceFields(&voice) {
|
||||
// Non-finite values stay invalid so validation still rejects them.
|
||||
if *value != nil && !math.IsNaN(**value) && !math.IsInf(**value, 0) {
|
||||
converted := SpeechFromLegacy(field, **value)
|
||||
*value = &converted
|
||||
}
|
||||
}
|
||||
return voice
|
||||
}
|
||||
|
||||
// Serial synthesizers used a different legacy conversion from SSIP.
|
||||
func hardwareVoiceFromLegacy(voice Voice) Voice {
|
||||
voice = cloneVoice(voice)
|
||||
for field, value := range voiceFields(&voice) {
|
||||
if *value != nil && !math.IsNaN(**value) && !math.IsInf(**value, 0) {
|
||||
maximum := 9.0
|
||||
if field == VoiceRate {
|
||||
maximum = 99
|
||||
}
|
||||
converted := math.Round(hardware.LegacyValue(**value, maximum))
|
||||
*value = &converted
|
||||
}
|
||||
}
|
||||
return voice
|
||||
}
|
||||
|
||||
// RoundSpeechValues keeps speech controls and persisted voices at whole
|
||||
// steps without changing the caller's values or turning inheritance into values.
|
||||
func RoundSpeechValues(settings Settings) Settings {
|
||||
for _, voice := range []*Voice{&settings.DefaultVoice, &settings.UppercaseVoice, &settings.HyperlinkVoice, &settings.SystemVoice, &settings.EchoVoice} {
|
||||
for _, field := range []**float64{&voice.Rate, &voice.AveragePitch, &voice.Gain} {
|
||||
for _, field := range voiceFields(voice) {
|
||||
if *field != nil {
|
||||
value := math.Round(**field*10) / 10
|
||||
value := math.Round(**field)
|
||||
*field = &value
|
||||
}
|
||||
}
|
||||
@@ -27,9 +86,10 @@ func EffectiveVoice(settings Settings, kind string) Voice {
|
||||
var override Voice
|
||||
switch kind {
|
||||
case "uppercase":
|
||||
pitch := 7.0
|
||||
pitch := 50.0
|
||||
if voice.AveragePitch != nil {
|
||||
pitch = min(9, max(pitch, *voice.AveragePitch+2))
|
||||
// Never lower than the normal voice, which may sit at the maximum.
|
||||
pitch = min(100, max(pitch, *voice.AveragePitch+40))
|
||||
}
|
||||
if settings.RaisePitchForCapitals {
|
||||
voice.AveragePitch = &pitch
|
||||
|
||||
+140
-14
@@ -12,7 +12,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSpeechNumbersPersistWithOneDecimal(t *testing.T) {
|
||||
func TestSpeechNumbersPersistAsWholeSteps(t *testing.T) {
|
||||
settings := DefaultSettings()
|
||||
rate, pitch, gain := 61.29999999999999, 4.499999999999998, 4.999999999999999
|
||||
settings.DefaultVoice = Voice{Rate: &rate, AveragePitch: &pitch, Gain: &gain}
|
||||
@@ -34,7 +34,7 @@ func TestSpeechNumbersPersistWithOneDecimal(t *testing.T) {
|
||||
}
|
||||
for index, voice := range []Voice{loaded.DefaultVoice, loaded.UppercaseVoice, loaded.HyperlinkVoice, loaded.SystemVoice, loaded.EchoVoice} {
|
||||
for field, value := range []*float64{voice.Rate, voice.AveragePitch, voice.Gain} {
|
||||
if value != nil && *value != []float64{61.3, 4.5, 5}[field] {
|
||||
if value != nil && *value != []float64{61, 4, 5}[field] {
|
||||
t.Fatalf("voice %d field %d = %g", index, field, *value)
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,8 @@ func TestSpeechNumbersPersistWithOneDecimal(t *testing.T) {
|
||||
t.Fatal("saving mutated caller's voice")
|
||||
}
|
||||
contents, err := os.ReadFile(path)
|
||||
if err != nil || strings.Contains(string(contents), "999999") || !strings.Contains(string(contents), "average-pitch = 4.5") {
|
||||
t.Fatalf("TOML does not contain rounded decimal values: %v", err)
|
||||
if err != nil || strings.Contains(string(contents), "999999") || !strings.Contains(string(contents), "average-pitch = 4.0") {
|
||||
t.Fatalf("TOML does not contain rounded whole values: %v", err)
|
||||
}
|
||||
if err := store.SaveForApplication("Example Editor", settings); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -70,16 +70,16 @@ func TestSpeechNumbersPersistWithOneDecimal(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
application, found, err := store.LoadForApplication("Example Editor")
|
||||
if err != nil || !found || *application.DefaultVoice.Gain != 3.3 {
|
||||
if err != nil || !found || *application.DefaultVoice.Gain != 3 {
|
||||
t.Fatalf("application speech was not rounded: %+v, %v", application.DefaultVoice, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVoiceTypesPersistAndInheritAcrossApplications(t *testing.T) {
|
||||
settings := DefaultSettings()
|
||||
rate, pitch, gain := 62.0, 8.0, 4.0
|
||||
rate, pitch, gain := 62.0, 30.0, 4.0
|
||||
settings.DefaultVoice = Voice{Rate: &rate, AveragePitch: &pitch, Gain: &gain, Family: &VoiceFamily{Name: "Default person", Lang: "en"}}
|
||||
upper, link, system := 8.5, 3.0, 2.0
|
||||
upper, link, system := 85.0, 30.0, 20.0
|
||||
settings.UppercaseVoice.AveragePitch = &upper
|
||||
settings.HyperlinkVoice.Rate = &link
|
||||
settings.SystemVoice.Gain = &system
|
||||
@@ -104,21 +104,21 @@ func TestVoiceTypesPersistAndInheritAcrossApplications(t *testing.T) {
|
||||
t.Fatal("indentation mode lost")
|
||||
}
|
||||
appSettings := loaded
|
||||
appPitch := 5.0
|
||||
appPitch := 50.0
|
||||
appSettings.UppercaseVoice.AveragePitch = &appPitch
|
||||
if err := store.SaveForApplication("example-app", appSettings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
application, found, err := store.LoadForApplication("example-app")
|
||||
if err != nil || !found || *EffectiveVoice(application, "uppercase").AveragePitch != 5 {
|
||||
if err != nil || !found || *EffectiveVoice(application, "uppercase").AveragePitch != 50 {
|
||||
t.Fatalf("application voice = %+v, %v", application.UppercaseVoice, err)
|
||||
}
|
||||
global, err := store.Load()
|
||||
if err != nil || *EffectiveVoice(global, "uppercase").AveragePitch != 8.5 {
|
||||
if err != nil || *EffectiveVoice(global, "uppercase").AveragePitch != 85 {
|
||||
t.Fatal("application voice changed global voice")
|
||||
}
|
||||
*store.Current().UppercaseVoice.AveragePitch = 0
|
||||
if *store.Current().UppercaseVoice.AveragePitch != 8.5 {
|
||||
if *store.Current().UppercaseVoice.AveragePitch != 85 {
|
||||
t.Fatal("voice snapshots alias")
|
||||
}
|
||||
appSettings.UppercaseVoice = Voice{}
|
||||
@@ -126,20 +126,20 @@ func TestVoiceTypesPersistAndInheritAcrossApplications(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
application, found, err = store.LoadForApplication("example-app")
|
||||
if err != nil || !found || application.UppercaseVoice.AveragePitch != nil || *EffectiveVoice(application, "uppercase").AveragePitch != 9 {
|
||||
if err != nil || !found || application.UppercaseVoice.AveragePitch != nil || *EffectiveVoice(application, "uppercase").AveragePitch != 70 {
|
||||
t.Fatalf("application automatic pitch reset = %+v, %v", application.UppercaseVoice, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomaticUppercasePitchAndExplicitOverride(t *testing.T) {
|
||||
settings := DefaultSettings()
|
||||
for _, tc := range []struct{ normal, upper float64 }{{3, 7}, {5, 7}, {7, 9}, {8, 9}, {9, 9}} {
|
||||
for _, tc := range []struct{ normal, upper float64 }{{-100, 50}, {0, 50}, {10, 50}, {20, 60}, {50, 90}, {90, 100}, {100, 100}} {
|
||||
settings.DefaultVoice.AveragePitch = &tc.normal
|
||||
if got := *EffectiveVoice(settings, "uppercase").AveragePitch; got != tc.upper {
|
||||
t.Fatalf("normal %g: uppercase %g, want %g", tc.normal, got, tc.upper)
|
||||
}
|
||||
}
|
||||
chosen := 6.0
|
||||
chosen := 60.0
|
||||
settings.UppercaseVoice.AveragePitch = &chosen
|
||||
if *EffectiveVoice(settings, "uppercase").AveragePitch != chosen {
|
||||
t.Fatal("explicit uppercase pitch ignored")
|
||||
@@ -149,3 +149,129 @@ func TestAutomaticUppercasePitchAndExplicitOverride(t *testing.T) {
|
||||
t.Fatal("invalid indentation mode accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaTwoVoicesMigrateToSpeechDispatcherScale(t *testing.T) {
|
||||
contents := `schema-version = 2
|
||||
active-profile = "default"
|
||||
[applications]
|
||||
"Example Editor" = "editor"
|
||||
[profiles.default.speech.default-voice]
|
||||
rate = 50.0
|
||||
average-pitch = 5.0
|
||||
gain = 9.0
|
||||
[profiles.default.speech.uppercase-voice]
|
||||
average-pitch = 7.0
|
||||
[profiles.default.key-echo.voice]
|
||||
rate = 100.0
|
||||
gain = 10.0
|
||||
[profiles.editor.speech.default-voice]
|
||||
rate = 0.0
|
||||
`
|
||||
path := filepath.Join(t.TempDir(), "settings.toml")
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := NewStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, err := store.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, check := range []struct {
|
||||
name string
|
||||
got *float64
|
||||
want float64
|
||||
}{
|
||||
{"default rate", settings.DefaultVoice.Rate, 2},
|
||||
{"default pitch", settings.DefaultVoice.AveragePitch, 10},
|
||||
{"default gain", settings.DefaultVoice.Gain, 100},
|
||||
{"uppercase pitch", settings.UppercaseVoice.AveragePitch, 50},
|
||||
{"echo rate", settings.EchoVoice.Rate, 100},
|
||||
{"echo gain", settings.EchoVoice.Gain, 100},
|
||||
} {
|
||||
if check.got == nil || *check.got != check.want {
|
||||
t.Fatalf("%s = %v, want %g", check.name, check.got, check.want)
|
||||
}
|
||||
}
|
||||
application, found, err := store.LoadForApplication("Example Editor")
|
||||
if err != nil || !found || *application.DefaultVoice.Rate != -98 {
|
||||
t.Fatalf("application profile was not migrated: %+v, %v", application.DefaultVoice, err)
|
||||
}
|
||||
if err := store.Save(settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := os.ReadFile(path)
|
||||
if err != nil || !strings.Contains(string(saved), "schema-version = 3") {
|
||||
t.Fatalf("migrated settings were not saved as schema 3: %v", err)
|
||||
}
|
||||
reloaded, err := store.Load()
|
||||
if err != nil || *reloaded.DefaultVoice.Rate != 2 {
|
||||
t.Fatalf("schema 3 values were migrated twice: %v, %v", reloaded.DefaultVoice.Rate, err)
|
||||
}
|
||||
// The editor profile is preserved on save and still holds its migrated value.
|
||||
application, _, err = store.LoadForApplication("Example Editor")
|
||||
if err != nil || *application.DefaultVoice.Rate != -98 {
|
||||
t.Fatalf("application profile after save: %+v, %v", application.DefaultVoice, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyFormulasRoundTripForRemoteAPI(t *testing.T) {
|
||||
for field, legacy := range []float64{50, 5, 9} {
|
||||
if got := LegacyFromSpeech(field, SpeechFromLegacy(field, legacy)); got != legacy {
|
||||
t.Fatalf("field %d: %g round-tripped to %g", field, legacy, got)
|
||||
}
|
||||
}
|
||||
if SpeechFromLegacy(VoiceRate, 1000) != 100 || LegacyFromSpeech(VoiceGain, -100) != 0 {
|
||||
t.Fatal("conversions were not clamped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyHardwareVoicesKeepTheirScale(t *testing.T) {
|
||||
contents := `schema-version = 2
|
||||
active-profile = "default"
|
||||
[applications]
|
||||
"Example Editor" = "editor"
|
||||
[profiles.default.speech]
|
||||
server-factory = "hardwarefactory"
|
||||
output-module = "doubletalk"
|
||||
hardware-device = "/dev/fixture-synth"
|
||||
[profiles.default.speech.default-voice]
|
||||
rate = 0
|
||||
average-pitch = 0
|
||||
gain = 0
|
||||
[profiles.default.key-echo.voice]
|
||||
rate = 50
|
||||
[profiles.editor.speech.default-voice]
|
||||
average-pitch = 4.5
|
||||
`
|
||||
path := writeConfig(t, contents)
|
||||
store, err := NewStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, err := store.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, value := range []*float64{settings.DefaultVoice.Rate, settings.DefaultVoice.AveragePitch, settings.DefaultVoice.Gain} {
|
||||
if value == nil || *value != -100 {
|
||||
t.Fatal("hardware minimum changed", value)
|
||||
}
|
||||
}
|
||||
if *settings.EchoVoice.Rate != 2 {
|
||||
t.Fatal("echo did not retain SSIP scale")
|
||||
}
|
||||
application, found, err := store.LoadForApplication("Example Editor")
|
||||
if err != nil || !found || *application.DefaultVoice.AveragePitch != 0 {
|
||||
t.Fatal(application.DefaultVoice, err)
|
||||
}
|
||||
if err := store.Save(settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reloaded, err := store.Load()
|
||||
if err != nil || *reloaded.DefaultVoice.Gain != -100 {
|
||||
t.Fatal(reloaded.DefaultVoice, err)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ const (
|
||||
SelectNextSpeechSetting Command = "select-next-speech-setting"
|
||||
DecreaseSpeechSetting Command = "decrease-speech-setting"
|
||||
IncreaseSpeechSetting Command = "increase-speech-setting"
|
||||
SelectPreviousSpeechCategory Command = "select-previous-speech-category"
|
||||
SelectNextSpeechCategory Command = "select-next-speech-category"
|
||||
SaveSpeechSettings Command = "save-speech-settings"
|
||||
PresentTime Command = "present-time"
|
||||
PresentDate Command = "present-date"
|
||||
@@ -168,6 +170,7 @@ const (
|
||||
leftShiftKeySymbol uint32 = 0xffe1
|
||||
rightShiftKeySymbol uint32 = 0xffe2
|
||||
controlModifier uint16 = 1 << 2
|
||||
altModifier uint16 = 1 << 3
|
||||
)
|
||||
|
||||
type CommandChord struct {
|
||||
@@ -236,8 +239,10 @@ func DefaultCommandBindings(layout KeyboardLayout) CommandBindings {
|
||||
{Symbol: 'f', CthulhuModifier: true}: PresentCharacterAttributes,
|
||||
{Symbol: upKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectParent,
|
||||
{Symbol: downKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectFirstChild,
|
||||
{Symbol: leftKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectPreviousSibling,
|
||||
{Symbol: rightKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectNextSibling,
|
||||
{Symbol: leftKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: SelectPreviousSpeechCategory,
|
||||
{Symbol: rightKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: SelectNextSpeechCategory,
|
||||
{Symbol: leftKeySymbol, Modifiers: altModifier, CthulhuModifier: true}: ObjectPreviousSibling,
|
||||
{Symbol: rightKeySymbol, Modifiers: altModifier, CthulhuModifier: true}: ObjectNextSibling,
|
||||
}
|
||||
for index := 0; index < 12; index++ {
|
||||
bindings[CommandChord{Symbol: 0xffbe + uint32(index), CthulhuModifier: true}] = MessageCommand(index, false)
|
||||
|
||||
@@ -221,25 +221,30 @@ func TestWhereAmIBindingsAreLayoutSpecific(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestObjectNavigationBindingsMatchPython(t *testing.T) {
|
||||
// Python used Control for all four; siblings moved to Alt so Control+Left/Right
|
||||
// can switch quick settings categories as in Fenrir.
|
||||
tests := []struct {
|
||||
symbol uint32
|
||||
command Command
|
||||
symbol uint32
|
||||
modifiers uint16
|
||||
command Command
|
||||
}{
|
||||
{upKeySymbol, ObjectParent},
|
||||
{downKeySymbol, ObjectFirstChild},
|
||||
{leftKeySymbol, ObjectPreviousSibling},
|
||||
{rightKeySymbol, ObjectNextSibling},
|
||||
{upKeySymbol, controlModifier, ObjectParent},
|
||||
{downKeySymbol, controlModifier, ObjectFirstChild},
|
||||
{leftKeySymbol, altModifier, ObjectPreviousSibling},
|
||||
{rightKeySymbol, altModifier, ObjectNextSibling},
|
||||
{leftKeySymbol, controlModifier, SelectPreviousSpeechCategory},
|
||||
{rightKeySymbol, controlModifier, SelectNextSpeechCategory},
|
||||
}
|
||||
for _, test := range tests {
|
||||
router := NewCommandRouter([]uint32{0xff63}, DefaultCommandBindings(DesktopKeyboardLayout))
|
||||
router.Handle(0xff63, 118, 0, true)
|
||||
if consumed, command := router.Handle(test.symbol, 111, controlModifier, true); !consumed || command != test.command {
|
||||
if consumed, command := router.Handle(test.symbol, 111, test.modifiers, true); !consumed || command != test.command {
|
||||
t.Fatalf("symbol %#x press = %v %q", test.symbol, consumed, command)
|
||||
}
|
||||
if consumed, command := router.Handle(test.symbol, 111, controlModifier, false); !consumed || command != "" {
|
||||
if consumed, command := router.Handle(test.symbol, 111, test.modifiers, false); !consumed || command != "" {
|
||||
t.Fatalf("symbol %#x release = %v %q", test.symbol, consumed, command)
|
||||
}
|
||||
if consumed, command := router.Handle(0xff63, 118, controlModifier, false); !consumed || command != "" {
|
||||
if consumed, command := router.Handle(0xff63, 118, test.modifiers, false); !consumed || command != "" {
|
||||
t.Fatalf("symbol %#x modifier release = %v %q, want %q", test.symbol, consumed, command, Command(""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,9 +81,9 @@ func (session *uiSession) setEchoVoice(values Values) {
|
||||
value *float64
|
||||
fallback float64
|
||||
}{
|
||||
{"echoRateScale", values.EchoVoice.Rate, voiceFallback(values.Rate, 50)},
|
||||
{"echoPitchScale", values.EchoVoice.AveragePitch, voiceFallback(values.Pitch, 5)},
|
||||
{"echoVolumeScale", values.EchoVoice.Gain, voiceFallback(values.Volume, 10)},
|
||||
{"echoRateScale", values.EchoVoice.Rate, voiceFallback(values.Rate, 0)},
|
||||
{"echoPitchScale", values.EchoVoice.AveragePitch, voiceFallback(values.Pitch, 0)},
|
||||
{"echoVolumeScale", values.EchoVoice.Gain, voiceFallback(values.Volume, 100)},
|
||||
} {
|
||||
id := C.CString(item.id)
|
||||
C.prefs_range_set(id, C.double(voiceFallback(item.value, item.fallback)))
|
||||
@@ -143,7 +143,7 @@ func (session *uiSession) getEchoVoice() (config.Voice, string) {
|
||||
{"echoRateScale", &voice.Rate}, {"echoPitchScale", &voice.AveragePitch}, {"echoVolumeScale", &voice.Gain},
|
||||
} {
|
||||
id := C.CString(item.id)
|
||||
value := math.Round(float64(C.prefs_number_value(id))*10) / 10
|
||||
value := math.Round(float64(C.prefs_number_value(id)))
|
||||
C.free(unsafe.Pointer(id))
|
||||
*item.target = &value
|
||||
}
|
||||
|
||||
@@ -119,10 +119,10 @@ static gboolean voice_scale_key_press(GtkWidget *control, GdkEventKey *event, gp
|
||||
if (event->state & gtk_accelerator_get_default_mod_mask()) return FALSE;
|
||||
double step;
|
||||
switch (event->keyval) {
|
||||
case GDK_KEY_Up: case GDK_KEY_KP_Up: step = 1.0; break;
|
||||
case GDK_KEY_Down: case GDK_KEY_KP_Down: step = -1.0; break;
|
||||
case GDK_KEY_Right: case GDK_KEY_KP_Right: step = 0.1; break;
|
||||
case GDK_KEY_Left: case GDK_KEY_KP_Left: step = -0.1; break;
|
||||
case GDK_KEY_Up: case GDK_KEY_KP_Up: step = 10.0; break;
|
||||
case GDK_KEY_Down: case GDK_KEY_KP_Down: step = -10.0; break;
|
||||
case GDK_KEY_Right: case GDK_KEY_KP_Right: step = 1.0; break;
|
||||
case GDK_KEY_Left: case GDK_KEY_KP_Left: step = -1.0; break;
|
||||
default: return FALSE;
|
||||
}
|
||||
// GtkRange clamps at the adjustment's bounds and emits value-changed,
|
||||
@@ -195,7 +195,7 @@ int prefs_init(const char *xml) {
|
||||
GtkWidget *control = prefs_widget(voiceScales[i]);
|
||||
g_signal_connect(control, "key-press-event", G_CALLBACK(voice_scale_key_press), NULL);
|
||||
atk_object_set_description(gtk_widget_get_accessible(control),
|
||||
"Up and Down change by 1; Left and Right change by 0.1.");
|
||||
"Up and Down change by 10; Left and Right change by 1.");
|
||||
}
|
||||
for (unsigned i = 0; i < G_N_ELEMENTS(echoControls); i++)
|
||||
g_signal_connect(prefs_widget(echoControls[i]), i < 3 ? "value-changed" : "changed",
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
<interface>
|
||||
<requires lib="gtk+" version="3.20" />
|
||||
<object class="GtkAdjustment" id="rate_adjustment">
|
||||
<property name="lower">0</property>
|
||||
<property name="upper">99</property>
|
||||
<property name="step-increment">0.1</property>
|
||||
<property name="page-increment">5</property>
|
||||
<property name="lower">-100</property>
|
||||
<property name="upper">100</property>
|
||||
<property name="step-increment">1</property>
|
||||
<property name="page-increment">10</property>
|
||||
</object>
|
||||
<object class="GtkAdjustment" id="pitch_adjustment">
|
||||
<property name="lower">0</property>
|
||||
<property name="upper">9</property>
|
||||
<property name="step-increment">0.1</property>
|
||||
<property name="page-increment">1</property>
|
||||
<property name="lower">-100</property>
|
||||
<property name="upper">100</property>
|
||||
<property name="step-increment">1</property>
|
||||
<property name="page-increment">10</property>
|
||||
</object>
|
||||
<object class="GtkAdjustment" id="volume_adjustment">
|
||||
<property name="lower">0</property>
|
||||
<property name="upper">9</property>
|
||||
<property name="step-increment">0.1</property>
|
||||
<property name="page-increment">1</property>
|
||||
<property name="lower">-100</property>
|
||||
<property name="upper">100</property>
|
||||
<property name="step-increment">1</property>
|
||||
<property name="page-increment">10</property>
|
||||
</object>
|
||||
<object class="GtkAdjustment" id="echo_rate_adjustment"><property name="lower">0</property><property name="upper">100</property><property name="step-increment">0.1</property><property name="page-increment">1</property></object>
|
||||
<object class="GtkAdjustment" id="echo_pitch_adjustment"><property name="lower">0</property><property name="upper">10</property><property name="step-increment">0.1</property><property name="page-increment">1</property></object>
|
||||
<object class="GtkAdjustment" id="echo_volume_adjustment"><property name="lower">0</property><property name="upper">10</property><property name="step-increment">0.1</property><property name="page-increment">1</property></object>
|
||||
<object class="GtkAdjustment" id="echo_rate_adjustment"><property name="lower">-100</property><property name="upper">100</property><property name="step-increment">1</property><property name="page-increment">10</property></object>
|
||||
<object class="GtkAdjustment" id="echo_pitch_adjustment"><property name="lower">-100</property><property name="upper">100</property><property name="step-increment">1</property><property name="page-increment">10</property></object>
|
||||
<object class="GtkAdjustment" id="echo_volume_adjustment"><property name="lower">-100</property><property name="upper">100</property><property name="step-increment">1</property><property name="page-increment">10</property></object>
|
||||
<object class="GtkAdjustment" id="sound_volume_adjustment"><property name="lower">0</property><property name="upper">1</property><property name="value">0.5</property><property name="step-increment">0.05</property><property name="page-increment">0.1</property></object>
|
||||
<object class="GtkAdjustment" id="braille_flash_adjustment"><property name="lower">0</property><property name="upper">60</property><property name="value">5</property><property name="step-increment">1</property><property name="page-increment">5</property></object>
|
||||
<object class="GtkAdjustment" id="speech_history_limit_adjustment"><property name="lower">1</property><property name="upper">1000</property><property name="value">50</property><property name="step-increment">1</property><property name="page-increment">10</property></object>
|
||||
@@ -116,11 +116,11 @@
|
||||
<child><object class="GtkComboBoxText" id="voiceTypesCombo"><property name="can-focus">False</property><items><item>Default</item><item>Uppercase</item><item>Hyperlink</item><item>System</item></items></object><packing><property name="left-attach">1</property><property name="top-attach">4</property></packing></child>
|
||||
<child><object class="GtkLabel"><property name="label">_Voice type:</property><property name="use-underline">True</property><property name="mnemonic-widget">voiceTypesCombo</property><property name="xalign">1</property></object><packing><property name="left-attach">0</property><property name="top-attach">4</property></packing></child>
|
||||
<child><object class="GtkLabel" id="volume_label"><property name="label">Vo_lume:</property><property name="use-underline">True</property><property name="mnemonic-widget">volume</property><property name="xalign">1</property></object><packing><property name="left-attach">0</property><property name="top-attach">5</property></packing></child>
|
||||
<child><object class="GtkScale" id="volume"><property name="adjustment">volume_adjustment</property><property name="can-focus">True</property><property name="digits">1</property><property name="hexpand">True</property><property name="value-pos">right</property></object><packing><property name="left-attach">1</property><property name="top-attach">5</property></packing></child>
|
||||
<child><object class="GtkScale" id="volume"><property name="adjustment">volume_adjustment</property><property name="can-focus">True</property><property name="digits">0</property><property name="hexpand">True</property><property name="value-pos">right</property></object><packing><property name="left-attach">1</property><property name="top-attach">5</property></packing></child>
|
||||
<child><object class="GtkLabel" id="pitch_label"><property name="label">Pi_tch:</property><property name="use-underline">True</property><property name="mnemonic-widget">pitch</property><property name="xalign">1</property></object><packing><property name="left-attach">0</property><property name="top-attach">6</property></packing></child>
|
||||
<child><object class="GtkScale" id="pitch"><property name="adjustment">pitch_adjustment</property><property name="can-focus">True</property><property name="digits">1</property><property name="hexpand">True</property><property name="value-pos">right</property></object><packing><property name="left-attach">1</property><property name="top-attach">6</property></packing></child>
|
||||
<child><object class="GtkScale" id="pitch"><property name="adjustment">pitch_adjustment</property><property name="can-focus">True</property><property name="digits">0</property><property name="hexpand">True</property><property name="value-pos">right</property></object><packing><property name="left-attach">1</property><property name="top-attach">6</property></packing></child>
|
||||
<child><object class="GtkLabel" id="rate_label"><property name="label">_Rate:</property><property name="use-underline">True</property><property name="mnemonic-widget">rate</property><property name="xalign">1</property></object><packing><property name="left-attach">0</property><property name="top-attach">7</property></packing></child>
|
||||
<child><object class="GtkScale" id="rate"><property name="adjustment">rate_adjustment</property><property name="can-focus">True</property><property name="digits">1</property><property name="hexpand">True</property><property name="value-pos">right</property></object><packing><property name="left-attach">1</property><property name="top-attach">7</property></packing></child>
|
||||
<child><object class="GtkScale" id="rate"><property name="adjustment">rate_adjustment</property><property name="can-focus">True</property><property name="digits">0</property><property name="hexpand">True</property><property name="value-pos">right</property></object><packing><property name="left-attach">1</property><property name="top-attach">7</property></packing></child>
|
||||
<child><object class="GtkFrame" id="capitalLettersFrame"><property name="label">Capital letters</property><child><object class="GtkBox"><property name="orientation">vertical</property><property name="spacing">6</property><property name="border-width">8</property>
|
||||
<child><object class="GtkCheckButton" id="raisePitchForCapitals"><property name="label">Raise pitch for capital letters</property><property name="can-focus">True</property></object></child>
|
||||
<child><object class="GtkCheckButton" id="beepForCapitals"><property name="label">Beep for capital letters</property><property name="can-focus">True</property></object></child>
|
||||
@@ -222,9 +222,9 @@
|
||||
<child><object class="GtkComboBoxText" id="echoSpeechServers"><property name="can-focus">False</property><items><item>Default</item></items></object></child>
|
||||
<child><object class="GtkLabel"><property name="label">Voice</property><property name="mnemonic-widget">echoSpeechFamilies</property><property name="xalign">0</property></object></child>
|
||||
<child><object class="GtkComboBoxText" id="echoSpeechFamilies"><property name="can-focus">False</property><items><item>Default</item></items></object></child>
|
||||
<child><object class="GtkScale" id="echoRateScale"><property name="digits">1</property><property name="adjustment">echo_rate_adjustment</property><property name="can-focus">True</property><property name="hexpand">True</property><property name="tooltip-text">Key echo rate</property></object></child>
|
||||
<child><object class="GtkScale" id="echoPitchScale"><property name="digits">1</property><property name="adjustment">echo_pitch_adjustment</property><property name="can-focus">True</property><property name="hexpand">True</property><property name="tooltip-text">Key echo pitch</property></object></child>
|
||||
<child><object class="GtkScale" id="echoVolumeScale"><property name="digits">1</property><property name="adjustment">echo_volume_adjustment</property><property name="can-focus">True</property><property name="hexpand">True</property><property name="tooltip-text">Key echo volume</property></object></child>
|
||||
<child><object class="GtkScale" id="echoRateScale"><property name="digits">0</property><property name="adjustment">echo_rate_adjustment</property><property name="can-focus">True</property><property name="hexpand">True</property><property name="tooltip-text">Key echo rate</property></object></child>
|
||||
<child><object class="GtkScale" id="echoPitchScale"><property name="digits">0</property><property name="adjustment">echo_pitch_adjustment</property><property name="can-focus">True</property><property name="hexpand">True</property><property name="tooltip-text">Key echo pitch</property></object></child>
|
||||
<child><object class="GtkScale" id="echoVolumeScale"><property name="digits">0</property><property name="adjustment">echo_volume_adjustment</property><property name="can-focus">True</property><property name="hexpand">True</property><property name="tooltip-text">Key echo volume</property></object></child>
|
||||
<child><object class="GtkFrame"><property name="label">Use the custom voice for:</property><child><object class="GtkBox"><property name="orientation">vertical</property><property name="spacing">7</property><property name="border-width">8</property>
|
||||
<child><object class="GtkCheckButton" id="useCustomEchoForKeyCheckButton"><property name="label">Key names</property><property name="can-focus">True</property></object></child>
|
||||
<child><object class="GtkCheckButton" id="useCustomEchoForCharacterCheckButton"><property name="label">Typed characters</property><property name="can-focus">True</property></object></child>
|
||||
|
||||
@@ -25,9 +25,9 @@ func TestSpeechValuesMergeRoundsNumbersAndPreservesInheritance(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if *merged.DefaultVoice.Rate != 61.3 || *merged.DefaultVoice.AveragePitch != 4.5 || *merged.DefaultVoice.Gain != 5 ||
|
||||
*merged.UppercaseVoice.AveragePitch != 4.5 || *merged.HyperlinkVoice.Rate != 61.3 || *merged.SystemVoice.Gain != 5 ||
|
||||
*merged.EchoVoice.Rate != 61.3 || *merged.EchoVoice.AveragePitch != 4.5 || *merged.EchoVoice.Gain != 5 {
|
||||
if *merged.DefaultVoice.Rate != 61 || *merged.DefaultVoice.AveragePitch != 4 || *merged.DefaultVoice.Gain != 5 ||
|
||||
*merged.UppercaseVoice.AveragePitch != 4 || *merged.HyperlinkVoice.Rate != 61 || *merged.SystemVoice.Gain != 5 ||
|
||||
*merged.EchoVoice.Rate != 61 || *merged.EchoVoice.AveragePitch != 4 || *merged.EchoVoice.Gain != 5 {
|
||||
t.Fatal("speech values retained floating-point noise")
|
||||
}
|
||||
if merged.UppercaseVoice.Rate != nil || merged.HyperlinkVoice.Gain != nil || merged.SystemVoice.AveragePitch != nil {
|
||||
@@ -36,7 +36,7 @@ func TestSpeechValuesMergeRoundsNumbersAndPreservesInheritance(t *testing.T) {
|
||||
if pitch != 4.499999999999998 {
|
||||
t.Fatal("merging mutated caller's values")
|
||||
}
|
||||
for _, invalid := range []float64{9.01, -0.01, math.NaN(), math.Inf(1)} {
|
||||
for _, invalid := range []float64{101, -101, math.NaN(), math.Inf(1)} {
|
||||
values.Pitch = &invalid
|
||||
if _, err := values.Merge(settings); err == nil {
|
||||
t.Fatalf("rounding hid invalid pitch %g", invalid)
|
||||
|
||||
@@ -300,18 +300,16 @@ func set_speech_numbers(values Values, inherited config.Voice, defaults speech.S
|
||||
value *float64
|
||||
inherited *float64
|
||||
server *int
|
||||
scale float64
|
||||
offset float64
|
||||
fallback float64
|
||||
}{
|
||||
{"rate", values.Rate, inherited.Rate, defaults.Rate, 2, 98, 50},
|
||||
{"pitch", values.Pitch, inherited.AveragePitch, defaults.Pitch, 20, 90, 5},
|
||||
{"volume", values.Volume, inherited.Gain, defaults.Volume, 15, 35, 5},
|
||||
{"rate", values.Rate, inherited.Rate, defaults.Rate, 0},
|
||||
{"pitch", values.Pitch, inherited.AveragePitch, defaults.Pitch, 0},
|
||||
{"volume", values.Volume, inherited.Gain, defaults.Volume, 100},
|
||||
} {
|
||||
id := C.CString(item.id)
|
||||
value := item.fallback
|
||||
if item.server != nil {
|
||||
value = math.Round((float64(*item.server)+item.offset)/item.scale*10) / 10
|
||||
value = float64(*item.server)
|
||||
}
|
||||
if item.inherited != nil {
|
||||
value = *item.inherited
|
||||
@@ -413,19 +411,18 @@ func (session *uiSession) read_voice_editor() (config.Voice, error) {
|
||||
for _, item := range []struct {
|
||||
id string
|
||||
target **float64
|
||||
max float64
|
||||
}{
|
||||
{"rate", &voice.Rate, 99}, {"pitch", &voice.AveragePitch, 9}, {"volume", &voice.Gain, 9},
|
||||
{"rate", &voice.Rate}, {"pitch", &voice.AveragePitch}, {"volume", &voice.Gain},
|
||||
} {
|
||||
id := C.CString(item.id)
|
||||
edited := C.prefs_number_edited(id) != 0
|
||||
value := math.Round(float64(C.prefs_number_value(id))*10) / 10
|
||||
value := math.Round(float64(C.prefs_number_value(id)))
|
||||
C.free(unsafe.Pointer(id))
|
||||
if !edited {
|
||||
continue
|
||||
}
|
||||
if !(value >= 0 && value <= item.max) {
|
||||
return voice, fmt.Errorf("Enter a %s between 0 and %.0f.", item.id, item.max)
|
||||
if !(value >= -100 && value <= 100) {
|
||||
return voice, fmt.Errorf("Enter a %s between -100 and 100.", item.id)
|
||||
}
|
||||
*item.target = &value
|
||||
}
|
||||
|
||||
@@ -47,20 +47,8 @@ func NewHardware(device, synth string, baud int) (*Hardware, error) {
|
||||
|
||||
func hardware_bytes(synth, text string, voice HardwareVoice) []byte {
|
||||
profile := hardware.Serial(synth == "dectalk")
|
||||
var values [3]*float64
|
||||
for index, value := range []*float64{voice.Rate, voice.Pitch, voice.Volume} {
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
maximum := 9.0
|
||||
if index == 0 {
|
||||
maximum = 99
|
||||
}
|
||||
normalized := hardware.LegacyValue(*value, maximum)
|
||||
values[index] = &normalized
|
||||
}
|
||||
var data []byte
|
||||
for _, command := range profile.Commands(hardware.Parameters{Rate: values[0], Pitch: values[1], Volume: values[2]}) {
|
||||
for _, command := range profile.Commands(hardware.Parameters{Rate: voice.Rate, Pitch: voice.Pitch, Volume: voice.Volume}) {
|
||||
data = append(data, command...)
|
||||
}
|
||||
return append(data, profile.Text(text)...)
|
||||
|
||||
@@ -7,7 +7,8 @@ package speech
|
||||
import "testing"
|
||||
|
||||
func TestHardwareProtocolsUseCommonEncoding(t *testing.T) {
|
||||
rate, pitch, volume := 99.0, 9.0, 9.0
|
||||
// Voices use Speech Dispatcher's -100..100 scale, like the common protocol.
|
||||
rate, pitch, volume := 100.0, 100.0, 100.0
|
||||
voice := HardwareVoice{Rate: &rate, Pitch: &pitch, Volume: &volume}
|
||||
for _, synth := range []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} {
|
||||
want := "\x019S\x0199P\x019VHello !\r"
|
||||
@@ -18,18 +19,18 @@ func TestHardwareProtocolsUseCommonEncoding(t *testing.T) {
|
||||
t.Fatalf("%s: got %q, want %q", synth, got, want)
|
||||
}
|
||||
}
|
||||
rate, pitch, volume = 0, 0, 0
|
||||
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" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
rate, pitch, volume = 49.5, 4.5, 4.5
|
||||
rate, pitch, volume = 0, 0, 0
|
||||
if got := string(hardware_bytes("litetalk", "Middle", voice)); got != "\x014S\x0150P\x014VMiddle\r" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDECtalkUsesCommonMidpointAndFiltersCommands(t *testing.T) {
|
||||
rate, pitch, volume := 49.5, 4.5, 4.5
|
||||
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 {
|
||||
|
||||
@@ -21,7 +21,7 @@ import "strings"
|
||||
|
||||
const Name = "Cthulhu"
|
||||
|
||||
const Version = "2026.11.13"
|
||||
const Version = "2026.11.15"
|
||||
const Channel = "testing"
|
||||
|
||||
var Build = Version
|
||||
|
||||
@@ -349,10 +349,10 @@ lang = "en"
|
||||
check_output(("Tab",), [("Key echo person", "main", ""), ("Default", "echo-b", "")])
|
||||
check_output(("Down",), [("Echo B (en)", "echo-b", "Echo B")])
|
||||
for control in ("rate", "pitch", "volume"):
|
||||
value = "50.0" if control == "rate" else "5.0"
|
||||
value = {"rate": "2", "pitch": "10", "volume": "40"}[control]
|
||||
check_output(("Tab",), [("Key echo " + control, "main", ""), (value, "echo-b", "Echo B")])
|
||||
for control in ("pitch", "rate", "person", "synthesizer"):
|
||||
value = {"pitch": "5.0", "rate": "50.0", "person": "Echo B (en)", "synthesizer": "echo-b"}[control]
|
||||
value = {"pitch": "10", "rate": "2", "person": "Echo B (en)", "synthesizer": "echo-b"}[control]
|
||||
label = "Key echo speech synthesizer" if control == "synthesizer" else "Key echo " + control
|
||||
check_output(("shift+Tab",), [(label, "main", ""), (value, "echo-b", "Echo B")])
|
||||
print(f"PASS: real reader + GTK + SSIP focus/selection previews, voice completion, no duplicate menu-item speech; evidence: {directory}")
|
||||
|
||||
+18
-21
@@ -142,7 +142,7 @@ def inside():
|
||||
initial["Catalog"]["espeak-ng"] = list(initial["Catalog"]["test-module"])
|
||||
if os.environ.get("CTHULHU_PREFS_NUMBERS_ONLY") == "1":
|
||||
initial["Values"].update(UseCustomEchoVoice=True,
|
||||
EchoVoice={"Rate": 50, "AveragePitch": 5, "Gain": 5})
|
||||
EchoVoice={"Rate": 50, "AveragePitch": 50, "Gain": 50})
|
||||
if os.environ.get("CTHULHU_PREFS_LARGE_CATALOG") == "1":
|
||||
initial["Catalog"]["espeak-ng"].extend(
|
||||
{"Name": f"Test voice {index}", "Language": "en" if index < 100 else "de", "Variant": "none"}
|
||||
@@ -632,17 +632,17 @@ def inside():
|
||||
for name, field in (("Rate", "Rate"), ("Pitch", "Pitch"), ("Volume", "Volume")):
|
||||
slider = next(n for n in nodes if n.getRole() == pyatspi.ROLE_SLIDER and n.name.lower().rstrip(":") == name.lower())
|
||||
focus(slider)
|
||||
assert abs(slider.queryValue().minimumIncrement - 0.1) < 1e-8, (name, "accessible increment")
|
||||
assert abs(slider.queryValue().minimumIncrement - 1) < 1e-8, (name, "accessible increment")
|
||||
startValue = slider.queryValue().currentValue
|
||||
for arrow, delta in (("Right", 0.1), ("Up", 1), ("Left", -0.1), ("Down", -1), ("Left", -0.1)):
|
||||
for arrow, delta in (("Right", 1), ("Up", 10), ("Left", -1), ("Down", -10), ("Left", -1)):
|
||||
expected = startValue + delta
|
||||
key(arrow)
|
||||
values = accept_preview()
|
||||
assert abs(slider.queryValue().currentValue - expected) < 1e-8, (name, arrow, expected)
|
||||
assert abs(values[field] - expected) < 1e-8, (name, arrow, values)
|
||||
assert values[field] == round(values[field], 1), (name, "precision", values)
|
||||
assert values[field] == round(values[field]), (name, "precision", values)
|
||||
startValue = expected
|
||||
for bound, arrows in ((0, ("Left", "Down")),
|
||||
for bound, arrows in ((-100, ("Left", "Down")),
|
||||
(slider.queryValue().maximumValue, ("Right", "Up"))):
|
||||
slider.queryValue().currentValue = bound
|
||||
accept_preview()
|
||||
@@ -662,20 +662,17 @@ def inside():
|
||||
slider = named(name)
|
||||
focus(slider)
|
||||
echoPreview = {"Rate": "rate", "AveragePitch": "pitch", "Gain": "volume"}[field]
|
||||
assert abs(slider.queryValue().minimumIncrement - 0.1) < 1e-8, (name, "accessible increment")
|
||||
for arrow, expected in (("Right", 5.1 if field != "Rate" else 50.1),
|
||||
("Up", 6.1 if field != "Rate" else 51.1),
|
||||
("Left", 6 if field != "Rate" else 51),
|
||||
("Down", 5 if field != "Rate" else 50),
|
||||
("Left", 4.9 if field != "Rate" else 49.9)):
|
||||
assert abs(slider.queryValue().minimumIncrement - 1) < 1e-8, (name, "accessible increment")
|
||||
# Speech Dispatcher's -100..100 scale: Left/Right step 1, Up/Down step 10.
|
||||
for arrow, expected in (("Right", 51), ("Up", 61), ("Left", 60), ("Down", 50), ("Left", 49)):
|
||||
key(arrow)
|
||||
values = accept_preview(echoPreview)
|
||||
wait_for(lambda: abs(slider.queryValue().currentValue - expected) < 1e-8,
|
||||
f"{name}: {arrow} did not produce {expected}")
|
||||
assert abs(values["EchoVoice"][field] - expected) < 1e-8, values
|
||||
assert values["EchoVoice"][field] == round(values["EchoVoice"][field], 1), (name, "precision", values)
|
||||
assert values["EchoVoice"][field] == round(values["EchoVoice"][field]), (name, "precision", values)
|
||||
finalValue = expected
|
||||
for bound, arrows in ((0, ("Left", "Down")),
|
||||
for bound, arrows in ((-100, ("Left", "Down")),
|
||||
(slider.queryValue().maximumValue, ("Right", "Up"))):
|
||||
slider.queryValue().currentValue = bound
|
||||
accept_preview(echoPreview)
|
||||
@@ -686,19 +683,19 @@ def inside():
|
||||
focus(named("Apply")); key("space")
|
||||
applied = request()
|
||||
assert applied["Save"], applied
|
||||
for field, expected in (("Rate", 49.9), ("Pitch", 4.9), ("Volume", 4.9)):
|
||||
for field, expected in (("Rate", 49), ("Pitch", 4), ("Volume", 4)):
|
||||
assert abs(applied["Values"][field] - expected) < 1e-8, applied
|
||||
assert applied["Values"][field] == round(applied["Values"][field], 1), applied
|
||||
for field, expected in (("Rate", 49.9), ("AveragePitch", 4.9), ("Gain", 4.9)):
|
||||
assert applied["Values"][field] == round(applied["Values"][field]), applied
|
||||
for field, expected in (("Rate", 49), ("AveragePitch", 49), ("Gain", 49)):
|
||||
assert abs(applied["Values"]["EchoVoice"][field] - expected) < 1e-8, applied
|
||||
assert applied["Values"]["EchoVoice"][field] == round(applied["Values"]["EchoVoice"][field], 1), applied
|
||||
assert applied["Values"]["EchoVoice"][field] == round(applied["Values"]["EchoVoice"][field]), applied
|
||||
send(dict(initial, Values=applied["Values"], Message="Speech settings saved."))
|
||||
wait_for(lambda: named("Apply").getState().contains(pyatspi.STATE_SENSITIVE), "Apply busy")
|
||||
for name, expected in (("Key echo rate", 49.9), ("Key echo pitch", 4.9), ("Key echo volume", 4.9)):
|
||||
for name, expected in (("Key echo rate", 49), ("Key echo pitch", 49), ("Key echo volume", 49)):
|
||||
assert abs(named(name).queryValue().currentValue - expected) < 1e-8, name
|
||||
focus(named("Cancel")); key("space")
|
||||
assert process.wait(timeout=2) == 0
|
||||
print("PASS: voice and echo sliders, whole/tenth arrow steps, previews, Tab/Shift+Tab, Apply/reload, Cancel")
|
||||
print("PASS: voice and echo sliders, one and ten arrow steps, previews, Tab/Shift+Tab, Apply/reload, Cancel")
|
||||
return
|
||||
if os.environ.get("CTHULHU_PREFS_APPLY_ONLY") == "1":
|
||||
reading_tree = next(node for node in nodes if node.name == "Reading settings"
|
||||
@@ -1596,7 +1593,7 @@ def inside():
|
||||
# Only one preview may be outstanding. Read and acknowledge each
|
||||
# changed value before moving focus, which discards stale previews.
|
||||
for control, field, value in (("rate", "Rate", 83),
|
||||
("pitch", "AveragePitch", 7.5),
|
||||
("pitch", "AveragePitch", 8),
|
||||
("volume", "Gain", 10)):
|
||||
slider = named("Key echo " + control)
|
||||
focus(slider)
|
||||
@@ -1624,7 +1621,7 @@ def inside():
|
||||
assert ev["ProgressBar"] == expectedProgress, ev
|
||||
assert echo_saved["Save"] and echo_saved["Close"] and ev["EnableKeyEcho"], echo_saved
|
||||
assert ev["UseCustomEchoVoice"] and ev["UseCustomEchoForWord"] and ev["KeyEchoInEditFieldsOnly"], ev
|
||||
assert ev["EchoVoice"]["Rate"] == 83 and ev["EchoVoice"]["AveragePitch"] == 7.5 and ev["EchoVoice"]["Gain"] == 10, ev
|
||||
assert ev["EchoVoice"]["Rate"] == 83 and ev["EchoVoice"]["AveragePitch"] == 8 and ev["EchoVoice"]["Gain"] == 10, ev
|
||||
assert ev["EchoVoice"]["Family"]["Name"] == "Test voice", ev
|
||||
send(dict(initial, Values=ev, Message="Echo voice saved."))
|
||||
wait_for(lambda: named("Apply").getState().contains(pyatspi.STATE_SENSITIVE), "OK stayed busy")
|
||||
|
||||
@@ -45,7 +45,8 @@ def check_no_config(window, tabs, server, configPath):
|
||||
controls = controls_for(window)
|
||||
assert not any(name.startswith(("Use server default", "Use Default voice", "Use automatic uppercase"))
|
||||
for name in controls)
|
||||
expected = {"Rate": 59, "Pitch": 4, "Volume": 9} if server.defaultsSupported else {"Rate": 50, "Pitch": 5, "Volume": 5}
|
||||
# Sliders show Speech Dispatcher's own -100..100 values without conversion.
|
||||
expected = {"Rate": 20, "Pitch": -10, "Volume": 100} if server.defaultsSupported else {"Rate": 0, "Pitch": 0, "Volume": 100}
|
||||
for name, value in expected.items():
|
||||
slider = controls[name]
|
||||
assert slider.getRole() == pyatspi.ROLE_SLIDER, (name, slider.getRoleName())
|
||||
@@ -59,7 +60,7 @@ def check_no_config(window, tabs, server, configPath):
|
||||
|
||||
voiceType = controls["Voice type"]
|
||||
assert voiceType.querySelection().selectChild(1)
|
||||
wait_for(lambda: controls["Pitch"].queryValue().currentValue == 7, "automatic uppercase pitch missing")
|
||||
wait_for(lambda: controls["Pitch"].queryValue().currentValue == 50, "automatic uppercase pitch missing")
|
||||
assert voiceType.querySelection().selectChild(0)
|
||||
wait_for(lambda: controls["Pitch"].queryValue().currentValue == expected["Pitch"], "Default pitch did not return")
|
||||
focus(controls["Apply"]); key("space")
|
||||
@@ -70,11 +71,11 @@ def check_no_config(window, tabs, server, configPath):
|
||||
wait_for(lambda: controls["Apply"].getState().contains(pyatspi.STATE_SENSITIVE), "Apply stayed busy")
|
||||
|
||||
expectedRaw = {}
|
||||
for name, scale, offset in (("Rate", 2, 98), ("Pitch", 20, 90), ("Volume", 15, 35)):
|
||||
for name in ("Rate", "Pitch", "Volume"):
|
||||
slider = controls[name]
|
||||
focus(slider); key("Down" if name == "Volume" else "Up")
|
||||
expected[name] += -1 if name == "Volume" else 1
|
||||
expectedRaw[name.upper()] = int(scale * expected[name] - offset)
|
||||
expected[name] += -10 if name == "Volume" else 10
|
||||
expectedRaw[name.upper()] = expected[name]
|
||||
wait_for(lambda: slider.queryValue().currentValue == expected[name], name + " did not change directly")
|
||||
wait_for(lambda: any(all(record["settings"][field] == value for field, value in expectedRaw.items())
|
||||
for record in server.snapshot()), name + " preview did not reach speech backend")
|
||||
@@ -96,11 +97,11 @@ def check_no_config(window, tabs, server, configPath):
|
||||
for name, value in expected.items():
|
||||
assert controls[name].queryValue().currentValue == value, (name, value)
|
||||
assert controls["Voice type"].querySelection().selectChild(1)
|
||||
wait_for(lambda: controls["Pitch"].queryValue().currentValue == max(7, expected["Pitch"] + 2),
|
||||
wait_for(lambda: controls["Pitch"].queryValue().currentValue == min(100, max(50, expected["Pitch"] + 40)),
|
||||
"untouched Uppercase pitch stopped following Default")
|
||||
assert controls["Voice type"].querySelection().selectChild(0)
|
||||
focus(controls["Rate"]); key("Up")
|
||||
changedRaw = dict(expectedRaw, RATE=expectedRaw["RATE"] + 2)
|
||||
changedRaw = dict(expectedRaw, RATE=expectedRaw["RATE"] + 10)
|
||||
wait_for(lambda: any(record["settings"] == changedRaw for record in server.snapshot()), "unsaved preview missing")
|
||||
focus(controls["Cancel"]); key("space")
|
||||
wait_for(lambda: find_window() is None, "Cancel did not close preferences")
|
||||
|
||||
Reference in new issue
Block a user