Use common v0.8.0 UI, transport, and translation APIs

This commit is contained in:
Storm Dragon committed 2026-11-16 20:10:47 -05:00
1 parent 317303adb7
commit 92fd479336
344 files changed
+4102 -4973

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ type EnchantDictionary struct {
native *C.SpellDictionary
}
func open_dictionary(language string) (Dictionary, error) {
func openDictionary(language string) (Dictionary, error) {
if language == "" {
return nil, fmt.Errorf("the session has no spelling language")
}
+11 -10
View File
@@ -17,11 +17,11 @@ import (
"time"
)
func Exceptions_path(home string) string {
func ExceptionsPath(home string) string {
return filepath.Join(home, ".local/share/stormux/fenrirscreenreader/spelling/exceptions.json")
}
func load_exceptions(path string) (map[string]string, error) {
func loadExceptions(path string) (map[string]string, error) {
words := make(map[string]string)
file, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
@@ -43,7 +43,7 @@ func load_exceptions(path string) (map[string]string, error) {
return nil, err
}
for _, word := range entries {
if !valid_word(word) {
if !validWord(word) {
return nil, fmt.Errorf("invalid exceptions file")
}
words[strings.ToLower(word)] = word
@@ -51,7 +51,7 @@ func load_exceptions(path string) (map[string]string, error) {
return words, nil
}
func exception_list(words map[string]string) []string {
func exceptionList(words map[string]string) []string {
entries := make([]string, 0, len(words))
for _, word := range words {
entries = append(entries, word)
@@ -62,7 +62,7 @@ func exception_list(words map[string]string) []string {
// Each edit reloads the latest list while holding a stable, per-file lock.
// Atomic replacement alone cannot protect against another reader's stale copy.
func update_exceptions(ctx context.Context, path string, operation Operation, word string) (map[string]string, error) {
func updateExceptions(ctx context.Context, path string, operation Operation, word string) (map[string]string, error) {
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return nil, err
}
@@ -99,7 +99,7 @@ func update_exceptions(ctx context.Context, path string, operation Operation, wo
case <-timer.C:
}
}
words, err := load_exceptions(path)
words, err := loadExceptions(path)
if err != nil {
return nil, err
}
@@ -109,14 +109,14 @@ func update_exceptions(ctx context.Context, path string, operation Operation, wo
} else {
delete(words, key)
}
if err := save_exceptions(path, words); err != nil {
if err := saveExceptions(path, words); err != nil {
return nil, err
}
return words, nil
}
func save_exceptions(path string, words map[string]string) error {
data, err := json.MarshalIndent(exception_list(words), "", " ")
func saveExceptions(path string, words map[string]string) error {
data, err := json.MarshalIndent(exceptionList(words), "", " ")
if err != nil {
return err
}
@@ -131,7 +131,8 @@ func save_exceptions(path string, words map[string]string) error {
if err != nil {
return err
}
defer os.Remove(file.Name())
// After a successful rename the temporary name no longer exists.
defer func() { _ = os.Remove(file.Name()) }()
if _, err := file.Write(append(data, '\n')); err != nil {
file.Close()
return err
+19 -19
View File
@@ -20,12 +20,12 @@ import (
func TestExceptionEditsPreserveOtherReadersChanges(t *testing.T) {
path := filepath.Join(t.TempDir(), "exceptions.json")
options := Options{ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{}, nil }}
first, second := New_service(context.Background(), options), New_service(context.Background(), options)
first, second := NewService(context.Background(), options), NewService(context.Background(), options)
defer first.Close()
defer second.Close()
// Both readers load the original list, then the user switches between them.
receive_result(t, first, Request{Operation: Inspect})
receive_result(t, second, Request{Operation: Inspect})
receiveResult(t, first, Request{Operation: Inspect})
receiveResult(t, second, Request{Operation: Inspect})
for _, edit := range []struct {
service *Service
request Request
@@ -37,12 +37,12 @@ func TestExceptionEditsPreserveOtherReadersChanges(t *testing.T) {
{second, Request{Operation: Add, Word: "Gamma"}, []string{"Beta", "Gamma"}},
{first, Request{Operation: Add, Word: "Alpha"}, []string{"Alpha", "Beta", "Gamma"}},
} {
result := receive_result(t, edit.service, edit.request)
result := receiveResult(t, edit.service, edit.request)
if result.Err != nil || !reflect.DeepEqual(result.Exceptions, edit.want) {
t.Fatalf("edit %v: result=%+v, want=%v", edit.request, result, edit.want)
}
words, err := load_exceptions(path)
if err != nil || !reflect.DeepEqual(exception_list(words), edit.want) {
words, err := loadExceptions(path)
if err != nil || !reflect.DeepEqual(exceptionList(words), edit.want) {
t.Fatalf("saved exceptions=%v, error=%v, want=%v", words, err, edit.want)
}
}
@@ -54,10 +54,10 @@ func TestExceptionWriterProcess(t *testing.T) {
if path == "" {
return
}
service := New_service(context.Background(), Options{ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{}, nil }})
service := NewService(context.Background(), Options{ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{}, nil }})
defer service.Close()
encoder, decoder := json.NewEncoder(os.Stdout), json.NewDecoder(os.Stdin)
result := receive_result(t, service, Request{Operation: Inspect})
result := receiveResult(t, service, Request{Operation: Inspect})
if result.Err != nil {
t.Fatal(result.Err)
}
@@ -72,7 +72,7 @@ func TestExceptionWriterProcess(t *testing.T) {
}
t.Fatal(err)
}
result := receive_result(t, service, request)
result := receiveResult(t, service, request)
if result.Err != nil {
t.Fatal(result.Err)
}
@@ -88,7 +88,7 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) {
encoder *json.Encoder
decoder *json.Decoder
}
start_writer := func() Writer {
startWriter := func() Writer {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestExceptionWriterProcess$")
cmd.Env = append(os.Environ(), "FENRIR_EXCEPTION_TEST_PATH="+path)
@@ -122,7 +122,7 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) {
}
return writer
}
first, second := start_writer(), start_writer()
first, second := startWriter(), startWriter()
for _, edit := range []struct {
writer Writer
word string
@@ -137,8 +137,8 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) {
t.Fatal(err)
}
}
words, err := load_exceptions(path)
if err != nil || !reflect.DeepEqual(exception_list(words), []string{"Alpha", "Beta"}) {
words, err := loadExceptions(path)
if err != nil || !reflect.DeepEqual(exceptionList(words), []string{"Alpha", "Beta"}) {
t.Fatal("lost concurrent addition", words, err)
}
info, err := os.Stat(path + ".lock")
@@ -149,7 +149,7 @@ func TestConcurrentExceptionProcessesKeepBothEdits(t *testing.T) {
func TestExceptionLockCancellationAndInvalidStorePreserveData(t *testing.T) {
path := filepath.Join(t.TempDir(), "exceptions.json")
if err := save_exceptions(path, map[string]string{"alpha": "Alpha"}); err != nil {
if err := saveExceptions(path, map[string]string{"alpha": "Alpha"}); err != nil {
t.Fatal(err)
}
lock, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0600)
@@ -162,23 +162,23 @@ func TestExceptionLockCancellationAndInvalidStorePreserveData(t *testing.T) {
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
if _, err := update_exceptions(ctx, path, Add, "Beta"); !errors.Is(err, context.DeadlineExceeded) {
if _, err := updateExceptions(ctx, path, Add, "Beta"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatal("lock wait ignored cancellation", err)
}
words, err := load_exceptions(path)
if err != nil || !reflect.DeepEqual(exception_list(words), []string{"Alpha"}) {
words, err := loadExceptions(path)
if err != nil || !reflect.DeepEqual(exceptionList(words), []string{"Alpha"}) {
t.Fatal("cancelled edit changed data", words, err)
}
if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_UN); err != nil {
t.Fatal(err)
}
if _, err := update_exceptions(context.Background(), path, Add, "Beta"); err != nil {
if _, err := updateExceptions(context.Background(), path, Add, "Beta"); err != nil {
t.Fatal("edit failed after lock release", err)
}
if err := os.WriteFile(path, []byte("invalid JSON"), 0600); err != nil {
t.Fatal(err)
}
if _, err := update_exceptions(context.Background(), path, Add, "Gamma"); err == nil {
if _, err := updateExceptions(context.Background(), path, Add, "Gamma"); err == nil {
t.Fatal("edit overwrote invalid shared file")
}
data, err := os.ReadFile(path)
+8 -8
View File
@@ -48,7 +48,7 @@ type Service struct {
once sync.Once
}
func New_service(parent context.Context, options Options) *Service {
func NewService(parent context.Context, options Options) *Service {
ctx, cancel := context.WithCancel(parent)
s := &Service{ctx: ctx, cancel: cancel, requests: make(chan Request, 16), automatic: make(chan Request, 32), results: make(chan Result, 32), done: make(chan struct{})}
go s.run(options)
@@ -84,7 +84,7 @@ type commandEntry struct {
// Commands are tested as executable PATH entries, never executed. Builtins are
// accepted separately because they have no executable file. Aliases/functions
// belong to the child shell and cannot be discovered from the reader process.
func valid_command(word string, cache map[string]commandEntry) bool {
func validCommand(word string, cache map[string]commandEntry) bool {
if strings.ContainsAny(word, "/\\\x00") {
return false
}
@@ -107,13 +107,13 @@ func (s *Service) run(options Options) {
defer close(s.done)
open := options.OpenDictionary
if open == nil {
open = open_dictionary
open = openDictionary
}
dict, dictionaryErr := open(options.Language)
if dict != nil {
defer dict.Close()
}
words, storeErr := load_exceptions(options.ExceptionsPath)
words, storeErr := loadExceptions(options.ExceptionsPath)
cache := make(map[string]commandEntry)
for {
var request Request
@@ -133,12 +133,12 @@ func (s *Service) run(options Options) {
result := Result{Request: request, Language: options.Language, Word: Word(request.Word), Available: dict != nil && dictionaryErr == nil, DictionaryError: dictionaryErr, Err: storeErr}
if request.Operation == Add || request.Operation == Remove {
result.Word = strings.TrimSpace(request.Word)
if result.Err == nil && !valid_word(result.Word) {
if result.Err == nil && !validWord(result.Word) {
result.Err = fmt.Errorf("enter a single word of at most 128 characters")
}
if result.Err == nil {
var draft map[string]string
draft, result.Err = update_exceptions(s.ctx, options.ExceptionsPath, request.Operation, result.Word)
draft, result.Err = updateExceptions(s.ctx, options.ExceptionsPath, request.Operation, result.Word)
if result.Err == nil {
words = draft
}
@@ -146,7 +146,7 @@ func (s *Service) run(options Options) {
} else if result.Err == nil && result.Word != "" {
_, result.Correct = words[strings.ToLower(result.Word)]
if request.Operation == Automatic && !result.Correct {
result.Correct = valid_command(result.Word, cache)
result.Correct = validCommand(result.Word, cache)
}
if !result.Correct && result.Available {
result.Correct, result.Err = dict.Check(result.Word)
@@ -156,7 +156,7 @@ func (s *Service) run(options Options) {
}
}
if request.Operation != Automatic {
result.Exceptions = exception_list(words)
result.Exceptions = exceptionList(words)
}
select {
case s.results <- result:
+24 -24
View File
@@ -30,7 +30,7 @@ func (*TestDictionary) Suggest(string) ([]string, error) {
}
func (*TestDictionary) Close() {}
func receive_result(t *testing.T, service *Service, request Request) Result {
func receiveResult(t *testing.T, service *Service, request Request) Result {
t.Helper()
if !service.Submit(request) {
t.Fatal("request not accepted")
@@ -81,18 +81,18 @@ func TestGlobalExceptionsPersistenceRemoveAndFailedWriteIsolation(t *testing.T)
path := filepath.Join(t.TempDir(), "spelling", "exceptions.json")
dict := &TestDictionary{}
options := Options{Language: "en_US", ExceptionsPath: path, OpenDictionary: func(string) (Dictionary, error) { return dict, nil }}
service := New_service(context.Background(), options)
service := NewService(context.Background(), options)
defer service.Close()
if got := receive_result(t, service, Request{Word: "helo"}); got.Correct || !reflect.DeepEqual(got.Suggestions, []string{"hello", "help", "held"}) {
if got := receiveResult(t, service, Request{Word: "helo"}); got.Correct || !reflect.DeepEqual(got.Suggestions, []string{"hello", "help", "held"}) {
t.Fatal(got)
}
for _, word := range []string{"Fenrir", "Café"} {
if got := receive_result(t, service, Request{Operation: Add, Word: word}); got.Err != nil {
if got := receiveResult(t, service, Request{Operation: Add, Word: word}); got.Err != nil {
t.Fatal(got)
}
}
for _, operation := range []Operation{Inspect, Automatic} {
if got := receive_result(t, service, Request{Operation: operation, Word: "FENRIR"}); !got.Correct || len(got.Suggestions) != 0 {
if got := receiveResult(t, service, Request{Operation: operation, Word: "FENRIR"}); !got.Correct || len(got.Suggestions) != 0 {
t.Fatal(got)
}
}
@@ -105,15 +105,15 @@ func TestGlobalExceptionsPersistenceRemoveAndFailedWriteIsolation(t *testing.T)
}
service.Close()
options.Language = "de_DE"
service = New_service(context.Background(), options)
service = NewService(context.Background(), options)
defer service.Close()
if got := receive_result(t, service, Request{Word: "café"}); !got.Correct {
if got := receiveResult(t, service, Request{Word: "café"}); !got.Correct {
t.Fatal("exception was language-specific", got)
}
if got := receive_result(t, service, Request{Operation: Remove, Word: "Fenrir"}); got.Err != nil || !reflect.DeepEqual(got.Exceptions, []string{"Café"}) {
if got := receiveResult(t, service, Request{Operation: Remove, Word: "Fenrir"}); got.Err != nil || !reflect.DeepEqual(got.Exceptions, []string{"Café"}) {
t.Fatal(got)
}
if got := receive_result(t, service, Request{Word: "Fenrir"}); got.Correct {
if got := receiveResult(t, service, Request{Word: "Fenrir"}); got.Correct {
t.Fatal("removed exception accepted", got)
}
// Replace the parent with a file so failure is deterministic even as root.
@@ -123,16 +123,16 @@ func TestGlobalExceptionsPersistenceRemoveAndFailedWriteIsolation(t *testing.T)
if err := os.WriteFile(filepath.Dir(path), []byte("blocked"), 0600); err != nil {
t.Fatal(err)
}
if got := receive_result(t, service, Request{Operation: Add, Word: "wrongword"}); got.Err == nil {
if got := receiveResult(t, service, Request{Operation: Add, Word: "wrongword"}); got.Err == nil {
t.Fatal("failed write announced success", got)
}
if got := receive_result(t, service, Request{Word: "wrongword"}); got.Correct {
if got := receiveResult(t, service, Request{Word: "wrongword"}); got.Correct {
t.Fatal("failed addition changed memory", got)
}
if got := receive_result(t, service, Request{Operation: Remove, Word: "Café"}); got.Err == nil {
if got := receiveResult(t, service, Request{Operation: Remove, Word: "Café"}); got.Err == nil {
t.Fatal(got)
}
if got := receive_result(t, service, Request{Word: "café"}); !got.Correct {
if got := receiveResult(t, service, Request{Word: "café"}); !got.Correct {
t.Fatal("failed removal changed memory", got)
}
}
@@ -151,10 +151,10 @@ func TestPATHCommandsBuiltinsAndNeverExecute(t *testing.T) {
t.Fatal(err)
}
dict := &TestDictionary{}
service := New_service(context.Background(), Options{ExceptionsPath: filepath.Join(root, "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return dict, nil }})
service := NewService(context.Background(), Options{ExceptionsPath: filepath.Join(root, "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return dict, nil }})
defer service.Close()
for _, word := range []string{"tac", "cd", "readarray", "ulimit"} {
if got := receive_result(t, service, Request{Operation: Automatic, Word: word}); !got.Correct {
if got := receiveResult(t, service, Request{Operation: Automatic, Word: word}); !got.Correct {
t.Fatal(word, got)
}
}
@@ -162,35 +162,35 @@ func TestPATHCommandsBuiltinsAndNeverExecute(t *testing.T) {
t.Fatal(dict.calls)
}
for _, word := range []string{"notexecutable", "directory", "typo"} {
if got := receive_result(t, service, Request{Operation: Automatic, Word: word}); got.Correct {
if got := receiveResult(t, service, Request{Operation: Automatic, Word: word}); got.Correct {
t.Fatal(word, got)
}
}
if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
t.Fatal("command executed", err)
}
if got := receive_result(t, service, Request{Word: "tac"}); got.Correct {
if got := receiveResult(t, service, Request{Word: "tac"}); got.Correct {
t.Fatal("manual lexical check skipped", got)
}
}
func TestMissingDictionaryStillAllowsExceptionManagement(t *testing.T) {
service := New_service(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return nil, errors.New("missing dictionary") }})
service := NewService(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return nil, errors.New("missing dictionary") }})
defer service.Close()
if got := receive_result(t, service, Request{Word: "hello"}); got.Available || got.DictionaryError == nil || got.Correct {
if got := receiveResult(t, service, Request{Word: "hello"}); got.Available || got.DictionaryError == nil || got.Correct {
t.Fatal(got)
}
if got := receive_result(t, service, Request{Operation: Add, Word: "Fenrir"}); got.Err != nil {
if got := receiveResult(t, service, Request{Operation: Add, Word: "Fenrir"}); got.Err != nil {
t.Fatal(got)
}
if got := receive_result(t, service, Request{Word: "fenrir"}); !got.Correct {
if got := receiveResult(t, service, Request{Word: "fenrir"}); !got.Correct {
t.Fatal(got)
}
}
func TestSlowDictionaryDoesNotBlockInputSubmissionOrShutdown(t *testing.T) {
gate := make(chan struct{})
service := New_service(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{gate: gate}, nil }})
service := NewService(context.Background(), Options{ExceptionsPath: filepath.Join(t.TempDir(), "exceptions.json"), OpenDictionary: func(string) (Dictionary, error) { return &TestDictionary{gate: gate}, nil }})
started := time.Now()
for range 100 {
service.Submit(Request{Operation: Automatic, Word: "helo"})
@@ -206,7 +206,7 @@ func TestSlowDictionaryDoesNotBlockInputSubmissionOrShutdown(t *testing.T) {
}
func TestActualEnchantDictionaryAndRankedSuggestions(t *testing.T) {
dict, err := open_dictionary("en_US")
dict, err := openDictionary("en_US")
if err != nil {
t.Skip(err)
}
@@ -220,7 +220,7 @@ func TestActualEnchantDictionaryAndRankedSuggestions(t *testing.T) {
if suggestions, err := dict.Suggest("helo"); err != nil || len(suggestions) == 0 {
t.Fatal(suggestions, err)
}
if dict, err := open_dictionary("zz_ZZ"); err == nil {
if dict, err := openDictionary("zz_ZZ"); err == nil {
dict.Close()
t.Fatal("missing dictionary accepted")
}
+4 -4
View File
@@ -15,13 +15,13 @@ import (
func Language() string {
for _, name := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
if value := os.Getenv(name); value != "" {
return language_tag(value)
return languageTag(value)
}
}
return ""
}
func language_tag(value string) string {
func languageTag(value string) string {
value, _, _ = strings.Cut(strings.TrimSpace(value), ".")
value, _, _ = strings.Cut(value, "@")
if value == "C" || value == "POSIX" {
@@ -45,13 +45,13 @@ func Word(value string) string {
return ""
}
value = strings.TrimFunc(value, func(char rune) bool { return !unicode.IsLetter(char) && !unicode.IsMark(char) })
if !valid_word(value) {
if !validWord(value) {
return ""
}
return value
}
func valid_word(value string) bool {
func validWord(value string) bool {
if !utf8.ValidString(value) || utf8.RuneCountInString(value) > 128 || value == "" {
return false
}