diff --git a/README.md b/README.md index 27f31c5..582edf2 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ checks. Leave submission to the contributor after their review and testing. The shared quick menu and validated discovery API are available starting with v0.5.0. Shared translation message ID lists are available starting with v0.6.1. -Both readers pin v0.8.0 for standalone builds. +Readers pin released module versions for standalone builds. ## License @@ -165,6 +165,15 @@ are separate from speaking connections, and ordinary discovery never autostarts a daemon. Startup can honor the invoking sudo user's credentials without changing the reader process's credentials. +Starting with v0.9.0, `Client.RetuneSettings` applies automatic voice changes +on the speaking connection without cancelling queued utterances. Cleared +settings regain the defaults for the same client identity. Explicit modules +are applied after language routing. Unqueryable defaults, including cleared +capitalization, return `ErrRetuneNeedsReconnect` before changing the speaking +connection; callers can use the cancelling `UpdateSettings` path. A failed +multi-client retune can have changed earlier clients, so reader hosts must +restore their previous complete configuration if fallback replacement fails. + Run `go test -race ./speechdispatcher` for protocol and recovery fixtures. `CTHULHU_NATIVE_SPEECH_STARTUP=1 go test -race ./speechdispatcher` additionally starts and restarts private dummy-output daemons; it does not restart the user's @@ -216,8 +225,8 @@ DECtalk encoding. built from `testdata/usb_fixture.c` and need a C compiler, not hardware. The protocol and presentation helpers are available starting with v0.4.0; -`hardware/transport` is available starting with v0.8.0. Both readers pin v0.8.0 -for standalone builds. Verify pinned dependencies with `GOWORK=off`; +`hardware/transport` is available starting with v0.8.0. Readers pin released +module versions for standalone builds. Verify pinned dependencies with `GOWORK=off`; physical keyboard, audible speech, braille, and hardware acceptance remain separate live checks. @@ -236,6 +245,7 @@ settings and never modifies unrelated preferences. `internalui.Session.FocusControl` restores a control when a child editor returns to its parent form. `quicksettings.Option.Literal` preserves user-chosen profile names without translation. These APIs are available starting with v0.6.0; -both readers pin v0.8.0 for standalone builds. Run `go test -race ./...` here and the -consumer settings/speech regressions with `GOWORK=off` in both readers. The +readers pin released module versions for standalone builds. Run +`go test -race ./...` here and the consumer settings/speech regressions with +`GOWORK=off` in both readers. The sibling workspace supports local development without machine-specific replaces. diff --git a/speechdispatcher/defaults.go b/speechdispatcher/defaults.go index 0856cba..456b375 100644 --- a/speechdispatcher/defaults.go +++ b/speechdispatcher/defaults.go @@ -10,18 +10,35 @@ import ( "fmt" "net" "strconv" + "strings" ) // ReadDefaults queries a fresh client, leaving the speaking client's settings // alone. Unsupported or invalid fields stay nil so preferences can use sensible // display values. The caller bounds the entire optional query with a deadline. func ReadDefaults(ctx context.Context, socket string) (Settings, error) { - var defaults Settings endpoint, err := ResolveAddress(socket) if err != nil { - return defaults, err + return Settings{}, err } - conn, err := (&net.Dialer{Timeout: connectTimeout}).DialContext(ctx, endpoint.Network, endpoint.Address) + defaults, err := readServerDefaults(ctx, endpoint.Network, endpoint.Address, "") + return Settings{Rate: defaults.Rate, Pitch: defaults.Pitch, Volume: defaults.Volume}, err +} + +// serverDefaults are the values a fresh connection starts with. Speech +// Dispatcher reports no default synthesis voice, only the voice type that a +// fresh connection resolves to a module voice. +type serverDefaults struct { + Settings + VoiceType string +} + +// readServerDefaults asks a fresh connection for its settings. A client name +// applies the same server-side client defaults as a speaking connection. +// Fields the server does not report stay empty or nil. +func readServerDefaults(ctx context.Context, network, address, clientName string) (serverDefaults, error) { + var defaults serverDefaults + conn, err := (&net.Dialer{Timeout: connectTimeout}).DialContext(ctx, network, address) if err != nil { return defaults, err } @@ -31,27 +48,61 @@ func ReadDefaults(ctx context.Context, socket string) (Settings, error) { return defaults, err } defer finish() - client := &Client{conn: conn, reader: bufio.NewReader(conn)} + client := &Client{conn: conn, reader: bufio.NewReader(conn), ioTimeout: ioTimeout} + if clientName != "" { + if err := client.sendCommand(ctx, []string{"SET", "SELF", "CLIENT_NAME", clientName + ":" + clientName + ":main"}); err != nil { + return defaults, err + } + } + get := func(name string) (string, bool, error) { + if _, err := fmt.Fprintf(conn, "GET %s\r\n", name); err != nil { + return "", false, err + } + response, err := client.readReply() + if err != nil { + return "", false, err + } + if response.code < 200 || response.code >= 300 || len(response.data) != 1 { + return "", false, nil + } + return response.data[0], true, nil + } for _, field := range []struct { name string target **int }{ {"RATE", &defaults.Rate}, {"PITCH", &defaults.Pitch}, {"VOLUME", &defaults.Volume}, } { - if _, err := fmt.Fprintf(conn, "GET %s\r\n", field.name); err != nil { - return defaults, err - } - response, err := client.readReply() + text, ok, err := get(field.name) if err != nil { return defaults, err } - if response.code < 200 || response.code >= 300 || len(response.data) != 1 { + if !ok { continue } - value, err := strconv.Atoi(response.data[0]) + value, err := strconv.Atoi(text) if err == nil && value >= -100 && value <= 100 { *field.target = &value } } + for _, field := range []struct { + name string + target *string + }{ + {"OUTPUT_MODULE", &defaults.OutputModule}, {"LANGUAGE", &defaults.Language}, + {"PUNCTUATION", &defaults.Punctuation}, {"VOICE_TYPE", &defaults.VoiceType}, + } { + text, ok, err := get(field.name) + if err != nil { + return defaults, err + } + if ok && validSSIPField(text) { + *field.target = text + } + } return defaults, nil } + +func validSSIPField(text string) bool { + return text != "" && !strings.ContainsAny(text, " \t\r\n\x00") +} diff --git a/speechdispatcher/retune_native_test.go b/speechdispatcher/retune_native_test.go new file mode 100644 index 0000000..36d5699 --- /dev/null +++ b/speechdispatcher/retune_native_test.go @@ -0,0 +1,119 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package speechdispatcher + +import ( + "context" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func retuneDaemon(t *testing.T, extra string) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "speech-retune-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + socket := filepath.Join(dir, "sd.sock") + configuration := fmt.Sprintf("LogLevel 0\nLogDir %q\nAddModule \"dummy\" \"sd_dummy\" \"\"\nDefaultModule dummy\nTimeout 0\n", dir) + extra + if err := os.WriteFile(filepath.Join(dir, "speechd.conf"), []byte(configuration), 0600); err != nil { + t.Fatal(err) + } + logFile, err := os.Create(filepath.Join(dir, "daemon.log")) + if err != nil { + t.Fatal(err) + } + cmd := exec.Command("speech-dispatcher", "--run-single", "--communication-method", "unix_socket", "--config-dir", dir, "--socket-path", socket, "--pid-file", filepath.Join(dir, "sd.pid")) + cmd.Stdout, cmd.Stderr = logFile, logFile + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); _ = logFile.Close() }) + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + c, err := net.DialTimeout("unix", socket, 50*time.Millisecond) + if err == nil { + c.Close() + return socket + } + time.Sleep(10 * time.Millisecond) + } + data, _ := os.ReadFile(filepath.Join(dir, "daemon.log")) + serverLog, _ := os.ReadFile(filepath.Join(dir, "speech-dispatcher.log")) + t.Fatalf("private daemon did not start: %s\n%s", data, serverLog) + return "" +} + +func TestNativeRetuneClientDefaults(t *testing.T) { + if os.Getenv("CTHULHU_NATIVE_SPEECH_STARTUP") != "1" { + t.Skip("requires isolated Speech Dispatcher startup") + } + path := retuneDaemon(t, "DefaultRate 5\nBeginClient \"reader:*\"\nDefaultRate 65\nDefaultVoiceType FEMALE1\nEndClient\n") + rate := 80 + client := NewWithSettings(path, Settings{ClientName: "reader", Rate: &rate, SynthesisVoice: "Old"}) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + defer client.Close(ctx) + if err := client.RetuneSettings(ctx, Settings{}); err != nil { + t.Fatal(err) + } + actualRate, err := client.fragmentParameter(ctx, "RATE") + if err != nil { + t.Fatal(err) + } + actualVoice, err := client.fragmentParameter(ctx, "VOICE_TYPE") + if err != nil { + t.Fatal(err) + } + fresh := NewWithSettings(path, Settings{ClientName: "reader"}) + if err := fresh.Connect(ctx); err != nil { + t.Fatal(err) + } + defer fresh.Close(ctx) + wantRate, _ := fresh.fragmentParameter(ctx, "RATE") + wantVoice, _ := fresh.fragmentParameter(ctx, "VOICE_TYPE") + if actualRate != wantRate || actualVoice != wantVoice { + t.Fatalf("retuned rate/voice=%s/%s; fresh reader defaults=%s/%s", actualRate, actualVoice, wantRate, wantVoice) + } +} + +func TestNativeRetuneClearedLanguageKeepsModule(t *testing.T) { + if os.Getenv("CTHULHU_NATIVE_SPEECH_STARTUP") != "1" { + t.Skip("requires isolated Speech Dispatcher startup") + } + path := retuneDaemon(t, "DefaultLanguage en\nLanguageDefaultModule en alternate\n") + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + client := NewWithSettings(path, Settings{OutputModule: "dummy", Language: "fr", SynthesisVoice: "Old"}) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + defer client.Close(ctx) + if err := client.RetuneSettings(ctx, Settings{OutputModule: "dummy"}); err != nil { + t.Fatal(err) + } + actual, err := client.fragmentParameter(ctx, "OUTPUT_MODULE") + if err != nil { + t.Fatal(err) + } + fresh := NewWithSettings(path, Settings{OutputModule: "dummy"}) + if err := fresh.Connect(ctx); err != nil { + t.Fatal(err) + } + defer fresh.Close(ctx) + want, _ := fresh.fragmentParameter(ctx, "OUTPUT_MODULE") + if actual != want { + t.Fatalf("retuned module=%s; fresh requested module=%s", actual, want) + } +} diff --git a/speechdispatcher/settings_test.go b/speechdispatcher/settings_test.go index 4cf97ac..14e94c7 100644 --- a/speechdispatcher/settings_test.go +++ b/speechdispatcher/settings_test.go @@ -8,6 +8,7 @@ package speechdispatcher import ( "bufio" "context" + "errors" "fmt" "net" "path/filepath" @@ -256,3 +257,206 @@ func TestUpdateSettingsCanceledContext(t *testing.T) { t.Fatal("canceled update interrupted speech") } } + +func TestRetuneSettingsKeepsQueuedSpeech(t *testing.T) { + path, server := newSettingsServer(t, nil) + rate := 20 + client := NewWithSettings(path, Settings{Rate: &rate, SynthesisVoice: "Old"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Close(ctx) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + if err := client.Speak(ctx, "queued before the change"); err != nil { + t.Fatal(err) + } + newRate := 60 + if err := client.RetuneSettings(ctx, Settings{Rate: &newRate, SynthesisVoice: "New", Language: "en"}); err != nil { + t.Fatal(err) + } + if err := client.Speak(ctx, "spoken with the new voice"); err != nil { + t.Fatal(err) + } + server.mu.Lock() + commands := append([]string(nil), server.commands[1]...) + cancelled := false + for id, history := range server.commands { + for _, command := range history { + if strings.HasPrefix(command, "CANCEL") { + cancelled = true + } + } + if id > 2 { + t.Errorf("retune opened connection %d", id) + } + } + server.mu.Unlock() + if cancelled { + t.Fatal("retune cancelled queued speech") + } + order := strings.Join(commands, "|") + want := "SPEAK|SET SELF RATE 60|SET SELF LANGUAGE en|SET SELF SYNTHESIS_VOICE New|SPEAK" + if !strings.Contains(order, want) { + t.Fatalf("retune commands were not between the two utterances on the speaking connection: %s", order) + } + if client.settings.Rate == nil || *client.settings.Rate != 60 || client.settings.ClientName != "screenreader" { + t.Fatal("retuned settings were not committed for reconnection") + } +} + +func TestRetuneSettingsWithoutServerDefaultRejectsClearedSetting(t *testing.T) { + path, server := newSettingsServer(t, nil) + rate := 20 + client := NewWithSettings(path, Settings{Rate: &rate}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Close(ctx) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + server.mu.Lock() + before := len(server.commands[1]) + server.mu.Unlock() + if err := client.RetuneSettings(ctx, Settings{}); !errors.Is(err, ErrRetuneNeedsReconnect) { + t.Fatalf("clearing rate returned %v", err) + } + server.mu.Lock() + after := len(server.commands[1]) + server.mu.Unlock() + if after != before || client.settings.Rate == nil { + t.Fatal("rejected retune changed the connection or settings") + } +} + +func TestRetuneSettingsUnchangedSendsNothing(t *testing.T) { + path, server := newSettingsServer(t, nil) + rate := 20 + client := NewWithSettings(path, Settings{Rate: &rate}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Close(ctx) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + server.mu.Lock() + before := len(server.commands[1]) + server.mu.Unlock() + same := 20 + if err := client.RetuneSettings(ctx, Settings{Rate: &same}); err != nil { + t.Fatal(err) + } + server.mu.Lock() + after := len(server.commands[1]) + server.mu.Unlock() + if after != before { + t.Fatal("unchanged retune sent commands") + } +} + +func TestRetuneSettingsRestoresClearedSettingsToServerDefaults(t *testing.T) { + path, server := newSettingsServer(t, func(command string) string { + switch command { + case "GET RATE": + return "251-50\r\n251 OK GET RETURNED\r\n" + case "GET OUTPUT_MODULE": + return "251-default\r\n251 OK GET RETURNED\r\n" + case "GET LANGUAGE": + return "251-en\r\n251 OK GET RETURNED\r\n" + case "GET VOICE_TYPE": + return "251-MALE1\r\n251 OK GET RETURNED\r\n" + } + return "" + }) + rate := 82 + client := NewWithSettings(path, Settings{Rate: &rate, Language: "en-us", SynthesisVoice: "Lyubov"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Close(ctx) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + if err := client.Speak(ctx, "queued in the old voice"); err != nil { + t.Fatal(err) + } + if err := client.RetuneSettings(ctx, Settings{}); err != nil { + t.Fatal(err) + } + server.mu.Lock() + speaking := strings.Join(server.commands[1], "|") + for _, history := range server.commands { + for _, command := range history { + if strings.HasPrefix(command, "CANCEL") { + t.Errorf("retune sent %s", command) + } + } + } + server.mu.Unlock() + want := "SPEAK|SET SELF RATE 50|SET SELF LANGUAGE en|SET SELF OUTPUT_MODULE default|SET SELF VOICE_TYPE MALE1" + if !strings.HasSuffix(speaking, want) { + t.Fatalf("cleared settings were not restored in place: %s", speaking) + } + if client.settings.Rate != nil || client.settings.Language != "" || client.settings.SynthesisVoice != "" { + t.Fatal("committed settings did not keep the requested cleared form") + } +} + +func TestRetuneSettingsRejectsUnknownCapitalizationDefault(t *testing.T) { + for _, current := range []string{"spell", "none"} { + t.Run(current, func(t *testing.T) { + path, server := newSettingsServer(t, nil) + client := NewWithSettings(path, Settings{Capitalization: current}) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + defer client.Close(ctx) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + server.mu.Lock() + before := len(server.commands[1]) + server.mu.Unlock() + if err := client.RetuneSettings(ctx, Settings{}); !errors.Is(err, ErrRetuneNeedsReconnect) { + t.Fatalf("clearing capitalization returned %v", err) + } + server.mu.Lock() + after := len(server.commands[1]) + server.mu.Unlock() + if after != before || client.settings.Capitalization != current { + t.Fatal("rejected retune changed active settings") + } + if err := client.Speak(ctx, "previous settings remain usable"); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestRetuneSettingsRejectionReconnectsPreviousConfiguration(t *testing.T) { + path, server := newSettingsServer(t, func(command string) string { + if command == "SET SELF PITCH 40" { + return "500 REJECTED\r\n" + } + return "" + }) + rate := 20 + client := NewWithSettings(path, Settings{Rate: &rate}) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + defer client.Close(ctx) + if err := client.Connect(ctx); err != nil { + t.Fatal(err) + } + newRate, pitch := 60, 40 + if err := client.RetuneSettings(ctx, Settings{Rate: &newRate, Pitch: &pitch}); err == nil { + t.Fatal("rejected retune succeeded") + } + if err := client.Speak(ctx, "previous settings after failure"); err != nil { + t.Fatal(err) + } + if err := client.Cancel(ctx); err != nil { + t.Fatal(err) + } + if !server.saw(3, "SET SELF RATE 20") || server.saw(3, "SET SELF RATE 60") || !server.saw(4, "CANCEL 3") { + t.Fatal("recovery did not restore previous settings and cancellation target") + } +} diff --git a/speechdispatcher/speech.go b/speechdispatcher/speech.go index a40d5bc..a02342c 100644 --- a/speechdispatcher/speech.go +++ b/speechdispatcher/speech.go @@ -161,6 +161,165 @@ func (client *Client) UpdateSettings(ctx context.Context, settings Settings) err return nil } +// ErrRetuneNeedsReconnect reports a configuration the current connection +// cannot reach in place: a setting is being cleared and the server does not +// report the default a fresh connection would use. Callers may fall back to +// UpdateSettings, which cancels. +var ErrRetuneNeedsReconnect = errors.New("speech settings require a fresh connection") + +// RetuneSettings applies a complete configuration to the current speaking +// connection without cancelling anything. Speech Dispatcher applies SET +// commands only to later SPEAK blocks, so utterances already queued keep the +// voice they were queued with and still finish. Use it for automatic changes, +// such as per-application voices, which must not interrupt speech; UpdateSettings +// remains the cancelling path for explicit user changes. +// +// SSIP cannot unset a value, so a setting being cleared is set to the value a +// fresh connection reports instead, and a cleared synthesis voice returns to +// the server's default voice type. When the server does not report a needed +// default, it fails with ErrRetuneNeedsReconnect before sending anything. A +// rejected SET closes the connection; the next Speak reconnects with the +// previous settings. +func (client *Client) RetuneSettings(ctx context.Context, settings Settings) error { + if !client.settingsMutex.TryLock() { + return errors.New("speech settings update already in progress") + } + defer client.settingsMutex.Unlock() + ctx, cancel := context.WithTimeout(ctx, ioTimeout) + defer cancel() + client.mutex.Lock() + defer client.mutex.Unlock() + settings = cloneSettings(settings) + settings.ClientName = client.settings.ClientName + settings.SystemFallback = client.settings.SystemFallback + if sameSettings(client.settings, settings) { + return nil + } + if err := client.ensureConnected(ctx); err != nil { + return err + } + commands := voiceCommands(settings) + if clearsSetting(client.settings, settings) { + address := client.conn.RemoteAddr() + defaults, err := readServerDefaults(ctx, address.Network(), address.String(), settings.ClientName) + if err != nil { + return fmt.Errorf("%w: read server defaults: %w", ErrRetuneNeedsReconnect, err) + } + applied, voiceType, err := restoreClearedSettings(client.settings, settings, defaults) + if err != nil { + return err + } + commands = voiceCommands(applied) + if voiceType != "" { + // VOICE_TYPE discards the named voice without changing language. + commands = append(commands, []string{"SET", "SELF", "VOICE_TYPE", voiceType}) + } + } + for _, command := range commands { + if err := client.sendCommand(ctx, command); err != nil { + return fmt.Errorf("retune Speech Dispatcher %s: %w", command[2], err) + } + } + // Keep the requested form so a reconnection matches a fresh configuration. + client.settings = settings + return nil +} + +// restoreClearedSettings fills each setting cleared from current to next with +// the server default. The returned voice type is set when a synthesis voice +// was cleared; it is empty otherwise. +func restoreClearedSettings(current, next Settings, defaults serverDefaults) (Settings, string, error) { + applied := cloneSettings(next) + for _, field := range []struct { + name string + current, def string + target *string + }{ + {"output module", current.OutputModule, defaults.OutputModule, &applied.OutputModule}, + {"punctuation", current.Punctuation, defaults.Punctuation, &applied.Punctuation}, + {"language", current.Language, defaults.Language, &applied.Language}, + } { + if field.current != "" && *field.target == "" { + if field.def == "" { + return Settings{}, "", fmt.Errorf("%w: server reports no default %s", ErrRetuneNeedsReconnect, field.name) + } + *field.target = field.def + } + } + // A named voice may have changed the effective language. Returning to an + // unspecified language must also undo language-to-module server routing. + if next.Language == "" && (current.Language != "" || current.SynthesisVoice != "" && next.SynthesisVoice == "") { + if defaults.Language == "" || next.OutputModule == "" && defaults.OutputModule == "" { + return Settings{}, "", fmt.Errorf("%w: server reports no default language or module", ErrRetuneNeedsReconnect) + } + applied.Language = defaults.Language + if next.OutputModule == "" { + applied.OutputModule = defaults.OutputModule + } + } + // The server's capitalization default is configurable but not queryable. + if current.Capitalization != "" && applied.Capitalization == "" { + return Settings{}, "", fmt.Errorf("%w: server cannot report default capitalization", ErrRetuneNeedsReconnect) + } + for _, field := range []struct { + name string + current, def *int + target **int + }{ + {"rate", current.Rate, defaults.Rate, &applied.Rate}, + {"pitch", current.Pitch, defaults.Pitch, &applied.Pitch}, + {"volume", current.Volume, defaults.Volume, &applied.Volume}, + } { + if field.current != nil && *field.target == nil { + if field.def == nil { + return Settings{}, "", fmt.Errorf("%w: server reports no default %s", ErrRetuneNeedsReconnect, field.name) + } + value := *field.def + *field.target = &value + } + } + voiceType := "" + if current.SynthesisVoice != "" && applied.SynthesisVoice == "" { + if defaults.VoiceType == "" { + return Settings{}, "", fmt.Errorf("%w: server reports no default voice type", ErrRetuneNeedsReconnect) + } + voiceType = defaults.VoiceType + } + return applied, voiceType, nil +} + +func sameSettings(current, next Settings) bool { + return current.OutputModule == next.OutputModule && current.Punctuation == next.Punctuation && + current.Capitalization == next.Capitalization && current.Language == next.Language && + current.SynthesisVoice == next.SynthesisVoice && sameNumber(current.Rate, next.Rate) && + sameNumber(current.Pitch, next.Pitch) && sameNumber(current.Volume, next.Volume) +} + +func sameNumber(current, next *int) bool { + if current == nil || next == nil { + return current == next + } + return *current == *next +} + +func clearsSetting(current, next Settings) bool { + for _, pair := range [][2]string{ + {current.OutputModule, next.OutputModule}, {current.Punctuation, next.Punctuation}, + {current.Capitalization, next.Capitalization}, {current.Language, next.Language}, + {current.SynthesisVoice, next.SynthesisVoice}, + } { + if pair[0] != "" && pair[1] == "" { + return true + } + } + for _, pair := range [][2]*int{{current.Rate, next.Rate}, {current.Pitch, next.Pitch}, {current.Volume, next.Volume}} { + if pair[0] != nil && pair[1] == nil { + return true + } + } + return false +} + func (client *Client) Connect(ctx context.Context) error { client.mutex.Lock() defer client.mutex.Unlock() @@ -264,33 +423,7 @@ func (client *Client) applySettings(ctx context.Context) error { {"SET", "SELF", "CLIENT_NAME", client.settings.ClientName + ":" + client.settings.ClientName + ":main"}, {"SET", "SELF", "PRIORITY", "MESSAGE"}, } - if client.settings.OutputModule != "" { - commands = append(commands, []string{"SET", "SELF", "OUTPUT_MODULE", client.settings.OutputModule}) - } - if client.settings.Punctuation != "" { - commands = append(commands, []string{"SET", "SELF", "PUNCTUATION", client.settings.Punctuation}) - } - if client.settings.Capitalization != "" { - commands = append(commands, []string{"SET", "SELF", "CAP_LET_RECOGN", client.settings.Capitalization}) - } - for _, setting := range []struct { - name string - value *int - }{ - {name: "RATE", value: client.settings.Rate}, - {name: "PITCH", value: client.settings.Pitch}, - {name: "VOLUME", value: client.settings.Volume}, - } { - if setting.value != nil { - commands = append(commands, []string{"SET", "SELF", setting.name, strconv.Itoa(*setting.value)}) - } - } - if client.settings.Language != "" { - commands = append(commands, []string{"SET", "SELF", "LANGUAGE", client.settings.Language}) - } - if client.settings.SynthesisVoice != "" { - commands = append(commands, []string{"SET", "SELF", "SYNTHESIS_VOICE", client.settings.SynthesisVoice}) - } + commands = append(commands, voiceCommands(client.settings)...) if client.background { commands = append(commands, []string{"SET", "SELF", "PRIORITY", "TEXT"}) @@ -303,6 +436,41 @@ func (client *Client) applySettings(ctx context.Context) error { return nil } +// voiceCommands lists the SET commands for every configured voice setting in +// the order a fresh connection applies them. Language precedes module because +// server language routing can change the module. The named voice comes last. +func voiceCommands(settings Settings) [][]string { + var commands [][]string + if settings.Punctuation != "" { + commands = append(commands, []string{"SET", "SELF", "PUNCTUATION", settings.Punctuation}) + } + if settings.Capitalization != "" { + commands = append(commands, []string{"SET", "SELF", "CAP_LET_RECOGN", settings.Capitalization}) + } + for _, setting := range []struct { + name string + value *int + }{ + {name: "RATE", value: settings.Rate}, + {name: "PITCH", value: settings.Pitch}, + {name: "VOLUME", value: settings.Volume}, + } { + if setting.value != nil { + commands = append(commands, []string{"SET", "SELF", setting.name, strconv.Itoa(*setting.value)}) + } + } + if settings.Language != "" { + commands = append(commands, []string{"SET", "SELF", "LANGUAGE", settings.Language}) + } + if settings.OutputModule != "" { + commands = append(commands, []string{"SET", "SELF", "OUTPUT_MODULE", settings.OutputModule}) + } + if settings.SynthesisVoice != "" { + commands = append(commands, []string{"SET", "SELF", "SYNTHESIS_VOICE", settings.SynthesisVoice}) + } + return commands +} + func (client *Client) sendCommand(ctx context.Context, fields []string) (result error) { defer func() { if result != nil && client.conn != nil {