Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03896de84e | ||
|
|
5ca137c879 |
No files matched your search
@@ -16,6 +16,24 @@ Import `git.stormux.org/storm/screenreader-common/emoji` and call
|
||||
|
||||
The module targets Go 1.24 or newer and has no external dependencies.
|
||||
|
||||
## Quick settings
|
||||
|
||||
`quicksettings.Menu` is the quick settings menu shared by both readers:
|
||||
categories of entries, a remembered position in each category, value stepping
|
||||
and the spoken announcement. Entries are toggles (checked/unchecked), choices
|
||||
and numeric ranges. Entries and categories wrap at both ends; ranges stop at
|
||||
their limits. Readers describe their entries, report current values through a
|
||||
`Host`, and apply each changed `Result` themselves, so each reader keeps its own
|
||||
settings storage, profiles, persistence and key bindings. `Replace` reports when
|
||||
the selected entry disappeared so a reader can refuse to change a different
|
||||
setting by mistake. `MessageIDs` lists the menu's own English messages for
|
||||
translation catalogs.
|
||||
|
||||
Both readers store rate, pitch and volume on Speech Dispatcher's -100..100
|
||||
scale, which the hardware protocol also uses. `speechdispatcher.DiscoverQuery`
|
||||
validates module and voice lists, drops repeated voice aliases and keeps
|
||||
partial results; `Discover` returns the same data as a `Catalog`.
|
||||
|
||||
## AI-assisted contributions
|
||||
|
||||
AI-assisted contributions are welcome. The person submitting a contribution
|
||||
@@ -25,6 +43,9 @@ review. Check the maintained branch and whether the change is still needed
|
||||
before editing. Describe what changed, the tests run, and remaining live reader
|
||||
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. Both readers pin v0.6.0 for standalone builds.
|
||||
|
||||
## License
|
||||
|
||||
GPL-3.0-or-later. See [LICENSE](LICENSE).
|
||||
@@ -153,7 +174,26 @@ and 0..9 pitch/volume values at the boundary. It no longer has a separate
|
||||
DECtalk encoding. Port opening, serial/USB I/O, flush timing and cancellation
|
||||
synchronization remain the responsibility of the device-owning reader.
|
||||
|
||||
These additions are available starting with v0.4.0. Both readers pin this
|
||||
version for standalone builds. Verify pinned dependencies with `GOWORK=off`;
|
||||
These additions are available starting with v0.4.0. Both readers pin v0.6.0
|
||||
for standalone builds. Verify pinned dependencies with `GOWORK=off`;
|
||||
physical keyboard, audible speech, braille, and hardware acceptance remain
|
||||
separate live checks.
|
||||
|
||||
## Primary voice profiles
|
||||
|
||||
`voiceprofiles` supplies the shared primary-voice preset model, collection
|
||||
validation/copying, unique automatic names, management-tab controls, and editor
|
||||
forms for software and hardware speech. `Editor.Refresh_session` maintains
|
||||
module/language/voice dependencies in the shared UI toolkit; native GTK hosts
|
||||
use the same form and dependent-control updates. Catalog discovery, native
|
||||
widget rendering, speech preparation/rollback and atomic settings persistence
|
||||
remain host responsibilities. Existing echo and message voice policies remain
|
||||
with each reader. A preset stores only primary speech transport/voice/numeric
|
||||
settings and never modifies unrelated preferences.
|
||||
|
||||
`internalui.Session.Focus_control` 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 in v0.6.0, pinned
|
||||
by both readers 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.
|
||||
@@ -175,6 +175,27 @@ func (s *Session) Focused_control() (Control, bool) {
|
||||
return control, true
|
||||
}
|
||||
|
||||
// Focus_control restores a host's focus after returning from a child dialog.
|
||||
func (s *Session) Focus_control(tabID, controlID string) bool {
|
||||
if s.closed {
|
||||
return false
|
||||
}
|
||||
for ti, tab := range s.form.Tabs {
|
||||
if tab.ID != tabID {
|
||||
continue
|
||||
}
|
||||
for ci, control := range tab.Controls {
|
||||
if control.ID == controlID && !control.Hidden && !control.Disabled {
|
||||
s.tab, s.focus = ti, ci
|
||||
s.cursor = len([]rune(control.Text))
|
||||
s.anchor = s.cursor
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Set_choices updates an asynchronous grid without moving keyboard focus or
|
||||
// discarding its search. Keep the selected word when it still matches.
|
||||
func (s *Session) Set_choices(tabID, controlID string, choices []Choice) {
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Package quicksettings implements the reader-independent quick settings
|
||||
// menu: categories of entries, a remembered position in each category,
|
||||
// value stepping and the spoken announcement. Readers own their settings:
|
||||
// they describe entries, report current values and apply each change.
|
||||
package quicksettings
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"git.stormux.org/storm/screenreader-common/internalui/message"
|
||||
)
|
||||
|
||||
type Messages = message.Messages
|
||||
|
||||
type Kind uint8
|
||||
|
||||
const (
|
||||
// Toggle is announced as checked or unchecked; either step flips it.
|
||||
Toggle Kind = iota + 1
|
||||
// Choice steps through Options and wraps at both ends.
|
||||
Choice
|
||||
// Range steps by Step and stops at Min and Max.
|
||||
Range
|
||||
)
|
||||
|
||||
type Option struct {
|
||||
ID, Label string
|
||||
Literal bool // User-provided labels bypass translation.
|
||||
}
|
||||
|
||||
// Entry describes one setting. Label and option labels are English message
|
||||
// IDs passed through the menu's translator.
|
||||
type Entry struct {
|
||||
ID string
|
||||
Label string
|
||||
Kind Kind
|
||||
// Range limits and step size.
|
||||
Min, Max, Step int
|
||||
// EmptyIsDefault announces a Choice whose selected ID is empty as
|
||||
// "<label> default", such as an unset speech module or voice.
|
||||
EmptyIsDefault bool
|
||||
}
|
||||
|
||||
type Category struct {
|
||||
ID, Label string
|
||||
Entries []Entry
|
||||
}
|
||||
|
||||
// Value holds an entry's value; only the field matching its Kind is used.
|
||||
type Value struct {
|
||||
Checked bool
|
||||
Choice string
|
||||
Number int
|
||||
}
|
||||
|
||||
// Host reports current values and the options of Choice entries. The menu
|
||||
// calls it synchronously from Handle.
|
||||
type Host interface {
|
||||
Value(Entry) Value
|
||||
Options(Entry) []Option
|
||||
}
|
||||
|
||||
type Command uint8
|
||||
|
||||
const (
|
||||
CurrentEntry Command = iota + 1
|
||||
CurrentValue
|
||||
NextEntry
|
||||
PreviousEntry
|
||||
NextValue
|
||||
PreviousValue
|
||||
NextCategory
|
||||
PreviousCategory
|
||||
)
|
||||
|
||||
// Result is one handled command. When Changed is true the host applies
|
||||
// Value to Entry before speaking Text; an asynchronous host speaks Text when
|
||||
// the change succeeds. Available is false for an empty menu or an entry
|
||||
// without options, and Text then explains why.
|
||||
type Result struct {
|
||||
Entry Entry
|
||||
Value Value
|
||||
Changed bool
|
||||
Available bool
|
||||
Text string
|
||||
}
|
||||
|
||||
// Menu is not safe for concurrent use. Copy it with Clone.
|
||||
type Menu struct {
|
||||
Messages Messages
|
||||
categories []Category
|
||||
category int
|
||||
positions []int
|
||||
}
|
||||
|
||||
// New drops categories without entries.
|
||||
func New(categories []Category, messages Messages) *Menu {
|
||||
menu := &Menu{Messages: messages}
|
||||
menu.Replace(categories)
|
||||
return menu
|
||||
}
|
||||
|
||||
// IsValueChange reports whether command changes the selected entry's value.
|
||||
func IsValueChange(command Command) bool { return command == NextValue || command == PreviousValue }
|
||||
|
||||
// Replace installs a new entry set, keeping the selected category and each
|
||||
// category's selected entry when their IDs are still present. kept is false
|
||||
// when the previously selected entry no longer exists; hosts should then not
|
||||
// apply a value change to whichever entry is selected instead.
|
||||
func (m *Menu) Replace(categories []Category) (kept bool) {
|
||||
var selectedCategory, selectedEntry string
|
||||
if entry, ok := m.Selected(); ok {
|
||||
selectedEntry = entry.ID
|
||||
}
|
||||
selectedEntries := make(map[string]string)
|
||||
for index, category := range m.categories {
|
||||
if index == m.category {
|
||||
selectedCategory = category.ID
|
||||
}
|
||||
selectedEntries[category.ID] = category.Entries[m.positions[index]].ID
|
||||
}
|
||||
m.categories, m.positions, m.category = nil, nil, 0
|
||||
for _, category := range categories {
|
||||
if len(category.Entries) == 0 {
|
||||
continue
|
||||
}
|
||||
category.Entries = append([]Entry(nil), category.Entries...)
|
||||
position := 0
|
||||
for index, entry := range category.Entries {
|
||||
if entry.ID == selectedEntries[category.ID] {
|
||||
position = index
|
||||
break
|
||||
}
|
||||
}
|
||||
if category.ID == selectedCategory {
|
||||
m.category = len(m.categories)
|
||||
}
|
||||
m.categories = append(m.categories, category)
|
||||
m.positions = append(m.positions, position)
|
||||
}
|
||||
entry, ok := m.Selected()
|
||||
return selectedEntry == "" || ok && entry.ID == selectedEntry
|
||||
}
|
||||
|
||||
func (m *Menu) Clone() *Menu {
|
||||
clone := *m
|
||||
clone.categories = append([]Category(nil), m.categories...)
|
||||
clone.positions = append([]int(nil), m.positions...)
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (m *Menu) Categories() []Category {
|
||||
categories := append([]Category(nil), m.categories...)
|
||||
for index := range categories {
|
||||
categories[index].Entries = append([]Entry(nil), categories[index].Entries...)
|
||||
}
|
||||
return categories
|
||||
}
|
||||
|
||||
// Selected reports the current entry; ok is false for an empty menu.
|
||||
func (m *Menu) Selected() (entry Entry, ok bool) {
|
||||
if len(m.categories) == 0 {
|
||||
return Entry{}, false
|
||||
}
|
||||
return m.categories[m.category].Entries[m.positions[m.category]], true
|
||||
}
|
||||
|
||||
func (m *Menu) Handle(command Command, host Host) Result {
|
||||
if len(m.categories) == 0 {
|
||||
return Result{Text: m.Messages.T("Quick menu not available")}
|
||||
}
|
||||
categoryChanged := command == NextCategory || command == PreviousCategory
|
||||
switch command {
|
||||
case NextCategory:
|
||||
m.category = (m.category + 1) % len(m.categories)
|
||||
case PreviousCategory:
|
||||
m.category = (m.category + len(m.categories) - 1) % len(m.categories)
|
||||
}
|
||||
entries := m.categories[m.category].Entries
|
||||
position := &m.positions[m.category]
|
||||
switch command {
|
||||
case NextEntry:
|
||||
*position = (*position + 1) % len(entries)
|
||||
case PreviousEntry:
|
||||
*position = (*position + len(entries) - 1) % len(entries)
|
||||
}
|
||||
entry := entries[*position]
|
||||
result := Result{Entry: entry, Value: host.Value(entry), Available: true}
|
||||
step := 0
|
||||
switch command {
|
||||
case NextValue:
|
||||
step = 1
|
||||
case PreviousValue:
|
||||
step = -1
|
||||
}
|
||||
var options []Option
|
||||
switch entry.Kind {
|
||||
case Toggle:
|
||||
if step != 0 {
|
||||
result.Value.Checked = !result.Value.Checked
|
||||
result.Changed = true
|
||||
}
|
||||
case Choice:
|
||||
options = host.Options(entry)
|
||||
if len(options) == 0 {
|
||||
result.Available = false
|
||||
result.Text = m.Messages.Format("{0} not available", m.Messages.T(entry.Label))
|
||||
if categoryChanged {
|
||||
result.Text = m.Messages.T(m.categories[m.category].Label) + ". " + result.Text
|
||||
}
|
||||
return result
|
||||
}
|
||||
if step != 0 {
|
||||
index := -1
|
||||
for candidate, option := range options {
|
||||
if option.ID == result.Value.Choice {
|
||||
index = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if index < 0 {
|
||||
if step > 0 {
|
||||
index = 0
|
||||
} else {
|
||||
index = len(options) - 1
|
||||
}
|
||||
} else {
|
||||
index = (index + step + len(options)) % len(options)
|
||||
}
|
||||
result.Changed = options[index].ID != result.Value.Choice
|
||||
result.Value.Choice = options[index].ID
|
||||
}
|
||||
case Range:
|
||||
if step != 0 {
|
||||
next := max(entry.Min, min(entry.Max, result.Value.Number+step*entry.Step))
|
||||
result.Changed = next != result.Value.Number
|
||||
result.Value.Number = next
|
||||
}
|
||||
}
|
||||
text, labelled := m.describe(entry, result.Value, options)
|
||||
if !labelled && (categoryChanged || command == CurrentEntry || command == NextEntry || command == PreviousEntry) {
|
||||
text = m.Messages.T(entry.Label) + " " + text
|
||||
}
|
||||
if categoryChanged {
|
||||
text = m.Messages.T(m.categories[m.category].Label) + ". " + text
|
||||
}
|
||||
result.Text = text
|
||||
return result
|
||||
}
|
||||
|
||||
// Describe returns the value announcement used after a value change.
|
||||
func (m *Menu) Describe(entry Entry, value Value, options []Option) string {
|
||||
text, _ := m.describe(entry, value, options)
|
||||
return text
|
||||
}
|
||||
|
||||
func (m *Menu) describe(entry Entry, value Value, options []Option) (text string, labelled bool) {
|
||||
switch entry.Kind {
|
||||
case Toggle:
|
||||
if value.Checked {
|
||||
return m.Messages.T("checked"), false
|
||||
}
|
||||
return m.Messages.T("unchecked"), false
|
||||
case Choice:
|
||||
if entry.EmptyIsDefault && value.Choice == "" {
|
||||
return m.Messages.T(entry.Label) + " " + m.Messages.T("default"), true
|
||||
}
|
||||
for _, option := range options {
|
||||
if option.ID == value.Choice {
|
||||
if option.Literal {
|
||||
return option.Label, false
|
||||
}
|
||||
return m.Messages.T(option.Label), false
|
||||
}
|
||||
}
|
||||
if len(options) > 0 {
|
||||
return m.Messages.Format("{0} not available", value.Choice), false
|
||||
}
|
||||
return value.Choice, false
|
||||
}
|
||||
return strconv.Itoa(value.Number), false
|
||||
}
|
||||
|
||||
// MessageIDs lists the menu's own English messages for translation catalogs.
|
||||
func MessageIDs() []string {
|
||||
return []string{"Quick menu not available", "{0} not available", "checked", "unchecked", "default"}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package quicksettings
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeHost struct {
|
||||
values map[string]Value
|
||||
options map[string][]Option
|
||||
}
|
||||
|
||||
func (h *fakeHost) Value(entry Entry) Value { return h.values[entry.ID] }
|
||||
func (h *fakeHost) Options(entry Entry) []Option { return h.options[entry.ID] }
|
||||
func (h *fakeHost) apply(result Result) { h.values[result.Entry.ID] = result.Value }
|
||||
func (h *fakeHost) run(m *Menu, command Command) Result {
|
||||
result := m.Handle(command, h)
|
||||
if result.Changed {
|
||||
h.apply(result)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func fixture() (*Menu, *fakeHost) {
|
||||
menu := New([]Category{
|
||||
{ID: "speech", Label: "Speech", Entries: []Entry{
|
||||
{ID: "rate", Label: "speech rate", Kind: Range, Min: -100, Max: 100, Step: 10},
|
||||
{ID: "voice", Label: "speech voice", Kind: Choice, EmptyIsDefault: true},
|
||||
}},
|
||||
{ID: "empty", Label: "Empty"},
|
||||
{ID: "reading", Label: "Reading", Entries: []Entry{
|
||||
{ID: "punctuation", Label: "punctuation level", Kind: Choice},
|
||||
{ID: "emoticons", Label: "emoticons", Kind: Toggle},
|
||||
}},
|
||||
}, Messages{})
|
||||
host := &fakeHost{
|
||||
values: map[string]Value{"rate": {Number: 80}, "punctuation": {Choice: "some"}},
|
||||
options: map[string][]Option{
|
||||
"voice": {{ID: "", Label: "default"}, {ID: "alice", Label: "Alice"}},
|
||||
"punctuation": {{ID: "none", Label: "none"}, {ID: "some", Label: "some"}, {ID: "all", Label: "all"}},
|
||||
},
|
||||
}
|
||||
return menu, host
|
||||
}
|
||||
|
||||
func TestNavigationAdjustmentAndAnnouncements(t *testing.T) {
|
||||
menu, host := fixture()
|
||||
for _, step := range []struct {
|
||||
command Command
|
||||
want string
|
||||
}{
|
||||
{CurrentEntry, "speech rate 80"},
|
||||
{NextValue, "90"},
|
||||
{NextValue, "100"},
|
||||
{NextValue, "100"},
|
||||
{CurrentValue, "100"},
|
||||
{NextEntry, "speech voice default"},
|
||||
{NextValue, "Alice"},
|
||||
{CurrentEntry, "speech voice Alice"},
|
||||
{NextValue, "speech voice default"},
|
||||
{NextEntry, "speech rate 100"},
|
||||
{PreviousEntry, "speech voice default"},
|
||||
{NextCategory, "Reading. punctuation level some"},
|
||||
{NextValue, "all"},
|
||||
{NextValue, "none"},
|
||||
{PreviousValue, "all"},
|
||||
{NextEntry, "emoticons unchecked"},
|
||||
{NextValue, "checked"},
|
||||
{PreviousValue, "unchecked"},
|
||||
{NextCategory, "Speech. speech voice default"},
|
||||
{PreviousCategory, "Reading. emoticons unchecked"},
|
||||
} {
|
||||
if got := host.run(menu, step.command).Text; got != step.want {
|
||||
t.Fatalf("%v: got %q, want %q", step.command, got, step.want)
|
||||
}
|
||||
}
|
||||
if len(menu.Categories()) != 2 {
|
||||
t.Fatal("empty category was kept", menu.Categories())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangedOnlyWhenValueMoves(t *testing.T) {
|
||||
menu, host := fixture()
|
||||
host.values["rate"] = Value{Number: 100}
|
||||
if result := menu.Handle(NextValue, host); result.Changed || !result.Available {
|
||||
t.Fatal(result)
|
||||
}
|
||||
if result := menu.Handle(PreviousValue, host); !result.Changed || result.Value.Number != 90 {
|
||||
t.Fatal(result)
|
||||
}
|
||||
if result := menu.Handle(CurrentValue, host); result.Changed {
|
||||
t.Fatal(result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnavailableMenuAndOptions(t *testing.T) {
|
||||
menu := New(nil, Messages{})
|
||||
if result := menu.Handle(NextEntry, &fakeHost{}); result.Available || result.Text != "Quick menu not available" {
|
||||
t.Fatal(result)
|
||||
}
|
||||
menu, host := fixture()
|
||||
host.options["voice"] = nil
|
||||
menu.Handle(NextEntry, host)
|
||||
if result := menu.Handle(NextValue, host); result.Available || result.Changed || result.Text != "speech voice not available" {
|
||||
t.Fatal(result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceKeepsSelectionByID(t *testing.T) {
|
||||
menu, host := fixture()
|
||||
menu.Handle(NextCategory, host)
|
||||
menu.Handle(NextEntry, host)
|
||||
categories := menu.Categories()
|
||||
categories[0], categories[1] = categories[1], categories[0]
|
||||
categories[0].Entries = append([]Entry{{ID: "new", Label: "new", Kind: Toggle}}, categories[0].Entries...)
|
||||
if !menu.Replace(categories) {
|
||||
t.Fatal("kept selection reported as removed")
|
||||
}
|
||||
if entry, ok := menu.Selected(); !ok || entry.ID != "emoticons" {
|
||||
t.Fatal(entry, ok)
|
||||
}
|
||||
categories[0].Entries = categories[0].Entries[:2]
|
||||
if menu.Replace(categories) {
|
||||
t.Fatal("removed selection reported as kept")
|
||||
}
|
||||
if !IsValueChange(NextValue) || !IsValueChange(PreviousValue) || IsValueChange(NextEntry) {
|
||||
t.Fatal("value change classification")
|
||||
}
|
||||
menu.Replace(nil)
|
||||
if _, ok := menu.Selected(); ok {
|
||||
t.Fatal("empty menu reported a selection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneIsIndependent(t *testing.T) {
|
||||
menu, host := fixture()
|
||||
clone := menu.Clone()
|
||||
menu.Handle(NextEntry, host)
|
||||
if entry, _ := clone.Selected(); entry.ID != "rate" {
|
||||
t.Fatal(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesAreTranslated(t *testing.T) {
|
||||
menu, host := fixture()
|
||||
menu.Messages = Messages{Translate: strings.ToUpper}
|
||||
if got := menu.Handle(NextCategory, host).Text; got != "READING. PUNCTUATION LEVEL SOME" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
for _, id := range MessageIDs() {
|
||||
if id == "" {
|
||||
t.Fatal("empty message ID")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingChoiceIsNotAnnouncedAsAnotherValue(t *testing.T) {
|
||||
menu, host := fixture()
|
||||
menu.Handle(NextEntry, host)
|
||||
host.values["voice"] = Value{Choice: "removed"}
|
||||
if got := menu.Handle(CurrentEntry, host).Text; got != "speech voice removed not available" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := menu.Handle(NextValue, host); !got.Changed || got.Value.Choice != "" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := menu.Handle(PreviousValue, host); !got.Changed || got.Value.Choice != "alice" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoriesCannotMutateMenuOrClone(t *testing.T) {
|
||||
menu, _ := fixture()
|
||||
clone := menu.Clone()
|
||||
categories := menu.Categories()
|
||||
categories[0].Entries[0].ID = "modified"
|
||||
for _, current := range []*Menu{menu, clone} {
|
||||
if entry, _ := current.Selected(); entry.ID != "rate" {
|
||||
t.Fatal(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiteralProfileNamesBypassTranslation(t *testing.T) {
|
||||
menu := New(nil, Messages{Translate: func(value string) string { return "translated " + value }})
|
||||
entry := Entry{ID: "profile", Label: "Voice profile", Kind: Choice}
|
||||
value := Value{Choice: "Reading"}
|
||||
if got := menu.Describe(entry, value, []Option{{ID: "Reading", Label: "Reading", Literal: true}}); got != "Reading" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := menu.Describe(entry, value, []Option{{ID: "Reading", Label: "Reading"}}); got != "translated Reading" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
+119
-28
@@ -7,56 +7,147 @@ package speechdispatcher
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type Voice struct{ Name, Language, Variant string }
|
||||
type Catalog map[string][]Voice
|
||||
|
||||
// Discover uses its own connection, so slow modules never hold up speech.
|
||||
// The empty module selects the server default.
|
||||
func Discover(ctx context.Context, socket string) (Catalog, error) {
|
||||
query, err := OpenQuery(ctx, socket, false, false)
|
||||
if err != nil {
|
||||
// Discovery is a complete catalog query. Modules lists the server's modules;
|
||||
// Voices holds each module's voices, keyed "" for the server default; Errors
|
||||
// records modules whose voice list could not be read.
|
||||
type Discovery struct {
|
||||
Modules []string
|
||||
Voices map[string][]Voice
|
||||
Errors map[string]error
|
||||
}
|
||||
|
||||
// ValidModule accepts module and language identifiers safe to send in SSIP.
|
||||
func ValidModule(module string) bool {
|
||||
for _, char := range module {
|
||||
if !(char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char >= '0' && char <= '9' || char == '.' || char == '_' || char == '+' || char == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ValidSelection rejects identifiers that could break an SSIP command line.
|
||||
func ValidSelection(module, language, voice string) error {
|
||||
if !ValidModule(module) || !ValidModule(language) {
|
||||
return fmt.Errorf("invalid speech module or language")
|
||||
}
|
||||
if !utf8.ValidString(voice) || len(voice) > 1024 || voice != "" && strings.TrimSpace(voice) == "" {
|
||||
return fmt.Errorf("invalid speech voice")
|
||||
}
|
||||
for _, char := range voice {
|
||||
if unicode.IsControl(char) {
|
||||
return fmt.Errorf("invalid speech voice")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseVoices validates a LIST SYNTHESIS_VOICES reply. Some modules repeat
|
||||
// aliases; the synthesis name is the stable ID, so repeats are dropped.
|
||||
func ParseVoices(rows []string) ([]Voice, error) {
|
||||
voices := make([]Voice, 0, len(rows))
|
||||
seen := map[string]bool{}
|
||||
for _, row := range rows {
|
||||
fields := strings.Split(row, "\t")
|
||||
if len(fields) < 2 || len(fields) > 3 || fields[0] == "" || fields[1] == "" {
|
||||
return nil, fmt.Errorf("invalid speech voice list")
|
||||
}
|
||||
if err := ValidSelection("", fields[1], fields[0]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer query.Close()
|
||||
modules, err := query.Command(ctx, "LIST OUTPUT_MODULES")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
catalog := Catalog{}
|
||||
for _, module := range append([]string{""}, modules...) {
|
||||
if strings.ContainsAny(module, "\r\n\x00") {
|
||||
if seen[fields[0]] {
|
||||
continue
|
||||
}
|
||||
seen[fields[0]] = true
|
||||
voice := Voice{Name: fields[0], Language: fields[1]}
|
||||
if len(fields) == 3 {
|
||||
voice.Variant = fields[2]
|
||||
}
|
||||
voices = append(voices, voice)
|
||||
}
|
||||
return voices, nil
|
||||
}
|
||||
|
||||
// DiscoverQuery never speaks. Partial failures keep the modules that
|
||||
// succeeded and record the others in Errors. The caller bounds ctx.
|
||||
func DiscoverQuery(ctx context.Context, query *Query) (Discovery, error) {
|
||||
result := Discovery{Voices: map[string][]Voice{}, Errors: map[string]error{}}
|
||||
modules, err := query.Command(ctx, "LIST OUTPUT_MODULES")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, module := range modules {
|
||||
if module == "" || !ValidModule(module) || seen[module] {
|
||||
return result, fmt.Errorf("invalid Speech Dispatcher module list")
|
||||
}
|
||||
seen[module] = true
|
||||
}
|
||||
result.Modules = modules
|
||||
// Query the server default before selecting any named module.
|
||||
for _, module := range append([]string{""}, modules...) {
|
||||
var rows []string
|
||||
var err error
|
||||
if module != "" {
|
||||
_, err = query.Command(ctx, "SET SELF OUTPUT_MODULE "+module)
|
||||
}
|
||||
if err == nil {
|
||||
rows, err = query.Command(ctx, "LIST SYNTHESIS_VOICES")
|
||||
}
|
||||
if err == nil {
|
||||
voices, parseErr := ParseVoices(rows)
|
||||
if parseErr != nil {
|
||||
// The reply was fully consumed; subsequent modules remain safe.
|
||||
result.Errors[module] = parseErr
|
||||
continue
|
||||
}
|
||||
result.Voices[module] = voices
|
||||
}
|
||||
if err != nil {
|
||||
delete(result.Voices, module)
|
||||
result.Errors[module] = err
|
||||
// A rejected command ends a complete reply. A broken stream must
|
||||
// never be reused: a late reply could belong to the previous module.
|
||||
var rejected *Rejection
|
||||
if errors.As(err, &rejected) {
|
||||
err = nil
|
||||
continue
|
||||
if !errors.As(err, &rejected) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Discover uses its own connection, so slow modules never hold up speech.
|
||||
// The empty module selects the server default. Modules whose voices could
|
||||
// not be read are omitted; a broken connection returns what was read.
|
||||
func Discover(ctx context.Context, socket string) (Catalog, error) {
|
||||
query, err := OpenQuery(ctx, socket, false, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer query.Close()
|
||||
discovery, err := DiscoverQuery(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
catalog := Catalog{}
|
||||
for module, voices := range discovery.Voices {
|
||||
catalog[module] = voices
|
||||
}
|
||||
for _, err := range discovery.Errors {
|
||||
var rejected *Rejection
|
||||
if !errors.As(err, &rejected) {
|
||||
return catalog, err
|
||||
}
|
||||
catalog[module] = nil
|
||||
for _, row := range rows {
|
||||
fields := strings.Split(row, "\t")
|
||||
if len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
voice := Voice{Name: fields[0], Language: fields[1]}
|
||||
if len(fields) > 2 {
|
||||
voice.Variant = fields[2]
|
||||
}
|
||||
catalog[module] = append(catalog[module], voice)
|
||||
}
|
||||
}
|
||||
return catalog, nil
|
||||
}
|
||||
@@ -41,3 +41,65 @@ func TestDiscoverVoicesAndOutputModule(t *testing.T) {
|
||||
t.Fatal("echo voice/module not configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseVoicesRejectsMalformedRowsAndKeepsNames(t *testing.T) {
|
||||
for _, row := range []string{"Missing tabs", "name\ten\tvariant\textra", "name\ten\rCANCEL ALL", "bad\x00name\ten"} {
|
||||
if _, err := ParseVoices([]string{row}); err == nil {
|
||||
t.Fatal("accepted malformed catalog row", row)
|
||||
}
|
||||
}
|
||||
voices, err := ParseVoices([]string{"Cherokee \tchr\tnone", "Alias\ten", "Alias\ten-US"})
|
||||
if err != nil || len(voices) != 2 || voices[0].Name != "Cherokee " || voices[1].Language != "en" {
|
||||
t.Fatal(voices, err)
|
||||
}
|
||||
if err := ValidSelection("espeak-ng", "chr", "Cherokee "); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ValidSelection("espeak-ng", "chr", " "); err == nil {
|
||||
t.Fatal("accepted whitespace-only name")
|
||||
}
|
||||
if err := ValidSelection("bad module", "", ""); err == nil {
|
||||
t.Fatal("accepted unsafe module")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverRejectsUnsafeModuleList(t *testing.T) {
|
||||
path, _ := newSettingsServer(t, func(command string) string {
|
||||
if command == "LIST OUTPUT_MODULES" {
|
||||
return "200-good\r\n200-bad module\r\n200 OK\r\n"
|
||||
}
|
||||
return "200 OK\r\n"
|
||||
})
|
||||
if _, err := Discover(context.Background(), path); err == nil {
|
||||
t.Fatal("accepted an unsafe module name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveryContinuesAfterMalformedVoiceList(t *testing.T) {
|
||||
module := ""
|
||||
path, _ := newSettingsServer(t, func(command string) string {
|
||||
switch command {
|
||||
case "LIST OUTPUT_MODULES":
|
||||
return "200-broken\r\n200-good\r\n200 OK\r\n"
|
||||
case "SET SELF OUTPUT_MODULE broken":
|
||||
module = "broken"
|
||||
case "SET SELF OUTPUT_MODULE good":
|
||||
module = "good"
|
||||
case "LIST SYNTHESIS_VOICES":
|
||||
if module == "broken" {
|
||||
return "200-malformed\r\n200 OK\r\n"
|
||||
}
|
||||
return "200-Voice\ten\tnone\r\n200 OK\r\n"
|
||||
}
|
||||
return "200 OK\r\n"
|
||||
})
|
||||
query, err := OpenQuery(context.Background(), path, false, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer query.Close()
|
||||
catalog, err := DiscoverQuery(context.Background(), query)
|
||||
if err != nil || catalog.Errors["broken"] == nil || len(catalog.Voices["good"]) != 1 {
|
||||
t.Fatal(catalog, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package voiceprofiles
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
ui "git.stormux.org/storm/screenreader-common/internalui"
|
||||
sd "git.stormux.org/storm/screenreader-common/speechdispatcher"
|
||||
)
|
||||
|
||||
const PageID = "voice-profile"
|
||||
|
||||
// Editor builds the same labeled controls for native GTK and internal forms.
|
||||
// Catalog queries and committing the draft remain host operations.
|
||||
type Editor struct {
|
||||
drivers []Driver
|
||||
catalog sd.Catalog
|
||||
previous Profile
|
||||
}
|
||||
|
||||
func New_editor(p Profile, drivers []Driver, catalog sd.Catalog) *Editor {
|
||||
copyCatalog := sd.Catalog{}
|
||||
for module, voices := range catalog {
|
||||
copyCatalog[module] = append([]sd.Voice(nil), voices...)
|
||||
}
|
||||
return &Editor{drivers: append([]Driver(nil), drivers...), catalog: copyCatalog, previous: p}
|
||||
}
|
||||
|
||||
func choice(id, label string) ui.Choice { return ui.Choice{ID: id, Label: label, Literal: true} }
|
||||
|
||||
func combo(id, label, selected string, choices []ui.Choice) ui.Control {
|
||||
index := -1
|
||||
for i, c := range choices {
|
||||
if c.ID == selected {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if index < 0 {
|
||||
index = len(choices)
|
||||
choices = append(choices, choice(selected, selected+" (unavailable)"))
|
||||
}
|
||||
return ui.Control{ID: id, Label: label, Kind: ui.ComboBox, Choices: choices, Selected: index}
|
||||
}
|
||||
|
||||
func (e *Editor) controls(p Profile) []ui.Control {
|
||||
drivers := []ui.Choice{}
|
||||
for _, driver := range e.drivers {
|
||||
drivers = append(drivers, choice(driver.ID, driver.Label))
|
||||
}
|
||||
controls := []ui.Control{{ID: "name", Label: "Voice Profile Name", Kind: ui.Entry, Text: p.Name, MaxLength: 128}, combo("driver", "Synthesizer", p.Driver, drivers)}
|
||||
driver, _ := driver_for(p.Driver)
|
||||
modules := []ui.Choice{choice("", "Default")}
|
||||
keys := []string{}
|
||||
for module := range e.catalog {
|
||||
if module != "" {
|
||||
keys = append(keys, module)
|
||||
}
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, module := range keys {
|
||||
modules = append(modules, choice(module, module))
|
||||
}
|
||||
languages := []ui.Choice{choice("", "Default")}
|
||||
voices := []ui.Choice{choice("", "Default")}
|
||||
seen := map[string]bool{"": true}
|
||||
for _, voice := range e.catalog[p.Module] {
|
||||
if !seen[voice.Language] {
|
||||
languages = append(languages, choice(voice.Language, voice.Language))
|
||||
seen[voice.Language] = true
|
||||
}
|
||||
}
|
||||
filtered := e.catalog[p.Module]
|
||||
if p.Language != "" {
|
||||
filtered = sd.LanguageVoices(filtered, p.Language)
|
||||
}
|
||||
seen = map[string]bool{"": true}
|
||||
for _, voice := range filtered {
|
||||
if !seen[voice.Name] {
|
||||
voices = append(voices, choice(voice.Name, voice.Name+" ("+voice.Language+")"))
|
||||
seen[voice.Name] = true
|
||||
}
|
||||
}
|
||||
for _, c := range []ui.Control{combo("module", "Module", p.Module, modules), combo("language", "Language", p.Language, languages), combo("voice", "Voice", p.Voice, voices)} {
|
||||
c.Hidden = driver.Hardware
|
||||
controls = append(controls, c)
|
||||
}
|
||||
baud := []ui.Choice{}
|
||||
for _, n := range BaudRates {
|
||||
baud = append(baud, choice(strconv.Itoa(n), strconv.Itoa(n)))
|
||||
}
|
||||
device := ui.Control{ID: "device", Label: "Serial device", Kind: ui.Entry, Text: p.Device, Hidden: !driver.Serial, MaxLength: 1024}
|
||||
baudControl := combo("baud", "Baud rate", strconv.Itoa(p.BaudRate), baud)
|
||||
baudControl.Hidden = !driver.Serial
|
||||
controls = append(controls, device, baudControl)
|
||||
for _, item := range []struct {
|
||||
id, label string
|
||||
value int
|
||||
}{{"rate", "Rate", p.Rate}, {"pitch", "Pitch", p.Pitch}, {"volume", "Volume", p.Volume}} {
|
||||
controls = append(controls, ui.Control{ID: item.id, Label: item.label, Kind: ui.Number, Number: float64(item.value), Min: -100, Max: 100, Step: 10, UpDownStep: 1})
|
||||
}
|
||||
return append(controls, ui.Control{ID: "save", Label: "Save Voice Profile", Kind: ui.Button, Action: "save-profile"}, ui.Control{ID: "cancel", Label: "Cancel", Kind: ui.Button, Action: "cancel", SkipValidation: true})
|
||||
}
|
||||
|
||||
func (e *Editor) Form() ui.Form {
|
||||
return ui.Form{Type: ui.FlatForm, Title: "Voice Profile", Tabs: []ui.Tab{{ID: PageID, Label: "Voice Profile", Controls: e.controls(e.previous)}}}
|
||||
}
|
||||
|
||||
func selected(c ui.Control) string {
|
||||
if c.Selected >= 0 && c.Selected < len(c.Choices) {
|
||||
return c.Choices[c.Selected].ID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (e *Editor) read(values map[string]ui.Control) Profile {
|
||||
get := func(id string) ui.Control { return values[PageID+"."+id] }
|
||||
baud, _ := strconv.Atoi(selected(get("baud")))
|
||||
p := Profile{Name: get("name").Text, Driver: selected(get("driver")), Module: selected(get("module")), Language: selected(get("language")), Voice: selected(get("voice")), Device: get("device").Text, BaudRate: baud, Rate: int(get("rate").Number), Pitch: int(get("pitch").Number), Volume: int(get("volume").Number)}
|
||||
if p.Module == e.previous.Module && p.Language == e.previous.Language && p.Voice == e.previous.Voice {
|
||||
p.Variant = e.previous.Variant
|
||||
}
|
||||
for _, voice := range e.catalog[p.Module] {
|
||||
if voice.Name == p.Voice && (p.Language == "" || strings.EqualFold(p.Language, voice.Language)) {
|
||||
p.Language = voice.Language
|
||||
p.Variant = voice.Variant
|
||||
break
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Refresh returns only dependent controls, preserving entry text and numeric drafts.
|
||||
func (e *Editor) Refresh(values map[string]ui.Control) []ui.Control {
|
||||
p := e.read(values)
|
||||
if p.Driver == e.previous.Driver && p.Module == e.previous.Module && selected(values[PageID+".language"]) == e.previous.Language {
|
||||
return nil
|
||||
}
|
||||
if p.Module != e.previous.Module {
|
||||
p.Language = ""
|
||||
p.Voice = ""
|
||||
p.Variant = ""
|
||||
}
|
||||
if selected(values[PageID+".language"]) != e.previous.Language {
|
||||
p.Voice = ""
|
||||
p.Variant = ""
|
||||
}
|
||||
// The language combo is a filter; selecting a voice alone must not reset it.
|
||||
p.Language = selected(values[PageID+".language"])
|
||||
if p.Module != e.previous.Module {
|
||||
p.Language = ""
|
||||
}
|
||||
e.previous = p
|
||||
var changes []ui.Control
|
||||
for _, c := range e.controls(p) {
|
||||
if c.ID == "module" || c.ID == "language" || c.ID == "voice" || c.ID == "device" || c.ID == "baud" {
|
||||
changes = append(changes, c)
|
||||
}
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
func (e *Editor) Refresh_session(session *ui.Session) {
|
||||
for _, c := range e.Refresh(session.Values()) {
|
||||
if c.Kind == ui.ComboBox {
|
||||
session.Replace_choices(PageID, c.ID, c.Choices, selected(c))
|
||||
}
|
||||
session.Set_hidden(PageID, c.ID, c.Hidden)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Editor) Read(values map[string]ui.Control) (Profile, error) {
|
||||
for _, id := range []string{"rate", "pitch", "volume"} {
|
||||
n := values[PageID+"."+id].Number
|
||||
if math.IsNaN(n) || math.IsInf(n, 0) || math.Trunc(n) != n || n < -100 || n > 100 {
|
||||
return Profile{}, fmt.Errorf("Enter a %s between -100 and 100", id)
|
||||
}
|
||||
}
|
||||
p := e.read(values).Normalize()
|
||||
found := false
|
||||
for _, driver := range e.drivers {
|
||||
if driver.ID == p.Driver {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return p, fmt.Errorf("Choose a supported synthesizer")
|
||||
}
|
||||
driver, _ := driver_for(p.Driver)
|
||||
if driver.Hardware {
|
||||
p.Module = ""
|
||||
p.Language = ""
|
||||
p.Voice = ""
|
||||
p.Variant = ""
|
||||
}
|
||||
if !driver.Serial {
|
||||
p.Device = ""
|
||||
p.BaudRate = 0
|
||||
}
|
||||
return p, p.Validate()
|
||||
}
|
||||
|
||||
func (c Collection) Tab() ui.Tab {
|
||||
tab := ui.Tab{ID: "voice-profiles", Label: "Voice Profiles"}
|
||||
if len(c.Profiles) > 0 {
|
||||
choices := []ui.Choice{}
|
||||
for _, p := range c.Profiles {
|
||||
choices = append(choices, choice(p.Name, p.Name))
|
||||
}
|
||||
tab.Controls = append(tab.Controls, ui.Control{ID: "profiles", Label: "Voice Profiles", Kind: ui.ComboBox, Choices: choices})
|
||||
}
|
||||
tab.Controls = append(tab.Controls, ui.Control{ID: "add", Label: "Add Voice Profile", Kind: ui.Button, Action: "add-profile"})
|
||||
if len(c.Profiles) > 0 {
|
||||
for _, item := range []struct{ id, label string }{{"edit", "Edit Voice Profile"}, {"remove", "Remove Voice Profile"}, {"use", "Use Voice Profile"}} {
|
||||
tab.Controls = append(tab.Controls, ui.Control{ID: item.id, Label: item.label, Kind: ui.Button, Action: item.id + "-profile"})
|
||||
}
|
||||
}
|
||||
return tab
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Package voiceprofiles owns primary-voice presets, independent of reader storage
|
||||
// and speech transports. Selecting a preset never changes echo or message voices.
|
||||
package voiceprofiles
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
sd "git.stormux.org/storm/screenreader-common/speechdispatcher"
|
||||
)
|
||||
|
||||
type Profile struct {
|
||||
Name string `toml:"name"`
|
||||
Driver string `toml:"driver"`
|
||||
Module string `toml:"module,omitempty"`
|
||||
Language string `toml:"language,omitempty"`
|
||||
Voice string `toml:"voice,omitempty"`
|
||||
Variant string `toml:"variant,omitempty"`
|
||||
Rate int `toml:"rate"`
|
||||
Pitch int `toml:"pitch"`
|
||||
Volume int `toml:"volume"`
|
||||
Device string `toml:"device,omitempty"`
|
||||
BaudRate int `toml:"baud-rate,omitempty"`
|
||||
}
|
||||
|
||||
type Collection struct {
|
||||
Profiles []Profile `toml:"profiles,omitempty"`
|
||||
}
|
||||
|
||||
func (c Collection) Clone() Collection { return Collection{Profiles: slices.Clone(c.Profiles)} }
|
||||
|
||||
type Driver struct {
|
||||
ID, Label string
|
||||
Hardware, Serial bool
|
||||
}
|
||||
|
||||
func Drivers() []Driver {
|
||||
return []Driver{{ID: "speech-dispatcher", Label: "Speech Dispatcher"},
|
||||
{ID: "dectalk", Label: "DECtalk", Hardware: true, Serial: true},
|
||||
{ID: "dectalk-usb", Label: "DECtalk USB", Hardware: true},
|
||||
{ID: "litetalk", Label: "LiteTalk", Hardware: true, Serial: true},
|
||||
{ID: "doubletalk", Label: "DoubleTalk LT", Hardware: true, Serial: true},
|
||||
{ID: "tripletalk", Label: "TripleTalk", Hardware: true, Serial: true}}
|
||||
}
|
||||
|
||||
func driver_for(id string) (Driver, bool) {
|
||||
for _, driver := range Drivers() {
|
||||
if driver.ID == id {
|
||||
return driver, true
|
||||
}
|
||||
}
|
||||
return Driver{}, false
|
||||
}
|
||||
|
||||
// Normalize supplies the saved name when the editor's name field is blank.
|
||||
func (p Profile) Normalize() Profile {
|
||||
p.Name = strings.TrimSpace(p.Name)
|
||||
if p.Name == "" {
|
||||
driver, _ := driver_for(p.Driver)
|
||||
if !driver.Hardware {
|
||||
p.Name = strings.TrimSpace(strings.Join([]string{p.Module, p.Voice}, " "))
|
||||
}
|
||||
if p.Name == "" {
|
||||
p.Name = driver.Label
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p Profile) Validate() error {
|
||||
if p.Name == "" || p.Name != strings.TrimSpace(p.Name) || utf8.RuneCountInString(p.Name) > 128 || !utf8.ValidString(p.Name) {
|
||||
return fmt.Errorf("Enter a voice profile name of at most 128 characters")
|
||||
}
|
||||
for _, char := range p.Name {
|
||||
if unicode.IsControl(char) {
|
||||
return fmt.Errorf("Voice profile names must be single-line text")
|
||||
}
|
||||
}
|
||||
driver, ok := driver_for(p.Driver)
|
||||
if !ok {
|
||||
return fmt.Errorf("Choose a supported synthesizer")
|
||||
}
|
||||
for _, number := range []int{p.Rate, p.Pitch, p.Volume} {
|
||||
if number < -100 || number > 100 {
|
||||
return fmt.Errorf("Voice rate, pitch and volume must be between -100 and 100")
|
||||
}
|
||||
}
|
||||
if err := sd.ValidSelection(p.Module, p.Language, p.Voice); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(p.Variant) > 1024 || strings.IndexFunc(p.Variant, unicode.IsControl) >= 0 {
|
||||
return fmt.Errorf("Invalid voice variant")
|
||||
}
|
||||
if driver.Serial {
|
||||
if !filepath.IsAbs(p.Device) || len(p.Device) > 1024 || strings.IndexFunc(p.Device, unicode.IsControl) >= 0 {
|
||||
return fmt.Errorf("Choose an absolute serial device path")
|
||||
}
|
||||
if !slices.Contains(BaudRates, p.BaudRate) {
|
||||
return fmt.Errorf("Choose a supported serial baud rate")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var BaudRates = []int{1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200}
|
||||
|
||||
func (c Collection) Validate() error {
|
||||
if len(c.Profiles) > 128 {
|
||||
return fmt.Errorf("At most 128 voice profiles can be saved")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, p := range c.Profiles {
|
||||
if err := p.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.ToLower(p.Name)
|
||||
if seen[name] {
|
||||
return fmt.Errorf("A voice profile named %q already exists", p.Name)
|
||||
}
|
||||
seen[name] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put replaces only the explicitly edited profile; duplicate names never overwrite.
|
||||
func (c Collection) Put(index int, p Profile) (Collection, error) {
|
||||
if index < -1 || index >= len(c.Profiles) {
|
||||
return c, fmt.Errorf("Voice profile no longer exists")
|
||||
}
|
||||
next := c.Clone()
|
||||
p = p.Normalize()
|
||||
if index == -1 {
|
||||
next.Profiles = append(next.Profiles, p)
|
||||
} else {
|
||||
next.Profiles[index] = p
|
||||
}
|
||||
if err := next.Validate(); err != nil {
|
||||
return c, err
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func (c Collection) Remove(index int) Collection {
|
||||
next := c.Clone()
|
||||
if index >= 0 && index < len(next.Profiles) {
|
||||
next.Profiles = slices.Delete(next.Profiles, index, index+1)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func Same_voice(a, b Profile) bool {
|
||||
a.Name = ""
|
||||
b.Name = ""
|
||||
a.Variant = ""
|
||||
b.Variant = ""
|
||||
return a == b
|
||||
}
|
||||
|
||||
func (c Collection) Matching(p Profile) string {
|
||||
for _, candidate := range c.Profiles {
|
||||
if Same_voice(candidate, p) {
|
||||
return candidate.Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c Collection) Find(name string) (Profile, bool) {
|
||||
for _, p := range c.Profiles {
|
||||
if p.Name == name {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return Profile{}, false
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package voiceprofiles
|
||||
|
||||
import (
|
||||
ui "git.stormux.org/storm/screenreader-common/internalui"
|
||||
sd "git.stormux.org/storm/screenreader-common/speechdispatcher"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fixture_profile() Profile {
|
||||
return Profile{Driver: "speech-dispatcher", Module: "fixture", Voice: "Reading voice", Language: "en", Volume: 100}
|
||||
}
|
||||
func TestCollectionNamingDuplicatesAndIsolation(t *testing.T) {
|
||||
p := fixture_profile()
|
||||
collection, err := (Collection{}).Put(-1, p)
|
||||
if err != nil || collection.Profiles[0].Name != "fixture Reading voice" {
|
||||
t.Fatal(collection, err)
|
||||
}
|
||||
before := collection.Clone()
|
||||
p.Name = "FIXTURE READING VOICE"
|
||||
if _, err = collection.Put(-1, p); err == nil {
|
||||
t.Fatal("duplicate silently overwrote a profile")
|
||||
}
|
||||
if !reflect.DeepEqual(before, collection) {
|
||||
t.Fatal("failed add mutated collection")
|
||||
}
|
||||
p.Name = "Long reading"
|
||||
next, err := collection.Put(0, p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Profiles[0].Name = "Changed"
|
||||
if collection.Profiles[0].Name != before.Profiles[0].Name {
|
||||
t.Fatal("aliased profile list")
|
||||
}
|
||||
for _, name := range []string{"bad\nname", strings.Repeat("x", 129)} {
|
||||
p.Name = name
|
||||
if _, err = collection.Put(-1, p); err == nil {
|
||||
t.Fatal("accepted invalid name")
|
||||
}
|
||||
}
|
||||
hardware := Profile{Driver: "dectalk", Device: "/dev/fixture", BaudRate: 9600, Volume: 100}.Normalize()
|
||||
if hardware.Name != "DECtalk" || hardware.Validate() != nil {
|
||||
t.Fatal(hardware)
|
||||
}
|
||||
if len(collection.Remove(0).Profiles) != 0 || len(collection.Profiles) != 1 {
|
||||
t.Fatal("remove mutated original")
|
||||
}
|
||||
}
|
||||
func TestEditorDependenciesHardwareAndUnavailableVoice(t *testing.T) {
|
||||
p := fixture_profile()
|
||||
p.Name = "Saved"
|
||||
p.Voice = "Offline voice"
|
||||
p.Variant = "saved"
|
||||
catalog := sd.Catalog{"fixture": {{Name: "English", Language: "en"}, {Name: "Spanish", Language: "es"}}, "other": {{Name: "Other", Language: "fr"}}}
|
||||
editor := New_editor(p, Drivers(), catalog)
|
||||
session, err := ui.New_session(editor.Form())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, _ := session.Focused_control(); c.ID != "name" {
|
||||
t.Fatal("name is not initially focused")
|
||||
}
|
||||
got, err := editor.Read(session.Values())
|
||||
if err != nil || got.Voice != p.Voice || got.Variant != p.Variant {
|
||||
t.Fatal("offline voice lost", got, err)
|
||||
}
|
||||
session.Focus_control(PageID, "rate")
|
||||
session.Handle(ui.Key{Name: "left"})
|
||||
session.Select(PageID, "module", 2)
|
||||
editor.Refresh_session(session)
|
||||
got, err = editor.Read(session.Values())
|
||||
if err != nil || got.Module != "other" || got.Voice != "" || got.Language != "" || got.Rate != -10 {
|
||||
t.Fatal("dependent reset lost draft", got, err)
|
||||
}
|
||||
session.Select(PageID, "language", 1)
|
||||
editor.Refresh_session(session)
|
||||
session.Select(PageID, "voice", 1)
|
||||
got, err = editor.Read(session.Values())
|
||||
if err != nil || got.Voice != "Other" || got.Language != "fr" {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
session.Select(PageID, "driver", 1)
|
||||
editor.Refresh_session(session)
|
||||
if !session.Values()[PageID+".voice"].Hidden || session.Values()[PageID+".device"].Hidden {
|
||||
t.Fatal("wrong hardware fields")
|
||||
}
|
||||
session.Focus_control(PageID, "device")
|
||||
session.Handle(ui.Key{Ctrl: true, Text: "a"})
|
||||
session.Insert("/dev/fixture")
|
||||
session.Select(PageID, "baud", 3)
|
||||
got, err = editor.Read(session.Values())
|
||||
if err != nil || got.Driver != "dectalk" || got.Module != "" || got.Voice != "" || got.BaudRate != 9600 {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
}
|
||||
func TestEditorCancelAndGeneratedName(t *testing.T) {
|
||||
p := fixture_profile()
|
||||
editor := New_editor(p, Drivers(), nil)
|
||||
session, err := ui.New_session(editor.Form())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := editor.Read(session.Values())
|
||||
if err != nil || got.Name != "fixture Reading voice" {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if !session.Handle(ui.Key{Name: "escape"}).Cancelled {
|
||||
t.Fatal("escape did not cancel")
|
||||
}
|
||||
if p.Name != "" {
|
||||
t.Fatal("editor mutated original")
|
||||
}
|
||||
tab := (Collection{}).Tab()
|
||||
if len(tab.Controls) != 1 || tab.Controls[0].Action != "add-profile" {
|
||||
t.Fatal(tab)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user