Use shared reader core v0.4.0

Use common date/time formatting, locale voice selection, tone synthesis, phonetic spelling, and hardware command encoding. Share whiskey and x ray spelling and retain reader-owned device I/O and presentation.

Validated affected race-enabled speech, sound, presentation, date/time, application, review, and preferences tests and standalone builds with GOWORK=off against the published module. Physical hardware, audible synthesis, keyboard, and braille remain separate live checks.
This commit is contained in:
ak47 committed 2026-11-12 23:45:10 -05:00
1 parent 0dd8e2f9c7
commit 24840d355c
9 files changed
+43 -272

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@ module git.stormux.org/storm/fenrir
go 1.27.2 go 1.27.2
require ( require (
git.stormux.org/storm/screenreader-common v0.3.0 git.stormux.org/storm/screenreader-common v0.4.0
github.com/jfreymuth/pulse v0.1.3 github.com/jfreymuth/pulse v0.1.3
github.com/leonelquinteros/gotext v1.8.0 github.com/leonelquinteros/gotext v1.8.0
github.com/pelletier/go-toml/v2 v2.4.3 github.com/pelletier/go-toml/v2 v2.4.3
+2
View File
@@ -4,6 +4,8 @@ git.stormux.org/storm/screenreader-common v0.2.0 h1:PbGwyIi/nT0qwvscje4pvIIsAxDL
git.stormux.org/storm/screenreader-common v0.2.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= git.stormux.org/storm/screenreader-common v0.2.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY=
git.stormux.org/storm/screenreader-common v0.3.0 h1:eWuSMf3lM8fB5RyegnsyHmdz1uP0CzPqMfFP8wonV3k= git.stormux.org/storm/screenreader-common v0.3.0 h1:eWuSMf3lM8fB5RyegnsyHmdz1uP0CzPqMfFP8wonV3k=
git.stormux.org/storm/screenreader-common v0.3.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= 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=
github.com/jfreymuth/pulse v0.1.3 h1:bc5TdxiB8E+2INnFjFWWgyfgXtz2IyNNNCX+Wt/ZD14= github.com/jfreymuth/pulse v0.1.3 h1:bc5TdxiB8E+2INnFjFWWgyfgXtz2IyNNNCX+Wt/ZD14=
github.com/jfreymuth/pulse v0.1.3/go.mod h1:cpYspI6YljhkUf1WLXLLDmeaaPFc3CnGLjDZf9dZ4no= github.com/jfreymuth/pulse v0.1.3/go.mod h1:cpYspI6YljhkUf1WLXLLDmeaaPFc3CnGLjDZf9dZ4no=
github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU= github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU=
+9 -134
View File
@@ -1,141 +1,16 @@
// Copyright (c) 2026 Storm Dragon // Copyright (c) 2026 Storm Dragon
// Author: Storm Dragon // Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
package datetime package datetime
/* import common "git.stormux.org/storm/screenreader-common/datetime"
#include <locale.h>
#include <stdlib.h>
#include <time.h>
*/
import "C"
import ( type Option = common.Option
"time"
"unsafe"
)
type Option struct { var Time_options = common.TimeOptions
Value string var Date_options = common.DateOptions
Label string var Format_time = common.FormatTime
} var Format_date = common.FormatDate
var Valid_time = common.ValidTime
var timeFormats = []struct { var Valid_date = common.ValidDate
Value string
Spec string
}{
{"locale", "%X"},
{"12-hour", "%I:%M %p"},
{"12-hour-seconds", "%I:%M:%S %p"},
{"24-hour-seconds", "%H:%M:%S"},
{"24-hour-seconds-words", "%H hours, %M minutes and %S seconds"},
{"24-hour", "%H:%M"},
{"24-hour-words", "%H hours and %M minutes"},
}
var dateFormats = []struct {
Value string
Spec string
}{
{"locale", "%x"},
{"numbers-dm", "%d/%m"},
{"numbers-md", "%m/%d"},
{"numbers-dmy", "%d/%m/%Y"},
{"numbers-mdy", "%m/%d/%Y"},
{"numbers-ymd", "%Y/%m/%d"},
{"full-dm", "%A, %-d %B"},
{"full-md", "%A, %B %-d"},
{"full-dmy", "%A, %-d %B, %Y"},
{"full-mdy", "%A, %B %-d, %Y"},
{"full-ymd", "%Y. %B %-d, %A"},
{"abbreviated-dm", "%a, %-d %b"},
{"abbreviated-md", "%a, %b %-d"},
{"abbreviated-dmy", "%a, %-d %b, %Y"},
{"abbreviated-mdy", "%a, %b %-d, %Y"},
{"abbreviated-ymd", "%Y. %b %-d, %a"},
}
func init() {
locale := C.CString("")
defer C.free(unsafe.Pointer(locale))
C.setlocale(C.LC_TIME, locale)
}
func Time_options(now time.Time) []Option {
return options(timeFormats, now)
}
func Date_options(now time.Time) []Option {
return options(dateFormats, now)
}
func options(formats []struct {
Value string
Spec string
}, now time.Time) []Option {
result := make([]Option, 0, len(formats))
for _, item := range formats {
result = append(result, Option{Value: item.Value, Label: format(now, item.Spec)})
}
return result
}
func Format_time(value string, now time.Time) (string, bool) {
return format_value(timeFormats, value, now)
}
func Format_date(value string, now time.Time) (string, bool) {
return format_value(dateFormats, value, now)
}
func Valid_time(value string) bool {
return valid(timeFormats, value)
}
func Valid_date(value string) bool {
return valid(dateFormats, value)
}
func format_value(formats []struct {
Value string
Spec string
}, value string, now time.Time) (string, bool) {
for _, item := range formats {
if item.Value == value {
return format(now, item.Spec), true
}
}
return "", false
}
func valid(formats []struct {
Value string
Spec string
}, value string) bool {
for _, item := range formats {
if item.Value == value {
return true
}
}
return false
}
func format(now time.Time, spec string) string {
cSpec := C.CString(spec)
defer C.free(unsafe.Pointer(cSpec))
tm := C.struct_tm{
tm_year: C.int(now.Year() - 1900),
tm_mon: C.int(int(now.Month()) - 1),
tm_mday: C.int(now.Day()),
tm_hour: C.int(now.Hour()),
tm_min: C.int(now.Minute()),
tm_sec: C.int(now.Second()),
tm_wday: C.int(int(now.Weekday())),
tm_yday: C.int(now.YearDay() - 1),
tm_isdst: -1,
}
buffer := make([]C.char, 512)
length := C.strftime(&buffer[0], C.size_t(len(buffer)), cSpec, &tm)
return C.GoStringN(&buffer[0], C.int(length))
}
+8 -6
View File
@@ -3,17 +3,19 @@
package presentation package presentation
import "unicode" import (
"unicode"
// Phonetic_letter matches Python Fenrir's alphabet, including its capitalization. "git.stormux.org/storm/screenreader-common/phonetic"
)
// Phonetic_letter matches the shared spelling alphabet with Fenrir capitalization.
// Other runes use the active punctuation profile's character naming instead. // Other runes use the active punctuation profile's character naming instead.
func Phonetic_letter(char rune) string { func Phonetic_letter(char rune) string {
words := [...]string{"alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whisky", "x ray", "yankee", "zulu"} word := phonetic.Letter(char)
upper := unicode.ToUpper(char) if word == "" {
if upper < 'A' || upper > 'Z' {
return "" return ""
} }
word := words[upper-'A']
if unicode.IsUpper(char) { if unicode.IsUpper(char) {
word = string(unicode.ToUpper(rune(word[0]))) + word[1:] word = string(unicode.ToUpper(rune(word[0]))) + word[1:]
} }
+1 -1
View File
@@ -11,7 +11,7 @@ func TestPythonPhoneticNamesAndUnicodeFallback(t *testing.T) {
want string want string
}{ }{
{'a', "alpha"}, {'A', "Alpha"}, {'j', "juliet"}, {'a', "alpha"}, {'A', "Alpha"}, {'j', "juliet"},
{'w', "whisky"}, {'W', "Whisky"}, {'x', "x ray"}, {'X', "X ray"}, {'w', "whiskey"}, {'W', "Whiskey"}, {'x', "x ray"}, {'X', "X ray"},
{'É', ""}, {'界', ""}, {'1', ""}, {'?', ""}, {' ', ""}, {'É', ""}, {'界', ""}, {'1', ""}, {'?', ""}, {' ', ""},
} { } {
if got := Phonetic_letter(trial.char); got != trial.want { if got := Phonetic_letter(trial.char); got != trial.want {
+9 -14
View File
@@ -18,7 +18,11 @@
// Tone synthesis adapted from Cthulhu (Storm Dragon and Angus Kola). // Tone synthesis adapted from Cthulhu (Storm Dragon and Angus Kola).
package sound package sound
import "math" import (
"math"
"git.stormux.org/storm/screenreader-common/tones"
)
// A small gain lift for progress tones, independent of normal cue volume. // A small gain lift for progress tones, independent of normal cue volume.
const progressGain = 1.03 * 1.02 const progressGain = 1.03 * 1.02
@@ -43,20 +47,11 @@ func progress_tone(percentage float64) *clip {
// The triangle variant shares progress's pitch, duration and resampling. // The triangle variant shares progress's pitch, duration and resampling.
func progress_tone_shape(percentage float64, triangle bool) *clip { func progress_tone_shape(percentage float64, triangle bool) *clip {
const sourceRate = 44100 const sourceRate = tones.SampleRate
frequency := float32(110 * math.Pow(2, percentage/25)) native := tones.Samples(tones.ProgressFrequency(percentage), 40, triangle)
cycleLength := float64(float32(sourceRate) / frequency) count := len(native)
samplesPerCycle := int(cycleLength)
count := sourceRate * 40 / 1000
count += samplesPerCycle - count%samplesPerCycle
source := make([]float32, count) source := make([]float32, count)
for index := range source { for index, value := range native {
phase := float64(index) * 2 * math.Pi / cycleLength
wave := min(1.0, max(-1.0, math.Sin(phase)*2))
if triangle {
wave = 2 / math.Pi * math.Asin(math.Sin(phase))
}
value := int16(wave * 7000)
source[index] = float32(value) / 32768 source[index] = float32(value) / 32768
} }
frames := (count*sampleRate + sourceRate - 1) / sourceRate frames := (count*sampleRate + sourceRate - 1) / sourceRate
+2 -46
View File
@@ -6,8 +6,6 @@ package speech
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"sort"
"strings" "strings"
"time" "time"
"unicode" "unicode"
@@ -115,50 +113,8 @@ func parse_voices(rows []string) ([]Voice, error) {
return voices, nil return voices, nil
} }
func Normalize_language(value string) string { var Normalize_language = sd.NormalizeLanguage
value = strings.Split(strings.Split(value, ".")[0], "@")[0] var Language_voices = sd.LanguageVoices
return strings.ToLower(strings.ReplaceAll(value, "_", "-"))
}
// Language_voices follows Cthulhu's eSpeak selection: exact dialect, then base
// language, with unmodified names before '+' variants. Empty means locale.
// Unknown locales retain the full catalog; explicit languages remain exact.
func Language_voices(voices []Voice, language string) []Voice {
explicit := language != ""
if !explicit {
for _, key := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
if language = os.Getenv(key); language != "" {
break
}
}
}
language = Normalize_language(language)
if !explicit && (language == "" || language == "c" || language == "posix") {
language = "en-us"
}
languages := []string{language}
if !explicit {
languages = append(languages, strings.SplitN(language, "-", 2)[0])
}
for _, match := range languages {
var selected []Voice
for _, voice := range voices {
if Normalize_language(voice.Language) == match {
selected = append(selected, voice)
}
}
if len(selected) > 0 {
sort.SliceStable(selected, func(i, j int) bool {
return !strings.Contains(selected[i].Name, "+") && strings.Contains(selected[j].Name, "+")
})
return selected
}
}
if explicit {
return nil
}
return voices
}
// Prepare checks membership because SSIP SET may accept unknown synthesis // Prepare checks membership because SSIP SET may accept unknown synthesis
// names without verifying them. The resulting client has not spoken anything. // names without verifying them. The resulting client has not spoken anything.
-27
View File
@@ -5,7 +5,6 @@ package speech
import ( import (
"fmt" "fmt"
"reflect"
"strings" "strings"
"testing" "testing"
) )
@@ -58,32 +57,6 @@ func TestBoundedRepliesAndInjection(t *testing.T) {
} }
} }
func TestEspeakLocaleDialectBaseAndExplicitLanguage(t *testing.T) {
voices := []Voice{{Name: "US+Variant", Language: "en-US"}, {Name: "German", Language: "de"}, {Name: "US", Language: "en-US"}, {Name: "English", Language: "en"}}
t.Setenv("LC_ALL", "en_US.UTF-8")
got := Language_voices(voices, "")
if !reflect.DeepEqual(got, []Voice{voices[2], voices[0]}) {
t.Fatal(got)
}
t.Setenv("LC_ALL", "en_AU.UTF-8")
if got := Language_voices(voices, ""); !reflect.DeepEqual(got, []Voice{voices[3]}) {
t.Fatal(got)
}
if got := Language_voices(voices, "de"); !reflect.DeepEqual(got, []Voice{voices[1]}) {
t.Fatal(got)
}
if got := Language_voices(voices, "unknown"); len(got) != 0 {
t.Fatal(got)
}
t.Setenv("LC_ALL", "zz_ZZ")
if got := Language_voices(voices, ""); !reflect.DeepEqual(got, voices) {
t.Fatal(got)
}
if voices[0].Name != "US+Variant" {
t.Fatal("catalog reordered in place")
}
}
func TestCandidateRejectionLeavesOriginalClientUsable(t *testing.T) { func TestCandidateRejectionLeavesOriginalClientUsable(t *testing.T) {
server := new_fake_server(t, false) server := new_fake_server(t, false)
original, err := Open(Options{Socket: server.path}) original, err := Open(Options{Socket: server.path})
+11 -43
View File
@@ -6,12 +6,13 @@ package speech
import ( import (
"errors" "errors"
"fmt" "fmt"
"math"
"path/filepath" "path/filepath"
"slices" "slices"
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"git.stormux.org/storm/screenreader-common/hardware"
) )
var errHardwareCanceled = errors.New("hardware speech write canceled") var errHardwareCanceled = errors.New("hardware speech write canceled")
@@ -100,25 +101,15 @@ func hardware_parameters(options Options) error {
return parameters.Validate() return parameters.Validate()
} }
// Python's normalized 0..1 values correspond to the shared -100..100 scale. func (c *HardwareClient) profile() hardware.Protocol {
// RoundToEven matches Python round, including LiteTalk's midpoint volume 4. if c.usb {
func hardware_scale(value, minimum, maximum int) int { return hardware.DECtalkUSB()
return int(math.RoundToEven(float64(minimum) + float64(value+100)*float64(maximum-minimum)/200))
} }
return hardware.Serial(c.dectalk)
func dectalk_scale(value, minimum, normal, maximum int) int {
if value <= 0 {
return hardware_scale(value*2+100, minimum, normal)
} }
return hardware_scale(value*2-100, normal, maximum)
}
func (c *HardwareClient) commands() [3]string { func (c *HardwareClient) commands() [3]string {
p := c.parameters rate, pitch, volume := float64(c.parameters.Rate), float64(c.parameters.Pitch), float64(c.parameters.Volume)
if c.dectalk { return c.profile().Commands(hardware.Parameters{Rate: &rate, Pitch: &pitch, Volume: &volume})
return [3]string{fmt.Sprintf("[:ra %d]", dectalk_scale(p.Rate, 75, 180, 650)), fmt.Sprintf("[:dv ap %d]", dectalk_scale(p.Pitch, 50, 122, 350)), fmt.Sprintf("[:dv g5 %d]", hardware_scale(p.Volume, 60, 86))}
}
return [3]string{fmt.Sprintf("\x01%dS", hardware_scale(p.Rate, 0, 9)), fmt.Sprintf("\x01%dP", hardware_scale(p.Pitch, 0, 99)), fmt.Sprintf("\x01%dV", hardware_scale(p.Volume, 0, 9))}
} }
func (c *HardwareClient) write(data []byte, generation uint64) error { func (c *HardwareClient) write(data []byte, generation uint64) error {
@@ -179,20 +170,7 @@ func (c *HardwareClient) Say(text string) error {
if err := c.configure(generation); err != nil { if err := c.configure(generation); err != nil {
return ignore_hardware_cancel(err) return ignore_hardware_cancel(err)
} }
var clean strings.Builder return ignore_hardware_cancel(c.write(c.profile().Text(text), generation))
for _, char := range text {
if char < 0x20 || char > 0x7e {
char = ' '
}
clean.WriteRune(char)
}
prepared := clean.String()
if c.dectalk {
prepared = strings.ReplaceAll(prepared, "[:", "[ :") + "\x0b"
} else {
prepared += "\r"
}
return ignore_hardware_cancel(c.write([]byte(prepared), generation))
} }
func (c *HardwareClient) Cancel() error { func (c *HardwareClient) Cancel() error {
@@ -200,12 +178,7 @@ func (c *HardwareClient) Cancel() error {
if c.closed.Load() { if c.closed.Load() {
return nil return nil
} }
command := []byte{0x18} command := c.profile().Cancel()
if c.usb {
command = []byte{0x06}
} else if c.dectalk {
command = []byte{0x03}
}
return c.port.Cancel(command) return c.port.Cancel(command)
} }
@@ -216,12 +189,7 @@ func (c *HardwareClient) Close() {
c.generation.Add(1) c.generation.Add(1)
// Cancel audible device buffers before releasing ownership. Port writes // Cancel audible device buffers before releasing ownership. Port writes
// are bounded, including when the device is disconnected or flow-stopped. // are bounded, including when the device is disconnected or flow-stopped.
command := []byte{0x18} command := c.profile().Cancel()
if c.usb {
command = []byte{0x06}
} else if c.dectalk {
command = []byte{0x03}
}
_ = c.port.Cancel(command) _ = c.port.Cancel(command)
c.port.Close() c.port.Close()
} }