Use common v0.8.0 UI, transport, and translation APIs
This commit is contained in:
1 parent
317303adb7
commit
92fd479336
344 files changed
+4102
-4973
No files matched your search
@@ -29,9 +29,9 @@ import (
|
||||
|
||||
type Target struct{ Display, Authority string }
|
||||
|
||||
// Display_candidates never falls through an explicit setting or DISPLAY to a
|
||||
// DisplayCandidates never falls through an explicit setting or DISPLAY to a
|
||||
// different session. Discovery uses existing local sockets, not a fixed :0..:9.
|
||||
func Display_candidates(configured, current, authority, home, socketDirectory string) ([]Target, error) {
|
||||
func DisplayCandidates(configured, current, authority, home, socketDirectory string) ([]Target, error) {
|
||||
if authority == "" {
|
||||
authority = filepath.Join(home, ".Xauthority")
|
||||
}
|
||||
@@ -71,14 +71,14 @@ func Display_candidates(configured, current, authority, home, socketDirectory st
|
||||
return targets, nil
|
||||
}
|
||||
|
||||
func system_targets(configured string) ([]Target, error) {
|
||||
func systemTargets(configured string) ([]Target, error) {
|
||||
home, _ := os.UserHomeDir()
|
||||
if os.Geteuid() == 0 && os.Getenv("SUDO_UID") != "" {
|
||||
if caller, err := user.LookupId(os.Getenv("SUDO_UID")); err == nil {
|
||||
home = caller.HomeDir
|
||||
}
|
||||
}
|
||||
targets, err := Display_candidates(configured, os.Getenv("DISPLAY"), os.Getenv("XAUTHORITY"), home, "/tmp/.X11-unix")
|
||||
targets, err := DisplayCandidates(configured, os.Getenv("DISPLAY"), os.Getenv("XAUTHORITY"), home, "/tmp/.X11-unix")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -34,9 +34,9 @@ type History struct {
|
||||
limit int
|
||||
}
|
||||
|
||||
func New_history(limit int) *History { return &History{limit: max(1, limit)} }
|
||||
func NewHistory(limit int) *History { return &History{limit: max(1, limit)} }
|
||||
|
||||
func Validate_text(text string) error {
|
||||
func ValidateText(text string) error {
|
||||
if len(text) > MaxBytes || !utf8.ValidString(text) {
|
||||
return fmt.Errorf("clipboard text must be valid UTF-8 and at most 4 MiB")
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func Validate_text(text string) error {
|
||||
}
|
||||
|
||||
func (h *History) Add(text string) error {
|
||||
if err := Validate_text(text); err != nil {
|
||||
if err := ValidateText(text); err != nil {
|
||||
return err
|
||||
}
|
||||
h.entries = append([]string{text}, h.entries[:min(len(h.entries), h.limit-1)]...)
|
||||
@@ -64,11 +64,11 @@ func (h *History) Move(delta int) {
|
||||
h.index = (h.index + delta + len(h.entries)) % len(h.entries)
|
||||
}
|
||||
}
|
||||
func (h *History) First() { h.index = 0 }
|
||||
func (h *History) Last() { h.index = max(0, len(h.entries)-1) }
|
||||
func (h *History) At_first() bool { return len(h.entries) > 0 && h.index == 0 }
|
||||
func (h *History) At_last() bool { return len(h.entries) > 0 && h.index == len(h.entries)-1 }
|
||||
func (h *History) Clear() { h.entries, h.index = nil, 0 }
|
||||
func (h *History) First() { h.index = 0 }
|
||||
func (h *History) Last() { h.index = max(0, len(h.entries)-1) }
|
||||
func (h *History) AtFirst() bool { return len(h.entries) > 0 && h.index == 0 }
|
||||
func (h *History) AtLast() bool { return len(h.entries) > 0 && h.index == len(h.entries)-1 }
|
||||
func (h *History) Clear() { h.entries, h.index = nil, 0 }
|
||||
|
||||
// Refresh adopts shared entries while retaining this reader's selected copy.
|
||||
// Count duplicates from the oldest end so a new identical copy stays distinct.
|
||||
|
||||
@@ -27,18 +27,18 @@ import (
|
||||
)
|
||||
|
||||
func TestHistoryLimitUnicodeWrappingAndClear(t *testing.T) {
|
||||
history := New_history(2)
|
||||
history := NewHistory(2)
|
||||
for _, text := range []string{"old", "é界\nnext", "new"} {
|
||||
if err := history.Add(text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
history.Move(-1)
|
||||
if text, ok := history.Current(); !ok || text != "é界\nnext" || !history.At_last() {
|
||||
if text, ok := history.Current(); !ok || text != "é界\nnext" || !history.AtLast() {
|
||||
t.Fatal(text, ok)
|
||||
}
|
||||
history.Move(1)
|
||||
if text, _ := history.Current(); text != "new" || !history.At_first() {
|
||||
if text, _ := history.Current(); text != "new" || !history.AtFirst() {
|
||||
t.Fatal(text)
|
||||
}
|
||||
history.Last()
|
||||
@@ -60,7 +60,7 @@ func TestHistoryLimitUnicodeWrappingAndClear(t *testing.T) {
|
||||
func TestDisplaySelectionDoesNotFallThroughAndDiscoversHigherNumbers(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for _, fixture := range []struct{ configured, current, want string }{{":8", ":7", ":8"}, {"", ":7", ":7"}} {
|
||||
targets, err := Display_candidates(fixture.configured, fixture.current, "/test/auth", root, "/does-not-exist")
|
||||
targets, err := DisplayCandidates(fixture.configured, fixture.current, "/test/auth", root, "/does-not-exist")
|
||||
if err != nil || len(targets) != 1 || targets[0] != (Target{fixture.want, "/test/auth"}) {
|
||||
t.Fatal(targets, err)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ func TestDisplaySelectionDoesNotFallThroughAndDiscoversHigherNumbers(t *testing.
|
||||
if err := os.WriteFile(filepath.Join(root, "X3"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
targets, err := Display_candidates("", "", "", root, root)
|
||||
targets, err := DisplayCandidates("", "", "", root, root)
|
||||
if err != nil || len(targets) != 1 || targets[0].Display != ":42" {
|
||||
t.Fatal(targets, err)
|
||||
}
|
||||
@@ -82,7 +82,7 @@ func TestDisplaySelectionDoesNotFallThroughAndDiscoversHigherNumbers(t *testing.
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer other.Close()
|
||||
if _, err := Display_candidates("", "", "", root, root); err == nil {
|
||||
if _, err := DisplayCandidates("", "", "", root, root); err == nil {
|
||||
t.Fatal("silently chose among multiple desktops")
|
||||
}
|
||||
}
|
||||
@@ -91,32 +91,32 @@ func TestFileRoundTripBoundsPrivacyAndNonregularInput(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
path := filepath.Join(root, "clipboard")
|
||||
text := "é界\nsecond line\n"
|
||||
if err := write_file(path, text); err != nil {
|
||||
if err := writeFile(path, text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := read_file(path); err != nil || got != text {
|
||||
if got, err := readFile(path); err != nil || got != text {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal(info, err)
|
||||
}
|
||||
if err := write_file(path, strings.Repeat("x", MaxBytes+1)); err == nil {
|
||||
if err := writeFile(path, strings.Repeat("x", MaxBytes+1)); err == nil {
|
||||
t.Fatal("oversize export accepted")
|
||||
}
|
||||
if got, _ := read_file(path); got != text {
|
||||
if got, _ := readFile(path); got != text {
|
||||
t.Fatal("failed export changed original")
|
||||
}
|
||||
if err := syscall.Mkfifo(filepath.Join(root, "fifo"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := read_file(filepath.Join(root, "fifo")); err == nil {
|
||||
if _, err := readFile(filepath.Join(root, "fifo")); err == nil {
|
||||
t.Fatal("FIFO accepted")
|
||||
}
|
||||
if err := os.WriteFile(path, []byte{0xff}, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := read_file(path); err == nil {
|
||||
if _, err := readFile(path); err == nil {
|
||||
t.Fatal("invalid UTF-8 imported")
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ type Snapshot struct {
|
||||
Selected int `json:"selected"`
|
||||
}
|
||||
|
||||
func History_path(home string, terminalMode bool) string {
|
||||
func HistoryPath(home string, terminalMode bool) string {
|
||||
if terminalMode {
|
||||
return filepath.Join(home, ".local/state/fenrir/clipboard/terminal.json")
|
||||
}
|
||||
@@ -36,13 +36,13 @@ func (h *History) Snapshot() Snapshot {
|
||||
return Snapshot{Version: 1, Entries: append([]string{}, h.entries...), Selected: h.index}
|
||||
}
|
||||
|
||||
func validate_snapshot(state Snapshot) error {
|
||||
func validateSnapshot(state Snapshot) error {
|
||||
if state.Version != 1 || len(state.Entries) > 10000 || state.Selected < 0 || (len(state.Entries) == 0 && state.Selected != 0) || (len(state.Entries) > 0 && state.Selected >= len(state.Entries)) {
|
||||
return fmt.Errorf("invalid clipboard history")
|
||||
}
|
||||
total := 0
|
||||
for _, text := range state.Entries {
|
||||
if err := Validate_text(text); err != nil {
|
||||
if err := ValidateText(text); err != nil {
|
||||
return err
|
||||
}
|
||||
total += len(text)
|
||||
@@ -54,7 +54,7 @@ func validate_snapshot(state Snapshot) error {
|
||||
}
|
||||
|
||||
func (h *History) Restore(state Snapshot) error {
|
||||
if err := validate_snapshot(state); err != nil {
|
||||
if err := validateSnapshot(state); err != nil {
|
||||
return err
|
||||
}
|
||||
h.entries = append([]string(nil), state.Entries[:min(len(state.Entries), h.limit)]...)
|
||||
@@ -70,8 +70,8 @@ func (h *History) Resize(limit int) {
|
||||
|
||||
// A stable lock inode serializes only individual transactions. Closing it
|
||||
// releases ownership; another reader can immediately read, update or clear.
|
||||
func acquire_history(path string, create bool) (*os.File, error) {
|
||||
if err := private_directory(filepath.Dir(path), create); err != nil {
|
||||
func acquireHistory(path string, create bool) (*os.File, error) {
|
||||
if err := privateDirectory(filepath.Dir(path), create); err != nil {
|
||||
if !create && errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func acquire_history(path string, create bool) (*os.File, error) {
|
||||
err = nil
|
||||
}
|
||||
if err == nil {
|
||||
err = remove_temporary_history(path)
|
||||
err = removeTemporaryHistory(path)
|
||||
}
|
||||
if err != nil {
|
||||
file.Close()
|
||||
@@ -104,7 +104,7 @@ func acquire_history(path string, create bool) (*os.File, error) {
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func private_directory(path string, create bool) error {
|
||||
func privateDirectory(path string, create bool) error {
|
||||
if create {
|
||||
if err := os.MkdirAll(path, 0700); err != nil {
|
||||
return err
|
||||
@@ -120,9 +120,9 @@ func private_directory(path string, create bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func load_history(path string) (Snapshot, error) {
|
||||
func loadHistory(path string) (Snapshot, error) {
|
||||
empty := Snapshot{Version: 1}
|
||||
if err := private_directory(filepath.Dir(path), false); err != nil {
|
||||
if err := privateDirectory(filepath.Dir(path), false); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return empty, nil
|
||||
}
|
||||
@@ -154,14 +154,14 @@ func load_history(path string) (Snapshot, error) {
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return empty, fmt.Errorf("invalid clipboard history JSON")
|
||||
}
|
||||
if err := validate_snapshot(state); err != nil {
|
||||
if err := validateSnapshot(state); err != nil {
|
||||
return empty, err
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func save_history(path string, state Snapshot) error {
|
||||
if err := validate_snapshot(state); err != nil {
|
||||
func saveHistory(path string, state Snapshot) error {
|
||||
if err := validateSnapshot(state); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.Marshal(state)
|
||||
@@ -171,7 +171,7 @@ func save_history(path string, state Snapshot) error {
|
||||
if len(data) > maxHistoryBytes {
|
||||
return fmt.Errorf("clipboard history exceeds 64 MiB")
|
||||
}
|
||||
if err := private_directory(filepath.Dir(path), true); err != nil {
|
||||
if err := privateDirectory(filepath.Dir(path), true); err != nil {
|
||||
return err
|
||||
}
|
||||
// Do not replace symlinks, devices or directories supplied at the destination.
|
||||
@@ -186,7 +186,8 @@ func save_history(path string, state Snapshot) 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()) }()
|
||||
_, writeErr := file.Write(data)
|
||||
err = errors.Join(writeErr, file.Sync(), file.Close())
|
||||
if err != nil {
|
||||
@@ -195,11 +196,11 @@ func save_history(path string, state Snapshot) error {
|
||||
if err := os.Rename(file.Name(), path); err != nil {
|
||||
return err
|
||||
}
|
||||
return sync_directory(filepath.Dir(path))
|
||||
return syncDirectory(filepath.Dir(path))
|
||||
}
|
||||
|
||||
func remove_history(path string) error {
|
||||
if err := private_directory(filepath.Dir(path), false); err != nil {
|
||||
func removeHistory(path string) error {
|
||||
if err := privateDirectory(filepath.Dir(path), false); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
@@ -212,10 +213,10 @@ func remove_history(path string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return sync_directory(filepath.Dir(path))
|
||||
return syncDirectory(filepath.Dir(path))
|
||||
}
|
||||
|
||||
func sync_directory(path string) error {
|
||||
func syncDirectory(path string) error {
|
||||
dir, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -225,7 +226,7 @@ func sync_directory(path string) error {
|
||||
|
||||
// A killed process can leave an atomic-write temporary file. Only clean this
|
||||
// history's own files after acquiring its lock, including when clearing it.
|
||||
func remove_temporary_history(path string) error {
|
||||
func removeTemporaryHistory(path string) error {
|
||||
entries, err := os.ReadDir(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -17,14 +17,14 @@ import (
|
||||
|
||||
func TestPersistentHistoryRoundTripResizeAndPrivateModes(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
history := New_history(3)
|
||||
history := NewHistory(3)
|
||||
for _, text := range []string{"old", "é界\nsecond line", "🎃"} {
|
||||
if err := history.Add(text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
history.Move(1)
|
||||
store := New_persistence(path, false)
|
||||
store := NewPersistence(path, false)
|
||||
store.Enable(history.Snapshot(), 3)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -35,15 +35,15 @@ func TestPersistentHistoryRoundTripResizeAndPrivateModes(t *testing.T) {
|
||||
t.Fatal(info, err)
|
||||
}
|
||||
}
|
||||
store = New_persistence(path, true)
|
||||
store = NewPersistence(path, true)
|
||||
if store.LoadErr != nil {
|
||||
t.Fatal(store.LoadErr)
|
||||
}
|
||||
restored := New_history(2)
|
||||
restored := NewHistory(2)
|
||||
if err := restored.Restore(store.Initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := restored.Current(); got != "é界\nsecond line" || !restored.At_last() {
|
||||
if got, _ := restored.Current(); got != "é界\nsecond line" || !restored.AtLast() {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
@@ -62,11 +62,11 @@ func TestPersistentHistoryRoundTripResizeAndPrivateModes(t *testing.T) {
|
||||
|
||||
func TestPersistenceDisabledDoesNotReadOrCreateAndModesAreSeparate(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
terminalPath := History_path(home, true)
|
||||
if !strings.HasPrefix(terminalPath, home+string(os.PathSeparator)) || History_path(home, false) != "/var/lib/fenrir/clipboard/tty.json" || terminalPath == History_path(home, false) {
|
||||
t.Fatal(terminalPath, History_path(home, false))
|
||||
terminalPath := HistoryPath(home, true)
|
||||
if !strings.HasPrefix(terminalPath, home+string(os.PathSeparator)) || HistoryPath(home, false) != "/var/lib/fenrir/clipboard/tty.json" || terminalPath == HistoryPath(home, false) {
|
||||
t.Fatal(terminalPath, HistoryPath(home, false))
|
||||
}
|
||||
store := New_persistence(terminalPath, false)
|
||||
store := NewPersistence(terminalPath, false)
|
||||
if store.LoadErr != nil || len(store.Initial.Entries) != 0 {
|
||||
t.Fatal(store)
|
||||
}
|
||||
@@ -79,7 +79,7 @@ func TestPersistenceDisabledDoesNotReadOrCreateAndModesAreSeparate(t *testing.T)
|
||||
// A pre-existing malformed file is also ignored while disabled.
|
||||
path := filepath.Join(home, "malformed.json")
|
||||
os.WriteFile(path, []byte("not json"), 0600)
|
||||
store = New_persistence(path, false)
|
||||
store = NewPersistence(path, false)
|
||||
if store.LoadErr != nil {
|
||||
t.Fatal("disabled persistence read a file", store.LoadErr)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ func TestPersistenceDisabledDoesNotReadOrCreateAndModesAreSeparate(t *testing.T)
|
||||
func TestPersistenceClearWinsOverQueuedWritesAndQuitFlushes(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "clipboard.json")
|
||||
state := Snapshot{Version: 1, Entries: []string{"first"}}
|
||||
store := New_persistence(path, false)
|
||||
store := NewPersistence(path, false)
|
||||
store.Enable(state, 200)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for {
|
||||
@@ -111,12 +111,12 @@ func TestPersistenceClearWinsOverQueuedWritesAndQuitFlushes(t *testing.T) {
|
||||
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("old write resurrected cleared history", err)
|
||||
}
|
||||
store = New_persistence(path, false)
|
||||
store = NewPersistence(path, false)
|
||||
store.Enable(state, 200)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := load_history(path)
|
||||
got, err := loadHistory(path)
|
||||
if err != nil || !reflect.DeepEqual(got, state) {
|
||||
t.Fatal("quit did not flush newest state", got, err)
|
||||
}
|
||||
@@ -129,7 +129,7 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) {
|
||||
}
|
||||
path := filepath.Join(root, "history.json")
|
||||
for _, data := range [][]byte{
|
||||
[]byte("not JSON"), []byte{0xff},
|
||||
[]byte("not JSON"), {0xff},
|
||||
[]byte(`{"version":2,"entries":[],"selected":0}`),
|
||||
[]byte(`{"version":1,"entries":["word"],"selected":2}`),
|
||||
[]byte(`{"version":1,"entries":[],"selected":-1}`),
|
||||
@@ -137,18 +137,18 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) {
|
||||
if err := os.WriteFile(path, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := load_history(path); err == nil {
|
||||
if _, err := loadHistory(path); err == nil {
|
||||
t.Fatal("invalid snapshot accepted")
|
||||
}
|
||||
}
|
||||
state := Snapshot{Version: 1, Entries: []string{"word"}}
|
||||
if err := save_history(path, state); err != nil {
|
||||
if err := saveHistory(path, state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(path, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := load_history(path); err == nil {
|
||||
if _, err := loadHistory(path); err == nil {
|
||||
t.Fatal("public file accepted")
|
||||
}
|
||||
os.Chmod(path, 0600)
|
||||
@@ -158,14 +158,14 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) {
|
||||
}
|
||||
file.Truncate(maxHistoryBytes + 1)
|
||||
file.Close()
|
||||
if _, err := load_history(path); err == nil {
|
||||
if _, err := loadHistory(path); err == nil {
|
||||
t.Fatal("oversized file accepted")
|
||||
}
|
||||
if err := save_history(path, state); err != nil {
|
||||
if err := saveHistory(path, state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := os.ReadFile(path)
|
||||
if err := save_history(path, Snapshot{Version: 1, Entries: []string{strings.Repeat("x", MaxBytes+1)}}); err == nil {
|
||||
if err := saveHistory(path, Snapshot{Version: 1, Entries: []string{strings.Repeat("x", MaxBytes+1)}}); err == nil {
|
||||
t.Fatal("oversized entry saved")
|
||||
}
|
||||
after, _ := os.ReadFile(path)
|
||||
@@ -176,22 +176,22 @@ func TestPersistenceRejectsCorruptUnsafeAndUnboundedFiles(t *testing.T) {
|
||||
if err := os.Symlink(path, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := load_history(link); err == nil {
|
||||
if _, err := loadHistory(link); err == nil {
|
||||
t.Fatal("symlink read")
|
||||
}
|
||||
if err := save_history(link, state); err == nil {
|
||||
if err := saveHistory(link, state); err == nil {
|
||||
t.Fatal("symlink replaced")
|
||||
}
|
||||
fifo := filepath.Join(root, "fifo")
|
||||
if err := syscall.Mkfifo(fifo, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := load_history(fifo); err == nil {
|
||||
if _, err := loadHistory(fifo); err == nil {
|
||||
t.Fatal("FIFO accepted")
|
||||
}
|
||||
public := filepath.Join(root, "public")
|
||||
os.Mkdir(public, 0755)
|
||||
if err := save_history(filepath.Join(public, "history.json"), state); err == nil {
|
||||
if err := saveHistory(filepath.Join(public, "history.json"), state); err == nil {
|
||||
t.Fatal("public directory accepted")
|
||||
}
|
||||
var decoded Snapshot
|
||||
@@ -213,7 +213,7 @@ func TestClearRemovesTemporaryHistoryLeftByInterruptedWrite(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
store := New_persistence(path, false)
|
||||
store := NewPersistence(path, false)
|
||||
store.Clear()
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -228,15 +228,15 @@ func TestClearRemovesTemporaryHistoryLeftByInterruptedWrite(t *testing.T) {
|
||||
|
||||
func TestPersistenceRetriesAfterHistoryLockTimeout(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
lock, err := acquire_history(path, true)
|
||||
lock, err := acquireHistory(path, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lock.Close()
|
||||
if err := save_history(path, Snapshot{Version: 1, Entries: []string{"shared"}}); err != nil {
|
||||
if err := saveHistory(path, Snapshot{Version: 1, Entries: []string{"shared"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := New_persistence(path, true)
|
||||
store := NewPersistence(path, true)
|
||||
defer store.Close()
|
||||
if !errors.Is(store.LoadErr, syscall.EWOULDBLOCK) {
|
||||
t.Fatalf("expected startup lock contention, got %v", store.LoadErr)
|
||||
@@ -268,10 +268,10 @@ func TestPersistenceRetriesAfterHistoryLockTimeout(t *testing.T) {
|
||||
func TestEnableMergePreservesSavedSelection(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
state := Snapshot{Version: 1, Entries: []string{"newer", "selected"}, Selected: 1}
|
||||
if err := save_history(path, state); err != nil {
|
||||
if err := saveHistory(path, state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
update, err := apply_history(path, historyJob{action: "enable", state: Snapshot{Version: 1, Entries: []string{"retained"}}, limit: 10})
|
||||
update, err := applyHistory(path, historyJob{action: "enable", state: Snapshot{Version: 1, Entries: []string{"retained"}}, limit: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -48,14 +48,14 @@ type Persistence struct {
|
||||
lastErr error
|
||||
}
|
||||
|
||||
func New_persistence(path string, load bool) *Persistence {
|
||||
func NewPersistence(path string, load bool) *Persistence {
|
||||
p := &Persistence{Initial: Snapshot{Version: 1}, InitialEnabled: load, wake: make(chan struct{}, 1), errors: make(chan error, 1), updates: make(chan HistoryUpdate, 1), done: make(chan struct{})}
|
||||
if load {
|
||||
file, err := acquire_history(path, false)
|
||||
file, err := acquireHistory(path, false)
|
||||
if err == nil {
|
||||
p.InitialEnabled, err = persistence_enabled(file)
|
||||
p.InitialEnabled, err = persistenceEnabled(file)
|
||||
if err == nil && p.InitialEnabled {
|
||||
p.Initial, err = load_history(path)
|
||||
p.Initial, err = loadHistory(path)
|
||||
}
|
||||
if file != nil {
|
||||
file.Close()
|
||||
@@ -121,7 +121,7 @@ func (p *Persistence) report(err error) {
|
||||
p.lastErr = err
|
||||
if err != nil {
|
||||
select {
|
||||
case <-p.errors:
|
||||
case _ = <-p.errors: // Keep only the newest error.
|
||||
default:
|
||||
}
|
||||
p.errors <- err
|
||||
@@ -146,7 +146,7 @@ func (p *Persistence) run(path string, watching bool) {
|
||||
p.jobs = nil
|
||||
p.mutex.Unlock()
|
||||
for _, job := range jobs {
|
||||
update, err := apply_history(path, job)
|
||||
update, err := applyHistory(path, job)
|
||||
acknowledged = job.sequence
|
||||
p.report(err)
|
||||
if job.action == "enable" {
|
||||
@@ -167,16 +167,16 @@ func (p *Persistence) run(path string, watching bool) {
|
||||
if !watching {
|
||||
continue
|
||||
}
|
||||
nextSignature := history_signature(path)
|
||||
nextSignature := historySignature(path)
|
||||
if nextSignature == signature && !retryLock {
|
||||
continue
|
||||
}
|
||||
file, err := acquire_history(path, false)
|
||||
file, err := acquireHistory(path, false)
|
||||
update := HistoryUpdate{State: Snapshot{Version: 1}, Sequence: acknowledged}
|
||||
if err == nil {
|
||||
update.Enabled, err = persistence_enabled(file)
|
||||
update.Enabled, err = persistenceEnabled(file)
|
||||
if err == nil && update.Enabled {
|
||||
update.State, err = load_history(path)
|
||||
update.State, err = loadHistory(path)
|
||||
}
|
||||
if file != nil {
|
||||
file.Close()
|
||||
@@ -210,7 +210,7 @@ func (p *Persistence) publish(update HistoryUpdate) {
|
||||
p.updates <- update
|
||||
}
|
||||
|
||||
func history_signature(path string) string {
|
||||
func historySignature(path string) string {
|
||||
result := ""
|
||||
for _, name := range []string{path, path + ".lock"} {
|
||||
info, err := os.Lstat(name)
|
||||
@@ -226,7 +226,7 @@ func history_signature(path string) string {
|
||||
|
||||
// The empty original lock file means enabled. One metadata byte coordinates
|
||||
// disabling without retaining clipboard text or resurrecting a deleted file.
|
||||
func persistence_enabled(file *os.File) (bool, error) {
|
||||
func persistenceEnabled(file *os.File) (bool, error) {
|
||||
if file == nil {
|
||||
return true, nil
|
||||
}
|
||||
@@ -244,7 +244,7 @@ func persistence_enabled(file *os.File) (bool, error) {
|
||||
return value[0] == '1', nil
|
||||
}
|
||||
|
||||
func set_persistence_enabled(file *os.File, enabled bool) error {
|
||||
func setPersistenceEnabled(file *os.File, enabled bool) error {
|
||||
value := []byte("0")
|
||||
if enabled {
|
||||
value[0] = '1'
|
||||
@@ -253,36 +253,36 @@ func set_persistence_enabled(file *os.File, enabled bool) error {
|
||||
return errors.Join(err, file.Sync())
|
||||
}
|
||||
|
||||
func apply_history(path string, job historyJob) (HistoryUpdate, error) {
|
||||
func applyHistory(path string, job historyJob) (HistoryUpdate, error) {
|
||||
result := HistoryUpdate{State: Snapshot{Version: 1}}
|
||||
create := job.action == "enable" || job.action == "add" || job.action == "disable"
|
||||
file, err := acquire_history(path, create)
|
||||
file, err := acquireHistory(path, create)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if file != nil {
|
||||
defer file.Close()
|
||||
}
|
||||
result.Enabled, err = persistence_enabled(file)
|
||||
result.Enabled, err = persistenceEnabled(file)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
switch job.action {
|
||||
case "clear", "disable":
|
||||
if job.action == "disable" {
|
||||
if err := set_persistence_enabled(file, false); err != nil {
|
||||
if err := setPersistenceEnabled(file, false); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Enabled = false
|
||||
}
|
||||
return result, remove_history(path)
|
||||
return result, removeHistory(path)
|
||||
case "enable":
|
||||
if err := validate_snapshot(job.state); err != nil {
|
||||
if err := validateSnapshot(job.state); err != nil {
|
||||
return result, err
|
||||
}
|
||||
// Enabling deliberately saves retained memory, but preserves newer shared
|
||||
// entries when another reader already has an active saved history.
|
||||
state, err := load_history(path)
|
||||
state, err := loadHistory(path)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
@@ -304,16 +304,16 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
result.State = trim_history(state, job.limit)
|
||||
result.State = trimHistory(state, job.limit)
|
||||
if len(result.State.Entries) > 0 {
|
||||
err = save_history(path, result.State)
|
||||
err = saveHistory(path, result.State)
|
||||
} else {
|
||||
err = remove_history(path)
|
||||
err = removeHistory(path)
|
||||
}
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := set_persistence_enabled(file, true); err != nil {
|
||||
if err := setPersistenceEnabled(file, true); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Enabled = true
|
||||
@@ -322,13 +322,13 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) {
|
||||
if !result.Enabled {
|
||||
return result, nil
|
||||
}
|
||||
result.State, err = load_history(path)
|
||||
result.State, err = loadHistory(path)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
switch job.action {
|
||||
case "add":
|
||||
if err := Validate_text(job.text); err != nil {
|
||||
if err := ValidateText(job.text); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if job.imported && len(result.State.Entries) > 0 && result.State.Entries[0] == job.text {
|
||||
@@ -336,11 +336,11 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) {
|
||||
}
|
||||
result.State.Entries = append([]string{job.text}, result.State.Entries...)
|
||||
result.State.Selected = 0
|
||||
result.State = trim_history(result.State, job.limit)
|
||||
result.State = trimHistory(result.State, job.limit)
|
||||
case "select":
|
||||
// Navigation cannot recreate entries removed by another reader.
|
||||
if job.state.Selected < len(job.state.Entries) && job.state.Selected >= 0 {
|
||||
history := New_history(10000)
|
||||
history := NewHistory(10000)
|
||||
if err := history.Restore(job.state); err != nil {
|
||||
return result, err
|
||||
}
|
||||
@@ -350,15 +350,15 @@ func apply_history(path string, job historyJob) (HistoryUpdate, error) {
|
||||
result.State.Selected = history.Snapshot().Selected
|
||||
}
|
||||
case "resize":
|
||||
result.State = trim_history(result.State, job.limit)
|
||||
result.State = trimHistory(result.State, job.limit)
|
||||
}
|
||||
if len(result.State.Entries) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
return result, save_history(path, result.State)
|
||||
return result, saveHistory(path, result.State)
|
||||
}
|
||||
|
||||
func trim_history(state Snapshot, limit int) Snapshot {
|
||||
func trimHistory(state Snapshot, limit int) Snapshot {
|
||||
state.Entries = state.Entries[:min(len(state.Entries), max(1, limit))]
|
||||
state.Selected = min(state.Selected, max(0, len(state.Entries)-1))
|
||||
return state
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestSharedClipboardProcess(t *testing.T) {
|
||||
if path == "" {
|
||||
return
|
||||
}
|
||||
store := New_persistence(path, true)
|
||||
store := NewPersistence(path, true)
|
||||
current := sharedReply{State: store.Initial, Enabled: store.InitialEnabled}
|
||||
if store.LoadErr != nil {
|
||||
current.Error = store.LoadErr.Error()
|
||||
@@ -114,7 +114,7 @@ type sharedProcess struct {
|
||||
decoder *json.Decoder
|
||||
}
|
||||
|
||||
func start_shared_process(t *testing.T, path string) *sharedProcess {
|
||||
func startSharedProcess(t *testing.T, path string) *sharedProcess {
|
||||
t.Helper()
|
||||
command := exec.Command(os.Args[0], "-test.run=^TestSharedClipboardProcess$")
|
||||
command.Env = append(os.Environ(), "FENRIR_CLIPBOARD_PROCESS_PATH="+path)
|
||||
@@ -196,7 +196,7 @@ func (p *sharedProcess) await(t *testing.T, entries []string, enabled bool) shar
|
||||
|
||||
func TestPersistentClipboardSharesAcrossProcessesAndClearCannotResurrect(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
first, second := start_shared_process(t, path), start_shared_process(t, path)
|
||||
first, second := startSharedProcess(t, path), startSharedProcess(t, path)
|
||||
first.action(t, sharedCommand{Action: "add", Text: "first"})
|
||||
second.await(t, []string{"first"}, true)
|
||||
second.action(t, sharedCommand{Action: "add", Text: "second"})
|
||||
@@ -224,7 +224,7 @@ func TestPersistentClipboardSharesAcrossProcessesAndClearCannotResurrect(t *test
|
||||
first.await(t, []string{"retained"}, true)
|
||||
first.action(t, sharedCommand{Action: "quit"})
|
||||
second.action(t, sharedCommand{Action: "add", Text: "survivor"})
|
||||
third := start_shared_process(t, path)
|
||||
third := startSharedProcess(t, path)
|
||||
third.await(t, []string{"survivor", "retained"}, true)
|
||||
if err := second.command.Process.Kill(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -235,7 +235,7 @@ func TestPersistentClipboardSharesAcrossProcessesAndClearCannotResurrect(t *test
|
||||
|
||||
func TestPersistentClipboardConcurrentProcessCopiesKeepBothUpdates(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
first, second := start_shared_process(t, path), start_shared_process(t, path)
|
||||
first, second := startSharedProcess(t, path), startSharedProcess(t, path)
|
||||
var group sync.WaitGroup
|
||||
for _, process := range []*sharedProcess{first, second} {
|
||||
group.Add(1)
|
||||
@@ -247,7 +247,7 @@ func TestPersistentClipboardConcurrentProcessCopiesKeepBothUpdates(t *testing.T)
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
state, err := load_history(path)
|
||||
state, err := loadHistory(path)
|
||||
if err != nil || len(state.Entries) != 8 {
|
||||
t.Fatal("lost concurrent copies", state, err)
|
||||
}
|
||||
@@ -263,7 +263,7 @@ func TestPersistentClipboardConcurrentProcessCopiesKeepBothUpdates(t *testing.T)
|
||||
}
|
||||
|
||||
func TestPersistentClipboardRefreshRetainsLocalSelectionAndDuplicateIdentity(t *testing.T) {
|
||||
history := New_history(5)
|
||||
history := NewHistory(5)
|
||||
history.Add("same")
|
||||
history.Add("middle")
|
||||
history.Add("same")
|
||||
@@ -284,7 +284,7 @@ func TestPersistentClipboardRefreshRetainsLocalSelectionAndDuplicateIdentity(t *
|
||||
|
||||
func TestPersistenceQueuedEnableThenClearStillParticipates(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
store := New_persistence(path, false)
|
||||
store := NewPersistence(path, false)
|
||||
store.Enable(Snapshot{Version: 1, Entries: []string{"old"}}, 200)
|
||||
store.Clear()
|
||||
store.Add("fresh", 200)
|
||||
@@ -313,7 +313,7 @@ func TestPersistenceQueuedEnableThenClearStillParticipates(t *testing.T) {
|
||||
|
||||
func TestPersistenceDuplicateXImportsAreOneEntryButCopiesRemainDistinct(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "private", "terminal.json")
|
||||
first, second := New_persistence(path, true), New_persistence(path, true)
|
||||
first, second := NewPersistence(path, true), NewPersistence(path, true)
|
||||
first.Import("shared X text", 200)
|
||||
if err := first.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -323,7 +323,7 @@ func TestPersistenceDuplicateXImportsAreOneEntryButCopiesRemainDistinct(t *testi
|
||||
if err := second.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := load_history(path)
|
||||
state, err := loadHistory(path)
|
||||
if err != nil || !reflect.DeepEqual(state.Entries, []string{"shared X text", "shared X text"}) {
|
||||
t.Fatal(state, err)
|
||||
}
|
||||
|
||||
@@ -64,9 +64,9 @@ type Worker struct {
|
||||
epoch uint64
|
||||
}
|
||||
|
||||
func New_worker(ctx context.Context, paste func(context.Context, string, int) error) *Worker {
|
||||
func NewWorker(ctx context.Context, paste func(context.Context, string, int) error) *Worker {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
w := &Worker{jobs: make(chan queuedRequest, 1), results: make(chan Result, 8), ctx: ctx, cancel: cancel, done: make(chan struct{}), targets: system_targets, paste: paste}
|
||||
w := &Worker{jobs: make(chan queuedRequest, 1), results: make(chan Result, 8), ctx: ctx, cancel: cancel, done: make(chan struct{}), targets: systemTargets, paste: paste}
|
||||
go w.run()
|
||||
return w
|
||||
}
|
||||
@@ -119,9 +119,9 @@ func (w *Worker) run() {
|
||||
result := Result{Request: request}
|
||||
switch request.Command {
|
||||
case command.ImportClipboard:
|
||||
result.Text, result.Err = read_file(request.Path)
|
||||
result.Text, result.Err = readFile(request.Path)
|
||||
case command.ExportClipboard:
|
||||
result.Err = write_file(request.Path, request.Text)
|
||||
result.Err = writeFile(request.Path, request.Text)
|
||||
case command.PasteClipboard:
|
||||
if ctx.Err() != nil {
|
||||
result.Err = ctx.Err()
|
||||
@@ -167,7 +167,7 @@ func (w *Worker) run() {
|
||||
}
|
||||
}
|
||||
|
||||
func read_file(path string) (string, error) {
|
||||
func readFile(path string) (string, error) {
|
||||
file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -184,18 +184,19 @@ func read_file(path string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), Validate_text(string(data))
|
||||
return string(data), ValidateText(string(data))
|
||||
}
|
||||
|
||||
func write_file(path, text string) error {
|
||||
if err := Validate_text(text); err != nil {
|
||||
func writeFile(path, text string) error {
|
||||
if err := ValidateText(text); err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.CreateTemp(filepath.Dir(path), ".fenrir-clipboard-*")
|
||||
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()) }()
|
||||
_, writeErr := file.WriteString(text)
|
||||
err = errors.Join(writeErr, file.Sync(), file.Close())
|
||||
if err != nil {
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestQueuedPasteCannotStartAfterTargetRetirement(t *testing.T) {
|
||||
|
||||
func TestActivePasteCancellationDoesNotBlockShutdown(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
worker := New_worker(context.Background(), func(ctx context.Context, text string, terminal int) error {
|
||||
worker := NewWorker(context.Background(), func(ctx context.Context, text string, terminal int) error {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
|
||||
@@ -104,7 +104,7 @@ func (x *xClipboard) read(ctx context.Context) (string, error) {
|
||||
}
|
||||
text = string(runes)
|
||||
}
|
||||
return text, Validate_text(text)
|
||||
return text, ValidateText(text)
|
||||
}
|
||||
return "", nil // Images, files and unowned selections are ordinary no-data.
|
||||
}
|
||||
@@ -113,7 +113,7 @@ func (x *xClipboard) write(ctx context.Context, text string) error {
|
||||
if text == "" {
|
||||
return fmt.Errorf("clipboard text is empty")
|
||||
}
|
||||
if err := Validate_text(text); err != nil {
|
||||
if err := ValidateText(text); err != nil {
|
||||
return err
|
||||
}
|
||||
// The owner outlives this request. Its parent-death signal and Close own
|
||||
@@ -129,14 +129,14 @@ func (x *xClipboard) write(ctx context.Context, text string) error {
|
||||
defer func() {
|
||||
if !accepted {
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
_ = <-done // Exit status of a killed writer is expected.
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-done:
|
||||
case _ = <-done:
|
||||
return fmt.Errorf("X clipboard writer exited before acknowledgement")
|
||||
default:
|
||||
}
|
||||
@@ -160,7 +160,7 @@ func (x *xClipboard) write(ctx context.Context, text string) error {
|
||||
func (x *xClipboard) close() {
|
||||
if x.owner != nil {
|
||||
_ = x.owner.Process.Kill()
|
||||
<-x.ownerDone
|
||||
_ = <-x.ownerDone // Exit status of a killed owner is expected.
|
||||
x.owner = nil
|
||||
x.ownerDone = nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user