diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4eeef40..8acb6bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,9 @@ on: push: branches: - main + - "rework/**" pull_request: + workflow_call: jobs: test: @@ -19,14 +21,17 @@ jobs: go-version-file: go.mod cache: true - - name: Vendor Go modules - run: go mod vendor + - name: gofmt + run: make fmt-check + + - name: go vet + run: make vet + + - name: vendor is up to date + run: make vendor-check - name: Build - run: GOFLAGS=-mod=vendor go build ./... + run: make build - - name: Vet - run: GOFLAGS=-mod=vendor go vet ./... - - - name: Test - run: GOFLAGS=-mod=vendor go test ./... + - name: Test (race) + run: make race diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c4bd8af..1446d60 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,19 +13,7 @@ env: jobs: test: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Go - uses: actions/setup-go@v5 - with: - go-version-file: go.mod - cache: true - - - name: Run tests - run: GOFLAGS=-mod=vendor go test ./... + uses: ./.github/workflows/ci.yml release: needs: test diff --git a/.gitignore b/.gitignore index 7ce7c11..032517b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,11 @@ target/ -vcom +/vcom + +# release artifacts +*.tar.gz +*.pkg.tar.zst +*.deb +*.rpm + +# local agent worktrees +.claude/worktrees/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..828429c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,80 @@ +# Changelog + +## v0.2.8 — stability hotfixes + +Data-loss and crash fixes for v0.2.7 while the larger rework is in progress. + +### Data loss +- **Archiving no longer destroys the source.** Archiving `data.tar` as tar (or `report.zip` as zip) into the same + directory used to truncate the source; archiving a directory into a pane inside it made the archive include + itself. Both are now refused. Archives are written to a temporary file and renamed into place only on success, + so a failed or cancelled run leaves no partial file and keeps an existing archive intact; replacing an existing + archive asks first. A replaced archive keeps its permissions (a private `0600` archive no longer becomes + world-readable), and archive names close to the file-name length limit work again. +- **Deleting a remote symlink to a directory no longer wipes the target directory.** The link itself is removed. +- **SSH panes no longer act on local files.** Rename, Enter (edit / run / open / enter archive), archive and unpack + in an SSH pane used to operate on the *local* file with the same path (e.g. running a local + `/usr/local/bin/deploy.sh`). They are now refused with a message until remote support lands. +- **No more writes into an archive pane or the SSH host list.** Copy/move/unpack/archive into a pane showing an + archive used to put files into a temporary directory that is deleted when the archive is closed; with the + `ssh://` host list as target, files went to `./ssh:/…` in the process directory. Both are now refused. +- **Delete moves to the trash by default.** Permanent deletion is chosen explicitly with `D`/`d` in the dialog. + `behavior.confirm_delete = false` now works and skips the question only for the trash. If an item cannot be moved + to the trash (e.g. it is on another filesystem than the home trash, or the trash is broken), the other items are + still trashed and vcom asks whether to delete only the refused ones permanently; nothing is deleted without that + confirmation. +- **Mirror (`p`) is refused inside an archive.** It used to give the other pane the archive's temporary directory as + a normal writable directory; changes there were lost when the archive was closed. Mirroring *into* a pane that is + inside an archive now leaves the archive properly (it used to keep treating the real directory as a read-only + archive). + +### SSH +- **One unsupported line in `~/.ssh/known_hosts` no longer breaks every connection.** Lines with key types vcom + cannot parse (e.g. OpenSSH 10 `ssh-mldsa44-ed25519`) are skipped with a warning in the log. A host recorded only + with such a key is refused rather than silently trusted with a different key. +- Host key types already recorded for a host are preferred in the handshake (like OpenSSH), so a server known only + by its ed25519 key is no longer reported as "REMOTE HOST IDENTIFICATION HAS CHANGED". + +### Crashes and races +- Caret mode (`i` in the info pane) no longer panics without colors (`NO_COLOR`, dumb terminals). +- Closing an SSH connection while it is in use (background transfer, mirrored pane, preview) no longer races or + panics. Mirrored panes and background jobs share a reference-counted connection: leaving a host in one pane no + longer disconnects the other pane or a running transfer. + +### Usability +- Status and error messages are shown in a line above the footer (they were never displayed before). +- Cyrillic (and other non-Latin) text can be typed in mkdir, rename, the filter and the SSH form; Russian-layout + keys still work as commands in the browser. +- `PgDn` works. +- `q` closes the info pane, the filter or the selection first, and quits only from the plain browser; `q` no longer + closes the SSH add-host form while typing. +- `n` cancels yes/no dialogs, as their hints say. +- Creating a directory that already exists reports an error instead of silent success, in local and SSH panes. +- `j`, `k` and other letters can be typed in the filter (they used to move the cursor); arrows still navigate. +- `?` can be typed in the SSH add-host form (e.g. in passwords); `F1` opens the form's help. + +### Trash +- Follows the freedesktop trash spec: items on another filesystem go to that filesystem's `$topdir/.Trash-$uid` + instead of failing; `.trashinfo` `Path=` is percent-encoded (names with spaces/Cyrillic restore correctly in other + tools); `XDG_DATA_HOME` is honoured; name collisions (including broken symlinks already in the trash) never + overwrite an existing trashed item. + +### Config, session and logs +- Choosing a theme changes only the `theme = ...` line; comments and other keys in `vcom.toml` are preserved. This + also works when the section is written as `ui.theme = ...` or `ui = { theme = ... }`. A read-only (`chmod a-w`) + config is not changed (as in v0.2.7). With `-config` / `$VCOM_CONFIG` naming a file that does not exist yet, the + theme is saved to that file. If saving the theme fails, the error stays visible in the status line. +- A broken config no longer prevents startup: vcom starts with defaults and shows the error (in red) in the status + line. +- `./vcom.toml` in the current directory is no longer picked up implicitly. +- Config and session are written atomically. The session moved to `$XDG_STATE_HOME/vcom/session.toml` (migrated + once from the old location; if the state directory is not writable, the old session is still restored and the + error is shown) and is also saved on SIGTERM/SIGHUP. +- A single rotating log at `$XDG_STATE_HOME/vcom/vcom.log` replaces a new file in `/tmp/vcom-logs` per run; + secrets are never logged. + +### Development +- In-process SSH/SFTP test server with a fault-injecting proxy (`internal/testutil/sshtest`), tree helpers + (`fstree`), a Bubble Tea test driver (`teadriver`) and behavioural smoke tests for the UI. +- CI: `make ci` runs gofmt, vet, a vendor consistency check, build and race-enabled tests; releases run the same + workflow. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f7039db --- /dev/null +++ b/Makefile @@ -0,0 +1,47 @@ +# Developer and CI entry points. CI (.github/workflows/*.yml) calls these +# targets so local runs and CI stay identical. + +GO ?= go +GOFLAGS ?= -mod=vendor +export GOFLAGS + +# Go sources we own (vendor/ is third-party and not reformatted). +GOFILES = $(shell git ls-files '*.go' | grep -v '^vendor/') + +# Targets mutate vendor/ (vendor-check) and then build from it: never run them +# concurrently, even under `make -j`. +.NOTPARALLEL: + +.PHONY: all build test race lint fmt-check vet vendor-check ci fmt + +all: build + +build: + $(GO) build ./... + +test: + $(GO) test -count=1 ./... + +race: + $(GO) test -race -count=1 ./... + +fmt: + gofmt -w $(GOFILES) + +fmt-check: + @out="$$(gofmt -l $(GOFILES) $$(git ls-files --others --exclude-standard '*.go' | grep -v '^vendor/'))"; \ + if [ -n "$$out" ]; then echo "gofmt needed for:"; echo "$$out"; exit 1; fi + +vet: + $(GO) vet ./... + +# go mod vendor must be a no-op: go.mod, go.sum and vendor/ are committed. +vendor-check: + GOFLAGS= $(GO) mod vendor + git diff --exit-code -- vendor go.mod go.sum + @untracked="$$(git ls-files --others --exclude-standard vendor)"; \ + if [ -n "$$untracked" ]; then echo "untracked files in vendor/:"; echo "$$untracked"; exit 1; fi + +lint: fmt-check vet vendor-check + +ci: lint build race diff --git a/PKGBUILD b/PKGBUILD index 03c429e..b0113b2 100644 --- a/PKGBUILD +++ b/PKGBUILD @@ -1,5 +1,5 @@ pkgname=vcom -pkgver=0.2.7 +pkgver=0.2.8 pkgrel=1 pkgdesc="Terminal file manager inspired by Midnight Commander" arch=("x86_64" "aarch64") diff --git a/README.md b/README.md index 859e961..668ba28 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,13 @@ go build -o vcom ./cmd/vcom Run directly from the flake: ```bash -nix run github:vrubelroman/vcom?ref=v0.2.7 +nix run github:vrubelroman/vcom?ref=v0.2.8 ``` Install into user profile: ```bash -nix profile add github:vrubelroman/vcom?ref=v0.2.7 +nix profile add github:vrubelroman/vcom?ref=v0.2.8 ``` The Nix package wraps `vcom` with `ueberzugpp` in `PATH`, so image preview works in non-`kitty` terminals out of the box. @@ -60,8 +60,8 @@ The Nix package wraps `vcom` with `ueberzugpp` in `PATH`, so image preview works Download and install the latest release: ```bash -curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.7/vcom_0.2.7_amd64.deb -o /tmp/vcom_0.2.7_amd64.deb -sudo apt install /tmp/vcom_0.2.7_amd64.deb +curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.8/vcom_0.2.8_amd64.deb -o /tmp/vcom_0.2.8_amd64.deb +sudo apt install /tmp/vcom_0.2.8_amd64.deb ``` The Debian package recommends `ueberzugpp` for image preview outside `kitty` (optional). To install it: @@ -85,7 +85,7 @@ The Arch package depends on `ueberzugpp`, so non-`kitty` image preview is instal Download and install the latest RPM: ```bash -curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.7/vcom-0.2.7-1.x86_64.rpm -o /tmp/vcom.rpm +curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.8/vcom-0.2.8-1.x86_64.rpm -o /tmp/vcom.rpm sudo dnf install /tmp/vcom.rpm ``` @@ -176,12 +176,18 @@ Preview mode (`F9` / `i`) temporarily replaces the inactive pane and shows: Optional config lookup order: 1. `-config /path/to/vcom.toml` -2. `./vcom.toml` -3. `./config/vcom.toml` -4. `$XDG_CONFIG_HOME/vcom/vcom.toml` -5. `~/.config/vcom/vcom.toml` +2. `$VCOM_CONFIG` +3. `$XDG_CONFIG_HOME/vcom/vcom.toml` +4. `~/.config/vcom/vcom.toml` -Reference config: [vcom.toml](/home/vrubel/projects/vcom/vcom.toml) +A `vcom.toml` in the current directory is no longer loaded. A broken config does not stop vcom: it starts with +defaults and shows the error. Unknown keys are reported as warnings. Choosing a theme edits only the `theme = ...` +line of the config; comments and other keys are kept. + +Reference config: [vcom.toml](vcom.toml) + +The session is kept in `$XDG_STATE_HOME/vcom/session.toml` (default `~/.local/state/vcom/`), next to the log +`vcom.log`. The log level is `warn` by default; use `--log-level=debug|info|warn|error`, `--debug` or `VCOM_LOG`. Icon mode example: @@ -216,7 +222,7 @@ Built-in themes (press `t` to open theme selector or set `ui.theme` in config): ## Releases -Pushing a tag like `v0.2.7` triggers GitHub Actions release workflow (`.github/workflows/release.yml`) which: +Pushing a tag like `v0.2.8` triggers GitHub Actions release workflow (`.github/workflows/release.yml`) which: - runs tests - vendors Go modules @@ -227,10 +233,10 @@ Pushing a tag like `v0.2.7` triggers GitHub Actions release workflow (`.github/w Release artifacts: -- `vcom-v0.2.7-x86_64-unknown-linux-gnu.tar.gz` -- `vcom_0.2.7_amd64.deb` -- `vcom-0.2.7-1.x86_64.rpm` -- `vcom-v0.2.7-checksums.txt` +- `vcom-v0.2.8-x86_64-unknown-linux-gnu.tar.gz` +- `vcom_0.2.8_amd64.deb` +- `vcom-0.2.8-1.x86_64.rpm` +- `vcom-v0.2.8-checksums.txt` ## Notes diff --git a/cmd/vcom/main.go b/cmd/vcom/main.go index 5927d03..51609f8 100644 --- a/cmd/vcom/main.go +++ b/cmd/vcom/main.go @@ -1,57 +1,249 @@ package main import ( + "context" + "errors" "flag" "fmt" - "log" + "log/slog" "os" + "os/signal" "path/filepath" + "sync" + "sync/atomic" + "syscall" "time" tea "github.com/charmbracelet/bubbletea" "vcom/internal/config" + "vcom/internal/imgview" + "vcom/internal/jobs" + "vcom/internal/logx" + "vcom/internal/paths" + "vcom/internal/ssh/conn" + "vcom/internal/ssh/sshconfig" + "vcom/internal/tui" "vcom/internal/ui" ) -func main() { +func main() { os.Exit(run()) } + +// run follows design §9.4: flags → log → config (not fatal) → run dir → UI; +// teardown (session, jobs, connections, temp files, run dir, log) happens +// after Program.Run in every case: normal quit, signal, or a panic Bubble +// Tea recovered from. +func run() int { configPath := flag.String("config", "", "path to vcom TOML config") + logLevel := flag.String("log-level", "", "log level: debug, info, warn, error (default warn, or $VCOM_LOG)") + debug := flag.Bool("debug", false, "shorthand for --log-level=debug") + uiFlag := flag.String("ui", "old", "user interface: old (default) or next (the new UI, work in progress)") flag.Parse() - cfg, resolvedPath, err := config.Load(*configPath) - if err != nil { - fmt.Fprintf(os.Stderr, "config error: %v\n", err) - os.Exit(1) + logger, logErr := openLog(*debug, *logLevel) + defer logger.Close() + slog.SetDefault(logger.Logger) + logx.RedirectStdLog(logger.Logger) + if logErr != nil { + fmt.Fprintf(os.Stderr, "vcom: log disabled: %v\n", logErr) } - // Set up debug logging to a file in /tmp - logDir := filepath.Join(os.TempDir(), "vcom-logs") - if err := os.MkdirAll(logDir, 0755); err != nil { - fmt.Fprintf(os.Stderr, "warning: cannot create log dir %s: %v\n", logDir, err) + // A broken config is not fatal: defaults + a message in the status line. + cfg, info, cfgErr := config.Load(*configPath) + // The theme is saved to resolvedPath: the file that was read, or — for + // an explicit -config/$VCOM_CONFIG that does not exist yet — that path, + // so the next start finds it (QA-15). "" means the default XDG file. + resolvedPath := "" + explicit := *configPath != "" || os.Getenv("VCOM_CONFIG") != "" + if cfgErr == nil && (info.Found || explicit) { + resolvedPath = info.Path } - logPath := filepath.Join(logDir, fmt.Sprintf("vcom-%s.log", time.Now().Format("2006-01-02_15-04-05"))) - f, err := tea.LogToFile(logPath, "") + notice := "" + switch { + case cfgErr != nil: + notice = "Config error: " + cfgErr.Error() // "error" → shown in red (QA-19) + slog.Warn("config", "err", cfgErr) + case len(info.Warnings) == 1: + notice = "config: " + info.Warnings[0] + case len(info.Warnings) > 1: + notice = fmt.Sprintf("config: %s (+%d more warnings in the log)", info.Warnings[0], len(info.Warnings)-1) + } + for _, w := range info.Warnings { + slog.Warn("config", "warning", w) + } + slog.Info("starting", "config", resolvedPath, "log", logger.Path, "ui", *uiFlag) + + runDir, err := paths.CreateRunDir() if err != nil { - fmt.Fprintf(os.Stderr, "warning: cannot set up log file %s: %v\n", logPath, err) + slog.Warn("run dir", "err", err) } else { - defer f.Close() - log.Printf("[INIT] Logging to %s", logPath) - log.Printf("[INIT] vcom starting — config: %s, resolved: %s", *configPath, resolvedPath) + defer func() { + if err := paths.RemoveRunDir(runDir); err != nil { + slog.Warn("remove run dir", "err", err) + } + }() } - model, err := ui.NewModel(cfg, resolvedPath) - if err != nil { - log.Printf("[FATAL] startup error: %v", err) - fmt.Fprintf(os.Stderr, "startup error: %v\n", err) - os.Exit(1) + var ( + program *tea.Program + teardown func() + onSignal = tea.Quit // SIGHUP: the new UI saves its session first + ) + switch *uiFlag { + case "next": + program, teardown = startNext(cfg, resolvedPath, notice, runDir) + onSignal = func() tea.Msg { return tui.Signal() } + case "old", "": + model, err := ui.NewModel(cfg, resolvedPath) + if err != nil { + slog.Error("startup", "err", err) + fmt.Fprintf(os.Stderr, "startup error: %v\n", err) + return 1 + } + model = model.WithStatus(notice) + program = tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion()) + teardown = func() {} + default: + fmt.Fprintf(os.Stderr, "vcom: unknown --ui=%s (old or next)\n", *uiFlag) + return 2 } - program := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion()) - log.Printf("[INIT] Bubble Tea program started") - if _, err := program.Run(); err != nil { - log.Printf("[FATAL] runtime error: %v", err) - fmt.Fprintf(os.Stderr, "runtime error: %v\n", err) - os.Exit(1) + // SIGTERM/SIGINT are handled by Bubble Tea itself; SIGHUP (terminal + // closed) is not. Do NOT subscribe to SIGTERM here: when our tea.Quit + // wins the race, Bubble Tea's own signal goroutine blocks forever on an + // unbuffered send and Program.shutdown waits for it (QA-12). + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGHUP) + defer signal.Stop(sigs) + go func() { + for s := range sigs { + slog.Info("signal", "sig", s.String()) + program.Send(onSignal()) + } + }() + + final, runErr := program.Run() + shutdown(final) + teardown() + switch { + case runErr == nil: + slog.Info("exited cleanly") + return 0 + case errors.Is(runErr, tea.ErrInterrupted): + return 130 + default: + slog.Error("runtime", "err", runErr) + fmt.Fprintf(os.Stderr, "runtime error: %v\n", runErr) + return 1 + } +} + +func openLog(debug bool, flagLevel string) (*logx.Logger, error) { + level, lerr := logx.ResolveLevel(debug, flagLevel, os.Getenv("VCOM_LOG")) + dir, err := paths.StateDir() + if err != nil { + return logx.Discard(), err + } + l, err := logx.Open(logx.Options{Dir: dir, Level: level}) + if err != nil { + return logx.Discard(), err + } + if lerr != nil { + l.Warn("log level", "err", lerr) + } + return l, nil +} + +// shutdown saves the session of the final model (idempotent if the quit key +// already did it). The new UI saves its session in stage 6.6. +func shutdown(final tea.Model) { + switch m := final.(type) { + case ui.Model: + m.Shutdown() + case *tui.App: + if err := m.Shutdown(); err != nil { + slog.Warn("session", "err", err) + } + case *ui.Model: + m.Shutdown() + } +} + +// startNext wires the new UI (design §9.4): the jobs manager, the SSH +// connection pool and the host resolver go into tui.Deps. The returned +// teardown cancels jobs (giving them 3 s to remove temp files) and closes +// every connection; it runs after Program.Run returns. +func startNext(cfg config.Config, cfgPath, notice, runDir string) (*tea.Program, func()) { + var prog atomic.Pointer[tea.Program] + var pendingMu sync.Mutex + var pending []tea.Msg + send := func(m tea.Msg) { + if p := prog.Load(); p != nil { + p.Send(m) + return + } + pendingMu.Lock() + pending = append(pending, m) + pendingMu.Unlock() + } + readHome, _ := paths.ReadHome() + deps := tui.DefaultDeps(cfg, cfgPath) + deps.Notice = notice + if runDir != "" { + deps.RunDir = runDir + } + deps.Jobs = jobs.New(func(e jobs.Event) { send(tui.JobEvent(e)) }, cfg.Transfer.MaxParallelJobs) + pool := conn.NewPool(conn.PoolOptions{ + DialOptions: conn.DialOptions{ + HandshakeTimeout: cfg.SSH.ConnectTimeout.Duration, + Home: readHome, + Warn: func(m string) { slog.Warn("ssh", "msg", m) }, + }, + KeepaliveInterval: cfg.SSH.KeepaliveInterval.Duration, + }) + deps.Pool = pool + var store *sshconfig.Store + if f, err := paths.DefaultConfigFile(); err == nil { + if s, err := sshconfig.OpenStore(filepath.Dir(f)); err == nil { + store = s + } else { + slog.Warn("hosts store", "err", err) + } + } + res, err := sshconfig.NewResolver(sshconfig.Options{Home: readHome, Store: store}) + if err != nil { + slog.Warn("ssh config", "err", err) + } + deps.Resolver = res + + tty := imgview.NewSyncTTY(os.Stdout) + images := imgview.Start(imgview.Options{ + Backend: imgview.Detect(cfg.Preview.ImageBackend, os.Getenv), + TTY: tty, + TmpDir: runDir, + Tmux: os.Getenv("TMUX") != "", + OnEvent: func(e imgview.Event) { send(tui.ImageEvent(e)) }, + }) + deps.Image = images + p := tea.NewProgram(tui.New(deps), tea.WithAltScreen(), tea.WithMouseCellMotion(), tea.WithOutput(tty)) + prog.Store(p) + pendingMu.Lock() + queued := append([]tea.Msg(nil), pending...) + pending = nil + pendingMu.Unlock() + go func() { + for _, m := range queued { + p.Send(m) + } + }() + return p, func() { + prog.Store(nil) + images.Stop() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := deps.Jobs.Shutdown(ctx); err != nil { + slog.Warn("jobs shutdown", "err", err) + } + pool.Close() } - log.Printf("[INIT] vcom exited cleanly") } diff --git a/cmd/vcom/qa_signal_test.go b/cmd/vcom/qa_signal_test.go new file mode 100644 index 0000000..d65ca72 --- /dev/null +++ b/cmd/vcom/qa_signal_test.go @@ -0,0 +1,97 @@ +package main + +// QA (v0.2.8 RC2): SIGTERM must end vcom and save the session. main +// registers its own SIGTERM handler next to Bubble Tea's; when main's +// tea.Quit wins, Bubble Tea's handler blocks forever on an unbuffered send +// and Program.shutdown waits for it: the process hangs in the alt screen +// and the session is never saved. The test runs the real run() in a child +// process (this test binary) on a pty (util-linux `script`) and sends +// SIGTERM repeatedly. + +import ( + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func TestQASigtermHelperProcess(t *testing.T) { + if os.Getenv("VCOM_QA_CHILD") != "1" { + t.Skip("helper process") + } + home := os.Getenv("HOME") + _ = os.WriteFile(filepath.Join(home, "pid"), []byte(strconv.Itoa(os.Getpid())), 0o600) + os.Args = []string{"vcom"} + os.Exit(run()) +} + +func TestQASigtermExitsAndSavesSession(t *testing.T) { + script, err := exec.LookPath("script") + if err != nil { + t.Skip("util-linux script not available") + } + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + // The hang was intermittent (~1 in 3); 12 runs take ~80s, so CI does a + // quick 2-run smoke and VCOM_SLOW_TESTS=1 enables the full loop. + runs := 2 + if os.Getenv("VCOM_SLOW_TESTS") != "" { + runs = 12 + } + hung, saved := 0, 0 + for i := 0; i < runs; i++ { + home := t.TempDir() + child := exe + " -test.run=^TestQASigtermHelperProcess$" + cmd := exec.Command(script, "-qfec", "stty rows 40 cols 120; "+child, "/dev/null") + cmd.Env = append(os.Environ(), + "VCOM_QA_CHILD=1", "HOME="+home, "TERM=xterm-256color", + "XDG_CONFIG_HOME="+filepath.Join(home, ".config"), + "XDG_STATE_HOME="+filepath.Join(home, ".local", "state"), + "XDG_CACHE_HOME="+filepath.Join(home, ".cache"), + "XDG_DATA_HOME="+filepath.Join(home, ".local", "share"), + "VCOM_CONFIG=", "SSH_AUTH_SOCK=", + ) + cmd.Dir = home + var out strings.Builder + cmd.Stdout, cmd.Stderr = &out, &out + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + go func() { cmd.Wait(); close(done) }() + var pid int + for w := 0; w < 500 && pid == 0; w++ { + time.Sleep(20 * time.Millisecond) + if b, err := os.ReadFile(filepath.Join(home, "pid")); err == nil { + pid, _ = strconv.Atoi(strings.TrimSpace(string(b))) + } + } + if pid == 0 { + cmd.Process.Kill() + <-done + t.Fatalf("child did not start: %.400q", out.String()) + } + time.Sleep(1500 * time.Millisecond) // UI up and idle + _ = syscall.Kill(pid, syscall.SIGTERM) + select { + case <-done: + case <-time.After(4 * time.Second): + hung++ + _ = syscall.Kill(pid, syscall.SIGKILL) + <-done + } + if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); err == nil { + saved++ + } + } + t.Logf("runs=%d hung=%d saved=%d", runs, hung, saved) + if hung > 0 || saved != runs { + t.Fatalf("SIGTERM: vcom hung in %d of %d runs; session saved in %d", hung, runs, saved) + } +} diff --git a/flake.nix b/flake.nix index 669311e..ccecd09 100644 --- a/flake.nix +++ b/flake.nix @@ -13,7 +13,7 @@ lib = pkgs.lib; packageBase = pkgs.buildGoModule { pname = "vcom"; - version = "0.2.6"; + version = "0.2.8"; src = ./.; vendorHash = null; diff --git a/go.mod b/go.mod index f4ef489..5fd88e9 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/pelletier/go-toml/v2 v2.2.4 github.com/pkg/sftp v1.13.10 golang.org/x/crypto v0.50.0 + golang.org/x/image v0.39.0 golang.org/x/sys v0.43.0 ) @@ -22,6 +23,7 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/kevinburke/ssh_config v1.6.0 // indirect github.com/kr/fs v0.1.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect diff --git a/go.sum b/go.sum index 8e88b2c..1d6cc14 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY= +github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M= github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= @@ -63,6 +65,8 @@ golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww= +golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= diff --git a/internal/archive/create.go b/internal/archive/create.go new file mode 100644 index 0000000..999e9c9 --- /dev/null +++ b/internal/archive/create.go @@ -0,0 +1,386 @@ +package archive + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "io/fs" + "strings" + "time" + + "vcom/internal/transfer" + "vcom/internal/vfs" +) + +// Create errors. +var ( + ErrSameFile = errors.New("the archive would overwrite one of its sources") + ErrIntoSource = errors.New("the archive would be written inside a source directory") +) + +// Create writes the given sources (any FS) into archivePath on dst (any FS) +// in format f (design §5.1). The archive is written through +// transfer.WriteAtomic: a failed or cancelled run leaves neither a partial +// archive nor a damaged previous one, and a source is never truncated. +// Refused up front: an archivePath that is one of the sources or lies inside +// a source directory (also through symlinks; U-P0-1). An existing archive is +// a conflict for h.Resolve (Overwrite / KeepBoth = "name (1).zip" / Skip / +// Abort); without Resolve it is refused. Symlinks are stored as links. +// Errors of the zip/tar/gzip writers' Close fail the operation (N-P2-13). +func Create(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string, f Format, + h transfer.Hooks) transfer.Report { + var rep transfer.Report + fail := func(err error) transfer.Report { + rep.Err = err + rep.Cancelled = ctx.Err() != nil + return rep + } + if dst.Caps().ReadOnly { + return fail(fmt.Errorf("%w: %s", transfer.ErrReadOnly, dst.Label())) + } + archivePath = dst.Paths().Clean(archivePath) + if err := checkSources(ctx, src, paths, dst, archivePath); err != nil { + return fail(err) + } + + target, replace, skip, err := resolveTarget(ctx, dst, archivePath, h) + if err != nil { + return fail(err) + } + if skip { + rep.Skipped = 1 + return rep + } + + var items []transfer.Item + var total int64 + seen := map[string]bool{} + err = transfer.FSSource(src, paths, transfer.CopyLinks).Walk(ctx, func(it transfer.Item) error { + if !strings.Contains(it.Rel, "/") { + if seen[it.Rel] { + return fmt.Errorf("%w: %s", transfer.ErrDuplicateName, it.Rel) + } + seen[it.Rel] = true + } + items = append(items, it) + if it.Kind == transfer.File { + total += it.Size + } + return nil + }) + if err != nil { + return fail(err) + } + + w := &writer{ctx: ctx, src: src, f: f, h: h, rep: &rep, items: items, total: total} + err = transfer.WriteAtomic(ctx, dst, target, transfer.WriteOptions{Perm: 0o644, Replace: replace, Fsync: true}, w.fill) + if ctx.Err() != nil { + rep.Cancelled = true + } + if err != nil { + if !rep.Cancelled && rep.Err == nil { + rep.Err = err + } + rep.Done, rep.Bytes = 0, 0 + return rep + } + rep.Affected = []vfs.Location{{FS: dst, Path: dst.Paths().Dir(target)}} + w.progress(true) + return rep +} + +func checkSources(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string) error { + for _, p := range paths { + same, err := vfs.SameFile(ctx, src, p, dst, archivePath) + if err != nil { + return err + } + if same { + return fmt.Errorf("%w: %s", ErrSameFile, p) + } + if src.Volume() != dst.Volume() { + continue + } + fi, err := src.Lstat(ctx, p) + if err != nil { + return err + } + if !fi.IsDir() { + continue + } + in, err := vfs.Within(ctx, dst, archivePath, p) + if err != nil { + return err + } + if in { + return fmt.Errorf("%w: %s", ErrIntoSource, p) + } + } + return nil +} + +// resolveTarget handles an existing archive file. +func resolveTarget(ctx context.Context, dst vfs.FS, p string, h transfer.Hooks) (target string, replace, skip bool, err error) { + fi, err := dst.Lstat(ctx, p) + if errors.Is(err, vfs.ErrNotExist) { + return p, false, false, nil + } + if err != nil { + return "", false, false, err + } + if fi.IsDir() { + return "", false, false, fmt.Errorf("%s is a directory", p) + } + if h.Resolve == nil { + return "", false, false, fmt.Errorf("%s: %w", p, vfs.ErrExist) + } + res, err := h.Resolve(ctx, transfer.Conflict{ + Item: transfer.Item{Rel: dst.Paths().Base(p), Kind: transfer.File, Existing: &fi}, + Kind: transfer.FileFile, + }) + if err != nil { + return "", false, false, err + } + switch res.Action { + case transfer.ResolveOverwrite: + return p, true, false, nil + case transfer.ResolveSkip: + return "", false, true, nil + case transfer.ResolveKeepBoth: + free, err := FreeName(ctx, dst, p) + return free, false, false, err + } + return "", false, false, transfer.ErrAborted +} + +// FreeName returns p or the first free "name (n).ext" next to it (the +// archive extension, e.g. .tar.gz, stays together). +func FreeName(ctx context.Context, fsys vfs.FS, p string) (string, error) { + ops := fsys.Paths() + dir, base := ops.Dir(p), ops.Base(p) + stem := stripArchiveExt(base) + ext := base[len(stem):] + for n := 0; n <= 10000; n++ { + cand := p + if n > 0 { + cand = ops.Join(dir, fmt.Sprintf("%s (%d)%s", stem, n, ext)) + } + _, err := fsys.Lstat(ctx, cand) + if errors.Is(err, vfs.ErrNotExist) { + return cand, nil + } + if err != nil { + return "", err + } + } + return "", fmt.Errorf("no free name for %s", p) +} + +// writer streams the items into the archive format. +type writer struct { + ctx context.Context + src vfs.FS + f Format + h transfer.Hooks + rep *transfer.Report + items []transfer.Item + total int64 + done int64 + files int + last time.Time +} + +func (w *writer) progress(force bool) { + if w.h.Progress == nil { + return + } + every := w.h.ProgressInterval + if every <= 0 { + every = 50 * time.Millisecond + } + if !force && time.Since(w.last) < every { + return + } + w.last = time.Now() + w.h.Progress(transfer.Progress{Phase: transfer.Copying, FilesDone: w.files, BytesDone: w.done, BytesTotal: w.total}) +} + +func (w *writer) fill(out io.Writer) error { + switch w.f { + case Zip: + zw := zip.NewWriter(out) + if err := w.each(zipAdder{zw}); err != nil { + return err + } + return zw.Close() + case Tar, TarGz: + var gz *gzip.Writer + if w.f == TarGz { + gz = gzip.NewWriter(out) + out = gz + } + tw := tar.NewWriter(out) + if err := w.each(tarAdder{tw}); err != nil { + return err + } + if err := tw.Close(); err != nil { + return err + } + if gz != nil { + return gz.Close() + } + return nil + } + return fmt.Errorf("archive: unknown format %d", w.f) +} + +// adder writes one entry; body is nil except for regular files. +type adder interface { + add(it transfer.Item, body io.Reader) error +} + +func (w *writer) each(a adder) error { + for _, it := range w.items { + if err := w.ctx.Err(); err != nil { + return err + } + switch it.Kind { + case transfer.Special: + w.rep.Skipped++ + w.rep.Warnings = append(w.rep.Warnings, it.Rel+": special file skipped") + continue + case transfer.Dir, transfer.Symlink: + if err := a.add(it, nil); err != nil { + return err + } + if it.Kind == transfer.Symlink { + w.rep.Done++ + w.files++ + } + continue + } + if err := w.addFile(a, it); err != nil { + return err + } + } + return nil +} + +// addFile opens the source first, so an unreadable file can be skipped +// (OnError) before its header is written. An error in the middle of a file +// aborts the archive (a tar header already promised its size). +func (w *writer) addFile(a adder, it transfer.Item) error { + for { + r, err := w.src.Open(w.ctx, it.Src) + if err == nil { + start := w.done + pr := &countReader{ctx: w.ctx, r: r, onRead: func(n int64) { w.done = start + n; w.progress(false) }} + err = a.add(it, pr) + r.Close() + if err != nil { + return fmt.Errorf("%s: %w", it.Rel, err) + } + if pr.n != it.Size { + return fmt.Errorf("%s: changed while archiving (%d of %d bytes)", it.Rel, pr.n, it.Size) + } + w.files++ + w.rep.Done++ + w.rep.Bytes += it.Size + return nil + } + ie := transfer.ItemError{Item: it, Op: "read", Err: err} + act := transfer.ErrorSkip + switch { + case w.h.OnError != nil: + var herr error + if act, herr = w.h.OnError(w.ctx, ie); herr != nil { + return herr + } + } + switch act { + case transfer.ErrorRetry: + continue + case transfer.ErrorStop: + w.rep.Errors = append(w.rep.Errors, ie) + w.rep.Failed++ + return fmt.Errorf("%w: %v", transfer.ErrAborted, ie) + } + w.rep.Errors = append(w.rep.Errors, ie) + w.rep.Failed++ + w.done += it.Size + return nil + } +} + +type countReader struct { + ctx context.Context + r io.Reader + n int64 + onRead func(int64) +} + +func (c *countReader) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + n, err := c.r.Read(p) + c.n += int64(n) + if n > 0 { + c.onRead(c.n) + } + return n, err +} + +type zipAdder struct{ zw *zip.Writer } + +func (z zipAdder) add(it transfer.Item, body io.Reader) error { + h := &zip.FileHeader{Name: it.Rel, Modified: it.ModTime, Method: zip.Deflate} + switch it.Kind { + case transfer.Dir: + h.Name += "/" + h.Method = zip.Store + h.SetMode(fs.ModeDir | it.Mode.Perm()) + case transfer.Symlink: + h.Method = zip.Store + h.SetMode(fs.ModeSymlink | 0o777) + body = strings.NewReader(it.LinkTarget) + default: + h.SetMode(it.Mode.Perm()) + h.UncompressedSize64 = uint64(it.Size) + } + w, err := z.zw.CreateHeader(h) + if err != nil { + return err + } + if body != nil { + _, err = io.Copy(w, body) + } + return err +} + +type tarAdder struct{ tw *tar.Writer } + +func (t tarAdder) add(it transfer.Item, body io.Reader) error { + h := &tar.Header{Name: it.Rel, ModTime: it.ModTime, Mode: int64(it.Mode.Perm())} + switch it.Kind { + case transfer.Dir: + h.Typeflag, h.Name = tar.TypeDir, it.Rel+"/" + case transfer.Symlink: + h.Typeflag, h.Linkname, h.Mode = tar.TypeSymlink, it.LinkTarget, 0o777 + default: + h.Typeflag, h.Size = tar.TypeReg, it.Size + } + if err := t.tw.WriteHeader(h); err != nil { + return err + } + if body != nil { + if _, err := io.Copy(t.tw, body); err != nil { + return err + } + } + return nil +} diff --git a/internal/archive/create_test.go b/internal/archive/create_test.go new file mode 100644 index 0000000..f199c91 --- /dev/null +++ b/internal/archive/create_test.go @@ -0,0 +1,214 @@ +package archive + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/transfer" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +var local = localfs.New() + +func noTemps(t *testing.T, dir string) { + t.Helper() + ents, _ := os.ReadDir(dir) + for _, e := range ents { + if strings.HasPrefix(e.Name(), ".vcom-") { + t.Errorf("temp left: %s", e.Name()) + } + } +} + +func TestUP01_ArchiveDoesNotDestroySource(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("data.tar", "").WithSize(64 << 10)}) + before, _ := os.ReadFile(filepath.Join(dir, "data.tar")) + name := Name([]string{"data.tar"}, Tar) + if name != "data.tar" { + t.Fatalf("name %s", name) + } + rep := Create(bg, local, []string{filepath.Join(dir, "data.tar")}, local, filepath.Join(dir, name), Tar, + transfer.Hooks{Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) { + return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil + }}) + if !errors.Is(rep.Err, ErrSameFile) { + t.Fatalf("err = %v, want ErrSameFile (U-P0-1)", rep.Err) + } + if after, _ := os.ReadFile(filepath.Join(dir, "data.tar")); string(after) != string(before) { + t.Fatal("source damaged") + } + // With another name (what the UI offers) it works. + free, err := FreeName(bg, local, filepath.Join(dir, name)) + if err != nil || filepath.Base(free) != "data (1).tar" { + t.Fatalf("free name %q %v", free, err) + } + rep = Create(bg, local, []string{filepath.Join(dir, "data.tar")}, local, free, Tar, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 1 { + t.Fatalf("%+v", rep) + } + idx, err := IndexFile(bg, local, free, nil) + if err != nil || len(idx.Entries) != 1 || idx.Entries[0].Size != 64<<10 { + t.Fatalf("index %+v %v", idx, err) + } +} + +func TestArchiveIntoSourceDirRejected(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("proj/a", "a"), fstree.Dir("proj/sub"), fstree.Symlink("alias", "proj")}) + for _, target := range []string{ + filepath.Join(dir, "proj", "proj.zip"), + filepath.Join(dir, "proj", "sub", "x.zip"), + filepath.Join(dir, "alias", "x.zip"), // through a symlink + } { + rep := Create(bg, local, []string{filepath.Join(dir, "proj")}, local, target, Zip, transfer.Hooks{}) + if !errors.Is(rep.Err, ErrIntoSource) { + t.Errorf("%s: %v", target, rep.Err) + } + if _, err := os.Lstat(target); !os.IsNotExist(err) { + t.Errorf("%s written", target) + } + } + if rep := Create(bg, local, []string{filepath.Join(dir, "proj")}, local, filepath.Join(dir, "proj.zip"), Zip, transfer.Hooks{}); rep.Err != nil { + t.Fatal(rep.Err) + } +} + +func TestArchiveCancelRemovesPartial(t *testing.T) { + src := t.TempDir() + fstree.Build(t, src, fstree.Spec{fstree.File("d/big", "").WithSize(4 << 20), fstree.File("d/b", "b")}) + out := t.TempDir() + old := filepath.Join(out, "d.tar.gz") + if err := os.WriteFile(old, []byte("previous archive"), 0o644); err != nil { + t.Fatal(err) + } + dst := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpWrite { + time.Sleep(2 * time.Millisecond) + } + return nil + }} + ctx, cancel := context.WithCancel(bg) + time.AfterFunc(50*time.Millisecond, cancel) + rep := Create(ctx, local, []string{filepath.Join(src, "d")}, dst, old, TarGz, transfer.Hooks{ + Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) { + return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil + }}) + if !rep.Cancelled || rep.Done != 0 { + t.Fatalf("%+v", rep) + } + if b, _ := os.ReadFile(old); string(b) != "previous archive" { + t.Fatal("previous archive damaged by a cancelled overwrite") + } + noTemps(t, out) +} + +func TestArchiveCloseErrorReported(t *testing.T) { + src := t.TempDir() + fstree.Build(t, src, fstree.Spec{fstree.File("a", "data")}) + for _, f := range []Format{Zip, Tar, TarGz} { + out := t.TempDir() + dst := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpClose, 1, syscall.EIO)} + target := filepath.Join(out, "a"+f.Ext()) + rep := Create(bg, local, []string{filepath.Join(src, "a")}, dst, target, f, transfer.Hooks{}) + if !errors.Is(rep.Err, syscall.EIO) || rep.Done != 0 { + t.Fatalf("%v: close error not reported (N-P2-13): %+v", f, rep) + } + if _, err := os.Lstat(target); !os.IsNotExist(err) { + t.Fatalf("%v: archive committed", f) + } + noTemps(t, out) + // A write error while the writers flush on Close is reported too. + dst = &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpWrite, 1, syscall.ENOSPC)} + rep = Create(bg, local, []string{filepath.Join(src, "a")}, dst, target, f, transfer.Hooks{}) + if !errors.Is(rep.Err, syscall.ENOSPC) { + t.Fatalf("%v: flush error: %+v", f, rep) + } + noTemps(t, out) + } +} + +func TestArchiveNameTarGzToZip(t *testing.T) { + if got := Name([]string{"/srv/foo.tar.gz"}, Zip); got != "foo.zip" { + t.Fatalf("got %s (U-P2: was foo.tar.zip)", got) + } + out := t.TempDir() + fstree.Build(t, out, fstree.Spec{fstree.File("a (1).tar.gz", ""), fstree.File("a.tar.gz", "")}) + if p, _ := FreeName(bg, local, filepath.Join(out, "a.tar.gz")); filepath.Base(p) != "a (2).tar.gz" { + t.Fatalf("free %s", p) + } +} + +func TestArchiveSymlinksPreserved(t *testing.T) { + src := t.TempDir() + mt := time.Date(2019, 3, 4, 5, 6, 7, 0, time.UTC) + spec := fstree.Spec{ + fstree.File("d/run.sh", "#!/bin/sh").WithMode(0o755).WithMTime(mt), + fstree.Symlink("d/ln", "run.sh"), + fstree.Symlink("d/broken", "../nowhere"), + fstree.Dir("d/empty"), + } + fstree.Build(t, src, spec) + for _, f := range []Format{Zip, Tar, TarGz} { + out := t.TempDir() + arch := filepath.Join(out, "d"+f.Ext()) + rep := Create(bg, local, []string{filepath.Join(src, "d")}, local, arch, f, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 3 { + t.Fatalf("%v: %+v", f, rep) + } + idx, err := IndexFile(bg, local, arch, nil) + if err != nil { + t.Fatal(err) + } + for p, want := range map[string]string{"d/ln": "run.sh", "d/broken": "../nowhere"} { + if e, ok := idx.Lookup(p); !ok || !e.IsSymlink() || e.Link != want { + t.Fatalf("%v: %s = %+v", f, p, e) + } + } + // Round trip through Unpack gives the same tree (modes, mtimes, links). + back := t.TempDir() + if rep := Unpack(bg, local, arch, idx, nil, local, back, transfer.DefaultOptions(), transfer.Hooks{}); rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%v: unpack %+v", f, rep) + } + fstree.Equal(t, fstree.Snapshot(t, filepath.Join(src, "d")), fstree.Snapshot(t, filepath.Join(back, "d")), + fstree.Opts{Mode: true, Links: true}) + if fi, _ := os.Stat(filepath.Join(back, "d", "run.sh")); !fi.ModTime().Equal(mt) { + t.Fatalf("%v: mtime %v", f, fi.ModTime()) + } + } +} + +func TestArchiveExistingTargetIsConflict(t *testing.T) { + src, out := t.TempDir(), t.TempDir() + fstree.Build(t, src, fstree.Spec{fstree.File("a", "new")}) + target := filepath.Join(out, "a.zip") + _ = os.WriteFile(target, []byte("old"), 0o644) + if rep := Create(bg, local, []string{filepath.Join(src, "a")}, local, target, Zip, transfer.Hooks{}); !errors.Is(rep.Err, vfs.ErrExist) { + t.Fatalf("no Resolve: %v", rep.Err) + } + rep := Create(bg, local, []string{filepath.Join(src, "a")}, local, target, Zip, transfer.Hooks{ + Resolve: func(_ context.Context, c transfer.Conflict) (transfer.Resolution, error) { + if c.Item.Existing == nil { + t.Error("no Existing") + } + return transfer.Resolution{Action: transfer.ResolveKeepBoth}, nil + }}) + if rep.Err != nil || len(rep.Affected) != 1 { + t.Fatalf("%+v", rep) + } + if b, _ := os.ReadFile(target); string(b) != "old" { + t.Fatal("KeepBoth overwrote") + } + if _, err := os.Stat(filepath.Join(out, "a (1).zip")); err != nil { + t.Fatal(err) + } +} diff --git a/internal/archive/format.go b/internal/archive/format.go new file mode 100644 index 0000000..d3c1830 --- /dev/null +++ b/internal/archive/format.go @@ -0,0 +1,89 @@ +// Package archive reads and writes zip, tar and tar.gz archives on top of +// vfs (design §5.1–5.3): an Index is built without unpacking anything to a +// temp directory, NewSource feeds members to the transfer engine in one pass +// over the archive (Unpack), and Create writes an archive through +// transfer.WriteAtomic. +package archive + +import ( + "path" + "strings" +) + +// Format of an archive. +type Format uint8 + +const ( + Zip Format = iota + Tar + TarGz +) + +func (f Format) String() string { + switch f { + case Zip: + return "zip" + case Tar: + return "tar" + case TarGz: + return "tar.gz" + } + return "unknown" +} + +// Ext is the file extension, with the dot. +func (f Format) Ext() string { return "." + f.String() } + +// knownExts in match order (longest first). +var knownExts = []struct { + ext string + f Format +}{ + {".tar.gz", TarGz}, {".tgz", TarGz}, {".tar", Tar}, {".zip", Zip}, +} + +// DetectFormat guesses the format from the file name. +func DetectFormat(name string) (Format, bool) { + lower := strings.ToLower(name) + for _, k := range knownExts { + if strings.HasSuffix(lower, k.ext) && len(lower) > len(k.ext) { + return k.f, true + } + } + return 0, false +} + +// stripArchiveExt removes a known archive extension, or else the last +// extension (report.pdf → report). +func stripArchiveExt(name string) string { + lower := strings.ToLower(name) + for _, k := range knownExts { + if strings.HasSuffix(lower, k.ext) && len(name) > len(k.ext) { + return name[:len(name)-len(k.ext)] + } + } + if ext := path.Ext(name); ext != "" && ext != name { + return name[:len(name)-len(ext)] + } + return name +} + +// Name proposes an archive file name for the given sources (paths or base +// names, slash-separated): one source → its name without extension +// (foo.tar.gz → foo.zip, not foo.tar.zip; U-P2); several → the name of +// their parent directory, or "archive". +func Name(srcNames []string, f Format) string { + if len(srcNames) == 1 { + base := path.Base(strings.TrimRight(srcNames[0], "/")) + if b := stripArchiveExt(base); b != "" && b != "." && b != "/" { + return b + f.Ext() + } + } + if len(srcNames) > 1 { + parent := path.Base(path.Dir(srcNames[0])) + if parent != "." && parent != "/" && parent != "" { + return parent + f.Ext() + } + } + return "archive" + f.Ext() +} diff --git a/internal/archive/helpers_test.go b/internal/archive/helpers_test.go new file mode 100644 index 0000000..b20b9ae --- /dev/null +++ b/internal/archive/helpers_test.go @@ -0,0 +1,135 @@ +package archive + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "io/fs" + "os" + "path/filepath" + "testing" + "time" +) + +var bg = context.Background() + +// member describes an entry for test archives. +type member struct { + name string + body string + mode fs.FileMode // type bits + perm; 0 → regular 0644 + link string +} + +var mtime = time.Date(2020, 5, 6, 7, 8, 9, 0, time.UTC) + +func dir(name string) member { return member{name: name, mode: fs.ModeDir | 0o755} } +func file(name, body string) member { return member{name: name, body: body} } +func symlink(name, target string) member { + return member{name: name, mode: fs.ModeSymlink | 0o777, link: target} +} + +// makeArchive writes members in the given format to a byte slice. +func makeArchive(t *testing.T, f Format, ms ...member) []byte { + t.Helper() + var buf bytes.Buffer + switch f { + case Zip: + zw := zip.NewWriter(&buf) + for _, m := range ms { + mode := m.mode + if mode == 0 { + mode = 0o644 + } + h := &zip.FileHeader{Name: m.name, Method: zip.Deflate, Modified: mtime} + h.SetMode(mode) + w, err := zw.CreateHeader(h) + if err != nil { + t.Fatal(err) + } + body := m.body + if mode&fs.ModeSymlink != 0 { + body = m.link + } + if _, err := w.Write([]byte(body)); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + default: + var gz *gzip.Writer + var tw *tar.Writer + if f == TarGz { + gz = gzip.NewWriter(&buf) + tw = tar.NewWriter(gz) + } else { + tw = tar.NewWriter(&buf) + } + for _, m := range ms { + h := &tar.Header{Name: m.name, Mode: 0o644, ModTime: mtime, Typeflag: tar.TypeReg, Size: int64(len(m.body))} + switch { + case m.mode.IsDir(): + h.Typeflag, h.Mode, h.Size = tar.TypeDir, 0o755, 0 + case m.mode&fs.ModeSymlink != 0: + h.Typeflag, h.Mode, h.Size, h.Linkname = tar.TypeSymlink, 0o777, 0, m.link + case m.mode&fs.ModeNamedPipe != 0: + h.Typeflag, h.Size = tar.TypeFifo, 0 + case m.mode != 0: + h.Mode = int64(m.mode.Perm()) + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if h.Size > 0 { + if _, err := tw.Write([]byte(m.body)); err != nil { + t.Fatal(err) + } + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if gz != nil { + if err := gz.Close(); err != nil { + t.Fatal(err) + } + } + } + return buf.Bytes() +} + +// writeArchive stores an archive as / and returns its path. +func writeArchive(t *testing.T, name string, ms ...member) string { + t.Helper() + f, ok := DetectFormat(name) + if !ok { + t.Fatalf("bad name %s", name) + } + p := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(p, makeArchive(t, f, ms...), 0o644); err != nil { + t.Fatal(err) + } + return p +} + +func index(t *testing.T, f Format, ms ...member) *Index { + t.Helper() + b := makeArchive(t, f, ms...) + idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), f, nil) + if err != nil { + t.Fatal(err) + } + return idx +} + +func paths(idx *Index) []string { + var out []string + for _, e := range idx.Entries { + out = append(out, e.Path) + } + return out +} diff --git a/internal/archive/index.go b/internal/archive/index.go new file mode 100644 index 0000000..1a3f960 --- /dev/null +++ b/internal/archive/index.go @@ -0,0 +1,308 @@ +package archive + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "io/fs" + "path" + "sort" + "strings" + "time" +) + +// Entry is one member of an archive. +type Entry struct { + Path string // clean, slash-separated, relative ("dir/file"); never "..", never absolute + Mode fs.FileMode + Size int64 + ModTime time.Time + Link string // symlink target, as stored + // Implicit: a parent directory that has no entry of its own. + Implicit bool + ord int // position in the archive (header number); -1 for implicit dirs +} + +// IsDir, IsSymlink and IsRegular classify the entry. +func (e Entry) IsDir() bool { return e.Mode.IsDir() } +func (e Entry) IsSymlink() bool { return e.Mode&fs.ModeSymlink != 0 } +func (e Entry) IsRegular() bool { return e.Mode.IsRegular() } + +// Index lists an archive's members, sorted by path (parents first). +type Index struct { + Format Format + Entries []Entry + TotalBytes int64 // sum of regular file sizes (shown before unpacking) + Rejected []string // unsafe names dropped (zip-slip, absolute, under a symlink) + byPath map[string]int +} + +// Lookup returns the entry at p ("" or "/" is not an entry). +func (x *Index) Lookup(p string) (Entry, bool) { + i, ok := x.byPath[strings.Trim(path.Clean("/"+p), "/")] + if !ok { + return Entry{}, false + } + return x.Entries[i], true +} + +// Limits protect against archive bombs. +type Limits struct { + MaxMembers int // default 1 000 000 + MaxBytes int64 // sum of declared sizes; 0 = unlimited +} + +// DefaultLimits are used by BuildIndex. +var DefaultLimits = Limits{MaxMembers: 1_000_000} + +// ErrTooManyMembers and ErrTooLarge are returned when Limits are exceeded. +var ( + ErrTooManyMembers = errors.New("archive has too many members") + ErrTooLarge = errors.New("archive is too large") +) + +// BuildIndex reads the archive's directory (zip) or walks it once (tar, +// tar.gz: one decompression pass). progress gets the member count so far; +// ctx cancels the pass. +func BuildIndex(ctx context.Context, r io.ReaderAt, size int64, f Format, progress func(n int)) (*Index, error) { + return BuildIndexLimits(ctx, r, size, f, DefaultLimits, progress) +} + +// BuildIndexLimits is BuildIndex with explicit limits. +func BuildIndexLimits(ctx context.Context, r io.ReaderAt, size int64, f Format, lim Limits, progress func(n int)) (*Index, error) { + b := &indexBuilder{idx: &Index{Format: f}, lim: lim, kinds: map[string]fs.FileMode{}, progress: progress} + var err error + switch f { + case Zip: + err = b.zip(ctx, r, size) + case Tar, TarGz: + err = b.tar(ctx, io.NewSectionReader(r, 0, size), f == TarGz) + default: + err = fmt.Errorf("archive: unknown format %d", f) + } + if err != nil { + return nil, err + } + b.finish() + return b.idx, nil +} + +type indexBuilder struct { + idx *Index + lim Limits + n int + kinds map[string]fs.FileMode // path → type bits of entries seen + entries map[string]Entry + progress func(int) +} + +func (b *indexBuilder) zip(ctx context.Context, r io.ReaderAt, size int64) error { + zr, err := zip.NewReader(r, size) + if err != nil && !errors.Is(err, zip.ErrInsecurePath) { // insecure names are rejected below + return err + } + for i, zf := range zr.File { + if i%256 == 0 { + if err := ctx.Err(); err != nil { + return err + } + } + mode := zf.Mode() + e := Entry{Path: zf.Name, Mode: mode, Size: int64(zf.UncompressedSize64), ModTime: zf.Modified, ord: i} + if mode&fs.ModeSymlink != 0 { + e.Size = 0 + link, err := readZipLink(zf) + if err != nil { + return fmt.Errorf("%s: %w", zf.Name, err) + } + e.Link = link + } + if err := b.add(e); err != nil { + return err + } + } + return nil +} + +// readZipLink reads a symlink's target, stored as the member's body. +func readZipLink(zf *zip.File) (string, error) { + rc, err := zf.Open() + if err != nil { + return "", err + } + defer rc.Close() + b, err := io.ReadAll(io.LimitReader(rc, 4096)) + return string(b), err +} + +func (b *indexBuilder) tar(ctx context.Context, r io.Reader, gz bool) error { + if gz { + zr, err := gzip.NewReader(r) + if err != nil { + return err + } + defer zr.Close() + r = zr + } + tr := tar.NewReader(&ctxReader{ctx: ctx, r: r}) + for i := 0; ; i++ { + h, err := tr.Next() + if err == io.EOF { + return nil + } + if errors.Is(err, tar.ErrInsecurePath) { + err = nil // (GODEBUG=tarinsecurepath=0) rejected by cleanName instead + } + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return err + } + e, ok := tarEntry(h, i) + if !ok { + continue // PAX globals, GNU long-name records handled by archive/tar + } + if err := b.add(e); err != nil { + return err + } + } +} + +func tarEntry(h *tar.Header, ord int) (Entry, bool) { + fi := h.FileInfo() + e := Entry{Path: h.Name, Mode: fi.Mode(), Size: h.Size, ModTime: h.ModTime, ord: ord} + switch h.Typeflag { + case tar.TypeReg, tar.TypeRegA, tar.TypeGNUSparse: + case tar.TypeDir: + e.Size = 0 + case tar.TypeSymlink: + e.Size, e.Link = 0, h.Linkname + case tar.TypeLink: + // Hard links are indexed as specials (skipped on unpack): following + // them would need a second pass. + e.Mode, e.Size = fs.ModeIrregular|fi.Mode().Perm(), 0 + case tar.TypeChar, tar.TypeBlock, tar.TypeFifo: + e.Size = 0 + default: + return Entry{}, false + } + return e, true +} + +// cleanName returns the safe relative path of a member, or false for +// zip-slip ("..", absolute paths, drive letters). +func cleanName(name string) (string, bool) { + name = strings.ReplaceAll(name, "\\", "/") + if strings.HasPrefix(name, "/") || (len(name) > 1 && name[1] == ':') { + return "", false + } + for _, part := range strings.Split(name, "/") { + if part == ".." { + return "", false + } + } + c := path.Clean(name) + if c == "." || c == "" { + return "", false + } + return c, true +} + +func (b *indexBuilder) add(e Entry) error { + b.n++ + if b.lim.MaxMembers > 0 && b.n > b.lim.MaxMembers { + return fmt.Errorf("%w (more than %d)", ErrTooManyMembers, b.lim.MaxMembers) + } + if b.progress != nil && b.n%256 == 0 { + b.progress(b.n) + } + p, ok := cleanName(e.Path) + if !ok { + b.idx.Rejected = append(b.idx.Rejected, e.Path) + return nil + } + // A member below a symlink (or file) of the same archive would be + // written through that link on unpack: reject it. + for d := path.Dir(p); d != "."; d = path.Dir(d) { + if m, seen := b.kinds[d]; seen && !m.IsDir() { + b.idx.Rejected = append(b.idx.Rejected, e.Path) + return nil + } + } + e.Path = p + if e.Mode.IsRegular() { + b.idx.TotalBytes += e.Size + if b.lim.MaxBytes > 0 && b.idx.TotalBytes > b.lim.MaxBytes { + return fmt.Errorf("%w (more than %d bytes)", ErrTooLarge, b.lim.MaxBytes) + } + } + if b.entries == nil { + b.entries = map[string]Entry{} + } + if old, dup := b.entries[p]; dup && old.Mode.IsRegular() { + b.idx.TotalBytes -= old.Size // a later member with the same name wins (tar semantics) + } + b.entries[p] = e + b.kinds[p] = e.Mode.Type() + return nil +} + +// finish drops members below a non-directory (in any archive order), adds +// implicit parent directories and sorts. +func (b *indexBuilder) finish() { + for p := range b.entries { + for d := path.Dir(p); d != "."; d = path.Dir(d) { + if e, ok := b.entries[d]; ok && !e.IsDir() { + b.idx.Rejected = append(b.idx.Rejected, p) + if old := b.entries[p]; old.Mode.IsRegular() { + b.idx.TotalBytes -= old.Size + } + delete(b.entries, p) + break + } + } + } + sort.Strings(b.idx.Rejected) + for p := range b.entries { + for d := path.Dir(p); d != "."; d = path.Dir(d) { + if _, ok := b.entries[d]; ok { + break + } + b.entries[d] = Entry{Path: d, Mode: fs.ModeDir | 0o755, Implicit: true, ord: -1} + } + } + x := b.idx + x.Entries = make([]Entry, 0, len(b.entries)) + for _, e := range b.entries { + x.Entries = append(x.Entries, e) + } + // Sort by components: "a/b" right after "a" (plain order puts "a-b" between). + sort.Slice(x.Entries, func(i, j int) bool { + return strings.ReplaceAll(x.Entries[i].Path, "/", "\x00") < strings.ReplaceAll(x.Entries[j].Path, "/", "\x00") + }) + x.byPath = make(map[string]int, len(x.Entries)) + for i, e := range x.Entries { + x.byPath[e.Path] = i + } + if b.progress != nil { + b.progress(b.n) + } +} + +// ctxReader stops a long decompression on cancel. +type ctxReader struct { + ctx context.Context + r io.Reader +} + +func (c *ctxReader) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + return c.r.Read(p) +} diff --git a/internal/archive/index_test.go b/internal/archive/index_test.go new file mode 100644 index 0000000..e4b4e81 --- /dev/null +++ b/internal/archive/index_test.go @@ -0,0 +1,211 @@ +package archive + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "vcom/internal/transfer" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +func TestIndexZip(t *testing.T) { + idx := index(t, Zip, + dir("docs/"), + file("docs/a.txt", "hello"), + file("deep/x/y.bin", "12345678"), // parents implicit + symlink("docs/ln", "a.txt"), + ) + if got := fmt.Sprint(paths(idx)); got != "[deep deep/x deep/x/y.bin docs docs/a.txt docs/ln]" { + t.Fatalf("paths %s", got) + } + if idx.TotalBytes != 13 || idx.Format != Zip { + t.Fatalf("total %d", idx.TotalBytes) + } + e, _ := idx.Lookup("/docs/ln") + if !e.IsSymlink() || e.Link != "a.txt" { + t.Fatalf("link %+v", e) + } + d, _ := idx.Lookup("deep") + if !d.IsDir() || !d.Implicit { + t.Fatalf("implicit dir %+v", d) + } + f, _ := idx.Lookup("docs/a.txt") + if f.Size != 5 || !f.ModTime.Equal(mtime) || f.Mode.Perm() != 0o644 { + t.Fatalf("file %+v", f) + } +} + +func TestIndexTarGz(t *testing.T) { + var ms []member + for i := range 1000 { + ms = append(ms, file(fmt.Sprintf("d/f%04d", i), "x")) + } + ms = append(ms, symlink("d/ln", "f0000"), member{name: "d/fifo", mode: os.ModeNamedPipe | 0o644}) + b := makeArchive(t, TarGz, ms...) + var progress []int + idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) { progress = append(progress, n) }) + if err != nil { + t.Fatal(err) + } + if len(idx.Entries) != 1003 || idx.TotalBytes != 1000 { + t.Fatalf("%d entries, %d bytes", len(idx.Entries), idx.TotalBytes) + } + if len(progress) < 3 || progress[len(progress)-1] != 1002 { + t.Fatalf("progress %v", progress) + } + if e, _ := idx.Lookup("d/fifo"); e.Mode&os.ModeNamedPipe == 0 { + t.Fatalf("fifo %+v", e) + } + + ctx, cancel := context.WithCancel(bg) + _, err = BuildIndex(ctx, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) { + if n >= 256 { + cancel() + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancel: %v", err) + } +} + +func TestZipSlipRejected(t *testing.T) { + for _, f := range []Format{Zip, Tar} { + idx := index(t, f, + file("../evil", "x"), + file("/abs/path", "x"), + file("a/../../up", "x"), + file(`..\win`, "x"), + file("C:/drive", "x"), + file("ok/./file", "fine"), + symlink("esc", "/etc"), + file("esc/passwd", "through the link"), + file("plainfile", "f"), + file("plainfile/child", "under a file"), + ) + if got := fmt.Sprint(paths(idx)); got != "[esc ok ok/file plainfile]" { + t.Errorf("%v: kept %s", f, got) + } + if len(idx.Rejected) != 7 { + t.Errorf("%v: rejected %v", f, idx.Rejected) + } + if idx.TotalBytes != 5 { + t.Errorf("%v: total %d", f, idx.TotalBytes) + } + } + // A member under a link is rejected whatever the order in the archive. + idx := index(t, Tar, file("esc/passwd", "x"), symlink("esc", "/etc")) + if fmt.Sprint(paths(idx)) != "[esc]" { + t.Fatalf("order-dependent: %v", paths(idx)) + } +} + +func TestMemberLimit(t *testing.T) { + var ms []member + for i := range 11 { + ms = append(ms, file(fmt.Sprintf("f%d", i), "abc")) + } + for _, f := range []Format{Zip, TarGz} { + b := makeArchive(t, f, ms...) + if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 10}, nil); !errors.Is(err, ErrTooManyMembers) { + t.Errorf("%v members: %v", f, err) + } + if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxBytes: 30}, nil); !errors.Is(err, ErrTooLarge) { + t.Errorf("%v bytes: %v", f, err) + } + if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 11, MaxBytes: 33}, nil); err != nil { + t.Errorf("%v at the limit: %v", f, err) + } + } +} + +// opens counts FS opens of one path. +type opens struct { + mu sync.Mutex + n map[string]int +} + +func (o *opens) hook(op vfstest.Op, p string) error { + if op == vfstest.OpOpen { + o.mu.Lock() + if o.n == nil { + o.n = map[string]int{} + } + o.n[p]++ + o.mu.Unlock() + } + return nil +} + +func TestSourceSinglePass(t *testing.T) { + for _, name := range []string{"a.tar.gz", "a.zip", "a.tar"} { + var ms []member + for i := range 50 { + ms = append(ms, file(fmt.Sprintf("top/f%02d", i), strings.Repeat("y", i))) + } + ms = append(ms, symlink("top/ln", "f01"), dir("top/empty/")) + arch := writeArchive(t, name, ms...) + o := &opens{} + fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: o.hook} + idx, err := IndexFile(bg, fsys, arch, nil) + if err != nil { + t.Fatal(err) + } + dst := t.TempDir() + rep := Unpack(bg, fsys, arch, idx, nil, localfs.New(), dst, transfer.DefaultOptions(), transfer.Hooks{}) + if rep.Err != nil || rep.Done != 51 || rep.Failed != 0 { + t.Fatalf("%s: %+v", name, rep) + } + if o.n[arch] != 2 { // one for the index, one for the unpack + t.Fatalf("%s: archive opened %d times, want 2 (one pass per phase)", name, o.n[arch]) + } + b, _ := os.ReadFile(filepath.Join(dst, "top", "f49")) + if len(b) != 49 { + t.Fatalf("%s: f49 has %d bytes", name, len(b)) + } + if l, _ := os.Readlink(filepath.Join(dst, "top", "ln")); l != "f01" { + t.Fatalf("%s: link %q", name, l) + } + if fi, err := os.Stat(filepath.Join(dst, "top", "empty")); err != nil || !fi.IsDir() { + t.Fatalf("%s: empty dir missing", name) + } + if fi, _ := os.Stat(filepath.Join(dst, "top", "f10")); !fi.ModTime().Equal(mtime) { + t.Fatalf("%s: mtime %v", name, fi.ModTime()) + } + } +} + +func TestNameAndDetect(t *testing.T) { + cases := []struct { + src []string + f Format + want string + }{ + {[]string{"foo.tar.gz"}, Zip, "foo.zip"}, + {[]string{"/x/foo.zip"}, TarGz, "foo.tar.gz"}, + {[]string{"report.pdf"}, Tar, "report.tar"}, + {[]string{"photos/"}, Zip, "photos.zip"}, + {[]string{"/home/u/proj/a", "/home/u/proj/b"}, Zip, "proj.zip"}, + {[]string{"a", "b"}, Tar, "archive.tar"}, + } + for _, c := range cases { + if got := Name(c.src, c.f); got != c.want { + t.Errorf("Name(%v, %v) = %q, want %q", c.src, c.f, got, c.want) + } + } + for name, want := range map[string]Format{"a.ZIP": Zip, "a.tgz": TarGz, "a.tar.gz": TarGz, "a.tar": Tar} { + if f, ok := DetectFormat(name); !ok || f != want { + t.Errorf("DetectFormat(%s) = %v %v", name, f, ok) + } + } + if _, ok := DetectFormat(".zip"); ok { + t.Error("bare extension detected") + } +} diff --git a/internal/archive/member.go b/internal/archive/member.go new file mode 100644 index 0000000..5e88367 --- /dev/null +++ b/internal/archive/member.go @@ -0,0 +1,94 @@ +package archive + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + + "vcom/internal/vfs" +) + +// OpenMember opens one regular member for reading. zip members are read +// directly; tar and tar.gz are scanned sequentially up to the member +// (expensive — meant for preview and single files, bulk extraction uses +// NewSource). The returned reader owns the archive file. +func OpenMember(ctx context.Context, fsys vfs.FS, archivePath string, idx *Index, p string) (io.ReadCloser, error) { + e, ok := idx.Lookup(p) + if !ok { + return nil, fmt.Errorf("%s: %w", p, vfs.ErrNotExist) + } + if !e.IsRegular() { + return nil, fmt.Errorf("%s: not a regular file", p) + } + file, err := fsys.Open(ctx, archivePath) + if err != nil { + return nil, err + } + rc, err := openMember(ctx, file, idx.Format, e.ord) + if err != nil { + file.Close() + return nil, err + } + return rc, nil +} + +func openMember(ctx context.Context, file vfs.File, f Format, ord int) (io.ReadCloser, error) { + if f == Zip { + fi, err := file.Stat() + if err != nil { + return nil, err + } + zr, err := zip.NewReader(file, fi.Size) + if err != nil && !errors.Is(err, zip.ErrInsecurePath) { + return nil, err + } + if ord >= len(zr.File) { + return nil, fmt.Errorf("archive changed since indexing: %w", vfs.ErrNotExist) + } + rc, err := zr.File[ord].Open() + if err != nil { + return nil, err + } + return multiCloser{rc, []io.Closer{rc, file}}, nil + } + var r io.Reader = &ctxReader{ctx: ctx, r: file} + closers := []io.Closer{file} + if f == TarGz { + zr, err := gzip.NewReader(r) + if err != nil { + return nil, err + } + r = zr + closers = append([]io.Closer{zr}, closers...) + } + tr := tar.NewReader(r) + for i := 0; ; i++ { + _, err := tr.Next() + if err == io.EOF { + return nil, fmt.Errorf("archive changed since indexing: %w", vfs.ErrNotExist) + } + if err != nil && !errors.Is(err, tar.ErrInsecurePath) { + return nil, err + } + if i == ord { + return multiCloser{tr, closers}, nil + } + } +} + +type multiCloser struct { + io.Reader + cs []io.Closer +} + +func (m multiCloser) Close() error { + var errs []error + for _, c := range m.cs { + errs = append(errs, c.Close()) + } + return errors.Join(errs...) +} diff --git a/internal/archive/remote_test.go b/internal/archive/remote_test.go new file mode 100644 index 0000000..854a8e3 --- /dev/null +++ b/internal/archive/remote_test.go @@ -0,0 +1,84 @@ +package archive + +import ( + "context" + "net" + "os" + "path/filepath" + "strconv" + "testing" + + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/ssh/conn" + "vcom/internal/testutil/fstree" + "vcom/internal/testutil/sshtest" + "vcom/internal/transfer" + "vcom/internal/vfs/sftpfs" +) + +// remoteFS starts an in-process SSH/SFTP server and returns an FS on it. +// The server shares this machine's file system, so results are checked on +// disk. +func remoteFS(t *testing.T) *sftpfs.FS { + t.Helper() + home := sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + kh := filepath.Join(home, ".ssh", "known_hosts") + f, err := os.OpenFile(kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + for _, k := range srv.HostKeys { + _, _ = f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(srv.Addr)}, k.PublicKey()) + "\n") + } + f.Close() + pool := conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{ + Home: home, AgentSocket: "-", KnownHostsFiles: []string{kh}, + }}) + t.Cleanup(func() { pool.Close() }) + host, port, _ := net.SplitHostPort(srv.Addr) + p, _ := strconv.Atoi(port) + l, err := pool.Acquire(context.Background(), conn.Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: srv.Password}) + if err != nil { + t.Fatal(err) + } + fsys := sftpfs.New(l) + t.Cleanup(fsys.Release) + return fsys +} + +// N-P1-15: archiving onto (and from) a remote panel works through vfs. +func TestArchiveToRemote(t *testing.T) { + remote := remoteFS(t) + src := t.TempDir() + fstree.Build(t, src, fstree.Spec{ + fstree.File("proj/a.txt", "alpha"), + fstree.File("proj/sub/b.bin", "").WithSize(300 << 10), + fstree.Symlink("proj/ln", "a.txt"), + }) + out := t.TempDir() + target := filepath.Join(out, "proj.tar.gz") + rep := Create(bg, local, []string{filepath.Join(src, "proj")}, remote, target, TarGz, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 3 { + t.Fatalf("local → remote: %+v", rep) + } + idx, err := IndexFile(bg, remote, target, nil) + if err != nil { + t.Fatal(err) + } + if e, ok := idx.Lookup("proj/sub/b.bin"); !ok || e.Size != 300<<10 { + t.Fatalf("index %+v", e) + } + if e, _ := idx.Lookup("proj/ln"); e.Link != "a.txt" { + t.Fatalf("link %+v", e) + } + noTemps(t, out) + + // Remote source → local archive. + back := filepath.Join(t.TempDir(), "again.zip") + rep = Create(bg, remote, []string{filepath.Join(src, "proj")}, local, back, Zip, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 3 { + t.Fatalf("remote → local: %+v", rep) + } +} diff --git a/internal/archive/source.go b/internal/archive/source.go new file mode 100644 index 0000000..39493bf --- /dev/null +++ b/internal/archive/source.go @@ -0,0 +1,242 @@ +package archive + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "path" + "strings" + + "vcom/internal/transfer" + "vcom/internal/vfs" +) + +// IndexFile opens p on fsys, detects the format from the name and builds the +// index. It reads the archive once and creates no temp files. +func IndexFile(ctx context.Context, fsys vfs.FS, p string, progress func(n int)) (*Index, error) { + f, ok := DetectFormat(p) + if !ok { + return nil, fmt.Errorf("archive: %s: unknown archive format", p) + } + file, err := fsys.Open(ctx, p) + if err != nil { + return nil, err + } + defer file.Close() + fi, err := file.Stat() + if err != nil { + return nil, err + } + return BuildIndex(ctx, file, fi.Size, f, progress) +} + +// NewSource returns a transfer.Source with the given members (archive paths; +// nil or empty = the whole archive). A member's Rel starts at its own name, +// so extracting "docs/a" yields "a" in the target. Stream reads the archive +// in one pass: directories and links come first (from the index), then file +// contents in archive order. +func NewSource(fsys vfs.FS, archivePath string, idx *Index, members []string) transfer.Source { + return &source{fs: fsys, path: archivePath, idx: idx, members: members} +} + +type source struct { + fs vfs.FS + path string + idx *Index + members []string + ordRel map[string]int // Rel of a file item → its ordinal in the archive +} + +func (s *source) Label() string { return s.fs.Paths().Base(s.path) } + +func (s *source) Walk(ctx context.Context, fn func(transfer.Item) error) error { + s.ordRel = map[string]int{} + emit := func(e Entry, rel string, root int) error { + it := transfer.Item{Rel: rel, Size: e.Size, Mode: e.Mode, ModTime: e.ModTime, LinkTarget: e.Link, Root: root} + switch { + case e.IsDir(): + it.Kind = transfer.Dir + case e.IsSymlink(): + it.Kind = transfer.Symlink + case e.IsRegular(): + it.Kind = transfer.File + s.ordRel[rel] = e.ord + default: + it.Kind = transfer.Special + } + return fn(it) + } + if len(s.members) == 0 { + roots := map[string]int{} + for i, e := range s.idx.Entries { + if i%256 == 0 { + if err := ctx.Err(); err != nil { + return err + } + } + top, _, _ := strings.Cut(e.Path, "/") + r, ok := roots[top] + if !ok { + r = len(roots) + roots[top] = r + } + if err := emit(e, e.Path, r); err != nil { + return err + } + } + return nil + } + for r, m := range s.members { + m = strings.Trim(path.Clean("/"+m), "/") + if _, ok := s.idx.Lookup(m); !ok { + return fmt.Errorf("%s: %w", m, vfs.ErrNotExist) + } + parent := path.Dir(m) + cut := 0 + if parent != "." { + cut = len(parent) + 1 + } + for _, e := range s.idx.Entries { + if e.Path != m && !strings.HasPrefix(e.Path, m+"/") { + continue + } + if err := emit(e, e.Path[cut:], r); err != nil { + return err + } + } + } + return ctx.Err() +} + +func (s *source) Stream(ctx context.Context, items []transfer.Item, fn func(transfer.Item, io.Reader) error) error { + wanted := map[int]transfer.Item{} + for _, it := range items { + if it.Kind == transfer.File { + ord, ok := s.ordRel[it.Rel] + if !ok { + return fmt.Errorf("archive: %s is not in the plan of this source", it.Rel) + } + wanted[ord] = it + continue + } + if err := fn(it, nil); err != nil { + return err + } + } + if len(wanted) == 0 { + return nil + } + file, err := s.fs.Open(ctx, s.path) + if err != nil { + return err + } + defer file.Close() + switch s.idx.Format { + case Zip: + err = s.streamZip(ctx, file, wanted, fn) + default: + err = s.streamTar(ctx, file, wanted, fn) + } + if err != nil { + return err + } + for _, it := range wanted { // members that vanished from the archive since indexing + if err := fn(it, errReader{fmt.Errorf("%s: %w in the archive", it.Rel, vfs.ErrNotExist)}); err != nil { + return err + } + } + return nil +} + +func (s *source) streamZip(ctx context.Context, file vfs.File, wanted map[int]transfer.Item, fn func(transfer.Item, io.Reader) error) error { + fi, err := file.Stat() + if err != nil { + return err + } + zr, err := zip.NewReader(file, fi.Size) + if err != nil && !errors.Is(err, zip.ErrInsecurePath) { + return err + } + for i, zf := range zr.File { + it, ok := wanted[i] + if !ok { + continue + } + if err := ctx.Err(); err != nil { + return err + } + delete(wanted, i) + rc, err := zf.Open() + if err != nil { + if err := fn(it, errReader{err}); err != nil { + return err + } + continue + } + err = fn(it, rc) + rc.Close() + if err != nil { + return err + } + } + return nil +} + +func (s *source) streamTar(ctx context.Context, file vfs.File, wanted map[int]transfer.Item, fn func(transfer.Item, io.Reader) error) error { + var r io.Reader = &ctxReader{ctx: ctx, r: file} + if s.idx.Format == TarGz { + zr, err := gzip.NewReader(r) + if err != nil { + return err + } + defer zr.Close() + r = zr + } + tr := tar.NewReader(r) + for i := 0; len(wanted) > 0; i++ { + _, err := tr.Next() + if err == io.EOF { + return nil + } + if errors.Is(err, tar.ErrInsecurePath) { + err = nil + } + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return err + } + it, ok := wanted[i] // i counts headers exactly as BuildIndex does + if !ok { + continue + } + delete(wanted, i) + if err := fn(it, tr); err != nil { + return err + } + } + return nil +} + +type errReader struct{ err error } + +func (r errReader) Read([]byte) (int, error) { return 0, r.err } + +// Unpack extracts members (nil = all) of the indexed archive into toDir on +// any FS through the transfer engine: conflicts are resolved by opts/hooks +// instead of silent overwrites, files are written via temp + rename, and an +// existing symlink in the target is never written through (U-P1-11). +func Unpack(ctx context.Context, fsys vfs.FS, archivePath string, idx *Index, members []string, + to vfs.FS, toDir string, opts transfer.Options, h transfer.Hooks) transfer.Report { + req := transfer.Request{Op: transfer.Copy, From: NewSource(fsys, archivePath, idx, members), To: to, ToDir: toDir, Opts: opts} + plan, err := transfer.Prepare(ctx, req, h.Progress) + if err != nil { + return transfer.Report{Err: err, Cancelled: ctx.Err() != nil} + } + return transfer.Execute(ctx, plan, h) +} diff --git a/internal/archive/unpack_test.go b/internal/archive/unpack_test.go new file mode 100644 index 0000000..affe55c --- /dev/null +++ b/internal/archive/unpack_test.go @@ -0,0 +1,123 @@ +package archive + +import ( + "context" + "os" + "path/filepath" + "testing" + + "vcom/internal/testutil/fstree" + "vcom/internal/transfer" +) + +// U-P1-11: an existing file is a conflict, not a silent overwrite. +func TestUnpackConflictAsks(t *testing.T) { + for _, name := range []string{"a.zip", "a.tar.gz"} { + arch := writeArchive(t, name, file("top/keep.txt", "from archive"), file("top/new.txt", "n")) + idx, err := IndexFile(bg, local, arch, nil) + if err != nil { + t.Fatal(err) + } + dst := t.TempDir() + fstree.Build(t, dst, fstree.Spec{fstree.File("top/keep.txt", "user data")}) + var asked []string + rep := Unpack(bg, local, arch, idx, nil, local, dst, transfer.DefaultOptions(), transfer.Hooks{ + Resolve: func(_ context.Context, c transfer.Conflict) (transfer.Resolution, error) { + asked = append(asked, c.Item.Rel) + return transfer.Resolution{Action: transfer.ResolveSkip}, nil + }, + }) + if len(asked) != 1 || asked[0] != "top/keep.txt" { + t.Fatalf("%s: asked %v", name, asked) + } + if rep.Done != 1 || rep.Skipped != 1 { + t.Fatalf("%s: %+v", name, rep) + } + if b, _ := os.ReadFile(filepath.Join(dst, "top", "keep.txt")); string(b) != "user data" { + t.Fatalf("%s: existing file overwritten", name) + } + // Overwrite replaces atomically. + rep = Unpack(bg, local, arch, idx, []string{"top/keep.txt"}, local, filepath.Join(dst, "top"), + transfer.Options{Conflict: transfer.Overwrite}, transfer.Hooks{}) + if b, _ := os.ReadFile(filepath.Join(dst, "top", "keep.txt")); rep.Done != 1 || string(b) != "from archive" { + t.Fatalf("%s: overwrite %+v %q", name, rep, b) + } + noTemps(t, filepath.Join(dst, "top")) + } +} + +func TestUnpackDoesNotWriteThroughSymlink(t *testing.T) { + elsewhere := t.TempDir() + arch := writeArchive(t, "a.tar", file("foo/x", "payload"), file("bar", "b")) + idx, err := IndexFile(bg, local, arch, nil) + if err != nil { + t.Fatal(err) + } + dst := t.TempDir() + if err := os.Symlink(elsewhere, filepath.Join(dst, "foo")); err != nil { + t.Fatal(err) + } + for _, pol := range []transfer.ConflictPolicy{transfer.Overwrite, transfer.Ask, transfer.Skip} { + rep := Unpack(bg, local, arch, idx, nil, local, dst, transfer.Options{Conflict: pol}, transfer.Hooks{ + Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) { + return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil + }, + }) + if rep.Err != nil { + t.Fatal(rep.Err) + } + if ents, _ := os.ReadDir(elsewhere); len(ents) != 0 { + t.Fatalf("policy %d: wrote through the symlink: %v", pol, ents) + } + if fi, err := os.Lstat(filepath.Join(dst, "foo")); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("the link itself was replaced") + } + } + // KeepBoth puts the directory beside the link. + rep := Unpack(bg, local, arch, idx, nil, local, dst, transfer.Options{Conflict: transfer.KeepBoth}, transfer.Hooks{}) + if b, _ := os.ReadFile(filepath.Join(dst, "foo (1)", "x")); rep.Err != nil || string(b) != "payload" { + t.Fatalf("keep both: %+v", rep) + } +} + +// N-P1-15: unpacking into a remote panel goes through the same engine. +func TestUnpackToRemote(t *testing.T) { + remote := remoteFS(t) + arch := writeArchive(t, "a.zip", file("top/a.txt", "alpha"), symlink("top/ln", "a.txt"), dir("top/empty/")) + idx, err := IndexFile(bg, local, arch, nil) + if err != nil { + t.Fatal(err) + } + dst := t.TempDir() + fstree.Build(t, dst, fstree.Spec{fstree.File("top/a.txt", "remote data")}) + asked := 0 + rep := Unpack(bg, local, arch, idx, nil, remote, dst, transfer.DefaultOptions(), transfer.Hooks{ + Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) { + asked++ + return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil + }, + }) + if rep.Err != nil || rep.Done != 2 || asked != 1 { + t.Fatalf("%+v asked=%d", rep, asked) + } + if b, _ := os.ReadFile(filepath.Join(dst, "top", "a.txt")); string(b) != "alpha" { + t.Fatalf("content %q", b) + } + if l, _ := os.Readlink(filepath.Join(dst, "top", "ln")); l != "a.txt" { + t.Fatalf("link %q", l) + } + noTemps(t, filepath.Join(dst, "top")) + + // And from a remote archive into a local directory. + arch2 := filepath.Join(dst, "copy.zip") + b, _ := os.ReadFile(arch) + _ = os.WriteFile(arch2, b, 0o644) + idx2, err := IndexFile(bg, remote, arch2, nil) + if err != nil { + t.Fatal(err) + } + dst2 := t.TempDir() + if rep := Unpack(bg, remote, arch2, idx2, nil, local, dst2, transfer.DefaultOptions(), transfer.Hooks{}); rep.Err != nil || rep.Done != 2 { + t.Fatalf("remote archive: %+v", rep) + } +} diff --git a/internal/atomicfile/atomicfile.go b/internal/atomicfile/atomicfile.go new file mode 100644 index 0000000..59432b8 --- /dev/null +++ b/internal/atomicfile/atomicfile.go @@ -0,0 +1,142 @@ +// Package atomicfile replaces local files atomically: temp file in the same +// directory → write → fsync → rename → fsync of the directory (design §9.2). +// A crash or error at any point leaves either the old file or the new one, +// never a truncated mix. Used for the config, the session, hosts.dat and +// known_hosts. +package atomicfile + +import ( + "bufio" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "syscall" + + "golang.org/x/sys/unix" +) + +// WriteFile atomically replaces path with data. See Write. +func WriteFile(path string, data []byte, perm fs.FileMode) error { + return Write(path, perm, func(w io.Writer) error { + _, err := w.Write(data) + return err + }) +} + +// Write atomically replaces path with what fill writes. If fill (or any later +// step) fails, the temp file is removed and path is untouched. +// +// - If path is a symlink (dotfiles!), the file it points to is replaced and +// the link is kept. +// - If path exists but is not writable by us (chmod a-w), Write fails with +// EACCES like a plain write would, instead of replacing it. +// - If path exists, its permission bits are kept (perm is used only for a +// new file) and, when running as root, its owner too — so sudo does not +// leave a root-owned file in a user's home. +func Write(path string, perm fs.FileMode, fill func(w io.Writer) error) (err error) { + target, err := resolve(path) + if err != nil { + return err + } + uid, gid := -1, -1 + if fi, err := os.Stat(target); err == nil { + if !fi.Mode().IsRegular() { + return fmt.Errorf("atomicfile: %s is not a regular file", target) + } + // A file the user made read-only stays untouched: the rename would + // replace it although open(O_WRONLY) is refused (QA-13). + if err := unix.Access(target, unix.W_OK); err != nil { + return &fs.PathError{Op: "open", Path: target, Err: err} + } + perm = fi.Mode().Perm() + if st, ok := fi.Sys().(*syscall.Stat_t); ok && os.Geteuid() == 0 { + uid, gid = int(st.Uid), int(st.Gid) + } + } else if !errors.Is(err, fs.ErrNotExist) { + return err + } + + dir := filepath.Dir(target) + tmp, err := os.CreateTemp(dir, "."+filepath.Base(target)+".tmp-*") + if err != nil { + return err + } + tmpName := tmp.Name() + defer func() { + if err != nil { + tmp.Close() + os.Remove(tmpName) + } + }() + + if err = tmp.Chmod(perm); err != nil { + return err + } + if uid >= 0 { + if err = tmp.Chown(uid, gid); err != nil { + return err + } + } + bw := bufio.NewWriter(tmp) + if err = fill(bw); err != nil { + return err + } + if err = bw.Flush(); err != nil { + return err + } + if err = tmp.Sync(); err != nil { + return err + } + if err = tmp.Close(); err != nil { + return err + } + if err = os.Rename(tmpName, target); err != nil { + return err + } + syncDir(dir) + return nil +} + +// resolve follows a symlink at path to the file it names (which may not exist +// yet: a dangling link is written through). +func resolve(path string) (string, error) { + path, err := filepath.Abs(path) + if err != nil { + return "", err + } + for range 40 { + fi, err := os.Lstat(path) + if errors.Is(err, fs.ErrNotExist) { + return path, nil + } + if err != nil { + return "", err + } + if fi.Mode()&fs.ModeSymlink == 0 { + return path, nil + } + link, err := os.Readlink(path) + if err != nil { + return "", err + } + if !filepath.IsAbs(link) { + link = filepath.Join(filepath.Dir(path), link) + } + path = link + } + return "", fmt.Errorf("atomicfile: %s: too many levels of symbolic links", path) +} + +// syncDir makes the rename durable. Some file systems refuse fsync on a +// directory; that is not worth failing the write for. +func syncDir(dir string) { + d, err := os.Open(dir) + if err != nil { + return + } + _ = d.Sync() + d.Close() +} diff --git a/internal/atomicfile/atomicfile_test.go b/internal/atomicfile/atomicfile_test.go new file mode 100644 index 0000000..fde3f7b --- /dev/null +++ b/internal/atomicfile/atomicfile_test.go @@ -0,0 +1,120 @@ +package atomicfile + +import ( + "errors" + "io" + "os" + "path/filepath" + "testing" +) + +func names(t *testing.T, dir string) []string { + t.Helper() + ents, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var out []string + for _, e := range ents { + out = append(out, e.Name()) + } + return out +} + +func TestAtomicWriteCrashLeavesOld(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "session.toml") + if err := os.WriteFile(p, []byte("old content"), 0o600); err != nil { + t.Fatal(err) + } + boom := errors.New("disk full") + err := Write(p, 0o644, func(w io.Writer) error { + _, _ = io.WriteString(w, "half of the new") + return boom + }) + if !errors.Is(err, boom) { + t.Fatalf("err = %v", err) + } + if b, _ := os.ReadFile(p); string(b) != "old content" { + t.Fatalf("old file damaged: %q", b) + } + if n := names(t, dir); len(n) != 1 { + t.Fatalf("temp file left behind: %v", n) + } +} + +func TestAtomicWriteReplacesAndKeepsMode(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "f") + if err := WriteFile(p, []byte("one"), 0o640); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o640 { + t.Fatalf("new file mode %v", fi.Mode().Perm()) + } + if err := os.Chmod(p, 0o600); err != nil { + t.Fatal(err) + } + if err := WriteFile(p, []byte("two"), 0o644); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p); string(b) != "two" { + t.Fatalf("content %q", b) + } + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 { + t.Fatalf("existing mode not kept: %v", fi.Mode().Perm()) + } + if n := names(t, dir); len(n) != 1 { + t.Fatalf("leftovers: %v", n) + } +} + +func TestAtomicWriteThroughSymlink(t *testing.T) { + dir := t.TempDir() + real := filepath.Join(dir, "dotfiles", "vcom.toml") + if err := os.MkdirAll(filepath.Dir(real), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(real, []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + link := filepath.Join(dir, "vcom.toml") + if err := os.Symlink("dotfiles/vcom.toml", link); err != nil { + t.Fatal(err) + } + if err := WriteFile(link, []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("symlink replaced by a regular file") + } + if b, _ := os.ReadFile(real); string(b) != "new" { + t.Fatalf("target content %q", b) + } +} + +func TestAtomicWriteRefusesDirectory(t *testing.T) { + if err := WriteFile(t.TempDir(), []byte("x"), 0o644); err == nil { + t.Fatal("writing over a directory must fail") + } +} + +func TestAtomicWriteRefusesReadOnlyFile(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root may write anything") + } + p := filepath.Join(t.TempDir(), "ro") + if err := os.WriteFile(p, []byte("keep"), 0o444); err != nil { + t.Fatal(err) + } + err := WriteFile(p, []byte("new"), 0o644) + if !errors.Is(err, os.ErrPermission) { + t.Fatalf("err = %v, want EACCES", err) + } + if b, _ := os.ReadFile(p); string(b) != "keep" { + t.Fatalf("read-only file replaced: %q", b) + } + if n := names(t, filepath.Dir(p)); len(n) != 1 { + t.Fatalf("leftovers %v", n) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 223cfd1..cbb3d8d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,16 +1,15 @@ +// Package config holds the vcom.toml schema, loading and the in-place +// SetKey edit (design §9.2). +// +// Loading never aborts the program: a broken file yields Default() plus an +// error for the status line; unknown or deprecated keys yield warnings; an +// invalid value is replaced by its default with a warning. package config import ( - "errors" "fmt" - "os" - "path/filepath" "strings" - "syscall" - - toml "github.com/pelletier/go-toml/v2" - - "vcom/internal/homedir" + "time" ) type Config struct { @@ -19,6 +18,8 @@ type Config struct { Browser BrowserConfig `toml:"browser"` Preview PreviewConfig `toml:"preview"` Behavior BehaviorConfig `toml:"behavior"` + Transfer TransferConfig `toml:"transfer"` + SSH SSHConfig `toml:"ssh"` } type StartupConfig struct { @@ -27,15 +28,18 @@ type StartupConfig struct { } type UIConfig struct { - AppTitle string `toml:"app_title"` - Theme string `toml:"theme"` - IconMode string `toml:"icon_mode"` - ShowTitleBar bool `toml:"show_title_bar"` - ShowFooter bool `toml:"show_footer"` - Border string `toml:"border"` - PathDisplay string `toml:"path_display"` - PaneGap int `toml:"pane_gap"` - CenterWidthPercent int `toml:"center_width_percent"` + // AppTitle is deprecated (warning when set); only the old UI still shows + // it. It goes away with the old UI in stage 7. + AppTitle string `toml:"app_title"` + Theme string `toml:"theme"` + IconMode string `toml:"icon_mode"` + ShowFooter bool `toml:"show_footer"` + Border string `toml:"border"` + PathDisplay string `toml:"path_display"` + PaneGap int `toml:"pane_gap"` + // PreviewWidthPercent is the preview width in the Info screen. The old + // name center_width_percent is accepted as an alias with a warning. + PreviewWidthPercent int `toml:"preview_width_percent"` } type BrowserConfig struct { @@ -65,211 +69,159 @@ type PreviewConfig struct { WrapText bool `toml:"wrap_text"` MaxPreviewBytes int64 `toml:"max_preview_bytes"` DirectoryPreviewLimit int `toml:"directory_preview_limit"` + // ImageBackend: auto | kitty | ueberzugpp | none. + ImageBackend string `toml:"image_backend"` + // MaxRemoteImageBytes: larger remote images are not downloaded for preview. + MaxRemoteImageBytes int64 `toml:"max_remote_image_bytes"` } type BehaviorConfig struct { - ConfirmDelete bool `toml:"confirm_delete"` + ConfirmDelete bool `toml:"confirm_delete"` // asks before moving to the trash ConfirmOverwrite bool `toml:"confirm_overwrite"` CalculateDirSizeOnSpace bool `toml:"calculate_dir_size_on_space"` - FollowSymlinks bool `toml:"follow_symlinks"` + FollowSymlinks bool `toml:"follow_symlinks"` // default of the transfer dialog + ConfirmQuit bool `toml:"confirm_quit"` +} + +type TransferConfig struct { + OnConflict string `toml:"on_conflict"` // ask | overwrite | skip | newer | rename + Preserve bool `toml:"preserve"` // keep mode and mtime + Fsync string `toml:"fsync"` // replace | always | never + MaxParallelJobs int `toml:"max_parallel_jobs"` +} + +type SSHConfig struct { + KeepaliveInterval Duration `toml:"keepalive_interval"` + ConnectTimeout Duration `toml:"connect_timeout"` +} + +// Duration is a time.Duration written as a Go duration string ("15s"). +type Duration struct{ time.Duration } + +func (d Duration) MarshalText() ([]byte, error) { return []byte(d.String()), nil } + +func (d *Duration) UnmarshalText(b []byte) error { + v, err := time.ParseDuration(string(b)) + if err != nil { + return err + } + d.Duration = v + return nil } func Default() Config { return Config{ - Startup: StartupConfig{}, UI: UIConfig{ - AppTitle: "vcom", - Theme: "catppuccin-mocha", - IconMode: "auto", - ShowTitleBar: true, - ShowFooter: true, - Border: "rounded", - PathDisplay: "short", - PaneGap: 1, - CenterWidthPercent: 30, + AppTitle: "vcom", + Theme: "catppuccin-mocha", + IconMode: "auto", + ShowFooter: true, + Border: "rounded", + PathDisplay: "short", + PaneGap: 1, + PreviewWidthPercent: 50, }, Browser: BrowserConfig{ ShowHidden: true, DirsFirst: true, HumanReadableSize: true, - Sort: SortConfig{ - By: "name", - Reverse: false, - }, - Columns: BrowserColumnsConfig{ - Name: true, - Size: true, - Modified: true, - }, + Sort: SortConfig{By: "name"}, + Columns: BrowserColumnsConfig{Name: true, Size: true, Modified: true}, }, Preview: PreviewConfig{ ShowMetadata: true, - WrapText: false, MaxPreviewBytes: 64 * 1024, DirectoryPreviewLimit: 80, + ImageBackend: "auto", + MaxRemoteImageBytes: 20 << 20, }, Behavior: BehaviorConfig{ ConfirmDelete: true, ConfirmOverwrite: true, CalculateDirSizeOnSpace: true, - FollowSymlinks: false, + ConfirmQuit: true, + }, + Transfer: TransferConfig{ + OnConflict: "ask", + Preserve: true, + Fsync: "replace", + MaxParallelJobs: 2, + }, + SSH: SSHConfig{ + KeepaliveInterval: Duration{15 * time.Second}, + ConnectTimeout: Duration{20 * time.Second}, }, } } -func Load(explicitPath string) (Config, string, error) { - cfg := Default() - - path, found, err := resolvePath(explicitPath) - if err != nil { - return Config{}, "", err +// Validate normalises c and replaces invalid values with their defaults. It +// returns one warning per replaced value; it never fails. +func (c *Config) Validate() []string { + d := Default() + var warns []string + reset := func(key string, got any, fix func()) { + warns = append(warns, fmt.Sprintf("%s: invalid value %v, using the default", key, got)) + fix() } - if !found { - return cfg, "", nil - } - - data, err := os.ReadFile(path) - if err != nil { - return Config{}, "", fmt.Errorf("read %s: %w", path, err) - } - if err := toml.Unmarshal(data, &cfg); err != nil { - return Config{}, "", fmt.Errorf("parse %s: %w", path, err) - } - - if err := cfg.Validate(); err != nil { - return Config{}, "", fmt.Errorf("validate %s: %w", path, err) - } - - return cfg, path, nil -} - -func Save(cfg Config, path string) (string, error) { - if err := cfg.Validate(); err != nil { - return "", err - } - - targetPath := strings.TrimSpace(path) - if targetPath == "" { - var err error - targetPath, err = DefaultUserPath() - if err != nil { - return "", err + oneOf := func(key string, v *string, def string, allowed ...string) { + s := strings.ToLower(strings.TrimSpace(*v)) + if s == "" { + *v = def + return } + for _, a := range allowed { + if s == a { + *v = s + return + } + } + reset(key, *v, func() { *v = def }) } - absPath, err := filepath.Abs(targetPath) - if err != nil { - return "", fmt.Errorf("resolve %s: %w", targetPath, err) - } - if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil { - return "", fmt.Errorf("mkdir %s: %w", filepath.Dir(absPath), err) - } - - data, err := toml.Marshal(cfg) - if err != nil { - return "", fmt.Errorf("marshal config: %w", err) - } - if err := os.WriteFile(absPath, data, 0o644); err != nil { - return "", fmt.Errorf("write %s: %w", absPath, err) - } - return absPath, nil -} - -func (c *Config) Validate() error { - if c.UI.Theme == "" { - return errors.New("ui.theme must not be empty") - } - switch strings.ToLower(strings.TrimSpace(c.UI.IconMode)) { - case "", "auto": - c.UI.IconMode = "auto" - case "nerd", "ascii": - default: - return errors.New("ui.icon_mode must be one of: auto, nerd, ascii") + if strings.TrimSpace(c.UI.Theme) == "" { + c.UI.Theme = d.UI.Theme } if strings.TrimSpace(c.UI.AppTitle) == "" { - c.UI.AppTitle = "vcom" - } - if c.Preview.MaxPreviewBytes <= 0 { - return errors.New("preview.max_preview_bytes must be > 0") - } - if c.Preview.DirectoryPreviewLimit <= 0 { - return errors.New("preview.directory_preview_limit must be > 0") - } - if !c.Browser.Columns.Name { - return errors.New("browser.columns.name must stay enabled") + c.UI.AppTitle = d.UI.AppTitle } + oneOf("ui.icon_mode", &c.UI.IconMode, "auto", "auto", "nerd", "ascii") if strings.TrimSpace(c.UI.PathDisplay) == "" { - c.UI.PathDisplay = "short" + c.UI.PathDisplay = d.UI.PathDisplay } if c.UI.PaneGap < 0 || c.UI.PaneGap > 4 { - return errors.New("ui.pane_gap must be between 0 and 4") + reset("ui.pane_gap", c.UI.PaneGap, func() { c.UI.PaneGap = d.UI.PaneGap }) } - if c.UI.CenterWidthPercent < 20 || c.UI.CenterWidthPercent > 60 { - return errors.New("ui.center_width_percent must be between 20 and 60") + if c.UI.PreviewWidthPercent < 20 || c.UI.PreviewWidthPercent > 80 { + reset("ui.preview_width_percent", c.UI.PreviewWidthPercent, func() { c.UI.PreviewWidthPercent = d.UI.PreviewWidthPercent }) } - switch strings.ToLower(strings.TrimSpace(c.Browser.Sort.By)) { - case "", "name": - c.Browser.Sort.By = "name" - case "modified", "size", "created", "extension": - default: - return fmt.Errorf("browser.sort.by must be one of: name, modified, size, created, extension") + oneOf("browser.sort.by", &c.Browser.Sort.By, "name", "name", "modified", "size", "created", "extension") + if !c.Browser.Columns.Name { + reset("browser.columns.name", false, func() { c.Browser.Columns.Name = true }) } - return nil -} - -func resolvePath(explicitPath string) (string, bool, error) { - var candidates []string - - if explicitPath != "" { - candidates = append(candidates, explicitPath) - } else { - homeDir := homedir.Dir() - if homeDir == "" { - return "", false, fmt.Errorf("cannot determine home directory") - } - xdgDir := os.Getenv("XDG_CONFIG_HOME") - if xdgDir == "" { - xdgDir = filepath.Join(homeDir, ".config") - } - - candidates = append(candidates, - "vcom.toml", - filepath.Join("config", "vcom.toml"), - filepath.Join(xdgDir, "vcom", "vcom.toml"), - filepath.Join(homeDir, ".config", "vcom", "vcom.toml"), - ) - } - - for _, candidate := range candidates { - if candidate == "" { - continue - } - absPath, err := filepath.Abs(candidate) - if err != nil { - return "", false, fmt.Errorf("resolve %s: %w", candidate, err) - } - if _, err := os.Stat(absPath); err == nil { - return absPath, true, nil - } else if !isMissingPathError(err) { - return "", false, fmt.Errorf("stat %s: %w", absPath, err) - } - } - - return "", false, nil -} - -func isMissingPathError(err error) bool { - return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) -} - -func DefaultUserPath() (string, error) { - homeDir := homedir.Dir() - if homeDir == "" { - return "", fmt.Errorf("cannot determine home directory") - } - xdgDir := os.Getenv("XDG_CONFIG_HOME") - if xdgDir == "" { - xdgDir = filepath.Join(homeDir, ".config") - } - return filepath.Join(xdgDir, "vcom", "vcom.toml"), nil + if c.Preview.MaxPreviewBytes <= 0 { + reset("preview.max_preview_bytes", c.Preview.MaxPreviewBytes, func() { c.Preview.MaxPreviewBytes = d.Preview.MaxPreviewBytes }) + } + if c.Preview.DirectoryPreviewLimit <= 0 { + reset("preview.directory_preview_limit", c.Preview.DirectoryPreviewLimit, func() { + c.Preview.DirectoryPreviewLimit = d.Preview.DirectoryPreviewLimit + }) + } + oneOf("preview.image_backend", &c.Preview.ImageBackend, "auto", "auto", "kitty", "ueberzugpp", "none") + if c.Preview.MaxRemoteImageBytes < 0 { + reset("preview.max_remote_image_bytes", c.Preview.MaxRemoteImageBytes, func() { + c.Preview.MaxRemoteImageBytes = d.Preview.MaxRemoteImageBytes + }) + } + oneOf("transfer.on_conflict", &c.Transfer.OnConflict, "ask", "ask", "overwrite", "skip", "newer", "rename") + oneOf("transfer.fsync", &c.Transfer.Fsync, "replace", "replace", "always", "never") + if c.Transfer.MaxParallelJobs < 1 || c.Transfer.MaxParallelJobs > 16 { + reset("transfer.max_parallel_jobs", c.Transfer.MaxParallelJobs, func() { c.Transfer.MaxParallelJobs = d.Transfer.MaxParallelJobs }) + } + if c.SSH.KeepaliveInterval.Duration < time.Second { + reset("ssh.keepalive_interval", c.SSH.KeepaliveInterval, func() { c.SSH.KeepaliveInterval = d.SSH.KeepaliveInterval }) + } + if c.SSH.ConnectTimeout.Duration < time.Second { + reset("ssh.connect_timeout", c.SSH.ConnectTimeout, func() { c.SSH.ConnectTimeout = d.SSH.ConnectTimeout }) + } + return warns } diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..8604b89 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,148 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestDefaultsValid(t *testing.T) { + c := Default() + if w := c.Validate(); len(w) != 0 { + t.Fatalf("defaults produce warnings: %v", w) + } + // New keys from design §9.2. + if !c.Behavior.ConfirmQuit || c.Transfer.OnConflict != "ask" || !c.Transfer.Preserve || + c.Transfer.Fsync != "replace" || c.Transfer.MaxParallelJobs != 2 || c.Preview.ImageBackend != "auto" || + c.Preview.MaxRemoteImageBytes != 20<<20 || c.SSH.KeepaliveInterval.Duration != 15*time.Second || + c.SSH.ConnectTimeout.Duration != 20*time.Second || c.UI.PreviewWidthPercent != 50 { + t.Fatalf("defaults: %+v", c) + } +} + +func TestReferenceConfigParsesClean(t *testing.T) { + data, err := os.ReadFile("../../vcom.toml") + if err != nil { + t.Fatal(err) + } + c, warns, err := Parse(data) + if err != nil { + t.Fatal(err) + } + if len(warns) != 0 { + t.Fatalf("reference vcom.toml produces warnings: %v", warns) + } + if c.UI.Theme != "github-dark" || c.SSH.ConnectTimeout.Duration != 20*time.Second { + t.Fatalf("parsed %+v", c) + } +} + +func TestLoadUnknownKeysWarns(t *testing.T) { + data := []byte(` +[ui] +theme = "nord" +show_title_bar = true +app_title = "x" +center_width_percent = 40 +mystery = 1 + +[behavior] +auto_refresh = true +auto_refresh_interval = 5 + +[nosuchsection] +k = "v" + +[ssh] +connect_timeout = "7s" +`) + c, warns, err := Parse(data) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(warns, "\n") + for _, want := range []string{ + "unknown key ui.mystery", + "unknown key nosuchsection", + "ui.show_title_bar", + "ui.app_title", + "ui.center_width_percent is renamed to ui.preview_width_percent", + "behavior.auto_refresh is not implemented", + "behavior.auto_refresh_interval", + } { + if !strings.Contains(joined, want) { + t.Errorf("missing warning %q in:\n%s", want, joined) + } + } + if c.UI.Theme != "nord" || c.SSH.ConnectTimeout.Duration != 7*time.Second { + t.Fatalf("known keys not applied: %+v", c) + } + if c.UI.PreviewWidthPercent != 40 { + t.Fatalf("alias center_width_percent not applied: %d", c.UI.PreviewWidthPercent) + } + // The new name wins over the alias. + c, _, _ = Parse([]byte("[ui]\ncenter_width_percent = 40\npreview_width_percent = 60\n")) + if c.UI.PreviewWidthPercent != 60 { + t.Fatalf("preview_width_percent = %d", c.UI.PreviewWidthPercent) + } +} + +func TestLoadInvalidValueUsesDefault(t *testing.T) { + c, warns, err := Parse([]byte("[ui]\npane_gap = 9\nicon_mode = 'weird'\n[transfer]\nfsync = 'sometimes'\n")) + if err != nil { + t.Fatal(err) + } + d := Default() + if c.UI.PaneGap != d.UI.PaneGap || c.UI.IconMode != "auto" || c.Transfer.Fsync != "replace" { + t.Fatalf("invalid values not reset: %+v", c) + } + if len(warns) != 3 { + t.Fatalf("warnings: %v", warns) + } +} + +func TestLoadBrokenConfigFallsBackToDefaults(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "vcom.toml") + if err := os.WriteFile(p, []byte("[ui]\ntheme = \"nord\"\nborder = \n"), 0o644); err != nil { + t.Fatal(err) + } + c, info, err := Load(p) + if err == nil { + t.Fatal("broken config must return an error") + } + if !strings.Contains(err.Error(), "line 3") { + t.Errorf("error should point at the line: %v", err) + } + if c != Default() { + t.Fatalf("got %+v, want defaults", c) + } + if !info.Found || info.Path != p { + t.Fatalf("info %+v", info) + } + // A missing explicit file: defaults, no error. + c, info, err = Load(filepath.Join(dir, "none.toml")) + if err != nil || info.Found || c != Default() { + t.Fatalf("missing file: %+v %+v %v", c, info, err) + } +} + +func TestLoadIgnoresCwdConfig(t *testing.T) { + cwd := t.TempDir() + if err := os.WriteFile(filepath.Join(cwd, "vcom.toml"), []byte("[ui]\ntheme = 'nord'\n"), 0o644); err != nil { + t.Fatal(err) + } + t.Chdir(cwd) + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("VCOM_CONFIG", "") + c, info, err := Load("") + if err != nil || info.Found || c.UI.Theme == "nord" { + t.Fatalf("cwd config was used: %+v %+v %v", c.UI, info, err) + } + if len(info.Warnings) != 1 || !strings.Contains(info.Warnings[0], "not loaded") { + t.Fatalf("expected a hint about ./vcom.toml, got %v", info.Warnings) + } +} diff --git a/internal/config/lookup.go b/internal/config/lookup.go new file mode 100644 index 0000000..3b8a1c2 --- /dev/null +++ b/internal/config/lookup.go @@ -0,0 +1,133 @@ +package config + +import ( + "bytes" + "errors" + "fmt" + "os" + "sort" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "vcom/internal/paths" +) + +// LoadInfo describes where the config came from. +type LoadInfo struct { + // Path is the file that was read, or — when Found is false — where + // SetKey would create one. + Path string + Found bool + // Warnings: unknown/deprecated keys, replaced invalid values, a stray + // ./vcom.toml that is no longer loaded. + Warnings []string +} + +// deprecated keys: accepted, ignored (or aliased), reported. +var deprecated = map[string]string{ + "ui.show_title_bar": "ui.show_title_bar is no longer used and is ignored", + "ui.center_width_percent": "ui.center_width_percent is renamed to ui.preview_width_percent", + "behavior.auto_refresh": "behavior.auto_refresh is not implemented and is ignored", + "behavior.auto_refresh_interval": "behavior.auto_refresh_interval is not implemented and is ignored", +} + +// Load reads the config found by paths.ConfigFile(explicit). It never fails +// hard: on a read or parse error it returns Default() and the error, and the +// caller starts anyway and shows the error. +func Load(explicit string) (Config, LoadInfo, error) { + cfg := Default() + path, found, err := paths.ConfigFile(explicit) + info := LoadInfo{Path: path, Found: found} + if err != nil { + return cfg, info, fmt.Errorf("config: %w", err) + } + if !found { + if stray, ok := paths.StrayCwdConfig(); ok { + info.Warnings = append(info.Warnings, fmt.Sprintf( + "%s is not loaded any more; move it to %s or pass -config", stray, path)) + } + return cfg, info, nil + } + data, err := os.ReadFile(path) + if err != nil { + return cfg, info, fmt.Errorf("config: %w", err) + } + c, warns, err := Parse(data) + info.Warnings = append(info.Warnings, warns...) + if err != nil { + return cfg, info, fmt.Errorf("config %s: %w (using defaults)", path, err) + } + return c, info, nil +} + +// Parse decodes a config file on top of Default(), applies aliases, reports +// unknown and deprecated keys and validates values. +func Parse(data []byte) (Config, []string, error) { + cfg := Default() + if err := toml.Unmarshal(data, &cfg); err != nil { + return Default(), nil, describe(err) + } + var raw map[string]any + _ = toml.Unmarshal(data, &raw) // cannot fail after the decode above + + var warns []string + present := func(key string) (any, bool) { + var cur any = raw + for _, part := range strings.Split(key, ".") { + m, ok := cur.(map[string]any) + if !ok { + return nil, false + } + if cur, ok = m[part]; !ok { + return nil, false + } + } + return cur, true + } + if v, ok := present("ui.center_width_percent"); ok { + if _, set := present("ui.preview_width_percent"); !set { + if n, ok := v.(int64); ok { + cfg.UI.PreviewWidthPercent = int(n) + } + } + } + if _, ok := present("ui.app_title"); ok { + warns = append(warns, "ui.app_title is deprecated and will be ignored by the new UI") + } + + // Strict pass: only for the list of unknown keys. + var strict Config + dec := toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields() + var sme *toml.StrictMissingError + if err := dec.Decode(&strict); errors.As(err, &sme) { + var unknown []string + for _, e := range sme.Errors { + key := strings.Join(e.Key(), ".") + if msg, ok := deprecated[key]; ok { + warns = append(warns, msg) + continue + } + unknown = append(unknown, key) + } + sort.Strings(unknown) + for _, k := range unknown { + warns = append(warns, fmt.Sprintf("unknown key %s (ignored)", k)) + } + } + warns = append(warns, cfg.Validate()...) + return cfg, warns, nil +} + +// describe adds the line/column go-toml knows to a decode error. +func describe(err error) error { + var de *toml.DecodeError + if errors.As(err, &de) { + row, col := de.Position() + return fmt.Errorf("line %d, column %d: %w", row, col, err) + } + return err +} + +// DefaultUserPath is where a new config file is created. +func DefaultUserPath() (string, error) { return paths.DefaultConfigFile() } diff --git a/internal/config/qa_rc2_test.go b/internal/config/qa_rc2_test.go new file mode 100644 index 0000000..2ed3171 --- /dev/null +++ b/internal/config/qa_rc2_test.go @@ -0,0 +1,189 @@ +package config + +// QA (v0.2.8 RC2): config loading and SetKey (stage 2C) from the user's +// side: symlinked/read-only/odd configs must never be lost or corrupted. + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func qaIsolate(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("VCOM_CONFIG", "") + return home +} + +func qaWrite(t *testing.T, p, s string, mode os.FileMode) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(s), mode); err != nil { + t.Fatal(err) + } + if err := os.Chmod(p, mode); err != nil { + t.Fatal(err) + } +} + +// Dotfiles: the config is a symlink into a dotfiles repo. The link stays, +// the target gets the new theme, comments survive. +func TestQASetKeyThroughSymlink(t *testing.T) { + home := qaIsolate(t) + target := filepath.Join(home, "dotfiles", "vcom.toml") + qaWrite(t, target, "# mine\n[ui]\ntheme = \"old\" # c\n", 0o640) + link := filepath.Join(home, ".config", "vcom", "vcom.toml") + if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("../../dotfiles/vcom.toml", link); err != nil { + t.Fatal(err) + } + cfg, info, err := Load("") + if err != nil || !info.Found || cfg.UI.Theme != "old" { + t.Fatalf("load via symlink: %v %+v theme=%q", err, info, cfg.UI.Theme) + } + if _, err := SetKey(info.Path, "ui", "theme", "new"); err != nil { + t.Fatal(err) + } + if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("symlink replaced by a regular file") + } + b, _ := os.ReadFile(target) + if string(b) != "# mine\n[ui]\ntheme = \"new\" # c\n" { + t.Fatalf("target content %q", b) + } + if fi, _ := os.Stat(target); fi.Mode().Perm() != 0o640 { + t.Fatalf("target mode changed to %o", fi.Mode().Perm()) + } +} + +// A user who made the config read-only (chmod a-w) expects vcom not to +// change it. v0.2.7 failed with EACCES; atomic rename now replaces it. +func TestQASetKeyReadOnlyConfig(t *testing.T) { + home := qaIsolate(t) + p := filepath.Join(home, ".config", "vcom", "vcom.toml") + qaWrite(t, p, "[ui]\ntheme = \"locked\"\n", 0o444) + if _, err := SetKey(p, "ui", "theme", "other"); err == nil { + b, _ := os.ReadFile(p) + t.Fatalf("read-only config was rewritten: %q", b) + } +} + +// Valid TOML forms of the same key: dotted key at the root and an inline +// table. SetKey must either edit them or fail without touching the file; +// failing means the theme silently stops being saved for these users. +func TestQASetKeyDottedAndInlineForms(t *testing.T) { + for name, content := range map[string]string{ + "dotted": "ui.theme = \"old\"\nui.icon_mode = \"ascii\"\n", + "inline": "ui = { theme = \"old\" }\n", + } { + t.Run(name, func(t *testing.T) { + home := qaIsolate(t) + p := filepath.Join(home, "vcom.toml") + qaWrite(t, p, content, 0o644) + if _, _, err := Parse([]byte(content)); err != nil { + t.Fatalf("fixture must be valid: %v", err) + } + if _, err := SetKey(p, "ui", "theme", "new"); err != nil { + t.Fatalf("SetKey on a valid %s config: %v", name, err) + } + b, _ := os.ReadFile(p) + c, _, err := Parse(b) + if err != nil || c.UI.Theme != "new" { + t.Fatalf("result %q: theme=%q err=%v", b, c.UI.Theme, err) + } + }) + } +} + +// Even when SetKey fails on such a file, it must stay byte-identical. +func TestQASetKeyFailureLeavesFileIntact(t *testing.T) { + for _, content := range []string{ + "ui.theme = \"old\"\n", + "ui = { theme = \"old\" }\n", + "[ui]\ntheme = \"\"\"multi\nline\"\"\"\n", + "[ui\ntheme = 1\n", // broken + } { + home := qaIsolate(t) + p := filepath.Join(home, "vcom.toml") + qaWrite(t, p, content, 0o600) + _, _ = SetKey(p, "ui", "theme", "new") + b, _ := os.ReadFile(p) + c, _, perr := Parse(b) + if string(b) != content && (perr != nil || c.UI.Theme != "new") { + t.Fatalf("file damaged: before %q after %q", content, b) + } + if left, _ := filepath.Glob(filepath.Join(home, ".vcom.toml.tmp-*")); len(left) != 0 { + t.Fatalf("temp files left: %v", left) + } + } +} + +// UTF-8 BOM and CRLF (configs edited on Windows / by some editors). +func TestQASetKeyBOM(t *testing.T) { + home := qaIsolate(t) + p := filepath.Join(home, "vcom.toml") + content := "\ufeff[ui]\r\ntheme = \"old\"\r\n" + qaWrite(t, p, content, 0o644) + if _, _, err := Parse([]byte(content)); err != nil { + t.Skipf("go-toml does not accept a BOM: %v", err) + } + _, err := SetKey(p, "ui", "theme", "new") + b, _ := os.ReadFile(p) + if err != nil { + if string(b) != content { + t.Fatalf("failed SetKey changed the file: %q", b) + } + t.Logf("SetKey refuses a BOM config: %v", err) + return + } + if c, _, err := Parse(b); err != nil || c.UI.Theme != "new" || strings.Count(string(b), "[ui]") != 1 { + t.Fatalf("BOM config result %q (err %v)", b, err) + } +} + +// Load: a directory or an unreadable file in place of the config gives +// defaults plus an error, never a crash. +func TestQALoadDirAndUnreadable(t *testing.T) { + home := qaIsolate(t) + p := filepath.Join(home, ".config", "vcom", "vcom.toml") + if err := os.MkdirAll(p, 0o755); err != nil { + t.Fatal(err) + } + cfg, _, err := Load("") + if err == nil { + t.Fatal("directory as config must report an error") + } + if cfg.UI.Theme != Default().UI.Theme { + t.Fatal("defaults not used") + } + os.Remove(p) + qaWrite(t, p, "[ui]\ntheme = \"x\"\n", 0o000) + if os.Geteuid() == 0 { + t.Skip("root reads 0000 files") + } + if _, _, err := Load(""); err == nil { + t.Fatal("unreadable config must report an error") + } +} + +// -config / $VCOM_CONFIG pointing to a missing file: Load reports where it +// would be created (info.Path = that file). +func TestQALoadExplicitMissing(t *testing.T) { + home := qaIsolate(t) + want := filepath.Join(home, "custom", "vcom.toml") + t.Setenv("VCOM_CONFIG", want) + _, info, err := Load("") + if err != nil || info.Found || info.Path != want { + t.Fatalf("info=%+v err=%v", info, err) + } +} diff --git a/internal/config/session.go b/internal/config/session.go index 1799344..1aaa23b 100644 --- a/internal/config/session.go +++ b/internal/config/session.go @@ -1,86 +1,19 @@ package config -import ( - "fmt" - "os" - "path/filepath" +import "vcom/internal/state" - toml "github.com/pelletier/go-toml/v2" - - "vcom/internal/homedir" +// Session types and functions are thin aliases over internal/state, kept so +// the old UI compiles unchanged until stage 7. +type ( + SessionState = state.Session + PaneSession = state.PaneSession ) -// SessionState stores the UI state that should be restored on next launch. -type SessionState struct { - ActivePane string `toml:"active_pane"` - Left PaneSession `toml:"left"` - Right PaneSession `toml:"right"` -} +// DefaultSessionPath returns the session file ($XDG_STATE_HOME/vcom/session.toml). +func DefaultSessionPath() (string, error) { return state.File() } -// PaneSession stores per-pane session state (path and selected entry name). -type PaneSession struct { - Path string `toml:"path"` - EntryName string `toml:"entry_name"` - CursorMemory map[string]string `toml:"cursor_memory"` -} +// LoadSession reads the session (migrating it from the old location once). +func LoadSession() (SessionState, error) { return state.Load() } -// DefaultSessionPath returns the path to the session file. -func DefaultSessionPath() (string, error) { - homeDir := homedir.Dir() - if homeDir == "" { - return "", fmt.Errorf("cannot determine home directory") - } - xdgDir := os.Getenv("XDG_CONFIG_HOME") - if xdgDir == "" { - xdgDir = filepath.Join(homeDir, ".config") - } - return filepath.Join(xdgDir, "vcom", "session.toml"), nil -} - -// LoadSession reads the session state from disk. -// Returns (SessionState, nil) on success, (empty, error) if file doesn't exist. -func LoadSession() (SessionState, error) { - path, err := DefaultSessionPath() - if err != nil { - return SessionState{}, err - } - - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { - return SessionState{}, nil - } - return SessionState{}, fmt.Errorf("read %s: %w", path, err) - } - - var s SessionState - if err := toml.Unmarshal(data, &s); err != nil { - return SessionState{}, fmt.Errorf("parse %s: %w", path, err) - } - return s, nil -} - -// SaveSession writes the session state to disk. -func SaveSession(s SessionState) error { - path, err := DefaultSessionPath() - if err != nil { - return err - } - - absPath, err := filepath.Abs(path) - if err != nil { - return fmt.Errorf("resolve %s: %w", path, err) - } - if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil { - return fmt.Errorf("mkdir %s: %w", filepath.Dir(absPath), err) - } - - data, err := toml.Marshal(s) - if err != nil { - return fmt.Errorf("marshal session: %w", err) - } - if err := os.WriteFile(absPath, data, 0o644); err != nil { - return fmt.Errorf("write %s: %w", path, err) - } - return nil -} +// SaveSession writes the session atomically. +func SaveSession(s SessionState) error { return state.Save(s) } diff --git a/internal/config/setkey.go b/internal/config/setkey.go new file mode 100644 index 0000000..6719377 --- /dev/null +++ b/internal/config/setkey.go @@ -0,0 +1,358 @@ +package config + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "vcom/internal/atomicfile" +) + +// SetKey sets section.key = value in the config file at path by editing that +// one line: comments, order, formatting and unknown keys are kept (design +// §9.2). A missing key is appended to its section, a missing section to the +// end of the file, a missing file is created (path "" means the default XDG +// location). The file must parse before the edit — a broken config is never +// touched — and the result is parsed again before it is written atomically. +// +// value is a string, bool, integer or float. section may be dotted +// ("browser.sort"). +func SetKey(path, section, key string, value any) (string, error) { + if path == "" { + var err error + if path, err = DefaultUserPath(); err != nil { + return "", err + } + } + lit, err := tomlValue(value) + if err != nil { + return "", err + } + data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + out := []byte("[" + section + "]\n" + key + " = " + lit + "\n") + if err := verify(out, section, key, value); err != nil { + return "", err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return "", err + } + return path, atomicfile.WriteFile(path, out, 0o644) + } + if err != nil { + return "", err + } + var probe map[string]any + if err := toml.Unmarshal(data, &probe); err != nil { + return "", fmt.Errorf("%s does not parse, not editing it: %w", path, describe(err)) + } + out, err := editTOML(data, section, key, lit) + if err != nil { + return "", fmt.Errorf("edit %s: %w", path, err) + } + if err := verify(out, section, key, value); err != nil { + return "", fmt.Errorf("edit %s: %w", path, err) + } + return path, atomicfile.WriteFile(path, out, 0o644) +} + +var ( + reHeader = regexp.MustCompile(`^\s*\[\s*([^\[\]]+?)\s*\]\s*(#.*)?$`) + reArray = regexp.MustCompile(`^\s*\[\[`) +) + +// normSection canonicalises a table name: `a . "b"` → `a.b`. +func normSection(s string) string { + parts := strings.Split(s, ".") + for i, p := range parts { + p = strings.TrimSpace(p) + if len(p) >= 2 && (p[0] == '"' && p[len(p)-1] == '"' || p[0] == '\'' && p[len(p)-1] == '\'') { + p = p[1 : len(p)-1] + } + parts[i] = p + } + return strings.Join(parts, ".") +} + +// editTOML returns data with section.key set to the TOML literal lit. +func editTOML(data []byte, section, key, lit string) ([]byte, error) { + text := string(data) + nl := "\n" + if strings.Contains(text, "\r\n") { + nl = "\r\n" + } + lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") + section = normSection(section) + reKey := regexp.MustCompile(`^(\s*(?:` + regexp.QuoteMeta(key) + `|"` + regexp.QuoteMeta(key) + `"|'` + + regexp.QuoteMeta(key) + `')\s*=\s*)(.*)$`) + + if out, ok, err := editRootForms(lines, section, key, lit); err != nil || ok { + if err != nil { + return nil, err + } + return []byte(strings.Join(out, nl)), nil + } + + cur := "" // the root table + inTarget := section == "" + lastContent := -1 // last key/value line of the target section + headerAt := -1 + for i, line := range lines { + if reArray.MatchString(line) { + cur, inTarget = "\x00array", false + continue + } + if m := reHeader.FindStringSubmatch(line); m != nil { + cur = normSection(m[1]) + inTarget = cur == section + if inTarget { + headerAt = i + } + continue + } + if !inTarget { + continue + } + if m := reKey.FindStringSubmatch(line); m != nil { + val, rest, err := splitValue(m[2]) + if err != nil { + return nil, fmt.Errorf("%s.%s: %w", section, key, err) + } + lines[i] = m[1] + styleLike(val, lit) + rest + return []byte(strings.Join(lines, nl)), nil + } + if t := strings.TrimSpace(line); t != "" && !strings.HasPrefix(t, "#") { + lastContent = i + } + } + newLine := key + " = " + lit + switch { + case headerAt >= 0 || section == "": + at := lastContent + if at < 0 { + at = headerAt // empty section (or root): right after the header + } + lines = append(lines[:at+1], append([]string{newLine}, lines[at+1:]...)...) + default: + for len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + if len(lines) > 0 { + lines = append(lines, "") + } + lines = append(lines, "["+section+"]", newLine, "") + } + return []byte(strings.Join(lines, nl)), nil +} + +// styleLike keeps the file's literal-string style ('...') when possible. +func styleLike(old, lit string) string { + if strings.HasPrefix(old, "'") && !strings.ContainsAny(lit, `'\`) && strings.HasPrefix(lit, `"`) { + if s, err := strconv.Unquote(lit); err == nil && !strings.ContainsAny(s, "'\n") { + return "'" + s + "'" + } + } + return lit +} + +// namePattern matches a TOML key path (bare or quoted parts, spaces around +// dots allowed). +func namePattern(dotted string) string { + var parts []string + for _, p := range strings.Split(dotted, ".") { + q := regexp.QuoteMeta(p) + parts = append(parts, `(?:`+q+`|"`+q+`"|'`+q+`')`) + } + return strings.Join(parts, `\s*\.\s*`) +} + +// editRootForms handles a section written without a [table] header, in the +// root table: dotted keys (`ui.theme = "x"`) or an inline table +// (`ui = { theme = "x" }`) — QA-14. ok reports whether it edited. +func editRootForms(lines []string, section, key, lit string) (out []string, ok bool, err error) { + if section == "" { + return nil, false, nil + } + sec, k := namePattern(section), namePattern(key) + reDotted := regexp.MustCompile(`^(\s*` + sec + `\s*\.\s*` + k + `\s*=\s*)(.*)$`) + reInline := regexp.MustCompile(`^(\s*` + sec + `\s*=\s*\{)(.*)\}(\s*(?:#.*)?)$`) + reInlineOpen := regexp.MustCompile(`^\s*` + sec + `\s*=\s*\{`) + rePrefix := regexp.MustCompile(`^\s*` + sec + `\s*\.`) + lastDotted := -1 + for i, line := range lines { + if reHeader.MatchString(line) || reArray.MatchString(line) { + break // end of the root table + } + if m := reDotted.FindStringSubmatch(line); m != nil { + val, rest, err := splitValue(m[2]) + if err != nil { + return nil, false, fmt.Errorf("%s.%s: %w", section, key, err) + } + lines[i] = m[1] + styleLike(val, lit) + rest + return lines, true, nil + } + if m := reInline.FindStringSubmatch(line); m != nil { + inner, err := setInline(m[2], key, lit) + if err != nil { + return nil, false, fmt.Errorf("%s: %w", section, err) + } + lines[i] = m[1] + inner + "}" + m[3] + return lines, true, nil + } + if reInlineOpen.MatchString(line) { + return nil, false, fmt.Errorf("%s: multi-line inline tables are not supported", section) + } + if rePrefix.MatchString(line) { + lastDotted = i + } + } + if lastDotted >= 0 { // the section exists only as dotted keys: add one more + nl := section + "." + key + " = " + lit + return append(lines[:lastDotted+1], append([]string{nl}, lines[lastDotted+1:]...)...), true, nil + } + return nil, false, nil +} + +// setInline sets key in the body of a one-line inline table. +func setInline(inner, key, lit string) (string, error) { + re := regexp.MustCompile(`(^|,)(\s*` + namePattern(key) + `\s*=\s*)`) + loc := re.FindStringSubmatchIndex(inner) + if loc == nil { + t := strings.TrimRight(inner, " \t") + if strings.TrimSpace(t) == "" { + return " " + key + " = " + lit + " ", nil + } + return t + ", " + key + " = " + lit + " ", nil + } + start := loc[1] + rest := inner[start:] + var end int + switch { + case strings.HasPrefix(rest, `"`) || strings.HasPrefix(rest, `'`): + val, _, err := splitValue(rest) + if err != nil { + return "", err + } + end = len(val) + case strings.HasPrefix(rest, "[") || strings.HasPrefix(rest, "{"): + return "", errors.New("nested values in inline tables are not supported") + default: + end = strings.IndexByte(rest, ',') + if end < 0 { + end = len(rest) + } + end = len(strings.TrimRight(rest[:end], " \t")) + } + return inner[:start] + styleLike(rest[:end], lit) + rest[end:], nil +} + +// splitValue splits "value # comment" into the value token and the rest +// (whitespace and comment), respecting quoted strings. +func splitValue(s string) (val, rest string, err error) { + if strings.HasPrefix(s, `"""`) || strings.HasPrefix(s, `'''`) { + return "", "", errors.New("multi-line string values are not supported") + } + end := len(s) + switch { + case strings.HasPrefix(s, `"`): + end = -1 + for i := 1; i < len(s); i++ { + if s[i] == '\\' { + i++ + continue + } + if s[i] == '"' { + end = i + 1 + break + } + } + case strings.HasPrefix(s, `'`): + end = -1 + if j := strings.IndexByte(s[1:], '\''); j >= 0 { + end = j + 2 + } + case strings.HasPrefix(s, "[") || strings.HasPrefix(s, "{"): + return "", "", errors.New("array and inline-table values are not supported") + default: + if j := strings.IndexByte(s, '#'); j >= 0 { + end = j + } + end = len(strings.TrimRight(s[:end], " \t")) + } + if end < 0 { + return "", "", errors.New("unterminated string") + } + return s[:end], s[end:], nil +} + +// tomlValue renders value as a TOML literal. +func tomlValue(v any) (string, error) { + switch x := v.(type) { + case string: + var b strings.Builder + b.WriteByte('"') + for _, r := range x { + switch { + case r == '"': + b.WriteString(`\"`) + case r == '\\': + b.WriteString(`\\`) + case r == '\n': + b.WriteString(`\n`) + case r == '\t': + b.WriteString(`\t`) + case r < 0x20 || r == 0x7f: + fmt.Fprintf(&b, `\u%04X`, r) + default: + b.WriteRune(r) + } + } + b.WriteByte('"') + return b.String(), nil + case bool: + return strconv.FormatBool(x), nil + case int: + return strconv.Itoa(x), nil + case int64: + return strconv.FormatInt(x, 10), nil + case float64: + return strconv.FormatFloat(x, 'g', -1, 64), nil + } + return "", fmt.Errorf("config: unsupported value type %T", v) +} + +// verify parses out and checks that section.key now holds value. +func verify(out []byte, section, key string, value any) error { + var m map[string]any + if err := toml.Unmarshal(out, &m); err != nil { + return fmt.Errorf("result does not parse: %w", err) + } + var cur any = m + path := append(strings.Split(normSection(section), "."), key) + if section == "" { + path = []string{key} + } + for _, p := range path { + mm, ok := cur.(map[string]any) + if !ok { + return fmt.Errorf("result: %s.%s not found", section, key) + } + cur = mm[p] + } + want := value + if n, ok := value.(int); ok { + want = int64(n) + } + if !reflect.DeepEqual(cur, want) { + return fmt.Errorf("result: %s.%s = %v, want %v", section, key, cur, value) + } + return nil +} diff --git a/internal/config/setkey_test.go b/internal/config/setkey_test.go new file mode 100644 index 0000000..9c599ae --- /dev/null +++ b/internal/config/setkey_test.go @@ -0,0 +1,178 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func writeFile(t *testing.T, p, s string) { + t.Helper() + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// diffLines returns the indexes of lines that differ (files of equal length). +func diffLines(t *testing.T, a, b string) []int { + t.Helper() + la, lb := strings.Split(a, "\n"), strings.Split(b, "\n") + if len(la) != len(lb) { + t.Fatalf("line count changed: %d -> %d\n%s", len(la), len(lb), b) + } + var d []int + for i := range la { + if la[i] != lb[i] { + d = append(d, i) + } + } + return d +} + +func TestSetKeyPreservesComments(t *testing.T) { + orig, err := os.ReadFile("../../vcom.toml") + if err != nil { + t.Fatal(err) + } + // Plus an unknown key and an extra comment the user added. + before := string(orig) + "\n# my own note\n[extra]\nmine = 1 # keep\n" + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, before) + + if _, err := SetKey(p, "ui", "theme", "nord"); err != nil { + t.Fatal(err) + } + after := readFile(t, p) + d := diffLines(t, before, after) + if len(d) != 1 { + t.Fatalf("changed lines %v, want only the theme line:\n%s", d, after) + } + line := strings.Split(after, "\n")[d[0]] + if !strings.HasPrefix(line, "theme = 'nord'") { + t.Fatalf("theme line = %q (style of the original literal string expected)", line) + } + c, _, err := Parse([]byte(after)) + if err != nil || c.UI.Theme != "nord" { + t.Fatalf("result: %v %+v", err, c.UI) + } + + // A value with a trailing comment keeps the comment; a nested section works. + if _, err := SetKey(p, "browser.sort", "by", "size"); err != nil { + t.Fatal(err) + } + if !strings.Contains(readFile(t, p), "by = 'size' # name | modified") { + t.Fatalf("trailing comment lost:\n%s", readFile(t, p)) + } + if _, err := SetKey(p, "ui", "pane_gap", 2); err != nil { + t.Fatal(err) + } + if !strings.Contains(readFile(t, p), "pane_gap = 2 # 0..4") { + t.Fatalf("int edit:\n%s", readFile(t, p)) + } +} + +func TestSetKeyMissingSection(t *testing.T) { + p := filepath.Join(t.TempDir(), "vcom.toml") + before := "# top comment\n[browser]\nshow_hidden = false # mine\n" + writeFile(t, p, before) + if _, err := SetKey(p, "ui", "theme", "nord"); err != nil { + t.Fatal(err) + } + after := readFile(t, p) + if !strings.HasPrefix(after, before) { + t.Fatalf("existing content changed:\n%s", after) + } + if !strings.HasSuffix(after, "\n[ui]\ntheme = \"nord\"\n") { + t.Fatalf("section not appended:\n%q", after) + } + + // Missing key in an existing section: inserted after its last key. + writeFile(t, p, "[ui]\nborder = 'thin' # b\n\n# about browser\n[browser]\nshow_hidden = true\n") + if _, err := SetKey(p, "ui", "theme", "nord"); err != nil { + t.Fatal(err) + } + want := "[ui]\nborder = 'thin' # b\ntheme = \"nord\"\n\n# about browser\n[browser]\nshow_hidden = true\n" + if got := readFile(t, p); got != want { + t.Fatalf("got:\n%s\nwant:\n%s", got, want) + } +} + +func TestSetKeyNoFile(t *testing.T) { + xdg := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", xdg) + t.Setenv("VCOM_CONFIG", "") + path, err := SetKey("", "ui", "theme", "nord") + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(xdg, "vcom", "vcom.toml"); path != want { + t.Fatalf("created %s, want %s", path, want) + } + if got := readFile(t, path); got != "[ui]\ntheme = \"nord\"\n" { + t.Fatalf("content %q", got) + } +} + +func TestSetKeyRefusesBrokenFile(t *testing.T) { + p := filepath.Join(t.TempDir(), "vcom.toml") + broken := "[ui]\ntheme = \"nord\nborder = 'x'\n" + writeFile(t, p, broken) + if _, err := SetKey(p, "ui", "theme", "dracula"); err == nil { + t.Fatal("SetKey edited a file that does not parse") + } + if readFile(t, p) != broken { + t.Fatal("broken file was modified") + } + // Unsupported shapes are refused, not mangled. + writeFile(t, p, "[ui]\ntheme = \"\"\"\nnord\"\"\"\n") + if _, err := SetKey(p, "ui", "theme", "x"); err == nil { + t.Fatal("multi-line string must be refused") + } +} + +func TestSetKeyQuotingAndCRLF(t *testing.T) { + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, "[ui]\r\ntheme = \"a#b\" # c\r\n") + if _, err := SetKey(p, "ui", "theme", `it's "q"`); err != nil { + t.Fatal(err) + } + if got := readFile(t, p); got != "[ui]\r\ntheme = \"it's \\\"q\\\"\" # c\r\n" { + t.Fatalf("got %q", got) + } +} + +func TestSetKeyRootForms(t *testing.T) { + cases := map[string]struct{ in, want string }{ + "dotted": {"ui.theme = 'old' # c\nui.icon_mode = \"ascii\"\n", "ui.theme = 'new' # c\nui.icon_mode = \"ascii\"\n"}, + "dotted missing": {"ui.icon_mode = \"ascii\"\n[browser]\nshow_hidden = true\n", "ui.icon_mode = \"ascii\"\nui.theme = \"new\"\n[browser]\nshow_hidden = true\n"}, + "inline": {"ui = { theme = \"old\", border = 'x' }\n", "ui = { theme = \"new\", border = 'x' }\n"}, + "inline missing": {"ui = { border = 'x' }\n", "ui = { border = 'x', theme = \"new\" }\n"}, + "inline empty": {"ui = {}\n", "ui = { theme = \"new\" }\n"}, + } + for name, c := range cases { + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, c.in) + if _, err := SetKey(p, "ui", "theme", "new"); err != nil { + t.Fatalf("%s: %v", name, err) + } + if got := readFile(t, p); got != c.want { + t.Errorf("%s:\n got %q\nwant %q", name, got, c.want) + } + } + // A multi-line inline table is refused, file untouched. + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, "ui = {\n}\n") + if _, err := SetKey(p, "ui", "theme", "new"); err == nil { + t.Fatal("multi-line inline accepted") + } +} diff --git a/internal/fs/archive.go b/internal/fs/archive.go index b90843e..9f45744 100644 --- a/internal/fs/archive.go +++ b/internal/fs/archive.go @@ -9,6 +9,7 @@ import ( "io" "os" "path/filepath" + "strconv" "strings" "time" ) @@ -315,22 +316,103 @@ func ArchiveName(sources []string, format string) string { // CreateArchive creates an archive from source paths using the given format. // Supported formats: "zip", "tar", "tar.gz" (or "targz", "tgz"). // Progress is reported via the callback function. +// +// The archive is written to a temporary file next to archivePath and renamed +// over it only on success, so a failed or cancelled run leaves neither a +// partial archive nor a damaged previous one. An archivePath that is one of +// the sources or lies inside one is refused (U-P0-1). func CreateArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error { if ctx == nil { ctx = context.Background() } + if err := CheckArchiveTarget(sources, archivePath); err != nil { + return err + } + var create func(context.Context, []string, string, func(CopyProgress)) error lower := strings.ToLower(archivePath) switch { case strings.HasSuffix(lower, ".zip"): - return createZipArchive(ctx, sources, archivePath, progress) + create = createZipArchive case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"): - return createTarGzArchive(ctx, sources, archivePath, progress) + create = createTarGzArchive case strings.HasSuffix(lower, ".tar"): - return createTarArchive(ctx, sources, archivePath, progress) + create = createTarArchive default: return fmt.Errorf("unsupported archive format: %s", filepath.Ext(archivePath)) } + + // Short temp name: a long but valid archive name plus a prefix would + // exceed NAME_MAX (QA-7). CreateTemp makes it 0600 while it is written. + tmp, err := os.CreateTemp(filepath.Dir(archivePath), ".vcom-tmp-*") + if err != nil { + return fmt.Errorf("create %s: %w", archivePath, err) + } + tmpPath := tmp.Name() + tmp.Close() + if err := create(ctx, sources, tmpPath, progress); err != nil { + os.Remove(tmpPath) + return err + } + // A replaced archive keeps its permissions (a private 0600 archive must + // not become world-readable, QA-6); a new one gets 0666 minus umask, + // as os.Create would. + mode := 0o666 &^ processUmask() + if st, err := os.Stat(archivePath); err == nil { + mode = st.Mode().Perm() + } + if err := os.Chmod(tmpPath, mode); err != nil { + os.Remove(tmpPath) + return err + } + if err := os.Rename(tmpPath, archivePath); err != nil { + os.Remove(tmpPath) + return fmt.Errorf("rename %s: %w", archivePath, err) + } + return nil +} + +// CheckArchiveTarget returns an error if writing archivePath would overwrite +// one of sources or place the archive inside a source directory (where it +// would be truncated before being read, or include itself). Symlinked +// parent directories are resolved. +func CheckArchiveTarget(sources []string, archivePath string) error { + target := []string{archivePath} + if r, ok := resolveParent(archivePath); ok { + target = append(target, r) + } + for _, src := range sources { + candidates := []string{src} + if r, ok := resolveParent(src); ok { + candidates = append(candidates, r) + } + for _, t := range target { + for _, c := range candidates { + within, err := pathWithin(t, c) + if err != nil { + return err + } + if within { + return fmt.Errorf("archive %s would overwrite or be inside its source %s", filepath.Base(archivePath), src) + } + } + } + } + return nil +} + +// resolveParent resolves symlinks in p's parent directory (p itself may not +// exist yet and is not followed). +func resolveParent(p string) (string, bool) { + abs, err := filepath.Abs(p) + if err != nil { + return "", false + } + dir, err := filepath.EvalSymlinks(filepath.Dir(abs)) + if err != nil { + return "", false + } + return filepath.Join(dir, filepath.Base(abs)), true } func createZipArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error { @@ -654,3 +736,19 @@ func commonBaseDir(paths []string) string { } return base } + +// processUmask reads the umask without changing it (syscall.Umask would +// briefly change it for the whole process). Falls back to 022. +func processUmask() os.FileMode { + data, err := os.ReadFile("/proc/self/status") + if err == nil { + for _, line := range strings.Split(string(data), "\n") { + if v, ok := strings.CutPrefix(line, "Umask:"); ok { + if n, err := strconv.ParseUint(strings.TrimSpace(v), 8, 32); err == nil { + return os.FileMode(n) & 0o777 + } + } + } + } + return 0o022 +} diff --git a/internal/fs/ops.go b/internal/fs/ops.go index 789d6c1..c0417e8 100644 --- a/internal/fs/ops.go +++ b/internal/fs/ops.go @@ -12,7 +12,7 @@ import ( "syscall" "time" - "vcom/internal/homedir" + "vcom/internal/vfs/localfs" ) type TransferStats struct { @@ -94,10 +94,10 @@ func CopyPathWithProgressContext(ctx context.Context, srcPath string, dstDir str progress = func(CopyProgress) {} } tracker := copyProgressState{ - ctx: ctx, - stats: stats, + ctx: ctx, + stats: stats, callback: progress, - stage: "Scanning files...", + stage: "Scanning files...", discover: stats.FilesTotal == 0, } tracker.emit(srcPath, true) @@ -272,68 +272,22 @@ func DeletePath(path string) error { return os.RemoveAll(path) } -// MoveToTrash moves a file or directory to the FreeDesktop Trash directory -// (~/.local/share/Trash). Follows the FreeDesktop Trash specification: -// - The original item is moved to Trash/files/ -// - A .trashinfo file is written to Trash/info/.trashinfo -// - If already exists in Trash/files, a numeric suffix is appended. +// MoveToTrash moves a file or directory to the freedesktop.org trash. It +// delegates to the new local vfs (internal/vfs/localfs): topdir trash on other +// volumes instead of EXDEV, URL-encoded Path=, O_EXCL info files and the +// effective user's trash under sudo (N-P2-12). func MoveToTrash(path string) error { - home := homedir.Dir() - if home == "" { - return fmt.Errorf("cannot determine home directory") - } - - trashDir := filepath.Join(home, ".local", "share", "Trash") - filesDir := filepath.Join(trashDir, "files") - infoDir := filepath.Join(trashDir, "info") - - if err := os.MkdirAll(filesDir, 0o700); err != nil { - return fmt.Errorf("cannot create trash files directory: %w", err) - } - if err := os.MkdirAll(infoDir, 0o700); err != nil { - return fmt.Errorf("cannot create trash info directory: %w", err) - } - - baseName := filepath.Base(path) - - // Generate a unique name in the trash directory - destName := baseName - for counter := 1; ; counter++ { - destPath := filepath.Join(filesDir, destName) - if _, err := os.Stat(destPath); os.IsNotExist(err) { - break - } else if err != nil { - return fmt.Errorf("cannot stat trash path: %w", err) - } - destName = fmt.Sprintf("%s.%d", baseName, counter) - } - - destPath := filepath.Join(filesDir, destName) - if err := os.Rename(path, destPath); err != nil { - // Cross-filesystem move: fall back to copy+delete - return fmt.Errorf("cannot move to trash: %w", err) - } - - // Write .trashinfo file - absPath, err := filepath.Abs(path) - if err != nil { - absPath = path - } - now := time.Now().Format("2006-01-02T15:04:05") - infoContent := fmt.Sprintf("[Trash Info]\nPath=%s\nDeletionDate=%s\n", absPath, now) - infoPath := filepath.Join(infoDir, destName+".trashinfo") - if err := os.WriteFile(infoPath, []byte(infoContent), 0o600); err != nil { - // Best-effort: if info file fails, try to move the file back - _ = os.Rename(destPath, path) - return fmt.Errorf("cannot write trash info: %w", err) - } - - return nil + return localfs.New().Trash(context.Background(), path) } func MakeDir(parent string, name string) (string, error) { target := filepath.Join(parent, name) - if err := os.MkdirAll(target, 0o755); err != nil { + // Parents may be created ("a/b"), but the final directory must be new: + // MkdirAll silently "succeeded" on an existing name. + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return "", err + } + if err := os.Mkdir(target, 0o755); err != nil { return "", err } return target, nil diff --git a/internal/fs/ops_test.go b/internal/fs/ops_test.go index 8fa7071..4df6c66 100644 --- a/internal/fs/ops_test.go +++ b/internal/fs/ops_test.go @@ -183,3 +183,58 @@ func TestRenamePathRejectsExistingTarget(t *testing.T) { t.Fatalf("expected overwrite error %q, got %q", want, got) } } + +func TestCreateArchiveRefusesSourceAndSelfInclusion(t *testing.T) { + d := t.TempDir() + src := filepath.Join(d, "data.tar") + if err := os.WriteFile(src, make([]byte, 100000), 0o644); err != nil { + t.Fatal(err) + } + if err := CreateArchive(context.Background(), []string{src}, filepath.Join(d, ArchiveName([]string{src}, "tar")), nil); err == nil { + t.Fatal("archive over its own source must be refused") + } + if st, _ := os.Stat(src); st.Size() != 100000 { + t.Fatalf("source damaged: %d", st.Size()) + } + + proj := filepath.Join(d, "proj") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + if err := CreateArchive(context.Background(), []string{proj}, filepath.Join(proj, "proj.zip"), nil); err == nil { + t.Fatal("archive inside its source must be refused") + } + // Same through a symlinked parent. + if err := os.Symlink(proj, filepath.Join(d, "alias")); err != nil { + t.Fatal(err) + } + if err := CreateArchive(context.Background(), []string{proj}, filepath.Join(d, "alias", "proj.zip"), nil); err == nil { + t.Fatal("archive inside its source via a symlinked dir must be refused") + } +} + +func TestCreateArchiveFailureKeepsOldArchive(t *testing.T) { + d := t.TempDir() + arc := filepath.Join(d, "out.zip") + if err := os.WriteFile(arc, []byte("OLD"), 0o644); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + src := filepath.Join(d, "src") + if err := os.MkdirAll(src, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(src, "f"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if err := CreateArchive(ctx, []string{src}, arc, nil); err == nil { + t.Fatal("cancelled archive should fail") + } + if b, _ := os.ReadFile(arc); string(b) != "OLD" { + t.Fatalf("failed run replaced the old archive: %q", b) + } + if left, _ := filepath.Glob(filepath.Join(d, ".vcom-tmp-*")); len(left) != 0 { + t.Fatalf("temp files left: %v", left) + } +} diff --git a/internal/fs/qa_archive_trash_test.go b/internal/fs/qa_archive_trash_test.go new file mode 100644 index 0000000..d36b235 --- /dev/null +++ b/internal/fs/qa_archive_trash_test.go @@ -0,0 +1,437 @@ +package vfs + +// QA (v0.2.8): independent checks of the stage-1 fixes in archive.go and +// ops.go (U-P0-1 archive safety, U-P0-4 trash as default delete, MakeDir). +// Tests that expose a still-open bug are skipped with "BUG QA-n" and are +// described in plans/rework/05-qa-v0.2.8.md. + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "io" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" +) + +func qaWrite(t *testing.T, p string, data string, mode os.FileMode) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(data), mode); err != nil { + t.Fatal(err) + } +} + +// Every format: archiving a file whose archive name equals its own name +// into the same directory is refused and leaves the source intact. +func TestQAArchiveIntoSourceDirAllFormats(t *testing.T) { + cases := []struct{ name, format string }{ + {"data.zip", "zip"}, + {"data.tar", "tar"}, + {"data.tar", "tar.gz"}, // data.tar -> data.tar.gz: allowed, different file + {"data.gz", "tar.gz"}, // data.gz -> data.tar.gz: allowed + } + for _, tc := range cases { + t.Run(tc.name+"->"+tc.format, func(t *testing.T) { + d := t.TempDir() + src := filepath.Join(d, tc.name) + payload := strings.Repeat("z", 50000) + qaWrite(t, src, payload, 0o644) + arc := filepath.Join(d, ArchiveName([]string{src}, tc.format)) + err := CreateArchive(context.Background(), []string{src}, arc, nil) + if arc == src { + if err == nil { + t.Fatal("archive equal to source must be refused") + } + } else if err != nil { + t.Fatalf("archive %s of %s should work: %v", arc, src, err) + } + if b, _ := os.ReadFile(src); string(b) != payload { + t.Fatalf("source changed (len %d)", len(b)) + } + if left, _ := filepath.Glob(filepath.Join(d, ".vcom-tmp-*")); len(left) != 0 { + t.Fatalf("temp files left: %v", left) + } + }) + } +} + +// The produced archive must actually contain the source (zip, tar, tar.gz), +// i.e. the temp+rename path did not break the formats. +func TestQAArchiveContentsRoundTrip(t *testing.T) { + for _, format := range []string{"zip", "tar", "tar.gz"} { + t.Run(format, func(t *testing.T) { + d, out := t.TempDir(), t.TempDir() + qaWrite(t, filepath.Join(d, "proj", "a.txt"), "alpha", 0o644) + qaWrite(t, filepath.Join(d, "proj", "sub", "б.txt"), "бета", 0o644) + src := filepath.Join(d, "proj") + arc := filepath.Join(out, ArchiveName([]string{src}, format)) + if err := CreateArchive(context.Background(), []string{src}, arc, nil); err != nil { + t.Fatal(err) + } + names := qaListArchive(t, arc) + joined := strings.Join(names, "\n") + for _, want := range []string{"a.txt", "б.txt"} { + if !strings.Contains(joined, want) { + t.Fatalf("%s missing from %s: %v", want, arc, names) + } + } + }) + } +} + +func qaListArchive(t *testing.T, p string) []string { + t.Helper() + var names []string + switch { + case strings.HasSuffix(p, ".zip"): + zr, err := zip.OpenReader(p) + if err != nil { + t.Fatal(err) + } + defer zr.Close() + for _, f := range zr.File { + names = append(names, f.Name) + } + default: + f, err := os.Open(p) + if err != nil { + t.Fatal(err) + } + defer f.Close() + var r io.Reader = f + if strings.HasSuffix(p, ".gz") { + gz, err := gzip.NewReader(f) + if err != nil { + t.Fatal(err) + } + r = gz + } + tr := tar.NewReader(r) + for { + h, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + names = append(names, h.Name) + } + } + return names +} + +// Overwriting an existing archive after confirmation must not widen its +// permissions: a private 0600 archive became world-readable 0644. +func TestQAArchiveOverwriteKeepsPermissions(t *testing.T) { + d, out := t.TempDir(), t.TempDir() + qaWrite(t, filepath.Join(d, "secret.txt"), "pin 1234", 0o600) + arc := filepath.Join(out, "secret.zip") + qaWrite(t, arc, "old", 0o600) + if err := CreateArchive(context.Background(), []string{filepath.Join(d, "secret.txt")}, arc, nil); err != nil { + t.Fatal(err) + } + st, err := os.Stat(arc) + if err != nil { + t.Fatal(err) + } + if st.Mode().Perm() != 0o600 { + t.Fatalf("existing 0600 archive replaced with mode %o", st.Mode().Perm()) + } +} + +// A long but valid file name (NAME_MAX is 255 bytes) can no longer be +// archived: the temp name ".vcom-tmp--" exceeds NAME_MAX. +func TestQAArchiveLongName(t *testing.T) { + d, out := t.TempDir(), t.TempDir() + base := strings.Repeat("n", 240) + src := filepath.Join(d, base+".txt") + qaWrite(t, src, "x", 0o644) + arc := filepath.Join(out, ArchiveName([]string{src}, "zip")) // 244 bytes: valid + if err := CreateArchive(context.Background(), []string{src}, arc, nil); err != nil { + t.Fatalf("archive with a valid %d-byte name failed: %v", len(filepath.Base(arc)), err) + } +} + +// A source that is a symlink to a directory, archived into that directory: +// the link is resolved by nobody, so the check does not see the archive is +// inside the (dereferenced) source. Make sure at least nothing is destroyed +// and the archive does not contain itself. +func TestQAArchiveSymlinkDirSourceIntoTarget(t *testing.T) { + d := t.TempDir() + proj := filepath.Join(d, "proj") + qaWrite(t, filepath.Join(proj, "a.txt"), "alpha", 0o644) + link := filepath.Join(d, "link") + if err := os.Symlink(proj, link); err != nil { + t.Fatal(err) + } + arc := filepath.Join(proj, "link.tar") + err := CreateArchive(context.Background(), []string{link}, arc, nil) + if b, _ := os.ReadFile(filepath.Join(proj, "a.txt")); string(b) != "alpha" { + t.Fatal("source content damaged") + } + if err == nil { + for _, n := range qaListArchive(t, arc) { + if strings.Contains(n, "link.tar") || strings.Contains(n, ".vcom-tmp") { + t.Fatalf("archive contains itself: %v", n) + } + } + } +} + +// Cancelled archive into a directory with an existing archive: old archive +// stays, no temp file (tar and tar.gz paths, the developer only tested zip). +func TestQAArchiveCancelKeepsOldAllFormats(t *testing.T) { + for _, format := range []string{"zip", "tar", "tar.gz"} { + t.Run(format, func(t *testing.T) { + d, out := t.TempDir(), t.TempDir() + qaWrite(t, filepath.Join(d, "src", "f"), "x", 0o644) + src := filepath.Join(d, "src") + arc := filepath.Join(out, ArchiveName([]string{src}, format)) + qaWrite(t, arc, "OLD", 0o644) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := CreateArchive(ctx, []string{src}, arc, nil); err == nil { + t.Fatal("cancelled archive should fail") + } + if b, _ := os.ReadFile(arc); string(b) != "OLD" { + t.Fatalf("old archive replaced: %q", b) + } + if left, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*")); len(left) != 0 { + t.Fatalf("temp files left: %v", left) + } + }) + } +} + +// --- Trash (now the default delete) --------------------------------------- + +func qaTrashHome(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + return filepath.Join(home, ".local", "share", "Trash") +} + +// Names with spaces and Cyrillic, and same-name collisions, all land in the +// trash under distinct names with a matching .trashinfo. +func TestQATrashNamesAndCollisions(t *testing.T) { + trash := qaTrashHome(t) + work := filepath.Join(os.Getenv("HOME"), "work") // same filesystem as HOME + names := []string{"my file.txt", "отчёт 2026.txt"} + for _, n := range names { + qaWrite(t, filepath.Join(work, "a", n), "A "+n, 0o644) + qaWrite(t, filepath.Join(work, "b", n), "B "+n, 0o644) + } + for _, sub := range []string{"a", "b"} { + for _, n := range names { + if err := MoveToTrash(filepath.Join(work, sub, n)); err != nil { + t.Fatalf("MoveToTrash(%s/%s): %v", sub, n, err) + } + } + } + files, _ := os.ReadDir(filepath.Join(trash, "files")) + infos, _ := os.ReadDir(filepath.Join(trash, "info")) + if len(files) != 4 || len(infos) != 4 { + t.Fatalf("want 4 trashed files and 4 infos, got %d/%d", len(files), len(infos)) + } + for _, f := range files { + if _, err := os.Stat(filepath.Join(trash, "info", f.Name()+".trashinfo")); err != nil { + t.Errorf("no trashinfo for %s", f.Name()) + } + } +} + +// The XDG trash spec requires Path= in .trashinfo to be percent-encoded +// (RFC 2396). Unencoded spaces/Cyrillic/newlines break restore in other +// tools (gio, trash-cli) — a newline in a file name corrupts the info file. +func TestQATrashInfoPathEncoded(t *testing.T) { + trash := qaTrashHome(t) + work := filepath.Join(os.Getenv("HOME"), "work") + p := filepath.Join(work, "my file\nx.txt") + qaWrite(t, p, "x", 0o644) + if err := MoveToTrash(p); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(filepath.Join(trash, "info", "my file\nx.txt.trashinfo")) + if err != nil { + t.Fatal(err) + } + var pathLine string + for _, l := range strings.Split(string(b), "\n") { + if strings.HasPrefix(l, "Path=") { + pathLine = strings.TrimPrefix(l, "Path=") + } + } + got, err := url.PathUnescape(pathLine) + if err != nil || got != p { + t.Fatalf("Path=%q does not decode to %q (err %v)", pathLine, p, err) + } +} + +// XDG_DATA_HOME must be honoured ($XDG_DATA_HOME/Trash), otherwise vcom and +// the desktop use different trash cans. +func TestQATrashHonoursXDGDataHome(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + xdg := filepath.Join(home, "xdgdata") + t.Setenv("XDG_DATA_HOME", xdg) + p := filepath.Join(home, "f.txt") + qaWrite(t, p, "x", 0o644) + if err := MoveToTrash(p); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(xdg, "Trash", "files", "f.txt")); err != nil { + t.Fatalf("file not in $XDG_DATA_HOME/Trash: %v", err) + } +} + +// otherDevice returns a writable directory on a different filesystem than +// home, or "" if none is available. +func otherDevice(t *testing.T, home string) string { + t.Helper() + var hs syscall.Stat_t + if err := syscall.Stat(home, &hs); err != nil { + return "" + } + wd, _ := os.Getwd() + for _, cand := range []string{"/dev/shm", os.Getenv("XDG_RUNTIME_DIR"), "/var/tmp", wd} { + if cand == "" { + continue + } + var cs syscall.Stat_t + if err := syscall.Stat(cand, &cs); err != nil || cs.Dev == hs.Dev { + continue + } + dir, err := os.MkdirTemp(cand, ".vcom-qa-*") + if err != nil { + continue + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return dir + } + return "" +} + +// With trash as the default, deleting a file on another filesystem than +// $HOME (/tmp on tmpfs, /mnt, USB, a second disk) must still work: the spec +// uses $topdir/.Trash-$uid or a copy. Here MoveToTrash only does os.Rename +// and fails with EXDEV. +func TestQATrashCrossDevice(t *testing.T) { + home := qaTrashHome(t) + _ = home + dir := otherDevice(t, os.Getenv("HOME")) + if dir == "" { + t.Skip("no second filesystem available") + } + name := "vcom-qa-" + filepath.Base(dir) + ".txt" + p := filepath.Join(dir, name) + qaWrite(t, p, "x", 0o644) + cleanupTopdirTrash(t, dir, name) + if err := MoveToTrash(p); err != nil { + t.Fatalf("MoveToTrash across filesystems: %v", err) + } + if _, err := os.Lstat(p); !os.IsNotExist(err) { + t.Fatal("file still in place") + } +} + +// A trashed broken symlink with the same name must not be silently replaced +// by the next trashed item (collision check uses Stat, which follows links). +func TestQATrashCollisionWithBrokenSymlink(t *testing.T) { + trash := qaTrashHome(t) + work := filepath.Join(os.Getenv("HOME"), "work") + if err := os.MkdirAll(work, 0o755); err != nil { + t.Fatal(err) + } + link := filepath.Join(work, "x") + if err := os.Symlink("/nonexistent/target", link); err != nil { + t.Fatal(err) + } + if err := MoveToTrash(link); err != nil { + t.Fatal(err) + } + qaWrite(t, link, "file now", 0o644) + if err := MoveToTrash(link); err != nil { + t.Fatal(err) + } + files, _ := os.ReadDir(filepath.Join(trash, "files")) + if len(files) != 2 { + t.Fatalf("want 2 items in trash, got %d (first one overwritten)", len(files)) + } +} + +// --- MakeDir --------------------------------------------------------------- + +func TestQAMakeDirEdgeCases(t *testing.T) { + d := t.TempDir() + if _, err := MakeDir(d, "a/b"); err != nil { + t.Fatalf("nested name: %v", err) + } + if _, err := MakeDir(d, "a/b"); err == nil { + t.Fatal("existing nested dir must error") + } + if _, err := MakeDir(d, "a"); err == nil { + t.Fatal("existing parent must error") + } + qaWrite(t, filepath.Join(d, "file"), "x", 0o644) + if _, err := MakeDir(d, "file"); err == nil { + t.Fatal("name of an existing file must error") + } + if _, err := MakeDir(d, "папка с пробелом"); err != nil { + t.Fatalf("cyrillic name: %v", err) + } +} + +// cleanupTopdirTrash removes name (and its .trashinfo) from the topdir trash +// of dir's filesystem after the test, and the trash dirs themselves if the +// test created them: the topdir is a real mount (/dev/shm, /run/user/...). +func cleanupTopdirTrash(t *testing.T, dir, name string) { + t.Helper() + var st syscall.Stat_t + if err := syscall.Stat(dir, &st); err != nil { + return + } + top := dir + for { + parent := filepath.Dir(top) + var ps syscall.Stat_t + if parent == top || syscall.Stat(parent, &ps) != nil || ps.Dev != st.Dev { + break + } + top = parent + } + uid := strconv.Itoa(os.Getuid()) + trashes := []string{filepath.Join(top, ".Trash-"+uid), filepath.Join(top, ".Trash", uid)} + existed := map[string]bool{} + for _, tr := range trashes { + if _, err := os.Lstat(tr); err == nil { + existed[tr] = true + } + } + t.Cleanup(func() { + for _, tr := range trashes { + matches, _ := filepath.Glob(filepath.Join(tr, "files", name+"*")) + for _, m := range matches { + os.RemoveAll(m) + os.Remove(filepath.Join(tr, "info", filepath.Base(m)+".trashinfo")) + } + if !existed[tr] { + os.Remove(filepath.Join(tr, "files")) + os.Remove(filepath.Join(tr, "info")) + os.Remove(filepath.Join(tr, "expunged")) + os.Remove(tr) + } + } + }) +} diff --git a/internal/fs/qa_fixes_test.go b/internal/fs/qa_fixes_test.go new file mode 100644 index 0000000..6ec863e --- /dev/null +++ b/internal/fs/qa_fixes_test.go @@ -0,0 +1,26 @@ +package vfs + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +// QA-6: a new archive gets 0666 minus umask (as os.Create would), not the +// 0600 of the temp file and not a fixed 0644. +func TestNewArchiveModeFollowsUmask(t *testing.T) { + d, out := t.TempDir(), t.TempDir() + qaWrite(t, filepath.Join(d, "a.txt"), "x", 0o644) + arc := filepath.Join(out, "a.tar") + if err := CreateArchive(context.Background(), []string{filepath.Join(d, "a.txt")}, arc, nil); err != nil { + t.Fatal(err) + } + st, err := os.Stat(arc) + if err != nil { + t.Fatal(err) + } + if want := 0o666 &^ processUmask(); st.Mode().Perm() != want { + t.Fatalf("new archive mode %o, want %o", st.Mode().Perm(), want) + } +} diff --git a/internal/fs/remote/client.go b/internal/fs/remote/client.go index abf41ee..67afb9d 100644 --- a/internal/fs/remote/client.go +++ b/internal/fs/remote/client.go @@ -12,6 +12,7 @@ import ( "path/filepath" "strings" "sync" + "sync/atomic" "time" "github.com/pkg/sftp" @@ -23,17 +24,61 @@ import ( ) // SSHClient wraps an SSH connection and SFTP client for remote filesystem access. +// +// It is safe for concurrent use: sshConn and sftpCli are set once by Connect +// and never reassigned, Close is serialized and only flips the closed flag +// and closes the underlying clients (which then fail calls with an error +// instead of panicking). Panels and jobs sharing a client use Acquire and +// Release; the client is closed when the last user releases it (N-P0-8). type SSHClient struct { // Host is the SSH host configuration used to establish the connection. Host SSHHost - sshConn *ssh.Client - sftpCli *sftp.Client + sshConn *ssh.Client // immutable after Connect + sftpCli *sftp.Client // immutable after Connect + + closeMu sync.Mutex + closed atomic.Bool + users atomic.Int32 keepaliveStop chan struct{} keepaliveWg sync.WaitGroup } +var errNotConnected = errors.New("not connected") + +// unusable reports whether the client cannot serve requests. +func (c *SSHClient) unusable() bool { + return c == nil || c.sftpCli == nil || c.sshConn == nil || c.closed.Load() +} + +// Acquire registers one more user of the client (a panel or a job). +func (c *SSHClient) Acquire() { + if c != nil { + c.users.Add(1) + } +} + +// Release drops one user; the last Release closes the client. Connect +// returns a client with one user (the caller). +func (c *SSHClient) Release() error { + if c == nil { + return nil + } + if c.users.Add(-1) <= 0 { + return c.Close() + } + return nil +} + +// Users reports the current number of users (for tests and logs). +func (c *SSHClient) Users() int { + if c == nil { + return 0 + } + return int(c.users.Load()) +} + // Connect establishes an SSH connection to the remote host and opens an SFTP session. // It uses key-based authentication if IdentityFile is set, otherwise falls back to password auth. func Connect(host SSHHost) (*SSHClient, error) { @@ -42,7 +87,7 @@ func Connect(host SSHHost) (*SSHClient, error) { return nil, fmt.Errorf("ssh auth: %w", err) } - hostKeyCB, err := tofuHostKeyCallback() + hostKeyCB, hostKeyAlgos, err := tofuHostKeyCallback(host.Addr()) if err != nil { return nil, fmt.Errorf("host key verification: %w", err) } @@ -53,10 +98,11 @@ func Connect(host SSHHost) (*SSHClient, error) { } config := &ssh.ClientConfig{ - User: user, - Auth: authMethods, - HostKeyCallback: hostKeyCB, - Timeout: 15 * time.Second, + User: user, + Auth: authMethods, + HostKeyCallback: hostKeyCB, + HostKeyAlgorithms: hostKeyAlgos, + Timeout: 15 * time.Second, } addr := host.Addr() @@ -77,6 +123,7 @@ func Connect(host SSHHost) (*SSHClient, error) { sftpCli: sftpCli, keepaliveStop: make(chan struct{}), } + client.users.Store(1) // Start keepalive goroutine — sends keepalive@openssh.com every 30s // to prevent the SSH server from dropping the connection during inactivity. @@ -108,30 +155,33 @@ func Connect(host SSHHost) (*SSHClient, error) { // previously recorded entry is rejected outright, since that's the signature // of a man-in-the-middle attack or a legitimately reissued key that the user // must verify and update manually (e.g. via `ssh-keygen -R `). -func tofuHostKeyCallback() (ssh.HostKeyCallback, error) { +// +// Lines of known_hosts that cannot be parsed (unknown key types) are skipped, +// see knownHostsDB. It also returns the host key algorithms to offer for addr. +func tofuHostKeyCallback(addr string) (ssh.HostKeyCallback, []string, error) { khPath := KnownHostsPath() if khPath == "" { - return nil, fmt.Errorf("cannot determine known_hosts path") + return nil, nil, fmt.Errorf("cannot determine known_hosts path") } if err := os.MkdirAll(filepath.Dir(khPath), 0o700); err != nil { - return nil, fmt.Errorf("create ssh dir: %w", err) + return nil, nil, fmt.Errorf("create ssh dir: %w", err) } if _, err := os.Stat(khPath); os.IsNotExist(err) { f, err := os.OpenFile(khPath, os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { - return nil, fmt.Errorf("create known_hosts: %w", err) + return nil, nil, fmt.Errorf("create known_hosts: %w", err) } f.Close() } - verify, err := knownhosts.New(khPath) + db, err := loadKnownHosts(khPath) if err != nil { - return nil, fmt.Errorf("parse known_hosts: %w", err) + return nil, nil, err } return func(hostname string, remote net.Addr, key ssh.PublicKey) error { - err := verify(hostname, remote, key) + err := db.verify(hostname, remote, key) if err == nil { return nil } @@ -141,6 +191,10 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) { return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for %s! This may indicate a man-in-the-middle attack, or the server's key was legitimately reissued. Refusing to connect; run `ssh-keygen -R %s` to remove the stale entry once you've verified the new key: %w", hostname, hostname, err) } + if db.unsupportedOnly(hostname) { + return fmt.Errorf("the host key of %s is recorded in %s only with a key type vcom does not support yet; refusing to trust a different key automatically. Add a supported key for it (e.g. from `ssh-keyscan -t ed25519`) after verifying it: %w", hostname, khPath, err) + } + // Unknown host: trust on first use and remember the key. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key) f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) @@ -152,7 +206,7 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) { return fmt.Errorf("cannot save host key for %s: %w", hostname, werr) } return nil - }, nil + }, db.hostKeyAlgorithms(addr), nil } // sshAgentAuth connects to the running ssh-agent (via SSH_AUTH_SOCK) and @@ -258,56 +312,56 @@ func authMethodsForHost(host SSHHost) ([]ssh.AuthMethod, error) { // ReadDir reads the contents of a remote directory and returns os.FileInfo entries. func (c *SSHClient) ReadDir(dirPath string) ([]os.FileInfo, error) { - if c.sftpCli == nil { - return nil, fmt.Errorf("not connected") + if c.unusable() { + return nil, errNotConnected } return c.sftpCli.ReadDir(dirPath) } // Lstat returns file information without following symlinks. func (c *SSHClient) Lstat(path string) (os.FileInfo, error) { - if c.sftpCli == nil { - return nil, fmt.Errorf("not connected") + if c.unusable() { + return nil, errNotConnected } return c.sftpCli.Lstat(path) } // Stat returns file information following symlinks. func (c *SSHClient) Stat(path string) (os.FileInfo, error) { - if c.sftpCli == nil { - return nil, fmt.Errorf("not connected") + if c.unusable() { + return nil, errNotConnected } return c.sftpCli.Stat(path) } // ReadLink reads the target of a symbolic link. func (c *SSHClient) ReadLink(linkPath string) (string, error) { - if c.sftpCli == nil { - return "", fmt.Errorf("not connected") + if c.unusable() { + return "", errNotConnected } return c.sftpCli.ReadLink(linkPath) } // RealPath resolves a path to its absolute form on the remote server. func (c *SSHClient) RealPath(p string) (string, error) { - if c.sftpCli == nil { - return "", fmt.Errorf("not connected") + if c.unusable() { + return "", errNotConnected } return c.sftpCli.RealPath(p) } // ReadFile opens a remote file for reading. func (c *SSHClient) ReadFile(filePath string) (io.ReadCloser, error) { - if c.sftpCli == nil { - return nil, fmt.Errorf("not connected") + if c.unusable() { + return nil, errNotConnected } return c.sftpCli.Open(filePath) } // CreateFile opens a remote file for writing, creating it if it doesn't exist. func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) { - if c.sftpCli == nil { - return nil, fmt.Errorf("not connected") + if c.unusable() { + return nil, errNotConnected } return c.sftpCli.Create(filePath) } @@ -315,8 +369,8 @@ func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) { // MkdirAll creates a remote directory and any necessary parents. // If the directory already exists, it returns nil (no error). func (c *SSHClient) MkdirAll(dirPath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } // sftp doesn't have MkdirAll, so we implement it manually // First check if the path already exists @@ -339,71 +393,92 @@ func (c *SSHClient) MkdirAll(dirPath string) error { // Mkdir creates a single remote directory. func (c *SSHClient) Mkdir(dirPath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected + } + return c.sftpCli.Mkdir(dirPath) +} + +// MkdirNew creates dirPath (and missing parents) and fails if dirPath +// already exists, like the local MakeDir: F7 with a taken name must report +// an error (QA-10). +func (c *SSHClient) MkdirNew(dirPath string) error { + if c.unusable() { + return errNotConnected + } + if _, err := c.sftpCli.Lstat(dirPath); err == nil { + return &os.PathError{Op: "mkdir", Path: dirPath, Err: os.ErrExist} + } else if !os.IsNotExist(err) { + return err + } + if parent := path.Dir(dirPath); parent != dirPath && parent != "." { + if err := c.MkdirAll(parent); err != nil { + return err + } } return c.sftpCli.Mkdir(dirPath) } // Remove deletes a remote file. func (c *SSHClient) Remove(filePath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } return c.sftpCli.Remove(filePath) } // RemoveDirectory removes a remote directory (must be empty). func (c *SSHClient) RemoveDirectory(dirPath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } return c.sftpCli.RemoveDirectory(dirPath) } // Rename moves/renames a remote file or directory. func (c *SSHClient) Rename(oldPath, newPath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } return c.sftpCli.Rename(oldPath, newPath) } -// Close closes the SFTP session and SSH connection. +// Close closes the SFTP session and SSH connection. It is idempotent and +// safe to call concurrently with other methods, which then return errors. func (c *SSHClient) Close() error { + if c == nil { + return nil + } + c.closeMu.Lock() + defer c.closeMu.Unlock() + if c.closed.Load() { + return nil + } + c.closed.Store(true) + // Stop the keepalive goroutine first if c.keepaliveStop != nil { - select { - case <-c.keepaliveStop: - // already closed - default: - close(c.keepaliveStop) - } + close(c.keepaliveStop) c.keepaliveWg.Wait() } var firstErr error - if c.sftpCli != nil { if err := c.sftpCli.Close(); err != nil { firstErr = err } - c.sftpCli = nil } - if c.sshConn != nil { if err := c.sshConn.Close(); err != nil && firstErr == nil { firstErr = err } - c.sshConn = nil } - return firstErr } // IsConnected returns true if the client has an active connection. func (c *SSHClient) IsConnected() bool { - return c.sftpCli != nil && c.sshConn != nil + return !c.unusable() } // ShellQuote wraps s in single quotes so it's safe to interpolate into a @@ -417,8 +492,8 @@ func ShellQuote(s string) string { // Exec runs a shell command on the remote server and returns combined output. func (c *SSHClient) Exec(cmd string) ([]byte, error) { - if c.sshConn == nil { - return nil, fmt.Errorf("not connected") + if c.unusable() { + return nil, errNotConnected } session, err := c.sshConn.NewSession() if err != nil { @@ -431,8 +506,8 @@ func (c *SSHClient) Exec(cmd string) ([]byte, error) { // ExecWithProgress runs a shell command on the remote server and calls onLine // for each line of stdout output. func (c *SSHClient) ExecWithProgress(cmd string, onLine func(line string)) error { - if c.sshConn == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } session, err := c.sshConn.NewSession() if err != nil { @@ -471,12 +546,17 @@ func (c *SSHClient) SameHostAs(other *SSHClient) bool { // RemoveRecursive recursively deletes a remote file or directory. // For directories, it walks and removes all children first. -func (c *SSHClient) RemoveRecursive(path string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") +func (c *SSHClient) RemoveRecursive(target string) error { + if c.unusable() { + return errNotConnected } + // Clean first: lstat("link/") resolves the link on POSIX servers, and + // the target's contents would be deleted (QA-9). + path := path.Clean(target) - info, err := c.sftpCli.Stat(path) + // Lstat, not Stat: a symlink to a directory must be removed as a link. + // Following it would delete the contents of the link's target (N-P0-3). + info, err := c.sftpCli.Lstat(path) if err != nil { return err } @@ -525,8 +605,8 @@ func (c *SSHClient) RemoveRecursive(path string) error { // CopyFileToRemote copies a local file to a remote destination via SFTP. // It creates parent directories as needed. func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } localFile, err := os.Open(localPath) @@ -558,8 +638,8 @@ func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error { // CopyFileFromRemote copies a remote file to a local destination via SFTP. // It creates parent directories as needed. func (c *SSHClient) CopyFileFromRemote(remotePath, localPath string) error { - if c.sftpCli == nil { - return fmt.Errorf("not connected") + if c.unusable() { + return errNotConnected } remoteFile, err := c.sftpCli.Open(remotePath) @@ -681,10 +761,10 @@ func (c *SSHClient) copyDirFromRemote(remoteDir, localDir string, onFile func(pa // by streaming the file contents through the local machine. Both SFTP connections // must be active (connected). func CopyFileBetweenRemotes(srcClient, dstClient *SSHClient, srcPath, dstPath string) error { - if srcClient.sftpCli == nil { + if srcClient.unusable() { return fmt.Errorf("source client not connected") } - if dstClient.sftpCli == nil { + if dstClient.unusable() { return fmt.Errorf("destination client not connected") } if srcClient.SameHostAs(dstClient) && path.Clean(srcPath) == path.Clean(dstPath) { @@ -781,8 +861,10 @@ func (c *SSHClient) Walk(root string, walkFn walkFunc) error { func (c *SSHClient) walk(dirPath string, walkFn walkFunc, info os.FileInfo) error { if info == nil { + // The root is examined with Lstat like every other entry, so a + // symlink root is reported as a leaf and never descended into. var statErr error - info, statErr = c.sftpCli.Stat(dirPath) + info, statErr = c.sftpCli.Lstat(dirPath) if statErr != nil { if fnErr := walkFn(dirPath, nil, statErr); fnErr != nil && fnErr != filepathSkipDir { return fnErr diff --git a/internal/fs/remote/client_test.go b/internal/fs/remote/client_test.go new file mode 100644 index 0000000..447a4f3 --- /dev/null +++ b/internal/fs/remote/client_test.go @@ -0,0 +1,134 @@ +package remote + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// B1 / N-P0-3: deleting a remote symlink that points to a directory wiped +// the target directory. +func TestRemoveRecursiveSymlinkToDir(t *testing.T) { + _, c, dir := setup(t) + target := filepath.Join(dir, "precious") + writeFile(t, filepath.Join(target, "a.txt"), 10, 0o644) + writeFile(t, filepath.Join(target, "sub", "b.txt"), 10, 0o644) + link := filepath.Join(dir, "link") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + + if err := c.RemoveRecursive(link); err != nil { + t.Fatalf("RemoveRecursive(link): %v", err) + } + for _, p := range []string{"a.txt", "sub/b.txt"} { + if _, err := os.Stat(filepath.Join(target, p)); err != nil { + t.Errorf("deleting the link removed target content %s: %v", p, err) + } + } + if _, err := os.Lstat(link); !os.IsNotExist(err) { + t.Errorf("the link itself must be gone, Lstat err=%v", err) + } +} + +func TestRemoveRecursiveDirKeepsLinkedTarget(t *testing.T) { + _, c, dir := setup(t) + outside := filepath.Join(dir, "outside") + writeFile(t, filepath.Join(outside, "keep.txt"), 10, 0o644) + tree := filepath.Join(dir, "tree") + writeFile(t, filepath.Join(tree, "f.txt"), 10, 0o644) + if err := os.Symlink(outside, filepath.Join(tree, "to-outside")); err != nil { + t.Fatal(err) + } + if err := c.RemoveRecursive(tree); err != nil { + t.Fatalf("RemoveRecursive(tree): %v", err) + } + if _, err := os.Lstat(tree); !os.IsNotExist(err) { + t.Errorf("tree should be gone: %v", err) + } + if _, err := os.Stat(filepath.Join(outside, "keep.txt")); err != nil { + t.Errorf("symlink inside the tree was followed: %v", err) + } +} + +func TestRemoveRecursiveFileAndDir(t *testing.T) { + _, c, dir := setup(t) + f := filepath.Join(dir, "f.bin") + writeFile(t, f, 100, 0o644) + if err := c.RemoveRecursive(f); err != nil { + t.Fatal(err) + } + d := filepath.Join(dir, "d") + writeFile(t, filepath.Join(d, "x", "y", "z.bin"), 100, 0o644) + if err := c.RemoveRecursive(d); err != nil { + t.Fatal(err) + } + for _, p := range []string{f, d} { + if _, err := os.Lstat(p); !os.IsNotExist(err) { + t.Errorf("%s still exists", p) + } + } +} + +// B5 / N-P0-8: Close() concurrently with use raced on the client fields and +// could call a method on a nil *sftp.Client. +func TestCloseRace(t *testing.T) { + _, c, dir := setup(t) + done := make(chan struct{}) + panicked := make(chan any, 1) + for w := 0; w < 4; w++ { + go func() { + defer func() { + if r := recover(); r != nil { + panicked <- r + } + done <- struct{}{} + }() + for i := 0; i < 500; i++ { + c.ReadDir(dir) + c.Lstat(dir) + c.IsConnected() + c.Exec("true") + } + }() + } + time.Sleep(5 * time.Millisecond) + go c.Close() + c.Close() + for w := 0; w < 4; w++ { + <-done + } + select { + case r := <-panicked: + t.Fatalf("panic during concurrent Close: %v", r) + default: + } + if c.IsConnected() { + t.Fatal("client still reports connected after Close") + } + if _, err := c.ReadDir(dir); err == nil { + t.Fatal("ReadDir after Close must fail") + } +} + +func TestAcquireReleaseClosesOnLastUser(t *testing.T) { + _, c, dir := setup(t) + if c.Users() != 1 { + t.Fatalf("Connect should return one user, got %d", c.Users()) + } + c.Acquire() // e.g. mirrored pane + c.Release() // first pane leaves the host + if _, err := c.ReadDir(dir); err != nil { + t.Fatalf("client closed while still in use: %v", err) + } + c.Release() // last user + if c.IsConnected() { + t.Fatal("last Release must close the client") + } + var nilClient *SSHClient + nilClient.Acquire() + if err := nilClient.Release(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/fs/remote/harness_test.go b/internal/fs/remote/harness_test.go new file mode 100644 index 0000000..982e38a --- /dev/null +++ b/internal/fs/remote/harness_test.go @@ -0,0 +1,28 @@ +package remote + +import ( + "os" + "testing" + + "vcom/internal/testutil/sshtest" +) + +// setup starts an in-process SSH server (serving the real filesystem), +// connects an SSHClient to it with an isolated HOME and returns the client +// and a scratch directory. +func setup(t *testing.T) (*sshtest.Server, *SSHClient, string) { + t.Helper() + sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + c, err := Connect(SSHHost{Name: "test", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password}) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { c.Close() }) + return srv, c, t.TempDir() +} + +func writeFile(t *testing.T, p string, size int, mode os.FileMode) { + t.Helper() + sshtest.WriteRandom(t, p, size, mode) +} diff --git a/internal/fs/remote/knownhosts.go b/internal/fs/remote/knownhosts.go new file mode 100644 index 0000000..d481474 --- /dev/null +++ b/internal/fs/remote/knownhosts.go @@ -0,0 +1,202 @@ +package remote + +import ( + "bufio" + "crypto/ed25519" + "errors" + "fmt" + "log" + "net" + "os" + "strconv" + "strings" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" +) + +// knownHostsDB is a tolerant view of ~/.ssh/known_hosts (QA-11). +// +// knownhosts.New rejects the whole file when a single line cannot be parsed, +// e.g. a key type x/crypto/ssh does not implement such as OpenSSH 10's +// "ssh-mldsa44-ed25519". OpenSSH skips such lines, and so do we: they are +// left out (with a warning in the log) and the rest of the file is used. +// +// A host whose skipped lines are its only record is not silently re-trusted +// on first use: unsupported records which apply to it make the unknown-host +// path refuse instead, since we cannot check the key the user already +// accepted. +type knownHostsDB struct { + verify ssh.HostKeyCallback + // unsupported matches the host patterns of skipped lines (with a + // placeholder key); nil when nothing was skipped. + unsupported ssh.HostKeyCallback + // hasCA: the file has @cert-authority lines, so known keys of a host + // cannot be told apart from CA keys; host key algorithms are then left + // at the x/crypto defaults. + hasCA bool +} + +// placeholderKey never matches a real host key; it is used to probe which +// keys are recorded for a host and as the key of placeholder lines. +var placeholderKey = func() ssh.PublicKey { + priv := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize)) + pub, err := ssh.NewPublicKey(priv.Public()) + if err != nil { + panic(err) + } + return pub +}() + +var probeRemote = &net.TCPAddr{IP: net.IPv4zero, Port: 0} + +// loadKnownHosts reads khPath, dropping lines knownhosts cannot parse. +func loadKnownHosts(khPath string) (*knownHostsDB, error) { + data, err := os.ReadFile(khPath) + if err != nil { + return nil, fmt.Errorf("read known_hosts: %w", err) + } + lines := strings.Split(string(data), "\n") + + verify, skipped, err := parseTolerant(lines, khPath) + if err != nil { + return nil, err + } + db := &knownHostsDB{verify: verify} + for _, l := range lines { + if strings.HasPrefix(strings.TrimSpace(l), "@cert-authority") { + db.hasCA = true + break + } + } + + var placeholders []string + marshalled := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(placeholderKey))) + for _, n := range skipped { + fields := strings.Fields(lines[n]) + if len(fields) == 0 || strings.HasPrefix(fields[0], "@") { + // @revoked / @cert-authority with an unsupported key: such a + // key can never be negotiated, nothing to protect. + continue + } + placeholders = append(placeholders, fields[0]+" "+marshalled) + } + if len(placeholders) > 0 { + unsupported, _, err := parseTolerant(placeholders, "") + if err == nil { + db.unsupported = unsupported + } + } + return db, nil +} + +// parseTolerant feeds lines to knownhosts.New, commenting out every line it +// rejects, and returns the callback and the indexes of the rejected lines. +// origin names the file in log warnings ("" = no warnings). +func parseTolerant(lines []string, origin string) (ssh.HostKeyCallback, []int, error) { + work := make([]string, len(lines)) + copy(work, lines) + var skipped []int + skip := func(i int, why string) { + if origin != "" { + log.Printf("[SSH] %s:%d: skipping known_hosts line: %s", origin, i+1, why) + } + work[i] = "#" + skipped = append(skipped, i) + } + for i, l := range work { + // bufio.Scanner in knownhosts fails the whole file on an over-long line. + if len(l) >= bufio.MaxScanTokenSize-1 { + skip(i, "line too long") + } + } + + tmp, err := os.CreateTemp("", "vcom-known_hosts-*") + if err != nil { + return nil, nil, fmt.Errorf("parse known_hosts: %w", err) + } + tmpPath := tmp.Name() + tmp.Close() + defer os.Remove(tmpPath) + + prefix := "knownhosts: " + tmpPath + ":" + for attempt := 0; attempt <= len(work); attempt++ { + if err := os.WriteFile(tmpPath, []byte(strings.Join(work, "\n")+"\n"), 0o600); err != nil { + return nil, nil, fmt.Errorf("parse known_hosts: %w", err) + } + cb, err := knownhosts.New(tmpPath) + if err == nil { + return cb, skipped, nil + } + msg := err.Error() + rest, ok := strings.CutPrefix(msg, prefix) + if !ok { + return nil, nil, fmt.Errorf("parse known_hosts: %w", err) + } + numStr, why, _ := strings.Cut(rest, ":") + n, perr := strconv.Atoi(numStr) + if perr != nil || n < 1 || n > len(work) || work[n-1] == "#" { + return nil, nil, fmt.Errorf("parse known_hosts: %w", err) + } + skip(n-1, strings.TrimSpace(why)) + } + return nil, nil, errors.New("parse known_hosts: too many invalid lines") +} + +// unsupportedOnly reports whether hostname has records only in lines that +// were skipped (so a new key must not be trusted on first use). +func (db *knownHostsDB) unsupportedOnly(hostname string) bool { + if db.unsupported == nil { + return false + } + var keyErr *knownhosts.KeyError + err := db.unsupported(hostname, probeRemote, placeholderKey) + if err == nil { + return true + } + return errors.As(err, &keyErr) && len(keyErr.Want) > 0 +} + +// plainHostKeyAlgos is what the client can verify without certificates. +var plainHostKeyAlgos = []string{ + ssh.KeyAlgoED25519, + ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521, + ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA, +} + +// hostKeyAlgorithms returns the host key algorithms to offer for addr: +// those of keys already recorded for it first (like OpenSSH), then the rest +// of the plain algorithms. Without that, x/crypto prefers ECDSA, and a +// server known only by its ed25519 key looks like a changed host key. +// Only algorithms x/crypto implements are returned, never the type of a +// skipped line. nil means "use the defaults". +func (db *knownHostsDB) hostKeyAlgorithms(addr string) []string { + if db.hasCA { + return nil + } + var keyErr *knownhosts.KeyError + if err := db.verify(addr, probeRemote, placeholderKey); !errors.As(err, &keyErr) || len(keyErr.Want) == 0 { + return nil + } + known := map[string]bool{} + for _, k := range keyErr.Want { + t := k.Key.Type() + if t == ssh.KeyAlgoRSA { + known[ssh.KeyAlgoRSASHA512] = true + known[ssh.KeyAlgoRSASHA256] = true + } + known[t] = true + } + var first, rest []string + for _, a := range plainHostKeyAlgos { + if known[a] { + first = append(first, a) + } else { + rest = append(rest, a) + } + } + if len(first) == 0 { + return nil + } + return append(first, rest...) +} diff --git a/internal/fs/remote/knownhosts_test.go b/internal/fs/remote/knownhosts_test.go new file mode 100644 index 0000000..b50c493 --- /dev/null +++ b/internal/fs/remote/knownhosts_test.go @@ -0,0 +1,146 @@ +package remote + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/testutil/sshtest" +) + +// Unsupported OpenSSH 10 post-quantum key (QA-11). The blob only has to look +// like base64; x/crypto rejects it by its algorithm name. +const mldsaKey = "ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA" + +func writeKnownHosts(t *testing.T, lines ...string) string { + t.Helper() + p := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts") + if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func connectTo(srv *sshtest.Server) (*SSHClient, error) { + return Connect(SSHHost{Name: "h", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password}) +} + +func hostPattern(srv *sshtest.Server) string { + return knownhosts.Normalize(fmt.Sprintf("127.0.0.1:%s", srv.Port())) +} + +// Unparseable lines for other hosts (unknown key type, garbage, bad hash) +// are skipped; the connection proceeds and the new key is recorded. +func TestKnownHostsSkipsUnparseableLines(t *testing.T) { + sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + kh := writeKnownHosts(t, + "# comment", + "otherhost "+mldsaKey, + "garbage-without-key", + "|2|bad|hash ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl", + "@revoked * "+mldsaKey, + ) + c, err := connectTo(srv) + if err != nil { + t.Fatalf("connect: %v", err) + } + c.Close() + data, _ := os.ReadFile(kh) + if !strings.Contains(string(data), "otherhost "+mldsaKey) { + t.Fatal("skipped lines must stay in known_hosts untouched") + } + if !strings.Contains(string(data), hostPattern(srv)+" ") { + t.Fatalf("new host key was not recorded:\n%s", data) + } + // Second connection verifies against the recorded key. + c, err = connectTo(srv) + if err != nil { + t.Fatalf("reconnect: %v", err) + } + c.Close() +} + +// The maintainer's case: the host is recorded with an unsupported PQ key and +// with its ed25519 key only. The server also has an ECDSA key, which +// x/crypto would prefer by default and then report as a changed key; the +// recorded algorithm must be negotiated instead. +func TestKnownHostsPrefersRecordedAlgorithm(t *testing.T) { + sshtest.IsolatedHome(t) + ed, ec := sshtest.GenKeys(t) + srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed, ec}}) + writeKnownHosts(t, + hostPattern(srv)+" "+mldsaKey, + knownhosts.Line([]string{hostPattern(srv)}, ed.PublicKey()), + ) + c, err := connectTo(srv) + if err != nil { + t.Fatalf("connect: %v", err) + } + c.Close() +} + +// A recorded key of a type we cannot check must not be replaced silently +// by trust-on-first-use of another key. +func TestKnownHostsUnsupportedOnlyRefuses(t *testing.T) { + sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + kh := writeKnownHosts(t, hostPattern(srv)+" "+mldsaKey) + if c, err := connectTo(srv); err == nil { + c.Close() + t.Fatal("connected although the only recorded key is of an unsupported type") + } else if !strings.Contains(err.Error(), "does not support") { + t.Fatalf("unexpected error: %v", err) + } + data, _ := os.ReadFile(kh) + if strings.Count(string(data), "\n") != 1 { + t.Fatalf("known_hosts modified:\n%s", data) + } +} + +// A changed key is still refused when the file also has unsupported lines. +func TestKnownHostsMismatchStillRefused(t *testing.T) { + sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + other, _ := sshtest.GenKeys(t) + writeKnownHosts(t, + "otherhost "+mldsaKey, + knownhosts.Line([]string{hostPattern(srv)}, other.PublicKey()), + ) + if c, err := connectTo(srv); err == nil { + c.Close() + t.Fatal("connected with a mismatching recorded key") + } else if !strings.Contains(err.Error(), "HAS CHANGED") { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestHostKeyAlgorithmsNeverUnsupported(t *testing.T) { + sshtest.IsolatedHome(t) + ed, _ := sshtest.GenKeys(t) + kh := writeKnownHosts(t, + "h.example "+mldsaKey, + knownhosts.Line([]string{"h.example"}, ed.PublicKey()), + ) + db, err := loadKnownHosts(kh) + if err != nil { + t.Fatal(err) + } + algos := db.hostKeyAlgorithms("h.example:22") + if len(algos) == 0 || algos[0] != ssh.KeyAlgoED25519 { + t.Fatalf("recorded algorithm not first: %v", algos) + } + for _, a := range algos { + if strings.Contains(a, "mldsa") { + t.Fatalf("unsupported algorithm offered: %v", algos) + } + } + if got := db.hostKeyAlgorithms("unknown.example:22"); got != nil { + t.Fatalf("unknown host: want defaults, got %v", got) + } +} diff --git a/internal/fs/remote/qa_fixes_test.go b/internal/fs/remote/qa_fixes_test.go new file mode 100644 index 0000000..dd8b772 --- /dev/null +++ b/internal/fs/remote/qa_fixes_test.go @@ -0,0 +1,50 @@ +package remote + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +// QA-10: MkdirNew creates missing parents but refuses an existing name +// (directory, file or symlink). +func TestMkdirNew(t *testing.T) { + _, c, dir := setup(t) + nested := filepath.Join(dir, "a", "b") + if err := c.MkdirNew(nested); err != nil { + t.Fatalf("nested mkdir: %v", err) + } + if fi, err := os.Stat(nested); err != nil || !fi.IsDir() { + t.Fatalf("not created: %v", err) + } + writeFile(t, filepath.Join(dir, "file"), 1, 0o644) + if err := os.Symlink("/nonexistent", filepath.Join(dir, "broken")); err != nil { + t.Fatal(err) + } + for _, n := range []string{"a", "a/b", "file", "broken"} { + if err := c.MkdirNew(filepath.Join(dir, n)); !errors.Is(err, os.ErrExist) { + t.Errorf("MkdirNew(%s) = %v, want ErrExist", n, err) + } + } +} + +// QA-9: a path with "/." or "//" variants of the link name is cleaned too. +func TestRemoveRecursiveCleansPath(t *testing.T) { + _, c, dir := setup(t) + target := filepath.Join(dir, "target") + writeFile(t, filepath.Join(target, "keep"), 10, 0o644) + link := filepath.Join(dir, "link") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + if err := c.RemoveRecursive(link + "/."); err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(link); !os.IsNotExist(err) { + t.Fatal("link not removed") + } + if _, err := os.Stat(filepath.Join(target, "keep")); err != nil { + t.Fatal("target contents deleted") + } +} diff --git a/internal/fs/remote/qa_remote_test.go b/internal/fs/remote/qa_remote_test.go new file mode 100644 index 0000000..1ebcebc --- /dev/null +++ b/internal/fs/remote/qa_remote_test.go @@ -0,0 +1,176 @@ +package remote + +// QA (v0.2.8): independent checks of N-P0-3 (RemoveRecursive never follows +// symlinks) and N-P0-8 (Close is safe under concurrent use, refcount). + +import ( + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +func TestQARemoveRecursiveSymlinkVariants(t *testing.T) { + _, c, dir := setup(t) + target := filepath.Join(dir, "target") + writeFile(t, filepath.Join(target, "keep.txt"), 10, 0o644) + file := filepath.Join(dir, "file.txt") + writeFile(t, file, 10, 0o644) + + mk := func(name, to string) string { + p := filepath.Join(dir, name) + if err := os.Symlink(to, p); err != nil { + t.Fatal(err) + } + return p + } + cases := map[string]string{ + "broken": mk("broken", filepath.Join(dir, "nowhere")), + "to-file": mk("to-file", file), + "relative": mk("relative", "target"), + "to-parent": mk("to-parent", ".."), + } + for name, p := range cases { + if err := c.RemoveRecursive(p); err != nil { + t.Errorf("%s: RemoveRecursive: %v", name, err) + } + if _, err := os.Lstat(p); !os.IsNotExist(err) { + t.Errorf("%s: link not removed", name) + } + } + if _, err := os.Stat(filepath.Join(target, "keep.txt")); err != nil { + t.Fatalf("target content removed: %v", err) + } + if _, err := os.Stat(file); err != nil { + t.Fatalf("link target file removed: %v", err) + } +} + +// A directory containing symlinks to a sibling directory and to a file +// outside: only the links go, targets survive. +func TestQARemoveRecursiveDirWithOutsideLinks(t *testing.T) { + _, c, dir := setup(t) + outside := filepath.Join(dir, "outside") + writeFile(t, filepath.Join(outside, "a.txt"), 10, 0o644) + writeFile(t, filepath.Join(outside, "b.txt"), 10, 0o644) + victim := filepath.Join(dir, "victim") + writeFile(t, filepath.Join(victim, "own.txt"), 10, 0o644) + if err := os.MkdirAll(filepath.Join(victim, "deep", "deeper"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(victim, "deep", "deeper", "dirlink")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(outside, "b.txt"), filepath.Join(victim, "filelink")); err != nil { + t.Fatal(err) + } + if err := c.RemoveRecursive(victim); err != nil { + t.Fatalf("RemoveRecursive: %v", err) + } + if _, err := os.Lstat(victim); !os.IsNotExist(err) { + t.Fatal("victim dir still exists") + } + for _, f := range []string{"a.txt", "b.txt"} { + if _, err := os.Stat(filepath.Join(outside, f)); err != nil { + t.Fatalf("outside/%s removed through a link: %v", f, err) + } + } +} + +// "link/" (trailing slash) makes lstat resolve the link on POSIX servers. +// The UI never builds such paths today, but RemoveRecursive is a public +// helper: with a trailing slash it still empties the target. +func TestQARemoveRecursiveSymlinkTrailingSlash(t *testing.T) { + _, c, dir := setup(t) + target := filepath.Join(dir, "target") + writeFile(t, filepath.Join(target, "keep.txt"), 10, 0o644) + link := filepath.Join(dir, "link") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + _ = c.RemoveRecursive(link + "/") + if _, err := os.Stat(filepath.Join(target, "keep.txt")); err != nil { + t.Fatalf("target content removed via link/: %v", err) + } +} + +// Close while uploads and downloads are streaming: errors, no panic, no race. +func TestQACloseDuringTransfers(t *testing.T) { + _, c, dir := setup(t) + src := filepath.Join(dir, "big.bin") + writeFile(t, src, 4<<20, 0o644) + var wg sync.WaitGroup + panics := make(chan any, 16) + for i := 0; i < 3; i++ { + wg.Add(2) + go func(i int) { + defer wg.Done() + defer func() { + if r := recover(); r != nil { + panics <- r + } + }() + _ = c.CopyFileToRemote(src, filepath.Join(dir, "up", "u"+string(rune('0'+i)))) + }(i) + go func(i int) { + defer wg.Done() + defer func() { + if r := recover(); r != nil { + panics <- r + } + }() + _ = c.CopyFileFromRemote(src, filepath.Join(dir, "down", "d"+string(rune('0'+i)))) + _ = c.RemoveRecursive(filepath.Join(dir, "up")) + _ = c.ExecWithProgress("true", func(string) {}) + _ = c.MkdirAll(filepath.Join(dir, "m", "n")) + }(i) + } + time.Sleep(10 * time.Millisecond) + var cw sync.WaitGroup + for i := 0; i < 3; i++ { + cw.Add(1) + go func() { defer cw.Done(); c.Close() }() + } + cw.Wait() + wg.Wait() + close(panics) + for p := range panics { + t.Fatalf("panic during Close: %v", p) + } + if c.IsConnected() { + t.Fatal("still connected after Close") + } +} + +// Concurrent Acquire/Release from panels and jobs: the client is closed +// exactly when the last user leaves, never earlier. +func TestQAAcquireReleaseConcurrent(t *testing.T) { + _, c, dir := setup(t) + const n = 50 + for i := 0; i < n; i++ { + c.Acquire() + } + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, _ = c.ReadDir(dir) + c.Release() + }() + } + wg.Wait() + if !c.IsConnected() { + t.Fatal("client closed while the original user still holds it") + } + if c.Users() != 1 { + t.Fatalf("users=%d, want 1", c.Users()) + } + c.Release() + if c.IsConnected() { + t.Fatal("last Release must close") + } + // Extra Release (double release by a buggy caller) must not panic. + c.Release() +} diff --git a/internal/imgview/actor.go b/internal/imgview/actor.go new file mode 100644 index 0000000..58c89d0 --- /dev/null +++ b/internal/imgview/actor.go @@ -0,0 +1,282 @@ +package imgview + +import ( + "context" + "errors" + "image" + "os/exec" + "strings" + "sync" + + "vcom/internal/preview" +) + +// Backend selects how images are drawn. +type Backend uint8 + +const ( + None Backend = iota + Kitty + Ueberzug +) + +func (b Backend) String() string { return [...]string{"none", "kitty", "ueberzugpp"}[b] } + +// Rect is a cell rectangle (0-based column/row). +type Rect struct{ X, Y, W, H int } + +// Desired is what the UI wants on screen; the actor converges to the latest. +type Desired struct { + Visible bool + Image preview.ImageRef + Rect Rect + Gen uint64 // content generation, used by the UI's change detection + Seq uint64 // effect order; zero keeps the standalone API unordered +} + +func (d Desired) same(o Desired) bool { + if d.Visible != o.Visible { + return false + } + if !d.Visible { + return true + } + return d.Rect == o.Rect && d.Image.Local == o.Image.Local && d.Image.Size == o.Image.Size && + d.Image.ModTime.Equal(o.Image.ModTime) +} + +// Event reports a problem to the UI (shown as a notification). +type Event struct { + Err error + Disabled bool // the backend was switched off (e.g. stuck helper) +} + +// Options configure Start. +type Options struct { + Backend Backend + TTY *SyncTTY + // CellW, CellH: pixel size of a cell; 0 → asked from the TTY, else 8×16. + CellW, CellH int + // TmpDir enables kitty's file transmission (local terminal only); "" → + // direct transmission. + TmpDir string + Tmux bool + // Ueberzug: the helper command (default "ueberzugpp layer --silent"). + Ueberzug []string + OnEvent func(Event) // called from the actor goroutine +} + +// Actor owns the image output. +type Actor struct { + o Options + mu sync.Mutex + want Desired + dirty bool + signal chan struct{} + done chan struct{} + quit chan struct{} + once sync.Once + + backend Backend + kitty *kitty + uz *ueberzug + shown Desired +} + +// Start launches the actor goroutine. A backend that cannot start falls +// back to None with an Event. +func Start(o Options) *Actor { + a := &Actor{o: o, signal: make(chan struct{}, 1), done: make(chan struct{}), quit: make(chan struct{}), backend: o.Backend} + if a.o.CellW <= 0 || a.o.CellH <= 0 { + a.o.CellW, a.o.CellH = 8, 16 + if o.TTY != nil { + if w, h, ok := o.TTY.CellSize(); ok { + a.o.CellW, a.o.CellH = w, h + } + } + } + switch o.Backend { + case Kitty: + a.kitty = &kitty{tty: o.TTY, tmpDir: o.TmpDir, tmux: o.Tmux} + case Ueberzug: + cmd := o.Ueberzug + if len(cmd) == 0 { + cmd = []string{"ueberzugpp", "layer", "--silent"} + } + uz, err := startUeberzug(cmd[0], cmd[1:]...) + if err != nil { + a.backend = None + a.event(Event{Err: err, Disabled: true}) + } else { + a.uz = uz + } + } + go a.loop() + return a +} + +// Backend reports the backend in use (None after a failure). +func (a *Actor) Backend() Backend { + a.mu.Lock() + defer a.mu.Unlock() + return a.backend +} + +// Apply records the desired state and returns at once; only the latest +// state is drawn. Non-zero Seq values reject commands delivered out of order. +func (a *Actor) Apply(d Desired) { + a.mu.Lock() + if d.Seq != 0 && a.want.Seq > d.Seq { + a.mu.Unlock() + return + } + a.want, a.dirty = d, true + a.mu.Unlock() + select { + case a.signal <- struct{}{}: + default: + } +} + +// Stop hides the image, kills ueberzugpp, removes temp files and waits for +// the actor goroutine. +func (a *Actor) Stop() { + a.once.Do(func() { close(a.quit) }) + <-a.done +} + +func (a *Actor) event(e Event) { + if a.o.OnEvent != nil { + a.o.OnEvent(e) + } +} + +func (a *Actor) take() (Desired, bool) { + a.mu.Lock() + defer a.mu.Unlock() + d, ok := a.want, a.dirty + a.dirty = false + return d, ok +} + +// stale reports whether a newer desired state has arrived. +func (a *Actor) stale() bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.dirty +} + +func (a *Actor) loop() { + defer close(a.done) + defer a.teardown() + for { + select { + case <-a.quit: + return + case <-a.signal: + } + d, ok := a.take() + if !ok || d.same(a.shown) { + continue + } + a.draw(d) + } +} + +func (a *Actor) draw(d Desired) { + if a.Backend() == None { + return + } + var err error + switch { + case !d.Visible || d.Image.Local == "": + err = a.hide() + d.Visible = d.Visible && d.Image.Local != "" + case a.kitty != nil: + var img *image.RGBA + img, err = loadScaled(context.Background(), d.Image.Local, d.Rect.W*a.o.CellW, d.Rect.H*a.o.CellH) + if err == nil && a.stale() { + return // superseded while decoding: draw the newer state instead + } + if err == nil { + err = a.kitty.show(img, d.Rect) + } + case a.uz != nil: + if err = checkSize(d.Image.Local); err == nil { + err = a.uz.show(d.Image.Local, d.Rect) + } + } + if err != nil { + disabled := errors.Is(err, ErrStuck) + if disabled { + a.disable() + } + a.event(Event{Err: err, Disabled: disabled}) + a.shown = Desired{} + return + } + a.shown = d +} + +func (a *Actor) hide() error { + switch { + case a.kitty != nil: + return a.kitty.hide() + case a.uz != nil: + return a.uz.hide() + } + return nil +} + +// disable kills a stuck helper and switches to None. +func (a *Actor) disable() { + if a.uz != nil { + a.uz.stop() + a.uz = nil + } + a.mu.Lock() + a.backend = None + a.mu.Unlock() +} + +func (a *Actor) teardown() { + if a.kitty != nil { + a.kitty.stop() + } + if a.uz != nil { + _ = a.uz.hide() + a.uz.stop() + } +} + +// checkSize refuses huge images for ueberzugpp too (it would decode them). +func checkSize(path string) error { + _, err := imageConfig(path) + return err +} + +// Detect picks the backend for preview.image_backend (auto | kitty | +// ueberzugpp | none). auto: kitty in kitty, WezTerm or ghostty outside tmux, +// else ueberzugpp if installed, else none. An explicit "kitty" works in tmux +// (passthrough). +func Detect(setting string, getenv func(string) string) Backend { + inTmux := getenv("TMUX") != "" + switch strings.ToLower(setting) { + case "none": + return None + case "kitty": + return Kitty + case "ueberzugpp", "ueberzug": + return Ueberzug + } + term, prog := getenv("TERM"), getenv("TERM_PROGRAM") + kittyLike := term == "xterm-kitty" || getenv("KITTY_WINDOW_ID") != "" || + prog == "WezTerm" || prog == "ghostty" || term == "xterm-ghostty" + if kittyLike && !inTmux { + return Kitty + } + if _, err := exec.LookPath("ueberzugpp"); err == nil { + return Ueberzug + } + return None +} diff --git a/internal/imgview/imgview.test b/internal/imgview/imgview.test new file mode 100755 index 0000000..7cff466 Binary files /dev/null and b/internal/imgview/imgview.test differ diff --git a/internal/imgview/imgview_test.go b/internal/imgview/imgview_test.go new file mode 100644 index 0000000..8dd35f6 --- /dev/null +++ b/internal/imgview/imgview_test.go @@ -0,0 +1,351 @@ +package imgview + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "image" + "image/jpeg" + "image/png" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "vcom/internal/preview" +) + +// slowWriter writes byte by byte, yielding in between, so unsynchronised +// writers would interleave. +type slowWriter struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (w *slowWriter) Write(p []byte) (int, error) { + for _, b := range p { + w.mu.Lock() + w.buf.WriteByte(b) + w.mu.Unlock() + runtime.Gosched() + } + return len(p), nil +} + +func TestSyncTTYNoInterleave(t *testing.T) { + w := &slowWriter{} + tty := NewSyncWriter(w) + var wg sync.WaitGroup + for i := range 8 { + wg.Add(2) + go func() { // renderer frames + defer wg.Done() + for j := range 20 { + _, _ = tty.Write([]byte(fmt.Sprintf("", i, j, strings.Repeat("x", 50)))) + } + }() + go func() { // kitty blocks in several parts + defer wg.Done() + for j := range 20 { + _ = tty.WriteBlock([]byte(fmt.Sprintf("")) + } + }() + } + wg.Wait() + out := w.buf.String() + // Every '<' must be followed by a whole unit up to its '>' with no '<' inside. + n := 0 + for len(out) > 0 { + if out[0] != '<' { + t.Fatalf("garbage at %q", out[:min(40, len(out))]) + } + end := strings.IndexByte(out, '>') + if end < 0 || strings.Contains(out[1:end], "<") { + t.Fatalf("interleaved output near %q", out[:min(80, len(out))]) + } + out = out[end+1:] + n++ + } + if n != 8*20*2 { + t.Fatalf("%d units", n) + } +} + +func writePNG(t testing.TB, dir, name string, w, h int) string { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for i := range img.Pix { + img.Pix[i] = byte(i) + } + p := filepath.Join(dir, name) + f, err := os.Create(p) + if err != nil { + t.Fatal(err) + } + if err := png.Encode(f, img); err != nil { + t.Fatal(err) + } + f.Close() + return p +} + +func TestActorLatestWins(t *testing.T) { + dir := t.TempDir() + var decodes atomic.Int32 + decodeHook = func() { decodes.Add(1); time.Sleep(20 * time.Millisecond) } + t.Cleanup(func() { decodeHook = nil }) + var out bytes.Buffer + var mu sync.Mutex + tty := NewSyncWriter(writerFunc(func(p []byte) (int, error) { mu.Lock(); defer mu.Unlock(); return out.Write(p) })) + a := Start(Options{Backend: Kitty, TTY: tty, CellW: 8, CellH: 16}) + defer a.Stop() + + var paths []string + for i := range 5 { + paths = append(paths, writePNG(t, dir, fmt.Sprintf("%d.png", i), 64+i, 32)) + } + t0 := time.Now() + for i := range 100 { + a.Apply(Desired{Visible: true, Rect: Rect{X: 1, Y: 1, W: 10, H: 5}, Gen: uint64(i), + Image: preview.ImageRef{Local: paths[i%5], Size: int64(i)}}) + } + if el := time.Since(t0); el > 50*time.Millisecond { + t.Fatalf("100 Apply took %v: Apply must not block", el) + } + deadline := time.Now().Add(2 * time.Second) + for { + mu.Lock() + got := strings.Count(out.String(), "a=T") + mu.Unlock() + if got > 0 && !a.stale() { + break + } + if time.Now().After(deadline) { + t.Fatal("nothing drawn") + } + time.Sleep(10 * time.Millisecond) + } + time.Sleep(60 * time.Millisecond) + if n := decodes.Load(); n > 2 { + t.Fatalf("%d decodes for 100 Apply calls, want ≤ 2", n) + } +} + +type writerFunc func([]byte) (int, error) + +func (f writerFunc) Write(p []byte) (int, error) { return f(p) } + +// hugePNG writes a valid PNG whose IHDR claims w×h (the pixel data is tiny +// and wrong: a full decode would fail or take ages; DecodeConfig must stop +// first). +func hugePNG(t *testing.T, w, h uint32) string { + var b bytes.Buffer + _ = png.Encode(&b, image.NewGray(image.Rect(0, 0, 1, 1))) + data := b.Bytes() + ihdr := data[8+8 : 8+8+13] // after signature, length and type + binary.BigEndian.PutUint32(ihdr[0:4], w) + binary.BigEndian.PutUint32(ihdr[4:8], h) + crc := crc32.ChecksumIEEE(data[8+4 : 8+8+13]) + binary.BigEndian.PutUint32(data[8+8+13:], crc) + p := filepath.Join(t.TempDir(), "huge.png") + _ = os.WriteFile(p, data, 0o644) + return p +} + +func TestRejectHugeImage(t *testing.T) { + p := hugePNG(t, 10000, 10000) // 100 Mpx + var decodes atomic.Int32 + decodeHook = func() { decodes.Add(1) } + t.Cleanup(func() { decodeHook = nil }) + t0 := time.Now() + _, err := loadScaled(t.Context(), p, 800, 600) + if !errors.Is(err, ErrTooLarge) || decodes.Load() != 0 { + t.Fatalf("err=%v decodes=%d", err, decodes.Load()) + } + if el := time.Since(t0); el > 50*time.Millisecond { + t.Fatalf("took %v", el) + } + // Through the actor the error becomes an event, nothing is drawn. + events := make(chan Event, 4) + var out bytes.Buffer + a := Start(Options{Backend: Kitty, TTY: NewSyncWriter(&out), CellW: 8, CellH: 16, OnEvent: func(e Event) { events <- e }}) + a.Apply(Desired{Visible: true, Rect: Rect{W: 10, H: 5}, Image: preview.ImageRef{Local: p}}) + select { + case e := <-events: + if !errors.Is(e.Err, ErrTooLarge) { + t.Fatalf("event %+v", e) + } + case <-time.After(2 * time.Second): + t.Fatal("no event") + } + a.Stop() + if strings.Contains(out.String(), "a=T") { + t.Fatal("drawn anyway") + } +} + +func TestUeberzugStuckIsKilled(t *testing.T) { + stuck := filepath.Join(t.TempDir(), "ueberzug") + pidFile := stuck + ".pid" + // Never reads stdin; records its pid. + _ = os.WriteFile(stuck, []byte("#!/bin/sh\necho $$ > "+pidFile+"\nexec sleep 60\n"), 0o755) + events := make(chan Event, 8) + a := Start(Options{Backend: Ueberzug, Ueberzug: []string{stuck}, OnEvent: func(e Event) { events <- e }}) + defer a.Stop() + if a.Backend() != Ueberzug { + t.Fatal("did not start") + } + img := writePNG(t, t.TempDir(), "a.png", 4, 4) + // Long paths fill the 64 KiB pipe after a few commands. + longDir := filepath.Join(t.TempDir(), strings.Repeat("d", 200), strings.Repeat("e", 200)) + _ = os.MkdirAll(longDir, 0o755) + long := filepath.Join(longDir, "a.png") + _ = os.Link(img, long) + + start := time.Now() + var disabledAt time.Time + for i := 0; disabledAt.IsZero() && time.Since(start) < 3*time.Second; i++ { + t0 := time.Now() + a.Apply(Desired{Visible: true, Rect: Rect{X: i % 7, W: 10 + i%5, H: 5}, Image: preview.ImageRef{Local: long + strings.Repeat("/.", 0)}}) + if el := time.Since(t0); el > 5*time.Millisecond { + t.Fatalf("Apply blocked for %v", el) + } + select { + case e := <-events: + if e.Disabled && errors.Is(e.Err, ErrStuck) { + disabledAt = time.Now() + } + case <-time.After(2 * time.Millisecond): + } + } + if disabledAt.IsZero() { + t.Fatal("stuck helper never detected") + } + if a.Backend() != None { + t.Fatal("backend not switched off") + } + // The helper is gone. + pid, _ := os.ReadFile(pidFile) + time.Sleep(50 * time.Millisecond) + if _, err := os.Stat("/proc/" + strings.TrimSpace(string(pid))); err == nil { + t.Fatalf("helper %s still running", pid) + } +} + +func TestUeberzugCommands(t *testing.T) { + log := filepath.Join(t.TempDir(), "log") + helper := filepath.Join(t.TempDir(), "uz") + _ = os.WriteFile(helper, []byte("#!/bin/sh\ncat > "+log+"\n"), 0o755) + a := Start(Options{Backend: Ueberzug, Ueberzug: []string{helper}}) + img := writePNG(t, t.TempDir(), "a.png", 4, 4) + a.Apply(Desired{Visible: true, Rect: Rect{X: 3, Y: 2, W: 10, H: 5}, Image: preview.ImageRef{Local: img}}) + time.Sleep(100 * time.Millisecond) + a.Apply(Desired{Visible: false}) + time.Sleep(100 * time.Millisecond) + a.Stop() + b, _ := os.ReadFile(log) + s := string(b) + if !strings.Contains(s, `"action":"add"`) || !strings.Contains(s, `"x":3`) || !strings.Contains(s, `"action":"remove"`) { + t.Fatalf("commands:\n%s", s) + } +} + +func TestKittyBlock(t *testing.T) { + var out bytes.Buffer + k := &kitty{tty: NewSyncWriter(&out)} + img := scaleToFit(image.NewRGBA(image.Rect(0, 0, 100, 100)), 40, 20) + if img.Rect.Dx() != 20 || img.Rect.Dy() != 20 { + t.Fatalf("scaled %v", img.Rect) + } + if err := k.show(img, Rect{X: 4, Y: 2, W: 5, H: 3}); err != nil { + t.Fatal(err) + } + s := out.String() + if !strings.Contains(s, "\x1b7\x1b[3;5H\x1b_Ga=T,f=32,s=20,v=20,") || !strings.HasSuffix(s, "\x1b8") || !strings.Contains(s, "C=1") { + t.Fatalf("block %q", s[:min(120, len(s))]) + } + // Chunked: every APC but the last says m=1. + if strings.Count(s, "m=1") != strings.Count(s, "\x1b_G")-2 { // minus the delete and the last chunk + t.Fatalf("chunks: %d m=1, %d APC", strings.Count(s, "m=1"), strings.Count(s, "\x1b_G")) + } + // File transmission and tmux passthrough. + out.Reset() + tmp := t.TempDir() + k = &kitty{tty: NewSyncWriter(&out), tmpDir: tmp, tmux: true} + if err := k.show(img, Rect{W: 5, H: 3}); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "t=t") || !strings.HasPrefix(out.String(), "\x1bPtmux;\x1b\x1b_G") { + t.Fatalf("tmux/file %q", out.String()[:min(80, out.Len())]) + } + k.stop() + if files, _ := filepath.Glob(filepath.Join(tmp, "*")); len(files) != 0 { + t.Fatalf("temp files after stop: %v", files) + } +} + +func TestDetect(t *testing.T) { + env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } + if Detect("auto", env(map[string]string{"TERM": "xterm-kitty"})) != Kitty { + t.Error("kitty") + } + if Detect("auto", env(map[string]string{"TERM_PROGRAM": "WezTerm"})) != Kitty { + t.Error("wezterm") + } + if Detect("auto", env(map[string]string{"KITTY_WINDOW_ID": "1", "TMUX": "x"})) == Kitty { + t.Error("kitty auto in tmux") + } + if Detect("kitty", env(map[string]string{"TMUX": "x"})) != Kitty || Detect("none", env(nil)) != None { + t.Error("explicit") + } +} + +func BenchmarkKittyPayload6000x4000(b *testing.B) { + dir := b.TempDir() + img := image.NewYCbCr(image.Rect(0, 0, 6000, 4000), image.YCbCrSubsampleRatio420) + for i := range img.Y { + img.Y[i] = byte(i * 7) + } + p := filepath.Join(dir, "photo.jpg") + f, _ := os.Create(p) + _ = jpeg.Encode(f, img, &jpeg.Options{Quality: 85}) + f.Close() + k := &kitty{tty: NewSyncWriter(writerFunc(func(p []byte) (int, error) { return len(p), nil }))} + b.ResetTimer() + for range b.N { + scaled, err := loadScaled(b.Context(), p, 100*8, 40*16) + if err != nil { + b.Fatal(err) + } + if _, err := k.kittyBlock(scaled, Rect{W: 100, H: 40}); err != nil { + b.Fatal(err) + } + } +} + +// Scale + payload only (the stdlib JPEG decoder dominates the benchmark +// above: ~180 of ~200 ms for 24 Mpx). +func BenchmarkKittyPayloadDecoded6000x4000(b *testing.B) { + img := image.NewYCbCr(image.Rect(0, 0, 6000, 4000), image.YCbCrSubsampleRatio420) + k := &kitty{tty: NewSyncWriter(writerFunc(func(p []byte) (int, error) { return len(p), nil }))} + b.ResetTimer() + for range b.N { + if _, err := k.kittyBlock(scaleToFit(img, 800, 640), Rect{W: 100, H: 40}); err != nil { + b.Fatal(err) + } + } +} + +func TestActorRejectsOutOfOrderDesired(t *testing.T) { + a := &Actor{signal: make(chan struct{}, 1)} + a.Apply(Desired{Visible: true, Seq: 2}) + a.Apply(Desired{Visible: false, Seq: 1}) + if !a.want.Visible || a.want.Seq != 2 { + t.Fatalf("older desired state replaced the newer one: %#v", a.want) + } +} diff --git a/internal/imgview/kitty.go b/internal/imgview/kitty.go new file mode 100644 index 0000000..f86348a --- /dev/null +++ b/internal/imgview/kitty.go @@ -0,0 +1,105 @@ +package imgview + +import ( + "encoding/base64" + "fmt" + "image" + "os" + "path/filepath" + "strings" +) + +// kittyImageID identifies vcom's single placement. +const kittyImageID = 31337 + +// kitty draws with the kitty graphics protocol. Each draw is one block +// "ESC 7, CUP, APC…, ESC 8" under the SyncTTY mutex: the cursor does not +// move and the renderer is not disturbed. With a local terminal the pixels +// go through a temp file (t=t), avoiding base64 of megabytes. +type kitty struct { + tty *SyncTTY + tmpDir string // "" → direct transmission + tmux bool + shown bool +} + +// kittyBlock builds the escape sequences for img at rect. +func (k *kitty) kittyBlock(img *image.RGBA, r Rect) ([]byte, error) { + w, h := img.Rect.Dx(), img.Rect.Dy() + ctrl := fmt.Sprintf("a=T,f=32,s=%d,v=%d,i=%d,c=%d,r=%d,C=1,q=2", w, h, kittyImageID, r.W, r.H) + var b strings.Builder + b.WriteString("\x1b7") + fmt.Fprintf(&b, "\x1b[%d;%dH", r.Y+1, r.X+1) + if k.tmpDir != "" { + f, err := os.CreateTemp(k.tmpDir, "tty-graphics-protocol-*.rgba") + if err != nil { + return nil, err + } + _, err = f.Write(img.Pix) + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(f.Name()) + return nil, err + } + // t=t: the terminal reads and deletes the file itself. + b.WriteString(k.apc(ctrl+",t=t", base64.StdEncoding.EncodeToString([]byte(f.Name())))) + } else { + payload := base64.StdEncoding.EncodeToString(img.Pix) + const chunk = 4096 + for i := 0; i < len(payload); i += chunk { + end := min(i+chunk, len(payload)) + more := 0 + if end < len(payload) { + more = 1 + } + c := fmt.Sprintf("m=%d", more) + if i == 0 { + c = ctrl + "," + c + } + b.WriteString(k.apc(c, payload[i:end])) + } + } + b.WriteString("\x1b8") + return []byte(b.String()), nil +} + +// apc wraps one graphics command (in tmux passthrough if needed). +func (k *kitty) apc(ctrl, payload string) string { + s := "\x1b_G" + ctrl + ";" + payload + "\x1b\\" + if k.tmux { + s = "\x1bPtmux;" + strings.ReplaceAll(s, "\x1b", "\x1b\x1b") + "\x1b\\" + } + return s +} + +func (k *kitty) show(img *image.RGBA, r Rect) error { + block, err := k.kittyBlock(img, r) + if err != nil { + return err + } + if err := k.tty.WriteBlock([]byte(k.apc(fmt.Sprintf("a=d,d=I,i=%d,q=2", kittyImageID), "")), block); err != nil { + return err + } + k.shown = true + return nil +} + +func (k *kitty) hide() error { + if !k.shown { + return nil + } + k.shown = false + return k.tty.WriteBlock([]byte(k.apc(fmt.Sprintf("a=d,d=I,i=%d,q=2", kittyImageID), ""))) +} + +func (k *kitty) stop() { + _ = k.hide() + if k.tmpDir != "" { + files, _ := filepath.Glob(filepath.Join(k.tmpDir, "tty-graphics-protocol-*")) + for _, f := range files { + os.Remove(f) + } + } +} diff --git a/internal/imgview/scale.go b/internal/imgview/scale.go new file mode 100644 index 0000000..18774b8 --- /dev/null +++ b/internal/imgview/scale.go @@ -0,0 +1,92 @@ +package imgview + +import ( + "context" + "errors" + "fmt" + "image" + _ "image/gif" // decoders + _ "image/jpeg" + _ "image/png" + "os" + + "golang.org/x/image/draw" + _ "golang.org/x/image/webp" +) + +// MaxPixels: images above this (by DecodeConfig) are refused without a +// full decode. +const MaxPixels = 50_000_000 + +// ErrTooLarge: the image has more than MaxPixels. +var ErrTooLarge = errors.New("image too large to display") + +// decodeHook counts full decodes (tests). +var decodeHook func() + +// loadScaled decodes the file and scales it to fit maxW×maxH pixels +// (keeping the aspect ratio, never enlarging). +func loadScaled(ctx context.Context, path string, maxW, maxH int) (*image.RGBA, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + if _, err := configOf(f); err != nil { + return nil, err + } + if _, err := f.Seek(0, 0); err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + if decodeHook != nil { + decodeHook() + } + src, _, err := image.Decode(f) + if err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + return scaleToFit(src, maxW, maxH), nil +} + +// scaleToFit returns src scaled into maxW×maxH with ApproxBiLinear. +func scaleToFit(src image.Image, maxW, maxH int) *image.RGBA { + b := src.Bounds() + w, h := b.Dx(), b.Dy() + if maxW > 0 && maxH > 0 && (w > maxW || h > maxH) { + if w*maxH > h*maxW { + w, h = maxW, max(1, h*maxW/w) + } else { + w, h = max(1, w*maxH/h), maxH + } + } + dst := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.ApproxBiLinear.Scale(dst, dst.Bounds(), src, b, draw.Src, nil) + return dst +} + +func configOf(f *os.File) (image.Config, error) { + cfg, _, err := image.DecodeConfig(f) + if err != nil { + return cfg, err + } + if int64(cfg.Width)*int64(cfg.Height) > MaxPixels { + return cfg, fmt.Errorf("%w: %dx%d", ErrTooLarge, cfg.Width, cfg.Height) + } + return cfg, nil +} + +// imageConfig reads only the header and enforces MaxPixels. +func imageConfig(path string) (image.Config, error) { + f, err := os.Open(path) + if err != nil { + return image.Config{}, err + } + defer f.Close() + return configOf(f) +} diff --git a/internal/imgview/synctty.go b/internal/imgview/synctty.go new file mode 100644 index 0000000..c86c5f5 --- /dev/null +++ b/internal/imgview/synctty.go @@ -0,0 +1,82 @@ +// Package imgview draws preview images next to the Bubble Tea UI (design +// §5.5) without side effects in View: an actor goroutine takes the latest +// desired state, decodes and scales off the UI goroutine and writes kitty +// graphics (or drives ueberzugpp) through a SyncTTY shared with the +// renderer, so escape sequences never interleave with a frame. +package imgview + +import ( + "io" + "os" + "sync" + + "golang.org/x/sys/unix" +) + +// SyncTTY serialises writes to the terminal. Bubble Tea writes each frame +// with one Write (tea.WithOutput(tty)); image blocks go through WriteBlock +// under the same mutex. It implements term.File (Read, Write, Close, Fd). +type SyncTTY struct { + mu sync.Mutex + w io.Writer + f *os.File +} + +// NewSyncTTY wraps the terminal file. +func NewSyncTTY(f *os.File) *SyncTTY { return &SyncTTY{w: f, f: f} } + +// NewSyncWriter wraps any writer (tests, non-terminal output). +func NewSyncWriter(w io.Writer) *SyncTTY { return &SyncTTY{w: w} } + +func (t *SyncTTY) Write(p []byte) (int, error) { + t.mu.Lock() + defer t.mu.Unlock() + return t.w.Write(p) +} + +// WriteBlock writes several pieces atomically with respect to frames. +func (t *SyncTTY) WriteBlock(parts ...[]byte) error { + t.mu.Lock() + defer t.mu.Unlock() + for _, p := range parts { + if _, err := t.w.Write(p); err != nil { + return err + } + } + return nil +} + +func (t *SyncTTY) Read(p []byte) (int, error) { + if t.f == nil { + return 0, io.EOF + } + return t.f.Read(p) +} + +func (t *SyncTTY) Close() error { + if t.f == nil { + return nil + } + return t.f.Close() +} + +// Fd returns the terminal descriptor (^0 when not a file). +func (t *SyncTTY) Fd() uintptr { + if t.f == nil { + return ^uintptr(0) + } + return t.f.Fd() +} + +// CellSize returns the pixel size of a character cell, if the terminal +// reports it (TIOCGWINSZ ws_xpixel/ws_ypixel). +func (t *SyncTTY) CellSize() (w, h int, ok bool) { + if t.f == nil { + return 0, 0, false + } + ws, err := unix.IoctlGetWinsize(int(t.f.Fd()), unix.TIOCGWINSZ) + if err != nil || ws.Col == 0 || ws.Row == 0 || ws.Xpixel == 0 || ws.Ypixel == 0 { + return 0, 0, false + } + return int(ws.Xpixel) / int(ws.Col), int(ws.Ypixel) / int(ws.Row), true +} diff --git a/internal/imgview/ueberzug.go b/internal/imgview/ueberzug.go new file mode 100644 index 0000000..0ebd069 --- /dev/null +++ b/internal/imgview/ueberzug.go @@ -0,0 +1,83 @@ +package imgview + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "syscall" + "time" +) + +// writeTimeout: a ueberzugpp that does not read its stdin for this long is +// considered stuck and killed (the UI never waits on it). +const writeTimeout = 200 * time.Millisecond + +// ErrStuck: the image helper stopped reading commands. +var ErrStuck = errors.New("image helper is not responding") + +// ueberzug drives `ueberzugpp layer` through JSON lines on its stdin. Writes +// happen on the actor goroutine with a deadline on the pipe. +type ueberzug struct { + cmd *exec.Cmd + w *os.File +} + +func startUeberzug(prog string, args ...string) (*ueberzug, error) { + if len(args) == 0 { + args = []string{"layer", "--silent"} + } + r, w, err := os.Pipe() + if err != nil { + return nil, err + } + cmd := exec.Command(prog, args...) + cmd.Stdin = r + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + r.Close() + w.Close() + return nil, err + } + r.Close() + return &ueberzug{cmd: cmd, w: w}, nil +} + +func (u *ueberzug) send(cmd map[string]any) error { + b, err := json.Marshal(cmd) + if err != nil { + return err + } + b = append(b, '\n') + if err := u.w.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil { + return err + } + if _, err := u.w.Write(b); err != nil { + if errors.Is(err, os.ErrDeadlineExceeded) { + return fmt.Errorf("%w (%v without reading)", ErrStuck, writeTimeout) + } + return err + } + return nil +} + +func (u *ueberzug) show(path string, r Rect) error { + return u.send(map[string]any{ + "action": "add", "identifier": "vcom", "path": path, + "x": r.X, "y": r.Y, "max_width": r.W, "max_height": r.H, "scaler": "fit_contain", + }) +} + +func (u *ueberzug) hide() error { + return u.send(map[string]any{"action": "remove", "identifier": "vcom"}) +} + +// stop kills the helper and its children and reaps it. +func (u *ueberzug) stop() { + _ = u.w.Close() + if u.cmd.Process != nil { + _ = syscall.Kill(-u.cmd.Process.Pid, syscall.SIGKILL) + _ = u.cmd.Wait() + } +} diff --git a/internal/jobs/events.go b/internal/jobs/events.go new file mode 100644 index 0000000..6d85adc --- /dev/null +++ b/internal/jobs/events.go @@ -0,0 +1,105 @@ +package jobs + +import ( + "fmt" + "time" +) + +// ID identifies a job within a Manager. +type ID uint64 + +// Kind names what a job does ("copy", "move", "delete", "trash", "archive", +// "unpack", "mount", "dirsize", "connect", "edit-upload", ...). +type Kind string + +// State of a job. +type State uint8 + +const ( + Queued State = iota + Running // fn is executing + Waiting // blocked in Handle.Ask until the user answers + Done // fn returned nil + Failed // fn returned an error or panicked + Cancelled // cancelled (before start, or fn returned context.Canceled) +) + +func (s State) String() string { + switch s { + case Queued: + return "queued" + case Running: + return "running" + case Waiting: + return "waiting" + case Done: + return "done" + case Failed: + return "failed" + case Cancelled: + return "cancelled" + } + return fmt.Sprintf("State(%d)", uint8(s)) +} + +// Finished reports whether s is terminal. +func (s State) Finished() bool { return s >= Done } + +// Progress is the latest progress a job reported. +type Progress struct { + Phase string + FilesDone int + FilesTotal int + BytesDone int64 + BytesTotal int64 + Current string +} + +// Snapshot is a copy of a job's state. +type Snapshot struct { + ID ID + Kind Kind + Title string + State State + Progress Progress + Started time.Time // when Start was called + Background bool + Result any // what fn returned (e.g. a transfer report), for Done/Failed/Cancelled + Err error // why it Failed or was Cancelled +} + +// Question is something a job asks the user (conflict, item error, host +// key, password, ...). Payload is defined by the job's domain; the UI picks a +// dialog by its type and answers with Manager.Answer(QID, answer). +type Question struct { + Job ID + QID uint64 + Payload any +} + +// Event is delivered to the notify callback given to New. +type Event interface{ isEvent() } + +// Started: a job was accepted (State Queued or Running). +type Started struct{ Snapshot Snapshot } + +// ProgressTick carries the jobs whose progress or state changed since the +// previous tick. At most 10 per second. +type ProgressTick struct{ Snapshots []Snapshot } + +// Asked: a job is waiting for an answer. +type Asked struct{ Question Question } + +// Unasked: a question was withdrawn without an answer (the job or the Ask +// context was cancelled); close its dialog. +type Unasked struct{ Question Question } + +// Finished: a job reached a terminal state. It is the last event for that +// job. +type Finished struct{ Snapshot Snapshot } + +func (Started) isEvent() {} +func (ProgressTick) isEvent() {} +func (Asked) isEvent() {} +func (Unasked) isEvent() {} +func (Finished) isEvent() {} diff --git a/internal/jobs/handle.go b/internal/jobs/handle.go new file mode 100644 index 0000000..f22e3fb --- /dev/null +++ b/internal/jobs/handle.go @@ -0,0 +1,82 @@ +package jobs + +import ( + "context" +) + +// Handle is a job's view of the Manager. It is passed to the job function +// and valid only while it runs. +type Handle struct { + m *Manager + j *job +} + +// ID of the job. +func (h *Handle) ID() ID { return h.j.id } + +// SetProgress records the latest progress. It is O(1), never blocks on the +// UI and may be called as often as wanted: the Manager publishes at most 10 +// ticks per second, each with the last value. +func (h *Handle) SetProgress(p Progress) { + h.m.mu.Lock() + h.j.progress = p + h.j.dirty = true + h.m.mu.Unlock() +} + +// Ask publishes a question and blocks this job's goroutine (State Waiting) +// until Manager.Answer, the job's cancellation or ctx. Other jobs and the +// UI keep running. +func (h *Handle) Ask(ctx context.Context, payload any) (any, error) { + m, j := h.m, h.j + ans := make(chan any, 1) + m.mu.Lock() + m.nextQID++ + q := Question{Job: j.id, QID: m.nextQID, Payload: payload} + m.questions[q.QID] = &pending{q: q, ch: ans, j: j} + j.asking++ + j.state = Waiting + j.dirty = true + m.emitLocked(Asked{Question: q}) + m.mu.Unlock() + + var ( + a any + err error + ) + select { + case a = <-ans: + case <-ctx.Done(): + err = ctx.Err() + case <-j.ctx.Done(): + err = j.ctx.Err() + } + + m.mu.Lock() + if err != nil { + if _, still := m.questions[q.QID]; still { + delete(m.questions, q.QID) + m.emitLocked(Unasked{Question: q}) + } else { + // Answered concurrently with the cancellation: the answer wins + // only if the job itself is not cancelled. + select { + case a = <-ans: + if j.ctx.Err() == nil { + err = nil + } + default: + } + } + } + j.asking-- + if j.asking == 0 && j.state == Waiting { + j.state = Running + j.dirty = true + } + m.mu.Unlock() + if err != nil { + return nil, err + } + return a, nil +} diff --git a/internal/jobs/manager.go b/internal/jobs/manager.go new file mode 100644 index 0000000..64ab514 --- /dev/null +++ b/internal/jobs/manager.go @@ -0,0 +1,436 @@ +// Package jobs runs background operations (copy, delete, archive, connect, +// ...) independently of the UI framework (design §6, D4). +// +// A Manager runs at most maxParallel jobs at once and queues the rest. Jobs +// report progress with Handle.SetProgress ("latest value wins"); the Manager +// publishes changes at most 10 times per second, so a job copying thousands +// of small files never waits for the UI. Questions to the user +// (Handle.Ask) block only the asking job. Every goroutine recovers panics: +// a panicking job ends as Failed instead of taking the process down. +// +// Events reach the notify callback from a single dispatcher goroutine in +// order. notify may block (Bubble Tea's Send does until the program reads +// it); that delays later events but never a job. +package jobs + +import ( + "context" + "errors" + "fmt" + "log/slog" + "runtime/debug" + "sort" + "sync" + "time" +) + +// DefaultMaxParallel is used when New gets maxParallel <= 0. +const DefaultMaxParallel = 2 + +// tickInterval bounds ProgressTick to 10 Hz. +var tickInterval = 100 * time.Millisecond + +// keepFinished is how many finished jobs Snapshot keeps for the job list. +const keepFinished = 100 + +// ErrShutdown is the Err of a job started after Shutdown. +var ErrShutdown = errors.New("job manager is shut down") + +// Releaser is something a job holds while it runs (a connection lease, a +// mounted archive). The Manager calls Release exactly once when the job +// ends, whatever the outcome. +type Releaser interface{ Release() } + +// Func is a job body. It must return soon after ctx is cancelled. +type Func func(ctx context.Context, h *Handle) (result any, err error) + +type job struct { + id ID + kind Kind + title string + state State + progress Progress + dirty bool + started time.Time + background bool + result any + err error + asking int + + fn Func + holds []Releaser + ctx context.Context + cancel context.CancelFunc +} + +type pending struct { + q Question + ch chan any + j *job +} + +// Manager runs jobs. It is safe for concurrent use. +type Manager struct { + notify func(Event) + maxParallel int + + mu sync.Mutex + nextID ID + nextQID uint64 + jobs map[ID]*job + finished []ID // finished job IDs, oldest first + queue []*job + running int // Running or Waiting + questions map[uint64]*pending + shutdown bool + + events []Event + dispatching bool + ticking bool + changed chan struct{} // closed and replaced on every idle-relevant change +} + +// New creates a Manager. notify receives every Event (main forwards them +// with program.Send); nil discards them. +func New(notify func(Event), maxParallel int) *Manager { + if maxParallel <= 0 { + maxParallel = DefaultMaxParallel + } + if notify == nil { + notify = func(Event) {} + } + return &Manager{ + notify: notify, + maxParallel: maxParallel, + jobs: map[ID]*job{}, + questions: map[uint64]*pending{}, + changed: make(chan struct{}), + } +} + +// broadcastLocked wakes Shutdown waiters. +func (m *Manager) broadcastLocked() { + close(m.changed) + m.changed = make(chan struct{}) +} + +// safeGo runs fn in a goroutine that logs and swallows panics. +func safeGo(what string, fn func()) { + go func() { + defer func() { + if r := recover(); r != nil { + slog.Error("jobs: panic", "in", what, "panic", r, "stack", string(debug.Stack())) + } + }() + fn() + }() +} + +// emitLocked queues e for the dispatcher; m.mu is held. +func (m *Manager) emitLocked(e Event) { + m.events = append(m.events, e) + if !m.dispatching { + m.dispatching = true + safeGo("dispatch", m.dispatch) + } +} + +func (m *Manager) dispatch() { + defer func() { + // notify panicked: keep delivering on a fresh goroutine. + if r := recover(); r != nil { + slog.Error("jobs: notify panicked", "panic", r, "stack", string(debug.Stack())) + m.mu.Lock() + m.dispatching = false + if len(m.events) > 0 { + m.dispatching = true + safeGo("dispatch", m.dispatch) + } + m.broadcastLocked() + m.mu.Unlock() + } + }() + for { + m.mu.Lock() + if len(m.events) == 0 { + m.dispatching = false + m.broadcastLocked() + m.mu.Unlock() + return + } + batch := m.events + m.events = nil + m.mu.Unlock() + for i, e := range batch { + func() { + defer func() { + if r := recover(); r != nil { + m.mu.Lock() + m.events = append(batch[i+1:len(batch):len(batch)], m.events...) + m.mu.Unlock() + panic(r) + } + }() + m.notify(e) + }() + } + } +} + +func (j *job) snapshot() Snapshot { + return Snapshot{ + ID: j.id, Kind: j.kind, Title: j.title, State: j.state, Progress: j.progress, + Started: j.started, Background: j.background, Result: j.result, Err: j.err, + } +} + +// Start queues a job and returns its ID. holds are released when the job +// ends (also when it is cancelled before running, or started after +// Shutdown). +func (m *Manager) Start(k Kind, title string, fn Func, holds ...Releaser) ID { + ctx, cancel := context.WithCancel(context.Background()) + m.mu.Lock() + defer m.mu.Unlock() + m.nextID++ + j := &job{ + id: m.nextID, kind: k, title: title, state: Queued, started: time.Now(), + fn: fn, holds: holds, ctx: ctx, cancel: cancel, + } + m.jobs[j.id] = j + if m.shutdown { + m.emitLocked(Started{Snapshot: j.snapshot()}) + m.finishLocked(j, Cancelled, nil, ErrShutdown) + return j.id + } + m.queue = append(m.queue, j) + m.scheduleLocked() + m.emitLocked(Started{Snapshot: j.snapshot()}) + return j.id +} + +// scheduleLocked starts queued jobs while slots are free. +func (m *Manager) scheduleLocked() { + for m.running < m.maxParallel && len(m.queue) > 0 { + j := m.queue[0] + m.queue = m.queue[1:] + m.running++ + j.state = Running + j.dirty = true + m.startTickerLocked() + safeGo("job", func() { m.run(j) }) + } +} + +func (m *Manager) run(j *job) { + var ( + res any + err error + ) + func() { + defer func() { + if r := recover(); r != nil { + slog.Error("jobs: job panicked", "job", j.id, "kind", j.kind, "panic", r, "stack", string(debug.Stack())) + err = fmt.Errorf("job %q panicked: %v", j.title, r) + res = nil + } + }() + res, err = j.fn(j.ctx, &Handle{m: m, j: j}) + }() + state := Done + switch { + case err == nil: + case errors.Is(err, context.Canceled): + state = Cancelled + default: + state = Failed + } + m.mu.Lock() + defer m.mu.Unlock() + m.running-- + m.finishLocked(j, state, res, err) + m.scheduleLocked() +} + +// finishLocked moves j to a terminal state, releases its holds and emits +// Finished. +func (m *Manager) finishLocked(j *job, s State, res any, err error) { + j.state, j.result, j.err, j.dirty = s, res, err, false + j.cancel() + for qid, p := range m.questions { + if p.j == j { + delete(m.questions, qid) + m.emitLocked(Unasked{Question: p.q}) + } + } + for _, h := range j.holds { + release(h) + } + j.holds = nil + j.fn = nil + m.emitLocked(Finished{Snapshot: j.snapshot()}) + m.finished = append(m.finished, j.id) + if len(m.finished) > keepFinished { + delete(m.jobs, m.finished[0]) + m.finished = m.finished[1:] + } + m.broadcastLocked() +} + +func release(h Releaser) { + defer func() { + if r := recover(); r != nil { + slog.Error("jobs: Release panicked", "panic", r, "stack", string(debug.Stack())) + } + }() + h.Release() +} + +// startTickerLocked runs the progress ticker while jobs are active. +func (m *Manager) startTickerLocked() { + if m.ticking { + return + } + m.ticking = true + safeGo("ticker", m.tick) +} + +func (m *Manager) tick() { + t := time.NewTicker(tickInterval) + defer t.Stop() + for range t.C { + m.mu.Lock() + var snaps []Snapshot + for _, j := range m.jobs { + if j.dirty && !j.state.Finished() { + j.dirty = false + snaps = append(snaps, j.snapshot()) + } + } + if len(snaps) > 0 { + sort.Slice(snaps, func(a, b int) bool { return snaps[a].ID < snaps[b].ID }) + m.emitLocked(ProgressTick{Snapshots: snaps}) + } + if m.running == 0 && len(m.queue) == 0 { + m.ticking = false + m.broadcastLocked() + m.mu.Unlock() + return + } + m.mu.Unlock() + } +} + +// Answer delivers the user's answer to question qid. Unknown or already +// withdrawn questions are ignored. +func (m *Manager) Answer(qid uint64, answer any) { + m.mu.Lock() + defer m.mu.Unlock() + p := m.questions[qid] + if p == nil { + return + } + delete(m.questions, qid) + p.ch <- answer // buffered, never blocks +} + +// Cancel cancels a job: a queued job ends at once as Cancelled, a running +// one gets its ctx cancelled (and any pending Ask returns). +func (m *Manager) Cancel(id ID) { + m.mu.Lock() + defer m.mu.Unlock() + j := m.jobs[id] + if j == nil || j.state.Finished() { + return + } + if j.state == Queued { + m.dequeueLocked(j) + m.finishLocked(j, Cancelled, nil, context.Canceled) + return + } + j.cancel() +} + +func (m *Manager) dequeueLocked(j *job) { + for i, q := range m.queue { + if q == j { + m.queue = append(m.queue[:i], m.queue[i+1:]...) + return + } + } +} + +// SetBackground marks a job as running in the background (the UI closes its +// progress dialog). +func (m *Manager) SetBackground(id ID, bg bool) { + m.mu.Lock() + defer m.mu.Unlock() + if j := m.jobs[id]; j != nil && j.background != bg { + j.background = bg + if !j.state.Finished() { + j.dirty = true + } + } +} + +// Snapshot returns all known jobs (active and the last finished ones) by ID. +func (m *Manager) Snapshot() []Snapshot { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]Snapshot, 0, len(m.jobs)) + for _, j := range m.jobs { + out = append(out, j.snapshot()) + } + sort.Slice(out, func(a, b int) bool { return out[a].ID < out[b].ID }) + return out +} + +// Get returns one job's snapshot. +func (m *Manager) Get(id ID) (Snapshot, bool) { + m.mu.Lock() + defer m.mu.Unlock() + j := m.jobs[id] + if j == nil { + return Snapshot{}, false + } + return j.snapshot(), true +} + +// Active counts queued, running and waiting jobs. +func (m *Manager) Active() int { + m.mu.Lock() + defer m.mu.Unlock() + return m.running + len(m.queue) +} + +// Shutdown cancels every job, refuses new ones and waits until running jobs +// have returned (so they can remove temp files) and all events have been +// delivered, or until ctx is done. +func (m *Manager) Shutdown(ctx context.Context) error { + m.mu.Lock() + m.shutdown = true + for len(m.queue) > 0 { + j := m.queue[0] + m.queue = m.queue[1:] + m.finishLocked(j, Cancelled, nil, context.Canceled) + } + for _, j := range m.jobs { + if !j.state.Finished() { + j.cancel() + } + } + m.mu.Unlock() + for { + m.mu.Lock() + idle := m.running == 0 && !m.dispatching && !m.ticking + ch := m.changed + m.mu.Unlock() + if idle { + return nil + } + select { + case <-ch: + case <-ctx.Done(): + return ctx.Err() + } + } +} diff --git a/internal/jobs/manager_test.go b/internal/jobs/manager_test.go new file mode 100644 index 0000000..b2fc9a8 --- /dev/null +++ b/internal/jobs/manager_test.go @@ -0,0 +1,447 @@ +package jobs + +import ( + "context" + "errors" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// noLeak runs fn as a subtest and checks the goroutine count returns to the +// baseline afterwards. +func noLeak(t *testing.T, fn func(t *testing.T)) { + t.Helper() + runtime.GC() + base := runtime.NumGoroutine() + t.Run("body", fn) + deadline := time.Now().Add(3 * time.Second) + var n int + for time.Now().Before(deadline) { + if n = runtime.NumGoroutine(); n <= base { + return + } + time.Sleep(10 * time.Millisecond) + } + buf := make([]byte, 1<<20) + t.Errorf("goroutines: base=%d after=%d\n%s", base, n, buf[:runtime.Stack(buf, true)]) +} + +// recorder collects events. +type recorder struct { + mu sync.Mutex + ev []Event + at []time.Time +} + +func (r *recorder) notify(e Event) { + r.mu.Lock() + r.ev = append(r.ev, e) + r.at = append(r.at, time.Now()) + r.mu.Unlock() +} + +func (r *recorder) events() []Event { + r.mu.Lock() + defer r.mu.Unlock() + return append([]Event(nil), r.ev...) +} + +func (r *recorder) finished(id ID) (Snapshot, bool) { + for _, e := range r.events() { + if f, ok := e.(Finished); ok && f.Snapshot.ID == id { + return f.Snapshot, true + } + } + return Snapshot{}, false +} + +func (r *recorder) asked() []Question { + var qs []Question + for _, e := range r.events() { + if a, ok := e.(Asked); ok { + qs = append(qs, a.Question) + } + } + return qs +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(time.Millisecond) + } +} + +func shutdown(t *testing.T, m *Manager) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := m.Shutdown(ctx); err != nil { + t.Fatalf("Shutdown: %v", err) + } +} + +type hold struct{ n atomic.Int32 } + +func (h *hold) Release() { h.n.Add(1) } + +// U section 2: progress went through a 256-slot channel with a full View per +// file. 100k SetProgress must neither slow the job down (even if nobody +// reads events) nor produce more than ~10 ticks per second. +func TestProgressCoalesced(t *testing.T) { + t.Run("NoReader", func(t *testing.T) { + noLeak(t, func(t *testing.T) { + unblock := make(chan struct{}) + m := New(func(Event) { <-unblock }, 2) // like an unread program.Send + done := make(chan time.Duration, 1) + m.Start("copy", "fast", func(ctx context.Context, h *Handle) (any, error) { + start := time.Now() + for i := 0; i < 100_000; i++ { + h.SetProgress(Progress{FilesDone: i, BytesDone: int64(i) * 10}) + } + done <- time.Since(start) + return nil, nil + }) + select { + case el := <-done: + if el > 100*time.Millisecond { + t.Errorf("100k SetProgress took %v", el) + } + case <-time.After(time.Second): + t.Fatal("job blocked by an unread notify") + } + waitFor(t, "job finished", func() bool { return m.Active() == 0 }) + close(unblock) + shutdown(t, m) + }) + }) + t.Run("TickRate", func(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 2) + id := m.Start("copy", "steady", func(ctx context.Context, h *Handle) (any, error) { + end := time.Now().Add(time.Second) + for i := 0; time.Now().Before(end); i++ { + h.SetProgress(Progress{FilesDone: i}) + if i%100 == 0 { + runtime.Gosched() + } + } + h.SetProgress(Progress{FilesDone: -1, Phase: "final"}) + return "ok", nil + }) + waitFor(t, "finished", func() bool { _, ok := rec.finished(id); return ok }) + shutdown(t, m) + ticks := 0 + for _, e := range rec.events() { + if _, ok := e.(ProgressTick); ok { + ticks++ + } + } + if ticks > 11 || ticks < 5 { + t.Errorf("%d ticks in ~1s, want 5..11", ticks) + } + // Finished is last for the job and carries the final progress. + evs := rec.events() + f, ok := evs[len(evs)-1].(Finished) + if !ok || f.Snapshot.Progress.Phase != "final" || f.Snapshot.State != Done || f.Snapshot.Result != "ok" { + t.Errorf("last event = %#v", evs[len(evs)-1]) + } + }) + }) +} + +func TestAskBlocksOnlyJob(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 2) + got := make(chan any, 1) + asker := m.Start("copy", "asker", func(ctx context.Context, h *Handle) (any, error) { + a, err := h.Ask(ctx, "overwrite?") + got <- a + return a, err + }) + waitFor(t, "question", func() bool { return len(rec.asked()) == 1 }) + if s, _ := m.Get(asker); s.State != Waiting { + t.Errorf("asker state = %v", s.State) + } + other := m.Start("delete", "other", func(ctx context.Context, h *Handle) (any, error) { return 42, nil }) + waitFor(t, "other job done while asker waits", func() bool { _, ok := rec.finished(other); return ok }) + if m.Active() != 1 { + t.Errorf("Active = %d", m.Active()) + } + q := rec.asked()[0] + if q.Job != asker || q.Payload != "overwrite?" { + t.Errorf("question = %+v", q) + } + m.Answer(q.QID, "yes") + m.Answer(q.QID, "again") // ignored + if a := <-got; a != "yes" { + t.Errorf("answer = %v", a) + } + waitFor(t, "asker done", func() bool { _, ok := rec.finished(asker); return ok }) + if s, _ := rec.finished(asker); s.State != Done || s.Result != "yes" { + t.Errorf("asker = %+v", s) + } + shutdown(t, m) + }) +} + +func TestCancelWhileWaiting(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 2) + h1 := &hold{} + askErr := make(chan error, 1) + id := m.Start("copy", "c", func(ctx context.Context, h *Handle) (any, error) { + _, err := h.Ask(ctx, "conflict") + askErr <- err + return nil, err + }, h1) + waitFor(t, "question", func() bool { return len(rec.asked()) == 1 }) + m.Cancel(id) + select { + case err := <-askErr: + if !errors.Is(err, context.Canceled) { + t.Errorf("Ask err = %v", err) + } + case <-time.After(time.Second): + t.Fatal("Ask not released by Cancel") + } + waitFor(t, "finished", func() bool { _, ok := rec.finished(id); return ok }) + s, _ := rec.finished(id) + if s.State != Cancelled || h1.n.Load() != 1 { + t.Errorf("state %v, releases %d", s.State, h1.n.Load()) + } + unasked := false + for _, e := range rec.events() { + if u, ok := e.(Unasked); ok && u.Question.QID == rec.asked()[0].QID { + unasked = true + } + } + if !unasked { + t.Error("no Unasked event") + } + m.Answer(rec.asked()[0].QID, "late") // no-op, must not block or panic + + // The Ask ctx alone withdraws the question; the job continues. + ctx, cancel := context.WithCancel(context.Background()) + id2 := m.Start("copy", "c2", func(_ context.Context, h *Handle) (any, error) { + _, err := h.Ask(ctx, "q") + return "continued after " + err.Error(), nil + }) + waitFor(t, "second question", func() bool { return len(rec.asked()) == 2 }) + cancel() + waitFor(t, "second finished", func() bool { _, ok := rec.finished(id2); return ok }) + if s, _ := rec.finished(id2); s.State != Done { + t.Errorf("job after Ask ctx cancel = %+v", s) + } + shutdown(t, m) + }) +} + +func TestPanicBecomesFailed(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 1) + h1 := &hold{} + id := m.Start("copy", "boom", func(ctx context.Context, h *Handle) (any, error) { + var p *Progress + _ = p.Phase // nil dereference + return nil, nil + }, h1) + next := m.Start("copy", "next", func(ctx context.Context, h *Handle) (any, error) { return nil, nil }) + waitFor(t, "both finished", func() bool { + _, a := rec.finished(id) + _, b := rec.finished(next) + return a && b + }) + s, _ := rec.finished(id) + if s.State != Failed || s.Err == nil || !strings.Contains(s.Err.Error(), "panicked") || h1.n.Load() != 1 { + t.Errorf("panicking job = %+v, releases %d", s, h1.n.Load()) + } + if s, _ := rec.finished(next); s.State != Done { + t.Errorf("next job = %+v", s) + } + // A panicking notify does not stop event delivery. + var calls atomic.Int32 + m2 := New(func(e Event) { + if calls.Add(1) == 1 { + panic("ui bug") + } + }, 1) + m2.Start("copy", "x", func(ctx context.Context, h *Handle) (any, error) { return nil, nil }) + waitFor(t, "events after notify panic", func() bool { return calls.Load() >= 2 }) + shutdown(t, m2) + shutdown(t, m) + }) +} + +func TestHoldsReleasedOnAllPaths(t *testing.T) { + noLeak(t, func(t *testing.T) { + m := New(nil, 1) + var holds []*hold + h := func() *hold { x := &hold{}; holds = append(holds, x); return x } + block := make(chan struct{}) + m.Start("copy", "ok", func(ctx context.Context, _ *Handle) (any, error) { return nil, nil }, h(), h()) + m.Start("copy", "err", func(ctx context.Context, _ *Handle) (any, error) { return nil, errors.New("x") }, h()) + m.Start("copy", "panic", func(ctx context.Context, _ *Handle) (any, error) { panic("p") }, h()) + running := m.Start("copy", "cancel-running", func(ctx context.Context, _ *Handle) (any, error) { + close(block) + <-ctx.Done() + return nil, ctx.Err() + }, h()) + queued := m.Start("copy", "cancel-queued", func(ctx context.Context, _ *Handle) (any, error) { return nil, nil }, h()) + <-block + m.Cancel(queued) + m.Cancel(running) + m.Start("copy", "on-shutdown-queue", func(ctx context.Context, _ *Handle) (any, error) { + <-ctx.Done() + return nil, ctx.Err() + }, h()) + shutdown(t, m) + after := m.Start("copy", "after-shutdown", func(ctx context.Context, _ *Handle) (any, error) { + t.Error("job ran after Shutdown") + return nil, nil + }, h()) + if s, _ := m.Get(after); s.State != Cancelled || !errors.Is(s.Err, ErrShutdown) { + t.Errorf("after shutdown: %+v", s) + } + for i, x := range holds { + if n := x.n.Load(); n != 1 { + t.Errorf("hold %d released %d times", i, n) + } + } + want := map[string]State{"ok": Done, "err": Failed, "panic": Failed, "cancel-running": Cancelled, + "cancel-queued": Cancelled, "on-shutdown-queue": Cancelled, "after-shutdown": Cancelled} + for _, s := range m.Snapshot() { + if s.State != want[s.Title] { + t.Errorf("%s: state %v, want %v", s.Title, s.State, want[s.Title]) + } + } + }) +} + +// U section 3: "Transfer is already running" — now jobs queue. +func TestQueueRespectsMaxParallel(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 2) + var cur, peak atomic.Int32 + var mu sync.Mutex + var order []int + var ids []ID + for i := 0; i < 6; i++ { + ids = append(ids, m.Start("copy", "j", func(ctx context.Context, _ *Handle) (any, error) { + mu.Lock() + order = append(order, i) + mu.Unlock() + n := cur.Add(1) + for { + p := peak.Load() + if n <= p || peak.CompareAndSwap(p, n) { + break + } + } + time.Sleep(20 * time.Millisecond) + cur.Add(-1) + return nil, nil + })) + } + if s, _ := m.Get(ids[5]); s.State != Queued { + t.Errorf("6th job state = %v, want queued", s.State) + } + waitFor(t, "all done", func() bool { return m.Active() == 0 }) + shutdown(t, m) + if p := peak.Load(); p != 2 { + t.Errorf("peak parallel = %d, want 2", p) + } + if order[0] > 1 || order[5] < 4 { + t.Errorf("not FIFO: %v", order) + } + for _, id := range ids { + if s, ok := rec.finished(id); !ok || s.State != Done { + t.Errorf("job %d: %+v", id, s) + } + } + }) +} + +func TestShutdownWaitsCleanup(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 2) + var cleaned atomic.Bool + id := m.Start("copy", "c", func(ctx context.Context, _ *Handle) (any, error) { + <-ctx.Done() + time.Sleep(100 * time.Millisecond) // remove temp files + cleaned.Store(true) + return nil, ctx.Err() + }) + waitFor(t, "running", func() bool { s, _ := m.Get(id); return s.State == Running }) + shutdown(t, m) + if !cleaned.Load() { + t.Error("Shutdown returned before the job cleaned up") + } + if _, ok := rec.finished(id); !ok { + t.Error("Finished not delivered before Shutdown returned") + } + + // A job ignoring cancellation: Shutdown gives up at the deadline. + m2 := New(nil, 1) + release := make(chan struct{}) + m2.Start("copy", "stubborn", func(ctx context.Context, _ *Handle) (any, error) { + <-release + return nil, nil + }) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + start := time.Now() + if err := m2.Shutdown(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("Shutdown = %v", err) + } + if el := time.Since(start); el > 500*time.Millisecond { + t.Errorf("Shutdown waited %v", el) + } + close(release) + shutdown(t, m2) + }) +} + +func TestBackgroundAndSnapshot(t *testing.T) { + noLeak(t, func(t *testing.T) { + var rec recorder + m := New(rec.notify, 1) + stop := make(chan struct{}) + id := m.Start("copy", "bg", func(ctx context.Context, h *Handle) (any, error) { + <-stop + return nil, nil + }) + m.SetBackground(id, true) + waitFor(t, "tick with background flag", func() bool { + for _, e := range rec.events() { + if pt, ok := e.(ProgressTick); ok { + for _, s := range pt.Snapshots { + if s.ID == id && s.Background && s.State == Running { + return true + } + } + } + } + return false + }) + close(stop) + shutdown(t, m) + if snaps := m.Snapshot(); len(snaps) != 1 || !snaps[0].Background || snaps[0].State != Done { + t.Errorf("snapshot = %+v", snaps) + } + }) +} diff --git a/internal/logx/logx.go b/internal/logx/logx.go new file mode 100644 index 0000000..d8c42f4 --- /dev/null +++ b/internal/logx/logx.go @@ -0,0 +1,151 @@ +// Package logx sets up vcom's log (design §9.3): log/slog text records in +// $XDG_STATE_HOME/vcom/vcom.log (file 0600, directory 0700), level from +// --log-level / --debug / $VCOM_LOG (default warn), one rotation on start when +// the file exceeds 5 MiB. Secrets (password, passphrase, keyboard-interactive +// answers) are redacted by attribute name and never reach the file. +package logx + +import ( + "context" + "fmt" + "io" + "log" + "log/slog" + "os" + "path/filepath" + "strings" +) + +// MaxSize is the size above which the log is rotated to vcom.log.1 on start. +const MaxSize = 5 << 20 + +// FileName is the log file name inside the state directory. +const FileName = "vcom.log" + +// Options configure Open. +type Options struct { + Dir string // state directory; created 0700 + Level slog.Level // minimum level written +} + +// Logger is an open log file with its slog logger. +type Logger struct { + *slog.Logger + Path string + file *os.File +} + +// Close flushes and closes the file. Safe on nil. +func (l *Logger) Close() error { + if l == nil || l.file == nil { + return nil + } + return l.file.Close() +} + +// ParseLevel accepts debug | info | warn | warning | error (any case). +func ParseLevel(s string) (slog.Level, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "debug": + return slog.LevelDebug, nil + case "info": + return slog.LevelInfo, nil + case "", "warn", "warning": + return slog.LevelWarn, nil + case "error": + return slog.LevelError, nil + } + return slog.LevelWarn, fmt.Errorf("unknown log level %q (want debug, info, warn or error)", s) +} + +// ResolveLevel picks the level: --debug, then --log-level, then $VCOM_LOG, +// then warn. +func ResolveLevel(debug bool, flagLevel, env string) (slog.Level, error) { + switch { + case debug: + return slog.LevelDebug, nil + case flagLevel != "": + return ParseLevel(flagLevel) + default: + return ParseLevel(env) + } +} + +// Open rotates and opens the log file and returns a logger writing to it. +func Open(o Options) (*Logger, error) { + if err := os.MkdirAll(o.Dir, 0o700); err != nil { + return nil, err + } + _ = os.Chmod(o.Dir, 0o700) + p := filepath.Join(o.Dir, FileName) + if err := rotate(p); err != nil { + return nil, err + } + f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) + if err != nil { + return nil, err + } + if err := f.Chmod(0o600); err != nil { // an older file may have been 0644 + f.Close() + return nil, err + } + return &Logger{Logger: slog.New(NewHandler(f, o.Level)), Path: p, file: f}, nil +} + +// rotate moves p to p.1 (replacing an older .1) when p exceeds MaxSize. +func rotate(p string) error { + fi, err := os.Stat(p) + if err != nil || fi.Size() <= MaxSize { + return nil + } + return os.Rename(p, p+".1") +} + +// secretKeys are attribute names whose values are never logged. +var secretKeys = map[string]bool{ + "password": true, + "passphrase": true, + "answers": true, + "answer": true, + "secret": true, + "token": true, +} + +// Redacted replaces secret values. +const Redacted = "[REDACTED]" + +// NewHandler returns a text handler at level that redacts secrets. +func NewHandler(w io.Writer, level slog.Level) slog.Handler { + return slog.NewTextHandler(w, &slog.HandlerOptions{ + Level: level, + ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { + if secretKeys[strings.ToLower(a.Key)] { + return slog.String(a.Key, Redacted) + } + return a + }, + }) +} + +// Discard is a logger that drops everything (when the log file cannot be +// opened). +func Discard() *Logger { + return &Logger{Logger: slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError + 100}))} +} + +// RedirectStdLog sends the standard "log" package (the old UI's 178 +// log.Printf calls) to l at debug level. +func RedirectStdLog(l *slog.Logger) { + log.SetFlags(0) + log.SetPrefix("") + log.SetOutput(stdWriter{l}) +} + +type stdWriter struct{ l *slog.Logger } + +func (w stdWriter) Write(b []byte) (int, error) { + if w.l.Enabled(context.Background(), slog.LevelDebug) { + w.l.Debug(strings.TrimRight(string(b), "\n"), "src", "ui") + } + return len(b), nil +} diff --git a/internal/logx/logx_test.go b/internal/logx/logx_test.go new file mode 100644 index 0000000..0eb6896 --- /dev/null +++ b/internal/logx/logx_test.go @@ -0,0 +1,132 @@ +package logx + +import ( + "bytes" + "log" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestRotateOver5MiB(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, FileName) + big := bytes.Repeat([]byte("x"), MaxSize+1) + if err := os.WriteFile(p, big, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p+".1", []byte("older"), 0o600); err != nil { + t.Fatal(err) + } + l, err := Open(Options{Dir: dir, Level: slog.LevelInfo}) + if err != nil { + t.Fatal(err) + } + l.Info("fresh") + l.Close() + if fi, err := os.Stat(p + ".1"); err != nil || fi.Size() != MaxSize+1 { + t.Fatalf("rotated file: %v %v", fi, err) + } + if b, _ := os.ReadFile(p); !strings.Contains(string(b), "fresh") || len(b) > 1000 { + t.Fatalf("new log: %d bytes", len(b)) + } + + // At or under the limit: appended, not rotated. + small := filepath.Join(t.TempDir(), FileName) + if err := os.WriteFile(small, []byte("keep\n"), 0o600); err != nil { + t.Fatal(err) + } + l, err = Open(Options{Dir: filepath.Dir(small), Level: slog.LevelInfo}) + if err != nil { + t.Fatal(err) + } + l.Info("more") + l.Close() + if b, _ := os.ReadFile(small); !strings.HasPrefix(string(b), "keep\n") { + t.Fatalf("small log not appended: %q", b) + } + if _, err := os.Stat(small + ".1"); !os.IsNotExist(err) { + t.Fatal("small log rotated") + } +} + +func TestLogFilePerms(t *testing.T) { + dir := filepath.Join(t.TempDir(), "state", "vcom") + l, err := Open(Options{Dir: dir, Level: slog.LevelWarn}) + if err != nil { + t.Fatal(err) + } + l.Close() + if fi, _ := os.Stat(dir); fi.Mode().Perm() != 0o700 { + t.Fatalf("dir mode %v", fi.Mode().Perm()) + } + if fi, _ := os.Stat(filepath.Join(dir, FileName)); fi.Mode().Perm() != 0o600 { + t.Fatalf("file mode %v", fi.Mode().Perm()) + } + // An existing world-readable log is tightened. + p := filepath.Join(dir, FileName) + if err := os.Chmod(p, 0o644); err != nil { + t.Fatal(err) + } + l, err = Open(Options{Dir: dir}) + if err != nil { + t.Fatal(err) + } + l.Close() + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 { + t.Fatalf("existing file mode %v", fi.Mode().Perm()) + } +} + +func TestRedactSecrets(t *testing.T) { + var buf bytes.Buffer + l := slog.New(NewHandler(&buf, slog.LevelDebug)) + l.Info("auth", "user", "bob", "password", "hunter2", "Passphrase", "s3cret-pp", + slog.Group("ki", slog.Any("answers", []string{"123456"}))) + l.With("password", "withpw").Debug("again") + out := buf.String() + for _, secret := range []string{"hunter2", "s3cret-pp", "123456", "withpw"} { + if strings.Contains(out, secret) { + t.Fatalf("secret %q leaked:\n%s", secret, out) + } + } + if !strings.Contains(out, "user=bob") || strings.Count(out, Redacted) != 4 { + t.Fatalf("output:\n%s", out) + } +} + +func TestLevelsAndStdLog(t *testing.T) { + cases := []struct { + debug bool + flag, env string + want slog.Level + wantErr bool + }{ + {false, "", "", slog.LevelWarn, false}, + {true, "error", "info", slog.LevelDebug, false}, + {false, "error", "debug", slog.LevelError, false}, + {false, "", "INFO", slog.LevelInfo, false}, + {false, "loud", "", slog.LevelWarn, true}, + } + for _, c := range cases { + got, err := ResolveLevel(c.debug, c.flag, c.env) + if got != c.want || (err != nil) != c.wantErr { + t.Errorf("%+v: got %v %v", c, got, err) + } + } + + var buf bytes.Buffer + defer log.SetOutput(os.Stderr) + RedirectStdLog(slog.New(NewHandler(&buf, slog.LevelWarn))) + log.Printf("[KEY] j") + if buf.Len() != 0 { + t.Fatalf("old log.Printf must be debug-only: %q", buf.String()) + } + RedirectStdLog(slog.New(NewHandler(&buf, slog.LevelDebug))) + log.Printf("[KEY] j") + if !strings.Contains(buf.String(), "level=DEBUG") || !strings.Contains(buf.String(), "[KEY] j") { + t.Fatalf("debug: %q", buf.String()) + } +} diff --git a/internal/paths/paths.go b/internal/paths/paths.go new file mode 100644 index 0000000..0cd6db1 --- /dev/null +++ b/internal/paths/paths.go @@ -0,0 +1,317 @@ +// Package paths decides where vcom reads and writes its files (design §9.1). +// +// - Config: -config PATH → $VCOM_CONFIG → $XDG_CONFIG_HOME/vcom/vcom.toml → +// ~/.config/vcom/vcom.toml. Never ./vcom.toml from the working directory. +// - State (session.toml, vcom.log): $XDG_STATE_HOME/vcom. +// - Cache and per-process temp files: $XDG_CACHE_HOME/vcom/run- (0700); +// run dirs of dead processes are swept on start (U-P1-15). +// - sudo: config and ~/.ssh are READ from the invoking user's home; state, +// cache, trash and known_hosts are WRITTEN only under the effective user's +// home, and inherited XDG_*_HOME variables are ignored for writing, so root +// never leaves files in ~user. +package paths + +import ( + "errors" + "fmt" + "io/fs" + "os" + "os/user" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +// system is the process environment; tests replace it. +type system struct { + getenv func(string) string + geteuid func() int + getpid func() int + getwd func() (string, error) + homeOfUser func(name string) (string, error) // home of a user name + homeOfUID func(uid int) (string, error) + alive func(pid int) bool +} + +var sys = osSystem() + +func osSystem() system { + return system{ + getenv: os.Getenv, + geteuid: os.Geteuid, + getpid: os.Getpid, + getwd: os.Getwd, + homeOfUser: func(name string) (string, error) { + u, err := user.Lookup(name) + if err != nil { + return "", err + } + return u.HomeDir, nil + }, + homeOfUID: func(uid int) (string, error) { + u, err := user.LookupId(strconv.Itoa(uid)) + if err != nil { + return "", err + } + return u.HomeDir, nil + }, + alive: pidAlive, + } +} + +// pidAlive: signal 0 succeeds or fails with EPERM for a live process. +func pidAlive(pid int) bool { + err := syscall.Kill(pid, 0) + return err == nil || errors.Is(err, syscall.EPERM) +} + +// SudoUser returns the invoking user's name when running as root via sudo. +func SudoUser() (string, bool) { + if sys.geteuid() != 0 { + return "", false + } + u := sys.getenv("SUDO_USER") + if u == "" || u == "root" { + return "", false + } + return u, true +} + +func envHome() (string, error) { + if h := sys.getenv("HOME"); h != "" { + return h, nil + } + if h, err := sys.homeOfUID(sys.geteuid()); err == nil && h != "" { + return h, nil + } + return "", errors.New("cannot determine home directory") +} + +// ReadHome is the home to read user configuration from (vcom.toml, ~/.ssh): +// the invoking user's home under sudo, $HOME otherwise. +func ReadHome() (string, error) { + if name, ok := SudoUser(); ok { + if h, err := sys.homeOfUser(name); err == nil && h != "" { + return h, nil + } + } + return envHome() +} + +// WriteHome is the home vcom may write under: the effective user's. +func WriteHome() (string, error) { + if _, ok := SudoUser(); ok { + h, err := sys.homeOfUID(sys.geteuid()) + if err != nil { + return "", fmt.Errorf("home of uid %d: %w", sys.geteuid(), err) + } + return h, nil + } + return envHome() +} + +// xdgWrite returns $env (if absolute and not under sudo) or WriteHome/def. +func xdgWrite(env string, def ...string) (string, error) { + if _, sudo := SudoUser(); !sudo { + if d := sys.getenv(env); filepath.IsAbs(d) { + return d, nil + } + } + h, err := WriteHome() + if err != nil { + return "", err + } + return filepath.Join(append([]string{h}, def...)...), nil +} + +// configHome is the directory holding vcom/ for reading. +func configHome() (string, error) { + if d := sys.getenv("XDG_CONFIG_HOME"); filepath.IsAbs(d) { + return d, nil + } + h, err := ReadHome() + if err != nil { + return "", err + } + return filepath.Join(h, ".config"), nil +} + +// ConfigFile resolves the config path. explicit is the -config flag. found +// reports whether the file exists; when it does not, path is where SetKey +// would create it (DefaultConfigFile), or explicit/$VCOM_CONFIG if given. +// The working directory is never consulted (see StrayCwdConfig). +func ConfigFile(explicit string) (path string, found bool, err error) { + for _, p := range []string{explicit, sys.getenv("VCOM_CONFIG")} { + if p == "" { + continue + } + abs, err := filepath.Abs(p) + if err != nil { + return "", false, err + } + ok, err := exists(abs) + return abs, ok, err + } + var candidates []string + if d, err := configHome(); err == nil { + candidates = append(candidates, filepath.Join(d, "vcom", "vcom.toml")) + } + if h, err := ReadHome(); err == nil { + candidates = append(candidates, filepath.Join(h, ".config", "vcom", "vcom.toml")) + } + if _, sudo := SudoUser(); sudo { + if h, err := WriteHome(); err == nil { + candidates = append(candidates, filepath.Join(h, ".config", "vcom", "vcom.toml")) + } + } + for _, c := range candidates { + ok, err := exists(c) + if err != nil { + return "", false, err + } + if ok { + return c, true, nil + } + } + def, err := DefaultConfigFile() + return def, false, err +} + +// DefaultConfigFile is where a new config file is created: $VCOM_CONFIG if +// set (the file every start reads; QA-15), else the XDG file. Under sudo it +// is the effective user's, so root does not create files in ~user. +func DefaultConfigFile() (string, error) { + if p := sys.getenv("VCOM_CONFIG"); p != "" { + return filepath.Abs(p) + } + if _, sudo := SudoUser(); sudo { + d, err := xdgWrite("XDG_CONFIG_HOME", ".config") + if err != nil { + return "", err + } + return filepath.Join(d, "vcom", "vcom.toml"), nil + } + d, err := configHome() + if err != nil { + return "", err + } + return filepath.Join(d, "vcom", "vcom.toml"), nil +} + +// StrayCwdConfig returns ./vcom.toml (or ./config/vcom.toml) when it exists: +// older versions loaded it; now it is only worth a hint in the log when no +// real config was found. +func StrayCwdConfig() (string, bool) { + wd, err := sys.getwd() + if err != nil { + return "", false + } + for _, c := range []string{filepath.Join(wd, "vcom.toml"), filepath.Join(wd, "config", "vcom.toml")} { + if ok, _ := exists(c); ok { + return c, true + } + } + return "", false +} + +// OldSessionFile is the pre-0.3 session location (next to the config), read +// once for migration. +func OldSessionFile() (string, error) { + d, err := configHome() + if err != nil { + return "", err + } + return filepath.Join(d, "vcom", "session.toml"), nil +} + +// StateDir is $XDG_STATE_HOME/vcom (effective user). It is not created. +func StateDir() (string, error) { + d, err := xdgWrite("XDG_STATE_HOME", ".local", "state") + if err != nil { + return "", err + } + return filepath.Join(d, "vcom"), nil +} + +// CacheDir is $XDG_CACHE_HOME/vcom (effective user). It is not created. +func CacheDir() (string, error) { + d, err := xdgWrite("XDG_CACHE_HOME", ".cache") + if err != nil { + return "", err + } + return filepath.Join(d, "vcom"), nil +} + +// DataHome is $XDG_DATA_HOME (effective user), e.g. for the trash. +func DataHome() (string, error) { return xdgWrite("XDG_DATA_HOME", ".local", "share") } + +// EnsureDir creates d and missing parents with mode 0700. +func EnsureDir(d string) error { return os.MkdirAll(d, 0o700) } + +// CreateRunDir sweeps run dirs of dead processes from CacheDir and creates +// CacheDir/run- (0700) for this process. The caller removes it on exit +// (RemoveRunDir). +func CreateRunDir() (string, error) { + cache, err := CacheDir() + if err != nil { + return "", err + } + if err := EnsureDir(cache); err != nil { + return "", err + } + SweepRunDirs(cache) + d := filepath.Join(cache, "run-"+strconv.Itoa(sys.getpid())) + if err := os.Mkdir(d, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { + return "", err + } + if err := os.Chmod(d, 0o700); err != nil { + return "", err + } + return d, nil +} + +// SweepRunDirs removes cache/run- directories whose process is gone +// (left behind by kill -9 or a crash). It returns what it removed. +func SweepRunDirs(cache string) []string { + ents, err := os.ReadDir(cache) + if err != nil { + return nil + } + var removed []string + self := sys.getpid() + for _, e := range ents { + rest, ok := strings.CutPrefix(e.Name(), "run-") + if !ok || !e.IsDir() { + continue + } + pid, err := strconv.Atoi(rest) + if err != nil || pid <= 0 || pid == self || sys.alive(pid) { + continue + } + p := filepath.Join(cache, e.Name()) + if os.RemoveAll(p) == nil { + removed = append(removed, p) + } + } + return removed +} + +// RemoveRunDir deletes this process's run dir (teardown). +func RemoveRunDir(d string) error { + if d == "" || !strings.HasPrefix(filepath.Base(d), "run-") { + return fmt.Errorf("refusing to remove %q: not a run dir", d) + } + return os.RemoveAll(d) +} + +func exists(p string) (bool, error) { + _, err := os.Stat(p) + if err == nil { + return true, nil + } + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) { + return false, nil + } + return false, err +} diff --git a/internal/paths/paths_test.go b/internal/paths/paths_test.go new file mode 100644 index 0000000..efb127e --- /dev/null +++ b/internal/paths/paths_test.go @@ -0,0 +1,182 @@ +package paths + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "testing" +) + +// fake installs a fake system for one test. +func fake(t *testing.T, env map[string]string, euid int, homes map[string]string) { + t.Helper() + orig := sys + t.Cleanup(func() { sys = orig }) + sys.getenv = func(k string) string { return env[k] } + sys.geteuid = func() int { return euid } + sys.homeOfUser = func(name string) (string, error) { + if h, ok := homes[name]; ok { + return h, nil + } + return "", errors.New("no such user") + } + sys.homeOfUID = func(uid int) (string, error) { + if h, ok := homes["uid:"+strconv.Itoa(uid)]; ok { + return h, nil + } + return "", errors.New("no such uid") + } +} + +func write(t *testing.T, p string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("[ui]\n"), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestConfigLookupIgnoresCwd(t *testing.T) { + home := t.TempDir() + cwd := t.TempDir() + write(t, filepath.Join(cwd, "vcom.toml")) + write(t, filepath.Join(cwd, "config", "vcom.toml")) + t.Chdir(cwd) + fake(t, map[string]string{"HOME": home}, 1000, nil) + + p, found, err := ConfigFile("") + if err != nil { + t.Fatal(err) + } + if found { + t.Fatalf("found %s: the working directory must not be searched", p) + } + if want := filepath.Join(home, ".config", "vcom", "vcom.toml"); p != want { + t.Fatalf("default path %s, want %s", p, want) + } + if stray, ok := StrayCwdConfig(); !ok || stray != filepath.Join(cwd, "vcom.toml") { + t.Fatalf("stray = %q %v", stray, ok) + } + + // The real XDG file is found; explicit and $VCOM_CONFIG win in that order. + write(t, filepath.Join(home, ".config", "vcom", "vcom.toml")) + if p, found, _ := ConfigFile(""); !found || p != filepath.Join(home, ".config", "vcom", "vcom.toml") { + t.Fatalf("home config: %s %v", p, found) + } + xdg := filepath.Join(home, "xdg") + write(t, filepath.Join(xdg, "vcom", "vcom.toml")) + env := map[string]string{"HOME": home, "XDG_CONFIG_HOME": xdg} + fake(t, env, 1000, nil) + if p, _, _ := ConfigFile(""); p != filepath.Join(xdg, "vcom", "vcom.toml") { + t.Fatalf("XDG_CONFIG_HOME not preferred: %s", p) + } + env["VCOM_CONFIG"] = filepath.Join(home, "env.toml") + if p, found, _ := ConfigFile(""); found || p != env["VCOM_CONFIG"] { + t.Fatalf("VCOM_CONFIG: %s %v", p, found) + } + if p, _, _ := ConfigFile("rel.toml"); p != filepath.Join(cwd, "rel.toml") { + t.Fatalf("explicit relative path: %s", p) + } +} + +func TestSudoWritePathsEffectiveUser(t *testing.T) { + tmp := t.TempDir() + bob, root := filepath.Join(tmp, "bob"), filepath.Join(tmp, "root") + write(t, filepath.Join(bob, ".config", "vcom", "vcom.toml")) + // sudo -E keeps bob's HOME and XDG variables. + env := map[string]string{ + "HOME": bob, + "SUDO_USER": "bob", + "XDG_STATE_HOME": filepath.Join(bob, ".local", "state"), + "XDG_CACHE_HOME": filepath.Join(bob, ".cache"), + "XDG_DATA_HOME": filepath.Join(bob, ".local", "share"), + "XDG_CONFIG_HOME": filepath.Join(bob, ".config"), + } + fake(t, env, 0, map[string]string{"bob": bob, "uid:0": root}) + + if p, found, _ := ConfigFile(""); !found || p != filepath.Join(bob, ".config", "vcom", "vcom.toml") { + t.Fatalf("config must be read from the invoking user: %s %v", p, found) + } + if h, _ := ReadHome(); h != bob { + t.Fatalf("ReadHome = %s", h) + } + checks := map[string]func() (string, error){ + filepath.Join(root, ".local", "state", "vcom"): StateDir, + filepath.Join(root, ".cache", "vcom"): CacheDir, + filepath.Join(root, ".local", "share"): DataHome, + filepath.Join(root, ".config", "vcom", "vcom.toml"): DefaultConfigFile, + root: WriteHome, + } + for want, f := range checks { + if got, err := f(); err != nil || got != want { + t.Errorf("got %s (%v), want %s", got, err, want) + } + } + + // Without sudo the XDG variables are honoured. + delete(env, "SUDO_USER") + fake(t, env, 1000, nil) + if d, _ := StateDir(); d != filepath.Join(bob, ".local", "state", "vcom") { + t.Fatalf("StateDir = %s", d) + } + // sudo with SUDO_USER=root (sudo -s from root) is not "sudo". + env["SUDO_USER"] = "root" + fake(t, env, 0, nil) + if _, ok := SudoUser(); ok { + t.Fatal("SUDO_USER=root must not count") + } +} + +func TestRunDirSweepDeadPID(t *testing.T) { + cacheHome := t.TempDir() + fake(t, map[string]string{"HOME": t.TempDir(), "XDG_CACHE_HOME": cacheHome}, 1000, nil) + sys.getpid = func() int { return 4242 } + sys.alive = func(pid int) bool { return pid == 222 } + cache := filepath.Join(cacheHome, "vcom") + for _, d := range []string{"run-111", "run-222", "run-abc", "keep"} { + write(t, filepath.Join(cache, d, "junk")) + } + + d, err := CreateRunDir() + if err != nil { + t.Fatal(err) + } + if d != filepath.Join(cache, "run-4242") { + t.Fatalf("run dir %s", d) + } + if fi, err := os.Stat(d); err != nil || fi.Mode().Perm() != 0o700 { + t.Fatalf("run dir mode: %v %v", fi, err) + } + for name, want := range map[string]bool{"run-111": false, "run-222": true, "run-abc": true, "keep": true} { + _, err := os.Stat(filepath.Join(cache, name)) + if (err == nil) != want { + t.Errorf("%s exists=%v, want %v", name, err == nil, want) + } + } + if err := RemoveRunDir(d); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(d); !os.IsNotExist(err) { + t.Fatal("run dir not removed") + } + if err := RemoveRunDir(cache); err == nil { + t.Fatal("RemoveRunDir must refuse a non-run dir") + } +} + +func TestPidAlive(t *testing.T) { + if !pidAlive(os.Getpid()) { + t.Fatal("self not alive") + } +} + +func TestDefaultConfigFileHonoursVCOMConfig(t *testing.T) { + home := t.TempDir() + fake(t, map[string]string{"HOME": home, "VCOM_CONFIG": filepath.Join(home, "custom", "v.toml")}, 1000, nil) + if p, _ := DefaultConfigFile(); p != filepath.Join(home, "custom", "v.toml") { + t.Fatalf("DefaultConfigFile = %s (QA-15)", p) + } +} diff --git a/internal/preview/build.go b/internal/preview/build.go new file mode 100644 index 0000000..8ec6cbc --- /dev/null +++ b/internal/preview/build.go @@ -0,0 +1,284 @@ +// Package preview builds the content shown for a selected entry (design +// §5.4): a pure Build(ctx, req) over vfs — no global state, no Bubble Tea. +// Non-regular files are never opened (U-P1-10); external tools run with a +// timeout and are killed with their children; text is highlighted by a +// chroma formatter that emits foreground SGR only, capped at MaxLines. +package preview + +import ( + "bytes" + "context" + "errors" + "fmt" + "image" + _ "image/gif" // DecodeConfig formats + _ "image/jpeg" + _ "image/png" + "io" + "io/fs" + "path" + "strings" + "time" + "unicode/utf8" + + "vcom/internal/vfs" +) + +// Kind of a preview. +type Kind uint8 + +const ( + Empty Kind = iota + Directory + Text + Image + PDF + Audio + Video + Binary + Special + Error +) + +func (k Kind) String() string { + return [...]string{"empty", "directory", "text", "image", "pdf", "audio", "video", "binary", "special", "error"}[k] +} + +// Metadata shown next to the preview. +type Metadata struct { + Path string + Label string // KindLabel: "directory", "go", "fifo", ... + Size int64 + Mode fs.FileMode + ModTime time.Time + LinkTarget string + + ImageFormat string + Width, Height int + + Duration, Bitrate, AudioCodec, VideoCodec, SampleRate, Channels, Dimensions string + PageCount string +} + +// ImageRef is what imgview needs to draw an image; it decodes the file +// itself, off the UI goroutine. +type ImageRef struct { + Loc vfs.Location + Size int64 + ModTime time.Time + Format string + Width, Height int + // Local is a local file with the image: the file itself for a local FS, + // a cached download for a remote one; "" when not available. + Local string + // TooLarge: a remote image above MaxRemoteImageBytes is not downloaded. + TooLarge bool +} + +// Request describes what to preview. +type Request struct { + Loc vfs.Location + Info vfs.FileInfo // Lstat of Loc; zero → Build does the Lstat + + MaxBytes int64 // bytes read for text (default 64 KiB) + MaxLines int // text lines kept (default 3000) + // HighlightLines: how many of the first lines are highlighted (default + // 400 — the chroma lexer costs ~2 ms per 1 KiB); the rest is plain. The + // viewer asks for more (up to MaxLines) when the user scrolls. + HighlightLines int + DirLimit int // directory entries kept (default 80) + ShowHidden bool // directory preview + Theme string + + Tools *Tools // external utilities; nil → none + Images *ImageCache // remote image downloads; nil → no downloads + MaxRemoteImageBytes int64 // default 20 MiB +} + +// Result of Build. +type Result struct { + Kind Kind + Meta Metadata + Lines []string // highlighted (foreground SGR only), one per screen line, no wrapping + Plain []string // the same lines without SGR (caret, yank) + Dir []vfs.FileInfo + Image *ImageRef + Truncated bool + // Highlighted is the number of leading Lines that carry highlighting. + Highlighted int + Err error +} + +const ( + defaultMaxBytes = 64 << 10 + defaultMaxLines = 3000 + defaultDirLimit = 80 + defaultMaxRemote = 20 << 20 +) + +func (r *Request) defaults() { + if r.MaxBytes <= 0 { + r.MaxBytes = defaultMaxBytes + } + if r.MaxLines <= 0 { + r.MaxLines = defaultMaxLines + } + if r.HighlightLines <= 0 { + r.HighlightLines = 400 + } + if r.HighlightLines > r.MaxLines { + r.HighlightLines = r.MaxLines + } + if r.DirLimit <= 0 { + r.DirLimit = defaultDirLimit + } + if r.MaxRemoteImageBytes <= 0 { + r.MaxRemoteImageBytes = defaultMaxRemote + } +} + +// Build makes the preview. It honours ctx everywhere it waits (reads, +// tools, highlighting) and returns Kind=Error with Err on failure. +func Build(ctx context.Context, req Request) Result { + req.defaults() + fsys, p := req.Loc.FS, req.Loc.Path + res := Result{Meta: Metadata{Path: p}} + fail := func(err error) Result { + res.Kind, res.Err = Error, err + return res + } + if err := ctx.Err(); err != nil { + return fail(err) + } + fi := req.Info + if fi.Name == "" { + var err error + if fi, err = fsys.Lstat(ctx, p); err != nil { + return fail(err) + } + } + res.Meta.Label = KindLabel(fi) + res.Meta.Size, res.Meta.Mode, res.Meta.ModTime = fi.Size, fi.Mode, fi.ModTime + eff := fi + if fi.IsSymlink() { + res.Meta.LinkTarget, _ = fsys.ReadLink(ctx, p) + if fi.Target == nil { + res.Kind = Special + if fi.LinkErr != nil { + res.Err = fmt.Errorf("broken symlink: %w", fi.LinkErr) + } + return res + } + eff = *fi.Target + } + + switch { + case eff.IsDir(): + return buildDir(ctx, req, res) + case !eff.Mode.IsRegular(): + res.Kind = Special // FIFO, socket, device: never opened (U-P1-10) + return res + case eff.Size == 0: + res.Kind = Empty + return res + } + + head, truncated, err := readHead(ctx, fsys, p, req.MaxBytes) + if err != nil { + return fail(err) + } + if cfg, format, err := image.DecodeConfig(bytes.NewReader(head)); err == nil { + return buildImage(ctx, req, res, eff, format, cfg) + } + ext := strings.ToLower(path.Ext(p)) + switch { + case ext == ".pdf": + return buildPDF(ctx, req, res) + case audioExts[ext]: + return buildMedia(ctx, req, res, Audio) + case videoExts[ext]: + return buildMedia(ctx, req, res, Video) + } + if isBinary(head) { + res.Kind = Binary + return res + } + res.Kind, res.Truncated = Text, truncated + return highlightInto(ctx, req, res, path.Base(p), string(head)) +} + +// readHead reads at most max bytes (and reports whether there was more). +func readHead(ctx context.Context, fsys vfs.FS, p string, max int64) ([]byte, bool, error) { + f, err := fsys.Open(ctx, p) + if err != nil { + return nil, false, err + } + defer f.Close() + stop := context.AfterFunc(ctx, func() { f.Close() }) + defer stop() + buf := make([]byte, max+1) + n, err := io.ReadFull(f, buf) + if ctx.Err() != nil { + return nil, false, ctx.Err() + } + if err != nil && err != io.EOF && !errors.Is(err, io.ErrUnexpectedEOF) { + return nil, false, err + } + if int64(n) > max { + return buf[:max], true, nil + } + return buf[:n], false, nil +} + +// isBinary: a NUL byte or mostly invalid UTF-8 in the sample. +func isBinary(b []byte) bool { + if bytes.IndexByte(b, 0) >= 0 { + return true + } + if len(b) > 4 { + b = b[:len(b)-4] // a rune may be cut at the end of the sample + } + bad := 0 + for len(b) > 0 { + r, n := utf8.DecodeRune(b) + if r == utf8.RuneError && n == 1 { + bad++ + } + b = b[n:] + } + return bad > 8 +} + +// KindLabel names an entry for the metadata line: "directory", "symlink", +// "fifo", "socket", "device", the lower-case extension ("go", "tar.gz"), or +// "file" (U-P2: the old label was inverted). +func KindLabel(fi vfs.FileInfo) string { + m := fi.Mode + switch { + case m.IsDir(): + return "directory" + case m&fs.ModeSymlink != 0: + return "symlink" + case m&fs.ModeNamedPipe != 0: + return "fifo" + case m&fs.ModeSocket != 0: + return "socket" + case m&fs.ModeDevice != 0: + return "device" + } + name := strings.ToLower(fi.Name) + if strings.HasSuffix(name, ".tar.gz") && len(name) > 7 { + return "tar.gz" + } + ext := path.Ext(name) + if ext == "" || ext == name { + return "file" + } + return ext[1:] +} + +var audioExts = map[string]bool{".mp3": true, ".flac": true, ".wav": true, ".ogg": true, ".m4a": true, + ".aac": true, ".opus": true, ".wma": true} + +var videoExts = map[string]bool{".mp4": true, ".mkv": true, ".webm": true, ".avi": true, ".mov": true, + ".wmv": true, ".flv": true, ".m4v": true} diff --git a/internal/preview/cache.go b/internal/preview/cache.go new file mode 100644 index 0000000..29fd5a4 --- /dev/null +++ b/internal/preview/cache.go @@ -0,0 +1,229 @@ +package preview + +import ( + "container/list" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "path" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "vcom/internal/vfs" +) + +// ImageCache keeps downloaded remote images in a local directory, keyed by +// (volume, path, size, mtime), evicting least recently used files above a +// total size budget (default 200 MiB). +type ImageCache struct { + dir string + max int64 + + mu sync.Mutex + lru *list.List // of *cached, front = most recent + byKey map[string]*list.Element + total int64 +} + +type cached struct { + key string + path string + size int64 +} + +// NewImageCache uses dir (created 0700). Files already there are kept up to +// the budget (oldest removed first), so the cache survives restarts. +func NewImageCache(dir string, maxBytes int64) (*ImageCache, error) { + if maxBytes <= 0 { + maxBytes = 200 << 20 + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + c := &ImageCache{dir: dir, max: maxBytes, lru: list.New(), byKey: map[string]*list.Element{}} + ents, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + type old struct { + name string + size int64 + mt time.Time + } + var files []old + for _, e := range ents { + fi, err := e.Info() + if err != nil || !fi.Mode().IsRegular() { + continue + } + if strings.HasPrefix(e.Name(), ".tmp-") { // an interrupted download + _ = os.Remove(filepath.Join(dir, e.Name())) + continue + } + files = append(files, old{e.Name(), fi.Size(), fi.ModTime()}) + } + sort.Slice(files, func(i, j int) bool { return files[i].mt.After(files[j].mt) }) + for _, f := range files { + c.add(strings.TrimSuffix(f.name, path.Ext(f.name)), filepath.Join(dir, f.name), f.size) + } + c.evict() + return c, nil +} + +func cacheKey(vol vfs.VolumeID, p string, size int64, mt time.Time) string { + h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d\x00%d", vol, p, size, mt.UnixNano()))) + return hex.EncodeToString(h[:16]) +} + +// add appends at the back (least recent): used while loading. +func (c *ImageCache) add(key, p string, size int64) { + c.byKey[key] = c.lru.PushBack(&cached{key: key, path: p, size: size}) + c.total += size +} + +func (c *ImageCache) evict() { + for c.total > c.max && c.lru.Len() > 1 { + e := c.lru.Back() + it := e.Value.(*cached) + c.lru.Remove(e) + delete(c.byKey, it.key) + c.total -= it.size + _ = os.Remove(it.path) + } +} + +// Fetch returns a local copy of p on fsys, downloading it if needed. +func (c *ImageCache) Fetch(ctx context.Context, fsys vfs.FS, p string, size int64, mt time.Time) (string, error) { + key := cacheKey(fsys.Volume(), p, size, mt) + c.mu.Lock() + if e, ok := c.byKey[key]; ok { + c.lru.MoveToFront(e) + lp := e.Value.(*cached).path + c.mu.Unlock() + return lp, nil + } + c.mu.Unlock() + + src, err := fsys.Open(ctx, p) + if err != nil { + return "", err + } + defer src.Close() + tmp, err := os.CreateTemp(c.dir, ".tmp-*") + if err != nil { + return "", err + } + n, err := io.Copy(tmp, &ctxRead{ctx: ctx, r: io.LimitReader(src, size+1)}) + if cerr := tmp.Close(); err == nil { + err = cerr + } + if err == nil && n != size { + err = fmt.Errorf("%s changed while downloading (%d of %d bytes)", p, n, size) + } + final := filepath.Join(c.dir, key+strings.ToLower(path.Ext(p))) + if err == nil { + err = os.Rename(tmp.Name(), final) + } + if err != nil { + _ = os.Remove(tmp.Name()) + return "", err + } + c.mu.Lock() + defer c.mu.Unlock() + if _, ok := c.byKey[key]; !ok { + c.byKey[key] = c.lru.PushFront(&cached{key: key, path: final, size: n}) + c.total += n + c.evict() + } + return final, nil +} + +type ctxRead struct { + ctx context.Context + r io.Reader +} + +func (c *ctxRead) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + return c.r.Read(p) +} + +// Cache keeps the last results (default 32) by (volume, path, size, mtime, +// theme, limits), so moving the cursor back and forth does not rebuild. +type Cache struct { + mu sync.Mutex + max int + lru *list.List + byKey map[resultKey]*list.Element +} + +type resultKey struct { + vol vfs.VolumeID + path string + size int64 + mtime int64 + theme string + maxBytes int64 + maxLines, dirLimit int + highlight int + hidden bool +} + +type resultEntry struct { + key resultKey + res Result +} + +// NewCache returns a result cache with room for max results (≤ 0 → 32). +func NewCache(max int) *Cache { + if max <= 0 { + max = 32 + } + return &Cache{max: max, lru: list.New(), byKey: map[resultKey]*list.Element{}} +} + +// Build returns a cached result or builds and caches it. Errors and +// cancelled builds are not cached. +func (c *Cache) Build(ctx context.Context, req Request) Result { + req.defaults() + if req.Info.Name == "" { + fi, err := req.Loc.FS.Lstat(ctx, req.Loc.Path) + if err != nil { + return Result{Kind: Error, Err: err, Meta: Metadata{Path: req.Loc.Path}} + } + req.Info = fi + } + k := resultKey{req.Loc.FS.Volume(), req.Loc.Path, req.Info.Size, req.Info.ModTime.UnixNano(), req.Theme, + req.MaxBytes, req.MaxLines, req.DirLimit, req.HighlightLines, req.ShowHidden} + c.mu.Lock() + if e, ok := c.byKey[k]; ok { + c.lru.MoveToFront(e) + r := e.Value.(*resultEntry).res + c.mu.Unlock() + return r + } + c.mu.Unlock() + r := Build(ctx, req) + if r.Err != nil || r.Kind == Error { + return r + } + c.mu.Lock() + defer c.mu.Unlock() + if _, ok := c.byKey[k]; !ok { + c.byKey[k] = c.lru.PushFront(&resultEntry{key: k, res: r}) + for c.lru.Len() > c.max { + e := c.lru.Back() + c.lru.Remove(e) + delete(c.byKey, e.Value.(*resultEntry).key) + } + } + return r +} diff --git a/internal/preview/dir.go b/internal/preview/dir.go new file mode 100644 index 0000000..fba6d5f --- /dev/null +++ b/internal/preview/dir.go @@ -0,0 +1,39 @@ +package preview + +import ( + "context" + "sort" + "strings" + + "vcom/internal/vfs" +) + +// buildDir lists a directory, keeping at most DirLimit entries (dirs first, +// then by name). Hidden entries are dropped unless ShowHidden. +func buildDir(ctx context.Context, req Request, res Result) Result { + ents, err := req.Loc.FS.ReadDir(ctx, req.Loc.Path) + if err != nil { + res.Kind, res.Err = Error, err + return res + } + kept := ents[:0] + for _, e := range ents { + if req.ShowHidden || !strings.HasPrefix(e.Name, ".") { + kept = append(kept, e) + } + } + sort.Slice(kept, func(i, j int) bool { + di, dj := kept[i].NavigableDir(), kept[j].NavigableDir() + if di != dj { + return di + } + return strings.ToLower(kept[i].Name) < strings.ToLower(kept[j].Name) + }) + res.Kind = Directory + if len(kept) > req.DirLimit { + kept, res.Truncated = kept[:req.DirLimit], true + } + res.Dir = make([]vfs.FileInfo, len(kept)) // do not pin the full listing + copy(res.Dir, kept) + return res +} diff --git a/internal/preview/highlight.go b/internal/preview/highlight.go new file mode 100644 index 0000000..9b7069b --- /dev/null +++ b/internal/preview/highlight.go @@ -0,0 +1,109 @@ +package preview + +import ( + "context" + "fmt" + "strings" + + "github.com/alecthomas/chroma/v2" + "github.com/alecthomas/chroma/v2/lexers" + "github.com/alecthomas/chroma/v2/styles" + + "vcom/internal/theme" +) + +// highlightInto fills Lines/Plain for text. The formatter writes SGR for +// foreground colour, bold, italic and underline only — never a background +// (no post-processing regexps). ctx is checked every 256 tokens. +func highlightInto(ctx context.Context, req Request, res Result, name, src string) Result { + plain, cut := textLines(src, req.MaxLines) + res.Plain = plain + res.Truncated = res.Truncated || cut + n := min(req.HighlightLines, len(plain)) + lines, err := Highlight(ctx, name, strings.Join(plain[:n], "\n"), req.Theme) + if err != nil { + res.Kind, res.Err = Error, err + res.Lines, res.Plain = nil, nil + return res + } + if len(lines) != n { + lines, n = plain[:n], 0 // a lexer that changed the text: show it plain + } + res.Lines = make([]string, 0, len(plain)) + res.Lines = append(append(res.Lines, lines...), plain[n:]...) + res.Highlighted = n + return res +} + +// Highlight returns src (already normalised: LF, no tabs) as highlighted +// lines for the given vcom theme. +func Highlight(ctx context.Context, name, src, themeName string) ([]string, error) { + lexer := lexers.Match(name) + if lexer == nil { + lexer = lexers.Analyse(src) + } + if lexer == nil { + return strings.Split(src, "\n"), nil + } + lexer = chroma.Coalesce(lexer) + style := styles.Get(theme.ChromaStyle(themeName)) + it, err := lexer.Tokenise(nil, src) + if err != nil { + return nil, err + } + sgr := map[chroma.TokenType]string{} + var lines []string + var cur strings.Builder + n := 0 + for tok := it(); tok != chroma.EOF; tok = it() { + if n++; n&255 == 0 { + if err := ctx.Err(); err != nil { + return nil, err + } + } + code, ok := sgr[tok.Type] + if !ok { + code = sgrFor(style.Get(tok.Type)) + sgr[tok.Type] = code + } + for i, seg := range strings.Split(tok.Value, "\n") { + if i > 0 { + lines = append(lines, cur.String()) + cur.Reset() + } + if seg == "" { + continue + } + if code != "" { + cur.WriteString(code) + cur.WriteString(seg) + cur.WriteString("\x1b[0m") + } else { + cur.WriteString(seg) + } + } + } + lines = append(lines, cur.String()) + return lines, nil +} + +// sgrFor renders a style entry as a foreground-only SGR sequence. +func sgrFor(e chroma.StyleEntry) string { + var parts []string + if e.Bold == chroma.Yes { + parts = append(parts, "1") + } + if e.Italic == chroma.Yes { + parts = append(parts, "3") + } + if e.Underline == chroma.Yes { + parts = append(parts, "4") + } + if e.Colour.IsSet() { + parts = append(parts, fmt.Sprintf("38;2;%d;%d;%d", e.Colour.Red(), e.Colour.Green(), e.Colour.Blue())) + } + if len(parts) == 0 { + return "" + } + return "\x1b[" + strings.Join(parts, ";") + "m" +} diff --git a/internal/preview/image.go b/internal/preview/image.go new file mode 100644 index 0000000..059a754 --- /dev/null +++ b/internal/preview/image.go @@ -0,0 +1,30 @@ +package preview + +import ( + "context" + "image" + + "vcom/internal/vfs" +) + +// buildImage reports format and size; imgview decodes later. A remote image +// is downloaded to the cache only up to MaxRemoteImageBytes (N-P1-16). +func buildImage(ctx context.Context, req Request, res Result, fi vfs.FileInfo, format string, cfg image.Config) Result { + res.Kind = Image + res.Meta.ImageFormat, res.Meta.Width, res.Meta.Height = format, cfg.Width, cfg.Height + ref := &ImageRef{Loc: req.Loc, Size: fi.Size, ModTime: fi.ModTime, Format: format, Width: cfg.Width, Height: cfg.Height} + res.Image = ref + switch { + case req.Loc.FS.Kind() == vfs.KindLocal: + ref.Local = req.Loc.Path + case fi.Size > req.MaxRemoteImageBytes: + ref.TooLarge = true + case req.Images != nil: + p, err := req.Images.Fetch(ctx, req.Loc.FS, req.Loc.Path, fi.Size, fi.ModTime) + if err != nil { + res.Err = err + } + ref.Local = p + } + return res +} diff --git a/internal/preview/media.go b/internal/preview/media.go new file mode 100644 index 0000000..6082328 --- /dev/null +++ b/internal/preview/media.go @@ -0,0 +1,150 @@ +package preview + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + + "vcom/internal/vfs" +) + +// localPath returns the path tools can read, or "" for a non-local FS. +func localPath(req Request) string { + if req.Loc.FS.Kind() == vfs.KindLocal { + return req.Loc.Path + } + return "" +} + +func message(res Result, k Kind, lines ...string) Result { + res.Kind, res.Lines, res.Plain = k, lines, lines + return res +} + +// buildPDF: the text of the first 3 pages via pdftotext, page count via +// pdfinfo. +func buildPDF(ctx context.Context, req Request, res Result) Result { + lp := localPath(req) + switch { + case lp == "": + return message(res, PDF, "PDF on a remote file system: text preview is not available.") + case req.Tools == nil || req.Tools.PdfToText == "": + return message(res, PDF, "PDF file. Install poppler-utils (pdftotext) for a text preview.") + } + out, err := req.Tools.run(ctx, req.MaxBytes, req.Tools.PdfToText, "-l", "3", "-layout", "-nopgbrk", lp, "-") + if err != nil { + res.Kind, res.Err = Error, err + return res + } + if req.Tools.PdfInfo != "" { + if info, err := req.Tools.run(ctx, 64<<10, req.Tools.PdfInfo, lp); err == nil { + for _, line := range strings.Split(string(info), "\n") { + if v, ok := strings.CutPrefix(line, "Pages:"); ok { + res.Meta.PageCount = strings.TrimSpace(v) + } + } + } + } + res.Kind = PDF + res.Plain, res.Truncated = textLines(string(out), req.MaxLines) + res.Lines = res.Plain + return res +} + +// buildMedia: duration, bitrate, codecs via ffprobe. +func buildMedia(ctx context.Context, req Request, res Result, k Kind) Result { + lp := localPath(req) + switch { + case lp == "": + return message(res, k, "Media file on a remote file system: metadata is not available.") + case req.Tools == nil || req.Tools.FFProbe == "": + return message(res, k, "Media file. Install ffmpeg (ffprobe) for metadata.") + } + out, err := req.Tools.run(ctx, 1<<20, req.Tools.FFProbe, "-v", "quiet", "-print_format", "json", + "-show_format", "-show_streams", lp) + if err != nil { + res.Kind, res.Err = Error, err + return res + } + var info struct { + Format struct { + Duration string `json:"duration"` + Bitrate string `json:"bit_rate"` + } `json:"format"` + Streams []struct { + CodecType string `json:"codec_type"` + CodecName string `json:"codec_name"` + SampleRate string `json:"sample_rate"` + Channels int `json:"channels"` + Width int `json:"width"` + Height int `json:"height"` + } `json:"streams"` + } + if err := json.Unmarshal(out, &info); err != nil { + res.Kind, res.Err = Error, fmt.Errorf("ffprobe output: %w", err) + return res + } + m := &res.Meta + if secs, err := strconv.ParseFloat(info.Format.Duration, 64); err == nil { + s := int(secs) + if s >= 3600 { + m.Duration = fmt.Sprintf("%d:%02d:%02d", s/3600, s%3600/60, s%60) + } else { + m.Duration = fmt.Sprintf("%d:%02d", s/60, s%60) + } + } + if bps, err := strconv.ParseInt(info.Format.Bitrate, 10, 64); err == nil { + m.Bitrate = fmt.Sprintf("%d kbps", bps/1000) + } + for _, st := range info.Streams { + switch st.CodecType { + case "video": + if m.VideoCodec == "" { + m.VideoCodec = st.CodecName + if st.Width > 0 { + m.Dimensions = fmt.Sprintf("%dx%d", st.Width, st.Height) + } + } + case "audio": + if m.AudioCodec == "" { + m.AudioCodec = st.CodecName + if st.SampleRate != "" { + m.SampleRate = st.SampleRate + " Hz" + } + m.Channels = channels(st.Channels) + } + } + } + var lines []string + add := func(label, v string) { + if v != "" { + lines = append(lines, fmt.Sprintf("%-11s %s", label+":", v)) + } + } + add("Duration", m.Duration) + add("Bitrate", m.Bitrate) + add("Video", m.VideoCodec) + add("Resolution", m.Dimensions) + add("Audio", m.AudioCodec) + add("Rate", m.SampleRate) + add("Channels", m.Channels) + return message(res, k, lines...) +} + +func channels(n int) string { + switch n { + case 0: + return "" + case 1: + return "mono" + case 2: + return "stereo" + case 6: + return "5.1" + case 8: + return "7.1" + } + return fmt.Sprintf("%d ch", n) +} diff --git a/internal/preview/preview.test b/internal/preview/preview.test new file mode 100755 index 0000000..6992a53 Binary files /dev/null and b/internal/preview/preview.test differ diff --git a/internal/preview/preview_test.go b/internal/preview/preview_test.go new file mode 100644 index 0000000..d7f41cc --- /dev/null +++ b/internal/preview/preview_test.go @@ -0,0 +1,387 @@ +package preview + +import ( + "bytes" + "context" + "errors" + "fmt" + "image" + "image/color" + "image/png" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/theme" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +var ( + bg = context.Background() + local = localfs.New() +) + +func at(p string) vfs.Location { return vfs.Location{FS: local, Path: p} } + +func pngBytes(t testing.TB, w, h int) []byte { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + img.Set(0, 0, color.RGBA{255, 0, 0, 255}) + var b bytes.Buffer + if err := png.Encode(&b, img); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +func TestFifoNotRead(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.FIFO("pipe"), fstree.Symlink("ln", "pipe")}) + for _, name := range []string{"pipe", "ln"} { + t0 := time.Now() + res := Build(bg, Request{Loc: at(filepath.Join(dir, name))}) + if el := time.Since(t0); el > 50*time.Millisecond { + t.Fatalf("%s: took %v (U-P1-10: a FIFO must not be opened)", name, el) + } + if res.Kind != Special || res.Err != nil { + t.Fatalf("%s: %+v", name, res) + } + } + if res := Build(bg, Request{Loc: at("/dev/zero")}); res.Kind != Special { + t.Fatalf("/dev/zero: %v", res.Kind) + } +} + +// fakeTool writes an executable shell script. +func fakeTool(t *testing.T, body string) string { + p := filepath.Join(t.TempDir(), "tool") + if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func TestToolTimeout(t *testing.T) { + dir := t.TempDir() + pdf := filepath.Join(dir, "doc.pdf") + _ = os.WriteFile(pdf, []byte("%PDF-1.4 not really"), 0o644) + // The script's child (sleep) keeps stdout open: only a group kill ends it. + tools := &Tools{PdfToText: fakeTool(t, "sleep 10 & wait"), Timeout: 3 * time.Second} + t0 := time.Now() + res := Build(bg, Request{Loc: at(pdf), Tools: tools}) + el := time.Since(t0) + if el > 3500*time.Millisecond { + t.Fatalf("returned after %v", el) + } + if res.Kind != Error || !errors.Is(res.Err, ErrToolTimeout) { + t.Fatalf("%+v", res) + } + + // A working tool: output is used and capped. + tools = &Tools{PdfToText: fakeTool(t, `yes "page text" | head -c 100000`), Timeout: 3 * time.Second} + res = Build(bg, Request{Loc: at(pdf), Tools: tools, MaxBytes: 1000}) + if res.Kind != PDF || len(strings.Join(res.Plain, "\n")) > 1000 || res.Plain[0] != "page text" { + t.Fatalf("pdf %v %d lines err=%v", res.Kind, len(res.Plain), res.Err) + } +} + +func TestBuildCancelled(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("a.go", "package a\n")}) + ctx, cancel := context.WithCancel(bg) + cancel() + res := Build(ctx, Request{Loc: at(filepath.Join(dir, "a.go"))}) + if res.Kind != Error || !errors.Is(res.Err, context.Canceled) { + t.Fatalf("%+v", res) + } + // Cancel during a slow read. + ctx, cancel = context.WithCancel(bg) + slow := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpRead { + cancel() + time.Sleep(10 * time.Millisecond) + } + return nil + }} + res = Build(ctx, Request{Loc: vfs.Location{FS: slow, Path: filepath.Join(dir, "a.go")}}) + if !errors.Is(res.Err, context.Canceled) { + t.Fatalf("mid-read: %+v", res) + } + // Cancel during highlighting of a big file. + src := strings.Repeat("func f() { x := 1; _ = x }\n", 3000) + ctx, cancel = context.WithCancel(bg) + time.AfterFunc(time.Millisecond, cancel) + if _, err := Highlight(ctx, "big.go", src, "nord"); err != nil && !errors.Is(err, context.Canceled) { + t.Fatal(err) + } +} + +func TestHighlightNoBackgroundSGR(t *testing.T) { + src := "package main\n\n// comment\nfunc main() {\n\tprintln(\"hi\", 42)\n}\n" + plain, _ := textLines(src, 100) + for _, th := range theme.Names() { + lines, err := Highlight(bg, "main.go", strings.Join(plain, "\n"), th) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(lines, "\n") + if !strings.Contains(joined, "\x1b[") { + t.Fatalf("%s: nothing highlighted", th) + } + for _, seq := range strings.Split(joined, "\x1b[")[1:] { + params := strings.Split(seq[:strings.IndexByte(seq, 'm')], ";") + for i := 0; i < len(params); i++ { + switch p := params[i]; { + case p == "38" && i+1 < len(params) && params[i+1] == "2": + i += 4 // 38;2;r;g;b + case p == "38": + i += 2 // 38;5;n + case p == "48" || p == "49" || (len(p) == 2 && p[0] == '4') || (len(p) == 3 && p[:2] == "10"): + t.Fatalf("%s: background SGR %q", th, params) + } + } + } + if len(lines) != len(plain) { + t.Fatalf("%s: %d lines for %d", th, len(lines), len(plain)) + } + } + // Lines and Plain match line by line. + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("m.go", src)}) + res := Build(bg, Request{Loc: at(filepath.Join(dir, "m.go")), Theme: "dracula"}) + if res.Kind != Text || len(res.Lines) != len(res.Plain) || res.Plain[4] != " println(\"hi\", 42)" { + t.Fatalf("%+v", res.Plain) + } +} + +func goSource(tb testing.TB) string { + b, err := os.ReadFile("highlight.go") + if err != nil { + tb.Fatal(err) + } + var s strings.Builder + for s.Len() < 64<<10 { + s.Write(b) + } + return s.String()[:64<<10] +} + +func BenchmarkPreviewGo64K(b *testing.B) { + dir := b.TempDir() + p := filepath.Join(dir, "big.go") + _ = os.WriteFile(p, []byte(goSource(b)), 0o644) + b.ResetTimer() + for range b.N { + if res := Build(bg, Request{Loc: at(p), Theme: "github-dark"}); res.Kind != Text { + b.Fatal(res.Kind) + } + } +} + +// A loose gate for the benchmark (target ≤ 40 ms, measured ~20 ms; was +// 190 ms). The margin covers -race (≈ ×8). +func TestPreviewGo64KFast(t *testing.T) { + if testing.Short() { + t.Skip() + } + r := testing.Benchmark(BenchmarkPreviewGo64K) + if per := time.Duration(r.NsPerOp()); per > 400*time.Millisecond { + t.Fatalf("Build on 64 KiB of Go: %v per op", per) + } +} + +// remote makes a local FS look remote (no tools, no direct image path). +type remote struct{ vfs.FS } + +func (remote) Kind() vfs.Kind { return vfs.KindSFTP } +func (remote) Volume() vfs.VolumeID { return "ssh:test" } + +func TestRemoteImageSizeLimit(t *testing.T) { + dir := t.TempDir() + small := filepath.Join(dir, "small.png") + _ = os.WriteFile(small, pngBytes(t, 40, 30), 0o644) + big := filepath.Join(dir, "big.png") + data := pngBytes(t, 40, 30) + _ = os.WriteFile(big, append(data, make([]byte, 50000)...), 0o644) // decodable header, large file + cacheDir := filepath.Join(t.TempDir(), "img") + cache, err := NewImageCache(cacheDir, 0) + if err != nil { + t.Fatal(err) + } + opens := 0 + rfs := remote{&vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpOpen { + opens++ + } + return nil + }}} + res := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: big}, Images: cache, MaxRemoteImageBytes: 10000}) + if res.Kind != Image || res.Image == nil || !res.Image.TooLarge || res.Image.Local != "" { + t.Fatalf("big: %+v", res.Image) + } + if ents, _ := os.ReadDir(cacheDir); len(ents) != 0 { + t.Fatal("a too large remote image was downloaded (N-P1-16)") + } + res = Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000}) + if res.Image == nil || res.Image.Local == "" || res.Meta.Width != 40 || res.Meta.Height != 30 { + t.Fatalf("small: %+v %v", res.Image, res.Err) + } + if b, _ := os.ReadFile(res.Image.Local); !bytes.Equal(b, pngBytes(t, 40, 30)) { + t.Fatal("cached copy differs") + } + before := opens + again := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000}) + if again.Image.Local != res.Image.Local || opens-before != 1 { // head read only, no second download + t.Fatalf("cache miss: opens %d", opens-before) + } + // Local images are referenced in place. + if r := Build(bg, Request{Loc: at(small)}); r.Image == nil || r.Image.Local != small { + t.Fatalf("local: %+v", r.Image) + } +} + +func TestImageCacheEvicts(t *testing.T) { + dir := t.TempDir() + src := t.TempDir() + c, err := NewImageCache(filepath.Join(dir, "c"), 2500) + if err != nil { + t.Fatal(err) + } + var paths []string + for i := range 3 { + p := filepath.Join(src, fmt.Sprintf("%d.png", i)) + _ = os.WriteFile(p, make([]byte, 1000), 0o644) + lp, err := c.Fetch(bg, remote{local}, p, 1000, time.Unix(int64(i), 0)) + if err != nil { + t.Fatal(err) + } + paths = append(paths, lp) + } + if _, err := os.Stat(paths[0]); !os.IsNotExist(err) { + t.Fatal("oldest entry not evicted") + } + if _, err := os.Stat(paths[2]); err != nil { + t.Fatal(err) + } + // Reopened: kept within the budget. + c2, err := NewImageCache(filepath.Join(dir, "c"), 1500) + if err != nil || c2.total > 1500 { + t.Fatalf("%v total=%d", err, c2.total) + } +} + +func TestDirPreviewLimited(t *testing.T) { + dir := t.TempDir() + var spec fstree.Spec + for i := range 100 { + spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), "")) + } + spec = append(spec, fstree.Dir("zdir"), fstree.File(".hidden", ""), fstree.Symlink("alink", "zdir")) + fstree.Build(t, dir, spec) + res := Build(bg, Request{Loc: at(dir), DirLimit: 10}) + if res.Kind != Directory || len(res.Dir) != 10 || !res.Truncated { + t.Fatalf("%v %d %v", res.Kind, len(res.Dir), res.Truncated) + } + if res.Dir[0].Name != "alink" || res.Dir[1].Name != "zdir" || res.Dir[2].Name != "f000" { + t.Fatalf("order %s %s %s", res.Dir[0].Name, res.Dir[1].Name, res.Dir[2].Name) + } + for _, e := range res.Dir { + if e.Name == ".hidden" { + t.Fatal("hidden shown") + } + } + if cap(res.Dir) > 10 { + t.Fatalf("result pins the full listing: cap %d", cap(res.Dir)) + } + if res := Build(bg, Request{Loc: at(dir), DirLimit: 1000, ShowHidden: true}); len(res.Dir) != 103 || res.Truncated { + t.Fatalf("all: %d", len(res.Dir)) + } +} + +func TestKindLabel(t *testing.T) { + cases := map[string]vfs.FileInfo{ + "directory": {Name: "src", Mode: os.ModeDir}, + "symlink": {Name: "l.go", Mode: os.ModeSymlink}, + "fifo": {Name: "p", Mode: os.ModeNamedPipe}, + "socket": {Name: "s", Mode: os.ModeSocket}, + "device": {Name: "zero", Mode: os.ModeDevice | os.ModeCharDevice}, + "go": {Name: "main.go"}, + "tar.gz": {Name: "a.TAR.GZ"}, + "file": {Name: "Makefile"}, + } + for want, fi := range cases { + if got := KindLabel(fi); got != want { + t.Errorf("KindLabel(%q) = %q, want %q", fi.Name, got, want) + } + } + if KindLabel(vfs.FileInfo{Name: ".bashrc"}) != "file" { + t.Error("dot-file") + } +} + +func TestBuildKinds(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.File("empty", ""), + fstree.File("bin", "a\x00b\x00c"), + fstree.File("long.txt", strings.Repeat("line\n", 5000)), + fstree.Symlink("broken", "nowhere"), + fstree.File("song.mp3", "ID3 not really"), + }) + _ = os.WriteFile(filepath.Join(dir, "pic.png"), pngBytes(t, 7, 5), 0o644) + kinds := map[string]Kind{"empty": Empty, "bin": Binary, "long.txt": Text, "broken": Special, "pic.png": Image, "song.mp3": Audio} + for name, want := range kinds { + res := Build(bg, Request{Loc: at(filepath.Join(dir, name)), MaxLines: 100}) + if res.Kind != want { + t.Errorf("%s: kind %v (%v), want %v", name, res.Kind, res.Err, want) + } + if name == "long.txt" && (len(res.Lines) != 100 || !res.Truncated) { + t.Errorf("long: %d lines truncated=%v", len(res.Lines), res.Truncated) + } + } + if res := Build(bg, Request{Loc: at(filepath.Join(dir, "broken"))}); res.Meta.LinkTarget != "nowhere" { + t.Error("link target") + } + // The result cache returns the same result without rebuilding. + c := NewCache(2) + opens := 0 + cfs := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpOpen { + opens++ + } + return nil + }} + loc := vfs.Location{FS: cfs, Path: filepath.Join(dir, "long.txt")} + r1 := c.Build(bg, Request{Loc: loc}) + r2 := c.Build(bg, Request{Loc: loc}) + if opens != 1 || len(r1.Lines) != len(r2.Lines) { + t.Fatalf("cache: opens=%d", opens) + } + if res := c.Build(bg, Request{Loc: vfs.Location{FS: local, Path: "/nonexistent"}}); !errors.Is(res.Err, syscall.ENOENT) { + t.Fatalf("missing: %v", res.Err) + } +} + +func TestHighlightWindow(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "big.go") + _ = os.WriteFile(p, []byte(goSource(t)), 0o644) + res := Build(bg, Request{Loc: at(p), HighlightLines: 50}) + if res.Highlighted != 50 || !strings.Contains(res.Lines[10]+res.Lines[0], "\x1b[") { + t.Fatalf("highlighted %d", res.Highlighted) + } + for i := 50; i < len(res.Lines); i++ { + if res.Lines[i] != res.Plain[i] { + t.Fatalf("line %d highlighted beyond the window", i) + } + } + full := Build(bg, Request{Loc: at(p), HighlightLines: 3000}) + if full.Highlighted != len(full.Plain) { + t.Fatalf("full: %d of %d", full.Highlighted, len(full.Plain)) + } +} diff --git a/internal/preview/text.go b/internal/preview/text.go new file mode 100644 index 0000000..fff8399 --- /dev/null +++ b/internal/preview/text.go @@ -0,0 +1,16 @@ +package preview + +import "strings" + +// textLines normalises text for display (CRLF → LF, tab → 4 spaces) and +// splits it into at most max lines. +func textLines(src string, max int) (lines []string, truncated bool) { + src = strings.ReplaceAll(src, "\r\n", "\n") + src = strings.ReplaceAll(src, "\t", " ") + src = strings.TrimSuffix(src, "\n") + lines = strings.Split(src, "\n") + if len(lines) > max { + lines, truncated = lines[:max], true + } + return lines, truncated +} diff --git a/internal/preview/tools.go b/internal/preview/tools.go new file mode 100644 index 0000000..8814978 --- /dev/null +++ b/internal/preview/tools.go @@ -0,0 +1,78 @@ +package preview + +import ( + "bytes" + "context" + "errors" + "fmt" + "os/exec" + "syscall" + "time" +) + +// Tools are the external utilities, looked up once at start. +type Tools struct { + PdfToText string + PdfInfo string + FFProbe string + Timeout time.Duration // per run; default 3 s +} + +// FindTools looks the utilities up in $PATH. +func FindTools() *Tools { + look := func(name string) string { + p, _ := exec.LookPath(name) + return p + } + return &Tools{PdfToText: look("pdftotext"), PdfInfo: look("pdfinfo"), FFProbe: look("ffprobe"), Timeout: 3 * time.Second} +} + +// ErrToolTimeout: the tool was killed after Tools.Timeout. +var ErrToolTimeout = errors.New("timed out") + +// run executes prog with a timeout. The tool gets its own process group and +// the whole group is killed on timeout or cancel, so a child holding stdout +// open cannot make Wait hang. Output beyond max bytes is discarded. +func (t *Tools) run(ctx context.Context, max int64, prog string, args ...string) ([]byte, error) { + timeout := t.Timeout + if timeout <= 0 { + timeout = 3 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + cmd := exec.CommandContext(ctx, prog, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + cmd.WaitDelay = 200 * time.Millisecond + out := &capped{max: max} + cmd.Stdout = out + err := cmd.Run() + if ctx.Err() == context.DeadlineExceeded { + return nil, fmt.Errorf("%s: %w after %v", prog, ErrToolTimeout, timeout) + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + if err != nil { + return nil, fmt.Errorf("%s: %w", prog, err) + } + return out.b.Bytes(), nil +} + +// capped keeps the first max bytes and swallows the rest (the tool is not +// killed by a broken pipe halfway through). +type capped struct { + b bytes.Buffer + max int64 +} + +func (c *capped) Write(p []byte) (int, error) { + if room := c.max - int64(c.b.Len()); room > 0 { + if int64(len(p)) > room { + c.b.Write(p[:room]) + } else { + c.b.Write(p) + } + } + return len(p), nil +} diff --git a/internal/ssh/conn/auth.go b/internal/ssh/conn/auth.go new file mode 100644 index 0000000..a42fa7e --- /dev/null +++ b/internal/ssh/conn/auth.go @@ -0,0 +1,263 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "os" + "strings" + "sync" + "sync/atomic" + "time" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" +) + +// agentConn is the process-wide connection to ssh-agent (N-P2-1: the old +// code opened a new socket per connect and never closed it). It is opened on +// first use, reopened after an error, and closed by dialer.close. +type agentConn struct { + sock string + + mu sync.Mutex + c net.Conn + ag agent.ExtendedAgent + dials atomic.Int32 // sockets opened, for tests +} + +// signers returns the agent's keys; no agent (or an agent error) yields nil. +func (a *agentConn) signers() []ssh.Signer { + if a == nil || a.sock == "" { + return nil + } + a.mu.Lock() + defer a.mu.Unlock() + if a.ag == nil { + c, err := net.DialTimeout("unix", a.sock, 2*time.Second) + if err != nil { + return nil + } + a.dials.Add(1) + a.c, a.ag = c, agent.NewClient(c) + } + ss, err := a.ag.Signers() + if err != nil { + a.c.Close() + a.c, a.ag = nil, nil + return nil + } + return ss +} + +func (a *agentConn) close() { + if a == nil { + return + } + a.mu.Lock() + defer a.mu.Unlock() + if a.c != nil { + a.c.Close() + a.c, a.ag = nil, nil + } +} + +// authMethods builds the auth chain (N-P2-2): public keys (explicit +// IdentityFiles, then agent keys, then default key files), password (stored +// or asked), keyboard-interactive (questions shown as they are, so 2FA +// works). x/crypto tries each method name once, so all keys go into one +// publickey method. +func (d *dialer) authMethods(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.AuthMethod { + methods := []ssh.AuthMethod{ssh.PublicKeysCallback(func() ([]ssh.Signer, error) { + return d.signers(ctx, ep, prompt), nil + })} + p := d.opts.Prompter + storedUsed := false // the handshake runs auth sequentially + if ep.Password != "" || p != nil { + methods = append(methods, ssh.PasswordCallback(func() (string, error) { + if ep.Password != "" && !storedUsed { + storedUsed = true + return ep.Password, nil + } + if p == nil { + return "", errors.New("password rejected") + } + var pw string + err := prompt(func() error { + var err error + pw, err = p.Password(ctx, ep) + return err + }) + return pw, err + })) + methods = append(methods, ssh.KeyboardInteractive(func(name, instruction string, qs []string, echo []bool) ([]string, error) { + if len(qs) == 0 { + return nil, nil + } + // A lone hidden question is the server's password prompt. + if ep.Password != "" && !storedUsed && len(qs) == 1 && !echo[0] { + storedUsed = true + return []string{ep.Password}, nil + } + if p == nil { + return nil, errors.New("keyboard-interactive: no way to ask the user") + } + instr := strings.TrimSpace(strings.TrimSpace(name) + "\n" + strings.TrimSpace(instruction)) + var answers []string + err := prompt(func() error { + var err error + answers, err = p.KeyboardInteractive(ctx, ep, instr, qs, echo) + return err + }) + if err == nil && len(answers) != len(qs) { + err = fmt.Errorf("keyboard-interactive: %d answers for %d questions", len(answers), len(qs)) + } + return answers, err + })) + } + return methods +} + +func (d *dialer) signers(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.Signer { + var out []ssh.Signer + seen := map[string]bool{} + add := func(s ssh.Signer) { + if s == nil { + return + } + k := string(s.PublicKey().Marshal()) + if !seen[k] { + seen[k] = true + out = append(out, s) + } + } + agentKeys := d.agent.signers() + inAgent := make(map[string]ssh.Signer, len(agentKeys)) + for _, s := range agentKeys { + inAgent[string(s.PublicKey().Marshal())] = s + } + for _, p := range ep.IdentityFiles { + add(d.loadKey(ctx, p, inAgent, prompt)) + } + if !ep.IdentitiesOnly { + for _, s := range agentKeys { + add(s) + } + for _, p := range d.opts.DefaultIdentityFiles { + add(d.loadKey(ctx, p, inAgent, prompt)) + } + } + return out +} + +// loadKey reads a private key. An encrypted key whose public half is known +// (embedded in the OpenSSH format or in path.pub) becomes a lazySigner: the +// passphrase is asked only if the server accepts the key. A key already +// unlocked in the agent is used from there. +func (d *dialer) loadKey(ctx context.Context, path string, inAgent map[string]ssh.Signer, prompt func(func() error) error) ssh.Signer { + data, err := os.ReadFile(path) + if err != nil { + return nil + } + s, err := ssh.ParsePrivateKey(data) + if err == nil { + return s + } + var pm *ssh.PassphraseMissingError + if !errors.As(err, &pm) { + d.warnf("identity %s: %v", path, err) + return nil + } + pub := pm.PublicKey + if pub == nil { + if b, err := os.ReadFile(path + ".pub"); err == nil { + pub, _, _, _, _ = ssh.ParseAuthorizedKey(b) + } + } + if pub != nil { + if as := inAgent[string(pub.Marshal())]; as != nil { + return as + } + } + if d.opts.Prompter == nil { + return nil + } + ls := &lazySigner{pub: pub, path: path, pem: data, ask: func() ([]byte, error) { + var pass []byte + err := prompt(func() error { + var err error + pass, err = d.opts.Prompter.Passphrase(ctx, path) + return err + }) + return pass, err + }} + if pub == nil { + // Without the public half the key cannot be offered lazily. + if _, err := ls.load(); err != nil { + d.warnf("identity %s: %v", path, err) + return nil + } + ls.pub = ls.s.PublicKey() + } + return ls +} + +// lazySigner decrypts a passphrase-protected key on first Sign. +type lazySigner struct { + pub ssh.PublicKey + path string + pem []byte + ask func() ([]byte, error) + + once sync.Once + s ssh.AlgorithmSigner + err error +} + +const passphraseAttempts = 3 + +func (l *lazySigner) load() (ssh.AlgorithmSigner, error) { + l.once.Do(func() { + for i := 0; i < passphraseAttempts; i++ { + pass, err := l.ask() + if err != nil { + l.err = err + return + } + s, err := ssh.ParsePrivateKeyWithPassphrase(l.pem, pass) + clear(pass) + if err != nil { + l.err = fmt.Errorf("identity %s: %w", l.path, err) + continue + } + as, ok := s.(ssh.AlgorithmSigner) + if !ok { + l.err = fmt.Errorf("identity %s: unsupported key type", l.path) + return + } + l.s, l.err = as, nil + return + } + }) + return l.s, l.err +} + +func (l *lazySigner) PublicKey() ssh.PublicKey { return l.pub } + +func (l *lazySigner) Sign(r io.Reader, data []byte) (*ssh.Signature, error) { + s, err := l.load() + if err != nil { + return nil, err + } + return s.Sign(r, data) +} + +func (l *lazySigner) SignWithAlgorithm(r io.Reader, data []byte, algo string) (*ssh.Signature, error) { + s, err := l.load() + if err != nil { + return nil, err + } + return s.SignWithAlgorithm(r, data, algo) +} diff --git a/internal/ssh/conn/conn.go b/internal/ssh/conn/conn.go new file mode 100644 index 0000000..3edda48 --- /dev/null +++ b/internal/ssh/conn/conn.go @@ -0,0 +1,360 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +var ( + // ErrConnLost: the connection died (keepalive timeout, network cut, + // server gone). The operation may be retried after Reconnect. sftpfs maps + // it to vfs.ErrConnLost. + ErrConnLost = errors.New("connection lost") + // ErrClosed: the connection was closed by the pool. + ErrClosed = errors.New("connection closed") +) + +// State of a Conn. +type State uint32 + +const ( + Connecting State = iota + Ready + Lost + Closed +) + +func (s State) String() string { + switch s { + case Connecting: + return "connecting" + case Ready: + return "ready" + case Lost: + return "lost" + case Closed: + return "closed" + } + return fmt.Sprintf("State(%d)", uint32(s)) +} + +// Event reports a state change (ConnStateChanged). main forwards it to the +// UI with program.Send; it is called from connection goroutines and must not +// block. +type Event struct { + Key string // Endpoint.Key() + State State + Gen uint64 // generation the state refers to + Err error // why the connection was lost (Lost), nil otherwise +} + +// Defaults for keepalive (§3.4). +const ( + DefaultKeepaliveInterval = 15 * time.Second + DefaultKeepaliveTimeout = 10 * time.Second + DefaultKeepaliveMaxMiss = 2 +) + +// ConnOptions tune liveness detection of one connection. +type ConnOptions struct { + KeepaliveInterval time.Duration // default 15s, or Endpoint.ServerAliveInterval + KeepaliveTimeout time.Duration // per keepalive reply; default 10s + KeepaliveMaxMiss int // default 2, or Endpoint.ServerAliveCountMax + OnEvent func(Event) +} + +func (o ConnOptions) withDefaults(ep Endpoint) ConnOptions { + if o.KeepaliveInterval <= 0 { + o.KeepaliveInterval = ep.ServerAliveInterval + } + if o.KeepaliveInterval <= 0 { + o.KeepaliveInterval = DefaultKeepaliveInterval + } + if o.KeepaliveTimeout <= 0 { + o.KeepaliveTimeout = DefaultKeepaliveTimeout + } + if o.KeepaliveMaxMiss <= 0 { + o.KeepaliveMaxMiss = ep.ServerAliveCountMax + } + if o.KeepaliveMaxMiss <= 0 { + o.KeepaliveMaxMiss = DefaultKeepaliveMaxMiss + } + return o +} + +// ConnCaps are server capabilities detected at connect time. +type ConnCaps struct { + PosixRename bool // posix-rename@openssh.com: atomic Rename(Replace) + Fsync bool // fsync@openssh.com + StatVFS bool // statvfs@openssh.com + Hardlink bool // hardlink@openssh.com +} + +// Conn is one logical connection to an endpoint. Its fields are never reset: +// the current *sftp.Client sits in an atomic pointer and, once the +// connection dies, keeps returning errors instead of disappearing (N-P0-8). +// Reconnect installs a new generation in the same Conn, so leases stay +// valid. Only the Pool closes a Conn. +type Conn struct { + d *dialer + ep Endpoint + key string + opts ConnOptions + + state atomic.Uint32 + gen atomic.Uint64 + sftp atomic.Pointer[sftp.Client] + cur atomic.Pointer[generation] + + mu sync.Mutex // serializes state transitions + lostBy error + + reconnectMu sync.Mutex // one reconnect at a time + + execMu sync.Mutex + execKnown bool + execOK bool + + wg sync.WaitGroup // per-generation goroutines +} + +// generation is one live link plus its lifetime signal. +type generation struct { + *link + gen uint64 + caps ConnCaps + done chan struct{} // closed when the link has ended +} + +func newGeneration(l *link, gen uint64) *generation { + g := &generation{link: l, gen: gen, done: make(chan struct{})} + _, g.caps.PosixRename = l.sftp.HasExtension("posix-rename@openssh.com") + _, g.caps.Fsync = l.sftp.HasExtension("fsync@openssh.com") + _, g.caps.StatVFS = l.sftp.HasExtension("statvfs@openssh.com") + _, g.caps.Hardlink = l.sftp.HasExtension("hardlink@openssh.com") + return g +} + +// connect dials ep and returns a Ready Conn with keepalive running. +func (d *dialer) connect(ctx context.Context, ep Endpoint, o ConnOptions) (*Conn, error) { + c := &Conn{d: d, ep: ep, key: ep.Key(), opts: o.withDefaults(ep)} + c.state.Store(uint32(Connecting)) + l, err := d.dial(ctx, ep) + if err != nil { + c.state.Store(uint32(Closed)) + return nil, err + } + c.mu.Lock() + c.install(l) + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Ready, Gen: c.gen.Load()}) + return c, nil +} + +// install makes l the current generation; c.mu is held. +func (c *Conn) install(l *link) { + gen := c.gen.Add(1) + g := newGeneration(l, gen) + c.cur.Store(g) + c.sftp.Store(l.sftp) + c.lostBy = nil + c.state.Store(uint32(Ready)) + c.wg.Add(2) + go func() { + defer c.wg.Done() + err := l.ssh.Wait() + close(g.done) + if err == nil { + err = io.EOF + } + c.lose(g, err) + }() + go func() { + defer c.wg.Done() + c.keepalive(g) + }() +} + +// lose marks generation g as Lost (if it is still current and Ready) and +// closes its SSH client, failing every pending request at once. +func (c *Conn) lose(g *generation, why error) { + c.mu.Lock() + if c.cur.Load() != g || c.State() != Ready { + c.mu.Unlock() + return + } + c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, why) + c.state.Store(uint32(Lost)) + err := c.lostBy + c.mu.Unlock() + g.ssh.Close() + g.sftp.Close() + c.emit(Event{Key: c.key, State: Lost, Gen: g.gen, Err: err}) +} + +func (c *Conn) emit(e Event) { + if c.opts.OnEvent != nil { + c.opts.OnEvent(e) + } +} + +// State returns the current state. +func (c *Conn) State() State { return State(c.state.Load()) } + +// Gen is the generation number; it grows with every successful Reconnect. +func (c *Conn) Gen() uint64 { return c.gen.Load() } + +// Key is the pool key (Endpoint.Key()). +func (c *Conn) Key() string { return c.key } + +// Endpoint returns the endpoint this connection was dialed with. +func (c *Conn) Endpoint() Endpoint { return c.ep } + +// Err explains the current state: why it was lost, ErrClosed, or nil. +func (c *Conn) Err() error { + switch c.State() { + case Closed: + return ErrClosed + case Lost, Connecting: + c.mu.Lock() + defer c.mu.Unlock() + if c.lostBy != nil { + return c.lostBy + } + return ErrConnLost + } + return nil +} + +// Client returns the SFTP client of the current generation, or an error +// wrapping ErrConnLost / ErrClosed when the connection is not Ready. The +// client is safe for concurrent use; after the connection dies its calls +// fail (map them with MapErr). +func (c *Conn) Client() (*sftp.Client, error) { + if err := c.Err(); err != nil { + return nil, err + } + return c.sftp.Load(), nil +} + +// SSH returns the SSH client of the current generation (for exec and port +// forwarding), with the same rules as Client. +func (c *Conn) SSH() (*ssh.Client, error) { + if err := c.Err(); err != nil { + return nil, err + } + return c.cur.Load().ssh, nil +} + +// Identity is the host key of the server; it does not change across +// reconnects (a different key fails the reconnect). +func (c *Conn) Identity() HostIdentity { return c.cur.Load().id } + +// ServerVersion is the server's SSH version banner, e.g. +// "SSH-2.0-OpenSSH_9.6" (sftpfs uses it for the symlink argument order). +func (c *Conn) ServerVersion() string { return c.cur.Load().serverVersion } + +// Caps returns the SFTP extensions of the current generation. Exec support +// is probed separately (ExecSupported) because it needs a round trip. +func (c *Conn) Caps() ConnCaps { return c.cur.Load().caps } + +// MapErr turns errors caused by a dead connection into ErrConnLost (wrapped, +// so the original stays visible); other errors are returned unchanged. +func (c *Conn) MapErr(err error) error { + if err == nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) { + return err + } + if errors.Is(err, sftp.ErrSSHFxConnectionLost) || errors.Is(err, net.ErrClosed) { + return fmt.Errorf("%w: %v", ErrConnLost, err) + } + if st := c.State(); st != Ready && (errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)) { + if st == Closed { + return fmt.Errorf("%w: %v", ErrClosed, err) + } + return fmt.Errorf("%w: %v", ErrConnLost, err) + } + return err +} + +// ErrIdentityChanged: on reconnect the server presented a different host key +// than the original connection (the Volume would no longer be the same). +var ErrIdentityChanged = errors.New("server host key differs from the original connection") + +// Reconnect dials a new generation if the connection is Lost. It is a +// single attempt (Pool.Reconnect adds backoff); concurrent calls are +// serialized and a call on a Ready connection is a no-op. Operations started +// on the old generation keep failing with ErrConnLost. +func (c *Conn) Reconnect(ctx context.Context) error { + c.reconnectMu.Lock() + defer c.reconnectMu.Unlock() + c.mu.Lock() + switch c.State() { + case Closed: + c.mu.Unlock() + return ErrClosed + case Ready: + c.mu.Unlock() + return nil + } + c.state.Store(uint32(Connecting)) + gen := c.gen.Load() + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Connecting, Gen: gen}) + + l, err := c.d.dial(ctx, c.ep) + if err == nil && l.id != c.Identity() { + l.close() + err = fmt.Errorf("reconnect %s: %w (was %s, now %s)", c.ep.Label(), ErrIdentityChanged, + c.Identity().FingerprintSHA256, l.id.FingerprintSHA256) + } + c.mu.Lock() + if c.State() == Closed { + c.mu.Unlock() + if err == nil { + l.close() + } + return ErrClosed + } + if err != nil { + c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, err) + c.state.Store(uint32(Lost)) + lostBy := c.lostBy + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Lost, Gen: gen, Err: lostBy}) + return err + } + c.install(l) + gen = c.gen.Load() + c.mu.Unlock() + c.emit(Event{Key: c.key, State: Ready, Gen: gen}) + return nil +} + +// close shuts the connection down for good and waits for its goroutines. +// Only the Pool calls it. +func (c *Conn) close() { + c.mu.Lock() + if c.State() == Closed { + c.mu.Unlock() + return + } + c.state.Store(uint32(Closed)) + g := c.cur.Load() + c.mu.Unlock() + if g != nil { + g.close() + } + c.wg.Wait() + if g != nil { + c.emit(Event{Key: c.key, State: Closed, Gen: g.gen}) + } +} diff --git a/internal/ssh/conn/conn_test.go b/internal/ssh/conn/conn_test.go new file mode 100644 index 0000000..cb2561b --- /dev/null +++ b/internal/ssh/conn/conn_test.go @@ -0,0 +1,297 @@ +package conn + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + "vcom/internal/testutil/sshtest" +) + +// events collects Conn events. +type events struct { + mu sync.Mutex + ev []Event +} + +func (e *events) add(ev Event) { + e.mu.Lock() + e.ev = append(e.ev, ev) + e.mu.Unlock() +} + +func (e *events) has(s State) bool { + e.mu.Lock() + defer e.mu.Unlock() + for _, ev := range e.ev { + if ev.State == s { + return true + } + } + return false +} + +func (e *events) snapshot() []Event { + e.mu.Lock() + defer e.mu.Unlock() + return append([]Event(nil), e.ev...) +} + +func (e *events) last() Event { + e.mu.Lock() + defer e.mu.Unlock() + if len(e.ev) == 0 { + return Event{} + } + return e.ev[len(e.ev)-1] +} + +// fastKeepalive makes liveness tests take well under a second. +var fastKeepalive = ConnOptions{ + KeepaliveInterval: 100 * time.Millisecond, + KeepaliveTimeout: 100 * time.Millisecond, + KeepaliveMaxMiss: 2, +} + +func (e *env) connect(addr, password string, o ConnOptions) *Conn { + e.t.Helper() + c, err := e.dialer(DialOptions{}).connect(context.Background(), endpointFor(addr, password), o) + if err != nil { + e.t.Fatalf("connect: %v", err) + } + e.t.Cleanup(c.close) + return c +} + +// Ported from the testbed (B6, TestFreezeHangs), N-P1-2: a frozen link was +// never noticed and calls hung forever. Now keepalive marks it Lost within +// interval*(miss+1)+timeout and the hung ReadDir returns ErrConnLost. +func TestFreezeDetectedAsLost(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + var ev events + o := fastKeepalive + o.OnEvent = ev.add + c := e.connect(px.Addr, srv.Password, o) + sc, err := c.Client() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + if _, err := sc.ReadDir(dir); err != nil { + t.Fatal(err) + } + + px.Freeze(true) + defer px.Freeze(false) + start := time.Now() + res := make(chan error, 1) + go func() { + _, err := sc.ReadDir(dir) + res <- c.MapErr(err) + }() + bound := o.KeepaliveInterval*time.Duration(o.KeepaliveMaxMiss+1) + o.KeepaliveTimeout + waitFor(t, bound+500*time.Millisecond, "state Lost", func() bool { return c.State() == Lost }) + t.Logf("lost after %v (bound %v)", time.Since(start), bound) + select { + case err := <-res: + if !errors.Is(err, ErrConnLost) { + t.Errorf("hung ReadDir: err = %v, want ErrConnLost", err) + } + case <-time.After(time.Second): + t.Fatal("hung ReadDir did not return after Lost") + } + waitFor(t, time.Second, "Lost event", func() bool { return ev.has(Lost) }) + if ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) { + t.Errorf("events = %+v", ev.snapshot()) + } + if _, err := c.Client(); !errors.Is(err, ErrConnLost) { + t.Errorf("Client() after Lost: %v", err) + } + }) +} + +func TestReconnectAfterCut(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + var ev events + o := ConnOptions{KeepaliveInterval: time.Hour, OnEvent: ev.add} + c := e.connect(px.Addr, srv.Password, o) + dir := t.TempDir() + gen := c.Gen() + id := c.Identity() + + px.CutAfter(1) + sc, _ := c.Client() + _, err := sc.ReadDir(dir) + if err == nil { + t.Fatal("ReadDir across a cut succeeded") + } + if !errors.Is(c.MapErr(err), ErrConnLost) { + t.Errorf("err = %v, want ErrConnLost", c.MapErr(err)) + } + waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost }) + + if err := c.Reconnect(context.Background()); err != nil { + t.Fatalf("Reconnect: %v", err) + } + if c.State() != Ready || c.Gen() != gen+1 || c.Identity() != id { + t.Errorf("after reconnect: state %v gen %d (was %d) id %+v", c.State(), c.Gen(), gen, c.Identity()) + } + sc2, err := c.Client() + if err != nil { + t.Fatal(err) + } + if _, err := sc2.ReadDir(dir); err != nil { + t.Fatalf("ReadDir after reconnect: %v", err) + } + // The old generation's client stays dead. + if _, err := sc.ReadDir(dir); !errors.Is(c.MapErr(err), ErrConnLost) { + t.Errorf("old-generation client: %v", err) + } + if err := c.Reconnect(context.Background()); err != nil { + t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err) + } + if !ev.has(Connecting) || ev.last().State != Ready { + t.Errorf("events = %+v", ev.snapshot()) + } + c.close() + if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) { + t.Errorf("Reconnect after close: %v", err) + } + if _, err := c.Client(); !errors.Is(err, ErrClosed) { + t.Errorf("Client after close: %v", err) + } + }) +} + +func TestReconnectFailsWhileServerDown(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour}) + px.Freeze(true) + defer px.Freeze(false) + px.KillAll() + waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost }) + c.d.opts.HandshakeTimeout = 200 * time.Millisecond + if err := c.Reconnect(context.Background()); err == nil { + t.Fatal("reconnect through a frozen link succeeded") + } + if c.State() != Lost { + t.Errorf("state = %v, want Lost", c.State()) + } +} + +func TestProbeMarksLost(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour}) + if err := c.Probe(context.Background(), time.Second); err != nil { + t.Fatalf("probe on a live link: %v", err) + } + px.Freeze(true) + defer px.Freeze(false) + if err := c.Probe(context.Background(), 100*time.Millisecond); !errors.Is(err, ErrConnLost) { + t.Fatalf("probe on a frozen link: %v", err) + } + if c.State() != Lost { + t.Errorf("state = %v", c.State()) + } +} + +// N-P2-15 / N-P1-7: Exec had no ctx and no timeout. +func TestExecCancelKills(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(100*time.Millisecond, cancel) + start := time.Now() + _, _, err := c.Exec(ctx, []string{"sleep", "60"}, 0) + if el := time.Since(start); el > time.Second { + t.Errorf("cancel took %v", el) + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v", err) + } + // The connection is still usable. + out, code, err := c.Exec(context.Background(), []string{"echo", "it's ok"}, 0) + if err != nil || code != 0 || string(out) != "it's ok\n" { + t.Errorf("exec after cancel: %q %d %v", out, code, err) + } +} + +func TestExecOutputLimit(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + start := time.Now() + out, _, err := c.Exec(context.Background(), []string{"yes"}, 1000) + if !errors.Is(err, ErrOutputLimit) { + t.Fatalf("err = %v, want ErrOutputLimit", err) + } + if len(out) != 1000 || !strings.HasPrefix(string(out), "y\ny\n") { + t.Errorf("output: %d bytes", len(out)) + } + if el := time.Since(start); el > 2*time.Second { + t.Errorf("limited exec took %v", el) + } +} + +func TestExecExitStatus(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + out, code, err := c.Exec(context.Background(), []string{"sh", "-c", "echo out; echo bad >&2; exit 3"}, 0) + var ee *ExitError + if !errors.As(err, &ee) || code != 3 || ee.Code != 3 || strings.TrimSpace(ee.Stderr) != "bad" || string(out) != "out\n" { + t.Errorf("out=%q code=%d err=%v", out, code, err) + } + if !c.ExecSupported(context.Background()) { + t.Error("ExecSupported = false on a server with exec") + } +} + +func TestExecSupportedNoExec(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{NoExec: true}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + if c.ExecSupported(context.Background()) { + t.Error("ExecSupported = true with ForceCommand internal-sftp") + } + if _, err := c.Client(); err != nil { + t.Errorf("a refused exec must not break the connection: %v", err) + } +} + +func TestQuote(t *testing.T) { + got := Quote([]string{"cp", "-r", "a b", "it's", "", "x;rm -rf /", "/ok/path_1.txt"}) + want := `cp -r 'a b' 'it'\''s' '' 'x;rm -rf /' /ok/path_1.txt` + if got != want { + t.Errorf("Quote = %s\nwant %s", got, want) + } +} + +func TestConnInfo(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + c := e.connect(srv.Addr, srv.Password, ConnOptions{}) + if c.Identity().FingerprintSHA256 == "" || !strings.HasPrefix(c.ServerVersion(), "SSH-2.0-") { + t.Errorf("identity %+v version %q", c.Identity(), c.ServerVersion()) + } + if !c.Caps().PosixRename { + t.Logf("caps: %+v", c.Caps()) + } + if c.Key() != "u@"+srv.Addr { + t.Errorf("Key = %q", c.Key()) + } +} diff --git a/internal/ssh/conn/dial.go b/internal/ssh/conn/dial.go new file mode 100644 index 0000000..13cc0a5 --- /dev/null +++ b/internal/ssh/conn/dial.go @@ -0,0 +1,235 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +// DefaultHandshakeTimeout bounds TCP connect + kex + auth + SFTP init. +const DefaultHandshakeTimeout = 20 * time.Second + +// ErrHandshakeTimeout: the server accepted TCP but did not finish the +// handshake in time (N-P1-3). +var ErrHandshakeTimeout = errors.New("ssh handshake timed out") + +// DialOptions configures how connections are established. +type DialOptions struct { + Prompter Prompter + // HandshakeTimeout covers the whole path TCP + kex + auth + SFTP init, + // excluding time spent waiting for the Prompter. Default 20s. + HandshakeTimeout time.Duration + // Home is the home directory for the default known_hosts and identity + // files ("" = os.UserHomeDir()). + Home string + // KnownHostsFiles are read in order. nil means Home/.ssh/known_hosts and + // /etc/ssh/ssh_known_hosts. + KnownHostsFiles []string + // KnownHostsWrite receives AcceptAndSave lines. "" means the first of + // KnownHostsFiles (the default user file). Set to "-" for memory only. + KnownHostsWrite string + // AgentSocket is the ssh-agent socket. "" means $SSH_AUTH_SOCK; "-" + // disables the agent. + AgentSocket string + // DefaultIdentityFiles are tried when the endpoint does not set + // IdentitiesOnly. nil means Home/.ssh/id_{ed25519,ecdsa,rsa}. + DefaultIdentityFiles []string + // Warn receives non-fatal problems (host key kept in memory only, + // unreadable identity file). May be nil. + Warn func(msg string) +} + +func (o DialOptions) withDefaults() DialOptions { + if o.HandshakeTimeout <= 0 { + o.HandshakeTimeout = DefaultHandshakeTimeout + } + if o.Home == "" { + o.Home, _ = os.UserHomeDir() + } + ssh := filepath.Join(o.Home, ".ssh") + if o.KnownHostsFiles == nil { + o.KnownHostsFiles = []string{filepath.Join(ssh, "known_hosts"), "/etc/ssh/ssh_known_hosts"} + } + switch o.KnownHostsWrite { + case "": + if len(o.KnownHostsFiles) > 0 { + o.KnownHostsWrite = o.KnownHostsFiles[0] + } + case "-": + o.KnownHostsWrite = "" + } + switch o.AgentSocket { + case "": + o.AgentSocket = os.Getenv("SSH_AUTH_SOCK") + case "-": + o.AgentSocket = "" + } + if o.DefaultIdentityFiles == nil { + for _, n := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} { + o.DefaultIdentityFiles = append(o.DefaultIdentityFiles, filepath.Join(ssh, n)) + } + } + return o +} + +// dialer establishes connections. One per Pool (i.e. per process): it owns +// the shared agent connection and the session-trusted host keys. +type dialer struct { + opts DialOptions + hosts *knownHosts + agent *agentConn + dials atomic.Int64 // successful TCP connects, for tests +} + +func newDialer(o DialOptions) *dialer { + o = o.withDefaults() + return &dialer{ + opts: o, + hosts: newKnownHosts(o.KnownHostsFiles, o.KnownHostsWrite, o.Warn), + agent: &agentConn{sock: o.AgentSocket}, + } +} + +func (d *dialer) close() { d.agent.close() } + +func (d *dialer) warnf(format string, args ...any) { + if d.opts.Warn != nil { + d.opts.Warn(fmt.Sprintf(format, args...)) + } +} + +// link is one established generation of a connection. +type link struct { + ssh *ssh.Client + sftp *sftp.Client + id HostIdentity + serverVersion string +} + +func (l *link) close() { + l.sftp.Close() + l.ssh.Close() +} + +// deadlineGate applies the handshake deadline to the raw connection and +// pauses it while the Prompter waits for the user. +type deadlineGate struct { + nc net.Conn + timeout time.Duration + mu sync.Mutex + done bool // handshake finished: never touch deadlines again +} + +func (g *deadlineGate) arm() { + g.mu.Lock() + defer g.mu.Unlock() + if !g.done { + g.nc.SetDeadline(time.Now().Add(g.timeout)) + } +} + +func (g *deadlineGate) finish() { + g.mu.Lock() + defer g.mu.Unlock() + g.done = true + g.nc.SetDeadline(time.Time{}) +} + +func (g *deadlineGate) prompt(fn func() error) error { + g.mu.Lock() + if !g.done { + g.nc.SetDeadline(time.Time{}) + } + g.mu.Unlock() + defer g.arm() + return fn() +} + +// sftpOptions: concurrent reads/writes so a transfer is not one packet per +// RTT (N-P1-6). +var sftpOptions = []sftp.ClientOption{ + sftp.UseConcurrentWrites(true), + sftp.UseConcurrentReads(true), + sftp.MaxConcurrentRequestsPerFile(64), +} + +// dial connects, verifies the host key, authenticates and starts SFTP. +// Cancelling ctx closes the socket at once; if the handshake still +// completes, the late client is closed here, never leaked (N-P1-3). +func (d *dialer) dial(ctx context.Context, ep Endpoint) (*link, error) { + timeout := d.opts.HandshakeTimeout + tcpTimeout := timeout + if ep.ConnectTimeout > 0 && ep.ConnectTimeout < tcpTimeout { + tcpTimeout = ep.ConnectTimeout + } + addr := ep.Addr() + nd := net.Dialer{Timeout: tcpTimeout} + nc, err := nd.DialContext(ctx, "tcp", addr) + if err != nil { + if ctx.Err() != nil { + return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) + } + return nil, fmt.Errorf("connect %s: %w", ep.Label(), err) + } + d.dials.Add(1) + gate := &deadlineGate{nc: nc, timeout: timeout} + gate.arm() + stop := context.AfterFunc(ctx, func() { nc.Close() }) + + var idMu sync.Mutex + var id HostIdentity + onKey := func(h HostIdentity) { + idMu.Lock() + defer idMu.Unlock() + if id.KeyType == "" { + id = h + } + } + cfg := &ssh.ClientConfig{ + User: ep.User, + Auth: d.authMethods(ctx, ep, gate.prompt), + HostKeyCallback: d.hosts.callback(ctx, ep, d.opts.Prompter, gate.prompt, onKey), + HostKeyAlgorithms: d.hosts.algorithms(addr), + } + fail := func(err error) (*link, error) { + stop() + nc.Close() + if ctx.Err() != nil { + return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) + } + if errors.Is(err, os.ErrDeadlineExceeded) { + return nil, fmt.Errorf("connect %s: %w after %v", ep.Label(), ErrHandshakeTimeout, timeout) + } + return nil, fmt.Errorf("connect %s: %w", ep.Label(), err) + } + sc, chans, reqs, err := ssh.NewClientConn(nc, addr, cfg) + if err != nil { + return fail(err) + } + client := ssh.NewClient(sc, chans, reqs) + sc2, err := sftp.NewClient(client, sftpOptions...) + if err != nil { + client.Close() + return fail(fmt.Errorf("sftp: %w", err)) + } + l := &link{ssh: client, sftp: sc2, serverVersion: string(client.ServerVersion())} + if !stop() { + // ctx fired while we were finishing: the caller is gone. + l.close() + return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) + } + gate.finish() + idMu.Lock() + l.id = id + idMu.Unlock() + return l, nil +} diff --git a/internal/ssh/conn/dial_test.go b/internal/ssh/conn/dial_test.go new file mode 100644 index 0000000..08c89d5 --- /dev/null +++ b/internal/ssh/conn/dial_test.go @@ -0,0 +1,452 @@ +package conn + +import ( + "bytes" + "context" + "crypto/rsa" + "errors" + "math/big" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "vcom/internal/testutil/sshtest" +) + +// N-P1-3: the server accepts TCP and then goes silent; the dial must fail +// within HandshakeTimeout (+1s slack), not hang. +func TestHandshakeTimeout(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := sshtest.NewProxy(t, srv.Addr) + px.Freeze(true) + const timeout = 300 * time.Millisecond + d := e.dialer(DialOptions{HandshakeTimeout: timeout}) + start := time.Now() + l, err := d.dial(context.Background(), endpointFor(px.Addr, srv.Password)) + el := time.Since(start) + if err == nil { + l.close() + t.Fatal("dial through a frozen proxy succeeded") + } + if !errors.Is(err, ErrHandshakeTimeout) { + t.Errorf("err = %v, want ErrHandshakeTimeout", err) + } + if el > timeout+time.Second { + t.Errorf("dial took %v, want <= %v", el, timeout+time.Second) + } + px.Freeze(false) + }) +} + +// N-P1-3: cancelling ctx mid-handshake returns at once; once the link +// unfreezes nothing is left behind (no client, no goroutines). +func TestDialCancelClosesLateClient(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := sshtest.NewProxy(t, srv.Addr) + px.Freeze(true) + d := e.dialer(DialOptions{HandshakeTimeout: 10 * time.Second}) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(100*time.Millisecond, cancel) + start := time.Now() + l, err := d.dial(ctx, endpointFor(px.Addr, srv.Password)) + if err == nil { + l.close() + t.Fatal("cancelled dial succeeded") + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if el := time.Since(start); el > time.Second { + t.Errorf("cancel took %v", el) + } + px.Freeze(false) + // The proxy forwards the buffered handshake now; the server must see + // the client gone and drop the connection. + time.Sleep(100 * time.Millisecond) + }) +} + +// A prompt answered after the caller gave up must not produce a live client. +func TestDialCancelDuringPrompt(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := sshtest.Start(t, sshtest.Options{}) + ctx, cancel := context.WithCancel(context.Background()) + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { + cancel() + time.Sleep(50 * time.Millisecond) + return AcceptOnce, nil // ignores ctx on purpose + }} + d := e.dialer(DialOptions{Prompter: p}) + l, err := d.dial(ctx, endpointFor(srv.Addr, srv.Password)) + if err == nil { + l.close() + t.Fatal("dial succeeded after cancel") + } + if !errors.Is(err, context.Canceled) { + t.Errorf("err = %v", err) + } + }) +} + +// The deadline is paused while the Prompter waits for the user. +func TestHandshakeDeadlinePausedDuringPrompt(t *testing.T) { + e := newEnv(t) + srv := sshtest.Start(t, sshtest.Options{}) + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { + time.Sleep(400 * time.Millisecond) + return AcceptOnce, nil + }} + d := e.dialer(DialOptions{Prompter: p, HandshakeTimeout: 200 * time.Millisecond}) + l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if err != nil { + t.Fatalf("slow user answer must not time out the handshake: %v", err) + } + l.close() +} + +// Ported from the testbed (B9), N-P1-4: known_hosts has only the ed25519 +// key, the server offers ed25519+ECDSA; Go would pick ECDSA and raise a +// false "host key changed". +func TestHostKeyAlgoMismatch(t *testing.T) { + e := newEnv(t) + ed, ec := sshtest.GenKeys(t) + srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ec, ed}}) + e.trust(srv.Addr, ed.PublicKey()) + d := e.dialer(DialOptions{}) + l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if err != nil { + t.Fatalf("connect with a valid known ed25519 key: %v", err) + } + defer l.close() + if want := IdentityOf(ed.PublicKey()); l.id != want { + t.Errorf("identity = %+v, want %+v", l.id, want) + } + if got := d.hosts.algorithms(srv.Addr); len(got) != 1 || got[0] != ssh.KeyAlgoED25519 { + t.Errorf("algorithms = %v", got) + } +} + +func TestHostKeyAlgorithmsRSA(t *testing.T) { + e := newEnv(t) + _, ec := sshtest.GenKeys(t) + rsaPub, err := ssh.ParsePublicKey(testRSAPublicKeyWire(t)) + if err != nil { + t.Fatal(err) + } + e.trust("[h]:2222", rsaPub, ec.PublicKey()) + d := e.dialer(DialOptions{}) + got := d.hosts.algorithms("h:2222") + want := []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA, ssh.KeyAlgoECDSA256} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("algorithms = %v, want %v", got, want) + } + if got := d.hosts.algorithms("other:22"); got != nil { + t.Errorf("unknown host algorithms = %v, want nil", got) + } +} + +func TestHostKeyChangedRejected(t *testing.T) { + e := newEnv(t) + ed, _ := sshtest.GenKeys(t) + stale, _ := sshtest.GenKeys(t) + srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed}}) + e.trust(srv.Addr, stale.PublicKey()) + before, _ := os.ReadFile(e.kh) + + // No prompter: refused. + d := e.dialer(DialOptions{}) + _, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if !errors.Is(err, ErrHostKeyChanged) { + t.Fatalf("err = %v, want ErrHostKeyChanged", err) + } + var hke *HostKeyError + if !errors.As(err, &hke) || !hke.Changed || len(hke.Known) != 1 || hke.Known[0] != IdentityOf(stale.PublicKey()) { + t.Errorf("HostKeyError = %+v", hke) + } + + // Prompter told about the change, rejects. + p := &fakePrompter{} + d = e.dialer(DialOptions{Prompter: p}) + _, err = d.dial(context.Background(), endpointFor(srv.Addr, srv.Password)) + if !errors.Is(err, ErrHostKeyChanged) { + t.Fatalf("err = %v, want ErrHostKeyChanged", err) + } + if len(p.hostKeys) != 1 || !p.hostKeys[0].changed { + t.Errorf("prompter calls = %+v, want one with changed=true", p.hostKeys) + } + after, _ := os.ReadFile(e.kh) + if !bytes.Equal(before, after) { + t.Error("known_hosts modified on a rejected changed key") + } +} + +// N-P2-14: an unknown host goes to the Prompter instead of silent TOFU. +func TestUnknownHostAsksPrompter(t *testing.T) { + e := newEnv(t) + srv := sshtest.Start(t, sshtest.Options{}) + ep := endpointFor(srv.Addr, srv.Password) + + t.Run("Reject", func(t *testing.T) { + p := &fakePrompter{} + _, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if !errors.Is(err, ErrHostKeyRejected) { + t.Fatalf("err = %v, want ErrHostKeyRejected", err) + } + if n, _, _, _ := p.counts(); n != 1 || p.hostKeys[0].changed || len(p.hostKeys[0].known) != 0 { + t.Errorf("prompter calls = %+v", p.hostKeys) + } + if _, err := os.Stat(e.kh); !os.IsNotExist(err) { + t.Error("known_hosts written on Reject") + } + }) + + t.Run("NoPrompter", func(t *testing.T) { + _, err := e.dialer(DialOptions{}).dial(context.Background(), ep) + if !errors.Is(err, ErrHostKeyRejected) { + t.Fatalf("err = %v, want ErrHostKeyRejected", err) + } + }) + + t.Run("AcceptOnce", func(t *testing.T) { + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptOnce, nil }} + d := e.dialer(DialOptions{Prompter: p}) + for i := 0; i < 2; i++ { + l, err := d.dial(context.Background(), ep) + if err != nil { + t.Fatal(err) + } + l.close() + } + if n, _, _, _ := p.counts(); n != 1 { + t.Errorf("asked %d times, want once per process", n) + } + if _, err := os.Stat(e.kh); !os.IsNotExist(err) { + t.Error("known_hosts written on AcceptOnce") + } + }) + + t.Run("AcceptAndSave", func(t *testing.T) { + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }} + l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if err != nil { + t.Fatal(err) + } + l.close() + data, err := os.ReadFile(e.kh) + if err != nil || !strings.Contains(string(data), "127.0.0.1") { + t.Fatalf("known_hosts = %q, %v", data, err) + } + if fi, _ := os.Stat(e.kh); fi.Mode().Perm() != 0o600 { + t.Errorf("known_hosts mode %v", fi.Mode().Perm()) + } + // A fresh process (dialer) trusts it without asking. + l, err = e.dialer(DialOptions{}).dial(context.Background(), ep) + if err != nil { + t.Fatalf("saved key not trusted: %v", err) + } + l.close() + }) + + t.Run("MemoryOnlyWarns", func(t *testing.T) { + os.Remove(e.kh) + var warns []string + var mu sync.Mutex + p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }} + d := e.dialer(DialOptions{Prompter: p, KnownHostsWrite: "-", Warn: func(s string) { + mu.Lock() + warns = append(warns, s) + mu.Unlock() + }}) + l, err := d.dial(context.Background(), ep) + if err != nil { + t.Fatal(err) + } + l.close() + if len(warns) != 1 || !strings.Contains(warns[0], "session only") { + t.Errorf("warnings = %q", warns) + } + if _, err := os.Stat(e.kh); !os.IsNotExist(err) { + t.Error("known_hosts written in memory-only mode") + } + }) +} + +// N-P2-2: a rejected IdentityFile used to end authentication; the agent +// must still be tried. +func TestAuthFallbackToAgentAfterIdentityRejected(t *testing.T) { + e := newEnv(t) + agentPriv, agentSigner := newKey(t) + otherPriv, _ := newKey(t) + idPath := filepath.Join(e.home, ".ssh", "id_other") + writeKey(t, idPath, otherPriv, "") + ag := startAgent(t, agentPriv) + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{agentSigner.PublicKey()}}) + d := e.dialer(DialOptions{AgentSocket: ag.sock}) + ep := endpointFor(srv.Addr, "") + ep.IdentityFiles = []string{idPath, filepath.Join(e.home, ".ssh", "missing")} + l, err := d.dial(context.Background(), ep) + if err != nil { + t.Fatalf("agent key not tried after the identity file was rejected: %v", err) + } + l.close() + + // IdentitiesOnly: the agent key is not offered. + ep.IdentitiesOnly = true + if _, err := d.dial(context.Background(), ep); err == nil { + t.Fatal("IdentitiesOnly must not offer unrelated agent keys") + } +} + +func TestAuthDefaultIdentityAndPasswordFallback(t *testing.T) { + e := newEnv(t) + priv, signer := newKey(t) + writeKey(t, filepath.Join(e.home, ".ssh", "id_ed25519"), priv, "") + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}}) + l, err := e.dialer(DialOptions{}).dial(context.Background(), endpointFor(srv.Addr, "")) + if err != nil { + t.Fatalf("default identity: %v", err) + } + l.close() + + // Password server: keys are offered and rejected, the prompter's password works. + srv2 := e.startTrusted(sshtest.Options{Password: "s3cret"}) + p := &fakePrompter{password: func(context.Context) (string, error) { return "s3cret", nil }} + l, err = e.dialer(DialOptions{Prompter: p}).dial(context.Background(), endpointFor(srv2.Addr, "")) + if err != nil { + t.Fatalf("prompted password: %v", err) + } + l.close() + if _, pw, _, _ := p.counts(); pw != 1 { + t.Errorf("password asked %d times", pw) + } +} + +// N-P2-2: keyboard-interactive questions reach the Prompter as they are +// (the old code answered every question, 2FA included, with the password). +func TestKeyboardInteractiveUsesPrompter(t *testing.T) { + e := newEnv(t) + qs := []string{"Password: ", "Verification code: "} + echo := []bool{false, true} + addr, hostKey := kiServer(t, qs, echo, []string{"pw", "123456"}) + e.trust(addr, hostKey) + p := &fakePrompter{ki: func([]string) ([]string, error) { return []string{"pw", "123456"}, nil }} + ep := endpointFor(addr, "pw") // the stored password must not answer the 2FA question + l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if err != nil { + t.Fatalf("keyboard-interactive: %v", err) + } + l.close() + if len(p.kiCalls) != 1 || strings.Join(p.kiCalls[0], "|") != strings.Join(qs, "|") || + p.kiEcho[0][0] || !p.kiEcho[0][1] { + t.Errorf("prompter saw %q echo %v", p.kiCalls, p.kiEcho) + } + if !strings.Contains(p.kiInstr[0], "Two factors please") { + t.Errorf("instruction = %q", p.kiInstr[0]) + } + + // A lone hidden question is answered with the stored password. + addr2, hostKey2 := kiServer(t, []string{"Password: "}, []bool{false}, []string{"pw"}) + e.trust(addr2, hostKey2) + p2 := &fakePrompter{} + l, err = e.dialer(DialOptions{Prompter: p2}).dial(context.Background(), endpointFor(addr2, "pw")) + if err != nil { + t.Fatalf("stored password via keyboard-interactive: %v", err) + } + l.close() + if _, _, ki, _ := p2.counts(); ki != 0 { + t.Errorf("prompter asked %d times", ki) + } +} + +// N-P2-1: one agent connection per process, not one per connect. +func TestAgentConnectionShared(t *testing.T) { + e := newEnv(t) + priv, signer := newKey(t) + ag := startAgent(t, priv) + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}}) + d := newDialer(DialOptions{Home: e.home, AgentSocket: ag.sock, KnownHostsFiles: []string{e.kh}}) + ep := endpointFor(srv.Addr, "") + var wg sync.WaitGroup + errs := make(chan error, 6) + for i := 0; i < 6; i++ { + wg.Add(1) + go func() { + defer wg.Done() + l, err := d.dial(context.Background(), ep) + if err == nil { + l.close() + } + errs <- err + }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + if n := ag.accepts.Load(); n != 1 { + t.Errorf("agent connections = %d, want 1", n) + } + d.close() + waitFor(t, 2*time.Second, "agent connection closed", func() bool { return ag.active.Load() == 0 }) +} + +// An encrypted key is decrypted only when the server accepts it. +func TestPassphraseAskedLazily(t *testing.T) { + e := newEnv(t) + accPriv, accSigner := newKey(t) + rejPriv, _ := newKey(t) + rej := filepath.Join(e.home, ".ssh", "id_rejected") + acc := filepath.Join(e.home, ".ssh", "id_accepted") + writeKey(t, rej, rejPriv, "one") + writeKey(t, acc, accPriv, "two") + srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{accSigner.PublicKey()}}) + tries := 0 + p := &fakePrompter{passphrase: func(path string) ([]byte, error) { + tries++ + if tries == 1 { + return []byte("wrong"), nil + } + return []byte("two"), nil + }} + ep := endpointFor(srv.Addr, "") + ep.IdentityFiles = []string{rej, acc} + l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep) + if err != nil { + t.Fatalf("encrypted key: %v", err) + } + l.close() + for _, ph := range p.phrases { + if ph != acc { + t.Errorf("passphrase asked for %s (server never accepted it)", ph) + } + } + if len(p.phrases) != 2 { + t.Errorf("passphrase asked %d times, want 2 (one wrong attempt)", len(p.phrases)) + } +} + +// testRSAPublicKeyWire returns an RSA public key in wire format. Only the +// type matters here, so the modulus is arbitrary (no slow key generation). +func testRSAPublicKeyWire(t *testing.T) []byte { + t.Helper() + n := new(big.Int).Lsh(big.NewInt(1), 2047) + n.Add(n, big.NewInt(12345)) + pub, err := ssh.NewPublicKey(&rsa.PublicKey{N: n, E: 65537}) + if err != nil { + t.Fatal(err) + } + return pub.Marshal() +} diff --git a/internal/ssh/conn/exec.go b/internal/ssh/conn/exec.go new file mode 100644 index 0000000..f1e1ef0 --- /dev/null +++ b/internal/ssh/conn/exec.go @@ -0,0 +1,195 @@ +package conn + +import ( + "bytes" + "context" + "errors" + "fmt" + "strings" + "sync" + + "golang.org/x/crypto/ssh" +) + +// DefaultExecLimit caps the captured stdout of Exec (§3.4). +const DefaultExecLimit = 1 << 20 + +// stderrLimit caps the stderr kept for ExitError. +const stderrLimit = 4 << 10 + +// ErrOutputLimit: the command printed more than the limit; it was killed +// and the output truncated (N-P2-15). +var ErrOutputLimit = errors.New("command output exceeds limit") + +// ExitError is a non-zero exit status. +type ExitError struct { + Code int + Stderr string // first 4 KiB +} + +func (e *ExitError) Error() string { + msg := strings.TrimSpace(e.Stderr) + if msg == "" { + return fmt.Sprintf("remote command exited with status %d", e.Code) + } + return fmt.Sprintf("remote command exited with status %d: %s", e.Code, msg) +} + +// Quote joins argv into a POSIX shell command line, quoting every argument +// that is not made of safe characters only. +func Quote(argv []string) string { + parts := make([]string, len(argv)) + for i, a := range argv { + parts[i] = quoteArg(a) + } + return strings.Join(parts, " ") +} + +func quoteArg(a string) string { + if a == "" { + return "''" + } + safe := true + for _, r := range a { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_./=:,+@%", r)) { + safe = false + break + } + } + if safe { + return a + } + return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'" +} + +// limitWriter keeps at most limit bytes and calls overflow once when more +// arrive. +type limitWriter struct { + mu sync.Mutex + buf bytes.Buffer + limit int64 + over bool + overflow func() +} + +func (w *limitWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.over { + return 0, ErrOutputLimit + } + room := w.limit - int64(w.buf.Len()) + if int64(len(p)) <= room { + return w.buf.Write(p) + } + w.buf.Write(p[:room]) + w.over = true + if w.overflow != nil { + go w.overflow() + } + return int(room), ErrOutputLimit +} + +func (w *limitWriter) bytes() ([]byte, bool) { + w.mu.Lock() + defer w.mu.Unlock() + return append([]byte(nil), w.buf.Bytes()...), w.over +} + +// Exec runs argv on the server (arguments are shell-quoted) and returns its +// stdout (at most limit bytes; <= 0 means DefaultExecLimit) and exit code. +// A non-zero exit returns *ExitError along with the code. Cancelling ctx +// sends SIGKILL and closes the session immediately (N-P1-7); output over +// the limit kills the command and returns ErrOutputLimit with the +// truncated output. Code is -1 when there is no exit status. +func (c *Conn) Exec(ctx context.Context, argv []string, limit int64) ([]byte, int, error) { + if len(argv) == 0 { + return nil, -1, errors.New("exec: empty command") + } + if limit <= 0 { + limit = DefaultExecLimit + } + client, err := c.SSH() + if err != nil { + return nil, -1, err + } + if err := ctx.Err(); err != nil { + return nil, -1, err + } + + var ( + mu sync.Mutex + sess *ssh.Session + killed bool + ) + kill := func() { + mu.Lock() + defer mu.Unlock() + killed = true + if sess != nil { + sess.Signal(ssh.SIGKILL) + sess.Close() + } + } + stdout := &limitWriter{limit: limit, overflow: kill} + stderr := &limitWriter{limit: stderrLimit} + type result struct{ err error } + done := make(chan result, 1) + go func() { + s, err := client.NewSession() + if err != nil { + done <- result{c.MapErr(err)} + return + } + mu.Lock() + if killed { + mu.Unlock() + s.Close() + done <- result{context.Canceled} + return + } + sess = s + mu.Unlock() + defer s.Close() + s.Stdout, s.Stderr = stdout, stderr + done <- result{s.Run(Quote(argv))} + }() + + var r result + select { + case r = <-done: + case <-ctx.Done(): + kill() + return nil, -1, ctx.Err() + } + out, over := stdout.bytes() + if over { + return out, -1, fmt.Errorf("%w (%d bytes)", ErrOutputLimit, limit) + } + if r.err == nil { + return out, 0, nil + } + var ee *ssh.ExitError + if errors.As(r.err, &ee) { + se, _ := stderr.bytes() + return out, ee.ExitStatus(), &ExitError{Code: ee.ExitStatus(), Stderr: string(se)} + } + return out, -1, c.MapErr(r.err) +} + +// ExecSupported reports whether the server runs commands (false for +// `ForceCommand internal-sftp`). Probed with `true`; only a definite answer +// is cached (a cancelled or lost probe is retried next time). +func (c *Conn) ExecSupported(ctx context.Context) bool { + c.execMu.Lock() + defer c.execMu.Unlock() + if c.execKnown { + return c.execOK + } + _, code, err := c.Exec(ctx, []string{"true"}, 64) + if ctx.Err() != nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) { + return false + } + c.execKnown, c.execOK = true, err == nil && code == 0 + return c.execOK +} diff --git a/internal/ssh/conn/helpers_test.go b/internal/ssh/conn/helpers_test.go new file mode 100644 index 0000000..347b3fa --- /dev/null +++ b/internal/ssh/conn/helpers_test.go @@ -0,0 +1,401 @@ +package conn + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "errors" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/testutil/sshtest" +) + +// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the +// goroutine count returns to the baseline within ±2. +func noLeak(t *testing.T, fn func(t *testing.T)) { + t.Helper() + runtime.GC() + base := runtime.NumGoroutine() + t.Run("body", fn) + deadline := time.Now().Add(5 * time.Second) + var n int + for time.Now().Before(deadline) { + n = runtime.NumGoroutine() + if n <= base+2 { + return + } + time.Sleep(20 * time.Millisecond) + } + buf := make([]byte, 1<<20) + buf = buf[:runtime.Stack(buf, true)] + t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf) +} + +// waitFor polls cond until it holds or d elapses. +func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out after %v waiting for %s", d, what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// env is an isolated HOME with helpers to dial the in-process server. +type env struct { + t *testing.T + home string + kh string // ~/.ssh/known_hosts +} + +func newEnv(t *testing.T) *env { + t.Helper() + home := sshtest.IsolatedHome(t) + return &env{t: t, home: home, kh: filepath.Join(home, ".ssh", "known_hosts")} +} + +// dialer returns a dialer rooted at the env HOME; the agent is disabled +// unless o.AgentSocket is set. +func (e *env) dialer(o DialOptions) *dialer { + if o.Home == "" { + o.Home = e.home + } + if o.AgentSocket == "" { + o.AgentSocket = "-" + } + if o.KnownHostsFiles == nil { + o.KnownHostsFiles = []string{e.kh} + } + d := newDialer(o) + e.t.Cleanup(d.close) + return d +} + +// trust writes known_hosts lines for addr. +func (e *env) trust(addr string, keys ...ssh.PublicKey) { + e.t.Helper() + var data []byte + for _, k := range keys { + data = append(data, knownhosts.Line([]string{knownhosts.Normalize(addr)}, k)+"\n"...) + } + if err := os.WriteFile(e.kh, data, 0o600); err != nil { + e.t.Fatal(err) + } +} + +func endpointFor(addr, password string) Endpoint { + host, port, _ := net.SplitHostPort(addr) + p, _ := strconv.Atoi(port) + return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password} +} + +// proxy starts a proxy in front of srv and trusts srv's keys at the proxy +// address too. +func (e *env) proxy(srv *sshtest.Server) *sshtest.Proxy { + px := sshtest.NewProxy(e.t, srv.Addr) + old, _ := os.ReadFile(e.kh) + var pubs []ssh.PublicKey + for _, k := range srv.HostKeys { + pubs = append(pubs, k.PublicKey()) + } + e.trust(px.Addr, pubs...) + added, _ := os.ReadFile(e.kh) + if err := os.WriteFile(e.kh, append(old, added...), 0o600); err != nil { + e.t.Fatal(err) + } + return px +} + +// startTrusted starts a server whose host keys are in known_hosts. +func (e *env) startTrusted(o sshtest.Options) *sshtest.Server { + srv := sshtest.Start(e.t, o) + var pubs []ssh.PublicKey + for _, k := range srv.HostKeys { + pubs = append(pubs, k.PublicKey()) + } + e.trust(srv.Addr, pubs...) + return srv +} + +func (l *link) closeOnCleanup(t *testing.T) *link { + t.Cleanup(l.close) + return l +} + +// fakePrompter records calls and answers with the configured functions. +type fakePrompter struct { + mu sync.Mutex + hostKeys []hostKeyCall + passwords int + kiCalls [][]string + kiEcho [][]bool + kiInstr []string + phrases []string + + hostKey func(ctx context.Context, changed bool) (HostKeyDecision, error) + password func(ctx context.Context) (string, error) + ki func(qs []string) ([]string, error) + passphrase func(path string) ([]byte, error) +} + +type hostKeyCall struct { + id HostIdentity + known []HostIdentity + changed bool +} + +func (p *fakePrompter) HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) { + p.mu.Lock() + p.hostKeys = append(p.hostKeys, hostKeyCall{id, known, changed}) + p.mu.Unlock() + if p.hostKey == nil { + return Reject, nil + } + return p.hostKey(ctx, changed) +} + +func (p *fakePrompter) Password(ctx context.Context, ep Endpoint) (string, error) { + p.mu.Lock() + p.passwords++ + p.mu.Unlock() + if p.password == nil { + return "", errors.New("no password") + } + return p.password(ctx) +} + +func (p *fakePrompter) KeyboardInteractive(ctx context.Context, ep Endpoint, instr string, qs []string, echo []bool) ([]string, error) { + p.mu.Lock() + p.kiCalls = append(p.kiCalls, append([]string(nil), qs...)) + p.kiEcho = append(p.kiEcho, append([]bool(nil), echo...)) + p.kiInstr = append(p.kiInstr, instr) + p.mu.Unlock() + if p.ki == nil { + return nil, errors.New("no answers") + } + return p.ki(qs) +} + +func (p *fakePrompter) Passphrase(ctx context.Context, path string) ([]byte, error) { + p.mu.Lock() + p.phrases = append(p.phrases, path) + p.mu.Unlock() + if p.passphrase == nil { + return nil, errors.New("no passphrase") + } + return p.passphrase(path) +} + +func (p *fakePrompter) counts() (hostKeys, passwords, ki, phrases int) { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.hostKeys), p.passwords, len(p.kiCalls), len(p.phrases) +} + +// newKey returns a fresh ed25519 private key and its signer. +func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + s, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + return priv, s +} + +// writeKey stores priv in OpenSSH format (encrypted when passphrase != ""). +func writeKey(t *testing.T, path string, priv ed25519.PrivateKey, passphrase string) { + t.Helper() + var blk *pem.Block + var err error + if passphrase == "" { + blk, err = ssh.MarshalPrivateKey(priv, "test") + } else { + blk, err = ssh.MarshalPrivateKeyWithPassphrase(priv, "test", []byte(passphrase)) + } + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, pem.EncodeToMemory(blk), 0o600); err != nil { + t.Fatal(err) + } +} + +// fakeAgent serves an in-memory keyring on a unix socket. +type fakeAgent struct { + sock string + accepts atomic.Int32 + active atomic.Int32 +} + +func startAgent(t *testing.T, keys ...ed25519.PrivateKey) *fakeAgent { + t.Helper() + kr := agent.NewKeyring() + for _, k := range keys { + if err := kr.Add(agent.AddedKey{PrivateKey: k}); err != nil { + t.Fatal(err) + } + } + dir, err := os.MkdirTemp("", "agent") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + a := &fakeAgent{sock: filepath.Join(dir, "s")} + ln, err := net.Listen("unix", a.sock) + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + var mu sync.Mutex + var conns []net.Conn + wg.Add(1) + go func() { + defer wg.Done() + for { + c, err := ln.Accept() + if err != nil { + return + } + a.accepts.Add(1) + a.active.Add(1) + mu.Lock() + conns = append(conns, c) + mu.Unlock() + wg.Add(1) + go func() { + defer wg.Done() + defer a.active.Add(-1) + agent.ServeAgent(kr, c) + c.Close() + }() + } + }() + t.Cleanup(func() { + ln.Close() + mu.Lock() + for _, c := range conns { + c.Close() + } + mu.Unlock() + wg.Wait() + }) + return a +} + +// kiServer is a minimal SSH server that only allows keyboard-interactive +// auth with the given questions; answers must equal want. It serves SFTP so +// the full dial path succeeds. +func kiServer(t *testing.T, questions []string, echo []bool, want []string) (string, ssh.PublicKey) { + t.Helper() + ed, _ := sshtest.GenKeys(t) + cfg := &ssh.ServerConfig{ + KeyboardInteractiveCallback: func(_ ssh.ConnMetadata, ch ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) { + ans, err := ch("vcom-test", "Two factors please", questions, echo) + if err != nil { + return nil, err + } + if len(ans) != len(want) { + return nil, errors.New("wrong answer count") + } + for i := range want { + if ans[i] != want[i] { + return nil, errors.New("wrong answer") + } + } + return nil, nil + }, + } + cfg.AddHostKey(ed) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + var mu sync.Mutex + var conns []net.Conn + wg.Add(1) + go func() { + defer wg.Done() + for { + nc, err := ln.Accept() + if err != nil { + return + } + mu.Lock() + conns = append(conns, nc) + mu.Unlock() + wg.Add(1) + go func() { + defer wg.Done() + defer nc.Close() + sc, chans, reqs, err := ssh.NewServerConn(nc, cfg) + if err != nil { + return + } + defer sc.Close() + go ssh.DiscardRequests(reqs) + for nch := range chans { + ch, creqs, err := nch.Accept() + if err != nil { + continue + } + wg.Add(1) + go func() { + defer wg.Done() + defer ch.Close() + for req := range creqs { + if req.Type == "subsystem" { + req.Reply(true, nil) + srv, err := sftp.NewServer(ch) + if err != nil { + return + } + go func() { + for range creqs { + } + }() + srv.Serve() + srv.Close() + return + } + req.Reply(false, nil) + } + }() + } + }() + } + }() + t.Cleanup(func() { + ln.Close() + mu.Lock() + for _, c := range conns { + c.Close() + } + mu.Unlock() + wg.Wait() + }) + return ln.Addr().String(), ed.PublicKey() +} diff --git a/internal/ssh/conn/hostkey.go b/internal/ssh/conn/hostkey.go new file mode 100644 index 0000000..7e65302 --- /dev/null +++ b/internal/ssh/conn/hostkey.go @@ -0,0 +1,272 @@ +package conn + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "sync" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/atomicfile" +) + +var ( + // ErrHostKeyRejected: the key is unknown and the user (or the absence of + // a Prompter) refused it. + ErrHostKeyRejected = errors.New("host key rejected") + // ErrHostKeyChanged: known_hosts has a different key of the same type. + ErrHostKeyChanged = errors.New("REMOTE HOST IDENTIFICATION HAS CHANGED") +) + +// HostKeyError describes a refused host key. It unwraps to +// ErrHostKeyChanged or ErrHostKeyRejected. +type HostKeyError struct { + Host string // host:port as checked against known_hosts + Identity HostIdentity + Known []HostIdentity + Changed bool +} + +func (e *HostKeyError) Error() string { + if e.Changed { + return fmt.Sprintf("%v for %s: server offers %s %s; remove the stale entry with `ssh-keygen -R %s` once the new key is verified", + ErrHostKeyChanged, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256, e.Host) + } + return fmt.Sprintf("%v: %s %s %s", ErrHostKeyRejected, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256) +} + +func (e *HostKeyError) Unwrap() error { + if e.Changed { + return ErrHostKeyChanged + } + return ErrHostKeyRejected +} + +// probeKey is a throwaway key that is never in known_hosts: checking it +// makes knownhosts report every key it has for a host (KeyError.Want). +var probeKey = sync.OnceValue(func() ssh.PublicKey { + pub, _, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + panic(err) + } + k, err := ssh.NewPublicKey(pub) + if err != nil { + panic(err) + } + return k +}) + +// knownHosts verifies host keys against known_hosts files plus keys +// accepted during this process. +type knownHosts struct { + files []string // read in order + write string // AcceptAndSave appends here ("" = memory only) + warn func(string) + + mu sync.Mutex + session map[string][]ssh.PublicKey // knownhosts.Normalize(host:port) -> keys +} + +func newKnownHosts(files []string, write string, warn func(string)) *knownHosts { + return &knownHosts{files: files, write: write, warn: warn, session: map[string][]ssh.PublicKey{}} +} + +// db parses the existing known_hosts files; nil when there are none. +func (h *knownHosts) db() (ssh.HostKeyCallback, error) { + var files []string + for _, f := range h.files { + if _, err := os.Stat(f); err == nil { + files = append(files, f) + } + } + if len(files) == 0 { + return nil, nil + } + return knownhosts.New(files...) +} + +// known returns every key on record for hostport (files, then session). +func (h *knownHosts) known(hostport string) []ssh.PublicKey { + var out []ssh.PublicKey + if cb, err := h.db(); err == nil && cb != nil { + var ke *knownhosts.KeyError + if err := cb(hostport, &net.TCPAddr{IP: net.IPv4zero}, probeKey()); errors.As(err, &ke) { + for _, k := range ke.Want { + out = append(out, k.Key) + } + } + } + h.mu.Lock() + out = append(out, h.session[knownhosts.Normalize(hostport)]...) + h.mu.Unlock() + return out +} + +// algorithms lists host key algorithms for the key types on record, so the +// server is asked for a key we can actually verify (N-P1-4: Go prefers ECDSA, +// OpenSSH usually records ed25519). nil means "library defaults". +func (h *knownHosts) algorithms(hostport string) []string { + var algos []string + seen := map[string]bool{} + add := func(a string) { + if !seen[a] { + seen[a] = true + algos = append(algos, a) + } + } + for _, k := range h.known(hostport) { + switch t := k.Type(); t { + case ssh.KeyAlgoRSA: + add(ssh.KeyAlgoRSASHA512) + add(ssh.KeyAlgoRSASHA256) + add(ssh.KeyAlgoRSA) + default: + add(t) + } + } + return algos +} + +func (h *knownHosts) sessionHas(hostport string, key ssh.PublicKey) bool { + h.mu.Lock() + defer h.mu.Unlock() + for _, k := range h.session[knownhosts.Normalize(hostport)] { + if string(k.Marshal()) == string(key.Marshal()) { + return true + } + } + return false +} + +func (h *knownHosts) remember(hostport string, key ssh.PublicKey) { + h.mu.Lock() + defer h.mu.Unlock() + n := knownhosts.Normalize(hostport) + h.session[n] = append(h.session[n], key) +} + +func (h *knownHosts) warnf(format string, args ...any) { + if h.warn != nil { + h.warn(fmt.Sprintf(format, args...)) + } +} + +// save appends a known_hosts line atomically (rewrite via temp copy). When +// the file belongs to another user (vcom under sudo) or cannot be written, +// the key is trusted for this process only and a warning is emitted +// (N-P2-14). +func (h *knownHosts) save(hostport string, key ssh.PublicKey) { + h.remember(hostport, key) + if h.write == "" { + h.warnf("host key for %s accepted for this session only (no known_hosts file configured)", hostport) + return + } + if foreignOwner(h.write) { + h.warnf("host key for %s accepted for this session only: %s belongs to another user", hostport, h.write) + return + } + h.mu.Lock() + defer h.mu.Unlock() + if err := appendKnownHost(h.write, knownhosts.Line([]string{knownhosts.Normalize(hostport)}, key)); err != nil { + h.warnf("host key for %s accepted for this session only: %v", hostport, err) + } +} + +func appendKnownHost(path, line string) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + perm := os.FileMode(0o600) + data, err := os.ReadFile(path) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + if fi, err := os.Stat(path); err == nil { + perm = fi.Mode().Perm() + } + if len(data) > 0 && data[len(data)-1] != '\n' { + data = append(data, '\n') + } + data = append(data, line+"\n"...) + return atomicfile.WriteFile(path, data, perm) +} + +// callback builds the HostKeyCallback for one dial. prompt wraps Prompter +// calls so the handshake deadline is paused while the user decides; onKey +// sees every key the server presents (also on later re-keys). +func (h *knownHosts) callback(ctx context.Context, ep Endpoint, p Prompter, prompt func(func() error) error, onKey func(HostIdentity)) ssh.HostKeyCallback { + return func(hostname string, remote net.Addr, key ssh.PublicKey) error { + id := IdentityOf(key) + onKey(id) + if h.sessionHas(hostname, key) { + return nil + } + var wants []ssh.PublicKey + cb, err := h.db() + if err != nil { + return fmt.Errorf("known_hosts: %w", err) + } + if cb != nil { + err := cb(hostname, remote, key) + if err == nil { + return nil + } + var ke *knownhosts.KeyError + if !errors.As(err, &ke) { + return err // revoked key, unreadable file, ... + } + for _, k := range ke.Want { + wants = append(wants, k.Key) + } + } + h.mu.Lock() + wants = append(wants, h.session[knownhosts.Normalize(hostname)]...) + h.mu.Unlock() + // Alarm only when a key of the same type is on record and differs; a + // key of a type we have no record for is merely unknown. + changed := false + known := make([]HostIdentity, 0, len(wants)) + for _, k := range wants { + known = append(known, IdentityOf(k)) + if k.Type() == key.Type() { + changed = true + } + } + herr := &HostKeyError{Host: hostname, Identity: id, Known: known, Changed: changed} + if p == nil { + return herr + } + var dec HostKeyDecision + if err := prompt(func() error { + var err error + dec, err = p.HostKey(ctx, ep, id, known, changed) + return err + }); err != nil { + return err + } + switch dec { + case AcceptOnce: + h.remember(hostname, key) + return nil + case AcceptAndSave: + if changed { + // Replacing a stale line is left to `ssh-keygen -R`; trust the + // new key for this process only. + h.remember(hostname, key) + h.warnf("changed host key for %s accepted for this session only", hostname) + return nil + } + h.save(hostname, key) + return nil + default: + return herr + } + } +} diff --git a/internal/ssh/conn/keepalive.go b/internal/ssh/conn/keepalive.go new file mode 100644 index 0000000..c78c874 --- /dev/null +++ b/internal/ssh/conn/keepalive.go @@ -0,0 +1,83 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "time" +) + +// errKeepalive is the reason recorded when keepalives go unanswered. +var errKeepalive = errors.New("no reply to keepalive") + +// keepalive sends keepalive@openssh.com every interval. KeepaliveMaxMiss +// unanswered requests in a row (each waits KeepaliveTimeout) close the SSH +// client: every pending request fails at once and the state becomes Lost +// (N-P1-2). Worst-case detection: interval*(maxMiss+1) + timeout. +func (c *Conn) keepalive(g *generation) { + t := time.NewTicker(c.opts.KeepaliveInterval) + defer t.Stop() + miss := 0 + for { + select { + case <-g.done: + return + case <-t.C: + } + if c.ping(g, c.opts.KeepaliveTimeout) { + miss = 0 + continue + } + miss++ + if miss >= c.opts.KeepaliveMaxMiss { + c.lose(g, fmt.Errorf("%w (%d × %v)", errKeepalive, miss, c.opts.KeepaliveTimeout)) + return + } + } +} + +// ping sends one keepalive and reports whether a reply (any reply: OpenSSH +// and x/crypto servers answer "failure" to unknown global requests) arrived +// within timeout. A request stuck on a dead link finishes when the client +// is closed (it is not tracked in c.wg: Probe may run concurrently with +// close, and WaitGroup.Add must not race with Wait). +func (c *Conn) ping(g *generation, timeout time.Duration) bool { + res := make(chan error, 1) + go func() { + _, _, err := g.ssh.SendRequest("keepalive@openssh.com", true, nil) + res <- err + }() + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case err := <-res: + return err == nil + case <-timer.C: + return false + case <-g.done: + return false + } +} + +// Probe is the operation watchdog (§3.4): when an SFTP call has hung for a +// long time, sftpfs sends an out-of-band keepalive. No reply within timeout +// marks the connection Lost (closing it, so the hung call returns) and +// returns ErrConnLost. ctx only bounds the wait; it does not mark anything. +func (c *Conn) Probe(ctx context.Context, timeout time.Duration) error { + if err := c.Err(); err != nil { + return err + } + g := c.cur.Load() + ok := make(chan bool, 1) + go func() { ok <- c.ping(g, timeout) }() + select { + case alive := <-ok: + if alive { + return nil + } + c.lose(g, fmt.Errorf("%w (probe, %v)", errKeepalive, timeout)) + return c.Err() + case <-ctx.Done(): + return ctx.Err() + } +} diff --git a/internal/ssh/conn/owner_other.go b/internal/ssh/conn/owner_other.go new file mode 100644 index 0000000..1b2ac6d --- /dev/null +++ b/internal/ssh/conn/owner_other.go @@ -0,0 +1,5 @@ +//go:build !unix + +package conn + +func foreignOwner(string) bool { return false } diff --git a/internal/ssh/conn/owner_unix.go b/internal/ssh/conn/owner_unix.go new file mode 100644 index 0000000..0ecb125 --- /dev/null +++ b/internal/ssh/conn/owner_unix.go @@ -0,0 +1,23 @@ +//go:build unix + +package conn + +import ( + "os" + "path/filepath" + "syscall" +) + +// foreignOwner reports whether path (or, if it does not exist, its parent +// directory) belongs to a user other than the effective one, e.g. the +// invoking user's ~/.ssh while vcom runs under sudo. +func foreignOwner(path string) bool { + fi, err := os.Stat(path) + if err != nil { + if fi, err = os.Stat(filepath.Dir(path)); err != nil { + return false + } + } + st, ok := fi.Sys().(*syscall.Stat_t) + return ok && int(st.Uid) != os.Geteuid() +} diff --git a/internal/ssh/conn/pool.go b/internal/ssh/conn/pool.go new file mode 100644 index 0000000..dcf4692 --- /dev/null +++ b/internal/ssh/conn/pool.go @@ -0,0 +1,328 @@ +package conn + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" +) + +// ErrPoolClosed is returned by Acquire after Pool.Close. +var ErrPoolClosed = errors.New("connection pool closed") + +// DefaultIdleClose is how long a connection without leases stays open. +const DefaultIdleClose = 60 * time.Second + +// DefaultReconnectBackoff: delays between Pool.Reconnect attempts (5 tries). +var DefaultReconnectBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second} + +// PoolOptions configure a Pool. +type PoolOptions struct { + DialOptions // Prompter, HandshakeTimeout, known_hosts, agent, ... + + KeepaliveInterval time.Duration // 15s (or ServerAliveInterval) + KeepaliveTimeout time.Duration // 10s + KeepaliveMaxMiss int // 2 (or ServerAliveCountMax) + // IdleClose closes a connection this long after its last lease is + // released. Default 60s; negative closes immediately. + IdleClose time.Duration + // ReconnectBackoff are the delays between Reconnect attempts; attempts + // = len+1. nil means DefaultReconnectBackoff (1,2,4,8s). + ReconnectBackoff []time.Duration + // OnEvent receives connection state changes (main forwards them with + // program.Send). Called from pool goroutines; must not block. + OnEvent func(Event) +} + +// Pool shares one connection per Endpoint.Key() among panels, jobs, +// previews and size counters. Each user holds a Lease; the pool alone +// closes connections: when the last lease has been released for IdleClose, +// or on Close (N-P0-8, N-P1-12). It is safe for concurrent use. +type Pool struct { + d *dialer + opts PoolOptions + + mu sync.Mutex + closed bool + entries map[string]*entry + inflight map[string]*call + wg sync.WaitGroup // dial goroutines and idle closes +} + +type entry struct { + key string + conn *Conn + refs int + idle *time.Timer + seq uint64 // invalidates stale idle timers +} + +// call is one in-flight dial shared by every concurrent Acquire of a key. +type call struct { + done chan struct{} + waiters int + cancel context.CancelFunc + e *entry + err error +} + +// NewPool creates a pool. +func NewPool(o PoolOptions) *Pool { + if o.IdleClose == 0 { + o.IdleClose = DefaultIdleClose + } + if o.ReconnectBackoff == nil { + o.ReconnectBackoff = DefaultReconnectBackoff + } + return &Pool{ + d: newDialer(o.DialOptions), + opts: o, + entries: map[string]*entry{}, + inflight: map[string]*call{}, + } +} + +func (p *Pool) connOptions() ConnOptions { + return ConnOptions{ + KeepaliveInterval: p.opts.KeepaliveInterval, + KeepaliveTimeout: p.opts.KeepaliveTimeout, + KeepaliveMaxMiss: p.opts.KeepaliveMaxMiss, + OnEvent: p.opts.OnEvent, + } +} + +// Acquire returns a lease on the connection for ep, dialing it if needed. +// Concurrent Acquires of the same key share one dial (N-P2-8: a double +// Enter makes one connection). A Lost connection gets one reconnect +// attempt. If every waiter gives up (ctx), the dial is cancelled; a dial +// that still completes is parked idle and closed after IdleClose. +func (p *Pool) Acquire(ctx context.Context, ep Endpoint) (*Lease, error) { + key := ep.Key() + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil, ErrPoolClosed + } + if e := p.entries[key]; e != nil { + l := p.lease(e) + p.mu.Unlock() + if e.conn.State() == Lost { + if err := e.conn.Reconnect(ctx); err != nil { + l.Release() + return nil, err + } + } + return l, nil + } + c := p.inflight[key] + if c == nil { + dctx, cancel := context.WithCancel(context.Background()) + c = &call{done: make(chan struct{}), cancel: cancel} + p.inflight[key] = c + p.wg.Add(1) + go p.dial(dctx, key, ep, c) + } + c.waiters++ + p.mu.Unlock() + + select { + case <-c.done: + case <-ctx.Done(): + p.mu.Lock() + c.waiters-- + select { + case <-c.done: + // Finished concurrently: the entry may now have no users. + if c.e != nil && c.e.refs == 0 { + p.startIdle(c.e) + } + default: + if c.waiters == 0 { + c.cancel() + } + } + p.mu.Unlock() + return nil, ctx.Err() + } + if c.err != nil { + return nil, c.err + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed || p.entries[key] != c.e { + return nil, ErrPoolClosed + } + return p.lease(c.e), nil +} + +func (p *Pool) dial(ctx context.Context, key string, ep Endpoint, c *call) { + defer p.wg.Done() + conn, err := p.d.connect(ctx, ep, p.connOptions()) + c.cancel() + p.mu.Lock() + delete(p.inflight, key) + if err == nil && p.closed { + err = ErrPoolClosed + p.mu.Unlock() + conn.close() + p.mu.Lock() + } + c.err = err + if err == nil { + c.e = &entry{key: key, conn: conn} + p.entries[key] = c.e + if c.waiters == 0 { + p.startIdle(c.e) // everyone gave up; keep briefly, then close + } + } + close(c.done) + p.mu.Unlock() +} + +// lease takes a reference on e; p.mu is held. +func (p *Pool) lease(e *entry) *Lease { + e.refs++ + e.seq++ + if e.idle != nil { + e.idle.Stop() + e.idle = nil + } + return &Lease{p: p, e: e} +} + +// startIdle schedules e to close after IdleClose; p.mu is held. +func (p *Pool) startIdle(e *entry) { + e.seq++ + seq := e.seq + if e.idle != nil { + e.idle.Stop() + } + fire := func() { + p.mu.Lock() + if e.seq != seq || e.refs != 0 || p.entries[e.key] != e { + p.mu.Unlock() + return + } + delete(p.entries, e.key) + // The entry was still registered, so Close has not started waiting: + // this Add cannot race with p.wg.Wait. + p.wg.Add(1) + p.mu.Unlock() + defer p.wg.Done() + e.conn.close() + } + if p.opts.IdleClose < 0 { + e.idle = nil + go fire() + return + } + e.idle = time.AfterFunc(p.opts.IdleClose, fire) +} + +func (p *Pool) release(e *entry) { + p.mu.Lock() + defer p.mu.Unlock() + e.refs-- + if e.refs == 0 && !p.closed && p.entries[e.key] == e { + p.startIdle(e) + } +} + +// Reconnect re-dials a Lost connection with backoff (1,2,4,8s between at +// most 5 attempts by default). A Ready connection is left alone. Host key +// problems and ctx cancellation stop the retries. +func (p *Pool) Reconnect(ctx context.Context, key string) error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return ErrPoolClosed + } + e := p.entries[key] + p.mu.Unlock() + if e == nil { + return ErrClosed + } + var err error + for i := 0; ; i++ { + if err = e.conn.Reconnect(ctx); err == nil { + return nil + } + if errors.Is(err, ErrClosed) || errors.Is(err, ErrHostKeyChanged) || + errors.Is(err, ErrHostKeyRejected) || errors.Is(err, ErrIdentityChanged) || ctx.Err() != nil { + return err + } + if i >= len(p.opts.ReconnectBackoff) { + return err + } + t := time.NewTimer(p.opts.ReconnectBackoff[i]) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return ctx.Err() + } + } +} + +// Close closes every connection, cancels pending dials and waits for them. +// Leases stay safe to use: their calls fail with ErrClosed. +func (p *Pool) Close() error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil + } + p.closed = true + var conns []*Conn + for k, e := range p.entries { + if e.idle != nil { + e.idle.Stop() + } + e.seq++ + conns = append(conns, e.conn) + delete(p.entries, k) + } + for _, c := range p.inflight { + c.cancel() + } + p.mu.Unlock() + for _, c := range conns { + c.close() + } + p.wg.Wait() + p.d.close() + return nil +} + +// Lease is one user's reference to a pooled connection. Release it when +// done; it is idempotent. A lease stays safe to use after the connection +// died or the pool closed: calls return errors, never panic. +type Lease struct { + p *Pool + e *entry + released atomic.Bool +} + +// Conn returns the leased connection. +func (l *Lease) Conn() *Conn { return l.e.conn } + +// Client is shorthand for Conn().Client(). +func (l *Lease) Client() (*sftp.Client, error) { return l.e.conn.Client() } + +// Acquire takes another reference to the same connection (mirror panel, +// background job). Release each lease separately. +func (l *Lease) Acquire() *Lease { + l.p.mu.Lock() + defer l.p.mu.Unlock() + return l.p.lease(l.e) +} + +// Release drops this reference; the second and later calls do nothing. +func (l *Lease) Release() { + if l.released.CompareAndSwap(false, true) { + l.p.release(l.e) + } +} diff --git a/internal/ssh/conn/pool_test.go b/internal/ssh/conn/pool_test.go new file mode 100644 index 0000000..91a1a1d --- /dev/null +++ b/internal/ssh/conn/pool_test.go @@ -0,0 +1,339 @@ +package conn + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "vcom/internal/testutil/sshtest" +) + +func (e *env) pool(o PoolOptions) *Pool { + e.t.Helper() + if o.Home == "" { + o.Home = e.home + } + if o.AgentSocket == "" { + o.AgentSocket = "-" + } + if o.KnownHostsFiles == nil { + o.KnownHostsFiles = []string{e.kh} + } + p := NewPool(o) + e.t.Cleanup(func() { p.Close() }) + return p +} + +func (p *Pool) entryCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.entries) +} + +func mustAcquire(t *testing.T, p *Pool, ep Endpoint) *Lease { + t.Helper() + l, err := p.Acquire(context.Background(), ep) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + return l +} + +// Ported from TestCloseRace (B5), N-P0-8: Close raced with running calls +// and could call a method on a nil *sftp.Client. Leases are used, released, +// re-acquired and the pool closed concurrently under -race. +func TestLeaseReleaseRace(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + p := e.pool(PoolOptions{IdleClose: 10 * time.Millisecond}) + ep := endpointFor(srv.Addr, srv.Password) + base := mustAcquire(t, p, ep) + dir := t.TempDir() + + var wg sync.WaitGroup + panicked := make(chan any, 8) + worker := func(fn func(i int)) { + wg.Add(1) + go func() { + defer wg.Done() + defer func() { + if r := recover(); r != nil { + panicked <- r + } + }() + for i := 0; i < 300; i++ { + fn(i) + } + }() + } + for w := 0; w < 3; w++ { + worker(func(int) { + l := base.Acquire() + defer l.Release() + defer l.Release() // idempotent + if sc, err := l.Client(); err == nil { + _, err := sc.ReadDir(dir) + if err != nil && !errors.Is(l.Conn().MapErr(err), ErrClosed) && !errors.Is(l.Conn().MapErr(err), ErrConnLost) { + t.Errorf("ReadDir: %v", err) + } + } + }) + } + worker(func(int) { + if l, err := p.Acquire(context.Background(), ep); err == nil { + l.Conn().State() + l.Release() + } + }) + worker(func(i int) { + switch i { + case 0: + time.Sleep(50 * time.Millisecond) // let the readers get going + case 1: + p.Close() + } + }) + wg.Wait() + close(panicked) + for r := range panicked { + t.Fatalf("panic: %v", r) + } + if _, err := base.Client(); !errors.Is(err, ErrClosed) { + t.Errorf("Client after pool Close: %v", err) + } + if _, err := p.Acquire(context.Background(), ep); !errors.Is(err, ErrPoolClosed) { + t.Errorf("Acquire after Close: %v", err) + } + base.Release() + }) +} + +// N-P2-8: a double Enter made two connections. +func TestAcquireSingleflight(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + px.SetDelay(20 * time.Millisecond) // keep the dial in flight while all callers arrive + p := e.pool(PoolOptions{}) + ep := endpointFor(px.Addr, srv.Password) + const n = 10 + leases := make([]*Lease, n) + errs := make([]error, n) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + leases[i], errs[i] = p.Acquire(context.Background(), ep) + }() + } + wg.Wait() + for i := 0; i < n; i++ { + if errs[i] != nil { + t.Fatal(errs[i]) + } + if leases[i].Conn() != leases[0].Conn() { + t.Error("leases on different connections") + } + } + if d := p.d.dials.Load(); d != 1 { + t.Errorf("dials = %d, want 1", d) + } + // Same user@host:port through another alias shares the connection. + ep2 := ep + ep2.Alias = "other-alias" + l := mustAcquire(t, p, ep2) + if l.Conn() != leases[0].Conn() || p.d.dials.Load() != 1 { + t.Error("alias with the same key did not share the connection") + } +} + +// Every caller gave up: the dial is cancelled and nothing stays open. +func TestAcquireAllWaitersGone(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + px.Freeze(true) + p := e.pool(PoolOptions{}) + ep := endpointFor(px.Addr, srv.Password) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + if _, err := p.Acquire(ctx, ep); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v", err) + } + if el := time.Since(start); el > time.Second { + t.Errorf("Acquire returned after %v", el) + } + waitFor(t, 2*time.Second, "in-flight dial gone", func() bool { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.inflight) == 0 && len(p.entries) == 0 + }) + px.Freeze(false) + }) +} + +func TestIdleClose(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + var ev events + p := e.pool(PoolOptions{IdleClose: 150 * time.Millisecond, OnEvent: ev.add}) + ep := endpointFor(srv.Addr, srv.Password) + l := mustAcquire(t, p, ep) + c := l.Conn() + l.Release() + l = mustAcquire(t, p, ep) // within IdleClose: reused + if l.Conn() != c || p.d.dials.Load() != 1 { + t.Fatal("connection not reused within IdleClose") + } + time.Sleep(300 * time.Millisecond) + if c.State() != Ready { + t.Fatal("connection with a live lease was closed") + } + l.Release() + waitFor(t, 2*time.Second, "idle close", func() bool { return ev.has(Closed) && p.entryCount() == 0 }) + if c.State() != Closed { + t.Errorf("state = %v", c.State()) + } + l = mustAcquire(t, p, ep) + if l.Conn() == c || p.d.dials.Load() != 2 { + t.Error("expected a fresh connection after idle close") + } + l.Release() +} + +// N-P1-12: mirror shared one client and a second mirror closed it. +func TestMirrorLeaseSurvivesRelease(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + p := e.pool(PoolOptions{IdleClose: -1}) + left := mustAcquire(t, p, endpointFor(srv.Addr, srv.Password)) + right := left.Acquire() // mirror + left.Release() + left.Release() + left.Release() // over-release must not steal right's reference + sc, err := right.Client() + if err != nil { + t.Fatalf("mirror lease broken: %v", err) + } + if _, err := sc.ReadDir(t.TempDir()); err != nil { + t.Fatalf("ReadDir on mirror: %v", err) + } + c := right.Conn() + right.Release() + waitFor(t, 2*time.Second, "close after last release", func() bool { return c.State() == Closed }) +} + +func TestAcquireReconnectsLost(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + p := e.pool(PoolOptions{}) + ep := endpointFor(px.Addr, srv.Password) + l := mustAcquire(t, p, ep) + defer l.Release() + px.KillAll() + waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost }) + l2 := mustAcquire(t, p, ep) + defer l2.Release() + if l2.Conn() != l.Conn() || l.Conn().State() != Ready || l.Conn().Gen() != 2 { + t.Errorf("state %v gen %d", l.Conn().State(), l.Conn().Gen()) + } + if _, err := l.Client(); err != nil { + t.Errorf("old lease after reconnect: %v", err) + } +} + +func TestPoolReconnectBackoff(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + var mu sync.Mutex + connecting := 0 + p := e.pool(PoolOptions{ + ReconnectBackoff: []time.Duration{10 * time.Millisecond, 10 * time.Millisecond}, + OnEvent: func(ev Event) { + if ev.State == Connecting { + mu.Lock() + connecting++ + mu.Unlock() + } + }, + }) + ep := endpointFor(px.Addr, srv.Password) + l := mustAcquire(t, p, ep) + defer l.Release() + px.Freeze(true) + px.KillAll() + waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost }) + p.d.opts.HandshakeTimeout = 100 * time.Millisecond + if err := p.Reconnect(context.Background(), ep.Key()); err == nil { + t.Fatal("reconnect through a frozen link succeeded") + } + mu.Lock() + if connecting != 3 { + t.Errorf("attempts = %d, want 3", connecting) + } + mu.Unlock() + px.Freeze(false) + if err := p.Reconnect(context.Background(), ep.Key()); err != nil { + t.Fatalf("reconnect after recovery: %v", err) + } + if l.Conn().State() != Ready { + t.Errorf("state = %v", l.Conn().State()) + } + if err := p.Reconnect(context.Background(), "nobody@nowhere:22"); !errors.Is(err, ErrClosed) { + t.Errorf("unknown key: %v", err) + } +} + +func TestPoolCloseCancelsDial(t *testing.T) { + noLeak(t, func(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + px := e.proxy(srv) + px.Freeze(true) + p := e.pool(PoolOptions{}) + res := make(chan error, 1) + go func() { + _, err := p.Acquire(context.Background(), endpointFor(px.Addr, srv.Password)) + res <- err + }() + waitFor(t, time.Second, "dial in flight", func() bool { return p.d.dials.Load() == 1 }) + start := time.Now() + p.Close() + select { + case err := <-res: + if err == nil { + t.Fatal("Acquire succeeded on a closed pool") + } + case <-time.After(2 * time.Second): + t.Fatal("Acquire still blocked after Close") + } + if el := time.Since(start); el > time.Second { + t.Errorf("Close took %v", el) + } + px.Freeze(false) + }) +} + +func TestPoolDifferentUsersSeparate(t *testing.T) { + e := newEnv(t) + srv := e.startTrusted(sshtest.Options{}) + p := e.pool(PoolOptions{}) + a := endpointFor(srv.Addr, srv.Password) + b := a + b.User = "other" + la, lb := mustAcquire(t, p, a), mustAcquire(t, p, b) + defer la.Release() + defer lb.Release() + if la.Conn() == lb.Conn() { + t.Error(fmt.Sprintf("users %s and %s share a connection", a.User, b.User)) + } +} diff --git a/internal/ssh/conn/prompter.go b/internal/ssh/conn/prompter.go new file mode 100644 index 0000000..6795c33 --- /dev/null +++ b/internal/ssh/conn/prompter.go @@ -0,0 +1,55 @@ +// Package conn owns SSH connections: dialing with a bounded handshake, +// host-key verification, authentication, keepalive, reconnect, remote exec +// and a reference-counted pool. Nothing outside the Pool closes a +// connection. +package conn + +import ( + "context" + "crypto/sha256" + "encoding/base64" + + "golang.org/x/crypto/ssh" + + "vcom/internal/ssh/sshconfig" +) + +// Endpoint is the resolved host to dial. +type Endpoint = sshconfig.Endpoint + +// HostIdentity identifies a server host key. +type HostIdentity struct { + KeyType string // e.g. "ssh-ed25519" + FingerprintSHA256 string // "SHA256:..." as printed by ssh-keygen -l +} + +// IdentityOf returns the identity of a public key. +func IdentityOf(k ssh.PublicKey) HostIdentity { + sum := sha256.Sum256(k.Marshal()) + return HostIdentity{ + KeyType: k.Type(), + FingerprintSHA256: "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:]), + } +} + +// HostKeyDecision is the answer to an unknown or changed host key. +type HostKeyDecision uint8 + +const ( + Reject HostKeyDecision = iota // refuse to connect + AcceptOnce // trust for this process only + AcceptAndSave // trust and append to known_hosts +) + +// Prompter asks the user. The UI implements it via jobs.Ask; every method +// must return promptly when ctx is cancelled. A nil Prompter rejects unknown +// host keys and offers no interactive authentication. +type Prompter interface { + // HostKey is called for a key that is not in known_hosts. changed is + // true when known_hosts has a different key of the same type (possible + // MITM); known lists the keys known_hosts has for the host. + HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) + Password(ctx context.Context, ep Endpoint) (string, error) + KeyboardInteractive(ctx context.Context, ep Endpoint, instruction string, questions []string, echo []bool) ([]string, error) + Passphrase(ctx context.Context, keyPath string) ([]byte, error) +} diff --git a/internal/ssh/sshconfig/flatten.go b/internal/ssh/sshconfig/flatten.go new file mode 100644 index 0000000..8ea3b20 --- /dev/null +++ b/internal/ssh/sshconfig/flatten.go @@ -0,0 +1,199 @@ +package sshconfig + +import ( + "fmt" + "os" + "path/filepath" + "sort" + "strings" +) + +// hashMark stands in for a literal '#' inside a value while the flattened +// config goes through kevinburke/ssh_config, whose lexer treats every '#' as +// the start of a comment. OpenSSH only starts a comment at a '#' that begins +// a word outside quotes (N-P1-5: "IdentityFile ~/.ssh/key#1"). +const hashMark = "" + +const maxIncludeDepth = 5 + +// flattener turns an ssh_config file and everything it Includes into a single +// text that kevinburke/ssh_config can parse without touching the disk: +// - comments are stripped with OpenSSH rules, literal '#' is escaped; +// - Include is inlined (relative to ~/.ssh), restoring the enclosing Host +// context after the included text, as OpenSSH does; +// - Host patterns are lowercased (OpenSSH matches host names +// case-insensitively; the alias is lowercased too before lookup); +// - "Match all" and "Match host a,b" become Host blocks; other Match +// criteria (user, exec, canonical, ...) become a block that never +// matches, instead of failing the whole file. +type flattener struct { + home string + b strings.Builder + explicit []string // non-wildcard Host names, in file order + seen map[string]bool + warnings []string +} + +func (f *flattener) warnf(format string, args ...any) { + f.warnings = append(f.warnings, fmt.Sprintf(format, args...)) +} + +func (f *flattener) file(path string, depth int) error { + data, err := os.ReadFile(path) + if err != nil { + return err + } + f.text(path, string(data), depth) + return nil +} + +func (f *flattener) text(path, data string, depth int) { + context := "" // current Host line written to the output, "" = implicit Host * + for n, raw := range strings.Split(data, "\n") { + line := strings.TrimSpace(stripComment(strings.TrimRight(raw, "\r"))) + if line == "" { + continue + } + kw, rest := splitKeyword(line) + switch strings.ToLower(kw) { + case "host": + pats := splitArgs(rest) + for i, p := range pats { + pats[i] = strings.ToLower(p) + if !strings.ContainsAny(p, "*?!") && !f.seen[pats[i]] { + f.seen[pats[i]] = true + f.explicit = append(f.explicit, p) + } + } + if len(pats) == 0 { + f.warnf("%s:%d: Host without patterns", path, n+1) + pats = []string{"!*"} + } + context = "Host " + strings.Join(pats, " ") + f.b.WriteString(context + "\n") + case "match": + context = f.match(path, n+1, rest) + f.b.WriteString(context + "\n") + case "include": + if depth >= maxIncludeDepth { + f.warnf("%s:%d: Include nested too deep, ignored", path, n+1) + continue + } + for _, pat := range splitArgs(rest) { + for _, m := range f.glob(pat) { + if err := f.file(m, depth+1); err != nil { + f.warnf("%s:%d: Include %s: %v", path, n+1, m, err) + } + } + } + // The included text may have opened its own Host blocks; the rest + // of this file continues in the block that contained the Include. + if context == "" { + f.b.WriteString("Host *\n") + } else { + f.b.WriteString(context + "\n") + } + default: + f.b.WriteString(kw + " " + strings.ReplaceAll(rest, "#", hashMark) + "\n") + } + } +} + +func (f *flattener) match(path string, line int, rest string) string { + fields := splitArgs(rest) + if len(fields) == 1 && strings.EqualFold(fields[0], "all") { + return "Host *" + } + if len(fields) == 2 && (strings.EqualFold(fields[0], "host") || strings.EqualFold(fields[0], "originalhost")) { + var pats []string + for _, p := range strings.Split(fields[1], ",") { + if p != "" { + pats = append(pats, strings.ToLower(p)) + } + } + if len(pats) > 0 { + return "Host " + strings.Join(pats, " ") + } + } + f.warnf("%s:%d: unsupported Match %q, block ignored", path, line, rest) + return "Host !*" +} + +func (f *flattener) glob(pat string) []string { + p := expandTilde(pat, f.home) + if !filepath.IsAbs(p) { + p = filepath.Join(f.home, ".ssh", p) + } + ms, err := filepath.Glob(p) + if err != nil { + f.warnf("Include %s: %v", pat, err) + return nil + } + sort.Strings(ms) + return ms +} + +// stripComment removes a trailing comment: a '#' that starts a word and is +// not inside double quotes (OpenSSH argv_split rules). +func stripComment(s string) string { + inQuote := false + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == '"': + inQuote = !inQuote + case c == '#' && !inQuote && (i == 0 || s[i-1] == ' ' || s[i-1] == '\t'): + return s[:i] + } + } + return s +} + +// splitKeyword splits "Key value", "Key=value" and "Key = value". +func splitKeyword(line string) (kw, rest string) { + i := strings.IndexAny(line, " \t=") + if i < 0 { + return line, "" + } + kw, rest = line[:i], strings.TrimLeft(line[i:], " \t") + if strings.HasPrefix(rest, "=") { + rest = strings.TrimLeft(rest[1:], " \t") + } + return kw, rest +} + +// splitArgs splits on whitespace, honouring double quotes. +func splitArgs(s string) []string { + var out []string + var cur strings.Builder + inQuote, have := false, false + for _, r := range s { + switch { + case r == '"': + inQuote = !inQuote + have = true + case (r == ' ' || r == '\t') && !inQuote: + if have { + out = append(out, cur.String()) + cur.Reset() + have = false + } + default: + cur.WriteRune(r) + have = true + } + } + if have { + out = append(out, cur.String()) + } + return out +} + +func expandTilde(p, home string) string { + if p == "~" { + return home + } + if strings.HasPrefix(p, "~/") { + return filepath.Join(home, p[2:]) + } + return p +} diff --git a/internal/ssh/sshconfig/resolver.go b/internal/ssh/sshconfig/resolver.go new file mode 100644 index 0000000..593b563 --- /dev/null +++ b/internal/ssh/sshconfig/resolver.go @@ -0,0 +1,391 @@ +// Package sshconfig resolves host aliases into connection endpoints using +// ~/.ssh/config (parsed with github.com/kevinburke/ssh_config) and vcom's own +// encrypted host list (hosts.dat, see Store). +package sshconfig + +import ( + "errors" + "fmt" + "net" + "os" + "os/user" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + ssh_config "github.com/kevinburke/ssh_config" +) + +// DefaultPort is the SSH port used when none is configured. +const DefaultPort = 22 + +// Endpoint is everything needed to dial one host. +type Endpoint struct { + Alias string // as the user named the host + User string + Host string // HostName; the alias when the config has none (N-P1-5) + Port int + + IdentityFiles []string // absolute paths, in config order + IdentitiesOnly bool + + // ProxyJump hops, resolved through the same config. Dialing through them + // is stage 8; for now the field is informational. + ProxyJump []Endpoint + + ServerAliveInterval time.Duration + ServerAliveCountMax int + ConnectTimeout time.Duration + + // Password is set only for hosts added in vcom (hosts.dat). + Password string +} + +// port returns Port or DefaultPort. +func (e Endpoint) port() int { + if e.Port <= 0 { + return DefaultPort + } + return e.Port +} + +// Addr is "host:port" for dialing. +func (e Endpoint) Addr() string { + return net.JoinHostPort(e.Host, strconv.Itoa(e.port())) +} + +// Key is "user@host:port", the connection pool key. Aliases that resolve to +// the same user, host and port share a connection; different users never do +// (N-P2-3). +func (e Endpoint) Key() string { + return e.User + "@" + e.Addr() +} + +// Label is a short name for the UI: "user@alias". +func (e Endpoint) Label() string { + name := e.Alias + if name == "" { + name = e.Host + } + if e.User == "" { + return name + } + return e.User + "@" + name +} + +// Source tells where a host entry comes from. +type Source uint8 + +const ( + FromSSHConfig Source = iota // ~/.ssh/config + FromStore // hosts.dat (added in vcom) +) + +// HostEntry is one row of the host list. +type HostEntry struct { + Alias string + Source Source + User string + Host string + Port int +} + +// DisplayName is "alias (user@host[:port])". +func (h HostEntry) DisplayName() string { + addr := h.Host + if h.Port != 0 && h.Port != DefaultPort { + addr = net.JoinHostPort(h.Host, strconv.Itoa(h.Port)) + } + if h.User != "" { + addr = h.User + "@" + addr + } + return h.Alias + " (" + addr + ")" +} + +// Options configures a Resolver. +type Options struct { + // ConfigPath is the ssh config to read. "" means Home/.ssh/config; a + // missing file is not an error. + ConfigPath string + // Home is used for "~", relative Include and IdentityFile paths and the + // default config path. "" means os.UserHomeDir(). + Home string + // LocalUser is the default remote user. "" means the current user. + LocalUser string + // Store adds the hosts saved in vcom. May be nil. + Store *Store +} + +// Resolver answers host lookups. It is safe for concurrent use. +type Resolver struct { + opts Options + + mu sync.RWMutex + cfg *ssh_config.Config + explicit []string + warnings []string +} + +// NewResolver loads the ssh config. On a parse error the returned Resolver +// is still usable (it knows only the Store hosts) and the error is returned +// alongside it. +func NewResolver(o Options) (*Resolver, error) { + if o.Home == "" { + o.Home, _ = os.UserHomeDir() + } + if o.ConfigPath == "" && o.Home != "" { + o.ConfigPath = filepath.Join(o.Home, ".ssh", "config") + } + if o.LocalUser == "" { + o.LocalUser = currentUser() + } + r := &Resolver{opts: o} + return r, r.Reload() +} + +func currentUser() string { + if u, err := user.Current(); err == nil && u.Username != "" { + return u.Username + } + return os.Getenv("USER") +} + +// Reload re-reads the ssh config file. +func (r *Resolver) Reload() error { + f := &flattener{home: r.opts.Home, seen: map[string]bool{}} + var loadErr error + if r.opts.ConfigPath != "" { + if err := f.file(r.opts.ConfigPath, 0); err != nil && !errors.Is(err, os.ErrNotExist) { + loadErr = err + } + } + cfg, err := ssh_config.DecodeBytes([]byte(f.b.String())) + if err != nil { + cfg, _ = ssh_config.DecodeBytes(nil) + f.explicit = nil + loadErr = fmt.Errorf("parse %s: %w", r.opts.ConfigPath, err) + } + r.mu.Lock() + r.cfg, r.explicit, r.warnings = cfg, f.explicit, f.warnings + r.mu.Unlock() + return loadErr +} + +// Warnings lists non-fatal problems found by the last Reload (unsupported +// Match criteria, unreadable Include files). +func (r *Resolver) Warnings() []string { + r.mu.RLock() + defer r.mu.RUnlock() + return append([]string(nil), r.warnings...) +} + +// Hosts lists the explicit (non-pattern) Host names of the ssh config, then +// the Store hosts whose names are not in the config. +func (r *Resolver) Hosts() []HostEntry { + r.mu.RLock() + names := append([]string(nil), r.explicit...) + r.mu.RUnlock() + var out []HostEntry + seen := map[string]bool{} + for _, n := range names { + seen[strings.ToLower(n)] = true + ep, err := r.resolveConfig(n, 0) + if err != nil { + ep = Endpoint{Alias: n, Host: n} + } + out = append(out, HostEntry{Alias: n, Source: FromSSHConfig, User: ep.User, Host: ep.Host, Port: ep.Port}) + } + if r.opts.Store != nil { + for _, h := range r.opts.Store.Hosts() { + if seen[strings.ToLower(h.Name)] { + continue + } + seen[strings.ToLower(h.Name)] = true + ep := h.Endpoint(r.opts.LocalUser) + out = append(out, HostEntry{Alias: h.Name, Source: FromStore, User: ep.User, Host: ep.Host, Port: ep.Port}) + } + } + return out +} + +func (r *Resolver) isExplicit(alias string) bool { + r.mu.RLock() + defer r.mu.RUnlock() + for _, n := range r.explicit { + if strings.EqualFold(n, alias) { + return true + } + } + return false +} + +// Resolve turns an alias into an Endpoint. Hosts named explicitly in the ssh +// config win over Store hosts with the same name; anything else not in the +// Store is resolved through the config (wildcard blocks apply, HostName +// defaults to the alias). +func (r *Resolver) Resolve(alias string) (Endpoint, error) { + alias = strings.TrimSpace(alias) + if alias == "" { + return Endpoint{}, errors.New("sshconfig: empty host name") + } + if r.opts.Store != nil && !r.isExplicit(alias) { + if h, ok := r.opts.Store.Find(alias); ok { + return h.Endpoint(r.opts.LocalUser), nil + } + } + return r.resolveConfig(alias, 0) +} + +func (r *Resolver) get(alias, key string) string { + r.mu.RLock() + cfg := r.cfg + r.mu.RUnlock() + v, _ := cfg.Get(strings.ToLower(alias), key) + return strings.ReplaceAll(strings.TrimSpace(v), hashMark, "#") +} + +func (r *Resolver) getAll(alias, key string) []string { + r.mu.RLock() + cfg := r.cfg + r.mu.RUnlock() + vs, _ := cfg.GetAll(strings.ToLower(alias), key) + out := make([]string, 0, len(vs)) + for _, v := range vs { + out = append(out, strings.ReplaceAll(strings.TrimSpace(v), hashMark, "#")) + } + return out +} + +func (r *Resolver) resolveConfig(alias string, depth int) (Endpoint, error) { + ep := Endpoint{Alias: alias, Port: DefaultPort} + ep.User = r.get(alias, "User") + if ep.User == "" { + ep.User = r.opts.LocalUser + } + ep.Host = r.get(alias, "HostName") + if ep.Host == "" { + ep.Host = alias + } else { + ep.Host = r.expandTokens(ep.Host, alias, ep.User) + } + if p := r.get(alias, "Port"); p != "" { + n, err := strconv.Atoi(p) + if err != nil || n <= 0 || n > 65535 { + return Endpoint{}, fmt.Errorf("sshconfig: host %s: invalid Port %q", alias, p) + } + ep.Port = n + } + seen := map[string]bool{} + for _, id := range r.getAll(alias, "IdentityFile") { + if strings.EqualFold(id, "none") { + continue + } + p := r.expandPath(r.expandTokens(id, ep.Host, ep.User)) + if !seen[p] { + seen[p] = true + ep.IdentityFiles = append(ep.IdentityFiles, p) + } + } + ep.IdentitiesOnly = strings.EqualFold(r.get(alias, "IdentitiesOnly"), "yes") + if v := r.get(alias, "ServerAliveInterval"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + ep.ServerAliveInterval = time.Duration(n) * time.Second + } + } + if v := r.get(alias, "ServerAliveCountMax"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + ep.ServerAliveCountMax = n + } + } + if v := r.get(alias, "ConnectTimeout"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + ep.ConnectTimeout = time.Duration(n) * time.Second + } + } + if pj := r.get(alias, "ProxyJump"); pj != "" && !strings.EqualFold(pj, "none") { + if depth >= maxIncludeDepth { + return Endpoint{}, fmt.Errorf("sshconfig: host %s: ProxyJump chain too long", alias) + } + for _, hop := range strings.Split(pj, ",") { + h, err := r.parseHop(strings.TrimSpace(hop), depth+1) + if err != nil { + return Endpoint{}, fmt.Errorf("sshconfig: host %s: ProxyJump: %w", alias, err) + } + ep.ProxyJump = append(ep.ProxyJump, h) + } + } + return ep, nil +} + +// parseHop resolves one ProxyJump element "[user@]host[:port]". +func (r *Resolver) parseHop(hop string, depth int) (Endpoint, error) { + hop = strings.TrimPrefix(hop, "ssh://") + var u string + if i := strings.LastIndex(hop, "@"); i >= 0 { + u, hop = hop[:i], hop[i+1:] + } + host, port := hop, "" + if h, p, err := net.SplitHostPort(hop); err == nil { + host, port = h, p + } + if host == "" { + return Endpoint{}, errors.New("empty hop") + } + ep, err := r.resolveConfig(host, depth) + if err != nil { + return Endpoint{}, err + } + if u != "" { + ep.User = u + } + if port != "" { + n, err := strconv.Atoi(port) + if err != nil || n <= 0 || n > 65535 { + return Endpoint{}, fmt.Errorf("invalid port %q", port) + } + ep.Port = n + } + return ep, nil +} + +// expandTokens handles the ssh_config tokens that make sense here. +func (r *Resolver) expandTokens(s, host, remoteUser string) string { + if !strings.Contains(s, "%") { + return s + } + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] != '%' || i+1 == len(s) { + b.WriteByte(s[i]) + continue + } + i++ + switch s[i] { + case '%': + b.WriteByte('%') + case 'h': + b.WriteString(host) + case 'd': + b.WriteString(r.opts.Home) + case 'u': + b.WriteString(r.opts.LocalUser) + case 'r': + b.WriteString(remoteUser) + default: + b.WriteByte('%') + b.WriteByte(s[i]) + } + } + return b.String() +} + +// expandPath expands "~" and makes relative paths relative to ~/.ssh. +func (r *Resolver) expandPath(p string) string { + p = expandTilde(p, r.opts.Home) + if !filepath.IsAbs(p) && r.opts.Home != "" { + p = filepath.Join(r.opts.Home, ".ssh", p) + } + return filepath.Clean(p) +} diff --git a/internal/ssh/sshconfig/resolver_test.go b/internal/ssh/sshconfig/resolver_test.go new file mode 100644 index 0000000..e08a91c --- /dev/null +++ b/internal/ssh/sshconfig/resolver_test.go @@ -0,0 +1,285 @@ +package sshconfig + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +// newTestResolver writes config text to home/.ssh/config and returns a +// Resolver over it. +func newTestResolver(t *testing.T, config string, store *Store) (*Resolver, string) { + t.Helper() + home := t.TempDir() + writeFile(t, filepath.Join(home, ".ssh", "config"), config) + r, err := NewResolver(Options{Home: home, LocalUser: "local", Store: store}) + if err != nil { + t.Fatalf("NewResolver: %v", err) + } + return r, home +} + +func writeFile(t *testing.T, p, s string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(s), 0o600); err != nil { + t.Fatal(err) + } +} + +func mustResolve(t *testing.T, r *Resolver, alias string) Endpoint { + t.Helper() + ep, err := r.Resolve(alias) + if err != nil { + t.Fatalf("Resolve(%q): %v", alias, err) + } + return ep +} + +// Ported from the testbed (B10): a Host without HostName dialed ":22", +// i.e. localhost; "HostName=10.0.0.1" was not parsed at all (N-P1-5). +func TestConfigNoHostName(t *testing.T) { + r, _ := newTestResolver(t, "Host myserver.example.com\n User bob\nHost alias\n HostName=10.0.0.1\n", nil) + ep := mustResolve(t, r, "myserver.example.com") + if ep.Host != "myserver.example.com" || ep.User != "bob" || ep.Port != 22 { + t.Errorf("no HostName: got %+v", ep) + } + if got := ep.Addr(); got != "myserver.example.com:22" { + t.Errorf("Addr = %q", got) + } + ep = mustResolve(t, r, "alias") + if ep.Host != "10.0.0.1" { + t.Errorf("HostName=10.0.0.1: got Host %q", ep.Host) + } + if ep.User != "local" { + t.Errorf("default user: got %q", ep.User) + } + for _, h := range r.Hosts() { + if h.Host == "" { + t.Errorf("host %q has empty Host", h.Alias) + } + } +} + +func TestConfigEqualsAndSpaces(t *testing.T) { + r, _ := newTestResolver(t, "Host a\n HostName = 10.0.0.2\n Port=2222\n User\tcarol\n", nil) + ep := mustResolve(t, r, "a") + if ep.Host != "10.0.0.2" || ep.Port != 2222 || ep.User != "carol" { + t.Errorf("got %+v", ep) + } +} + +func TestConfigHostStarDefaults(t *testing.T) { + cfg := `Host special + User alice + IdentityFile ~/.ssh/id_special + +Host * + User defuser + IdentityFile ~/.ssh/id_star + ServerAliveInterval 7 + ServerAliveCountMax 4 + ConnectTimeout 3 +` + r, home := newTestResolver(t, cfg, nil) + ep := mustResolve(t, r, "plain.example.com") + if ep.User != "defuser" { + t.Errorf("Host * User not applied: %q", ep.User) + } + if want := []string{filepath.Join(home, ".ssh", "id_star")}; !reflect.DeepEqual(ep.IdentityFiles, want) { + t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want) + } + if ep.ServerAliveInterval != 7*time.Second || ep.ServerAliveCountMax != 4 || ep.ConnectTimeout != 3*time.Second { + t.Errorf("alive/timeout: %+v", ep) + } + ep = mustResolve(t, r, "special") + if ep.User != "alice" { + t.Errorf("first match must win: User %q", ep.User) + } + want := []string{filepath.Join(home, ".ssh", "id_special"), filepath.Join(home, ".ssh", "id_star")} + if !reflect.DeepEqual(ep.IdentityFiles, want) { + t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want) + } + hosts := r.Hosts() + if len(hosts) != 1 || hosts[0].Alias != "special" { + t.Errorf("Hosts() must list only explicit hosts: %+v", hosts) + } +} + +func TestConfigMultipleIdentityFiles(t *testing.T) { + r, home := newTestResolver(t, "Host m\n IdentityFile ~/.ssh/one\n IdentityFile two\n IdentityFile /abs/three\n IdentityFile ~/.ssh/one\n IdentitiesOnly yes\n", nil) + ep := mustResolve(t, r, "m") + want := []string{filepath.Join(home, ".ssh", "one"), filepath.Join(home, ".ssh", "two"), "/abs/three"} + if !reflect.DeepEqual(ep.IdentityFiles, want) { + t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want) + } + if !ep.IdentitiesOnly { + t.Error("IdentitiesOnly not parsed") + } +} + +func TestConfigQuotes(t *testing.T) { + r, home := newTestResolver(t, "Host q\n IdentityFile \"~/.ssh/my key\"\n HostName \"q.example.com\"\n", nil) + ep := mustResolve(t, r, "q") + if want := filepath.Join(home, ".ssh", "my key"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want { + t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want) + } + if ep.Host != "q.example.com" { + t.Errorf("Host = %q", ep.Host) + } +} + +func TestConfigHashInValue(t *testing.T) { + cfg := "# leading comment\nHost h # trailing comment on Host\n IdentityFile ~/.ssh/key#1 # real comment\n User \"u#2\"\n" + r, home := newTestResolver(t, cfg, nil) + ep := mustResolve(t, r, "h") + if want := filepath.Join(home, ".ssh", "key#1"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want { + t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want) + } + if ep.User != "u#2" { + t.Errorf("User = %q, want u#2", ep.User) + } +} + +func TestConfigInclude(t *testing.T) { + home := t.TempDir() + writeFile(t, filepath.Join(home, ".ssh", "conf.d", "10-work"), "Host work\n HostName work.example.com\n User worker\n") + writeFile(t, filepath.Join(home, ".ssh", "conf.d", "20-misc"), "Host misc\n Port 2200\n") + abs := filepath.Join(home, "elsewhere.conf") + writeFile(t, abs, "Host abs\n HostName 192.168.1.1\n") + cfg := "Include conf.d/*\nHost outer\n Include " + abs + "\n User outeruser\nHost *\n User fallback\n" + writeFile(t, filepath.Join(home, ".ssh", "config"), cfg) + r, err := NewResolver(Options{Home: home, LocalUser: "local"}) + if err != nil { + t.Fatal(err) + } + if ep := mustResolve(t, r, "work"); ep.Host != "work.example.com" || ep.User != "worker" { + t.Errorf("work: %+v", ep) + } + if ep := mustResolve(t, r, "misc"); ep.Port != 2200 || ep.User != "fallback" { + t.Errorf("misc: %+v", ep) + } + if ep := mustResolve(t, r, "abs"); ep.Host != "192.168.1.1" { + t.Errorf("abs: %+v", ep) + } + // Lines after an Include stay in the block that contained it. + if ep := mustResolve(t, r, "outer"); ep.User != "outeruser" { + t.Errorf("outer: User %q, want outeruser", ep.User) + } + var names []string + for _, h := range r.Hosts() { + names = append(names, h.Alias) + } + if want := []string{"work", "misc", "outer", "abs"}; !reflect.DeepEqual(names, want) { + t.Errorf("Hosts = %v, want %v", names, want) + } +} + +func TestConfigUnsupportedMatchIgnored(t *testing.T) { + cfg := "Match user root\n User ignored\nMatch host *.corp,10.*\n User corp\nHost x\n HostName x.example.com\n" + r, _ := newTestResolver(t, cfg, nil) + if ep := mustResolve(t, r, "x"); ep.User != "local" { + t.Errorf("unsupported Match applied: %+v", ep) + } + if ep := mustResolve(t, r, "a.corp"); ep.User != "corp" { + t.Errorf("Match host not applied: %+v", ep) + } + if len(r.Warnings()) != 1 { + t.Errorf("warnings = %v", r.Warnings()) + } +} + +func TestConfigCaseInsensitiveHost(t *testing.T) { + r, _ := newTestResolver(t, "Host MyBox\n HostName 10.1.1.1\n", nil) + if ep := mustResolve(t, r, "mybox"); ep.Host != "10.1.1.1" { + t.Errorf("got %+v", ep) + } + if ep := mustResolve(t, r, "MYBOX"); ep.Host != "10.1.1.1" || ep.Alias != "MYBOX" { + t.Errorf("got %+v", ep) + } +} + +func TestConfigInvalidPort(t *testing.T) { + r, _ := newTestResolver(t, "Host p\n Port abc\n", nil) + if _, err := r.Resolve("p"); err == nil { + t.Fatal("want error for invalid port") + } +} + +func TestConfigProxyJump(t *testing.T) { + r, _ := newTestResolver(t, "Host target\n ProxyJump admin@bastion:2022,hop2\nHost bastion\n HostName b.example.com\n", nil) + ep := mustResolve(t, r, "target") + if len(ep.ProxyJump) != 2 { + t.Fatalf("ProxyJump = %+v", ep.ProxyJump) + } + if h := ep.ProxyJump[0]; h.Host != "b.example.com" || h.User != "admin" || h.Port != 2022 { + t.Errorf("hop 1: %+v", h) + } + if h := ep.ProxyJump[1]; h.Host != "hop2" || h.Port != 22 { + t.Errorf("hop 2: %+v", h) + } +} + +func TestConfigMissingFile(t *testing.T) { + r, err := NewResolver(Options{Home: t.TempDir(), LocalUser: "me"}) + if err != nil { + t.Fatalf("missing config must not be an error: %v", err) + } + ep := mustResolve(t, r, "anything") + if ep.Host != "anything" || ep.User != "me" || ep.Port != 22 { + t.Errorf("got %+v", ep) + } +} + +// N-P2-3: SameAs ignored User, so two users on one host shared a client. +func TestEndpointKeyIncludesUser(t *testing.T) { + r, _ := newTestResolver(t, "Host a1\n HostName srv\n User alice\nHost a2\n HostName srv\n User alice\nHost b\n HostName srv\n User bob\n", nil) + a1, a2, b := mustResolve(t, r, "a1"), mustResolve(t, r, "a2"), mustResolve(t, r, "b") + if a1.Key() != a2.Key() { + t.Errorf("same user@host:port must share a key: %q vs %q", a1.Key(), a2.Key()) + } + if a1.Key() == b.Key() { + t.Errorf("different users must not share a key: %q", a1.Key()) + } + if !strings.HasPrefix(a1.Key(), "alice@") || a1.Key() != "alice@srv:22" { + t.Errorf("Key = %q", a1.Key()) + } + v6 := Endpoint{User: "u", Host: "::1", Port: 2222} + if v6.Key() != "u@[::1]:2222" { + t.Errorf("IPv6 key = %q", v6.Key()) + } +} + +func TestResolverStoreHosts(t *testing.T) { + st, err := OpenStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := st.Put(StoredHost{Name: "mine", HostName: "10.9.9.9", Port: 2022, User: "me", Password: "secret"}); err != nil { + t.Fatal(err) + } + if err := st.Put(StoredHost{Name: "dup", HostName: "store.example.com"}); err != nil { + t.Fatal(err) + } + r, _ := newTestResolver(t, "Host dup\n HostName config.example.com\n", st) + ep := mustResolve(t, r, "mine") + if ep.Host != "10.9.9.9" || ep.Port != 2022 || ep.User != "me" || ep.Password != "secret" { + t.Errorf("store host: %+v", ep) + } + if ep := mustResolve(t, r, "dup"); ep.Host != "config.example.com" { + t.Errorf("ssh config must win over the store: %+v", ep) + } + hosts := r.Hosts() + if len(hosts) != 2 || hosts[0].Alias != "dup" || hosts[0].Source != FromSSHConfig || + hosts[1].Alias != "mine" || hosts[1].Source != FromStore { + t.Errorf("Hosts = %+v", hosts) + } + if got := hosts[1].DisplayName(); got != "mine (me@10.9.9.9:2022)" { + t.Errorf("DisplayName = %q", got) + } +} diff --git a/internal/ssh/sshconfig/store.go b/internal/ssh/sshconfig/store.go new file mode 100644 index 0000000..fa39c45 --- /dev/null +++ b/internal/ssh/sshconfig/store.go @@ -0,0 +1,317 @@ +package sshconfig + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + + "vcom/internal/atomicfile" +) + +// File names inside the Store directory (compatible with vcom <= 0.2.x). +const ( + HostsFile = "hosts.dat" + KeyFile = ".hosts-key" +) + +// ErrHostNotFound is returned by Store.Remove for an unknown name. +var ErrHostNotFound = errors.New("sshconfig: host not found") + +// StoredHost is a host added in vcom. +type StoredHost struct { + Name string + HostName string + Port int // 0 = default + User string + Password string // plaintext in memory, encrypted on disk + IdentityFile string +} + +// Endpoint converts a stored host to an Endpoint; localUser is the default +// user. +func (h StoredHost) Endpoint(localUser string) Endpoint { + ep := Endpoint{ + Alias: h.Name, + User: h.User, + Host: h.HostName, + Port: h.Port, + Password: h.Password, + } + if ep.Host == "" { + ep.Host = h.Name + } + if ep.Port <= 0 { + ep.Port = DefaultPort + } + if ep.User == "" { + ep.User = localUser + } + if h.IdentityFile != "" { + ep.IdentityFiles = []string{h.IdentityFile} + } + return ep +} + +// Store is vcom's own host list: hosts.dat, AES-256-GCM encrypted with the +// key in .hosts-key (both in the vcom config directory). Every save is +// atomic. It is safe for concurrent use. +type Store struct { + path string + key []byte + + mu sync.Mutex + hosts []StoredHost +} + +// OpenStore loads dir/hosts.dat, creating the encryption key if there is +// none yet. A missing hosts.dat means an empty list. +func OpenStore(dir string) (*Store, error) { + if dir == "" { + return nil, errors.New("sshconfig: empty store directory") + } + key, err := loadOrCreateKey(filepath.Join(dir, KeyFile)) + if err != nil { + return nil, fmt.Errorf("sshconfig: hosts key: %w", err) + } + s := &Store{path: filepath.Join(dir, HostsFile), key: key} + if err := s.load(); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return s, nil +} + +func loadOrCreateKey(path string) ([]byte, error) { + data, err := os.ReadFile(path) + if err == nil { + key, derr := base64.StdEncoding.DecodeString(strings.TrimSpace(string(data))) + if derr == nil && len(key) == 32 { + return key, nil + } + // A damaged key must not be silently replaced: hosts.dat would become + // undecryptable for good. + return nil, fmt.Errorf("%s: invalid key", path) + } + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + return nil, err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return nil, err + } + if err := atomicfile.WriteFile(path, []byte(base64.StdEncoding.EncodeToString(key)), 0o600); err != nil { + return nil, err + } + return key, nil +} + +// On-disk format (unchanged from vcom 0.2.x). +type storedHosts struct { + Hosts []storedHost `json:"hosts"` +} + +type storedHost struct { + Name string `json:"name"` + HostName string `json:"hostname"` + Port string `json:"port,omitempty"` + User string `json:"user,omitempty"` + Password string `json:"password,omitempty"` // encrypted + IdentityFile string `json:"identity_file,omitempty"` +} + +func (s *Store) load() error { + data, err := os.ReadFile(s.path) + if err != nil { + return err + } + plain, err := decrypt(data, s.key) + if err != nil { + return fmt.Errorf("sshconfig: decrypt %s: %w", s.path, err) + } + var st storedHosts + if err := json.Unmarshal(plain, &st); err != nil { + return fmt.Errorf("sshconfig: parse %s: %w", s.path, err) + } + hosts := make([]StoredHost, 0, len(st.Hosts)) + for _, h := range st.Hosts { + pw := decryptPassword(h.Password, s.key) + port, _ := strconv.Atoi(h.Port) + hosts = append(hosts, StoredHost{ + Name: h.Name, HostName: h.HostName, Port: port, User: h.User, + Password: pw, IdentityFile: h.IdentityFile, + }) + } + s.mu.Lock() + s.hosts = hosts + s.mu.Unlock() + return nil +} + +// save writes hosts.dat; the caller holds s.mu. +func (s *Store) save() error { + st := storedHosts{Hosts: make([]storedHost, 0, len(s.hosts))} + for _, h := range s.hosts { + pw := "" + if h.Password != "" { + enc, err := encrypt([]byte(h.Password), s.key) + if err != nil { + return err + } + pw = base64.StdEncoding.EncodeToString(enc) + } + port := "" + if h.Port > 0 { + port = strconv.Itoa(h.Port) + } + st.Hosts = append(st.Hosts, storedHost{ + Name: h.Name, HostName: h.HostName, Port: port, User: h.User, + Password: pw, IdentityFile: h.IdentityFile, + }) + } + data, err := json.Marshal(st) + if err != nil { + return err + } + enc, err := encrypt(data, s.key) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil { + return err + } + return atomicfile.WriteFile(s.path, enc, 0o600) +} + +// Hosts returns a copy of the stored hosts. +func (s *Store) Hosts() []StoredHost { + s.mu.Lock() + defer s.mu.Unlock() + return append([]StoredHost(nil), s.hosts...) +} + +// Find looks a host up by name (case-insensitive). +func (s *Store) Find(name string) (StoredHost, bool) { + s.mu.Lock() + defer s.mu.Unlock() + for _, h := range s.hosts { + if strings.EqualFold(h.Name, name) { + return h, true + } + } + return StoredHost{}, false +} + +// Put adds h, replacing a host with the same name, and saves. On a save +// error the in-memory list is left unchanged. +func (s *Store) Put(h StoredHost) error { + if strings.TrimSpace(h.Name) == "" { + return errors.New("sshconfig: host name is required") + } + s.mu.Lock() + defer s.mu.Unlock() + old := s.hosts + next := make([]StoredHost, 0, len(old)+1) + replaced := false + for _, x := range old { + if strings.EqualFold(x.Name, h.Name) { + next = append(next, h) + replaced = true + } else { + next = append(next, x) + } + } + if !replaced { + next = append(next, h) + } + s.hosts = next + if err := s.save(); err != nil { + s.hosts = old + return err + } + return nil +} + +// Remove deletes a host by name and saves. +func (s *Store) Remove(name string) error { + s.mu.Lock() + defer s.mu.Unlock() + old := s.hosts + next := make([]StoredHost, 0, len(old)) + for _, x := range old { + if !strings.EqualFold(x.Name, name) { + next = append(next, x) + } + } + if len(next) == len(old) { + return fmt.Errorf("%w: %s", ErrHostNotFound, name) + } + s.hosts = next + if err := s.save(); err != nil { + s.hosts = old + return err + } + return nil +} + +// decryptPassword reads the password field. vcom <= 0.2.x stored the raw +// ciphertext as a JSON string, which json.Marshal mangles (invalid UTF-8 +// becomes U+FFFD), so such passwords usually cannot be recovered; the field +// is now base64. Both forms are tried; failure yields "". +func decryptPassword(field string, key []byte) string { + if field == "" { + return "" + } + if raw, err := base64.StdEncoding.DecodeString(field); err == nil { + if p, err := decrypt(raw, key); err == nil { + return string(p) + } + } + if p, err := decrypt([]byte(field), key); err == nil { + return string(p) + } + return "" +} + +func encrypt(plaintext, key []byte) ([]byte, error) { + gcm, err := newGCM(key) + if err != nil { + return nil, err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } + return gcm.Seal(nonce, nonce, plaintext, nil), nil +} + +func decrypt(ciphertext, key []byte) ([]byte, error) { + gcm, err := newGCM(key) + if err != nil { + return nil, err + } + n := gcm.NonceSize() + if len(ciphertext) < n { + return nil, errors.New("ciphertext too short") + } + return gcm.Open(nil, ciphertext[:n], ciphertext[n:], nil) +} + +func newGCM(key []byte) (cipher.AEAD, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + return cipher.NewGCM(block) +} diff --git a/internal/ssh/sshconfig/store_test.go b/internal/ssh/sshconfig/store_test.go new file mode 100644 index 0000000..e0fbe8f --- /dev/null +++ b/internal/ssh/sshconfig/store_test.go @@ -0,0 +1,102 @@ +package sshconfig + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" +) + +func TestStoreRoundTrip(t *testing.T) { + dir := filepath.Join(t.TempDir(), "vcom") + st, err := OpenStore(dir) + if err != nil { + t.Fatal(err) + } + h := StoredHost{Name: "box", HostName: "10.0.0.5", Port: 2200, User: "root", Password: "hunter2", IdentityFile: "/k"} + if err := st.Put(h); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(dir, HostsFile)) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte("hunter2")) || bytes.Contains(raw, []byte("10.0.0.5")) { + t.Fatal("hosts.dat must be encrypted") + } + for _, name := range []string{HostsFile, KeyFile} { + fi, err := os.Stat(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if fi.Mode().Perm() != 0o600 { + t.Errorf("%s mode = %v", name, fi.Mode().Perm()) + } + } + + st2, err := OpenStore(dir) + if err != nil { + t.Fatal(err) + } + got, ok := st2.Find("BOX") + if !ok || got != h { + t.Fatalf("reloaded = %+v (ok=%v), want %+v", got, ok, h) + } + + h.Password = "changed" + if err := st2.Put(h); err != nil { + t.Fatal(err) + } + if hs := st2.Hosts(); len(hs) != 1 || hs[0].Password != "changed" { + t.Errorf("Put must replace by name: %+v", hs) + } + if err := st2.Remove("box"); err != nil { + t.Fatal(err) + } + if err := st2.Remove("box"); !errors.Is(err, ErrHostNotFound) { + t.Errorf("Remove unknown: %v", err) + } + ents, _ := os.ReadDir(dir) + for _, e := range ents { + if e.Name() != HostsFile && e.Name() != KeyFile { + t.Errorf("leftover file %s (atomic write must clean up)", e.Name()) + } + } +} + +func TestStoreDamagedKeyNotReplaced(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, KeyFile), "not base64 !!") + if _, err := OpenStore(dir); err == nil { + t.Fatal("damaged key must be an error") + } + b, _ := os.ReadFile(filepath.Join(dir, KeyFile)) + if string(b) != "not base64 !!" { + t.Fatal("damaged key was overwritten") + } +} + +func TestStoreSaveFailureKeepsState(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + dir := t.TempDir() + st, err := OpenStore(dir) + if err != nil { + t.Fatal(err) + } + if err := st.Put(StoredHost{Name: "a"}); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + defer os.Chmod(dir, 0o700) + if err := st.Put(StoredHost{Name: "b"}); err == nil { + t.Fatal("Put into read-only dir must fail") + } + if hs := st.Hosts(); len(hs) != 1 || hs[0].Name != "a" { + t.Errorf("failed save changed state: %+v", hs) + } +} diff --git a/internal/state/qa_rc2_test.go b/internal/state/qa_rc2_test.go new file mode 100644 index 0000000..9724b7d --- /dev/null +++ b/internal/state/qa_rc2_test.go @@ -0,0 +1,114 @@ +package state + +// QA (v0.2.8 RC2): session edge cases (stage 2C.3). + +import ( + "os" + "path/filepath" + "testing" +) + +func qaWrite(t *testing.T, p, s string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestQASessionEmptyAndBroken(t *testing.T) { + home := isolate(t) + p := filepath.Join(home, ".local", "state", "vcom", "session.toml") + qaWrite(t, p, "") + if s, err := Load(); err != nil || s.Left.Path != "" { + t.Fatalf("empty session: %+v %v", s, err) + } + qaWrite(t, p, "active_pane = 'left'\n[left\npath = '/x'\n") + if _, err := Load(); err == nil { + t.Fatal("broken session must report an error") + } + // A broken new file must not trigger migration from the old one. + old := filepath.Join(home, ".config", "vcom", "session.toml") + qaWrite(t, old, "active_pane = 'right'\n") + _, _ = Load() + if _, err := os.Stat(old); err != nil { + t.Fatal("old session removed although the new one is broken") + } + // Saving replaces the broken file with a valid one. + if err := Save(Session{ActivePane: "right"}); err != nil { + t.Fatal(err) + } + if s, err := Load(); err != nil || s.ActivePane != "right" { + t.Fatalf("after save: %+v %v", s, err) + } +} + +// A broken OLD session is neither migrated nor deleted. +func TestQASessionBrokenOldKept(t *testing.T) { + home := isolate(t) + old := filepath.Join(home, ".config", "vcom", "session.toml") + qaWrite(t, old, "[[[") + if _, err := Load(); err == nil { + t.Fatal("broken old session must report an error") + } + if _, err := os.Stat(old); err != nil { + t.Fatal("broken old session deleted") + } + if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); !os.IsNotExist(err) { + t.Fatal("broken old session migrated") + } +} + +// Session as a symlink (dotfiles) stays a symlink. +func TestQASessionSymlink(t *testing.T) { + home := isolate(t) + target := filepath.Join(home, "elsewhere", "session.toml") + qaWrite(t, target, "active_pane = 'left'\n") + p := filepath.Join(home, ".local", "state", "vcom", "session.toml") + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Fatal(err) + } + if err := Save(Session{ActivePane: "right"}); err != nil { + t.Fatal(err) + } + if fi, _ := os.Lstat(p); fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("session symlink replaced") + } + if s, _ := Load(); s.ActivePane != "right" { + t.Fatal("target not updated") + } +} + +// When the new state dir cannot be written, Load returns the old session +// AND an error; the caller (ui.applySession) drops the session on any +// error, so the user loses the restored panes although they were read. +func TestQASessionMigrationUnwritableStateDir(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores permissions") + } + home := isolate(t) + old := filepath.Join(home, ".config", "vcom", "session.toml") + qaWrite(t, old, "active_pane = 'right'\n[left]\npath = '/tmp'\n") + ro := filepath.Join(home, "ro") + if err := os.MkdirAll(ro, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(ro, 0o700) }) + t.Setenv("XDG_STATE_HOME", filepath.Join(ro, "state")) + s, err := Load() + if s.ActivePane != "right" { + t.Fatalf("old session not returned: %+v %v", s, err) + } + if _, serr := os.Stat(old); serr != nil { + t.Fatal("old session removed although migration failed") + } + if err == nil { + t.Fatal("expected a migration error") + } + // Documented in the report as QA-16: ui.applySession ignores s when err != nil. +} diff --git a/internal/state/session.go b/internal/state/session.go new file mode 100644 index 0000000..64d1430 --- /dev/null +++ b/internal/state/session.go @@ -0,0 +1,184 @@ +// Package state persists the UI session (design §9.1, §9.2): +// $XDG_STATE_HOME/vcom/session.toml, written atomically, migrated once from +// the pre-0.3 location next to the config. +package state + +import ( + "bytes" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + + toml "github.com/pelletier/go-toml/v2" + + "vcom/internal/atomicfile" + "vcom/internal/paths" +) + +// MaxCursorMemory bounds the remembered "cursor per directory" entries per pane. +const MaxCursorMemory = 200 + +// Session is the UI state restored on the next launch. +type Session struct { + ActivePane string `toml:"active_pane"` + Left PaneSession `toml:"left"` + Right PaneSession `toml:"right"` +} + +// PaneSession is one pane's state: its directory, the selected entry and the +// last selected entry per visited directory. +type PaneSession struct { + Path string `toml:"path"` + EntryName string `toml:"entry_name"` + CursorMemory map[string]string `toml:"cursor_memory"` +} + +// File is the session path: StateDir/session.toml. +func File() (string, error) { + d, err := paths.StateDir() + if err != nil { + return "", err + } + return filepath.Join(d, "session.toml"), nil +} + +// Load reads the session. A missing file is not an error (zero Session). If +// only the old file (~/.config/vcom/session.toml) exists, it is read, saved +// to the new location and removed — except under sudo, where the old file +// belongs to the invoking user and is left alone. +func Load() (Session, error) { + p, err := File() + if err != nil { + return Session{}, err + } + s, err := read(p) + if err == nil || !errors.Is(err, fs.ErrNotExist) { + return s, err + } + old, oerr := paths.OldSessionFile() + if oerr != nil { + return Session{}, nil + } + s, err = read(old) + if errors.Is(err, fs.ErrNotExist) { + return Session{}, nil + } + if err != nil { + return Session{}, err + } + if err := Save(s); err != nil { + return s, fmt.Errorf("migrate session from %s: %w", old, err) + } + if _, sudo := paths.SudoUser(); !sudo { + _ = os.Remove(old) + } + return s, nil +} + +func read(p string) (Session, error) { + data, err := os.ReadFile(p) + if err != nil { + return Session{}, err + } + var s Session + if err := toml.Unmarshal(data, &s); err != nil { + return Session{}, fmt.Errorf("parse %s: %w", p, err) + } + return s, nil +} + +// Save normalises s (see Normalize) and writes it atomically (0600) into a +// 0700 state directory. +func Save(s Session) error { + p, err := File() + if err != nil { + return err + } + if err := paths.EnsureDir(filepath.Dir(p)); err != nil { + return err + } + s.Normalize(transientPrefixes()) + var buf bytes.Buffer + if err := toml.NewEncoder(&buf).Encode(s); err != nil { + return fmt.Errorf("encode session: %w", err) + } + return atomicfile.WriteFile(p, buf.Bytes(), 0o600) +} + +// transientPrefixes are directories whose paths are not worth remembering: +// vcom's cache/run dirs and the old UI's temp mounts. +func transientPrefixes() []string { + var out []string + if c, err := paths.CacheDir(); err == nil { + out = append(out, c) + } + tmp := os.TempDir() + out = append(out, filepath.Join(tmp, "vcom-archive-"), filepath.Join(tmp, "vcom-remote-")) + return out +} + +// Normalize drops cursor-memory entries under any of the transient prefixes +// and caps each pane at MaxCursorMemory entries. +func (s *Session) Normalize(transient []string) { + s.Left.CursorMemory = capMemory(s.Left.CursorMemory, s.Left.Path, transient) + s.Right.CursorMemory = capMemory(s.Right.CursorMemory, s.Right.Path, transient) +} + +// capMemory keeps at most MaxCursorMemory entries. The map carries no +// recency, so it keeps first the entries on the pane's current path (its +// ancestors and descendants: where the user is most likely to go back), then +// the rest in path order. Deterministic, which keeps the file diff-friendly. +func capMemory(m map[string]string, current string, transient []string) map[string]string { + if len(m) == 0 { + return m + } + keys := make([]string, 0, len(m)) + for k, v := range m { + if k == "" || v == "" || hasAnyPrefix(k, transient) { + continue + } + keys = append(keys, k) + } + related := func(k string) bool { + return current != "" && (isWithin(k, current) || isWithin(current, k)) + } + sort.Slice(keys, func(i, j int) bool { + ri, rj := related(keys[i]), related(keys[j]) + if ri != rj { + return ri + } + return keys[i] < keys[j] + }) + if len(keys) > MaxCursorMemory { + keys = keys[:MaxCursorMemory] + } + out := make(map[string]string, len(keys)) + for _, k := range keys { + out[k] = m[k] + } + return out +} + +func hasAnyPrefix(p string, prefixes []string) bool { + for _, pre := range prefixes { + if pre != "" && (p == pre || strings.HasPrefix(p, pre)) { + return true + } + } + return false +} + +func isWithin(child, parent string) bool { + child, parent = filepath.Clean(child), filepath.Clean(parent) + if child == parent { + return true + } + if !strings.HasSuffix(parent, string(filepath.Separator)) { + parent += string(filepath.Separator) + } + return strings.HasPrefix(child, parent) +} diff --git a/internal/state/session_test.go b/internal/state/session_test.go new file mode 100644 index 0000000..012de2e --- /dev/null +++ b/internal/state/session_test.go @@ -0,0 +1,121 @@ +package state + +import ( + "fmt" + "os" + "path/filepath" + "testing" +) + +// isolate points HOME and the XDG dirs at a temp dir. +func isolate(t *testing.T) (home string) { + home = t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("SUDO_USER", "") + return home +} + +func TestSessionAtomic(t *testing.T) { + home := isolate(t) + s := Session{ActivePane: "right", Left: PaneSession{Path: "/a", EntryName: "x"}} + if err := Save(s); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, ".local", "state", "vcom") + p := filepath.Join(dir, "session.toml") + if fi, err := os.Stat(p); err != nil || fi.Mode().Perm() != 0o600 { + t.Fatalf("session file: %v %v", fi, err) + } + if fi, _ := os.Stat(dir); fi.Mode().Perm() != 0o700 { + t.Fatalf("state dir mode %v", fi.Mode().Perm()) + } + got, err := Load() + if err != nil || got.ActivePane != "right" || got.Left.EntryName != "x" { + t.Fatalf("round trip: %+v %v", got, err) + } + + // A failing write leaves the previous session intact and no temp files. + if os.Geteuid() != 0 { + before, _ := os.ReadFile(p) + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + if err := Save(Session{ActivePane: "left"}); err == nil { + t.Fatal("save into a read-only dir succeeded") + } + _ = os.Chmod(dir, 0o700) + after, _ := os.ReadFile(p) + if string(before) != string(after) { + t.Fatal("old session damaged by a failed save") + } + if ents, _ := os.ReadDir(dir); len(ents) != 1 { + t.Fatalf("leftovers in state dir: %v", ents) + } + } +} + +func TestSessionMigratesFromOldPath(t *testing.T) { + home := isolate(t) + old := filepath.Join(home, ".config", "vcom", "session.toml") + if err := os.MkdirAll(filepath.Dir(old), 0o755); err != nil { + t.Fatal(err) + } + content := "active_pane = 'right'\n[left]\npath = '/srv'\nentry_name = 'data'\n[left.cursor_memory]\n'/srv' = 'data'\n" + if err := os.WriteFile(old, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + s, err := Load() + if err != nil { + t.Fatal(err) + } + if s.ActivePane != "right" || s.Left.Path != "/srv" || s.Left.CursorMemory["/srv"] != "data" { + t.Fatalf("migrated %+v", s) + } + if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); err != nil { + t.Fatalf("not written to the new location: %v", err) + } + if _, err := os.Stat(old); !os.IsNotExist(err) { + t.Fatal("old session file not removed after migration") + } + // Nothing anywhere: empty session, no error. + isolate(t) + if s, err := Load(); err != nil || s.ActivePane != "" { + t.Fatalf("empty: %+v %v", s, err) + } +} + +func TestCursorMemoryCapped(t *testing.T) { + home := isolate(t) + mem := map[string]string{} + for i := range 500 { + mem[fmt.Sprintf("/data/d%03d", i)] = "f" + } + mem["/work/project/src"] = "main.go" + mem["/work"] = "project" + cache := filepath.Join(home, ".cache", "vcom", "run-1", "preview") + mem[cache] = "img.png" + mem[filepath.Join(os.TempDir(), "vcom-archive-123", "x")] = "y" + if err := Save(Session{Left: PaneSession{Path: "/work/project", CursorMemory: mem}}); err != nil { + t.Fatal(err) + } + s, err := Load() + if err != nil { + t.Fatal(err) + } + got := s.Left.CursorMemory + if len(got) != MaxCursorMemory { + t.Fatalf("%d entries, want %d", len(got), MaxCursorMemory) + } + if got["/work/project/src"] != "main.go" || got["/work"] != "project" { + t.Fatal("entries on the current path must survive the cap") + } + for k := range got { + if k == cache || filepath.Dir(k) == filepath.Join(os.TempDir(), "vcom-archive-123") { + t.Fatalf("transient path kept: %s", k) + } + } +} diff --git a/internal/testutil/fstree/fstree.go b/internal/testutil/fstree/fstree.go new file mode 100644 index 0000000..8956def --- /dev/null +++ b/internal/testutil/fstree/fstree.go @@ -0,0 +1,320 @@ +// Package fstree builds, snapshots and compares directory trees in tests. +// +// spec := fstree.Spec{ +// fstree.File("a.txt", "hello"), +// fstree.Dir("ro").WithMode(0o555), +// fstree.File("ro/b.bin", "").WithSize(1 << 20), +// fstree.Symlink("link", "a.txt"), +// } +// fstree.Build(t, src, spec) +// ... copy src -> dst ... +// fstree.Equal(t, fstree.Snapshot(t, src), fstree.Snapshot(t, dst), fstree.Opts{Mode: true, Links: true}) +package fstree + +import ( + "bytes" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strings" + "syscall" + "testing" + "time" +) + +// Kind of a tree node. +type Kind int + +const ( + KindFile Kind = iota + KindDir + KindSymlink + KindFIFO + KindOther +) + +func (k Kind) String() string { + switch k { + case KindFile: + return "file" + case KindDir: + return "dir" + case KindSymlink: + return "symlink" + case KindFIFO: + return "fifo" + } + return "other" +} + +// Entry describes one node to create. Path is slash-separated and relative +// to the root passed to Build. +type Entry struct { + Path string + Kind Kind + Content []byte + // Size, when > 0 and Content is empty, fills the file with a + // deterministic pattern of that many bytes. + Size int64 + // Mode is the permission bits; 0 means 0644 for files/FIFOs, 0755 for dirs. + Mode fs.FileMode + // MTime is applied after the whole tree is built; zero leaves it alone + // (and means "don't care" when the spec is used as an expectation). + MTime time.Time + Target string // symlink target +} + +// File, Dir, Symlink and FIFO construct entries. +func File(p, content string) Entry { return Entry{Path: p, Kind: KindFile, Content: []byte(content)} } +func Dir(p string) Entry { return Entry{Path: p, Kind: KindDir} } +func Symlink(p, target string) Entry { + return Entry{Path: p, Kind: KindSymlink, Target: target} +} +func FIFO(p string) Entry { return Entry{Path: p, Kind: KindFIFO} } + +// WithMode, WithMTime and WithSize return a modified copy. +func (e Entry) WithMode(m fs.FileMode) Entry { e.Mode = m; return e } +func (e Entry) WithMTime(t time.Time) Entry { e.MTime = t; return e } +func (e Entry) WithSize(n int64) Entry { e.Size = n; return e } +func (e Entry) WithContent(b []byte) Entry { e.Content = b; return e } + +// Spec is a list of entries; parents are created implicitly (0755). +type Spec []Entry + +func (e Entry) data() []byte { + if len(e.Content) > 0 || e.Size <= 0 { + return e.Content + } + b := make([]byte, e.Size) + for i := range b { + b[i] = byte(i % 251) + } + return b +} + +func (e Entry) perm() fs.FileMode { + if e.Mode != 0 { + return e.Mode.Perm() + } + if e.Kind == KindDir { + return 0o755 + } + return 0o644 +} + +// Build creates spec under root (which must exist). Directory modes and all +// mtimes are applied after every node exists, deepest first, so a 0555 +// directory can still be populated. A Cleanup restores write permission on +// directories so t.TempDir removal works. +func Build(t testing.TB, root string, spec Spec) { + t.Helper() + sorted := append(Spec(nil), spec...) + sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path }) + var dirs []string + t.Cleanup(func() { + for _, d := range dirs { + os.Chmod(d, 0o755) + } + }) + for _, e := range sorted { + p := filepath.Join(root, filepath.FromSlash(e.Path)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatalf("fstree: %v", err) + } + var err error + switch e.Kind { + case KindFile: + err = os.WriteFile(p, e.data(), 0o600) + if err == nil { + err = os.Chmod(p, e.perm()) + } + case KindDir: + err = os.MkdirAll(p, 0o755) + dirs = append(dirs, p) + case KindSymlink: + err = os.Symlink(e.Target, p) + case KindFIFO: + err = syscall.Mkfifo(p, 0o600) + if err == nil { + err = os.Chmod(p, e.perm()) + } + default: + err = fmt.Errorf("unsupported kind %v", e.Kind) + } + if err != nil { + t.Fatalf("fstree: build %s: %v", e.Path, err) + } + } + // Deepest first so setting a parent's mtime/mode comes last. + for i := len(sorted) - 1; i >= 0; i-- { + e := sorted[i] + p := filepath.Join(root, filepath.FromSlash(e.Path)) + if !e.MTime.IsZero() && e.Kind != KindSymlink { + if err := os.Chtimes(p, e.MTime, e.MTime); err != nil { + t.Fatalf("fstree: chtimes %s: %v", e.Path, err) + } + } + if e.Kind == KindDir { + if err := os.Chmod(p, e.perm()); err != nil { + t.Fatalf("fstree: chmod %s: %v", e.Path, err) + } + } + } +} + +// Node is one entry of a snapshot. +type Node struct { + Kind Kind + Mode fs.FileMode // permission bits; 0 in an expectation means "don't care" + Data []byte // file content + MTime time.Time // zero in an expectation means "don't care" + Target string // symlink target +} + +// Tree maps slash-separated relative paths to nodes (root excluded). +type Tree map[string]Node + +// FromSpec turns a spec into the tree Build would produce, for use as an +// expectation. Implicit parent directories are included with mode 0755. +func FromSpec(spec Spec) Tree { + tr := Tree{} + for _, e := range spec { + for d := path.Dir(e.Path); d != "." && d != "/"; d = path.Dir(d) { + if _, ok := tr[d]; !ok { + tr[d] = Node{Kind: KindDir, Mode: 0o755} + } + } + n := Node{Kind: e.Kind, Mode: e.perm(), MTime: e.MTime} + switch e.Kind { + case KindFile: + n.Data = e.data() + case KindSymlink: + n.Mode, n.MTime, n.Target = 0, time.Time{}, e.Target + } + tr[e.Path] = n + } + return tr +} + +// Snapshot reads the tree under root without following symlinks. +func Snapshot(t testing.TB, root string) Tree { + t.Helper() + tr := Tree{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if p == root { + return nil + } + rel, _ := filepath.Rel(root, p) + rel = filepath.ToSlash(rel) + info, err := d.Info() + if err != nil { + return err + } + n := Node{Mode: info.Mode().Perm(), MTime: info.ModTime()} + switch m := info.Mode(); { + case m.IsRegular(): + n.Kind = KindFile + b, err := os.ReadFile(p) + if err != nil { + return err + } + n.Data = b + case m.IsDir(): + n.Kind = KindDir + case m&fs.ModeSymlink != 0: + n.Kind = KindSymlink + n.Target, err = os.Readlink(p) + if err != nil { + return err + } + case m&fs.ModeNamedPipe != 0: + n.Kind = KindFIFO + default: + n.Kind = KindOther + } + tr[rel] = n + return nil + }) + if err != nil { + t.Fatalf("fstree: snapshot %s: %v", root, err) + } + return tr +} + +// Opts selects what Equal compares besides kind and file content. +type Opts struct { + Mode bool // permission bits (skipped where want.Mode == 0) + MTime bool // mtime at 1 s granularity (skipped where want.MTime is zero); dirs included + Links bool // compare symlinks and their targets; false ignores symlinks on both sides +} + +// Diff returns human-readable differences between want and got, sorted. +func Diff(want, got Tree, o Opts) []string { + var out []string + keys := map[string]bool{} + for k := range want { + keys[k] = true + } + for k := range got { + keys[k] = true + } + sorted := make([]string, 0, len(keys)) + for k := range keys { + sorted = append(sorted, k) + } + sort.Strings(sorted) + for _, k := range sorted { + w, wok := want[k] + g, gok := got[k] + if !o.Links && ((wok && w.Kind == KindSymlink) || (gok && g.Kind == KindSymlink)) { + continue + } + switch { + case !gok: + out = append(out, fmt.Sprintf("missing %s %s", w.Kind, k)) + continue + case !wok: + out = append(out, fmt.Sprintf("unexpected %s %s", g.Kind, k)) + continue + } + if w.Kind != g.Kind { + out = append(out, fmt.Sprintf("%s: kind want %s, got %s", k, w.Kind, g.Kind)) + continue + } + if w.Kind == KindFile && !bytes.Equal(w.Data, g.Data) { + out = append(out, fmt.Sprintf("%s: content want %s, got %s", k, short(w.Data), short(g.Data))) + } + if w.Kind == KindSymlink && w.Target != g.Target { + out = append(out, fmt.Sprintf("%s: link target want %q, got %q", k, w.Target, g.Target)) + } + if o.Mode && w.Kind != KindSymlink && w.Mode != 0 && w.Mode != g.Mode { + out = append(out, fmt.Sprintf("%s: mode want %04o, got %04o", k, w.Mode, g.Mode)) + } + if o.MTime && w.Kind != KindSymlink && !w.MTime.IsZero() && + !w.MTime.Truncate(time.Second).Equal(g.MTime.Truncate(time.Second)) { + out = append(out, fmt.Sprintf("%s: mtime want %s, got %s", k, w.MTime.Format(time.RFC3339), g.MTime.Format(time.RFC3339))) + } + } + return out +} + +// Equal fails t with a readable diff if the trees differ. +func Equal(t testing.TB, want, got Tree, o Opts) { + t.Helper() + if d := Diff(want, got, o); len(d) > 0 { + t.Errorf("fstree: trees differ (%d):\n %s", len(d), strings.Join(d, "\n ")) + } +} + +func short(b []byte) string { + if len(b) <= 32 { + return fmt.Sprintf("%q", b) + } + return fmt.Sprintf("%d bytes %q...", len(b), b[:16]) +} diff --git a/internal/testutil/fstree/fstree_test.go b/internal/testutil/fstree/fstree_test.go new file mode 100644 index 0000000..aaaa69f --- /dev/null +++ b/internal/testutil/fstree/fstree_test.go @@ -0,0 +1,66 @@ +package fstree + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestFstreeRoundTrip(t *testing.T) { + old := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC) + spec := Spec{ + File("a.txt", "hello").WithMTime(old), + File("bin/run.sh", "#!/bin/sh\n").WithMode(0o755), + Dir("ro").WithMode(0o555).WithMTime(old), + File("ro/inside.bin", "").WithSize(100000), + Symlink("link", "a.txt"), + Symlink("broken", "/nonexistent/zzz"), + FIFO("pipe"), + Dir("empty"), + } + root := t.TempDir() + Build(t, root, spec) + + st, err := os.Stat(filepath.Join(root, "ro")) + if err != nil || st.Mode().Perm() != 0o555 { + t.Fatalf("ro dir: %v %v", st, err) + } + got := Snapshot(t, root) + if got["ro/inside.bin"].Kind != KindFile || len(got["ro/inside.bin"].Data) != 100000 { + t.Fatalf("sized file not built: %+v", got["ro/inside.bin"].Kind) + } + Equal(t, FromSpec(spec), got, Opts{Mode: true, MTime: true, Links: true}) + + // A second build of the same spec is equal, including mode and mtime. + root2 := t.TempDir() + Build(t, root2, spec) + Equal(t, got, Snapshot(t, root2), Opts{Mode: true, Links: true}) +} + +func TestFstreeDiffReportsDifferences(t *testing.T) { + want := FromSpec(Spec{ + File("a", "x"), + File("b", "y").WithMode(0o600), + Symlink("l", "a"), + Dir("d"), + }) + got := FromSpec(Spec{ + File("a", "z"), + File("b", "y").WithMode(0o644), + Symlink("l", "b"), + File("d", ""), + File("extra", ""), + }) + d := Diff(want, got, Opts{Mode: true, Links: true}) + joined := strings.Join(d, "\n") + for _, s := range []string{"a: content", "b: mode want 0600, got 0644", "l: link target", "d: kind want dir, got file", "unexpected file extra"} { + if !strings.Contains(joined, s) { + t.Errorf("diff lacks %q:\n%s", s, joined) + } + } + if d := Diff(want, got, Opts{}); strings.Contains(strings.Join(d, "\n"), "link target") { + t.Errorf("Links=false must ignore symlinks: %v", d) + } +} diff --git a/internal/testutil/sshtest/home.go b/internal/testutil/sshtest/home.go new file mode 100644 index 0000000..84d6ce7 --- /dev/null +++ b/internal/testutil/sshtest/home.go @@ -0,0 +1,68 @@ +package sshtest + +import ( + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "os" + "path/filepath" + "testing" + + "golang.org/x/crypto/ssh" +) + +// IsolatedHome points HOME at a fresh temp dir (with ~/.ssh, mode 0700), +// clears SSH_AUTH_SOCK so no real agent is used, and returns the new HOME. +// Uses t.Setenv, so the test must not be parallel. +func IsolatedHome(t testing.TB) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("SSH_AUTH_SOCK", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil { + t.Fatal(err) + } + return home +} + +// GenKeys returns a fresh ed25519 signer and a fresh ECDSA P-256 signer. +func GenKeys(t testing.TB) (ed, ec ssh.Signer) { + t.Helper() + _, edPriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + if ed, err = ssh.NewSignerFromKey(edPriv); err != nil { + t.Fatal(err) + } + ecPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + if ec, err = ssh.NewSignerFromKey(ecPriv); err != nil { + t.Fatal(err) + } + return ed, ec +} + +// WriteRandom creates p (and parents) with size random bytes and mode. +func WriteRandom(t testing.TB, p string, size int, mode os.FileMode) []byte { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + b := make([]byte, size) + if _, err := rand.Read(b); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, b, mode); err != nil { + t.Fatal(err) + } + if err := os.Chmod(p, mode); err != nil { + t.Fatal(err) + } + return b +} diff --git a/internal/testutil/sshtest/proxy.go b/internal/testutil/sshtest/proxy.go new file mode 100644 index 0000000..cb765f5 --- /dev/null +++ b/internal/testutil/sshtest/proxy.go @@ -0,0 +1,222 @@ +package sshtest + +import ( + "net" + "sync" + "sync/atomic" + "testing" + "time" +) + +// Proxy is a TCP proxy in front of a target address that can inject latency, +// freeze traffic, or cut connections after a number of bytes. +type Proxy struct { + // Addr is host:port to dial instead of the target. + Addr string + + target string + ln net.Listener + + delay atomic.Int64 // one-way delay in nanoseconds, applied both ways + frozen atomic.Bool + sent atomic.Int64 // client->server bytes, all connections + cutAt atomic.Int64 // 0 = disabled; kill all when sent exceeds it + + mu sync.Mutex + links map[*link]struct{} + closed bool + wg sync.WaitGroup +} + +type link struct { + client, upstream net.Conn + done chan struct{} + once sync.Once +} + +func (l *link) kill() { + l.once.Do(func() { + close(l.done) + l.client.Close() + l.upstream.Close() + }) +} + +// NewProxy starts a proxy to target and registers its shutdown with +// t.Cleanup. +func NewProxy(t testing.TB, target string) *Proxy { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("sshtest: proxy listen: %v", err) + } + p := &Proxy{Addr: ln.Addr().String(), target: target, ln: ln, links: map[*link]struct{}{}} + p.wg.Add(1) + go p.acceptLoop() + t.Cleanup(p.Close) + return p +} + +// Port returns the TCP port of Addr. +func (p *Proxy) Port() string { + _, port, _ := net.SplitHostPort(p.Addr) + return port +} + +// SetDelay sets the one-way latency applied to every chunk in both +// directions (RTT grows by about 2*d). +func (p *Proxy) SetDelay(d time.Duration) { p.delay.Store(int64(d)) } + +// Freeze stops (on=true) or resumes forwarding in both directions. Data is +// buffered while frozen, connections stay open. +func (p *Proxy) Freeze(on bool) { p.frozen.Store(on) } + +// CutAfter kills all current connections once n more bytes have been sent +// client->server (counted across connections). The trigger fires once; +// n <= 0 disarms it. +func (p *Proxy) CutAfter(n int64) { + if n <= 0 { + p.cutAt.Store(0) + return + } + p.cutAt.Store(p.sent.Load() + n) +} + +// Sent reports the total client->server bytes forwarded so far. +func (p *Proxy) Sent() int64 { return p.sent.Load() } + +// KillAll closes every current connection; the proxy keeps accepting new +// ones. +func (p *Proxy) KillAll() { + p.mu.Lock() + ls := make([]*link, 0, len(p.links)) + for l := range p.links { + ls = append(ls, l) + } + p.mu.Unlock() + for _, l := range ls { + l.kill() + } +} + +// Close stops the proxy and waits for all its goroutines. Idempotent. +func (p *Proxy) Close() { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return + } + p.closed = true + p.mu.Unlock() + p.ln.Close() + p.KillAll() + p.wg.Wait() +} + +func (p *Proxy) acceptLoop() { + defer p.wg.Done() + for { + c, err := p.ln.Accept() + if err != nil { + return + } + u, err := net.DialTimeout("tcp", p.target, 5*time.Second) + if err != nil { + c.Close() + continue + } + l := &link{client: c, upstream: u, done: make(chan struct{})} + p.mu.Lock() + if p.closed { + p.mu.Unlock() + l.kill() + return + } + p.links[l] = struct{}{} + p.mu.Unlock() + var lw sync.WaitGroup + lw.Add(2) + p.wg.Add(1) + go func() { + defer p.wg.Done() + lw.Wait() + l.kill() + p.mu.Lock() + delete(p.links, l) + p.mu.Unlock() + }() + go func() { defer lw.Done(); p.pipe(l, c, u, true) }() + go func() { defer lw.Done(); p.pipe(l, u, c, false) }() + } +} + +type chunk struct { + b []byte + at time.Time +} + +// pipe forwards src -> dst through a delay queue. Returning from either +// direction kills the whole link. +func (p *Proxy) pipe(l *link, src, dst net.Conn, upstream bool) { + defer l.kill() + q := make(chan chunk, 1024) + writerDone := make(chan struct{}) + go func() { + defer close(writerDone) + defer l.kill() + for { + var c chunk + var ok bool + select { + case c, ok = <-q: + if !ok { + return // reader finished and queue drained + } + case <-l.done: + return + } + if d := time.Until(c.at); d > 0 { + t := time.NewTimer(d) + select { + case <-t.C: + case <-l.done: + t.Stop() + return + } + } + for p.frozen.Load() { + select { + case <-time.After(5 * time.Millisecond): + case <-l.done: + return + } + } + if _, err := dst.Write(c.b); err != nil { + return + } + } + }() + defer func() { close(q); <-writerDone }() + buf := make([]byte, 32*1024) + for { + n, err := src.Read(buf) + if n > 0 { + if upstream { + total := p.sent.Add(int64(n)) + if lim := p.cutAt.Load(); lim > 0 && total > lim && p.cutAt.CompareAndSwap(lim, 0) { + p.KillAll() + return + } + } + c := chunk{b: append([]byte(nil), buf[:n]...), at: time.Now().Add(time.Duration(p.delay.Load()))} + select { + case q <- c: + case <-l.done: + return + } + } + if err != nil { + return + } + } +} diff --git a/internal/testutil/sshtest/server.go b/internal/testutil/sshtest/server.go new file mode 100644 index 0000000..547ac52 --- /dev/null +++ b/internal/testutil/sshtest/server.go @@ -0,0 +1,357 @@ +// Package sshtest provides an in-process SSH/SFTP server and a fault-injecting +// TCP proxy for tests. It is a regular (non _test) package so that tests in +// different packages can share it. +// +// The server serves the real OS filesystem over the "sftp" subsystem and runs +// "exec" requests through `sh -c`, reporting exit-status and stderr. Every +// goroutine it starts is stopped by t.Cleanup. +package sshtest + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "net" + "os/exec" + "sync" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +// DefaultPassword is accepted when Options.Password is empty and no +// AuthorizedKeys are configured. +const DefaultPassword = "pw" + +// Options configures Start. +type Options struct { + // Password accepted for any user. Empty means DefaultPassword (unless + // AuthorizedKeys is set, in which case password auth is disabled). + Password string + // AuthorizedKeys enables public-key auth for these keys. + AuthorizedKeys []ssh.PublicKey + // HostKeys the server offers. Empty means a fresh ed25519 + ECDSA pair. + HostKeys []ssh.Signer + // NoExec rejects "exec" requests, like `ForceCommand internal-sftp`. + NoExec bool + // Chroot sets the SFTP working directory and the cwd of exec commands. + // Relative paths resolve against it. It is NOT a security boundary: + // absolute paths still reach the whole filesystem. + Chroot string +} + +// Server is a running in-process SSH server. +type Server struct { + // Addr is host:port to dial. + Addr string + // HostKeys the server offers. + HostKeys []ssh.Signer + // Root is the directory relative paths resolve against ("/" by default). + Root string + // Password accepted by the server ("" when password auth is disabled). + Password string + + opts Options + cfg *ssh.ServerConfig + ln net.Listener + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup + + mu sync.Mutex + conns map[net.Conn]struct{} + closed bool +} + +// Start launches a server on 127.0.0.1 and registers its shutdown with +// t.Cleanup. +func Start(t testing.TB, o Options) *Server { + t.Helper() + if len(o.HostKeys) == 0 { + ed, ec := GenKeys(t) + o.HostKeys = []ssh.Signer{ed, ec} + } + pass := o.Password + if pass == "" && len(o.AuthorizedKeys) == 0 { + pass = DefaultPassword + } + cfg := &ssh.ServerConfig{} + if pass != "" { + cfg.PasswordCallback = func(_ ssh.ConnMetadata, p []byte) (*ssh.Permissions, error) { + if string(p) == pass { + return nil, nil + } + return nil, errors.New("password rejected") + } + } + if len(o.AuthorizedKeys) > 0 { + keys := o.AuthorizedKeys + cfg.PublicKeyCallback = func(_ ssh.ConnMetadata, k ssh.PublicKey) (*ssh.Permissions, error) { + for _, ak := range keys { + if ak.Type() == k.Type() && string(ak.Marshal()) == string(k.Marshal()) { + return nil, nil + } + } + return nil, errors.New("key rejected") + } + } + for _, k := range o.HostKeys { + cfg.AddHostKey(k) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("sshtest: listen: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + root := o.Chroot + if root == "" { + root = "/" + } + s := &Server{ + Addr: ln.Addr().String(), + HostKeys: o.HostKeys, + Root: root, + Password: pass, + opts: o, + cfg: cfg, + ln: ln, + ctx: ctx, + cancel: cancel, + conns: map[net.Conn]struct{}{}, + } + s.wg.Add(1) + go s.acceptLoop() + t.Cleanup(s.Close) + return s +} + +// Port returns the TCP port of Addr. +func (s *Server) Port() string { + _, p, _ := net.SplitHostPort(s.Addr) + return p +} + +// Close stops the server, drops all connections and waits for every +// goroutine to exit. It is idempotent and called automatically by Cleanup. +func (s *Server) Close() { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return + } + s.closed = true + for c := range s.conns { + c.Close() + } + s.mu.Unlock() + s.cancel() + s.ln.Close() + s.wg.Wait() +} + +// DropConnections closes every live client connection, leaving the server +// listening (simulates a server-side disconnect). +func (s *Server) DropConnections() { + s.mu.Lock() + defer s.mu.Unlock() + for c := range s.conns { + c.Close() + } +} + +func (s *Server) track(c net.Conn) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return false + } + s.conns[c] = struct{}{} + return true +} + +func (s *Server) untrack(c net.Conn) { + s.mu.Lock() + delete(s.conns, c) + s.mu.Unlock() +} + +func (s *Server) acceptLoop() { + defer s.wg.Done() + for { + nc, err := s.ln.Accept() + if err != nil { + return + } + if !s.track(nc) { + nc.Close() + return + } + s.wg.Add(1) + go func() { + defer s.wg.Done() + defer s.untrack(nc) + defer nc.Close() + s.handle(nc) + }() + } +} + +func (s *Server) handle(nc net.Conn) { + sconn, chans, reqs, err := ssh.NewServerConn(nc, s.cfg) + if err != nil { + return + } + defer sconn.Close() + s.wg.Add(1) + go func() { + defer s.wg.Done() + ssh.DiscardRequests(reqs) + }() + for nch := range chans { + if nch.ChannelType() != "session" { + nch.Reject(ssh.UnknownChannelType, "only session channels") + continue + } + ch, creqs, err := nch.Accept() + if err != nil { + continue + } + s.wg.Add(1) + go func() { + defer s.wg.Done() + s.session(ch, creqs) + }() + } +} + +func (s *Server) session(ch ssh.Channel, reqs <-chan *ssh.Request) { + defer ch.Close() + started := false + var work sync.WaitGroup + defer work.Wait() + for req := range reqs { + switch { + case req.Type == "subsystem" && !started: + name, ok := parseString(req.Payload) + if !ok || name != "sftp" { + req.Reply(false, nil) + continue + } + var opts []sftp.ServerOption + if s.opts.Chroot != "" { + opts = append(opts, sftp.WithServerWorkingDirectory(s.opts.Chroot)) + } + srv, err := sftp.NewServer(ch, opts...) + if err != nil { + req.Reply(false, nil) + continue + } + started = true + req.Reply(true, nil) + work.Add(1) + go func() { + defer work.Done() + srv.Serve() + srv.Close() + ch.Close() + }() + case req.Type == "exec" && !started: + if s.opts.NoExec { + req.Reply(false, nil) + continue + } + cmdStr, ok := parseString(req.Payload) + if !ok { + req.Reply(false, nil) + continue + } + started = true + req.Reply(true, nil) + work.Add(1) + go func() { + defer work.Done() + s.runExec(ch, cmdStr) + }() + default: + if req.WantReply { + req.Reply(false, nil) + } + } + } +} + +func (s *Server) runExec(ch ssh.Channel, cmdStr string) { + c := exec.CommandContext(s.ctx, "sh", "-c", cmdStr) + c.WaitDelay = time.Second + if s.opts.Chroot != "" { + c.Dir = s.opts.Chroot + } + c.Stdout = ch + c.Stderr = ch.Stderr() + code := 0 + if err := c.Run(); err != nil { + code = 127 + var ee *exec.ExitError + if errors.As(err, &ee) && ee.ExitCode() >= 0 { + code = ee.ExitCode() + } + } + st := make([]byte, 4) + binary.BigEndian.PutUint32(st, uint32(code)) + ch.SendRequest("exit-status", false, st) + ch.Close() +} + +// parseString decodes an SSH wire-format string (uint32 length + bytes). +func parseString(b []byte) (string, bool) { + if len(b) < 4 { + return "", false + } + n := binary.BigEndian.Uint32(b) + if uint64(len(b)-4) < uint64(n) { + return "", false + } + return string(b[4 : 4+n]), true +} + +// ClientConfig returns an ssh.ClientConfig that authenticates to s with its +// password and pins its first host key. +func (s *Server) ClientConfig(user string) *ssh.ClientConfig { + if user == "" { + user = "u" + } + cfg := &ssh.ClientConfig{ + User: user, + Timeout: 5 * time.Second, + HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error { + for _, hk := range s.HostKeys { + if string(hk.PublicKey().Marshal()) == string(key.Marshal()) { + return nil + } + } + return fmt.Errorf("sshtest: unexpected host key %s", key.Type()) + }, + } + if s.Password != "" { + cfg.Auth = []ssh.AuthMethod{ssh.Password(s.Password)} + } + return cfg +} + +// Dial connects to addr (s.Addr or a proxy in front of it) with +// ClientConfig and closes the client on Cleanup. +func (s *Server) Dial(t testing.TB, addr string) *ssh.Client { + t.Helper() + if addr == "" { + addr = s.Addr + } + c, err := ssh.Dial("tcp", addr, s.ClientConfig("")) + if err != nil { + t.Fatalf("sshtest: dial %s: %v", addr, err) + } + t.Cleanup(func() { c.Close() }) + return c +} diff --git a/internal/testutil/sshtest/sshtest_test.go b/internal/testutil/sshtest/sshtest_test.go new file mode 100644 index 0000000..6b54c4f --- /dev/null +++ b/internal/testutil/sshtest/sshtest_test.go @@ -0,0 +1,264 @@ +package sshtest + +import ( + "bytes" + "errors" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the +// goroutine count returns to the baseline within ±2. +func noLeak(t *testing.T, fn func(t *testing.T)) { + t.Helper() + runtime.GC() + base := runtime.NumGoroutine() + t.Run("body", fn) + deadline := time.Now().Add(3 * time.Second) + var n int + for time.Now().Before(deadline) { + n = runtime.NumGoroutine() + if n <= base+2 { + return + } + time.Sleep(20 * time.Millisecond) + } + buf := make([]byte, 1<<20) + buf = buf[:runtime.Stack(buf, true)] + t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf) +} + +func sftpClient(t *testing.T, c *ssh.Client) *sftp.Client { + t.Helper() + sc, err := sftp.NewClient(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { sc.Close() }) + return sc +} + +func TestServerSFTPRoundTrip(t *testing.T) { + noLeak(t, func(t *testing.T) { + srv := Start(t, Options{}) + sc := sftpClient(t, srv.Dial(t, "")) + dir := t.TempDir() + p := filepath.Join(dir, "sub", "f.bin") + if err := sc.MkdirAll(filepath.Dir(p)); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte("vcom"), 50000) + f, err := sc.Create(p) + if err != nil { + t.Fatal(err) + } + if _, err := f.Write(want); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(p) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("disk content mismatch: err=%v len=%d", err, len(got)) + } + r, err := sc.Open(p) + if err != nil { + t.Fatal(err) + } + back, err := io.ReadAll(r) + r.Close() + if err != nil || !bytes.Equal(back, want) { + t.Fatalf("read back mismatch: err=%v len=%d", err, len(back)) + } + }) +} + +func TestServerChrootWorkingDir(t *testing.T) { + root := t.TempDir() + WriteRandom(t, filepath.Join(root, "x.bin"), 10, 0o644) + srv := Start(t, Options{Chroot: root}) + sc := sftpClient(t, srv.Dial(t, "")) + if _, err := sc.Stat("x.bin"); err != nil { + t.Fatalf("relative path should resolve inside Chroot: %v", err) + } + if srv.Root != root { + t.Fatalf("Root=%q want %q", srv.Root, root) + } +} + +func TestServerExecStatusAndStderr(t *testing.T) { + noLeak(t, func(t *testing.T) { + srv := Start(t, Options{}) + c := srv.Dial(t, "") + s, err := c.NewSession() + if err != nil { + t.Fatal(err) + } + var out, errb bytes.Buffer + s.Stdout, s.Stderr = &out, &errb + err = s.Run("echo hi; echo oops >&2; exit 3") + s.Close() + var ee *ssh.ExitError + if !errors.As(err, &ee) || ee.ExitStatus() != 3 { + t.Fatalf("want exit status 3, got %v", err) + } + if out.String() != "hi\n" || errb.String() != "oops\n" { + t.Fatalf("stdout=%q stderr=%q", out.String(), errb.String()) + } + }) +} + +func TestServerNoExec(t *testing.T) { + srv := Start(t, Options{NoExec: true}) + c := srv.Dial(t, "") + s, err := c.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + if err := s.Run("true"); err == nil { + t.Fatal("exec must be rejected with NoExec") + } + sftpClient(t, c) // sftp still works +} + +func TestServerPublicKeyAuth(t *testing.T) { + ed, _ := GenKeys(t) + srv := Start(t, Options{AuthorizedKeys: []ssh.PublicKey{ed.PublicKey()}}) + cfg := srv.ClientConfig("") + if _, err := ssh.Dial("tcp", srv.Addr, cfg); err == nil { + t.Fatal("password auth must be disabled when only keys are configured") + } + cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(ed)} + c, err := ssh.Dial("tcp", srv.Addr, cfg) + if err != nil { + t.Fatal(err) + } + c.Close() +} + +func rtt(t *testing.T, sc *sftp.Client, p string) time.Duration { + t0 := time.Now() + if _, err := sc.Stat(p); err != nil { + t.Fatal(err) + } + return time.Since(t0) +} + +func TestProxyDelay(t *testing.T) { + noLeak(t, func(t *testing.T) { + srv := Start(t, Options{}) + px := NewProxy(t, srv.Addr) + sc := sftpClient(t, srv.Dial(t, px.Addr)) + dir := t.TempDir() + base := rtt(t, sc, dir) + const d = 40 * time.Millisecond + px.SetDelay(d) + got := rtt(t, sc, dir) + t.Logf("rtt without delay=%v with %v one-way delay=%v", base, d, got) + if got < d { + t.Fatalf("rtt %v < delay %v", got, d) + } + px.SetDelay(0) + }) +} + +func TestProxyFreeze(t *testing.T) { + noLeak(t, func(t *testing.T) { + srv := Start(t, Options{}) + px := NewProxy(t, srv.Addr) + sc := sftpClient(t, srv.Dial(t, px.Addr)) + dir := t.TempDir() + px.Freeze(true) + res := make(chan error, 1) + go func() { _, err := sc.ReadDir(dir); res <- err }() + select { + case err := <-res: + t.Fatalf("request completed while frozen: %v", err) + case <-time.After(300 * time.Millisecond): + } + px.Freeze(false) + select { + case err := <-res: + if err != nil { + t.Fatalf("request failed after unfreeze: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("request did not complete after unfreeze") + } + }) +} + +func TestProxyCut(t *testing.T) { + noLeak(t, func(t *testing.T) { + srv := Start(t, Options{}) + px := NewProxy(t, srv.Addr) + c := srv.Dial(t, px.Addr) + sc := sftpClient(t, c) + dir := t.TempDir() + before := px.Sent() + px.CutAfter(256 << 10) + f, err := sc.Create(filepath.Join(dir, "big.bin")) + if err != nil { + t.Fatal(err) + } + _, werr := f.Write(make([]byte, 4<<20)) + f.Close() + if werr == nil { + t.Fatal("write of 4 MiB should fail after cut at 256 KiB") + } + sent := px.Sent() - before + if sent > 1<<20 { + t.Fatalf("proxy forwarded %d bytes after a 256 KiB cut", sent) + } + done := make(chan struct{}) + go func() { c.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("ssh connection still alive after cut") + } + // The proxy keeps accepting connections after a cut. + sc2 := sftpClient(t, srv.Dial(t, px.Addr)) + if _, err := sc2.Stat(dir); err != nil { + t.Fatalf("new connection after cut: %v", err) + } + }) +} + +func TestProxyKillAll(t *testing.T) { + srv := Start(t, Options{}) + px := NewProxy(t, srv.Addr) + c := srv.Dial(t, px.Addr) + px.KillAll() + done := make(chan error, 1) + go func() { done <- c.Wait() }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("connection survived KillAll") + } +} + +func TestIsolatedHome(t *testing.T) { + h := IsolatedHome(t) + if os.Getenv("HOME") != h || os.Getenv("SSH_AUTH_SOCK") != "" { + t.Fatal("env not isolated") + } + st, err := os.Stat(filepath.Join(h, ".ssh")) + if err != nil || st.Mode().Perm() != 0o700 { + t.Fatalf(".ssh: %v %v", st, err) + } + if !strings.HasPrefix(h, os.TempDir()) { + t.Logf("home outside TMPDIR: %s", h) + } +} diff --git a/internal/testutil/teadriver/driver.go b/internal/testutil/teadriver/driver.go new file mode 100644 index 0000000..baf05b9 --- /dev/null +++ b/internal/testutil/teadriver/driver.go @@ -0,0 +1,350 @@ +// Package teadriver drives a Bubble Tea model in tests without a terminal: +// it feeds key/mouse messages to Update, executes returned commands in +// goroutines (unwrapping Batch and Sequence) and feeds their results back +// until the model is quiet, and renders View without ANSI escapes. +// +// The lipgloss color profile is process-global, so tests using a Driver must +// not run in parallel with each other. +package teadriver + +import ( + "fmt" + "reflect" + "strings" + "sync" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" +) + +// DefaultLongCmd is how long Settle waits for a single command before +// treating it as a timer or long wait (e.g. tea.Tick with a long delay) and +// returning without it. Its result is still delivered on a later Settle. +const DefaultLongCmd = time.Second + +// Option configures New. +type Option func(*Driver) + +// WithProfile renders with the given color profile instead of Ascii. +func WithProfile(p termenv.Profile) Option { return func(d *Driver) { d.profile = p } } + +// WithLongCmd overrides DefaultLongCmd. +func WithLongCmd(dur time.Duration) Option { return func(d *Driver) { d.LongCmd = dur } } + +// WithoutInit skips running the model's Init command. +func WithoutInit() Option { return func(d *Driver) { d.skipInit = true } } + +// Driver runs a model. It is not safe for concurrent use. +type Driver struct { + // LongCmd: see DefaultLongCmd. + LongCmd time.Duration + + t testing.TB + m tea.Model + w, h int + profile termenv.Profile + skipInit bool + + pending []tea.Cmd + nextID int + inflight map[int]time.Time + results chan result + + quit bool + execs []tea.Msg + msgs int +} + +type result struct { + id int + msg tea.Msg + final bool // the command (or whole sequence) is done + panic any +} + +// New creates a driver, sets the color profile (Ascii by default), sends a +// WindowSizeMsg of w×h and queues the model's Init command (run by the +// next Settle). +func New(t testing.TB, m tea.Model, w, h int, opts ...Option) *Driver { + t.Helper() + d := &Driver{ + LongCmd: DefaultLongCmd, + t: t, + m: m, + w: w, + h: h, + profile: termenv.Ascii, + inflight: map[int]time.Time{}, + results: make(chan result, 1024), + } + for _, o := range opts { + o(d) + } + prev := lipgloss.ColorProfile() + lipgloss.SetColorProfile(d.profile) + t.Cleanup(func() { lipgloss.SetColorProfile(prev) }) + if !d.skipInit { + d.enqueue(m.Init()) + } + d.Send(tea.WindowSizeMsg{Width: w, Height: h}) + return d +} + +// Model returns the current model. +func (d *Driver) Model() tea.Model { return d.m } + +// Quit reports whether a command returned tea.QuitMsg. +func (d *Driver) Quit() bool { return d.quit } + +// Execs returns the tea.ExecProcess requests the model made. They are +// recorded, never run. +func (d *Driver) Execs() []tea.Msg { return d.execs } + +// Send passes msg to Update synchronously and queues the returned command. +func (d *Driver) Send(msg tea.Msg) { + d.t.Helper() + m, cmd := d.m.Update(msg) + if m == nil { + d.t.Fatalf("teadriver: Update(%T) returned nil model", msg) + } + d.m = m + d.msgs++ + d.enqueue(cmd) +} + +// Press sends one key message per argument, using tea key names: "enter", +// "esc", "tab", "f5", "pgdown", "ctrl+r", "alt+left", "shift+up", " " or +// "space", or literal text ("j", "п") sent as runes. +func (d *Driver) Press(keys ...string) { + d.t.Helper() + for _, k := range keys { + d.Send(Key(d.t, k)) + } +} + +// Type sends one rune key message per rune of text. +func (d *Driver) Type(text string) { + d.t.Helper() + for _, r := range text { + if r == ' ' { + d.Send(tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}}) + continue + } + d.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) + } +} + +// Mouse sends a press of button at cell (x, y) followed by a release. +func (d *Driver) Mouse(x, y int, button tea.MouseButton) { + d.t.Helper() + d.Send(tea.MouseMsg{X: x, Y: y, Button: button, Action: tea.MouseActionPress}) + if button != tea.MouseButtonWheelUp && button != tea.MouseButtonWheelDown { + d.Send(tea.MouseMsg{X: x, Y: y, Button: button, Action: tea.MouseActionRelease}) + } +} + +// Screen renders View with ANSI escapes stripped. +func (d *Driver) Screen() string { return ansi.Strip(d.m.View()) } + +// ScreenContains reports whether the rendered screen contains s. +func (d *Driver) ScreenContains(s string) bool { return strings.Contains(d.Screen(), s) } + +// Settle runs queued commands concurrently and feeds their messages back to +// Update until nothing is left, except commands that have been running +// longer than LongCmd (timers); their results arrive on a later Settle. It +// also returns at timeout, logging what is still running. +func (d *Driver) Settle(timeout time.Duration) { + d.t.Helper() + deadline := time.Now().Add(timeout) + for { + d.launchPending() + // Deliver whatever is already done without blocking. + if d.drainReady() { + continue + } + if len(d.inflight) == 0 { + return + } + now := time.Now() + var wake time.Time + for _, started := range d.inflight { + if old := started.Add(d.LongCmd); old.After(now) && (wake.IsZero() || old.Before(wake)) { + wake = old + } + } + if wake.IsZero() { + return // only long-running commands remain + } + if now.After(deadline) { + d.t.Logf("teadriver: Settle timed out after %v with %d command(s) running", timeout, len(d.inflight)) + return + } + if deadline.Before(wake) { + wake = deadline + } + timer := time.NewTimer(time.Until(wake)) + select { + case r := <-d.results: + timer.Stop() + d.handle(r) + case <-timer.C: + } + } +} + +func (d *Driver) drainReady() bool { + got := false + for { + select { + case r := <-d.results: + d.handle(r) + got = true + default: + return got + } + } +} + +func (d *Driver) enqueue(cmd tea.Cmd) { + if cmd != nil { + d.pending = append(d.pending, cmd) + } +} + +func (d *Driver) launchPending() { + cmds := d.pending + d.pending = nil + for _, c := range cmds { + d.launch([]tea.Cmd{c}) + } +} + +// launch runs cmds one after another in a goroutine (one cmd for a plain +// command, several for a Sequence). +func (d *Driver) launch(cmds []tea.Cmd) { + id := d.nextID + d.nextID++ + d.inflight[id] = time.Now() + results := d.results + go func() { + var once sync.Once + defer func() { + if p := recover(); p != nil { + once.Do(func() { results <- result{id: id, final: true, panic: p} }) + } + }() + for _, c := range cmds { + if c != nil { + results <- result{id: id, msg: c()} + } + } + once.Do(func() { results <- result{id: id, final: true} }) + }() +} + +func (d *Driver) handle(r result) { + d.t.Helper() + if r.final { + delete(d.inflight, r.id) + } + if r.panic != nil { + d.t.Fatalf("teadriver: command panicked: %v", r.panic) + } + d.deliver(r.msg) +} + +func (d *Driver) deliver(msg tea.Msg) { + d.t.Helper() + switch msg := msg.(type) { + case nil: + return + case tea.BatchMsg: + for _, c := range msg { + d.enqueue(c) + } + return + case tea.QuitMsg: + d.quit = true + return + } + if cmds, ok := asSequence(msg); ok { + d.launch(cmds) + return + } + if isExec(msg) { + d.execs = append(d.execs, msg) + return + } + d.Send(msg) +} + +const teaPkg = "github.com/charmbracelet/bubbletea" + +func asSequence(msg tea.Msg) ([]tea.Cmd, bool) { + v := reflect.ValueOf(msg) + t := v.Type() + if t.PkgPath() != teaPkg || t.Name() != "sequenceMsg" || t.Kind() != reflect.Slice { + return nil, false + } + cmds := make([]tea.Cmd, v.Len()) + for i := range cmds { + cmds[i], _ = v.Index(i).Interface().(tea.Cmd) + } + return cmds, true +} + +func isExec(msg tea.Msg) bool { + t := reflect.TypeOf(msg) + return t.PkgPath() == teaPkg && t.Name() == "execMsg" +} + +var keyTypes = func() map[string]tea.KeyType { + m := map[string]tea.KeyType{} + for kt := tea.KeyType(-200); kt <= 200; kt++ { + if kt == tea.KeyRunes { + continue + } + name := tea.Key{Type: kt}.String() + if name == "" { + continue + } + if _, dup := m[name]; !dup { + m[name] = kt + } + } + m["space"] = tea.KeySpace + return m +}() + +// Key converts a key name (see Press) to a tea.KeyMsg. +func Key(t testing.TB, s string) tea.KeyMsg { + t.Helper() + if kt, ok := keyTypes[s]; ok { + k := tea.KeyMsg{Type: kt} + if kt == tea.KeySpace { + k.Runes = []rune{' '} + } + return k + } + if rest, ok := strings.CutPrefix(s, "alt+"); ok && rest != "" { + k := Key(t, rest) + k.Alt = true + return k + } + if s == "" { + t.Fatalf("teadriver: empty key") + } + if strings.Contains(s, "+") && len([]rune(s)) > 1 { + t.Fatalf("teadriver: unknown key %q", s) + } + return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} +} + +// String describes the driver state for failure messages. +func (d *Driver) String() string { + return fmt.Sprintf("teadriver{msgs=%d inflight=%d pending=%d quit=%v}", d.msgs, len(d.inflight), len(d.pending), d.quit) +} diff --git a/internal/testutil/teadriver/driver_test.go b/internal/testutil/teadriver/driver_test.go new file mode 100644 index 0000000..78594de --- /dev/null +++ b/internal/testutil/teadriver/driver_test.go @@ -0,0 +1,107 @@ +package teadriver + +import ( + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +type note string + +type toy struct { + got []string + keys []string +} + +func (m toy) Init() tea.Cmd { return func() tea.Msg { return note("init") } } + +func emit(s string) tea.Cmd { return func() tea.Msg { return note(s) } } + +func (m toy) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case note: + m.got = append(m.got, string(msg)) + if msg == "a" { + return m, emit("a-followup") + } + case tea.KeyMsg: + m.keys = append(m.keys, msg.String()) + switch msg.String() { + case "x": + return m, tea.Batch( + emit("a"), + tea.Batch(emit("b"), nil, emit("c")), + tea.Sequence(emit("s1"), emit("s2")), + tea.Tick(time.Hour, func(time.Time) tea.Msg { return note("never") }), + ) + case "q": + return m, tea.Quit + } + } + return m, nil +} + +func (m toy) View() string { return "\x1b[1mgot:\x1b[0m " + strings.Join(m.got, ",") } + +func TestDriverSettleBatch(t *testing.T) { + d := New(t, toy{}, 80, 24, WithLongCmd(100*time.Millisecond)) + d.Settle(time.Second) + d.Press("x") + t0 := time.Now() + d.Settle(5 * time.Second) + if el := time.Since(t0); el > 2*time.Second { + t.Fatalf("Settle waited for the long tick: %v", el) + } + m := d.Model().(toy) + have := map[string]bool{} + for _, g := range m.got { + have[g] = true + } + for _, want := range []string{"init", "a", "a-followup", "b", "c", "s1", "s2"} { + if !have[want] { + t.Errorf("missing %q in %v", want, m.got) + } + } + if have["never"] { + t.Error("hour-long tick must not be awaited") + } + idx := func(s string) int { + for i, g := range m.got { + if g == s { + return i + } + } + return -1 + } + if idx("s1") > idx("s2") { + t.Errorf("sequence out of order: %v", m.got) + } + if s := d.Screen(); strings.Contains(s, "\x1b") || !strings.HasPrefix(s, "got: init") { + t.Errorf("screen not stripped: %q", s) + } + d.Press("q") + d.Settle(time.Second) + if !d.Quit() { + t.Error("tea.Quit not detected") + } +} + +func TestDriverKeys(t *testing.T) { + for _, k := range []string{"enter", "esc", "tab", "f5", "f12", "pgdown", "ctrl+r", "shift+up", "alt+left", "backspace", "delete", " ", "j", "п"} { + got := Key(t, k).String() + want := k + if k == "alt+left" { + want = "alt+left" + } + if got != want { + t.Errorf("Key(%q).String() = %q", k, got) + } + } + d := New(t, toy{}, 80, 24, WithoutInit()) + d.Type("ab п") + if got := strings.Join(d.Model().(toy).keys, "|"); got != "a|b| |п" { + t.Errorf("typed keys %q", got) + } +} diff --git a/internal/theme/chroma.go b/internal/theme/chroma.go new file mode 100644 index 0000000..fc5f3d5 --- /dev/null +++ b/internal/theme/chroma.go @@ -0,0 +1,36 @@ +package theme + +import "strings" + +// chromaStyles maps every built-in theme to the closest chroma style +// (U-P2: the old table knew 7 of the themes and fell back to catppuccin). +var chromaStyles = map[string]string{ + "catppuccin-mocha": "catppuccin-mocha", + "catppuccin-macchiato": "catppuccin-macchiato", + "catppuccin-lavender": "catppuccin-mocha", + "tokyo-night": "tokyonight-night", + "gruvbox-dark": "gruvbox", + "nord": "nord", + "one-dark": "onedark", + "everforest": "evergarden", + "github-dark": "github-dark", + "ayu-dark": "doom-one", + "breeze": "nordic", + "cyberpunk": "aura-theme-dark", + "dracula": "dracula", + "eldritch": "aura-theme-dark-soft", + "kanagawa": "tokyonight-storm", + "kanagawa-paper": "tokyonight-moon", + "rose-pine": "rose-pine", + "solarized-dark": "solarized-dark", + "vesper": "monokai", +} + +// ChromaStyle returns the chroma style name for a theme (unknown themes get +// the default theme's style). +func ChromaStyle(theme string) string { + if s, ok := chromaStyles[strings.ToLower(strings.TrimSpace(theme))]; ok { + return s + } + return chromaStyles[builtInThemes[0]] +} diff --git a/internal/theme/chroma_test.go b/internal/theme/chroma_test.go new file mode 100644 index 0000000..a45fedc --- /dev/null +++ b/internal/theme/chroma_test.go @@ -0,0 +1,26 @@ +package theme + +import ( + "testing" + + "github.com/alecthomas/chroma/v2/styles" +) + +func TestEveryThemeHasChromaStyle(t *testing.T) { + for _, name := range Names() { + s, ok := chromaStyles[name] + if !ok { + t.Errorf("theme %q has no chroma mapping", name) + continue + } + if _, ok := styles.Registry[s]; !ok { + t.Errorf("theme %q maps to unknown chroma style %q", name, s) + } + } + if len(chromaStyles) != len(Names()) { + t.Errorf("mapping has %d entries for %d themes", len(chromaStyles), len(Names())) + } + if ChromaStyle("no-such-theme") != "catppuccin-mocha" { + t.Error("fallback") + } +} diff --git a/internal/transfer/atomic.go b/internal/transfer/atomic.go new file mode 100644 index 0000000..ea7df99 --- /dev/null +++ b/internal/transfer/atomic.go @@ -0,0 +1,203 @@ +package transfer + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "time" + "unicode/utf8" + + "vcom/internal/vfs" +) + +// oldPrefix names the aside copy of a replaced file on FSes without atomic +// replace: /.vcom-old-<8hex>-. +const oldPrefix = ".vcom-old-" + +// maxName is NAME_MAX on Linux and OpenSSH servers. +const maxName = 255 + +// WriteOptions control WriteAtomic. +type WriteOptions struct { + Perm fs.FileMode // final mode (0 → 0644); the temp file is 0600 while being written + ModTime time.Time // zero → leave as written + Replace bool // replace an existing target (else ErrExist if it exists) + Fsync bool // fsync before the rename (if the FS supports it) +} + +// WriteAtomic is the only way the engine (and archive.Create, remote edit) +// writes a file: fill writes into /.vcom-part-<8hex>-, which is +// then closed, chmod'ed, chtimes'ed and renamed over path. On any error or +// cancellation the temp file is removed and an existing target is untouched: +// it is replaced only by the final rename (N-P0-4). A Close error is an +// error (N-P2-6). +func WriteAtomic(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) error { + tmp, err := writeTemp(ctx, fsys, path, o, fill) + if err != nil { + return err + } + if err := commit(ctx, fsys, tmp, path, o.Replace); err != nil { + removeQuiet(ctx, fsys, tmp) + return err + } + return nil +} + +// tempName returns /<8hex>-, truncating name so the result +// fits NAME_MAX. +func tempName(fsys vfs.FS, path, prefix string) string { + ops := fsys.Paths() + var b [4]byte + _, _ = rand.Read(b[:]) + head := prefix + hex.EncodeToString(b[:]) + "-" + name := ops.Base(path) + if len(head)+len(name) > maxName { + name = name[:maxName-len(head)] + for len(name) > 0 && !utf8.ValidString(name) { + name = name[:len(name)-1] + } + } + return ops.Join(ops.Dir(path), head+name) +} + +// writeTemp writes the content into a fresh temp file next to path and +// returns its name; on error nothing is left behind. +func writeTemp(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + var ( + tmp string + f vfs.File + err error + ) + for range 8 { + tmp = tempName(fsys, path, partPrefix) + f, err = fsys.Create(ctx, tmp, 0o600, vfs.CreateExcl) + if !errors.Is(err, vfs.ErrExist) { + break + } + } + if err != nil { + return "", err + } + // A hung network write is released by closing the file on cancel. + stop := context.AfterFunc(ctx, func() { _ = f.Close() }) + err = fill(&ctxWriter{ctx: ctx, f: f}) + if err == nil && o.Fsync && fsys.Caps().Fsync { + err = f.Sync() + } + var cerr error + if stop() { + cerr = f.Close() + } + if ctx.Err() != nil { + err = ctx.Err() + } + if err == nil && cerr != nil { + err = fmt.Errorf("close: %w", cerr) + } + if err == nil { + err = finishMeta(ctx, fsys, tmp, o) + } + if err != nil { + if rerr := removeQuiet(ctx, fsys, tmp); rerr != nil { + return "", &leftoverError{path: tmp, err: err} + } + return "", err + } + return tmp, nil +} + +// leftoverError: the operation failed and its temp file could not be +// removed either (typically a dead connection). The executor removes it +// later — on a retry or at the end of the transfer. +type leftoverError struct { + path string + err error +} + +func (e *leftoverError) Error() string { return e.err.Error() } +func (e *leftoverError) Unwrap() error { return e.err } + +func finishMeta(ctx context.Context, fsys vfs.FS, p string, o WriteOptions) error { + caps := fsys.Caps() + perm := o.Perm + if perm == 0 { + perm = 0o644 + } + if caps.Chmod { + if err := fsys.Chmod(ctx, p, perm); err != nil { + return err + } + } + if caps.Chtimes && !o.ModTime.IsZero() { + if err := fsys.Chtimes(ctx, p, o.ModTime, o.ModTime); err != nil { + return err + } + } + return nil +} + +// commit renames tmp to path. Without replace it fails with ErrExist when +// path exists. With replace on an FS without atomic replace it renames the +// old target aside first and restores it if the second rename fails. +func commit(ctx context.Context, fsys vfs.FS, tmp, path string, replace bool) error { + if !replace { + return fsys.Rename(ctx, tmp, path, vfs.NoReplace) + } + if fsys.Caps().AtomicReplace { + return fsys.Rename(ctx, tmp, path, vfs.Replace) + } + err := fsys.Rename(ctx, tmp, path, vfs.NoReplace) + if !errors.Is(err, vfs.ErrExist) { + return err + } + old := tempName(fsys, path, oldPrefix) + if err := fsys.Rename(ctx, path, old, vfs.NoReplace); err != nil { + return err + } + if err := fsys.Rename(ctx, tmp, path, vfs.NoReplace); err != nil { + if rerr := fsys.Rename(context.WithoutCancel(ctx), old, path, vfs.NoReplace); rerr != nil { + return fmt.Errorf("%w (and restoring the old file from %s failed: %v)", err, old, rerr) + } + return err + } + removeQuiet(ctx, fsys, old) + return nil +} + +// removeQuiet deletes a temp file even when ctx is already cancelled. A +// file that is already gone is not an error. +func removeQuiet(ctx context.Context, fsys vfs.FS, p string) error { + err := fsys.Remove(context.WithoutCancel(ctx), p) + if err == nil || errors.Is(err, vfs.ErrNotExist) { + return nil + } + return err +} + +// ctxWriter stops writing once ctx is done and keeps the File's ReadFrom +// (pkg/sftp uses it for concurrent writes; N-P1-6). +type ctxWriter struct { + ctx context.Context + f vfs.File +} + +func (w *ctxWriter) Write(p []byte) (int, error) { + if err := w.ctx.Err(); err != nil { + return 0, err + } + return w.f.Write(p) +} + +func (w *ctxWriter) ReadFrom(r io.Reader) (int64, error) { + if rf, ok := w.f.(io.ReaderFrom); ok { + return rf.ReadFrom(r) + } + return io.Copy(struct{ io.Writer }{w}, r) +} diff --git a/internal/transfer/cancel_test.go b/internal/transfer/cancel_test.go new file mode 100644 index 0000000..0fcc97b --- /dev/null +++ b/internal/transfer/cancel_test.go @@ -0,0 +1,96 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +// slow sleeps on every op of the given kind (a slow link). +func slow(op vfstest.Op, d time.Duration) func(vfstest.Op, string) error { + return func(o vfstest.Op, _ string) error { + if o == op { + time.Sleep(d) + } + return nil + } +} + +func TestCancelMidFileReportsCancelled(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("big.bin", "").WithSize(3 << 20), fstree.File("next", "n")}, + fstree.Spec{fstree.File("big.bin", "OLD")}) + to := &vfstest.FaultFS{FS: local, Hook: slow(vfstest.OpWrite, 5*time.Millisecond)} // ~0.5 s for 3 MiB + plan, err := Prepare(bg, req(Copy, local, join(src, "big.bin", "next"), to, dst, overwrite), nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(bg) + var cancelledAt time.Time + time.AfterFunc(150*time.Millisecond, func() { cancelledAt = time.Now(); cancel() }) + var last Progress + rep := Execute(ctx, plan, Hooks{Progress: func(p Progress) { last = p }}) + took := time.Since(cancelledAt) + if took > 200*time.Millisecond { + t.Fatalf("returned %v after cancel (N-P1-7)", took) + } + if !rep.Cancelled || rep.Done != 0 || rep.Err != nil { + t.Fatalf("report %+v: must say cancelled, not success", rep) + } + if read(t, filepath.Join(dst, "big.bin")) != "OLD" { + t.Fatal("old target damaged by a cancelled overwrite") + } + if _, err := os.Lstat(filepath.Join(dst, "next")); !os.IsNotExist(err) { + t.Fatal("items after the cancel were copied") + } + if last.BytesDone >= plan.TotalBytes { + t.Fatalf("progress claims completion: %+v", last) + } + noLeftovers(t, dst) +} + +func TestCancelDuringPrepare(t *testing.T) { + var spec fstree.Spec + for i := range 100 { + spec = append(spec, fstree.File(fmt.Sprintf("d/s%03d/f", i), "")) + } + src, dst := layout(t, spec, nil) + from := &vfstest.FaultFS{FS: local, Hook: slow(vfstest.OpReadDir, 20*time.Millisecond)} // ~2 s walk + ctx, cancel := context.WithCancel(bg) + time.AfterFunc(50*time.Millisecond, cancel) + t0 := time.Now() + plan, err := Prepare(ctx, req(Copy, from, join(src, "d"), local, dst), nil) + if !errors.Is(err, vfs.ErrCancelled) || plan != nil { + t.Fatalf("plan=%v err=%v, want cancelled", plan, err) + } + if el := time.Since(t0); el > 200*time.Millisecond { + t.Fatalf("Prepare took %v after a cancel at 50 ms", el) + } + if ents, _ := os.ReadDir(dst); len(ents) != 0 { + t.Fatal("Prepare wrote to the target") + } +} + +func TestCancelBeforeExecute(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", "a")}, nil) + plan, err := Prepare(bg, req(Copy, local, join(src, "a"), local, dst), nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(bg) + cancel() + rep := Execute(ctx, plan, Hooks{}) + if !rep.Cancelled || rep.Done != 0 { + t.Fatalf("%+v", rep) + } + if ents, _ := os.ReadDir(dst); len(ents) != 0 { + t.Fatalf("wrote after cancel: %v", ents) + } +} diff --git a/internal/transfer/conflict.go b/internal/transfer/conflict.go new file mode 100644 index 0000000..295f647 --- /dev/null +++ b/internal/transfer/conflict.go @@ -0,0 +1,161 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "path" + "strings" + + "vcom/internal/vfs" +) + +// resolve decides what to do with an item whose target exists. +func (e *executor) resolve(it Item, existing vfs.FileInfo, kind ConflictKind) (ResolveAction, error) { + if r, ok := e.applyAll[kind]; ok { + return e.restrict(it, kind, r), nil + } + var a ResolveAction + switch e.opts.Conflict { + case Overwrite: + a = ResolveOverwrite + case Skip: + a = ResolveSkip + case KeepBoth: + a = ResolveKeepBoth + case OverwriteOlder: + a = ResolveSkip + if it.ModTime.After(existing.ModTime) { + a = ResolveOverwrite + } + default: // Ask + if e.h.Resolve == nil { + a = ResolveSkip + break + } + c := Conflict{Item: it, Kind: kind} + c.Item.Existing = &existing + res, err := e.h.Resolve(e.ctx, c) + if err != nil { + return ResolveAbort, err + } + if res.ApplyToAll && res.Action != ResolveAbort { + e.applyAll[kind] = res.Action + } + a = res.Action + } + return e.restrict(it, kind, a), nil +} + +// restrict: a type mismatch (file↔dir, link↔dir) is never overwritten — +// that would mean deleting a directory tree. +func (e *executor) restrict(it Item, kind ConflictKind, a ResolveAction) ResolveAction { + if kind == TypeMismatch && a == ResolveOverwrite { + e.rep.Warnings = append(e.rep.Warnings, it.Rel+": target is of another type (file/directory); not overwritten") + return ResolveSkip + } + return a +} + +func conflictKind(it Item, existing vfs.FileInfo) ConflictKind { + if (it.Kind == Dir) != existing.IsDir() { + return TypeMismatch + } + return FileFile +} + +// keepBothName returns "name (n).ext" for n = 1, 2, ... (".tar.gz" and +// friends stay together; dot-files and directories get no extension split). +func keepBothName(name string, n int, isDir bool) string { + stem, ext := name, "" + if !isDir { + lower := strings.ToLower(name) + for _, double := range []string{".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst"} { + if strings.HasSuffix(lower, double) && len(name) > len(double) { + ext = name[len(name)-len(double):] + break + } + } + if ext == "" { + if ext = path.Ext(name); ext == name { + ext = "" + } + } + stem = name[:len(name)-len(ext)] + } + return fmt.Sprintf("%s (%d)%s", stem, n, ext) +} + +// freeRel finds a rel "name (n).ext" that does not exist in the target. +func (e *executor) freeRel(rel string, isDir bool) (string, error) { + parent, name := splitRel(rel) + for n := 1; n <= 10000; n++ { + cand := keepBothName(name, n, isDir) + if parent != "" { + cand = parent + "/" + cand + } + _, err := e.to.Lstat(e.ctx, dstPath(e.to, e.toDir, cand)) + if errors.Is(err, vfs.ErrNotExist) { + return cand, nil + } + if err != nil { + return "", err + } + } + return "", fmt.Errorf("no free name for %s", rel) +} + +var errStop = errors.New("transfer stopped") + +// handleError applies the error policy. It returns errStop to end the +// transfer, nil to skip the item, or errRetry. +func (e *executor) handleError(it Item, op string, err error) error { + if e.ctx.Err() != nil { + return errStop + } + ie := ItemError{Item: it, Op: op, Err: err} + record := func() { + e.rep.Errors = append(e.rep.Errors, ie) + e.rep.Failed++ + e.markIncomplete(it.Rel) + } + if e.skipErrors || e.opts.OnError == ErrorSkipAll { + record() + return nil + } + if e.opts.OnError == ErrorAbort { + record() + e.rep.Err = fmt.Errorf("%w: %v", ErrAborted, ie) + return errStop + } + if e.h.OnError == nil { + record() + return nil + } + a, herr := e.h.OnError(e.ctx, ie) + if herr != nil { + record() + if e.ctx.Err() == nil { + e.rep.Err = herr + } + return errStop + } + switch a { + case ErrorRetry: + return errRetry + case ErrorSkipRest: + e.skipErrors = true + case ErrorStop: + record() + e.rep.Err = fmt.Errorf("%w: %v", ErrAborted, ie) + return errStop + } + record() + return nil +} + +var errRetry = errors.New("retry") + +func isCancel(ctx context.Context, err error) bool { + return ctx.Err() != nil || errors.Is(err, context.Canceled) +} diff --git a/internal/transfer/conflict_test.go b/internal/transfer/conflict_test.go new file mode 100644 index 0000000..fe59914 --- /dev/null +++ b/internal/transfer/conflict_test.go @@ -0,0 +1,288 @@ +package transfer + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync/atomic" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +func TestConflictAskApplyToAll(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/a", "new-a"), fstree.File("d/b", "new-b"), fstree.File("d/c", "new-c"), fstree.File("d/n", "n"), + }, fstree.Spec{fstree.File("d/a", "old"), fstree.File("d/b", "old"), fstree.File("d/c", "old")}) + var asked []string + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{ + Resolve: func(_ context.Context, c Conflict) (Resolution, error) { + asked = append(asked, c.Item.Rel) + if c.Item.Existing == nil || c.Kind != FileFile { + t.Errorf("conflict without Existing/kind: %+v", c) + } + if c.Item.Rel == "d/a" { + return Resolution{Action: ResolveSkip}, nil + } + return Resolution{Action: ResolveOverwrite, ApplyToAll: true}, nil + }, + }) + if len(asked) != 2 || asked[0] != "d/a" || asked[1] != "d/b" { + t.Fatalf("asked %v: ApplyToAll must stop further questions", asked) + } + for name, want := range map[string]string{"a": "old", "b": "new-b", "c": "new-c", "n": "n"} { + if got := read(t, filepath.Join(dst, "d", name)); got != want { + t.Errorf("%s = %q, want %q", name, got, want) + } + } + if rep.Done != 3 || rep.Skipped != 1 { + t.Fatalf("%+v", rep) + } + + // Abort stops the transfer. + _, rep = run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{ + Resolve: func(context.Context, Conflict) (Resolution, error) { return Resolution{Action: ResolveAbort}, nil }, + }) + if !errors.Is(rep.Err, ErrAborted) || rep.Done != 0 { + t.Fatalf("abort: %+v", rep) + } +} + +func TestConflictTypeMismatchNeverDeletesDir(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("x", "file over dir"), + fstree.Dir("y"), fstree.File("y/inner", "dir over file"), + }, fstree.Spec{ + fstree.File("x/precious", "keep"), + fstree.File("y", "a file"), + }) + for _, pol := range []ConflictPolicy{Overwrite, OverwriteOlder, Ask} { + _, rep := run(t, req(Copy, local, join(src, "x", "y"), local, dst, func(o *Options) { o.Conflict = pol }), Hooks{ + Resolve: func(context.Context, Conflict) (Resolution, error) { + return Resolution{Action: ResolveOverwrite}, nil // not allowed for a mismatch + }, + }) + if rep.Done != 0 || rep.Err != nil { + t.Fatalf("policy %d: %+v", pol, rep) + } + if read(t, filepath.Join(dst, "x", "precious")) != "keep" || read(t, filepath.Join(dst, "y")) != "a file" { + t.Fatalf("policy %d: a type mismatch was overwritten", pol) + } + } + // KeepBoth writes beside it. + _, rep := run(t, req(Copy, local, join(src, "x", "y"), local, dst, func(o *Options) { o.Conflict = KeepBoth }), Hooks{}) + if rep.Done != 2 || read(t, filepath.Join(dst, "x (1)")) != "file over dir" || read(t, filepath.Join(dst, "y (1)", "inner")) != "dir over file" { + t.Fatalf("keep both: %+v", rep) + } +} + +func TestKeepBothNaming(t *testing.T) { + cases := []struct { + name string + n int + dir bool + want string + }{ + {"report.pdf", 1, false, "report (1).pdf"}, + {"report.pdf", 3, false, "report (3).pdf"}, + {"archive.tar.gz", 1, false, "archive (1).tar.gz"}, + {".bashrc", 1, false, ".bashrc (1)"}, + {"Makefile", 2, false, "Makefile (2)"}, + {"photos.2024", 1, true, "photos.2024 (1)"}, + {"данные.txt", 1, false, "данные (1).txt"}, + } + for _, c := range cases { + if got := keepBothName(c.name, c.n, c.dir); got != c.want { + t.Errorf("keepBothName(%q, %d) = %q, want %q", c.name, c.n, got, c.want) + } + } + src, dst := layout(t, fstree.Spec{fstree.File("a.txt", "3rd")}, + fstree.Spec{fstree.File("a.txt", "1st"), fstree.File("a (1).txt", "2nd")}) + _, rep := run(t, req(Copy, local, join(src, "a.txt"), local, dst, func(o *Options) { o.Conflict = KeepBoth }), Hooks{}) + if rep.Done != 1 || read(t, filepath.Join(dst, "a (2).txt")) != "3rd" || read(t, filepath.Join(dst, "a.txt")) != "1st" { + t.Fatalf("%+v", rep) + } +} + +func TestTargetAppearedAfterPlanIsConflict(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("f", "mine"), fstree.Dir("d"), fstree.File("d/g", "mine")}, nil) + plan, err := Prepare(bg, req(Copy, local, join(src, "f", "d"), local, dst), nil) + if err != nil { + t.Fatal(err) + } + if len(plan.Conflicts) != 0 { + t.Fatal("no conflicts expected at plan time") + } + // Someone creates the targets between plan and execute. + fstree.Build(t, dst, fstree.Spec{fstree.File("f", "theirs"), fstree.File("d/g", "theirs")}) + var asked []string + rep := Execute(bg, plan, Hooks{Resolve: func(_ context.Context, c Conflict) (Resolution, error) { + asked = append(asked, c.Item.Rel) + if c.Item.Existing == nil { + t.Error("runtime conflict without Existing") + } + return Resolution{Action: ResolveSkip}, nil + }}) + if len(asked) != 2 { + t.Fatalf("asked %v", asked) + } + if read(t, filepath.Join(dst, "f")) != "theirs" || read(t, filepath.Join(dst, "d", "g")) != "theirs" { + t.Fatal("a target that appeared after the plan was overwritten without asking") + } + if rep.Skipped != 2 || rep.Done != 0 { + t.Fatalf("%+v", rep) + } + noLeftovers(t, dst) +} + +func TestErrorRetryThenSuccess(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", "").WithSize(100 << 10), fstree.File("b", "b")}, nil) + to := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpWrite, 1, syscall.EIO)} + var asked []ItemError + _, rep := run(t, req(Copy, local, join(src, "a", "b"), to, dst), Hooks{ + OnError: func(_ context.Context, e ItemError) (ErrorAction, error) { + asked = append(asked, e) + return ErrorRetry, nil + }, + }) + if len(asked) != 1 || asked[0].Item.Rel != "a" || !errors.Is(asked[0].Err, syscall.EIO) { + t.Fatalf("asked %+v", asked) + } + if rep.Done != 2 || rep.Failed != 0 || len(rep.Errors) != 0 || rep.Bytes != 100<<10+1 { + t.Fatalf("%+v", rep) + } + if fi, _ := os.Stat(filepath.Join(dst, "a")); fi.Size() != 100<<10 { + t.Fatal("retried file incomplete") + } + noLeftovers(t, dst) +} + +func TestErrorSkipAllContinues(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", "1"), fstree.File("b", "2"), fstree.File("c", "3"), fstree.File("d", "4")}, nil) + fail := map[string]bool{"a": true, "b": true, "c": true} + to := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpCreate { + for n := range fail { + if hasSuffixName(p, n) { + return syscall.EACCES + } + } + } + return nil + }} + asks := 0 + _, rep := run(t, req(Copy, local, join(src, "a", "b", "c", "d"), to, dst), Hooks{ + OnError: func(context.Context, ItemError) (ErrorAction, error) { + asks++ + return ErrorSkipRest, nil + }, + }) + if asks != 1 { + t.Fatalf("asked %d times after SkipAll", asks) + } + if rep.Failed != 3 || rep.Done != 1 || len(rep.Errors) != 3 { + t.Fatalf("%+v", rep) + } + if read(t, filepath.Join(dst, "d")) != "4" { + t.Fatal("transfer did not continue") + } + // Policy-level SkipAll never asks; Abort stops at the first error. + _, dst2 := layout(t, nil, nil) + _, rep = run(t, req(Copy, local, join(src, "a", "b", "c", "d"), to, dst2, func(o *Options) { o.OnError = ErrorAbort }), Hooks{}) + if !errors.Is(rep.Err, ErrAborted) || rep.Failed != 1 || rep.Done != 0 { + t.Fatalf("abort: %+v", rep) + } +} + +// hasSuffixName: temp files are ".vcom-part-xxxxxxxx-". +func hasSuffixName(p, name string) bool { + b := filepath.Base(p) + return len(b) > len(name) && b[len(b)-len(name)-1:] == "-"+name +} + +func TestReportCounts(t *testing.T) { + old := time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC) + src, dst := layout(t, fstree.Spec{ + fstree.File("d/new", "12345"), + fstree.File("d/older", "xx").WithMTime(old), + fstree.File("d/newer", "yyy"), + fstree.File("d/broken", "zz"), + fstree.FIFO("d/fifo"), + fstree.Symlink("d/ln", "new"), + }, fstree.Spec{ + fstree.File("d/older", "dst-newer"), + fstree.File("d/newer", "dst-old").WithMTime(old), + }) + to := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpCreate && hasSuffixName(p, "broken") { + return syscall.EIO + } + return nil + }} + plan, rep := run(t, req(Copy, local, join(src, "d"), to, dst, skipAll, func(o *Options) { o.Conflict = OverwriteOlder }), Hooks{}) + // new, newer, ln copied; older skipped (target is newer); fifo skipped; broken failed. + if rep.Done != 3 || rep.Skipped != 2 || rep.Failed != 1 || rep.Bytes != 5+3 { + t.Fatalf("report %+v", rep) + } + if plan.TotalFiles != 5 || plan.TotalBytes != 5+2+3+2 { + t.Fatalf("plan %d/%d", plan.TotalFiles, plan.TotalBytes) + } + if read(t, filepath.Join(dst, "d", "older")) != "dst-newer" || read(t, filepath.Join(dst, "d", "newer")) != "yyy" { + t.Fatal("OverwriteOlder decided wrong") + } + wantAffected := map[string]bool{dst: true, filepath.Join(dst, "d"): true} + for _, l := range rep.Affected { + if !wantAffected[l.Path] || l.FS != vfs.FS(to) { + t.Fatalf("affected %v", rep.Affected) + } + delete(wantAffected, l.Path) + } + if len(wantAffected) != 0 { + t.Fatalf("missing affected %v", wantAffected) + } +} + +// A write fails and its temp cannot be removed (dead connection): the +// executor remembers the temp and removes it on the retry (3.7 finding). +func TestRetryRemovesTempOfFailedAttempt(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", "").WithSize(200 << 10)}, nil) + var dead atomic.Bool + dead.Store(true) + wrote := 0 + to := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + switch { + case op == vfstest.OpWrite && dead.Load(): + if wrote++; wrote == 2 { + return vfs.ErrConnLost + } + case op == vfstest.OpRemove && dead.Load(): + return vfs.ErrConnLost + } + return nil + }} + _, rep := run(t, req(Copy, local, join(src, "a"), to, dst), Hooks{ + OnError: func(context.Context, ItemError) (ErrorAction, error) { + dead.Store(false) // "reconnected" + return ErrorRetry, nil + }, + }) + if rep.Done != 1 || len(rep.Warnings) != 0 { + t.Fatalf("%+v", rep) + } + noLeftovers(t, dst) + + // Without a working connection until the end, the leftover is reported. + dead.Store(true) + wrote = 0 + _, dst2 := layout(t, nil, nil) + _, rep = run(t, req(Copy, local, join(src, "a"), to, dst2, skipAll), Hooks{}) + if rep.Failed != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], partPrefix) { + t.Fatalf("%+v", rep) + } +} diff --git a/internal/transfer/errors.go b/internal/transfer/errors.go new file mode 100644 index 0000000..5c3ccb7 --- /dev/null +++ b/internal/transfer/errors.go @@ -0,0 +1,13 @@ +package transfer + +import "errors" + +// Prepare refuses a request with one of these (wrapped with the path). +var ( + ErrSameFile = errors.New("source and target are the same file") + ErrIntoItself = errors.New("cannot copy a directory into itself") + ErrTargetNotDir = errors.New("target is not a directory") + ErrDuplicateName = errors.New("two sources have the same name") + ErrReadOnly = errors.New("read-only file system") + ErrAborted = errors.New("transfer aborted") +) diff --git a/internal/transfer/execute.go b/internal/transfer/execute.go new file mode 100644 index 0000000..9a63c6d --- /dev/null +++ b/internal/transfer/execute.go @@ -0,0 +1,581 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "sort" + "time" + + "vcom/internal/vfs" +) + +// Execute runs a plan (design §4.3). It never returns early without a +// Report: Report.Cancelled is set when ctx was cancelled, Report.Err on an +// abort. Completed items stay in place; the item in flight leaves nothing +// under its target name. +func Execute(ctx context.Context, plan *Plan, h Hooks) Report { + e := newExecutor(ctx, plan, h) + e.run() + return e.rep +} + +type executor struct { + ctx context.Context + plan *Plan + h Hooks + to vfs.FS + toDir string + opts Options + move bool + + rep Report + prog *emitter + applyAll map[ConflictKind]ResolveAction + skipErrors bool + doneBytes int64 // processed bytes of finished items + renamed map[string]string // rel of a dir written under another name → its new rel + skipped map[string]bool // rel of dirs whose subtree is not written + incomplete map[string]bool // rel of source dirs that keep content (move) + dirFix []dirFix + affected map[string]bool + leftovers []string // temp files whose removal failed (dead connection) + srcDirs []Item // move: source directories, removed post-order + srcDirsAffected map[string]bool + crossVol bool +} + +type dirFix struct { + path string + mode fs.FileMode // 0: leave + mtime time.Time // zero: leave +} + +func newExecutor(ctx context.Context, plan *Plan, h Hooks) *executor { + e := &executor{ + ctx: ctx, + plan: plan, + h: h, + to: plan.Req.To, + toDir: plan.Req.ToDir, + opts: plan.Req.Opts, + move: plan.Req.Op == Move, + prog: newEmitter(h.Progress, h.ProgressInterval), + applyAll: map[ConflictKind]ResolveAction{}, + renamed: map[string]string{}, + skipped: map[string]bool{}, + incomplete: map[string]bool{}, + affected: map[string]bool{}, + } + if fb, ok := plan.Req.From.(FSBacked); ok { + e.crossVol = fb.FS().Volume() != e.to.Volume() + } else { + e.crossVol = true + } + e.prog.p = Progress{Phase: Copying, FilesTotal: plan.TotalFiles, BytesTotal: plan.TotalBytes} + return e +} + +func (e *executor) run() { + e.rep.Warnings = append(e.rep.Warnings, e.plan.Warnings...) + e.affected[e.toDir] = true + e.prog.emit(true) + + items := e.plan.Items + if e.move { + items = e.renameWhole(items) + } + var err error + if op, ok := e.plan.Req.From.(Opener); ok { + for _, it := range items { + if err = e.process(it, func() (io.ReadCloser, error) { return op.Open(e.ctx, it) }); err != nil { + break + } + } + } else { + err = e.plan.Req.From.Stream(e.ctx, items, func(it Item, r io.Reader) error { + used := false + return e.process(it, func() (io.ReadCloser, error) { + if used { + return nil, errors.New("this source cannot be read twice") + } + used = true + return io.NopCloser(r), nil + }) + }) + } + if err != nil && !errors.Is(err, errStop) && e.rep.Err == nil && !isCancel(e.ctx, err) { + e.rep.Err = err + } + e.finish() +} + +// finish applies directory modes/mtimes (post-order, so read-only source +// directories can be filled: N-P1-17), removes moved source directories and +// fills the report. +func (e *executor) finish() { + bg := context.WithoutCancel(e.ctx) + e.cleanLeftovers() + for _, p := range e.leftovers { + e.rep.Warnings = append(e.rep.Warnings, p+": temp file of a failed write could not be removed") + } + for i := len(e.dirFix) - 1; i >= 0; i-- { + d := e.dirFix[i] + caps := e.to.Caps() + if caps.Chmod && d.mode != 0 { + if err := e.to.Chmod(bg, d.path, d.mode); err != nil { + e.rep.Warnings = append(e.rep.Warnings, fmt.Sprintf("%s: chmod: %v", d.path, err)) + } + } + if caps.Chtimes && !d.mtime.IsZero() { + if err := e.to.Chtimes(bg, d.path, d.mtime, d.mtime); err != nil { + e.rep.Warnings = append(e.rep.Warnings, fmt.Sprintf("%s: chtimes: %v", d.path, err)) + } + } + } + if e.move && e.ctx.Err() == nil && e.rep.Err == nil { + e.removeSourceDirs() + } + if e.ctx.Err() != nil { + e.rep.Cancelled = true + } + for _, d := range sortedKeys(e.affected) { + e.rep.Affected = append(e.rep.Affected, vfs.Location{FS: e.to, Path: d}) + } + if e.move { + e.addSourceAffected() + } + e.prog.p.Phase = Finishing + e.prog.p.Current = "" + e.prog.emit(true) +} + +// mapRel applies KeepBoth renames of ancestor directories. +func (e *executor) mapRel(rel string) string { + for i := len(rel) - 1; i > 0; i-- { + if rel[i] != '/' { + continue + } + if nr, ok := e.renamed[rel[:i]]; ok { + return nr + rel[i:] + } + } + return rel +} + +// underSkipped reports whether an ancestor directory was skipped or failed. +func (e *executor) underSkipped(rel string) bool { + for i := len(rel) - 1; i > 0; i-- { + if rel[i] == '/' && e.skipped[rel[:i]] { + return true + } + } + return false +} + +// markIncomplete records that rel stays in the source, so its source +// ancestors must not be removed by a move. +func (e *executor) markIncomplete(rel string) { + for { + parent, _ := splitRel(rel) + if parent == "" { + return + } + e.incomplete[parent] = true + rel = parent + } +} + +func (e *executor) skipItem(it Item) { + if it.Kind != Dir { + e.rep.Skipped++ + e.finishFile(it, false) + } else { + e.skipped[it.Rel] = true + } + e.markIncomplete(it.Rel) +} + +// finishFile advances the per-file counters. +func (e *executor) finishFile(it Item, done bool) { + if it.Kind == File || it.Kind == Symlink { + e.prog.p.FilesDone++ + e.doneBytes += it.Size + } + if done { + e.rep.Done++ + e.rep.Bytes += it.Size + } + e.prog.p.BytesDone = e.doneBytes + e.prog.p.CurrentDone, e.prog.p.CurrentSize = 0, 0 + e.prog.emit(false) +} + +func (e *executor) process(it Item, open func() (io.ReadCloser, error)) error { + if err := e.ctx.Err(); err != nil { + return errStop + } + if e.underSkipped(it.Rel) { + e.skipItem(it) + return nil + } + e.prog.p.Current = it.Rel + var err error + switch it.Kind { + case Special: + e.rep.Skipped++ + e.markIncomplete(it.Rel) // already in plan.Warnings + case Dir: + err = e.doDir(it) + default: + err = e.doFile(it, open) + } + return err +} + +func (e *executor) parentAffected(rel string) { + parent, _ := splitRel(rel) + if parent == "" { + e.affected[e.toDir] = true + return + } + e.affected[dstPath(e.to, e.toDir, parent)] = true +} + +// perm is the mode to give a written item. +func (e *executor) perm(it Item) fs.FileMode { + if !e.opts.PreserveMode { + if it.Kind == Dir { + return 0o755 + } + return 0o644 + } + m := it.Mode & (fs.ModePerm | fs.ModeSticky) + if !e.crossVol { + m |= it.Mode & (fs.ModeSetuid | fs.ModeSetgid) + } + return m +} + +func (e *executor) doDir(it Item) error { + rel := e.mapRel(it.Rel) + dst := dstPath(e.to, e.toDir, rel) + if e.move { + e.srcDirs = append(e.srcDirs, it) + } + if it.ScanErr != nil { + for { + switch err := e.handleError(it, "scan", it.ScanErr); err { + case errRetry: + continue // a directory listing from Prepare cannot be redone here + case nil: + e.skipped[it.Rel] = true + return nil + default: + return err + } + } + } + existing := it.Existing + for attempt := 0; ; attempt++ { + if existing != nil { + if existing.IsDir() { + e.fixDir(it, dst, false) + return nil + } + a, err := e.resolve(it, *existing, TypeMismatch) + if err != nil { + e.rep.Err = err + return errStop + } + switch a { + case ResolveAbort: + e.rep.Err = ErrAborted + return errStop + case ResolveKeepBoth: + nr, err := e.freeRel(rel, true) + if err != nil { + return e.dirFailed(it, "mkdir", err) + } + e.renamed[it.Rel] = nr + rel, dst, existing = nr, dstPath(e.to, e.toDir, nr), nil + continue + default: + e.skipItem(it) + return nil + } + } + err := e.to.Mkdir(e.ctx, dst, 0o700) + if err == nil { + e.parentAffected(rel) + e.affected[dst] = true + e.fixDir(it, dst, true) + return nil + } + if errors.Is(err, vfs.ErrExist) && attempt < 3 { + fi, lerr := e.to.Lstat(e.ctx, dst) + if lerr == nil { + existing = &fi // appeared after the plan: merge or conflict + continue + } + } + if r := e.handleError(it, "mkdir", err); r != errRetry { + if r == nil { + e.skipped[it.Rel] = true + } + return r + } + } +} + +func (e *executor) dirFailed(it Item, op string, err error) error { + r := e.handleError(it, op, err) + if r == nil || r == errRetry { + e.skipped[it.Rel] = true + return nil + } + return r +} + +// fixDir schedules mode/mtime for a directory: created ones get the real +// mode after they are filled; existing ones only when preserving. +func (e *executor) fixDir(it Item, dst string, created bool) { + f := dirFix{path: dst} + if created || e.opts.PreserveMode { + f.mode = e.perm(it) + } + if e.opts.PreserveTimes { + f.mtime = it.ModTime + } + if f.mode != 0 || !f.mtime.IsZero() { + e.dirFix = append(e.dirFix, f) + } +} + +// doFile copies a file or symlink item. +func (e *executor) doFile(it Item, open func() (io.ReadCloser, error)) error { + rel := e.mapRel(it.Rel) + replace := false + if it.Existing != nil { + switch next, err := e.decide(it, &rel, *it.Existing); { + case err != nil: + return err + case next == ResolveSkip: + e.skipItem(it) + return nil + case next == ResolveOverwrite: + replace = true + } + } + if e.move && e.plan.SameConn { + if e.renameItem(it, rel, replace) { + return nil + } + } + for { + dst := dstPath(e.to, e.toDir, rel) + e.prog.p.CurrentSize = it.Size + tmp, op, err := e.writeItem(it, dst, replace, open) + if err == nil { + err, op = e.commitItem(it, &rel, tmp, &replace), "rename" + if errors.Is(err, errSkipItem) { + e.skipItem(it) + return nil + } + if errors.Is(err, errStop) { + return err + } + } + if err == nil { + e.parentAffected(rel) + if e.move { + if rerr := e.removeSource(it); rerr != nil { + return rerr + } + } + e.finishFile(it, true) + return nil + } + var lo *leftoverError + if errors.As(err, &lo) { + e.leftovers = append(e.leftovers, lo.path) + } + if isCancel(e.ctx, err) { + return errStop + } + switch r := e.handleError(it, op, err); r { + case errRetry: + e.cleanLeftovers() // e.g. the pool reconnected inside OnError + continue + case nil: + e.finishFile(it, false) + return nil + default: + return r + } + } +} + +// decide resolves a planned or runtime conflict for a file item; for +// KeepBoth it rewrites *rel to a free name. +func (e *executor) decide(it Item, rel *string, existing vfs.FileInfo) (ResolveAction, error) { + a, err := e.resolve(it, existing, conflictKind(it, existing)) + if err != nil { + e.rep.Err = err + return 0, errStop + } + switch a { + case ResolveAbort: + e.rep.Err = ErrAborted + return 0, errStop + case ResolveKeepBoth: + nr, err := e.freeRel(*rel, false) + if err != nil { + return 0, err + } + *rel = nr + return ResolveKeepBoth, nil + } + return a, nil +} + +var errSkipItem = errors.New("skip item") + +// commitItem renames the temp into place; a target that appeared after the +// plan is a conflict resolved by policy (Ask asks). +func (e *executor) commitItem(it Item, rel *string, tmp string, replace *bool) error { + for range 5 { + dst := dstPath(e.to, e.toDir, *rel) + err := commit(e.ctx, e.to, tmp, dst, *replace) + if !errors.Is(err, vfs.ErrExist) || *replace { + if err != nil { + e.dropTemp(tmp) + } + return err + } + fi, lerr := e.to.Lstat(e.ctx, dst) + if lerr != nil { + e.dropTemp(tmp) + return lerr + } + a, derr := e.decide(it, rel, fi) + if derr != nil { + e.dropTemp(tmp) + return derr + } + switch a { + case ResolveSkip: + e.dropTemp(tmp) + return errSkipItem + case ResolveOverwrite: + *replace = true + } + } + e.dropTemp(tmp) + return fmt.Errorf("%s: target keeps changing", *rel) +} + +// writeItem produces the temp file (or temp symlink) next to dst. +func (e *executor) writeItem(it Item, dst string, replace bool, open func() (io.ReadCloser, error)) (string, string, error) { + if it.Kind == Symlink { + if !e.to.Caps().Symlinks { + return "", "symlink", fmt.Errorf("%w: symlinks on %s", vfs.ErrUnsupported, e.to.Label()) + } + var err error + for range 8 { + tmp := tempName(e.to, dst, partPrefix) + if err = e.to.Symlink(e.ctx, it.LinkTarget, tmp); err == nil { + return tmp, "symlink", nil + } + if !errors.Is(err, vfs.ErrExist) { + break + } + } + return "", "symlink", err + } + + src, err := open() + if err != nil { + return "", "read", err + } + defer src.Close() + o := WriteOptions{ + Perm: e.perm(it), + Fsync: e.opts.Fsync == FsyncAlways || (e.opts.Fsync == FsyncReplace && replace), + } + if e.opts.PreserveTimes { + o.ModTime = it.ModTime + } + pr := &progressReader{ctx: e.ctx, r: src, size: it.Size, onRead: func(n int64) { + e.prog.p.CurrentDone = n + e.prog.p.BytesDone = e.doneBytes + min(n, it.Size) + e.prog.emit(false) + }} + var readErr error + tmp, err := writeTemp(e.ctx, e.to, dst, o, func(w io.Writer) error { + _, err := io.Copy(w, readTracker{pr, &readErr}) + return err + }) + if err != nil { + op := "write" + if readErr != nil && errors.Is(err, readErr) { + op = "read" + } + return "", op, err + } + if e.move && pr.n != it.Size { + e.dropTemp(tmp) + return "", "read", fmt.Errorf("source changed during the move: read %d of %d bytes", pr.n, it.Size) + } + return tmp, "write", nil +} + +// readTracker remembers a read error so it can be told from a write error. +type readTracker struct { + r io.Reader + err *error +} + +func (t readTracker) Read(p []byte) (int, error) { + n, err := t.r.Read(p) + if err != nil && err != io.EOF { + *t.err = err + } + return n, err +} + +func (t readTracker) Size() int64 { + if s, ok := t.r.(interface{ Size() int64 }); ok { + return s.Size() + } + return 0 +} + +func sortedKeys(m map[string]bool) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// dropTemp removes a temp file, remembering it if that fails. +func (e *executor) dropTemp(p string) { + if removeQuiet(e.ctx, e.to, p) != nil { + e.leftovers = append(e.leftovers, p) + } +} + +// cleanLeftovers retries the removal of temp files from failed attempts. +func (e *executor) cleanLeftovers() { + keep := e.leftovers[:0] + for _, p := range e.leftovers { + if removeQuiet(e.ctx, e.to, p) != nil { + keep = append(keep, p) + } + } + e.leftovers = keep +} diff --git a/internal/transfer/execute_test.go b/internal/transfer/execute_test.go new file mode 100644 index 0000000..e9182af --- /dev/null +++ b/internal/transfer/execute_test.go @@ -0,0 +1,386 @@ +package transfer + +import ( + "context" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +// run prepares and executes; it fails the test on a Prepare error. +func run(t *testing.T, r Request, h Hooks) (*Plan, Report) { + t.Helper() + plan, err := Prepare(bg, r, nil) + if err != nil { + t.Fatalf("prepare: %v", err) + } + return plan, Execute(bg, plan, h) +} + +func overwrite(o *Options) { o.Conflict = Overwrite } +func skipAll(o *Options) { o.OnError = ErrorSkipAll } +func follow(o *Options) { o.Symlinks = FollowLinks } + +func TestOverwriteFailureKeepsDest(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("f.txt", "").WithSize(300 << 10)}, + fstree.Spec{fstree.File("f.txt", "OLD VALUABLE")}) + to := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpWrite, 2, syscall.ENOSPC)} + _, rep := run(t, req(Copy, local, join(src, "f.txt"), to, dst, overwrite, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Done != 0 || len(rep.Errors) != 1 || !errors.Is(rep.Errors[0].Err, syscall.ENOSPC) { + t.Fatalf("report %+v", rep) + } + if rep.Errors[0].Op != "write" { + t.Fatalf("op %q", rep.Errors[0].Op) + } + if got := read(t, filepath.Join(dst, "f.txt")); got != "OLD VALUABLE" { + t.Fatalf("old target damaged: %q (N-P0-4)", got) + } + noLeftovers(t, dst) + + // Unreadable source (the testbed case): the old target survives too. + if os.Geteuid() != 0 { + if err := os.Chmod(filepath.Join(src, "f.txt"), 0); err != nil { + t.Fatal(err) + } + _, rep = run(t, req(Copy, local, join(src, "f.txt"), local, dst, overwrite, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Errors[0].Op != "read" || !errors.Is(rep.Errors[0].Err, vfs.ErrPermission) { + t.Fatalf("unreadable source: %+v", rep) + } + if got := read(t, filepath.Join(dst, "f.txt")); got != "OLD VALUABLE" { + t.Fatalf("old target damaged by unreadable source: %q", got) + } + noLeftovers(t, dst) + } +} + +func TestCloseErrorIsItemError(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", "data")}, nil) + closeErr := errors.New("EIO on close") + to := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpClose, 1, closeErr)} + _, rep := run(t, req(Copy, local, join(src, "a"), to, dst, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Done != 0 || !errors.Is(rep.Errors[0].Err, closeErr) { + t.Fatalf("close error must fail the item (N-P2-6): %+v", rep) + } + if _, err := os.Lstat(filepath.Join(dst, "a")); !os.IsNotExist(err) { + t.Fatal("file committed despite the close error") + } + noLeftovers(t, dst) +} + +func TestDirMergeKeepsExtra(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("proj/a.txt", "new"), fstree.File("proj/sub/b", "b")}, + fstree.Spec{fstree.File("proj/keep.txt", "user data"), fstree.File("proj/a.txt", "old"), fstree.File("proj/sub/c", "c")}) + _, rep := run(t, req(Copy, local, join(src, "proj"), local, dst, overwrite), Hooks{}) + if rep.Err != nil || rep.Done != 2 { + t.Fatalf("report %+v", rep) + } + fstree.Equal(t, fstree.FromSpec(fstree.Spec{ + fstree.File("proj/a.txt", "new"), + fstree.File("proj/keep.txt", "user data"), + fstree.File("proj/sub/b", "b"), + fstree.File("proj/sub/c", "c"), + }), fstree.Snapshot(t, dst), fstree.Opts{}) +} + +func TestCopyReadOnlyDir(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("ro/a.txt", "x"), + fstree.File("ro/inner/b", "y"), + fstree.Dir("ro/inner").WithMode(0o555), + fstree.Dir("ro").WithMode(0o555), + }, nil) + t.Cleanup(func() { + for _, d := range []string{filepath.Join(dst, "ro"), filepath.Join(dst, "ro", "inner")} { + _ = os.Chmod(d, 0o755) + } + }) + _, rep := run(t, req(Copy, local, join(src, "ro"), local, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 || rep.Done != 2 { + t.Fatalf("copying a read-only dir failed (N-P1-17): %+v", rep) + } + for _, d := range []string{"ro", "ro/inner"} { + if fi, _ := os.Stat(filepath.Join(dst, d)); fi.Mode().Perm() != 0o555 { + t.Errorf("%s mode %v, want 0555", d, fi.Mode().Perm()) + } + } + if read(t, filepath.Join(dst, "ro", "inner", "b")) != "y" { + t.Fatal("content missing") + } +} + +func TestLocalMtime(t *testing.T) { + old := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + src, dst := layout(t, fstree.Spec{ + fstree.File("d/f.txt", "x").WithMTime(old), + fstree.Dir("d").WithMTime(old.Add(time.Hour)), + }, nil) + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{}) + if rep.Err != nil || rep.Done != 1 { + t.Fatalf("%+v", rep) + } + if fi, _ := os.Stat(filepath.Join(dst, "d", "f.txt")); !fi.ModTime().Equal(old) { + t.Fatalf("file mtime %v (N-P1-9)", fi.ModTime()) + } + if fi, _ := os.Stat(filepath.Join(dst, "d")); !fi.ModTime().Equal(old.Add(time.Hour)) { + t.Fatalf("dir mtime %v", fi.ModTime()) + } +} + +func TestPermsPreserved(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("run.sh", "#!/bin/sh").WithMode(0o755), + fstree.File("secret", "s").WithMode(0o600), + fstree.Dir("shared"), + }, nil) + if err := os.Chmod(filepath.Join(src, "shared"), 0o777|fs.ModeSticky); err != nil { + t.Fatal(err) + } + _, rep := run(t, req(Copy, local, join(src, "run.sh", "secret", "shared"), local, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + for name, want := range map[string]fs.FileMode{"run.sh": 0o755, "secret": 0o600, "shared": 0o777 | fs.ModeSticky} { + fi, _ := os.Stat(filepath.Join(dst, name)) + if got := fi.Mode() & (fs.ModePerm | fs.ModeSticky); got != want { + t.Errorf("%s mode %v, want %v", name, got, want) + } + } + // PreserveMode off: plain defaults. + _, dst2 := layout(t, nil, nil) + _, rep = run(t, req(Copy, local, join(src, "run.sh"), local, dst2, func(o *Options) { o.PreserveMode = false }), Hooks{}) + if fi, _ := os.Stat(filepath.Join(dst2, "run.sh")); rep.Done != 1 || fi.Mode().Perm() != 0o644 { + t.Fatalf("PreserveMode=false: %v", fi.Mode()) + } +} + +func TestBrokenSymlinkCopiedAsLink(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.Symlink("dir/broken", "nowhere"), fstree.File("dir/f", "x")}, nil) + _, rep := run(t, req(Copy, local, join(src, "dir"), local, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 || rep.Done != 2 { + t.Fatalf("%+v", rep) + } + if tgt, err := os.Readlink(filepath.Join(dst, "dir", "broken")); err != nil || tgt != "nowhere" { + t.Fatalf("broken link: %q %v (N-P1-8)", tgt, err) + } + noLeftovers(t, dst) +} + +func TestSymlinkToDirCopiedAsLink(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("data/big", "").WithSize(1 << 20), + fstree.Symlink("proj/link", "../data"), + fstree.File("proj/own", "o"), + }, nil) + plan, rep := run(t, req(Copy, local, join(src, "proj"), local, dst), Hooks{}) + if rep.Err != nil || rep.Done != 2 || plan.TotalBytes != 1 { + t.Fatalf("plan bytes %d, report %+v", plan.TotalBytes, rep) + } + if fi, err := os.Lstat(filepath.Join(dst, "proj", "link")); err != nil || fi.Mode()&fs.ModeSymlink == 0 { + t.Fatal("link to a directory was not copied as a link") + } + // A link given as a root is copied as a link too. + _, dst2 := layout(t, nil, nil) + if _, rep := run(t, req(Copy, local, join(src, "proj/link"), local, dst2), Hooks{}); rep.Done != 1 { + t.Fatalf("%+v", rep) + } + if tgt, _ := os.Readlink(filepath.Join(dst2, "link")); tgt != "../data" { + t.Fatalf("root link target %q", tgt) + } +} + +func TestFollowLinksCycle(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/f", "x"), + fstree.Symlink("d/loop", "."), + fstree.Symlink("d/up", ".."), + fstree.File("ext/g", "g"), + fstree.Symlink("d/ext", "../ext"), + }, nil) + plan, rep := run(t, req(Copy, local, join(src, "d"), local, dst, follow), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + if len(plan.Warnings) == 0 || !strings.Contains(plan.Warnings[0], "d/loop: symlink loop") { + t.Fatalf("warnings %v", plan.Warnings) + } + for _, w := range plan.Warnings { + if !strings.Contains(w, "symlink loop") { + t.Fatalf("unexpected warning %q", w) + } + } + // ext followed: a real directory with the file. + if fi, err := os.Lstat(filepath.Join(dst, "d", "ext")); err != nil || !fi.IsDir() || read(t, filepath.Join(dst, "d", "ext", "g")) != "g" { + t.Fatal("followed link to a directory not copied as a directory") + } + // up (→ src) is no ancestor of d, so it is followed once; its own d/loop + // and d/up inside are cut as loops — the walk terminates. + if fi, err := os.Lstat(filepath.Join(dst, "d", "loop")); err != nil || fi.Mode()&fs.ModeSymlink == 0 { + t.Fatal("loop must stay a link") + } +} + +func TestFifoSkippedWithWarning(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.FIFO("d/pipe"), fstree.File("d/f", "x")}, nil) + done := make(chan Report, 1) + go func() { + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{}) + done <- rep + }() + select { + case rep := <-done: + if rep.Done != 1 || rep.Skipped != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], "d/pipe") { + t.Fatalf("%+v", rep) + } + case <-time.After(5 * time.Second): + t.Fatal("blocked reading a FIFO (U-P1-10)") + } + if _, err := os.Lstat(filepath.Join(dst, "d", "pipe")); !os.IsNotExist(err) { + t.Fatal("FIFO copied") + } +} + +func TestNoTempLeftovers(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/a", "").WithSize(100 << 10), + fstree.File("d/b", "b"), + fstree.Symlink("d/l", "a"), + }, fstree.Spec{fstree.File("d/a", "old"), fstree.File("d/l", "old")}) + hooks := map[string]func(vfstest.Op, string) error{ + "write": vfstest.FailNth(vfstest.OpWrite, 2, syscall.EIO), + "close": vfstest.FailNth(vfstest.OpClose, 1, syscall.EIO), + "chmod": vfstest.FailNth(vfstest.OpChmod, 1, syscall.EPERM), + "chtimes": vfstest.FailNth(vfstest.OpChtimes, 1, syscall.EPERM), + "rename": vfstest.FailNth(vfstest.OpRename, 2, syscall.EIO), + "symlink": func(op vfstest.Op, _ string) error { + if op == vfstest.OpSymlink { + return syscall.EIO + } + return nil + }, + } + for name, hook := range hooks { + to := &vfstest.FaultFS{FS: local, Hook: hook} + _, rep := run(t, req(Copy, local, join(src, "d"), to, dst, overwrite, skipAll), Hooks{}) + if rep.Failed == 0 { + t.Errorf("%s: no failure injected? %+v", name, rep) + } + noLeftovers(t, dst) + if got := read(t, filepath.Join(dst, "d", "a")); got != "old" && len(got) != 100<<10 { + t.Errorf("%s: target a is partial (%d bytes)", name, len(got)) + } + } +} + +// atomicOff hides atomic replace, as on an SFTP server without posix-rename. +type atomicOff struct{ vfs.FS } + +func (a atomicOff) Caps() vfs.Caps { + c := a.FS.Caps() + c.AtomicReplace = false + return c +} + +func (a atomicOff) Rename(ctx context.Context, from, to string, mode vfs.RenameMode) error { + if mode == vfs.Replace { + return errors.New("Replace used without Caps.AtomicReplace") + } + return a.FS.Rename(ctx, from, to, mode) +} + +func TestWriteAtomicWithoutAtomicReplace(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "f") + if err := os.WriteFile(p, []byte("old"), 0o600); err != nil { + t.Fatal(err) + } + fsys := atomicOff{local} + write := func(s string) error { + return WriteAtomic(bg, fsys, p, WriteOptions{Replace: true, Perm: 0o640}, func(w io.Writer) error { + _, err := io.WriteString(w, s) + return err + }) + } + if err := write("new"); err != nil { + t.Fatal(err) + } + if read(t, p) != "new" { + t.Fatal("not replaced") + } + noLeftovers(t, dir) + // Without Replace an existing target is ErrExist and stays. + err := WriteAtomic(bg, local, p, WriteOptions{}, func(w io.Writer) error { _, err := io.WriteString(w, "x"); return err }) + if !errors.Is(err, vfs.ErrExist) || read(t, p) != "new" { + t.Fatalf("no-replace: %v", err) + } + noLeftovers(t, dir) + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o640 { + t.Fatalf("mode %v", fi.Mode()) + } + // A very long name still fits NAME_MAX in the temp name. + long := filepath.Join(dir, strings.Repeat("я", 127)) // 254 bytes + if err := WriteAtomic(bg, local, long, WriteOptions{}, func(w io.Writer) error { return nil }); err != nil { + t.Fatalf("long name: %v", err) + } +} + +func TestProgressHonestAndThrottled(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/big", "").WithSize(4 << 20), + fstree.File("d/small", "12345"), + }, nil) + var calls []Progress + plan, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{ + Progress: func(p Progress) { calls = append(calls, p) }, + ProgressInterval: time.Hour, + }) + if rep.Err != nil || rep.Bytes != plan.TotalBytes { + t.Fatalf("%+v", rep) + } + if len(calls) > 3 { + t.Fatalf("%d progress calls with a 1h interval: not throttled", len(calls)) + } + last := calls[len(calls)-1] + if last.BytesTotal != 4<<20+5 || last.BytesDone != last.BytesTotal || last.FilesDone != 2 || last.FilesTotal != 2 { + t.Fatalf("final progress %+v", last) + } + // Default interval: several calls, monotonic, never above the total. + calls = nil + _, dst2 := layout(t, nil, nil) + _, _ = run(t, req(Copy, local, join(src, "d"), local, dst2), Hooks{ + Progress: func(p Progress) { calls = append(calls, p) }, + ProgressInterval: time.Nanosecond, + }) + for i := 1; i < len(calls); i++ { + if calls[i].BytesDone < calls[i-1].BytesDone || calls[i].BytesDone > calls[i].BytesTotal { + t.Fatalf("progress not monotonic/bounded at %d: %+v -> %+v", i, calls[i-1], calls[i]) + } + } + if len(calls) < 10 { + t.Fatalf("only %d progress calls for a 4 MiB file", len(calls)) + } +} + +func TestSourceNeverModified(t *testing.T) { + spec := fstree.Spec{ + fstree.File("d/a", "aaa").WithMode(0o640).WithMTime(time.Unix(1e9, 0)), + fstree.Symlink("d/l", "a"), + fstree.Dir("d/sub").WithMode(0o700), + } + src, dst := layout(t, spec, fstree.Spec{fstree.File("d/a", "other")}) + before := fstree.Snapshot(t, src) + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst, overwrite), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + fstree.Equal(t, before, fstree.Snapshot(t, src), fstree.Opts{Mode: true, MTime: true, Links: true}) +} diff --git a/internal/transfer/helpers_test.go b/internal/transfer/helpers_test.go new file mode 100644 index 0000000..898545f --- /dev/null +++ b/internal/transfer/helpers_test.go @@ -0,0 +1,99 @@ +package transfer + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +var bg = context.Background() + +var local = localfs.New() + +// counter is a FaultFS hook that counts operations (and optionally fails). +type counter struct { + mu sync.Mutex + n map[vfstest.Op]int +} + +func (c *counter) hook(op vfstest.Op, _ string) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.n == nil { + c.n = map[vfstest.Op]int{} + } + c.n[op]++ + return nil +} + +func (c *counter) get(op vfstest.Op) int { + c.mu.Lock() + defer c.mu.Unlock() + return c.n[op] +} + +// otherVolume makes a local FS look like a different volume (as a remote +// would): no SameConn, no identity checks. +type otherVolume struct{ vfs.FS } + +func (otherVolume) Volume() vfs.VolumeID { return "other" } +func (otherVolume) Kind() vfs.Kind { return vfs.KindSFTP } + +// layout builds /src and /dst from specs and returns their paths. +func layout(t *testing.T, src, dst fstree.Spec) (string, string) { + t.Helper() + d := t.TempDir() + s, ds := filepath.Join(d, "src"), filepath.Join(d, "dst") + for _, p := range []string{s, ds} { + if err := os.MkdirAll(p, 0o755); err != nil { + t.Fatal(err) + } + } + fstree.Build(t, s, src) + fstree.Build(t, ds, dst) + return s, ds +} + +func req(op Op, from vfs.FS, paths []string, to vfs.FS, toDir string, mut ...func(*Options)) Request { + o := DefaultOptions() + for _, f := range mut { + f(&o) + } + return Request{Op: op, From: FSSource(from, paths, o.Symlinks), To: to, ToDir: toDir, Opts: o} +} + +func join(dir string, names ...string) []string { + out := make([]string, len(names)) + for i, n := range names { + out[i] = filepath.Join(dir, n) + } + return out +} + +// noLeftovers fails if any .vcom-part-* / .vcom-old-* remains under dir. +func noLeftovers(t *testing.T, dir string) { + t.Helper() + _ = filepath.Walk(dir, func(p string, fi os.FileInfo, err error) error { + if err == nil && (strings.HasPrefix(fi.Name(), partPrefix) || strings.HasPrefix(fi.Name(), oldPrefix)) { + t.Errorf("temp file left behind: %s", p) + } + return nil + }) +} + +func read(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} diff --git a/internal/transfer/move.go b/internal/transfer/move.go new file mode 100644 index 0000000..c4619de --- /dev/null +++ b/internal/transfer/move.go @@ -0,0 +1,158 @@ +package transfer + +import ( + "errors" + "fmt" + "strings" + + "vcom/internal/vfs" +) + +// renameWhole is the fast path of a move (design §4.3): with SameConn, a +// top-level item that has no target yet is renamed as a whole (NoReplace). +// Anything that cannot be renamed — EXDEV, a target that appeared, any +// other error — falls back to the per-item copy+delete path. It returns the +// items still to process. +func (e *executor) renameWhole(items []Item) []Item { + fb, ok := e.plan.Req.From.(FSBacked) + if !ok { + e.rep.Err = errors.New("transfer: move needs a file-system source") + return nil + } + if !e.plan.SameConn { + return items + } + src := fb.FS() + var rest []Item + for i := 0; i < len(items); { + root := items[i] + end := i + 1 + for end < len(items) && strings.HasPrefix(items[end].Rel, root.Rel+"/") { + end++ + } + if e.ctx.Err() != nil { + return append(rest, items[i:]...) + } + if root.Existing == nil && root.Src != "" && root.ScanErr == nil && !hasScanErr(items[i:end]) { + dst := dstPath(e.to, e.toDir, root.Rel) + if err := e.to.Rename(e.ctx, root.Src, dst, vfs.NoReplace); err == nil { + for _, it := range items[i:end] { + if it.Kind == File || it.Kind == Symlink { + e.prog.p.FilesDone++ + e.doneBytes += it.Size + e.rep.Done++ + } + } + e.prog.p.BytesDone = e.doneBytes + e.prog.emit(false) + e.parentAffected(root.Rel) + e.srcAffected(src.Paths().Dir(root.Src)) + i = end + continue + } + // EXDEV (another device), ErrExist (appeared) or anything else: + // copy and delete item by item instead. + } + rest = append(rest, items[i:end]...) + i = end + } + return rest +} + +func hasScanErr(items []Item) bool { + for _, it := range items { + if it.ScanErr != nil { + return true + } + } + return false +} + +func (e *executor) srcFS() vfs.FS { return e.plan.Req.From.(FSBacked).FS() } + +func (e *executor) srcAffected(dir string) { + if e.srcDirsAffected == nil { + e.srcDirsAffected = map[string]bool{} + } + e.srcDirsAffected[dir] = true +} + +// removeSource deletes a file or link from the source after it was copied. +// Remove never follows links (N-P0-3 for move). +func (e *executor) removeSource(it Item) error { + src := e.srcFS() + for { + err := src.Remove(e.ctx, it.Src) + if err == nil || errors.Is(err, vfs.ErrNotExist) { + e.srcAffected(src.Paths().Dir(it.Src)) + return nil + } + switch r := e.handleError(it, "remove", err); r { + case errRetry: + continue + case nil: + return nil + default: + return r + } + } +} + +// removeSourceDirs removes moved source directories bottom-up, only those +// with nothing left behind (skipped, failed or special items stay). +func (e *executor) removeSourceDirs() { + if len(e.srcDirs) == 0 { + return + } + src := e.srcFS() + e.prog.p.Phase = Removing + e.prog.emit(true) + for i := len(e.srcDirs) - 1; i >= 0; i-- { + it := e.srcDirs[i] + if e.incomplete[it.Rel] || e.skipped[it.Rel] || e.underSkipped(it.Rel) { + continue + } + err := src.Remove(e.ctx, it.Src) + if err == nil || errors.Is(err, vfs.ErrNotExist) { + e.srcAffected(src.Paths().Dir(it.Src)) + continue + } + if e.ctx.Err() != nil { + return + } + e.rep.Errors = append(e.rep.Errors, ItemError{Item: it, Op: "remove", + Err: fmt.Errorf("source directory not removed: %w", err)}) + e.rep.Failed++ + e.markIncomplete(it.Rel) + } +} + +func (e *executor) addSourceAffected() { + src := e.srcFS() + for _, d := range sortedKeys(e.srcDirsAffected) { + e.rep.Affected = append(e.rep.Affected, vfs.Location{FS: src, Path: d}) + } +} + +// renameItem moves one file or link inside a merged directory by rename +// when source and target share the namespace. It reports whether it did; +// on any failure (EXDEV, a target that appeared, ...) the caller copies. +func (e *executor) renameItem(it Item, rel string, replace bool) bool { + if it.Src == "" { + return false + } + mode := vfs.NoReplace + if replace { + if !e.to.Caps().AtomicReplace { + return false + } + mode = vfs.Replace + } + if err := e.to.Rename(e.ctx, it.Src, dstPath(e.to, e.toDir, rel), mode); err != nil { + return false + } + e.parentAffected(rel) + e.srcAffected(e.srcFS().Paths().Dir(it.Src)) + e.finishFile(it, true) + return true +} diff --git a/internal/transfer/move_test.go b/internal/transfer/move_test.go new file mode 100644 index 0000000..8569bd7 --- /dev/null +++ b/internal/transfer/move_test.go @@ -0,0 +1,227 @@ +package transfer + +import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "syscall" + "testing" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +func inode(t *testing.T, p string) uint64 { + t.Helper() + fi, err := os.Lstat(p) + if err != nil { + t.Fatal(err) + } + return fi.Sys().(*syscall.Stat_t).Ino +} + +func gone(t *testing.T, p string) { + t.Helper() + if _, err := os.Lstat(p); !os.IsNotExist(err) { + t.Errorf("%s still exists", p) + } +} + +func TestMoveSameVolumeIsRename(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("proj/big", "").WithSize(1 << 20), fstree.File("f.txt", "f")}, + fstree.Spec{fstree.File("merge/keep", "k")}) + inoDir, inoFile := inode(t, filepath.Join(src, "proj")), inode(t, filepath.Join(src, "f.txt")) + c := &counter{} + to := &vfstest.FaultFS{FS: local, Hook: c.hook} + plan, rep := run(t, req(Move, local, join(src, "proj", "f.txt"), to, dst), Hooks{}) + if !plan.SameConn || rep.Err != nil || rep.Done != 2 { + t.Fatalf("plan.SameConn=%v report %+v", plan.SameConn, rep) + } + if inode(t, filepath.Join(dst, "proj")) != inoDir || inode(t, filepath.Join(dst, "f.txt")) != inoFile { + t.Fatal("same-volume move copied instead of renaming (inode changed)") + } + if c.get(vfstest.OpCreate) != 0 || c.get(vfstest.OpWrite) != 0 { + t.Fatalf("data was written: create=%d write=%d", c.get(vfstest.OpCreate), c.get(vfstest.OpWrite)) + } + gone(t, filepath.Join(src, "proj")) + gone(t, filepath.Join(src, "f.txt")) + + // Merging into an existing directory renames file by file. + fstree.Build(t, src, fstree.Spec{fstree.File("merge/new", "n")}) + ino := inode(t, filepath.Join(src, "merge", "new")) + if _, rep := run(t, req(Move, local, join(src, "merge"), local, dst), Hooks{}); rep.Done != 1 || rep.Err != nil { + t.Fatalf("%+v", rep) + } + if inode(t, filepath.Join(dst, "merge", "new")) != ino || read(t, filepath.Join(dst, "merge", "keep")) != "k" { + t.Fatal("merge move") + } + gone(t, filepath.Join(src, "merge")) +} + +func TestMoveFallsBackOnEXDEV(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("d/a", "aaa"), fstree.Symlink("d/l", "a")}, nil) + to := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpRename && strings.HasPrefix(p, src+"/") { + return &os.LinkError{Op: "rename", Old: p, Err: syscall.EXDEV} + } + return nil + }} + _, rep := run(t, req(Move, local, join(src, "d"), to, dst), Hooks{}) + if rep.Err != nil || rep.Done != 2 || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + if read(t, filepath.Join(dst, "d", "a")) != "aaa" { + t.Fatal("not copied") + } + gone(t, filepath.Join(src, "d")) + noLeftovers(t, dst) +} + +func TestMoveSkippedItemStaysInSource(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("d/conflict", "mine"), fstree.File("d/free", "f"), fstree.File("d/sub/x", "x")}, + fstree.Spec{fstree.File("d/conflict", "theirs")}) + for _, to := range []vfs.FS{local, otherVolume{local}} { + _, rep := run(t, req(Move, local, join(src, "d"), to, dst, func(o *Options) { o.Conflict = Skip }), Hooks{}) + if rep.Err != nil || rep.Skipped != 1 || rep.Done != 2 { + t.Fatalf("%T: %+v", to, rep) + } + fstree.Equal(t, fstree.FromSpec(fstree.Spec{fstree.File("d/conflict", "mine")}), fstree.Snapshot(t, src), fstree.Opts{}) + if read(t, filepath.Join(dst, "d", "conflict")) != "theirs" || read(t, filepath.Join(dst, "d", "sub", "x")) != "x" { + t.Fatal("target wrong") + } + // Reset for the second (cross-volume) round. + fstree.Build(t, src, fstree.Spec{fstree.File("d/free", "f"), fstree.File("d/sub/x", "x")}) + _ = os.RemoveAll(filepath.Join(dst, "d", "sub")) + _ = os.Remove(filepath.Join(dst, "d", "free")) + } +} + +func TestMoveFailedItemStaysInSource(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("d/bad", "b"), fstree.File("d/good", "g")}, nil) + to := &vfstest.FaultFS{FS: otherVolume{local}, Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpCreate && hasSuffixName(p, "bad") { + return syscall.EIO + } + return nil + }} + _, rep := run(t, req(Move, local, join(src, "d"), to, dst, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Done != 1 || rep.Errors[0].Item.Rel != "d/bad" { + t.Fatalf("%+v", rep) + } + if read(t, filepath.Join(src, "d", "bad")) != "b" { + t.Fatal("failed item removed from the source") + } + gone(t, filepath.Join(src, "d", "good")) + gone(t, filepath.Join(dst, "d", "bad")) + noLeftovers(t, dst) + + // A failed removal of the source is reported, the copy stays. + src2, dst2 := layout(t, fstree.Spec{fstree.File("e/f", "f")}, nil) + from := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpRemove { + return syscall.EACCES + } + return nil + }} + plan, err := Prepare(bg, Request{Op: Move, From: FSSource(from, join(src2, "e"), CopyLinks), To: otherVolume{local}, ToDir: dst2, Opts: DefaultOptions()}, nil) + if err != nil { + t.Fatal(err) + } + rep = Execute(bg, plan, Hooks{OnError: func(context.Context, ItemError) (ErrorAction, error) { return ErrorSkip, nil }}) + if rep.Failed != 1 || rep.Errors[0].Op != "remove" || read(t, filepath.Join(dst2, "e", "f")) != "f" || read(t, filepath.Join(src2, "e", "f")) != "f" { + t.Fatalf("%+v", rep) + } +} + +func TestMoveDirWithSymlinkKeepsLink(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("target/data", "precious"), + fstree.Symlink("d/link", "../target"), + fstree.Symlink("d/broken", "nowhere"), + fstree.File("d/f", "f"), + }, nil) + _, rep := run(t, req(Move, local, join(src, "d"), otherVolume{local}, dst, follow), Hooks{}) // follow is ignored for move + if rep.Err != nil || rep.Failed != 0 || rep.Done != 3 { + t.Fatalf("%+v", rep) + } + for name, want := range map[string]string{"link": "../target", "broken": "nowhere"} { + if tgt, err := os.Readlink(filepath.Join(dst, "d", name)); err != nil || tgt != want { + t.Fatalf("%s: %q %v (N-P1-8: link lost in move)", name, tgt, err) + } + } + gone(t, filepath.Join(src, "d")) + if read(t, filepath.Join(src, "target", "data")) != "precious" { + t.Fatal("link target damaged") + } +} + +func TestMoveNeverFollowsSourceLinks(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("outside/keep1", "1"), + fstree.File("outside/sub/keep2", "2"), + fstree.Symlink("rootlink", "outside"), + fstree.Symlink("d/inner", "../outside"), + fstree.File("d/own", "o"), + }, nil) + for _, to := range []vfs.FS{otherVolume{local}, local} { + _, rep := run(t, req(Move, local, join(src, "rootlink", "d"), to, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%T: %+v", to, rep) + } + fstree.Equal(t, fstree.FromSpec(fstree.Spec{fstree.File("outside/keep1", "1"), fstree.File("outside/sub/keep2", "2")}), + fstree.Snapshot(t, src), fstree.Opts{Links: true}) + if fi, err := os.Lstat(filepath.Join(dst, "rootlink")); err != nil || fi.Mode()&fs.ModeSymlink == 0 { + t.Fatal("root link not moved as a link") + } + // Back for the second round. + _ = os.RemoveAll(filepath.Join(dst, "d")) + _ = os.Remove(filepath.Join(dst, "rootlink")) + fstree.Build(t, src, fstree.Spec{fstree.Symlink("rootlink", "outside"), fstree.Symlink("d/inner", "../outside"), fstree.File("d/own", "o")}) + } +} + +func TestMoveAffectedIncludesSource(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("d/sub/f", "f"), fstree.File("top", "t")}, nil) + to := otherVolume{local} + _, rep := run(t, req(Move, local, join(src, "d", "top"), to, dst), Hooks{}) + if rep.Err != nil { + t.Fatal(rep.Err) + } + var srcDirs, dstDirs []string + for _, l := range rep.Affected { + if l.FS == vfs.FS(local) { + srcDirs = append(srcDirs, l.Path) + } else { + dstDirs = append(dstDirs, l.Path) + } + } + sort.Strings(srcDirs) + if len(srcDirs) == 0 || srcDirs[0] != src { + t.Fatalf("source dir not affected: %v", srcDirs) + } + if len(dstDirs) == 0 || dstDirs[0] != dst { + t.Fatalf("target dir not affected: %v", dstDirs) + } + // Same-volume rename path too. + src, dst = layout(t, fstree.Spec{fstree.File("x", "x")}, nil) + _, rep = run(t, req(Move, local, join(src, "x"), local, dst), Hooks{}) + found := false + for _, l := range rep.Affected { + found = found || l.Path == src + } + if !found { + t.Fatalf("rename move: source not in Affected %v", rep.Affected) + } +} + +func TestMoveRejectsNonFSSourceAndSelf(t *testing.T) { + src, _ := layout(t, fstree.Spec{fstree.File("d/f", "")}, nil) + if _, err := Prepare(bg, req(Move, local, join(src, "d"), local, filepath.Join(src, "d")), nil); !errors.Is(err, ErrIntoItself) { + t.Fatalf("move into itself: %v", err) + } +} diff --git a/internal/transfer/prepare.go b/internal/transfer/prepare.go new file mode 100644 index 0000000..cb75e45 --- /dev/null +++ b/internal/transfer/prepare.go @@ -0,0 +1,218 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "strings" + + "vcom/internal/vfs" +) + +// partPrefix names temp files of WriteAtomic: /.vcom-part-<8hex>-. +const partPrefix = ".vcom-part-" + +// Prepare validates req and builds the plan (design §4.2): the target is +// writable and a directory; no root is the same file as its target and no +// directory is copied into itself (SameFile/Within, through symlinks); the +// source is walked once; every target directory that already exists is +// listed once (not one call per file) to find Existing and the Conflicts; +// totals are exact. progress, if non-nil, receives Scanning snapshots. +func Prepare(ctx context.Context, req Request, progress func(Progress)) (*Plan, error) { + if req.To == nil || req.From == nil { + return nil, errors.New("transfer: incomplete request") + } + if req.Op == Move { + req.Opts.Symlinks = CopyLinks // a move never follows links + } + if req.To.Caps().ReadOnly { + return nil, fmt.Errorf("%w: %s", ErrReadOnly, req.To.Label()) + } + toOps := req.To.Paths() + req.ToDir = toOps.Clean(req.ToDir) + if fi, err := req.To.Stat(ctx, req.ToDir); err != nil { + return nil, err + } else if !fi.IsDir() { + return nil, fmt.Errorf("%w: %s", ErrTargetNotDir, req.ToDir) + } + + if _, ok := req.From.(FSBacked); !ok && req.Op == Move { + return nil, errors.New("transfer: move needs a file-system source") + } + if fb, ok := req.From.(FSBacked); ok { + if req.Op == Move && fb.FS().Caps().ReadOnly { + return nil, fmt.Errorf("%w: cannot move from %s", ErrReadOnly, fb.FS().Label()) + } + if err := checkRoots(ctx, fb, req); err != nil { + return nil, err + } + if fs, ok := fb.(*fsSource); ok && fs.sym != req.Opts.Symlinks { + cp := *fs + cp.sym = req.Opts.Symlinks + req.From = &cp + } + } + + plan := &Plan{Req: req} + report := func() { + if progress != nil { + progress(Progress{Phase: Scanning, FilesTotal: plan.TotalFiles, BytesTotal: plan.TotalBytes}) + } + } + err := req.From.Walk(ctx, func(it Item) error { + if it.Warning != "" { + plan.Warnings = append(plan.Warnings, it.Rel+": "+it.Warning) + } + switch it.Kind { + case File: + plan.TotalFiles++ + plan.TotalBytes += it.Size + case Symlink: + plan.TotalFiles++ + case Special: + plan.Warnings = append(plan.Warnings, it.Rel+": special file skipped") + } + plan.Items = append(plan.Items, it) + if len(plan.Items)%256 == 0 { + report() + } + return nil + }) + if err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + seen := map[string]bool{} + for _, it := range plan.Items { + if !strings.Contains(it.Rel, "/") { + if seen[it.Rel] { + return nil, fmt.Errorf("%w: %s", ErrDuplicateName, it.Rel) + } + seen[it.Rel] = true + } + } + if err := findExisting(ctx, plan); err != nil { + return nil, err + } + report() + + if fb, ok := req.From.(FSBacked); ok { + a, b := fb.FS(), req.To + plan.SameConn = (a.Kind() == vfs.KindLocal && b.Kind() == vfs.KindLocal) || + (a == b && a.Volume() == b.Volume()) + } + return plan, nil +} + +// checkRoots refuses roots that are their own target or contain ToDir. +func checkRoots(ctx context.Context, fb FSBacked, req Request) error { + src := fb.FS() + for _, root := range fb.Roots() { + dst := req.To.Paths().Join(req.ToDir, src.Paths().Base(root)) + same, err := vfs.SameFile(ctx, src, root, req.To, dst) + if err != nil { + return err + } + if same { + return fmt.Errorf("%w: %s", ErrSameFile, root) + } + if src.Volume() != req.To.Volume() { + continue + } + fi, err := src.Lstat(ctx, root) + if err != nil { + return err + } + isDir := fi.IsDir() || (req.Opts.Symlinks == FollowLinks && fi.NavigableDir()) + if !isDir { + continue + } + in, err := vfs.Within(ctx, req.To, req.ToDir, root) + if err != nil { + return err + } + if in { + return fmt.Errorf("%w: %s → %s", ErrIntoItself, root, req.ToDir) + } + } + return nil +} + +// dstPath maps an item's Rel onto the target FS. +func dstPath(to vfs.FS, toDir, rel string) string { + return to.Paths().Join(append([]string{toDir}, strings.Split(rel, "/")...)...) +} + +func splitRel(rel string) (parent, name string) { + i := strings.LastIndexByte(rel, '/') + if i < 0 { + return "", rel + } + return rel[:i], rel[i+1:] +} + +// findExisting fills Existing and Conflicts. ToDir and the target +// directories a source directory merges into are listed — one ReadDir per +// directory, never a stat per file (N-P2-4/5). +func findExisting(ctx context.Context, plan *Plan) error { + to, toDir := plan.Req.To, plan.Req.ToDir + listings := map[string]map[string]vfs.FileInfo{} + + list := func(rel, p string) error { + ents, err := to.ReadDir(ctx, p) + if err != nil { + return err + } + m := make(map[string]vfs.FileInfo, len(ents)) + for _, e := range ents { + m[e.Name] = e + if strings.HasPrefix(e.Name, partPrefix) { + plan.Warnings = append(plan.Warnings, fmt.Sprintf("%s: leftover of an interrupted transfer", + to.Paths().Join(p, e.Name))) + } + } + listings[rel] = m + return nil + } + + // ToDir is always listed once: it gives Existing for every root without + // a stat per root and reveals temp files left by an interrupted transfer + // (a dead connection cannot remove them). + if err := list("", toDir); err != nil { + return err + } + + for i := range plan.Items { + if i%256 == 0 { + if err := ctx.Err(); err != nil { + return err + } + } + it := &plan.Items[i] + parent, name := splitRel(it.Rel) + var existing *vfs.FileInfo + if l, ok := listings[parent]; ok { + if fi, ok := l[name]; ok { + existing = &fi + } + } + it.Existing = existing + if existing == nil { + continue + } + switch { + case it.Kind == Dir && existing.IsDir(): + if err := list(it.Rel, dstPath(to, toDir, it.Rel)); err != nil { + return err + } + case it.Kind == Dir || existing.IsDir(): + plan.Conflicts = append(plan.Conflicts, Conflict{Item: *it, Kind: TypeMismatch}) + case it.Kind == Special: + default: + plan.Conflicts = append(plan.Conflicts, Conflict{Item: *it, Kind: FileFile}) + } + } + return nil +} diff --git a/internal/transfer/prepare_test.go b/internal/transfer/prepare_test.go new file mode 100644 index 0000000..0e6aa97 --- /dev/null +++ b/internal/transfer/prepare_test.go @@ -0,0 +1,227 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "strings" + "testing" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +func TestPrepareCountsBytes(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("dir/a", "1234567890"), + fstree.File("dir/sub/b", "").WithSize(1000), + fstree.Symlink("dir/ln", "a"), + fstree.FIFO("dir/fifo"), + fstree.File("top.txt", "abc"), + }, nil) + var last Progress + plan, err := Prepare(bg, req(Copy, local, join(src, "dir", "top.txt"), local, dst), func(p Progress) { last = p }) + if err != nil { + t.Fatal(err) + } + if plan.TotalBytes != 10+1000+3 || plan.TotalFiles != 4 { + t.Fatalf("totals: files=%d bytes=%d (N-P1-13: dir bytes must be counted)", plan.TotalFiles, plan.TotalBytes) + } + if last.Phase != Scanning || last.BytesTotal != plan.TotalBytes { + t.Fatalf("final scanning progress %+v", last) + } + if len(plan.Warnings) != 1 || plan.Warnings[0] != "dir/fifo: special file skipped" { + t.Fatalf("warnings %v", plan.Warnings) + } + var rels []string + for _, it := range plan.Items { + rels = append(rels, it.Rel+":"+it.Kind.String()) + } + want := "[dir:dir dir/a:file dir/fifo:special dir/ln:symlink dir/sub:dir dir/sub/b:file top.txt:file]" + if fmt.Sprint(rels) != want { + t.Fatalf("items %v", rels) + } + if !plan.SameConn { + t.Fatal("local→local is SameConn") + } +} + +func TestPrepareRejectsSameFile(t *testing.T) { + src, _ := layout(t, fstree.Spec{fstree.File("real/f.txt", "ONLY COPY"), fstree.Symlink("alias", "real")}, nil) + cases := map[string]Request{ + "same dir": req(Copy, local, join(src, "real/f.txt"), local, filepath.Join(src, "real")), + "via dir alias": req(Copy, local, join(src, "real/f.txt"), local, filepath.Join(src, "alias")), + "dir onto alias": req(Move, local, join(src, "real"), local, src), + } + for name, r := range cases { + if _, err := Prepare(bg, r, nil); !errors.Is(err, ErrSameFile) { + t.Errorf("%s: err = %v, want ErrSameFile (N-P0-6)", name, err) + } + } + if read(t, filepath.Join(src, "real", "f.txt")) != "ONLY COPY" { + t.Fatal("source touched") + } +} + +func TestPrepareRejectsIntoItself(t *testing.T) { + src, _ := layout(t, fstree.Spec{fstree.Dir("proj/sub/deep"), fstree.Symlink("plink", "proj/sub")}, nil) + for _, to := range []string{ + filepath.Join(src, "proj"), + filepath.Join(src, "proj", "sub", "deep"), + filepath.Join(src, "plink"), // inside through a symlink + } { + if _, err := Prepare(bg, req(Copy, local, join(src, "proj"), local, to), nil); !errors.Is(err, ErrIntoItself) { + t.Errorf("to %s: err = %v, want ErrIntoItself", to, err) + } + } + // A sibling with a common prefix is fine. + fstree.Build(t, src, fstree.Spec{fstree.Dir("project")}) + if _, err := Prepare(bg, req(Copy, local, join(src, "proj"), local, filepath.Join(src, "project")), nil); err != nil { + t.Fatal(err) + } +} + +func TestPrepareConflictsPerFile(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("proj/same.txt", "new"), + fstree.File("proj/new.txt", "n"), + fstree.File("proj/isdir", "file in src"), + fstree.Dir("proj/isfile"), + fstree.File("proj/isfile/x", ""), + fstree.File("proj/sub/deeper.txt", "d"), + }, fstree.Spec{ + fstree.File("proj/same.txt", "old"), + fstree.Dir("proj/isdir"), + fstree.File("proj/isfile", "file in dst"), + fstree.File("proj/sub/deeper.txt", "old"), + fstree.File("proj/only-in-dst", ""), + fstree.File("proj/.vcom-part-deadbeef-x", ""), + }) + plan, err := Prepare(bg, req(Copy, local, join(src, "proj"), local, dst), nil) + if err != nil { + t.Fatal(err) + } + got := map[string]ConflictKind{} + for _, c := range plan.Conflicts { + got[c.Item.Rel] = c.Kind + } + want := map[string]ConflictKind{ + "proj/same.txt": FileFile, + "proj/isdir": TypeMismatch, + "proj/isfile": TypeMismatch, + "proj/sub/deeper.txt": FileFile, + } + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("conflicts %v, want %v", got, want) + } + for _, it := range plan.Items { + if (it.Rel == "proj/new.txt" || it.Rel == "proj/isfile/x") && it.Existing != nil { + t.Errorf("%s has Existing", it.Rel) + } + if it.Rel == "proj" && (it.Existing == nil || !it.Existing.IsDir()) { + t.Error("root dir merge target not found") + } + } + if len(plan.Warnings) != 1 { + t.Fatalf("leftover warning expected: %v", plan.Warnings) + } +} + +func TestPrepareReadDirPerDirNotPerFile(t *testing.T) { + var spec, dspec fstree.Spec + for i := range 1000 { + spec = append(spec, fstree.File(fmt.Sprintf("d/f%04d", i), "")) + if i%2 == 0 { + dspec = append(dspec, fstree.File(fmt.Sprintf("d/f%04d", i), "")) + } + } + src, dst := layout(t, spec, dspec) + c := &counter{} + to := &vfstest.FaultFS{FS: local, Hook: c.hook} + plan, err := Prepare(bg, req(Copy, local, join(src, "d"), to, dst), nil) + if err != nil { + t.Fatal(err) + } + if len(plan.Conflicts) != 500 { + t.Fatalf("%d conflicts", len(plan.Conflicts)) + } + if n := c.get(vfstest.OpReadDir); n != 2 { // ToDir and d + t.Fatalf("%d ReadDir calls on the target, want 2: one per directory (N-P2-4/5)", n) + } + if n := c.get(vfstest.OpLstat) + c.get(vfstest.OpStat); n > 4 { + t.Fatalf("%d stat calls on the target", n) + } + + // Many roots: one listing of ToDir, no stat per root. + var roots fstree.Spec + var names []string + for i := range 50 { + n := fmt.Sprintf("r%02d", i) + roots = append(roots, fstree.File(n, "")) + names = append(names, n) + } + src, dst = layout(t, roots, nil) + c = &counter{} + to = &vfstest.FaultFS{FS: local, Hook: c.hook} + if _, err := Prepare(bg, req(Copy, local, join(src, names...), to, dst), nil); err != nil { + t.Fatal(err) + } + if c.get(vfstest.OpReadDir) != 1 || c.get(vfstest.OpLstat) > 0 { + t.Fatalf("many roots: readdir=%d lstat=%d", c.get(vfstest.OpReadDir), c.get(vfstest.OpLstat)) + } +} + +func TestPrepareCancel(t *testing.T) { + var spec fstree.Spec + for i := range 50 { + spec = append(spec, fstree.File(fmt.Sprintf("d/s%02d/f", i), "")) + } + src, dst := layout(t, spec, nil) + ctx, cancel := context.WithCancel(bg) + n := 0 + from := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpReadDir { + if n++; n == 5 { + cancel() + } + } + return nil + }} + _, err := Prepare(ctx, req(Copy, from, join(src, "d"), local, dst), nil) + if !errors.Is(err, vfs.ErrCancelled) { + t.Fatalf("err = %v, want cancelled", err) + } + if n > 6 { + t.Fatalf("walk continued after cancel: %d ReadDirs", n) + } +} + +func TestPrepareRejectsBadTargets(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", ""), fstree.File("x/a", "")}, fstree.Spec{fstree.File("file", "")}) + if _, err := Prepare(bg, req(Copy, local, join(src, "a"), vfs.ReadOnly(local), dst), nil); !errors.Is(err, ErrReadOnly) { + t.Fatalf("read-only target: %v", err) + } + if _, err := Prepare(bg, req(Copy, local, join(src, "a"), local, filepath.Join(dst, "file")), nil); !errors.Is(err, ErrTargetNotDir) { + t.Fatalf("file target: %v", err) + } + if _, err := Prepare(bg, req(Copy, local, join(src, "a", "x/a"), local, dst), nil); !errors.Is(err, ErrDuplicateName) { + t.Fatalf("duplicate names: %v", err) + } + if _, err := Prepare(bg, req(Move, vfs.ReadOnly(local), join(src, "a"), local, dst), nil); !errors.Is(err, ErrReadOnly) { + t.Fatalf("move from read-only: %v", err) + } +} + +func TestPrepareWarnsAboutLeftoversInToDir(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("important.db", "new")}, + fstree.Spec{fstree.File("important.db", "old"), fstree.File(".vcom-part-0badc0de-important.db", "half")}) + plan, err := Prepare(bg, req(Copy, local, join(src, "important.db"), local, dst, overwrite), nil) + if err != nil { + t.Fatal(err) + } + if len(plan.Warnings) != 1 || !strings.Contains(plan.Warnings[0], ".vcom-part-0badc0de-important.db") { + t.Fatalf("warnings %v: a leftover next to a single root must be reported", plan.Warnings) + } +} diff --git a/internal/transfer/reader.go b/internal/transfer/reader.go new file mode 100644 index 0000000..f831238 --- /dev/null +++ b/internal/transfer/reader.go @@ -0,0 +1,65 @@ +package transfer + +import ( + "context" + "io" + "time" +) + +// progressReader checks ctx before every chunk (cancellation inside a file: +// N-P1-7) and reports bytes read. Size lets pkg/sftp pick its concurrent +// ReadFrom path. +type progressReader struct { + ctx context.Context + r io.Reader + size int64 + n int64 + onRead func(total int64) +} + +func (r *progressReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + n, err := r.r.Read(p) + if n > 0 { + r.n += int64(n) + if r.onRead != nil { + r.onRead(r.n) + } + } + return n, err +} + +func (r *progressReader) Size() int64 { return r.size } + +// defaultProgressInterval bounds how often Hooks.Progress is called. +const defaultProgressInterval = 50 * time.Millisecond + +// emitter throttles progress callbacks. +type emitter struct { + fn func(Progress) + every time.Duration + last time.Time + p Progress +} + +func newEmitter(fn func(Progress), every time.Duration) *emitter { + if every <= 0 { + every = defaultProgressInterval + } + return &emitter{fn: fn, every: every} +} + +// emit calls fn if the interval has passed or force is set. +func (e *emitter) emit(force bool) { + if e.fn == nil { + return + } + now := time.Now() + if !force && now.Sub(e.last) < e.every { + return + } + e.last = now + e.fn(e.p) +} diff --git a/internal/transfer/remote_test.go b/internal/transfer/remote_test.go new file mode 100644 index 0000000..88ae8ac --- /dev/null +++ b/internal/transfer/remote_test.go @@ -0,0 +1,621 @@ +package transfer + +// Stage 3.7: the key transfer scenarios over SFTP on the in-process stand +// (internal/testutil/sshtest). The stand serves the real file system, so +// remote paths are local temp paths and results are checked with os.*. + +import ( + "bytes" + "context" + "errors" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/ssh/conn" + "vcom/internal/testutil/sshtest" + "vcom/internal/vfs" + "vcom/internal/vfs/sftpfs" +) + +// rstand is a server, its keys in an isolated known_hosts and a pool with +// fast keepalive (a frozen link is Lost within ~0.4 s). +type rstand struct { + t *testing.T + srv *sshtest.Server + pool *conn.Pool + kh string +} + +func newRStand(t *testing.T) *rstand { + t.Helper() + return newRStandWith(t, conn.PoolOptions{ + KeepaliveInterval: 100 * time.Millisecond, + KeepaliveTimeout: 100 * time.Millisecond, + KeepaliveMaxMiss: 2, + ReconnectBackoff: []time.Duration{50 * time.Millisecond, 100 * time.Millisecond}, + }) +} + +// newRStandWith uses o (keepalive, backoff); zero values are the pool +// defaults (15 s keepalive). +func newRStandWith(t *testing.T, o conn.PoolOptions) *rstand { + t.Helper() + home := sshtest.IsolatedHome(t) + s := &rstand{t: t, srv: sshtest.Start(t, sshtest.Options{}), kh: filepath.Join(home, ".ssh", "known_hosts")} + s.trust(s.srv.Addr) + o.DialOptions = conn.DialOptions{Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh}} + s.pool = conn.NewPool(o) + t.Cleanup(func() { s.pool.Close() }) + return s +} + +func (s *rstand) trust(addr string) { + s.t.Helper() + f, err := os.OpenFile(s.kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + s.t.Fatal(err) + } + defer f.Close() + for _, k := range s.srv.HostKeys { + if _, err := f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(addr)}, k.PublicKey()) + "\n"); err != nil { + s.t.Fatal(err) + } + } +} + +func (s *rstand) proxy() *sshtest.Proxy { + px := sshtest.NewProxy(s.t, s.srv.Addr) + s.trust(px.Addr) + return px +} + +// fs connects as user ("" = "u") to addr ("" = the server itself). +func (s *rstand) fs(addr, user string) *sftpfs.FS { + s.t.Helper() + if addr == "" { + addr = s.srv.Addr + } + if user == "" { + user = "u" + } + host, port, _ := net.SplitHostPort(addr) + p, _ := strconv.Atoi(port) + l, err := s.pool.Acquire(context.Background(), conn.Endpoint{ + Alias: "alias-" + port, User: user, Host: host, Port: p, Password: s.srv.Password, + }) + if err != nil { + s.t.Fatalf("acquire: %v", err) + } + f := sftpfs.New(l) + s.t.Cleanup(f.Release) + return f +} + +func prepare(t *testing.T, r Request) *Plan { + t.Helper() + plan, err := Prepare(bg, r, nil) + if err != nil { + t.Fatalf("Prepare: %v", err) + } + return plan +} + +// partFiles lists .vcom-part-* / .vcom-old-* names directly in dir. +func partFiles(t *testing.T, dir string) []string { + t.Helper() + ents, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var out []string + for _, e := range ents { + if n := e.Name(); len(n) > len(partPrefix) && (n[:len(partPrefix)] == partPrefix || n[:len(oldPrefix)] == oldPrefix) { + out = append(out, n) + } + } + return out +} + +// Ported from the testbed (B8), N-P0-4: the connection is cut in the middle +// of overwriting a remote file. The old file must survive, and nothing +// partial may sit under its name. +func TestOverwriteThenDrop(t *testing.T) { + s := newRStand(t) + px := s.proxy() + remote := s.fs(px.Addr, "") + dir := t.TempDir() + dst := filepath.Join(dir, "important.db") + old := sshtest.WriteRandom(t, dst, 2<<20, 0o644) + srcDir := t.TempDir() + sshtest.WriteRandom(t, filepath.Join(srcDir, "important.db"), 8<<20, 0o644) + + plan := prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite)) + px.CutAfter(1 << 20) + rep := Execute(bg, plan, Hooks{}) + if rep.Failed != 1 || rep.Done != 0 { + t.Fatalf("report = %+v", rep) + } + if !errors.Is(rep.Errors[0].Err, vfs.ErrConnLost) { + t.Errorf("item error = %v, want ErrConnLost", rep.Errors[0].Err) + } + now, err := os.ReadFile(dst) + if err != nil || !bytes.Equal(now, old) { + t.Fatalf("old destination damaged: %d bytes, err %v", len(now), err) + } + // The temp file cannot be removed over a dead connection; the next plan + // for this directory must report it. + parts := partFiles(t, dir) + if len(parts) != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], parts[0]) { + t.Fatalf("temp after the cut: %v; the report must name it: %v", parts, rep.Warnings) + } + if err := s.pool.Reconnect(bg, remote.Conn().Key()); err != nil { + t.Fatal(err) + } + plan = prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite)) + for _, p := range parts { + found := false + for _, w := range plan.Warnings { + found = found || strings.Contains(w, p) + } + if !found { + t.Errorf("leftover %s not reported by Prepare: %v", p, plan.Warnings) + } + } + rep = Execute(bg, plan, Hooks{}) + if rep.Done != 1 { + t.Fatalf("copy after reconnect: %+v", rep) + } + if now, _ := os.ReadFile(dst); len(now) != 8<<20 { + t.Errorf("after retry: %d bytes", len(now)) + } +} + +// The same cut, but the caller answers the error with reconnect + Retry +// inside one Execute: the temp of the failed attempt is removed on the new +// connection, nothing is left behind. +func TestOverwriteThenDropRetryLeavesNoTemp(t *testing.T) { + s := newRStand(t) + px := s.proxy() + remote := s.fs(px.Addr, "") + dir := t.TempDir() + dst := filepath.Join(dir, "important.db") + sshtest.WriteRandom(t, dst, 2<<20, 0o644) + srcDir := t.TempDir() + want := sshtest.WriteRandom(t, filepath.Join(srcDir, "important.db"), 8<<20, 0o644) + + plan := prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite)) + px.CutAfter(1 << 20) + retries := 0 + rep := Execute(bg, plan, Hooks{OnError: func(ctx context.Context, e ItemError) (ErrorAction, error) { + if !errors.Is(e.Err, vfs.ErrConnLost) || retries > 0 { + return ErrorStop, nil + } + retries++ + if err := s.pool.Reconnect(ctx, remote.Conn().Key()); err != nil { + return ErrorStop, err + } + return ErrorRetry, nil + }}) + if rep.Done != 1 || rep.Failed != 0 || retries != 1 { + t.Fatalf("report = %+v, retries %d", rep, retries) + } + if now, _ := os.ReadFile(dst); !bytes.Equal(now, want) { + t.Fatalf("target after retry: %d bytes", len(now)) + } + if parts := partFiles(t, dir); len(parts) != 0 { + t.Fatalf("temp files left after a successful retry: %v", parts) + } + if len(rep.Warnings) != 0 { + t.Fatalf("warnings %v", rep.Warnings) + } +} + +// Ported from TestSameFileViaAliasTruncates (B4), N-P0-5: the same file +// through two aliases of one server was truncated to zero. +func TestSameFileViaAliasRejected(t *testing.T) { + s := newRStand(t) + a := s.fs("", "") + b := s.fs(s.proxy().Addr, "") + if a.Conn() == b.Conn() { + t.Fatal("test needs two connections") + } + dir := t.TempDir() + f := filepath.Join(dir, "data.bin") + data := sshtest.WriteRandom(t, f, 1<<20, 0o644) + + _, err := Prepare(bg, req(Copy, a, []string{f}, b, dir, overwrite), nil) + if !errors.Is(err, ErrSameFile) { + t.Fatalf("Prepare = %v, want ErrSameFile", err) + } + + // Even if the check is bypassed, the write goes to a temp file and the + // rename replaces the file only with complete content. + other := t.TempDir() + plan := prepare(t, req(Copy, a, []string{f}, b, other, overwrite)) + plan.Req.ToDir = dir + fi, err := b.Lstat(bg, f) + if err != nil { + t.Fatal(err) + } + plan.Items[0].Existing = &fi + rep := Execute(bg, plan, Hooks{}) + if rep.Done != 1 { + t.Fatalf("report = %+v", rep) + } + if now, _ := os.ReadFile(f); !bytes.Equal(now, data) { + t.Fatalf("file damaged: %d bytes", len(now)) + } + noLeftovers(t, dir) +} + +func brokenLinkTree(t *testing.T, root string) { + t.Helper() + sshtest.WriteRandom(t, filepath.Join(root, "a.txt"), 10, 0o644) + sshtest.WriteRandom(t, filepath.Join(root, "z_after.txt"), 10, 0o644) + if err := os.Symlink("/nonexistent/zzz", filepath.Join(root, "broken")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(".", filepath.Join(root, "loopdir")); err != nil { + t.Fatal(err) + } +} + +func checkBrokenLinkCopy(t *testing.T, rep Report, dst string) { + t.Helper() + if rep.Failed != 0 || rep.Err != nil || rep.Done != 4 { + t.Fatalf("report = %+v", rep) + } + for _, n := range []string{"a.txt", "z_after.txt"} { + if _, err := os.Stat(filepath.Join(dst, n)); err != nil { + t.Errorf("%s missing: %v", n, err) + } + } + for n, want := range map[string]string{"broken": "/nonexistent/zzz", "loopdir": "."} { + if got, err := os.Readlink(filepath.Join(dst, n)); err != nil || got != want { + t.Errorf("%s -> %q (%v), want link to %q", n, got, err, want) + } + } + noLeftovers(t, dst) +} + +// Ported (B2), N-P1-8: a broken symlink aborted a directory upload. +func TestUploadDirWithBrokenSymlink(t *testing.T) { + s := newRStand(t) + remote := s.fs("", "") + src := filepath.Join(t.TempDir(), "src") + brokenLinkTree(t, src) + dst := t.TempDir() + rep := Execute(bg, prepare(t, req(Copy, local, []string{src}, remote, dst)), Hooks{}) + checkBrokenLinkCopy(t, rep, filepath.Join(dst, "src")) +} + +func TestDownloadDirWithBrokenSymlink(t *testing.T) { + s := newRStand(t) + remote := s.fs("", "") + src := filepath.Join(t.TempDir(), "src") + brokenLinkTree(t, src) + dst := t.TempDir() + rep := Execute(bg, prepare(t, req(Copy, remote, []string{src}, local, dst)), Hooks{}) + checkBrokenLinkCopy(t, rep, filepath.Join(dst, "src")) +} + +// Ported from TestPermsMtimeLost (B3), N-P1-9. +func TestRemotePermsMtimePreserved(t *testing.T) { + s := newRStand(t) + remote := s.fs("", "") + dir := t.TempDir() + src := filepath.Join(dir, "run.sh") + sshtest.WriteRandom(t, src, 100, 0o755) + mt := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + if err := os.Chtimes(src, mt, mt); err != nil { + t.Fatal(err) + } + up, down := t.TempDir(), t.TempDir() + if rep := Execute(bg, prepare(t, req(Copy, local, []string{src}, remote, up)), Hooks{}); rep.Done != 1 { + t.Fatalf("upload: %+v", rep) + } + if rep := Execute(bg, prepare(t, req(Copy, remote, []string{src}, local, down)), Hooks{}); rep.Done != 1 { + t.Fatalf("download: %+v", rep) + } + for _, p := range []string{filepath.Join(up, "run.sh"), filepath.Join(down, "run.sh")} { + st, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + if st.Mode().Perm() != 0o755 || !st.ModTime().Equal(mt) { + t.Errorf("%s: mode %v mtime %v", p, st.Mode().Perm(), st.ModTime()) + } + } +} + +// N-P1-10 / N-P2-3: two users on one host are different connections; a +// remote→remote copy between them merges into an existing directory (no +// dst/proj/proj) and a move is copy+delete, not a server-side rename. +func TestRemoteToRemoteDifferentUsersNotSameConn(t *testing.T) { + s := newRStand(t) + alice := s.fs("", "alice") + bob := s.fs("", "bob") + if alice.Conn() == bob.Conn() { + t.Fatal("different users share a connection") + } + base := t.TempDir() + src := filepath.Join(base, "src", "proj") + sshtest.WriteRandom(t, filepath.Join(src, "new.txt"), 100, 0o644) + sshtest.WriteRandom(t, filepath.Join(src, "sub", "deep.txt"), 100, 0o644) + dst := filepath.Join(base, "dst") + sshtest.WriteRandom(t, filepath.Join(dst, "proj", "keep.txt"), 10, 0o644) + + plan := prepare(t, req(Copy, alice, []string{src}, bob, dst)) + if plan.SameConn { + t.Error("plan.SameConn for different users") + } + rep := Execute(bg, plan, Hooks{}) + if rep.Failed != 0 || rep.Done != 2 { + t.Fatalf("report = %+v", rep) + } + for _, p := range []string{"proj/new.txt", "proj/sub/deep.txt", "proj/keep.txt"} { + if _, err := os.Stat(filepath.Join(dst, p)); err != nil { + t.Errorf("%s: %v", p, err) + } + } + if _, err := os.Stat(filepath.Join(dst, "proj", "proj")); err == nil { + t.Error("copy nested proj/proj") + } + + mv := filepath.Join(base, "dst2") + if err := os.Mkdir(mv, 0o755); err != nil { + t.Fatal(err) + } + rep = Execute(bg, prepare(t, req(Move, alice, []string{src}, bob, mv)), Hooks{}) + if rep.Failed != 0 || rep.Done != 2 { + t.Fatalf("move report = %+v", rep) + } + if _, err := os.Lstat(src); !os.IsNotExist(err) { + t.Errorf("move left the source: %v", err) + } + if _, err := os.Stat(filepath.Join(mv, "proj", "sub", "deep.txt")); err != nil { + t.Errorf("moved content missing: %v", err) + } +} + +// N-P1-2: a cut connection surfaces as ErrConnLost; the caller reconnects +// and retries, and the copy completes. +func TestConnLostAsksRetry(t *testing.T) { + s := newRStand(t) + px := s.proxy() + remote := s.fs(px.Addr, "") + srcDir := t.TempDir() + data := sshtest.WriteRandom(t, filepath.Join(srcDir, "big.bin"), 4<<20, 0o644) + dst := t.TempDir() + plan := prepare(t, req(Copy, local, join(srcDir, "big.bin"), remote, dst)) + px.CutAfter(512 << 10) + var asked atomic.Int32 + rep := Execute(bg, plan, Hooks{OnError: func(ctx context.Context, e ItemError) (ErrorAction, error) { + asked.Add(1) + if !errors.Is(e.Err, vfs.ErrConnLost) { + t.Errorf("OnError got %v, want ErrConnLost", e.Err) + return ErrorStop, nil + } + if err := s.pool.Reconnect(ctx, remote.Conn().Key()); err != nil { + t.Errorf("reconnect: %v", err) + return ErrorStop, nil + } + return ErrorRetry, nil + }}) + if rep.Done != 1 || rep.Failed != 0 || asked.Load() != 1 { + t.Fatalf("report = %+v, asked %d", rep, asked.Load()) + } + if got, _ := os.ReadFile(filepath.Join(dst, "big.bin")); !bytes.Equal(got, data) { + t.Fatal("content mismatch after retry") + } + if remote.Conn().Gen() != 2 { + t.Errorf("gen = %d", remote.Conn().Gen()) + } +} + +// Cancelling in the middle of an upload over a live link returns promptly, +// keeps the old target and removes the temp file (N-P1-7). +func TestRemoteCancelMidFile(t *testing.T) { + s := newRStand(t) + px := s.proxy() + px.SetDelay(5 * time.Millisecond) + remote := s.fs(px.Addr, "") + dir := t.TempDir() + old := sshtest.WriteRandom(t, filepath.Join(dir, "f.bin"), 1<<20, 0o644) + srcDir := t.TempDir() + sshtest.WriteRandom(t, filepath.Join(srcDir, "f.bin"), 32<<20, 0o644) + plan := prepare(t, req(Copy, local, join(srcDir, "f.bin"), remote, dir, overwrite)) + ctx, cancel := context.WithCancel(bg) + defer cancel() + var once sync.Once + var cancelled time.Time + rep := Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) { + if p.CurrentDone > 2<<20 { + once.Do(func() { cancelled = time.Now(); cancel() }) + } + }}) + if cancelled.IsZero() { + t.Fatal("never cancelled") + } + if el := time.Since(cancelled); el > time.Second { + t.Errorf("Execute returned %v after cancel", el) + } + if !rep.Cancelled || rep.Done != 0 { + t.Errorf("report = %+v", rep) + } + if now, _ := os.ReadFile(filepath.Join(dir, "f.bin")); !bytes.Equal(now, old) { + t.Fatal("old target damaged") + } + noLeftovers(t, dir) +} + +// A link that freezes in the middle of a file (Wi-Fi gone): cancelling +// returns once the pool notices the dead link (fast keepalive here), with +// the old target intact. +func TestRemoteFreezeMidFileThenCancel(t *testing.T) { + s := newRStand(t) + px := s.proxy() + remote := s.fs(px.Addr, "") + dir := t.TempDir() + old := sshtest.WriteRandom(t, filepath.Join(dir, "f.bin"), 1<<20, 0o644) + srcDir := t.TempDir() + sshtest.WriteRandom(t, filepath.Join(srcDir, "f.bin"), 16<<20, 0o644) + plan := prepare(t, req(Copy, local, join(srcDir, "f.bin"), remote, dir, overwrite)) + ctx, cancel := context.WithCancel(bg) + defer cancel() + var once sync.Once + var cancelled time.Time + var mu sync.Mutex + done := make(chan Report, 1) + go func() { + done <- Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) { + if p.CurrentDone > 1<<20 { + once.Do(func() { + px.Freeze(true) + time.AfterFunc(50*time.Millisecond, func() { + mu.Lock() + cancelled = time.Now() + mu.Unlock() + cancel() + }) + }) + } + }}) + }() + var rep Report + select { + case rep = <-done: + case <-time.After(5 * time.Second): + t.Fatal("Execute hung on a frozen link after cancel") + } + px.Freeze(false) + mu.Lock() + el := time.Since(cancelled) + mu.Unlock() + t.Logf("returned %v after cancel", el) + if el > 2*time.Second { + t.Errorf("returned %v after cancel", el) + } + if rep.Done != 0 || !(rep.Cancelled || rep.Failed == 1) { + t.Errorf("report = %+v", rep) + } + if now, _ := os.ReadFile(filepath.Join(dir, "f.bin")); !bytes.Equal(now, old) { + t.Fatal("old target damaged") + } +} + +// freezeCancel runs plan, freezes px once the current file passed 1 MiB and +// cancels 50 ms later; it returns the report and the time from cancel to +// return. +func freezeCancel(t *testing.T, px *sshtest.Proxy, plan *Plan) (Report, time.Duration) { + t.Helper() + ctx, cancel := context.WithCancel(bg) + defer cancel() + var once sync.Once + var mu sync.Mutex + var cancelled time.Time + done := make(chan Report, 1) + go func() { + done <- Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) { + if p.CurrentDone > 1<<20 { + once.Do(func() { + px.Freeze(true) + time.AfterFunc(50*time.Millisecond, func() { + mu.Lock() + cancelled = time.Now() + mu.Unlock() + cancel() + }) + }) + } + }}) + }() + var rep Report + select { + case rep = <-done: + case <-time.After(20 * time.Second): + t.Fatal("Execute hung after cancel on a frozen link") + } + mu.Lock() + defer mu.Unlock() + if cancelled.IsZero() { + t.Fatal("never cancelled") + } + return rep, time.Since(cancelled) +} + +// With the DEFAULT keepalive (15 s × 2 + 10 s) a cancel on a link frozen in +// the middle of a file must return within 3 s: the sftpfs cancel watchdog +// probes the link and tears it down. Upload and download. +func TestRemoteFreezeCancelDefaultKeepalive(t *testing.T) { + for _, dir := range []string{"upload", "download"} { + t.Run(dir, func(t *testing.T) { + s := newRStandWith(t, conn.PoolOptions{}) + px := s.proxy() + remote := s.fs(px.Addr, "") + src, dst := t.TempDir(), t.TempDir() + sshtest.WriteRandom(t, filepath.Join(src, "f.bin"), 32<<20, 0o644) + old := sshtest.WriteRandom(t, filepath.Join(dst, "f.bin"), 1<<20, 0o644) + from, to := vfs.FS(local), vfs.FS(remote) + if dir == "download" { + from, to = remote, local + } + px.SetDelay(2 * time.Millisecond) // keep the copy in flight long enough to freeze it + plan := prepare(t, req(Copy, from, join(src, "f.bin"), to, dst, overwrite)) + rep, el := freezeCancel(t, px, plan) + px.Freeze(false) + t.Logf("%s: returned %v after cancel, report %+v", dir, el, rep) + if el > 3*time.Second { + t.Errorf("returned %v after cancel, want <= 3s", el) + } + if rep.Done != 0 { + t.Errorf("report = %+v", rep) + } + if now, _ := os.ReadFile(filepath.Join(dst, "f.bin")); !bytes.Equal(now, old) { + t.Fatal("old target damaged") + } + }) + } +} + +// A slow but live link is not torn down by a cancel: the probe answers. +func TestRemoteSlowLinkCancelKeepsConn(t *testing.T) { + s := newRStandWith(t, conn.PoolOptions{}) + px := s.proxy() + remote := s.fs(px.Addr, "") + src, dst := t.TempDir(), t.TempDir() + sshtest.WriteRandom(t, filepath.Join(src, "f.bin"), 8<<20, 0o644) + px.SetDelay(150 * time.Millisecond) // RTT ≈ 300 ms + plan := prepare(t, req(Copy, local, join(src, "f.bin"), remote, dst)) + ctx, cancel := context.WithCancel(bg) + defer cancel() + var once sync.Once + rep := Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) { + if p.CurrentDone > 1<<20 { + once.Do(cancel) + } + }}) + if !rep.Cancelled { + t.Errorf("report = %+v", rep) + } + time.Sleep(cancelWatchdogSettle) + if st := remote.Conn().State(); st != conn.Ready { + t.Fatalf("slow but live link torn down by cancel: state %v (%v)", st, remote.Conn().Err()) + } + if _, err := remote.Stat(bg, dst); err != nil { + t.Fatalf("conn unusable after cancel: %v", err) + } + noLeftovers(t, dst) +} + +// cancelWatchdogSettle covers sftpfs' cancel grace + probe timeout. +const cancelWatchdogSettle = 3 * time.Second diff --git a/internal/transfer/source.go b/internal/transfer/source.go new file mode 100644 index 0000000..1c2b375 --- /dev/null +++ b/internal/transfer/source.go @@ -0,0 +1,190 @@ +package transfer + +import ( + "context" + "fmt" + "io" + "sort" + "strings" + + "vcom/internal/vfs" +) + +// Source yields the items of a transfer. +type Source interface { + Label() string + // Walk emits every item once, parents before children (plan phase). + Walk(ctx context.Context, fn func(Item) error) error + // Stream calls fn for items in source order; r is the content of File + // items and nil otherwise (execute phase). + Stream(ctx context.Context, items []Item, fn func(Item, io.Reader) error) error +} + +// Opener is a Source with random access: Execute reopens an item for every +// attempt, so Retry after a read error works. +type Opener interface { + Open(ctx context.Context, it Item) (io.ReadCloser, error) +} + +// FSBacked is a Source over a vfs.FS (FSSource): Prepare checks identity +// against the target and Move can rename and remove source items. +type FSBacked interface { + Source + FS() vfs.FS + Roots() []string +} + +// FSSource reads the given paths (files, directories, links) from fsys. +func FSSource(fsys vfs.FS, paths []string, sym SymlinkPolicy) Source { + roots := make([]string, len(paths)) + for i, p := range paths { + roots[i] = fsys.Paths().Clean(p) + } + return &fsSource{fs: fsys, roots: roots, sym: sym} +} + +type fsSource struct { + fs vfs.FS + roots []string + sym SymlinkPolicy +} + +func (s *fsSource) Label() string { return s.fs.Label() } +func (s *fsSource) FS() vfs.FS { return s.fs } +func (s *fsSource) Roots() []string { return s.roots } + +// maxFollowDepth bounds FollowLinks recursion (design §4.3). +const maxFollowDepth = 40 + +func (s *fsSource) Walk(ctx context.Context, fn func(Item) error) error { + ops := s.fs.Paths() + for i, root := range s.roots { + base := ops.Base(root) + if base == "" || base == "." || base == ".." || base == string(ops.Sep()) { + return fmt.Errorf("transfer: cannot use %q as a source", root) + } + fi, err := s.fs.Lstat(ctx, root) + if err != nil { + return err + } + if err := s.walk(ctx, i, root, base, fi, 0, map[string]bool{}, fn); err != nil { + return err + } + } + return nil +} + +func (s *fsSource) walk(ctx context.Context, root int, p, rel string, fi vfs.FileInfo, depth int, + ancestors map[string]bool, fn func(Item) error) error { + if err := ctx.Err(); err != nil { + return err + } + it := Item{Rel: rel, Root: root, Src: p, Mode: fi.Mode, ModTime: fi.ModTime, Size: fi.Size} + follow := s.sym == FollowLinks && fi.IsSymlink() + var real string + if follow { + switch { + case fi.Target == nil: + it.Warning = "broken symlink copied as a link" + follow = false + case fi.Target.IsDir(): + rp, err := s.fs.RealPath(ctx, p) + if err != nil || ancestors[rp] || depth >= maxFollowDepth { + it.Warning = "symlink loop copied as a link" + follow = false + } else { + real = rp + } + } + if follow { + t := *fi.Target + it.Mode, it.ModTime, it.Size = t.Mode, t.ModTime, t.Size + } + } + switch { + case it.Mode.IsDir(): + it.Kind, it.Size = Dir, 0 + case it.Mode.IsRegular(): + it.Kind = File + case fi.IsSymlink() && !follow: + it.Kind, it.Size = Symlink, 0 + t, err := s.fs.ReadLink(ctx, p) + if err != nil { + return err + } + it.LinkTarget = t + default: + it.Kind, it.Size = Special, 0 + } + if it.Kind != Dir { + return fn(it) + } + + ents, err := s.fs.ReadDir(ctx, p) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + it.ScanErr = err + return fn(it) + } + if err := fn(it); err != nil { + return err + } + if s.sym == FollowLinks { + if real == "" { + if real, err = s.fs.RealPath(ctx, p); err != nil { + return err + } + } + ancestors[real] = true + defer delete(ancestors, real) + } + sort.Slice(ents, func(i, j int) bool { return ents[i].Name < ents[j].Name }) + ops := s.fs.Paths() + for _, e := range ents { + if strings.HasPrefix(e.Name, partPrefix) { + continue // leftovers of an interrupted transfer are never copied + } + if err := s.walk(ctx, root, ops.Join(p, e.Name), rel+"/"+e.Name, e, depth+1, ancestors, fn); err != nil { + return err + } + } + return nil +} + +func (s *fsSource) Open(ctx context.Context, it Item) (io.ReadCloser, error) { + return s.fs.Open(ctx, it.Src) +} + +func (s *fsSource) Stream(ctx context.Context, items []Item, fn func(Item, io.Reader) error) error { + for _, it := range items { + if err := ctx.Err(); err != nil { + return err + } + if it.Kind != File { + if err := fn(it, nil); err != nil { + return err + } + continue + } + f, err := s.Open(ctx, it) + if err != nil { + if err := fn(it, errReader{err}); err != nil { + return err + } + continue + } + err = fn(it, f) + f.Close() + if err != nil { + return err + } + } + return nil +} + +// errReader reports an open error through the first Read. +type errReader struct{ err error } + +func (r errReader) Read([]byte) (int, error) { return 0, r.err } diff --git a/internal/transfer/types.go b/internal/transfer/types.go new file mode 100644 index 0000000..d2d15ef --- /dev/null +++ b/internal/transfer/types.go @@ -0,0 +1,238 @@ +// Package transfer is the one engine for copy, move and unpack (design §4): +// Prepare walks the source once and plans every item, Execute writes each file +// through WriteAtomic (temp name + rename), merges directories, copies +// symlinks as links and asks the caller about conflicts and errors through +// Hooks. It works over any pair of vfs.FS. +// +// Invariants: the source is never modified by a copy; an existing target is +// replaced only by the final rename of a fully written temp file; after an +// error or cancellation no partial file is left under a target name; a move +// removes a source item only after it was copied; directories are never +// deleted to make room for a file. +package transfer + +import ( + "context" + "io/fs" + "time" + + "vcom/internal/vfs" +) + +// Op is what Execute does with the source. +type Op uint8 + +const ( + Copy Op = iota + Move +) + +// ConflictPolicy decides what happens when a target already exists. +type ConflictPolicy uint8 + +const ( + Ask ConflictPolicy = iota // Hooks.Resolve decides (Skip if nil) + Overwrite // replace files (never directories) + Skip // keep the target + OverwriteOlder // replace only if the source is newer + KeepBoth // write under a free "name (1).ext" +) + +// SymlinkPolicy: copy links as links (default) or copy what they point to. +type SymlinkPolicy uint8 + +const ( + CopyLinks SymlinkPolicy = iota + FollowLinks +) + +// ErrorPolicy decides what happens on an item error. +type ErrorPolicy uint8 + +const ( + ErrorAsk ErrorPolicy = iota // Hooks.OnError decides (Skip if nil) + ErrorSkipAll // record and continue + ErrorAbort // stop at the first error +) + +// FsyncPolicy decides when a written file is fsync'ed before its rename. +type FsyncPolicy uint8 + +const ( + FsyncReplace FsyncPolicy = iota // only when replacing an existing file + FsyncAlways + FsyncNever +) + +// Options tune a request. Use DefaultOptions for the defaults. +type Options struct { + Conflict ConflictPolicy + Symlinks SymlinkPolicy + OnError ErrorPolicy + Fsync FsyncPolicy + PreserveMode bool + PreserveTimes bool +} + +// DefaultOptions: ask on conflicts and errors, copy links as links, fsync +// before replacing, keep mode and mtime. +func DefaultOptions() Options { + return Options{PreserveMode: true, PreserveTimes: true} +} + +// ItemKind classifies a source item. +type ItemKind uint8 + +const ( + File ItemKind = iota + Dir + Symlink + Special // FIFO, socket, device: skipped with a warning +) + +func (k ItemKind) String() string { + switch k { + case File: + return "file" + case Dir: + return "dir" + case Symlink: + return "symlink" + } + return "special" +} + +// Item is one node of the plan. +type Item struct { + Rel string // path relative to ToDir, slash-separated; first element is the root's name + Kind ItemKind + Size int64 + Mode fs.FileMode + ModTime time.Time + LinkTarget string + Existing *vfs.FileInfo // what is at the target (Lstat); nil — nothing + Root int // index of the top-level source + + // Src is the item's path on the source FS (FSSource); empty for + // sources without one (archives). + Src string + // Warning is set by the source when the item is degraded, e.g. a + // symlink loop under FollowLinks copied as a link. + Warning string + // ScanErr: the directory could not be listed during Prepare; Execute + // reports it as the item's error. + ScanErr error +} + +// Request describes one transfer. +type Request struct { + Op Op + From Source + To vfs.FS + ToDir string + Opts Options +} + +// ConflictKind: same type on both sides, or file↔dir / link↔dir. +type ConflictKind uint8 + +const ( + FileFile ConflictKind = iota + TypeMismatch +) + +// Conflict is an item whose target exists. +type Conflict struct { + Item Item + Kind ConflictKind +} + +// ResolveAction answers a conflict. +type ResolveAction uint8 + +const ( + ResolveOverwrite ResolveAction = iota + ResolveSkip + ResolveKeepBoth + ResolveAbort +) + +// Resolution is the caller's answer to a conflict; ApplyToAll reuses it for +// every later conflict of the same ConflictKind. +type Resolution struct { + Action ResolveAction + ApplyToAll bool +} + +// Plan is the result of Prepare. +type Plan struct { + Req Request + Items []Item + TotalFiles int // files and symlinks + TotalBytes int64 + Conflicts []Conflict + Warnings []string + SameConn bool // From and To are the same connection (or both local) +} + +// Phase of a running transfer. +type Phase uint8 + +const ( + Scanning Phase = iota + Copying + Removing + Finishing +) + +// Progress is a snapshot; BytesTotal comes from Prepare, BytesDone counts +// processed bytes (copied plus skipped), so it reaches BytesTotal. +type Progress struct { + Phase Phase + FilesDone, FilesTotal int + BytesDone, BytesTotal int64 + Current string + CurrentDone int64 + CurrentSize int64 +} + +// ErrorAction answers an item error. +type ErrorAction uint8 + +const ( + ErrorRetry ErrorAction = iota + ErrorSkip + ErrorSkipRest // skip this and every later error + ErrorStop // abort the transfer +) + +// Hooks connect Execute to its caller (the jobs manager). +type Hooks struct { + // Progress is called after every chunk and item, at most once per + // ProgressInterval (default 50 ms), plus a final call per phase. + Progress func(Progress) + ProgressInterval time.Duration + Resolve func(ctx context.Context, c Conflict) (Resolution, error) + OnError func(ctx context.Context, e ItemError) (ErrorAction, error) +} + +// ItemError is a failed item. +type ItemError struct { + Item Item + Op string // "read", "write", "mkdir", "symlink", "rename", "remove", "scan", ... + Err error +} + +func (e ItemError) Error() string { return e.Op + " " + e.Item.Rel + ": " + e.Err.Error() } +func (e ItemError) Unwrap() error { return e.Err } + +// Report is the outcome of Execute. +type Report struct { + Done, Skipped, Failed int + Bytes int64 // bytes of completed files (copied, or moved by rename) + Errors []ItemError + Warnings []string + Cancelled bool + Affected []vfs.Location // directories that changed (to reload panels) + Err error // fatal: aborted, invalid plan +} diff --git a/internal/tui/actions.go b/internal/tui/actions.go new file mode 100644 index 0000000..c06e8de --- /dev/null +++ b/internal/tui/actions.go @@ -0,0 +1,148 @@ +package tui + +import ( + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" +) + +// actionDef is the handler of one action. +type actionDef struct { + Run func(a *App) tea.Cmd + // Enabled is checked before Run; an error is shown ("Unavailable: …") + // and Run is skipped. nil means always enabled. + Enabled func(a *App) error +} + +// actionTable maps actions to handlers. Features fill it in register_*.go. +type actionTable map[keys.ActionID]actionDef + +func (t actionTable) add(id keys.ActionID, run func(*App) tea.Cmd, enabled func(*App) error) { + t[id] = actionDef{Run: run, Enabled: enabled} +} + +// dispatch runs action id. +func (a *App) dispatch(id keys.ActionID) tea.Cmd { + def, ok := a.actions[id] + if !ok || def.Run == nil { + return a.notify(notify.Info, a.actionHelp(id)+": not available yet") + } + if def.Enabled != nil { + if err := def.Enabled(a); err != nil { + return a.notify(notify.Warn, "Unavailable: "+err.Error()) + } + } + return def.Run(a) +} + +func (a *App) actionHelp(id keys.ActionID) string { + for _, ctx := range keys.Contexts() { + for _, s := range a.keys.Help(ctx) { + for _, it := range s.Items { + if it.Action == id { + return it.Help + } + } + } + } + return string(id) +} + +// registerCore installs the actions of the 6.1 skeleton. +func registerCore(t actionTable) { + move := func(f func(p *panel.Model)) func(*App) tea.Cmd { + return func(a *App) tea.Cmd { + f(a.Active()) + return a.selectionChanged() + } + } + t.add(keys.NavUp, move(func(p *panel.Model) { p.MoveCursor(-1) }), nil) + t.add(keys.NavDown, move(func(p *panel.Model) { p.MoveCursor(1) }), nil) + t.add(keys.NavPageUp, move(func(p *panel.Model) { p.Page(-1, false) }), nil) + t.add(keys.NavPageDown, move(func(p *panel.Model) { p.Page(1, false) }), nil) + t.add(keys.NavHalfUp, move(func(p *panel.Model) { p.Page(-1, true) }), nil) + t.add(keys.NavHalfDown, move(func(p *panel.Model) { p.Page(1, true) }), nil) + t.add(keys.NavHome, move(func(p *panel.Model) { p.SetCursor(0) }), nil) + t.add(keys.NavEnd, move(func(p *panel.Model) { p.SetCursor(p.VisibleLen() - 1) }), nil) + t.add(keys.MarkToggle, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(1) }), nil) + t.add(keys.MarkUp, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(-1) }), nil) + t.add(keys.MarkDown, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(1) }), nil) + + t.add(keys.NavOpen, (*App).openSelected, nil) + t.add(keys.NavEnter, (*App).enterSelected, nil) + t.add(keys.NavParent, (*App).goParent, nil) + t.add(keys.NavBack, func(a *App) tea.Cmd { return a.history(false) }, nil) + t.add(keys.NavForward, func(a *App) tea.Cmd { return a.history(true) }, nil) + t.add(keys.PaneSwitch, func(a *App) tea.Cmd { + a.active = 1 - a.active + a.relayout() + return a.selectionChanged() + }, nil) + t.add(keys.PanesReload, func(a *App) tea.Cmd { return tea.Batch(a.reload(0), a.reload(1)) }, nil) + t.add(keys.ToggleHidden, func(a *App) tea.Cmd { + a.deps.Config.Browser.ShowHidden = !a.deps.Config.Browser.ShowHidden + o := a.panelOptions() + for _, p := range a.panels { + p.SetOptions(o) + } + if o.ShowHidden { + return a.notify(notify.Info, "Hidden files shown") + } + return a.notify(notify.Info, "Hidden files hidden") + }, nil) + t.add(keys.BrowseEscape, func(a *App) tea.Cmd { a.escapeLayer(); return a.selectionChanged() }, nil) + t.add(keys.BrowseCtrlC, func(a *App) tea.Cmd { + if a.escapeLayer() { + return a.selectionChanged() + } + return a.askQuit() + }, nil) + t.add(keys.FilterStart, (*App).startFilter, nil) + t.add(keys.ScreenInfo, func(a *App) tea.Cmd { return a.setScreen(ScreenInfo) }, nil) + t.add(keys.InfoClose, func(a *App) tea.Cmd { return a.setScreen(ScreenBrowse) }, nil) + t.add(keys.ScreenView, (*App).openView, nil) + t.add(keys.ThemeSelect, (*App).openThemeSelect, nil) + t.add(keys.HelpShow, (*App).openHelp, nil) + t.add(keys.LogShow, (*App).openLog, nil) + t.add(keys.AppQuit, (*App).askQuit, nil) + + // Viewer focus machine; stage 6.3 registers the full motion set. + t.add(keys.ViewerFocus, (*App).viewerFocus, nil) + t.add(keys.ViewerCaret, (*App).viewerCaret, nil) + t.add(keys.ViewerVisual, (*App).viewerVisual, nil) + t.add(keys.ViewerBack, (*App).viewerBack, nil) + t.add(keys.ViewerClose, (*App).viewerClose, nil) + t.add(keys.NativeSelect, (*App).toggleNativeSelect, nil) + t.add(keys.PreviewDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil) + t.add(keys.PreviewUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil) + t.add(keys.ViewerLineUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil) + t.add(keys.ViewerLineDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil) + t.add(keys.ViewerPageUp, func(a *App) tea.Cmd { a.viewer.Page(-1); return nil }, nil) + t.add(keys.ViewerPageDown, func(a *App) tea.Cmd { a.viewer.Page(1); return nil }, nil) + t.add(keys.ViewerTop, func(a *App) tea.Cmd { a.viewer.Jump(false); return nil }, nil) + t.add(keys.ViewerBottom, func(a *App) tea.Cmd { a.viewer.Jump(true); return nil }, nil) +} + +// escapeLayer drops the filter, then the marks of the active panel; it +// reports whether something was dropped (Esc never quits). +func (a *App) escapeLayer() bool { + p := a.Active() + if p.Filter() != "" { + p.SetFilter("") + return true + } + return p.ClearMarks() +} + +// notify pushes a note and schedules its expiry. +func (a *App) notify(l notify.Level, text string) tea.Cmd { + n := a.notes.Push(l, text, a.now()) + id := n.ID + return tea.Tick(notify.TTL(l), func(time.Time) tea.Msg { return noteExpiredMsg{id} }) +} + +type noteExpiredMsg struct{ id uint64 } diff --git a/internal/tui/app.go b/internal/tui/app.go new file mode 100644 index 0000000..4b5e13b --- /dev/null +++ b/internal/tui/app.go @@ -0,0 +1,186 @@ +// Package tui is the new user interface (design §7), enabled with +// --ui=next. The App is a tea.Model with an explicit mode machine (Screen × +// viewer focus × native selection × filter edit × modal stack); one +// function decides who owns the keyboard (inputOwner), keys resolve through +// the keys.Registry, every async result carries a Ticket and is dropped +// when stale, and View only reads state. +// +// Extension points for stages 6.2–6.6 (each feature in its own files): +// - actions: registerOps/registerViewer/registerSSH/registerArchive/ +// registerMisc add handlers to the action table (register_*.go); +// - messages: a.handle(fn) for the feature's own message types; +// - job events: a.onJob(fn) for jobs.Event; +// - key bindings: keys/bindings_.go; +// - modals: internal/tui/modal. +// +// Rules: Cmd functions never capture *App (only immutable inputs: Target, +// Ticket, options, leases); no file I/O outside vfs.FS (TestImportsGuard). +package tui + +import ( + "time" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/theme" + "vcom/internal/tui/keys" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/tui/style" + "vcom/internal/tui/viewer" +) + +// Screen is the main screen. +type Screen uint8 + +const ( + ScreenBrowse Screen = iota + ScreenInfo + ScreenView +) + +func (s Screen) String() string { + return [...]string{"browse", "info", "view"}[s] +} + +// App is the root model. +type App struct { + deps Deps + keys *keys.Registry + styles *style.Styles + theme string + + screen Screen + viewBack Screen + panels [2]*panel.Model + active int + filter *textinput.Model // non-nil while the filter line is edited + viewer viewer.Model + nativeSelect bool + modals modal.Stack + notes notify.Center + req Tracker + + w, h int + layout Layout + applied effects + + actions actionTable + handlers []func(*App, tea.Msg) (tea.Cmd, bool) + jobHooks []func(*App, jobEvent) tea.Cmd + jobSnaps map[uint64]jobSnap + + // openFile handles Enter on a non-directory entry; set by stage 6.5 + // (archives) and 6.6 (edit / run menu / xdg-open) in their hooks. + openFile func(*App, panel.Entry) tea.Cmd + + ops *opsState // file operations and archives (stages 6.2, 6.5) + misc *miscState // session, external programs (stage 6.6) + + previewFor string // what the viewer shows / is loading (location + name) + lastClick click + quitting bool +} + +type click struct { + at time.Time + pane, row int +} + +// New builds the App. Call Init (Bubble Tea does) to load the panels. +func New(d Deps) *App { + d.fill() + a := &App{deps: d, keys: keys.MustDefault(), jobSnaps: map[uint64]jobSnap{}} + a.setTheme(d.Config.UI.Theme) + if d.Config.Preview.WrapText { + a.viewer.ToggleWrap() + } + opts := a.panelOptions() + for i := range a.panels { + m := panel.NewMount(d.LocalFS, "/", nil, "", nil, nil) + a.panels[i] = panel.New(i, opts, []panel.Mount{m}, d.StartDirs[i]) + } + a.actions = actionTable{} + registerCore(a.actions) + registerOps(a.actions) + registerViewer(a.actions) + registerSSH(a.actions) + registerArchive(a.actions) + registerMisc(a.actions) + registerOpsHooks(a) + registerViewerHooks(a) + registerSSHHooks(a) + registerArchiveHooks(a) + registerMiscHooks(a) + return a +} + +func (a *App) panelOptions() panel.Options { + b := a.deps.Config.Browser + return panel.Options{ + ShowHidden: b.ShowHidden, + DirsFirst: b.DirsFirst, + SortBy: b.Sort.By, + Reverse: b.Sort.Reverse, + ShowSize: b.Columns.Size, + ShowTime: b.Columns.Modified, + HumanSize: b.HumanReadableSize, + } +} + +// setTheme switches the palette (unknown names fall back to the default). +func (a *App) setTheme(name string) { + p, err := theme.Resolve(name) + if err != nil { + p, _ = theme.Resolve("catppuccin-mocha") + name = p.Name + } + a.theme = name + a.styles = style.New(p) +} + +// Init loads both panels. +func (a *App) Init() tea.Cmd { + var cmds []tea.Cmd + if a.deps.Notice != "" { + cmds = append(cmds, a.notify(notify.Warn, a.deps.Notice)) + } + for i, p := range a.panels { + cmds = append(cmds, a.navigate(i, p.Here(), "", panel.NavReplace)) + } + cmds = append(cmds, a.reconcile(), a.miscInit()) + return tea.Batch(cmds...) +} + +// Active returns the active panel. +func (a *App) Active() *panel.Model { return a.panels[a.active] } + +// Passive returns the other panel. +func (a *App) Passive() *panel.Model { return a.panels[1-a.active] } + +// Panel returns panel i. +func (a *App) Panel(i int) *panel.Model { return a.panels[i] } + +// Screen returns the current screen. +func (a *App) Screen() Screen { return a.screen } + +// ThemeName is the theme in use. +func (a *App) ThemeName() string { return a.theme } + +// Viewer exposes the viewer model (tests, stage 6.3). +func (a *App) Viewer() *viewer.Model { return &a.viewer } + +// Quitting reports whether the user confirmed quitting. +func (a *App) Quitting() bool { return a.quitting } + +// handle registers a handler for feature messages; it returns true when it +// consumed the message. +func (a *App) handle(fn func(*App, tea.Msg) (tea.Cmd, bool)) { a.handlers = append(a.handlers, fn) } + +// onJob registers a job-event hook. +func (a *App) onJob(fn func(*App, jobEvent) tea.Cmd) { a.jobHooks = append(a.jobHooks, fn) } + +// now is the clock. +func (a *App) now() time.Time { return a.deps.Clock() } diff --git a/internal/tui/app_test.go b/internal/tui/app_test.go new file mode 100644 index 0000000..036119d --- /dev/null +++ b/internal/tui/app_test.go @@ -0,0 +1,536 @@ +package tui + +import ( + "context" + "fmt" + "math/rand" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/config" + "vcom/internal/testutil/fstree" + "vcom/internal/testutil/teadriver" + "vcom/internal/tui/keys" + "vcom/internal/tui/viewer" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +const settle = 3 * time.Second + +type harness struct { + t *testing.T + d *teadriver.Driver + app *App + dir string +} + +type opt func(*Deps) + +func newHarness(t *testing.T, fsys vfs.FS, dir string, opts ...opt) *harness { + t.Helper() + cfg := config.Default() + cfg.Behavior.ConfirmQuit = true + d := Deps{ + Config: cfg, + LocalFS: fsys, + StartDirs: [2]string{dir, dir}, + SetConfigKey: func(string, string, string, any) (string, error) { return "test.toml", nil }, + Opener: []string{"true"}, + Clipboard: func(string) error { return nil }, + } + for _, o := range opts { + o(&d) + } + app := New(d) + h := &harness{t: t, app: app, dir: dir} + h.d = teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(150*time.Millisecond)) + h.d.Settle(settle) + h.check() + return h +} + +func (h *harness) check() { + h.t.Helper() + if err := h.app.Invariants(); err != nil { + h.t.Fatalf("invariants: %v\n%s", err, h.d.Screen()) + } +} + +// press sends keys, settling and checking invariants after each. +func (h *harness) press(ks ...string) { + h.t.Helper() + for _, k := range ks { + h.d.Press(k) + h.d.Settle(settle) + h.check() + } +} + +func (h *harness) typ(s string) { + h.t.Helper() + h.d.Type(s) + h.d.Settle(settle) + h.check() +} + +func (h *harness) selected() string { + e, _ := h.app.Active().Selected() + return e.Name +} + +// cursorTo moves the active panel's cursor onto name. +func (h *harness) cursorTo(name string) { + h.t.Helper() + p := h.app.Active() + for i := 0; i < p.VisibleLen(); i++ { + if e, _ := p.Visible(i); e.Name == name { + p.SetCursor(i) + return + } + } + h.t.Fatalf("%s not in panel: %s", name, h.d.Screen()) +} + +func tree(t *testing.T, spec fstree.Spec) string { + t.Helper() + dir := t.TempDir() + fstree.Build(t, dir, spec) + return dir +} + +// gate blocks hooks until released. +type gate struct { + once sync.Once + ch chan struct{} +} + +func newGate(t *testing.T) *gate { + g := &gate{ch: make(chan struct{})} + t.Cleanup(g.open) + return g +} + +func (g *gate) open() { g.once.Do(func() { close(g.ch) }) } + +// N-P1-1, U-P1-9: a hung ReadDir must not block Update; Esc and q work. +func TestUpdateNeverBlocks(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("f", "x")}) + g := newGate(t) + fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpReadDir { + <-g.ch + } + return nil + }} + cfg := config.Default() + cfg.Behavior.ConfirmQuit = true + app := New(Deps{Config: cfg, LocalFS: fsys, StartDirs: [2]string{dir, dir}}) + d := teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(50*time.Millisecond)) + d.Settle(time.Second) // the listings hang + for _, k := range []string{"esc", "j", "tab", "o", "o", "q"} { + start := time.Now() + d.Press(k) + if el := time.Since(start); el > 10*time.Millisecond { + t.Errorf("Update(%s) took %v", k, el) + } + } + if !strings.Contains(d.Screen(), "Quit vcom?") { + t.Fatalf("quit dialog not shown while a listing hangs:\n%s", d.Screen()) + } + d.Press("q") + d.Settle(time.Second) + if !d.Quit() { + t.Fatal("q q did not quit while a listing hangs") + } + g.open() +} + +// U-P1-13: a listing that arrives after a newer navigation is dropped. +func TestStaleListingIgnored(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.Dir("a"), fstree.File("a/in-a", ""), fstree.Dir("b"), fstree.File("b/in-b", "")}) + g := newGate(t) + fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpReadDir && filepath.Base(p) == "a" { + <-g.ch + } + return nil + }} + h := newHarness(t, fsys, dir) + h.cursorTo("a") + h.press("enter") // hangs + if h.app.Active().Path() != dir { + t.Fatal("panel changed before its listing arrived") + } + h.cursorTo("b") + h.press("enter") + if got := h.app.Active().Path(); got != filepath.Join(dir, "b") { + t.Fatalf("path = %s", got) + } + g.open() + h.d.Settle(settle) + if got := h.app.Active().Path(); got != filepath.Join(dir, "b") { + t.Fatalf("stale listing of a applied: path = %s", got) + } + if h.selected() != "in-b" && !h.d.ScreenContains("in-b") { + t.Fatalf("b's content not shown:\n%s", h.d.Screen()) + } +} + +// U-P1-13: a stale preview (Image) must not knock the viewer out of Caret. +func TestStalePreviewDoesNotExitCaret(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a.txt", "line1\nline2"), fstree.File("b.png", "img")}) + g := newGate(t) + prev := func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) { + if fi.Name == "b.png" { + <-g.ch // ignores ctx on purpose: the result arrives late + return viewer.Content{Kind: viewer.Image, Title: "b.png"}, nil + } + return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"line1", "line2"}}, nil + } + h := newHarness(t, localfs.New(), dir, func(d *Deps) { d.Preview = prev }) + h.cursorTo("a.txt") + h.press("o") + if h.app.Viewer().Kind != viewer.Text { + t.Fatalf("preview of a.txt not loaded: %v", h.app.Viewer().Kind) + } + h.press("j") // b.png: its preview hangs + h.press("k") // back to a.txt + h.press("i") + if h.app.InputOwner() != keys.CtxCaret { + t.Fatalf("not in caret: %s", h.app.InputOwner()) + } + g.open() + h.d.Settle(settle) + h.check() + if h.app.InputOwner() != keys.CtxCaret || h.app.Viewer().Kind != viewer.Text { + t.Fatalf("stale preview changed the viewer: owner %s kind %v", h.app.InputOwner(), h.app.Viewer().Kind) + } +} + +func lockedFS(dir string) vfs.FS { + return &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpReadDir && filepath.Base(p) == "locked" { + return &os.PathError{Op: "open", Path: p, Err: vfs.ErrPermission} + } + return nil + }} +} + +// U-P1-8: a failed navigation leaves the panel as it was. +func TestNavErrorKeepsPanel(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.Dir("locked"), fstree.File("other", "")}) + h := newHarness(t, lockedFS(dir), dir) + h.cursorTo("locked") + before := h.app.Active().VisibleLen() + h.press("enter") + p := h.app.Active() + if p.Path() != dir || p.VisibleLen() != before || h.selected() != "locked" || p.Loading { + t.Fatalf("panel changed: path %s, %d entries, on %q", p.Path(), p.VisibleLen(), h.selected()) + } +} + +// U-P1-1: errors are visible in the status line. +func TestStatusLineShowsError(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.Dir("locked")}) + h := newHarness(t, lockedFS(dir), dir) + h.cursorTo("locked") + h.press("enter") + scr := h.d.Screen() + last := strings.Split(scr, "\n") + status := last[len(last)-2] + if !strings.Contains(status, "Cannot open") || !strings.Contains(status, "permission") { + t.Fatalf("status line = %q", status) + } + // It stays at least until a key is pressed. + h.d.Settle(settle) + if !h.d.ScreenContains("Cannot open") { + t.Fatal("error vanished without a key press") + } +} + +// U-P1-8: if the current directory vanishes, a refresh climbs to the +// nearest existing parent. +func TestVanishedDirClimbsUp(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.Dir("x/y/z"), fstree.File("x/keep", "")}) + deep := filepath.Join(dir, "x", "y", "z") + h := newHarness(t, localfs.New(), deep) + if err := os.RemoveAll(filepath.Join(dir, "x", "y")); err != nil { + t.Fatal(err) + } + h.press("ctrl+r") + if got := h.app.Active().Path(); got != filepath.Join(dir, "x") { + t.Fatalf("path = %s, want %s", got, filepath.Join(dir, "x")) + } + if got := h.app.Passive().Path(); got != filepath.Join(dir, "x") { + t.Fatalf("passive path = %s", got) + } + if !h.d.ScreenContains("vanished") { + t.Fatalf("no notice:\n%s", h.d.Screen()) + } +} + +// U-P1-16: q closes layers first; quitting needs confirmation; q q is fast. +func TestQClosesLayersThenConfirmsQuit(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("apple", ""), fstree.File("banana", "")}) + h := newHarness(t, localfs.New(), dir) + h.press("o") + if h.app.Screen() != ScreenInfo { + t.Fatal("o did not open Info") + } + h.press("q") + if h.app.Screen() != ScreenBrowse || h.d.Quit() { + t.Fatal("q in Info did not just close Info") + } + h.press("/") + h.typ("an") + h.press("enter") + if h.app.Active().Filter() != "an" { + t.Fatalf("filter = %q", h.app.Active().Filter()) + } + h.press("q") + if h.d.Quit() || !h.d.ScreenContains("Quit vcom?") { + t.Fatal("q in Browse quit without asking") + } + h.press("esc") + if h.d.Quit() || h.d.ScreenContains("Quit vcom?") { + t.Fatal("Esc in the quit dialog did not just close it") + } + h.press("esc") // drops the filter, never quits + if h.app.Active().Filter() != "" || h.d.Quit() { + t.Fatal("Esc did not drop the filter") + } + h.press("q", "q") + if !h.d.Quit() || !h.app.Quitting() { + t.Fatal("q q did not quit") + } +} + +// U-P1-6: PgDn moves a page. +func TestPgDn(t *testing.T) { + var spec fstree.Spec + for i := 0; i < 200; i++ { + spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), "")) + } + h := newHarness(t, localfs.New(), tree(t, spec)) + rows := h.app.Active().Rows() + if rows < 10 { + t.Fatalf("rows = %d", rows) + } + h.press("pgdown") + if c := h.app.Active().Cursor(); c != rows-1 { + t.Fatalf("cursor after PgDn = %d, want %d", c, rows-1) + } + h.press("pgdown", "pgup") + if c := h.app.Active().Cursor(); c != rows-1 { + t.Fatalf("cursor after PgDn PgUp = %d", c) + } + h.press("G") + if c := h.app.Active().Cursor(); c != 200 { // ".." + 200 files + t.Fatalf("G: cursor %d", c) + } +} + +func TestInvariantsAfterEachStep(t *testing.T) { + dir := tree(t, fstree.Spec{ + fstree.File("a.txt", "hello\nworld"), fstree.File("b.bin", "\x00\x01"), fstree.Dir("sub"), + fstree.File("sub/c.txt", "c"), fstree.Symlink("link", "sub"), + }) + seed := time.Now().UnixNano() + t.Logf("seed %d", seed) + rng := rand.New(rand.NewSource(seed)) + pool := []string{"j", "k", "o", "i", "v", "esc", "q", "/", "a", "enter", "tab", "ctrl+t", "f3", + "pgdown", "g", "G", "?", "t", "h", "l", "n", "y", "insert", "ctrl+c", "backspace", "W", "й", "п"} + cfg := config.Default() + cfg.Behavior.ConfirmQuit = true + app := New(Deps{Config: cfg, LocalFS: localfs.New(), StartDirs: [2]string{dir, dir}, + SetConfigKey: func(string, string, string, any) (string, error) { return "x", nil }, + Opener: []string{"true"}, Clipboard: func(string) error { return nil }}) + d := teadriver.New(t, app, 80, 24, teadriver.WithLongCmd(20*time.Millisecond)) + d.Settle(settle) + for i := 0; i < 400; i++ { + k := pool[rng.Intn(len(pool))] + d.Press(k) + d.Settle(settle) + if err := app.Invariants(); err != nil { + t.Fatalf("step %d (%q): %v", i, k, err) + } + _ = d.Screen() + } +} + +// Design §9.2: the theme is saved with config.SetKey (comments kept). +func TestThemeSelectPreservesConfigComments(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("f", "")}) + cfgPath := filepath.Join(t.TempDir(), "vcom.toml") + orig := "# my settings\n[ui]\n# the look\ntheme = \"nord\"\nshow_footer = true\n" + if err := os.WriteFile(cfgPath, []byte(orig), 0o600); err != nil { + t.Fatal(err) + } + h := newHarness(t, localfs.New(), dir, func(d *Deps) { + d.Config.UI.Theme = "nord" + d.ConfigPath = cfgPath + d.SetConfigKey = config.SetKey + }) + h.press("t", "down") + next := h.app.ThemeName() + if next == "nord" { + t.Fatal("no live preview") + } + h.press("enter") + data, _ := os.ReadFile(cfgPath) + got := string(data) + if !strings.Contains(got, "theme = \""+next+"\"") || !strings.Contains(got, "# my settings") || + !strings.Contains(got, "# the look") || !strings.Contains(got, "show_footer = true") { + t.Fatalf("config after save:\n%s", got) + } + // Esc reverts the live preview and writes nothing. + h.press("t", "down", "esc") + if h.app.ThemeName() != next { + t.Fatalf("Esc kept %s", h.app.ThemeName()) + } + if data2, _ := os.ReadFile(cfgPath); string(data2) != got { + t.Fatal("Esc wrote the config") + } +} + +// Crutch #10/#14: under a modal, the mouse does nothing to the panels. +func TestMouseUnderModalIgnored(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", ""), fstree.File("c", "")}) + h := newHarness(t, localfs.New(), dir) + h.press("q") + cur := h.app.Active().Cursor() + lr := h.app.listRect(0) + h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonLeft) + h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonWheelDown) + h.d.Settle(settle) + if h.app.Active().Cursor() != cur || h.app.active != 0 || !h.d.ScreenContains("Quit vcom?") { + t.Fatal("click under the modal acted") + } +} + +func TestMarksKeptOnTab(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", "")}) + h := newHarness(t, localfs.New(), dir) + h.cursorTo("a") + h.press("insert") + h.press("tab", "tab") + if h.app.Active().MarkCount() != 1 || !h.app.Active().Marked("a") { + t.Fatal("marks lost on Tab") + } + h.press("esc") + if h.app.Active().MarkCount() != 0 { + t.Fatal("Esc did not clear marks") + } +} + +// U-P1-4 through the App: a click picks the visible row under the mouse. +func TestFilterVisibleIndexAndMouseApp(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("abc", ""), fstree.File("bcd", ""), fstree.File("xyz", ""), fstree.File("xbz", "")}) + h := newHarness(t, localfs.New(), dir) + h.press("/") + h.typ("b") + h.press("enter") + lr := h.app.listRect(0) + h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft) // third row: "..", abc, bcd + h.d.Settle(settle) + if got := h.selected(); got != "bcd" { + t.Fatalf("clicked %q, want bcd\n%s", got, h.d.Screen()) + } + // A double click opens like Enter (here: a file → not available yet, no crash). + h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft) + h.d.Settle(settle) + h.check() +} + +// U-P1-5 through the App: Cyrillic goes into the filter as typed. +func TestTextContextPassesRunesApp(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.Dir("папка"), fstree.File("quit", "")}) + h := newHarness(t, localfs.New(), dir) + h.press("/") + h.typ("папка") + if got := h.app.Active().Filter(); got != "папка" { + t.Fatalf("filter = %q", got) + } + h.press("enter") + h.press("/") + h.typ("q") // a letter here, not quit + if h.d.Quit() || h.d.ScreenContains("Quit vcom?") { + t.Fatal("q in the filter line acted as a command") + } +} + +func TestNavigationHistoryAndParent(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.Dir("sub/deeper"), fstree.File("top", "")}) + h := newHarness(t, localfs.New(), dir) + h.cursorTo("sub") + h.press("l") + h.cursorTo("deeper") + h.press("enter") + if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") { + t.Fatal("enter failed") + } + h.press("h") + if h.app.Active().Path() != filepath.Join(dir, "sub") || h.selected() != "deeper" { + t.Fatalf("parent: %s on %q", h.app.Active().Path(), h.selected()) + } + h.press("[") + if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") { + t.Fatalf("back: %s", h.app.Active().Path()) + } + h.press("]") + if h.app.Active().Path() != filepath.Join(dir, "sub") { + t.Fatalf("forward: %s", h.app.Active().Path()) + } + h.press("?") + if !h.d.ScreenContains("Help") || !h.d.ScreenContains("history back") { + t.Fatalf("help:\n%s", h.d.Screen()) + } + h.press("esc") + _ = h.app.dispatch(keys.ActionID("test.unbound")) // an action without a handler: a note, no crash + if !h.d.ScreenContains("not available yet") { + t.Fatalf("no note for an unimplemented action:\n%s", h.d.Screen()) + } +} + +func TestViewScreenAndBack(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a.txt", "one\ntwo\nthree"), fstree.Dir("d")}) + h := newHarness(t, localfs.New(), dir) + h.cursorTo("d") + h.press("f3") + if h.app.Screen() != ScreenBrowse { + t.Fatal("F3 on a directory opened View") + } + h.cursorTo("a.txt") + h.press("f3") + if h.app.Screen() != ScreenView || !h.d.ScreenContains("three") { + t.Fatalf("View:\n%s", h.d.Screen()) + } + h.press("i", "v") + if h.app.InputOwner() != keys.CtxVisual { + t.Fatalf("owner %s", h.app.InputOwner()) + } + h.press("esc", "esc") + if h.app.InputOwner() != keys.CtxViewScroll { + t.Fatalf("owner %s", h.app.InputOwner()) + } + h.press("ctrl+t") + if !h.app.nativeSelect { + t.Fatal("ctrl+t") + } + h.press("esc") + if h.app.nativeSelect || h.app.Screen() != ScreenView { + t.Fatal("Esc must end native selection first") + } + h.press("q") + if h.app.Screen() != ScreenBrowse { + t.Fatal("q did not close View") + } +} diff --git a/internal/tui/archive_create.go b/internal/tui/archive_create.go new file mode 100644 index 0000000..02f5505 --- /dev/null +++ b/internal/tui/archive_create.go @@ -0,0 +1,87 @@ +package tui + +import ( + "context" + "errors" + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/archive" + "vcom/internal/jobs" + "vcom/internal/transfer" + "vcom/internal/tui/modal" + "vcom/internal/tui/panel" +) + +func (a *App) canCreateArchive() error { + p := a.Active() + switch { + case p.Source != panel.SourceDir: + return errors.New("nothing to archive here") + case p.FS().Caps().ReadOnly: + return errors.New("this panel is read-only (archive)") + } + if es, _ := p.Targets(); len(es) == 0 { + return errors.New("nothing selected") + } + return nil +} + +// createArchive is a: format list → name (proposed by archive.Name) → a +// job writing the archive into this panel's directory through +// archive.Create (temp + rename; never over or into a source: U-P0-1). +func (a *App) createArchive() tea.Cmd { + p := a.Active() + paths, names, _ := a.opTargets() + here := p.Here() + items := []modal.Item{ + {Label: "zip", Value: archive.Zip}, + {Label: "tar.gz", Value: archive.TarGz}, + {Label: "tar", Value: archive.Tar}, + } + a.openModal(modal.NewList("Archive format", items, nil), func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + f := o.Value.(archive.Format) + in := modal.NewInput("Create archive", modal.Field{Label: "Name", Value: archive.Name(names, f)}) + in.Text = fmt.Sprintf("%s → %s", describe(names), displayPath(here.Location())) + in.Validate = func(v []string) error { return validName(v[0]) } + a.openModal(in, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + name := o.Value.([]string)[0] + fsys := here.FS() + target := fsys.Paths().Join(here.Path, name) + fn := func(ctx context.Context, h *jobs.Handle) (any, error) { + rep := archive.Create(ctx, fsys, paths, fsys, target, f, transferHooks(h)) + if rep.Cancelled { + return rep, context.Canceled + } + return rep, rep.Err + } + return a.startJob("archive", "Archive "+name, fn, nil, holdMounts(here)...) + }) + return nil + }) + return nil +} + +// unpackJob indexes the archive, then runs the same plan → execute flow as +// copy, with the archive as the source (one pass over it). +func unpackJob(src panel.Target, archivePath string, to panel.Target, opts transfer.Options) jobs.Func { + return func(ctx context.Context, h *jobs.Handle) (any, error) { + h.SetProgress(jobs.Progress{Phase: "reading the archive index", Current: archivePath}) + idx, err := archive.IndexFile(ctx, src.FS(), archivePath, func(n int) { + h.SetProgress(jobs.Progress{Phase: "reading the archive index", Current: archivePath, FilesDone: n}) + }) + if err != nil { + return transfer.Report{Err: err}, err + } + req := transfer.Request{Op: transfer.Copy, From: archive.NewSource(src.FS(), archivePath, idx, nil), + To: to.FS(), ToDir: to.Path, Opts: opts} + return transferJob(req, "Extract", 0)(ctx, h) + } +} diff --git a/internal/tui/archive_mount.go b/internal/tui/archive_mount.go new file mode 100644 index 0000000..85c1881 --- /dev/null +++ b/internal/tui/archive_mount.go @@ -0,0 +1,77 @@ +package tui + +import ( + "context" + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/archive" + "vcom/internal/jobs" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" + "vcom/internal/vfs/archivefs" +) + +// isArchive reports whether the entry looks like an archive vcom can open. +func isArchive(e panel.Entry) bool { + if !e.IsRegularLike() { + return false + } + _, ok := archive.DetectFormat(e.Name) + return ok +} + +type mountResult struct { + Pane int + Origin panel.Target // where the archive file lies + Name string + Index *archive.Index +} + +// openArchive is Enter on an archive: a job indexes it (progress, cancel; +// the UI never waits — U-P1-9) and the panel enters it as a read-only +// mount; ".." from its root comes back with the cursor on the archive. +// Nothing is unpacked to a temp directory (U-P0-2). An archive on a remote +// FS is indexed and read over the connection. +func (a *App) openArchive(e panel.Entry) tea.Cmd { + p := a.Active() + pane, origin, name := a.active, p.Here(), e.Name + fsys, path := p.FS(), p.FS().Paths().Join(p.Path(), e.Name) + fn := func(ctx context.Context, h *jobs.Handle) (any, error) { + h.SetProgress(jobs.Progress{Phase: "reading the archive index", Current: path}) + idx, err := archive.IndexFile(ctx, fsys, path, func(n int) { + h.SetProgress(jobs.Progress{Phase: "reading the archive index", Current: path, FilesDone: n}) + }) + return mountResult{Pane: pane, Origin: origin, Name: name, Index: idx}, err + } + return a.startJob("mount", "Open "+name, fn, (*App).finishMount, holdMounts(origin)...) +} + +func (a *App) finishMount(s jobs.Snapshot) tea.Cmd { + res, _ := s.Result.(mountResult) + switch { + case s.State == jobs.Cancelled: + return nil + case s.Err != nil || res.Index == nil: + return a.notify(notify.Error, fmt.Sprintf("Cannot open %s: %v", res.Name, cleanErr(s.Err))) + } + p := a.panels[res.Pane] + if !p.Location().Same(res.Origin.Location()) { + return a.notify(notify.Info, res.Name+" indexed, but the panel moved on") + } + outer := res.Origin.FS() + afs := archivefs.New(outer, outer.Paths().Join(res.Origin.Path, res.Name), res.Index) + ret := res.Origin.Location() + m := panel.NewMount(afs, "/", &ret, res.Name, nil, nil) + t := panel.Target{Mounts: append(res.Origin.Mounts, m), Path: "/"} + var cmd tea.Cmd + if n := len(res.Index.Rejected); n > 0 { + cmd = a.notify(notify.Warn, fmt.Sprintf("%s: %d unsafe member name(s) ignored", res.Name, n)) + } + return tea.Batch(a.navigate(res.Pane, t, "", panel.NavPush), cmd) +} + +// inArchive reports whether the panel shows an archive. +func inArchive(p *panel.Model) bool { return p.FS().Kind() == vfs.KindArchive } diff --git a/internal/tui/archive_test.go b/internal/tui/archive_test.go new file mode 100644 index 0000000..d640f0c --- /dev/null +++ b/internal/tui/archive_test.go @@ -0,0 +1,196 @@ +package tui + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "vcom/internal/archive" + "vcom/internal/testutil/fstree" + "vcom/internal/transfer" + "vcom/internal/tui/modal" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +// makeArchive archives src/ into dir/. +func makeArchive(t *testing.T, src string, names []string, dst string, f archive.Format) { + t.Helper() + var paths []string + for _, n := range names { + paths = append(paths, filepath.Join(src, n)) + } + if rep := archive.Create(context.Background(), localfs.New(), paths, localfs.New(), dst, f, transfer.Hooks{}); rep.Err != nil { + t.Fatal(rep.Err) + } +} + +func (h *opsH) enterArchive(name string) { + h.t.Helper() + h.cursorTo(name) + h.press("enter") + h.until("archive mounted", func() bool { return inArchive(h.app.Active()) }) +} + +func archiveDir(t *testing.T) string { + dir := tree(t, fstree.Spec{fstree.File("src/inner/a.txt", "alpha"), fstree.File("src/b.txt", "beta"), fstree.File("w.txt", "w")}) + makeArchive(t, filepath.Join(dir, "src"), []string{"inner", "b.txt"}, filepath.Join(dir, "box.zip"), archive.Zip) + return dir +} + +// U-P0-2: inside an archive every mutating action is refused, and the +// archive panel is never a target. +func TestUP02_ArchivePaneReadOnlyActionsDisabled(t *testing.T) { + t.Setenv("TMPDIR", t.TempDir()) // the old UI extracted archives here + dir := archiveDir(t) + h := newOps(t, localfs.New(), dir, dir) + h.enterArchive("box.zip") + h.cursorTo("b.txt") + for _, k := range []string{"f6", "f7", "f8", "X", "f2", "a"} { + h.press(k) + if h.app.modals.Len() != 0 || h.mgr.Active() != 0 { + t.Fatalf("%s acted inside the archive", k) + } + } + h.press("tab") + h.cursorTo("w.txt") + h.press("f5") + if h.app.modals.Len() != 0 || !h.d.ScreenContains("read-only") { + t.Fatalf("copy into the archive not refused:\n%s", h.d.Screen()) + } + if ents, _ := os.ReadDir(os.TempDir()); len(ents) != 0 { + t.Fatalf("temp extraction dirs: %v", ents) + } + // Reading works: copy a member out of the archive. + h.press("tab") + h.cursorTo("b.txt") + h.press("tab") + h.press("tab") + h.press("f5") + h.waitDialog("Copy 1 item(s)?") + h.press("y") + h.idle() + // The other panel is dir itself: b.txt lands next to box.zip. + if read(t, filepath.Join(dir, "b.txt")) != "beta" { + t.Fatal("copy out of the archive failed") + } +} + +func TestLeaveArchiveCursorOnArchive(t *testing.T) { + dir := archiveDir(t) + h := newOps(t, localfs.New(), dir, dir) + h.enterArchive("box.zip") + h.cursorTo("inner") + h.press("enter") + if h.app.Active().Path() != "/inner" { + t.Fatalf("path %s", h.app.Active().Path()) + } + h.press("backspace", "backspace") + if inArchive(h.app.Active()) || h.app.Active().Path() != dir || h.selected() != "box.zip" { + t.Fatalf("left to %s on %q", h.app.Active().Path(), h.selected()) + } +} + +func TestEnterArchiveNonBlocking(t *testing.T) { + var spec fstree.Spec + for i := range 300 { + spec = append(spec, fstree.File(fmt.Sprintf("big/f%03d", i), "").WithSize(4<<10)) + } + dir := tree(t, spec) + makeArchive(t, dir, []string{"big"}, filepath.Join(dir, "big.tar.gz"), archive.TarGz) + slow := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error { + if op == vfstest.OpRead && filepath.Base(p) == "big.tar.gz" { + time.Sleep(2 * time.Millisecond) + } + return nil + }} + h := newOps(t, slow, dir, dir) + h.cursorTo("big.tar.gz") + start := time.Now() + h.d.Press("enter") + if el := time.Since(start); el > 20*time.Millisecond { + t.Fatalf("Enter on an archive took %v in Update (U-P1-9)", el) + } + h.d.Settle(settle) + if _, ok := h.app.modals.Top().(*modal.Progress); !ok { + t.Fatalf("no progress while indexing: %T", h.app.modals.Top()) + } + start = time.Now() + h.d.Press("j") // keys still handled (the progress modal owns them) + if el := time.Since(start); el > 20*time.Millisecond { + t.Fatalf("key took %v while indexing", el) + } + h.until("archive mounted", func() bool { return inArchive(h.app.Active()) }) + h.cursorTo("big") + h.press("enter") + if h.app.Active().VisibleLen() < 300 { + t.Fatalf("%d entries", h.app.Active().VisibleLen()) + } +} + +// U-P0-1 through the UI: archiving data.tar as tar into its own directory +// proposes the same name; Create refuses, the source stays intact. +func TestArchiveSameDirDoesNotDestroySource(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("data.tar", "").WithSize(64 << 10)}) + before := read(t, filepath.Join(dir, "data.tar")) + h := newOps(t, localfs.New(), dir, dir) + h.cursorTo("data.tar") + h.press("a", "j", "j", "enter") // format: tar + in, ok := h.app.modals.Top().(*modal.Input) + if !ok || in.Values()[0] != "data.tar" { + t.Fatalf("name input %T %v", h.app.modals.Top(), in) + } + h.press("enter") + h.idle() + if read(t, filepath.Join(dir, "data.tar")) != before { + t.Fatal("source destroyed (U-P0-1)") + } + if !h.d.ScreenContains("overwrite one of its sources") { + t.Fatalf("no error:\n%s", h.d.Screen()) + } + // Another name works and the archive is listed. + h.press("a", "enter", "enter") // zip, proposed name data.zip + h.idle() + if _, err := archive.IndexFile(context.Background(), localfs.New(), filepath.Join(dir, "data.zip"), nil); err != nil { + t.Fatalf("data.zip: %v", err) + } + found := false + for i := 0; i < h.app.Active().VisibleLen(); i++ { + e, _ := h.app.Active().Visible(i) + found = found || e.Name == "data.zip" + } + if !found { + t.Fatal("panel not reloaded after archiving") + } +} + +// N-P1-15: extracting into a remote panel. +func TestUnpackToRemotePane(t *testing.T) { + dir := archiveDir(t) + rdir := t.TempDir() + h := newOps(t, localfs.New(), dir, dir) + h.mountRemote(1, standFS(t), rdir) + h.cursorTo("box.zip") + h.press("e") + h.waitDialog("Extract") + h.press("y") + h.idle() + if read(t, filepath.Join(rdir, "inner", "a.txt")) != "alpha" || read(t, filepath.Join(rdir, "b.txt")) != "beta" { + t.Fatal("not extracted to the remote panel") + } + noParts(t, rdir) + // Again: the existing files are conflicts, not silent overwrites (U-P1-11). + h.press("e") + d := h.waitDialog("Extract") + if len(d.Buttons) < 3 { + t.Fatalf("plan dialog without conflict choices: %v", fieldsOf(d)) + } + h.press("s") // skip existing + h.idle() +} + +var _ = vfs.KindArchive diff --git a/internal/tui/archive_unpack.go b/internal/tui/archive_unpack.go new file mode 100644 index 0000000..b5d20ed --- /dev/null +++ b/internal/tui/archive_unpack.go @@ -0,0 +1,42 @@ +package tui + +import ( + "errors" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/transfer" +) + +// canUnpack: an archive under the cursor (or a panel inside an archive) +// and a writable directory in the other panel. +func (a *App) canUnpack() error { + if inArchive(a.Active()) { + return a.canTransfer(false) // extracting members = copying out of the archive FS + } + e, ok := a.Active().Selected() + if !ok || !isArchive(e) { + return errors.New("put the cursor on an archive") + } + dst := a.Passive() + if dst.FS().Caps().ReadOnly { + return errors.New("the other panel is read-only (archive)") + } + return a.canTransfer(false) +} + +// unpack is e/F11: extract the archive under the cursor into the other +// panel (any FS, N-P1-15) through the transfer engine: conflicts are asked, +// files are written via temp + rename, existing symlinks in the target are +// never written through (U-P1-11). Inside an archive it copies the marked +// members out. +func (a *App) unpack() tea.Cmd { + if inArchive(a.Active()) { + return a.startTransfer(transfer.Copy) + } + src, dst := a.Active(), a.Passive() + e, _ := src.Selected() + path := src.FS().Paths().Join(src.Path(), e.Name) + return a.startJob("unpack", "Extract "+e.Name, unpackJob(src.Here(), path, dst.Here(), a.transferOptions()), nil, + holdMounts(src.Here(), dst.Here())...) +} diff --git a/internal/tui/deps.go b/internal/tui/deps.go new file mode 100644 index 0000000..d3760cc --- /dev/null +++ b/internal/tui/deps.go @@ -0,0 +1,184 @@ +package tui + +import ( + "context" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + "unicode/utf8" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/config" + "vcom/internal/imgview" + "vcom/internal/jobs" + "vcom/internal/paths" + "vcom/internal/preview" + "vcom/internal/ssh/conn" + "vcom/internal/ssh/sshconfig" + "vcom/internal/state" + "vcom/internal/tui/viewer" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" +) + +// PreviewFunc is the small preview interface used by the skeleton and tests. +type PreviewFunc func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error) + +// PreviewBuildFunc builds a full preview, including highlighting, metadata, +// directory listings and remote images. +type PreviewBuildFunc func(ctx context.Context, req preview.Request) preview.Result + +// ImageApplier is the non-blocking side of imgview.Actor used by effects. +type ImageApplier interface { + Apply(imgview.Desired) +} + +// Deps are the App's outside world. Everything the UI touches goes through +// them, so tests substitute fakes (FaultFS, a fixed clock, a fake preview). +// This file and external.go are the only ones in internal/tui allowed to +// import os (TestImportsGuard). +type Deps struct { + Config config.Config + ConfigPath string // file the theme choice is written to ("" = default XDG path) + // SetConfigKey edits one key of the config file (default config.SetKey). + SetConfigKey func(path, section, key string, value any) (string, error) + + LocalFS vfs.FS + StartDirs [2]string // initial directories of the left and right panel + + Jobs *jobs.Manager + Pool *conn.Pool + Resolver *sshconfig.Resolver + + Preview PreviewFunc + BuildPreview PreviewBuildFunc + Image ImageApplier + Clock func() time.Time + // Notice is shown in the status line at start (config warnings). + Notice string + + // External programs and files (stage 6.6; defaults in external.go). + // Exec runs a foreground program (editor, Run) suspending the UI; + // tests run it synchronously. + Exec func(c *exec.Cmd, done tea.ExecCallback) tea.Cmd + // Opener is the "open with the desktop" command (xdg-open / open). + Opener []string + // RunDir holds temp files of this process (remote edit/open copies). + RunDir string + Getenv func(string) string + // Clipboard copies text (y). + Clipboard func(string) error + + // Session restored at start (nil = none) and how to save one. + Session *state.Session + SaveSession func(state.Session) error +} + +// DefaultDeps fills Deps for the real program. +func DefaultDeps(cfg config.Config, configPath string) Deps { + wd, err := os.Getwd() + if err != nil { + wd, _ = os.UserHomeDir() + } + left, right := wd, wd + if cfg.Startup.LeftPath != "" { + left = expandHome(cfg.Startup.LeftPath) + } + if cfg.Startup.RightPath != "" { + right = expandHome(cfg.Startup.RightPath) + } + d := Deps{ + Config: cfg, + ConfigPath: configPath, + LocalFS: localfs.New(), + StartDirs: [2]string{left, right}, + } + + tools := preview.FindTools() + results := preview.NewCache(32) + var images *preview.ImageCache + if dir, err := paths.CacheDir(); err == nil { + images, _ = preview.NewImageCache(filepath.Join(dir, "images"), 200<<20) + } + d.BuildPreview = func(ctx context.Context, req preview.Request) preview.Result { + req.Tools = tools + req.Images = images + return results.Build(ctx, req) + } + + // A saved session wins over the start paths (only directories that + // still exist; remote/archive panels were saved as their local place). + if s, err := state.Load(); err == nil && (s.Left.Path != "" || s.Right.Path != "") { + for i, ps := range []state.PaneSession{s.Left, s.Right} { + if fi, err := os.Stat(ps.Path); err == nil && fi.IsDir() { + d.StartDirs[i] = ps.Path + } + } + d.Session = &s + } + return d +} + +func expandHome(p string) string { + if p == "~" || strings.HasPrefix(p, "~/") { + if h, err := os.UserHomeDir(); err == nil { + return h + p[1:] + } + } + return p +} + +func (d *Deps) fill() { + if d.SetConfigKey == nil { + d.SetConfigKey = config.SetKey + } + if d.Clock == nil { + d.Clock = time.Now + } + if d.Preview == nil { + d.Preview = defaultPreview + } + if d.LocalFS == nil { + d.LocalFS = localfs.New() + } + fillExternal(d) + for i, p := range d.StartDirs { + if p == "" { + d.StartDirs[i] = "/" + } + } +} + +// defaultPreview is the lightweight fallback used by isolated UI tests. +func defaultPreview(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error) { + p := loc.FS.Paths().Join(loc.Path, fi.Name) + meta := viewer.Content{Kind: viewer.Other, Title: fi.Name, Lines: []string{ + fi.Name, + fi.Mode.String(), + fi.ModTime.Format("2006-01-02 15:04:05"), + }} + if !fi.IsRegularLike() { + return meta, nil + } + if maxBytes <= 0 { + maxBytes = 64 << 10 + } + f, err := loc.FS.Open(ctx, p) + if err != nil { + return viewer.Content{}, err + } + defer f.Close() + buf, err := io.ReadAll(io.LimitReader(f, maxBytes)) + if err != nil { + return viewer.Content{}, err + } + if !utf8.Valid(buf) || strings.ContainsRune(string(buf), 0) { + return meta, nil + } + lines := strings.Split(strings.TrimRight(string(buf), "\n"), "\n") + return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: lines, Plain: lines}, nil +} diff --git a/internal/tui/effects.go b/internal/tui/effects.go new file mode 100644 index 0000000..3c0b466 --- /dev/null +++ b/internal/tui/effects.go @@ -0,0 +1,106 @@ +package tui + +import ( + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/imgview" + "vcom/internal/tui/geom" + "vcom/internal/tui/notify" + "vcom/internal/tui/viewer" +) + +// Terminal side effects (mouse mode, image overlay) are not done in View or +// scattered in handlers: after every Update the desired state is compared +// with what was applied and commands fix the difference (design §7.9). + +const ( + mouseUnknown int8 = iota + mouseOn + mouseOff +) + +type effects struct { + mouse int8 + overlay imgview.Desired + overlaySeq uint64 + overlaySet bool +} + +type desiredEffects struct { + Mouse bool + Overlay imgview.Desired +} + +func (a *App) desired() desiredEffects { + d := desiredEffects{Mouse: !a.nativeSelect} + d.Overlay.Visible = (a.screen == ScreenInfo || a.screen == ScreenView) && + a.viewer.Kind == viewer.Image && a.viewer.Image != nil && a.modals.Len() == 0 + if a.viewer.Image != nil { + d.Overlay.Image = *a.viewer.Image + } + d.Overlay.Gen = a.viewer.Gen + var r geom.Rect + if a.screen == ScreenView { + r = geom.Rect{X: a.layout.Viewer.X, Y: a.layout.Viewer.Y + 1, W: a.layout.Viewer.W, H: max(0, a.layout.Viewer.H-1)} + } else if a.screen == ScreenInfo { + r = a.layout.PreviewBody + } + d.Overlay.Rect = imgview.Rect{X: r.X, Y: r.Y, W: r.W, H: r.H} + return d +} + +// reconcile returns commands that bring the terminal to the desired state. +func (a *App) reconcile() tea.Cmd { + d := a.desired() + var mouseCmd, imageCmd tea.Cmd + want := mouseOff + if d.Mouse { + want = mouseOn + } + if a.applied.mouse != want { + a.applied.mouse = want + if want == mouseOn { + mouseCmd = tea.EnableMouseCellMotion + } else { + mouseCmd = tea.DisableMouse + } + } + if a.deps.Image != nil && (!a.applied.overlaySet || !sameOverlay(a.applied.overlay, d.Overlay)) { + a.applied.overlaySeq++ + d.Overlay.Seq = a.applied.overlaySeq + a.applied.overlay, a.applied.overlaySet = d.Overlay, true + apply, overlay := a.deps.Image, d.Overlay + imageCmd = func() tea.Msg { + apply.Apply(overlay) + return nil + } + } + return tea.Batch(mouseCmd, imageCmd) +} + +func sameOverlay(a, b imgview.Desired) bool { + if a.Visible != b.Visible { + return false + } + if !a.Visible { + return true + } + return a.Rect == b.Rect && a.Gen == b.Gen && a.Image.Local == b.Image.Local && + a.Image.Size == b.Image.Size && a.Image.ModTime.Equal(b.Image.ModTime) +} + +// ImageEvent wraps an imgview event for delivery through tea.Program.Send. +func ImageEvent(e imgview.Event) tea.Msg { return imageEventMsg{event: e} } + +type imageEventMsg struct{ event imgview.Event } + +func (a *App) onImageEvent(m imageEventMsg) tea.Cmd { + if m.event.Err == nil { + return nil + } + text := "Image preview: " + m.event.Err.Error() + if m.event.Disabled { + text += " (backend disabled)" + } + return a.notify(notify.Warn, text) +} diff --git a/internal/tui/external.go b/internal/tui/external.go new file mode 100644 index 0000000..1769316 --- /dev/null +++ b/internal/tui/external.go @@ -0,0 +1,140 @@ +package tui + +// external.go is, with deps.go, the only file of internal/tui allowed to +// touch os and os/exec (TestImportsGuard): external programs (editor, Run, +// xdg-open) and the clipboard. + +import ( + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + + "github.com/atotto/clipboard" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/state" +) + +func fillExternal(d *Deps) { + if d.Exec == nil { + d.Exec = func(c *exec.Cmd, done tea.ExecCallback) tea.Cmd { return tea.ExecProcess(c, done) } + } + if len(d.Opener) == 0 { + d.Opener = []string{"xdg-open"} + if runtime.GOOS == "darwin" { + d.Opener = []string{"open"} + } + } + if d.Getenv == nil { + d.Getenv = os.Getenv + } + if d.RunDir == "" { + d.RunDir = os.TempDir() + } + if d.Clipboard == nil { + d.Clipboard = func(s string) error { + if err := clipboard.WriteAll(s); err == nil { + return nil + } + // No X/Wayland clipboard tool: OSC 52 (terminal clipboard). + _, err := fmt.Fprint(os.Stderr, ansi.SetSystemClipboard(s)) + return err + } + } + if d.SaveSession == nil { + d.SaveSession = state.Save + } +} + +// shellSplit splits a command line like a POSIX shell would for words: +// quotes and backslashes are honoured (U-P2: strings.Fields broke +// EDITOR="code --wait" with quoted paths). +func shellSplit(s string) ([]string, error) { + var out []string + var cur strings.Builder + inWord, quote := false, byte(0) + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case quote == '\'': + if c == '\'' { + quote = 0 + } else { + cur.WriteByte(c) + } + case quote == '"': + switch { + case c == '"': + quote = 0 + case c == '\\' && i+1 < len(s) && strings.ContainsRune(`"\$`+"`", rune(s[i+1])): + i++ + cur.WriteByte(s[i]) + default: + cur.WriteByte(c) + } + case c == '\'' || c == '"': + quote, inWord = c, true + case c == '\\' && i+1 < len(s): + i++ + cur.WriteByte(s[i]) + inWord = true + case c == ' ' || c == '\t' || c == '\n': + if inWord { + out = append(out, cur.String()) + cur.Reset() + inWord = false + } + default: + cur.WriteByte(c) + inWord = true + } + } + if quote != 0 { + return nil, errors.New("unterminated quote") + } + if inWord { + out = append(out, cur.String()) + } + return out, nil +} + +// editorCmd builds the editor command for a local file: $VISUAL, $EDITOR, +// else vi. +func editorCmd(getenv func(string) string, path string) (*exec.Cmd, error) { + line := getenv("VISUAL") + if strings.TrimSpace(line) == "" { + line = getenv("EDITOR") + } + if strings.TrimSpace(line) == "" { + line = "vi" + } + argv, err := shellSplit(line) + if err != nil || len(argv) == 0 { + return nil, fmt.Errorf("cannot parse $EDITOR %q: %v", line, err) + } + return exec.Command(argv[0], append(argv[1:], path)...), nil +} + +// runCmd runs a local executable in dir and waits for Enter afterwards so +// its output can be read (U-P1-3). +func runCmd(path, dir string) *exec.Cmd { + script := `"$0"; s=$?; printf '\n[exit %d] Press Enter to return to vcom' "$s"; read _` + c := exec.Command("sh", "-c", script, path) + c.Dir = dir + return c +} + +// openDetached starts the desktop opener and reaps it in the background: +// no zombie processes (U-P1-15). +func openDetached(opener []string, path string) error { + c := exec.Command(opener[0], append(opener[1:], path)...) + if err := c.Start(); err != nil { + return err + } + go func() { _ = c.Wait() }() + return nil +} diff --git a/internal/tui/external_edit.go b/internal/tui/external_edit.go new file mode 100644 index 0000000..641ebd3 --- /dev/null +++ b/internal/tui/external_edit.go @@ -0,0 +1,309 @@ +package tui + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/archive" + "vcom/internal/jobs" + "vcom/internal/transfer" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +// editFile is F4 (and Enter on text): local files go straight to the +// editor; a file on another FS is downloaded to the run dir, edited there +// and uploaded back with a check that it did not change on the server in +// the meantime (§7.12, N-P0-2). +func (a *App) editFile(loc vfs.Location, name string) tea.Cmd { + path := loc.FS.Paths().Join(loc.Path, name) + switch { + case loc.FS.Caps().ReadOnly: + return a.notify(notify.Warn, name+" is read-only here (archive): use F3 to view it") + case loc.FS.Kind() == vfs.KindLocal: + cmd, err := editorCmd(a.deps.Getenv, path) + if err != nil { + return a.notify(notify.Error, err.Error()) + } + return a.deps.Exec(cmd, func(err error) tea.Msg { return extDoneMsg{Loc: loc, What: "Editor", Err: err} }) + } + return a.startJob("edit-download", "Download "+name, downloadJob(loc, name, a.deps.LocalFS, a.deps.RunDir), + (*App).finishEditDownload, a.holdAt(loc)...) +} + +// holdAt keeps the mounts of a panel standing at loc for a job. +func (a *App) holdAt(loc vfs.Location) []jobs.Releaser { + if p := a.panelAt(loc); p != nil { + return holdMounts(p.Here()) + } + return nil +} + +func (a *App) canEdit() error { + p := a.Active() + e, ok := p.Selected() + switch { + case p.Source != panel.SourceDir || !ok || e.Parent || e.NavigableDir(): + return fmt.Errorf("put the cursor on a file") + case !e.IsRegularLike(): + return fmt.Errorf("%s is not a regular file", e.Name) + } + return nil +} + +func (a *App) editSelected() tea.Cmd { + p := a.Active() + e, _ := p.Selected() + return a.editFile(p.Location(), e.Name) +} + +// editCopy is a downloaded copy of a remote file. +type editCopy struct { + Loc vfs.Location // remote directory + Name string + LocalDir string // run-dir subdirectory holding the copy + Local string + Size int64 + ModTime time.Time + Stat vfs.FileInfo // of the server file when downloaded (mode) + Sum [32]byte + Open bool // for the desktop opener (no upload) +} + +// downloadJob copies loc/name into a private directory of runDir. +func downloadJob(loc vfs.Location, name string, local vfs.FS, runDir string) jobs.Func { + return func(ctx context.Context, h *jobs.Handle) (any, error) { + rp := loc.FS.Paths().Join(loc.Path, name) + fi, err := loc.FS.Stat(ctx, rp) + if err != nil { + return nil, err + } + var b [4]byte + _, _ = rand.Read(b[:]) + dir := local.Paths().Join(runDir, "edit-"+hex.EncodeToString(b[:])) + if err := local.Mkdir(ctx, dir, 0o700); err != nil { + return nil, err + } + c := editCopy{Loc: loc, Name: name, LocalDir: dir, Local: local.Paths().Join(dir, name), Size: fi.Size, ModTime: fi.ModTime, Stat: fi} + src, err := loc.FS.Open(ctx, rp) + if err != nil { + return nil, err + } + defer src.Close() + dst, err := local.Create(ctx, c.Local, 0o600, vfs.CreateExcl) + if err != nil { + return nil, err + } + sum := sha256.New() + n, err := io.Copy(io.MultiWriter(dst, sum), &progressCount{ctx: ctx, r: src, h: h, total: fi.Size, name: name}) + if cerr := dst.Close(); err == nil { + err = cerr + } + if err != nil { + _ = vfs.RemoveTree(context.WithoutCancel(ctx), local, dir, nil) + return nil, err + } + c.Size = n + copy(c.Sum[:], sum.Sum(nil)) + return c, nil + } +} + +type progressCount struct { + ctx context.Context + r io.Reader + h *jobs.Handle + n int64 + total int64 + name string +} + +func (p *progressCount) Read(b []byte) (int, error) { + if err := p.ctx.Err(); err != nil { + return 0, err + } + n, err := p.r.Read(b) + p.n += int64(n) + p.h.SetProgress(jobs.Progress{Phase: "downloading", Current: p.name, BytesDone: p.n, BytesTotal: p.total}) + return n, err +} + +func (a *App) finishEditDownload(s jobs.Snapshot) tea.Cmd { + c, ok := s.Result.(editCopy) + if !ok || s.Err != nil { + if s.State == jobs.Cancelled { + return nil + } + return a.notify(notify.Error, fmt.Sprintf("%s: %v", s.Title, cleanErr(s.Err))) + } + cmd, err := editorCmd(a.deps.Getenv, c.Local) + if err != nil { + return a.notify(notify.Error, err.Error()) + } + return a.deps.Exec(cmd, func(err error) tea.Msg { return remoteEditedMsg{Copy: c, Err: err} }) +} + +type remoteEditedMsg struct { + Copy editCopy + Err error +} + +func (a *App) onRemoteEdited(m remoteEditedMsg) tea.Cmd { + a.applied.mouse = mouseUnknown + c := m.Copy + var warn tea.Cmd + if m.Err != nil { + warn = a.notify(notify.Warn, "Editor: "+m.Err.Error()) + } + return tea.Batch(warn, a.startJob("edit-upload", "Upload "+c.Name, uploadJob(c, a.deps.LocalFS), (*App).finishEditUpload, a.holdAt(c.Loc)...)) +} + +type editUpload struct { + Copy editCopy + Outcome string // "unchanged", "uploaded", "copy", "kept" + Copied string // name of the copy saved beside +} + +// uploadJob writes the edited copy back with WriteAtomic. If the copy did +// not change, nothing is written. If the server file changed since the +// download, the user chooses: overwrite, save a copy beside, or keep the +// local copy (U-P1-12). +func uploadJob(c editCopy, local vfs.FS) jobs.Func { + return func(ctx context.Context, h *jobs.Handle) (any, error) { + res := editUpload{Copy: c} + data, sum, err := readAll(ctx, local, c.Local) + if err != nil { + return res, err + } + if sum == c.Sum { + res.Outcome = "unchanged" + _ = vfs.RemoveTree(ctx, local, c.LocalDir, nil) + return res, nil + } + fsys := c.Loc.FS + target := fsys.Paths().Join(c.Loc.Path, c.Name) + replace := true + if fi, err := fsys.Stat(ctx, target); err == nil && (fi.Size != c.Size || !fi.ModTime.Equal(c.ModTime)) { + d := &modal.Dialog{ + Title: "The file changed on the server", + Fields: []modal.KV{{Label: "File", Value: displayPath(vfs.Location{FS: fsys, Path: target})}, {Label: "Your copy", Value: c.Local}}, + Text: []string{"It was modified after you opened it."}, + Buttons: []modal.Button{ + {Label: "Overwrite", Key: "o", Value: "overwrite", Danger: true}, + {Label: "Save a copy beside", Key: "c", Value: "copy", Default: true}, + {Label: "Keep local copy", Key: "n", Cancel: true}, + }, + } + ans, err := h.Ask(ctx, askConfirm{D: d}) + if err != nil { + return res, err + } + switch ans { + case "overwrite": + case "copy": + free, err := archive.FreeName(ctx, fsys, target) + if err != nil { + return res, err + } + target, replace, res.Copied = free, false, fsys.Paths().Base(free) + default: + res.Outcome = "kept" + return res, nil + } + } + h.SetProgress(jobs.Progress{Phase: "uploading", Current: c.Name, BytesTotal: int64(len(data))}) + err = transfer.WriteAtomic(ctx, fsys, target, transfer.WriteOptions{Perm: c.Stat.Mode.Perm(), Replace: replace, Fsync: true}, + func(w io.Writer) error { _, err := w.Write(data); return err }) + if err != nil { + return res, err + } + res.Outcome = "uploaded" + if res.Copied != "" { + res.Outcome = "copy" + } + _ = vfs.RemoveTree(ctx, local, c.LocalDir, nil) + return res, nil + } +} + +func readAll(ctx context.Context, fsys vfs.FS, p string) ([]byte, [32]byte, error) { + f, err := fsys.Open(ctx, p) + if err != nil { + return nil, [32]byte{}, err + } + defer f.Close() + var buf bytes.Buffer + if _, err := io.Copy(&buf, f); err != nil { + return nil, [32]byte{}, err + } + return buf.Bytes(), sha256.Sum256(buf.Bytes()), nil +} + +func (a *App) finishEditUpload(s jobs.Snapshot) tea.Cmd { + res, _ := s.Result.(editUpload) + c := res.Copy + if s.Err != nil { + if s.State == jobs.Cancelled { + return a.notify(notify.Warn, fmt.Sprintf("Upload of %s cancelled; your copy: %s", c.Name, c.Local)) + } + return a.notify(notify.Error, fmt.Sprintf("Upload of %s failed: %v; your copy: %s", c.Name, cleanErr(s.Err), c.Local)) + } + reload := a.invalidate([]vfs.Location{c.Loc}) + switch res.Outcome { + case "unchanged": + return a.notify(notify.Info, c.Name+": no changes") + case "copy": + return tea.Batch(reload, a.notify(notify.Warn, fmt.Sprintf("%s changed on the server: your version saved as %s", c.Name, res.Copied))) + case "kept": + return a.notify(notify.Warn, fmt.Sprintf("%s not uploaded; your copy: %s", c.Name, c.Local)) + } + return tea.Batch(reload, a.notify(notify.Success, "Uploaded "+c.Name)) +} + +// openWithDesktop opens a file with xdg-open (reaped, no zombies: +// U-P1-15). A file on another FS (SSH, archive) is downloaded to the run +// dir first; edits of that copy are not synced back. +func (a *App) openWithDesktop(loc vfs.Location, name string) tea.Cmd { + if loc.FS.Kind() == vfs.KindLocal { + opener, path := a.deps.Opener, loc.FS.Paths().Join(loc.Path, name) + return func() tea.Msg { return openedMsg{Name: name, Err: openDetached(opener, path)} } + } + return a.startJob("open-download", "Download "+name, downloadJob(loc, name, a.deps.LocalFS, a.deps.RunDir), + func(a *App, s jobs.Snapshot) tea.Cmd { + c, ok := s.Result.(editCopy) + if !ok || s.Err != nil { + if s.State == jobs.Cancelled { + return nil + } + return a.notify(notify.Error, fmt.Sprintf("%s: %v", s.Title, cleanErr(s.Err))) + } + opener := a.deps.Opener + return func() tea.Msg { return openedMsg{Name: name, Copy: true, Err: openDetached(opener, c.Local)} } + }, a.holdAt(loc)...) +} + +type openedMsg struct { + Name string + Copy bool + Err error +} + +func (a *App) onOpened(m openedMsg) tea.Cmd { + switch { + case m.Err != nil: + return a.notify(notify.Error, fmt.Sprintf("Cannot open %s: %v", m.Name, m.Err)) + case m.Copy: + return a.notify(notify.Info, "Opened a local copy of "+m.Name+" (changes are not synced back)") + } + return a.notify(notify.Info, "Opened "+m.Name) +} diff --git a/internal/tui/geom/geom.go b/internal/tui/geom/geom.go new file mode 100644 index 0000000..138d5bd --- /dev/null +++ b/internal/tui/geom/geom.go @@ -0,0 +1,20 @@ +// Package geom holds the screen rectangles shared by layout, rendering and +// mouse hit-testing (one source of truth: design §7.3). +package geom + +// Rect is a cell rectangle; W or H of 0 means empty. +type Rect struct{ X, Y, W, H int } + +// Contains reports whether cell (x, y) is inside r. +func (r Rect) Contains(x, y int) bool { + return x >= r.X && x < r.X+r.W && y >= r.Y && y < r.Y+r.H +} + +// Empty reports whether r has no cells. +func (r Rect) Empty() bool { return r.W <= 0 || r.H <= 0 } + +// Center returns a w×h rectangle centered in r (clamped to r). +func (r Rect) Center(w, h int) Rect { + w, h = min(w, r.W), min(h, r.H) + return Rect{X: r.X + (r.W-w)/2, Y: r.Y + (r.H-h)/2, W: w, H: h} +} diff --git a/internal/tui/help.go b/internal/tui/help.go new file mode 100644 index 0000000..fc78b9d --- /dev/null +++ b/internal/tui/help.go @@ -0,0 +1,61 @@ +package tui + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/keys" + "vcom/internal/tui/modal" +) + +// openHelp shows the bindings of the context that owned input, generated +// from the registry (design §7.4). +func (a *App) openHelp() tea.Cmd { + ctx := a.inputOwner() + var lines []string + for i, s := range a.keys.Help(ctx) { + if i > 0 { + lines = append(lines, "") + } + lines = append(lines, "── "+s.Title+" ──") + w := 0 + for _, it := range s.Items { + w = max(w, ansi.StringWidth(it.Keys)) + } + for _, it := range s.Items { + lines = append(lines, fmt.Sprintf(" %s%s %s", it.Keys, strings.Repeat(" ", w-ansi.StringWidth(it.Keys)), it.Help)) + } + } + a.openModal(modal.NewText("Help: "+contextTitle(ctx), lines), nil) + return nil +} + +func contextTitle(c keys.Context) string { + switch c { + case keys.CtxBrowse: + return "panels" + case keys.CtxInfo: + return "info" + case keys.CtxViewScroll: + return "viewer" + } + return c.String() +} + +// openLog is "L": the message log, newest last. +func (a *App) openLog() tea.Cmd { + var lines []string + for _, n := range a.notes.Log() { + lines = append(lines, fmt.Sprintf("%s %-5s %s", n.At.Format("15:04:05"), n.Level, n.Text)) + } + if len(lines) == 0 { + lines = []string{"(no messages)"} + } + l := modal.NewText("Messages", lines) + a.openModal(l, nil) + l.Key(keys.ModalEnd, tea.KeyMsg{}) + return nil +} diff --git a/internal/tui/imports_test.go b/internal/tui/imports_test.go new file mode 100644 index 0000000..d9552b5 --- /dev/null +++ b/internal/tui/imports_test.go @@ -0,0 +1,119 @@ +package tui + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +// forbidden imports in internal/tui/** (design §7.13): the UI reaches files +// only through vfs.FS, so "forgot the remote case" cannot compile. +var forbidden = map[string]bool{ + "os": true, + "os/exec": true, + "io/fs": true, + "path/filepath": true, + "syscall": true, + "vcom/internal/vfs/localfs": true, + "github.com/pkg/sftp": true, + "vcom/internal/fs": true, + "vcom/internal/fs/remote": true, + "vcom/internal/ui": true, + "vcom/internal/homedir": true, + "github.com/atotto/clipboard": false, // allowed (clipboard.go, stage 6.3) +} + +// allowed files (relative to internal/tui): factories and external programs. +var importAllow = map[string]bool{ + "deps.go": true, + "external.go": true, +} + +func goFiles(t *testing.T) []string { + t.Helper() + var out []string + err := filepath.Walk(".", func(p string, fi os.FileInfo, err error) error { + if err != nil { + return err + } + if !fi.IsDir() && strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, "_test.go") { + out = append(out, p) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +func TestImportsGuard(t *testing.T) { + fset := token.NewFileSet() + files := goFiles(t) + if len(files) < 10 { + t.Fatalf("only %d files found", len(files)) + } + for _, p := range files { + f, err := parser.ParseFile(fset, p, nil, parser.ImportsOnly) + if err != nil { + t.Fatal(err) + } + for _, imp := range f.Imports { + path, _ := strconv.Unquote(imp.Path.Value) + if forbidden[path] && !importAllow[filepath.ToSlash(p)] { + t.Errorf("%s imports %s: go through vfs.FS / Deps instead", p, path) + } + } + } +} + +// Design §7.4: key strings are compared only in internal/tui/keys; elsewhere +// keys are resolved to actions. +func TestNoRawKeyMatching(t *testing.T) { + fset := token.NewFileSet() + for _, p := range goFiles(t) { + if strings.HasPrefix(filepath.ToSlash(p), "keys/") { + continue + } + f, err := parser.ParseFile(fset, p, nil, 0) + if err != nil { + t.Fatal(err) + } + ast.Inspect(f, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.BinaryExpr: + if x.Op == token.EQL || x.Op == token.NEQ { + if isStringCall(x.X) && isStringLit(x.Y) || isStringCall(x.Y) && isStringLit(x.X) { + t.Errorf("%s: msg.String() compared with a literal; use keys.Registry", fset.Position(x.Pos())) + } + } + case *ast.CallExpr: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Matches" { + if id, ok := sel.X.(*ast.Ident); ok && id.Name == "key" { + t.Errorf("%s: key.Matches; use keys.Registry", fset.Position(x.Pos())) + } + } + } + return true + }) + } +} + +func isStringCall(e ast.Expr) bool { + c, ok := e.(*ast.CallExpr) + if !ok || len(c.Args) != 0 { + return false + } + sel, ok := c.Fun.(*ast.SelectorExpr) + return ok && sel.Sel.Name == "String" +} + +func isStringLit(e ast.Expr) bool { + b, ok := e.(*ast.BasicLit) + return ok && b.Kind == token.STRING +} diff --git a/internal/tui/jobs.go b/internal/tui/jobs.go new file mode 100644 index 0000000..1df38cf --- /dev/null +++ b/internal/tui/jobs.go @@ -0,0 +1,87 @@ +package tui + +import ( + "fmt" + "sort" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/jobs" + "vcom/internal/tui/notify" +) + +// JobEvent wraps a jobs.Event for the program: main passes +// func(e jobs.Event) { program.Send(tui.JobEvent(e)) } as the jobs notify +// callback. +func JobEvent(e jobs.Event) tea.Msg { return jobEventMsg{E: e} } + +type jobEventMsg struct{ E jobs.Event } + +// jobEvent is what feature hooks receive. +type jobEvent = jobEventMsg + +type jobSnap = jobs.Snapshot + +// onJobEvent keeps snapshots for the status line and runs feature hooks +// (stage 6.2 opens progress/conflict modals there). Without a hook a +// finished job is reported in the status line. +func (a *App) onJobEvent(m jobEventMsg) tea.Cmd { + var cmds []tea.Cmd + switch e := m.E.(type) { + case jobs.Started: + a.jobSnaps[uint64(e.Snapshot.ID)] = e.Snapshot + case jobs.ProgressTick: + for _, s := range e.Snapshots { + a.jobSnaps[uint64(s.ID)] = s + } + case jobs.Finished: + delete(a.jobSnaps, uint64(e.Snapshot.ID)) + if len(a.jobHooks) == 0 { + cmds = append(cmds, a.reportJob(e.Snapshot)) + } + case jobs.Asked: + if len(a.jobHooks) == 0 { + cmds = append(cmds, a.notify(notify.Warn, fmt.Sprintf("Job %q is waiting for an answer", a.jobTitle(e.Question.Job)))) + } + } + for _, h := range a.jobHooks { + cmds = append(cmds, h(a, m)) + } + return tea.Batch(cmds...) +} + +func (a *App) jobTitle(id jobs.ID) string { + if s, ok := a.jobSnaps[uint64(id)]; ok { + return s.Title + } + return fmt.Sprint(id) +} + +func (a *App) reportJob(s jobs.Snapshot) tea.Cmd { + switch s.State { + case jobs.Done: + return a.notify(notify.Success, s.Title+": done") + case jobs.Cancelled: + return a.notify(notify.Warn, s.Title+": cancelled") + default: + return a.notify(notify.Error, fmt.Sprintf("%s: %v", s.Title, s.Err)) + } +} + +// activeJobs returns running/queued snapshots by ID. +func (a *App) activeJobs() []jobs.Snapshot { + out := make([]jobs.Snapshot, 0, len(a.jobSnaps)) + for _, s := range a.jobSnaps { + out = append(out, s) + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out +} + +// activeJobCount prefers the manager (authoritative) over snapshots. +func (a *App) activeJobCount() int { + if a.deps.Jobs != nil { + return a.deps.Jobs.Active() + } + return len(a.jobSnaps) +} diff --git a/internal/tui/keys/bindings_archive.go b/internal/tui/keys/bindings_archive.go new file mode 100644 index 0000000..47319c1 --- /dev/null +++ b/internal/tui/keys/bindings_archive.go @@ -0,0 +1,4 @@ +package keys + +// archiveBindings holds the extra bindings of archives (stage 6.5). +func archiveBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_browse.go b/internal/tui/keys/bindings_browse.go new file mode 100644 index 0000000..66b265c --- /dev/null +++ b/internal/tui/keys/bindings_browse.go @@ -0,0 +1,139 @@ +package keys + +// Browse/Info actions (design §8.1). +const ( + NavUp ActionID = "nav.up" + NavDown ActionID = "nav.down" + NavPageUp ActionID = "nav.pageUp" + NavPageDown ActionID = "nav.pageDown" + NavHalfUp ActionID = "nav.halfUp" + NavHalfDown ActionID = "nav.halfDown" + NavHome ActionID = "nav.home" + NavEnd ActionID = "nav.end" + NavOpen ActionID = "nav.open" // Enter: dispatch by entry type + NavEnter ActionID = "nav.enter" // l/→: enter directory or archive + NavParent ActionID = "nav.parent" // h/←/Backspace + NavBack ActionID = "nav.back" + NavForward ActionID = "nav.forward" + PaneSwitch ActionID = "pane.switch" + PaneMirror ActionID = "pane.mirror" + PanesReload ActionID = "panes.reload" + MarkToggle ActionID = "mark.toggle" // Insert: mark and move down + MarkUp ActionID = "mark.up" + MarkDown ActionID = "mark.down" + BrowseEscape ActionID = "browse.escape" // Esc: drop filter, then marks + BrowseCtrlC ActionID = "browse.ctrlC" // like Esc; quits from a clean Browse + DirSize ActionID = "dir.size" + FilterStart ActionID = "filter.start" + ToggleHidden ActionID = "view.hidden" + SortMenu ActionID = "sort.menu" + ScreenInfo ActionID = "screen.info" + ScreenView ActionID = "screen.view" + FileRename ActionID = "file.rename" + FileEdit ActionID = "file.edit" + FileCopy ActionID = "file.copy" + FileMove ActionID = "file.move" + FileMkdir ActionID = "file.mkdir" + FileTrash ActionID = "file.trash" + FileDelete ActionID = "file.delete" // permanent + ArchiveNew ActionID = "archive.create" + ArchiveUnzip ActionID = "archive.extract" + PathYank ActionID = "path.yank" + SSHHosts ActionID = "ssh.hosts" + ThemeSelect ActionID = "theme.select" + JobsList ActionID = "jobs.list" + LogShow ActionID = "log.show" + HelpShow ActionID = "help.show" + AppQuit ActionID = "app.quit" + + // Info only. + ViewerFocus ActionID = "viewer.focus" + PreviewDown ActionID = "preview.scrollDown" + PreviewUp ActionID = "preview.scrollUp" + NativeSelect ActionID = "viewer.nativeSelect" + InfoClose ActionID = "screen.infoClose" + FilterCommit ActionID = "filter.commit" + FilterCancel ActionID = "filter.cancel" + FilterClearAll ActionID = "filter.clear" +) + +// browseCommon is shared by Browse and Info (Info adds its own keys and +// closes on q/Esc instead of quitting). +func browseCommon() []Binding { + return []Binding{ + {Action: NavUp, Keys: []string{"up", "k"}, Help: "cursor up", Group: "Navigation"}, + {Action: NavDown, Keys: []string{"down", "j"}, Help: "cursor down", Group: "Navigation"}, + {Action: NavPageUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "Navigation"}, + {Action: NavPageDown, Keys: []string{"pgdown", "ctrl+f"}, Help: "page down", Group: "Navigation"}, + {Action: NavHalfUp, Keys: []string{"ctrl+u"}, Help: "half page up", Group: "Navigation"}, + {Action: NavHalfDown, Keys: []string{"ctrl+d"}, Help: "half page down", Group: "Navigation"}, + {Action: NavHome, Keys: []string{"home", "g"}, Help: "first entry", Group: "Navigation"}, + {Action: NavEnd, Keys: []string{"end", "G"}, Help: "last entry", Group: "Navigation"}, + {Action: NavOpen, Keys: []string{"enter"}, Help: "open", Group: "Navigation", Footer: true}, + {Action: NavEnter, Keys: []string{"right", "l"}, Help: "enter directory", Group: "Navigation"}, + {Action: NavParent, Keys: []string{"left", "h", "backspace"}, Help: "parent directory", Group: "Navigation"}, + {Action: NavBack, Keys: []string{"alt+left", "["}, Help: "history back", Group: "Navigation"}, + {Action: NavForward, Keys: []string{"alt+right", "]"}, Help: "history forward", Group: "Navigation"}, + {Action: PaneSwitch, Keys: []string{"tab"}, Help: "switch pane", Group: "Panels", Footer: true}, + {Action: PaneMirror, Keys: []string{"p"}, Help: "mirror: other pane to this place", Group: "Panels"}, + {Action: PanesReload, Keys: []string{"ctrl+r"}, Help: "reload panes", Group: "Panels"}, + {Action: MarkToggle, Keys: []string{"insert"}, Help: "mark and move down", Group: "Marks"}, + {Action: MarkUp, Keys: []string{"shift+up", "K"}, Help: "mark moving up", Group: "Marks"}, + {Action: MarkDown, Keys: []string{"shift+down", "J"}, Help: "mark moving down", Group: "Marks"}, + {Action: DirSize, Keys: []string{" "}, Help: "directory size", Group: "Files"}, + {Action: FilterStart, Keys: []string{"/"}, Help: "filter", Group: "Panels", Footer: true}, + {Action: ToggleHidden, Keys: []string{"."}, Help: "show hidden files", Group: "Panels"}, + {Action: SortMenu, Keys: []string{"S"}, Help: "sort menu", Group: "Panels"}, + {Action: ScreenView, Keys: []string{"f3", "v"}, Help: "view file", Group: "Files", Footer: true}, + {Action: FileRename, Keys: []string{"f2", "r"}, Help: "rename", Group: "Files"}, + {Action: FileEdit, Keys: []string{"f4"}, Help: "edit", Group: "Files", Footer: true}, + {Action: FileCopy, Keys: []string{"f5", "c"}, Help: "copy", Group: "Files", Footer: true}, + {Action: FileMove, Keys: []string{"f6", "m"}, Help: "move", Group: "Files", Footer: true}, + {Action: FileMkdir, Keys: []string{"f7", "n"}, Help: "make directory", Group: "Files", Footer: true}, + {Action: FileTrash, Keys: []string{"f8", "delete", "x"}, Help: "move to trash", Group: "Files", Footer: true}, + {Action: FileDelete, Keys: []string{"f20", "X"}, Help: "delete permanently", Group: "Files"}, + {Action: ArchiveNew, Keys: []string{"a"}, Help: "create archive", Group: "Files"}, + {Action: ArchiveUnzip, Keys: []string{"e", "f11"}, Help: "extract archive", Group: "Files"}, + {Action: PathYank, Keys: []string{"y"}, Help: "copy path to clipboard", Group: "Files"}, + {Action: SSHHosts, Keys: []string{"s", "f12"}, Help: "SSH hosts", Group: "Panels"}, + {Action: ThemeSelect, Keys: []string{"t"}, Help: "choose theme", Group: "Other"}, + {Action: JobsList, Keys: []string{"B"}, Help: "background jobs", Group: "Other"}, + {Action: LogShow, Keys: []string{"L"}, Help: "message log", Group: "Other"}, + {Action: HelpShow, Keys: []string{"f1", "?"}, Help: "help", Group: "Other", Footer: true}, + } +} + +func browseBindings() []Binding { + var out []Binding + for _, b := range browseCommon() { + b.Context = CtxBrowse + out = append(out, b) + } + out = append(out, + Binding{Context: CtxBrowse, Action: BrowseEscape, Keys: []string{"esc"}, Help: "clear filter, then marks", Group: "Marks"}, + Binding{Context: CtxBrowse, Action: BrowseCtrlC, Keys: []string{"ctrl+c"}}, + Binding{Context: CtxBrowse, Action: ScreenInfo, Keys: []string{"o", "f9"}, Help: "info / preview", Group: "Panels", Footer: true}, + Binding{Context: CtxBrowse, Action: AppQuit, Keys: []string{"q", "f10"}, Help: "quit", Group: "Other", Footer: true}, + ) + for _, b := range browseCommon() { + b.Context = CtxInfo + b.Footer = false + out = append(out, b) + } + out = append(out, + Binding{Context: CtxInfo, Action: InfoClose, Keys: []string{"o", "f9", "q", "f10", "esc", "ctrl+c"}, Help: "close info", Group: "Info", Footer: true}, + Binding{Context: CtxInfo, Action: ViewerFocus, Keys: []string{"i"}, Help: "cursor in preview", Group: "Info", Footer: true}, + Binding{Context: CtxInfo, Action: PreviewDown, Keys: []string{"ctrl+e"}, Help: "scroll preview down", Group: "Info"}, + Binding{Context: CtxInfo, Action: PreviewUp, Keys: []string{"ctrl+y"}, Help: "scroll preview up", Group: "Info"}, + Binding{Context: CtxInfo, Action: NativeSelect, Keys: []string{"ctrl+t"}, Help: "select with the terminal mouse", Group: "Info"}, + ) + // Filter line (text context): only control keys. + out = append(out, + Binding{Context: CtxFilterEdit, Action: FilterCommit, Keys: []string{"enter"}, Help: "keep filter", Group: "Filter", Footer: true}, + Binding{Context: CtxFilterEdit, Action: FilterCancel, Keys: []string{"esc", "ctrl+c"}, Help: "drop filter", Group: "Filter", Footer: true}, + Binding{Context: CtxFilterEdit, Action: FilterClearAll, Keys: []string{"ctrl+u"}, Help: "clear text", Group: "Filter"}, + Binding{Context: CtxFilterEdit, Action: NavUp, Keys: []string{"up"}, Help: "cursor up", Group: "Filter"}, + Binding{Context: CtxFilterEdit, Action: NavDown, Keys: []string{"down"}, Help: "cursor down", Group: "Filter"}, + ) + return out +} diff --git a/internal/tui/keys/bindings_misc.go b/internal/tui/keys/bindings_misc.go new file mode 100644 index 0000000..b9e2ed0 --- /dev/null +++ b/internal/tui/keys/bindings_misc.go @@ -0,0 +1,4 @@ +package keys + +// miscBindings holds the extra bindings of stage 6.6 (sort menu, run menu). +func miscBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_modal.go b/internal/tui/keys/bindings_modal.go new file mode 100644 index 0000000..2b26699 --- /dev/null +++ b/internal/tui/keys/bindings_modal.go @@ -0,0 +1,42 @@ +package keys + +// Actions shared by modal contexts (design §8.4). Dialog button hotkeys are +// not in the table: a Dialog matches them itself (see Translate). +const ( + ModalConfirm ActionID = "modal.confirm" + ModalCancel ActionID = "modal.cancel" + ModalNext ActionID = "modal.next" + ModalPrev ActionID = "modal.prev" + ModalUp ActionID = "modal.up" + ModalDown ActionID = "modal.down" + ModalPgUp ActionID = "modal.pageUp" + ModalPgDown ActionID = "modal.pageDown" + ModalHome ActionID = "modal.home" + ModalEnd ActionID = "modal.end" + ModalClear ActionID = "modal.clear" +) + +func modalBindings() []Binding { + d, in, l := CtxModalDialog, CtxModalInput, CtxModalList + return []Binding{ + {Context: d, Action: ModalConfirm, Keys: []string{"enter"}, Help: "press focused button", Group: "Dialog", Footer: true}, + {Context: d, Action: ModalNext, Keys: []string{"tab", "right", "l"}, Help: "next button", Group: "Dialog"}, + {Context: d, Action: ModalPrev, Keys: []string{"shift+tab", "left", "h"}, Help: "previous button", Group: "Dialog"}, + {Context: d, Action: ModalCancel, Keys: []string{"esc", "ctrl+c", "q"}, Help: "cancel", Group: "Dialog", Footer: true}, + + {Context: in, Action: ModalConfirm, Keys: []string{"enter"}, Help: "OK", Group: "Input", Footer: true}, + {Context: in, Action: ModalCancel, Keys: []string{"esc", "ctrl+c"}, Help: "cancel", Group: "Input", Footer: true}, + {Context: in, Action: ModalNext, Keys: []string{"tab", "down"}, Help: "next field", Group: "Input"}, + {Context: in, Action: ModalPrev, Keys: []string{"shift+tab", "up"}, Help: "previous field", Group: "Input"}, + {Context: in, Action: ModalClear, Keys: []string{"ctrl+u"}, Help: "clear field", Group: "Input"}, + + {Context: l, Action: ModalUp, Keys: []string{"up", "k"}, Help: "up", Group: "List"}, + {Context: l, Action: ModalDown, Keys: []string{"down", "j"}, Help: "down", Group: "List"}, + {Context: l, Action: ModalPgUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "List"}, + {Context: l, Action: ModalPgDown, Keys: []string{"pgdown", "ctrl+f", " "}, Help: "page down", Group: "List"}, + {Context: l, Action: ModalHome, Keys: []string{"home", "g"}, Help: "first", Group: "List"}, + {Context: l, Action: ModalEnd, Keys: []string{"end", "G"}, Help: "last", Group: "List"}, + {Context: l, Action: ModalConfirm, Keys: []string{"enter"}, Help: "choose", Group: "List", Footer: true}, + {Context: l, Action: ModalCancel, Keys: []string{"esc", "q", "ctrl+c", "f1", "?"}, Help: "close", Group: "List", Footer: true}, + } +} diff --git a/internal/tui/keys/bindings_ops.go b/internal/tui/keys/bindings_ops.go new file mode 100644 index 0000000..5384899 --- /dev/null +++ b/internal/tui/keys/bindings_ops.go @@ -0,0 +1,17 @@ +package keys + +// Actions of the progress modal (stage 6.2). +const ( + ProgressBackground ActionID = "progress.background" + ProgressCancel ActionID = "progress.cancel" +) + +// opsBindings holds the extra bindings of file operations (stage 6.2: +// progress modal). Browse keys live in bindings_browse.go. +func opsBindings() []Binding { + p := CtxModalProgress + return []Binding{ + {Context: p, Action: ProgressBackground, Keys: []string{"esc", "b", "enter"}, Help: "continue in the background", Group: "Progress", Footer: true}, + {Context: p, Action: ProgressCancel, Keys: []string{"c", "ctrl+c"}, Help: "cancel the operation (asks)", Group: "Progress", Footer: true}, + } +} diff --git a/internal/tui/keys/bindings_ssh.go b/internal/tui/keys/bindings_ssh.go new file mode 100644 index 0000000..0736138 --- /dev/null +++ b/internal/tui/keys/bindings_ssh.go @@ -0,0 +1,5 @@ +package keys + +// sshBindings holds the extra bindings of SSH (stage 6.4: host list, +// prompts). Browse keys live in bindings_browse.go. +func sshBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_viewer.go b/internal/tui/keys/bindings_viewer.go new file mode 100644 index 0000000..785a781 --- /dev/null +++ b/internal/tui/keys/bindings_viewer.go @@ -0,0 +1,76 @@ +package keys + +// Viewer actions (design §8.2). +const ( + ViewerLineUp ActionID = "viewer.lineUp" + ViewerLineDown ActionID = "viewer.lineDown" + ViewerPageUp ActionID = "viewer.pageUp" + ViewerPageDown ActionID = "viewer.pageDown" + ViewerHalfUp ActionID = "viewer.halfUp" + ViewerHalfDown ActionID = "viewer.halfDown" + ViewerLeft ActionID = "viewer.left" + ViewerRight ActionID = "viewer.right" + ViewerWordNext ActionID = "viewer.wordNext" + ViewerWordPrev ActionID = "viewer.wordPrev" + ViewerWordEnd ActionID = "viewer.wordEnd" + ViewerLineStart ActionID = "viewer.lineStart" + ViewerFirstNonBlank ActionID = "viewer.firstNonBlank" + ViewerLineEnd ActionID = "viewer.lineEnd" + ViewerTop ActionID = "viewer.top" + ViewerBottom ActionID = "viewer.bottom" + ViewerCaret ActionID = "viewer.caret" + ViewerVisual ActionID = "viewer.visual" + ViewerYank ActionID = "viewer.yank" + ViewerYankLine ActionID = "viewer.yankLine" + ViewerWrap ActionID = "viewer.wrap" + ViewerBack ActionID = "viewer.back" // Esc: one focus step back + ViewerClose ActionID = "viewer.close" // q/F3: close View / unfocus Info +) + +func viewerBindings() []Binding { + motion := func(ctx Context) []Binding { + return []Binding{ + {Context: ctx, Action: ViewerLineUp, Keys: []string{"up", "k"}, Help: "up", Group: "Viewer"}, + {Context: ctx, Action: ViewerLineDown, Keys: []string{"down", "j"}, Help: "down", Group: "Viewer"}, + {Context: ctx, Action: ViewerLeft, Keys: []string{"left", "h"}, Help: "left", Group: "Viewer"}, + {Context: ctx, Action: ViewerRight, Keys: []string{"right", "l"}, Help: "right", Group: "Viewer"}, + {Context: ctx, Action: ViewerPageUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "Viewer"}, + {Context: ctx, Action: ViewerPageDown, Keys: []string{"pgdown", "ctrl+f"}, Help: "page down", Group: "Viewer"}, + {Context: ctx, Action: ViewerHalfUp, Keys: []string{"ctrl+u"}, Help: "half page up", Group: "Viewer"}, + {Context: ctx, Action: ViewerHalfDown, Keys: []string{"ctrl+d"}, Help: "half page down", Group: "Viewer"}, + {Context: ctx, Action: ViewerTop, Keys: []string{"home", "g"}, Help: "top", Group: "Viewer"}, + {Context: ctx, Action: ViewerBottom, Keys: []string{"end", "G"}, Help: "bottom", Group: "Viewer"}, + {Context: ctx, Action: ViewerWrap, Keys: []string{"W"}, Help: "wrap lines", Group: "Viewer"}, + {Context: ctx, Action: NativeSelect, Keys: []string{"ctrl+t"}, Help: "select with the terminal mouse", Group: "Viewer"}, + {Context: ctx, Action: ViewerBack, Keys: []string{"esc"}, Help: "back", Group: "Viewer", Footer: true}, + {Context: ctx, Action: ViewerClose, Keys: []string{"q", "f3", "ctrl+c"}, Help: "close", Group: "Viewer", Footer: true}, + } + } + var out []Binding + out = append(out, motion(CtxViewScroll)...) + out = append(out, + Binding{Context: CtxViewScroll, Action: ViewerCaret, Keys: []string{"i"}, Help: "cursor mode", Group: "Viewer", Footer: true}, + Binding{Context: CtxViewScroll, Action: ViewerVisual, Keys: []string{"v"}, Help: "visual selection", Group: "Viewer"}, + ) + out = append(out, motion(CtxCaret)...) + out = append(out, + Binding{Context: CtxCaret, Action: ViewerVisual, Keys: []string{"v"}, Help: "visual selection", Group: "Viewer", Footer: true}, + Binding{Context: CtxCaret, Action: ViewerYankLine, Keys: []string{"y y"}, Help: "copy line", Group: "Viewer", Footer: true}, + ) + out = append(out, motion(CtxVisual)...) + out = append(out, + Binding{Context: CtxVisual, Action: ViewerCaret, Keys: []string{"v"}, Help: "end selection", Group: "Viewer"}, + Binding{Context: CtxVisual, Action: ViewerYank, Keys: []string{"y"}, Help: "copy selection", Group: "Viewer", Footer: true}, + ) + for _, ctx := range []Context{CtxCaret, CtxVisual} { + out = append(out, + Binding{Context: ctx, Action: ViewerWordNext, Keys: []string{"w"}, Help: "next word", Group: "Viewer"}, + Binding{Context: ctx, Action: ViewerWordPrev, Keys: []string{"b"}, Help: "previous word", Group: "Viewer"}, + Binding{Context: ctx, Action: ViewerWordEnd, Keys: []string{"e"}, Help: "end of word", Group: "Viewer"}, + Binding{Context: ctx, Action: ViewerLineStart, Keys: []string{"0"}, Help: "start of line", Group: "Viewer"}, + Binding{Context: ctx, Action: ViewerFirstNonBlank, Keys: []string{"^"}, Help: "first non-blank", Group: "Viewer"}, + Binding{Context: ctx, Action: ViewerLineEnd, Keys: []string{"$"}, Help: "end of line", Group: "Viewer"}, + ) + } + return out +} diff --git a/internal/tui/keys/defaults.go b/internal/tui/keys/defaults.go new file mode 100644 index 0000000..840198d --- /dev/null +++ b/internal/tui/keys/defaults.go @@ -0,0 +1,34 @@ +package keys + +import "unicode" + +// DefaultBindings collects the bindings of every feature file. Features add +// their own bindings_.go so parallel work does not touch one file. +func DefaultBindings() []Binding { + var out []Binding + for _, part := range [][]Binding{ + browseBindings(), modalBindings(), viewerBindings(), + opsBindings(), sshBindings(), archiveBindings(), miscBindings(), + } { + out = append(out, part...) + } + return out +} + +// Translate maps a key typed in the ЙЦУКЕН layout to its QWERTY name, for +// matching per-modal hotkeys (dialog buttons) the same way Resolve does. +// Other keys are returned unchanged. +func Translate(k string) string { + rs := []rune(k) + if len(rs) != 1 { + return k + } + q, ok := jcuken[unicode.ToLower(rs[0])] + if !ok { + return k + } + if unicode.IsUpper(rs[0]) { + q = unicode.ToUpper(q) + } + return string(q) +} diff --git a/internal/tui/keys/keys.go b/internal/tui/keys/keys.go new file mode 100644 index 0000000..b21f93e --- /dev/null +++ b/internal/tui/keys/keys.go @@ -0,0 +1,308 @@ +// Package keys is the single key-routing table of the new UI (design §7.4, +// §8): actions are named by ActionID, bound per input Context, and resolved +// from tea.KeyMsg in one place. Help and the footer are generated from the +// same table, so they cannot drift from what the keys do. +// +// Command contexts also accept keys typed in the Russian ЙЦУКЕН layout +// (й→q, …); text contexts (filter line, input fields) never translate and +// let everything except a few control keys through to the text field +// (U-P1-5: "папка" stays "папка"). +package keys + +import ( + "fmt" + "sort" + "strings" + + tea "github.com/charmbracelet/bubbletea" +) + +// ActionID names an action: "nav.down", "file.copy", "viewer.visual", ... +type ActionID string + +// Pending is returned by Resolve when the key started a chord ("y" of +// "y y"); the caller does nothing and waits for the next key. +const Pending ActionID = "keys.pending" + +// Context is who owns the keyboard right now (see App.inputOwner). +type Context uint8 + +const ( + CtxBrowse Context = iota + CtxInfo + CtxFilterEdit + CtxViewScroll + CtxCaret + CtxVisual + CtxModalDialog + CtxModalInput + CtxModalList + CtxModalProgress + CtxModalConflict + CtxModalPrompt + numContexts +) + +// Contexts lists every context (for tests and help). +func Contexts() []Context { + out := make([]Context, numContexts) + for i := range out { + out[i] = Context(i) + } + return out +} + +var ctxNames = [...]string{ + "browse", "info", "filter", "view", "caret", "visual", + "dialog", "input", "list", "progress", "conflict", "prompt", +} + +func (c Context) String() string { + if int(c) < len(ctxNames) { + return ctxNames[c] + } + return fmt.Sprintf("Context(%d)", uint8(c)) +} + +// IsText reports whether c edits text: only a few control keys are bound, +// everything else goes to the text field untranslated. +func (c Context) IsText() bool { + return c == CtxFilterEdit || c == CtxModalInput || c == CtxModalPrompt +} + +// textKeys are the only keys a text context may bind. +var textKeys = map[string]bool{ + "enter": true, "esc": true, "tab": true, "shift+tab": true, + "up": true, "down": true, "ctrl+c": true, "ctrl+u": true, +} + +// Binding binds keys to an action in one context. +type Binding struct { + Context Context + Action ActionID + // Keys in tea.KeyMsg.String() form ("j", "ctrl+f", "f5", "shift+up"). + // A chord is space separated: "y y". + Keys []string + Help string // one line for help; "" hides the binding from help + Group string // help section ("Navigation", "Files", ...) + Footer bool // shown in the footer +} + +// Registry resolves keys. It keeps a small chord buffer per context; it is +// not safe for concurrent use (it lives in the UI goroutine). +type Registry struct { + byCtx [numContexts]map[string]ActionID // key or chord → action + prefixes [numContexts]map[string]bool // chord prefixes + bindings []Binding + + pendingCtx Context + pending string +} + +// New builds a registry from bindings. It fails on a key bound twice in one +// context or a text context binding a non-control key. +func New(bindings []Binding) (*Registry, error) { + r := &Registry{bindings: bindings} + for i := range r.byCtx { + r.byCtx[i] = map[string]ActionID{} + r.prefixes[i] = map[string]bool{} + } + var errs []string + for _, b := range bindings { + if b.Context >= numContexts { + errs = append(errs, fmt.Sprintf("%s: bad context %d", b.Action, b.Context)) + continue + } + for _, k := range b.Keys { + if b.Context.IsText() && !textKeys[k] { + errs = append(errs, fmt.Sprintf("%s: %q binds a typing key in text context %s", b.Action, k, b.Context)) + continue + } + if prev, dup := r.byCtx[b.Context][k]; dup && prev != b.Action { + errs = append(errs, fmt.Sprintf("%s: %q in %s already bound to %s", b.Action, k, b.Context, prev)) + continue + } + r.byCtx[b.Context][k] = b.Action + parts := strings.Fields(k) + for i := 1; i < len(parts); i++ { + r.prefixes[b.Context][strings.Join(parts[:i], " ")] = true + } + } + } + if len(errs) > 0 { + return r, fmt.Errorf("keys: %s", strings.Join(errs, "; ")) + } + return r, nil +} + +// MustDefault returns the registry of DefaultBindings and panics on a +// conflict (a programming error caught by TestNoDuplicateKeysPerContext). +func MustDefault() *Registry { + r, err := New(DefaultBindings()) + if err != nil { + panic(err) + } + return r +} + +// Resolve maps a key in ctx to an action. ok is false when the key is not +// bound (in a text context: when it must go to the text field). A chord +// prefix yields (Pending, true). Changing context drops a pending chord. +func (r *Registry) Resolve(ctx Context, msg tea.KeyMsg) (ActionID, bool) { + key := msg.String() + if ctx != r.pendingCtx { + r.pending = "" + r.pendingCtx = ctx + } + if ctx.IsText() { + if !textKeys[key] { + return "", false + } + a, ok := r.byCtx[ctx][key] + return a, ok + } + cands := []string{key} + if t, ok := translate(msg); ok { + cands = append(cands, t) + } + if r.pending != "" { + prefix := r.pending + r.pending = "" + for _, k := range cands { + chord := prefix + " " + k + if a, ok := r.byCtx[ctx][chord]; ok { + return a, true + } + if r.prefixes[ctx][chord] { + r.pending = chord + return Pending, true + } + } + // Not a continuation: fall through and treat the key on its own. + } + for _, k := range cands { + if r.prefixes[ctx][k] { + r.pending = k + return Pending, true + } + if a, ok := r.byCtx[ctx][k]; ok { + return a, true + } + } + return "", false +} + +// Reset drops a pending chord. +func (r *Registry) Reset() { r.pending = "" } + +// Keys returns the keys bound to action in ctx, in declaration order. +func (r *Registry) Keys(ctx Context, a ActionID) []string { + for _, b := range r.bindings { + if b.Context == ctx && b.Action == a { + return b.Keys + } + } + return nil +} + +// HelpItem is one line of help or footer. +type HelpItem struct { + Action ActionID + Keys string // "F5/c" + Help string +} + +// Section is a group of help items. +type Section struct { + Title string + Items []HelpItem +} + +// Help lists the bindings of ctx grouped by section, in declaration order. +func (r *Registry) Help(ctx Context) []Section { + var out []Section + idx := map[string]int{} + for _, b := range r.bindings { + if b.Context != ctx || b.Help == "" { + continue + } + g := b.Group + if g == "" { + g = "Keys" + } + i, ok := idx[g] + if !ok { + i = len(out) + idx[g] = i + out = append(out, Section{Title: g}) + } + out[i].Items = append(out[i].Items, HelpItem{Action: b.Action, Keys: KeyLabel(b.Keys), Help: b.Help}) + } + return out +} + +// Footer lists the footer bindings of ctx. +func (r *Registry) Footer(ctx Context) []HelpItem { + var out []HelpItem + for _, b := range r.bindings { + if b.Context == ctx && b.Footer { + out = append(out, HelpItem{Action: b.Action, Keys: KeyLabel(b.Keys[:1]), Help: b.Help}) + } + } + return out +} + +// Actions lists every action bound in ctx (sorted). +func (r *Registry) Actions(ctx Context) []ActionID { + seen := map[ActionID]bool{} + for _, a := range r.byCtx[ctx] { + seen[a] = true + } + out := make([]ActionID, 0, len(seen)) + for a := range seen { + out = append(out, a) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// KeyLabel renders keys for humans: "F5/c", "Shift+↓/J", "y y". +func KeyLabel(ks []string) string { + parts := make([]string, len(ks)) + for i, k := range ks { + parts[i] = label(k) + } + return strings.Join(parts, "/") +} + +var keyLabels = map[string]string{ + "up": "↑", "down": "↓", "left": "←", "right": "→", "enter": "Enter", "esc": "Esc", + "tab": "Tab", "shift+tab": "Shift+Tab", "backspace": "Backspace", "delete": "Del", + "insert": "Ins", "pgup": "PgUp", "pgdown": "PgDn", "home": "Home", "end": "End", + " ": "Space", "f20": "Shift+F8", +} + +func label(k string) string { + if strings.Contains(k, " ") && k != " " { + ps := strings.Fields(k) + for i, p := range ps { + ps[i] = label(p) + } + return strings.Join(ps, " ") + } + if l, ok := keyLabels[k]; ok { + return l + } + if len(k) >= 2 && k[0] == 'f' && k[1] >= '0' && k[1] <= '9' { + return "F" + k[1:] + } + out := k + for _, mod := range []string{"ctrl+", "alt+", "shift+"} { + if strings.HasPrefix(out, mod) { + rest := strings.TrimPrefix(out, mod) + out = strings.ToUpper(mod[:1]) + mod[1:] + label(rest) + break + } + } + return out +} diff --git a/internal/tui/keys/keys_test.go b/internal/tui/keys/keys_test.go new file mode 100644 index 0000000..9ed259b --- /dev/null +++ b/internal/tui/keys/keys_test.go @@ -0,0 +1,141 @@ +package keys + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" +) + +func runeKey(s string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} } + +// U-P1-16: one key in one context = one action. +func TestNoDuplicateKeysPerContext(t *testing.T) { + if _, err := New(DefaultBindings()); err != nil { + t.Fatal(err) + } + r, err := New([]Binding{ + {Context: CtxBrowse, Action: "a", Keys: []string{"x"}}, + {Context: CtxBrowse, Action: "b", Keys: []string{"x"}}, + }) + if err == nil || r == nil { + t.Fatal("duplicate key not reported") + } + if _, err := New([]Binding{{Context: CtxFilterEdit, Action: "a", Keys: []string{"q"}}}); err == nil { + t.Fatal("text context binding a typing key not reported") + } +} + +// U-P1-5: ЙЦУКЕН is translated for commands only. +func TestLayoutTranslationCommandsOnly(t *testing.T) { + r := MustDefault() + if a, ok := r.Resolve(CtxBrowse, runeKey("й")); !ok || a != AppQuit { + t.Errorf("Browse й = %q %v, want %s", a, ok, AppQuit) + } + if a, ok := r.Resolve(CtxBrowse, runeKey("с")); !ok || a != FileCopy { + t.Errorf("Browse с = %q %v, want %s", a, ok, FileCopy) + } + if a, ok := r.Resolve(CtxBrowse, runeKey("Р")); ok { + t.Errorf("Browse Р (H) resolved to %q", a) + } + if a, ok := r.Resolve(CtxBrowse, runeKey("П")); !ok || a != NavEnd { + t.Errorf("Browse П (G) = %q %v, want %s", a, ok, NavEnd) + } + for _, ctx := range []Context{CtxFilterEdit, CtxModalInput} { + if a, ok := r.Resolve(ctx, runeKey("й")); ok { + t.Errorf("%s: й resolved to %q", ctx, a) + } + if a, ok := r.Resolve(ctx, runeKey("q")); ok { + t.Errorf("%s: q resolved to %q (must be typable)", ctx, a) + } + } + if got := Translate("н"); got != "y" { + t.Errorf("Translate(н) = %q", got) + } +} + +func TestTextContextPassesRunes(t *testing.T) { + r := MustDefault() + for _, ctx := range []Context{CtxFilterEdit, CtxModalInput} { + for _, ch := range "папка q/j" { + k := runeKey(string(ch)) + if ch == ' ' { + k = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}} + } + if a, ok := r.Resolve(ctx, k); ok { + t.Errorf("%s: %q resolved to %q", ctx, ch, a) + } + } + if a, ok := r.Resolve(ctx, tea.KeyMsg{Type: tea.KeyEnter}); !ok || a == "" { + t.Errorf("%s: enter not resolved", ctx) + } + } +} + +func TestChordYY(t *testing.T) { + r := MustDefault() + if a, ok := r.Resolve(CtxCaret, runeKey("y")); !ok || a != Pending { + t.Fatalf("first y = %q %v, want Pending", a, ok) + } + if a, ok := r.Resolve(CtxCaret, runeKey("y")); !ok || a != ViewerYankLine { + t.Fatalf("y y = %q %v, want %s", a, ok, ViewerYankLine) + } + // A non-continuing key drops the chord and acts on its own. + r.Resolve(CtxCaret, runeKey("y")) + if a, ok := r.Resolve(CtxCaret, runeKey("j")); !ok || a != ViewerLineDown { + t.Fatalf("y j = %q %v, want %s", a, ok, ViewerLineDown) + } + if a, _ := r.Resolve(CtxCaret, runeKey("y")); a != Pending { + t.Fatal("chord did not restart") + } + // A context change drops it too. + if a, ok := r.Resolve(CtxVisual, runeKey("y")); !ok || a != ViewerYank { + t.Fatalf("visual y = %q %v", a, ok) + } + if a, _ := r.Resolve(CtxCaret, runeKey("y")); a != Pending { + t.Fatal("chord survived a context change") + } + // In the ЙЦУКЕН layout too. + r.Reset() + r.Resolve(CtxCaret, runeKey("н")) + if a, _ := r.Resolve(CtxCaret, runeKey("н")); a != ViewerYankLine { + t.Fatalf("н н = %q", a) + } +} + +func TestHelpGeneratedFromRegistry(t *testing.T) { + r := MustDefault() + var found bool + for _, s := range r.Help(CtxBrowse) { + for _, it := range s.Items { + if it.Action == FileCopy { + found = true + if it.Keys != "F5/c" || it.Help != "copy" || s.Title != "Files" { + t.Errorf("copy help = %+v in %q", it, s.Title) + } + } + } + } + if !found { + t.Fatal("file.copy missing from help") + } + var foot []string + for _, it := range r.Footer(CtxBrowse) { + foot = append(foot, it.Keys+" "+it.Help) + } + if !strings.Contains(strings.Join(foot, "|"), "F5 copy") { + t.Errorf("footer = %v", foot) + } + if got := KeyLabel([]string{"f20", "X", "shift+up", "y y", " "}); got != "Shift+F8/X/Shift+↑/y y/Space" { + t.Errorf("KeyLabel = %q", got) + } + for _, ctx := range Contexts() { + for _, s := range r.Help(ctx) { + for _, it := range s.Items { + if it.Keys == "" { + t.Errorf("%s: %s has no keys", ctx, it.Action) + } + } + } + } +} diff --git a/internal/tui/keys/layout.go b/internal/tui/keys/layout.go new file mode 100644 index 0000000..4dad2d4 --- /dev/null +++ b/internal/tui/keys/layout.go @@ -0,0 +1,35 @@ +package keys + +import ( + "unicode" + + tea "github.com/charmbracelet/bubbletea" +) + +// jcuken maps the Russian ЙЦУКЕН layout to the US QWERTY key in the same +// position (lower case; upper case is derived). +var jcuken = map[rune]rune{ + 'й': 'q', 'ц': 'w', 'у': 'e', 'к': 'r', 'е': 't', 'н': 'y', 'г': 'u', 'ш': 'i', 'щ': 'o', 'з': 'p', + 'х': '[', 'ъ': ']', 'ф': 'a', 'ы': 's', 'в': 'd', 'а': 'f', 'п': 'g', 'р': 'h', 'о': 'j', 'л': 'k', + 'д': 'l', 'ж': ';', 'э': '\'', 'я': 'z', 'ч': 'x', 'с': 'c', 'м': 'v', 'и': 'b', 'т': 'n', 'ь': 'm', + 'б': ',', 'ю': '.', 'ё': '`', +} + +// translate returns the QWERTY key name for a single Cyrillic rune key +// (with alt preserved). Only command contexts use it. +func translate(msg tea.KeyMsg) (string, bool) { + if msg.Type != tea.KeyRunes || len(msg.Runes) != 1 { + return "", false + } + r := msg.Runes[0] + upper := unicode.IsUpper(r) + q, ok := jcuken[unicode.ToLower(r)] + if !ok { + return "", false + } + if upper { + q = unicode.ToUpper(q) + } + k := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{q}, Alt: msg.Alt} + return k.String(), true +} diff --git a/internal/tui/layout.go b/internal/tui/layout.go new file mode 100644 index 0000000..622d6be --- /dev/null +++ b/internal/tui/layout.go @@ -0,0 +1,94 @@ +package tui + +import ( + "vcom/internal/tui/geom" + "vcom/internal/tui/panel" +) + +// Layout holds every screen rectangle. Rendering, mouse hit-tests and the +// image overlay use the same values (design §7.3). +type Layout struct { + W, H int + Panes [2]geom.Rect // empty when the pane is hidden (Info shows only the active one) + Preview geom.Rect // Info: the preview box (with border) + PreviewBody geom.Rect // inside the preview border + Viewer geom.Rect // View screen: full content area + Status geom.Rect + Footer geom.Rect + Screen geom.Rect // whole terminal (modals center in it) +} + +// computeLayout splits the terminal for the current screen. +func computeLayout(w, h int, screen Screen, active int, footer bool, previewPct, gap int) Layout { + l := Layout{W: w, H: h, Screen: geom.Rect{W: w, H: h}} + bottom := 1 + if footer && h >= 8 { + bottom = 2 + } + l.Status = geom.Rect{X: 0, Y: h - bottom, W: w, H: 1} + if bottom == 2 { + l.Footer = geom.Rect{X: 0, Y: h - 1, W: w, H: 1} + } + body := geom.Rect{W: w, H: max(0, h-bottom)} + switch screen { + case ScreenView: + l.Viewer = body + case ScreenInfo: + pct := previewPct + if pct < 20 || pct > 80 { + pct = 50 + } + pw := body.W * pct / 100 + lw := body.W - pw + l.Panes[active] = geom.Rect{X: 0, Y: 0, W: lw, H: body.H} + l.Preview = geom.Rect{X: lw, Y: 0, W: pw, H: body.H} + l.PreviewBody = geom.Rect{X: lw + 1, Y: 2, W: max(0, pw-2), H: max(0, body.H-3)} + default: + gap = max(0, min(gap, 4)) + lw := (body.W - gap) / 2 + l.Panes[0] = geom.Rect{X: 0, Y: 0, W: lw, H: body.H} + l.Panes[1] = geom.Rect{X: lw + gap, Y: 0, W: body.W - lw - gap, H: body.H} + } + return l +} + +// paneAt returns the pane whose rectangle contains (x, y). +func (l Layout) paneAt(x, y int) (int, bool) { + for i, r := range l.Panes { + if !r.Empty() && r.Contains(x, y) { + return i, true + } + } + return 0, false +} + +// listRect is the rows area of pane i given its filter state. +func (a *App) listRect(i int) geom.Rect { + return panel.ListRect(a.layout.Panes[i], a.filterRow(i)) +} + +func (a *App) filterRow(i int) bool { + return a.panels[i].Filter() != "" || (a.filter != nil && i == a.active) +} + +// relayout recomputes the layout and tells panels and the viewer their +// sizes. Called after every Update (cheap) so View stays pure. +func (a *App) relayout() { + c := a.deps.Config.UI + a.layout = computeLayout(a.w, a.h, a.screen, a.active, c.ShowFooter, c.PreviewWidthPercent, c.PaneGap) + for i, p := range a.panels { + r := a.layout.Panes[i] + if r.Empty() { + r = a.layout.Panes[a.active] + } + p.SetRows(panel.ListRect(r, a.filterRow(i)).H) + } + switch a.screen { + case ScreenView: + a.viewer.SetRows(a.layout.Viewer.H - 1) + a.viewer.SetWidth(a.layout.Viewer.W) + case ScreenInfo: + a.viewer.SetRows(a.layout.PreviewBody.H) + a.viewer.SetWidth(a.layout.PreviewBody.W) + } +} diff --git a/internal/tui/mirror.go b/internal/tui/mirror.go new file mode 100644 index 0000000..034a1f5 --- /dev/null +++ b/internal/tui/mirror.go @@ -0,0 +1,57 @@ +package tui + +import ( + "context" + "errors" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +type mirrorMsg struct { + Ticket Ticket + Src panel.Target + Infos []vfs.FileInfo + Err error +} + +func (a *App) canMirror() error { + if a.Active().Source != panel.SourceDir || a.Passive().Source != panel.SourceDir { + return errors.New("mirror works between directory panels") + } + return nil +} + +// mirror is p: the other panel goes to this panel's place — the same mount +// stack, each mount with its own reference (Acquire), so leaving the +// archive or host in one panel does not break the other (U-P1-14, +// N-P1-12). +func (a *App) mirror() tea.Cmd { + src := a.Active().Here() + tk, ctx := a.req.Begin(ReqKey{Kind: ReqFeature, Pane: 1 - a.active, Extra: "mirror"}) + return func() tea.Msg { + infos, err := src.FS().ReadDir(ctx, src.Path) + return mirrorMsg{Ticket: tk, Src: src, Infos: infos, Err: err} + } +} + +func (a *App) onMirror(m mirrorMsg) tea.Cmd { + if !a.req.Accept(m.Ticket) { + return nil + } + if m.Err != nil { + if errors.Is(m.Err, context.Canceled) { + return nil + } + return a.notify(notify.Error, "Mirror: "+cleanErr(m.Err).Error()) + } + act := a.Active() + if !act.Location().Same(m.Src.Location()) { + return nil // the active panel moved on meanwhile + } + a.Passive().MirrorOf(act, m.Infos) + return a.notify(notify.Info, "Mirrored: "+displayPath(act.Location())) +} diff --git a/internal/tui/misc_test.go b/internal/tui/misc_test.go new file mode 100644 index 0000000..effc08a --- /dev/null +++ b/internal/tui/misc_test.go @@ -0,0 +1,383 @@ +package tui + +import ( + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/state" + "vcom/internal/testutil/fstree" + "vcom/internal/tui/modal" + "vcom/internal/tui/panel" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" +) + +// execRec runs foreground programs synchronously and records them. +type execRec struct { + mu sync.Mutex + cmds [][]string +} + +func (r *execRec) opt(d *Deps) { + d.Exec = func(c *exec.Cmd, done tea.ExecCallback) tea.Cmd { + r.mu.Lock() + r.cmds = append(r.cmds, c.Args) + r.mu.Unlock() + return func() tea.Msg { return done(c.Run()) } + } +} + +func (r *execRec) list() [][]string { + r.mu.Lock() + defer r.mu.Unlock() + return append([][]string(nil), r.cmds...) +} + +func script(t *testing.T, body string) string { + p := filepath.Join(t.TempDir(), "prog") + if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func noSave(d *Deps) { d.SaveSession = func(state.Session) error { return nil } } + +func TestEnterExecutableOpensRunMenu(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("deploy.sh", "#!/bin/sh\necho ran > \"$(dirname \"$0\")/ran.txt\"\n").WithMode(0o755)}) + rec := &execRec{} + h := newOps(t, localfs.New(), dir, dir, rec.opt, noSave) + h.cursorTo("deploy.sh") + h.press("enter") + l, ok := h.app.modals.Top().(*modal.List) + if !ok || !strings.Contains(l.Title, "executable") { + t.Fatalf("no run menu: %T", h.app.modals.Top()) + } + if len(rec.list()) != 0 || exists(filepath.Join(dir, "ran.txt")) { + t.Fatal("Enter ran the executable (U-P1-3, N-P0-2)") + } + h.press("esc") + if exists(filepath.Join(dir, "ran.txt")) { + t.Fatal("ran after Esc") + } + h.press("enter", "enter") // Run + h.idle() + cmds := rec.list() + if len(cmds) != 1 || cmds[0][0] != "sh" || cmds[0][len(cmds[0])-1] != filepath.Join(dir, "deploy.sh") { + t.Fatalf("run command %v", cmds) + } +} + +func TestNoZombieAfterOpen(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("pic.bin", "\x00\x01\x02binary")}) + pidFile := filepath.Join(t.TempDir(), "pid") + opener := script(t, "echo $$ > "+pidFile) + h := newOps(t, localfs.New(), dir, dir, noSave, func(d *Deps) { d.Opener = []string{opener} }) + h.cursorTo("pic.bin") + h.press("enter") + h.idle() + if !h.d.ScreenContains("Opened pic.bin") { + t.Fatalf("not opened:\n%s", h.d.Screen()) + } + var pid string + for i := 0; i < 100 && pid == ""; i++ { + b, _ := os.ReadFile(pidFile) + pid = strings.TrimSpace(string(b)) + time.Sleep(10 * time.Millisecond) + } + if pid == "" { + t.Fatal("opener did not run") + } + deadline := time.Now().Add(2 * time.Second) + for { + stat, err := os.ReadFile("/proc/" + pid + "/stat") + if err != nil { + return // reaped + } + if fields := strings.Fields(string(stat)); len(fields) > 2 && fields[2] != "Z" { + // still running: wait + } + if time.Now().After(deadline) { + t.Fatalf("opener %s left as %q (zombie; U-P1-15)", pid, strings.Fields(string(stat))[2]) + } + time.Sleep(20 * time.Millisecond) + } +} + +func TestEditLocalRunsEditor(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("notes.txt", "hello\n")}) + rec := &execRec{} + editor := script(t, `for a; do f=$a; done; echo edited >> "$f"`) // edits its last argument + h := newOps(t, localfs.New(), dir, dir, rec.opt, noSave, func(d *Deps) { + d.Getenv = func(k string) string { + if k == "EDITOR" { + return `"` + editor + `" --wait` + } + return "" + } + }) + h.cursorTo("notes.txt") + h.press("enter") // text → editor + h.idle() + cmds := rec.list() + if len(cmds) != 1 || cmds[0][0] != editor || cmds[0][1] != "--wait" { + t.Fatalf("editor command %v", cmds) + } + if read(t, filepath.Join(dir, "notes.txt")) != "hello\nedited\n" { + t.Fatal("editor did not get the file") + } + h.press("f4") + h.idle() + if n := len(rec.list()); n != 2 { + t.Fatalf("F4: %d commands", n) + } +} + +// remoteLike wraps the local FS as a remote one (no exec, no trash). +type remoteLike struct{ vfs.FS } + +func (remoteLike) Kind() vfs.Kind { return vfs.KindSFTP } +func (remoteLike) Volume() vfs.VolumeID { return "ssh:fake" } +func (remoteLike) Label() string { return "bob@fake" } +func (r remoteLike) Caps() vfs.Caps { + c := r.FS.Caps() + c.Exec, c.Trash = false, false + return c +} + +func editorEnv(editor string) opt { + return func(d *Deps) { + d.Getenv = func(k string) string { + if k == "EDITOR" { + return editor + } + return "" + } + } +} + +func TestRemoteEditUploadsBack(t *testing.T) { + ldir := t.TempDir() + rdir := tree(t, fstree.Spec{fstree.File("conf.ini", "a=1\n").WithMode(0o640)}) + run := t.TempDir() + rec := &execRec{} + h := newOps(t, localfs.New(), ldir, ldir, rec.opt, noSave, editorEnv(script(t, `echo b=2 >> "$1"`)), + func(d *Deps) { d.RunDir = run }) + h.mountRemote(1, remoteLike{localfs.New()}, rdir) + h.press("tab") + h.cursorTo("conf.ini") + h.press("enter") + h.idle() + if got := read(t, filepath.Join(rdir, "conf.ini")); got != "a=1\nb=2\n" { + t.Fatalf("remote content %q (N-P0-2: edit must upload back)", got) + } + if fi, _ := os.Stat(filepath.Join(rdir, "conf.ini")); fi.Mode().Perm() != 0o640 { + t.Fatalf("mode %v", fi.Mode()) + } + if cmds := rec.list(); len(cmds) != 1 || !strings.HasPrefix(cmds[0][1], run) { + t.Fatalf("editor not on a run-dir copy: %v", cmds) + } + if ents, _ := os.ReadDir(run); len(ents) != 0 { + t.Fatalf("temp copy left: %v", ents) + } + noParts(t, rdir) + if !h.d.ScreenContains("Uploaded conf.ini") { + t.Fatalf("no note:\n%s", h.d.Screen()) + } +} + +func TestRemoteEditConflictAsks(t *testing.T) { + ldir := t.TempDir() + rdir := tree(t, fstree.Spec{fstree.File("conf.ini", "a=1\n")}) + remote := filepath.Join(rdir, "conf.ini") + // The editor edits the copy while someone changes the server file. + editor := script(t, `echo mine >> "$1"; sleep 0.01; echo theirs >> "`+remote+`"; touch -d '2001-01-01' "`+remote+`"`) + h := newOps(t, localfs.New(), ldir, ldir, (&execRec{}).opt, noSave, editorEnv(editor), func(d *Deps) { d.RunDir = t.TempDir() }) + h.mountRemote(1, remoteLike{localfs.New()}, rdir) + h.press("tab") + h.cursorTo("conf.ini") + h.press("f4") + d := h.waitDialog("changed on the server") + if d.Buttons[d.Focused()].Label != "Save a copy beside" { + t.Fatalf("default %q", d.Buttons[d.Focused()].Label) + } + h.press("enter") + h.idle() + if got := read(t, remote); got != "a=1\ntheirs\n" { + t.Fatalf("server version overwritten: %q (U-P1-12)", got) + } + if got := read(t, filepath.Join(rdir, "conf (1).ini")); got != "a=1\nmine\n" { + t.Fatalf("copy beside %q", got) + } +} + +func TestSortMenuAndYank(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a", "1"), fstree.File("b", "333"), fstree.File("c", "22")}) + var saved []string + var clip atomic.Value + h := newOps(t, localfs.New(), dir, dir, noSave, func(d *Deps) { + d.SetConfigKey = func(_ string, section, key string, v any) (string, error) { + saved = append(saved, section+"."+key+"="+strconv.Quote(strings.TrimSpace(strings.ReplaceAll(toString(v), "\n", "")))) + return "x", nil + } + d.Clipboard = func(s string) error { clip.Store(s); return nil } + }) + h.press("S", "j", "enter") // Size + h.idle() + var names []string + p := h.app.Active() + for i := 0; i < p.VisibleLen(); i++ { + if e, _ := p.Visible(i); !e.Parent { + names = append(names, e.Name) + } + } + if strings.Join(names, "") != "acb" { + t.Fatalf("sorted by size: %v", names) + } + if len(saved) != 1 || !strings.HasPrefix(saved[0], "browser.sort.by=") { + t.Fatalf("saved %v", saved) + } + h.cursorTo("b") + h.press("y") + h.idle() + if clip.Load() != filepath.Join(dir, "b") { + t.Fatalf("clipboard %v", clip.Load()) + } +} + +func toString(v any) string { + switch x := v.(type) { + case string: + return x + case bool: + return strconv.FormatBool(x) + } + return "" +} + +// U-P1-14, N-P1-12: after mirror, leaving the archive (or the host) in the +// active panel leaves the mirrored panel working. +func TestUP114_MirrorArchiveAndRemote(t *testing.T) { + dir := archiveDir(t) + h := newOps(t, localfs.New(), dir, dir, noSave) + h.enterArchive("box.zip") + h.press("p") + if !inArchive(h.app.Passive()) { + t.Fatal("mirror did not enter the archive in the other panel") + } + h.press("backspace") // leave the archive in the active panel + if inArchive(h.app.Active()) || !inArchive(h.app.Passive()) { + t.Fatal("panels wrong after leaving") + } + h.press("tab") + h.cursorTo("b.txt") + h.press("f3") + if f, err := h.app.Active().FS().Open(t.Context(), "/b.txt"); err != nil { + t.Fatalf("mirrored archive dead: %v", err) + } else { + f.Close() + } + + // Remote: every mount holds its own reference. + ldir := t.TempDir() + rdir := tree(t, fstree.Spec{fstree.File("r.txt", "r")}) + h2 := newOps(t, localfs.New(), ldir, ldir, noSave) + var refs atomic.Int32 + rfs := standFS(t) + p := h2.app.Panel(0) + ret := p.Location() + refs.Store(1) + m := panel.NewMount(rfs, "/", &ret, "", func() { refs.Add(-1) }, func() func() { + refs.Add(1) + return func() { refs.Add(-1) } + }) + h2.d.Send(h2.app.navigate(0, panel.Target{Mounts: append(p.Here().Mounts, m), Path: rdir}, "", panel.NavPush)()) + h2.d.Settle(settle) + h2.press("p") + if refs.Load() != 2 { + t.Fatalf("refs after mirror = %d", refs.Load()) + } + h2.press("backspace") // active leaves the host (its history may keep its reference) + h2.idle() + if refs.Load() < 1 { + t.Fatalf("refs after leaving = %d: the mirrored panel lost its reference", refs.Load()) + } + if _, err := h2.app.Passive().FS().ReadDir(t.Context(), rdir); err != nil { + t.Fatalf("mirrored remote panel dead: %v", err) + } +} + +func TestSessionRestoresLocalForRemote(t *testing.T) { + ldir := tree(t, fstree.Spec{fstree.File("pick", ""), fstree.File("z", "")}) + rdir := tree(t, fstree.Spec{fstree.File("r.txt", "")}) + var got state.Session + h := newOps(t, localfs.New(), ldir, ldir, func(d *Deps) { d.SaveSession = func(s state.Session) error { got = s; return nil } }) + h.press("tab") + h.cursorTo("pick") + h.mountRemote(1, remoteLike{localfs.New()}, rdir) + if err := h.app.Shutdown(); err != nil { + t.Fatal(err) + } + if got.Right.Path != ldir || got.Right.EntryName != "" && got.Right.EntryName != "pick" || got.ActivePane != "right" { + t.Fatalf("session %+v: a remote panel must be saved as its local place", got) + } + // Restore: start dirs from the session, active pane and cursor. + got.Right.EntryName = "pick" + h2 := newOps(t, localfs.New(), got.Left.Path, got.Right.Path, noSave, func(d *Deps) { d.Session = &got }) + if h2.app.active != 1 || h2.app.Panel(1).Path() != ldir { + t.Fatalf("restored active %d path %s", h2.app.active, h2.app.Panel(1).Path()) + } + if e, _ := h2.app.Panel(1).Selected(); e.Name != "pick" { + t.Fatalf("restored cursor on %q", e.Name) + } +} + +func TestSignalSavesSession(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("f", "")}) + saved := make(chan state.Session, 1) + h := newOps(t, localfs.New(), dir, dir, func(d *Deps) { d.SaveSession = func(s state.Session) error { saved <- s; return nil } }) + h.d.Send(Signal()) + h.d.Settle(settle) + select { + case s := <-saved: + if s.Left.Path != dir { + t.Fatalf("saved %+v", s) + } + default: + t.Fatal("session not saved on signal") + } + if !h.d.Quit() { + t.Fatal("did not quit on signal") + } + if err := h.app.Shutdown(); err != nil || len(saved) != 0 { + t.Fatal("teardown saved twice") + } +} + +func TestShellSplit(t *testing.T) { + cases := map[string][]string{ + `code --wait`: {"code", "--wait"}, + `"/opt/my editor/bin" -n`: {"/opt/my editor/bin", "-n"}, + `vim -c 'set ft=go'`: {"vim", "-c", "set ft=go"}, + `emacs\ client -t`: {"emacs client", "-t"}, + `nano "a \"q\" b"`: {"nano", `a "q" b`}, + } + for in, want := range cases { + got, err := shellSplit(in) + if err != nil || strings.Join(got, "|") != strings.Join(want, "|") { + t.Errorf("shellSplit(%q) = %q, %v", in, got, err) + } + } + if _, err := shellSplit(`vim "x`); err == nil { + t.Error("unterminated quote accepted") + } +} diff --git a/internal/tui/modal/conflict.go b/internal/tui/modal/conflict.go new file mode 100644 index 0000000..d70334d --- /dev/null +++ b/internal/tui/modal/conflict.go @@ -0,0 +1,58 @@ +package modal + +// Conflict answers (Values of the Conflict dialog's buttons). +const ( + ConflictOverwrite = "overwrite" + ConflictSkip = "skip" + ConflictKeepBoth = "keep" + ConflictOverwriteAll = "overwrite-all" + ConflictSkipAll = "skip-all" + ConflictKeepBothAll = "keep-all" + ConflictAbort = "abort" +) + +// Conflict builds the dialog for a target that already exists. fields +// compare source and target; mismatch (file ↔ directory) offers no +// overwrite: a directory tree is never deleted to make room (§4.3). The +// default is Skip. +func Conflict(title string, fields []KV, mismatch bool) *Dialog { + d := &Dialog{Title: title, Fields: fields, Width: 64} + if mismatch { + d.Warnings = []string{"The target is of another type (file ↔ directory): it cannot be overwritten."} + } else { + d.Buttons = append(d.Buttons, + Button{Label: "Overwrite", Key: "o", Value: ConflictOverwrite}, + Button{Label: "Overwrite all", Key: "O", Value: ConflictOverwriteAll}) + } + d.Buttons = append(d.Buttons, + Button{Label: "Skip", Key: "s", Value: ConflictSkip, Default: true}, + Button{Label: "Skip all", Key: "S", Value: ConflictSkipAll}, + Button{Label: "Keep both", Key: "k", Value: ConflictKeepBoth}, + Button{Label: "Keep both all", Key: "K", Value: ConflictKeepBothAll}, + Button{Label: "Abort", Key: "a", Value: ConflictAbort, Danger: true}) + return d +} + +// Item-error answers. +const ( + ErrorRetry = "retry" + ErrorSkip = "skip" + ErrorSkipAll = "skip-all" + ErrorAbort = "abort" +) + +// ItemError builds the dialog for a failed item: Retry / Skip / Skip all / +// Abort (default Retry). +func ItemError(title, item, err string) *Dialog { + return &Dialog{ + Title: title, + Fields: []KV{{Label: "Item", Value: item}, {Label: "Error", Value: err}}, + Width: 64, + Buttons: []Button{ + {Label: "Retry", Key: "r", Value: ErrorRetry, Default: true}, + {Label: "Skip", Key: "s", Value: ErrorSkip}, + {Label: "Skip all", Key: "S", Value: ErrorSkipAll}, + {Label: "Abort", Key: "a", Value: ErrorAbort, Danger: true}, + }, + } +} diff --git a/internal/tui/modal/dialog.go b/internal/tui/modal/dialog.go new file mode 100644 index 0000000..9fa775d --- /dev/null +++ b/internal/tui/modal/dialog.go @@ -0,0 +1,210 @@ +package modal + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/keys" + "vcom/internal/tui/style" +) + +// KV is one "Label: value" line of a Dialog. +type KV struct{ Label, Value string } + +// Button of a Dialog. Key is a single-key hotkey ("y"); it is matched in +// the ЙЦУКЕН layout too and wins over the Dialog's own cancel keys. +type Button struct { + Label string + Key string + Value any + Danger bool // drawn in the danger color when focused + Default bool // focused when the dialog opens + Cancel bool // pressing it closes as Cancelled +} + +// Dialog is a structured confirmation (crutch #14: no heuristics on text). +// Enter presses the focused button, Tab/←/→ move focus, hotkeys press their +// button, Esc/Ctrl+C/q cancel. +type Dialog struct { + Title string + Fields []KV + Text []string // free paragraphs, wrapped + Warnings []string + Buttons []Button + Width int // preferred content width (default 60) + + focus int + init bool +} + +func (d *Dialog) Context() keys.Context { return keys.CtxModalDialog } + +func (d *Dialog) setup() { + if d.init { + return + } + d.init = true + for i, b := range d.Buttons { + if b.Default { + d.focus = i + } + } +} + +// Focused is the index of the focused button. +func (d *Dialog) Focused() int { d.setup(); return d.focus } + +func (d *Dialog) press(i int) Outcome { + b := d.Buttons[i] + if b.Cancel { + return Outcome{Close: true, Cancelled: true, Value: b.Value} + } + return Done(b.Value) +} + +func (d *Dialog) Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) { + d.setup() + if k.Type == tea.KeyRunes && len(k.Runes) == 1 { + ks := k.String() + for i, b := range d.Buttons { + if b.Key != "" && (b.Key == ks || b.Key == keys.Translate(ks)) { + return d.press(i), nil + } + } + } + switch a { + case keys.ModalConfirm: + if len(d.Buttons) == 0 { + return Done(nil), nil + } + return d.press(d.focus), nil + case keys.ModalNext: + if n := len(d.Buttons); n > 0 { + d.focus = (d.focus + 1) % n + } + case keys.ModalPrev: + if n := len(d.Buttons); n > 0 { + d.focus = (d.focus + n - 1) % n + } + case keys.ModalCancel: + return Cancel(), nil + } + return Keep, nil +} + +// layout renders the content lines; btnRow is the line of the buttons and +// spans their cell ranges on it. +func (d *Dialog) layout(maxW, maxH int, st *style.Styles) (lines []string, btnRow int, spans [][2]int) { + d.setup() + want := d.Width + if want == 0 { + want = 60 + } + cw := innerWidth(maxW, want) + var body []string + for _, f := range d.Fields { + l := st.ModalLabel.Render(f.Label+": ") + f.Value + body = append(body, ansi.Truncate(l, cw, "…")) + } + for _, p := range d.Text { + if len(body) > 0 && len(d.Fields) > 0 { + body = append(body, "") + } + body = append(body, strings.Split(ansi.Wrap(p, cw, ""), "\n")...) + } + for _, w := range d.Warnings { + for _, l := range strings.Split(ansi.Wrap("! "+w, cw, ""), "\n") { + body = append(body, st.ModalWarning.Render(l)) + } + } + // Buttons line. + var b strings.Builder + x := 0 + for i, btn := range d.Buttons { + if i > 0 { + b.WriteString(" ") + x += 2 + } + label := btn.Label + if btn.Key != "" { + label = fmt.Sprintf("%s (%s)", btn.Label, btn.Key) + } + s := st.Button + if i == d.focus { + s = st.ButtonFocused + if btn.Danger { + s = st.ButtonDanger + } + } + r := s.Render(label) + w := ansi.StringWidth(r) + spans = append(spans, [2]int{x, x + w}) + x += w + b.WriteString(r) + } + // Keep the buttons visible: cut the body if the modal is too tall + // (border 2 + title 1 + blank 1 + buttons 1). + room := maxH - 5 + if room < 0 { + room = 0 + } + if len(body) > room { + cut := len(body) - room + 1 + if room == 0 { + body = nil + } else { + body = append(body[:room-1], st.Muted.Render(fmt.Sprintf("… %d more lines", cut))) + } + } + lines = append(lines, body...) + if len(d.Buttons) > 0 { + if len(body) > 0 { + lines = append(lines, "") + } + btnRow = len(lines) + lines = append(lines, b.String()) + } + return lines, btnRow, spans +} + +func (d *Dialog) View(maxW, maxH int, st *style.Styles) string { + lines, _, _ := d.layout(maxW, maxH, st) + return frame(st, d.Title, lines, maxW) +} + +func (d *Dialog) Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) { + if m.Action != tea.MouseActionPress || m.Button != tea.MouseButtonLeft { + return Keep, nil + } + _, row, spans := d.layout(w, h, st) + cx, cy := x-2, y-1 // border + padding + if d.Title != "" { + cy-- + } + if cy != row { + return Keep, nil + } + for i, s := range spans { + if cx >= s[0] && cx < s[1] { + d.focus = i + return d.press(i), nil + } + } + return Keep, nil +} + +// Confirm builds a yes/no dialog. With danger the default focus is on the +// cancel button (permanent delete, U-P0-4). +func Confirm(title string, text string, yes string, danger bool) *Dialog { + return &Dialog{ + Title: title, + Text: []string{text}, + Buttons: []Button{ + {Label: yes, Key: "y", Value: true, Danger: danger, Default: !danger}, + {Label: "Cancel", Key: "n", Cancel: true, Default: danger}, + }, + } +} diff --git a/internal/tui/modal/input.go b/internal/tui/modal/input.go new file mode 100644 index 0000000..c4d655f --- /dev/null +++ b/internal/tui/modal/input.go @@ -0,0 +1,144 @@ +package modal + +import ( + "strings" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/keys" + "vcom/internal/tui/style" +) + +// Field of an Input modal. +type Field struct { + Label string + Value string + Placeholder string + Secret bool +} + +// Input is a form of one or more text fields (mkdir, rename, SSH host). +// Every typed key goes to the focused field untranslated ("q" is a letter +// here, U section 7). Enter submits ([]string of values), Esc cancels. +type Input struct { + Title string + Text string // optional line above the fields + // Validate is called on Enter; an error is shown and the modal stays. + Validate func(values []string) error + Width int + + fields []textinput.Model + labels []string + focus int + err string +} + +// NewInput builds an Input. +func NewInput(title string, fields ...Field) *Input { + in := &Input{Title: title} + for _, f := range fields { + ti := textinput.New() + ti.Prompt = "" + ti.SetValue(f.Value) + ti.Placeholder = f.Placeholder + ti.CursorEnd() + if f.Secret { + ti.EchoMode = textinput.EchoPassword + } + in.fields = append(in.fields, ti) + in.labels = append(in.labels, f.Label) + } + if len(in.fields) > 0 { + in.fields[0].Focus() + } + return in +} + +func (in *Input) Context() keys.Context { return keys.CtxModalInput } + +// Values returns the current field values. +func (in *Input) Values() []string { + out := make([]string, len(in.fields)) + for i, f := range in.fields { + out[i] = f.Value() + } + return out +} + +func (in *Input) setFocus(i int) { + in.fields[in.focus].Blur() + in.focus = i + in.fields[in.focus].Focus() +} + +func (in *Input) Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) { + n := len(in.fields) + switch a { + case keys.ModalConfirm: + vals := in.Values() + if in.Validate != nil { + if err := in.Validate(vals); err != nil { + in.err = err.Error() + return Keep, nil + } + } + return Done(vals), nil + case keys.ModalCancel: + return Cancel(), nil + case keys.ModalNext: + if n > 1 { + in.setFocus((in.focus + 1) % n) + } + return Keep, nil + case keys.ModalPrev: + if n > 1 { + in.setFocus((in.focus + n - 1) % n) + } + return Keep, nil + case keys.ModalClear: + if n > 0 { + in.fields[in.focus].SetValue("") + } + return Keep, nil + } + if n == 0 { + return Keep, nil + } + in.err = "" + var cmd tea.Cmd + in.fields[in.focus], cmd = in.fields[in.focus].Update(k) + return Keep, cmd +} + +func (in *Input) View(maxW, maxH int, st *style.Styles) string { + want := in.Width + if want == 0 { + want = 56 + } + cw := innerWidth(maxW, want) + var lines []string + if in.Text != "" { + lines = append(lines, strings.Split(ansi.Wrap(in.Text, cw, ""), "\n")...) + } + lw := 0 + for _, l := range in.labels { + lw = max(lw, ansi.StringWidth(l)) + } + for i := range in.fields { + f := &in.fields[i] + f.Width = max(4, cw-lw-3) + label := st.ModalLabel.Render(in.labels[i] + strings.Repeat(" ", lw-ansi.StringWidth(in.labels[i])) + " ") + lines = append(lines, ansi.Truncate(label+"▏"+f.View(), cw, "")) + } + if in.err != "" { + lines = append(lines, st.NoteError.Render(ansi.Truncate(in.err, cw, "…"))) + } + lines, _, _ = clip(lines, in.focus, max(1, maxH-3)) + return frame(st, in.Title, lines, maxW) +} + +func (in *Input) Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) { + return Keep, nil +} diff --git a/internal/tui/modal/list.go b/internal/tui/modal/list.go new file mode 100644 index 0000000..0b37296 --- /dev/null +++ b/internal/tui/modal/list.go @@ -0,0 +1,244 @@ +package modal + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/keys" + "vcom/internal/tui/style" +) + +// Item of a List. A Header item is a section title: drawn, never selected. +type Item struct { + Label string + Detail string // right-aligned, muted + Value any + Header bool +} + +// List is a scrollable list of choices (theme, sort, hosts, jobs) or, with +// no selectable items, a scrollable text (help, message log). It never +// grows past the screen: on a small terminal it scrolls (crutch #10). +type List struct { + Title string + Items []Item + Width int + // OnMove is called when the cursor lands on another item (live theme + // preview); its command is returned with the key's. + OnMove func(Item) tea.Cmd + + cursor int // index into Items (a selectable one), -1 for text lists + offset int // first visible row + page int // rows shown last time (for PgUp/PgDn) + init bool +} + +// NewList builds a list with the cursor on the first selectable item, or on +// the item whose Value equals selected (if any). +func NewList(title string, items []Item, selected any) *List { + l := &List{Title: title, Items: items, cursor: -1} + for i, it := range items { + if it.Header { + continue + } + if l.cursor < 0 { + l.cursor = i + } + if selected != nil && it.Value == selected { + l.cursor = i + break + } + } + return l +} + +// NewText builds a read-only scrollable text. +func NewText(title string, lines []string) *List { + items := make([]Item, len(lines)) + for i, s := range lines { + items[i] = Item{Label: s, Header: true} + } + return &List{Title: title, Items: items, cursor: -1} +} + +func (l *List) Context() keys.Context { return keys.CtxModalList } + +// Cursor returns the selected item index (-1 for a text list). +func (l *List) Cursor() int { return l.cursor } + +// Offset returns the first visible row. +func (l *List) Offset() int { return l.offset } + +func (l *List) selectable(i int) bool { return i >= 0 && i < len(l.Items) && !l.Items[i].Header } + +// move the cursor by delta selectable steps (text lists scroll instead). +func (l *List) move(delta int) tea.Cmd { + if l.cursor < 0 { + l.offset = max(0, min(l.offset+delta, len(l.Items)-max(1, l.page))) + return nil + } + old := l.cursor + step := 1 + if delta < 0 { + step = -1 + } + for n := abs(delta); n > 0; n-- { + i := l.cursor + step + for i >= 0 && i < len(l.Items) && !l.selectable(i) { + i += step + } + if !l.selectable(i) { + break + } + l.cursor = i + } + l.follow() + if l.cursor != old && l.OnMove != nil { + return l.OnMove(l.Items[l.cursor]) + } + return nil +} + +func (l *List) jump(toEnd bool) tea.Cmd { + if l.cursor < 0 { + if toEnd { + l.offset = max(0, len(l.Items)-max(1, l.page)) + } else { + l.offset = 0 + } + return nil + } + if toEnd { + return l.move(len(l.Items)) + } + return l.move(-len(l.Items)) +} + +func (l *List) follow() { + if l.page <= 0 { + return + } + if l.cursor < l.offset { + l.offset = l.cursor + // Show the section header right above, if any. + if l.offset > 0 && l.Items[l.offset-1].Header { + l.offset-- + } + } + if l.cursor >= l.offset+l.page { + l.offset = l.cursor - l.page + 1 + } +} + +func (l *List) Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) { + page := max(1, l.page-1) + switch a { + case keys.ModalUp: + return Keep, l.move(-1) + case keys.ModalDown: + return Keep, l.move(1) + case keys.ModalPgUp: + return Keep, l.move(-page) + case keys.ModalPgDown: + return Keep, l.move(page) + case keys.ModalHome: + return Keep, l.jump(false) + case keys.ModalEnd: + return Keep, l.jump(true) + case keys.ModalConfirm: + if l.cursor < 0 { + return Cancel(), nil + } + return Done(l.Items[l.cursor].Value), nil + case keys.ModalCancel: + return Cancel(), nil + } + return Keep, nil +} + +// rows is how many item rows fit in maxH (border 2 + title 1). +func (l *List) rows(maxH int) int { return max(1, min(len(l.Items), maxH-3)) } + +func (l *List) View(maxW, maxH int, st *style.Styles) string { + want := l.Width + if want == 0 { + want = 4 + for _, it := range l.Items { + want = max(want, ansi.StringWidth(it.Label)+ansi.StringWidth(it.Detail)+4) + } + want = min(want, 76) + } + cw := innerWidth(maxW, want) + n := l.rows(maxH) + if !l.init || n != l.page { + l.init = true + l.page = n + l.follow() + } + l.offset = max(0, min(l.offset, max(0, len(l.Items)-n))) + var lines []string + for i := l.offset; i < len(l.Items) && len(lines) < n; i++ { + lines = append(lines, l.renderItem(i, cw, st)) + } + title := l.Title + if len(l.Items) > n { + title = fmt.Sprintf("%s %d–%d/%d", l.Title, l.offset+1, l.offset+len(lines), len(l.Items)) + } + return frame(st, title, lines, maxW) +} + +func (l *List) renderItem(i, cw int, st *style.Styles) string { + it := l.Items[i] + if it.Header { + s := ansi.Truncate(it.Label, cw, "…") + if l.cursor >= 0 { + return st.Section.Render(s) + } + return s + } + label := ansi.Truncate(it.Label, max(1, cw-ansi.StringWidth(it.Detail)-1), "…") + gap := max(1, cw-ansi.StringWidth(label)-ansi.StringWidth(it.Detail)) + line := label + strings.Repeat(" ", gap) + st.Muted.Render(it.Detail) + if i == l.cursor { + return st.ListCursor.Render(ansi.Strip(label) + strings.Repeat(" ", gap) + it.Detail) + } + return line +} + +func (l *List) Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) { + switch m.Button { + case tea.MouseButtonWheelUp: + return Keep, l.move(-3) + case tea.MouseButtonWheelDown: + return Keep, l.move(3) + case tea.MouseButtonLeft: + if m.Action != tea.MouseActionPress { + return Keep, nil + } + row := y - 2 // border + title + i := l.offset + row + if row < 0 || row >= l.page || !l.selectable(i) { + return Keep, nil + } + if i == l.cursor { + return Done(l.Items[i].Value), nil + } + l.cursor = i + l.follow() + if l.OnMove != nil { + return Keep, l.OnMove(l.Items[i]) + } + return Keep, nil + } + return Keep, nil +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/internal/tui/modal/modal_test.go b/internal/tui/modal/modal_test.go new file mode 100644 index 0000000..f43be53 --- /dev/null +++ b/internal/tui/modal/modal_test.go @@ -0,0 +1,234 @@ +package modal + +import ( + "fmt" + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/theme" + "vcom/internal/tui/geom" + "vcom/internal/tui/keys" + "vcom/internal/tui/style" +) + +var reg = keys.MustDefault() + +func st(t *testing.T) *style.Styles { + t.Helper() + p, err := theme.Resolve("catppuccin-mocha") + if err != nil { + t.Fatal(err) + } + return style.New(p) +} + +func key(s string) tea.KeyMsg { + switch s { + case "enter": + return tea.KeyMsg{Type: tea.KeyEnter} + case "esc": + return tea.KeyMsg{Type: tea.KeyEsc} + case "tab": + return tea.KeyMsg{Type: tea.KeyTab} + case "pgdown": + return tea.KeyMsg{Type: tea.KeyPgDown} + case "down": + return tea.KeyMsg{Type: tea.KeyDown} + } + return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} +} + +// press sends k to the stack's top modal the way the App does. +func press(s *Stack, k string) tea.Cmd { + km := key(k) + a, _ := reg.Resolve(s.Top().Context(), km) + return s.Key(a, km) +} + +func TestDialogButtonsAndHotkeys(t *testing.T) { + var got []Outcome + open := func(d *Dialog) *Stack { + s := &Stack{} + s.Push(d, func(o Outcome) tea.Cmd { got = append(got, o); return nil }) + return s + } + quit := func() *Dialog { + return &Dialog{Title: "Quit?", Buttons: []Button{ + {Label: "Quit", Key: "q", Value: "quit", Default: true}, + {Label: "Back", Key: "n", Cancel: true}, + }} + } + + // Enter presses the default button. + s := open(quit()) + press(s, "enter") + if s.Len() != 0 || len(got) != 1 || got[0].Value != "quit" || got[0].Cancelled { + t.Fatalf("enter: %+v", got) + } + // A button hotkey wins over the dialog's cancel key (q q quits fast). + s = open(quit()) + press(s, "q") + if got[1].Value != "quit" { + t.Fatalf("q: %+v", got[1]) + } + // ЙЦУКЕН hotkey. + s = open(quit()) + press(s, "т") + if !got[2].Cancelled { + t.Fatalf("т (n): %+v", got[2]) + } + // Tab moves focus, Enter presses it. + s = open(quit()) + press(s, "tab") + press(s, "enter") + if !got[3].Cancelled { + t.Fatalf("tab enter: %+v", got[3]) + } + // Esc cancels; unknown keys keep it open. + s = open(quit()) + press(s, "z") + if s.Len() != 1 { + t.Fatal("unbound key closed the dialog") + } + press(s, "esc") + if !got[4].Cancelled { + t.Fatalf("esc: %+v", got[4]) + } + // Danger confirm: focus on Cancel, Enter cancels, y confirms. + d := Confirm("Delete permanently?", "3 items", "Delete", true) + if d.Focused() != 1 { + t.Fatal("permanent delete must default to Cancel") + } + s = open(d) + press(s, "enter") + if !got[5].Cancelled { + t.Fatal("enter on danger confirm did not cancel") + } + s = open(Confirm("Delete permanently?", "3 items", "Delete", true)) + press(s, "y") + if got[6].Value != true { + t.Fatalf("y: %+v", got[6]) + } + + // Mouse: a click on a button presses it, a click elsewhere does not. + styles := st(t) + screen := geom.Rect{W: 80, H: 24} + s = open(quit()) + box := s.Box(screen, styles) + view := ansi.Strip(s.Top().View(80, 24, styles)) + lines := strings.Split(view, "\n") + for row, l := range lines { + if col := strings.Index(l, "Back"); col >= 0 { + x := box.X + ansi.StringWidth(l[:col]) + s.Mouse(tea.MouseMsg{X: x, Y: box.Y + row, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}, screen, styles) + } + } + if len(got) != 8 || !got[7].Cancelled { + t.Fatalf("click on Back: %+v", got) + } +} + +// Crutch #10: tall modals (help, theme list) on a small terminal must fit +// and scroll. +func TestModalScrollsOnSmallTerminal(t *testing.T) { + styles := st(t) + var lines []string + for i := 0; i < 100; i++ { + lines = append(lines, fmt.Sprintf("line %03d %s", i, strings.Repeat("x", 90))) + } + s := &Stack{} + s.Push(NewText("Help", lines), nil) + screen := geom.Rect{W: 72, H: 18} + v := s.Top().View(screen.W, screen.H, styles) + if w, h := lipgloss.Width(v), lipgloss.Height(v); w > 72 || h > 18 { + t.Fatalf("modal %d×%d does not fit 72×18", w, h) + } + if !strings.Contains(ansi.Strip(v), "line 000") || strings.Contains(ansi.Strip(v), "line 050") { + t.Fatal("wrong initial window") + } + press(s, "pgdown") + v = ansi.Strip(s.Top().View(screen.W, screen.H, styles)) + if strings.Contains(v, "line 000") { + t.Fatal("PgDn did not scroll") + } + for i := 0; i < 20; i++ { + press(s, "pgdown") + } + v = ansi.Strip(s.Top().View(screen.W, screen.H, styles)) + if !strings.Contains(v, "line 099") { + t.Fatal("cannot scroll to the end") + } + + // A selectable list keeps the cursor visible. + var items []Item + for i := 0; i < 50; i++ { + items = append(items, Item{Label: fmt.Sprintf("theme-%02d", i), Value: i}) + } + var moved []any + l := NewList("Theme", items, 40) + l.OnMove = func(it Item) tea.Cmd { moved = append(moved, it.Value); return nil } + s.Push(l, nil) + v = ansi.Strip(s.Top().View(screen.W, screen.H, styles)) + if !strings.Contains(v, "theme-40") { + t.Fatal("preselected item not visible") + } + press(s, "down") + if len(moved) != 1 || moved[0] != 41 { + t.Fatalf("OnMove = %v", moved) + } + // The overlay keeps the base around the box. + base := strings.Repeat(strings.Repeat(".", 72)+"\n", 17) + strings.Repeat(".", 72) + out := ansi.Strip(s.Render(base, screen, styles)) + if lipgloss.Height(out) != 18 || !strings.HasPrefix(out, "...") { + t.Fatalf("overlay broke the base:\n%s", out) + } +} + +func TestMouseOutsideModalIgnored(t *testing.T) { + styles := st(t) + screen := geom.Rect{W: 80, H: 24} + closed := false + s := &Stack{} + s.Push(Confirm("Sure?", "text", "OK", false), func(Outcome) tea.Cmd { closed = true; return nil }) + box := s.Box(screen, styles) + s.Mouse(tea.MouseMsg{X: box.X - 1, Y: box.Y, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}, screen, styles) + s.Mouse(tea.MouseMsg{X: 0, Y: 0, Button: tea.MouseButtonLeft, Action: tea.MouseActionPress}, screen, styles) + if closed || s.Len() != 1 { + t.Fatal("click outside the modal acted") + } +} + +func TestInputTypesEverything(t *testing.T) { + in := NewInput("New directory", Field{Label: "Name"}) + in.Validate = func(v []string) error { + if strings.Contains(v[0], "/") { + return fmt.Errorf("name must not contain /") + } + return nil + } + var res Outcome + s := &Stack{} + s.Push(in, func(o Outcome) tea.Cmd { res = o; return nil }) + for _, r := range "qпапка/" { + press(s, string(r)) + } + press(s, "enter") + if s.Len() != 1 { + t.Fatal("invalid value accepted") + } + if !strings.Contains(ansi.Strip(in.View(80, 24, st(t))), "must not contain") { + t.Fatal("validation error not shown") + } + s.Key(keys.ModalClear, tea.KeyMsg{Type: tea.KeyCtrlU}) + for _, r := range "qпапка" { + press(s, string(r)) + } + press(s, "enter") + if v, ok := res.Value.([]string); !ok || v[0] != "qпапка" { + t.Fatalf("value = %#v", res.Value) + } +} diff --git a/internal/tui/modal/progress.go b/internal/tui/modal/progress.go new file mode 100644 index 0000000..e988433 --- /dev/null +++ b/internal/tui/modal/progress.go @@ -0,0 +1,105 @@ +package modal + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/keys" + "vcom/internal/tui/style" +) + +// ProgressState is what a Progress modal shows; the App updates it from job +// progress ticks. +type ProgressState struct { + Phase string + Current string + FilesDone int + FilesTotal int + BytesDone int64 + BytesTotal int64 + Waiting bool // the job waits for an answer +} + +// ProgressBackground is the Value of a Progress closed with b/Esc/Enter: the +// job goes on in the background. +const ProgressBackground = "background" + +// Progress shows a running job. b/Esc/Enter send it to the background +// (closes); c asks to cancel through OnCancel (the App opens a +// confirmation above it, so "c c" never cancels by itself; U-P1-16). +type Progress struct { + Title string + State ProgressState + OnCancel func() tea.Msg + Width int +} + +func (p *Progress) Context() keys.Context { return keys.CtxModalProgress } + +func (p *Progress) Key(a keys.ActionID, _ tea.KeyMsg) (Outcome, tea.Cmd) { + switch a { + case keys.ProgressBackground: + return Done(ProgressBackground), nil + case keys.ProgressCancel: + if p.OnCancel != nil { + return Keep, p.OnCancel + } + } + return Keep, nil +} + +func (p *Progress) Mouse(tea.MouseMsg, int, int, int, int, *style.Styles) (Outcome, tea.Cmd) { + return Keep, nil +} + +// HumanBytes formats a byte count (1.5 MiB). +func HumanBytes(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%d B", n) + } + div, exp := int64(unit), 0 + for m := n / unit; m >= unit; m /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp]) +} + +func (p *Progress) View(maxW, maxH int, st *style.Styles) string { + w := p.Width + if w == 0 { + w = 60 + } + cw := innerWidth(maxW, w) + s := p.State + var lines []string + phase := s.Phase + if s.Waiting { + phase = "waiting for your answer" + } + if phase != "" { + lines = append(lines, ansi.Truncate(phase, cw, "…")) + } + if s.Current != "" { + lines = append(lines, ansi.Truncate(s.Current, cw, "…")) + } + if s.FilesTotal > 0 { + lines = append(lines, fmt.Sprintf("Files: %d / %d", s.FilesDone, s.FilesTotal)) + } + if s.BytesTotal > 0 { + lines = append(lines, fmt.Sprintf("Bytes: %s / %s", HumanBytes(s.BytesDone), HumanBytes(s.BytesTotal))) + frac := float64(s.BytesDone) / float64(s.BytesTotal) + filled := int(frac * float64(cw)) + filled = max(0, min(cw, filled)) + lines = append(lines, strings.Repeat("█", filled)+strings.Repeat("░", cw-filled)) + } + lines = append(lines, "", st.Muted.Render(ansi.Truncate("b/Esc: background · c: cancel", cw, "…"))) + if maxH > 2 && len(lines) > maxH-3 { + lines = lines[len(lines)-(maxH-3):] + } + return frame(st, p.Title, lines, maxW) +} diff --git a/internal/tui/modal/stack.go b/internal/tui/modal/stack.go new file mode 100644 index 0000000..ce011d5 --- /dev/null +++ b/internal/tui/modal/stack.go @@ -0,0 +1,225 @@ +// Package modal is the modal stack of the new UI (design §7.5): Dialog +// (structured confirm), Input (one or more text fields), List (choices, +// help, logs). While a modal is open it gets every key and mouse event; a +// click outside it is ignored, nothing under it changes. +// +// A modal never closes itself through side effects: Key/Mouse return an +// Outcome, the Stack pops it and runs the onClose callback given to Push. +// Stage 6.2/6.4 add Progress, Conflict and Prompt modals in this package. +package modal + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/geom" + "vcom/internal/tui/keys" + "vcom/internal/tui/style" +) + +// Outcome of a key or mouse event. +type Outcome struct { + Close bool + Cancelled bool // closed by Esc/q/Ctrl+C or a Cancel button + Value any +} + +// Keep leaves the modal open. +var Keep = Outcome{} + +// Done closes with value v. +func Done(v any) Outcome { return Outcome{Close: true, Value: v} } + +// Cancel closes as cancelled. +func Cancel() Outcome { return Outcome{Close: true, Cancelled: true} } + +// Modal is one layer of the stack. +type Modal interface { + // Context selects the key table (keys.CtxModalDialog, ...). + Context() keys.Context + // Key gets the resolved action ("" if the key is unbound) and the raw + // key (text fields, button hotkeys). + Key(a keys.ActionID, k tea.KeyMsg) (Outcome, tea.Cmd) + // Mouse gets an event at (x, y) relative to the modal's top-left + // corner; w×h is the space View was given. + Mouse(m tea.MouseMsg, x, y, w, h int, st *style.Styles) (Outcome, tea.Cmd) + // View renders the modal into at most maxW×maxH cells; a modal taller + // than that scrolls itself. + View(maxW, maxH int, st *style.Styles) string +} + +type entry struct { + id uint64 + m Modal + onClose func(Outcome) tea.Cmd +} + +// Stack of modals; the top one owns input. +type Stack struct { + entries []entry + nextID uint64 +} + +// Push opens m; onClose (may be nil) runs when it closes, with its outcome. +func (s *Stack) Push(m Modal, onClose func(Outcome) tea.Cmd) uint64 { + s.nextID++ + s.entries = append(s.entries, entry{id: s.nextID, m: m, onClose: onClose}) + return s.nextID +} + +// Len is the number of open modals. +func (s *Stack) Len() int { return len(s.entries) } + +// Top returns the top modal (nil if none). +func (s *Stack) Top() Modal { + if len(s.entries) == 0 { + return nil + } + return s.entries[len(s.entries)-1].m +} + +// TopID returns the id of the top modal (0 if none). +func (s *Stack) TopID() uint64 { + if len(s.entries) == 0 { + return 0 + } + return s.entries[len(s.entries)-1].id +} + +// Has reports whether modal id is open. +func (s *Stack) Has(id uint64) bool { + for _, e := range s.entries { + if e.id == id { + return true + } + } + return false +} + +// Get returns modal id. +func (s *Stack) Get(id uint64) Modal { + for _, e := range s.entries { + if e.id == id { + return e.m + } + } + return nil +} + +// CloseByID removes modal id without running onClose (e.g. its job ended); +// it reports whether it was open. +func (s *Stack) CloseByID(id uint64) bool { + for i, e := range s.entries { + if e.id == id { + s.entries = append(s.entries[:i], s.entries[i+1:]...) + return true + } + } + return false +} + +func (s *Stack) finish(o Outcome, cmd tea.Cmd) tea.Cmd { + if !o.Close || len(s.entries) == 0 { + return cmd + } + e := s.entries[len(s.entries)-1] + s.entries = s.entries[:len(s.entries)-1] + if e.onClose != nil { + return tea.Batch(cmd, e.onClose(o)) + } + return cmd +} + +// Key routes a key to the top modal. +func (s *Stack) Key(a keys.ActionID, k tea.KeyMsg) tea.Cmd { + top := s.Top() + if top == nil { + return nil + } + return s.finish(top.Key(a, k)) +} + +// Mouse routes a mouse event to the top modal if it is inside the modal's +// box (screen is the area modals are centered in); events outside are +// swallowed. +func (s *Stack) Mouse(m tea.MouseMsg, screen geom.Rect, st *style.Styles) tea.Cmd { + top := s.Top() + if top == nil { + return nil + } + box := s.Box(screen, st) + if !box.Contains(m.X, m.Y) { + return nil + } + return s.finish(top.Mouse(m, m.X-box.X, m.Y-box.Y, screen.W, screen.H, st)) +} + +// Box is where the top modal is drawn inside screen. +func (s *Stack) Box(screen geom.Rect, st *style.Styles) geom.Rect { + top := s.Top() + if top == nil { + return geom.Rect{} + } + v := top.View(screen.W, screen.H, st) + return screen.Center(lipgloss.Width(v), lipgloss.Height(v)) +} + +// Render draws the top modal centered over base (screen-sized). +func (s *Stack) Render(base string, screen geom.Rect, st *style.Styles) string { + top := s.Top() + if top == nil { + return base + } + v := top.View(screen.W, screen.H, st) + box := screen.Center(lipgloss.Width(v), lipgloss.Height(v)) + return Overlay(base, v, box.X, box.Y) +} + +// Overlay draws box over base with its top-left corner at (x, y). +func Overlay(base, box string, x, y int) string { + lines := strings.Split(base, "\n") + for i, bl := range strings.Split(box, "\n") { + row := y + i + if row < 0 || row >= len(lines) { + continue + } + line := lines[row] + w := ansi.StringWidth(line) + if w < x { + line += strings.Repeat(" ", x-w) + w = x + } + left := ansi.Truncate(line, x, "") + right := ansi.TruncateLeft(line, x+ansi.StringWidth(bl), "") + lines[row] = left + bl + right + } + return strings.Join(lines, "\n") +} + +// frame wraps content in the modal border with a title. +func frame(st *style.Styles, title string, body []string, maxW int) string { + content := strings.Join(body, "\n") + if title != "" { + content = st.ModalTitle.Render(ansi.Truncate(title, max(1, maxW-4), "…")) + "\n" + content + } + return st.Modal.Render(content) +} + +// innerWidth is the content width for a modal given maxW (border + padding). +func innerWidth(maxW, want int) int { + return max(8, min(want, maxW-4)) +} + +// clip returns at most n lines starting at off and whether lines were cut +// above/below. +func clip(lines []string, off, n int) (out []string, above, below bool) { + if n <= 0 { + return nil, len(lines) > 0, false + } + off = max(0, min(off, max(0, len(lines)-n))) + end := min(len(lines), off+n) + return lines[off:end], off > 0, end < len(lines) +} diff --git a/internal/tui/modes.go b/internal/tui/modes.go new file mode 100644 index 0000000..e39622e --- /dev/null +++ b/internal/tui/modes.go @@ -0,0 +1,329 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/notify" + "vcom/internal/tui/viewer" + "vcom/internal/vfs" +) + +// inputOwner decides who gets the keyboard — the one place that does +// (design §7.3). +func (a *App) inputOwner() keys.Context { + switch { + case a.modals.Len() > 0: + return a.modals.Top().Context() + case a.filter != nil: + return keys.CtxFilterEdit + case a.screen == ScreenView: + return viewerCtx(a.viewer.Focus) + case a.screen == ScreenInfo && a.viewer.Focus != viewer.Scroll: + return viewerCtx(a.viewer.Focus) + case a.screen == ScreenInfo: + return keys.CtxInfo + } + return keys.CtxBrowse +} + +// InputOwner is inputOwner for tests and features. +func (a *App) InputOwner() keys.Context { return a.inputOwner() } + +func viewerCtx(f viewer.Focus) keys.Context { + switch f { + case viewer.Caret: + return keys.CtxCaret + case viewer.Visual: + return keys.CtxVisual + } + return keys.CtxViewScroll +} + +// Invariants checks the allowed state combinations (design §7.2); tests +// call it after every step. +func (a *App) Invariants() error { + var errs []error + if a.viewer.Focus != viewer.Scroll && (a.screen == ScreenBrowse || a.viewer.Kind != viewer.Text) { + errs = append(errs, fmt.Errorf("viewer focus %d on screen %s with kind %d", a.viewer.Focus, a.screen, a.viewer.Kind)) + } + if a.nativeSelect && a.screen == ScreenBrowse { + errs = append(errs, errors.New("native selection in Browse")) + } + if a.filter != nil && (a.screen == ScreenView || a.modals.Len() > 0) { + errs = append(errs, fmt.Errorf("filter edited on %s with %d modals", a.screen, a.modals.Len())) + } + if a.active != 0 && a.active != 1 { + errs = append(errs, fmt.Errorf("active pane %d", a.active)) + } + for i, p := range a.panels { + if n := p.VisibleLen(); n > 0 && (p.Cursor() < 0 || p.Cursor() >= n) { + errs = append(errs, fmt.Errorf("pane %d cursor %d of %d", i, p.Cursor(), n)) + } + } + return errors.Join(errs...) +} + +// setScreen switches the screen; leaving Info/View resets the viewer focus +// and native selection. +func (a *App) setScreen(s Screen) tea.Cmd { + if s == a.screen { + return nil + } + prev := a.screen + a.screen = s + if s == ScreenBrowse || (prev == ScreenView && s == ScreenInfo) { + a.viewer.Focus = viewer.Scroll + a.nativeSelect = false + } + if s == ScreenView && a.filter != nil { + a.commitFilter() + } + a.relayout() + switch s { + case ScreenInfo: + a.previewFor = "" + return a.requestPreview(false) + case ScreenBrowse: + a.req.Cancel(ReqKey{Kind: ReqPreview}) + a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce}) + a.previewFor = "" + } + return nil +} + +// openView is F3/v: the selected file full screen. +func (a *App) openView() tea.Cmd { + e, ok := a.Active().Selected() + if !ok || e.Parent || e.Navigable() { + return a.notify(notify.Info, "Not a file") + } + a.viewBack = a.screen + a.screen = ScreenView + a.viewer.Focus = viewer.Scroll + if a.filter != nil { + a.commitFilter() + } + a.relayout() + a.previewFor = "" + return a.requestPreview(true) +} + +// Viewer focus transitions (design §7.2). + +func (a *App) viewerFocus() tea.Cmd { + if !a.viewer.EnterCaret() { + return a.notify(notify.Info, "Preview is not text") + } + return nil +} + +func (a *App) viewerCaret() tea.Cmd { + switch a.viewer.Focus { + case viewer.Visual: + a.viewer.Focus = viewer.Caret + case viewer.Scroll: + if !a.viewer.EnterCaret() { + return a.notify(notify.Info, "Not text") + } + } + return nil +} + +func (a *App) viewerVisual() tea.Cmd { + if !a.viewer.EnterVisual() { + return a.notify(notify.Info, "Not text") + } + return nil +} + +// viewerBack is Esc: one focus step back, then close. +func (a *App) viewerBack() tea.Cmd { + if a.nativeSelect { + return a.toggleNativeSelect() + } + switch a.viewer.Focus { + case viewer.Visual: + a.viewer.Focus = viewer.Caret + return nil + case viewer.Caret: + a.viewer.Focus = viewer.Scroll + return nil + } + return a.viewerClose() +} + +// viewerClose is q/F3: close View, or drop the focus in Info. +func (a *App) viewerClose() tea.Cmd { + a.nativeSelect = false + if a.screen == ScreenView { + a.viewer.Focus = viewer.Scroll + back := a.viewBack + a.screen = back + a.relayout() + a.req.Cancel(ReqKey{Kind: ReqPreview}) + a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce}) + a.previewFor = "" + if back == ScreenInfo { + return a.requestPreview(false) + } + return nil + } + a.viewer.Focus = viewer.Scroll + return nil +} + +func (a *App) toggleNativeSelect() tea.Cmd { + if a.screen == ScreenBrowse { + return nil + } + a.nativeSelect = !a.nativeSelect + if a.nativeSelect { + return a.notify(notify.Info, "Terminal mouse selection: Ctrl+T or Esc to end") + } + return nil +} + +// Filter line. + +func (a *App) startFilter() tea.Cmd { + ti := textinput.New() + ti.Prompt = "/" + ti.SetValue(a.Active().Filter()) + ti.CursorEnd() + ti.Focus() + a.filter = &ti + a.relayout() + return nil +} + +func (a *App) commitFilter() { + a.filter = nil + a.relayout() +} + +// filterKey handles a key while the filter line owns input. +func (a *App) filterKey(act keys.ActionID, ok bool, k tea.KeyMsg) tea.Cmd { + p := a.Active() + if ok { + switch act { + case keys.FilterCommit: + a.commitFilter() + case keys.FilterCancel: + p.SetFilter("") + a.commitFilter() + case keys.FilterClearAll: + a.filter.SetValue("") + p.SetFilter("") + case keys.NavUp: + p.MoveCursor(-1) + case keys.NavDown: + p.MoveCursor(1) + } + return a.selectionChanged() + } + ti, cmd := a.filter.Update(k) + a.filter = &ti + p.SetFilter(ti.Value()) + return tea.Batch(cmd, a.selectionChanged()) +} + +// Preview requests (design §7.7): cursor moves are debounced 100 ms, one +// preview in flight per app, stale results dropped. + +const previewDebounce = 100 * time.Millisecond + +type previewTickMsg struct{ Ticket Ticket } + +type previewMsg struct { + Ticket Ticket + For string + Content viewer.Content + Err error +} + +// selectionChanged is called after anything that may move the cursor. +func (a *App) selectionChanged() tea.Cmd { + if a.screen != ScreenInfo { + return nil + } + return a.requestPreview(false) +} + +func (a *App) previewKey() (string, vfs.Location, vfs.FileInfo, bool) { + p := a.Active() + e, ok := p.Selected() + if !ok || e.Parent { + return "", vfs.Location{}, vfs.FileInfo{}, false + } + loc := p.Location() + return fmt.Sprintf("%s\x00%s\x00%s", loc.FS.Volume(), loc.Path, e.Name), loc, e.FileInfo, true +} + +func (a *App) requestPreview(now bool) tea.Cmd { + key, loc, fi, ok := a.previewKey() + if !ok { + a.req.Cancel(ReqKey{Kind: ReqPreview}) + a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce}) + a.previewFor = "" + a.viewer.Clear() + return nil + } + if key == a.previewFor { + return nil + } + a.previewFor = key + if !now { + a.req.Cancel(ReqKey{Kind: ReqPreview}) + tk, _ := a.req.Begin(ReqKey{Kind: ReqPreviewDebounce}) + return tea.Tick(previewDebounce, func(time.Time) tea.Msg { return previewTickMsg{tk} }) + } + return a.startPreview(key, loc, fi) +} + +func (a *App) startPreview(key string, loc vfs.Location, fi vfs.FileInfo) tea.Cmd { + tk, ctx := a.req.Begin(ReqKey{Kind: ReqPreview}) + build, legacy := a.deps.BuildPreview, a.deps.Preview + req := a.previewRequest(loc, fi) + limit := a.deps.Config.Preview.MaxPreviewBytes + return func() tea.Msg { + if build != nil { + res := build(ctx, req) + return previewMsg{Ticket: tk, For: key, Content: contentFromPreview(fi, res), Err: res.Err} + } + c, err := legacy(ctx, loc, fi, limit) + return previewMsg{Ticket: tk, For: key, Content: c, Err: err} + } +} + +func (a *App) onPreviewTick(m previewTickMsg) tea.Cmd { + if !a.req.Accept(m.Ticket) { + return nil + } + key, loc, fi, ok := a.previewKey() + if !ok || key != a.previewFor { + return nil + } + return a.startPreview(key, loc, fi) +} + +func (a *App) onPreview(m previewMsg) tea.Cmd { + if m.For != a.previewFor || !a.req.Accept(m.Ticket) { + return nil // stale: must not touch the viewer (U-P1-13) + } + if m.Err != nil { + if errors.Is(m.Err, context.Canceled) { + return nil + } + a.viewer.SetContent(viewer.Content{Kind: viewer.Other, Lines: []string{"Preview failed: " + cleanErr(m.Err).Error()}}) + return nil + } + a.viewer.SetContent(m.Content) + return nil +} diff --git a/internal/tui/nav.go b/internal/tui/nav.go new file mode 100644 index 0000000..0605bd2 --- /dev/null +++ b/internal/tui/nav.go @@ -0,0 +1,184 @@ +package tui + +import ( + "context" + "errors" + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +// listingMsg is the result of a directory read for pane. +type listingMsg struct { + Ticket Ticket + Pane int + Target panel.Target + Infos []vfs.FileInfo + Err error + Focus string + Mode panel.NavMode + Reload bool // refresh of the current directory (keep cursor, filter) + Climb bool // a refresh whose directory vanished: walking up +} + +// readDir is the Cmd reading t; it captures only immutable inputs. +func readDir(ctx context.Context, tk Ticket, pane int, t panel.Target, focus string, mode panel.NavMode, reload, climb bool) tea.Cmd { + return func() tea.Msg { + infos, err := t.FS().ReadDir(ctx, t.Path) + return listingMsg{Ticket: tk, Pane: pane, Target: t, Infos: infos, Err: err, Focus: focus, Mode: mode, Reload: reload, Climb: climb} + } +} + +// navigate starts the transaction "show t in pane". The panel changes only +// when the listing arrives and succeeds (U-P1-8); a newer navigation of the +// same pane makes this one stale (U-P1-13). +func (a *App) navigate(pane int, t panel.Target, focus string, mode panel.NavMode) tea.Cmd { + tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: pane}) + a.panels[pane].Loading = true + return readDir(ctx, tk, pane, t, focus, mode, false, false) +} + +// reload re-reads the current directory of pane. +func (a *App) reload(pane int) tea.Cmd { + p := a.panels[pane] + if p.Source != panel.SourceDir { + return nil + } + tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: pane}) + p.Loading = true + return readDir(ctx, tk, pane, p.Here(), "", panel.NavReplace, true, false) +} + +// invalidate reloads every panel showing one of locs (after an operation: +// each panel keeps its own cursor; U-P1-7, N-P1-11). +func (a *App) invalidate(locs []vfs.Location) tea.Cmd { + var cmds []tea.Cmd + for i, p := range a.panels { + for _, l := range locs { + if p.Location().Same(l) { + cmds = append(cmds, a.reload(i)) + break + } + } + } + return tea.Batch(cmds...) +} + +func (a *App) onListing(m listingMsg) tea.Cmd { + if !a.req.Accept(m.Ticket) { + return nil // stale: a newer navigation of this pane won + } + p := a.panels[m.Pane] + p.Loading = false + if m.Err != nil { + if (m.Reload || m.Climb) && errors.Is(m.Err, vfs.ErrNotExist) { + // The directory vanished: walk up to the nearest existing parent. + tmp := panel.New(-1, p.Opts, m.Target.Mounts, m.Target.Path) + if t, _, _, ok := tmp.ParentTarget(); ok { + tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: m.Pane}) + p.Loading = true + return readDir(ctx, tk, m.Pane, t, "", panel.NavReplace, false, true) + } + } + if errors.Is(m.Err, context.Canceled) { + return nil + } + return a.notify(notify.Error, fmt.Sprintf("Cannot open %s: %v", displayPath(m.Target.Location()), cleanErr(m.Err))) + } + if m.Reload { + p.Reload(m.Infos) + } else { + p.Apply(m.Target, m.Infos, m.Focus, m.Mode) + } + var cmd tea.Cmd + if m.Climb { + cmd = a.notify(notify.Warn, "Directory vanished, moved up to "+displayPath(p.Location())) + } + if m.Pane == a.active { + return tea.Batch(cmd, a.selectionChanged()) + } + return cmd +} + +// openSelected is Enter: go into directories (and links to them), up on +// "..". Files are dispatched by stage 6.6 (edit / run menu / xdg-open). +func (a *App) openSelected() tea.Cmd { + e, ok := a.Active().Selected() + if !ok { + return nil + } + if e.Parent { + return a.goParent() + } + if e.Navigable() { + return a.enterSelected() + } + if a.openFile != nil { + return a.openFile(a, e) + } + return a.notify(notify.Info, "Opening files: not available yet") +} + +// enterSelected is l/→: enter a directory; nothing on files. +func (a *App) enterSelected() tea.Cmd { + p := a.Active() + e, ok := p.Selected() + if !ok { + return nil + } + if e.Parent { + return a.goParent() + } + if !e.Navigable() { + return nil + } + return a.navigate(a.active, p.ChildTarget(e.Name), "", panel.NavPush) +} + +// goParent is h/←/Backspace and Enter on "..". +func (a *App) goParent() tea.Cmd { + p := a.Active() + t, focus, _, ok := p.ParentTarget() + if !ok { + return nil + } + return a.navigate(a.active, t, focus, panel.NavPush) +} + +// history goes back (or forward) in the active panel. +func (a *App) history(forward bool) tea.Cmd { + p := a.Active() + snap, ok := p.BackTarget() + mode := panel.NavBack + if forward { + snap, ok = p.ForwardTarget() + mode = panel.NavForward + } + if !ok { + return nil + } + return a.navigate(a.active, snap.Target, snap.Focus, mode) +} + +// displayPath renders a location for messages and titles. +func displayPath(l vfs.Location) string { + if l.FS == nil || l.FS.Kind() == vfs.KindLocal { + return l.Path + } + return l.FS.Label() + ":" + l.Path +} + +// cleanErr drops the "op path:" prefix of a path error (the message +// already names the path). +func cleanErr(err error) error { + if u, ok := err.(interface{ Unwrap() error }); ok { + if in := u.Unwrap(); in != nil { + return in + } + } + return err +} diff --git a/internal/tui/notify/notify.go b/internal/tui/notify/notify.go new file mode 100644 index 0000000..a183bc3 --- /dev/null +++ b/internal/tui/notify/notify.go @@ -0,0 +1,142 @@ +// Package notify is the notification center of the new UI (design §7.6): +// short messages shown in the status line with a time-to-live by level and +// a log of the last 200 for the "L" list. Notifications are not modals, so +// a timer can only ever hide its own note (U-P1-1, crutch #13). +// +// The center does no timing itself: Push returns the note and its TTL; the +// App schedules tea.Tick(ttl, expiredMsg{ID}) and calls Expire(ID) — only +// that note is affected. Errors stay until a key is pressed after the TTL. +package notify + +import "time" + +// Level of a note. +type Level uint8 + +const ( + Info Level = iota + Success + Warn + Error +) + +func (l Level) String() string { + switch l { + case Info: + return "info" + case Success: + return "ok" + case Warn: + return "warn" + case Error: + return "error" + } + return "?" +} + +// TTL is how long a note of level l stays: Info/Success 3 s, Warn 6 s, +// Error at least 3 s and then until the next key press. +func TTL(l Level) time.Duration { + if l == Warn { + return 6 * time.Second + } + return 3 * time.Second +} + +// LogSize is how many notes Log keeps. +const LogSize = 200 + +// Note is one notification. +type Note struct { + ID uint64 + Level Level + Text string + At time.Time + + ttlDone bool // the TTL timer fired + keyHit bool // (Error) a key was pressed after Push + hidden bool +} + +// Center holds notes. Not safe for concurrent use (UI goroutine only). +type Center struct { + nextID uint64 + live []*Note // not yet hidden, oldest first + log []Note // ring, oldest first +} + +// Push adds a note and returns it; schedule Expire(n.ID) after TTL(n.Level). +func (c *Center) Push(l Level, text string, now time.Time) Note { + c.nextID++ + n := &Note{ID: c.nextID, Level: l, Text: text, At: now} + c.live = append(c.live, n) + c.log = append(c.log, *n) + if len(c.log) > LogSize { + c.log = c.log[len(c.log)-LogSize:] + } + return *n +} + +// Expire is called when the TTL timer of note id fires. It hides that note +// only — an Error note stays until a key was pressed. +func (c *Center) Expire(id uint64) { + for _, n := range c.live { + if n.ID != id { + continue + } + n.ttlDone = true + if n.Level != Error || n.keyHit { + n.hidden = true + } + } + c.compact() +} + +// KeyPressed dismisses Error notes whose minimum time has passed and marks +// younger ones to go when their timer fires. +func (c *Center) KeyPressed() { + for _, n := range c.live { + if n.Level != Error { + continue + } + n.keyHit = true + if n.ttlDone { + n.hidden = true + } + } + c.compact() +} + +// Dismiss hides note id at once. +func (c *Center) Dismiss(id uint64) { + for _, n := range c.live { + if n.ID == id { + n.hidden = true + } + } + c.compact() +} + +func (c *Center) compact() { + out := c.live[:0] + for _, n := range c.live { + if !n.hidden { + out = append(out, n) + } + } + for i := len(out); i < len(c.live); i++ { + c.live[i] = nil + } + c.live = out +} + +// Current is the note to show: the newest one still alive. +func (c *Center) Current() (Note, bool) { + if len(c.live) == 0 { + return Note{}, false + } + return *c.live[len(c.live)-1], true +} + +// Log returns the last LogSize notes, oldest first. +func (c *Center) Log() []Note { return append([]Note(nil), c.log...) } diff --git a/internal/tui/notify/notify_test.go b/internal/tui/notify/notify_test.go new file mode 100644 index 0000000..6f99437 --- /dev/null +++ b/internal/tui/notify/notify_test.go @@ -0,0 +1,81 @@ +package notify + +import ( + "fmt" + "testing" + "time" +) + +var t0 = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + +func TestNoteTTLByLevel(t *testing.T) { + if TTL(Info) != 3*time.Second || TTL(Success) != 3*time.Second || TTL(Warn) != 6*time.Second || TTL(Error) != 3*time.Second { + t.Fatal("TTL table") + } + var c Center + info := c.Push(Info, "copied", t0) + c.Expire(info.ID) + if _, ok := c.Current(); ok { + t.Fatal("info survived its TTL") + } + + // Error: the timer alone does not hide it; a key afterwards does. + e := c.Push(Error, "boom", t0) + c.Expire(e.ID) + if n, ok := c.Current(); !ok || n.ID != e.ID { + t.Fatal("error hidden by its timer without a key press") + } + c.KeyPressed() + if _, ok := c.Current(); ok { + t.Fatal("error not dismissed by a key after its TTL") + } + + // Error: a key before the minimum time does not hide it at once. + e2 := c.Push(Error, "boom2", t0) + c.KeyPressed() + if n, ok := c.Current(); !ok || n.ID != e2.ID { + t.Fatal("error dismissed before its minimum time") + } + c.Expire(e2.ID) + if _, ok := c.Current(); ok { + t.Fatal("error with an earlier key press not hidden when its timer fired") + } +} + +// Crutch #13: a timer closed whatever was showing. +func TestTimerClosesOnlyOwnNote(t *testing.T) { + var c Center + a := c.Push(Info, "a", t0) + b := c.Push(Warn, "b", t0) + c.Expire(a.ID) + if n, ok := c.Current(); !ok || n.ID != b.ID { + t.Fatalf("current = %+v %v, want b", n, ok) + } + c.Expire(a.ID) // twice: no effect + c.Expire(999) // unknown: no effect + if n, _ := c.Current(); n.ID != b.ID { + t.Fatal("stray expire hid b") + } + c.Expire(b.ID) + if _, ok := c.Current(); ok { + t.Fatal("b survived") + } + // An older live note shows again when a newer one goes. + x := c.Push(Warn, "x", t0) + y := c.Push(Info, "y", t0) + c.Expire(y.ID) + if n, _ := c.Current(); n.ID != x.ID { + t.Fatal("older note not shown") + } +} + +func TestLogRing(t *testing.T) { + var c Center + for i := 0; i < LogSize+50; i++ { + c.Push(Info, fmt.Sprint(i), t0) + } + l := c.Log() + if len(l) != LogSize || l[0].Text != "50" || l[len(l)-1].Text != fmt.Sprint(LogSize+49) { + t.Fatalf("log: %d entries, first %q", len(l), l[0].Text) + } +} diff --git a/internal/tui/ops_delete.go b/internal/tui/ops_delete.go new file mode 100644 index 0000000..bfb0e1d --- /dev/null +++ b/internal/tui/ops_delete.go @@ -0,0 +1,215 @@ +package tui + +import ( + "context" + "errors" + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/jobs" + "vcom/internal/transfer" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +func (a *App) canDelete() error { + p := a.Active() + switch { + case p.Source != panel.SourceDir: + return errors.New("nothing to delete here") + case p.FS().Caps().ReadOnly: + return errors.New("this panel is read-only (archive)") + } + if es, _ := p.Targets(); len(es) == 0 { + return errors.New("nothing selected") + } + return nil +} + +// trashSelected is F8/Delete/x: move to the trash (D9, U-P0-4). Without a +// trash on this FS (SSH) it offers permanent deletion, default Cancel. +func (a *App) trashSelected() tea.Cmd { + p := a.Active() + paths, names, hidden := a.opTargets() + fsys, here := p.FS(), p.Here() + tr, ok := fsys.(vfs.Trasher) + if !ok || !fsys.Caps().Trash { + return a.confirmPermanent(here, paths, names, hidden, fmt.Sprintf("%s has no trash.", fsys.Label())) + } + start := func() tea.Cmd { + return a.startJob("trash", "Trash "+describe(names), trashJob(tr, here.Location(), paths), (*App).finishTrash, holdMounts(here)...) + } + if !a.deps.Config.Behavior.ConfirmDelete && hidden == 0 { + return start() + } + d := &modal.Dialog{ + Title: fmt.Sprintf("Move %s to the trash?", describe(names)), + Fields: []modal.KV{{Label: "From", Value: displayPath(here.Location())}}, + Buttons: []modal.Button{ + {Label: "Move to trash", Key: "y", Value: true, Default: true}, + {Label: "Cancel", Key: "n", Cancel: true}, + }, + } + if hidden > 0 { + d.Warnings = []string{fmt.Sprintf("%d marked item(s) hidden by the filter are NOT included", hidden)} + } + a.openModal(d, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + return start() + }) + return nil +} + +// deleteSelected is Shift+F8/X: permanent deletion, always confirmed, +// default Cancel. +func (a *App) deleteSelected() tea.Cmd { + p := a.Active() + paths, names, hidden := a.opTargets() + return a.confirmPermanent(p.Here(), paths, names, hidden, "") +} + +func (a *App) confirmPermanent(here panel.Target, paths, names []string, hidden int, why string) tea.Cmd { + d := &modal.Dialog{ + Title: fmt.Sprintf("Delete %s permanently?", describe(names)), + Fields: []modal.KV{{Label: "From", Value: displayPath(here.Location())}}, + Text: []string{"This cannot be undone."}, + Buttons: []modal.Button{ + {Label: "Delete permanently", Key: "d", Value: true, Danger: true}, + {Label: "Cancel", Key: "n", Cancel: true, Default: true}, + }, + } + if why != "" { + d.Text = append([]string{why}, d.Text...) + } + if len(names) > 1 && len(names) <= 10 { + for _, n := range names { + d.Fields = append(d.Fields, modal.KV{Label: "•", Value: n}) + } + } + if hidden > 0 { + d.Warnings = []string{fmt.Sprintf("%d marked item(s) hidden by the filter are NOT included", hidden)} + } + a.openModal(d, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + return a.startJob("delete", "Delete "+describe(names), deleteJob(here.FS(), here.Location(), paths), nil, holdMounts(here)...) + }) + return nil +} + +// trashResult is what a trash job returns. +type trashResult struct { + Here panel.Target + Done int + Failed []string // refused by the trash: offered for permanent deletion + Errs []error + Loc vfs.Location +} + +func trashJob(tr vfs.Trasher, loc vfs.Location, paths []string) jobs.Func { + return func(ctx context.Context, h *jobs.Handle) (any, error) { + res := trashResult{Loc: loc} + for i, p := range paths { + if err := ctx.Err(); err != nil { + return res, err + } + h.SetProgress(jobs.Progress{Phase: "moving to trash", Current: p, FilesDone: i, FilesTotal: len(paths)}) + if err := tr.Trash(ctx, p); err != nil { + res.Failed = append(res.Failed, p) // keep going: only refused items are offered (QA-17) + res.Errs = append(res.Errs, err) + continue + } + res.Done++ + } + return res, nil + } +} + +func (a *App) finishTrash(s jobs.Snapshot) tea.Cmd { + res, _ := s.Result.(trashResult) + cmds := []tea.Cmd{a.invalidate([]vfs.Location{res.Loc})} + switch { + case s.State == jobs.Cancelled: + cmds = append(cmds, a.notify(notify.Warn, fmt.Sprintf("Trash cancelled (%d moved)", res.Done))) + case len(res.Failed) > 0: + var names []string + for _, p := range res.Failed { + names = append(names, res.Loc.FS.Paths().Base(p)) + } + here := panel.Target{Mounts: nil, Path: res.Loc.Path} + if p := a.panelAt(res.Loc); p != nil { + here = p.Here() + } + if len(here.Mounts) == 0 { + break + } + why := fmt.Sprintf("The trash refused %d item(s): %v", len(res.Failed), cleanErr(res.Errs[0])) + cmds = append(cmds, a.confirmPermanent(here, res.Failed, names, 0, why)) + default: + cmds = append(cmds, a.notify(notify.Success, fmt.Sprintf("Moved %d item(s) to the trash", res.Done))) + } + return tea.Batch(cmds...) +} + +// panelAt returns a panel standing at loc. +func (a *App) panelAt(loc vfs.Location) *panel.Model { + for _, p := range a.panels { + if p.Location().Same(loc) { + return p + } + } + return nil +} + +// deleteJob removes trees without following links (vfs.RemoveTree), asking +// on errors (Retry/Skip/Skip all/Abort). +func deleteJob(fsys vfs.FS, loc vfs.Location, paths []string) jobs.Func { + return func(ctx context.Context, h *jobs.Handle) (any, error) { + rep := transfer.Report{Affected: []vfs.Location{loc}} + removed, skipAll := 0, false + for i := 0; i < len(paths); i++ { + p := paths[i] + h.SetProgress(jobs.Progress{Phase: "deleting", Current: p, FilesDone: i, FilesTotal: len(paths)}) + err := vfs.RemoveTree(ctx, fsys, p, func(n int) { + h.SetProgress(jobs.Progress{Phase: "deleting", Current: p, FilesDone: i, FilesTotal: len(paths), BytesDone: int64(removed + n)}) + }) + if err == nil { + rep.Done++ + continue + } + if ctx.Err() != nil { + rep.Cancelled = true + return rep, ctx.Err() + } + ie := transfer.ItemError{Item: transfer.Item{Rel: fsys.Paths().Base(p)}, Op: "delete", Err: err} + act := transfer.ErrorSkip + if !skipAll { + ans, aerr := h.Ask(ctx, askItemError{E: ie}) + if aerr != nil { + return rep, aerr + } + act, _ = ans.(transfer.ErrorAction) + } + switch act { + case transfer.ErrorRetry: + i-- + continue + case transfer.ErrorSkipRest: + skipAll = true + case transfer.ErrorStop: + rep.Failed++ + rep.Errors = append(rep.Errors, ie) + return rep, transfer.ErrAborted + } + rep.Failed++ + rep.Errors = append(rep.Errors, ie) + } + return rep, nil + } +} diff --git a/internal/tui/ops_dirsize.go b/internal/tui/ops_dirsize.go new file mode 100644 index 0000000..a7713a8 --- /dev/null +++ b/internal/tui/ops_dirsize.go @@ -0,0 +1,69 @@ +package tui + +import ( + "context" + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/jobs" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/vfs" +) + +type dirSizeResult struct { + Loc vfs.Location // directory holding the entry + Name string + Size vfs.SizeResult +} + +// dirSize is Space: compute the size of the directory under the cursor in +// the background; unreadable subdirectories make it "≥ X" (N-P1-14). +func (a *App) dirSize() tea.Cmd { + p := a.Active() + e, ok := p.Selected() + if !ok || e.Parent || !e.NavigableDir() { + return a.notify(notify.Info, "Directory size: put the cursor on a directory") + } + loc, name := p.Location(), e.Name + fsys, path := p.FS(), p.FS().Paths().Join(p.Path(), e.Name) + fn := func(ctx context.Context, h *jobs.Handle) (any, error) { + r, err := vfs.DirSize(ctx, fsys, path, func(s vfs.SizeResult) { + h.SetProgress(jobs.Progress{Phase: "counting", Current: path, FilesDone: s.Files, BytesDone: s.Bytes}) + }) + return dirSizeResult{Loc: loc, Name: name, Size: r}, err + } + return a.startJobOpts("dirsize", "Size of "+name, true, fn, (*App).finishDirSize, holdMounts(p.Here())...) +} + +// SizeText renders a DirSize result: "12.3 MiB" or "≥ 12.3 MiB (2 unreadable)". +func SizeText(r vfs.SizeResult) string { + if r.Unreadable > 0 { + return fmt.Sprintf("≥ %s (%d unreadable)", modal.HumanBytes(r.Bytes), r.Unreadable) + } + return modal.HumanBytes(r.Bytes) +} + +func (a *App) finishDirSize(s jobs.Snapshot) tea.Cmd { + res, _ := s.Result.(dirSizeResult) + if s.State != jobs.Done { + if s.State == jobs.Cancelled { + return nil + } + return a.notify(notify.Error, fmt.Sprintf("Size of %s: %v", res.Name, cleanErr(s.Err))) + } + label := SizeText(res.Size) + short := modal.HumanBytes(res.Size.Bytes) + if res.Size.Unreadable > 0 { + short = "≥" + short + } + if p := a.panelAt(res.Loc); p != nil { + p.SetSizeLabel(res.Name, short) + } + lvl := notify.Info + if res.Size.Unreadable > 0 { + lvl = notify.Warn + } + return a.notify(lvl, fmt.Sprintf("%s: %s, %d files, %d dirs", res.Name, label, res.Size.Files, res.Size.Dirs)) +} diff --git a/internal/tui/ops_joblist.go b/internal/tui/ops_joblist.go new file mode 100644 index 0000000..70e4d18 --- /dev/null +++ b/internal/tui/ops_joblist.go @@ -0,0 +1,43 @@ +package tui + +import ( + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/jobs" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" +) + +// jobsList is B: running and recent jobs; Enter brings a running one back +// to the foreground. +func (a *App) jobsList() tea.Cmd { + if a.deps.Jobs == nil { + return a.notify(notify.Info, "No background jobs") + } + snaps := a.deps.Jobs.Snapshot() + if len(snaps) == 0 { + return a.notify(notify.Info, "No background jobs") + } + var items []modal.Item + for i := len(snaps) - 1; i >= 0; i-- { + s := snaps[i] + detail := s.State.String() + if !s.State.Finished() && s.Progress.BytesTotal > 0 { + detail = fmt.Sprintf("%s %d%%", detail, s.Progress.BytesDone*100/s.Progress.BytesTotal) + } + items = append(items, modal.Item{Label: s.Title, Detail: detail, Value: s.ID}) + } + l := modal.NewList("Jobs", items, nil) + a.openModal(l, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + if id, ok := o.Value.(jobs.ID); ok { + a.showProgress(id) + } + return nil + }) + return nil +} diff --git a/internal/tui/ops_jobs.go b/internal/tui/ops_jobs.go new file mode 100644 index 0000000..40c1735 --- /dev/null +++ b/internal/tui/ops_jobs.go @@ -0,0 +1,384 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/jobs" + "vcom/internal/transfer" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/vfs" +) + +// opsState is the UI side of background operations (6.2, 6.5). +type opsState struct { + jobs map[jobs.ID]*opJob + questions map[uint64]uint64 // question id → modal id +} + +// opJob is a job started by the UI. +type opJob struct { + title string + progress uint64 // modal id of its Progress (0 = in the background) + state modal.ProgressState + // onFinish turns the job result into UI updates (summary, reloads, the + // permanent-delete offer, ...). nil → default summary of a Report. + onFinish func(a *App, s jobs.Snapshot) tea.Cmd +} + +// Ask payloads of UI jobs; the answer types are noted. +type ( + askPlan struct { // → transfer.ConflictPolicy, or nil to cancel + Verb string + Plan *transfer.Plan + Hidden int + } + askConflict struct{ C transfer.Conflict } // → transfer.Resolution + askItemError struct{ E transfer.ItemError } // → transfer.ErrorAction + askConfirm struct{ D *modal.Dialog } // → the pressed button's Value, nil if cancelled +) + +type progressCancelMsg struct{ ID jobs.ID } + +func registerOpsState(a *App) { + if a.ops == nil { + a.ops = &opsState{jobs: map[jobs.ID]*opJob{}, questions: map[uint64]uint64{}} + a.onJob((*App).opsJobEvent) + a.handle(func(a *App, msg tea.Msg) (tea.Cmd, bool) { + if m, ok := msg.(progressCancelMsg); ok { + return a.askCancelJob(m.ID), true + } + return nil, false + }) + } +} + +// startJob runs fn as a job with a Progress modal in front. +func (a *App) startJob(kind jobs.Kind, title string, fn jobs.Func, onFinish func(*App, jobs.Snapshot) tea.Cmd, holds ...jobs.Releaser) tea.Cmd { + return a.startJobOpts(kind, title, false, fn, onFinish, holds...) +} + +// startJobOpts is startJob; background starts it without a Progress modal +// (directory size). +func (a *App) startJobOpts(kind jobs.Kind, title string, background bool, fn jobs.Func, onFinish func(*App, jobs.Snapshot) tea.Cmd, holds ...jobs.Releaser) tea.Cmd { + if a.deps.Jobs == nil { + for _, h := range holds { + h.Release() + } + return a.notify(notify.Error, "Background jobs are not available") + } + id := a.deps.Jobs.Start(kind, title, fn, holds...) + j := &opJob{title: title, onFinish: onFinish, state: modal.ProgressState{Phase: "starting"}} + a.ops.jobs[id] = j + if background { + a.deps.Jobs.SetBackground(id, true) + } else { + a.showProgress(id) + } + return nil +} + +// showProgress opens (or reopens from the background) a job's Progress. +func (a *App) showProgress(id jobs.ID) { + j := a.ops.jobs[id] + if j == nil || (j.progress != 0 && a.modals.Has(j.progress)) { + return + } + p := &modal.Progress{Title: j.title, State: j.state, OnCancel: func() tea.Msg { return progressCancelMsg{id} }} + j.progress = a.openModal(p, func(o modal.Outcome) tea.Cmd { + j.progress = 0 + if a.deps.Jobs != nil { + a.deps.Jobs.SetBackground(id, true) + } + return nil + }) + if a.deps.Jobs != nil { + a.deps.Jobs.SetBackground(id, false) + } +} + +// askCancelJob confirms cancelling (default: keep running). +func (a *App) askCancelJob(id jobs.ID) tea.Cmd { + j := a.ops.jobs[id] + if j == nil { + return nil + } + d := &modal.Dialog{ + Title: "Cancel " + j.title + "?", + Text: []string{"Files already done stay; the file in progress is removed."}, + Buttons: []modal.Button{ + {Label: "Cancel operation", Key: "y", Value: true, Danger: true}, + {Label: "Continue", Key: "n", Cancel: true, Default: true}, + }, + } + a.openModal(d, func(o modal.Outcome) tea.Cmd { + if !o.Cancelled && a.deps.Jobs != nil { + a.deps.Jobs.Cancel(id) + } + return nil + }) + return nil +} + +func (a *App) opsJobEvent(m jobEvent) tea.Cmd { + switch e := m.E.(type) { + case jobs.ProgressTick: + for _, s := range e.Snapshots { + a.updateProgress(s) + } + case jobs.Started: + a.updateProgress(e.Snapshot) + case jobs.Asked: + return a.onAsked(e.Question) + case jobs.Unasked: + if mid, ok := a.ops.questions[e.Question.QID]; ok { + a.modals.CloseByID(mid) + delete(a.ops.questions, e.Question.QID) + } + case jobs.Finished: + j := a.ops.jobs[e.Snapshot.ID] + if j == nil { + return nil + } + delete(a.ops.jobs, e.Snapshot.ID) + if j.progress != 0 { + a.modals.CloseByID(j.progress) + } + if j.onFinish != nil { + return j.onFinish(a, e.Snapshot) + } + return a.finishReport(e.Snapshot) + } + return nil +} + +func (a *App) updateProgress(s jobs.Snapshot) { + j := a.ops.jobs[s.ID] + if j == nil { + return + } + p := s.Progress + j.state = modal.ProgressState{Phase: p.Phase, Current: p.Current, FilesDone: p.FilesDone, FilesTotal: p.FilesTotal, + BytesDone: p.BytesDone, BytesTotal: p.BytesTotal, Waiting: s.State == jobs.Waiting} + if j.progress != 0 { + if pm, ok := a.modals.Get(j.progress).(*modal.Progress); ok { + pm.State = j.state + } + } +} + +// onAsked opens the dialog for a job question; the answer goes back +// through Manager.Answer. +func (a *App) onAsked(q jobs.Question) tea.Cmd { + var d *modal.Dialog + var answer func(o modal.Outcome) any + switch p := q.Payload.(type) { + case askPlan: + d, answer = planDialog(p) + case askConflict: + d, answer = conflictDialog(p.C) + case askItemError: + d = modal.ItemError("Error", p.E.Item.Rel, fmt.Sprintf("%s: %v", p.E.Op, cleanErr(p.E.Err))) + answer = func(o modal.Outcome) any { + switch o.Value { + case modal.ErrorRetry: + return transfer.ErrorRetry + case modal.ErrorSkipAll: + return transfer.ErrorSkipRest + case modal.ErrorAbort: + return transfer.ErrorStop + } + return transfer.ErrorSkip + } + case askConfirm: + d = p.D + answer = func(o modal.Outcome) any { + if o.Cancelled { + return nil + } + return o.Value + } + default: + return nil // someone else's question (SSH prompts: 6.4) + } + qid := q.QID + mid := a.openModal(d, func(o modal.Outcome) tea.Cmd { + delete(a.ops.questions, qid) + if a.deps.Jobs != nil { + a.deps.Jobs.Answer(qid, answer(o)) + } + return nil + }) + a.ops.questions[qid] = mid + return nil +} + +func planDialog(p askPlan) (*modal.Dialog, func(modal.Outcome) any) { + pl := p.Plan + d := &modal.Dialog{ + Title: fmt.Sprintf("%s %d item(s)?", p.Verb, len(rootsOf(pl))), + Fields: []modal.KV{ + {Label: "Files", Value: fmt.Sprintf("%d (%s)", pl.TotalFiles, modal.HumanBytes(pl.TotalBytes))}, + {Label: "To", Value: displayPath(vfs.Location{FS: pl.Req.To, Path: pl.Req.ToDir})}, + }, + Width: 64, + } + if n := len(pl.Conflicts); n > 0 { + d.Fields = append(d.Fields, modal.KV{Label: "Existing", Value: fmt.Sprintf("%d item(s) already exist in the target", n)}) + } + if p.Hidden > 0 { + d.Warnings = append(d.Warnings, fmt.Sprintf("%d marked item(s) hidden by the filter are NOT included", p.Hidden)) + } + for i, w := range pl.Warnings { + if i == 5 { + d.Warnings = append(d.Warnings, fmt.Sprintf("… and %d more warnings", len(pl.Warnings)-5)) + break + } + d.Warnings = append(d.Warnings, w) + } + pol := pl.Req.Opts.Conflict + if len(pl.Conflicts) == 0 { + d.Buttons = []modal.Button{ + {Label: p.Verb, Key: "y", Value: pol, Default: true}, + {Label: "Cancel", Key: "n", Cancel: true}, + } + } else { + d.Buttons = []modal.Button{ + {Label: p.Verb + ", ask", Key: "y", Value: transfer.Ask, Default: true}, + {Label: "Overwrite all", Key: "o", Value: transfer.Overwrite, Danger: true}, + {Label: "Skip existing", Key: "s", Value: transfer.Skip}, + {Label: "Overwrite older", Key: "u", Value: transfer.OverwriteOlder}, + {Label: "Cancel", Key: "n", Cancel: true}, + } + } + return d, func(o modal.Outcome) any { + if o.Cancelled { + return nil + } + return o.Value + } +} + +func rootsOf(pl *transfer.Plan) []transfer.Item { + var out []transfer.Item + for _, it := range pl.Items { + if !strings.Contains(it.Rel, "/") { + out = append(out, it) + } + } + return out +} + +func conflictDialog(c transfer.Conflict) (*modal.Dialog, func(modal.Outcome) any) { + src := c.Item + fields := []modal.KV{{Label: "Name", Value: src.Rel}} + desc := func(kind string, size int64, mt time.Time) string { + return fmt.Sprintf("%s, %s, %s", kind, modal.HumanBytes(size), mt.Format("2006-01-02 15:04")) + } + fields = append(fields, modal.KV{Label: "Source", Value: desc(src.Kind.String(), src.Size, src.ModTime)}) + if ex := src.Existing; ex != nil { + kind := "file" + switch { + case ex.IsDir(): + kind = "dir" + case ex.IsSymlink(): + kind = "symlink" + } + fields = append(fields, modal.KV{Label: "Target", Value: desc(kind, ex.Size, ex.ModTime)}) + } + d := modal.Conflict("Target exists", fields, c.Kind == transfer.TypeMismatch) + return d, func(o modal.Outcome) any { + switch o.Value { + case modal.ConflictOverwrite: + return transfer.Resolution{Action: transfer.ResolveOverwrite} + case modal.ConflictOverwriteAll: + return transfer.Resolution{Action: transfer.ResolveOverwrite, ApplyToAll: true} + case modal.ConflictKeepBoth: + return transfer.Resolution{Action: transfer.ResolveKeepBoth} + case modal.ConflictKeepBothAll: + return transfer.Resolution{Action: transfer.ResolveKeepBoth, ApplyToAll: true} + case modal.ConflictSkipAll: + return transfer.Resolution{Action: transfer.ResolveSkip, ApplyToAll: true} + case modal.ConflictAbort: + return transfer.Resolution{Action: transfer.ResolveAbort} + } + return transfer.Resolution{Action: transfer.ResolveSkip} + } +} + +// transferHooks connects transfer.Execute to a job: progress to the +// manager (it throttles), conflicts and item errors to the user. +func transferHooks(h *jobs.Handle) transfer.Hooks { + return transfer.Hooks{ + Progress: func(p transfer.Progress) { + phase := [...]string{"scanning", "copying", "removing", "finishing"}[p.Phase] + h.SetProgress(jobs.Progress{Phase: phase, Current: p.Current, FilesDone: p.FilesDone, + FilesTotal: p.FilesTotal, BytesDone: p.BytesDone, BytesTotal: p.BytesTotal}) + }, + ProgressInterval: 20 * time.Millisecond, + Resolve: func(ctx contextT, c transfer.Conflict) (transfer.Resolution, error) { + ans, err := h.Ask(ctx, askConflict{C: c}) + if err != nil { + return transfer.Resolution{}, err + } + r, _ := ans.(transfer.Resolution) + return r, nil + }, + OnError: func(ctx contextT, e transfer.ItemError) (transfer.ErrorAction, error) { + ans, err := h.Ask(ctx, askItemError{E: e}) + if err != nil { + return transfer.ErrorStop, err + } + act, _ := ans.(transfer.ErrorAction) + return act, nil + }, + } +} + +// finishReport is the default end of a job whose result is a Report. +func (a *App) finishReport(s jobs.Snapshot) tea.Cmd { + rep, _ := s.Result.(transfer.Report) + return tea.Batch(a.invalidate(rep.Affected), a.reportSummary(s, rep)) +} + +func (a *App) reportSummary(s jobs.Snapshot, rep transfer.Report) tea.Cmd { + var parts []string + if rep.Done > 0 { + parts = append(parts, fmt.Sprintf("%d done", rep.Done)) + } + if rep.Skipped > 0 { + parts = append(parts, fmt.Sprintf("%d skipped", rep.Skipped)) + } + if rep.Failed > 0 { + parts = append(parts, fmt.Sprintf("%d failed", rep.Failed)) + } + sum := strings.Join(parts, ", ") + if sum == "" { + sum = "nothing to do" + } + switch { + case s.State == jobs.Cancelled || rep.Cancelled: + return a.notify(notify.Warn, fmt.Sprintf("%s: cancelled (%s)", s.Title, sum)) + case s.Err != nil && !errors.Is(s.Err, errUserCancelled): + return a.notify(notify.Error, fmt.Sprintf("%s failed: %v (%s)", s.Title, cleanErr(s.Err), sum)) + case errors.Is(s.Err, errUserCancelled): + return nil + case rep.Failed > 0: + first := rep.Errors[0] + return a.notify(notify.Error, fmt.Sprintf("%s: %s; %s: %v", s.Title, sum, first.Item.Rel, cleanErr(first.Err))) + case len(rep.Warnings) > 0: + return a.notify(notify.Warn, fmt.Sprintf("%s: %s; %s", s.Title, sum, rep.Warnings[0])) + } + return a.notify(notify.Success, fmt.Sprintf("%s: %s", s.Title, sum)) +} + +// errUserCancelled: the user said no to the plan dialog (not a failure). +var errUserCancelled = errors.New("cancelled by the user") + +type contextT = context.Context diff --git a/internal/tui/ops_mkdir_rename.go b/internal/tui/ops_mkdir_rename.go new file mode 100644 index 0000000..b4f27c2 --- /dev/null +++ b/internal/tui/ops_mkdir_rename.go @@ -0,0 +1,121 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +// validName rejects names that are not a single path element (U-P2: "a/b" +// used to create or move into subdirectories silently). +func validName(name string) error { + switch { + case strings.TrimSpace(name) == "": + return errors.New("name is empty") + case strings.ContainsAny(name, "/\x00"): + return errors.New(`name must not contain "/"`) + case name == "." || name == "..": + return errors.New("invalid name") + } + return nil +} + +func (a *App) canWriteHere() error { + p := a.Active() + switch { + case p.Source != panel.SourceDir: + return errors.New("not a directory") + case p.FS().Caps().ReadOnly: + return errors.New("this panel is read-only (archive)") + } + return nil +} + +// fsDoneMsg reports a quick FS operation (mkdir, rename) of a pane. +type fsDoneMsg struct { + Pane int + Loc vfs.Location + Focus string + What string + Err error +} + +// mkdir is F7: create a directory through the panel's FS (local, SSH). +func (a *App) mkdir() tea.Cmd { + p := a.Active() + pane, here := a.active, p.Here() + in := modal.NewInput("Make directory", modal.Field{Label: "Name"}) + in.Validate = func(v []string) error { return validName(v[0]) } + a.openModal(in, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + name := o.Value.([]string)[0] + fsys, dir := here.FS(), here.Path + return func() tea.Msg { + err := fsys.Mkdir(context.Background(), fsys.Paths().Join(dir, name), 0o755) + return fsDoneMsg{Pane: pane, Loc: here.Location(), Focus: name, What: "Created " + name, Err: err} + } + }) + return nil +} + +// rename is F2: rename within the panel's FS (N-P0-1: never the local file +// with the same path), refusing to replace an existing name. +func (a *App) rename() tea.Cmd { + p := a.Active() + e, ok := p.Selected() + if !ok || e.Parent { + return a.notify(notify.Warn, "Select an item to rename") + } + pane, here, old := a.active, p.Here(), e.Name + in := modal.NewInput("Rename "+old, modal.Field{Label: "New name", Value: old}) + in.Validate = func(v []string) error { + if err := validName(v[0]); err != nil { + return err + } + if v[0] == old { + return errors.New("the name did not change") + } + return nil + } + a.openModal(in, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + name := o.Value.([]string)[0] + fsys, dir := here.FS(), here.Path + return func() tea.Msg { + ops := fsys.Paths() + err := fsys.Rename(context.Background(), ops.Join(dir, old), ops.Join(dir, name), vfs.NoReplace) + return fsDoneMsg{Pane: pane, Loc: here.Location(), Focus: name, What: fmt.Sprintf("Renamed %s → %s", old, name), Err: err} + } + }) + return nil +} + +func (a *App) onFSDone(m fsDoneMsg) tea.Cmd { + if m.Err != nil { + return a.notify(notify.Error, fmt.Sprintf("%s failed: %v", strings.SplitN(m.What, " ", 2)[0], cleanErr(m.Err))) + } + var cmds []tea.Cmd + for i, p := range a.panels { + if !p.Location().Same(m.Loc) { + continue + } + if i == m.Pane { + cmds = append(cmds, a.navigate(i, p.Here(), m.Focus, panel.NavReplace)) + } else { + cmds = append(cmds, a.reload(i)) + } + } + return tea.Batch(append(cmds, a.notify(notify.Success, m.What))...) +} diff --git a/internal/tui/ops_remote_test.go b/internal/tui/ops_remote_test.go new file mode 100644 index 0000000..746cc2f --- /dev/null +++ b/internal/tui/ops_remote_test.go @@ -0,0 +1,152 @@ +package tui + +import ( + "context" + "net" + "os" + "path/filepath" + "strconv" + "sync/atomic" + "testing" + + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/ssh/conn" + "vcom/internal/testutil/fstree" + "vcom/internal/testutil/sshtest" + "vcom/internal/tui/panel" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/sftpfs" + "vcom/internal/vfs/vfstest" +) + +// standFS starts an in-process SSH/SFTP server and returns an FS on it (it +// shares this machine's file system: results are checked on disk). +func standFS(t *testing.T) *sftpfs.FS { + t.Helper() + home := sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + kh := filepath.Join(home, ".ssh", "known_hosts") + f, err := os.OpenFile(kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + for _, k := range srv.HostKeys { + _, _ = f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(srv.Addr)}, k.PublicKey()) + "\n") + } + f.Close() + pool := conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{Home: home, AgentSocket: "-", KnownHostsFiles: []string{kh}}}) + t.Cleanup(func() { pool.Close() }) + host, port, _ := net.SplitHostPort(srv.Addr) + p, _ := strconv.Atoi(port) + l, err := pool.Acquire(context.Background(), conn.Endpoint{Alias: "stand", User: "u", Host: host, Port: p, Password: srv.Password}) + if err != nil { + t.Fatal(err) + } + fsys := sftpfs.New(l) + t.Cleanup(fsys.Release) + return fsys +} + +// mountRemote puts pane at dir on rfs (as connecting does in 6.4). +func (h *opsH) mountRemote(pane int, rfs vfs.FS, dir string) { + h.t.Helper() + p := h.app.Panel(pane) + ret := p.Location() + m := panel.NewMount(rfs, "/", &ret, "", nil, nil) + t := panel.Target{Mounts: append(p.Here().Mounts, m), Path: dir} + h.d.Send(h.app.navigate(pane, t, "", panel.NavPush)()) + h.d.Settle(settle) + if p.FS() != rfs { + h.t.Fatalf("pane %d not mounted", pane) + } +} + +// counting wraps an FS and counts renames/removes. +func counting(fsys vfs.FS, n *atomic.Int32) vfs.FS { + return &vfstest.FaultFS{FS: fsys, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpRename || op == vfstest.OpRemove { + n.Add(1) + } + return nil + }} +} + +// N-P0-1: rename in a remote panel goes through the remote FS, never the +// local file system. +func TestNP01_RemoteRenameUsesRemoteFS(t *testing.T) { + ldir := tree(t, fstree.Spec{fstree.File("foo", "local")}) + rdir := tree(t, fstree.Spec{fstree.File("foo", "remote")}) + var localOps, remoteOps atomic.Int32 + rfs := counting(standFS(t), &remoteOps) + h := newOps(t, counting(localfs.New(), &localOps), ldir, ldir) + h.mountRemote(1, rfs, rdir) + h.press("tab") + h.cursorTo("foo") + h.press("f2", "ctrl+u") + h.typ("bar") + h.press("enter") + h.idle() + if !exists(filepath.Join(rdir, "bar")) || exists(filepath.Join(rdir, "foo")) { + t.Fatal("remote file not renamed") + } + if read(t, filepath.Join(ldir, "foo")) != "local" || localOps.Load() != 0 || remoteOps.Load() != 1 { + t.Fatalf("local ops %d, remote ops %d", localOps.Load(), remoteOps.Load()) + } + if h.selected() != "bar" { + t.Fatalf("remote panel cursor on %q", h.selected()) + } +} + +// N-P1-11: deleting in a remote panel reloads the remote panel (the old UI +// reloaded the local one). +func TestNP111_RemoteDeleteReloadsRemote(t *testing.T) { + ldir := tree(t, fstree.Spec{fstree.File("other", "x")}) + rdir := tree(t, fstree.Spec{fstree.File("gone.txt", "x"), fstree.File("stay.txt", "y")}) + h := newOps(t, localfs.New(), ldir, ldir) + h.mountRemote(1, standFS(t), rdir) + h.press("tab") + h.cursorTo("gone.txt") + h.press("f8") // no trash over SSH: permanent dialog + h.waitDialog("permanently") + h.press("d") + h.idle() + if exists(filepath.Join(rdir, "gone.txt")) { + t.Fatal("not deleted") + } + p := h.app.Active() + for i := 0; i < p.VisibleLen(); i++ { + if e, _ := p.Visible(i); e.Name == "gone.txt" { + t.Fatal("remote panel still lists the deleted file") + } + } + if h.selected() != "stay.txt" { + t.Fatalf("cursor on %q", h.selected()) + } +} + +// Copy local → remote and back through the same engine. +func TestCopyToRemotePane(t *testing.T) { + ldir := tree(t, fstree.Spec{fstree.File("up.bin", "").WithSize(200 << 10)}) + rdir := t.TempDir() + h := newOps(t, localfs.New(), ldir, ldir) + h.mountRemote(1, standFS(t), rdir) + h.cursorTo("up.bin") + h.press("f5") + h.waitDialog("Copy 1 item(s)?") + h.press("y") + h.idle() + if fi, err := os.Stat(filepath.Join(rdir, "up.bin")); err != nil || fi.Size() != 200<<10 { + t.Fatalf("remote copy: %v", err) + } + found := false + p := h.app.Passive() + for i := 0; i < p.VisibleLen(); i++ { + e, _ := p.Visible(i) + found = found || e.Name == "up.bin" + } + if !found { + t.Fatal("remote panel not reloaded") + } +} diff --git a/internal/tui/ops_test.go b/internal/tui/ops_test.go new file mode 100644 index 0000000..fe27c58 --- /dev/null +++ b/internal/tui/ops_test.go @@ -0,0 +1,458 @@ +package tui + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "vcom/internal/jobs" + "vcom/internal/state" + "vcom/internal/testutil/fstree" + "vcom/internal/tui/modal" + "vcom/internal/tui/panel" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +// opsH is a harness with a real jobs.Manager whose events are pumped into +// the driver by the test. +type opsH struct { + *harness + mgr *jobs.Manager + ev chan jobs.Event +} + +func newOps(t *testing.T, fsys vfs.FS, left, right string, opts ...opt) *opsH { + t.Helper() + ev := make(chan jobs.Event, 8192) + mgr := jobs.New(func(e jobs.Event) { ev <- e }, 2) + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = mgr.Shutdown(ctx) + }) + opts = append([]opt{func(d *Deps) { + d.Jobs = mgr + d.StartDirs = [2]string{left, right} + d.SaveSession = func(state.Session) error { return nil } // never the real session file + }}, opts...) + return &opsH{harness: newHarness(t, fsys, left, opts...), mgr: mgr, ev: ev} +} + +// pump delivers queued job events. +func (h *opsH) pump() bool { + got := false + for { + select { + case e := <-h.ev: + h.d.Send(JobEvent(e)) + got = true + default: + if got { + h.d.Settle(settle) + h.check() + } + return got + } + } +} + +// until pumps events until cond holds. +func (h *opsH) until(what string, cond func() bool) { + h.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !cond() { + if time.Now().After(deadline) { + h.t.Fatalf("timed out waiting for %s\n%s", what, h.d.Screen()) + } + if !h.pump() { + time.Sleep(5 * time.Millisecond) + } + } +} + +func (h *opsH) idle() { + h.t.Helper() + h.until("jobs to finish", func() bool { return h.mgr.Active() == 0 && len(h.ev) == 0 && len(h.app.ops.jobs) == 0 }) + h.pump() +} + +func (h *opsH) topDialog(title string) *modal.Dialog { + d, _ := h.app.modals.Top().(*modal.Dialog) + if d == nil || !strings.Contains(d.Title, title) { + return nil + } + return d +} + +func (h *opsH) waitDialog(title string) *modal.Dialog { + h.t.Helper() + var d *modal.Dialog + h.until("dialog "+title, func() bool { d = h.topDialog(title); return d != nil }) + return d +} + +func read(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func exists(p string) bool { _, err := os.Lstat(p); return err == nil } + +func noParts(t *testing.T, dir string) { + t.Helper() + _ = filepath.Walk(dir, func(p string, fi os.FileInfo, err error) error { + if err == nil && strings.HasPrefix(fi.Name(), ".vcom-") { + t.Errorf("temp left: %s", p) + } + return nil + }) +} + +func TestCopyConflictDialogAndSkip(t *testing.T) { + left := tree(t, fstree.Spec{fstree.File("a.txt", "new"), fstree.File("b.txt", "b")}) + right := tree(t, fstree.Spec{fstree.File("a.txt", "old")}) + h := newOps(t, localfs.New(), left, right) + h.cursorTo("a.txt") + h.press("insert", "insert", "f5") + d := h.waitDialog("Copy 2 item(s)?") + if !strings.Contains(strings.Join(fieldsOf(d), "|"), "1 item(s) already exist") { + t.Fatalf("plan dialog fields %v", fieldsOf(d)) + } + h.press("y") // copy, ask on conflicts + h.waitDialog("Target exists") + h.press("s") + h.idle() + if read(t, filepath.Join(right, "a.txt")) != "old" || read(t, filepath.Join(right, "b.txt")) != "b" { + t.Fatal("skip did not keep the target or b.txt not copied") + } + if !h.d.ScreenContains("1 skipped") { + t.Fatalf("summary missing:\n%s", h.d.Screen()) + } + if h.app.modals.Len() != 0 { + t.Fatal("modals left open") + } +} + +func fieldsOf(d *modal.Dialog) []string { + var out []string + for _, f := range d.Fields { + out = append(out, f.Label+": "+f.Value) + } + return out +} + +// slowFS sleeps on every write (a slow disk or link). +func slowFS(d time.Duration) vfs.FS { + return &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpWrite { + time.Sleep(d) + } + return nil + }} +} + +func TestProgressCCAsksConfirm(t *testing.T) { + left := tree(t, fstree.Spec{fstree.File("big", "").WithSize(8 << 20)}) + right := t.TempDir() + h := newOps(t, slowFS(5*time.Millisecond), left, right) + h.cursorTo("big") + h.press("f5") + h.waitDialog("Copy 1 item(s)?") + h.press("y") + if _, ok := h.app.modals.Top().(*modal.Progress); !ok { + t.Fatalf("no progress modal: %T", h.app.modals.Top()) + } + h.press("c") + h.waitDialog("Cancel Copy big?") + h.press("c") // a second c is not a confirmation (U-P1-16) + if h.topDialog("Cancel") == nil || h.mgr.Active() != 1 { + t.Fatal("c c cancelled without y") + } + h.press("n") // continue + if _, ok := h.app.modals.Top().(*modal.Progress); !ok || h.mgr.Active() != 1 { + t.Fatal("job not running after Continue") + } + h.press("c", "y") + h.idle() + if exists(filepath.Join(right, "big")) { + t.Fatal("cancelled copy left the file") + } + noParts(t, right) + if !h.d.ScreenContains("cancelled") { + t.Fatalf("no cancel note:\n%s", h.d.Screen()) + } +} + +func TestDeleteDefaultTrash(t *testing.T) { + data := t.TempDir() + t.Setenv("XDG_DATA_HOME", data) + dir := tree(t, fstree.Spec{fstree.File("junk.txt", "x")}) + h := newOps(t, localfs.New(), dir, dir) + h.cursorTo("junk.txt") + h.press("f8") + d := h.waitDialog("to the trash?") + if d.Buttons[d.Focused()].Label != "Move to trash" { + t.Fatalf("default button %q", d.Buttons[d.Focused()].Label) + } + h.press("enter") + h.idle() + if exists(filepath.Join(dir, "junk.txt")) || !exists(filepath.Join(data, "Trash", "files", "junk.txt")) { + t.Fatal("not moved to the trash") + } + for i := 0; i < h.app.Active().VisibleLen(); i++ { + if e, _ := h.app.Active().Visible(i); e.Name == "junk.txt" { + t.Fatal("panel not reloaded") + } + } +} + +func TestPermanentDeleteDefaultsToCancel(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("keep.txt", "x"), fstree.File("sub/f", "y")}) + h := newOps(t, localfs.New(), dir, dir) + h.cursorTo("keep.txt") + h.press("X") + h.waitDialog("permanently") + h.press("enter") + h.idle() + if !exists(filepath.Join(dir, "keep.txt")) { + t.Fatal("Enter deleted permanently (default must be Cancel; U-P0-4)") + } + h.cursorTo("sub") + h.press("X") + h.waitDialog("permanently") + h.press("d") + h.idle() + if exists(filepath.Join(dir, "sub")) { + t.Fatal("not deleted") + } +} + +// noTrash is a local FS that looks remote (no trash), like SFTP. +type noTrash struct{ vfs.FS } + +func (noTrash) Kind() vfs.Kind { return vfs.KindSFTP } +func (noTrash) Volume() vfs.VolumeID { return "ssh:test" } +func (noTrash) Label() string { return "bob@host" } +func (n noTrash) Caps() vfs.Caps { + c := n.FS.Caps() + c.Trash = false + return c +} + +func TestRemoteDeleteNoTrashShowsPermanentDialog(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("r.txt", "x")}) + h := newOps(t, noTrash{localfs.New()}, dir, dir) + h.cursorTo("r.txt") + h.press("f8") + d := h.waitDialog("permanently") + if !strings.Contains(strings.Join(d.Text, " "), "has no trash") || d.Buttons[d.Focused()].Label != "Cancel" { + t.Fatalf("dialog %+v focus %d", d.Text, d.Focused()) + } + h.press("enter") + if !exists(filepath.Join(dir, "r.txt")) { + t.Fatal("deleted on Enter") + } +} + +func TestTwoJobsParallel(t *testing.T) { + left := tree(t, fstree.Spec{fstree.File("f1", "").WithSize(256 << 10), fstree.File("f2", "").WithSize(256 << 10)}) + right := t.TempDir() + g := newGate(t) + var blocked atomic.Int32 + fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpWrite { + blocked.Add(1) + <-g.ch + } + return nil + }} + h := newOps(t, fsys, left, right) + for _, f := range []string{"f1", "f2"} { + h.cursorTo(f) + h.press("f5") + h.waitDialog("Copy 1 item(s)?") + h.press("y", "b") // confirm, then send to the background + } + h.until("two running jobs", func() bool { + n := 0 + for _, s := range h.mgr.Snapshot() { + if s.State == jobs.Running { + n++ + } + } + return n == 2 && blocked.Load() >= 2 + }) + g.open() + h.idle() + if !exists(filepath.Join(right, "f1")) || !exists(filepath.Join(right, "f2")) { + t.Fatal("copies missing") + } +} + +func TestQuitWithJobsCancelsAndCleans(t *testing.T) { + left := tree(t, fstree.Spec{fstree.File("big", "").WithSize(16 << 20)}) + right := t.TempDir() + h := newOps(t, slowFS(5*time.Millisecond), left, right) + h.cursorTo("big") + h.press("f5") + h.waitDialog("Copy 1 item(s)?") + h.press("y", "b") + h.until("copy running", func() bool { + s := h.mgr.Snapshot() + return len(s) == 1 && s[0].Progress.BytesDone > 0 + }) + h.press("q") + h.waitDialog("Quit and cancel operations?") + h.press("q") + if !h.app.Quitting() { + t.Fatal("not quitting") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := h.mgr.Shutdown(ctx); err != nil { // main's teardown + t.Fatal(err) + } + noParts(t, right) // N-P2-11 + if exists(filepath.Join(right, "big")) { + t.Fatal("partial copy under the target name") + } +} + +func TestHostsListNotATarget(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a", "x")}) + h := newOps(t, localfs.New(), dir, dir) + h.app.Passive().Source = panel.SourceHosts + h.cursorTo("a") + h.press("f5") + if h.app.modals.Len() != 0 || h.mgr.Active() != 0 { + t.Fatal("copy started into the host list (N-P2-10)") + } + if !h.d.ScreenContains("not a directory") { + t.Fatalf("no explanation:\n%s", h.d.Screen()) + } +} + +func TestRenameRejectsSlash(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a.txt", "x"), fstree.Dir("sub")}) + h := newOps(t, localfs.New(), dir, dir) + h.cursorTo("a.txt") + h.press("f2", "ctrl+u") + h.typ("sub/b.txt") + h.press("enter") + if _, ok := h.app.modals.Top().(*modal.Input); !ok { + t.Fatal("input closed on an invalid name") + } + if !h.d.ScreenContains(`must not contain "/"`) { + t.Fatalf("no error shown:\n%s", h.d.Screen()) + } + h.press("esc") + if !exists(filepath.Join(dir, "a.txt")) || exists(filepath.Join(dir, "sub", "b.txt")) { + t.Fatal("file moved") + } + // A valid rename and mkdir land on the new name. + h.press("f2", "ctrl+u") + h.typ("c.txt") + h.press("enter") + h.idle() + if !exists(filepath.Join(dir, "c.txt")) || h.selected() != "c.txt" { + t.Fatalf("rename: selected %q", h.selected()) + } + h.press("f7") + h.typ("новая") + h.press("enter") + h.idle() + if fi, err := os.Stat(filepath.Join(dir, "новая")); err != nil || !fi.IsDir() || h.selected() != "новая" { + t.Fatalf("mkdir: %v selected %q", err, h.selected()) + } +} + +func TestPassiveCursorKeptAfterCopy(t *testing.T) { + left := tree(t, fstree.Spec{fstree.File("a0", "new")}) + right := tree(t, fstree.Spec{fstree.File("x1", ""), fstree.File("x2", ""), fstree.File("x3", ""), fstree.File("x4", "")}) + h := newOps(t, localfs.New(), left, right) + h.press("tab") + h.cursorTo("x3") + h.press("tab") + h.cursorTo("a0") + h.press("f5") + h.waitDialog("Copy") + h.press("y") + h.idle() + p := h.app.Passive() + if e, _ := p.Selected(); e.Name != "x3" { + t.Fatalf("passive cursor on %q after copy (U-P1-7)", e.Name) + } + found := false + for i := 0; i < p.VisibleLen(); i++ { + e, _ := p.Visible(i) + found = found || e.Name == "a0" + } + if !found { + t.Fatal("passive panel not reloaded") + } +} + +func TestDirSizeShowsUnreadable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads everything") + } + dir := tree(t, fstree.Spec{fstree.File("d/a", "").WithSize(1000), fstree.File("d/locked/b", "x")}) + if err := os.Chmod(filepath.Join(dir, "d", "locked"), 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(filepath.Join(dir, "d", "locked"), 0o755) }) + h := newOps(t, localfs.New(), dir, dir) + h.cursorTo("d") + h.press(" ") + if h.app.modals.Len() != 0 { + t.Fatal("dir size must run in the background") + } + h.idle() + if !h.d.ScreenContains("1 unreadable") || !h.d.ScreenContains("≥") { + t.Fatalf("N-P1-14: unreadable not shown:\n%s", h.d.Screen()) + } +} + +func TestMoveAndJobsList(t *testing.T) { + left := tree(t, fstree.Spec{fstree.File("m.txt", "m")}) + right := t.TempDir() + h := newOps(t, localfs.New(), left, right) + h.cursorTo("m.txt") + h.press("f6") + h.waitDialog("Move 1 item(s)?") + h.press("y") + h.idle() + if exists(filepath.Join(left, "m.txt")) || read(t, filepath.Join(right, "m.txt")) != "m" { + t.Fatal("move") + } + h.press("B") + if l, ok := h.app.modals.Top().(*modal.List); !ok || len(l.Items) != 1 || !strings.Contains(l.Items[0].Label, "Move m.txt") { + t.Fatalf("jobs list %T", h.app.modals.Top()) + } + h.press("esc") +} + +func TestArchivePanelOpsDisabled(t *testing.T) { + dir := tree(t, fstree.Spec{fstree.File("a", "x")}) + h := newOps(t, vfs.ReadOnly(localfs.New()), dir, dir) + h.cursorTo("a") + for _, k := range []string{"f5", "f6", "f7", "f8", "X", "f2"} { + h.press(k) + if h.app.modals.Len() != 0 || h.mgr.Active() != 0 { + t.Fatalf("%s acted on a read-only panel", k) + } + } + if !h.d.ScreenContains("read-only") { + t.Fatalf("no explanation:\n%s", h.d.Screen()) + } +} diff --git a/internal/tui/ops_transfer.go b/internal/tui/ops_transfer.go new file mode 100644 index 0000000..e173a67 --- /dev/null +++ b/internal/tui/ops_transfer.go @@ -0,0 +1,145 @@ +package tui + +import ( + "context" + "errors" + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/jobs" + "vcom/internal/transfer" + "vcom/internal/tui/panel" +) + +// releaser adapts a release func to jobs.Releaser. +type releaser func() + +func (r releaser) Release() { r() } + +// holdMounts takes a reference on every mount of the given targets for the +// lifetime of a job (an SSH lease must not be closed under a transfer when +// the panel leaves the host; N-P1-12). +func holdMounts(ts ...panel.Target) []jobs.Releaser { + var out []jobs.Releaser + seen := map[uint64]bool{} + for _, t := range ts { + for _, m := range t.Mounts { + if m.Acquire == nil || seen[m.ID] { + continue + } + seen[m.ID] = true + if rel := m.Acquire(); rel != nil { + out = append(out, releaser(rel)) + } + } + } + return out +} + +// transferOptions maps [transfer]/[behavior] of the config. +func (a *App) transferOptions() transfer.Options { + c := a.deps.Config + o := transfer.DefaultOptions() + o.PreserveMode, o.PreserveTimes = c.Transfer.Preserve, c.Transfer.Preserve + switch c.Transfer.OnConflict { + case "overwrite": + o.Conflict = transfer.Overwrite + case "skip": + o.Conflict = transfer.Skip + case "newer": + o.Conflict = transfer.OverwriteOlder + case "rename": + o.Conflict = transfer.KeepBoth + } + switch c.Transfer.Fsync { + case "always": + o.Fsync = transfer.FsyncAlways + case "never": + o.Fsync = transfer.FsyncNever + } + if c.Behavior.FollowSymlinks { + o.Symlinks = transfer.FollowLinks + } + return o +} + +// opTargets are the active panel's targets as paths. +func (a *App) opTargets() (paths, names []string, hidden int) { + p := a.Active() + es, hidden := p.Targets() + for _, e := range es { + names = append(names, e.Name) + paths = append(paths, p.FS().Paths().Join(p.Path(), e.Name)) + } + return paths, names, hidden +} + +// canTransfer: the source lists files, the target is a writable directory +// (not the SSH host list, not an archive; N-P2-10, U-P0-2). +func (a *App) canTransfer(move bool) error { + src, dst := a.Active(), a.Passive() + switch { + case src.Source != panel.SourceDir: + return errors.New("nothing to copy here") + case dst.Source != panel.SourceDir: + return errors.New("the other panel is not a directory") + case dst.FS().Caps().ReadOnly: + return errors.New("the other panel is read-only (archive)") + case move && src.FS().Caps().ReadOnly: + return errors.New("cannot move out of a read-only panel") + } + if es, _ := src.Targets(); len(es) == 0 { + return errors.New("nothing selected") + } + return nil +} + +func (a *App) startTransfer(op transfer.Op) tea.Cmd { + src, dst := a.Active(), a.Passive() + paths, names, hidden := a.opTargets() + opts := a.transferOptions() + req := transfer.Request{Op: op, From: transfer.FSSource(src.FS(), paths, opts.Symlinks), To: dst.FS(), ToDir: dst.Path(), Opts: opts} + verb, kind := "Copy", jobs.Kind("copy") + if op == transfer.Move { + verb, kind = "Move", "move" + } + title := fmt.Sprintf("%s %s", verb, describe(names)) + return a.startJob(kind, title, transferJob(req, verb, hidden), nil, holdMounts(src.Here(), dst.Here())...) +} + +// describe names a selection: "a.txt" or "3 items". +func describe(names []string) string { + if len(names) == 1 { + return names[0] + } + return fmt.Sprintf("%d items", len(names)) +} + +// transferJob: Prepare (scanning) → plan dialog → Execute. It captures only +// the request. +func transferJob(req transfer.Request, verb string, hidden int) jobs.Func { + return func(ctx context.Context, h *jobs.Handle) (any, error) { + h.SetProgress(jobs.Progress{Phase: "scanning"}) + plan, err := transfer.Prepare(ctx, req, func(p transfer.Progress) { + h.SetProgress(jobs.Progress{Phase: "scanning", FilesTotal: p.FilesTotal, BytesTotal: p.BytesTotal}) + }) + if err != nil { + return transfer.Report{Err: err}, err + } + ans, err := h.Ask(ctx, askPlan{Verb: verb, Plan: plan, Hidden: hidden}) + if err != nil { + return transfer.Report{Cancelled: true}, err + } + pol, ok := ans.(transfer.ConflictPolicy) + if !ok { + return transfer.Report{}, errUserCancelled + } + plan.Req.Opts.Conflict = pol + rep := transfer.Execute(ctx, plan, transferHooks(h)) + if rep.Cancelled { + return rep, context.Canceled + } + return rep, rep.Err + } +} diff --git a/internal/tui/panel/entry.go b/internal/tui/panel/entry.go new file mode 100644 index 0000000..9d9a3dd --- /dev/null +++ b/internal/tui/panel/entry.go @@ -0,0 +1,127 @@ +package panel + +import ( + "sort" + "strings" + + "vcom/internal/vfs" +) + +// Category drives the color and icon of a row. +type Category uint8 + +const ( + CatFile Category = iota + CatDir + CatLinkDir // symlink to a directory: navigable (U-P1-2) + CatLink // symlink to a file + CatBroken // dangling symlink + CatExec // regular (or link to regular) with an x bit + CatSpecial // FIFO, socket, device + CatParent // ".." +) + +// Entry is a row: the file info plus fields computed once per listing. +type Entry struct { + vfs.FileInfo + Parent bool // the ".." row + // SizeLabel replaces "DIR" in the size column (computed directory size, + // stage 6.2); it lives until the next listing. + SizeLabel string + Cat Category + lower string // sort and filter key + ext string +} + +// Navigable reports whether Enter/l goes into the entry (directory or link +// to one). +func (e Entry) Navigable() bool { return e.Parent || e.NavigableDir() } + +func classify(fi vfs.FileInfo) Category { + switch { + case fi.IsDir(): + return CatDir + case fi.IsSymlink() && fi.Target == nil: + return CatBroken + case fi.IsSymlink() && fi.Target.IsDir(): + return CatLinkDir + case fi.IsRegularLike() && execBits(fi): + return CatExec + case fi.IsSymlink(): + return CatLink + case fi.Mode.IsRegular(): + return CatFile + } + return CatSpecial +} + +func execBits(fi vfs.FileInfo) bool { + m := fi.Mode + if fi.IsSymlink() && fi.Target != nil { + m = fi.Target.Mode + } + return m.Perm()&0o111 != 0 +} + +func buildEntries(infos []vfs.FileInfo, o Options, parent bool) []Entry { + out := make([]Entry, 0, len(infos)+1) + if parent { + out = append(out, Entry{FileInfo: vfs.FileInfo{Name: ".."}, Parent: true, Cat: CatParent}) + } + start := len(out) + for _, fi := range infos { + if fi.Name == "" || fi.Name == "." || fi.Name == ".." { + continue + } + if !o.ShowHidden && strings.HasPrefix(fi.Name, ".") { + continue + } + lower := strings.ToLower(fi.Name) + ext := "" + if i := strings.LastIndexByte(lower, '.'); i > 0 { + ext = lower[i+1:] + } + out = append(out, Entry{FileInfo: fi, Cat: classify(fi), lower: lower, ext: ext}) + } + rest := out[start:] + sort.SliceStable(rest, func(i, j int) bool { return less(rest[i], rest[j], o) }) + return out +} + +func less(a, b Entry, o Options) bool { + if o.DirsFirst { + ad, bd := a.Navigable(), b.Navigable() + if ad != bd { + return ad + } + } + var c int + switch o.SortBy { + case "size": + c = cmp(a.Size, b.Size) + case "modified", "mtime", "time": + c = cmp(a.ModTime.UnixNano(), b.ModTime.UnixNano()) + case "ext", "extension": + c = strings.Compare(a.ext, b.ext) + } + if c == 0 { + c = strings.Compare(a.lower, b.lower) + } + if c == 0 { + c = strings.Compare(a.Name, b.Name) + } + if o.Reverse { + return c > 0 + } + return c < 0 +} + +func cmp[T int64](a, b T) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} diff --git a/internal/tui/panel/lru.go b/internal/tui/panel/lru.go new file mode 100644 index 0000000..72a4f3d --- /dev/null +++ b/internal/tui/panel/lru.go @@ -0,0 +1,44 @@ +package panel + +// lru is a small bounded string map for cursor memory (oldest evicted). +type lru struct { + cap int + m map[string]string + order []string // oldest first +} + +func newLRU(n int) *lru { return &lru{cap: n, m: map[string]string{}} } + +func (l *lru) get(k string) (string, bool) { + v, ok := l.m[k] + if ok { + l.touch(k) + } + return v, ok +} + +func (l *lru) put(k, v string) { + if _, ok := l.m[k]; ok { + l.m[k] = v + l.touch(k) + return + } + l.m[k] = v + l.order = append(l.order, k) + for len(l.order) > l.cap { + delete(l.m, l.order[0]) + l.order = l.order[1:] + } +} + +func (l *lru) touch(k string) { + for i, o := range l.order { + if o == k { + copy(l.order[i:], l.order[i+1:]) + l.order[len(l.order)-1] = k + return + } + } +} + +func (l *lru) len() int { return len(l.m) } diff --git a/internal/tui/panel/panel.go b/internal/tui/panel/panel.go new file mode 100644 index 0000000..a6be749 --- /dev/null +++ b/internal/tui/panel/panel.go @@ -0,0 +1,607 @@ +// Package panel is one file panel of the new UI (design §7.8): a stack of +// mounts (local → archive → archive-in-archive, or a remote host), the +// listing of the current directory, cursor, marks, filter, history and +// cursor memory. It does no I/O: the App reads directories asynchronously +// and applies the result as one transaction (Apply), so a failed +// navigation never leaves the panel half-changed (U-P1-8). +package panel + +import ( + "strings" + "sync/atomic" + + "vcom/internal/vfs" +) + +var mountIDs atomic.Uint64 + +// Mount is one level of the panel's FS stack. +type Mount struct { + ID uint64 + FS vfs.FS + Root string // ".." in Root leaves this mount + // Return is where ".." from Root goes (the directory holding the + // archive, the local directory before connecting); nil on the bottom + // local mount. ReturnFocus is the name put under the cursor there. + Return *vfs.Location + ReturnFocus string + // Release drops the mount's reference (lease, archive index); called + // once when no snapshot of the panel uses the mount any more. + Release func() + // Acquire returns another reference for a mirrored panel (lease + // Acquire); nil means the mount can be shared as is (local). + Acquire func() (release func()) +} + +// NewMount builds a mount with a fresh ID. +func NewMount(fsys vfs.FS, root string, ret *vfs.Location, retFocus string, release func(), acquire func() func()) Mount { + return Mount{ID: mountIDs.Add(1), FS: fsys, Root: root, Return: ret, ReturnFocus: retFocus, Release: release, Acquire: acquire} +} + +// Source is what the panel lists. +type Source uint8 + +const ( + SourceDir Source = iota // a directory of the top mount's FS + SourceHosts // the SSH host list (stage 6.4): not an FS, never a target +) + +// Target is a place to navigate to. +type Target struct { + Mounts []Mount + Path string +} + +// FS is the file system of the target's top mount. +func (t Target) FS() vfs.FS { return t.Mounts[len(t.Mounts)-1].FS } + +// Location of the target. +func (t Target) Location() vfs.Location { return vfs.Location{FS: t.FS(), Path: t.Path} } + +// Snapshot is a history entry. +type Snapshot struct { + Target + Focus string +} + +// NavMode tells Apply how the navigation affects history. +type NavMode uint8 + +const ( + NavPush NavMode = iota // a new place: current one goes to history + NavBack // history back + NavForward // history forward + NavReplace // same history slot (climb to an existing parent) +) + +// Options are the listing options (same for every FS, N-P2-7). +type Options struct { + ShowHidden bool + DirsFirst bool + SortBy string // name | size | modified | ext + Reverse bool + ShowSize bool + ShowTime bool + HumanSize bool +} + +const historyMax = 100 + +// Model is one panel. +type Model struct { + ID int + Source Source + Opts Options + // Badge is a short connection state shown in the title ("⚠ lost"); + // set by the App from conn events. + Badge string + // Loading is set while a listing for this panel is in flight. + Loading bool + + mounts []Mount + path string + entries []Entry + gen uint64 // bumps whenever entries or visible change (render cache) + visible []int + cursor int // index into visible + offset int + rows int // list rows on screen (for paging); set by SetRows + marks map[string]bool + filter string + history []Snapshot + future []Snapshot + memory *lru + cache rowCache +} + +// New makes an empty panel at target (call Apply with a listing). +func New(id int, opts Options, mounts []Mount, path string) *Model { + return &Model{ID: id, Opts: opts, mounts: mounts, path: path, marks: map[string]bool{}, memory: newLRU(200), rows: 20} +} + +// Mounts returns the mount stack (do not modify). +func (p *Model) Mounts() []Mount { return p.mounts } + +// Top is the top mount. +func (p *Model) Top() Mount { return p.mounts[len(p.mounts)-1] } + +// FS of the top mount. +func (p *Model) FS() vfs.FS { return p.Top().FS } + +// Path in the top mount's FS. +func (p *Model) Path() string { return p.path } + +// Location is where the panel stands. +func (p *Model) Location() vfs.Location { return vfs.Location{FS: p.FS(), Path: p.path} } + +// Here is the current place as a Target. +func (p *Model) Here() Target { + return Target{Mounts: append([]Mount(nil), p.mounts...), Path: p.path} +} + +// Gen changes with every change of what the panel shows. +func (p *Model) Gen() uint64 { return p.gen } + +func (p *Model) bump() { p.gen++ } + +// Filter returns the current filter text. +func (p *Model) Filter() string { return p.filter } + +// Entries returns all entries of the directory (sorted, ".." first). +func (p *Model) Entries() []Entry { return p.entries } + +// VisibleLen is the number of rows after the filter. +func (p *Model) VisibleLen() int { return len(p.visible) } + +// Visible returns the i-th visible entry. +func (p *Model) Visible(i int) (Entry, bool) { + if i < 0 || i >= len(p.visible) { + return Entry{}, false + } + return p.entries[p.visible[i]], true +} + +// Cursor is the cursor position in the visible rows. +func (p *Model) Cursor() int { return p.cursor } + +// Offset is the first visible row on screen. +func (p *Model) Offset() int { return p.offset } + +// Selected is the entry under the cursor (always one of the visible rows). +func (p *Model) Selected() (Entry, bool) { return p.Visible(p.cursor) } + +// SetRows tells the panel how many list rows are on screen. +func (p *Model) SetRows(n int) { + p.rows = max(1, n) + p.follow() +} + +// Rows is the number of list rows on screen. +func (p *Model) Rows() int { return p.rows } + +func (p *Model) key(loc vfs.Location) string { + if loc.FS == nil { + return loc.Path + } + return string(loc.FS.Volume()) + "\x00" + loc.Path +} + +// rememberCursor stores the selected name for the current directory. +func (p *Model) rememberCursor() { + if e, ok := p.Selected(); ok && !e.Parent { + p.memory.put(p.key(p.Location()), e.Name) + } +} + +// Apply installs a successful listing of target as one transaction: +// location, entries, history and cursor change together. focus is the name +// to put the cursor on ("" = remembered name for that directory). Mounts no +// longer used by the panel or its history are released. +func (p *Model) Apply(t Target, infos []vfs.FileInfo, focus string, mode NavMode) { + old := p.liveMounts() + cur := Snapshot{Target: p.Here(), Focus: p.selectedName()} + p.rememberCursor() + switch mode { + case NavPush: + p.history = append(p.history, cur) + if len(p.history) > historyMax { + p.history = p.history[len(p.history)-historyMax:] + } + p.future = nil + case NavBack: + if n := len(p.history); n > 0 { + p.history = p.history[:n-1] + } + p.future = append(p.future, cur) + case NavForward: + if n := len(p.future); n > 0 { + p.future = p.future[:n-1] + } + p.history = append(p.history, cur) + } + p.mounts = t.Mounts + p.path = t.Path + p.Loading = false + if focus == "" { + focus, _ = p.memory.get(p.key(p.Location())) + } + p.filter = "" + p.marks = map[string]bool{} + p.setEntries(infos) + p.cursor = 0 + p.offset = 0 + if i := p.indexOf(focus); i >= 0 { + p.cursor = i + } + p.follow() + p.releaseDropped(old) +} + +// Reload replaces the entries of the current directory, keeping the cursor +// on the same name; if that entry is gone the cursor stays at the same +// index, i.e. on its neighbour (U-P1-7). Marks of vanished names drop, +// the filter stays. +func (p *Model) Reload(infos []vfs.FileInfo) { + name := p.selectedName() + idx := p.cursor + p.Loading = false + p.setEntries(infos) + present := map[string]bool{} + for _, e := range p.entries { + present[e.Name] = true + } + for m := range p.marks { + if !present[m] { + delete(p.marks, m) + } + } + if i := p.indexOf(name); i >= 0 { + p.cursor = i + } else { + p.cursor = max(0, min(idx, len(p.visible)-1)) + } + p.follow() +} + +// SetOptions changes listing options and re-sorts. +func (p *Model) SetOptions(o Options) { + name := p.selectedName() + p.Opts = o + infos := make([]vfs.FileInfo, 0, len(p.entries)) + for _, e := range p.entries { + if !e.Parent { + infos = append(infos, e.FileInfo) + } + } + p.setEntries(infos) + if i := p.indexOf(name); i >= 0 { + p.cursor = i + } else { + p.cursor = 0 + } + p.follow() +} + +func (p *Model) selectedName() string { + if e, ok := p.Selected(); ok && !e.Parent { + return e.Name + } + return "" +} + +// indexOf finds name among the visible rows. +func (p *Model) indexOf(name string) int { + if name == "" { + return -1 + } + for i, ei := range p.visible { + if p.entries[ei].Name == name && !p.entries[ei].Parent { + return i + } + } + return -1 +} + +func (p *Model) setEntries(infos []vfs.FileInfo) { + p.entries = buildEntries(infos, p.Opts, p.HasParent()) + p.bump() + p.refilter() +} + +// HasParent reports whether ".." leads somewhere. +func (p *Model) HasParent() bool { + if p.Source == SourceHosts { + return true + } + _, _, _, ok := p.ParentTarget() + return ok +} + +// ParentTarget is where ".." goes and the name to focus there. ok is false +// at the very root; leaving reports that the top mount is left. +func (p *Model) ParentTarget() (t Target, focus string, leaving bool, ok bool) { + top := p.Top() + ops := top.FS.Paths() + if ops.Clean(p.path) != ops.Clean(top.Root) { + parent := ops.Dir(p.path) + if parent == p.path { + return Target{}, "", false, false + } + return Target{Mounts: p.Here().Mounts, Path: parent}, ops.Base(p.path), false, true + } + if len(p.mounts) < 2 { + return Target{}, "", false, false + } + below := append([]Mount(nil), p.mounts[:len(p.mounts)-1]...) + path := below[len(below)-1].Root + if top.Return != nil { + path = top.Return.Path + } + return Target{Mounts: below, Path: path}, top.ReturnFocus, true, true +} + +// ChildTarget is the target for entering directory name in the top mount. +func (p *Model) ChildTarget(name string) Target { + return Target{Mounts: p.Here().Mounts, Path: p.FS().Paths().Join(p.path, name)} +} + +// History. + +// BackTarget is the previous place in history. +func (p *Model) BackTarget() (Snapshot, bool) { + if len(p.history) == 0 { + return Snapshot{}, false + } + return p.history[len(p.history)-1], true +} + +// ForwardTarget is the next place in history. +func (p *Model) ForwardTarget() (Snapshot, bool) { + if len(p.future) == 0 { + return Snapshot{}, false + } + return p.future[len(p.future)-1], true +} + +// liveMounts returns the IDs of every mount referenced by the panel. +func (p *Model) liveMounts() map[uint64]Mount { + out := map[uint64]Mount{} + add := func(ms []Mount) { + for _, m := range ms { + out[m.ID] = m + } + } + add(p.mounts) + for _, s := range p.history { + add(s.Mounts) + } + for _, s := range p.future { + add(s.Mounts) + } + return out +} + +// releaseDropped releases mounts that were referenced before and are not +// any more. History entries that point into a mount the panel has left are +// dropped first: a closed archive or host is not reopened from history. +func (p *Model) releaseDropped(before map[uint64]Mount) { + cur := map[uint64]bool{} + for _, m := range p.mounts { + cur[m.ID] = true + } + keep := func(ss []Snapshot) []Snapshot { + out := ss[:0] + for _, s := range ss { + ok := true + for _, m := range s.Mounts { + ok = ok && cur[m.ID] + } + if ok { + out = append(out, s) + } + } + return out + } + p.history = keep(p.history) + p.future = keep(p.future) + after := p.liveMounts() + for id, m := range before { + if _, ok := after[id]; !ok && m.Release != nil { + m.Release() + } + } +} + +// Close releases every mount (the panel is going away). +func (p *Model) Close() { + before := p.liveMounts() + p.mounts = p.mounts[:0] + p.history, p.future = nil, nil + for _, m := range before { + if m.Release != nil { + m.Release() + } + } +} + +// MirrorOf makes p show the same place as o: every mount is re-acquired so +// leaving it in one panel does not break the other (U-P1-14, N-P1-12). +func (p *Model) MirrorOf(o *Model, infos []vfs.FileInfo) { + ms := make([]Mount, len(o.mounts)) + for i, m := range o.mounts { + c := m + c.ID = mountIDs.Add(1) + if m.Acquire != nil { + c.Release = m.Acquire() + } else { + c.Release = nil + } + ms[i] = c + } + p.Apply(Target{Mounts: ms, Path: o.path}, infos, o.selectedName(), NavPush) +} + +// Filter. + +// SetFilter shows only entries whose name contains s (case-insensitive); +// the cursor stays on the same entry if it is still visible. +func (p *Model) SetFilter(s string) { + if s == p.filter { + return + } + name := p.selectedName() + p.filter = s + p.refilter() + if i := p.indexOf(name); i >= 0 { + p.cursor = i + } else { + p.cursor = 0 + } + p.offset = 0 + p.follow() +} + +func (p *Model) refilter() { + p.visible = p.visible[:0] + f := strings.ToLower(p.filter) + for i, e := range p.entries { + if f == "" || e.Parent || strings.Contains(e.lower, f) { + p.visible = append(p.visible, i) + } + } + p.bump() + p.cursor = max(0, min(p.cursor, len(p.visible)-1)) +} + +// Marks. + +// Marked reports whether name is marked. +func (p *Model) Marked(name string) bool { return p.marks[name] } + +// MarkCount is the number of marked entries (visible or not). +func (p *Model) MarkCount() int { return len(p.marks) } + +// ToggleMark marks or unmarks the entry under the cursor ("..": no-op). +func (p *Model) ToggleMark() { + e, ok := p.Selected() + if !ok || e.Parent { + return + } + if p.marks[e.Name] { + delete(p.marks, e.Name) + } else { + p.marks[e.Name] = true + } + p.bump() +} + +// ClearMarks drops every mark; it reports whether there were any. +func (p *Model) ClearMarks() bool { + if len(p.marks) == 0 { + return false + } + p.marks = map[string]bool{} + p.bump() + return true +} + +// Targets returns what an operation acts on: the marked entries that are +// visible, or the entry under the cursor if none is marked. hiddenMarked +// counts marked entries hidden by the filter — they are NOT included, and +// the operation dialog says so. +func (p *Model) Targets() (out []Entry, hiddenMarked int) { + if len(p.marks) > 0 { + seen := 0 + for _, i := range p.visible { + e := p.entries[i] + if p.marks[e.Name] && !e.Parent { + out = append(out, e) + seen++ + } + } + hiddenMarked = len(p.marks) - seen + if len(out) > 0 { + return out, hiddenMarked + } + } + if e, ok := p.Selected(); ok && !e.Parent { + out = append(out, e) + } + return out, hiddenMarked +} + +// Cursor movement. + +// MoveCursor moves by delta rows (clamped). +func (p *Model) MoveCursor(delta int) { + p.SetCursor(p.cursor + delta) +} + +// SetCursor puts the cursor on visible row i (clamped). +func (p *Model) SetCursor(i int) { + if len(p.visible) == 0 { + p.cursor = 0 + return + } + n := max(0, min(i, len(p.visible)-1)) + if n != p.cursor { + p.cursor = n + p.bump() + } + p.follow() +} + +// Page moves by a screen (dir = ±1) or half a screen (half). +func (p *Model) Page(dir int, half bool) { + step := max(1, p.rows-1) + if half { + step = max(1, p.rows/2) + } + p.MoveCursor(dir * step) +} + +// Scroll moves the view by delta rows, dragging the cursor along when it +// would leave the screen (mouse wheel). +func (p *Model) Scroll(delta int) { + maxOff := max(0, len(p.visible)-p.rows) + p.offset = max(0, min(p.offset+delta, maxOff)) + if p.cursor < p.offset { + p.cursor = p.offset + } + if p.cursor >= p.offset+p.rows { + p.cursor = p.offset + p.rows - 1 + } + p.bump() +} + +// RowAt maps a list row on screen (0 = first) to a visible index. +func (p *Model) RowAt(row int) (int, bool) { + i := p.offset + row + if row < 0 || row >= p.rows || i >= len(p.visible) { + return 0, false + } + return i, true +} + +func (p *Model) follow() { + if p.cursor < p.offset { + p.offset = p.cursor + } + if p.cursor >= p.offset+p.rows { + p.offset = p.cursor - p.rows + 1 + } + p.offset = max(0, min(p.offset, max(0, len(p.visible)-p.rows))) +} + +// SetSizeLabel shows label in the size column of entry name (a computed +// directory size); it reports whether the entry is listed. +func (p *Model) SetSizeLabel(name, label string) bool { + for i := range p.entries { + if p.entries[i].Name == name && !p.entries[i].Parent { + p.entries[i].SizeLabel = label + p.bump() + return true + } + } + return false +} diff --git a/internal/tui/panel/panel_test.go b/internal/tui/panel/panel_test.go new file mode 100644 index 0000000..d11fce4 --- /dev/null +++ b/internal/tui/panel/panel_test.go @@ -0,0 +1,309 @@ +package panel + +import ( + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/charmbracelet/x/ansi" + + "vcom/internal/theme" + "vcom/internal/tui/geom" + "vcom/internal/tui/style" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" +) + +var local = localfs.New() + +func infos(names ...string) []vfs.FileInfo { + out := make([]vfs.FileInfo, len(names)) + for i, n := range names { + mode := fs.FileMode(0o644) + if strings.HasSuffix(n, "/") { + n = strings.TrimSuffix(n, "/") + mode = fs.ModeDir | 0o755 + } + out[i] = vfs.FileInfo{Name: n, Mode: mode, Size: int64(len(n)), ModTime: time.Unix(0, 0)} + } + return out +} + +func newPanel(path string, names ...string) *Model { + m := NewMount(local, "/", nil, "", nil, nil) + p := New(0, Options{ShowHidden: true, DirsFirst: true}, []Mount{m}, path) + p.Apply(Target{Mounts: []Mount{m}, Path: path}, infos(names...), "", NavReplace) + return p +} + +func names(p *Model) []string { + var out []string + for i := 0; i < p.VisibleLen(); i++ { + e, _ := p.Visible(i) + out = append(out, e.Name) + } + return out +} + +// U-P1-4: with a filter, row N on screen is the N-th visible entry. +func TestFilterVisibleIndexAndMouse(t *testing.T) { + p := newPanel("/d", "a", "b", "c", "abc", "dir/") + p.SetRows(10) + p.SetFilter("B") + if got := strings.Join(names(p), ","); got != "..,abc,b" { + t.Fatalf("visible = %s", got) + } + i, ok := p.RowAt(2) // third row on screen + if !ok { + t.Fatal("row 2 not mapped") + } + p.SetCursor(i) + if e, _ := p.Selected(); e.Name != "b" { + t.Fatalf("selected %q, want b", e.Name) + } + if _, ok := p.RowAt(3); ok { + t.Fatal("row past the end mapped") + } + // The cursor stays on the same entry when the filter changes. + p.SetFilter("") + if e, _ := p.Selected(); e.Name != "b" { + t.Fatalf("after clearing the filter: %q", e.Name) + } +} + +func TestFilterResetOnDirChange(t *testing.T) { + p := newPanel("/d", "a", "b", "sub/") + p.SetFilter("a") + p.SetCursor(1) + p.ToggleMark() + p.Apply(p.ChildTarget("sub"), infos("x", "y"), "", NavPush) + if p.Filter() != "" || p.MarkCount() != 0 || p.VisibleLen() != 3 { + t.Fatalf("filter %q marks %d visible %v", p.Filter(), p.MarkCount(), names(p)) + } + // Back restores the cursor from memory. + snap, ok := p.BackTarget() + if !ok || snap.Path != "/d" || snap.Focus != "a" { + t.Fatalf("history = %+v", snap) + } + p.Apply(snap.Target, infos("a", "b", "sub/"), snap.Focus, NavBack) + if e, _ := p.Selected(); e.Name != "a" { + t.Fatalf("back: cursor on %q", e.Name) + } + if f, ok := p.ForwardTarget(); !ok || f.Path != "/d/sub" { + t.Fatalf("future = %+v", f) + } +} + +func TestTargetsExcludeHiddenMarks(t *testing.T) { + p := newPanel("/d", "apple", "banana", "cherry") + for _, n := range []string{"apple", "banana", "cherry"} { + p.SetCursor(p.indexOf(n)) + p.ToggleMark() + } + p.SetFilter("an") + ts, hidden := p.Targets() + if len(ts) != 1 || ts[0].Name != "banana" || hidden != 2 { + t.Fatalf("targets %v hidden %d", ts, hidden) + } + // Nothing marked: the cursor entry; ".." is never a target. + p.ClearMarks() + p.SetFilter("") + p.SetCursor(0) + if ts, _ := p.Targets(); len(ts) != 0 { + t.Fatalf("'..' became a target: %v", ts) + } + p.SetCursor(2) + if ts, _ := p.Targets(); len(ts) != 1 || ts[0].Name != "banana" { + t.Fatalf("cursor target %v", ts) + } +} + +// U-P1-7: after an operation both panels on the same directory reload, each +// keeping its own cursor; a deleted entry leaves the cursor on its index. +func TestReloadKeepsCursorPerPane(t *testing.T) { + a := newPanel("/d", "a", "b", "c", "d") + b := newPanel("/d", "a", "b", "c", "d") + a.SetCursor(a.indexOf("b")) + b.SetCursor(b.indexOf("d")) + a.Reload(infos("a", "b", "c", "d", "e")) + b.Reload(infos("a", "b", "c", "d", "e")) + if ea, _ := a.Selected(); ea.Name != "b" { + t.Errorf("a: %q", ea.Name) + } + if eb, _ := b.Selected(); eb.Name != "d" { + t.Errorf("b: %q", eb.Name) + } +} + +func TestDeletedItemCursorStaysAtIndex(t *testing.T) { + p := newPanel("/d", "a", "b", "c", "d") + p.SetCursor(p.indexOf("b")) + idx := p.Cursor() + p.Reload(infos("a", "c", "d")) + if p.Cursor() != idx { + t.Fatalf("cursor %d, want %d", p.Cursor(), idx) + } + if e, _ := p.Selected(); e.Name != "c" { + t.Fatalf("on %q, want the neighbour c", e.Name) + } + p.SetCursor(p.VisibleLen() - 1) + p.Reload(infos("a")) + if e, _ := p.Selected(); e.Name != "a" { + t.Fatalf("last deleted: on %q", e.Name) + } +} + +// U-P1-2: a symlink to a directory is navigable, a broken one is not. +func TestSymlinkDirNavigable(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "real"), 0o755); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(dir, "f.sh"), []byte("#!/bin/sh"), 0o755) + os.Symlink("real", filepath.Join(dir, "linkdir")) + os.Symlink("f.sh", filepath.Join(dir, "linkfile")) + os.Symlink("missing", filepath.Join(dir, "broken")) + ents, err := local.ReadDir(context.Background(), dir) + if err != nil { + t.Fatal(err) + } + m := NewMount(local, "/", nil, "", nil, nil) + p := New(0, Options{ShowHidden: true, DirsFirst: true}, []Mount{m}, dir) + p.Apply(Target{Mounts: []Mount{m}, Path: dir}, ents, "", NavReplace) + want := map[string]Category{"real": CatDir, "linkdir": CatLinkDir, "linkfile": CatExec, "broken": CatBroken, "f.sh": CatExec} + for i := 0; i < p.VisibleLen(); i++ { + e, _ := p.Visible(i) + if e.Parent { + continue + } + if e.Cat != want[e.Name] { + t.Errorf("%s: cat %d, want %d", e.Name, e.Cat, want[e.Name]) + } + if e.Navigable() != (e.Name == "real" || e.Name == "linkdir") { + t.Errorf("%s: navigable = %v", e.Name, e.Navigable()) + } + } + // Directories (and links to them) sort first. + if got := names(p); got[1] != "linkdir" || got[2] != "real" { + t.Errorf("order = %v", got) + } +} + +func TestMountsReleasedWhenLeft(t *testing.T) { + released := 0 + base := NewMount(local, "/", nil, "", nil, nil) + p := New(0, Options{}, []Mount{base}, "/data") + p.Apply(Target{Mounts: []Mount{base}, Path: "/data"}, infos("a.zip"), "", NavReplace) + arc := NewMount(otherFS{local}, "/", &vfs.Location{FS: local, Path: "/data"}, "a.zip", func() { released++ }, nil) + p.Apply(Target{Mounts: []Mount{base, arc}, Path: "/"}, infos("inside", "dir/"), "", NavPush) + p.Apply(p.ChildTarget("dir"), infos("x"), "", NavPush) + if released != 0 { + t.Fatal("released while inside") + } + // ".." twice leaves the archive with the cursor on it. + tg, focus, leaving, ok := p.ParentTarget() + if !ok || leaving { + t.Fatalf("parent in archive: %+v %v %v", tg, leaving, ok) + } + p.Apply(tg, infos("inside", "dir/"), focus, NavPush) + tg, focus, leaving, ok = p.ParentTarget() + if !ok || !leaving || tg.Path != "/data" || focus != "a.zip" || len(tg.Mounts) != 1 { + t.Fatalf("leaving: %+v %q %v %v", tg, focus, leaving, ok) + } + p.Apply(tg, infos("a.zip"), focus, NavPush) + if released != 1 { + t.Fatalf("released %d times", released) + } + if e, _ := p.Selected(); e.Name != "a.zip" { + t.Fatalf("cursor on %q", e.Name) + } + for s, ok := p.BackTarget(); ok; s, ok = p.BackTarget() { + if len(s.Mounts) != 1 { + t.Fatal("history still points into the closed archive") + } + p.Apply(s.Target, infos("a.zip"), s.Focus, NavBack) + } +} + +func TestMirrorAcquires(t *testing.T) { + acquired, released := 0, 0 + base := NewMount(local, "/", nil, "", nil, nil) + remote := NewMount(otherFS{local}, "/", &vfs.Location{FS: local, Path: "/"}, "", func() { released++ }, + func() func() { acquired++; return func() { released++ } }) + a := New(0, Options{}, []Mount{base}, "/") + a.Apply(Target{Mounts: []Mount{base, remote}, Path: "/srv"}, infos("x"), "", NavPush) + b := New(1, Options{}, []Mount{base}, "/") + b.MirrorOf(a, infos("x")) + if acquired != 1 || b.Path() != "/srv" || len(b.Mounts()) != 2 { + t.Fatalf("acquired %d path %s", acquired, b.Path()) + } + a.Close() + if released != 1 { + t.Fatalf("released %d after closing a", released) + } + b.Close() + if released != 2 { + t.Fatalf("released %d after closing b", released) + } +} + +func TestRenderFitsAndMarks(t *testing.T) { + p := newPanel("/d", "alpha", "beta", "gamma", "dir/") + p.SetCursor(2) + p.ToggleMark() + st := style.New(mustPalette(t)) + r := geom.Rect{W: 40, H: 8} + p.SetRows(ListRect(r, false).H) + out := p.Render(View{Rect: r, Active: true, Title: "/d", Styles: st}) + lines := strings.Split(ansi.Strip(out), "\n") + if len(lines) != 8 { + t.Fatalf("%d lines", len(lines)) + } + for _, l := range lines { + if ansi.StringWidth(l) != 40 { + t.Fatalf("line width %d: %q", ansi.StringWidth(l), l) + } + } + if !strings.Contains(lines[4], "* alpha") || !strings.Contains(lines[3], "dir/") { + t.Fatalf("render:\n%s", strings.Join(lines, "\n")) + } + p.SetFilter("et") + out = ansi.Strip(p.Render(View{Rect: r, Active: true, Title: "/d", Styles: st})) + if !strings.Contains(out, "/et") { + t.Fatalf("filter row missing:\n%s", out) + } +} + +func BenchmarkRender20k(b *testing.B) { + var ns []string + for i := 0; i < 20000; i++ { + ns = append(ns, fmt.Sprintf("file-%05d.txt", i)) + } + p := newPanel("/big", ns...) + st := style.New(mustPalette(b)) + r := geom.Rect{W: 100, H: 50} + p.SetRows(ListRect(r, false).H) + b.ResetTimer() + for i := 0; i < b.N; i++ { + p.MoveCursor(1) + _ = p.Render(View{Rect: r, Active: true, Title: "/big", Styles: st}) + } +} + +func mustPalette(t testing.TB) theme.Palette { + pal, err := theme.Resolve("catppuccin-mocha") + if err != nil { + t.Fatal(err) + } + return pal +} + +// otherFS is the local FS posing as another volume (archive, remote). +type otherFS struct{ vfs.FS } + +func (otherFS) Volume() vfs.VolumeID { return "other" } diff --git a/internal/tui/panel/render.go b/internal/tui/panel/render.go new file mode 100644 index 0000000..9ae3526 --- /dev/null +++ b/internal/tui/panel/render.go @@ -0,0 +1,216 @@ +package panel + +import ( + "fmt" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/geom" + "vcom/internal/tui/style" +) + +// View describes how to draw the panel. +type View struct { + Rect geom.Rect + Active bool + // FilterLine is the filter row content while the filter is edited + // (with the text cursor); "" shows the committed filter, if any. + FilterLine string + Title string // path as the App wants it shown + Styles *style.Styles +} + +func (v View) filterRow(p *Model) bool { return v.FilterLine != "" || p.filter != "" } + +// ListRect is where the rows are inside the panel rectangle r: border, +// title row, optional filter row. Rendering and mouse hit-tests both use it. +func ListRect(r geom.Rect, filterRow bool) geom.Rect { + h := r.H - 3 // borders + title + if filterRow { + h-- + } + return geom.Rect{X: r.X + 1, Y: r.Y + 2, W: max(0, r.W-2), H: max(0, h)} +} + +// ListRectFor is ListRect for the panel's current state. +func (p *Model) ListRectFor(v View) geom.Rect { return ListRect(v.Rect, v.filterRow(p)) } + +type rowKey struct { + gen, styles uint64 + idx int + cursor, active bool + marked bool + width int + showSize, showTm bool +} + +type rowCache struct { + m map[rowKey]string +} + +func (c *rowCache) get(k rowKey, rows int, build func() string) string { + if s, ok := c.m[k]; ok { + return s + } + if c.m == nil || len(c.m) > 4*max(rows, 16) { + c.m = make(map[rowKey]string, 4*max(rows, 16)) + } + s := build() + c.m[k] = s + return s +} + +// Render draws the panel into v.Rect. +func (p *Model) Render(v View) string { + st := v.Styles + r := v.Rect + if r.W < 4 || r.H < 3 { + return "" + } + inner := r.W - 2 + lr := p.ListRectFor(v) // the App keeps p.rows == lr.H via SetRows (View stays pure) + + var b strings.Builder + title := v.Title + if p.Badge != "" { + title += " " + p.Badge + } + if p.Loading { + title += " …" + } + ts := st.PaneTitle + if v.Active { + ts = st.PaneTitleActive + } + b.WriteString(ts.Render(pad(ansi.Truncate(title, inner, "…"), inner))) + for row := 0; row < lr.H; row++ { + b.WriteByte('\n') + i := p.offset + row + if i >= len(p.visible) { + b.WriteString(strings.Repeat(" ", inner)) + continue + } + e := p.entries[p.visible[i]] + k := rowKey{gen: p.gen, styles: st.Gen, idx: i, cursor: i == p.cursor, active: v.Active, + marked: p.marks[e.Name], width: inner, showSize: p.Opts.ShowSize, showTm: p.Opts.ShowTime} + b.WriteString(p.cache.get(k, lr.H, func() string { return p.renderRow(e, k, st) })) + } + if v.filterRow(p) { + b.WriteByte('\n') + line := v.FilterLine + if line == "" { + line = "/" + p.filter + } + b.WriteString(st.FilterLine.Render(pad(ansi.Truncate(line, inner, "…"), inner))) + } + border := st.PaneBorder + if v.Active { + border = st.PaneBorderActive + } + return border.Width(inner).Render(b.String()) +} + +func (p *Model) renderRow(e Entry, k rowKey, st *style.Styles) string { + w := k.width + sizeW, timeW := 0, 0 + if k.showSize && w >= 30 { + sizeW = 8 + } + if k.showTm && w >= 50 { + timeW = 16 + } + nameW := w - 2 - sizeW - timeW + if sizeW > 0 { + nameW-- + } + if timeW > 0 { + nameW-- + } + mark := " " + if k.marked { + mark = "* " + } + name := e.Name + switch e.Cat { + case CatDir, CatLinkDir, CatParent: + name += "/" + } + if e.IsSymlink() { + name = "~" + name + } + line := mark + pad(ansi.Truncate(name, max(1, nameW), "…"), max(1, nameW)) + if sizeW > 0 { + line += " " + fmt.Sprintf("%*s", sizeW, sizeText(e, p.Opts.HumanSize)) + } + if timeW > 0 { + line += " " + timeText(e) + } + line = pad(ansi.Truncate(line, w, ""), w) + var s lipgloss.Style + switch { + case k.cursor && k.active: + return st.RowCursor.Render(line) + case k.cursor: + return st.RowCursorPassive.Render(line) + case k.marked: + s = st.RowMarked + case e.Cat == CatDir || e.Cat == CatLinkDir || e.Cat == CatParent: + s = st.Dir + case e.Cat == CatLink: + s = st.Link + case e.Cat == CatBroken || e.Cat == CatSpecial: + s = st.RowMuted + case e.Cat == CatExec: + s = st.Exec + default: + s = st.Row + } + return s.Render(line) +} + +func sizeText(e Entry, human bool) string { + switch e.Cat { + case CatParent: + return "UP" + case CatDir, CatLinkDir: + if e.SizeLabel != "" { + return e.SizeLabel + } + return "DIR" + } + if !human { + return fmt.Sprint(e.Size) + } + return HumanSize(e.Size) +} + +// HumanSize formats bytes as 1.2K / 34M. +func HumanSize(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%dB", n) + } + div, exp := int64(unit), 0 + for x := n / unit; x >= unit && exp < 5; x /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f%c", float64(n)/float64(div), "KMGTPE"[exp]) +} + +func timeText(e Entry) string { + if e.Parent || e.ModTime.IsZero() { + return strings.Repeat(" ", 16) + } + return e.ModTime.In(time.Local).Format("2006-01-02 15:04") +} + +func pad(s string, w int) string { + if n := ansi.StringWidth(s); n < w { + return s + strings.Repeat(" ", w-n) + } + return s +} diff --git a/internal/tui/panel/session.go b/internal/tui/panel/session.go new file mode 100644 index 0000000..9d663bc --- /dev/null +++ b/internal/tui/panel/session.go @@ -0,0 +1,45 @@ +package panel + +import ( + "strings" + + "vcom/internal/vfs" +) + +// LocalPlace is where the panel stands on the local file system: its +// location if no mount is pushed, else the directory the first mount (an +// archive, a host) was entered from, with the name to focus there. A +// session stores this, never a remote or archive path. +func (p *Model) LocalPlace() (path, focus string) { + if len(p.mounts) == 1 { + return p.path, p.selectedName() + } + m := p.mounts[1] + if m.Return != nil { + return m.Return.Path, m.ReturnFocus + } + return p.mounts[0].Root, "" +} + +// MemoryOf returns the remembered cursor names for directories of volume +// vol (path → name), oldest first in iteration-independent form. +func (p *Model) MemoryOf(vol vfs.VolumeID) map[string]string { + p.rememberCursor() + prefix := string(vol) + "\x00" + out := map[string]string{} + for _, k := range p.memory.order { + if strings.HasPrefix(k, prefix) { + out[k[len(prefix):]] = p.memory.m[k] + } + } + return out +} + +// SeedMemory loads remembered cursor names (path → name) for volume vol. +func (p *Model) SeedMemory(vol vfs.VolumeID, m map[string]string) { + for path, name := range m { + if path != "" && name != "" { + p.memory.put(string(vol)+"\x00"+path, name) + } + } +} diff --git a/internal/tui/preview_req.go b/internal/tui/preview_req.go new file mode 100644 index 0000000..12ff818 --- /dev/null +++ b/internal/tui/preview_req.go @@ -0,0 +1,86 @@ +package tui + +import ( + "fmt" + "strings" + + "vcom/internal/preview" + "vcom/internal/tui/viewer" + "vcom/internal/vfs" +) + +func (a *App) previewRequest(loc vfs.Location, fi vfs.FileInfo) preview.Request { + loc.Path = loc.FS.Paths().Join(loc.Path, fi.Name) + cfg := a.deps.Config + return preview.Request{ + Loc: loc, + Info: fi, + MaxBytes: cfg.Preview.MaxPreviewBytes, + MaxLines: 3000, + HighlightLines: 400, + DirLimit: cfg.Preview.DirectoryPreviewLimit, + ShowHidden: cfg.Browser.ShowHidden, + Theme: a.theme, + MaxRemoteImageBytes: cfg.Preview.MaxRemoteImageBytes, + } +} + +func contentFromPreview(fi vfs.FileInfo, res preview.Result) viewer.Content { + c := viewer.Content{Kind: viewer.Other, Title: fi.Name, Image: res.Image} + switch res.Kind { + case preview.Text: + c.Kind = viewer.Text + c.Lines, c.Plain = res.Lines, res.Plain + return c + case preview.Image: + c.Kind = viewer.Image + } + c.Lines = previewMetadata(res) + if res.Kind == preview.Directory { + for _, entry := range res.Dir { + name := entry.Name + if entry.NavigableDir() { + name += "/" + } + c.Lines = append(c.Lines, name) + } + } + if res.Image != nil && res.Image.TooLarge { + c.Lines = append(c.Lines, "Remote image is too large to download") + } + if res.Truncated { + c.Lines = append(c.Lines, "…") + } + return c +} + +func previewMetadata(res preview.Result) []string { + m := res.Meta + var lines []string + if m.Label != "" { + line := m.Label + if m.Size >= 0 { + line += fmt.Sprintf(" · %d bytes", m.Size) + } + lines = append(lines, line) + } + if !m.ModTime.IsZero() { + lines = append(lines, m.ModTime.Format("2006-01-02 15:04:05")) + } + if m.LinkTarget != "" { + lines = append(lines, "→ "+m.LinkTarget) + } + if m.ImageFormat != "" { + lines = append(lines, fmt.Sprintf("%s · %d×%d", strings.ToUpper(m.ImageFormat), m.Width, m.Height)) + } + if m.Dimensions != "" { + lines = append(lines, m.Dimensions) + } + if m.Duration != "" { + lines = append(lines, m.Duration) + } + if m.PageCount != "" { + lines = append(lines, m.PageCount+" pages") + } + return lines +} diff --git a/internal/tui/quit.go b/internal/tui/quit.go new file mode 100644 index 0000000..8cb2447 --- /dev/null +++ b/internal/tui/quit.go @@ -0,0 +1,45 @@ +package tui + +import ( + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/modal" +) + +// askQuit is q/F10 in Browse (and Ctrl+C with nothing to clear). With +// confirm_quit or running jobs it asks; "q q" quits fast because the Quit +// button's hotkey is q (U-P1-16). Running jobs are cancelled and cleaned +// up by main's teardown (jobs.Shutdown). +func (a *App) askQuit() tea.Cmd { + n := a.activeJobCount() + if !a.deps.Config.Behavior.ConfirmQuit && n == 0 { + return a.quit() + } + d := &modal.Dialog{ + Title: "Quit vcom?", + Buttons: []modal.Button{ + {Label: "Quit", Key: "q", Value: true, Default: true}, + {Label: "Back", Key: "n", Cancel: true}, + }, + } + if n > 0 { + d.Title = "Quit and cancel operations?" + d.Warnings = []string{fmt.Sprintf("%d operation(s) running: they will be cancelled and their temp files removed", n)} + d.Buttons[0].Label = "Cancel them and quit" + d.Buttons[0].Danger = true + } + a.openModal(d, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + return a.quit() + }) + return nil +} + +func (a *App) quit() tea.Cmd { + a.quitting = true + return tea.Quit +} diff --git a/internal/tui/register_archive.go b/internal/tui/register_archive.go new file mode 100644 index 0000000..d1a513f --- /dev/null +++ b/internal/tui/register_archive.go @@ -0,0 +1,31 @@ +package tui + +import ( + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" +) + +// registerArchive adds the archive actions of stage 6.5. +func registerArchive(t actionTable) { + t.add(keys.ArchiveNew, (*App).createArchive, (*App).canCreateArchive) + t.add(keys.ArchiveUnzip, (*App).unpack, (*App).canUnpack) +} + +// registerArchiveHooks makes Enter on an archive open it. Another openFile +// set before (or after, if it chains the same way) handles other files. +func registerArchiveHooks(a *App) { + registerOpsState(a) + prev := a.openFile + a.openFile = func(a *App, e panel.Entry) tea.Cmd { + if isArchive(e) { + return a.openArchive(e) + } + if prev != nil { + return prev(a, e) + } + return a.notify(notify.Info, "Opening files: not available yet") + } +} diff --git a/internal/tui/register_misc.go b/internal/tui/register_misc.go new file mode 100644 index 0000000..7804e12 --- /dev/null +++ b/internal/tui/register_misc.go @@ -0,0 +1,60 @@ +package tui + +import ( + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/panel" +) + +// registerMisc adds the actions of stage 6.6. +func registerMisc(t actionTable) { + t.add(keys.PaneMirror, (*App).mirror, (*App).canMirror) + t.add(keys.SortMenu, (*App).sortMenu, nil) + t.add(keys.PathYank, (*App).yankPath, nil) + t.add(keys.FileEdit, (*App).editSelected, (*App).canEdit) +} + +// registerMiscHooks installs the Enter dispatcher for files, the session +// and the messages of stage 6.6. +func registerMiscHooks(a *App) { + a.misc = &miscState{} + a.restoreSession() + // Archives keep going to the archive hook (6.5); everything else is + // dispatched here (§7.12). + prev := a.openFile + a.openFile = func(a *App, e panel.Entry) tea.Cmd { + if prev != nil && isArchive(e) { + return prev(a, e) + } + return a.openRegular(e) + } + a.handle(func(a *App, msg tea.Msg) (tea.Cmd, bool) { + switch m := msg.(type) { + case openDecisionMsg: + return a.onOpenDecision(m), true + case extDoneMsg: + return a.onExtDone(m), true + case remoteEditedMsg: + return a.onRemoteEdited(m), true + case openedMsg: + return a.onOpened(m), true + case mirrorMsg: + return a.onMirror(m), true + case sortSavedMsg: + return a.onSortSaved(m), true + case yankedMsg: + return a.onYanked(m), true + case sessionTickMsg: + return a.onSessionTick(), true + case sessionSavedMsg: + if m.err == nil { + a.misc.lastSaved = m.fp + } + return nil, true + case signalMsg: + return a.onSignal(), true + } + return nil, false + }) +} diff --git a/internal/tui/register_ops.go b/internal/tui/register_ops.go new file mode 100644 index 0000000..d4e3667 --- /dev/null +++ b/internal/tui/register_ops.go @@ -0,0 +1,33 @@ +package tui + +import ( + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/transfer" + "vcom/internal/tui/keys" +) + +// registerOps adds the file operations of stage 6.2. +func registerOps(t actionTable) { + t.add(keys.FileCopy, func(a *App) tea.Cmd { return a.startTransfer(transfer.Copy) }, + func(a *App) error { return a.canTransfer(false) }) + t.add(keys.FileMove, func(a *App) tea.Cmd { return a.startTransfer(transfer.Move) }, + func(a *App) error { return a.canTransfer(true) }) + t.add(keys.FileTrash, (*App).trashSelected, (*App).canDelete) + t.add(keys.FileDelete, (*App).deleteSelected, (*App).canDelete) + t.add(keys.FileMkdir, (*App).mkdir, (*App).canWriteHere) + t.add(keys.FileRename, (*App).rename, (*App).canWriteHere) + t.add(keys.DirSize, (*App).dirSize, nil) + t.add(keys.JobsList, (*App).jobsList, nil) +} + +// registerOpsHooks adds message and job-event handlers of stage 6.2. +func registerOpsHooks(a *App) { + registerOpsState(a) + a.handle(func(a *App, msg tea.Msg) (tea.Cmd, bool) { + if m, ok := msg.(fsDoneMsg); ok { + return a.onFSDone(m), true + } + return nil, false + }) +} diff --git a/internal/tui/register_ssh.go b/internal/tui/register_ssh.go new file mode 100644 index 0000000..d2d592d --- /dev/null +++ b/internal/tui/register_ssh.go @@ -0,0 +1,7 @@ +package tui + +// registerSSH adds the action handlers of stage 6.4 (stub until then). +func registerSSH(t actionTable) {} + +// registerSSHHooks adds message and job-event handlers of stage 6.4. +func registerSSHHooks(a *App) {} diff --git a/internal/tui/register_viewer.go b/internal/tui/register_viewer.go new file mode 100644 index 0000000..b7b0ab1 --- /dev/null +++ b/internal/tui/register_viewer.go @@ -0,0 +1,67 @@ +package tui + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/notify" + "vcom/internal/tui/viewer" +) + +// registerViewer installs the full text viewer of stage 6.3. +func registerViewer(t actionTable) { + t.add(keys.ViewerLineUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil) + t.add(keys.ViewerLineDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil) + t.add(keys.ViewerPageUp, func(a *App) tea.Cmd { a.viewer.Page(-1); return nil }, nil) + t.add(keys.ViewerPageDown, func(a *App) tea.Cmd { a.viewer.Page(1); return nil }, nil) + t.add(keys.ViewerHalfUp, func(a *App) tea.Cmd { a.viewer.HalfPage(-1); return nil }, nil) + t.add(keys.ViewerHalfDown, func(a *App) tea.Cmd { a.viewer.HalfPage(1); return nil }, nil) + t.add(keys.ViewerLeft, func(a *App) tea.Cmd { a.viewer.MoveHorizontal(-1); return nil }, nil) + t.add(keys.ViewerRight, func(a *App) tea.Cmd { a.viewer.MoveHorizontal(1); return nil }, nil) + t.add(keys.ViewerWordNext, func(a *App) tea.Cmd { a.viewer.MoveWord('w'); return nil }, nil) + t.add(keys.ViewerWordPrev, func(a *App) tea.Cmd { a.viewer.MoveWord('b'); return nil }, nil) + t.add(keys.ViewerWordEnd, func(a *App) tea.Cmd { a.viewer.MoveWord('e'); return nil }, nil) + t.add(keys.ViewerLineStart, func(a *App) tea.Cmd { a.viewer.LineStart(false); return nil }, nil) + t.add(keys.ViewerFirstNonBlank, func(a *App) tea.Cmd { a.viewer.LineStart(true); return nil }, nil) + t.add(keys.ViewerLineEnd, func(a *App) tea.Cmd { a.viewer.LineEnd(); return nil }, nil) + t.add(keys.ViewerTop, func(a *App) tea.Cmd { a.viewer.Jump(false); return nil }, nil) + t.add(keys.ViewerBottom, func(a *App) tea.Cmd { a.viewer.Jump(true); return nil }, nil) + t.add(keys.ViewerWrap, func(a *App) tea.Cmd { + if a.viewer.ToggleWrap() { + return a.notify(notify.Info, "Line wrap: on") + } + return a.notify(notify.Info, "Line wrap: off") + }, nil) + t.add(keys.ViewerYankLine, (*App).yankViewer, nil) + t.add(keys.ViewerYank, (*App).yankViewer, nil) +} + +// registerViewerHooks handles clipboard results. +func registerViewerHooks(a *App) { + a.handle(func(a *App, msg tea.Msg) (tea.Cmd, bool) { + m, ok := msg.(viewerYankedMsg) + if !ok { + return nil, false + } + if m.err != nil { + return a.notify(notify.Error, "Clipboard: "+m.err.Error()), true + } + return a.notify(notify.Success, "Selection copied to the clipboard"), true + }) +} + +type viewerYankedMsg struct{ err error } + +func (a *App) yankViewer() tea.Cmd { + text := strings.Join(a.viewer.Selection(), "\n") + if text == "" { + return a.notify(notify.Info, "Nothing to copy") + } + if a.viewer.Focus == viewer.Visual { + a.viewer.Focus = viewer.Caret + } + clip := a.deps.Clipboard + return func() tea.Msg { return viewerYankedMsg{err: clip(text)} } +} diff --git a/internal/tui/run_menu.go b/internal/tui/run_menu.go new file mode 100644 index 0000000..683a934 --- /dev/null +++ b/internal/tui/run_menu.go @@ -0,0 +1,125 @@ +package tui + +import ( + "context" + "io" + "unicode/utf8" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +// miscState is the UI state of stage 6.6. +type miscState struct { + lastSaved string // fingerprint of the last saved session + shutDown bool +} + +// openRegular is Enter on a file that is not an archive (§7.12): an +// executable opens the Run menu (never runs by itself; U-P1-3, N-P0-2), +// text goes to the editor, anything else to the desktop opener. +func (a *App) openRegular(e panel.Entry) tea.Cmd { + p := a.Active() + if e.Cat == panel.CatExec && p.FS().Caps().Exec { + return a.runMenu(e) + } + loc, fsys := p.Location(), p.FS() + path := fsys.Paths().Join(p.Path(), e.Name) + name := e.Name + return func() tea.Msg { + text, err := sniffText(fsys, path) + return openDecisionMsg{Loc: loc, Name: name, Text: text, Err: err} + } +} + +type openDecisionMsg struct { + Loc vfs.Location + Name string + Text bool + Err error +} + +// sniffText reads the head of the file: valid UTF-8 without NUL is text. +func sniffText(fsys vfs.FS, path string) (bool, error) { + f, err := fsys.Open(context.Background(), path) + if err != nil { + return false, err + } + defer f.Close() + buf := make([]byte, 8192) + n, err := io.ReadFull(f, buf) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return false, err + } + b := buf[:n] + for _, c := range b { + if c == 0 { + return false, nil + } + } + if n == len(buf) { // the sample may end in the middle of a rune + for i := 0; i < 3 && len(b) > 0 && !utf8.Valid(b); i++ { + b = b[:len(b)-1] + } + } + return utf8.Valid(b), nil +} + +func (a *App) onOpenDecision(m openDecisionMsg) tea.Cmd { + if m.Err != nil { + return a.notify(notify.Error, "Cannot open "+m.Name+": "+cleanErr(m.Err).Error()) + } + if m.Text && !m.Loc.FS.Caps().ReadOnly { + return a.editFile(m.Loc, m.Name) + } + return a.openWithDesktop(m.Loc, m.Name) +} + +// runMenu: Run / Edit / View / Cancel for an executable. +func (a *App) runMenu(e panel.Entry) tea.Cmd { + p := a.Active() + loc := p.Location() + path := p.FS().Paths().Join(p.Path(), e.Name) + items := []modal.Item{ + {Label: "Run", Detail: "r", Value: "run"}, + {Label: "Edit", Detail: "F4", Value: "edit"}, + {Label: "View", Detail: "F3", Value: "view"}, + {Label: "Cancel", Value: "cancel"}, + } + a.openModal(modal.NewList(e.Name+" is executable", items, nil), func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + switch o.Value { + case "run": + return a.deps.Exec(runCmd(path, loc.Path), func(err error) tea.Msg { return extDoneMsg{Loc: loc, What: "Run " + e.Name, Err: err} }) + case "edit": + return a.editFile(loc, e.Name) + case "view": + return a.dispatch(keys.ScreenView) + } + return nil + }) + return nil +} + +// extDoneMsg: a foreground program (editor, Run) returned. +type extDoneMsg struct { + Loc vfs.Location + What string + Err error +} + +func (a *App) onExtDone(m extDoneMsg) tea.Cmd { + a.applied.mouse = mouseUnknown // the program may have reset the terminal (U-P1-3) + cmds := []tea.Cmd{a.invalidate([]vfs.Location{m.Loc})} + if m.Err != nil { + cmds = append(cmds, a.notify(notify.Warn, m.What+": "+m.Err.Error())) + } + return tea.Batch(cmds...) +} diff --git a/internal/tui/session.go b/internal/tui/session.go new file mode 100644 index 0000000..22e400e --- /dev/null +++ b/internal/tui/session.go @@ -0,0 +1,99 @@ +package tui + +import ( + "fmt" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/state" +) + +// sessionInterval: the session is saved this often when it changed (§9.2). +const sessionInterval = 30 * time.Second + +type ( + sessionTickMsg struct{} + sessionSavedMsg struct { + fp string + err error + } +) + +// miscInit starts the periodic session save. +func (a *App) miscInit() tea.Cmd { + return tea.Tick(sessionInterval, func(time.Time) tea.Msg { return sessionTickMsg{} }) +} + +// SessionSnapshot is what would be saved now. A panel inside an archive or +// on a host is saved as the local directory it was entered from (no +// auto-connect on start). +func (a *App) SessionSnapshot() state.Session { + s := state.Session{ActivePane: "left"} + if a.active == 1 { + s.ActivePane = "right" + } + vol := a.deps.LocalFS.Volume() + for i, p := range a.panels { + path, focus := p.LocalPlace() + ps := state.PaneSession{Path: path, EntryName: focus, CursorMemory: p.MemoryOf(vol)} + if i == 0 { + s.Left = ps + } else { + s.Right = ps + } + } + return s +} + +func fingerprint(s state.Session) string { return fmt.Sprintf("%v", s) } // maps print sorted + +// SaveSession writes the session now (teardown, signals). +func (a *App) SaveSession() error { + s := a.SessionSnapshot() + if err := a.deps.SaveSession(s); err != nil { + return err + } + a.misc.lastSaved = fingerprint(s) + return nil +} + +// Shutdown saves the session once; main calls it after Program.Run returns +// (quit, signal, recovered panic). +func (a *App) Shutdown() error { + if a.misc.shutDown { + return nil + } + a.misc.shutDown = true + return a.SaveSession() +} + +func (a *App) onSessionTick() tea.Cmd { + next := a.miscInit() + s := a.SessionSnapshot() + fp := fingerprint(s) + if fp == a.misc.lastSaved || a.misc.shutDown { + return next + } + save := a.deps.SaveSession + return tea.Batch(next, func() tea.Msg { return sessionSavedMsg{fp: fp, err: save(s)} }) +} + +// restoreSession applies the saved active pane and cursor memory (the start +// directories were chosen by DefaultDeps). +func (a *App) restoreSession() { + s := a.deps.Session + if s == nil { + return + } + if s.ActivePane == "right" { + a.active = 1 + } + vol := a.deps.LocalFS.Volume() + for i, ps := range []state.PaneSession{s.Left, s.Right} { + a.panels[i].SeedMemory(vol, ps.CursorMemory) + if ps.EntryName != "" && ps.Path == a.deps.StartDirs[i] { + a.panels[i].SeedMemory(vol, map[string]string{ps.Path: ps.EntryName}) + } + } +} diff --git a/internal/tui/signals.go b/internal/tui/signals.go new file mode 100644 index 0000000..1911b39 --- /dev/null +++ b/internal/tui/signals.go @@ -0,0 +1,20 @@ +package tui + +import tea "github.com/charmbracelet/bubbletea" + +// Signal is what main sends on SIGHUP (terminal closed): save the session +// and quit without asking. Running jobs are cancelled by main's teardown. +func Signal() tea.Msg { return signalMsg{} } + +type signalMsg struct{} + +func (a *App) onSignal() tea.Cmd { + s := a.SessionSnapshot() + a.misc.shutDown = true + a.quitting = true + save := a.deps.SaveSession + return func() tea.Msg { + _ = save(s) + return tea.Quit() + } +} diff --git a/internal/tui/sort_menu.go b/internal/tui/sort_menu.go new file mode 100644 index 0000000..3118dd7 --- /dev/null +++ b/internal/tui/sort_menu.go @@ -0,0 +1,76 @@ +package tui + +import ( + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" +) + +// sortMenu is S: sort key, reverse order, directories first. The choice +// applies to both panels and is saved to the config (one line each, like +// the theme). +func (a *App) sortMenu() tea.Cmd { + b := a.deps.Config.Browser + onOff := func(v bool) string { + if v { + return "on" + } + return "off" + } + cur := b.Sort.By + mark := func(by string) string { + if by == cur { + return "●" + } + return "" + } + items := []modal.Item{ + {Label: "Sort by", Header: true}, + {Label: "Name", Detail: mark("name"), Value: "name"}, + {Label: "Size", Detail: mark("size"), Value: "size"}, + {Label: "Modified", Detail: mark("modified"), Value: "modified"}, + {Label: "Extension", Detail: mark("extension"), Value: "extension"}, + {Label: "Options", Header: true}, + {Label: "Reverse order", Detail: onOff(b.Sort.Reverse), Value: "reverse"}, + {Label: "Directories first", Detail: onOff(b.DirsFirst), Value: "dirsfirst"}, + } + a.openModal(modal.NewList("Sort", items, cur), func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + return nil + } + c := &a.deps.Config.Browser + var section, key string + var value any + switch v := o.Value.(string); v { + case "reverse": + c.Sort.Reverse = !c.Sort.Reverse + section, key, value = "browser.sort", "reverse", c.Sort.Reverse + case "dirsfirst": + c.DirsFirst = !c.DirsFirst + section, key, value = "browser", "dirs_first", c.DirsFirst + default: + c.Sort.By = v + section, key, value = "browser.sort", "by", v + } + opts := a.panelOptions() + for _, p := range a.panels { + p.SetOptions(opts) + } + set, path := a.deps.SetConfigKey, a.deps.ConfigPath + save := func() tea.Msg { + if _, err := set(path, section, key, value); err != nil { + return sortSavedMsg{err} + } + return nil + } + return tea.Batch(save, a.selectionChanged()) + }) + return nil +} + +type sortSavedMsg struct{ err error } + +func (a *App) onSortSaved(m sortSavedMsg) tea.Cmd { + return a.notify(notify.Error, "Sort order not saved: "+m.err.Error()) +} diff --git a/internal/tui/status.go b/internal/tui/status.go new file mode 100644 index 0000000..cddf87f --- /dev/null +++ b/internal/tui/status.go @@ -0,0 +1,98 @@ +package tui + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/notify" + "vcom/internal/tui/viewer" +) + +// modeBadge names the mode shown at the left of the status line. +func (a *App) modeBadge() string { + switch { + case a.nativeSelect: + return "SELECT" + case a.filter != nil: + return "FILTER" + case a.viewer.Focus == viewer.Visual && a.screen != ScreenBrowse: + return "VISUAL" + case a.viewer.Focus == viewer.Caret && a.screen != ScreenBrowse: + return "CARET" + case a.screen == ScreenView: + return "VIEW" + case a.screen == ScreenInfo: + return "INFO" + } + return "" +} + +// statusLine: mode badge and current note on the left; jobs and the +// connection state of the active panel on the right (design §7.6). +func (a *App) statusLine() string { + st := a.styles + w := a.layout.Status.W + var left strings.Builder + if b := a.modeBadge(); b != "" { + left.WriteString(st.Badge.Render(b)) + left.WriteString(st.Status.Render(" ")) + } + if n, ok := a.notes.Current(); ok { + s := st.NoteInfo + switch n.Level { + case notify.Success: + s = st.NoteOK + case notify.Warn: + s = st.NoteWarn + case notify.Error: + s = st.NoteError + } + left.WriteString(s.Render(n.Text)) + } else if e, ok := a.Active().Selected(); ok && !e.Parent { + left.WriteString(st.Status.Render(e.Name)) + } + + var right []string + if jobs := a.activeJobs(); len(jobs) > 0 { + j := jobs[0] + pct := "" + if t := j.Progress.BytesTotal; t > 0 { + pct = fmt.Sprintf(" %d%%", j.Progress.BytesDone*100/t) + } + r := fmt.Sprintf("⟳ %s%s", j.Title, pct) + if len(jobs) > 1 { + r += fmt.Sprintf(" · +%d", len(jobs)-1) + } + right = append(right, r) + } + if b := a.Active().Badge; b != "" { + right = append(right, b) + } + r := st.Status.Render(strings.Join(right, " ")) + rw := ansi.StringWidth(r) + l := ansi.Truncate(left.String(), max(0, w-rw-1), "…") + gap := max(0, w-ansi.StringWidth(l)-rw) + return l + st.Status.Render(strings.Repeat(" ", gap)) + r +} + +// footerLine lists the footer bindings of the context owning input. +func (a *App) footerLine() string { + st := a.styles + w := a.layout.Footer.W + var b strings.Builder + used := 0 + for _, it := range a.keys.Footer(a.inputOwner()) { + k := st.FooterKey.Render(it.Keys) + h := st.Footer.Render(" " + it.Help + " ") + n := ansi.StringWidth(k) + ansi.StringWidth(h) + if used+n > w { + break + } + b.WriteString(k) + b.WriteString(h) + used += n + } + return b.String() + st.Footer.Render(strings.Repeat(" ", max(0, w-used))) +} diff --git a/internal/tui/style/style.go b/internal/tui/style/style.go new file mode 100644 index 0000000..79bf91f --- /dev/null +++ b/internal/tui/style/style.go @@ -0,0 +1,102 @@ +// Package style builds every lipgloss style of the new UI once per theme +// (design §7.10): render code never calls lipgloss.NewStyle. Gen changes +// with every theme switch and is part of every render-cache key. +package style + +import ( + "sync/atomic" + + "github.com/charmbracelet/lipgloss" + + "vcom/internal/theme" +) + +var gens atomic.Uint64 + +// Styles of one theme. +type Styles struct { + Gen uint64 + Pal theme.Palette + + // Panels. + PaneBorder lipgloss.Style + PaneBorderActive lipgloss.Style + PaneTitle lipgloss.Style + PaneTitleActive lipgloss.Style + Row lipgloss.Style + RowCursor lipgloss.Style // cursor in the active pane + RowCursorPassive lipgloss.Style // cursor in the passive pane + RowMarked lipgloss.Style + RowMuted lipgloss.Style + Dir lipgloss.Style + Link lipgloss.Style + Exec lipgloss.Style + FilterLine lipgloss.Style + + // Status line and footer. + Status lipgloss.Style + Badge lipgloss.Style + NoteInfo lipgloss.Style + NoteOK lipgloss.Style + NoteWarn lipgloss.Style + NoteError lipgloss.Style + Footer lipgloss.Style + FooterKey lipgloss.Style + + // Modals. + Modal lipgloss.Style + ModalTitle lipgloss.Style + ModalLabel lipgloss.Style + ModalWarning lipgloss.Style + Button lipgloss.Style + ButtonFocused lipgloss.Style + ButtonDanger lipgloss.Style + ListCursor lipgloss.Style + Muted lipgloss.Style + Text lipgloss.Style + Section lipgloss.Style +} + +// New builds the styles of p. +func New(p theme.Palette) *Styles { + base := lipgloss.NewStyle().Foreground(p.Text) + return &Styles{ + Gen: gens.Add(1), + Pal: p, + + PaneBorder: lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(p.Border), + PaneBorderActive: lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(p.BorderActive), + PaneTitle: lipgloss.NewStyle().Foreground(p.Muted), + PaneTitleActive: lipgloss.NewStyle().Foreground(p.ActivePath).Bold(true), + Row: base, + RowCursor: lipgloss.NewStyle().Foreground(p.Text).Background(p.Selection).Bold(true), + RowCursorPassive: lipgloss.NewStyle().Foreground(p.Text).Background(p.Hover), + RowMarked: lipgloss.NewStyle().Foreground(p.Marked).Bold(true), + RowMuted: lipgloss.NewStyle().Foreground(p.Muted), + Dir: lipgloss.NewStyle().Foreground(p.Folder).Bold(true), + Link: lipgloss.NewStyle().Foreground(p.Accent), + Exec: lipgloss.NewStyle().Foreground(p.ExecFile), + FilterLine: lipgloss.NewStyle().Foreground(p.Accent), + + Status: lipgloss.NewStyle().Foreground(p.Text).Background(p.StatusBar), + Badge: lipgloss.NewStyle().Foreground(p.Background).Background(p.Accent).Bold(true).Padding(0, 1), + NoteInfo: lipgloss.NewStyle().Foreground(p.Info).Background(p.StatusBar), + NoteOK: lipgloss.NewStyle().Foreground(p.Success).Background(p.StatusBar), + NoteWarn: lipgloss.NewStyle().Foreground(p.Warning).Background(p.StatusBar).Bold(true), + NoteError: lipgloss.NewStyle().Foreground(p.Danger).Background(p.StatusBar).Bold(true), + Footer: lipgloss.NewStyle().Foreground(p.Muted).Background(p.Footer), + FooterKey: lipgloss.NewStyle().Foreground(p.FooterKey).Background(p.Footer).Bold(true), + + Modal: lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(p.BorderActive).Padding(0, 1), + ModalTitle: lipgloss.NewStyle().Foreground(p.Accent).Bold(true), + ModalLabel: lipgloss.NewStyle().Foreground(p.Muted), + ModalWarning: lipgloss.NewStyle().Foreground(p.Warning), + Button: lipgloss.NewStyle().Foreground(p.Text).Padding(0, 1), + ButtonFocused: lipgloss.NewStyle().Foreground(p.Background).Background(p.ConfirmButton).Bold(true).Padding(0, 1), + ButtonDanger: lipgloss.NewStyle().Foreground(p.Background).Background(p.Danger).Bold(true).Padding(0, 1), + ListCursor: lipgloss.NewStyle().Foreground(p.Text).Background(p.Selection).Bold(true), + Muted: lipgloss.NewStyle().Foreground(p.Muted), + Text: base, + Section: lipgloss.NewStyle().Foreground(p.HelpNav).Bold(true), + } +} diff --git a/internal/tui/theme_select.go b/internal/tui/theme_select.go new file mode 100644 index 0000000..6a9c50a --- /dev/null +++ b/internal/tui/theme_select.go @@ -0,0 +1,54 @@ +package tui + +import ( + "fmt" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/theme" + "vcom/internal/tui/modal" + "vcom/internal/tui/notify" +) + +type themeSavedMsg struct { + Theme string + Path string + Err error +} + +// openThemeSelect is "t": a list with live preview; Enter keeps and saves +// the theme with config.SetKey (comments kept, design §9.2), Esc reverts. +func (a *App) openThemeSelect() tea.Cmd { + orig := a.theme + var items []modal.Item + for _, n := range theme.Names() { + items = append(items, modal.Item{Label: n, Value: n}) + } + l := modal.NewList("Theme", items, orig) + l.OnMove = func(it modal.Item) tea.Cmd { + a.setTheme(it.Value.(string)) // runs in Update: no I/O + return nil + } + a.openModal(l, func(o modal.Outcome) tea.Cmd { + if o.Cancelled { + a.setTheme(orig) + return nil + } + name := o.Value.(string) + a.setTheme(name) + a.deps.Config.UI.Theme = name + set, path := a.deps.SetConfigKey, a.deps.ConfigPath + return func() tea.Msg { + p, err := set(path, "ui", "theme", name) + return themeSavedMsg{Theme: name, Path: p, Err: err} + } + }) + return nil +} + +func (a *App) onThemeSaved(m themeSavedMsg) tea.Cmd { + if m.Err != nil { + return a.notify(notify.Error, fmt.Sprintf("Theme %s not saved: %v", m.Theme, m.Err)) + } + return a.notify(notify.Success, fmt.Sprintf("Theme %s saved to %s", m.Theme, m.Path)) +} diff --git a/internal/tui/tracker.go b/internal/tui/tracker.go new file mode 100644 index 0000000..6e2c013 --- /dev/null +++ b/internal/tui/tracker.go @@ -0,0 +1,95 @@ +package tui + +import "context" + +// ReqKind is a kind of async request. +type ReqKind uint8 + +const ( + ReqList ReqKind = iota + ReqPreview + ReqPreviewDebounce + ReqDirSize + ReqMount + ReqConnect + ReqFeature // features (6.2–6.6) use ReqKey.Extra to tell their requests apart +) + +// ReqKey identifies a request slot: a newer request with the same key +// supersedes the older one. +type ReqKey struct { + Kind ReqKind + Pane int + Extra string +} + +// Ticket travels with every async message. Update accepts a message only if +// its ticket is still current (design §7.7, U-P1-13). +type Ticket struct { + Key ReqKey + Gen uint64 +} + +type slot struct { + gen uint64 + cancel context.CancelFunc + live bool +} + +// Tracker hands out tickets. UI goroutine only. +type Tracker struct { + gen uint64 + slots map[ReqKey]*slot +} + +// Begin starts a request for k: the previous one with the same key is +// cancelled and its ticket becomes stale. +func (t *Tracker) Begin(k ReqKey) (Ticket, context.Context) { + if t.slots == nil { + t.slots = map[ReqKey]*slot{} + } + if s := t.slots[k]; s != nil && s.cancel != nil { + s.cancel() + } + t.gen++ + ctx, cancel := context.WithCancel(context.Background()) + t.slots[k] = &slot{gen: t.gen, cancel: cancel, live: true} + return Ticket{Key: k, Gen: t.gen}, ctx +} + +// Accept reports whether tk is the current ticket of its key; if so the +// request is finished (its context released) and the slot freed. +func (t *Tracker) Accept(tk Ticket) bool { + s := t.slots[tk.Key] + if s == nil || !s.live || s.gen != tk.Gen { + return false + } + s.live = false + s.cancel() + delete(t.slots, tk.Key) + return true +} + +// Pending reports whether a request for k is in flight. +func (t *Tracker) Pending(k ReqKey) bool { + s := t.slots[k] + return s != nil && s.live +} + +// Cancel cancels the request for k (its ticket becomes stale). +func (t *Tracker) Cancel(k ReqKey) { + if s := t.slots[k]; s != nil { + s.cancel() + delete(t.slots, k) + } +} + +// CancelAll cancels every request of kind. +func (t *Tracker) CancelAll(kind ReqKind) { + for k, s := range t.slots { + if k.Kind == kind { + s.cancel() + delete(t.slots, k) + } + } +} diff --git a/internal/tui/update.go b/internal/tui/update.go new file mode 100644 index 0000000..8d5fcc0 --- /dev/null +++ b/internal/tui/update.go @@ -0,0 +1,156 @@ +package tui + +import ( + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/keys" + "vcom/internal/tui/modal" +) + +// doubleClick is the max interval between clicks of a double click. +const doubleClick = 400 * time.Millisecond + +// Update is the single entry point of the model. It never blocks: all I/O +// runs in Cmds (N-P1-1). +func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + cmd := a.update(msg) + a.relayout() + return a, tea.Batch(cmd, a.reconcile()) +} + +func (a *App) update(msg tea.Msg) tea.Cmd { + switch m := msg.(type) { + case tea.WindowSizeMsg: + a.w, a.h = m.Width, m.Height + return nil + case tea.KeyMsg: + return a.key(m) + case tea.MouseMsg: + return a.mouse(m) + case listingMsg: + return a.onListing(m) + case previewTickMsg: + return a.onPreviewTick(m) + case previewMsg: + return a.onPreview(m) + case noteExpiredMsg: + a.notes.Expire(m.id) + return nil + case themeSavedMsg: + return a.onThemeSaved(m) + case jobEventMsg: + return a.onJobEvent(m) + case execDoneMsg: + a.applied.mouse = mouseUnknown // the external program may have reset it (U-P1-3) + return nil + case imageEventMsg: + return a.onImageEvent(m) + } + for _, h := range a.handlers { + if cmd, ok := h(a, msg); ok { + return cmd + } + } + return nil +} + +func (a *App) key(k tea.KeyMsg) tea.Cmd { + a.notes.KeyPressed() + if a.nativeSelect && k.Type == tea.KeyEsc && a.modals.Len() == 0 { + return a.toggleNativeSelect() + } + ctx := a.inputOwner() + act, ok := a.keys.Resolve(ctx, k) + if ok && act == keys.Pending { + return nil + } + switch { + case a.modals.Len() > 0: + return a.modals.Key(act, k) + case ctx == keys.CtxFilterEdit: + return a.filterKey(act, ok, k) + case ok: + return a.dispatch(act) + } + return nil +} + +// mouse routes mouse events: everything to the top modal while one is open +// (clicks outside it are ignored); otherwise by Layout hit-test. +func (a *App) mouse(m tea.MouseMsg) tea.Cmd { + if a.modals.Len() > 0 { + return a.modals.Mouse(m, a.layout.Screen, a.styles) + } + if a.nativeSelect { + return nil + } + switch m.Button { + case tea.MouseButtonWheelUp, tea.MouseButtonWheelDown: + d := 3 + if m.Button == tea.MouseButtonWheelUp { + d = -3 + } + if a.screen == ScreenView || (a.screen == ScreenInfo && a.layout.Preview.Contains(m.X, m.Y)) { + a.viewer.Scroll(d) + return nil + } + if i, ok := a.layout.paneAt(m.X, m.Y); ok { + a.panels[i].Scroll(d) + if i == a.active { + return a.selectionChanged() + } + } + return nil + } + if m.Action != tea.MouseActionPress || a.screen == ScreenView { + return nil + } + i, ok := a.layout.paneAt(m.X, m.Y) + if !ok { + return nil + } + if m.Button == tea.MouseButtonRight { + if a.screen == ScreenInfo { + return a.setScreen(ScreenBrowse) + } + return a.setScreen(ScreenInfo) + } + if m.Button != tea.MouseButtonLeft || a.filter != nil && i != a.active { + return nil + } + if i != a.active { + a.active = i + } + lr := a.listRect(i) + if !lr.Contains(m.X, m.Y) { + return a.selectionChanged() + } + row, ok := a.panels[i].RowAt(m.Y - lr.Y) + if !ok { + return a.selectionChanged() + } + now := a.now() + double := a.lastClick.pane == i && a.lastClick.row == row && now.Sub(a.lastClick.at) <= doubleClick + a.lastClick = click{at: now, pane: i, row: row} + a.panels[i].SetCursor(row) + if double { + a.lastClick = click{} + return a.dispatch(keys.NavOpen) + } + return a.selectionChanged() +} + +// openModal pushes m; a filter being edited is committed first (the filter +// line never coexists with a modal). +func (a *App) openModal(m modal.Modal, onClose func(modal.Outcome) tea.Cmd) uint64 { + if a.filter != nil { + a.commitFilter() + } + a.keys.Reset() + return a.modals.Push(m, onClose) +} + +// execDoneMsg is sent after an external program (editor, run) returns. +type execDoneMsg struct{ Err error } diff --git a/internal/tui/view.go b/internal/tui/view.go new file mode 100644 index 0000000..7f5c214 --- /dev/null +++ b/internal/tui/view.go @@ -0,0 +1,133 @@ +package tui + +import ( + "strconv" + "strings" + + "github.com/charmbracelet/x/ansi" + + "vcom/internal/tui/geom" + "vcom/internal/tui/panel" + "vcom/internal/vfs" +) + +// View renders the screen. It only reads state (design §7.9): sizes were +// set in Update (relayout), effects are applied by reconcile. +func (a *App) View() string { + if a.w <= 0 || a.h <= 0 { + return "" + } + canvas := make([]string, a.h) + blank := strings.Repeat(" ", a.w) + for i := range canvas { + canvas[i] = blank + } + draw := func(r geom.Rect, s string) { + if r.Empty() || s == "" { + return + } + for i, line := range strings.Split(s, "\n") { + y := r.Y + i + if i >= r.H || y >= len(canvas) { + break + } + canvas[y] = place(canvas[y], ansi.Truncate(line, r.W, ""), r.X, a.w) + } + } + switch a.screen { + case ScreenView: + draw(a.layout.Viewer, a.renderViewer()) + default: + for i, p := range a.panels { + r := a.layout.Panes[i] + if r.Empty() { + continue + } + draw(r, p.Render(panel.View{ + Rect: r, + Active: i == a.active, + FilterLine: a.filterLine(i), + Title: a.paneTitle(p), + Styles: a.styles, + })) + } + if a.screen == ScreenInfo { + draw(a.layout.Preview, a.renderPreview()) + } + } + draw(a.layout.Status, a.statusLine()) + if !a.layout.Footer.Empty() { + draw(a.layout.Footer, a.footerLine()) + } + out := strings.Join(canvas, "\n") + return a.modals.Render(out, a.layout.Screen, a.styles) +} + +// place writes s into line at column x. +func place(line, s string, x, w int) string { + left := ansi.Truncate(line, x, "") + if n := ansi.StringWidth(left); n < x { + left += strings.Repeat(" ", x-n) + } + right := ansi.TruncateLeft(line, x+ansi.StringWidth(s), "") + out := left + s + right + if n := ansi.StringWidth(out); n < w { + out += strings.Repeat(" ", w-n) + } + return out +} + +func (a *App) filterLine(i int) string { + if a.filter == nil || i != a.active { + return "" + } + return a.filter.View() +} + +func (a *App) paneTitle(p *panel.Model) string { + if p.Source == panel.SourceHosts { + return "SSH hosts" + } + t := displayPath(p.Location()) + if n := p.MarkCount(); n > 0 { + t += " [" + strconv.Itoa(n) + " marked]" + } + return t +} + +func (a *App) renderPreview() string { + r := a.layout.Preview + if r.W < 4 || r.H < 3 { + return "" + } + inner := r.W - 2 + title := a.viewer.Title() + if title == "" { + if e, ok := a.Active().Selected(); ok && !e.Parent { + title = e.Name + } + } + body := a.viewer.Render(inner, a.layout.PreviewBody.H, a.styles) + content := a.styles.PaneTitle.Render(pad(ansi.Truncate(title, inner, "…"), inner)) + "\n" + body + return a.styles.PaneBorder.Width(inner).Render(content) +} + +func (a *App) renderViewer() string { + r := a.layout.Viewer + title := a.viewer.Title() + if title == "" { + title = "View" + } + head := a.styles.PaneTitleActive.Render(pad(ansi.Truncate(title, r.W, "…"), r.W)) + return head + "\n" + a.viewer.Render(r.W, max(0, r.H-1), a.styles) +} + +func pad(s string, w int) string { + if n := ansi.StringWidth(s); n < w { + return s + strings.Repeat(" ", w-n) + } + return s +} + +// locationOf is a helper for features: the active panel's location. +func (a *App) locationOf(i int) vfs.Location { return a.panels[i].Location() } diff --git a/internal/tui/viewer/viewer.go b/internal/tui/viewer/viewer.go new file mode 100644 index 0000000..8bb5bd4 --- /dev/null +++ b/internal/tui/viewer/viewer.go @@ -0,0 +1,667 @@ +// Package viewer shows file content in the Info preview and the View +// screen. Rendering is limited to the visible window; caret and visual +// positions are stored as graphemes and rendered by terminal cell width. +package viewer + +import ( + "strings" + "unicode" + + "github.com/charmbracelet/x/ansi" + "github.com/rivo/uniseg" + + "vcom/internal/preview" + "vcom/internal/tui/style" +) + +// Kind of content. +type Kind uint8 + +const ( + None Kind = iota + Text // lines of text: caret and visual are possible + Image // drawn by imgview + Other // metadata only (binary, directory, error) +) + +// Focus of the viewer. +type Focus uint8 + +const ( + Scroll Focus = iota // keys scroll + Caret // a cursor in the text + Visual // a selection +) + +// Content is what a preview produced. +type Content struct { + Kind Kind + Title string + Lines []string // possibly syntax-highlighted + Plain []string // the same text without SGR; defaults to stripped Lines + Image *preview.ImageRef +} + +type position struct { + line, col int // col is a grapheme index, not a byte or cell offset +} + +// Model is the viewer state. +type Model struct { + Focus Focus + Kind Kind + Gen uint64 // bumps with every SetContent (overlay effects key on it) + Image *preview.ImageRef + + title string + lines []string + plain []string + offset int // first source line on screen + sub int // first wrapped segment of offset on screen + hOffset int + caret position + anchor position + rows int + width int + wrap bool +} + +// SetContent shows c. Non-text content drops the focus back to Scroll. +func (m *Model) SetContent(c Content) { + m.Gen++ + m.Kind = c.Kind + m.title = c.Title + lines := c.Lines + if len(lines) == 0 { + lines = c.Plain + } + m.lines = expandTabs(lines) + m.plain = expandTabs(c.Plain) + if len(m.plain) != len(m.lines) { + m.plain = make([]string, len(m.lines)) + for i, line := range m.lines { + m.plain[i] = ansi.Strip(line) + } + } + m.Image = c.Image + m.offset, m.sub, m.hOffset = 0, 0, 0 + m.caret, m.anchor = position{}, position{} + if m.Kind != Text { + m.Focus = Scroll + } +} + +func expandTabs(lines []string) []string { + out := make([]string, len(lines)) + for i, line := range lines { + out[i] = strings.ReplaceAll(line, "\t", " ") + } + return out +} + +// Clear drops the content. +func (m *Model) Clear() { m.SetContent(Content{}) } + +// Lines returns the highlighted text lines. +func (m *Model) Lines() []string { return m.lines } + +// Offset is the first source line on screen. +func (m *Model) Offset() int { return m.offset } + +// CaretLine is the caret source line. +func (m *Model) CaretLine() int { return m.caret.line } + +// CaretColumn is the caret grapheme column. +func (m *Model) CaretColumn() int { return m.caret.col } + +// SetRows tells the viewer how many terminal rows fit. +func (m *Model) SetRows(n int) { + m.rows = max(1, n) + if m.Focus != Scroll { + m.ensureCaretVisible() + } +} + +// SetWidth tells the viewer how many terminal cells fit. +func (m *Model) SetWidth(n int) { + m.width = max(1, n) + if m.Focus != Scroll { + m.ensureCaretVisible() + return + } + m.sub = min(m.sub, m.wrapCount(m.offset)-1) +} + +// ToggleWrap switches hard wrapping and reports the new state. +func (m *Model) ToggleWrap() bool { + m.wrap = !m.wrap + m.offset, m.sub, m.hOffset = m.caret.line, 0, 0 + if m.Focus == Scroll { + m.offset, m.sub = 0, 0 + } + m.ensureCaretVisible() + return m.wrap +} + +// Wrapping reports whether hard wrapping is enabled. +func (m *Model) Wrapping() bool { return m.wrap } + +// Scroll moves the view (Scroll focus) or the caret (Caret/Visual). +func (m *Model) Scroll(delta int) { + if m.Focus == Scroll { + if m.wrap { + m.scrollWrapped(delta) + } else { + m.offset = max(0, min(m.offset+delta, max(0, len(m.lines)-m.rows))) + } + return + } + if m.wrap { + m.moveCaretWrapped(delta) + } else { + m.caret.line = max(0, min(m.caret.line+delta, max(0, len(m.lines)-1))) + m.clampCaretColumn() + } + m.ensureCaretVisible() +} + +// MoveHorizontal scrolls in Scroll focus or moves the caret by graphemes. +func (m *Model) MoveHorizontal(delta int) { + if m.Focus == Scroll { + if !m.wrap { + m.hOffset = max(0, m.hOffset+delta) + } + return + } + m.caret.col = max(0, min(m.caret.col+delta, len(graphemes(m.linePlain(m.caret.line))))) + m.ensureCaretVisible() +} + +// MoveWord implements w (next start), b (previous start), and e (next end). +func (m *Model) MoveWord(word rune) { + if m.Focus == Scroll || len(m.lines) == 0 { + return + } + switch word { + case 'w': + m.caret = m.nextWordStart() + case 'b': + m.caret = m.previousWordStart() + case 'e': + m.caret = m.nextWordEnd() + } + m.ensureCaretVisible() +} + +// LineStart moves to column 0 or the first non-blank grapheme. +func (m *Model) LineStart(firstNonBlank bool) { + if m.Focus == Scroll { + return + } + m.caret.col = 0 + if firstNonBlank { + for i, g := range graphemes(m.linePlain(m.caret.line)) { + if graphemeClass(g) != 0 { + m.caret.col = i + break + } + } + } + m.ensureCaretVisible() +} + +// LineEnd moves to the last grapheme of the caret line. +func (m *Model) LineEnd() { + if m.Focus == Scroll { + return + } + m.caret.col = max(0, len(graphemes(m.linePlain(m.caret.line)))-1) + m.ensureCaretVisible() +} + +// Page scrolls by a screen. +func (m *Model) Page(dir int) { m.Scroll(dir * max(1, m.rows-1)) } + +// HalfPage scrolls by half a screen. +func (m *Model) HalfPage(dir int) { m.Scroll(dir * max(1, m.rows/2)) } + +// Jump goes to the top or the bottom. +func (m *Model) Jump(end bool) { + distance := len(m.lines) + m.rows + if m.wrap { + distance = m.rows + for line := range m.lines { + distance += m.wrapCount(line) + } + } + if end { + m.Scroll(distance) + } else { + m.Scroll(-distance) + } +} + +// EnterCaret puts the caret on the first visible line (text only). +func (m *Model) EnterCaret() bool { + if m.Kind != Text { + return false + } + m.Focus = Caret + m.placeCaretAtViewport() + m.ensureCaretVisible() + return true +} + +// EnterVisual starts a selection at the caret (from Scroll: at the first +// visible line). +func (m *Model) EnterVisual() bool { + if m.Kind != Text { + return false + } + if m.Focus == Scroll { + m.placeCaretAtViewport() + } + m.Focus = Visual + m.ensureCaretVisible() + m.anchor = m.caret + return true +} + +// Selection returns the selected text (Visual) or the whole caret line. +func (m *Model) Selection() []string { + if len(m.lines) == 0 { + return nil + } + if m.Focus != Visual { + return []string{m.linePlain(m.caret.line)} + } + a, b := m.orderedSelection() + if a.line == b.line { + gs := graphemes(m.linePlain(a.line)) + return []string{strings.Join(sliceGraphemes(gs, a.col, b.col+1), "")} + } + out := make([]string, 0, b.line-a.line+1) + out = append(out, strings.Join(sliceGraphemes(graphemes(m.linePlain(a.line)), a.col, -1), "")) + for i := a.line + 1; i < b.line; i++ { + out = append(out, m.linePlain(i)) + } + out = append(out, strings.Join(sliceGraphemes(graphemes(m.linePlain(b.line)), 0, b.col+1), "")) + return out +} + +// Render draws the visible window into w×h. +func (m *Model) Render(w, h int, st *style.Styles) string { + if w <= 0 || h <= 0 { + return "" + } + rows := make([]string, 0, h) + line, sub := m.offset, m.sub + for len(rows) < h { + if line >= len(m.lines) { + if len(rows) == 0 && m.Kind == None { + rows = append(rows, st.Muted.Render("(no preview)")) + } + break + } + text := m.lines[line] + if m.Focus != Scroll { + text = m.plain[line] + } + if m.wrap { + parts := strings.Split(ansi.Hardwrap(text, w, true), "\n") + segments := wrapSegments(m.linePlain(line), w) + for i := sub; i < len(parts) && len(rows) < h; i++ { + rows = append(rows, m.renderRow(line, parts[i], segments[i].startCell, w, st)) + } + } else { + rows = append(rows, m.renderRow(line, ansi.Cut(text, m.hOffset, m.hOffset+w), m.hOffset, w, st)) + } + line++ + sub = 0 + } + for len(rows) < h { + rows = append(rows, "") + } + for i, row := range rows { + rows[i] = ansi.Truncate(row, w, "") + if n := ansi.StringWidth(rows[i]); n < w { + rows[i] += strings.Repeat(" ", w-n) + } + } + return strings.Join(rows[:h], "\n") +} + +func (m *Model) renderRow(line int, text string, startCell, width int, st *style.Styles) string { + if m.Focus == Scroll || line >= len(m.plain) { + return text + } + from, to := -1, -1 + if m.Focus == Visual { + a, b := m.orderedSelection() + if line >= a.line && line <= b.line { + from = startCell + to = startCell + width + if line == a.line { + from = max(from, cellAt(m.linePlain(a.line), a.col)) + } + if line == b.line { + to = min(to, cellAt(m.linePlain(b.line), b.col+1)) + } + } + } else if line == m.caret.line { + from = cellAt(m.linePlain(line), m.caret.col) + to = cellAt(m.linePlain(line), m.caret.col+1) + if to == from { + to++ + } + } + if from < 0 || to <= startCell || from >= startCell+width { + return text + } + left, right := max(startCell, from), min(startCell+width, to) + plain := m.plain[line] + before := ansi.Cut(plain, startCell, left) + marked := ansi.Cut(plain, left, right) + if marked == "" { + marked = " " + } + after := ansi.Cut(plain, right, startCell+width) + return before + st.ListCursor.Render(marked) + after +} + +// Title of the content. +func (m *Model) Title() string { return m.title } + +func (m *Model) linePlain(i int) string { + if i < 0 || i >= len(m.plain) { + return "" + } + return m.plain[i] +} + +func (m *Model) orderedSelection() (position, position) { + a, b := m.anchor, m.caret + if b.line < a.line || b.line == a.line && b.col < a.col { + a, b = b, a + } + return a, b +} + +func (m *Model) clampCaretColumn() { + m.caret.col = max(0, min(m.caret.col, len(graphemes(m.linePlain(m.caret.line))))) +} + +type wrapSegment struct { + startCol int + endCol int + startCell int +} + +func wrapSegments(s string, width int) []wrapSegment { + parts := strings.Split(ansi.Hardwrap(s, max(1, width), true), "\n") + segments := make([]wrapSegment, 0, len(parts)) + col, cell := 0, 0 + for _, part := range parts { + segment := wrapSegment{startCol: col, startCell: cell} + col += len(graphemes(part)) + cell += ansi.StringWidth(part) + segment.endCol = col + segments = append(segments, segment) + } + return segments +} + +func caretSegment(segments []wrapSegment, col int) int { + for i, segment := range segments { + if col < segment.endCol { + return i + } + } + return len(segments) - 1 +} + +func (m *Model) wrapCount(line int) int { + if !m.wrap { + return 1 + } + return len(wrapSegments(m.linePlain(line), m.width)) +} + +func (m *Model) scrollWrapped(delta int) { + for delta > 0 && (m.offset < len(m.lines)-1 || m.sub < m.wrapCount(m.offset)-1) { + if m.sub+1 < m.wrapCount(m.offset) { + m.sub++ + } else { + m.offset++ + m.sub = 0 + } + delta-- + } + for delta < 0 && (m.offset > 0 || m.sub > 0) { + if m.sub > 0 { + m.sub-- + } else { + m.offset-- + m.sub = m.wrapCount(m.offset) - 1 + } + delta++ + } +} + +func (m *Model) moveCaretWrapped(delta int) { + if len(m.lines) == 0 { + return + } + segments := wrapSegments(m.linePlain(m.caret.line), m.width) + segment := caretSegment(segments, m.caret.col) + column := max(0, cellAt(m.linePlain(m.caret.line), m.caret.col)-segments[segment].startCell) + segment += delta + for segment < 0 && m.caret.line > 0 { + m.caret.line-- + segment += m.wrapCount(m.caret.line) + } + for segment >= m.wrapCount(m.caret.line) && m.caret.line < len(m.lines)-1 { + segment -= m.wrapCount(m.caret.line) + m.caret.line++ + } + segments = wrapSegments(m.linePlain(m.caret.line), m.width) + segment = max(0, min(segment, len(segments)-1)) + m.caret.col = columnAtCell(m.linePlain(m.caret.line), segments[segment].startCell+column) +} + +func (m *Model) placeCaretAtViewport() { + m.caret.line = min(m.offset, max(0, len(m.lines)-1)) + if !m.wrap { + m.caret.col = columnAtCell(m.linePlain(m.caret.line), m.hOffset) + return + } + segments := wrapSegments(m.linePlain(m.caret.line), m.width) + m.sub = max(0, min(m.sub, len(segments)-1)) + m.caret.col = segments[m.sub].startCol +} + +func (m *Model) ensureCaretVisible() { + if len(m.lines) == 0 { + return + } + m.caret.line = max(0, min(m.caret.line, len(m.lines)-1)) + m.clampCaretColumn() + m.offset = max(0, min(m.offset, len(m.lines)-1)) + if !m.wrap { + if m.caret.line < m.offset { + m.offset = m.caret.line + } + if m.caret.line >= m.offset+m.rows { + m.offset = m.caret.line - m.rows + 1 + } + cell := cellAt(m.linePlain(m.caret.line), m.caret.col) + if cell < m.hOffset { + m.hOffset = cell + } + if cell >= m.hOffset+m.width { + m.hOffset = cell - m.width + 1 + } + return + } + m.sub = max(0, min(m.sub, m.wrapCount(m.offset)-1)) + segments := wrapSegments(m.linePlain(m.caret.line), m.width) + segment := caretSegment(segments, m.caret.col) + if m.caret.line < m.offset || m.caret.line == m.offset && segment < m.sub { + m.offset, m.sub = m.caret.line, segment + return + } + line, sub, row := m.offset, m.sub, 0 + for line < m.caret.line || line == m.caret.line && sub <= segment { + if line == m.caret.line && sub == segment { + if row >= m.rows { + m.offset, m.sub = m.caret.line, max(0, segment-m.rows+1) + } + return + } + row++ + if sub+1 < m.wrapCount(line) { + sub++ + } else { + line++ + sub = 0 + } + } + m.offset, m.sub = m.caret.line, max(0, segment-m.rows+1) +} + +func (m *Model) nextWordStart() position { + p := m.caret + gs := graphemes(m.linePlain(p.line)) + if p.col < len(gs) && graphemeClass(gs[p.col]) != 0 { + class := graphemeClass(gs[p.col]) + for p.col < len(gs) && graphemeClass(gs[p.col]) == class { + p.col++ + } + } + for { + gs = graphemes(m.linePlain(p.line)) + for p.col < len(gs) && graphemeClass(gs[p.col]) == 0 { + p.col++ + } + if p.col < len(gs) || p.line == len(m.lines)-1 { + return p + } + p.line++ + p.col = 0 + } +} + +func (m *Model) previousWordStart() position { + p := m.caret + for { + gs := graphemes(m.linePlain(p.line)) + p.col = min(p.col, len(gs)) + if p.col == 0 { + if p.line == 0 { + return position{} + } + p.line-- + p.col = len(graphemes(m.linePlain(p.line))) + continue + } + p.col-- + if graphemeClass(gs[p.col]) == 0 { + continue + } + class := graphemeClass(gs[p.col]) + for p.col > 0 && graphemeClass(gs[p.col-1]) == class { + p.col-- + } + return p + } +} + +func (m *Model) nextWordEnd() position { + p := m.caret + gs := graphemes(m.linePlain(p.line)) + if p.col < len(gs) { + p.col++ + } + for { + gs = graphemes(m.linePlain(p.line)) + for p.col < len(gs) && graphemeClass(gs[p.col]) == 0 { + p.col++ + } + if p.col < len(gs) { + class := graphemeClass(gs[p.col]) + for p.col+1 < len(gs) && graphemeClass(gs[p.col+1]) == class { + p.col++ + } + return p + } + if p.line == len(m.lines)-1 { + return m.lastWordEnd() + } + p.line++ + p.col = 0 + } +} + +func (m *Model) lastWordEnd() position { + for line := len(m.lines) - 1; line >= 0; line-- { + gs := graphemes(m.linePlain(line)) + for col := len(gs) - 1; col >= 0; col-- { + if graphemeClass(gs[col]) != 0 { + return position{line: line, col: col} + } + } + } + return m.caret +} + +func graphemes(s string) []string { + g := uniseg.NewGraphemes(s) + var out []string + for g.Next() { + out = append(out, g.Str()) + } + return out +} + +func sliceGraphemes(gs []string, from, to int) []string { + from = max(0, min(from, len(gs))) + if to < 0 || to > len(gs) { + to = len(gs) + } + to = max(from, to) + return gs[from:to] +} + +func cellAt(s string, col int) int { + gs := graphemes(s) + col = max(0, min(col, len(gs))) + width := 0 + for _, g := range gs[:col] { + width += ansi.StringWidth(g) + } + return width +} + +func columnAtCell(s string, cell int) int { + gs := graphemes(s) + width := 0 + for i, g := range gs { + next := width + ansi.StringWidth(g) + if next > cell { + return i + } + width = next + } + return len(gs) +} + +func graphemeClass(g string) int { + r := []rune(g)[0] + if unicode.IsSpace(r) { + return 0 + } + if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { + return 1 + } + return 2 +} diff --git a/internal/tui/viewer/viewer_test.go b/internal/tui/viewer/viewer_test.go new file mode 100644 index 0000000..984f1f8 --- /dev/null +++ b/internal/tui/viewer/viewer_test.go @@ -0,0 +1,307 @@ +package viewer + +import ( + "fmt" + "strings" + "testing" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" + + "vcom/internal/theme" + "vcom/internal/tui/style" +) + +func testStyles(t *testing.T) *style.Styles { + t.Helper() + p, err := theme.Resolve("nord") + if err != nil { + t.Fatal(err) + } + return style.New(p) +} + +func TestUP03_CaretAsciiAndTrueColorNoPanic(t *testing.T) { + for _, profile := range []termenv.Profile{termenv.Ascii, termenv.TrueColor} { + t.Run(fmt.Sprint(profile), func(t *testing.T) { + previous := lipgloss.ColorProfile() + lipgloss.SetColorProfile(profile) + defer lipgloss.SetColorProfile(previous) + m := Model{} + m.SetRows(4) + m.SetWidth(12) + m.SetContent(Content{Kind: Text, Lines: []string{"one", "two", "three"}, Plain: []string{"one", "two", "three"}}) + if !m.EnterCaret() || !m.EnterVisual() { + t.Fatal("caret/visual unavailable for text") + } + m.MoveHorizontal(1) + m.Scroll(1) + if got := ansi.Strip(m.Render(12, 4, testStyles(t))); !strings.Contains(got, "two") { + t.Fatalf("render:\n%s", got) + } + }) + } +} + +func TestCaretCJKColumns(t *testing.T) { + m := Model{} + m.SetRows(3) + m.SetWidth(4) + m.SetContent(Content{Kind: Text, Plain: []string{"a界b"}, Lines: []string{"a界b"}}) + m.EnterCaret() + m.MoveHorizontal(1) + if got := m.CaretColumn(); got != 1 { + t.Fatalf("column = %d, want 1 grapheme", got) + } + m.EnterVisual() + m.MoveHorizontal(1) + if got := m.CaretColumn(); got != 2 { + t.Fatalf("column = %d, want 2 graphemes", got) + } + if got := cellAt(m.linePlain(0), m.CaretColumn()); got != 3 { + t.Fatalf("cell = %d, want 3 (CJK is two cells)", got) + } + if got := strings.Join(m.Selection(), ""); got != "界b" { + t.Fatalf("selection = %q", got) + } + if got := ansi.Strip(m.Render(4, 1, testStyles(t))); ansi.StringWidth(got) != 4 || !strings.Contains(got, "界") { + t.Fatalf("render = %q (width %d)", got, ansi.StringWidth(got)) + } +} + +func TestVisualSelectionAcrossLines(t *testing.T) { + m := Model{} + m.SetRows(5) + m.SetWidth(20) + m.SetContent(Content{Kind: Text, Plain: []string{"alpha", "beta", "gamma"}}) + m.EnterCaret() + m.LineEnd() + m.EnterVisual() + m.Scroll(2) + m.LineStart(false) + m.MoveHorizontal(1) + want := []string{"a", "beta", "ga"} + got := m.Selection() + if len(got) != len(want) { + t.Fatalf("selection = %#v", got) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("selection[%d] = %q, want %q", i, got[i], want[i]) + } + } +} + +func TestWrapScrollsByVisibleRows(t *testing.T) { + m := Model{} + m.SetRows(2) + m.SetWidth(4) + m.ToggleWrap() + m.SetContent(Content{Kind: Text, Plain: []string{"abcdefgh", "ijkl"}}) + m.Scroll(1) + if m.offset != 0 || m.sub != 1 { + t.Fatalf("offset = %d/%d, want wrapped segment 0/1", m.offset, m.sub) + } + if got := ansi.Strip(m.Render(4, 1, testStyles(t))); !strings.HasPrefix(got, "efgh") { + t.Fatalf("second wrapped segment = %q", got) + } + m.Scroll(1) + if m.offset != 1 || m.sub != 0 { + t.Fatalf("offset = %d/%d, want next source line", m.offset, m.sub) + } +} + +func newTextModel(lines []string, width, rows int, wrap bool) Model { + m := Model{} + m.SetRows(rows) + m.SetWidth(width) + if wrap { + m.ToggleWrap() + } + m.SetContent(Content{Kind: Text, Plain: lines}) + return m +} + +func TestWrapMatchesHardwrapAndEndCaret(t *testing.T) { + m := newTextModel([]string{"a界b"}, 2, 3, true) + if got := m.wrapCount(0); got != 3 { + t.Fatalf("wrapCount = %d, want 3 Hardwrap segments", got) + } + segments := wrapSegments(m.linePlain(0), 2) + wantCells := []int{0, 1, 3} + for i, want := range wantCells { + if segments[i].startCell != want { + t.Errorf("segment %d starts at cell %d, want %d", i, segments[i].startCell, want) + } + } + m.EnterCaret() + m.MoveHorizontal(3) + if got := caretSegment(segments, m.CaretColumn()); got != 2 { + t.Fatalf("end caret segment = %d, want last segment 2", got) + } + + m = newTextModel([]string{"abcd"}, 2, 1, true) + m.EnterCaret() + m.MoveHorizontal(4) + if m.offset != 0 || m.sub != 1 { + t.Fatalf("end caret viewport = %d/%d, want 0/1", m.offset, m.sub) + } + m.Scroll(1) + if m.CaretColumn() != 4 || m.offset != 0 || m.sub != 1 { + t.Fatalf("moving at end created a segment: caret %d, viewport %d/%d", m.CaretColumn(), m.offset, m.sub) + } +} + +func TestRenderNeverExceedsCellWidth(t *testing.T) { + for _, wrap := range []bool{false, true} { + for _, width := range []int{1, 2, 3} { + m := newTextModel([]string{"a界b"}, width, 4, wrap) + if wrap { + m.EnterCaret() + m.MoveHorizontal(2) + } else { + m.MoveHorizontal(1) + } + for row, rendered := range strings.Split(m.Render(width, 4, testStyles(t)), "\n") { + if got := ansi.StringWidth(rendered); got > width { + t.Errorf("wrap=%v width=%d row=%d has cell width %d: %q", wrap, width, row, got, rendered) + } + } + } + } +} + +func TestResizeKeepsCaretVisible(t *testing.T) { + m := newTextModel([]string{"abcdefgh"}, 4, 2, true) + m.EnterCaret() + m.MoveHorizontal(8) + m.SetRows(1) + if m.offset != 0 || m.sub != 1 { + t.Fatalf("after row resize viewport = %d/%d, want 0/1", m.offset, m.sub) + } + m.SetWidth(2) + if m.offset != 0 || m.sub != 3 { + t.Fatalf("after width resize viewport = %d/%d, want 0/3", m.offset, m.sub) + } + + m = newTextModel([]string{"abcdefgh", "ijkl"}, 4, 2, false) + m.EnterCaret() + m.Scroll(1) + m.LineEnd() + m.SetRows(1) + if m.offset != 1 { + t.Fatalf("after row resize offset = %d, want caret line 1", m.offset) + } + m.MoveHorizontal(4) + m.SetWidth(2) + if cell := cellAt(m.linePlain(m.caret.line), m.caret.col); cell < m.hOffset || cell >= m.hOffset+m.width { + t.Fatalf("after width resize caret cell %d outside [%d,%d)", cell, m.hOffset, m.hOffset+m.width) + } +} + +func TestEnterModesUseVisibleViewportPosition(t *testing.T) { + for _, visual := range []bool{false, true} { + m := newTextModel([]string{"abcdef"}, 2, 1, true) + m.Scroll(2) + if visual { + m.EnterVisual() + } else { + m.EnterCaret() + } + if m.CaretColumn() != 4 { + t.Errorf("wrapped visual=%v caret column = %d, want 4", visual, m.CaretColumn()) + } + if visual && m.anchor.col != 4 { + t.Errorf("visual anchor column = %d, want 4", m.anchor.col) + } + + m = newTextModel([]string{"abcdef"}, 2, 1, false) + m.MoveHorizontal(3) + if visual { + m.EnterVisual() + } else { + m.EnterCaret() + } + if m.CaretColumn() != 3 { + t.Errorf("horizontal visual=%v caret column = %d, want 3", visual, m.CaretColumn()) + } + } +} + +func TestJumpCrossesAllWrappedSegments(t *testing.T) { + m := newTextModel([]string{"abcdefghij"}, 2, 2, true) + m.EnterCaret() + m.Jump(true) + if m.CaretColumn() != 8 || m.sub != 3 { + t.Fatalf("jump to end: caret %d, sub %d; want 8, 3", m.CaretColumn(), m.sub) + } + m.Jump(false) + if m.CaretColumn() != 0 || m.offset != 0 || m.sub != 0 { + t.Fatalf("jump to start: caret %d, viewport %d/%d", m.CaretColumn(), m.offset, m.sub) + } + + m = newTextModel([]string{"abcdefghij"}, 2, 2, true) + m.Jump(true) + if m.offset != 0 || m.sub != 4 { + t.Fatalf("scroll jump to end = %d/%d, want 0/4", m.offset, m.sub) + } + m.Jump(false) + if m.offset != 0 || m.sub != 0 { + t.Fatalf("scroll jump to start = %d/%d, want 0/0", m.offset, m.sub) + } +} + +func TestWordMotionsCrossLinesAndSkipTrailingSpaces(t *testing.T) { + m := newTextModel([]string{"one ", " two", "", "three!"}, 20, 4, false) + m.EnterCaret() + m.MoveWord('e') + if m.caret != (position{line: 0, col: 2}) { + t.Fatalf("first e = %+v, want line 0 col 2", m.caret) + } + m.MoveWord('e') + if m.caret != (position{line: 1, col: 4}) { + t.Fatalf("cross-line e = %+v, want line 1 col 4", m.caret) + } + m.MoveWord('w') + if m.caret != (position{line: 3, col: 0}) { + t.Fatalf("cross-line w = %+v, want line 3 col 0", m.caret) + } + m.MoveWord('b') + if m.caret != (position{line: 1, col: 2}) { + t.Fatalf("cross-line b = %+v, want line 1 col 2", m.caret) + } + m.MoveWord('b') + if m.caret != (position{line: 0, col: 0}) { + t.Fatalf("second b = %+v, want line 0 col 0", m.caret) + } + + m = newTextModel([]string{"one", "two "}, 20, 2, false) + m.EnterCaret() + m.LineEnd() + m.MoveWord('e') + if m.caret != (position{line: 1, col: 2}) { + t.Fatalf("e before trailing spaces = %+v, want line 1 col 2", m.caret) + } + m.MoveWord('e') + if m.caret != (position{line: 1, col: 2}) { + t.Fatalf("e stuck in trailing spaces: %+v", m.caret) + } +} + +func BenchmarkCaretMove64K(b *testing.B) { + lines := make([]string, 64*1024) + for i := range lines { + lines[i] = fmt.Sprintf("line %d: some text to move through", i) + } + m := Model{} + m.SetRows(30) + m.SetWidth(100) + m.SetContent(Content{Kind: Text, Plain: lines}) + m.EnterCaret() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.LineEnd() + m.LineStart(false) + } +} diff --git a/internal/tui/viewer_actions_test.go b/internal/tui/viewer_actions_test.go new file mode 100644 index 0000000..59978fa --- /dev/null +++ b/internal/tui/viewer_actions_test.go @@ -0,0 +1,195 @@ +package tui + +import ( + "context" + "fmt" + "strings" + "sync" + "sync/atomic" + "testing" + + "vcom/internal/imgview" + "vcom/internal/preview" + "vcom/internal/testutil/fstree" + "vcom/internal/tui/keys" + "vcom/internal/tui/viewer" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" +) + +type recordingImages struct { + mu sync.Mutex + desired []imgview.Desired +} + +func (r *recordingImages) Apply(d imgview.Desired) { + r.mu.Lock() + defer r.mu.Unlock() + r.desired = append(r.desired, d) +} + +func (r *recordingImages) last() imgview.Desired { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.desired) == 0 { + return imgview.Desired{} + } + return r.desired[len(r.desired)-1] +} + +func (r *recordingImages) count() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.desired) +} + +func TestPreviewDebounceSingleFlight(t *testing.T) { + var spec fstree.Spec + for i := 0; i < 60; i++ { + spec = append(spec, fstree.File(fmt.Sprintf("f%02d", i), "text")) + } + var calls atomic.Int32 + h := newHarness(t, localfs.New(), tree(t, spec), func(d *Deps) { + d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) { + calls.Add(1) + return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{fi.Name}}, nil + } + }) + h.press("o") + before := calls.Load() + for i := 0; i < 50; i++ { + h.d.Press("j") + } + h.d.Settle(settle) + h.check() + if got := calls.Load() - before; got != 1 { + t.Fatalf("50 rapid cursor moves caused %d preview builds, want 1 (total %d)", got, calls.Load()) + } +} + +func TestOverlayHiddenUnderModal(t *testing.T) { + images := &recordingImages{} + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("image.png", "fake")}), func(d *Deps) { + d.Image = images + d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) { + return viewer.Content{Kind: viewer.Image, Title: fi.Name, Image: &preview.ImageRef{Local: "fake.png"}}, nil + } + }) + h.cursorTo("image.png") + h.press("o") + if got := images.last(); !got.Visible || got.Image.Local != "fake.png" { + t.Fatalf("overlay was not shown: %#v", got) + } + h.press("?") + if !h.d.ScreenContains("Help") { + t.Fatal("help modal did not open") + } + if got := images.last(); got.Visible { + t.Fatalf("overlay stayed visible under a modal: %#v", got) + } + h.press("esc") + if got := images.last(); !got.Visible { + t.Fatal("overlay was not restored after closing the modal") + } +} + +func TestViewIsPure(t *testing.T) { + images := &recordingImages{} + var previews atomic.Int32 + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "text")}), func(d *Deps) { + d.Image = images + d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) { + previews.Add(1) + return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"text"}}, nil + } + }) + h.cursorTo("a.txt") + h.press("o") + calls, applies := previews.Load(), images.count() + before := h.d.Screen() + for i := 0; i < 1000; i++ { + if got := h.app.View(); got != before { + t.Fatalf("View changed between identical calls at %d", i) + } + } + if previews.Load() != calls || images.count() != applies { + t.Fatalf("View triggered dependencies: previews %d→%d, overlays %d→%d", calls, previews.Load(), applies, images.count()) + } +} + +func TestVisualReachableFromViewAndInfo(t *testing.T) { + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one\ntwo")})) + h.cursorTo("a.txt") + h.press("o", "i", "v") + if h.app.InputOwner() != keys.CtxVisual { + t.Fatalf("Info did not enter Visual: %s", h.app.InputOwner()) + } + h.press("q", "f3", "v") + if h.app.InputOwner() != keys.CtxVisual || h.app.Screen() != ScreenView { + t.Fatalf("View did not enter Visual: screen %s, owner %s", h.app.Screen(), h.app.InputOwner()) + } +} + +func TestViewerYankUsesPlainText(t *testing.T) { + var copied string + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one")}), func(d *Deps) { + d.Clipboard = func(s string) error { copied = s; return nil } + d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) { + return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"\x1b[31mone\x1b[0m"}, Plain: []string{"one"}}, nil + } + }) + h.cursorTo("a.txt") + h.press("o", "i", "v", "l", "y") + if copied != "on" { + t.Fatalf("copied %q, want plain selected text %q", copied, "on") + } + if strings.Contains(copied, "\x1b") { + t.Fatal("ANSI escape copied to clipboard") + } +} + +func TestPreviewCancelledWhenViewCloses(t *testing.T) { + g := newGate(t) + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one")}), func(d *Deps) { + d.Preview = func(_ context.Context, _ vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) { + <-g.ch + return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"one"}}, nil + } + }) + h.cursorTo("a.txt") + h.press("f3") + if !h.app.req.Pending(ReqKey{Kind: ReqPreview}) { + t.Fatal("preview request was not started") + } + h.press("q") + if h.app.req.Pending(ReqKey{Kind: ReqPreview}) { + t.Fatal("closing View left its preview request running") + } + g.open() +} + +func TestMouseRestoredAfterExternalProcess(t *testing.T) { + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "one")})) + if h.app.applied.mouse != mouseOn { + t.Fatal("mouse was not enabled initially") + } + h.d.Send(execDoneMsg{}) + h.d.Settle(settle) + if h.app.applied.mouse != mouseOn { + t.Fatal("mouse was not restored after external process") + } +} + +func TestPreviewResultRejectedDuringNextDebounce(t *testing.T) { + h := newHarness(t, localfs.New(), tree(t, fstree.Spec{fstree.File("a.txt", "a"), fstree.File("b.txt", "b")})) + h.cursorTo("a.txt") + h.press("o") + before := h.app.Viewer().Title() + tk, _ := h.app.req.Begin(ReqKey{Kind: ReqPreview}) + h.cursorTo("b.txt") + _ = h.app.requestPreview(false) + h.app.onPreview(previewMsg{Ticket: tk, For: "a.txt", Content: viewer.Content{Kind: viewer.Text, Title: "stale"}}) + if got := h.app.Viewer().Title(); got != before { + t.Fatalf("stale preview %q replaced %q during debounce", got, before) + } +} diff --git a/internal/tui/yank_path.go b/internal/tui/yank_path.go new file mode 100644 index 0000000..9e1fac0 --- /dev/null +++ b/internal/tui/yank_path.go @@ -0,0 +1,42 @@ +package tui + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/tui/notify" + "vcom/internal/vfs" +) + +type yankedMsg struct { + n int + err error +} + +// yankPath is y: copy the full path(s) of the targets (or of the current +// directory) to the clipboard. Remote paths carry their host label. +func (a *App) yankPath() tea.Cmd { + p := a.Active() + es, _ := p.Targets() + var lines []string + for _, e := range es { + lines = append(lines, displayPath(vfs.Location{FS: p.FS(), Path: p.FS().Paths().Join(p.Path(), e.Name)})) + } + if len(lines) == 0 { + lines = []string{displayPath(p.Location())} + } + clip, text := a.deps.Clipboard, strings.Join(lines, "\n") + return func() tea.Msg { return yankedMsg{n: len(lines), err: clip(text)} } +} + +func (a *App) onYanked(m yankedMsg) tea.Cmd { + if m.err != nil { + return a.notify(notify.Error, "Clipboard: "+m.err.Error()) + } + if m.n == 1 { + return a.notify(notify.Info, "Path copied to the clipboard") + } + return a.notify(notify.Info, fmt.Sprintf("%d paths copied to the clipboard", m.n)) +} diff --git a/internal/ui/config_smoke_test.go b/internal/ui/config_smoke_test.go new file mode 100644 index 0000000..3d1d2bd --- /dev/null +++ b/internal/ui/config_smoke_test.go @@ -0,0 +1,93 @@ +package ui + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "vcom/internal/config" + "vcom/internal/testutil/teadriver" +) + +// Choosing a theme rewrites only the theme line of the user's config (2C.3): +// comments, unknown keys and order survive. +func TestSmokeThemeSelectKeepsConfigComments(t *testing.T) { + isolateEnv(t) + dir := t.TempDir() + cfgPath := filepath.Join(dir, "vcom.toml") + before := "# my settings\n[ui]\n# the look\ntheme = 'catppuccin-mocha' # favourite\nicon_mode = 'ascii'\n\n[behavior]\nauto_refresh = true # unknown, keep\n" + writeFile(t, cfgPath, before) + + cfg, info, err := config.Load(cfgPath) + if err != nil || !info.Found { + t.Fatalf("load: %v %+v", err, info) + } + cfg.Startup.LeftPath, cfg.Startup.RightPath = dir, dir + m, err := NewModel(cfg, info.Path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.cleanupArchiveMounts(); m.cleanupRemoteImageTemp() }) + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + + d.Press("t", "j", "enter") + d.Settle(settle) + + chosen := cur(t, d).cfg.UI.Theme + if chosen == "catppuccin-mocha" { + t.Fatal("theme did not change") + } + b, err := os.ReadFile(cfgPath) + if err != nil { + t.Fatal(err) + } + want := strings.Replace(before, "theme = 'catppuccin-mocha'", "theme = '"+chosen+"'", 1) + if string(b) != want { + t.Fatalf("config rewritten:\n%s\nwant:\n%s", b, want) + } +} + +// The session goes to $XDG_STATE_HOME/vcom/session.toml. +func TestSmokeSessionInStateDir(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, dir) + m := cur(t, d) + m.saveSession() + p := filepath.Join(os.Getenv("XDG_STATE_HOME"), "vcom", "session.toml") + if _, err := os.Stat(p); err != nil { + t.Fatalf("session not in state dir: %v", err) + } + if _, err := os.Stat(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "vcom", "session.toml")); !os.IsNotExist(err) { + t.Fatal("session written to the old config location") + } +} + +// main calls Shutdown on the final model after Program.Run (signal, panic): +// it saves the session once and is idempotent after the quit key. +func TestSmokeShutdownSavesSessionOnce(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, dir) + d.Press("q") + d.Settle(settle) + if !d.Quit() { + t.Fatal("q did not quit") + } + p := filepath.Join(os.Getenv("XDG_STATE_HOME"), "vcom", "session.toml") + if err := os.Remove(p); err != nil { + t.Fatalf("quit key did not save the session: %v", err) + } + m := cur(t, d) + m.Shutdown() // already shut down by q: must not save again + if _, err := os.Stat(p); !os.IsNotExist(err) { + t.Fatal("Shutdown ran twice") + } + fresh := newTestModel(t, dir, dir) // re-isolates the environment + fresh.Shutdown() + p = filepath.Join(os.Getenv("XDG_STATE_HOME"), "vcom", "session.toml") + if _, err := os.Stat(p); err != nil { + t.Fatalf("Shutdown on a live model must save the session: %v", err) + } +} diff --git a/internal/ui/helpers_test.go b/internal/ui/helpers_test.go new file mode 100644 index 0000000..066bc59 --- /dev/null +++ b/internal/ui/helpers_test.go @@ -0,0 +1,199 @@ +package ui + +import ( + "io" + "log" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "vcom/internal/config" + "vcom/internal/fs/remote" + "vcom/internal/testutil/sshtest" + "vcom/internal/testutil/teadriver" +) + +func TestMain(m *testing.M) { + log.SetOutput(io.Discard) + os.Exit(m.Run()) +} + +// isolateEnv points HOME/XDG dirs at a temp dir so session, trash and SSH +// state never touch the real user's files. +func isolateEnv(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("VCOM_CONFIG", "") + t.Setenv("SSH_AUTH_SOCK", "") + t.Setenv("VISUAL", "") + t.Setenv("EDITOR", "") + if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil { + t.Fatal(err) + } + return home +} + +// newTestModel builds the old UI model with both panes at the given paths. +func newTestModel(t *testing.T, left, right string, mutate ...func(*config.Config)) Model { + t.Helper() + isolateEnv(t) + cfg := config.Default() + cfg.UI.IconMode = "ascii" + cfg.Startup.LeftPath = left + cfg.Startup.RightPath = right + for _, f := range mutate { + f(&cfg) + } + m, err := NewModel(cfg, "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + m.cleanupArchiveMounts() + m.cleanupRemoteImageTemp() + }) + return m +} + +const settle = 5 * time.Second + +func newDriver(t *testing.T, left, right string, mutate ...func(*config.Config)) *teadriver.Driver { + t.Helper() + m := newTestModel(t, left, right, mutate...) + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + return d +} + +// asModel unwraps the driver's model (Update returns Model or *Model). +func asModel(t *testing.T, tm tea.Model) Model { + t.Helper() + switch v := tm.(type) { + case Model: + return v + case *Model: + return *v + } + t.Fatalf("unexpected model type %T", tm) + return Model{} +} + +func cur(t *testing.T, d *teadriver.Driver) Model { return asModel(t, d.Model()) } + +func writeFile(t *testing.T, p, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +// selectName moves the active pane's cursor to the entry called name using +// j/k presses (as a user would). +func selectName(t *testing.T, d *teadriver.Driver, name string) { + t.Helper() + m := cur(t, d) + p := m.activePane() + idx := -1 + for i, e := range p.Entries { + if e.Name == name { + idx = i + } + } + if idx < 0 { + t.Fatalf("entry %q not in active pane %s", name, p.Path) + } + for p.Cursor != idx { + if p.Cursor < idx { + d.Press("j") + } else { + d.Press("k") + } + m = cur(t, d) + p = m.activePane() + } + d.Settle(settle) +} + +func selectedEntryName(t *testing.T, d *teadriver.Driver) string { + t.Helper() + m := cur(t, d) + e, ok := m.activePane().Selected() + if !ok { + return "" + } + return e.Name +} + +// activeOf returns a copy of the active pane. +func activeOf(t *testing.T, d *teadriver.Driver) *BrowserPane { + t.Helper() + m := cur(t, d) + p := *m.activePane() + return &p +} + +// connectTestHost starts an in-process SSH server and connects the app's +// own client to it. The server serves the real filesystem, so remote paths +// and local paths name the same files. +func connectTestHost(t *testing.T) *remote.SSHClient { + t.Helper() + srv := sshtest.Start(t, sshtest.Options{}) + c, err := remote.Connect(remote.SSHHost{ + Name: "testhost", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password, + }) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { c.Close() }) + return c +} + +// mountRemote puts pane id of m into a remote mount at dir. +func mountRemote(t *testing.T, m *Model, id PaneID, c *remote.SSHClient, dir string) { + t.Helper() + p := m.paneByID(id) + p.PushRemote(RemoteMount{Host: c.Host, RemotePath: dir, Client: c, Connected: true}) + p.Path = dir + if err := m.reloadRemotePane(id, ""); err != nil { + t.Fatalf("reloadRemotePane: %v", err) + } +} + +// newRemoteDriver opens the left pane on dir over SSH and the right pane on +// right (local). +func newRemoteDriver(t *testing.T, dir, right string) *teadriver.Driver { + t.Helper() + m := newTestModel(t, right, right) + c := connectTestHost(t) + mountRemote(t, &m, PaneLeft, c, dir) + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + return d +} + +// recordProcesses replaces startProcess for the test and returns the list of +// commands that would have been started. +func recordProcesses(t *testing.T) *[]string { + t.Helper() + var started []string + prev := startProcess + startProcess = func(c *exec.Cmd) error { + started = append(started, strings.Join(c.Args, " ")) + return nil + } + t.Cleanup(func() { startProcess = prev }) + return &started +} diff --git a/internal/ui/hotfix_test.go b/internal/ui/hotfix_test.go new file mode 100644 index 0000000..df3590e --- /dev/null +++ b/internal/ui/hotfix_test.go @@ -0,0 +1,549 @@ +package ui + +// Regression tests for the stage-1 hotfixes (plans/rework/03-tasks.md). + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" + + "vcom/internal/config" + vfs "vcom/internal/fs" + "vcom/internal/testutil/teadriver" +) + +// U-P1-1: status/error messages were assigned but never rendered. +func TestStatusVisible(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "taken"), 0o755); err != nil { + t.Fatal(err) + } + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("taken") + d.Press("enter") + d.Settle(settle) + status := cur(t, d).status + if classifyStatus(status) != statusError { + t.Fatalf("mkdir over existing dir should report an error, status=%q", status) + } + screen := d.Screen() + if !strings.Contains(screen, status) { + t.Fatalf("error %q not on screen:\n%s", status, screen) + } + lines := strings.Split(screen, "\n") + if len(lines) != 40 { + t.Fatalf("view must keep terminal height 40, got %d lines", len(lines)) + } +} + +func TestStatusLineKeepsHeightWhileFiltering(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, t.TempDir()) + d.Press("/") + d.Type("x") + if n := len(strings.Split(d.Screen(), "\n")); n != 40 { + t.Fatalf("filter bar must replace the status line, view has %d lines", n) + } +} + +// N-P0-1: F2 in an SSH pane renamed the LOCAL file with the same path. +func TestNP01_RemoteRenameBlocked(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "foo"), "data") + d := newRemoteDriver(t, dir, t.TempDir()) + selectName(t, d, "foo") + d.Press("f2") + opened := cur(t, d).modal.kind == modalRename + if !opened && !d.ScreenContains("not supported in SSH panes") { + t.Fatalf("no explanation on screen:\n%s", d.Screen()) + } + if opened { + d.Press("ctrl+u") + d.Type("bar") + d.Press("enter") + d.Settle(settle) + } + if !exists(filepath.Join(dir, "foo")) || exists(filepath.Join(dir, "bar")) { + t.Fatal("rename in an SSH pane went through os.Rename on the local filesystem") + } + if opened { + t.Fatal("rename dialog must not open in an SSH pane") + } +} + +// N-P0-2: Enter on a remote file ran/edited/opened the LOCAL file with the +// same path. +func TestNP02_RemoteEnterDoesNotTouchLocal(t *testing.T) { + dir := t.TempDir() + marker := filepath.Join(dir, "ran") + script := filepath.Join(dir, "deploy") + writeFile(t, script, "#!/bin/sh\ntouch "+marker+"\n") + if err := os.Chmod(script, 0o755); err != nil { + t.Fatal(err) + } + writeFile(t, filepath.Join(dir, "app.conf"), "x=1\n") + writeFile(t, filepath.Join(dir, "photo.png"), "not really a png") + writeFile(t, filepath.Join(dir, "bundle.zip"), "not really a zip") + t.Setenv("VISUAL", "true") // an editor exists, so only the guard can stop it + started := recordProcesses(t) + + d := newRemoteDriver(t, dir, t.TempDir()) + for _, name := range []string{"deploy", "app.conf", "photo.png", "bundle.zip"} { + selectName(t, d, name) + d.Press("enter") + d.Settle(settle) + if p := activeOf(t, d).Path; p != dir { + t.Fatalf("Enter on %s changed pane path to %s", name, p) + } + } + if n := len(d.Execs()); n != 0 { + t.Fatalf("Enter on remote files requested %d local process(es) via ExecProcess", n) + } + if len(*started) != 0 { + t.Fatalf("Enter on remote files started local processes: %v", *started) + } + if exists(marker) { + t.Fatal("local executable was run") + } + if !d.ScreenContains("Opening remote files is not supported") { + t.Fatalf("no explanation on screen:\n%s", d.Screen()) + } +} + +// Control: in a local pane Enter on a non-text file still goes to the +// opener (the guard must not block local files). +func TestNP02_LocalEnterStillOpens(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "photo.png"), "x") + started := recordProcesses(t) + t.Setenv("PATH", fakeOpenerDir(t)) + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "photo.png") + d.Press("enter") + d.Settle(settle) + if len(*started) != 1 { + t.Fatalf("local Enter should launch the opener once, got %v (status %q)", *started, cur(t, d).status) + } +} + +func fakeOpenerDir(t *testing.T) string { + t.Helper() + bin := t.TempDir() + writeFile(t, filepath.Join(bin, "xdg-open"), "#!/bin/sh\nexit 0\n") + if err := os.Chmod(filepath.Join(bin, "xdg-open"), 0o755); err != nil { + t.Fatal(err) + } + return bin +} + +// U-P0-2 / N-P2-10 / N-P1-15: writes into a passive archive pane land in a +// temp dir that is deleted on exit; the host list is not a directory; and +// archive/unpack only understand local paths. +func TestUP02_NoWriteIntoArchivePane(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "inner.txt"), "in archive") + zipPath := filepath.Join(dir, "box.zip") + if err := vfs.CreateArchive(context.Background(), []string{filepath.Join(dir, "inner.txt")}, zipPath, nil); err != nil { + t.Fatal(err) + } + work := t.TempDir() + writeFile(t, filepath.Join(work, "precious.txt"), "user data") + writeFile(t, filepath.Join(work, "other.zip"), "") + if err := vfs.CreateArchive(context.Background(), []string{filepath.Join(work, "precious.txt")}, filepath.Join(work, "other.zip"), nil); err != nil { + t.Fatal(err) + } + + d := newDriver(t, dir, work) + selectName(t, d, "box.zip") + d.Press("enter") // left pane enters the archive + d.Settle(settle) + if !activeOf(t, d).InArchive() { + t.Fatal("left pane did not enter the archive") + } + d.Press("tab") // right (local) pane active, left (archive) passive + selectName(t, d, "precious.txt") + + for _, key := range []string{"f5", "f6", "f4"} { + d.Press(key) + d.Settle(settle) + if k := cur(t, d).modal.kind; k != modalNone { + t.Fatalf("%s opened dialog %d with an archive pane as target", key, k) + } + if !strings.Contains(cur(t, d).status, "archive") { + t.Fatalf("%s: status %q does not explain the archive target", key, cur(t, d).status) + } + } + selectName(t, d, "other.zip") + d.Press("f11") + d.Settle(settle) + if k := cur(t, d).modal.kind; k != modalNone { + t.Fatalf("unpack into an archive pane opened dialog %d", k) + } + if !exists(filepath.Join(work, "precious.txt")) { + t.Fatal("precious.txt left its directory") + } +} + +func TestNP210_NoTransferIntoHostList(t *testing.T) { + work := t.TempDir() + writeFile(t, filepath.Join(work, "a.txt"), "x") + m := newTestModel(t, work, work) + m.right.Path = sshHostListPath + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + selectName(t, d, "a.txt") + for _, key := range []string{"f5", "f6", "f4"} { + d.Press(key) + d.Settle(settle) + if k := cur(t, d).modal.kind; k != modalNone { + t.Fatalf("%s opened dialog %d with the host list as target", key, k) + } + } +} + +// N-P1-15: archive/unpack with an SSH pane on either side are blocked. +func TestNP115_ArchiveUnpackBlockedWithSSHPane(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + local := t.TempDir() + writeFile(t, filepath.Join(local, "l.zip"), "") + if err := vfs.CreateArchive(context.Background(), []string{filepath.Join(dir, "a.txt")}, filepath.Join(local, "l.zip"), nil); err != nil { + t.Fatal(err) + } + d := newRemoteDriver(t, dir, local) + selectName(t, d, "a.txt") + d.Press("f4") + d.Settle(settle) + if k := cur(t, d).modal.kind; k != modalNone || cur(t, d).busy { + t.Fatalf("archive in an SSH pane started (modal %d)", k) + } + d.Press("tab") + selectName(t, d, "l.zip") + for _, key := range []string{"f4", "f11"} { + d.Press(key) + d.Settle(settle) + if k := cur(t, d).modal.kind; k != modalNone { + t.Fatalf("%s with an SSH passive pane opened dialog %d", key, k) + } + } +} + +func trashFiles(t *testing.T) string { + t.Helper() + return filepath.Join(os.Getenv("HOME"), ".local", "share", "Trash", "files") +} + +// U-P0-4: Enter in the delete dialog deleted permanently by default. +func TestUP04_DeleteDefaultsToTrash(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "doc.txt"), "draft") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "doc.txt") + d.Press("f8") + d.Settle(settle) + if !d.ScreenContains("trash") { + t.Fatalf("dialog should say the file goes to the trash:\n%s", d.Screen()) + } + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(dir, "doc.txt")) { + t.Fatal("doc.txt not removed") + } + b, err := os.ReadFile(filepath.Join(trashFiles(t), "doc.txt")) + if err != nil || string(b) != "draft" { + t.Fatalf("doc.txt not in trash: %v", err) + } +} + +func TestUP04_PermanentIsExplicit(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "junk.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "junk.txt") + d.Press("f8", "D") + if !d.ScreenContains("Permanently delete") { + t.Fatalf("D should switch to permanent mode:\n%s", d.Screen()) + } + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(dir, "junk.txt")) || exists(filepath.Join(trashFiles(t), "junk.txt")) { + t.Fatal("permanent delete should neither keep nor trash the file") + } +} + +// U-P0-4: "n" did not close the dialog although the note promised it. +func TestUP04_NCancels(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "keep.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "keep.txt") + d.Press("f8") + if cur(t, d).modal.kind != modalConfirm { + t.Fatal("delete dialog did not open") + } + d.Press("n") + d.Settle(settle) + if k := cur(t, d).modal.kind; k != modalNone { + t.Fatalf("n did not close the dialog (modal %d)", k) + } + if !exists(filepath.Join(dir, "keep.txt")) { + t.Fatal("n deleted the file") + } +} + +func TestUP04_NoConfirmOnlyForTrash(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + d := newDriver(t, dir, t.TempDir(), func(c *config.Config) { c.Behavior.ConfirmDelete = false }) + selectName(t, d, "a.txt") + d.Press("f8") + d.Settle(settle) + if exists(filepath.Join(dir, "a.txt")) || !exists(filepath.Join(trashFiles(t), "a.txt")) { + t.Fatal("confirm_delete=false should move straight to the trash") + } +} + +// U-P0-3: caret mode panicked under the Ascii color profile (NO_COLOR). +func TestUP03_CaretAsciiNoPanic(t *testing.T) { + profiles := map[string]termenv.Profile{"Ascii": termenv.Ascii, "ANSI": termenv.ANSI, "ANSI256": termenv.ANSI256, "TrueColor": termenv.TrueColor} + for name, profile := range profiles { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "notes.txt"), "hello world\nsecond line\nthird\n") + m := newTestModel(t, dir, t.TempDir()) + d := teadriver.New(t, m, 160, 40, teadriver.WithProfile(profile), teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + selectName(t, d, "notes.txt") + d.Press("f9") // info pane with text preview + d.Settle(settle) + d.Press("i") // caret mode + d.Settle(settle) + if !cur(t, d).cursorMode { + t.Fatalf("caret mode not entered, status %q", cur(t, d).status) + } + d.Press("j", "l", "v", "l") + if s := d.Screen(); !strings.Contains(s, "second line") { + t.Fatalf("preview text not rendered:\n%s", s) + } + }) + } +} + +func TestBackgroundPreservingReset(t *testing.T) { + prev := lipgloss.ColorProfile() + defer lipgloss.SetColorProfile(prev) + lipgloss.SetColorProfile(termenv.Ascii) + if _, ok := backgroundPreservingReset("#112233"); ok { + t.Fatal("Ascii profile has no background to preserve") + } + lipgloss.SetColorProfile(termenv.TrueColor) + got, ok := backgroundPreservingReset("#112233") + if !ok || got != "\x1b[39;22;23;24;59;48;2;17;34;51m" { + t.Fatalf("got %q %v", got, ok) + } +} + +// U-P1-16: "q" quit the program even with the info pane, a filter or a +// selection open; it must close that layer first. +func TestUP116_QClosesInfo(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + writeFile(t, filepath.Join(dir, "b.txt"), "y") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "a.txt") + + d.Press("f9") + d.Settle(settle) + if !cur(t, d).infoMode { + t.Fatal("info pane did not open") + } + d.Press("q") + d.Settle(settle) + if d.Quit() { + t.Fatal("q with the info pane open quit the program") + } + if cur(t, d).infoMode { + t.Fatal("q did not close the info pane") + } + + d.Press("/") + d.Type("a") + d.Press("enter", "q") + d.Settle(settle) + if d.Quit() || cur(t, d).filterQuery != "" { + t.Fatalf("q should clear the filter (quit=%v filter=%q)", d.Quit(), cur(t, d).filterQuery) + } + + d.Press("J") // mark an entry + if len(activeOf(t, d).MarkedEntries()) == 0 { + t.Fatal("J did not mark") + } + d.Press("q") + d.Settle(settle) + if d.Quit() || len(activeOf(t, d).MarkedEntries()) != 0 { + t.Fatal("q should clear the selection first") + } + + d.Press("q") + d.Settle(settle) + if !d.Quit() { + t.Fatal("q from the bare browser should quit") + } +} + +// U-P1-5: Cyrillic in the filter and rename fields stays Cyrillic, while +// commands still work from the Russian layout. +func TestUP15_CyrillicTextAndCommands(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "отчёт.txt"), "x") + writeFile(t, filepath.Join(dir, "other.txt"), "y") + d := newDriver(t, dir, t.TempDir()) + d.Press("/") + d.Type("отч") + if q := cur(t, d).filterQuery; q != "отч" { + t.Fatalf("filter query %q", q) + } + d.Press("esc") + selectName(t, d, "other.txt") + d.Press("к") // "r" on the Russian layout: rename + if cur(t, d).modal.kind != modalRename { + t.Fatal("command key on the Russian layout no longer works") + } + d.Press("ctrl+u") + d.Type("новое.txt") + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "новое.txt")) { + t.Fatal("rename with a Cyrillic name failed") + } +} + +func fileSize(t *testing.T, p string) int64 { + t.Helper() + st, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + return st.Size() +} + +// U-P0-1: archiving data.tar as tar into the same directory truncated the +// source (archive name == source name). +func TestUP01_ArchiveDoesNotDestroySource(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "data.tar") + writeFile(t, src, strings.Repeat("x", 100000)) + d := newDriver(t, dir, dir) + selectName(t, d, "data.tar") + d.Press("f4") + d.Settle(settle) + if cur(t, d).modal.kind != modalArchiveType { + t.Fatalf("archive dialog did not open, status %q", cur(t, d).status) + } + d.Press("f") // zip -> tar + if cur(t, d).archiveFormat != "tar" { + t.Fatalf("format %q", cur(t, d).archiveFormat) + } + d.Press("enter") + d.Settle(settle) + if got := fileSize(t, src); got != 100000 { + t.Fatalf("source truncated to %d bytes", got) + } + if !d.ScreenContains("Cannot archive") { + t.Fatalf("refusal not shown:\n%s", d.Screen()) + } +} + +// U-P0-1: passive pane inside the archived directory made the archive +// include itself. +func TestUP01_ArchiveNotInsideSource(t *testing.T) { + dir := t.TempDir() + proj := filepath.Join(dir, "proj") + writeFile(t, filepath.Join(proj, "a.bin"), strings.Repeat("y", 1<<16)) + d := newDriver(t, dir, proj) + selectName(t, d, "proj") + d.Press("f4") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + entries, _ := os.ReadDir(proj) + if len(entries) != 1 { + t.Fatalf("archive was written inside its own source: %v", entries) + } + if !d.ScreenContains("Cannot archive") { + t.Fatalf("refusal not shown:\n%s", d.Screen()) + } +} + +// U-P0-1 (adjacent): an existing archive was overwritten without asking. +func TestUP01_ExistingArchiveNeedsConfirm(t *testing.T) { + dir, out := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "new content") + old := filepath.Join(out, "a.zip") + writeFile(t, old, "OLD ARCHIVE") + d := newDriver(t, dir, out) + selectName(t, d, "a.txt") + + d.Press("f4") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + if !d.ScreenContains("Overwrite existing archive") { + t.Fatalf("no overwrite confirmation:\n%s", d.Screen()) + } + d.Press("n") + d.Settle(settle) + if b, _ := os.ReadFile(old); string(b) != "OLD ARCHIVE" { + t.Fatal("cancelled overwrite changed the archive") + } + + d.Press("f4") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + d.Press("enter") // confirm overwrite + d.Settle(settle) + if b, _ := os.ReadFile(old); string(b) == "OLD ARCHIVE" || len(b) == 0 { + t.Fatalf("confirmed overwrite did not write the archive (status %q)", cur(t, d).status) + } + leftovers, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*")) + if len(leftovers) != 0 { + t.Fatalf("temp files left: %v", leftovers) + } +} + +// N-P1-12 / N-P0-8: after mirror (p) both panes share one client; leaving +// the host in one pane closed it under the other. +func TestNP112_MirrorThenLeaveKeepsOtherPaneConnected(t *testing.T) { + m := newTestModel(t, t.TempDir(), t.TempDir()) + c := connectTestHost(t) + mountRemote(t, &m, PaneLeft, c, "/") + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + + d.Press("p", "p") // mirror twice: the second used to Close the shared client + d.Settle(settle) + if !c.IsConnected() { + t.Fatal("repeated mirror closed the shared client") + } + d.Press("backspace") // left pane at remote root: leave the host + d.Settle(settle) + if !c.IsConnected() { + t.Fatal("leaving the host in one pane closed the client used by the mirrored pane") + } + mm := cur(t, d) + if err := mm.reloadRemotePane(PaneRight, ""); err != nil { + t.Fatalf("mirrored pane broken: %v", err) + } + d.Press("tab", "backspace") // the mirrored pane leaves too + d.Settle(settle) + if c.IsConnected() { + t.Fatal("client should be closed once no pane uses it") + } +} diff --git a/internal/ui/keymap.go b/internal/ui/keymap.go index 9d8cdbd..9bff6f9 100644 --- a/internal/ui/keymap.go +++ b/internal/ui/keymap.go @@ -62,7 +62,7 @@ func DefaultKeyMap() KeyMap { SelectUp: key.NewBinding(key.WithKeys("shift+up", "K"), key.WithHelp("S-↑/K", "select up")), SelectDown: key.NewBinding(key.WithKeys("shift+down", "J"), key.WithHelp("S-↓/J", "select down")), PageUp: key.NewBinding(key.WithKeys("pgup"), key.WithHelp("PgUp", "page up")), - PageDown: key.NewBinding(), + PageDown: key.NewBinding(key.WithKeys("pgdown"), key.WithHelp("PgDn", "page down")), Filter: key.NewBinding(key.WithKeys("/"), key.WithHelp("/", "filter")), Open: key.NewBinding(key.WithKeys("enter", "right"), key.WithHelp("Enter", "open")), Back: key.NewBinding(key.WithKeys("backspace", "left"), key.WithHelp("←", "parent")), diff --git a/internal/ui/model.go b/internal/ui/model.go index bdcbf1d..bc0e7ea 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -28,7 +28,7 @@ import ( "vcom/internal/theme" ) -const version = "v0.2.7" +const version = "v0.2.8" type modalKind int @@ -70,6 +70,7 @@ type pendingOperation struct { overwrite bool existingTargets int stats vfs.TransferStats + format string // archive format for opArchive // Remote operation fields — non-nil when source/target is remote srcClient *remote.SSHClient @@ -132,6 +133,10 @@ type archiveDoneMsg struct { sourcePaths []string targetPath string err error + // trashFailed lists the items a trash job could not move to the trash + // (the failing one and the rest); the user is offered to delete them + // permanently (QA-1). + trashFailed []string } type copyDoneMsg struct { @@ -188,6 +193,7 @@ type hoverState struct { type Model struct { cfg config.Config configPath string + shutDown bool // Shutdown already ran palette theme.Palette keys KeyMap nerdIcons bool @@ -237,16 +243,22 @@ type Model struct { archiveProgress chan tea.Msg archiveFormat string deleteKind string // "trash" or "permanent" — selected in delete modal - ssh *sshState - preSSHPath string // original path before entering SSH mode - themeSelector *themeSelectorState // nil when not in theme selector dialog - remoteImageTemp string // temp file of downloaded remote image, cleaned on change/quit + ssh *sshState + preSSHPath string // original path before entering SSH mode + themeSelector *themeSelectorState // nil when not in theme selector dialog + remoteImageTemp string // temp file of downloaded remote image, cleaned on change/quit } func NewModel(cfg config.Config, configPath string) (Model, error) { palette, err := theme.Resolve(cfg.UI.Theme) + themeErr := "" if err != nil { - return Model{}, err + // An unknown theme name in the config is not fatal. + themeErr = err.Error() + cfg.UI.Theme = config.Default().UI.Theme + if palette, err = theme.Resolve(cfg.UI.Theme); err != nil { + return Model{}, err + } } home := homedir.Dir() @@ -297,6 +309,10 @@ func NewModel(cfg config.Config, configPath string) (Model, error) { model.ssh = sshSt } + if themeErr != "" { + model.status = themeErr + } + // Apply saved session (overrides startup paths if a previous session exists) applySession(&model) @@ -311,6 +327,29 @@ func NewModel(cfg config.Config, configPath string) (Model, error) { return model, nil } +// Shutdown saves the session and releases temp files, archive mounts and the +// image overlay. It runs once: the quit key calls it, and main calls it again +// on the final model after Program.Run (signal, panic, external quit). +func (m *Model) Shutdown() { + if m.shutDown { + return + } + m.shutDown = true + m.saveSession() + m.cleanupArchiveMounts() + m.cleanupImageOverlay() + m.cleanupRemoteImageTemp() +} + +// WithStatus returns m with s in the status line (startup notices such as a +// broken config). An empty s changes nothing. +func (m Model) WithStatus(s string) Model { + if s != "" { + m.status = s + } + return m +} + func (m Model) Init() tea.Cmd { return m.loadPreviewCmd() } @@ -627,6 +666,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.modal.kind == modalArchiveProgress { m.modal = modalState{} } + if len(msg.trashFailed) > 0 && msg.err != context.Canceled { + m.offerPermanentDelete(msg.trashFailed, msg.err) + } return m, m.loadPreviewCmd() } @@ -837,7 +879,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case tea.KeyMsg: - msg = translateKeyMsg(msg) + // Russian-layout letters are mapped to their Latin keys only when + // the key is a command; text fields get the original runes (U-P1-5). + if !m.textInputActive() { + msg = translateKeyMsg(msg) + } if msg.String() != "y" { m.pendingY = false } @@ -992,6 +1038,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Filter mode: route keys to the filter input if m.filterMode { + // Printable keys are text for the query, even if they are + // also navigation keys in the browser (j/k): QA-3. + printable := msg.Type == tea.KeyRunes || msg.Type == tea.KeySpace switch { case msg.String() == "esc": log.Printf("[KEY] Filter: Esc — clear filter") @@ -1007,16 +1056,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.filterInput.Blur() m.status = fmt.Sprintf("Filter: %s", m.filterQuery) return m, nil - case key.Matches(msg, m.keys.Up): + case !printable && key.Matches(msg, m.keys.Up): m.moveFilteredCursor(-1) return m, m.loadPreviewCmd() - case key.Matches(msg, m.keys.Down): + case !printable && key.Matches(msg, m.keys.Down): m.moveFilteredCursor(1) return m, m.loadPreviewCmd() - case key.Matches(msg, m.keys.PageUp): + case !printable && key.Matches(msg, m.keys.PageUp): m.moveFilteredCursor(-max(m.bodyHeight()-6, 5)) return m, m.loadPreviewCmd() - case key.Matches(msg, m.keys.PageDown): + case !printable && key.Matches(msg, m.keys.PageDown): m.moveFilteredCursor(max(m.bodyHeight()-6, 5)) return m, m.loadPreviewCmd() default: @@ -1047,13 +1096,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } _ = remotePrefix // used in logs below + // "q" first closes whatever layer is open (filter, info pane, + // selection), like Esc; it quits only from the bare browser (U-P1-16). + if msg.String() == "q" && m.hasClosableLayer() { + msg = tea.KeyMsg{Type: tea.KeyEsc} + } + switch { case key.Matches(msg, m.keys.Quit): log.Printf("[KEY] Quit — exiting application") - m.saveSession() - m.cleanupArchiveMounts() - m.cleanupImageOverlay() - m.cleanupRemoteImageTemp() + m.Shutdown() return m, tea.Quit case key.Matches(msg, m.keys.Help): log.Printf("[KEY] Help — open help modal") @@ -1264,8 +1316,14 @@ func (m Model) View() string { parts := make([]string, 0, 3) parts = append(parts, panels) - if m.filterMode { - parts = append(parts, renderFilterBar(m)) + if !m.viewMode { + // One line between panels and footer: the filter input while + // filtering, otherwise the last status/error message. + if m.filterMode { + parts = append(parts, renderFilterBar(m)) + } else { + parts = append(parts, renderStatusLine(m)) + } } if m.cfg.UI.ShowFooter && !m.viewMode { parts = append(parts, renderFooter(m)) @@ -1333,7 +1391,7 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case modalConfirm: switch { - case isModalCloseKey(msg, m.keys): + case isModalCloseKey(msg, m.keys), isModalNoKey(msg): log.Printf("[MODAL] Confirm — cancelled (Esc)") m.modal = modalState{} m.status = "Cancelled" @@ -1412,6 +1470,16 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, m.startDeleteJob(pending.kind, pending.sourcePaths) } + // Archive over an existing file, confirmed + if pending.kind == opArchive { + if m.archiveJob != nil { + m.status = "Archive is already running" + return m, nil + } + m.busy = true + return m, m.startArchiveJob(pending.sourcePaths, pending.targetDir, pending.format, pending.stats) + } + // Extract archive if pending.kind == opExtractArchive { if m.archiveJob != nil { @@ -1452,7 +1520,7 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case modalArchiveType: switch { - case isModalCloseKey(msg, m.keys): + case isModalCloseKey(msg, m.keys), isModalNoKey(msg): log.Printf("[MODAL] Archive — cancelled (Esc)") m.modal = modalState{} m.status = "Cancelled" @@ -1469,6 +1537,23 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.status = "Archive is already running" return m, nil } + archivePath := filepath.Join(pending.targetDir, vfs.ArchiveName(pending.sourcePaths, m.archiveFormat)) + if err := vfs.CheckArchiveTarget(pending.sourcePaths, archivePath); err != nil { + m.busy = false + m.status = fmt.Sprintf("Cannot archive: %v", err) + return m, nil + } + if _, err := os.Lstat(archivePath); err == nil { + pending.format = m.archiveFormat + pending.overwrite = true + m.openConfirmModal( + "Overwrite existing archive?", + fmt.Sprintf("Archive: %s\nexists and will be replaced.", archivePath), + "Enter / y to overwrite, Esc / n to cancel", + pending, + ) + return m, nil + } m.busy = true log.Printf("[MODAL] Archive confirmed — sources=%d targetDir=%s format=%s", len(pending.sourcePaths), pending.targetDir, m.archiveFormat) return m, m.startArchiveJob(pending.sourcePaths, pending.targetDir, m.archiveFormat, pending.stats) @@ -1491,7 +1576,7 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case modalSSHConnect: switch { - case isModalCloseKey(msg, m.keys): + case key.Matches(msg, m.keys.Cancel): // not "q": it is typed into the form log.Printf("[MODAL] SSH connect — cancelled (Esc)") m.modal = modalState{} if m.ssh != nil && m.ssh.testingConn { @@ -1515,10 +1600,9 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case msg.String() == "shift+tab": m.ssh.cycleInput(-1) return m, nil - case key.Matches(msg, m.keys.Help): - m.ssh.showHelp = !m.ssh.showHelp - return m, nil - case msg.String() == "?": + case msg.String() == "f1", m.ssh.showHelp && key.Matches(msg, m.keys.Help): + // '?' is text in the fields (passwords, user names): only F1 + // opens the help; '?' still closes it while it is shown (QA-4). m.ssh.showHelp = !m.ssh.showHelp return m, nil default: @@ -1558,10 +1642,9 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil } selected := m.themeSelector.names[m.themeSelector.cursor] - m.finalizeTheme(selected) + m.finalizeTheme(selected) // sets the status, including a save failure (QA-19) m.themeSelector = nil m.modal = modalState{} - m.status = fmt.Sprintf("Theme: %s", selected) log.Printf("[THEME] Applied: %s", selected) return m, nil case isModalCloseKey(msg, m.keys): @@ -1646,6 +1729,35 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil } +// isModalNoKey is the "n" answer of yes/no dialogs (their notes promise +// "Esc / n to cancel"). Not used by dialogs with text input. +// textInputActive reports whether keys currently go to a text field. +func (m *Model) textInputActive() bool { + switch m.modal.kind { + case modalMkdir, modalRename, modalSSHConnect: + return true + case modalNone: + return m.filterMode && !m.viewMode + } + return false +} + +// hasClosableLayer reports whether Esc/q would close something in browse +// mode instead of doing nothing (Esc) or quitting (q). +func (m *Model) hasClosableLayer() bool { + if m.filterQuery != "" && m.filterPaneID == m.active { + return true + } + if m.infoMode { + return true + } + return len(m.activePane().MarkedEntries()) > 0 +} + +func isModalNoKey(msg tea.KeyMsg) bool { + return msg.String() == "n" || msg.String() == "N" +} + func isModalCloseKey(msg tea.KeyMsg, keys KeyMap) bool { return key.Matches(msg, keys.Cancel) || msg.String() == "q" } @@ -1693,8 +1805,6 @@ func (m *Model) refreshAllPanes(status string) (tea.Model, tea.Cmd) { return m, m.loadPreviewCmd() } - - func (m *Model) moveCursor(delta int) { // When a filter query is active on this pane, move through filtered entries // only, so the cursor always lands on a matching item. @@ -1933,6 +2043,13 @@ func (m *Model) handleOpenSelected() (tea.Model, tea.Cmd) { return m, nil } + if !selected.IsDir { + if err := localFileActionAllowed(m.activePane()); err != nil { + m.status = err.Error() + return m, nil + } + } + if selected.IsDir { if m.activePane().InRemote() { return m.enterRemoteDir(selected) @@ -1986,9 +2103,13 @@ func (m *Model) goParent() error { // At remote root — pop remote, disconnect, and return to host list log.Printf("[NAV] goParent — closing remote mount, returning to host list") pane.PopRemote() - mount.Client.Close() + // Release, not Close: the other pane (mirror) or a background + // job may still use this client (N-P0-8, N-P1-12). + mount.Client.Release() if m.ssh != nil { - m.ssh.connectedHosts[mount.Host.Name] = false + if mount.Client.Users() == 0 { + m.ssh.connectedHosts[mount.Host.Name] = false + } entries := buildSSHHostEntries(m.ssh.store, m.ssh.connectedHosts) pane.SetEntries(entries, "") pane.Path = "ssh://" @@ -2286,6 +2407,15 @@ func (m *Model) handleTransfer(kind fileOpKind) (tea.Model, tea.Cmd) { return m, nil } + if m.activePane().Path == sshHostListPath { + m.status = fmt.Sprintf("Cannot %s SSH host entries", operationVerb(kind)) + return m, nil + } + if err := canWriteTo(m.passivePane()); err != nil { + m.status = fmt.Sprintf("Cannot %s: %v", operationVerb(kind), err) + return m, nil + } + sources := m.operationSources() if len(sources) == 0 { log.Printf("[SKIP] Transfer: no sources, kind=%d", kind) @@ -2375,6 +2505,18 @@ func (m *Model) handleTransfer(kind fileOpKind) (tea.Model, tea.Cmd) { } func (m *Model) handleArchive() (tea.Model, tea.Cmd) { + if paneOnRemote(m.activePane()) { + m.status = "Archiving is not supported in SSH panes yet" + return m, nil + } + if err := canWriteTo(m.passivePane()); err != nil { + m.status = fmt.Sprintf("Cannot archive: %v", err) + return m, nil + } + if m.passivePane().InRemote() { + m.status = "Cannot archive into an SSH pane yet" + return m, nil + } sources := m.operationSources() if len(sources) == 0 { log.Printf("[SKIP] Archive: no sources") @@ -2430,11 +2572,22 @@ func (m *Model) handleDelete() (tea.Model, tea.Cmd) { return m, nil } - // Default to permanent delete - m.deleteKind = "permanent" + // Default to the trash; permanent deletion is an explicit choice (D/d + // in the dialog). U-P0-4. + m.deleteKind = "trash" + + // behavior.confirm_delete=false skips the question, but only for the + // recoverable trash path. + if !m.cfg.Behavior.ConfirmDelete { + if m.archiveJob != nil { + m.status = "Delete is already running" + return m, nil + } + return m, m.startDeleteJob(opDelete, sources) + } // Show confirm dialog with mode toggle (no plan — skip counting files) - title := "Permanently delete selected entr" + pluralSuffix(len(sources), "y", "ies") + "?" + title := "Move selected entr" + pluralSuffix(len(sources), "y", "ies") + " to trash?" body := fmt.Sprintf("Items: %d", len(sources)) note := fmt.Sprintf("Mode: %s (D/d to change)\nEnter / y to confirm, Esc / n to cancel", m.deleteKind) m.openConfirmModal(title, body, note, pendingOperation{ @@ -2445,6 +2598,18 @@ func (m *Model) handleDelete() (tea.Model, tea.Cmd) { } func (m *Model) handleUnpack() (tea.Model, tea.Cmd) { + if paneOnRemote(m.activePane()) { + m.status = "Unpacking is not supported in SSH panes yet" + return m, nil + } + if err := canWriteTo(m.passivePane()); err != nil { + m.status = fmt.Sprintf("Cannot unpack: %v", err) + return m, nil + } + if m.passivePane().InRemote() { + m.status = "Cannot unpack into an SSH pane yet" + return m, nil + } selected, ok := m.activePane().Selected() if !ok || !isArchiveEntry(selected) { log.Printf("[SKIP] Unpack: no archive selected") @@ -2481,14 +2646,13 @@ func (m *Model) handleMirrorPane() (tea.Model, tea.Cmd) { // If active is in a remote mount, clone the remote stack to passive if mount, ok := active.CurrentRemote(); ok { - // If passive already has a remote connection, clean it up first - if existingMount, exists := passive.CurrentRemote(); exists { - existingMount.Client.Close() - passive.PopRemote() + // The passive pane shares the client: take a reference first, then + // drop the passive pane's old mounts (which may be the same client). + mount.Client.Acquire() + releaseMounts(passive.ClearRemotes()) + for _, am := range passive.ClearArchives() { + _ = os.RemoveAll(am.TempDir) } - // Clone the mount — don't clone the client, open a new connection - // For simplicity, just set the path; the mount will reconnect on reload - passive.ClearRemotes() passive.Remote = append(passive.Remote, mount) passive.Path = active.Path if err := m.reloadRemotePane(passive.ID, ""); err != nil { @@ -2496,15 +2660,19 @@ func (m *Model) handleMirrorPane() (tea.Model, tea.Cmd) { return m, nil } } else if active.InArchive() { - // Archive mounts: set path directly, archive data stays on active pane - passive.Path = targetPath - if err := m.reloadPane(passive.ID, ""); err != nil { - m.status = fmt.Sprintf("Mirror failed: %v", err) - return m, nil - } + // The archive mount (and its temp extraction dir) belongs to the + // active pane; the passive pane would get the temp dir as a plain + // writable directory whose changes vanish when the archive is + // closed (QA-2). Refused until archive mounts can be shared. + m.status = "Mirror is not supported inside an archive" + return m, nil } else { - // Local directory — simple path copy - passive.ClearRemotes() + // Local directory — simple path copy. The passive pane leaves any + // archive it was in (QA-18): its mount and temp dir go away. + releaseMounts(passive.ClearRemotes()) + for _, mount := range passive.ClearArchives() { + _ = os.RemoveAll(mount.TempDir) + } passive.Path = targetPath if err := m.reloadPane(passive.ID, ""); err != nil { m.status = fmt.Sprintf("Mirror failed: %v", err) @@ -2559,6 +2727,10 @@ func (m *Model) exitViewMode() (tea.Model, tea.Cmd) { } func (m *Model) handleOpenExternal() (tea.Model, tea.Cmd) { + if err := localFileActionAllowed(m.activePane()); err != nil { + m.status = err.Error() + return m, nil + } selected, ok := m.activePane().Selected() if !ok || selected.IsParent || selected.IsDir { m.status = "Select a file to open" @@ -2578,6 +2750,10 @@ func (m *Model) handleOpenExternal() (tea.Model, tea.Cmd) { } func (m *Model) handleEdit() (tea.Model, tea.Cmd) { + if err := localFileActionAllowed(m.activePane()); err != nil { + m.status = err.Error() + return m, nil + } selected, ok := m.activePane().Selected() if !ok || selected.IsParent || selected.IsDir { m.status = "Select a file to edit" @@ -2599,6 +2775,10 @@ func (m *Model) handleEdit() (tea.Model, tea.Cmd) { } func (m *Model) handleExecute(entry vfs.Entry) (tea.Model, tea.Cmd) { + if err := localFileActionAllowed(m.activePane()); err != nil { + m.status = err.Error() + return m, nil + } log.Printf("[ACTION] Execute: path=%s", entry.Path) m.cleanupImageOverlay() cmd := exec.Command(entry.Path) @@ -2892,7 +3072,7 @@ func (m *Model) cycleTheme() (tea.Model, tea.Cmd) { log.Printf("[TOGGLE] CycleTheme: %s -> %s", m.cfg.UI.Theme, next) m.cfg.UI.Theme = next m.palette = palette - savedPath, saveErr := config.Save(m.cfg, m.configPath) + savedPath, saveErr := config.SetKey(m.configPath, "ui", "theme", m.cfg.UI.Theme) if saveErr != nil { m.status = fmt.Sprintf("Theme: %s (save failed: %v)", next, saveErr) return m, nil @@ -2940,12 +3120,13 @@ func (m *Model) finalizeTheme(name string) { } m.cfg.UI.Theme = name m.palette = palette - savedPath, saveErr := config.Save(m.cfg, m.configPath) + savedPath, saveErr := config.SetKey(m.configPath, "ui", "theme", m.cfg.UI.Theme) if saveErr != nil { m.status = fmt.Sprintf("Theme: %s (save failed: %v)", name, saveErr) return } m.configPath = savedPath + m.status = fmt.Sprintf("Theme: %s", name) } func copyTextToClipboard(text string) error { @@ -3032,6 +3213,10 @@ func (m *Model) openMkdirModal() { m.status = "Archive mode is read-only; create directory is disabled" return } + if m.activePane().Path == sshHostListPath { + m.status = "Cannot create a directory in the SSH host list" + return + } input := textinput.New() input.Placeholder = "new-directory" @@ -3053,6 +3238,10 @@ func (m *Model) openRenameModal() { m.status = "Archive mode is read-only; rename is disabled" return } + if paneOnRemote(m.activePane()) { + m.status = "Rename is not supported in SSH panes yet" + return + } selected, ok := m.activePane().Selected() if !ok || selected.IsParent { @@ -3075,6 +3264,25 @@ func (m *Model) openRenameModal() { } } +// offerPermanentDelete asks, after the trash refused some items (another +// filesystem without a usable trash, broken trash), whether to delete them +// permanently instead. Nothing is deleted without this explicit +// confirmation (QA-1). +func (m *Model) offerPermanentDelete(paths []string, cause error) { + m.deleteKind = "permanent" + n := len(paths) + m.openConfirmModal( + "Cannot move to trash. Delete permanently?", + fmt.Sprintf("%s\nNot in trash: %d entr%s (first: %s)\nPermanently deleted files cannot be restored.", + strings.Join(strings.Fields(cause.Error()), " "), n, pluralSuffix(n, "y", "ies"), filepath.Base(paths[0])), + "Enter / y to delete permanently, Esc / n to keep the files", + pendingOperation{ + kind: opPermanentDelete, + sourcePaths: append([]string(nil), paths...), + }, + ) +} + func (m *Model) openConfirmModal(title, body, note string, pending pendingOperation) { m.modal = modalState{ kind: modalConfirm, @@ -3092,7 +3300,7 @@ func (m *Model) openHelpModal() { " k / Up move up", " Shift+Down/J extend selection down", " Shift+Up/K extend selection up", - " PgUp / b page up", + " PgUp / PgDn page up / down", " Enter / Right open selected entry", " Backspace/Left go to parent directory", " Tab / h / l switch active pane", @@ -3317,14 +3525,30 @@ func (m *Model) renderTextCursorContent() string { // foreground and text attributes, then restore the panel background // so that gutter markers, cursor highlights, and selection highlights // don't break the panel background for subsequent text on the line. - panelBG := lipgloss.NewStyle().Background(m.palette.Panel).Render("") - bgCode := strings.TrimSuffix(panelBG, "\x1b[0m") - inner := bgCode[2 : len(bgCode)-1] - safeReset := "\x1b[39;22;23;24;59;" + inner + "m" - result = strings.ReplaceAll(result, "\x1b[0m", safeReset) + // The background sequence comes from the active color profile instead + // of slicing lipgloss output, which is empty under the Ascii profile + // (NO_COLOR, dumb terminals) and used to panic (U-P0-3). + if safeReset, ok := backgroundPreservingReset(m.palette.Panel); ok { + result = strings.ReplaceAll(result, "\x1b[0m", safeReset) + } return result } +// backgroundPreservingReset returns an SGR sequence that resets foreground +// and text attributes but sets the background to bg. ok is false when the +// current profile has no colors (then a plain reset loses nothing). +func backgroundPreservingReset(bg lipgloss.Color) (string, bool) { + c := lipgloss.ColorProfile().Color(string(bg)) + if c == nil { + return "", false + } + seq := c.Sequence(true) + if seq == "" { + return "", false + } + return "\x1b[39;22;23;24;59;" + seq + "m", true +} + func (m *Model) moveTextCursorWordForward() { if !m.cursorMode { return @@ -3471,6 +3695,9 @@ func (m *Model) bodyHeight() int { if m.cfg.UI.ShowFooter && !m.viewMode { height-- } + if !m.viewMode { + height-- // status line / filter bar + } return max(height, 8) } @@ -3774,6 +4001,64 @@ func renderFooter(m Model) string { return line } +// statusLevel classifies a status message by its wording so errors stand +// out. Statuses are free-form strings set in ~200 places; this keeps the +// hotfix local instead of threading a level through all of them. +type statusLevel int + +const ( + statusInfo statusLevel = iota + statusWarn + statusError +) + +var ( + statusErrorWords = []string{ + "fail", "error", "denied", "cannot", "can't", "no such", "not found", + "refus", "invalid", "must not", "unable", "not connected", "already exists", + "file exists", "not empty", "not permitted", "panic", "interrupted", + } + statusWarnWords = []string{ + "read-only", "disabled", "nothing to", "cancel", "select ", "not supported", + "not available", "already running", "no directory history", "no forward history", + "no entry selected", "press y again", "blocked", "not allowed", + } +) + +func classifyStatus(s string) statusLevel { + l := strings.ToLower(s) + for _, w := range statusErrorWords { + if strings.Contains(l, w) { + return statusError + } + } + for _, w := range statusWarnWords { + if strings.Contains(l, w) { + return statusWarn + } + } + return statusInfo +} + +func renderStatusLine(m Model) string { + text := strings.Join(strings.Fields(m.status), " ") // single line + fg := m.palette.Muted + prefix := " " + switch classifyStatus(text) { + case statusError: + fg = m.palette.Danger + prefix = " ! " + case statusWarn: + fg = m.palette.Warning + } + style := lipgloss.NewStyle().Background(m.palette.StatusBar).Foreground(fg) + line := ansi.Truncate(prefix+text, m.width, "…") + if fill := m.width - ansi.StringWidth(line); fill > 0 { + line += strings.Repeat(" ", fill) + } + return style.Render(line) +} + func renderFilterBar(m Model) string { prompt := lipgloss.NewStyle(). Background(m.palette.Footer). @@ -5008,6 +5293,8 @@ func (m *Model) startDeleteJob(kind fileOpKind, sources []string) tea.Cmd { if kind == opPermanentDelete { verb = "delete permanently" } + var trashFailed []string + var firstErr error for i, sourcePath := range sources { select { case <-ctx.Done(): @@ -5027,12 +5314,20 @@ func (m *Model) startDeleteJob(kind fileOpKind, sources []string) tea.Cmd { err = vfs.MoveToTrash(sourcePath) } if err != nil { - m.archiveProgress <- archiveDoneMsg{ - jobID: jobID, - sourcePaths: append([]string(nil), sources...), - err: fmt.Errorf("%s %s: %w", verb, sourcePath, err), + if kind == opPermanentDelete { + m.archiveProgress <- archiveDoneMsg{ + jobID: jobID, + sourcePaths: append([]string(nil), sources...), + err: fmt.Errorf("%s %s: %w", verb, sourcePath, err), + } + return + } + // Keep trashing the rest: only items the trash refused + // are offered for permanent deletion (QA-17). + trashFailed = append(trashFailed, sourcePath) + if firstErr == nil { + firstErr = fmt.Errorf("%s %s: %w", verb, sourcePath, err) } - return } m.archiveProgress <- archiveProgressMsg{ @@ -5048,6 +5343,8 @@ func (m *Model) startDeleteJob(kind fileOpKind, sources []string) tea.Cmd { m.archiveProgress <- archiveDoneMsg{ jobID: jobID, sourcePaths: append([]string(nil), sources...), + err: firstErr, + trashFailed: trashFailed, } }() return nil @@ -5090,7 +5387,7 @@ func (m *Model) mkdirCmd(parent, name string) tea.Cmd { if mount, ok := m.activePane().CurrentRemote(); ok { return func() tea.Msg { targetPath := path.Join(parent, name) - err := mount.Client.MkdirAll(targetPath) + err := mount.Client.MkdirNew(targetPath) return opMsg{kind: opMkdir, targetPath: targetPath, err: err} } } @@ -5170,8 +5467,10 @@ func copyCursorMemory(src map[string]string) map[string]string { func applySession(m *Model) { s, err := config.LoadSession() if err != nil { + // A session read from the old location is still applied when moving + // it to the state dir fails (QA-16); the error goes to the status. log.Printf("[SESSION] load failed: %v", err) - return + m.status = fmt.Sprintf("Session error: %v", err) } if s.ActivePane == "" && s.Left.Path == "" && s.Right.Path == "" { log.Printf("[SESSION] no previous session found") @@ -5381,12 +5680,16 @@ func externalCommandFromEnv(envVars []string, fallbacks []string, path string) ( return exec.Command(parts[0], args...), filepath.Base(parts[0]), nil } +// startProcess starts a detached external process (xdg-open). Tests +// replace it to observe launches without running anything. +var startProcess = func(c *exec.Cmd) error { return c.Start() } + func startExternalOpenCmd(command *exec.Cmd, path string) tea.Cmd { return func() tea.Msg { command.Stdin = nil command.Stdout = io.Discard command.Stderr = io.Discard - if err := command.Start(); err != nil { + if err := startProcess(command); err != nil { return externalOpenMsg{path: path, err: err} } return externalOpenMsg{path: path} @@ -5523,6 +5826,45 @@ func isEditableEntry(entry vfs.Entry) bool { } } +// sshHostListPath is the pseudo-path of the SSH host list pane. +const sshHostListPath = "ssh://" + +// paneOnRemote reports whether the pane's entries are not local files: a +// remote mount or the SSH host list. +func paneOnRemote(p *BrowserPane) bool { + return p.InRemote() || p.Path == sshHostListPath +} + +// canWriteTo reports why the pane cannot be the destination of a write +// (copy, move, archive, unpack). Archive panes show a temp extraction that +// is deleted on exit, and the host list is not a directory at all. +func canWriteTo(p *BrowserPane) error { + if p.InArchive() { + return fmt.Errorf("target pane is inside an archive (read-only)") + } + if p.Path == sshHostListPath { + return fmt.Errorf("target pane is the SSH host list") + } + return nil +} + +// localFileActionAllowed guards actions that hand a file path to the local +// OS (editor, executable, xdg-open, archive mount). In an SSH pane the path +// is remote, and the same path on this machine is a different file. +func localFileActionAllowed(p *BrowserPane) error { + if paneOnRemote(p) { + return fmt.Errorf("Opening remote files is not supported yet; copy the file to a local pane (F5)") + } + return nil +} + +// releaseMounts drops the pane's reference on each mount's client. +func releaseMounts(mounts []RemoteMount) { + for _, mt := range mounts { + mt.Client.Release() + } +} + func isArchiveEntry(entry vfs.Entry) bool { return !entry.IsDir && !entry.IsParent && entry.Category() == "archive" } @@ -5719,7 +6061,7 @@ func (m *Model) exitSSHMode() (tea.Model, tea.Cmd) { m.ssh.connectedHosts[mount.Host.Name] = false } pane.PopRemote() - mount.Client.Close() + mount.Client.Release() } // Close all stored active clients (connections kept alive in host list) @@ -6070,9 +6412,15 @@ func (m *Model) startRemoteDeleteJob(sources []string, client *remote.SSHClient) log.Printf("[ACTION] startRemoteDeleteJob: job=%d sources=%v", jobID, sources) + // The job holds its own reference so leaving the host in the pane does + // not close the connection under it. + client.Acquire() return tea.Batch( func() tea.Msg { go func() { + defer client.Release() + var trashFailed []string + var firstErr error for i, sourcePath := range sources { select { case <-ctx.Done(): @@ -6110,6 +6458,8 @@ func (m *Model) startRemoteDeleteJob(sources []string, client *remote.SSHClient) m.archiveProgress <- archiveDoneMsg{ jobID: jobID, sourcePaths: append([]string(nil), sources...), + err: firstErr, + trashFailed: trashFailed, } }() return nil @@ -6159,9 +6509,13 @@ func (m *Model) startRemoteCopyJob(kind fileOpKind, sources []string, targetDir log.Printf("[JOB] startRemoteCopyJob: id=%d kind=%d sources=%d targetDir=%s srcRemote=%v dstRemote=%v stats={files=%d bytes=%d}", jobID, kind, len(sources), targetDir, sourceIsRemote, targetIsRemote, stats.FilesTotal, stats.BytesTotal) + srcClient.Acquire() + dstClient.Acquire() return tea.Batch( func() tea.Msg { go func() { + defer srcClient.Release() + defer dstClient.Release() doneFiles := 0 var doneBytes int64 totalFiles := 0 @@ -6187,8 +6541,12 @@ func (m *Model) startRemoteCopyJob(kind fileOpKind, sources []string, targetDir } if info.IsDir() { err := srcClient.Walk(sourcePath, func(_ string, info os.FileInfo, err error) error { - if err != nil { return err } - if !info.IsDir() { count++ } + if err != nil { + return err + } + if !info.IsDir() { + count++ + } return nil }) if err != nil { @@ -6242,7 +6600,7 @@ func (m *Model) startRemoteCopyJob(kind fileOpKind, sources []string, targetDir var info os.FileInfo var err error - serverSide := false // true if copy/move happened on server without streaming + serverSide := false // true if copy/move happened on server without streaming trackedProgress := false // true if per-file progress callback was used // Get file info and perform copy depending on direction. @@ -6544,10 +6902,10 @@ func renderSSHConnectModal(m Model, palette theme.Palette, width int) string { } lines = append(lines, spacer) // Use hint token renderer to highlight Enter, Esc, F1 - if hl, ok := renderModalHintTokens("Enter to confirm · Esc to cancel · F1/? for help", contentWidth, palette, palette.Muted); ok { + if hl, ok := renderModalHintTokens("Enter to confirm · Esc to cancel · F1 for help", contentWidth, palette, palette.Muted); ok { lines = append(lines, hl) } else { - lines = append(lines, noteStyle.Render("Enter to confirm · Esc to cancel · F1/? for help")) + lines = append(lines, noteStyle.Render("Enter to confirm · Esc to cancel · F1 for help")) } } diff --git a/internal/ui/qa_fixes_test.go b/internal/ui/qa_fixes_test.go new file mode 100644 index 0000000..bd64721 --- /dev/null +++ b/internal/ui/qa_fixes_test.go @@ -0,0 +1,87 @@ +package ui + +// Developer C (v0.2.8 QA fixes): tests for fixes that need more than the QA +// tests in qa_*_test.go. + +import ( + "os" + "path/filepath" + "testing" + "time" + + "vcom/internal/testutil/teadriver" +) + +// QA-1: when the trash refuses an item (another filesystem without a +// usable trash, a broken trash), the same flow offers permanent deletion; +// nothing is deleted without the explicit confirmation. +func TestQA1TrashFailureOffersPermanentDelete(t *testing.T) { + for _, tc := range []struct { + name string + answer string + deleted bool + }{ + {"confirm", "enter", true}, + {"y", "y", true}, + {"cancel", "esc", false}, + {"n", "n", false}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + writeFile(t, filepath.Join(dir, "b.txt"), "y") + d := newDriver(t, dir, t.TempDir()) + // A file where the trash directory should be: MoveToTrash fails. + writeFile(t, filepath.Join(os.Getenv("HOME"), ".local", "share", "Trash"), "not a dir") + m := cur(t, d) + for _, e := range m.activePane().Entries { + if !e.IsParent { + m.activePane().EnsureMarked(e.Path) + } + } + d = teadriver.New(t, m, 160, 40, teadriver.WithoutInit(), teadriver.WithLongCmd(300*time.Millisecond)) + d.Press("f8", "enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "a.txt")) || !exists(filepath.Join(dir, "b.txt")) { + t.Fatal("files deleted before confirmation") + } + if !d.ScreenContains("Delete permanently?") || !d.ScreenContains("Not in trash: 2") { + t.Fatalf("permanent delete not offered:\n%s", d.Screen()) + } + d.Press(tc.answer) + d.Settle(settle) + for _, n := range []string{"a.txt", "b.txt"} { + if got := exists(filepath.Join(dir, n)); got == tc.deleted { + t.Fatalf("%s exists=%v after %q (status %q)", n, got, tc.answer, cur(t, d).status) + } + } + if cur(t, d).modal.kind != modalNone { + t.Fatalf("dialog still open:\n%s", d.Screen()) + } + }) + } +} + +// QA-3: in the filter j/k are text, while the arrow keys still move the +// cursor through the filtered list. +func TestQA3FilterArrowsStillNavigate(t *testing.T) { + dir := t.TempDir() + for _, n := range []string{"jk1.txt", "jk2.txt", "other.txt"} { + writeFile(t, filepath.Join(dir, n), "x") + } + d := newDriver(t, dir, t.TempDir()) + d.Press("/") + d.Type("jk") + if q := cur(t, d).filterQuery; q != "jk" { + t.Fatalf("query %q", q) + } + cursor := func() int { m := cur(t, d); return m.activePane().Cursor } + before := cursor() + d.Press("down") + if cursor() == before { + t.Fatal("down arrow does not move the cursor in filter mode") + } + if q := cur(t, d).filterQuery; q != "jk" { + t.Fatalf("arrow changed the query: %q", q) + } +} diff --git a/internal/ui/qa_hotfix_test.go b/internal/ui/qa_hotfix_test.go new file mode 100644 index 0000000..21b4991 --- /dev/null +++ b/internal/ui/qa_hotfix_test.go @@ -0,0 +1,460 @@ +package ui + +// QA (v0.2.8): independent checks of the stage-1 UI hotfixes, aimed at the +// paths next to the ones the developer fixed. Tests that expose an open bug +// are skipped with "BUG QA-n"; see plans/rework/05-qa-v0.2.8.md. + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/muesli/termenv" + + vfs "vcom/internal/fs" + "vcom/internal/testutil/teadriver" +) + +// --- U-P1-5: Cyrillic / arbitrary text in every input --------------------- + +// Mkdir and rename fields must accept the letters that are also dialog +// keys elsewhere: q (close), n (no), y (confirm), j/k (move), ? (help). +func TestQATextModalsAcceptCommandLetters(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "old.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("qnyjk?п") + if got := cur(t, d).modal.input.Value(); got != "qnyjk?п" { + t.Fatalf("mkdir input %q, want %q", got, "qnyjk?п") + } + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "qnyjk?п")) { + t.Fatalf("dir not created, status %q", cur(t, d).status) + } + + selectName(t, d, "old.txt") + d.Press("f2", "ctrl+u") + d.Type("qй ё?.txt") + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "qй ё?.txt")) { + t.Fatalf("rename failed, status %q", cur(t, d).status) + } +} + +// The filter is a text field: typing "jpg" or "kotlin" must filter by that +// text. j/k are bound to Up/Down inside the filter handler and never reach +// the input. +func TestQAFilterAcceptsJK(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "photo.jpg"), "x") + writeFile(t, filepath.Join(dir, "notes.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + d.Press("/") + d.Type("jpg") + if q := cur(t, d).filterQuery; q != "jpg" { + t.Fatalf("filter query %q, want jpg", q) + } +} + +// Cyrillic filter: the list really narrows (the developer only checked the +// query string). +func TestQAFilterCyrillicNarrows(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "отчёт.txt"), "x") + writeFile(t, filepath.Join(dir, "summary.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + d.Press("/") + d.Type("отч") + d.Press("enter") + s := d.Screen() + if !strings.Contains(s, "отчёт.txt") || strings.Contains(s, "summary.txt") { + t.Fatalf("Cyrillic filter did not narrow the list:\n%s", s) + } +} + +func openSSHAddForm(t *testing.T, d *teadriver.Driver) { + t.Helper() + d.Press("s") // SSH host list + d.Settle(settle) + if p := activeOf(t, d).Path; p != sshHostListPath { + t.Fatalf("SSH host list not opened, path %q", p) + } + selectName(t, d, "+ Add host") + d.Press("enter") + d.Settle(settle) + if cur(t, d).modal.kind != modalSSHConnect { + t.Fatalf("add-host form not opened (modal %d)", cur(t, d).modal.kind) + } +} + +// SSH form: Cyrillic name, and q/n/y/j/k in fields. +func TestQASSHFormCyrillicAndLetters(t *testing.T) { + d := newDriver(t, t.TempDir(), t.TempDir()) + openSSHAddForm(t, d) + d.Type("сервер-qnyjk") + d.Press("tab") + d.Type("host.example") + m := cur(t, d) + if got := m.ssh.inputs[0].Value(); got != "сервер-qnyjk" { + t.Fatalf("name field %q", got) + } + if got := m.ssh.inputs[1].Value(); got != "host.example" { + t.Fatalf("host field %q", got) + } + if m.modal.kind != modalSSHConnect { + t.Fatal("form closed while typing") + } +} + +// '?' is a valid password character, but in the SSH form it toggles help. +func TestQASSHFormPasswordQuestionMark(t *testing.T) { + d := newDriver(t, t.TempDir(), t.TempDir()) + openSSHAddForm(t, d) + for i := 0; i < 4; i++ { + d.Press("tab") + } + d.Type("pa?ss") + if got := cur(t, d).ssh.inputs[4].Value(); got != "pa?ss" { + t.Fatalf("password field %q, want pa?ss", got) + } +} + +// Russian layout in yes/no dialogs: "т" (n) cancels, "н" (y) confirms. +func TestQARussianLayoutInConfirm(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "a.txt") + d.Press("f8", "т") + d.Settle(settle) + if cur(t, d).modal.kind != modalNone || !exists(filepath.Join(dir, "a.txt")) { + t.Fatal("т (n on the Russian layout) should cancel") + } + d.Press("f8", "н") + d.Settle(settle) + if exists(filepath.Join(dir, "a.txt")) { + t.Fatal("н (y on the Russian layout) should confirm") + } +} + +// --- U-P1-16: q / Esc in every layer -------------------------------------- + +func TestQAQAndEscCloseEveryLayer(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "hello\nworld\n") + writeFile(t, filepath.Join(dir, "b.txt"), "x") + type layer struct { + name string + open []string + check func(m Model) bool // true while the layer is open + } + layers := []layer{ + {"help", []string{"f1"}, func(m Model) bool { return m.modal.kind == modalHelp }}, + {"theme", []string{"t"}, func(m Model) bool { return m.modal.kind == modalThemeSelect }}, + {"view", []string{"f3"}, func(m Model) bool { return m.viewMode }}, + {"info", []string{"f9"}, func(m Model) bool { return m.infoMode }}, + {"caret", []string{"f9", "i"}, func(m Model) bool { return m.cursorMode || m.infoMode }}, + {"confirm-delete", []string{"f8"}, func(m Model) bool { return m.modal.kind == modalConfirm }}, + {"archive-type", []string{"f4"}, func(m Model) bool { return m.modal.kind == modalArchiveType }}, + {"copy-confirm", []string{"f5"}, func(m Model) bool { return m.modal.kind == modalConfirm }}, + {"selection", []string{"J"}, func(m Model) bool { return len(m.activePane().MarkedEntries()) > 0 }}, + } + for _, closeKey := range []string{"q", "esc"} { + for _, l := range layers { + t.Run(closeKey+"/"+l.name, func(t *testing.T) { + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "a.txt") + d.Press(l.open...) + d.Settle(settle) + if !l.check(cur(t, d)) { + t.Fatalf("layer did not open") + } + for i := 0; i < 3 && l.check(cur(t, d)); i++ { + d.Press(closeKey) + d.Settle(settle) + if d.Quit() { + t.Fatalf("%s quit the program with %s open", closeKey, l.name) + } + } + if l.check(cur(t, d)) { + t.Fatalf("%s did not close %s", closeKey, l.name) + } + if !exists(filepath.Join(dir, "a.txt")) { + t.Fatal("closing a layer deleted a.txt") + } + }) + } + } +} + +// --- U-P0-1: archive through the UI, all formats --------------------------- + +func TestQAArchiveSameDirZipThroughUI(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "report.zip") + writeFile(t, src, strings.Repeat("r", 40000)) + d := newDriver(t, dir, dir) + selectName(t, d, "report.zip") + d.Press("f4") + d.Settle(settle) + if f := cur(t, d).archiveFormat; f != "zip" { + t.Fatalf("default format %q", f) + } + d.Press("enter") + d.Settle(settle) + if fileSize(t, src) != 40000 { + t.Fatal("report.zip truncated") + } + if !d.ScreenContains("Cannot archive") { + t.Fatalf("no refusal on screen:\n%s", d.Screen()) + } +} + +// Archive a directory into the same pane for every format, then archive it +// again over the existing file with confirmation. +func TestQAArchiveFormatsAndOverwriteThroughUI(t *testing.T) { + formats := []struct { + presses int // presses of "f" from the default zip + ext string + }{{0, ".zip"}, {1, ".tar"}, {2, ".tar.gz"}} + for _, f := range formats { + t.Run(f.ext, func(t *testing.T) { + dir, out := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(dir, "proj", "a.txt"), "alpha") + d := newDriver(t, dir, out) + selectName(t, d, "proj") + for round := 0; round < 2; round++ { + d.Press("f4") + d.Settle(settle) + for i := 0; i < f.presses; i++ { + d.Press("f") + } + d.Press("enter") + d.Settle(settle) + if round == 1 { + if !d.ScreenContains("Overwrite existing archive") { + t.Fatalf("second archive did not ask to overwrite:\n%s", d.Screen()) + } + d.Press("y") + d.Settle(settle) + } + } + arc := filepath.Join(out, "proj"+f.ext) + if st, err := os.Stat(arc); err != nil || st.Size() == 0 { + t.Fatalf("archive %s not written: %v (status %q)", arc, err, cur(t, d).status) + } + left, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*")) + if len(left) != 0 { + t.Fatalf("temp files left: %v", left) + } + }) + } +} + +// --- U-P0-2: archive pane as target, adjacent paths ------------------------- + +// Mirror (p) from a pane inside an archive gives the passive pane the +// archive's temp extraction directory as a plain local path: it is not +// marked as an archive, so canWriteTo lets copy/move write there, and the +// directory is deleted when the archive is closed. +func TestQAMirrorFromArchiveKeepsReadOnly(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "inner.txt"), "in archive") + if err := vfs.CreateArchive(context.Background(), []string{filepath.Join(dir, "inner.txt")}, filepath.Join(dir, "box.zip"), nil); err != nil { + t.Fatal(err) + } + work := t.TempDir() + writeFile(t, filepath.Join(work, "precious.txt"), "user data") + + d := newDriver(t, dir, work) + selectName(t, d, "box.zip") + d.Press("enter") + d.Settle(settle) + if !activeOf(t, d).InArchive() { + t.Fatal("did not enter archive") + } + d.Press("p") // mirror: right pane now shows the archive's temp dir + d.Settle(settle) + m := cur(t, d) + // Developer C: refusing the mirror (passive pane stays on its own + // directory) is the chosen fix; a read-only mirror would pass too. + if m.passivePane().Path == work && !strings.Contains(m.status, "not supported") { + t.Fatalf("mirror neither applied nor refused visibly (status %q)", m.status) + } + if err := canWriteTo(m.passivePane()); err == nil && m.passivePane().Path != work { + // Show the actual loss: move a real file there, close the archive. + m.passivePane() + t.Fatalf("passive pane %q (mirror of an archive) is writable", m.passivePane().Path) + } +} + +// Delete/mkdir in a pane that shows an archive's temp dir via mirror. +// (Documented together with QA-2.) + +// --- U-P0-3: caret on every profile, with the status line and the filter --- + +func TestQACaretAllProfilesNarrowTerminal(t *testing.T) { + for name, profile := range map[string]termenv.Profile{"Ascii": termenv.Ascii, "ANSI": termenv.ANSI, "ANSI256": termenv.ANSI256, "TrueColor": termenv.TrueColor} { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "t.txt"), "строка один\n\tтаб\n"+strings.Repeat("длинная ", 40)+"\n") + m := newTestModel(t, dir, t.TempDir()) + d := teadriver.New(t, m, 72, 18, teadriver.WithProfile(profile), teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + selectName(t, d, "t.txt") + d.Press("f9") + d.Settle(settle) + d.Press("i") + d.Settle(settle) + d.Press("j", "j", "l", "l", "w", "v", "l", "l", "e", "b", "k") + _ = d.Screen() + d.Press("f3") // view mode on top + d.Settle(settle) + _ = d.Screen() + if n := len(strings.Split(d.Screen(), "\n")); n != 18 { + t.Fatalf("view height %d, want 18", n) + } + }) + } +} + +// --- U-P1-1: the status line ------------------------------------------------ + +// Multi-line and very long errors stay on one line and keep the height. +func TestQAStatusLineMultilineAndLong(t *testing.T) { + d := newDriver(t, t.TempDir(), t.TempDir()) + m := cur(t, d) + m.status = "Copy failed: first line\nsecond line\r\n" + strings.Repeat("ошибка ", 100) + d2 := teadriver.New(t, m, 80, 20, teadriver.WithoutInit()) + s := d2.Screen() + lines := strings.Split(s, "\n") + if len(lines) != 20 { + t.Fatalf("height %d, want 20", len(lines)) + } + found := false + for _, l := range lines { + if strings.Contains(l, "first line second line") { + found = true + } + } + if !found { + t.Fatalf("status not joined on one line:\n%s", s) + } +} + +// Status line under every profile does not change the line count. +func TestQAStatusLineProfiles(t *testing.T) { + for _, profile := range []termenv.Profile{termenv.Ascii, termenv.ANSI, termenv.TrueColor} { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "x"), 0o755); err != nil { + t.Fatal(err) + } + m := newTestModel(t, dir, t.TempDir()) + d := teadriver.New(t, m, 100, 25, teadriver.WithProfile(profile), teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + d.Press("f7") + d.Type("x") + d.Press("enter") + d.Settle(settle) + if !d.ScreenContains("file exists") { + t.Fatalf("profile %v: error not shown:\n%s", profile, d.Screen()) + } + if n := len(strings.Split(d.Screen(), "\n")); n != 25 { + t.Fatalf("profile %v: %d lines", profile, n) + } + } +} + +// --- U-P0-4: delete defaults to trash ---------------------------------------- + +// Multi-selection with names containing spaces and Cyrillic, plus a +// directory, all go to the trash. +func TestQADeleteToTrashMultiSelection(t *testing.T) { + dir := t.TempDir() + for _, n := range []string{"a b.txt", "отчёт.txt"} { + writeFile(t, filepath.Join(dir, n), n) + } + writeFile(t, filepath.Join(dir, "папка", "inner"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "a b.txt") + m := cur(t, d) + p := m.activePane() + for _, e := range p.Entries { + if !e.IsParent { + p.EnsureMarked(e.Path) + } + } + d = teadriver.New(t, m, 160, 40, teadriver.WithoutInit(), teadriver.WithLongCmd(300*time.Millisecond)) + d.Press("f8") + d.Settle(settle) + if !d.ScreenContains("to trash") { + t.Fatalf("dialog does not say trash:\n%s", d.Screen()) + } + d.Press("enter") + d.Settle(settle) + left, _ := os.ReadDir(dir) + if len(left) != 0 { + t.Fatalf("left in dir: %v (status %q)", left, cur(t, d).status) + } + trashed, _ := os.ReadDir(trashFiles(t)) + if len(trashed) != 3 { + t.Fatalf("trash has %d items, want 3", len(trashed)) + } +} + +// D toggles to permanent and back: the second D must return to trash. +func TestQADeleteModeToggleBack(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "a.txt") + d.Press("f8", "D", "D") + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(trashFiles(t), "a.txt")) { + t.Fatalf("after D,D the file should go to the trash (status %q)", cur(t, d).status) + } +} + +// The delete kind must not leak into the next dialog: after a permanent +// delete, the next F8 starts in trash mode again. +func TestQADeleteModeResetsBetweenDialogs(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + writeFile(t, filepath.Join(dir, "b.txt"), "y") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "a.txt") + d.Press("f8", "D", "esc") + selectName(t, d, "b.txt") + d.Press("f8", "enter") + d.Settle(settle) + if !exists(filepath.Join(trashFiles(t), "b.txt")) { + t.Fatal("cancelled permanent mode leaked into the next delete") + } +} + +// With trash as default, the user sees the failure when the trash is not +// usable (here: a file where the trash directory should be) and the file +// stays. +func TestQADeleteTrashFailureVisible(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + trash := filepath.Join(os.Getenv("HOME"), ".local", "share", "Trash") + writeFile(t, trash, "not a dir") + selectName(t, d, "a.txt") + d.Press("f8", "enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "a.txt")) { + t.Fatal("file lost although the trash is broken") + } + if st := cur(t, d).status; classifyStatus(st) != statusError || !d.ScreenContains("trash") { + t.Fatalf("trash failure not reported: %q\n%s", st, d.Screen()) + } +} diff --git a/internal/ui/qa_rc2_test.go b/internal/ui/qa_rc2_test.go new file mode 100644 index 0000000..3e43dc9 --- /dev/null +++ b/internal/ui/qa_rc2_test.go @@ -0,0 +1,335 @@ +package ui + +// QA (v0.2.8 RC2): re-check of the QA fixes from the user's side and of the +// stage-2C changes the old UI now uses (config/SetKey, session, trash). + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "vcom/internal/config" + vfs "vcom/internal/fs" + "vcom/internal/testutil/teadriver" +) + +// newModelLikeMain mirrors cmd/vcom/main.go: Load, pass info.Path only if +// the file was found and parsed, set the notice. +func newModelLikeMain(t *testing.T, left, right string) (*teadriver.Driver, config.LoadInfo) { + t.Helper() + cfg, info, err := config.Load("") + resolved := "" + if info.Found && err == nil { + resolved = info.Path + } + cfg.UI.IconMode = "ascii" + cfg.Startup.LeftPath, cfg.Startup.RightPath = left, right + m, merr := NewModel(cfg, resolved) + if merr != nil { + t.Fatalf("NewModel: %v", merr) + } + if err != nil { + m = m.WithStatus(err.Error()) + } + t.Cleanup(func() { m.cleanupArchiveMounts(); m.cleanupRemoteImageTemp() }) + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + return d, info +} + +func userConfig(t *testing.T) string { + return filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "vcom", "vcom.toml") +} + +// Unknown theme name: vcom starts with the default theme and says why; +// choosing a theme then fixes the file, keeping the rest of it. +func TestQAUnknownThemeStartsAndIsFixable(t *testing.T) { + isolateEnv(t) + dir := t.TempDir() + p := userConfig(t) + writeFile(t, p, "# keep me\n[ui]\ntheme = \"no-such-theme\"\nicon_mode = \"ascii\"\n") + d, _ := newModelLikeMain(t, dir, dir) + if !d.ScreenContains("no-such-theme") { + t.Fatalf("unknown theme not explained on screen:\n%s", d.Screen()) + } + d.Press("t", "j", "enter") + d.Settle(settle) + b, _ := os.ReadFile(p) + if strings.Contains(string(b), "no-such-theme") || !strings.Contains(string(b), "# keep me") || !strings.Contains(string(b), "icon_mode") { + t.Fatalf("config after theme choice: %q (status %q)", b, cur(t, d).status) + } +} + +// Broken config: vcom starts with defaults, shows the error; choosing a +// theme must not overwrite (or "repair") the user's broken file. +func TestQABrokenConfigNotOverwrittenByTheme(t *testing.T) { + isolateEnv(t) + dir := t.TempDir() + p := userConfig(t) + broken := "[ui]\ntheme = \"catppuccin-mocha\"\nicon_mode = \n# half-edited\n" + writeFile(t, p, broken) + d, _ := newModelLikeMain(t, dir, dir) + if !d.ScreenContains("incomplete number") { // shown, though not highlighted as an error (see report) + t.Fatalf("broken config not reported: %q", cur(t, d).status) + } + d.Press("t", "j", "enter") + d.Settle(settle) + if b, _ := os.ReadFile(p); string(b) != broken { + t.Fatalf("broken config was rewritten: %q", b) + } +} + +// $VCOM_CONFIG (or -config) names a file that does not exist yet: the +// theme must be saved there, so the next start (which reads $VCOM_CONFIG) +// sees it. main passes "" for a missing file and SetKey("") writes the +// default ~/.config/vcom/vcom.toml instead. +func TestQAThemeSavedToExplicitMissingConfig(t *testing.T) { + home := isolateEnv(t) + explicit := filepath.Join(home, "custom", "vcom.toml") + t.Setenv("VCOM_CONFIG", explicit) + dir := t.TempDir() + d, info := newModelLikeMain(t, dir, dir) + if info.Path != explicit { + t.Fatalf("Load info.Path=%q", info.Path) + } + d.Press("t", "j", "enter") + d.Settle(settle) + if _, err := os.Stat(explicit); err != nil { + t.Fatalf("theme not saved to $VCOM_CONFIG (%v); default exists: %v", err, exists(userConfig(t))) + } +} + +// A broken session.toml: start at the startup paths, quit writes a valid one. +func TestQABrokenSessionRecovers(t *testing.T) { + isolateEnv(t) + dir := t.TempDir() + sp := filepath.Join(os.Getenv("XDG_STATE_HOME"), "vcom", "session.toml") + writeFile(t, sp, "active_pane = 'right'\n[left\n") + d := teadriver.New(t, newTestModelKeepEnv(t, dir, dir), 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + if p := activeOf(t, d).Path; p != dir { + t.Fatalf("pane at %q, want startup %q", p, dir) + } + d.Press("q") + d.Settle(settle) + s, err := config.LoadSession() + if err != nil || s.Left.Path != dir { + t.Fatalf("session after quit: %+v %v", s, err) + } +} + +// Old session location: restored once, then moved to the state dir. +func TestQAOldSessionMigratedThroughUI(t *testing.T) { + isolateEnv(t) + start, saved := t.TempDir(), t.TempDir() + old := filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "vcom", "session.toml") + writeFile(t, old, "active_pane = 'left'\n[left]\npath = '"+saved+"'\n[right]\npath = '"+saved+"'\n") + m := newTestModelKeepEnv(t, start, start) + if m.left.Path != saved { + t.Fatalf("old session not restored: left=%q", m.left.Path) + } + if exists(old) { + t.Fatal("old session not removed after migration") + } + if !exists(filepath.Join(os.Getenv("XDG_STATE_HOME"), "vcom", "session.toml")) { + t.Fatal("session not written to the state dir") + } +} + +// State dir not writable (e.g. XDG_STATE_HOME on a read-only mount): the +// old session is read but not applied, because applySession drops the +// session whenever Load returns an error. +func TestQAOldSessionRestoredWhenStateDirReadOnly(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores permissions") + } + home := isolateEnv(t) + start, saved := t.TempDir(), t.TempDir() + old := filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "vcom", "session.toml") + writeFile(t, old, "active_pane = 'left'\n[left]\npath = '"+saved+"'\n") + ro := filepath.Join(home, "ro") + if err := os.MkdirAll(ro, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(ro, 0o700) }) + t.Setenv("XDG_STATE_HOME", filepath.Join(ro, "state")) + m := newTestModelKeepEnv(t, start, start) + if m.left.Path != saved { + t.Fatalf("session not restored: left=%q", m.left.Path) + } +} + +// newTestModelKeepEnv is newTestModel without re-isolating the environment +// (the test prepared files in it). +func newTestModelKeepEnv(t *testing.T, left, right string) Model { + t.Helper() + cfg := config.Default() + cfg.UI.IconMode = "ascii" + cfg.Startup.LeftPath, cfg.Startup.RightPath = left, right + m, err := NewModel(cfg, "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.cleanupArchiveMounts(); m.cleanupRemoteImageTemp() }) + return m +} + +// QA-1 bypass: one item the trash refuses (name too long for its +// .trashinfo) in a multi-selection with an ordinary file. Only the refused +// item may be offered for permanent deletion; the ordinary file belongs in +// the trash. +func TestQATrashOfferOnlyForRefusedItems(t *testing.T) { + dir := t.TempDir() + long := strings.Repeat("a", 250) // + ".trashinfo" > NAME_MAX + writeFile(t, filepath.Join(dir, long), "x") + writeFile(t, filepath.Join(dir, "b.txt"), "ordinary") + d := newDriver(t, dir, t.TempDir()) + m := cur(t, d) + for _, e := range m.activePane().Entries { + if !e.IsParent { + m.activePane().EnsureMarked(e.Path) + } + } + d = teadriver.New(t, m, 160, 40, teadriver.WithoutInit(), teadriver.WithLongCmd(300*time.Millisecond)) + d.Press("f8", "enter") + d.Settle(settle) + if exists(filepath.Join(dir, "b.txt")) { + if d.ScreenContains("Not in trash: 2") { + t.Fatalf("b.txt (trashable) offered for permanent deletion:\n%s", d.Screen()) + } + } + if !exists(filepath.Join(trashFiles(t), "b.txt")) { + t.Fatal("b.txt should be in the trash") + } +} + +// Long names: does the trash accept a 250-byte name at all? (Recorded in +// the report; the offer flow covers it.) +func TestQATrashLongNameOffered(t *testing.T) { + dir := t.TempDir() + long := strings.Repeat("л", 125) // 250 bytes + writeFile(t, filepath.Join(dir, long), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, long) + d.Press("f8", "enter") + d.Settle(settle) + if exists(filepath.Join(dir, long)) { + if !d.ScreenContains("Delete permanently?") { + t.Fatalf("long name neither trashed nor offered:\n%s\nstatus %q", d.Screen(), cur(t, d).status) + } + d.Press("esc") + d.Settle(settle) + if !exists(filepath.Join(dir, long)) { + t.Fatal("esc deleted the file") + } + } +} + +// QA-2 neighbour: mirror from a local pane INTO a pane that is inside an +// archive. The passive pane keeps its archive mount while showing a real +// directory: it stays "read-only" on the real filesystem, can never leave +// the archive (root is the temp dir) and the temp dir lingers. +func TestQAMirrorIntoArchivePane(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "inner.txt"), "in") + if err := vfs.CreateArchive(context.Background(), []string{filepath.Join(dir, "inner.txt")}, filepath.Join(dir, "box.zip"), nil); err != nil { + t.Fatal(err) + } + work := t.TempDir() + writeFile(t, filepath.Join(work, "w.txt"), "w") + d := newDriver(t, dir, work) + selectName(t, d, "box.zip") + d.Press("enter") // left into the archive + d.Settle(settle) + d.Press("tab", "p") // right (local) mirrors into left + d.Settle(settle) + m := cur(t, d) + if m.passivePane().Path == work && m.passivePane().InArchive() { + t.Fatalf("passive pane shows %s but is still in the archive", work) + } +} + +// QA-3 re-check: shifted letters, digits, space and Cyrillic are text in +// the filter; arrows still navigate. +func TestQAFilterAllPrintable(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "My Kj 2 файл.txt"), "x") + writeFile(t, filepath.Join(dir, "other"), "x") + d := newDriver(t, dir, t.TempDir()) + d.Press("/") + d.Type("My Kj 2 фа") + if q := cur(t, d).filterQuery; q != "My Kj 2 фа" { + t.Fatalf("filter query %q", q) + } + d.Press("enter") + if d.ScreenContains("other") { + t.Fatalf("filter did not narrow:\n%s", d.Screen()) + } +} + +// QA-4 re-check: '?' typed into every SSH form field; F1 toggles help. +func TestQASSHFormQuestionMarkEveryField(t *testing.T) { + d := newDriver(t, t.TempDir(), t.TempDir()) + openSSHAddForm(t, d) + for i := 0; i < 5; i++ { + d.Type("a?b") + if got := cur(t, d).ssh.inputs[i].Value(); got != "a?b" { + t.Fatalf("field %d = %q", i, got) + } + d.Press("tab") + } + d.Press("f1") + if !cur(t, d).ssh.showHelp { + t.Fatal("F1 did not open help") + } + d.Press("f1") + if cur(t, d).ssh.showHelp || cur(t, d).modal.kind != modalSSHConnect { + t.Fatal("F1 did not close help") + } +} + +// QA-10 re-check: F7 in an SSH pane: existing name → error, new nested +// name works, existing *file* name → error. +func TestQARemoteMkdirVariants(t *testing.T) { + rdir := t.TempDir() + writeFile(t, filepath.Join(rdir, "file"), "x") + d := newRemoteDriver(t, rdir, t.TempDir()) + for _, tc := range []struct { + name string + ok bool + }{{"file", false}, {"new/sub", true}, {"new/sub", false}, {"папка", true}} { + d.Press("f7") + d.Type(tc.name) + d.Press("enter") + d.Settle(settle) + isErr := classifyStatus(cur(t, d).status) == statusError + if cur(t, d).modal.kind != modalNone { + d.Press("esc") // the dialog stays open after an error + } + if isErr == tc.ok { + t.Fatalf("mkdir %q: status %q", tc.name, cur(t, d).status) + } + } + if !exists(filepath.Join(rdir, "new", "sub")) || !exists(filepath.Join(rdir, "папка")) { + t.Fatal("remote dirs not created") + } +} + +// When saving the chosen theme fails (broken config, forms SetKey cannot +// edit), the user must see it. finalizeTheme sets "Theme: X (save failed: +// ...)", but the theme selector overwrites the status with "Theme: X" right +// after, so a theme that was not persisted looks saved. +func TestQAThemeSaveFailureVisible(t *testing.T) { + isolateEnv(t) + dir := t.TempDir() + writeFile(t, userConfig(t), "[ui]\nicon_mode = \n") + d, _ := newModelLikeMain(t, dir, dir) + d.Press("t", "j", "enter") + d.Settle(settle) + if !strings.Contains(cur(t, d).status, "save failed") { + t.Fatalf("theme save failure not reported: %q", cur(t, d).status) + } +} diff --git a/internal/ui/qa_regression_test.go b/internal/ui/qa_regression_test.go new file mode 100644 index 0000000..c632fcf --- /dev/null +++ b/internal/ui/qa_regression_test.go @@ -0,0 +1,477 @@ +package ui + +// QA (v0.2.8): regression pass over the main user scenarios through the +// teadriver (local panes) and through sshtest (remote pane). + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "vcom/internal/config" + "vcom/internal/fs/remote" + "vcom/internal/testutil/sshtest" + "vcom/internal/testutil/teadriver" +) + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatalf("read %s: %v", p, err) + } + return string(b) +} + +// F5 local->local: overwrite confirmed replaces, cancelled keeps. +func TestQACopyOverwriteConfirmAndCancel(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(src, "a.txt"), "NEW") + writeFile(t, filepath.Join(dst, "a.txt"), "OLD") + d := newDriver(t, src, dst) + selectName(t, d, "a.txt") + + d.Press("f5") + d.Settle(settle) + if !d.ScreenContains("verwrite") { + t.Fatalf("no overwrite warning:\n%s", d.Screen()) + } + d.Press("n") + d.Settle(settle) + if got := readFile(t, filepath.Join(dst, "a.txt")); got != "OLD" { + t.Fatalf("cancel overwrote: %q", got) + } + d.Press("f5") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + if got := readFile(t, filepath.Join(dst, "a.txt")); got != "NEW" { + t.Fatalf("confirmed overwrite: %q (status %q)", got, cur(t, d).status) + } +} + +// F6 local->local: file and directory, without and with an existing target. +func TestQAMoveFileAndDir(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(src, "f.txt"), "file") + writeFile(t, filepath.Join(src, "dir", "inner.txt"), "inner") + writeFile(t, filepath.Join(src, "dup.txt"), "NEW") + writeFile(t, filepath.Join(dst, "dup.txt"), "OLD") + d := newDriver(t, src, dst) + for _, n := range []string{"f.txt", "dir"} { + selectName(t, d, n) + d.Press("f6") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(src, n)) || !exists(filepath.Join(dst, n)) { + t.Fatalf("move %s failed (status %q)", n, cur(t, d).status) + } + } + if readFile(t, filepath.Join(dst, "dir", "inner.txt")) != "inner" { + t.Fatal("moved dir content wrong") + } + selectName(t, d, "dup.txt") + d.Press("f6") + d.Settle(settle) + d.Press("esc") + d.Settle(settle) + if !exists(filepath.Join(src, "dup.txt")) || readFile(t, filepath.Join(dst, "dup.txt")) != "OLD" { + t.Fatal("cancelled move changed files") + } + d.Press("f6") + d.Settle(settle) + d.Press("y") + d.Settle(settle) + if exists(filepath.Join(src, "dup.txt")) || readFile(t, filepath.Join(dst, "dup.txt")) != "NEW" { + t.Fatalf("confirmed move-overwrite failed (status %q)", cur(t, d).status) + } +} + +// Sorting, hidden files toggle, history back/forward, mirror, info, view, +// theme selector, PgUp/PgDn. +func TestQABrowseScenarios(t *testing.T) { + dir := t.TempDir() + for i := 0; i < 60; i++ { + writeFile(t, filepath.Join(dir, fmt.Sprintf("f%02d.txt", i)), strings.Repeat("x", i)) + } + writeFile(t, filepath.Join(dir, ".hidden"), "h") + writeFile(t, filepath.Join(dir, "sub", "deep", "z.txt"), "z") + other := t.TempDir() + d := newDriver(t, dir, other) + + // hidden toggle + before := d.ScreenContains(".hidden") + d.Press(".") + d.Settle(settle) + if d.ScreenContains(".hidden") == before { + t.Fatal(". did not toggle hidden files") + } + + // sort cycles and changes order + first := func() string { + p := activeOf(t, d) + for _, e := range p.Entries { + if !e.IsParent && !e.IsDir { + return e.Name + } + } + return "" + } + order0 := first() + changed := false + for i := 0; i < 4; i++ { + d.Press("g") + d.Settle(settle) + if first() != order0 { + changed = true + } + } + if !changed { + t.Fatal("g never changed the order") + } + + // PgDn / PgUp + d.Press("pgdown") + mid := activeOf(t, d).Cursor + d.Press("pgup") + if mid == 0 || activeOf(t, d).Cursor >= mid { + t.Fatalf("PgDn/PgUp: %d then %d", mid, activeOf(t, d).Cursor) + } + + // history + selectName(t, d, "sub") + d.Press("enter") + d.Settle(settle) + selectName(t, d, "deep") + d.Press("enter") + d.Settle(settle) + d.Press("alt+left") + d.Settle(settle) + if p := activeOf(t, d).Path; p != filepath.Join(dir, "sub") { + t.Fatalf("history back -> %s", p) + } + d.Press("alt+right") + d.Settle(settle) + if p := activeOf(t, d).Path; p != filepath.Join(dir, "sub", "deep") { + t.Fatalf("history forward -> %s", p) + } + + // mirror + d.Press("p") + d.Settle(settle) + m := cur(t, d) + if m.passivePane().Path != filepath.Join(dir, "sub", "deep") { + t.Fatalf("mirror: passive at %s", m.passivePane().Path) + } + + // info + view + selectName(t, d, "z.txt") + d.Press("f9") + d.Settle(settle) + if !cur(t, d).infoMode { + t.Fatal("info did not open") + } + d.Press("f3") + d.Settle(settle) + if !cur(t, d).viewMode { + t.Fatal("view did not open") + } + d.Press("esc") + d.Settle(settle) + if cur(t, d).viewMode { + t.Fatal("esc did not close view") + } + d.Press("f9") + d.Settle(settle) + + // theme selector: move and confirm + d.Press("t") + d.Settle(settle) + if cur(t, d).modal.kind != modalThemeSelect { + t.Fatal("theme selector did not open") + } + d.Press("j", "enter") + d.Settle(settle) + if cur(t, d).modal.kind != modalNone { + t.Fatal("theme selector did not close on enter") + } + if n := len(strings.Split(d.Screen(), "\n")); n != 40 { + t.Fatalf("height %d after theme change", n) + } +} + +// F7 with a nested name and the error for an existing one is visible. +func TestQAMkdirNestedAndExisting(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("a/b") + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "a", "b")) { + t.Fatalf("nested mkdir failed: %q", cur(t, d).status) + } + d.Press("f7") + d.Type("a") + d.Press("enter") + d.Settle(settle) + if classifyStatus(cur(t, d).status) != statusError || !d.ScreenContains("exists") { + t.Fatalf("existing dir not reported: %q", cur(t, d).status) + } +} + +// --- remote pane (sshtest) ------------------------------------------------- + +func TestQARemoteListingCopyBothWays(t *testing.T) { + rdir, local := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(rdir, "remote.txt"), "from server") + writeFile(t, filepath.Join(rdir, "rdir", "nested.txt"), "nested") + writeFile(t, filepath.Join(local, "local.txt"), "from laptop") + writeFile(t, filepath.Join(local, "ldir", "n.txt"), "ln") + d := newRemoteDriver(t, rdir, local) + if !d.ScreenContains("remote.txt") || !d.ScreenContains("rdir") { + t.Fatalf("remote listing missing:\n%s", d.Screen()) + } + // remote -> local, file and dir + for _, n := range []string{"remote.txt", "rdir"} { + selectName(t, d, n) + d.Press("f5") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + } + if readFile(t, filepath.Join(local, "remote.txt")) != "from server" || readFile(t, filepath.Join(local, "rdir", "nested.txt")) != "nested" { + t.Fatal("remote->local copy wrong") + } + // local -> remote + d.Press("tab") + for _, n := range []string{"local.txt", "ldir"} { + selectName(t, d, n) + d.Press("f5") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + } + if readFile(t, filepath.Join(rdir, "local.txt")) != "from laptop" || readFile(t, filepath.Join(rdir, "ldir", "n.txt")) != "ln" { + t.Fatalf("local->remote copy wrong (status %q)", cur(t, d).status) + } + // the remote pane shows the uploaded files after refresh + d.Press("tab", "ctrl+r") + d.Settle(settle) + if !d.ScreenContains("local.txt") { + t.Fatalf("remote pane not refreshed:\n%s", d.Screen()) + } +} + +func TestQARemoteDeleteFileDirAndSymlink(t *testing.T) { + rdir := t.TempDir() + writeFile(t, filepath.Join(rdir, "f.txt"), "x") + writeFile(t, filepath.Join(rdir, "d", "inner.txt"), "x") + precious := t.TempDir() + writeFile(t, filepath.Join(precious, "keep.txt"), "keep") + if err := os.Symlink(precious, filepath.Join(rdir, "link")); err != nil { + t.Fatal(err) + } + // confirm_delete=false must not skip the question for a permanent remote delete + m := newTestModel(t, t.TempDir(), t.TempDir(), func(c *config.Config) { c.Behavior.ConfirmDelete = false }) + c := connectTestHost(t) + mountRemote(t, &m, PaneLeft, c, rdir) + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + for _, n := range []string{"f.txt", "d", "link"} { + selectName(t, d, n) + d.Press("f8") + d.Settle(settle) + if cur(t, d).modal.kind != modalConfirm { + t.Fatalf("remote delete of %s did not ask (permanent)", n) + } + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(rdir, n)) { + t.Fatalf("%s not deleted (status %q)", n, cur(t, d).status) + } + } + if readFile(t, filepath.Join(precious, "keep.txt")) != "keep" { + t.Fatal("deleting the remote symlink removed the target content") + } + if d.ScreenContains("f.txt") { + t.Fatalf("remote pane not refreshed after delete:\n%s", d.Screen()) + } +} + +// Remote mkdir with an existing name: the local path now reports an error +// (CHANGELOG: "Creating a directory that already exists reports an +// error"), the SSH pane still reports success. +func TestQARemoteMkdirExisting(t *testing.T) { + rdir := t.TempDir() + if err := os.Mkdir(filepath.Join(rdir, "taken"), 0o755); err != nil { + t.Fatal(err) + } + d := newRemoteDriver(t, rdir, t.TempDir()) + d.Press("f7") + d.Type("taken") + d.Press("enter") + d.Settle(settle) + if classifyStatus(cur(t, d).status) != statusError { + t.Fatalf("existing remote dir not reported: %q", cur(t, d).status) + } +} + +// Every local-file action is refused in an SSH pane; none touches the local +// file with the same path (adjacent to N-P0-1/N-P0-2: edit, open, view, +// archive, unpack, rename, move-within). +func TestQARemoteLocalActionsRefused(t *testing.T) { + rdir := t.TempDir() + conf := filepath.Join(rdir, "app.conf") + writeFile(t, conf, "x=1\n") + writeFile(t, filepath.Join(rdir, "a.zip"), "PK") + t.Setenv("VISUAL", "true") + started := recordProcesses(t) + d := newRemoteDriver(t, rdir, t.TempDir()) + selectName(t, d, "app.conf") + for _, k := range []string{"f4", "a", "f2", "r", "enter"} { + d.Press(k) + d.Settle(settle) + if mk := cur(t, d).modal.kind; mk != modalNone { + t.Fatalf("%s opened modal %d in an SSH pane", k, mk) + } + } + selectName(t, d, "a.zip") + for _, k := range []string{"f11", "e", "enter"} { + d.Press(k) + d.Settle(settle) + if mk := cur(t, d).modal.kind; mk != modalNone { + t.Fatalf("%s opened modal %d on a remote archive", k, mk) + } + if activeOf(t, d).InArchive() { + t.Fatal("entered a remote archive through the local path") + } + } + if len(*started) != 0 || len(d.Execs()) != 0 { + t.Fatalf("local processes started: %v execs=%d", *started, len(d.Execs())) + } + if readFile(t, conf) != "x=1\n" { + t.Fatal("file changed") + } +} + +// N-P0-8 / N-P1-12 in the UI: a remote copy sent to the background keeps +// working after the pane leaves the host; the connection is closed only +// when the job is done. +func TestQARemoteBackgroundCopyThenLeaveHost(t *testing.T) { + rdir, local := t.TempDir(), t.TempDir() + data := sshtest.WriteRandom(t, filepath.Join(rdir, "big.bin"), 2<<20, 0o644) + + m := newTestModel(t, local, local) // isolates HOME before connecting + srv := sshtest.Start(t, sshtest.Options{}) + proxy := sshtest.NewProxy(t, srv.Addr) + c, err := remote.Connect(remote.SSHHost{Name: "testhost", HostName: "127.0.0.1", Port: proxy.Port(), User: "u", Password: srv.Password}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + + mountRemote(t, &m, PaneLeft, c, "/") + p := m.paneByID(PaneLeft) + p.Path = rdir + if err := m.reloadRemotePane(PaneLeft, ""); err != nil { + t.Fatal(err) + } + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + selectName(t, d, "big.bin") + proxy.SetDelay(2 * time.Millisecond) + d.Press("f5") + d.Settle(settle) + d.Press("enter") // job starts: holds its own client reference + if cur(t, d).modal.kind != modalCopyProgress { + t.Fatalf("no progress dialog (modal %d)", cur(t, d).modal.kind) + } + d.Press("b") // background + // leave the host: walk up to "/" and once more + for i := 0; i < 20 && activeOf(t, d).InRemote(); i++ { + d.Press("backspace") + } + if activeOf(t, d).InRemote() { + t.Fatal("could not leave the host") + } + if !c.IsConnected() { + t.Fatal("leaving the host closed the client under the background job") + } + d.Settle(30 * time.Second) + got, err := os.ReadFile(filepath.Join(local, "big.bin")) + if err != nil || len(got) != len(data) || string(got) != string(data) { + t.Fatalf("background copy incomplete: %d/%d bytes, err %v, status %q", len(got), len(data), err, cur(t, d).status) + } + deadline := time.Now().Add(5 * time.Second) + for c.IsConnected() && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if c.IsConnected() { + t.Fatal("client not closed after the last user (job) finished") + } +} + +// Mirror an SSH pane, start a remote delete job, leave the host in both +// panes while it runs: no panic or race, the job finishes. +func TestQARemoteMirrorDeleteJobAndLeave(t *testing.T) { + rdir := t.TempDir() + for i := 0; i < 30; i++ { + writeFile(t, filepath.Join(rdir, "victim", fmt.Sprintf("f%02d", i)), "x") + } + writeFile(t, filepath.Join(rdir, "keep.txt"), "k") + m := newTestModel(t, t.TempDir(), t.TempDir()) + c := connectTestHost(t) + mountRemote(t, &m, PaneLeft, c, "/") + p := m.paneByID(PaneLeft) + p.Path = rdir + if err := m.reloadRemotePane(PaneLeft, ""); err != nil { + t.Fatal(err) + } + d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond)) + d.Settle(settle) + d.Press("p") // mirror + d.Settle(settle) + selectName(t, d, "victim") + d.Press("f8", "enter", "b") // job holds a reference; send it to the background + for i := 0; i < 20 && activeOf(t, d).InRemote(); i++ { + d.Press("backspace") + } + d.Press("tab") + for i := 0; i < 20 && activeOf(t, d).InRemote(); i++ { + d.Press("backspace") + } + d.Settle(20 * time.Second) + if exists(filepath.Join(rdir, "victim")) { + t.Fatalf("delete job did not finish (status %q)", cur(t, d).status) + } + if !exists(filepath.Join(rdir, "keep.txt")) { + t.Fatal("keep.txt removed") + } + deadline := time.Now().Add(5 * time.Second) + for c.IsConnected() && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if c.IsConnected() { + t.Fatalf("client still open after both panes left and the job ended (users=%d)", c.Users()) + } +} + +// A single known_hosts line with a key type x/crypto/ssh does not know +// (OpenSSH 10 post-quantum "ssh-mldsa44-ed25519", present on the +// maintainer's machine) makes every connection fail with "parse known_hosts". +func TestQAKnownHostsUnknownAlgorithm(t *testing.T) { + isolateEnv(t) + kh := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts") + writeFile(t, kh, "otherhost ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA\n") + srv := sshtest.Start(t, sshtest.Options{}) + c, err := remote.Connect(remote.SSHHost{Name: "h", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password}) + if err != nil { + t.Fatalf("connect fails because of an unrelated known_hosts line: %v", err) + } + c.Close() +} diff --git a/internal/ui/smoke_test.go b/internal/ui/smoke_test.go new file mode 100644 index 0000000..635423f --- /dev/null +++ b/internal/ui/smoke_test.go @@ -0,0 +1,178 @@ +package ui + +// Behavioural smoke tests for the old UI: keys in, effect on disk and on the +// screen out. They avoid model internals where possible so they can be +// re-pointed at the new UI later. + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +func exists(p string) bool { _, err := os.Lstat(p); return err == nil } + +func TestSmokeNavigateIntoDirAndBack(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.txt"), "hello") + writeFile(t, filepath.Join(dir, "sub", "inner.txt"), "b") + d := newDriver(t, dir, t.TempDir()) + + selectName(t, d, "sub") + d.Press("enter") + d.Settle(settle) + if got := activeOf(t, d).Path; got != filepath.Join(dir, "sub") { + t.Fatalf("after Enter path=%q", got) + } + if !d.ScreenContains("inner.txt") { + t.Fatalf("inner.txt not on screen:\n%s", d.Screen()) + } + + d.Press("backspace") + d.Settle(settle) + if got := activeOf(t, d).Path; got != dir { + t.Fatalf("after Backspace path=%q", got) + } + if got := selectedEntryName(t, d); got != "sub" { + t.Fatalf("cursor should return to sub, got %q", got) + } + if !d.ScreenContains("a.txt") { + t.Fatalf("a.txt not on screen:\n%s", d.Screen()) + } +} + +func TestSmokeMkdir(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("newdir") + d.Press("enter") + d.Settle(settle) + if st, err := os.Stat(filepath.Join(dir, "newdir")); err != nil || !st.IsDir() { + t.Fatalf("newdir not created: %v", err) + } + if !d.ScreenContains("newdir/") { + t.Fatalf("newdir not on screen:\n%s", d.Screen()) + } + if got := selectedEntryName(t, d); got != "newdir" { + t.Fatalf("cursor on %q, want newdir", got) + } +} + +func TestSmokeMkdirCyrillic(t *testing.T) { + dir := t.TempDir() + d := newDriver(t, dir, t.TempDir()) + d.Press("f7") + d.Type("папка") + d.Press("enter") + d.Settle(settle) + if !exists(filepath.Join(dir, "папка")) { + entries, _ := os.ReadDir(dir) + t.Fatalf("папка not created; dir has %v", entries) + } +} + +func TestSmokeCopyFile(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(src, "a.txt"), "payload") + d := newDriver(t, src, dst) + selectName(t, d, "a.txt") + d.Press("f5") + d.Settle(settle) + d.Press("enter") + d.Settle(settle) + b, err := os.ReadFile(filepath.Join(dst, "a.txt")) + if err != nil || string(b) != "payload" { + t.Fatalf("copy result: %q %v", b, err) + } + if !exists(filepath.Join(src, "a.txt")) { + t.Fatal("source disappeared after copy") + } + if n := strings.Count(d.Screen(), "a.txt"); n < 2 { + t.Fatalf("a.txt should be visible in both panes (%d):\n%s", n, d.Screen()) + } +} + +func TestSmokeRename(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "old.txt"), "x") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "old.txt") + d.Press("f2", "ctrl+u") + d.Type("new.txt") + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(dir, "old.txt")) || !exists(filepath.Join(dir, "new.txt")) { + t.Fatal("rename did not happen on disk") + } + if !d.ScreenContains("new.txt") || d.ScreenContains("old.txt") { + t.Fatalf("screen not updated:\n%s", d.Screen()) + } +} + +func TestSmokeFilterNarrowsList(t *testing.T) { + dir := t.TempDir() + for _, n := range []string{"a1", "b1", "b2", "c1", "zz-target"} { + writeFile(t, filepath.Join(dir, n), "x") + } + d := newDriver(t, dir, t.TempDir()) + if !d.ScreenContains("b2") { + t.Fatalf("b2 should be visible before filtering:\n%s", d.Screen()) + } + d.Press("/") + d.Type("zz") + d.Settle(settle) + s := d.Screen() + if !strings.Contains(s, "zz-target") { + t.Fatalf("zz-target hidden by filter:\n%s", s) + } + for _, n := range []string{"a1", "b1", "b2", "c1"} { + if strings.Contains(s, " "+n+" ") || strings.Contains(s, "] "+n) { + t.Fatalf("%s still visible with filter zz:\n%s", n, s) + } + } +} + +func TestSmokeDeleteWithConfirm(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "victim.txt"), "x") + writeFile(t, filepath.Join(dir, "keep.txt"), "y") + d := newDriver(t, dir, t.TempDir()) + selectName(t, d, "victim.txt") + d.Press("f8") + d.Settle(settle) + if !exists(filepath.Join(dir, "victim.txt")) { + t.Fatal("deleted before confirmation") + } + d.Press("enter") + d.Settle(settle) + if exists(filepath.Join(dir, "victim.txt")) { + t.Fatal("victim.txt still on disk after confirmed delete") + } + if !exists(filepath.Join(dir, "keep.txt")) { + t.Fatal("keep.txt removed") + } + if d.ScreenContains("victim.txt") { + t.Fatalf("victim.txt still on screen:\n%s", d.Screen()) + } +} + +func TestSmokePageDown(t *testing.T) { + dir := t.TempDir() + for i := 0; i < 200; i++ { + writeFile(t, filepath.Join(dir, fmt.Sprintf("f%03d", i)), "x") + } + d := newDriver(t, dir, t.TempDir()) + before := activeOf(t, d).Cursor + d.Press("pgdown") + d.Settle(settle) + after := activeOf(t, d).Cursor + if after <= before+5 { + t.Fatalf("PgDn moved cursor %d -> %d", before, after) + } + if !d.ScreenContains(fmt.Sprintf("f%03d", after-1)) { + t.Fatalf("list did not scroll to the cursor:\n%s", d.Screen()) + } +} diff --git a/internal/vfs/archivefs/archivefs.go b/internal/vfs/archivefs/archivefs.go new file mode 100644 index 0000000..59d5a80 --- /dev/null +++ b/internal/vfs/archivefs/archivefs.go @@ -0,0 +1,303 @@ +// Package archivefs is a read-only vfs.FS over an archive index (design +// §2.5). Mounting builds an index; nothing is unpacked to a temp directory, +// so a write "into the archive" cannot silently land in /tmp (U-P0-2): every +// mutating method returns vfs.ErrReadOnly. Paths are virtual posix paths +// ("/dir/file"). +package archivefs + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "path" + "strings" + "time" + + "vcom/internal/archive" + "vcom/internal/vfs" +) + +// FS is a mounted archive. +type FS struct { + outer vfs.FS + path string + idx *archive.Index + children map[string][]archive.Entry // parent key ("" = root) → entries +} + +var _ vfs.FS = (*FS)(nil) + +// Mount indexes archivePath on outer (one pass; progress gets the member +// count) and returns the FS. +func Mount(ctx context.Context, outer vfs.FS, archivePath string, progress func(n int)) (*FS, error) { + idx, err := archive.IndexFile(ctx, outer, archivePath, progress) + if err != nil { + return nil, err + } + return New(outer, archivePath, idx), nil +} + +// New wraps an existing index. +func New(outer vfs.FS, archivePath string, idx *archive.Index) *FS { + f := &FS{outer: outer, path: archivePath, idx: idx, children: map[string][]archive.Entry{}} + for _, e := range idx.Entries { + parent := path.Dir(e.Path) + if parent == "." { + parent = "" + } + f.children[parent] = append(f.children[parent], e) + } + return f +} + +// Index returns the archive index; ArchivePath and Outer where it lives. +func (f *FS) Index() *archive.Index { return f.idx } +func (f *FS) ArchivePath() string { return f.path } +func (f *FS) Outer() vfs.FS { return f.outer } + +func (f *FS) Kind() vfs.Kind { return vfs.KindArchive } +func (f *FS) Volume() vfs.VolumeID { + return vfs.VolumeID("archive:" + string(f.outer.Volume()) + ":" + f.path) +} +func (f *FS) Caps() vfs.Caps { return vfs.Caps{ReadOnly: true, Symlinks: true} } +func (f *FS) Label() string { return f.outer.Paths().Base(f.path) } +func (f *FS) Paths() vfs.PathOps { return vfs.PosixPaths } + +func key(p string) string { return strings.Trim(path.Clean("/"+p), "/") } + +var rootEntry = archive.Entry{Path: "", Mode: fs.ModeDir | 0o555} + +func (f *FS) lookup(k string) (archive.Entry, bool) { + if k == "" { + return rootEntry, true + } + return f.idx.Lookup(k) +} + +func notExist(op, p string) error { return &fs.PathError{Op: op, Path: p, Err: vfs.ErrNotExist} } + +const maxLinks = 40 + +// resolve returns the key of p with every symlink (also the last one, if +// follow) resolved inside the archive. Absolute links and links leaving the +// archive root are broken. +func (f *FS) resolve(p string, follow bool, depth int) (string, error) { + if depth > maxLinks { + return "", errors.New("too many levels of symbolic links") + } + k := key(p) + if k == "" { + return "", nil + } + parts := strings.Split(k, "/") + cur := "" + for i, part := range parts { + next := part + if cur != "" { + next = cur + "/" + part + } + e, ok := f.lookup(next) + if !ok { + return "", vfs.ErrNotExist + } + last := i == len(parts)-1 + if e.IsSymlink() && (!last || follow) { + if path.IsAbs(e.Link) { + return "", vfs.ErrNotExist + } + target := path.Join(cur, e.Link) // relative to the link's directory + if target == ".." || strings.HasPrefix(target, "../") { + return "", vfs.ErrNotExist // leaves the archive + } + r, err := f.resolve(target, true, depth+1) + if err != nil { + return "", err + } + cur = r + continue + } + if !last && !e.IsDir() { + return "", vfs.ErrNotExist + } + cur = next + } + return cur, nil +} + +func info(name string, e archive.Entry) vfs.FileInfo { + return vfs.FileInfo{Name: name, Size: e.Size, Mode: e.Mode, ModTime: e.ModTime} +} + +func baseName(p string) string { + if b := path.Base("/" + p); b != "" { + return b + } + return "/" +} + +func (f *FS) withTarget(fi vfs.FileInfo, e archive.Entry) vfs.FileInfo { + if !e.IsSymlink() { + return fi + } + r, err := f.resolve(e.Path, true, 0) + if err != nil { + fi.LinkErr = err + return fi + } + t, _ := f.lookup(r) + ti := info(fi.Name, t) + fi.Target = &ti + return fi +} + +func (f *FS) Stat(_ context.Context, p string) (vfs.FileInfo, error) { + k, err := f.resolve(p, true, 0) + if err != nil { + return vfs.FileInfo{}, &fs.PathError{Op: "stat", Path: p, Err: err} + } + e, _ := f.lookup(k) + return info(baseName(p), e), nil +} + +func (f *FS) Lstat(_ context.Context, p string) (vfs.FileInfo, error) { + k, err := f.resolve(p, false, 0) + if err != nil { + return vfs.FileInfo{}, &fs.PathError{Op: "lstat", Path: p, Err: err} + } + e, _ := f.lookup(k) + return f.withTarget(info(baseName(p), e), e), nil +} + +func (f *FS) ReadDir(_ context.Context, p string) ([]vfs.FileInfo, error) { + k, err := f.resolve(p, true, 0) + if err != nil { + return nil, &fs.PathError{Op: "readdir", Path: p, Err: err} + } + if e, _ := f.lookup(k); !e.IsDir() { + return nil, &fs.PathError{Op: "readdir", Path: p, Err: errors.New("not a directory")} + } + kids := f.children[k] + out := make([]vfs.FileInfo, 0, len(kids)) + for _, e := range kids { + out = append(out, f.withTarget(info(path.Base(e.Path), e), e)) + } + return out, nil +} + +func (f *FS) ReadLink(_ context.Context, p string) (string, error) { + k, err := f.resolve(p, false, 0) + if err != nil { + return "", &fs.PathError{Op: "readlink", Path: p, Err: err} + } + e, _ := f.lookup(k) + if !e.IsSymlink() { + return "", &fs.PathError{Op: "readlink", Path: p, Err: errors.New("not a symlink")} + } + return e.Link, nil +} + +func (f *FS) RealPath(_ context.Context, p string) (string, error) { + k, err := f.resolve(p, true, 0) + if err != nil { + return "", &fs.PathError{Op: "realpath", Path: p, Err: err} + } + return "/" + k, nil +} + +// Open opens a regular member. Read is sequential; ReadAt re-reads from the +// start when it has to go backwards. +func (f *FS) Open(ctx context.Context, p string) (vfs.File, error) { + k, err := f.resolve(p, true, 0) + if err != nil { + return nil, &fs.PathError{Op: "open", Path: p, Err: err} + } + e, _ := f.lookup(k) + if !e.IsRegular() { + return nil, &fs.PathError{Op: "open", Path: p, Err: fmt.Errorf("not a regular file")} + } + m := &member{fs: f, ctx: context.WithoutCancel(ctx), key: k, fi: info(baseName(p), e)} + if err := m.reopen(); err != nil { + return nil, err + } + return m, nil +} + +func roErr(op, p string) error { return &fs.PathError{Op: op, Path: p, Err: vfs.ErrReadOnly} } + +func (f *FS) Create(_ context.Context, p string, _ fs.FileMode, _ vfs.CreateMode) (vfs.File, error) { + return nil, roErr("create", p) +} +func (f *FS) Mkdir(_ context.Context, p string, _ fs.FileMode) error { return roErr("mkdir", p) } +func (f *FS) Remove(_ context.Context, p string) error { return roErr("remove", p) } +func (f *FS) Rename(_ context.Context, from, _ string, _ vfs.RenameMode) error { + return roErr("rename", from) +} +func (f *FS) Symlink(_ context.Context, _, p string) error { return roErr("symlink", p) } +func (f *FS) Chmod(_ context.Context, p string, _ fs.FileMode) error { return roErr("chmod", p) } +func (f *FS) Chtimes(_ context.Context, p string, _, _ time.Time) error { + return roErr("chtimes", p) +} + +type member struct { + fs *FS + ctx context.Context + key string + fi vfs.FileInfo + rc io.ReadCloser + pos int64 +} + +func (m *member) reopen() error { + if m.rc != nil { + m.rc.Close() + } + rc, err := archive.OpenMember(m.ctx, m.fs.outer, m.fs.path, m.fs.idx, m.key) + if err != nil { + m.rc = nil + return err + } + m.rc, m.pos = rc, 0 + return nil +} + +func (m *member) Read(p []byte) (int, error) { + if m.rc == nil { + return 0, fs.ErrClosed + } + n, err := m.rc.Read(p) + m.pos += int64(n) + return n, err +} + +func (m *member) ReadAt(p []byte, off int64) (int, error) { + if off < m.pos { + if err := m.reopen(); err != nil { + return 0, err + } + } + if off > m.pos { + if _, err := io.CopyN(io.Discard, m, off-m.pos); err != nil { + return 0, err + } + } + n, err := io.ReadFull(m, p) + if err == io.ErrUnexpectedEOF { + err = io.EOF + } + return n, err +} + +func (m *member) Stat() (vfs.FileInfo, error) { return m.fi, nil } +func (m *member) Write([]byte) (int, error) { return 0, vfs.ErrReadOnly } +func (m *member) Sync() error { return vfs.ErrUnsupported } + +func (m *member) Close() error { + if m.rc == nil { + return nil + } + err := m.rc.Close() + m.rc = nil + return err +} diff --git a/internal/vfs/archivefs/archivefs_test.go b/internal/vfs/archivefs/archivefs_test.go new file mode 100644 index 0000000..ba619e4 --- /dev/null +++ b/internal/vfs/archivefs/archivefs_test.go @@ -0,0 +1,206 @@ +package archivefs + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "testing" + "time" + + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +var bg = context.Background() + +// fixtureArchive writes vfstest.ReadOnlyFixture as /fixture.. +func fixtureArchive(t *testing.T, ext string) string { + t.Helper() + var buf bytes.Buffer + mt := time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC) + if ext == ".zip" { + zw := zip.NewWriter(&buf) + for _, e := range vfstest.ReadOnlyFixture { + h := &zip.FileHeader{Name: e.Path, Modified: mt, Method: zip.Deflate} + body := e.Content + switch { + case e.Dir: + h.Name += "/" + h.SetMode(fs.ModeDir | 0o755) + case e.Link != "": + h.SetMode(fs.ModeSymlink | 0o777) + body = e.Link + default: + h.SetMode(0o644) + } + w, err := zw.CreateHeader(h) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write([]byte(body)); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + } else { + var gz *gzip.Writer + tw := tar.NewWriter(&buf) + if ext == ".tar.gz" { + gz = gzip.NewWriter(&buf) + tw = tar.NewWriter(gz) + } + for _, e := range vfstest.ReadOnlyFixture { + h := &tar.Header{Name: e.Path, ModTime: mt, Mode: 0o644, Typeflag: tar.TypeReg, Size: int64(len(e.Content))} + switch { + case e.Dir: + h.Typeflag, h.Mode, h.Size = tar.TypeDir, 0o755, 0 + case e.Link != "": + h.Typeflag, h.Linkname, h.Size = tar.TypeSymlink, e.Link, 0 + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if _, err := tw.Write([]byte(e.Content)); err != nil && h.Size > 0 { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if gz != nil { + if err := gz.Close(); err != nil { + t.Fatal(err) + } + } + } + p := filepath.Join(t.TempDir(), "fixture"+ext) + if err := os.WriteFile(p, buf.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + return p +} + +func TestReadOnlyConformance(t *testing.T) { + for _, ext := range []string{".zip", ".tar", ".tar.gz"} { + t.Run(ext, func(t *testing.T) { + fsys, err := Mount(bg, localfs.New(), fixtureArchive(t, ext), nil) + if err != nil { + t.Fatal(err) + } + vfstest.RunReadOnly(t, fsys, "/") + }) + } +} + +func TestArchiveFSMutationsReadOnly(t *testing.T) { + arch := fixtureArchive(t, ".zip") + before, _ := os.ReadFile(arch) + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) + fsys, err := Mount(bg, localfs.New(), arch, nil) + if err != nil { + t.Fatal(err) + } + if !fsys.Caps().ReadOnly || fsys.Kind() != vfs.KindArchive { + t.Fatalf("caps %+v kind %v", fsys.Caps(), fsys.Kind()) + } + // U-P0-2: the old code wrote "into the archive" in a temp copy and lost it. + _, err = fsys.Create(bg, "/d/new.txt", 0o644, vfs.CreateExcl) + if !errors.Is(err, vfs.ErrReadOnly) { + t.Fatalf("create: %v", err) + } + for _, err := range []error{ + fsys.Mkdir(bg, "/nd", 0o755), + fsys.Rename(bg, "/f", "/g", vfs.Replace), + fsys.Remove(bg, "/d/inner"), + } { + if !errors.Is(err, vfs.ErrReadOnly) { + t.Fatalf("mutation: %v", err) + } + } + if ro := vfs.ReadOnly(fsys); ro.Caps().ReadOnly != true { + t.Fatal("wrapping keeps read-only") + } + after, _ := os.ReadFile(arch) + if !bytes.Equal(before, after) { + t.Fatal("archive file changed") + } + if ents, _ := os.ReadDir(tmp); len(ents) != 0 { + t.Fatalf("temp files: %v", ents) + } + if want := vfs.VolumeID("archive:local:" + arch); fsys.Volume() != want { + t.Fatalf("volume %q", fsys.Volume()) + } + if fsys.Label() != "fixture.zip" { + t.Fatalf("label %q", fsys.Label()) + } +} + +func TestNoTempDirOnMount(t *testing.T) { + for _, ext := range []string{".zip", ".tar.gz"} { + arch := fixtureArchive(t, ext) + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) + fsys, err := Mount(bg, localfs.New(), arch, nil) + if err != nil { + t.Fatal(err) + } + f, err := fsys.Open(bg, "/big") + if err != nil { + t.Fatal(err) + } + buf := make([]byte, 100) + if _, err := f.ReadAt(buf, 500); err != nil { + t.Fatal(err) + } + f.Close() + if _, err := fsys.ReadDir(bg, "/d"); err != nil { + t.Fatal(err) + } + if ents, _ := os.ReadDir(tmp); len(ents) != 0 { + t.Fatalf("%s: mount/open created %v in TMPDIR", ext, ents) + } + } +} + +func TestEscapingLinksAreBroken(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, h := range []*tar.Header{ + {Name: "abs", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd"}, + {Name: "d/up", Typeflag: tar.TypeSymlink, Linkname: "../../outside"}, + {Name: "d/ok", Typeflag: tar.TypeSymlink, Linkname: "../f"}, + {Name: "f", Typeflag: tar.TypeReg, Size: 1, Mode: 0o644}, + } { + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if h.Size > 0 { + _, _ = tw.Write([]byte("x")) + } + } + tw.Close() + p := filepath.Join(t.TempDir(), "esc.tar") + _ = os.WriteFile(p, buf.Bytes(), 0o644) + fsys, err := Mount(bg, localfs.New(), p, nil) + if err != nil { + t.Fatal(err) + } + for _, l := range []string{"/abs", "/d/up"} { + if _, err := fsys.Stat(bg, l); !errors.Is(err, vfs.ErrNotExist) { + t.Errorf("%s resolved outside the archive: %v", l, err) + } + } + if fi, err := fsys.Stat(bg, "/d/ok"); err != nil || fi.Size != 1 { + t.Fatalf("in-archive link: %+v %v", fi, err) + } +} diff --git a/internal/vfs/errors.go b/internal/vfs/errors.go new file mode 100644 index 0000000..e04aea5 --- /dev/null +++ b/internal/vfs/errors.go @@ -0,0 +1,35 @@ +package vfs + +import ( + "context" + "errors" + "io/fs" +) + +// Sentinel errors, checked with errors.Is. Implementations map their native +// errors (errno, SFTP status codes) onto these, so the UI and transfer never +// see *sftp.StatusError. +// +// ErrNotExist, ErrExist and ErrPermission are the io/fs sentinels and +// ErrUnsupported is errors.ErrUnsupported, so *os.PathError values from the +// local disk already match without wrapping. ErrCancelled is context.Canceled. +var ( + ErrNotExist = fs.ErrNotExist + ErrExist = fs.ErrExist + ErrPermission = fs.ErrPermission + ErrUnsupported = errors.ErrUnsupported + ErrCancelled = context.Canceled + + // ErrReadOnly: the FS (or the volume behind it) does not allow writes. + ErrReadOnly = errors.New("read-only file system") + // ErrConnLost: the connection died; the operation may be retried after + // a reconnect. + ErrConnLost = errors.New("connection lost") +) + +// SkipDir and SkipAll are returned by a WalkFunc to skip a directory's +// contents or stop the walk without an error. +var ( + SkipDir = fs.SkipDir + SkipAll = fs.SkipAll +) diff --git a/internal/vfs/fileinfo.go b/internal/vfs/fileinfo.go new file mode 100644 index 0000000..12db09f --- /dev/null +++ b/internal/vfs/fileinfo.go @@ -0,0 +1,36 @@ +package vfs + +import ( + "io/fs" + "time" +) + +// FileInfo describes one directory entry with lstat semantics. +type FileInfo struct { + Name string + Size int64 + Mode fs.FileMode // as from Lstat: ModeSymlink, ModeDir, ModeNamedPipe, ... + ModTime time.Time + // Target is the Stat of a symlink's target; nil if the link is broken or + // the target was not resolved. LinkErr says why it is nil. + Target *FileInfo + LinkErr error +} + +// IsDir reports whether the entry itself is a directory (not a link to one). +func (fi FileInfo) IsDir() bool { return fi.Mode.IsDir() } + +// IsSymlink reports whether the entry is a symbolic link. +func (fi FileInfo) IsSymlink() bool { return fi.Mode&fs.ModeSymlink != 0 } + +// NavigableDir reports whether a panel can enter the entry: a directory or a +// symlink whose target is a directory (U-P1-2). +func (fi FileInfo) NavigableDir() bool { + return fi.IsDir() || (fi.IsSymlink() && fi.Target != nil && fi.Target.IsDir()) +} + +// IsRegularLike reports whether the entry is a regular file or a symlink to +// one. FIFOs, devices and sockets are not. +func (fi FileInfo) IsRegularLike() bool { + return fi.Mode.IsRegular() || (fi.IsSymlink() && fi.Target != nil && fi.Target.Mode.IsRegular()) +} diff --git a/internal/vfs/fs.go b/internal/vfs/fs.go new file mode 100644 index 0000000..e782992 --- /dev/null +++ b/internal/vfs/fs.go @@ -0,0 +1,138 @@ +// Package vfs is the file-system abstraction every panel, transfer and preview +// works through (design §2). One interface covers the local disk (localfs), +// SFTP (sftpfs) and read-only archives (archivefs); the helpers in this package +// (Walk, RemoveTree, DirSize, SameFile, Within) are written once against it. +// +// All methods take a context. LocalFS mostly ignores it; SFTPFS uses it to stop +// waiting on a hung server. Paths are interpreted by FS.Paths(): posix for sftp +// and archives, the native separator for local. +package vfs + +import ( + "context" + "io" + "io/fs" + "time" +) + +// Kind identifies the implementation behind an FS. +type Kind uint8 + +const ( + KindLocal Kind = iota + KindSFTP + KindArchive +) + +func (k Kind) String() string { + switch k { + case KindLocal: + return "local" + case KindSFTP: + return "sftp" + case KindArchive: + return "archive" + } + return "unknown" +} + +// VolumeID: equal VolumeIDs mean "the same file namespace" (best effort). +// local: "local"; sftp: "ssh:" + SHA256 host-key fingerprint (not the HostName +// string — N-P0-5); archive: "archive:" + outer VolumeID + ":" + archive path. +type VolumeID string + +// Caps describes what an FS can do. Callers check Caps instead of Kind. +type Caps struct { + ReadOnly bool // all mutating methods return ErrReadOnly + AtomicReplace bool // Rename(..., Replace) is atomic (local: rename(2); sftp: posix-rename@openssh.com) + NoReplace bool // Rename(..., NoReplace) is atomic (local: renameat2 RENAME_NOREPLACE; sftp: SSH_FXP_RENAME v3) + Symlinks bool + Chmod bool + Chtimes bool + Fsync bool // File.Sync works (local: yes; sftp: fsync@openssh.com) + Trash bool // the FS implements Trasher + Exec bool // files can be executed (local only) +} + +// RenameMode selects what Rename does when the target exists. +type RenameMode uint8 + +const ( + // NoReplace fails with ErrExist if the target exists. + NoReplace RenameMode = iota + // Replace atomically replaces an existing target where Caps.AtomicReplace. + Replace +) + +// CreateMode selects what Create does when the file exists. +type CreateMode uint8 + +const ( + // CreateExcl fails with ErrExist if the file exists (the transfer engine + // only uses this, for its temp files). + CreateExcl CreateMode = iota + // CreateTrunc truncates an existing file. + CreateTrunc +) + +// File is an open file. Sync returns ErrUnsupported when !Caps.Fsync. +type File interface { + io.Reader + io.Writer + io.ReaderAt + io.Closer + Stat() (FileInfo, error) + Sync() error +} + +// FS is one file namespace. +type FS interface { + Kind() Kind + Volume() VolumeID + Caps() Caps + Label() string // for the UI: "local", "bob@prod", "foo.zip" + Paths() PathOps // path rules: posix (sftp, archive) or native (local) + + // Stat follows symlinks; Lstat does not. For a symlink Lstat also fills + // FileInfo.Target the same way ReadDir does. + Stat(ctx context.Context, p string) (FileInfo, error) + Lstat(ctx context.Context, p string) (FileInfo, error) + // ReadDir has lstat semantics; for symlinks the implementation fills + // Target (local: Stat; sftp: parallel Stat, at most 16 in flight). + // The order is unspecified; the panel sorts. + ReadDir(ctx context.Context, p string) ([]FileInfo, error) + ReadLink(ctx context.Context, p string) (string, error) + // RealPath returns the absolute path with all symlinks resolved. + RealPath(ctx context.Context, p string) (string, error) + + Open(ctx context.Context, p string) (File, error) + Create(ctx context.Context, p string, perm fs.FileMode, mode CreateMode) (File, error) + Mkdir(ctx context.Context, p string, perm fs.FileMode) error + // Remove deletes a file, a symlink or an EMPTY directory. It never + // follows symlinks. + Remove(ctx context.Context, p string) error + Rename(ctx context.Context, from, to string, mode RenameMode) error + Symlink(ctx context.Context, target, p string) error + Chmod(ctx context.Context, p string, mode fs.FileMode) error + Chtimes(ctx context.Context, p string, atime, mtime time.Time) error +} + +// Optional capabilities, discovered by type assertion. + +// Trasher moves p to the FS's trash (local: freedesktop trash). +type Trasher interface { + Trash(ctx context.Context, p string) error +} + +// BirthTimer reports the creation time of p, if the FS knows it. ReadDir does +// not compute it (it is expensive); callers ask only when a "created" column or +// sort is enabled. +type BirthTimer interface { + BirthTime(ctx context.Context, p string) (time.Time, bool) +} + +// Execer runs a command next to the files (sftpfs over a conn with exec), for +// server-side transfer optimisations. The implementation quotes arguments. +type Execer interface { + Exec(ctx context.Context, argv []string) (stdout []byte, err error) +} diff --git a/internal/vfs/helpers_test.go b/internal/vfs/helpers_test.go new file mode 100644 index 0000000..81cad09 --- /dev/null +++ b/internal/vfs/helpers_test.go @@ -0,0 +1,268 @@ +package vfs_test + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" +) + +var ctx = context.Background() + +func TestRemoveTreeSymlinkToDirKeepsTarget(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.File("data/precious", "keep me"), + fstree.File("data/sub/also", "keep"), + fstree.Symlink("link", "data"), + fstree.File("tree/f", "x"), + fstree.Symlink("tree/inner", "../data"), + }) + fsys := localfs.New() + + // Root is a symlink to a directory: only the link goes. + if err := vfs.RemoveTree(ctx, fsys, filepath.Join(dir, "link"), nil); err != nil { + t.Fatal(err) + } + // A tree containing a link to a directory: the link is unlinked, not walked. + if err := vfs.RemoveTree(ctx, fsys, filepath.Join(dir, "tree"), nil); err != nil { + t.Fatal(err) + } + fstree.Equal(t, fstree.FromSpec(fstree.Spec{ + fstree.File("data/precious", "keep me"), + fstree.File("data/sub/also", "keep"), + }), fstree.Snapshot(t, dir), fstree.Opts{Links: true}) +} + +func TestRemoveTreeCancel(t *testing.T) { + dir := t.TempDir() + var spec fstree.Spec + for i := range 20 { + spec = append(spec, fstree.File(fmt.Sprintf("big/f%02d", i), "x")) + } + fstree.Build(t, dir, spec) + c, cancel := context.WithCancel(ctx) + defer cancel() + removed := 0 + err := vfs.RemoveTree(c, localfs.New(), filepath.Join(dir, "big"), func(n int) { + removed = n + if n == 3 { + cancel() + } + }) + if !errors.Is(err, vfs.ErrCancelled) { + t.Fatalf("err = %v, want ErrCancelled", err) + } + if removed != 3 { + t.Fatalf("removed %d after cancel, want 3", removed) + } + left, _ := os.ReadDir(filepath.Join(dir, "big")) + if len(left) != 17 { + t.Fatalf("%d entries left, want 17", len(left)) + } +} + +func TestRemoveTreeProgressAndNonEmpty(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("a/b/c", ""), fstree.File("a/d", "")}) + var last int + if err := vfs.RemoveTree(ctx, localfs.New(), filepath.Join(dir, "a"), func(n int) { last = n }); err != nil { + t.Fatal(err) + } + if last != 4 { // c, b, d, a + t.Fatalf("progress = %d, want 4", last) + } + if _, err := os.Lstat(filepath.Join(dir, "a")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("tree still there") + } + if err := vfs.RemoveTree(ctx, localfs.New(), filepath.Join(dir, "missing"), nil); !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("missing root: %v", err) + } +} + +func TestDirSizeRootError(t *testing.T) { + dir := t.TempDir() + _, err := vfs.DirSize(ctx, localfs.New(), filepath.Join(dir, "missing"), nil) + if !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("missing root: err = %v, want ErrNotExist (not a silent 0 B)", err) + } + if os.Geteuid() != 0 { + fstree.Build(t, dir, fstree.Spec{fstree.File("locked/f", "x")}) + lock(t, filepath.Join(dir, "locked")) + if _, err := vfs.DirSize(ctx, localfs.New(), filepath.Join(dir, "locked"), nil); !errors.Is(err, vfs.ErrPermission) { + t.Fatalf("unreadable root: err = %v, want ErrPermission", err) + } + } + c, cancel := context.WithCancel(ctx) + cancel() + if _, err := vfs.DirSize(c, localfs.New(), dir, nil); !errors.Is(err, vfs.ErrCancelled) { + t.Fatalf("cancelled: %v", err) + } +} + +// lock makes dir unreadable (mode 0) until the test ends. +func lock(t *testing.T, dir string) { + t.Helper() + if err := os.Chmod(dir, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) +} + +func TestDirSizeCountsUnreadable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads mode-0 directories") + } + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.File("a.bin", "").WithSize(100), + fstree.File("ok/b.bin", "").WithSize(20), + fstree.File("locked/hidden", "").WithSize(1000), + fstree.Symlink("ln", "a.bin"), + }) + lock(t, filepath.Join(dir, "locked")) + var calls int + r, err := vfs.DirSize(ctx, localfs.New(), dir, func(vfs.SizeResult) { calls++ }) + if err != nil { + t.Fatal(err) + } + want := vfs.SizeResult{Bytes: 100 + 20 + int64(len("a.bin")), Files: 3, Dirs: 2, Unreadable: 1} + if r != want { + t.Fatalf("got %+v, want %+v", r, want) + } + if calls == 0 { + t.Fatal("no progress") + } +} + +func TestSameFileSymlinkAlias(t *testing.T) { + home := t.TempDir() + fstree.Build(t, home, fstree.Spec{ + fstree.File("real/f.txt", "data"), + fstree.File("other/f.txt", "data"), + fstree.Symlink("alias", "real"), + }) + fsys := localfs.New() + same, err := vfs.SameFile(ctx, fsys, filepath.Join(home, "real", "f.txt"), fsys, filepath.Join(home, "alias", "f.txt")) + if err != nil || !same { + t.Fatalf("~/real/f.txt vs ~/alias/f.txt: same=%v err=%v, want true (N-P0-6)", same, err) + } + same, err = vfs.SameFile(ctx, fsys, filepath.Join(home, "real"), fsys, filepath.Join(home, "alias")) + if err != nil || !same { + t.Fatalf("dir vs its alias: %v %v", same, err) + } + same, err = vfs.SameFile(ctx, fsys, filepath.Join(home, "real", "f.txt"), fsys, filepath.Join(home, "other", "f.txt")) + if err != nil || same { + t.Fatalf("equal content is not identity: %v %v", same, err) + } + same, err = vfs.SameFile(ctx, fsys, filepath.Join(home, "real", "f.txt"), fsys, filepath.Join(home, "nope")) + if err != nil || same { + t.Fatalf("missing: %v %v", same, err) + } + // Different volume is never the same, even with an identical path. + ro := otherVolume{vfs.ReadOnly(fsys)} + same, err = vfs.SameFile(ctx, fsys, filepath.Join(home, "real"), ro, filepath.Join(home, "real")) + if err != nil || same { + t.Fatalf("different volumes: %v %v", same, err) + } + // Same volume, non-local kind: RealPath comparison. + rp := realPathOnly{vfs.ReadOnly(fsys)} + same, err = vfs.SameFile(ctx, rp, filepath.Join(home, "real", "f.txt"), rp, filepath.Join(home, "alias", "f.txt")) + if err != nil || !same { + t.Fatalf("realpath comparison: %v %v", same, err) + } +} + +type otherVolume struct{ vfs.FS } + +func (otherVolume) Volume() vfs.VolumeID { return "other" } + +type realPathOnly struct{ vfs.FS } + +func (realPathOnly) Kind() vfs.Kind { return vfs.KindSFTP } + +func TestWithinViaSymlink(t *testing.T) { + home := t.TempDir() + fstree.Build(t, home, fstree.Spec{ + fstree.Dir("src/sub"), + fstree.Dir("srcsibling"), + fstree.Symlink("alias", "src"), + fstree.Symlink("sublink", "src/sub"), + }) + fsys := localfs.New() + j := func(p ...string) string { return filepath.Join(append([]string{home}, p...)...) } + cases := []struct { + child, parent string + want bool + }{ + {j("alias", "sub"), j("src"), true}, // through an alias of the parent + {j("sublink"), j("src"), true}, // a link pointing inside + {j("src"), j("alias"), true}, // equal after resolution + {j("alias", "sub", "new", "deeper"), j("src"), true}, // child does not exist yet + {j("srcsibling"), j("src"), false}, // prefix is not containment + {j("src"), j("src", "sub"), false}, + } + for _, c := range cases { + got, err := vfs.Within(ctx, fsys, c.child, c.parent) + if err != nil || got != c.want { + t.Errorf("Within(%s, %s) = %v, %v; want %v", + strings.TrimPrefix(c.child, home), strings.TrimPrefix(c.parent, home), got, err, c.want) + } + } +} + +func TestWalkDoesNotFollowLinks(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.File("root/b", ""), + fstree.File("root/a/x", ""), + fstree.File("root/c/skipme", ""), + fstree.Symlink("root/loop", "."), + fstree.Symlink("root/out", "../outside"), + fstree.File("outside/secret", ""), + }) + root := filepath.Join(dir, "root") + var got []string + err := vfs.Walk(ctx, localfs.New(), root, func(p string, fi vfs.FileInfo, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + kind := "f" + switch { + case fi.IsSymlink(): + kind = "l" + case fi.IsDir(): + kind = "d" + } + got = append(got, kind+":"+filepath.ToSlash(rel)) + if fi.Name == "c" { + return vfs.SkipDir + } + return nil + }) + if err != nil { + t.Fatal(err) + } + want := "d:. d:a f:a/x f:b d:c l:loop l:out" + if strings.Join(got, " ") != want { + t.Fatalf("walk order:\n got %s\nwant %s", strings.Join(got, " "), want) + } + + // Missing root: fn gets the error. + var rootErr error + _ = vfs.Walk(ctx, localfs.New(), filepath.Join(dir, "missing"), func(_ string, _ vfs.FileInfo, err error) error { + rootErr = err + return nil + }) + if !errors.Is(rootErr, vfs.ErrNotExist) { + t.Fatalf("root error = %v", rootErr) + } +} diff --git a/internal/vfs/localfs/birth_linux.go b/internal/vfs/localfs/birth_linux.go new file mode 100644 index 0000000..af6bfe2 --- /dev/null +++ b/internal/vfs/localfs/birth_linux.go @@ -0,0 +1,26 @@ +//go:build linux + +package localfs + +import ( + "context" + "time" + + "golang.org/x/sys/unix" +) + +// statx is a hook so tests can verify ReadDir never asks for birth times. +var statx = unix.Statx + +// BirthTime returns the creation time of p (without following a final +// symlink) when the kernel and file system report it. +func (*FS) BirthTime(_ context.Context, p string) (time.Time, bool) { + var st unix.Statx_t + if err := statx(unix.AT_FDCWD, p, unix.AT_SYMLINK_NOFOLLOW, unix.STATX_BTIME, &st); err != nil { + return time.Time{}, false + } + if st.Mask&unix.STATX_BTIME == 0 { + return time.Time{}, false + } + return time.Unix(st.Btime.Sec, int64(st.Btime.Nsec)), true +} diff --git a/internal/vfs/localfs/birth_other.go b/internal/vfs/localfs/birth_other.go new file mode 100644 index 0000000..6533f45 --- /dev/null +++ b/internal/vfs/localfs/birth_other.go @@ -0,0 +1,11 @@ +//go:build !linux + +package localfs + +import ( + "context" + "time" +) + +// BirthTime is not available on this platform. +func (*FS) BirthTime(context.Context, string) (time.Time, bool) { return time.Time{}, false } diff --git a/internal/vfs/localfs/conformance_test.go b/internal/vfs/localfs/conformance_test.go new file mode 100644 index 0000000..5f41000 --- /dev/null +++ b/internal/vfs/localfs/conformance_test.go @@ -0,0 +1,37 @@ +package localfs_test + +import ( + "os" + "path/filepath" + "testing" + + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +func TestConformance(t *testing.T) { + vfstest.Run(t, func(t *testing.T) (vfs.FS, string) { return localfs.New(), t.TempDir() }) +} + +// The read-only suite itself, on a fixture tree behind vfs.ReadOnly. +func TestReadOnlyConformance(t *testing.T) { + dir := t.TempDir() + for _, e := range vfstest.ReadOnlyFixture { + p := filepath.Join(dir, e.Path) + var err error + switch { + case e.Dir: + err = os.MkdirAll(p, 0o755) + case e.Link != "": + err = os.Symlink(e.Link, p) + default: + _ = os.MkdirAll(filepath.Dir(p), 0o755) + err = os.WriteFile(p, []byte(e.Content), 0o644) + } + if err != nil { + t.Fatal(err) + } + } + vfstest.RunReadOnly(t, vfs.ReadOnly(localfs.New()), dir) +} diff --git a/internal/vfs/localfs/localfs.go b/internal/vfs/localfs/localfs.go new file mode 100644 index 0000000..81cd9c2 --- /dev/null +++ b/internal/vfs/localfs/localfs.go @@ -0,0 +1,218 @@ +// Package localfs implements vfs.FS on the local disk (design §2.3). +package localfs + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "syscall" + "time" + + "vcom/internal/vfs" +) + +// FS is the local file system. The zero value is not usable; call New. +type FS struct { + trash trashConfig +} + +var ( + _ vfs.FS = (*FS)(nil) + _ vfs.Trasher = (*FS)(nil) + _ vfs.BirthTimer = (*FS)(nil) +) + +// New returns the local FS. +func New() *FS { return &FS{trash: defaultTrashConfig()} } + +func (*FS) Kind() vfs.Kind { return vfs.KindLocal } +func (*FS) Volume() vfs.VolumeID { return "local" } +func (*FS) Label() string { return "local" } +func (*FS) Paths() vfs.PathOps { return vfs.NativePaths } +func (*FS) String() string { return "local" } +func (*FS) Caps() vfs.Caps { + return vfs.Caps{ + AtomicReplace: true, + NoReplace: true, + Symlinks: true, + Chmod: true, + Chtimes: true, + Fsync: true, + Trash: true, + Exec: true, + } +} + +// mapErr adds the vfs sentinels that the os errors do not already match: +// EROFS → ErrReadOnly. fs.ErrNotExist/ErrExist/ErrPermission and +// errors.ErrUnsupported match *os.PathError natively. +func mapErr(err error) error { + if err == nil { + return nil + } + if errors.Is(err, syscall.EROFS) { + return fmt.Errorf("%w: %w", vfs.ErrReadOnly, err) + } + return err +} + +func toInfo(name string, fi os.FileInfo) vfs.FileInfo { + return vfs.FileInfo{Name: name, Size: fi.Size(), Mode: fi.Mode(), ModTime: fi.ModTime()} +} + +// withTarget fills Target/LinkErr for a symlink entry at p. +func withTarget(p string, info vfs.FileInfo) vfs.FileInfo { + if !info.IsSymlink() { + return info + } + t, err := os.Stat(p) + if err != nil { + info.LinkErr = mapErr(err) + return info + } + ti := toInfo(info.Name, t) + info.Target = &ti + return info +} + +func (*FS) Stat(_ context.Context, p string) (vfs.FileInfo, error) { + fi, err := os.Stat(p) + if err != nil { + return vfs.FileInfo{}, mapErr(err) + } + return toInfo(filepath.Base(p), fi), nil +} + +func (*FS) Lstat(_ context.Context, p string) (vfs.FileInfo, error) { + fi, err := os.Lstat(p) + if err != nil { + return vfs.FileInfo{}, mapErr(err) + } + return withTarget(p, toInfo(filepath.Base(p), fi)), nil +} + +// ReadDir lists p with lstat semantics and resolves symlink targets. It does +// not compute birth times (see BirthTime). Entries that vanish between the +// listing and their lstat are skipped. +func (*FS) ReadDir(ctx context.Context, p string) ([]vfs.FileInfo, error) { + ents, err := os.ReadDir(p) + if err != nil { + return nil, mapErr(err) + } + out := make([]vfs.FileInfo, 0, len(ents)) + for i, e := range ents { + if i&1023 == 1023 { + if err := ctx.Err(); err != nil { + return nil, err + } + } + fi, err := e.Info() + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + continue + } + return nil, mapErr(err) + } + out = append(out, withTarget(filepath.Join(p, e.Name()), toInfo(e.Name(), fi))) + } + return out, nil +} + +func (*FS) ReadLink(_ context.Context, p string) (string, error) { + s, err := os.Readlink(p) + return s, mapErr(err) +} + +func (*FS) RealPath(_ context.Context, p string) (string, error) { + abs, err := filepath.Abs(p) + if err != nil { + return "", err + } + r, err := filepath.EvalSymlinks(abs) + return r, mapErr(err) +} + +// file adapts *os.File to vfs.File. +type file struct{ *os.File } + +func (f file) Stat() (vfs.FileInfo, error) { + fi, err := f.File.Stat() + if err != nil { + return vfs.FileInfo{}, mapErr(err) + } + return toInfo(filepath.Base(f.Name()), fi), nil +} + +// Open opens p for reading. It does not refuse FIFOs or devices: callers that +// read content (preview, transfer) check IsRegularLike first (U-P1-10). +func (*FS) Open(_ context.Context, p string) (vfs.File, error) { + f, err := os.Open(p) + if err != nil { + return nil, mapErr(err) + } + return file{f}, nil +} + +func (*FS) Create(_ context.Context, p string, perm fs.FileMode, mode vfs.CreateMode) (vfs.File, error) { + flag := os.O_RDWR | os.O_CREATE + switch mode { + case vfs.CreateExcl: + flag |= os.O_EXCL + case vfs.CreateTrunc: + flag |= os.O_TRUNC + default: + return nil, fmt.Errorf("create %s: unknown mode %d", p, mode) + } + f, err := os.OpenFile(p, flag, perm) + if err != nil { + return nil, mapErr(err) + } + return file{f}, nil +} + +func (*FS) Mkdir(_ context.Context, p string, perm fs.FileMode) error { + return mapErr(os.Mkdir(p, perm)) +} + +// Remove unlinks a file or symlink, or removes an empty directory. A link is +// removed itself, never its target. +func (*FS) Remove(_ context.Context, p string) error { + return mapErr(os.Remove(p)) +} + +func (*FS) Rename(_ context.Context, from, to string, mode vfs.RenameMode) error { + switch mode { + case vfs.Replace: + return mapErr(os.Rename(from, to)) + case vfs.NoReplace: + return mapErr(renameNoReplace(from, to)) + } + return fmt.Errorf("rename %s: unknown mode %d", from, mode) +} + +func (*FS) Symlink(_ context.Context, target, p string) error { + return mapErr(os.Symlink(target, p)) +} + +func (*FS) Chmod(_ context.Context, p string, mode fs.FileMode) error { + return mapErr(os.Chmod(p, mode)) +} + +func (*FS) Chtimes(_ context.Context, p string, atime, mtime time.Time) error { + return mapErr(os.Chtimes(p, atime, mtime)) +} + +// renameByCheck is the non-atomic NoReplace fallback: Lstat the target, then +// rename. A file created at `to` between the two calls is replaced (narrow +// TOCTOU window, accepted where the kernel offers nothing better). +func renameByCheck(from, to string) error { + if _, err := os.Lstat(to); err == nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: fs.ErrExist} + } else if !errors.Is(err, fs.ErrNotExist) { + return err + } + return os.Rename(from, to) +} diff --git a/internal/vfs/localfs/localfs_test.go b/internal/vfs/localfs/localfs_test.go new file mode 100644 index 0000000..7bf8677 --- /dev/null +++ b/internal/vfs/localfs/localfs_test.go @@ -0,0 +1,157 @@ +package localfs + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + "golang.org/x/sys/unix" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" +) + +var ctx = context.Background() + +func TestRenameNoReplaceExisting(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.File("src", "new"), + fstree.File("dst", "old"), + fstree.Dir("d1"), + fstree.Dir("d2"), + }) + fsys := New() + err := fsys.Rename(ctx, filepath.Join(dir, "src"), filepath.Join(dir, "dst"), vfs.NoReplace) + if !errors.Is(err, vfs.ErrExist) { + t.Fatalf("rename onto existing file: %v, want ErrExist", err) + } + if b, _ := os.ReadFile(filepath.Join(dir, "dst")); string(b) != "old" { + t.Fatalf("target changed: %q", b) + } + if _, err := os.Stat(filepath.Join(dir, "src")); err != nil { + t.Fatalf("source gone: %v", err) + } + // An empty directory is an existing target too (plain rename(2) would replace it). + if err := fsys.Rename(ctx, filepath.Join(dir, "d1"), filepath.Join(dir, "d2"), vfs.NoReplace); !errors.Is(err, vfs.ErrExist) { + t.Fatalf("rename dir onto empty dir: %v, want ErrExist", err) + } + // The fallbacks keep the same contract. + if err := renameByCheck(filepath.Join(dir, "src"), filepath.Join(dir, "dst")); !errors.Is(err, vfs.ErrExist) { + t.Fatalf("renameByCheck: %v", err) + } + // Free target: moves. + if err := fsys.Rename(ctx, filepath.Join(dir, "src"), filepath.Join(dir, "free"), vfs.NoReplace); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(filepath.Join(dir, "free")); string(b) != "new" { + t.Fatalf("moved content %q", b) + } + // Replace mode replaces. + if err := fsys.Rename(ctx, filepath.Join(dir, "free"), filepath.Join(dir, "dst"), vfs.Replace); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(filepath.Join(dir, "dst")); string(b) != "new" { + t.Fatalf("replace content %q", b) + } +} + +func TestReadDirSymlinkTarget(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{ + fstree.Dir("real"), + fstree.File("real/f", "x"), + fstree.File("plain", "abc"), + fstree.Symlink("todir", "real"), + fstree.Symlink("tofile", "plain"), + fstree.Symlink("broken", "missing"), + }) + ents, err := New().ReadDir(ctx, dir) + if err != nil { + t.Fatal(err) + } + byName := map[string]vfs.FileInfo{} + for _, e := range ents { + byName[e.Name] = e + } + if len(byName) != 5 { + t.Fatalf("entries: %v", ents) + } + td := byName["todir"] + if !td.IsSymlink() || td.IsDir() || !td.NavigableDir() || td.Target == nil || !td.Target.IsDir() { + t.Fatalf("todir = %+v", td) + } + tf := byName["tofile"] + if tf.NavigableDir() || !tf.IsRegularLike() || tf.Target.Size != 3 { + t.Fatalf("tofile = %+v", tf) + } + br := byName["broken"] + if !br.IsSymlink() || br.Target != nil || br.LinkErr == nil || br.NavigableDir() { + t.Fatalf("broken = %+v", br) + } + if !errors.Is(br.LinkErr, vfs.ErrNotExist) { + t.Fatalf("broken LinkErr = %v", br.LinkErr) + } + if !byName["real"].IsDir() || byName["plain"].Size != 3 { + t.Fatalf("plain entries wrong: %+v", byName) + } + // Lstat agrees with ReadDir. + li, err := New().Lstat(ctx, filepath.Join(dir, "todir")) + if err != nil || !li.NavigableDir() || li.IsDir() { + t.Fatalf("Lstat todir = %+v, %v", li, err) + } +} + +func TestReadDirNoBirthByDefault(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("a", ""), fstree.File("b", ""), fstree.Dir("c")}) + calls := 0 + orig := statx + statx = func(dirfd int, path string, flags, mask int, st *unix.Statx_t) error { + calls++ + return orig(dirfd, path, flags, mask, st) + } + t.Cleanup(func() { statx = orig }) + + fsys := New() + if _, err := fsys.ReadDir(ctx, dir); err != nil { + t.Fatal(err) + } + if calls != 0 { + t.Fatalf("ReadDir made %d statx calls, want 0", calls) + } + if _, ok := fsys.BirthTime(ctx, filepath.Join(dir, "a")); calls != 1 { + t.Fatalf("BirthTime made %d statx calls (ok=%v), want 1", calls, ok) + } +} + +func TestCreateExclAndErrors(t *testing.T) { + dir := t.TempDir() + fsys := New() + p := filepath.Join(dir, "f") + f, err := fsys.Create(ctx, p, 0o600, vfs.CreateExcl) + if err != nil { + t.Fatal(err) + } + if _, err := f.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + if err := f.Sync(); err != nil { + t.Fatal(err) + } + if fi, err := f.Stat(); err != nil || fi.Size != 5 || fi.Name != "f" { + t.Fatalf("stat = %+v, %v", fi, err) + } + f.Close() + if _, err := fsys.Create(ctx, p, 0o600, vfs.CreateExcl); !errors.Is(err, vfs.ErrExist) { + t.Fatalf("excl on existing: %v", err) + } + if _, err := fsys.Stat(ctx, filepath.Join(dir, "nope")); !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("stat missing: %v", err) + } + if err := mapErr(&os.PathError{Op: "open", Path: "x", Err: unix.EROFS}); !errors.Is(err, vfs.ErrReadOnly) || !errors.Is(err, unix.EROFS) { + t.Fatalf("EROFS mapping: %v", err) + } +} diff --git a/internal/vfs/localfs/rename_linux.go b/internal/vfs/localfs/rename_linux.go new file mode 100644 index 0000000..258651a --- /dev/null +++ b/internal/vfs/localfs/rename_linux.go @@ -0,0 +1,36 @@ +//go:build linux + +package localfs + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +// renameNoReplace uses renameat2(RENAME_NOREPLACE). If the file system does +// not support it (EINVAL/ENOSYS), files fall back to link+unlink (also +// atomic against an existing target) and directories to renameByCheck. +func renameNoReplace(from, to string) error { + err := unix.Renameat2(unix.AT_FDCWD, from, unix.AT_FDCWD, to, unix.RENAME_NOREPLACE) + if err == nil { + return nil + } + if !errors.Is(err, unix.EINVAL) && !errors.Is(err, unix.ENOSYS) { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + fi, lerr := os.Lstat(from) + if lerr != nil { + return lerr + } + if !fi.IsDir() { + if err := os.Link(from, to); err == nil { + return os.Remove(from) + } else if errors.Is(err, os.ErrExist) { + return err + } + // No hard links on this FS (vfat, some FUSE): fall through. + } + return renameByCheck(from, to) +} diff --git a/internal/vfs/localfs/rename_other.go b/internal/vfs/localfs/rename_other.go new file mode 100644 index 0000000..2998d14 --- /dev/null +++ b/internal/vfs/localfs/rename_other.go @@ -0,0 +1,6 @@ +//go:build !linux + +package localfs + +// renameNoReplace has no atomic primitive here; see renameByCheck. +func renameNoReplace(from, to string) error { return renameByCheck(from, to) } diff --git a/internal/vfs/localfs/trash.go b/internal/vfs/localfs/trash.go new file mode 100644 index 0000000..41852af --- /dev/null +++ b/internal/vfs/localfs/trash.go @@ -0,0 +1,242 @@ +package localfs + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "vcom/internal/paths" + "vcom/internal/vfs" +) + +// trashConfig holds what the freedesktop trash depends on, so tests can fake +// devices and homes. +type trashConfig struct { + // dataHome returns the effective user's XDG data home (under sudo: + // root's, never the invoking user's); the home trash is dataHome()/Trash. + dataHome func() (string, error) + // uid is the effective uid (topdir trash names, sudo → root's trash). + uid int + // statDev returns the device of p without following a final symlink. + statDev func(p string) (uint64, error) + now func() time.Time +} + +func defaultTrashConfig() trashConfig { + return trashConfig{dataHome: paths.DataHome, uid: os.Geteuid(), statDev: lstatDev, now: time.Now} +} + +func lstatDev(p string) (uint64, error) { + fi, err := os.Lstat(p) + if err != nil { + return 0, err + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + return 0, fmt.Errorf("stat %s: no device information", p) + } + return uint64(st.Dev), nil //nolint:unconvert // Dev is int32 on darwin +} + +// Trash moves p to the freedesktop.org trash (design §2.3): +// - same device as the home trash → $XDG_DATA_HOME/Trash, info Path= absolute; +// - otherwise the volume's top directory: $topdir/.Trash/$uid if .Trash is a +// real directory with the sticky bit, else $topdir/.Trash-$uid; info Path= +// relative to $topdir. Never a cross-device copy. +// +// The .trashinfo file is created with O_EXCL first (it reserves the name; +// collisions get a ".N" suffix), Path= is URL-encoded and DeletionDate is local +// time. p itself is moved without following a final symlink. +func (f *FS) Trash(_ context.Context, p string) error { + c := f.trash + abs, err := filepath.Abs(p) + if err != nil { + return err + } + if abs == string(filepath.Separator) { + return fmt.Errorf("trash %s: refusing to trash the root directory", abs) + } + if _, err := os.Lstat(abs); err != nil { + return mapErr(err) + } + dev, err := c.statDev(abs) + if err != nil { + return mapErr(err) + } + + trashDir, infoPath, err := c.pickTrash(abs, dev) + if err != nil { + return err + } + filesDir := filepath.Join(trashDir, "files") + infoDir := filepath.Join(trashDir, "info") + for _, d := range []string{filesDir, infoDir} { + if err := ensurePrivateDir(d); err != nil { + return fmt.Errorf("trash %s: %w", abs, err) + } + } + + name, info, err := reserveTrashName(filesDir, infoDir, filepath.Base(abs)) + if err != nil { + return fmt.Errorf("trash %s: %w", abs, err) + } + content := "[Trash Info]\nPath=" + trashEscape(infoPath) + + "\nDeletionDate=" + c.now().Format("2006-01-02T15:04:05") + "\n" + if _, err := info.WriteString(content); err == nil { + err = info.Sync() + } + cerr := info.Close() + infoFile := filepath.Join(infoDir, name+".trashinfo") + if err != nil || cerr != nil { + _ = os.Remove(infoFile) + return fmt.Errorf("trash %s: write info: %w", abs, errors.Join(err, cerr)) + } + if err := renameNoReplace(abs, filepath.Join(filesDir, name)); err != nil { + _ = os.Remove(infoFile) + return mapErr(err) + } + return nil +} + +// pickTrash returns the trash directory for abs and the Path= value for its +// info file. +func (c trashConfig) pickTrash(abs string, dev uint64) (dir, infoPath string, err error) { + home, err := c.dataHome() + if err != nil { + return "", "", err + } + homeTrash := filepath.Join(home, "Trash") + if vfs.IsWithin(vfs.NativePaths, abs, homeTrash) { + return "", "", fmt.Errorf("trash %s: already in the trash", abs) + } + homeDev, err := c.statDev(existingAncestor(homeTrash)) + if err != nil { + return "", "", err + } + if homeDev == dev { + if err := os.MkdirAll(homeTrash, 0o700); err != nil { + return "", "", fmt.Errorf("trash %s: %w", abs, err) + } + return homeTrash, abs, nil + } + + top := c.topdir(abs, dev) + rel, err := filepath.Rel(top, abs) + if err != nil { + return "", "", err + } + uid := strconv.Itoa(c.uid) + // $topdir/.Trash/$uid: only if .Trash is a real, sticky directory. + shared := filepath.Join(top, ".Trash") + if fi, err := os.Lstat(shared); err == nil && fi.IsDir() && fi.Mode()&fs.ModeSticky != 0 { + d := filepath.Join(shared, uid) + if err := ensurePrivateDir(d); err == nil { + return d, rel, nil + } + } + d := filepath.Join(top, ".Trash-"+uid) + if err := ensurePrivateDir(d); err != nil { + return "", "", fmt.Errorf("trash %s: no usable trash on this volume (%s): %w", abs, top, err) + } + return d, rel, nil +} + +// topdir climbs from abs's parent while the device stays the same: the mount +// point of the volume abs lives on. +func (c trashConfig) topdir(abs string, dev uint64) string { + d := filepath.Dir(abs) + for { + parent := filepath.Dir(d) + if parent == d { + return d + } + if pd, err := c.statDev(parent); err != nil || pd != dev { + return d + } + d = parent + } +} + +func existingAncestor(p string) string { + for { + if _, err := os.Lstat(p); err == nil { + return p + } + parent := filepath.Dir(p) + if parent == p { + return p + } + p = parent + } +} + +// ensurePrivateDir creates d (0700) if missing and checks it is a real +// directory, not a symlink planted by someone else. +func ensurePrivateDir(d string) error { + if err := os.Mkdir(d, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { + return err + } + fi, err := os.Lstat(d) + if err != nil { + return err + } + if !fi.IsDir() { + return fmt.Errorf("%s is not a directory", d) + } + return nil +} + +// reserveTrashName creates info/.trashinfo with O_EXCL for the first +// free name (base, base.2, base.3, ...) that is also free in files/. +func reserveTrashName(filesDir, infoDir, base string) (string, *os.File, error) { + for i := 1; i <= 10000; i++ { + name := base + if i > 1 { + name = base + "." + strconv.Itoa(i) + } + infoFile := filepath.Join(infoDir, name+".trashinfo") + f, err := os.OpenFile(infoFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if errors.Is(err, fs.ErrExist) { + continue + } + if err != nil { + return "", nil, err + } + if _, err := os.Lstat(filepath.Join(filesDir, name)); err == nil { + // An orphan in files/ without info: leave it, try the next name. + f.Close() + _ = os.Remove(infoFile) + continue + } + return name, f, nil + } + return "", nil, fmt.Errorf("no free name for %q in the trash", base) +} + +// trashEscape URL-encodes a path for Path= (RFC 2396 as the spec asks): bytes +// other than unreserved characters and '/' become %XX, so spaces and +// non-ASCII names survive other tools' restore. +func trashEscape(p string) string { + const hex = "0123456789ABCDEF" + var b strings.Builder + for i := 0; i < len(p); i++ { + c := p[i] + switch { + case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9', + c == '/', c == '-', c == '_', c == '.', c == '~': + b.WriteByte(c) + default: + b.WriteByte('%') + b.WriteByte(hex[c>>4]) + b.WriteByte(hex[c&15]) + } + } + return b.String() +} diff --git a/internal/vfs/localfs/trash_test.go b/internal/vfs/localfs/trash_test.go new file mode 100644 index 0000000..704aed8 --- /dev/null +++ b/internal/vfs/localfs/trash_test.go @@ -0,0 +1,224 @@ +package localfs + +import ( + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "vcom/internal/testutil/fstree" +) + +var fixedNow = time.Date(2026, 10, 31, 12, 34, 56, 0, time.Local) + +// newTrashFS returns an FS whose home trash lives in /home/.local/share/Trash. +func newTrashFS(t *testing.T) (fsys *FS, tmp, trash string) { + tmp = t.TempDir() + data := filepath.Join(tmp, "home", ".local", "share") + fsys = New() + fsys.trash.dataHome = func() (string, error) { return data, nil } + fsys.trash.now = func() time.Time { return fixedNow } + return fsys, tmp, filepath.Join(data, "Trash") +} + +func readInfo(t *testing.T, trash, name string) (path, date string) { + t.Helper() + b, err := os.ReadFile(filepath.Join(trash, "info", name+".trashinfo")) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + if len(lines) != 3 || lines[0] != "[Trash Info]" { + t.Fatalf("info file:\n%s", b) + } + return strings.TrimPrefix(lines[1], "Path="), strings.TrimPrefix(lines[2], "DeletionDate=") +} + +func TestTrashHome(t *testing.T) { + fsys, tmp, trash := newTrashFS(t) + fstree.Build(t, tmp, fstree.Spec{ + fstree.File("work/a.txt", "A"), + fstree.File("work/dir/x", "X"), + fstree.File("target/keep", "K"), + fstree.Symlink("work/link", "../target"), + }) + for _, n := range []string{"a.txt", "dir", "link"} { + if err := fsys.Trash(ctx, filepath.Join(tmp, "work", n)); err != nil { + t.Fatalf("trash %s: %v", n, err) + } + if _, err := os.Lstat(filepath.Join(tmp, "work", n)); !os.IsNotExist(err) { + t.Fatalf("%s still in place", n) + } + p, date := readInfo(t, trash, n) + if p != filepath.Join(tmp, "work", n) { // temp paths are plain ASCII + t.Fatalf("Path=%s", p) + } + if date != "2026-10-31T12:34:56" { + t.Fatalf("DeletionDate=%s", date) + } + } + if b, _ := os.ReadFile(filepath.Join(trash, "files", "a.txt")); string(b) != "A" { + t.Fatal("file content not in trash") + } + if b, _ := os.ReadFile(filepath.Join(trash, "files", "dir", "x")); string(b) != "X" { + t.Fatal("dir not in trash") + } + if fi, err := os.Lstat(filepath.Join(trash, "files", "link")); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("link must be trashed as a link: %v %v", fi, err) + } + if b, _ := os.ReadFile(filepath.Join(tmp, "target", "keep")); string(b) != "K" { + t.Fatal("link target damaged") + } + for _, d := range []string{"files", "info"} { + if fi, _ := os.Stat(filepath.Join(trash, d)); fi.Mode().Perm() != 0o700 { + t.Fatalf("%s mode %v", d, fi.Mode().Perm()) + } + } + if err := fsys.Trash(ctx, filepath.Join(trash, "files", "a.txt")); err == nil { + t.Fatal("trashing inside the trash must fail") + } + if err := fsys.Trash(ctx, filepath.Join(tmp, "work", "missing")); !os.IsNotExist(err) { + t.Fatalf("missing: %v", err) + } +} + +func TestTrashInfoURLEncoded(t *testing.T) { + fsys, tmp, trash := newTrashFS(t) + rel := "папка/my file ё%.txt" + fstree.Build(t, tmp, fstree.Spec{fstree.File(rel, "")}) + src := filepath.Join(tmp, rel) + if err := fsys.Trash(ctx, src); err != nil { + t.Fatal(err) + } + p, _ := readInfo(t, trash, "my file ё%.txt") + if strings.ContainsAny(p, " ёп") { + t.Fatalf("Path= not encoded: %s", p) + } + if !strings.HasSuffix(p, "/%D0%BF%D0%B0%D0%BF%D0%BA%D0%B0/my%20file%20%D1%91%25.txt") { + t.Fatalf("Path=%s", p) + } + if dec, err := url.PathUnescape(p); err != nil || dec != src { + t.Fatalf("decoded %q, %v; want %q", dec, err, src) + } +} + +func TestTrashNameCollision(t *testing.T) { + fsys, tmp, trash := newTrashFS(t) + fstree.Build(t, tmp, fstree.Spec{ + fstree.File("one/a.txt", "1"), + fstree.File("two/a.txt", "2"), + fstree.File("three/a.txt", "3"), + }) + for _, d := range []string{"one", "two"} { + if err := fsys.Trash(ctx, filepath.Join(tmp, d, "a.txt")); err != nil { + t.Fatal(err) + } + } + // An orphan in files/ without an info file blocks its name too. + if err := os.WriteFile(filepath.Join(trash, "files", "a.txt.3"), []byte("orphan"), 0o600); err != nil { + t.Fatal(err) + } + if err := fsys.Trash(ctx, filepath.Join(tmp, "three", "a.txt")); err != nil { + t.Fatal(err) + } + for name, want := range map[string]string{"a.txt": "1", "a.txt.2": "2", "a.txt.3": "orphan", "a.txt.4": "3"} { + if b, _ := os.ReadFile(filepath.Join(trash, "files", name)); string(b) != want { + t.Errorf("files/%s = %q, want %q", name, b, want) + } + } + if p, _ := readInfo(t, trash, "a.txt.4"); p != filepath.Join(tmp, "three", "a.txt") { + t.Errorf("info a.txt.4 Path=%s", p) + } + if _, err := os.Stat(filepath.Join(trash, "info", "a.txt.3.trashinfo")); !os.IsNotExist(err) { + t.Error("an info file was left for the orphan's name") + } +} + +// TestTrashTopdir fakes a second volume mounted at /vol (N-P2-12: the +// old code failed with EXDEV here). +func TestTrashTopdir(t *testing.T) { + setup := func(t *testing.T) (*FS, string, string) { + fsys, tmp, _ := newTrashFS(t) + vol := filepath.Join(tmp, "vol") + fsys.trash.uid = 1234 + fsys.trash.statDev = func(p string) (uint64, error) { + if _, err := os.Lstat(p); err != nil { + return 0, err + } + if p == vol || strings.HasPrefix(p, vol+"/") { + return 2, nil + } + return 1, nil + } + fstree.Build(t, tmp, fstree.Spec{fstree.File("vol/sub/f b.txt", "data")}) + return fsys, tmp, vol + } + + t.Run("TrashUID", func(t *testing.T) { + fsys, tmp, vol := setup(t) + if err := fsys.Trash(ctx, filepath.Join(vol, "sub", "f b.txt")); err != nil { + t.Fatal(err) + } + trash := filepath.Join(vol, ".Trash-1234") + if b, _ := os.ReadFile(filepath.Join(trash, "files", "f b.txt")); string(b) != "data" { + t.Fatal("not in $topdir/.Trash-$uid") + } + if p, _ := readInfo(t, trash, "f b.txt"); p != "sub/f%20b.txt" { + t.Fatalf("Path=%s, want relative to topdir", p) + } + if fi, _ := os.Stat(trash); fi.Mode().Perm() != 0o700 { + t.Fatalf("mode %v", fi.Mode().Perm()) + } + if _, err := os.Stat(filepath.Join(tmp, "home", ".local", "share", "Trash", "files")); !os.IsNotExist(err) { + t.Fatal("home trash must not be used across devices") + } + }) + + t.Run("SharedStickyTrash", func(t *testing.T) { + fsys, _, vol := setup(t) + shared := filepath.Join(vol, ".Trash") + if err := os.Mkdir(shared, 0o777|os.ModeSticky); err != nil { + t.Fatal(err) + } + if err := os.Chmod(shared, 0o777|os.ModeSticky); err != nil { + t.Fatal(err) + } + if err := fsys.Trash(ctx, filepath.Join(vol, "sub", "f b.txt")); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(shared, strconv.Itoa(1234), "files", "f b.txt")); err != nil { + t.Fatalf("not in $topdir/.Trash/$uid: %v", err) + } + }) + + t.Run("RejectsSymlinkedOrNonStickyTrash", func(t *testing.T) { + fsys, tmp, vol := setup(t) + // .Trash as a symlink to a sticky dir elsewhere must be ignored. + elsewhere := filepath.Join(tmp, "elsewhere") + if err := os.Mkdir(elsewhere, 0o777); err != nil { + t.Fatal(err) + } + _ = os.Chmod(elsewhere, 0o777|os.ModeSticky) + if err := os.Symlink(elsewhere, filepath.Join(vol, ".Trash")); err != nil { + t.Fatal(err) + } + if err := fsys.Trash(ctx, filepath.Join(vol, "sub", "f b.txt")); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(vol, ".Trash-1234", "files", "f b.txt")); err != nil { + t.Fatalf("expected fallback to .Trash-$uid: %v", err) + } + if ents, _ := os.ReadDir(elsewhere); len(ents) != 0 { + t.Fatal("followed a symlinked .Trash") + } + }) +} + +func TestTrashEscape(t *testing.T) { + if got := trashEscape("/a b/~x_y-z.1/#?&"); got != "/a%20b/~x_y-z.1/%23%3F%26" { + t.Fatal(got) + } +} diff --git a/internal/vfs/location.go b/internal/vfs/location.go new file mode 100644 index 0000000..704d06d --- /dev/null +++ b/internal/vfs/location.go @@ -0,0 +1,28 @@ +package vfs + +// Location is "where a panel stands / where an operation writes". +type Location struct { + FS FS + Path string +} + +// Same reports whether both locations name the same path on the same volume +// (lexically: equal VolumeID and equal cleaned paths). It does not resolve +// symlinks; use SameFile or Within for identity. +func (l Location) Same(o Location) bool { + if l.FS == nil || o.FS == nil { + return l.FS == nil && o.FS == nil && l.Path == o.Path + } + if l.FS.Volume() != o.FS.Volume() { + return false + } + return l.FS.Paths().Clean(l.Path) == o.FS.Paths().Clean(o.Path) +} + +// String renders "label:path" for logs and messages. +func (l Location) String() string { + if l.FS == nil { + return l.Path + } + return l.FS.Label() + ":" + l.Path +} diff --git a/internal/vfs/paths.go b/internal/vfs/paths.go new file mode 100644 index 0000000..5a2a341 --- /dev/null +++ b/internal/vfs/paths.go @@ -0,0 +1,55 @@ +package vfs + +import ( + "path" + "path/filepath" + "strings" +) + +// PathOps are the path rules of an FS. +type PathOps interface { + Join(elem ...string) string + Dir(p string) string + Base(p string) string + Clean(p string) string + IsAbs(p string) bool + Sep() byte +} + +// PosixPaths are slash-separated paths (sftp, archives). +var PosixPaths PathOps = posixPaths{} + +// NativePaths follow the host OS (path/filepath); used by localfs. +var NativePaths PathOps = nativePaths{} + +type posixPaths struct{} + +func (posixPaths) Join(elem ...string) string { return path.Join(elem...) } +func (posixPaths) Dir(p string) string { return path.Dir(p) } +func (posixPaths) Base(p string) string { return path.Base(p) } +func (posixPaths) Clean(p string) string { return path.Clean(p) } +func (posixPaths) IsAbs(p string) bool { return path.IsAbs(p) } +func (posixPaths) Sep() byte { return '/' } + +type nativePaths struct{} + +func (nativePaths) Join(elem ...string) string { return filepath.Join(elem...) } +func (nativePaths) Dir(p string) string { return filepath.Dir(p) } +func (nativePaths) Base(p string) string { return filepath.Base(p) } +func (nativePaths) Clean(p string) string { return filepath.Clean(p) } +func (nativePaths) IsAbs(p string) bool { return filepath.IsAbs(p) } +func (nativePaths) Sep() byte { return filepath.Separator } + +// IsWithin reports whether child equals parent or lies under it, comparing +// cleaned paths lexically with ops (no symlink resolution; see Within). +func IsWithin(ops PathOps, child, parent string) bool { + child, parent = ops.Clean(child), ops.Clean(parent) + if child == parent { + return true + } + sep := string(ops.Sep()) + if !strings.HasSuffix(parent, sep) { + parent += sep + } + return strings.HasPrefix(child, parent) +} diff --git a/internal/vfs/readonly.go b/internal/vfs/readonly.go new file mode 100644 index 0000000..fa24fe5 --- /dev/null +++ b/internal/vfs/readonly.go @@ -0,0 +1,84 @@ +package vfs + +import ( + "context" + "io/fs" + "time" +) + +// ReadOnly wraps fsys so that Caps().ReadOnly is true and every mutating +// method returns ErrReadOnly without reaching fsys. Trash and Exec are hidden; +// BirthTime is passed through. +func ReadOnly(fsys FS) FS { + if ro, ok := fsys.(readOnlyFS); ok { + return ro + } + return readOnlyFS{fsys} +} + +type readOnlyFS struct{ inner FS } + +func (r readOnlyFS) Kind() Kind { return r.inner.Kind() } +func (r readOnlyFS) Volume() VolumeID { return r.inner.Volume() } +func (r readOnlyFS) Label() string { return r.inner.Label() } +func (r readOnlyFS) Paths() PathOps { return r.inner.Paths() } + +func (r readOnlyFS) Caps() Caps { + c := r.inner.Caps() + c.ReadOnly = true + c.Trash = false + c.Exec = false + return c +} + +func (r readOnlyFS) Stat(ctx context.Context, p string) (FileInfo, error) { + return r.inner.Stat(ctx, p) +} +func (r readOnlyFS) Lstat(ctx context.Context, p string) (FileInfo, error) { + return r.inner.Lstat(ctx, p) +} +func (r readOnlyFS) ReadDir(ctx context.Context, p string) ([]FileInfo, error) { + return r.inner.ReadDir(ctx, p) +} +func (r readOnlyFS) ReadLink(ctx context.Context, p string) (string, error) { + return r.inner.ReadLink(ctx, p) +} +func (r readOnlyFS) RealPath(ctx context.Context, p string) (string, error) { + return r.inner.RealPath(ctx, p) +} + +// Open returns a file whose Write fails with ErrReadOnly. +func (r readOnlyFS) Open(ctx context.Context, p string) (File, error) { + f, err := r.inner.Open(ctx, p) + if err != nil { + return nil, err + } + return readOnlyFile{f}, nil +} + +func (r readOnlyFS) BirthTime(ctx context.Context, p string) (time.Time, bool) { + if bt, ok := r.inner.(BirthTimer); ok { + return bt.BirthTime(ctx, p) + } + return time.Time{}, false +} + +func roErr(op, p string) error { return &fs.PathError{Op: op, Path: p, Err: ErrReadOnly} } + +func (readOnlyFS) Create(_ context.Context, p string, _ fs.FileMode, _ CreateMode) (File, error) { + return nil, roErr("create", p) +} +func (readOnlyFS) Mkdir(_ context.Context, p string, _ fs.FileMode) error { return roErr("mkdir", p) } +func (readOnlyFS) Remove(_ context.Context, p string) error { return roErr("remove", p) } +func (readOnlyFS) Rename(_ context.Context, from, _ string, _ RenameMode) error { + return roErr("rename", from) +} +func (readOnlyFS) Symlink(_ context.Context, _, p string) error { return roErr("symlink", p) } +func (readOnlyFS) Chmod(_ context.Context, p string, _ fs.FileMode) error { return roErr("chmod", p) } +func (readOnlyFS) Chtimes(_ context.Context, p string, _, _ time.Time) error { + return roErr("chtimes", p) +} + +type readOnlyFile struct{ File } + +func (readOnlyFile) Write([]byte) (int, error) { return 0, ErrReadOnly } diff --git a/internal/vfs/remove.go b/internal/vfs/remove.go new file mode 100644 index 0000000..5bcaf18 --- /dev/null +++ b/internal/vfs/remove.go @@ -0,0 +1,47 @@ +package vfs + +import ( + "context" + "fmt" +) + +// RemoveTree deletes p and, if p is a real directory, everything under it +// (post-order). The root is Lstat'ed: a symlink — even to a directory — is +// removed as a link, and links met inside are never followed (N-P0-3). +// progress, if non-nil, is called after every removed node with the running +// count. The first error stops the removal and is returned; ctx is checked +// before every node. +func RemoveTree(ctx context.Context, fsys FS, p string, progress func(removed int)) error { + fi, err := fsys.Lstat(ctx, p) + if err != nil { + return err + } + n := 0 + return removeTree(ctx, fsys, p, fi, &n, progress) +} + +func removeTree(ctx context.Context, fsys FS, p string, fi FileInfo, n *int, progress func(int)) error { + if err := ctx.Err(); err != nil { + return err + } + if fi.IsDir() { + ents, err := fsys.ReadDir(ctx, p) + if err != nil { + return fmt.Errorf("remove %s: %w", p, err) + } + ops := fsys.Paths() + for _, e := range ents { + if err := removeTree(ctx, fsys, ops.Join(p, e.Name), e, n, progress); err != nil { + return err + } + } + } + if err := fsys.Remove(ctx, p); err != nil { + return err + } + *n++ + if progress != nil { + progress(*n) + } + return nil +} diff --git a/internal/vfs/same.go b/internal/vfs/same.go new file mode 100644 index 0000000..8d1816a --- /dev/null +++ b/internal/vfs/same.go @@ -0,0 +1,87 @@ +package vfs + +import ( + "context" + "errors" + "os" +) + +// SameFile reports whether pa on a and pb on b are the same file, following +// symlinks. local+local compares device and inode (os.SameFile), which also +// catches hard links and bind mounts; other FSes on the same Volume compare +// RealPath; different volumes are never the same. A missing path is not an +// error: the answer is false. +func SameFile(ctx context.Context, a FS, pa string, b FS, pb string) (bool, error) { + if a.Volume() != b.Volume() { + return false, nil + } + if a.Kind() == KindLocal && b.Kind() == KindLocal { + fa, err := os.Stat(pa) + if err != nil { + return false, notExistIsFalse(err) + } + fb, err := os.Stat(pb) + if err != nil { + return false, notExistIsFalse(err) + } + return os.SameFile(fa, fb), nil + } + ra, err := a.RealPath(ctx, pa) + if err != nil { + return false, notExistIsFalse(err) + } + rb, err := b.RealPath(ctx, pb) + if err != nil { + return false, notExistIsFalse(err) + } + return a.Paths().Clean(ra) == b.Paths().Clean(rb), nil +} + +func notExistIsFalse(err error) error { + if errors.Is(err, ErrNotExist) { + return nil + } + return err +} + +// Within reports whether child is parent or lies inside it after resolving +// symlinks on both (e.g. "copy a directory into its own subdirectory through +// an alias"). child need not exist yet: its deepest existing ancestor is +// resolved and the rest appended. parent must exist. +func Within(ctx context.Context, fsys FS, child, parent string) (bool, error) { + rp, err := fsys.RealPath(ctx, parent) + if err != nil { + return false, err + } + rc, err := realPathLenient(ctx, fsys, child) + if err != nil { + return false, err + } + return IsWithin(fsys.Paths(), rc, rp), nil +} + +// realPathLenient resolves p, or — if p does not exist — its deepest existing +// ancestor joined with the missing tail. +func realPathLenient(ctx context.Context, fsys FS, p string) (string, error) { + ops := fsys.Paths() + p = ops.Clean(p) + var tail []string + for { + r, err := fsys.RealPath(ctx, p) + if err == nil { + for i := len(tail) - 1; i >= 0; i-- { + r = ops.Join(r, tail[i]) + } + return r, nil + } + if !errors.Is(err, ErrNotExist) { + return "", err + } + parent := ops.Dir(p) + if parent == p { + return "", err + } + tail = append(tail, ops.Base(p)) + p = parent + } +} diff --git a/internal/vfs/sftpfs/cancel_test.go b/internal/vfs/sftpfs/cancel_test.go new file mode 100644 index 0000000..977dc60 --- /dev/null +++ b/internal/vfs/sftpfs/cancel_test.go @@ -0,0 +1,76 @@ +package sftpfs + +import ( + "context" + "errors" + "io" + "path/filepath" + "testing" + "time" + + "vcom/internal/testutil/sshtest" + "vcom/internal/vfs" +) + +// A read stuck on a frozen link is released shortly after the ctx the file +// was opened with is cancelled, even with the default 15 s keepalive. +func TestFileCancelReleasesStuckRead(t *testing.T) { + s := newStand(t, sshtest.Options{}) + px := s.proxy() + f := s.fs(px.Addr) + p := filepath.Join(t.TempDir(), "big") + sshtest.WriteRandom(t, p, 4<<20, 0o644) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fl, err := f.Open(ctx, p) + if err != nil { + t.Fatal(err) + } + defer fl.Close() + px.Freeze(true) + defer px.Freeze(false) + res := make(chan error, 1) + go func() { + _, err := io.Copy(io.Discard, fl) + res <- err + }() + time.Sleep(50 * time.Millisecond) + cancel() + start := time.Now() + select { + case err := <-res: + if !errors.Is(err, vfs.ErrConnLost) { + t.Errorf("err = %v, want ErrConnLost", err) + } + case <-time.After(5 * time.Second): + t.Fatal("stuck read not released") + } + if el := time.Since(start); el > cancelGrace+cancelProbeTimeout+time.Second { + t.Errorf("released after %v", el) + } +} + +// Cancelling the ctx of a file on a live link with no stuck operation +// leaves the connection alone. +func TestFileCancelLiveLinkUntouched(t *testing.T) { + s := newStand(t, sshtest.Options{}) + f := s.fs("") + p := filepath.Join(t.TempDir(), "small") + sshtest.WriteRandom(t, p, 1000, 0o644) + ctx, cancel := context.WithCancel(context.Background()) + fl, err := f.Open(ctx, p) + if err != nil { + t.Fatal(err) + } + cancel() + if _, err := io.Copy(io.Discard, fl); err != nil { + t.Fatal(err) + } + time.Sleep(cancelGrace + 200*time.Millisecond) + if err := fl.Close(); err != nil { + t.Fatal(err) + } + if err := f.Conn().Err(); err != nil { + t.Fatalf("conn: %v", err) + } +} diff --git a/internal/vfs/sftpfs/errors.go b/internal/vfs/sftpfs/errors.go new file mode 100644 index 0000000..4b3473a --- /dev/null +++ b/internal/vfs/sftpfs/errors.go @@ -0,0 +1,69 @@ +package sftpfs + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + + "github.com/pkg/sftp" + + "vcom/internal/ssh/conn" + "vcom/internal/vfs" +) + +// sshFxOPUnsupported is SSH_FX_OP_UNSUPPORTED. +const sshFxOPUnsupported = 8 + +// mapErr turns an SFTP/connection error into vfs sentinels: a dead or closed +// connection becomes vfs.ErrConnLost (still matching conn.ErrConnLost / +// conn.ErrClosed), SSH_FX_OP_UNSUPPORTED becomes vfs.ErrUnsupported. +// ENOENT/EACCES already arrive as fs.ErrNotExist/fs.ErrPermission from +// pkg/sftp. Context errors and io.EOF pass through untouched. +func (f *FS) mapErr(err error) error { + if err == nil || err == io.EOF || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + err = f.c.MapErr(err) + if errors.Is(err, conn.ErrConnLost) || errors.Is(err, conn.ErrClosed) { + if errors.Is(err, vfs.ErrConnLost) { + return err + } + return fmt.Errorf("%w: %w", vfs.ErrConnLost, err) + } + var se *sftp.StatusError + if errors.As(err, &se) && se.Code == sshFxOPUnsupported { + return fmt.Errorf("%w: %w", vfs.ErrUnsupported, err) + } + return err +} + +// wrap maps err and attaches op and path (unless the error already is a +// *fs.PathError, as pkg/sftp returns for some calls). +func (f *FS) wrap(op, p string, err error) error { + err = f.mapErr(err) + if err == nil || err == io.EOF || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + var pe *fs.PathError + if errors.As(err, &pe) && !errors.Is(err, vfs.ErrConnLost) { + return err + } + return &fs.PathError{Op: op, Path: p, Err: err} +} + +// existErr refines a failed create/mkdir/rename: SFTP v3 has no +// "already exists" status (OpenSSH and pkg/sftp send SSH_FX_FAILURE), so if +// the target now exists the error becomes vfs.ErrExist. +func (f *FS) existErr(ctx context.Context, op, p string, err error) error { + werr := f.wrap(op, p, err) + if werr == nil || errors.Is(werr, vfs.ErrNotExist) || errors.Is(werr, vfs.ErrPermission) || + errors.Is(werr, vfs.ErrConnLost) || ctx.Err() != nil { + return werr + } + if _, lerr := f.lstatRaw(ctx, p); lerr == nil { + return &fs.PathError{Op: op, Path: p, Err: vfs.ErrExist} + } + return werr +} diff --git a/internal/vfs/sftpfs/integration_test.go b/internal/vfs/sftpfs/integration_test.go new file mode 100644 index 0000000..13f8e6a --- /dev/null +++ b/internal/vfs/sftpfs/integration_test.go @@ -0,0 +1,163 @@ +//go:build integration + +package sftpfs + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "errors" + "fmt" + "net" + "os" + "os/exec" + "os/user" + "path/filepath" + "strconv" + "testing" + "time" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/ssh/conn" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +const sshdPath = "/usr/sbin/sshd" + +// realSSHD starts the system sshd as the current user on a free port and +// returns an FS connected to it. The test is skipped when that is not +// possible (no sshd, sandbox without ports, ...). +func realSSHD(t *testing.T) *FS { + t.Helper() + if _, err := os.Stat(sshdPath); err != nil { + t.Skip("no " + sshdPath) + } + u, err := user.Current() + if err != nil { + t.Skip(err) + } + dir, err := os.MkdirTemp("", "vcom-sshd") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + writeKey := func(name string) ssh.PublicKey { + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + blk, err := ssh.MarshalPrivateKey(priv, name) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, name), pem.EncodeToMemory(blk), 0o600); err != nil { + t.Fatal(err) + } + s, _ := ssh.NewSignerFromKey(priv) + return s.PublicKey() + } + hostPub := writeKey("host_key") + clientPub := writeKey("client_key") + if err := os.WriteFile(filepath.Join(dir, "authorized_keys"), ssh.MarshalAuthorizedKey(clientPub), 0o600); err != nil { + t.Fatal(err) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Skip(err) + } + port := ln.Addr().(*net.TCPAddr).Port + ln.Close() + cfg := fmt.Sprintf(`Port %d +ListenAddress 127.0.0.1 +HostKey %[2]s/host_key +PidFile %[2]s/sshd.pid +AuthorizedKeysFile %[2]s/authorized_keys +StrictModes no +UsePAM no +PasswordAuthentication no +KbdInteractiveAuthentication no +PubkeyAuthentication yes +Subsystem sftp internal-sftp +`, port, dir) + if err := os.WriteFile(filepath.Join(dir, "sshd_config"), []byte(cfg), 0o600); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + cmd := exec.Command(sshdPath, "-D", "-e", "-f", filepath.Join(dir, "sshd_config")) + cmd.Stdout, cmd.Stderr = &out, &out + if err := cmd.Start(); err != nil { + t.Skip(err) + } + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + deadline := time.Now().Add(5 * time.Second) + for { + c, err := net.DialTimeout("tcp", addr, 100*time.Millisecond) + if err == nil { + c.Close() + break + } + if time.Now().After(deadline) { + t.Skipf("sshd did not start: %s", out.String()) + } + time.Sleep(50 * time.Millisecond) + } + kh := filepath.Join(dir, "known_hosts") + if err := os.WriteFile(kh, []byte(knownhosts.Line([]string{knownhosts.Normalize(addr)}, hostPub)+"\n"), 0o600); err != nil { + t.Fatal(err) + } + pool := conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{ + Home: dir, AgentSocket: "-", KnownHostsFiles: []string{kh}, DefaultIdentityFiles: []string{}, + }}) + t.Cleanup(func() { pool.Close() }) + l, err := pool.Acquire(context.Background(), conn.Endpoint{ + Alias: "sshd", User: u.Username, Host: "127.0.0.1", Port: port, + IdentityFiles: []string{filepath.Join(dir, "client_key")}, IdentitiesOnly: true, + }) + if err != nil { + t.Skipf("cannot log in to the test sshd: %v\n%s", err, out.String()) + } + f := New(l) + t.Cleanup(f.Release) + return f +} + +// SSH_FXP_SYMLINK argument order differs between the draft and OpenSSH; the +// link must point where we asked. +func TestSymlinkOrderOpenSSH(t *testing.T) { + f := realSSHD(t) + ctx := context.Background() + dir := t.TempDir() + if err := f.Symlink(ctx, "target-name", dir+"/link"); err != nil { + t.Fatal(err) + } + got, err := os.Readlink(filepath.Join(dir, "link")) + if err != nil || got != "target-name" { + t.Fatalf("link -> %q (%v), want target-name", got, err) + } + if t2, err := f.ReadLink(ctx, dir+"/link"); err != nil || t2 != "target-name" { + t.Errorf("ReadLink = %q, %v", t2, err) + } + c := f.Caps() + if !c.NoReplace || !c.AtomicReplace { + t.Errorf("OpenSSH caps = %+v", c) + } + if err := os.WriteFile(filepath.Join(dir, "a"), []byte("a"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "b"), []byte("b"), 0o644); err != nil { + t.Fatal(err) + } + if err := f.Rename(ctx, dir+"/a", dir+"/b", vfs.NoReplace); !errors.Is(err, vfs.ErrExist) { + t.Errorf("Rename(NoReplace) onto existing: %v", err) + } +} + +func TestConformanceOpenSSH(t *testing.T) { + vfstest.Run(t, func(t *testing.T) (vfs.FS, string) { return realSSHD(t), t.TempDir() }) +} diff --git a/internal/vfs/sftpfs/sftpfs.go b/internal/vfs/sftpfs/sftpfs.go new file mode 100644 index 0000000..1006237 --- /dev/null +++ b/internal/vfs/sftpfs/sftpfs.go @@ -0,0 +1,491 @@ +// Package sftpfs is vfs.FS over a pooled SSH connection (design §2.4). +// +// Every call takes the current *sftp.Client from the leased conn.Conn, so a +// reconnect is picked up transparently. Metadata calls honour ctx: a +// cancelled ctx returns at once while the abandoned request finishes (or +// fails) in the background; the result is discarded. A call hanging longer +// than the watchdog interval triggers an out-of-band keepalive that marks a +// dead connection Lost, which fails the hung request. +package sftpfs + +import ( + "context" + "errors" + "io" + "io/fs" + "os" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/sftp" + + "vcom/internal/ssh/conn" + "vcom/internal/vfs" +) + +// Watchdog settings (§3.4); variables so tests can shorten them. +var ( + watchdogAfter = 30 * time.Second + watchdogTimeout = 5 * time.Second +) + +// linkStatParallel bounds the Stat calls ReadDir issues for symlink targets. +const linkStatParallel = 16 + +// FS is an SFTP file system. It owns its lease: call Release when the panel +// or job is done with it. +type FS struct { + lease *conn.Lease + c *conn.Conn + caps vfs.Caps + label string + vol vfs.VolumeID + // serverRealPath: the server's REALPATH resolves symlinks (OpenSSH does, + // pkg/sftp's server only cleans the path). + serverRealPath bool +} + +var ( + _ vfs.FS = (*FS)(nil) + _ vfs.Execer = (*FS)(nil) +) + +// New builds an FS on lease and takes ownership of it. +func New(lease *conn.Lease) *FS { + c := lease.Conn() + cc := c.Caps() + openssh := strings.Contains(c.ServerVersion(), "OpenSSH") + return &FS{ + lease: lease, + c: c, + label: c.Endpoint().Label(), + vol: vfs.VolumeID("ssh:" + c.Identity().FingerprintSHA256), + caps: vfs.Caps{ + AtomicReplace: cc.PosixRename, + // OpenSSH implements SSH_FXP_RENAME with link(2)+unlink(2): it + // never replaces. Other servers (pkg/sftp uses rename(2)) may, so + // there NoReplace is only a non-atomic Lstat pre-check. + NoReplace: openssh, + Symlinks: true, + Chmod: true, + Chtimes: true, + Fsync: cc.Fsync, + }, + serverRealPath: openssh, + } +} + +// Release gives the lease back to the pool. Idempotent. +func (f *FS) Release() { f.lease.Release() } + +// Lease returns the lease this FS holds (Acquire on it for a second user). +func (f *FS) Lease() *conn.Lease { return f.lease } + +// Conn exposes the connection (state, reconnect, events). +func (f *FS) Conn() *conn.Conn { return f.c } + +func (f *FS) Kind() vfs.Kind { return vfs.KindSFTP } +func (f *FS) Volume() vfs.VolumeID { return f.vol } +func (f *FS) Caps() vfs.Caps { return f.caps } +func (f *FS) Label() string { return f.label } +func (f *FS) Paths() vfs.PathOps { return vfs.PosixPaths } +func (f *FS) String() string { return "sftp:" + f.label } +func (f *FS) client() (*sftp.Client, error) { + cl, err := f.c.Client() + if err != nil { + return nil, f.mapErr(err) + } + return cl, nil +} + +// call runs fn on the current client, returning early when ctx is done. +func (f *FS) call(ctx context.Context, fn func(cl *sftp.Client) error) error { + if err := ctx.Err(); err != nil { + return err + } + cl, err := f.client() + if err != nil { + return err + } + done := make(chan error, 1) + go func() { done <- fn(cl) }() + wd := time.NewTimer(watchdogAfter) + defer wd.Stop() + for { + select { + case err := <-done: + return err + case <-ctx.Done(): + return ctx.Err() + case <-wd.C: + // Hung for long: check the link out of band. A dead link is + // closed by Probe, which makes fn return with an error. + go f.c.Probe(context.Background(), watchdogTimeout) + } + } +} + +// openCall is call for functions returning an open file: if ctx gives up +// first, the file opened later is closed instead of leaking. +func (f *FS) openCall(ctx context.Context, open func(cl *sftp.Client) (*sftp.File, error)) (*sftp.File, error) { + var mu sync.Mutex + var sf *sftp.File + abandoned := false + err := f.call(ctx, func(cl *sftp.Client) error { + h, err := open(cl) + mu.Lock() + defer mu.Unlock() + if abandoned { + if h != nil { + h.Close() + } + return err + } + sf = h + return err + }) + mu.Lock() + defer mu.Unlock() + if err != nil { + abandoned = true + if sf != nil && ctx.Err() != nil { + sf.Close() + } + return nil, err + } + return sf, nil +} + +func toInfo(name string, fi os.FileInfo) vfs.FileInfo { + return vfs.FileInfo{Name: name, Size: fi.Size(), Mode: fi.Mode(), ModTime: fi.ModTime()} +} + +func base(p string) string { return vfs.PosixPaths.Base(p) } + +func (f *FS) lstatRaw(ctx context.Context, p string) (os.FileInfo, error) { + var fi os.FileInfo + err := f.call(ctx, func(cl *sftp.Client) error { + var err error + fi, err = cl.Lstat(p) + return err + }) + return fi, err +} + +// Stat follows symlinks. +func (f *FS) Stat(ctx context.Context, p string) (vfs.FileInfo, error) { + var fi os.FileInfo + err := f.call(ctx, func(cl *sftp.Client) error { + var err error + fi, err = cl.Stat(p) + return err + }) + if err != nil { + return vfs.FileInfo{}, f.wrap("stat", p, err) + } + return toInfo(base(p), fi), nil +} + +// Lstat does not follow symlinks; for a symlink Target/LinkErr are filled. +func (f *FS) Lstat(ctx context.Context, p string) (vfs.FileInfo, error) { + var out vfs.FileInfo + err := f.call(ctx, func(cl *sftp.Client) error { + fi, err := cl.Lstat(p) + if err != nil { + return err + } + out = toInfo(base(p), fi) + if out.IsSymlink() { + f.fillTarget(cl, p, &out) + } + return nil + }) + if err != nil { + return vfs.FileInfo{}, f.wrap("lstat", p, err) + } + return out, nil +} + +func (f *FS) fillTarget(cl *sftp.Client, p string, fi *vfs.FileInfo) { + t, err := cl.Stat(p) + if err != nil { + fi.LinkErr = f.wrap("stat", p, err) + return + } + ti := toInfo(fi.Name, t) + fi.Target = &ti +} + +// ReadDir lists p with lstat semantics; symlink targets are resolved with +// at most 16 parallel Stat calls. +func (f *FS) ReadDir(ctx context.Context, p string) ([]vfs.FileInfo, error) { + var out []vfs.FileInfo + err := f.call(ctx, func(cl *sftp.Client) error { + ents, err := cl.ReadDir(p) + if err != nil { + return err + } + out = make([]vfs.FileInfo, len(ents)) + sem := make(chan struct{}, linkStatParallel) + var wg sync.WaitGroup + for i, e := range ents { + out[i] = toInfo(e.Name(), e) + if !out[i].IsSymlink() { + continue + } + wg.Add(1) + sem <- struct{}{} + go func(fi *vfs.FileInfo) { + defer wg.Done() + defer func() { <-sem }() + f.fillTarget(cl, vfs.PosixPaths.Join(p, fi.Name), fi) + }(&out[i]) + } + wg.Wait() + return nil + }) + if err != nil { + return nil, f.wrap("readdir", p, err) + } + return out, nil +} + +func (f *FS) ReadLink(ctx context.Context, p string) (string, error) { + var t string + err := f.call(ctx, func(cl *sftp.Client) error { + var err error + t, err = cl.ReadLink(p) + return err + }) + return t, f.wrap("readlink", p, err) +} + +func (f *FS) Open(ctx context.Context, p string) (vfs.File, error) { + sf, err := f.openCall(ctx, func(cl *sftp.Client) (*sftp.File, error) { return cl.Open(p) }) + if err != nil { + return nil, f.wrap("open", p, err) + } + return newFile(ctx, f, sf, p), nil +} + +// Create opens p for writing. CreateExcl fails with vfs.ErrExist on any +// existing entry (a dangling symlink included) and applies perm; CreateTrunc +// keeps an existing file's mode. +func (f *FS) Create(ctx context.Context, p string, perm fs.FileMode, mode vfs.CreateMode) (vfs.File, error) { + flags := os.O_WRONLY | os.O_CREATE + if mode == vfs.CreateExcl { + flags |= os.O_EXCL + } else { + flags |= os.O_TRUNC + } + sf, err := f.openCall(ctx, func(cl *sftp.Client) (*sftp.File, error) { + sf, err := cl.OpenFile(p, flags) + if err == nil && mode == vfs.CreateExcl { + if cerr := sf.Chmod(perm.Perm()); cerr != nil { + sf.Close() + return nil, cerr + } + } + return sf, err + }) + if err != nil { + if mode == vfs.CreateExcl { + return nil, f.existErr(ctx, "create", p, err) + } + return nil, f.wrap("create", p, err) + } + return newFile(ctx, f, sf, p), nil +} + +func (f *FS) Mkdir(ctx context.Context, p string, perm fs.FileMode) error { + err := f.call(ctx, func(cl *sftp.Client) error { + if err := cl.Mkdir(p); err != nil { + return err + } + if perm.Perm() != 0o755 { + return cl.Chmod(p, perm.Perm()) + } + return nil + }) + return f.existErr(ctx, "mkdir", p, err) +} + +// Remove deletes a file, a symlink (never its target) or an empty directory. +func (f *FS) Remove(ctx context.Context, p string) error { + err := f.call(ctx, func(cl *sftp.Client) error { + fi, err := cl.Lstat(p) + if err != nil { + return err + } + if fi.IsDir() { + return cl.RemoveDirectory(p) + } + return cl.Remove(p) + }) + return f.wrap("remove", p, err) +} + +// Rename moves from to to. NoReplace refuses an existing target with +// vfs.ErrExist (atomically on OpenSSH, see Caps.NoReplace). Replace uses +// posix-rename@openssh.com when available; without it an existing target +// yields vfs.ErrExist and the transfer engine renames it aside. +func (f *FS) Rename(ctx context.Context, from, to string, mode vfs.RenameMode) error { + if mode == vfs.NoReplace || !f.caps.AtomicReplace { + if _, err := f.lstatRaw(ctx, to); err == nil { + if _, serr := f.lstatRaw(ctx, from); serr != nil { + return f.wrap("rename", from, serr) + } + return &fs.PathError{Op: "rename", Path: to, Err: vfs.ErrExist} + } + } + err := f.call(ctx, func(cl *sftp.Client) error { + if mode == vfs.Replace && f.caps.AtomicReplace { + return cl.PosixRename(from, to) + } + return cl.Rename(from, to) + }) + if err == nil { + return nil + } + werr := f.wrap("rename", from, err) + if errors.Is(werr, vfs.ErrNotExist) { + return werr + } + return f.existErr(ctx, "rename", to, err) +} + +func (f *FS) Chmod(ctx context.Context, p string, mode fs.FileMode) error { + err := f.call(ctx, func(cl *sftp.Client) error { return cl.Chmod(p, mode.Perm()) }) + return f.wrap("chmod", p, err) +} + +func (f *FS) Chtimes(ctx context.Context, p string, atime, mtime time.Time) error { + err := f.call(ctx, func(cl *sftp.Client) error { return cl.Chtimes(p, atime, mtime) }) + return f.wrap("chtimes", p, err) +} + +// Exec runs argv on the server (vfs.Execer); vfs.ErrUnsupported when the +// server refuses exec (ForceCommand internal-sftp). +func (f *FS) Exec(ctx context.Context, argv []string) ([]byte, error) { + if !f.c.ExecSupported(ctx) { + if err := ctx.Err(); err != nil { + return nil, err + } + return nil, vfs.ErrUnsupported + } + out, _, err := f.c.Exec(ctx, argv, 0) + return out, f.mapErr(err) +} + +// Cancel watchdog for open files: when the ctx a file was opened with is +// cancelled while one of its operations is still running, wait +// cancelGrace for it to return (a live link returns at the next chunk), +// then probe the connection; no keepalive reply within cancelProbeTimeout +// marks it Lost, which fails the stuck request at once. On a slow but live +// link the probe succeeds and nothing is torn down. Variables for tests. +var ( + cancelGrace = 300 * time.Millisecond + cancelProbeTimeout = 1500 * time.Millisecond +) + +// file is an open remote file. +type file struct { + f *sftp.File + fs *FS + path string + + inflight atomic.Int32 + stop func() bool // unregisters the cancel watchdog +} + +func newFile(ctx context.Context, f *FS, sf *sftp.File, p string) *file { + fl := &file{f: sf, fs: f, path: p} + fl.stop = context.AfterFunc(ctx, fl.onCancel) + return fl +} + +func (fl *file) onCancel() { + // No early exit on inflight == 0: an operation may be just starting. + t := time.NewTimer(cancelGrace) + defer t.Stop() + <-t.C + if fl.inflight.Load() == 0 { + return + } + _ = fl.fs.c.Probe(context.Background(), cancelProbeTimeout) +} + +// track marks an operation in flight for the cancel watchdog. +func (fl *file) track() func() { + fl.inflight.Add(1) + return func() { fl.inflight.Add(-1) } +} + +func (fl *file) err(op string, err error) error { + if err == nil || err == io.EOF { + return err + } + return fl.fs.wrap(op, fl.path, err) +} + +func (fl *file) Read(p []byte) (int, error) { + defer fl.track()() + n, err := fl.f.Read(p) + return n, fl.err("read", err) +} + +func (fl *file) ReadAt(p []byte, off int64) (int, error) { + defer fl.track()() + n, err := fl.f.ReadAt(p, off) + return n, fl.err("read", err) +} + +func (fl *file) Write(p []byte) (int, error) { + defer fl.track()() + n, err := fl.f.Write(p) + return n, fl.err("write", err) +} + +// ReadFrom lets io.Copy use pkg/sftp's concurrent writes (N-P1-6). The +// source should expose Size() int64 (os.File, bytes.Reader, the transfer +// engine's ctx reader), otherwise pkg/sftp falls back to sequential writes. +func (fl *file) ReadFrom(r io.Reader) (int64, error) { + defer fl.track()() + n, err := fl.f.ReadFrom(r) + return n, fl.err("write", err) +} + +// WriteTo lets io.Copy use concurrent reads. +func (fl *file) WriteTo(w io.Writer) (int64, error) { + defer fl.track()() + n, err := fl.f.WriteTo(w) + return n, fl.err("read", err) +} + +// Close closes the remote handle. A Close racing a stuck operation (the +// transfer engine closes on cancel) is covered by the cancel watchdog too. +func (fl *file) Close() error { + defer fl.track()() + err := fl.f.Close() + fl.stop() + return fl.err("close", err) +} + +func (fl *file) Stat() (vfs.FileInfo, error) { + defer fl.track()() + fi, err := fl.f.Stat() + if err != nil { + return vfs.FileInfo{}, fl.err("stat", err) + } + return toInfo(base(fl.path), fi), nil +} + +func (fl *file) Sync() error { + if !fl.fs.caps.Fsync { + return &fs.PathError{Op: "sync", Path: fl.path, Err: vfs.ErrUnsupported} + } + defer fl.track()() + return fl.err("sync", fl.f.Sync()) +} diff --git a/internal/vfs/sftpfs/sftpfs_test.go b/internal/vfs/sftpfs/sftpfs_test.go new file mode 100644 index 0000000..2c648cc --- /dev/null +++ b/internal/vfs/sftpfs/sftpfs_test.go @@ -0,0 +1,293 @@ +package sftpfs + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/ssh/conn" + "vcom/internal/testutil/sshtest" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +// stand is an isolated HOME with a server, its keys in known_hosts and a pool. +type stand struct { + t *testing.T + srv *sshtest.Server + pool *conn.Pool + kh string +} + +func newStand(t *testing.T, o sshtest.Options) *stand { + t.Helper() + home := sshtest.IsolatedHome(t) + s := &stand{t: t, srv: sshtest.Start(t, o), kh: filepath.Join(home, ".ssh", "known_hosts")} + s.trust(s.srv.Addr) + s.pool = conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{ + Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh}, + }}) + t.Cleanup(func() { s.pool.Close() }) + return s +} + +// trust appends the server's host keys for addr to known_hosts. +func (s *stand) trust(addr string) { + s.t.Helper() + f, err := os.OpenFile(s.kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + s.t.Fatal(err) + } + defer f.Close() + for _, k := range s.srv.HostKeys { + if _, err := f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(addr)}, k.PublicKey()) + "\n"); err != nil { + s.t.Fatal(err) + } + } +} + +func (s *stand) proxy() *sshtest.Proxy { + px := sshtest.NewProxy(s.t, s.srv.Addr) + s.trust(px.Addr) + return px +} + +func endpoint(addr, password string) conn.Endpoint { + host, port, _ := net.SplitHostPort(addr) + p, _ := strconv.Atoi(port) + return conn.Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password} +} + +// fs opens an FS on addr ("" = the server itself). +func (s *stand) fs(addr string) *FS { + s.t.Helper() + if addr == "" { + addr = s.srv.Addr + } + l, err := s.pool.Acquire(context.Background(), endpoint(addr, s.srv.Password)) + if err != nil { + s.t.Fatalf("acquire: %v", err) + } + f := New(l) + s.t.Cleanup(f.Release) + return f +} + +func TestConformance(t *testing.T) { + vfstest.Run(t, func(t *testing.T) (vfs.FS, string) { + s := newStand(t, sshtest.Options{}) + return s.fs(""), t.TempDir() + }) +} + +// N-P0-5: two aliases of one server (different HostName/port) are one +// volume, so copying a file onto itself through them is detected. +func TestVolumeByHostKey(t *testing.T) { + s := newStand(t, sshtest.Options{}) + direct := s.fs("") + viaProxy := s.fs(s.proxy().Addr) + if direct.Lease().Conn() == viaProxy.Lease().Conn() { + t.Fatal("test needs two distinct connections") + } + if direct.Volume() != viaProxy.Volume() || direct.Volume() == "" { + t.Fatalf("volumes differ: %q vs %q", direct.Volume(), viaProxy.Volume()) + } + dir := t.TempDir() + p := filepath.Join(dir, "f") + if err := os.WriteFile(p, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + same, err := vfs.SameFile(context.Background(), direct, p, viaProxy, p) + if err != nil || !same { + t.Fatalf("SameFile through aliases = %v, %v", same, err) + } + other := newStand(t, sshtest.Options{}).fs("") + if other.Volume() == direct.Volume() { + t.Error("different servers share a volume") + } +} + +// A metadata call on a frozen link returns promptly once ctx is cancelled. +func TestCallCancelReturnsFast(t *testing.T) { + s := newStand(t, sshtest.Options{}) + px := s.proxy() + f := s.fs(px.Addr) + dir := t.TempDir() + px.Freeze(true) + defer px.Freeze(false) + ctx, cancel := context.WithCancel(context.Background()) + var cancelled time.Time + time.AfterFunc(50*time.Millisecond, func() { cancelled = time.Now(); cancel() }) + _, err := f.ReadDir(ctx, dir) + el := time.Since(cancelled) + if !errors.Is(err, vfs.ErrCancelled) { + t.Fatalf("err = %v, want ErrCancelled", err) + } + if el > 100*time.Millisecond { + t.Errorf("returned %v after cancel", el) + } + _, err = f.Open(ctx, filepath.Join(dir, "x")) + if !errors.Is(err, vfs.ErrCancelled) { + t.Errorf("Open with a cancelled ctx: %v", err) + } +} + +// N-P1-6: upload went one 32 KiB packet per RTT (4 MiB at 20 ms RTT took +// seconds). io.Copy into a File must use concurrent writes. +func TestUploadThroughputLatency(t *testing.T) { + s := newStand(t, sshtest.Options{}) + px := s.proxy() + px.SetDelay(10 * time.Millisecond) // RTT ≈ 20 ms + f := s.fs(px.Addr) + dir := t.TempDir() + src := filepath.Join(dir, "big.bin") + data := sshtest.WriteRandom(t, src, 4<<20, 0o644) + lf, err := os.Open(src) + if err != nil { + t.Fatal(err) + } + defer lf.Close() + ctx := context.Background() + + start := time.Now() + rf, err := f.Create(ctx, filepath.Join(dir, "up.bin"), 0o644, vfs.CreateExcl) + if err != nil { + t.Fatal(err) + } + if _, err := io.Copy(rf, lf); err != nil { + t.Fatal(err) + } + if err := rf.Close(); err != nil { + t.Fatal(err) + } + up := time.Since(start) + + start = time.Now() + rf2, err := f.Open(ctx, filepath.Join(dir, "up.bin")) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + if _, err := io.Copy(&buf, rf2); err != nil { + t.Fatal(err) + } + rf2.Close() + down := time.Since(start) + t.Logf("4 MiB @ 20 ms RTT: upload %v, download %v", up, down) + if !bytes.Equal(buf.Bytes(), data) { + t.Fatal("content mismatch") + } + if up > 500*time.Millisecond { + t.Errorf("upload took %v, want <= 500ms", up) + } +} + +func TestConnLostMapsToVFS(t *testing.T) { + s := newStand(t, sshtest.Options{}) + px := s.proxy() + f := s.fs(px.Addr) + dir := t.TempDir() + px.KillAll() + deadline := time.Now().Add(2 * time.Second) + for f.Conn().State() != conn.Lost && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + _, err := f.ReadDir(context.Background(), dir) + if !errors.Is(err, vfs.ErrConnLost) || !errors.Is(err, conn.ErrConnLost) { + t.Fatalf("err = %v, want vfs.ErrConnLost", err) + } + if err := s.pool.Reconnect(context.Background(), f.Conn().Key()); err != nil { + t.Fatal(err) + } + if _, err := f.ReadDir(context.Background(), dir); err != nil { + t.Fatalf("ReadDir after reconnect: %v", err) + } + s.pool.Close() + if _, err := f.Stat(context.Background(), dir); !errors.Is(err, vfs.ErrConnLost) { + t.Errorf("after pool close: %v", err) + } +} + +// The watchdog notices a hung call on a dead link without waiting for the +// regular keepalive. +func TestWatchdogMarksLost(t *testing.T) { + oldAfter, oldTimeout := watchdogAfter, watchdogTimeout + watchdogAfter, watchdogTimeout = 100*time.Millisecond, 100*time.Millisecond + defer func() { watchdogAfter, watchdogTimeout = oldAfter, oldTimeout }() + s := newStand(t, sshtest.Options{}) + px := s.proxy() + f := s.fs(px.Addr) + px.Freeze(true) + defer px.Freeze(false) + start := time.Now() + _, err := f.Stat(context.Background(), t.TempDir()) + if !errors.Is(err, vfs.ErrConnLost) { + t.Fatalf("err = %v, want ErrConnLost", err) + } + if el := time.Since(start); el > 2*time.Second { + t.Errorf("hung call returned after %v", el) + } +} + +func TestCapsAndInfo(t *testing.T) { + s := newStand(t, sshtest.Options{}) + f := s.fs("") + c := f.Caps() + if !c.AtomicReplace || c.NoReplace || c.Fsync || c.Trash || c.Exec || c.ReadOnly || !c.Symlinks { + t.Errorf("caps on pkg/sftp server = %+v", c) + } + if f.Kind() != vfs.KindSFTP || f.Label() != "u@test" || f.Paths().Sep() != '/' { + t.Errorf("kind %v label %q", f.Kind(), f.Label()) + } + out, err := f.Exec(context.Background(), []string{"echo", "a b"}) + if err != nil || string(out) != "a b\n" { + t.Errorf("Exec = %q, %v", out, err) + } + noexec := newStand(t, sshtest.Options{NoExec: true}).fs("") + if _, err := noexec.Exec(context.Background(), []string{"true"}); !errors.Is(err, vfs.ErrUnsupported) { + t.Errorf("Exec without exec: %v", err) + } +} + +// RealPath resolves links even when the server's REALPATH does not. +func TestRealPathResolvesChains(t *testing.T) { + s := newStand(t, sshtest.Options{}) + f := s.fs("") + dir, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(f.Mkdir(ctx, dir+"/real", 0o755)) + must(f.Mkdir(ctx, dir+"/real/sub", 0o755)) + must(f.Symlink(ctx, "real", dir+"/a")) + must(f.Symlink(ctx, dir+"/a/sub", dir+"/b")) + got, err := f.RealPath(ctx, dir+"/b/../sub") + must(err) + if want := dir + "/real/sub"; got != want { + // b -> real/sub, b/.. is real (symlinks resolved before ..), real/sub + t.Errorf("RealPath = %q, want %q", got, want) + } + must(f.Symlink(ctx, "loop", dir+"/loop")) + if _, err := f.RealPath(ctx, dir+"/loop"); err == nil { + t.Error("symlink loop resolved") + } + if _, err := f.RealPath(ctx, dir+"/missing"); !errors.Is(err, vfs.ErrNotExist) { + t.Errorf("missing: %v", err) + } +} diff --git a/internal/vfs/sftpfs/symlink.go b/internal/vfs/sftpfs/symlink.go new file mode 100644 index 0000000..4b7fef3 --- /dev/null +++ b/internal/vfs/sftpfs/symlink.go @@ -0,0 +1,93 @@ +package sftpfs + +import ( + "context" + "errors" + "io/fs" + "strings" + + "github.com/pkg/sftp" + + "vcom/internal/vfs" +) + +var errTooManyLinks = errors.New("too many levels of symbolic links") + +// maxLinks bounds symlink resolution in RealPath (like Linux ELOOP). +const maxLinks = 40 + +// RealPath returns the absolute path with every symlink resolved. OpenSSH's +// REALPATH does this; for other servers it is resolved component by +// component on the client. +func (f *FS) RealPath(ctx context.Context, p string) (string, error) { + var out string + err := f.call(ctx, func(cl *sftp.Client) error { + if f.serverRealPath { + var err error + out, err = cl.RealPath(p) + return err + } + // The server's REALPATH would clean ".." lexically before links are + // resolved; use it only to anchor a relative path. + abs := p + if !vfs.PosixPaths.IsAbs(p) { + wd, err := cl.RealPath(".") + if err != nil { + return err + } + abs = wd + "/" + p + } + var err error + out, err = resolveLinks(cl, abs) + return err + }) + return out, f.wrap("realpath", p, err) +} + +func resolveLinks(cl *sftp.Client, abs string) (string, error) { + ops := vfs.PosixPaths + rest := strings.Split(strings.Trim(abs, "/"), "/") + cur := "/" + links := 0 + for len(rest) > 0 { + name := rest[0] + rest = rest[1:] + if name == "" || name == "." { + continue + } + if name == ".." { + cur = ops.Dir(cur) + continue + } + next := ops.Join(cur, name) + fi, err := cl.Lstat(next) + if err != nil { + return "", err + } + if fi.Mode()&fs.ModeSymlink == 0 { + cur = next + continue + } + if links++; links > maxLinks { + return "", &fs.PathError{Op: "realpath", Path: abs, Err: errTooManyLinks} + } + t, err := cl.ReadLink(next) + if err != nil { + return "", err + } + if ops.IsAbs(t) { + cur = "/" + } + rest = append(strings.Split(strings.Trim(t, "/"), "/"), rest...) + } + return cur, nil +} + +// Symlink creates p pointing at target. pkg/sftp marshals SSH_FXP_SYMLINK in +// OpenSSH's (historically swapped) argument order, which pkg/sftp's server +// also expects, so no per-server swap is needed (verified against a real +// sshd in TestSymlinkOrderOpenSSH, tag integration). +func (f *FS) Symlink(ctx context.Context, target, p string) error { + err := f.call(ctx, func(cl *sftp.Client) error { return cl.Symlink(target, p) }) + return f.existErr(ctx, "symlink", p, err) +} diff --git a/internal/vfs/size.go b/internal/vfs/size.go new file mode 100644 index 0000000..cac5ab4 --- /dev/null +++ b/internal/vfs/size.go @@ -0,0 +1,54 @@ +package vfs + +import "context" + +// SizeResult is the outcome of DirSize. Bytes sums the (lstat) sizes of all +// non-directory entries; Files counts them; Dirs counts directories below the +// root. Unreadable counts subdirectories whose listing failed — when it is +// non-zero the totals are a lower bound ("≥ X, N unreadable"). +type SizeResult struct { + Bytes int64 + Files int + Dirs int + Unreadable int +} + +// DirSize sums the tree under p without following symlinks. An error on the +// root (missing, unreadable, cancelled) is returned; errors on nested +// directories are counted in Unreadable instead (N-P1-14). progress, if +// non-nil, receives the running totals after each directory. +func DirSize(ctx context.Context, fsys FS, p string, progress func(SizeResult)) (SizeResult, error) { + var r SizeResult + err := Walk(ctx, fsys, p, func(q string, fi FileInfo, err error) error { + if err != nil { + if q == p { + return err + } + r.Unreadable++ + return SkipDir + } + switch { + case fi.IsDir(): + if q != p { + r.Dirs++ + } + if progress != nil { + progress(r) + } + default: + r.Files++ + r.Bytes += fi.Size + } + return nil + }) + if err != nil { + return r, err + } + if err := ctx.Err(); err != nil { + return r, err + } + if progress != nil { + progress(r) + } + return r, nil +} diff --git a/internal/vfs/vfs_test.go b/internal/vfs/vfs_test.go new file mode 100644 index 0000000..a87f1c7 --- /dev/null +++ b/internal/vfs/vfs_test.go @@ -0,0 +1,189 @@ +package vfs + +import ( + "context" + "errors" + "io/fs" + "testing" + "time" +) + +// recFS is a fake FS that records which methods reached it. +type recFS struct{ calls []string } + +func (r *recFS) rec(op string) { r.calls = append(r.calls, op) } + +func (r *recFS) Kind() Kind { return KindLocal } +func (r *recFS) Volume() VolumeID { return "fake" } +func (r *recFS) Caps() Caps { return Caps{Trash: true, Exec: true, Chmod: true} } +func (r *recFS) Label() string { return "fake" } +func (r *recFS) Paths() PathOps { return PosixPaths } +func (r *recFS) Stat(context.Context, string) (FileInfo, error) { + r.rec("stat") + return FileInfo{}, nil +} +func (r *recFS) Lstat(context.Context, string) (FileInfo, error) { + r.rec("lstat") + return FileInfo{}, nil +} +func (r *recFS) ReadDir(context.Context, string) ([]FileInfo, error) { + r.rec("readdir") + return nil, nil +} +func (r *recFS) ReadLink(context.Context, string) (string, error) { r.rec("readlink"); return "", nil } +func (r *recFS) RealPath(context.Context, string) (string, error) { r.rec("realpath"); return "", nil } +func (r *recFS) Open(context.Context, string) (File, error) { r.rec("open"); return fakeFile{}, nil } +func (r *recFS) Create(context.Context, string, fs.FileMode, CreateMode) (File, error) { + r.rec("create") + return fakeFile{}, nil +} +func (r *recFS) Mkdir(context.Context, string, fs.FileMode) error { r.rec("mkdir"); return nil } +func (r *recFS) Remove(context.Context, string) error { r.rec("remove"); return nil } +func (r *recFS) Rename(context.Context, string, string, RenameMode) error { + r.rec("rename") + return nil +} +func (r *recFS) Symlink(context.Context, string, string) error { r.rec("symlink"); return nil } +func (r *recFS) Chmod(context.Context, string, fs.FileMode) error { r.rec("chmod"); return nil } +func (r *recFS) Chtimes(context.Context, string, time.Time, time.Time) error { + r.rec("chtimes") + return nil +} +func (r *recFS) Trash(context.Context, string) error { r.rec("trash"); return nil } + +type fakeFile struct{} + +func (fakeFile) Read([]byte) (int, error) { return 0, nil } +func (fakeFile) Write(b []byte) (int, error) { return len(b), nil } +func (fakeFile) ReadAt([]byte, int64) (int, error) { return 0, nil } +func (fakeFile) Close() error { return nil } +func (fakeFile) Stat() (FileInfo, error) { return FileInfo{}, nil } +func (fakeFile) Sync() error { return nil } + +func TestReadOnlyRejectsMutations(t *testing.T) { + ctx := context.Background() + inner := &recFS{} + ro := ReadOnly(inner) + + if !ro.Caps().ReadOnly || ro.Caps().Trash || ro.Caps().Exec { + t.Fatalf("caps = %+v, want ReadOnly and no Trash/Exec", ro.Caps()) + } + if !ro.Caps().Chmod { + t.Fatalf("other caps must pass through: %+v", ro.Caps()) + } + if _, ok := ro.(Trasher); ok { + t.Fatal("read-only wrapper must not expose Trasher") + } + + _, errCreate := ro.Create(ctx, "/a", 0o644, CreateExcl) + muts := map[string]error{ + "create": errCreate, + "mkdir": ro.Mkdir(ctx, "/a", 0o755), + "remove": ro.Remove(ctx, "/a"), + "rename": ro.Rename(ctx, "/a", "/b", Replace), + "symlink": ro.Symlink(ctx, "/a", "/b"), + "chmod": ro.Chmod(ctx, "/a", 0o600), + "chtimes": ro.Chtimes(ctx, "/a", time.Now(), time.Now()), + } + for op, err := range muts { + if !errors.Is(err, ErrReadOnly) { + t.Errorf("%s: err = %v, want ErrReadOnly", op, err) + } + } + if len(inner.calls) != 0 { + t.Fatalf("mutations reached the inner FS: %v", inner.calls) + } + + // Reads pass through; files opened through the wrapper refuse writes. + if _, err := ro.Stat(ctx, "/a"); err != nil { + t.Fatal(err) + } + if _, err := ro.ReadDir(ctx, "/"); err != nil { + t.Fatal(err) + } + f, err := ro.Open(ctx, "/a") + if err != nil { + t.Fatal(err) + } + if _, err := f.Write([]byte("x")); !errors.Is(err, ErrReadOnly) { + t.Fatalf("write through read-only open: %v", err) + } + if got := inner.calls; len(got) != 3 || got[0] != "stat" || got[1] != "readdir" || got[2] != "open" { + t.Fatalf("inner calls = %v", got) + } + if ReadOnly(ro) != ro { + t.Fatal("ReadOnly must not double-wrap") + } +} + +func TestPosixPathOps(t *testing.T) { + p := PosixPaths + if p.Sep() != '/' { + t.Fatal("sep") + } + cases := []struct{ got, want string }{ + {p.Join("/a", "b", "../c"), "/a/c"}, + {p.Join("a", "", "b"), "a/b"}, + {p.Dir("/a/b/c"), "/a/b"}, + {p.Dir("/"), "/"}, + {p.Dir("file"), "."}, + {p.Base("/a/b/"), "b"}, + {p.Base("/"), "/"}, + {p.Clean("/a//b/./c/.."), "/a/b"}, + {p.Clean(""), "."}, + {p.Join("/srv", `back\slash`), `/srv/back\slash`}, // backslash is a normal char in posix + } + for i, c := range cases { + if c.got != c.want { + t.Errorf("case %d: got %q, want %q", i, c.got, c.want) + } + } + if !p.IsAbs("/x") || p.IsAbs("x") { + t.Error("IsAbs") + } + within := []struct { + child, parent string + want bool + }{ + {"/a/b", "/a", true}, + {"/a", "/a/", true}, + {"/ab", "/a", false}, + {"/a/../b", "/a", false}, + {"/anything", "/", true}, + } + for _, c := range within { + if got := IsWithin(p, c.child, c.parent); got != c.want { + t.Errorf("IsWithin(%q, %q) = %v", c.child, c.parent, got) + } + } +} + +func TestLocationSame(t *testing.T) { + a := &recFS{} + l1 := Location{FS: a, Path: "/x/y/"} + l2 := Location{FS: ReadOnly(a), Path: "/x/./y"} + if !l1.Same(l2) { + t.Fatal("same volume and cleaned path must be Same") + } + if l1.Same(Location{FS: a, Path: "/x"}) { + t.Fatal("different paths") + } +} + +func TestFileInfoPredicates(t *testing.T) { + dir := FileInfo{Mode: fs.ModeDir | 0o755} + file := FileInfo{Mode: 0o644} + linkDir := FileInfo{Mode: fs.ModeSymlink, Target: &dir} + linkFile := FileInfo{Mode: fs.ModeSymlink, Target: &file} + broken := FileInfo{Mode: fs.ModeSymlink, LinkErr: ErrNotExist} + fifo := FileInfo{Mode: fs.ModeNamedPipe} + if !dir.NavigableDir() || !linkDir.NavigableDir() || linkFile.NavigableDir() || broken.NavigableDir() { + t.Error("NavigableDir") + } + if linkDir.IsDir() || !linkDir.IsSymlink() { + t.Error("a link to a dir is not itself a dir") + } + if !file.IsRegularLike() || !linkFile.IsRegularLike() || fifo.IsRegularLike() || broken.IsRegularLike() { + t.Error("IsRegularLike") + } +} diff --git a/internal/vfs/vfstest/conformance.go b/internal/vfs/vfstest/conformance.go new file mode 100644 index 0000000..0b4c868 --- /dev/null +++ b/internal/vfs/vfstest/conformance.go @@ -0,0 +1,468 @@ +// Package vfstest holds the conformance suite every vfs.FS must pass and +// FaultFS, a wrapper that injects errors, delays and blocking (design §11.1, +// §11.3). +// +// func TestConformance(t *testing.T) { +// vfstest.Run(t, func(t *testing.T) (vfs.FS, string) { return localfs.New(), t.TempDir() }) +// } +package vfstest + +import ( + "bytes" + "context" + "errors" + "io" + "io/fs" + "sort" + "strings" + "testing" + "time" + + "vcom/internal/vfs" +) + +// Factory returns the FS under test and an existing, empty, writable +// directory on it. It is called once per subtest. +type Factory func(t *testing.T) (fsys vfs.FS, root string) + +// Run executes the conformance suite. Everything is set up and checked +// through the vfs API only, so the same suite runs over SFTP. Subtests that +// need an optional capability (symlinks, chmod, chtimes, atomic replace) are +// skipped when Caps says it is missing. Read-only FSes are not supported yet +// (they need a pre-built fixture; see archivefs, stage 5A). +func Run(t *testing.T, newFS Factory) { + t.Helper() + tests := []struct { + name string + fn func(t *testing.T, h *h) + }{ + {"LstatStatSymlinks", testLstatStatSymlinks}, + {"ReadDirSymlinks", testReadDirSymlinks}, + {"CreateExcl", testCreateExcl}, + {"CreateTrunc", testCreateTrunc}, + {"OpenReadAt", testOpenReadAt}, + {"Mkdir", testMkdir}, + {"RenameNoReplace", testRenameNoReplace}, + {"RenameReplace", testRenameReplace}, + {"Remove", testRemove}, + {"RemoveDoesNotFollowLinks", testRemoveDoesNotFollowLinks}, + {"RemoveTreeSymlinkToDir", testRemoveTreeSymlinkToDir}, + {"Chmod", testChmod}, + {"Chtimes", testChtimes}, + {"RealPath", testRealPath}, + {"ErrorMapping", testErrorMapping}, + {"Sync", testSync}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + fsys, root := newFS(t) + if fsys.Caps().ReadOnly { + t.Skip("read-only FS: conformance needs a writable root") + } + tc.fn(t, &h{t: t, fs: fsys, root: root, ctx: context.Background()}) + }) + } +} + +// h bundles the FS under test with small assertion helpers. +type h struct { + t *testing.T + fs vfs.FS + root string + ctx context.Context +} + +func (h *h) p(elem ...string) string { + return h.fs.Paths().Join(append([]string{h.root}, elem...)...) +} + +func (h *h) must(err error, what string) { + h.t.Helper() + if err != nil { + h.t.Fatalf("%s: %v", what, err) + } +} + +func (h *h) write(name, content string) { + h.t.Helper() + f, err := h.fs.Create(h.ctx, h.p(name), 0o644, vfs.CreateExcl) + h.must(err, "create "+name) + _, err = io.WriteString(f, content) + h.must(err, "write "+name) + h.must(f.Close(), "close "+name) +} + +func (h *h) read(name string) string { + h.t.Helper() + f, err := h.fs.Open(h.ctx, h.p(name)) + h.must(err, "open "+name) + defer f.Close() + b, err := io.ReadAll(f) + h.must(err, "read "+name) + return string(b) +} + +func (h *h) mkdir(name string) { + h.t.Helper() + h.must(h.fs.Mkdir(h.ctx, h.p(name), 0o755), "mkdir "+name) +} + +func (h *h) symlink(target, name string) { + h.t.Helper() + h.must(h.fs.Symlink(h.ctx, target, h.p(name)), "symlink "+name) +} + +func (h *h) needSymlinks() { + h.t.Helper() + if !h.fs.Caps().Symlinks { + h.t.Skip("FS has no symlinks") + } +} + +func (h *h) exists(name string) bool { + h.t.Helper() + _, err := h.fs.Lstat(h.ctx, h.p(name)) + if err != nil && !errors.Is(err, vfs.ErrNotExist) { + h.t.Fatalf("lstat %s: %v", name, err) + } + return err == nil +} + +func (h *h) wantErr(err error, target error, what string) { + h.t.Helper() + if !errors.Is(err, target) { + h.t.Fatalf("%s: err = %v, want %v", what, err, target) + } +} + +// fixture: file f ("hello"), dir d with d/inner, links lf->f, ld->d, broken->missing. +func (h *h) linkFixture() { + h.t.Helper() + h.needSymlinks() + h.write("f", "hello") + h.mkdir("d") + h.write("d/inner", "x") + h.symlink("f", "lf") + h.symlink("d", "ld") + h.symlink("missing", "broken") +} + +func testLstatStatSymlinks(t *testing.T, h *h) { + h.linkFixture() + li, err := h.fs.Lstat(h.ctx, h.p("ld")) + h.must(err, "lstat ld") + if !li.IsSymlink() || li.IsDir() || li.Name != "ld" { + t.Fatalf("Lstat(ld) = %+v, want a symlink named ld", li) + } + if li.Target == nil || !li.Target.IsDir() || !li.NavigableDir() { + t.Fatalf("Lstat(ld).Target = %+v, want a directory", li.Target) + } + si, err := h.fs.Stat(h.ctx, h.p("ld")) + h.must(err, "stat ld") + if !si.IsDir() || si.IsSymlink() { + t.Fatalf("Stat(ld) = %+v, want the directory", si) + } + si, err = h.fs.Stat(h.ctx, h.p("lf")) + h.must(err, "stat lf") + if !si.Mode.IsRegular() || si.Size != 5 { + t.Fatalf("Stat(lf) = %+v, want a 5-byte regular file", si) + } + bi, err := h.fs.Lstat(h.ctx, h.p("broken")) + h.must(err, "lstat broken") + if !bi.IsSymlink() || bi.Target != nil || bi.LinkErr == nil { + t.Fatalf("Lstat(broken) = %+v, want symlink with Target=nil and LinkErr", bi) + } + _, err = h.fs.Stat(h.ctx, h.p("broken")) + h.wantErr(err, vfs.ErrNotExist, "Stat(broken)") + tgt, err := h.fs.ReadLink(h.ctx, h.p("ld")) + h.must(err, "readlink") + if tgt != "d" { + t.Fatalf("ReadLink(ld) = %q, want %q", tgt, "d") + } + fi, err := h.fs.Lstat(h.ctx, h.p("f")) + h.must(err, "lstat f") + if fi.IsSymlink() || fi.Target != nil || !fi.Mode.IsRegular() { + t.Fatalf("Lstat(f) = %+v", fi) + } +} + +func testReadDirSymlinks(t *testing.T, h *h) { + h.linkFixture() + ents, err := h.fs.ReadDir(h.ctx, h.root) + h.must(err, "readdir") + by := map[string]vfs.FileInfo{} + var names []string + for _, e := range ents { + by[e.Name] = e + names = append(names, e.Name) + } + sort.Strings(names) + if strings.Join(names, ",") != "broken,d,f,ld,lf" { + t.Fatalf("names = %v", names) + } + if e := by["d"]; !e.IsDir() || e.IsSymlink() { + t.Errorf("d = %+v", e) + } + if e := by["f"]; !e.Mode.IsRegular() || e.Size != 5 { + t.Errorf("f = %+v", e) + } + if e := by["ld"]; !e.IsSymlink() || e.IsDir() || !e.NavigableDir() { + t.Errorf("ld = %+v (Target %+v), want symlink with NavigableDir", e, e.Target) + } + if e := by["lf"]; !e.IsSymlink() || e.NavigableDir() || !e.IsRegularLike() { + t.Errorf("lf = %+v", e) + } + if e := by["broken"]; !e.IsSymlink() || e.Target != nil || e.LinkErr == nil { + t.Errorf("broken = %+v", e) + } +} + +func testCreateExcl(t *testing.T, h *h) { + h.write("a", "first") + _, err := h.fs.Create(h.ctx, h.p("a"), 0o644, vfs.CreateExcl) + h.wantErr(err, vfs.ErrExist, "CreateExcl on existing file") + if got := h.read("a"); got != "first" { + t.Fatalf("existing file changed by failed CreateExcl: %q", got) + } + _, err = h.fs.Create(h.ctx, h.p("nodir", "a"), 0o644, vfs.CreateExcl) + h.wantErr(err, vfs.ErrNotExist, "Create in missing directory") + if h.fs.Caps().Symlinks { + // O_EXCL never follows a (dangling) symlink. + h.symlink("elsewhere", "trap") + _, err = h.fs.Create(h.ctx, h.p("trap"), 0o644, vfs.CreateExcl) + h.wantErr(err, vfs.ErrExist, "CreateExcl on dangling symlink") + if h.exists("elsewhere") { + t.Fatal("CreateExcl followed a dangling symlink") + } + } +} + +func testCreateTrunc(t *testing.T, h *h) { + h.write("a", "a long first version") + f, err := h.fs.Create(h.ctx, h.p("a"), 0o644, vfs.CreateTrunc) + h.must(err, "CreateTrunc") + _, err = io.WriteString(f, "short") + h.must(err, "write") + h.must(f.Close(), "close") + if got := h.read("a"); got != "short" { + t.Fatalf("after CreateTrunc: %q", got) + } +} + +func testOpenReadAt(t *testing.T, h *h) { + content := strings.Repeat("0123456789", 1000) + h.write("big", content) + f, err := h.fs.Open(h.ctx, h.p("big")) + h.must(err, "open") + defer f.Close() + buf := make([]byte, 10) + n, err := f.ReadAt(buf, 5005) + if n != 10 || (err != nil && err != io.EOF) { + t.Fatalf("ReadAt = %d, %v", n, err) + } + if string(buf) != "5678901234" { + t.Fatalf("ReadAt content %q", buf) + } + fi, err := f.Stat() + h.must(err, "file stat") + if fi.Size != int64(len(content)) { + t.Fatalf("File.Stat size %d", fi.Size) + } + all, err := io.ReadAll(f) + h.must(err, "read") + if !bytes.Equal(all, []byte(content)) { + t.Fatal("content mismatch") + } +} + +func testMkdir(t *testing.T, h *h) { + h.mkdir("d") + fi, err := h.fs.Stat(h.ctx, h.p("d")) + h.must(err, "stat") + if !fi.IsDir() { + t.Fatalf("not a dir: %+v", fi) + } + h.wantErr(h.fs.Mkdir(h.ctx, h.p("d"), 0o755), vfs.ErrExist, "Mkdir existing dir") + h.write("f", "") + h.wantErr(h.fs.Mkdir(h.ctx, h.p("f"), 0o755), vfs.ErrExist, "Mkdir over a file") + h.wantErr(h.fs.Mkdir(h.ctx, h.p("no", "such"), 0o755), vfs.ErrNotExist, "Mkdir with missing parent") +} + +func testRenameNoReplace(t *testing.T, h *h) { + h.write("src", "new") + h.write("dst", "old") + err := h.fs.Rename(h.ctx, h.p("src"), h.p("dst"), vfs.NoReplace) + h.wantErr(err, vfs.ErrExist, "Rename(NoReplace) onto existing file") + if got := h.read("dst"); got != "old" { + t.Fatalf("target changed: %q", got) + } + if got := h.read("src"); got != "new" { + t.Fatalf("source changed: %q", got) + } + h.must(h.fs.Rename(h.ctx, h.p("src"), h.p("moved"), vfs.NoReplace), "rename to free name") + if h.exists("src") || h.read("moved") != "new" { + t.Fatal("rename to free name did not move") + } + h.mkdir("d1") + h.write("d1/x", "1") + h.mkdir("d2") + h.wantErr(h.fs.Rename(h.ctx, h.p("d1"), h.p("d2"), vfs.NoReplace), vfs.ErrExist, "Rename(NoReplace) dir onto empty dir") + h.must(h.fs.Rename(h.ctx, h.p("d1"), h.p("d3"), vfs.NoReplace), "rename dir") + if h.read("d3/x") != "1" { + t.Fatal("dir content lost") + } +} + +func testRenameReplace(t *testing.T, h *h) { + if !h.fs.Caps().AtomicReplace { + t.Skip("no atomic replace: the transfer engine renames aside instead") + } + h.write("src", "new") + h.write("dst", "old") + h.must(h.fs.Rename(h.ctx, h.p("src"), h.p("dst"), vfs.Replace), "Rename(Replace)") + if h.exists("src") { + t.Fatal("source still exists") + } + if got := h.read("dst"); got != "new" { + t.Fatalf("dst = %q", got) + } + h.must(h.fs.Rename(h.ctx, h.p("dst"), h.p("free"), vfs.Replace), "Rename(Replace) to free name") +} + +func testRemove(t *testing.T, h *h) { + h.write("f", "x") + h.must(h.fs.Remove(h.ctx, h.p("f")), "remove file") + if h.exists("f") { + t.Fatal("file still exists") + } + h.mkdir("empty") + h.must(h.fs.Remove(h.ctx, h.p("empty")), "remove empty dir") + if h.exists("empty") { + t.Fatal("empty dir still exists") + } + h.mkdir("full") + h.write("full/keep", "k") + if err := h.fs.Remove(h.ctx, h.p("full")); err == nil { + t.Fatal("Remove of a non-empty directory succeeded") + } + if h.read("full/keep") != "k" { + t.Fatal("non-empty dir content damaged") + } + h.wantErr(h.fs.Remove(h.ctx, h.p("missing")), vfs.ErrNotExist, "Remove missing") +} + +func testRemoveDoesNotFollowLinks(t *testing.T, h *h) { + h.linkFixture() + h.must(h.fs.Remove(h.ctx, h.p("ld")), "remove link to dir") + h.must(h.fs.Remove(h.ctx, h.p("lf")), "remove link to file") + h.must(h.fs.Remove(h.ctx, h.p("broken")), "remove broken link") + if h.exists("ld") || h.exists("lf") || h.exists("broken") { + t.Fatal("links still exist") + } + if h.read("f") != "hello" || h.read("d/inner") != "x" { + t.Fatal("link targets damaged") + } +} + +func testRemoveTreeSymlinkToDir(t *testing.T, h *h) { + h.needSymlinks() + h.mkdir("data") + h.write("data/precious", "keep me") + h.symlink("data", "link") + h.mkdir("tree") + h.write("tree/f", "x") + h.symlink("../data", "tree/inner") + h.must(vfs.RemoveTree(h.ctx, h.fs, h.p("link"), nil), "RemoveTree(link)") + h.must(vfs.RemoveTree(h.ctx, h.fs, h.p("tree"), nil), "RemoveTree(tree)") + if h.exists("link") || h.exists("tree") { + t.Fatal("not removed") + } + if h.read("data/precious") != "keep me" { + t.Fatal("RemoveTree followed a symlink into its target (N-P0-3)") + } +} + +func testChmod(t *testing.T, h *h) { + if !h.fs.Caps().Chmod { + t.Skip("no chmod") + } + h.write("f", "") + for _, m := range []fs.FileMode{0o600, 0o755, 0o640} { + h.must(h.fs.Chmod(h.ctx, h.p("f"), m), "chmod") + fi, err := h.fs.Stat(h.ctx, h.p("f")) + h.must(err, "stat") + if fi.Mode.Perm() != m { + t.Fatalf("mode = %v, want %v", fi.Mode.Perm(), m) + } + } + h.wantErr(h.fs.Chmod(h.ctx, h.p("missing"), 0o600), vfs.ErrNotExist, "Chmod missing") +} + +func testChtimes(t *testing.T, h *h) { + if !h.fs.Caps().Chtimes { + t.Skip("no chtimes") + } + h.write("f", "") + mt := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC) // whole seconds: SFTP v3 has no sub-second times + h.must(h.fs.Chtimes(h.ctx, h.p("f"), mt, mt), "chtimes") + fi, err := h.fs.Stat(h.ctx, h.p("f")) + h.must(err, "stat") + if !fi.ModTime.Equal(mt) { + t.Fatalf("mtime = %v, want %v", fi.ModTime, mt) + } + h.mkdir("d") + h.must(h.fs.Chtimes(h.ctx, h.p("d"), mt, mt), "chtimes dir") + fi, err = h.fs.Stat(h.ctx, h.p("d")) + h.must(err, "stat dir") + if !fi.ModTime.Equal(mt) { + t.Fatalf("dir mtime = %v", fi.ModTime) + } +} + +func testRealPath(t *testing.T, h *h) { + h.mkdir("d") + rd, err := h.fs.RealPath(h.ctx, h.p("d")) + h.must(err, "realpath d") + if !h.fs.Paths().IsAbs(rd) { + t.Fatalf("RealPath not absolute: %q", rd) + } + if h.fs.Caps().Symlinks { + h.symlink("d", "ld") + rl, err := h.fs.RealPath(h.ctx, h.p("ld")) + h.must(err, "realpath ld") + if rl != rd { + t.Fatalf("RealPath(ld) = %q, want %q", rl, rd) + } + } +} + +func testErrorMapping(t *testing.T, h *h) { + missing := h.p("missing") + _, err := h.fs.Stat(h.ctx, missing) + h.wantErr(err, vfs.ErrNotExist, "Stat") + _, err = h.fs.Lstat(h.ctx, missing) + h.wantErr(err, vfs.ErrNotExist, "Lstat") + _, err = h.fs.ReadDir(h.ctx, missing) + h.wantErr(err, vfs.ErrNotExist, "ReadDir") + _, err = h.fs.Open(h.ctx, missing) + h.wantErr(err, vfs.ErrNotExist, "Open") + h.wantErr(h.fs.Rename(h.ctx, missing, h.p("x"), vfs.NoReplace), vfs.ErrNotExist, "Rename missing source") + h.write("file", "") + if _, err := h.fs.ReadDir(h.ctx, h.p("file")); err == nil { + t.Fatal("ReadDir on a regular file succeeded") + } +} + +func testSync(t *testing.T, h *h) { + f, err := h.fs.Create(h.ctx, h.p("s"), 0o644, vfs.CreateExcl) + h.must(err, "create") + defer f.Close() + _, err = io.WriteString(f, "data") + h.must(err, "write") + err = f.Sync() + if h.fs.Caps().Fsync { + h.must(err, "Sync with Caps.Fsync") + } else { + h.wantErr(err, vfs.ErrUnsupported, "Sync without Caps.Fsync") + } +} diff --git a/internal/vfs/vfstest/faultfs.go b/internal/vfs/vfstest/faultfs.go new file mode 100644 index 0000000..49f2b08 --- /dev/null +++ b/internal/vfs/vfstest/faultfs.go @@ -0,0 +1,272 @@ +package vfstest + +import ( + "context" + "io/fs" + "sync" + "sync/atomic" + "time" + + "vcom/internal/vfs" +) + +// Op names an operation FaultFS can intercept. +type Op string + +const ( + OpStat Op = "stat" + OpLstat Op = "lstat" + OpReadDir Op = "readdir" + OpReadLink Op = "readlink" + OpRealPath Op = "realpath" + OpOpen Op = "open" + OpCreate Op = "create" + OpMkdir Op = "mkdir" + OpRemove Op = "remove" + OpRename Op = "rename" // p is the source + OpSymlink Op = "symlink" + OpChmod Op = "chmod" + OpChtimes Op = "chtimes" + OpTrash Op = "trash" + // File methods; p is the path the file was opened or created with. + OpRead Op = "read" // Read and ReadAt + OpWrite Op = "write" + OpClose Op = "close" + OpSync Op = "sync" +) + +// FaultFS wraps an FS and calls Hook before every operation. A non-nil error +// from Hook is returned instead of calling the inner FS (for Close the file is +// still closed). Hook may also sleep or block on a channel. A nil Hook passes +// everything through. Hook may be called from several goroutines. +type FaultFS struct { + vfs.FS + Hook func(op Op, p string) error +} + +var ( + _ vfs.FS = (*FaultFS)(nil) + _ vfs.Trasher = (*FaultFS)(nil) + _ vfs.BirthTimer = (*FaultFS)(nil) +) + +func (f *FaultFS) hook(op Op, p string) error { + if f.Hook == nil { + return nil + } + return f.Hook(op, p) +} + +func (f *FaultFS) Stat(ctx context.Context, p string) (vfs.FileInfo, error) { + if err := f.hook(OpStat, p); err != nil { + return vfs.FileInfo{}, err + } + return f.FS.Stat(ctx, p) +} + +func (f *FaultFS) Lstat(ctx context.Context, p string) (vfs.FileInfo, error) { + if err := f.hook(OpLstat, p); err != nil { + return vfs.FileInfo{}, err + } + return f.FS.Lstat(ctx, p) +} + +func (f *FaultFS) ReadDir(ctx context.Context, p string) ([]vfs.FileInfo, error) { + if err := f.hook(OpReadDir, p); err != nil { + return nil, err + } + return f.FS.ReadDir(ctx, p) +} + +func (f *FaultFS) ReadLink(ctx context.Context, p string) (string, error) { + if err := f.hook(OpReadLink, p); err != nil { + return "", err + } + return f.FS.ReadLink(ctx, p) +} + +func (f *FaultFS) RealPath(ctx context.Context, p string) (string, error) { + if err := f.hook(OpRealPath, p); err != nil { + return "", err + } + return f.FS.RealPath(ctx, p) +} + +func (f *FaultFS) Open(ctx context.Context, p string) (vfs.File, error) { + if err := f.hook(OpOpen, p); err != nil { + return nil, err + } + file, err := f.FS.Open(ctx, p) + if err != nil { + return nil, err + } + return &faultFile{File: file, fs: f, p: p}, nil +} + +func (f *FaultFS) Create(ctx context.Context, p string, perm fs.FileMode, mode vfs.CreateMode) (vfs.File, error) { + if err := f.hook(OpCreate, p); err != nil { + return nil, err + } + file, err := f.FS.Create(ctx, p, perm, mode) + if err != nil { + return nil, err + } + return &faultFile{File: file, fs: f, p: p}, nil +} + +func (f *FaultFS) Mkdir(ctx context.Context, p string, perm fs.FileMode) error { + if err := f.hook(OpMkdir, p); err != nil { + return err + } + return f.FS.Mkdir(ctx, p, perm) +} + +func (f *FaultFS) Remove(ctx context.Context, p string) error { + if err := f.hook(OpRemove, p); err != nil { + return err + } + return f.FS.Remove(ctx, p) +} + +func (f *FaultFS) Rename(ctx context.Context, from, to string, mode vfs.RenameMode) error { + if err := f.hook(OpRename, from); err != nil { + return err + } + return f.FS.Rename(ctx, from, to, mode) +} + +func (f *FaultFS) Symlink(ctx context.Context, target, p string) error { + if err := f.hook(OpSymlink, p); err != nil { + return err + } + return f.FS.Symlink(ctx, target, p) +} + +func (f *FaultFS) Chmod(ctx context.Context, p string, mode fs.FileMode) error { + if err := f.hook(OpChmod, p); err != nil { + return err + } + return f.FS.Chmod(ctx, p, mode) +} + +func (f *FaultFS) Chtimes(ctx context.Context, p string, atime, mtime time.Time) error { + if err := f.hook(OpChtimes, p); err != nil { + return err + } + return f.FS.Chtimes(ctx, p, atime, mtime) +} + +// Trash forwards to the inner FS, or returns ErrUnsupported if it has no trash. +func (f *FaultFS) Trash(ctx context.Context, p string) error { + if err := f.hook(OpTrash, p); err != nil { + return err + } + if t, ok := f.FS.(vfs.Trasher); ok { + return t.Trash(ctx, p) + } + return vfs.ErrUnsupported +} + +// BirthTime forwards to the inner FS (not hooked). +func (f *FaultFS) BirthTime(ctx context.Context, p string) (time.Time, bool) { + if b, ok := f.FS.(vfs.BirthTimer); ok { + return b.BirthTime(ctx, p) + } + return time.Time{}, false +} + +type faultFile struct { + vfs.File + fs *FaultFS + p string +} + +func (f *faultFile) Read(b []byte) (int, error) { + if err := f.fs.hook(OpRead, f.p); err != nil { + return 0, err + } + return f.File.Read(b) +} + +func (f *faultFile) ReadAt(b []byte, off int64) (int, error) { + if err := f.fs.hook(OpRead, f.p); err != nil { + return 0, err + } + return f.File.ReadAt(b, off) +} + +func (f *faultFile) Write(b []byte) (int, error) { + if err := f.fs.hook(OpWrite, f.p); err != nil { + return 0, err + } + return f.File.Write(b) +} + +func (f *faultFile) Sync() error { + if err := f.fs.hook(OpSync, f.p); err != nil { + return err + } + return f.File.Sync() +} + +func (f *faultFile) Close() error { + herr := f.fs.hook(OpClose, f.p) + cerr := f.File.Close() + if herr != nil { + return herr + } + return cerr +} + +// FailNth returns a Hook that fails the n-th (1-based) call of op with err +// and passes everything else, e.g. ENOSPC on the 3rd write. +func FailNth(op Op, n int, err error) func(Op, string) error { + var count atomic.Int64 + return func(o Op, _ string) error { + if o == op && count.Add(1) == int64(n) { + return err + } + return nil + } +} + +// Gate blocks the operations it is attached to until Release. Entered +// receives a value each time an operation reaches the gate, so a test can +// wait until the code under test is really stuck inside the FS. +type Gate struct { + Entered chan string + release chan struct{} + once sync.Once +} + +// NewGate returns a closed-for-business gate. +func NewGate() *Gate { + return &Gate{Entered: make(chan string, 64), release: make(chan struct{})} +} + +// Hook blocks every op in ops (all ops if none given) until Release. +func (g *Gate) Hook(ops ...Op) func(Op, string) error { + return func(op Op, p string) error { + if len(ops) > 0 && !containsOp(ops, op) { + return nil + } + select { + case g.Entered <- p: + default: + } + <-g.release + return nil + } +} + +// Release unblocks all current and future waiters. +func (g *Gate) Release() { g.once.Do(func() { close(g.release) }) } + +func containsOp(ops []Op, op Op) bool { + for _, o := range ops { + if o == op { + return true + } + } + return false +} diff --git a/internal/vfs/vfstest/faultfs_test.go b/internal/vfs/vfstest/faultfs_test.go new file mode 100644 index 0000000..894f90f --- /dev/null +++ b/internal/vfs/vfstest/faultfs_test.go @@ -0,0 +1,87 @@ +package vfstest_test + +import ( + "context" + "errors" + "io" + "path/filepath" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +func TestFaultFSBlocksAndReleases(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("a", ""), fstree.File("b", "")}) + gate := vfstest.NewGate() + fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: gate.Hook(vfstest.OpReadDir)} + t.Cleanup(gate.Release) + + // Other operations are not gated. + if _, err := fsys.Stat(context.Background(), dir); err != nil { + t.Fatal(err) + } + + type res struct { + n int + err error + } + done := make(chan res, 1) + go func() { + ents, err := fsys.ReadDir(context.Background(), dir) + done <- res{len(ents), err} + }() + select { + case p := <-gate.Entered: + if p != dir { + t.Fatalf("entered with %q", p) + } + case <-time.After(5 * time.Second): + t.Fatal("ReadDir never reached the gate") + } + select { + case r := <-done: + t.Fatalf("ReadDir returned while gated: %+v", r) + case <-time.After(50 * time.Millisecond): + } + gate.Release() + select { + case r := <-done: + if r.err != nil || r.n != 2 { + t.Fatalf("after release: %+v", r) + } + case <-time.After(5 * time.Second): + t.Fatal("ReadDir still blocked after Release") + } +} + +func TestFaultFSFailNthWrite(t *testing.T) { + dir := t.TempDir() + fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: vfstest.FailNth(vfstest.OpWrite, 3, syscall.ENOSPC)} + f, err := fsys.Create(context.Background(), filepath.Join(dir, "f"), 0o644, vfs.CreateExcl) + if err != nil { + t.Fatal(err) + } + defer f.Close() + for i := 1; i <= 4; i++ { + _, err := io.WriteString(f, "x") + if (i == 3) != errors.Is(err, syscall.ENOSPC) { + t.Fatalf("write %d: %v", i, err) + } + } + if _, ok := vfs.FS(fsys).(vfs.Trasher); !ok { + t.Fatal("FaultFS should forward Trasher") + } +} + +// The wrapper itself must not break the contract. +func TestFaultFSConformance(t *testing.T) { + vfstest.Run(t, func(t *testing.T) (vfs.FS, string) { + return &vfstest.FaultFS{FS: localfs.New()}, t.TempDir() + }) +} diff --git a/internal/vfs/vfstest/readonly.go b/internal/vfs/vfstest/readonly.go new file mode 100644 index 0000000..a913ed3 --- /dev/null +++ b/internal/vfs/vfstest/readonly.go @@ -0,0 +1,187 @@ +package vfstest + +import ( + "bytes" + "context" + "errors" + "io" + "sort" + "strings" + "testing" + "time" + + "vcom/internal/vfs" +) + +// FixtureEntry is one node of ReadOnlyFixture. +type FixtureEntry struct { + Path string // slash-separated, relative to the root + Dir bool + Content string + Link string // symlink target +} + +// FixtureBig is the content of "big" in ReadOnlyFixture (for ReadAt). +var FixtureBig = strings.Repeat("0123456789", 1000) + +// ReadOnlyFixture is the tree RunReadOnly expects under its root. The FS +// under test (an archive, a read-only wrapper) is built from it by the test. +var ReadOnlyFixture = []FixtureEntry{ + {Path: "f", Content: "hello"}, + {Path: "big", Content: FixtureBig}, + {Path: "d", Dir: true}, + {Path: "d/inner", Content: "x"}, + {Path: "lf", Link: "f"}, + {Path: "ld", Link: "d"}, + {Path: "broken", Link: "missing"}, +} + +// RunReadOnly checks a read-only FS that contains ReadOnlyFixture at root: +// metadata and symlink semantics, reads (also through a linked directory), +// error mapping, and that every mutation fails with ErrReadOnly. +func RunReadOnly(t *testing.T, fsys vfs.FS, root string) { + t.Helper() + ctx := context.Background() + p := func(elem ...string) string { return fsys.Paths().Join(append([]string{root}, elem...)...) } + must := func(t *testing.T, err error, what string) { + t.Helper() + if err != nil { + t.Fatalf("%s: %v", what, err) + } + } + + t.Run("Caps", func(t *testing.T) { + if !fsys.Caps().ReadOnly { + t.Fatal("Caps().ReadOnly must be true") + } + }) + t.Run("LstatStatSymlinks", func(t *testing.T) { + li, err := fsys.Lstat(ctx, p("ld")) + must(t, err, "lstat ld") + if !li.IsSymlink() || li.IsDir() || !li.NavigableDir() { + t.Fatalf("Lstat(ld) = %+v (Target %+v)", li, li.Target) + } + si, err := fsys.Stat(ctx, p("lf")) + must(t, err, "stat lf") + if !si.Mode.IsRegular() || si.Size != 5 { + t.Fatalf("Stat(lf) = %+v", si) + } + bi, err := fsys.Lstat(ctx, p("broken")) + must(t, err, "lstat broken") + if !bi.IsSymlink() || bi.Target != nil || bi.LinkErr == nil { + t.Fatalf("Lstat(broken) = %+v", bi) + } + if _, err := fsys.Stat(ctx, p("broken")); !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("Stat(broken): %v", err) + } + if l, err := fsys.ReadLink(ctx, p("ld")); err != nil || l != "d" { + t.Fatalf("ReadLink(ld) = %q, %v", l, err) + } + di, err := fsys.Stat(ctx, p("ld", "inner")) + must(t, err, "stat through a linked dir") + if di.Size != 1 { + t.Fatalf("Stat(ld/inner) = %+v", di) + } + }) + t.Run("ReadDir", func(t *testing.T) { + ents, err := fsys.ReadDir(ctx, root) + must(t, err, "readdir") + var names []string + by := map[string]vfs.FileInfo{} + for _, e := range ents { + names = append(names, e.Name) + by[e.Name] = e + } + sort.Strings(names) + if strings.Join(names, ",") != "big,broken,d,f,ld,lf" { + t.Fatalf("names %v", names) + } + if !by["d"].IsDir() || !by["ld"].NavigableDir() || by["broken"].Target != nil || !by["lf"].IsRegularLike() { + t.Fatalf("entries %+v", by) + } + if ents, err := fsys.ReadDir(ctx, p("ld")); err != nil || len(ents) != 1 || ents[0].Name != "inner" { + t.Fatalf("ReadDir(ld) = %v, %v", ents, err) + } + }) + t.Run("OpenReadAt", func(t *testing.T) { + f, err := fsys.Open(ctx, p("big")) + must(t, err, "open") + defer f.Close() + buf := make([]byte, 10) + for _, off := range []int64{5005, 10, 9990} { // forwards, backwards, to the end + n, err := f.ReadAt(buf, off) + if n != 10 || (err != nil && err != io.EOF) || string(buf) != FixtureBig[off:off+10] { + t.Fatalf("ReadAt(%d) = %d %v %q", off, n, err, buf) + } + } + if n, err := f.ReadAt(buf, int64(len(FixtureBig)-3)); n != 3 || err != io.EOF { + t.Fatalf("short ReadAt = %d, %v (want 3, EOF)", n, err) + } + g, err := fsys.Open(ctx, p("ld", "inner")) + must(t, err, "open through a linked dir") + b, err := io.ReadAll(g) + g.Close() + if err != nil || string(b) != "x" { + t.Fatalf("read ld/inner = %q, %v", b, err) + } + h, err := fsys.Open(ctx, p("big")) + must(t, err, "open big again") + defer h.Close() + if fi, err := h.Stat(); err != nil || fi.Size != int64(len(FixtureBig)) { + t.Fatalf("File.Stat = %+v, %v", fi, err) + } + all, err := io.ReadAll(h) + if err != nil || !bytes.Equal(all, []byte(FixtureBig)) { + t.Fatal("sequential read mismatch") + } + }) + t.Run("RealPath", func(t *testing.T) { + rd, err := fsys.RealPath(ctx, p("d")) + must(t, err, "realpath d") + rl, err := fsys.RealPath(ctx, p("ld")) + must(t, err, "realpath ld") + if rd != rl || !fsys.Paths().IsAbs(rd) { + t.Fatalf("RealPath(ld) = %q, RealPath(d) = %q", rl, rd) + } + }) + t.Run("ErrorMapping", func(t *testing.T) { + if _, err := fsys.Stat(ctx, p("missing")); !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("Stat: %v", err) + } + if _, err := fsys.ReadDir(ctx, p("missing")); !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("ReadDir: %v", err) + } + if _, err := fsys.Open(ctx, p("missing")); !errors.Is(err, vfs.ErrNotExist) { + t.Fatalf("Open: %v", err) + } + if _, err := fsys.ReadDir(ctx, p("f")); err == nil { + t.Fatal("ReadDir on a file succeeded") + } + }) + t.Run("MutationsReadOnly", func(t *testing.T) { + _, cerr := fsys.Create(ctx, p("new"), 0o644, vfs.CreateExcl) + errs := map[string]error{ + "create": cerr, + "mkdir": fsys.Mkdir(ctx, p("nd"), 0o755), + "remove": fsys.Remove(ctx, p("f")), + "rename": fsys.Rename(ctx, p("f"), p("g"), vfs.NoReplace), + "symlink": fsys.Symlink(ctx, "f", p("l2")), + "chmod": fsys.Chmod(ctx, p("f"), 0o600), + "chtimes": fsys.Chtimes(ctx, p("f"), time.Now(), time.Now()), + } + for op, err := range errs { + if !errors.Is(err, vfs.ErrReadOnly) { + t.Errorf("%s: %v, want ErrReadOnly", op, err) + } + } + f, err := fsys.Open(ctx, p("f")) + must(t, err, "open") + defer f.Close() + if _, err := f.Write([]byte("x")); err == nil { + t.Error("Write on a read-only file succeeded") + } + if _, err := fsys.Stat(ctx, p("new")); !errors.Is(err, vfs.ErrNotExist) { + t.Error("a failed Create left a file") + } + }) +} diff --git a/internal/vfs/walk.go b/internal/vfs/walk.go new file mode 100644 index 0000000..8d006f7 --- /dev/null +++ b/internal/vfs/walk.go @@ -0,0 +1,61 @@ +package vfs + +import ( + "context" + "errors" + "sort" +) + +// WalkFunc is called for every node Walk visits. err != nil means p could not +// be read: for the root it is the Lstat error (fi is zero); for a directory it +// is the ReadDir error, reported in a second call after the first one for that +// directory succeeded. Returning SkipDir skips a directory's contents (or, for +// a non-directory, the rest of its parent); SkipAll stops the walk with nil. +// Any other error stops the walk and is returned. +type WalkFunc func(p string, fi FileInfo, err error) error + +// Walk visits root and everything under it through Lstat/ReadDir; symlinks are +// reported but never followed. A parent is visited before its children and +// children in name order. ctx is checked before every directory read. +func Walk(ctx context.Context, fsys FS, root string, fn WalkFunc) error { + fi, err := fsys.Lstat(ctx, root) + if err != nil { + err = fn(root, FileInfo{}, err) + } else { + err = walk(ctx, fsys, root, fi, fn) + } + if errors.Is(err, SkipDir) || errors.Is(err, SkipAll) { + return nil + } + return err +} + +func walk(ctx context.Context, fsys FS, p string, fi FileInfo, fn WalkFunc) error { + if err := fn(p, fi, nil); err != nil || !fi.IsDir() { + return err + } + if err := ctx.Err(); err != nil { + return err + } + ents, err := fsys.ReadDir(ctx, p) + if err != nil { + if errors.Is(err, ErrCancelled) { + return err + } + return fn(p, fi, err) + } + sort.Slice(ents, func(i, j int) bool { return ents[i].Name < ents[j].Name }) + ops := fsys.Paths() + for _, e := range ents { + if err := walk(ctx, fsys, ops.Join(p, e.Name), e, fn); err != nil { + if errors.Is(err, SkipDir) { + if e.IsDir() { + continue + } + return nil // SkipDir on a file: skip the rest of this directory + } + return err + } + } + return nil +} diff --git a/plans/rework/01-analysis-network.md b/plans/rework/01-analysis-network.md new file mode 100644 index 0000000..eb9761b --- /dev/null +++ b/plans/rework/01-analysis-network.md @@ -0,0 +1,507 @@ +# 01. Анализ: сетевые соединения и передача файлов + +Ветка: `rework/stabilize` (HEAD `e451402`). Что смотрел: `internal/fs/remote/{client,config,host}.go`, `internal/ui/ssh.go`, +`internal/fs/ops.go`, `internal/fs/archive.go` (в части передачи) и все места в `internal/ui/model.go`, где запускаются +transfer-джобы, обращаются к `*remote.SSHClient` или перезагружают remote-панель. + +Как проверял: +- `go build ./...` — OK; `go vet ./...` — чисто; `go test -race ./...` — проходит, но тестов на `remote` и `ui` нет вообще, + поэтому это ничего не говорит о сети. +- Собрал **стенд для воспроизведения** (вне репозитория, копия проекта в scratchpad). В нём SSH-сервер в том же процессе + (`x/crypto/ssh` + `sftp.NewServer` поверх реальной ФС, exec через `sh -c`, вход по паролю) и TCP-прокси, который умеет + добавлять задержку, «замораживать» трафик и рвать соединение после N байт. Через него вызывается настоящий + `remote.Connect()` (с `HOME`, подменённым на временный каталог, чтобы known_hosts был изолирован). Как его воспроизвести — + в разделе «Стенд для тестировщика» в конце. + +Обозначения: **[ВОСПР]** — воспроизведено тестом на стенде; **[КОД]** — доказано чтением кода (путь исполнения однозначен); +**[ПРЕДП]** — предположение или оценка, тестом не подтверждено. + +Приоритеты: **P0** — крах или потеря/порча данных; **P1** — зависание или неверное поведение; **P2** — мелочи, утечки, мёртвый код. + +--- + +## Сводка (топ-15) + +| # | Приор. | Проблема | Статус | +|---|---|---|---| +| 1 | P0 | Rename (F2) в remote-панели переименовывает **локальный** файл с тем же путём | КОД | +| 2 | P0 | Enter на remote-файле запускает/редактирует/открывает **локальный** файл с тем же путём | КОД | +| 3 | P0 | Удаление remote-симлинка на каталог стирает **содержимое целевого каталога** | ВОСПР | +| 4 | P0 | Перезапись = truncate/RemoveAll до копирования: при ошибке, отмене или обрыве старый файл потерян, остаётся обрубок | ВОСПР | +| 5 | P0 | Копирование файла «в себя» через два алиаса одного сервера обнуляет файл | ВОСПР | +| 6 | P0 | Локально: целевой каталог — симлинк на исходный, при перезаписи исходник уничтожается | ВОСПР | +| 7 | P0 | Гонка `Close()` с идущими операциями (race detector); nil-deref может уронить процесс | ВОСПР (race) | +| 8 | P1 | Блокирующий SFTP-I/O в `Update` → TUI зависает; при пропавшей сети — на минуты | ВОСПР + КОД | +| 9 | P1 | Мёртвое соединение не обнаруживается: нет таймаутов, keepalive молча завершается, переподключения нет | ВОСПР | +| 10 | P1 | Ложная тревога «REMOTE HOST IDENTIFICATION HAS CHANGED» из-за выбора алгоритма host key | ВОСПР | +| 11 | P1 | Host из ~/.ssh/config без `HostName` подключается к `:22`, то есть к **localhost** | ВОСПР | +| 12 | P1 | Upload и remote→remote идут по одному пакету 32 КиБ за RTT: в 26 раз медленнее (20 мс RTT) | ВОСПР | +| 13 | P1 | Отмена не прерывает текущий файл, `cp`/`mv` на сервере и удаление; после отмены может прийти «успех» | ВОСПР | +| 14 | P1 | Симлинки: битый симлинк обрывает всю передачу каталога; симлинк на каталог молча пропускается, а при move удаляется | ВОСПР | +| 15 | P1 | Same-host `cp -r` / `mv` в существующий каталог вкладывает `dst/name/name` | ВОСПР | + +Ниже все проблемы подробно. + +--- + +## P0 — крах / потеря данных + +### P0-1. Rename в remote-панели работает с локальной ФС [КОД] +- **Где:** `internal/ui/model.go:3051` (`openRenameModal` проверяет только archive, remote не проверяет) → + `model.go:1327` → `renameCmd` в `model.go:5104` → `vfs.RenamePath` (`internal/fs/ops.go:342`), а там `os.Rename`. +- **Сценарий:** подключиться к серверу, перейти в `/tmp`, где есть `foo`. Локально тоже есть `/tmp/foo`. F2 → `bar` → + Enter. Локальный `/tmp/foo` переименован в `/tmp/bar`, на сервере ничего не изменилось. Если локального файла нет, придёт + ошибка «no such file», и пользователь сочтёт это «глюком». +- **Причина:** нет абстракции ФС, и операция берёт `selected.Path` как локальный путь. +- **Направление:** все файловые операции выполнять через интерфейс ФС панели (см. «Архитектура»). Минимальный фикс — + `if pane.InRemote() { client.Rename(...) }` (для перезаписи — `PosixRename`). + +### P0-2. Enter / F4 на remote-файле работает с локальным путём [КОД] +- **Где:** `model.go:1902` `handleOpenSelected`: для remote-записей `IsRemote=false`, флаг ставится только у записей-хостов + (`ssh.go:59`, `ssh.go:180-189`). Если запись не каталог, управление уходит в `enterArchive` (`model.go:1946`), + `handleEdit` (`model.go:2580`), `handleExecute` (`model.go:2601`, где вызывается `exec.Command(entry.Path)`) или + `handleOpenExternal`. F4 (`handleEdit`) и F3 → open тоже не проверяют remote. +- **Сценарий:** в remote-панели встать на `/usr/local/bin/deploy.sh` (с битом x) и нажать Enter. Запустится **локальный** + `/usr/local/bin/deploy.sh`, если он есть. На `*.conf` откроется `$EDITOR` с локальным путём: пользователь думает, что + правит конфиг на сервере, а сохраняет новый локальный файл. На `*.zip` вызовется `ExtractArchiveToTemp(remotePath)` по + локальной ФС. +- **Направление:** для remote-файлов Enter/F3/F4 — скачать во временный файл, после редактирования залить обратно + (с проверкой mtime/размера на конфликт); запуск remote-файлов запретить. Самое срочное — заблокировать + execute/edit/archive для `pane.InRemote()`. + +### P0-3. Удаление remote-симлинка на каталог стирает содержимое цели [ВОСПР] +- **Где:** `internal/fs/remote/client.go:479`: `RemoveRecursive` вызывает `c.sftpCli.Stat(path)` (идёт по ссылке), затем + `Walk` → `walk()` на `client.go:785`, там тоже `Stat`, и `ReadDir(link)` читает содержимое цели. +- **Сценарий:** на сервере `ln -s /srv/data link`, в vcom выделить `link`, F8 (удаление), подтвердить. Удаляются все файлы + в `/srv/data/**`, сама ссылка остаётся (`RemoveDirectory(link)` падает, но ошибку уже поздно показывать). Тест + `TestRemoveRecursiveSymlinkToDir`: `err=`, цель пуста. +- **То же место — move:** после remote→local / remote→remote move исходник удаляется через `RemoveRecursive` + (`model.go:6414`). Это сработает на симлинке, если копирование такого источника «прошло». +- **Направление:** `Lstat` на корне. Симлинк удалять через `Remove` и никогда не обходить. В `walk` корень тоже обрабатывать + через `Lstat`. + +### P0-4. Перезапись разрушает цель до успешной записи; обрубки не удаляются [ВОСПР] +- **Где (remote):** `client.go:544` (`sftpCli.Create` = `O_TRUNC`), `client.go:577` (`os.Create`), `client.go:709`. + Нет временного файла, нет удаления частичного файла при ошибке. +- **Где (local):** `ops.go:85` и `ops.go:214`: `os.RemoveAll(targetPath)` выполняется **до** копирования. +- **Сценарий (remote, ВОСПР `TestOverwriteThenDrop`):** на сервере есть `important.db` (2 МиБ). Копируем поверх него новый + файл (8 МиБ), сеть рвётся на 1 МиБ. Результат: `copy to remote: connection lost`, на сервере 1 015 808 байт мусора, старый + файл потерян. +- **Сценарий (local, ВОСПР `TestLocalOverwriteFailureLosesDest`):** исходник нечитаем (или отмена, или ENOSPC), старая цель + уже удалена `RemoveAll`, новой нет. +- **Отмена:** remote-копирование при отмене или ошибке оставляет частично скопированное дерево и обрубок текущего файла. + Локальный `copyFile` обрубок удаляет (`ops.go:466-474`), remote-ветки — нет. +- **Направление:** писать в `name.vcom-part-` в целевом каталоге. После успешных `Close` и `Chmod`/`Chtimes` сделать + атомарный rename (`PosixRename`, extension `posix-rename@openssh.com`; локально — `os.Rename`). При ошибке или отмене + временный файл удалять. Старая цель удаляется только самим rename. + +### P0-5. Тот же файл через два алиаса одного сервера обнуляется [ВОСПР] +- **Где:** `client.go:690` защищается только при `SameHostAs`, а `host.go:57` `SameAs` сравнивает **строку** `HostName` + (и порт). +- **Сценарий:** в левой панели хост `prod` (HostName `10.0.0.5`), в правой `prod-dns` (HostName `prod.example.com`) — это + один сервер. Обе панели в `/data`, F5 на `big.bin`. `Create` обнуляет файл до начала чтения. Тест + `TestSameFileViaAliasTruncates`: было 1 МиБ, стало 0, `err=`. +- **Направление:** перед записью сравнивать идентичность файла, а не имени хоста: открыть источник, затем сделать `Stat` цели + и сравнить (size, mtime, а для OpenSSH — `inode` через расширенные атрибуты, если они есть). Надёжнее всего запись во + временный файл + rename (P0-4): тогда источник в принципе не обрезается. Плюс проверка `realpath` на обеих сторонах, если + host key fingerprint совпадает (это и есть настоящий «тот же сервер»). + +### P0-6. Локально: цель — симлинк-алиас исходного каталога, при перезаписи исходник удаляется [ВОСПР] +- **Где:** `ops.go:534` `samePath` и `ops.go:550` `pathWithin` работают через `filepath.Abs` без `EvalSymlinks`, затем + `RemoveAll` на `ops.go:85`. +- **Сценарий:** `~/alias -> ~/real`. Левая панель в `~/real`, правая в `~/alias`. F5 на `f.txt` → диалог «Overwrite: 1 + existing target» → Enter. `RemoveAll(~/alias/f.txt)` удаляет единственную копию, потом `open ... no such file`. Тест + `TestLocalOverwriteViaSymlinkAlias`. +- **Направление:** сравнивать `os.SameFile(Stat(src), Stat(dst))` и проверять, что `EvalSymlinks(dstDir)` не лежит внутри + `EvalSymlinks(src)`. Плюс схема temp+rename из P0-4. + +### P0-7. Локально: перезапись каталога удаляет файлы, которые есть только в цели [ВОСПР] +- **Где:** `ops.go:85` (и `ops.go:214` для move): каталог заменяется целиком через `RemoveAll`. +- **Сценарий:** `dst/proj/keep.txt` существует, копируем `src/proj` с подтверждением перезаписи — `keep.txt` удалён + (`TestLocalOverwriteDirDeletesExtra`). Все популярные файловые менеджеры (mc, TC, Dolphin) в этом случае **сливают** + каталоги. Remote-ветка при этом сливает (`MkdirAll` + `Create`), то есть поведение local и remote различается. +- **Направление:** слияние каталогов с разрешением конфликтов по файлам (ask/overwrite/skip/newer). Это решение + продукта, нужно обсудить с дизайнером. + +### P0-8. `Close()` клиента гоняется с идущими операциями [ВОСПР race; падение — ПРЕДП] +- **Где:** `client.go:373-402` (`Close` обнуляет `c.sftpCli` и `c.sshConn` без синхронизации), все методы делают + `if c.sftpCli == nil` и затем `c.sftpCli.X()` (повторное чтение поля). `IsConnected` (`client.go:405`) тоже без защиты. +- **Кто закрывает клиента, пока его кто-то использует:** + - `goParent` в корне remote: `model.go:1989`. Передача ушла в фон (клавиша Background), пользователь вышел из хоста — + фоновая джоба продолжает работать с закрытым клиентом; + - `handleMirrorPane`: `model.go:2486`; + - `exitSSHMode`: `model.go:5722`; + - `executeSSHHostDelete`: `model.go:5995`; + - превью (`model.go:2136`) и `remoteDirSizeCmd` (`model.go:4671`) крутятся в своих goroutine. +- **Проверка:** `go test -race` с `ReadDir` в цикле и параллельным `Close()` даёт **DATA RACE** на `client.go:261` против + `client.go:391`. Если `Close` попадёт между проверкой на nil и вызовом, получится вызов метода на nil `*sftp.Client`, то + есть panic в goroutine. Bubble Tea его не перехватывает: процесс падает, терминал остаётся в raw/alt-screen. +- **Направление:** менеджер соединений с подсчётом ссылок (refcount) — панели и джобы берут и отпускают ссылку. + `Close` — под mutex, поля не обнулять (`sftp.Client` после `Close` сам вернёт ошибку). Можно также `atomic.Pointer`. + +--- + +## P1 — зависания / неверное поведение + +### P1-1. Синхронный сетевой I/O в UI-потоке (Update) [КОД + ВОСПР блокировки] +- **Где:** `reloadRemotePane` (`model.go:5823`) → `remoteDirToEntries` → `ReadDir` вызывается синхронно из `Update`: + - `sshConnectMsg` (`model.go:394`); + - `enterRemoteDir` (`model.go:6035`); + - `goParent` (`model.go:2010`); + - refresh (`model.go:1680`); + - `opMsg` (`model.go:524/529`); + - `copyDoneMsg` (`model.go:744-775`); + - mirror (`model.go:2494`). + + Кроме того, `handleTransfer` делает `Lstat` на каждый выбранный источник прямо в `Update` (`model.go:2314`). +- **Сценарий:** медленный канал (VPN, мобильная сеть): каждый вход в каталог замораживает весь интерфейс на время + `ReadDir` (большие каталоги вроде `/usr/lib` — сотни миллисекунд и больше). 2000 отмеченных файлов + F5 дают 2000 RTT + заморозки. Если сеть пропала (Wi-Fi отвалился, ноутбук уснул), `ReadDir` висит без ограничения + (`TestFreezeHangs`: >8 с, `IsConnected()=true`). На реальном TCP это до срабатывания TCP keepalive / retransmit + timeout — от ~2,5 до ~15 минут по умолчаниям Linux [ПРЕДП]. Всё это время не работает даже `q`/Ctrl+C: клавиши тоже + обрабатывает `Update`. +- **Направление:** любой remote-вызов — только из `tea.Cmd`. Ответ приходит сообщением `listingLoadedMsg{paneID, path, + reqID}`, устаревшие ответы отбрасываются по `reqID`. Пока ждём — спиннер «loading…». Проверку существования целей + перенести в джобу (фаза plan). + +### P1-2. Нет обнаружения мёртвого соединения, таймаутов и переподключения [ВОСПР] +- **Где:** keepalive в `client.go:84-99`. `SendRequest(..., wantReply=true)` блокируется на мёртвом соединении, а при ошибке + goroutine просто делает `return`: соединение не закрывается, UI не уведомляется. У SFTP-запросов нет дедлайнов. + `IsConnected` проверяет только поля на nil. Переподключения нет нигде (grep `reconnect` → только комментарий на + `model.go:2490`, который неправду пишет: «the mount will reconnect on reload»). +- **Сценарий:** после сна ноутбука или смены сети панель «живая», но любое действие висит (см. P1-1), а потом приходит + `connection lost`. Восстановиться можно только выходом в список хостов и повторным входом. +- **Направление:** keepalive с таймаутом. Если ответа нет за N с (например 15 с, 3 попытки), `sshConn.Close()` — все + висящие запросы сразу получат ошибку. Затем сообщение `connLostMsg{host}` в UI: панель показывает «disconnected — Enter + для переподключения» или переподключается автоматически с backoff. Дополнительно — обёртка `net.Conn` с + `SetDeadline` на чтение (idle timeout) и `context` на каждой операции джобы. + +### P1-3. `Connect` ограничен таймаутом только на TCP; отмена add-host течёт [КОД] +- **Где:** `client.go:59`: в `ssh.ClientConfig.Timeout` документировано «maximum amount of time for the TCP connection to + establish» (`vendor/golang.org/x/crypto/ssh/client.go:239`). Handshake, аутентификация и `sftp.NewClient` (ожидание + `SSH_FXP_VERSION`) ничем не ограничены. +- **Сценарий:** сервер принял TCP и молчит (перегружен, или порт закрыт фильтром «tarpit»). Статус «Connecting…» висит + бесконечно, `m.busy=true`. В диалоге add-host Esc (`model.go:5905-5916`): если `Connect` ещё не завершился, срабатывает + ветка `default`, goroutine остаётся висеть, а успешно созданный позже клиент никто не закрывает: утечка соединения и + keepalive-goroutine. +- **Направление:** `net.Dialer` с контекстом + `conn.SetDeadline(now+20s)` на время handshake и `sftp.NewClient`, после + чего дедлайн снимается. Cancel закрывает conn. В add-host после отмены дождаться результата в фоне и закрыть клиента. + +### P1-4. Ложная тревога «REMOTE HOST IDENTIFICATION HAS CHANGED» [ВОСПР] +- **Где:** `client.go:55-60` (не задан `HostKeyAlgorithms`) + `client.go:140`. Go-клиент по умолчанию предпочитает ECDSA, а + ED25519 у него последний (`vendor/golang.org/x/crypto/ssh/common.go:179`). OpenSSH обычно записывает в known_hosts + ed25519. +- **Сценарий:** в known_hosts для хоста только ed25519-ключ (обычная ситуация после `ssh host`), сервер предлагает + ecdsa+ed25519. Go договаривается об ECDSA, `knownhosts` возвращает `KeyError{Want: [ed25519]}`, и код выдаёт «MITM, + отказ». Тест `TestHostKeyAlgoMismatch` это воспроизводит. Владелец видит «не подключается к хосту, который работает + в ssh». +- **Направление:** перед Dial собрать из known_hosts алгоритмы для этого хоста и выставить + `config.HostKeyAlgorithms` (стандартный приём — `knownhosts` callback с пробным вызовом или разбор файла). Тревогу + поднимать, только если совпадает тип ключа, а сам ключ другой. + +### P1-5. Разбор ~/.ssh/config: Host без HostName → localhost; другие пропуски [ВОСПР] +- **Где:** `config.go:61-118`, `host.go:49`. +- **Что не так:** + - нет `HostName` (самый частый случай: `Host myserver.example.com` + `User bob`) → `HostName=""` → `Addr()==":22"` → + `ssh.Dial` идёт на **локальную машину** (`TestConfigNoHostName`). Должно использоваться имя из `Host`; + - синтаксис `HostName=10.0.0.1` (через `=`) не разбирается вовсе — хост тоже получает пустой HostName (ВОСПР, тот же + тест); + - игнорируются `Host *` и другие шаблонные блоки с умолчаниями (`User`, `IdentityFile`, `Port`), `Include`, + `ProxyJump`/`ProxyCommand`, `IdentitiesOnly`, кавычки в путях, несколько `IdentityFile`, `Match`; + - удаление комментария по первому `#` ломает значения, в которых есть `#`. +- **Направление:** взять готовый парсер (`github.com/kevinburke/ssh_config`) или хотя бы: HostName по умолчанию = alias, + `key=value`, `Host *` как умолчания, `Include`. ProxyJump реализуется через `ssh.Client.Dial` к следующему хопу. + +### P1-6. Медленный upload и remote→remote: 1 пакет 32 КиБ за RTT [ВОСПР] +- **Где:** `client.go:68`: `sftp.NewClient(sshConn)` без опций. `io.Copy(remoteFile, localFile)` → `File.ReadFrom`, который + без `UseConcurrentWrites` пишет последовательно (`vendor/github.com/pkg/sftp/client.go:2014-2080`). Remote→remote: + `srcFile.WriteTo(dstFile)` → `dstFile.Write` по одному пакету (`client.go:1799-1820`). +- **Замер (`TestUploadThroughputLatency`, 4 МиБ, RTT ≈ 20 мс):** upload сейчас — **2,66 с**; download — 0,14 с; + upload с `UseConcurrentWrites(true)` — **0,10 с**, то есть в 26 раз быстрее. При RTT 100 мс текущий upload упирается + примерно в 320 КБ/с [ПРЕДП, экстраполяция]. Это и есть «копирование хост→хост ужасно медленное / зависло». +- **Направление:** `sftp.NewClient(conn, sftp.UseConcurrentWrites(true), sftp.UseConcurrentReads(true), + sftp.MaxConcurrentRequestsPerFile(64), sftp.UseFstat(true))`. Если сервер — OpenSSH и поддерживает `limits@openssh.com`, + поднять пакет до 256 КиБ через `MaxPacketUnchecked`. Для отмены и прогресса не оборачивать запись в «немой» Writer, иначе + потеряется `ReadFrom`: нужен ctx-aware Reader с `Size()` (тогда `ReadFrom` выберет конкурентный путь) или собственный + pipelined copy. + +### P1-7. Отмена не работает внутри операции; после отмены может прийти «успех» [ВОСПР] +- **Где:** + - `CopyFileToRemote`/`FromRemote`/`BetweenRemotes` вообще не принимают `ctx` (`client.go:527/560/683`), ctx + проверяется только между файлами (`client.go:612`, `648`, `741`); + - same-host `Exec("cp -r ...")`/`mv` (`model.go:6326/6350`) не прерываются, у `Exec` нет ни ctx, ни таймаута + (`client.go:419`); + - `RemoveRecursive` не прерывается, а remote delete проверяет ctx только между верхнеуровневыми путями + (`model.go:6080-6088`). +- **Сценарий (`TestCancelSingleFile`):** каталог с одним файлом 3 МиБ, отмена на 150 мс. Функция вернулась через 1,05 с с + `err=`: файл докопирован, отмена **проглочена**, UI покажет «Copied». С файлом 10 ГБ пользователь нажимает «Cancel», + видит «cancelling…» и ждёт до конца файла. +- **Направление:** ctx в каждом чтении/записи (reader-обёртка проверяет `ctx.Err()`). Для зависшего сетевого вызова — + закрывать файл-хэндл, а в крайнем случае соединение. Для `Exec` — `session.Signal(KILL)` + `session.Close()` по ctx. + В конце walk повторно проверять `ctx.Err()`. Частичный файл удалять (P0-4). + +### P1-8. Симлинки при передаче [ВОСПР] +- **Где:** upload — `client.go:608` `filepath.Walk` (Lstat) → `CopyFileToRemote` → `os.Open` идёт по ссылке. Download и + remote→remote — `client.go:663/753` пропускают симлинк на каталог, остальные разыменовывают. +- **Сценарии:** + - каталог с битым симлинком (типичные `node_modules/.bin`, venv, `.git`-хуки, `/etc/alternatives`) — **вся** передача + обрывается на нём: upload — `open local: ... no such file or directory`, download — `open remote: file does not exist` + (`TestUploadDirWithBrokenSymlink`, `TestDownloadDirWithBrokenSymlink`). Файлы после него не копируются, уже + скопированные остаются; + - симлинк на каталог при upload: `os.Open(dir)` + `io.Copy` → ошибка «is a directory», передача оборвана [КОД]; + - симлинк на файл копируется как обычный файл (содержимое), а не как ссылка. Локальное копирование + (`ops.go:113/412`) при этом сохраняет ссылки — несогласованность; + - **move** remote→local или remote→remote каталога с симлинком на каталог: при копировании он молча пропущен, затем + `RemoveRecursive` удаляет ссылку в исходнике. Ссылка теряется без следа [КОД]; + - верхнеуровневый источник local→remote — `os.Stat` (`model.go:6253`) идёт по ссылке: симлинк на каталог заливается как + полный каталог. +- **Направление:** единая политика симлинков: по умолчанию копировать как симлинк (`sftp.Symlink` / `os.Symlink` с + `ReadLink`), опция «следовать». Битые ссылки переносятся как ссылки, без ошибки. Ошибки по отдельным файлам собирать + в отчёт, а не обрывать всю джобу (skip/retry/abort). + +### P1-9. Права и mtime теряются [ВОСПР] +- **Где:** `client.go:544` (`Create` → 0666&umask), `client.go:577` (`os.Create`), `client.go:661` (каталоги 0755), нет + `Chmod`/`Chtimes`. Локально `ops.go:443` сохраняет права, но не mtime. +- **Сценарий:** залить скрипт `run.sh` (0755) — на сервере `-rw-r--r--`, запускать нельзя. mtime — время копирования, из-за + этого ломаются rsync/make/бэкапы (`TestPermsMtimeLost`, `TestLocalMtime`). +- **Направление:** после записи `Chmod(mode.Perm())` и `Chtimes(atime, mtime)` (в sftp — `File.Chmod`/`Chtimes`), каталогам + проставлять mtime после заполнения. Для same-host — `cp -a`/`cp -rp`. + +### P1-10. Same-host `cp -r` / `mv` в существующий каталог вкладывает [ВОСПР] +- **Где:** `model.go:6318-6352`: `mv 'src' 'targetDir/base'` и `cp -r 'src' 'targetDir/base'`. +- **Сценарий:** обе панели на одном сервере, в цели уже есть `proj/`. Копирование `proj` создаёт `proj/proj/`, move — + тоже `proj/proj/` (`TestSameHostCpIntoExistingDir`). Это прямо противоречит диалогу «Overwrite: 1 existing target». +- **Ещё в этой ветке:** + - любая ошибка `mv` (нет прав, другой раздел) → fallback на `cp` → fallback на потоковую передачу → `RemoveRecursive`. + Одна и та же ошибка повторяется трижды, и каждая попытка может оставить частичный результат; + - команды выполняются от пользователя **srcClient**, хотя `SameAs` игнорирует `User` (`host.go:57`): в панели `root@srv` + и `bob@srv` файл, «скопированный в bob», окажется с владельцем root; + - `cp` без `-p`/`-a` теряет права и mtime; + - на SFTP-only серверах (`ForceCommand internal-sftp`) exec не работает — это правильно уходит в fallback, но ценой + лишнего RTT и записи в лог. +- **Направление:** same-host move — через `PosixRename` по SFTP (без shell). Copy — `cp -a --no-target-directory` + (`-T`, GNU) или, надёжнее, обычный движок передачи с потоковым копированием; серверный `cp` как оптимизация только после + проверки, что цель отсутствует. Считать хост «тем же» только если совпадают fingerprint ключа хоста и пользователь. + +### P1-11. После remote-delete remote-панели перечитываются как локальные [КОД] +- **Где:** обработчик `archiveDoneMsg`: `model.go:603-604` (ошибка/отмена), `model.go:653-654` (delete), `model.go:683-684` + — безусловно вызывают `reloadPane` (то есть `vfs.ListDir` по **локальной** ФС), без проверки `InRemote()`. + `startRemoteDeleteJob` (`model.go:6047`) использует именно этот путь. +- **Сценарий:** в remote-панели `/home/bob` удалить файл. Если локально есть `/home/bob`, remote-панель покажет **локальные** + файлы, оставаясь при этом в remote-mount. Следующее F8 по «этому» файлу удалит на сервере файл с тем же именем. Если + такого локального каталога нет, ошибка проглочена (`_ =`) и в списке висит уже удалённый файл. +- **Направление:** единая функция `reloadPaneAny(id)`, вызываемая асинхронно (см. P1-1). + +### P1-12. Mirror делит одного клиента; повторный mirror закрывает его [КОД] +- **Где:** `model.go:2483-2494`: пассивной панели кладётся **тот же** `RemoteMount` с тем же `*SSHClient`. Если в пассивной + уже есть mount (например, от прошлого mirror), сначала `existingMount.Client.Close()`. +- **Сценарий:** подключиться слева, mirror, ещё раз mirror. Закрыт общий клиент, обе панели получают «not connected». + Другой вариант: после mirror в одной панели выйти в корень и нажать `..` (`goParent`, `model.go:1989`) — клиент закрыт, + вторая панель «мертва». `ClearRemotes()` (`model.go:2489`) выбрасывает остальные mount’ы стека без `Close` — утечка. +- **Направление:** refcount-пул соединений (P0-8), mirror делает `Acquire`. + +### P1-13. Прогресс врёт [КОД, частично ВОСПР] +- `pending.stats` для remote не заполняется (`handleTransfer`, `model.go:2365-2373`), поэтому `BytesTotal=0`; байты внутри + файла не считаются. Один большой файл показывает «0/1» до конца без ETA. +- `model.go:6181`: `count = 1`, затем для каталога прибавляются файлы — каждый каталог-источник даёт **+1** к total, и + прогресс никогда не доходит до 100%. +- `model.go:6432`: если отработал per-file callback (`trackedProgress`), `doneFiles` **не увеличивается**. При нескольких + источниках-каталогах прогресс второго начинается с прежнего значения и откатывается назад (`dirA 1..10/20`, затем + `dirB 1..10/20`). +- `vfs.CopyStats` для каталога не считает байты: `BytesTotal=0` (`ops.go:146-175`, ВОСПР `TestCopyStatsBytes`). +- Remote delete считает только верхнеуровневые пути. +- **Направление:** фаза plan считает файлы и байты (Lstat-walk). Движок передачи шлёт `{filesDone, bytesDone}` из + reader-обёртки с троттлингом (как уже сделано в `ops.go:512`). + +### P1-14. Размер каталога: ошибки проглатываются [ВОСПР] +- **Где:** `client.go:866-883`: при любой ошибке callback возвращает `filepathSkipDir`, в том числе для корня. +- **Сценарий:** несуществующий или нечитаемый каталог (или обрыв связи посреди walk) → «Directory size calculated: 0 B» + (`TestDirSizeSwallowsError`). Частичные суммы при пропущенных подкаталогах тоже выдаются как точные. +- **Направление:** ошибку корня возвращать; пропущенные подкаталоги считать и показывать «≥ X (N недоступно)». Плюс ctx для + отмены (сейчас долгий walk не отменить). `m.busy` при этом остаётся true до конца. + +### P1-15. Archive/Unpack игнорируют remote-панели [КОД] +- **Где:** `handleArchive` (`model.go:2377`) и `handleUnpack` (`model.go:2447`) не проверяют `InRemote()`. `archive.go` + работает только с `os.*`. +- **Сценарий:** пассивная панель — remote `/home/bob`, активная — локальный архив. Unpack распаковывает в **локальный** + `/home/bob` (через `MkdirAll` создаст путь, если хватает прав). Источник remote — пытается открыть remote-путь локально. +- **Направление:** до появления абстракции ФС запретить с понятным сообщением. Потом — распаковка в temp + upload движком. + +### P1-16. Remote-превью: неограниченные параллельные чтения [КОД, оценка нагрузки — ПРЕДП] +- **Где:** `model.go:2134-2185`: на каждое перемещение курсора своя goroutine читает до `MaxPreviewBytes`; для картинок — + **полное** скачивание файла (`DownloadFile`) во временный файл. Отмены и дедупликации нет. +- **Сценарий:** быстро пролистать каталог с фото по 20 МБ на медленном канале. Десятки параллельных скачиваний делят одно + SSH-соединение с идущей передачей и тормозят её; при «замёрзшем» соединении накапливаются зависшие goroutine. +- **Направление:** debounce 150–200 мс, отмена предыдущего превью (ctx + закрытие файла), лимит размера для скачивания + картинок, одно превью в полёте на панель. + +### P1-17. Локально: копирование read-only каталога падает [ВОСПР] +- **Где:** `ops.go:377`: `MkdirAll(dstDir, info.Mode().Perm())` создаёт каталог 0555 до того, как в него записаны файлы. +- **Сценарий:** скопировать каталог с правами `r-x` (часто встречается в `/usr/share/...`, Go module cache, nix store) → + `mkdir .../ro: permission denied` (в `TestLocalCopyReadOnlyDir` падение на вложенном уровне). Плюс `cleanupOnErr` + потом не сможет удалить такой каталог. +- **Направление:** создавать с 0700, проставлять настоящие права после заполнения (в обратном порядке обхода). + +--- + +## P2 — мелочи, утечки, мёртвый код + +1. **Утечка fd ssh-agent** — `client.go:163-174`: на каждый `Connect` открывается unix-сокет к агенту и никогда не + закрывается. Комментарий признаёт это «на время жизни процесса», но на деле это один сокет на **каждое** подключение, + и они копятся. [КОД] +2. **Аутентификация** — `client.go:179-257`: + - если `IdentityFile` задан и распарсился, агент и стандартные ключи не пробуются: сервер отверг ключ — отказ без + fallback; + - `IdentityFile` указан, но файла нет, и пароля нет — «no authentication methods», хотя агент мог бы подойти; + - для хоста с паролем агент не используется; + - нет запроса passphrase и пароля в UI (keyboard-interactive отвечает сохранённым паролем на **все** вопросы, включая + 2FA-код). [КОД] +3. **`SameAs` игнорирует `User`** — `host.go:57`, последствия см. P1-10. [КОД] +4. **`MkdirAll` на каждый файл** — `client.go:540` (и `705`): лишний `Stat(parent)` на каждый файл даёт +1 RTT на файл. + Вместе с `Create`/`Close` получается ~4–5 RTT на мелкий файл: 10 000 мелких файлов при RTT 50 мс ≈ 40 минут [ПРЕДП, + расчёт]. `MkdirAll` возвращает nil, если путь существует **как файл**, и ошибка всплывает позже с непонятным текстом. +5. **Двойной обход дерева** — фаза 1 (`model.go:6187`) и фаза 2 обходят remote-дерево дважды (каждый `ReadDir` — RTT). +6. **Ошибки `Close()` при записи игнорируются** (`defer remoteFile.Close()`, `client.go:548/581/713`, `ops.go:459`). Для + NFS, FUSE, квот ошибка часто приходит именно на close, а пользователь видит «успех». Fsync перед rename отсутствует. +7. **Remote-листинг** — `ssh.go:149-195`: + - симлинк на каталог имеет `IsDir=false` (SFTP ReadDir работает как lstat), в такой каталог нельзя войти + (`/var/run`, `~/current` у деплоев); + - не применяются `ShowHidden`, `DirsFirst`, сортировка — порядок «как отдал сервер». [КОД] +8. **`sshConnectMsg`** (`model.go:366-402`): + - mount кладётся в панель, активную **в момент ответа**: если за время подключения пользователь переключил панель + (Tab), хост откроется не там; + - двойной Enter — два подключения и два mount в стеке; + - если `reloadRemotePane` упал, mount уже вставлен, а в панели остался список хостов (несогласованное состояние). [КОД] +9. **Мёртвый код:** + - `activeClients` нигде не заполняется (только читается и удаляется: `model.go:5787`, `5994`, `5727`); + - не используются `ExecWithProgress`, `CopyDirToRemote`, `CopyDirFromRemote`, `CopyDirBetweenRemotes`, + `SftpToFileInfo`, `WalkDirEntry`/`NewWalkDirEntry`, `ResolveAddr`, `IsConnected`, `DialTimeout`, `DefaultPort` + (`client.go`). [КОД] +10. **Цель — панель со списком хостов (`ssh://`)**: `filepath.Join("ssh://", name)` = `ssh:/name`, относительный путь. + Копирование каталога создаст `./ssh:/name` в **текущем каталоге процесса** (`copyDir` → `MkdirAll`). [КОД] +11. **Выход (q) во время передачи** (`model.go:1052-1058`): джоба не отменяется, частичные файлы остаются, клиенты не + закрываются. [КОД] +12. **`MoveToTrash`** (`ops.go:280-332`): при переносе между ФС (`EXDEV`) — ошибка, хотя комментарий обещает fallback. + `Path=` в `.trashinfo` не URL-кодируется, как требует спецификация FreeDesktop. [КОД] +13. **Архивы** (`archive.go`): + - ошибки `zipWriter.Close()`/`tarWriter.Close()`/`gzip.Close()` игнорируются (`defer`) — битый архив с отчётом + «успешно»; + - распаковка через `O_TRUNC` пишет сквозь уже существующие симлинки в цели; + - симлинки из tar и zip не восстанавливаются (zip-симлинк станет файлом с текстом пути); + - при ошибке или отмене создания частичный архив не удаляется. [КОД] +14. **TOFU принимает новый ключ молча** — `client.go:144-154`. Это ок для `accept-new`, но стоит показывать fingerprint + в статусе или модалке при первом подключении. [КОД] +15. **`Exec` без таймаута**, `CombinedOutput` без лимита размера (`client.go:419-429`). [КОД] + +--- + +## Потокобезопасность и goroutine — отдельно + +- `*sftp.Client` сам по себе потокобезопасен (pkg/sftp это гарантирует), параллельное использование из превью, dir-size + и джобы допустимо. Проблема в обёртке `SSHClient`: `Close()` и поля без синхронизации (P0-8), а владения нет вообще — + закрыть клиента может кто угодно. +- Каналы прогресса (`copyProgress`, `archiveProgress`, буфер 256) обрабатываются корректно, пока сообщения чужих джоб не + приходят: на чужой `jobID` обработчик **не перезапускает** `waitCopyProgressCmd` (`model.go:719/584`). Сейчас это + безопасно, потому что джоба шлёт `done` последним, а в момент времени возможна одна джоба. Но при введении очереди джоб + это сразу превратится в «прогресс перестал обновляться» и заблокированную goroutine. Помечаю как хрупкое место [ПРЕДП]. +- `Update` — value receiver. Goroutine джоб захватывают `m` — копию модели, из которой читаются только каналы. Гонок по + модели race detector не нашёл бы, но и тестов `ui` нет [ПРЕДП: явных гонок не видно]. +- Утечки goroutine: keepalive у клиентов, которые никто не закрыл (add-host cancel — P1-3; mirror `ClearRemotes` — + P1-12); зависшие превью на мёртвом соединении (P1-16). + +--- + +## Архитектурные выводы + +1. **Абстракции ФС нет.** Всё держится на ветвлениях `if pane.InRemote()` / `CurrentRemote()` / `sourceIsRemote && + targetIsRemote` в 15+ местах `model.go`, а там, где ветку забыли (rename, enter/edit/execute, archive, unpack, reload + после delete), операция молча уходит в **локальную** ФС с remote-путём. Отсюда класс P0-1, P0-2, P1-11, P1-15. +2. **Пять независимых реализаций копирования** с разной семантикой: + 1. `ops.go` `copyDir`/`copyFile` (local): заменяет каталог, симлинки как ссылки, права сохраняет, mtime нет, обрубок + чистит; + 2. `CopyFileToRemote` + `copyDirToRemote`: слияние, симлинки разыменовывает, на ссылке на каталог падает, права и mtime + нет, обрубки остаются; + 3. `CopyFileFromRemote` + `copyDirFromRemote`: ссылки на каталог пропускает молча; + 4. `CopyFileBetweenRemotes` + `copyDirBetweenRemotes`; + 5. same-host shell `cp -r`/`mv`: вкладывает в существующий каталог. + + Перезапись, симлинки, права, отмена, прогресс и очистка в каждой ведут себя по-своему. +3. **Логика передачи живёт в UI.** `startRemoteCopyJob` — 330 строк goroutine внутри `model.go` (`6131-6467`), с ручной + отправкой ~20 видов сообщений. Тестировать её можно только через Bubble Tea, поэтому тестов и нет. +4. **Нет владельца соединений.** Клиент создаётся в `handleSSHConnectHost`, кладётся в `RemoteMount` и закрывается кем + попало: goParent, mirror, exitSSHMode, удаление хоста. Состояние «подключён» (`connectedHosts`, `RemoteMount.Connected`) + ведётся вручную и не отражает реальность. +5. **Сетевой I/O смешан с UI-потоком** (P1-1). + +### Рекомендуемая целевая схема + +``` +internal/fs/vfs (или internal/fsys) + type FS interface { + Lstat(p) / Stat(p) / ReadDir(p) / ReadLink(p) + Open(ctx, p) (File, error) / OpenFile(ctx, p, flag, perm) + Mkdir(p, perm) / Remove(p) / RemoveAll(ctx, p) / Rename(old, new, overwrite bool) + Symlink(target, p) / Chmod(p, m) / Chtimes(p, a, m) + SameFile(a, b) / Join / Dir / Base // пути: path (posix) для remote, filepath для local + ID() string // "local" | "sftp:user@host:port#fingerprint" + } + LocalFS, SFTPFS (поверх *sftp.Client), ArchiveFS (позже) + +internal/transfer + Plan(ctx, src FS, srcPaths, dst FS, dstDir) -> []Item{src, dst, kind, size, conflict} + Run(ctx, plan, Options{Conflict: Ask|Overwrite|Skip|Merge|Newer, Symlinks: Copy|Follow, + PreserveMode, PreserveTimes, OnProgress, OnConflict}) -> Report + - одна реализация copy-loop: io.CopyBuffer/ReadFrom с ctx-reader и подсчётом байт + - запись в .vcom-part-XXXX + Close + Chmod/Chtimes + Rename (atomic replace) + - move: если src.ID()==dst.ID() — Rename (PosixRename); иначе copy → verify(size) → delete + - ошибки по элементам копятся в Report (skip/retry), фатальные — abort с очисткой temp-файлов + +internal/fs/remote: ConnPool + Acquire(host) / Release(client), refcount, health-check keepalive с таймаутом, + connLost → событие в UI, Reconnect(ctx) с backoff, ограничение handshake по времени, + sftp-клиент с UseConcurrentWrites/Reads, MaxPacket по limits@openssh.com +``` + +UI: панель хранит `FS` + путь. Все операции (list, rename, mkdir, delete, preview, size, transfer) идут асинхронными +`tea.Cmd` через `FS`. Ответы приходят сообщениями с `reqID`, устаревшие отбрасываются. Джобы получают ссылку на клиента +из пула и отпускают её по завершении. + +### Порядок работ (предложение) +1. Быстрые стоп-краны P0 (1–2 дня): запретить rename, enter-exec/edit, archive и unpack в remote-панелях; `Lstat` в + `RemoveRecursive`; temp+rename для записи файлов; mutex в `SSHClient.Close`; не закрывать клиента, которого использует + джоба или вторая панель. +2. Соединения: таймауты handshake, keepalive с детектом смерти, `HostKeyAlgorithms`, HostName по умолчанию = alias, + опции sftp-клиента (сразу даёт ×10–×25 на upload). +3. Асинхронные listing/stat в UI. +4. `FS`-интерфейс + единый движок `transfer` с тестами на стенде; удалить пять старых реализаций и мёртвый код. +5. Конфликты (ask/merge/skip), симлинки, права и mtime, честный прогресс — уже в новом движке. + +--- + +## Стенд для тестировщика (как воспроизводить) + +Файлы стенда (временные, в репозиторий не добавлялись): +- `/tmp/claude-1000/-home-vrubel-services-vcom/ce8e886a-3143-4d8b-9d47-13837c4ebd48/scratchpad/vcom/internal/fs/remote/harness_test.go` + — SSH-сервер в процессе + toxic-прокси; +- `.../scratchpad/vcom/internal/fs/remote/bugs_test.go`, `samehost_test.go` — тесты B1–B12; +- `.../scratchpad/vcom/internal/fs/bugs_local_test.go` — локальные тесты. + +Запуск: `cd /vcom && go test -count=1 -v ./internal/fs/remote/ ./internal/fs/ && go test -race -run +TestCloseRace ./internal/fs/remote/`. + +Суть, если стенд пропадёт (его стоит перенести в репозиторий как `internal/fs/remote/testserver_test.go`): +1. `ssh.ServerConfig{PasswordCallback: pw=="pw"}` + `AddHostKey` (ed25519 и ecdsa, сгенерированные на лету), `net.Listen + ("127.0.0.1:0")`. +2. На канал `session`: запрос `subsystem` со значением `sftp` → `sftp.NewServer(ch).Serve()` (работает по реальной ФС, + поэтому корректно воспроизводит симлинки и права). Запрос `exec` → `sh -c `, stdout в канал, затем `exit-status`. +3. Toxic-прокси: TCP-форвардер с очередью чанков. Задержка — `time.Sleep(until(at))`; freeze — флаг, при котором чанки не + доставляются, но сокет не закрывается (так ведёт себя уснувший Wi-Fi); cut — закрыть оба сокета после N байт + клиент→сервер. +4. `t.Setenv("HOME", t.TempDir())`, `t.Setenv("SSH_AUTH_SOCK", "")`, затем настоящий `remote.Connect(SSHHost{HostName: + "127.0.0.1", Port: , User: "u", Password: "pw"})`. +5. Для UI-сценариев (P0-1, P0-2, P1-1, P1-11, P1-12) нужен тест уровня `ui` с моделью и сообщениями. Сейчас его нет, это + задача на этап разработки (тестировать `Update` с подставным `FS`). + +Результаты прогона на текущем коде: упали (то есть баг подтверждён) B1 symlink-delete, B2/B2' symlink-abort, B3 +perms/mtime, B4 alias-truncate, B5 race (под `-race`), B6 freeze, B8 overwrite+drop, B9 host-key, B10 config, B11 cancel, +B12 dir-size, same-host cp/mv, все 6 локальных. B7 — замер скорости (см. P1-6). diff --git a/plans/rework/01-analysis-ui-core.md b/plans/rework/01-analysis-ui-core.md new file mode 100644 index 0000000..4ad3b9f --- /dev/null +++ b/plans/rework/01-analysis-ui-core.md @@ -0,0 +1,404 @@ +# 01. Анализ UI и ядра (internal/ui, internal/fs, config, theme, main) + +Ветка: `rework/stabilize` (HEAD `e451402`). Код не менялся. Все проверки делались временными тестами, которые подключались через `go test -overlay` из scratchpad-каталога, в репозиторий ничего не добавлялось. + +Обозначения: +- **[ПОДТВЕРЖДЕНО]**: воспроизведено тестом или бенчмарком (ниже приведён вывод). +- **[КОД]**: однозначно следует из кода, но отдельно не запускалось. +- **[ПРЕДПОЛОЖЕНИЕ]**: вероятно, но не проверено. +- **[SSH]**: пересекается с зоной второго аналитика (SSH/SFTP), здесь только отмечено. + +Базовая проверка: `go build ./...` проходит, `go vet ./...` чистый, `go test -race ./...` проходит. Но в `internal/ui` **нет ни одного теста**, тесты есть только у `internal/fs/ops`. + +--- + +## 0. Топ-10 (кратко) + +| # | Приоритет | Проблема | Статус | +|---|---|---|---| +| 1 | P0 | Архивация файла в каталог, где он сам лежит, уничтожает исходник (`data.tar` → формат tar → `os.Create` обрезает источник до 0, а потом читает его же) | ПОДТВЕРЖДЕНО | +| 2 | P0 | Move/Copy/Unpack/Archive в пассивную панель, открытую внутри архива, пишет во временный каталог, а при закрытии архива он удаляется через `RemoveAll`. При Move файл теряется | КОД | +| 3 | P0 | Паника в caret-режиме (`i`), если lipgloss выбрал профиль Ascii (NO_COLOR, TERM=dumb, не tty): `bgCode[2:len-1]` | ПОДТВЕРЖДЕНО | +| 4 | P1 | `m.status` нигде не отрисовывается: title bar стал мёртвым кодом, поэтому пользователь не видит ни одной ошибки или результата операции | КОД (grep) | +| 5 | P1 | По умолчанию удаление **безвозвратное** (`deleteKind = "permanent"`), `confirm_delete` игнорируется, `n` не закрывает диалог, хотя подсказка это обещает | ПОДТВЕРЖДЕНО | +| 6 | P1 | Симлинк на каталог показывается как `executable`, Enter пытается его *выполнить*; войти в симлинк-каталог нельзя (`follow_symlinks` не используется) | ПОДТВЕРЖДЕНО | +| 7 | P1 | При активном фильтре клик мышью выделяет другой файл (индекс берётся из отфильтрованного вида, а применяется к полному списку); двойной клик открывает или выполняет не тот файл | ПОДТВЕРЖДЕНО | +| 8 | P1 | `translateKeyMsg` (ЙЦУКЕН → QWERTY) действует и в полях ввода: набранное в mkdir «папка» превращается в `gfgrf`. Кириллицей нельзя назвать файл или фильтровать | ПОДТВЕРЖДЕНО | +| 9 | P1 | Блокирующие операции в Update/View: `ListDir` (32 мс на 20k), распаковка архива целиком в /tmp при Enter, kitty-декод картинки в `View()` (≈1 с на 6000×4000), превью FIFO блокирует горутину навсегда, `/dev/tty` крадёт ввод | ПОДТВЕРЖДЕНО (частично) | +| 10 | P1 | Распаковка молча перезаписывает существующие файлы; создание архива молча перезаписывает существующий архив | ПОДТВЕРЖДЕНО | + +Кроме того: PgDn не работает вообще (пустой binding), `q` всегда выходит без подтверждения, после любой операции курсор пассивной панели сбрасывается в 0, Enter на удалённом файле открывает или **выполняет локальный** файл с тем же путём [SSH]. + +--- + +## 1. Баги + +### P0: крах и потеря данных + +**P0-1. Архивация уничтожает исходный файл** [ПОДТВЕРЖДЕНО] +- Где: `internal/fs/archive.go:302` (`ArchiveName`), `:337`/`:477` (`os.Create(archivePath)`), `internal/ui/model.go:4863` (`startArchiveJob`). +- Сценарий: обе панели в одном каталоге (самый частый случай), выбираем `data.tar`, `a`, формат `tar`. Имя архива получается `data` + `.tar` = `data.tar`, то есть сам источник. `os.Create` обрезает файл, затем он читается как источник. +- Тест: `archive data.tar as tar into same dir: name=data.tar err=archive/tar: write too long source size now=1536 (was 100000)`. +- То же с `report.zip` → zip. +- Смежные проблемы: существующий архив с таким именем перезаписывается без вопроса; при ошибке или отмене частичный архив не удаляется. Если пассивная панель находится внутри архивируемого каталога, архив включает сам себя (tar падает с `write too long` и оставляет 2 МБ мусора, zip молча кладёт внутрь битую копию). +- Как исправлять: писать во временный файл в целевом каталоге и затем делать `rename`. Отказываться, если `archivePath` совпадает с одним из источников или лежит внутри него (`pathWithin` уже есть в ops.go). Для существующего архива нужен confirm overwrite или автосуффикс. При ошибке удалять временный файл. + +**P0-2. Операции в пассивную панель-архив пишут во временный каталог** [КОД] +- Где: `model.go:2282` (`handleTransfer`). Проверяется только `m.activePane().InArchive()`, а у пассивной панели нет. То же в `handleUnpack` (`:2447`) и `handleArchive` (`:2377`), которые используют `passivePane().Path` без проверки. +- Сценарий: левая панель открыта в `foo.zip` (Path=`/tmp/vcom-archive-XXX/...`), правая на локальном каталоге. В правой нажимаем F6 на файле: он перемещается в /tmp. Потом выходим из архива: `goParent` → `os.RemoveAll(mount.TempDir)` (`model.go:2022`), и файл уничтожен. Пользователь при этом думал, что «положил файл в архив». +- Как исправлять: правило «архив — только для чтения» применять к **цели**, а не только к источнику: централизованная проверка `canWriteTo(pane)`. + +**P0-3. Паника в caret-режиме при цветовом профиле Ascii** [ПОДТВЕРЖДЕНО] +- Где: `model.go:3320-3322`: + ```go + panelBG := lipgloss.NewStyle().Background(m.palette.Panel).Render("") + bgCode := strings.TrimSuffix(panelBG, "\x1b[0m") + inner := bgCode[2 : len(bgCode)-1] + ``` +- Сценарий: `NO_COLOR=1 vcom` (или TERM без цветов), затем `o` (info) на текстовом файле, затем `i`. Тест: `CONFIRMED PANIC in caret mode with Ascii profile: runtime error: slice bounds out of range [:-1]`. +- Bubble Tea перехватит панику и восстановит терминал, но не выполнит cleanup: временные каталоги архивов, ueberzugpp, сессия. +- Как исправлять: не парсить вывод lipgloss. Собирать строку из стилей, а «безопасный reset» строить через termenv/ansi с явной проверкой профиля. + +**P0-4 (по сути P1, но с риском потери данных). Удаление по умолчанию безвозвратное** [ПОДТВЕРЖДЕНО] +- Где: `model.go:2432` (`m.deleteKind = "permanent"`). +- В `plans/feature-roadmap.md` прямо записано «Delete/F8 → корзина, Shift+Delete → навсегда». Сейчас Enter в диалоге удаляет навсегда, а режим переключается клавишей `D/d`. `behavior.confirm_delete` нигде не читается. +- Тест: `delete modal title="Permanently delete selected entry?" deleteKind=permanent`, после `n`: `modal kind still=3` (не закрылся), хотя note пишет «Esc / n to cancel». +- Как исправлять: по умолчанию корзина, отдельная клавиша для безвозвратного удаления, `n` = отмена. Состояние `deleteKind` перенести в pendingOperation, а не держать на модели. + +### P1: зависания и неверное поведение + +**P1-1. Статус и ошибки никогда не показываются** [КОД] +- `m.status` присваивается примерно в 200 местах и не читается ни в одном render (grep `m.status` без присваиваний даёт 0). `renderTitleBar` недостижим (deadcode), `ui.show_title_bar` не используется. Поле `m.busy` тоже только записывается. +- Итог: «Permission denied», «Copy failed», «Nothing to delete», «Press y again…» уходят в никуда. +- Как исправлять: статус-строка или toast-слой с уровнем (info/warn/error) и TTL. + +**P1-2. Симлинки на каталоги** [ПОДТВЕРЖДЕНО] +- `fs/scan.go:51`: `dirEntry.Info()` — это Lstat, поэтому для симлинка `IsDir=false`, а `Mode&0o111 != 0`, и Category становится `executable` (`entry.go:139`). +- Тест: `entry "linkdir" isDir=false category=executable`. +- Enter (`model.go:1957`) уходит в `handleExecute`, то есть `exec.Command(linkPath)`. Для каталога будет ошибка (её не видно, см. P1-1). Для симлинка на бинарь без расширения бинарь **запускается** по Enter. Войти в `~/.config` → `/somewhere` нельзя. Превью симлинка-каталога: `os.Open` + `CopyN` даёт ошибку «is a directory». +- Как исправлять: для симлинков делать `os.Stat` и хранить `IsSymlink` и `TargetIsDir`; навигацию строить по target. `follow_symlinks` либо реализовать, либо удалить. + +**P1-3. Enter запускает исполняемые файлы без подтверждения** [КОД] +- `model.go:1955-1957`, `:2601`. Любой файл без известного расширения с битом `x` (скрипт из загрузок, симлинк, см. P1-2) выполняется по Enter или по двойному клику. Код возврата ≠ 0 приходит как `opMsg.err`, и в этой ветке не возвращается `enableMouseCmd()` (`:438-442`), так что мышь остаётся выключенной. +- Как исправлять: confirm перед запуском, отдельная клавиша Run; обработку ошибки ExecProcess свести в общий хук «после внешнего процесса». + +**P1-4. Фильтр и мышь, фильтр и операции** [ПОДТВЕРЖДЕНО: мышь; КОД: остальное] +- `mouseTarget` → `paneIndexFromMouse(…, &m.left)` (`model.go:5482`, `:5501`) считает индекс по реальному `pane.Offset/Entries`, а `View` рисует `filteredPane` (`:1222`). Тест: `filter=zz, clicked 2nd visible row (zz-target), real selection="a1"`. +- `filteredCount` не учитывает `..`, а `filteredPane` учитывает (`:1781` против `:1800`), поэтому счётчик в filter bar на 1 меньше. +- Фильтр не сбрасывается при смене каталога (`enterSelected`, `goParent`, history), хотя roadmap этого требует: `clearFilter()` вызывается только по Esc. В новом каталоге фильтр применяется молча. +- [ПРЕДПОЛОЖЕНИЕ] После reload (rename, copy-done) курсор восстанавливается по имени через `SetEntries`. Если это имя не проходит фильтр, `filteredPane` подсвечивает первую видимую строку (`filteredCursor = 0`), а `Selected()` возвращает скрытый файл. Тогда F8 или F6 действуют на невидимый файл (в confirm будут показаны только «Items: 1»). +- Метки (`Marked`) остаются на скрытых фильтром файлах и участвуют в операциях. +- Как исправлять: фильтр как часть модели панели: `visible []int`, курсор в пространстве видимых, мышь и рендер через одну функцию. + +**P1-5. Кириллица в полях ввода** [ПОДТВЕРЖДЕНО] +- `model.go:829` `msg = translateKeyMsg(msg)` вызывается **до** роутинга в модалки и фильтр. Тест: `typed 'папка' into mkdir modal -> input value="gfgrf"`. Это ломает mkdir, rename, фильтр и SSH-форму [SSH]. +- Как исправлять: транслировать только при сопоставлении команд (`key.Matches` по транслированной копии), а в textinput отдавать оригинал. + +**P1-6. `PageDown` не назначен** [ПОДТВЕРЖДЕНО] +- `keymap.go:65` `PageDown: key.NewBinding()` без клавиш. Тест: `PgDown: cursor before=0 after=0`. Help при этом обещает `PgUp / b` (`model.go:3096`), но `b` не назначена. + +**P1-7. Курсор пассивной панели сбрасывается после любой операции** [ПОДТВЕРЖДЕНО] +- `archiveDoneMsg`/`copyDoneMsg` (`model.go:561-562`, `655-656`, `691-692`, `737-746`) вызывают `reloadPane(PaneRight, activeSelection)` с именем из **активной** панели. `FindSelected` при промахе возвращает 0 (`scan.go:216`). Тест: `passive pane cursor after reload with active selection name: 500 -> 0`. +- После delete-job в активной панели preserve равен имени удалённого файла, поэтому курсор уходит на `..` (0), а не на соседнюю строку. Логика «cursor--» есть только в мёртвых ветках `opMsg{opDelete}` (`:459-488`). +- Как исправлять: у каждой панели свой preserve; `FindSelected` возвращает -1, а при промахе сохраняется ближайший индекс. + +**P1-8. Несогласованность Path и Entries при ошибке перехода** [КОД] +- `enterSelected` (`:1882`), `historyBack/Forward` (`:2076`, `:2104`), `goParent`, `handleMirrorPane` сначала присваивают `pane.Path = new`, затем вызывают `reloadPane`. При ошибке (нет прав, каталог удалён) Path уже новый, а Entries старые. Заголовок показывает новый путь, а F7/F5-цель направлены в недоступный каталог. История при этом уже pop/push-нута. +- Каталог удалили из соседней панели или извне: `refreshAllPanes` (`:1670`) возвращается на первой ошибке и не обновляет вторую панель; ошибки reload в обработчиках завершения подавлены через `_ =` (19 мест). Панель навсегда «висит» в несуществующем каталоге, и подъёма к ближайшему существующему родителю нет. +- История содержит пути временных каталогов архивов, которые уже удалены после закрытия архива, поэтому Alt+← в них выдаёт ошибку (P1-8 срабатывает). +- Как исправлять: транзакция навигации «загрузить → при успехе применить Path+Entries+history», а для удалённого каталога fallback вверх. + +**P1-9. Блокирующий I/O в Update и View** [ПОДТВЕРЖДЕНО: замеры] +| Где | Что | Цена | +|---|---|---| +| `reloadPane` (`:1653`), вызывается синхронно из Update на каждую навигацию | `os.ReadDir` + `Info()` + `statx` на каждый файл + сортировка | 32 мс на 20k файлов (warm cache); на NFS или HDD секунды | +| `enterArchive` (`:4678`) | `ExtractArchiveToTemp`: **полная** распаковка архива в `/tmp` синхронно в Update, без прогресса и отмены | архив на 2 ГБ означает зависание на минуты; /tmp часто tmpfs (RAM); zip-бомба | +| `syncImageOverlay` из `View()` (`:1289`) → `showWithKitty` → `image.Decode` + `resizeNearest` (через `At/Set`) + `png.Encode` | синхронно в рендере | **≈973 мс, 208 МБ** на PNG 6000×4000 (бенч) | +| `handleTransfer` (`:2310`) | Stat/Lstat каждого источника, для remote это сетевой Lstat | [SSH] | +| `reloadRemotePane`, `goParent` на remote | SFTP ReadDir синхронно | [SSH] | +| `config.Save` в `finalizeTheme` | запись файла в Update | мелочь | +| `resolveIconMode` | `fc-list` при старте | 50–300 мс на старте [ПРЕДПОЛОЖЕНИЕ] | + +**P1-10. Превью: специальные файлы и внешние утилиты** [ПОДТВЕРЖДЕНО: FIFO] +- `fs/preview.go:116`: `os.Open` + `io.CopyN` без проверки `Mode().IsRegular()`. + - FIFO: горутина блокируется навсегда (тест: `BuildPreview on FIFO blocked >2s`), каждое наведение курсора даёт новую зависшую горутину. + - `/dev/tty`, `/dev/pts/*`: превью читает до 64 КБ с терминала и **крадёт нажатия** у Bubble Tea [ПРЕДПОЛОЖЕНИЕ, механизм очевиден]. `/dev/zero`, `/dev/urandom` читаются впустую. +- `pdftotext`, `pdfinfo`, `ffprobe` (`:434`, `:477`, `:551`) запускаются без таймаута и контекста; `pdftotext` переводит в текст **весь** документ в память, обрезка только потом. При быстром скролле по каталогу с PDF или видео запускаются десятки параллельных процессов, отмены нет. +- Как исправлять: `IsRegular` или явный allowlist типов; `exec.CommandContext` с таймаутом; отменять предыдущее превью (context на каждый запрос, generation-id). + +**P1-11. Распаковка перезаписывает файлы без вопроса** [ПОДТВЕРЖДЕНО] +- `fs/archive.go:263` `O_TRUNC`. Тест: `extract over existing file: content="NEW"` (было `PRECIOUS`). Confirm-диалог Unpack о конфликтах не говорит. +- Распаковка идёт через существующие симлинки в целевом каталоге (`MkdirAll` и `OpenFile` по пути с симлинком): если в target уже есть `foo -> /etc`, запись `foo/x` попадёт в `/etc` [КОД]. Сами симлинки из архива пропускаются, это хорошо. Zip-slip по `..` и абсолютным путям закрыт в `safeArchivePath`. +- Отмена проверяется только между файлами, поэтому один большой файл отменить нельзя. +- Как исправлять: план конфликтов до распаковки (как в copy), `O_EXCL` или «перезаписать/пропустить/все», проверка `Lstat` компонентов пути. + +**P1-12. Enter или edit на удалённом файле открывает ЛОКАЛЬНЫЙ файл** [КОД] [SSH] +- `handleOpenSelected` (`:1953-1960`): для файлов на remote-панели нет отдельной ветки. `handleEdit` и `handleExecute` получают `selected.Path` вида `/etc/hosts`, и редактор открывает **локальный** `/etc/hosts`, `handleExecute` **запускает локальный** бинарь по этому пути, `xdg-open` открывает локальный файл. Передаю второму аналитику, но риск высокий. + +**P1-13. Ложные или устаревшие async-сообщения** [КОД, кроме отмеченного] +- `previewMsg` (`:331`): условие `ok && selected.Path == msg.entryPath`. Для пустой панели `ok=false`, и превью «Nothing selected» никогда не применяется: остаётся превью старого файла. [ПОДТВЕРЖДЕНО: `title after previewMsg: "OLD"`] +- Там же: ветки выхода из selectMode/caret (`:345-353`) выполняются **и для устаревших** сообщений. Превью картинки, пришедшее для давно ушедшего курсора, выключит caret-режим на текущем текстовом файле. +- Устаревший `previewMsg` с `remoteImageTemp` не совпал по пути, и временный файл не удаляется никогда (утечка в `/tmp/vcom-remote-images`) [SSH]. +- `dirSizeMsg`: `busy=false` для любого сообщения; два параллельных Space перезаписывают статус. Отмены нет: `DirectorySize` по `/` продолжает работать после выхода из каталога. +- `dismissNoticeMsg` (`:812`) закрывает **любой** текущий `modalNotice`: таймер от первого уведомления (1 с) закроет второе, даже если у того «Press Esc to close». Таймер — обход отсутствия id у модалки. +- `sshConnectMsg` монтирует хост в **текущую активную** панель, а не в ту, где начинали подключение [SSH]. +- Превью строится без отмены: 64 КБ Go-файла подсвечиваются chroma за **190 мс и 46 МБ аллокаций** (бенч). Зажатая `j` по каталогу исходников запускает параллельно N таких горутин, результаты отбрасываются, но CPU уже потрачен. +- Как исправлять: монотонный `requestID` и `paneID` в каждом async-msg; context на запрос; отмена предыдущего. + +**P1-14. Mirror (`p`) ломает состояние панелей** [КОД] +- `handleMirrorPane` (`:2474`): + - Архив: пассивной панели присваивается путь внутри temp-каталога **без** ArchiveMount. Закрытие архива в активной панели удаляет каталог, и пассивная показывает несуществующий путь (P1-8); `..` из пассивной ведёт в `/tmp`. + - Локальный путь: `passive.ClearRemotes()` без `Client.Close()` даёт утечку соединений [SSH]; стек `Archive` пассивной панели не чистится, поэтому `InArchive()` остаётся true при обычном пути, и операции запрещены, а goParent ведёт себя странно. + - Remote: один `*SSHClient` разделяется двумя панелями; `goParent` в корне одной панели делает `Close()`, и вторая сломана [SSH]. + +**P1-15. Создание и закрытие в нестандартных ситуациях** [КОД] +- Выход по сигналу (SIGTERM, SIGHUP при закрытии терминала) или по панике: `cleanupArchiveMounts`, `cleanupImageOverlay`, `saveSession` вызываются **только** в ветке клавиши Quit (`:1047`). Временные каталоги `vcom-archive-*` остаются в /tmp. +- `startExternalOpenCmd` (`:5384`) делает `Start()` без `Wait()`: каждый `xdg-open` оставляет зомби-процесс до выхода vcom. + +**P1-16. Клавиши: конфликты и недостижимые ветки** [КОД; `q` ПОДТВЕРЖДЕНО] +- `q` есть в `Quit` (`keymap.go:79`) и проверяется в switch **раньше**, чем `case Cancel, msg.String()=="q"` (`model.go:1053`). Поэтому `q` с открытым info-pane, фильтром или выделением сразу выходит из программы без подтверждения (тест: `q with info pane open -> quit=true`). Ветка «q закрывает info/фильтр/выделение» мертва для `q`. При этом в модалках `q` означает «закрыть модалку» (`isModalCloseKey`), в view mode тоже «закрыть». Один и тот же `q` в разных режимах значит «выход из программы» и «назад». +- `ctrl+c`: в info mode с `copyPath` это «скопировать путь» (`:965`), в обычном режиме выход, в view/caret mode игнорируется (default). Пользователь, который жмёт Ctrl+C «выйти», в info mode получает копирование пути. +- `v`: `View` (`f3`,`v`) стоит в switch раньше `Visual` (`v`) (`:1088` против `:1095`), поэтому ветка Visual в обычном режиме **недостижима**. В view mode Visual проверяется только при `!selectMode`, а `handleView` ставит `selectMode = true` для текста (`:2531`). В итоге Visual в F3 тоже недостижим, хотя `toggleSelectMode` пишет «Use v/y in F3 view for keyboard selection» (`:2760`). +- `h`/`l`: в обычном режиме это Switch pane, в caret и view это движение курсора; `left`/`right` в обычном режиме означают Back/Open. Навигация vim-стиля непоследовательна: `h` не «вверх по дереву», а «другая панель». +- `c`: Copy и ProgressCancel. Сейчас контексты разные, но пользователь, нажавший `c` дважды (copy → confirm Enter → снова `c`), **отменит** копирование. +- `y`: в info mode копирует путь и перехватывается раньше всех (`:962`). +- `x`, `delete`, `f8`: Delete. Shift+Delete, обещанный roadmap, не назначен. +- Тест `PgDn` (P1-6) показал, что binding пустой. +- 30 мест с `msg.String() == "…"` в обход keymap (`h`, `l`, `left`, `right`, `w`, `b`, `y`, `d/D`, `f/F`, `tab`, `esc`, `enter`, `?`, `up/k`…), поэтому keymap не единственный источник правды и help ему не соответствует. + +### P2: мелочи + +- **Подсветка строки 0 в caret-режиме до первого yank** [КОД]: `yankFlashLine` не инициализируется значением -1 в `NewModel` (`:228`, используется на `:3306`), поэтому первая строка рисуется flash-стилем. +- Ширина символов: caret, visual и yank считают колонки в **рунах** (`lineRuneCount`, `sliceRunes`), а `ansi.Cut` режет по **ячейкам** (`:3283-3296`). С CJK или emoji курсор и выделение рисуются не там, где копируется текст. `isWordRune` знает только латиницу и кириллицу. +- `previewIcon` в ui (`:4619`) всегда возвращает Nerd-глифы, в ASCII-режиме в заголовке превью «тофу». В ASCII-режиме иконка копирования — emoji `📋` (`:3655`), в превью аудио и видео `🎵`/`🎬` (`preview.go:540`, `:652`): ширина emoji неоднозначна, отсюда сдвиг рамок. +- `kindLabel` (`preview.go:684`): для файла без расширения возвращает пустую строку (`kind: n/a`), для файла с расширением всегда просто `file`. +- `RenamePath` (`ops.go:343`): ввод `sub/name` молча превращается в `name` (Base), без ошибки. +- `MoveToTrash` (`ops.go:280`): на другой ФС (USB, /tmp, /mnt) падает с EXDEV, а спецификация требует `$topdir/.Trash-$uid`. `Path=` в `.trashinfo` не URL-кодирован (пробелы и кириллица ломают restore в других инструментах). TOCTOU между Stat и Rename. +- Под `sudo` (`homedir.Dir` указывает на HOME пользователя) session.toml и vcom.toml пишутся root'ом в `~/.config/vcom`, и потом обычный пользователь молча не может сохранить сессию. +- Метаданные в info-pane имеют переменную высоту (видео, аудио, картинка), а `resizePreview` считает её фиксированной (`metaHeight = 7`, `:3481`). `ensureTextCursorVisible` работает со «старой» высотой viewport, и курсор уходит за край. Позиция kitty-overlay пересчитывается отдельно третьим способом (`:5560`). +- `mouseOverPathLine` (`:5629`): «клик по иконке копирования» на деле означает «любой клик в правой половине по y 1..7»; копирует путь при случайном клике. +- Help-модалка (`:3088`) без разделов про операции (F5/F6/F7/F8/F2/a/e/s); цвета для `Dialogs and Transfers` и `Mouse` есть, а самих разделов нет. Модалки (help, theme на 22 темы) не скроллятся, и на терминале 72×18 (минимально допустимом) обрезаются через `overlayCenter`. +- `renderModalBodyLine` содержит ветку `"Existing targets"` (`:4024`), но `handleTransfer` пишет `"Overwrite: N existing target(s)"`, поэтому подсветка-предупреждение о перезаписи не срабатывает никогда. +- `handleTransfer`: `overwrite = existingTargets > 0` независимо от `confirm_overwrite`. Флаг влияет только на то, что выражение потом повторно присваивает `true` (`:2341-2344`), а диалог показывается всегда. +- `cursorMemory` растёт без ограничений и сохраняется в session.toml между запусками (включая пути `/tmp/vcom-archive-*`). Сессия сохраняется только по `q`/F10. +- `ArchiveName` для `foo.tar.gz` в zip даёт `foo.tar.zip`. +- `countArchiveEntries` для tar.gz разжимает архив целиком лишний раз только ради счётчика. +- Логи (`cmd/vcom/main.go:28`): каждый запуск создаёт новый файл в `/tmp/vcom-logs/`, без ротации и очистки. Логируются каждое нажатие, пути, каждое progress-сообщение (178 вызовов `log.Printf` в model.go). Каталог создаётся с `0755` в общем /tmp: второй пользователь на машине не сможет создать там свой лог, а предупреждение печатается в stderr до alt-screen. Файл `0600`, это нормально. Флага `--debug` нет, логирование включено всегда. +- `strings.Title` (deprecated) используется в 8 местах. Собственные `min`/`max` (`:5434`, `:5451`) затеняют builtin'ы Go 1.21+. +- `Update` возвращает то `Model`, то `*Model`: все `handle*` с pointer receiver возвращают `m` типа `*Model`. Тип модели внутри Bubble Tea «прыгает». Это работает только потому, что методы с value receiver входят в method set указателя; тест на `mm.(Model)` упал с `tea.Model is *ui.Model, not ui.Model`. Такой код хрупок и сбивает при тестировании. +- `externalCommandFromEnv`: `strings.Fields($EDITOR)` ломает кавычки (`EDITOR='code --wait'` работает, а пути с пробелами нет). + +### Конфиг и сессия + +- **Неатомарная запись** `config.Save` (`config.go:149`) и `SaveSession` (`session.go:83`) через `os.WriteFile`. Обрыв или нехватка места дают обрезанный TOML. Тогда `config.Load` при следующем старте вернёт parse error, и **vcom не запустится** (`main.go:23` → `os.Exit(1)`). Битая сессия просто молча игнорируется. [КОД] +- **Выбор темы переписывает пользовательский конфиг** через `toml.Marshal(cfg)`: исчезают все комментарии и закомментированные колонки, ради которых в `docs/architecture.md` выбран TOML. Неизвестные ключи (`auto_refresh`, `auto_refresh_interval` из `vcom.toml`) тоже удаляются. [КОД] +- В поиске конфига первым кандидатом стоит `./vcom.toml` из **текущего каталога** (`config.go:233`). Запуск vcom внутри любого проекта с `vcom.toml` загрузит чужой конфиг, а выбор темы **перезапишет файл в этом проекте** (так и происходит в самом репозитории vcom). [КОД] +- Мёртвые или невыполненные опции: `behavior.confirm_delete`, `behavior.follow_symlinks`, `ui.show_title_bar` не читаются; `auto_refresh` и `auto_refresh_interval` есть в `vcom.toml`, но отсутствуют в структуре (non-strict unmarshal их молча игнорирует), автообновления нет вообще. +- `chromaStyleName` знает 7 из 22 тем, остальные (`github-dark`, дефолт `vcom.toml`) получают подсветку catppuccin. + +### Image overlay (kitty / ueberzugpp) + +- Вызов из `View()` с побочными эффектами: `View` должна быть чистой, а здесь она запускает процессы, пишет в pipe, декодирует картинки и **пишет escape-последовательности напрямую в `os.Stdout`** (`image_overlay.go:76`, `:181`) параллельно с рендерером Bubble Tea. Возможны перемешанные последовательности и артефакты [ПРЕДПОЛОЖЕНИЕ о частоте, механизм есть в коде]. Bubble Tea вызывает View после каждого Update, и кэш `lastPath/lastRect` спасает только при неизменном rect. +- Замер kitty-пути: ≈1 с на большой PNG синхронно в рендере (см. P1-9). `resizeNearest` через `img.At`/`dst.Set` даёт 1.2 млн аллокаций. +- `send()` пишет в stdin ueberzugpp синхронно. Если процесс завис и pipe-буфер (64 КБ) заполнен, `View()` блокируется навсегда. +- Под tmux (`KITTY_WINDOW_ID` унаследован) kitty APC уходит без passthrough: мусор или пустота. +- `m.overlay.hide()` вызывается в View при модалке; при переключении pane и info, view mode приходится пересчитывать прямоугольник вручную по «магическим» отступам (`contentTop = 1+1+meta+1+1`). +- Утечки процессов: ueberzugpp убивается в `stop()` только при Quit или внешнем редакторе. При панике или сигнале он остаётся сиротой, пока не закроет stdin (обычно завершается сам) [ПРЕДПОЛОЖЕНИЕ]. +- Как исправлять: overlay как отдельный актор с собственной горутиной и очередью команд; декод и масштабирование async; вывод kitty только через `tea.Printf`/`tea.Raw` или после кадра; View только вычисляет желаемый rect, а применение идёт командой в Update. + +--- + +## 2. Производительность (замеры) + +Машина: 24 потока, Go 1.26, warm page cache; каталог из 20 000 пустых файлов; терминал 200×60. + +| Операция | Время | Аллокации | Комментарий | +|---|---|---|---| +| `View()` (2 панели по 20k) | **7.0 мс/кадр** | 5.8 МБ, 64.7k allocs | рисуются только видимые строки (хорошо), но на каждую ячейку идёт `lipgloss.NewStyle()`, `buildColumns` вызывается заново **на каждую строку** (`pane.go:489`) | +| `View()` с фильтром | 8.1 мс | 9.2 МБ | `filteredPane` пересоздаёт и фильтрует 20k entries с `ToLower` каждый кадр | +| Update(`j`) + View | 7.2 мс | 5.6 МБ | от нажатия до кадра; на 120 Hz автоповторе это ~85 % одного ядра | +| `reloadPane` 20k (в Update!) | **32 мс** | 19 МБ | из них ≈11 мс на `statx` birth time на каждый файл (37.5 против 26.4 мс на голый ReadDir+Info) | +| `BuildPreview` каталога 20k | 36 мс | 19 МБ | полный `ListDir` ради 80 строк превью; `preview.Entries` хранит все 20k | +| `BuildPreview` Go-файла 64 КБ | **190 мс** | 46 МБ, 832k allocs | chroma + regexp-постобработка SGR; без отмены | +| Caret-движение по 64 КБ файлу | **9.7 мс/нажатие** | 7.4 МБ | `syncPreviewContent` перерисовывает **весь** файл (~2000 строк), строит 7 стилей и делает `strings.ReplaceAll` по всему результату | +| kitty `loadKittyPayload` 6000×4000 PNG | **973 мс** | 208 МБ | синхронно в `View()` | + +Другие наблюдения: +- **Прогресс без троттлинга**: `finishFile` форсирует emit на каждый файл (`ops.go:509`, `force=true`); extract шлёт сообщение на каждый файл (`archive.go:179`, `:244`); delete-job шлёт на каждый элемент. Каждое сообщение даёт Update и полный View (7 мс). На 100k мелких файлов это 100k кадров, а канал на 256 элементов создаёт **backpressure**: копирование замедляется до скорости рендера. Плюс `log.Printf` на каждое progress-сообщение. +- `renderSelectionPane` вызывает `viewport.SetContent` на весь текст **каждый кадр** (`:3586`) в F3. +- `renderThemeSelectModal` вызывает `theme.Resolve` для 22 тем каждый кадр (дёшево, но лишнее). +- Сортировка по имени: `strings.ToLower` дважды на каждое сравнение (`scan.go:121`), O(n log n) аллокаций. Ключи стоит посчитать заранее. +- 10k+ файлов: сам рендер масштабируется нормально (окно видимых строк), узкие места — синхронный `ListDir`, фильтр на каждый кадр и превью-каталога. + +Что делать в первую очередь: (1) кэш `[]columnSpec` и стилей на ширину и палитру; (2) отрендеренные строки кэшировать по `(entry, selected, marked, hovered, width)`; (3) `ListDir` асинхронно с generation-id и `statx` лениво (только если включена колонка created или sort=created); (4) троттлинг прогресса 50–100 мс в одном месте (в UI-адаптере канала, а не в каждой функции fs); (5) caret-рендер только видимого окна. + +--- + +## 3. Карта состояний UI + +### Фактическое состояние (набор независимых флагов на `Model`) + +Флаги режимов: `infoMode`, `viewMode`, `viewPrevInfo`, `selectMode`, `cursorMode`, `visualMode`, `filterMode` (+ `filterQuery`/`filterPaneID`), `modal.kind` (11 видов), `themeSelector != nil`, `pendingY`, `copyJob != nil` (+ `background`), `archiveJob != nil` (+ `background`, `kind` ∈ archive|extract|delete), `ssh.testingConn`, `pane.Path == "ssh://"`, `len(pane.Archive)>0`, `len(pane.Remote)>0`, `preSSHPath`, `deleteKind`, `archiveFormat`, `copyPath`, `yankFlashLine`, `busy`. Состояние мыши (включена или выключена) — это **побочный эффект**, не хранится нигде и выводится из `selectMode`. + +Теоретически это 2^7 × 11 комбинаций, причём допустимы примерно 12. + +### Как должно быть (явные режимы) + +``` +Browse ──o/F9──▶ Info ──i──▶ Caret ──v──▶ Visual + ▲ │ │ ▲ │ Esc │ Esc/y + │ │ │ └────────┘◀─────────┘ + │ │ └─C-t──▶ MouseSelect (мышь выкл.) ──C-t/Esc──▶ Info + │ ├─F3/v──▶ View(kind=text|image|other) ──Esc/q/F3──▶ (предыдущий: Browse|Info) + │ ├─/──▶ FilterInput ──Enter──▶ Browse[filter=committed] ──Esc──▶ Browse + │ └─(любая команда)──▶ Modal(kind) ──Esc/Enter──▶ предыдущий режим + └─────────── фоновые задачи: CopyJob / ArchiveJob — ортогональны режиму, не модалка +Панель: Local | Archive(stack) | SSHHostList | Remote(stack) — состояние панели, не модели +``` +Допустимое состояние описывается тройкой: `Mode` (одно значение enum) + `Overlay` (стек модалок) + `Jobs` (список фоновых задач). Выделение текста — подсостояние Info/View, а не отдельные флаги. + +### Где переходы нарушаются (найдено в коде) + +| Нарушение | Где | +|---|---| +| `selectMode` значит два разных состояния: «Ctrl+T мышиное выделение в info» и «F3 на текстовом файле, мышь выключена» | `handleView` `:2531`, `toggleSelectMode` `:2758`, `previewMsg` `:345` | +| `handleView` выбирает selectMode по **предыдущему** `previewData.Kind` до прихода нового превью, поэтому для картинки мышь может выключиться, а для текста остаться включённой | `:2531` | +| Visual недостижим из Browse (перехвачен View) и из View (selectMode=true) | `:1088/1095`, `:849` | +| `exitViewMode` восстанавливает `infoMode = viewPrevInfo`, но не восстанавливает `cursorMode` и `selectMode` и не выключает `cursorMode` | `:2546` | +| `toggleInfo` (выкл.) сбрасывает select/cursor/visual, но правый клик по превью (`:2683`) не сбрасывает `selectMode`, и мышь остаётся в непонятном состоянии | `:2732` против `:2683` | +| Esc/`q` в Browse закрывает info **без** `resizePreview`/`syncPreviewContent` (в отличие от toggleInfo) | `:1062-1070` | +| Фильтр «прилипает» к панели (`filterPaneID`), но `snapFilterCursor` и `filteredCount` работают по `activePane()`: после Tab на другую панель и `/` запрос переносится, а счётчик считает не ту панель | `:1717`, `:1788`, `:1793` | +| Переход между каталогами не сбрасывает фильтр, метки сбрасываются только при Tab или клике по другой панели, а при Tab метки **обеих** панелей стираются (потеря выделения при простом переключении) | `:1110-1111` | +| Модалка открыта, но мышь обрабатывается: клик и колесо меняют курсор и активную панель **под** модалкой, двойной клик открывает или запускает файл | `handleMouse` не проверяет `modal.kind` (`:2612`) | +| `copyJob`/`archiveJob` по одной штуке на тип: второй copy при фоновом первом получает «Transfer is already running», но только **после** подтверждения в диалоге | `:1358`, `:1371` | +| `deleteKind` и `archiveFormat` живут на модели, а не в pending-операции, и протекают между диалогами | `:1404-1410`, `:530` | +| `pane.Path == "ssh://"` — магическая строка вместо типа панели; `preSSHPath` один на модель, а не на панель (SSH в обеих панелях затирает путь возврата) [SSH] | `:5684-5700` | +| `pendingY`: двухнажатийный `yy` реализован глобальным флагом, который сбрасывается на любой клавише ≠ `y` до роутинга. Работает только в caret, но держится на всей модели | `:830-832`, `:937` | + +--- + +## 4. Костыли и хаки (что маскируют и как должно быть) + +| # | Костыль | Где | Что маскирует | Как правильно | +|---|---|---|---|---| +| 1 | 7 bool-флагов режимов + `viewPrevInfo` | `Model` `:200-212` | отсутствие модели режимов, отсюда недостижимые и противоречивые комбинации (раздел 3) | `type mode int` + стек оверлеев; переходы через `enter(mode)`/`exit()` с хуками (мышь, resize, sync) | +| 2 | `translateKeyMsg` до роутинга | `layout.go:30`, `model.go:829` | keymap не умеет раскладку | транслировать только копию msg для `key.Matches` в командном режиме; в textinput отдавать оригинал | +| 3 | 30 × `msg.String()=="…"` | Update, handleModalKey | keymap неполный (h/l/w/b/y/d/f/tab/esc/enter и т. д.) | всё в KeyMap, контекстные keymap'ы на режим (`BrowseKeys`, `CaretKeys`, `ModalKeys`); help генерируется из них | +| 4 | Дублирование веток навигации курсора текста (view и caret, каждая по 60 строк, `left`/`h`, `right`/`l` отдельными case) | `:861-916`, `:946-976` | нет общего обработчика текстового курсора | один `textCursorKeys` на компонент «text viewer» | +| 5 | `pendingY` | `:830`, `:937` | нет поддержки chord-клавиш | маленький chord-buffer в keymap-слое (или `yy` → `Y`) | +| 6 | `enableMouseCmd`/`disableMouseCmd` разбросаны по 10 местам | `:438`, `:1993`, `:2539`, `:2541`, `:2554`… | состояние мыши не хранится и выводится из selectMode; при ошибке внешнего процесса мышь не возвращается | мышь как производное от режима: после каждого перехода сравнивать желаемое состояние с применённым и выпускать одну команду | +| 7 | `syncImageOverlay` и `overlay.hide()` в `View()` | `:1282`, `:1289`, `:5530` | нет async-канала для overlay | актор overlay, команды из Update, View без побочных эффектов | +| 8 | Ручной расчёт прямоугольника картинки «магическими» отступами (`contentTop = 1+1+meta+1+1`, `x+3`, `w-6`) и тремя разными формулами высоты метаданных | `:5560-5575`, `resizePreview :3481`, `renderPreviewPane :3545` | layout не вычисляется один раз | единый `layout` struct (rect'ы панелей, превью, viewport, overlay), который считается в `WindowSizeMsg` и при смене режима; им пользуются рендер, мышь и overlay | +| 9 | `mouseTarget`/`paneIndexFromMouse` (`listStartY=3`), `mouseOverPathLine` (`y 1..7`, «правая половина») | `:5458-5660` | нет hit-test по реальному layout | hit-test по тому же `layout`; zones (например `bubblezone`) | +| 10 | `overlayCenter` + `ansi.Cut` построчно | `:4563` | нет слоя модалок; высокие модалки обрезаются | lipgloss `Place`/`layer` (v2) или собственный compositor с клипом и скроллом модалки | +| 11 | «Безопасный reset» через парсинг вывода lipgloss (`bgCode[2:len-1]`) + `strings.ReplaceAll("\x1b[0m")` | `:3320-3326` | lipgloss сбрасывает фон панели; это **P0-паника** | рендерить строки с явным фоном (`Style.Inherit`, `ansi` builder) | +| 12 | `stripBackgroundSGR` + 2 regexp на весь вывод chroma | `preview.go:207` | chroma-стиль ставит фон | свой chroma formatter (или trimmed style) без фона; это же даст выигрыш на 190 мс превью | +| 13 | Таймеры `dismissNoticeCmd(1s)` и `dismissYankFlashCmd(140ms)` без id | `:4746-4756`, `:812-819` | у модалок и вспышек нет идентичности; таймер закрывает чужую модалку | id у уведомления; закрывать только совпадающий | +| 14 | Сентинел `note == "confirm-actions"`; эвристики разметки текста модалки (split по `:`, `" to "`, `" ("`, `","`; токены «Enter», «Esc», «Cancel»; префикс `"Existing targets"`) | `:3850`, `:3995-4126` | модалка — это строка, а не структура | `modal{title, fields []kv, warnings, actions []action}`; рендер по структуре | +| 15 | Магическая строка пути `"ssh://"` | `:2399`, `:1972`, `:5684`, `pane.go:408` | у панели нет типа источника | `pane.Source` = Local / Archive / SSHHosts / Remote (интерфейс VFS) | +| 16 | `archiveJob` переиспользуется для delete (`kind:"delete"`), а `"archive"`/`"extract"`/`"delete"` — строки; завершение различается по `progress.Stage == "delete permanently"` | `:4977`, `:675-679` | нет общего типа фоновой задачи | `Job` с типом, id, ctx, progress, `onDone`; менеджер задач с очередью | +| 17 | `opMsg` для delete-веток, `pendingOperation.cmd()` для delete и move, `trashPathsCmd`, `deletePathsPermanentCmd`, `moveCmd`, `operationCmd` — старый синхронный путь, оставленный рядом с job-путём | `:459-488`, `:4642-4662`, `:5059-5086` | незавершённый рефакторинг | удалить и оставить один путь | +| 18 | `_ = m.reloadPane(...)` в 19 местах; «reload обеих панелей с preserve из активной» | обработчики done | нет модели «что изменилось» | после операции инвалидировать затронутые каталоги; каждая панель перечитывает себя со своим preserve | +| 19 | `remotePrefix` и `_ = remotePrefix // used in logs below` | `:1037-1042` | логирование ради логирования | убрать; один middleware-лог событий под `--debug` | +| 20 | Горутины внутри `tea.Cmd` (`func() tea.Msg { go func(){…}(); return nil }`) + общий канал на 256 + `waitXProgressCmd`, захват `m *Model` (указатель на локальную копию модели из Update) | `:4782`, `:4889`, `:4943`, `:5003` | нет механизма стрима сообщений | `program.Send` через инжектированный sender или канал на задачу, закрываемый в конце; не захватывать модель | +| 21 | `Update` возвращает то `Model`, то `*Model` | все `handle*` | смешанные receiver'ы | единообразно: `*Model` везде или value везде | +| 22 | `copyPath` дублирует `previewData.Metadata.Path` и ставится только при infoMode | `:3143`, `:2693` | дублирование состояния | брать из previewData | +| 23 | `cycleTheme`, `renderTitleBar`, `renderConfirmActions`, `renderProgressActions`, `transferSourceLabel`, `isEditableEntry` (см. раздел 6) | — | хвосты прошлых итераций | удалить | +| 24 | `previewMsg` применяет побочные эффекты (выход из режимов) даже для устаревших сообщений | `:345-353` | нет generation-id | requestID | +| 25 | `kittyTried`/`kittyOK` всегда true («проверка» без проверки) | `image_overlay.go:64` | нет реального probe (`a=q`) | запрос возможностей терминала при старте | + +--- + +## 5. Архитектура и декомпозиция model.go + +### Что сейчас + +`model.go` содержит 6555 строк, 95 методов и функций (84 с `*Model`, 11 с `Model`). `Update` — один метод на ~880 строк (`:318-1196`) с вложенными switch по режимам, `handleModalKey` занимает ещё ~350 строк (`:1295-1647`). В одном файле смешаны: +1. Роутинг ввода (клавиши, мышь, раскладка). +2. Машина режимов (на флагах). +3. Навигация панелей, история, cursor memory, фильтр. +4. Превью: загрузка (включая SFTP-чтение и скачивание картинок), caret, visual, yank. +5. Файловые операции: планирование, confirm, запуск job, обработка завершения (local и remote отдельно). +6. Архивы: монтирование, распаковка, создание. +7. SSH: подключение, список хостов, добавление и удаление, remote copy/delete (~900 строк, `:5664-6555`). +8. Рендер: превью, метаданные, модалки (6 видов), прогресс, footer, filter bar, overlay-композиция. +9. Сессия, тема, внешние процессы, overlay, утилиты. + +### Предлагаемая структура (пакет `internal/ui` + подпакеты) + +``` +internal/ui/ + app.go // Model: ссылки на компоненты, Update-диспетчер (~200 строк), View-композиция + mode.go // enum Mode + переходы + side-effects (мышь, resize, overlay) + layout.go // Layout{left, right, preview, viewport, overlay rect} — один расчёт; hit-test + input/ // keymap по контекстам, chord, раскладка (translate только для команд) + panel/ // Panel: Source (Local/Archive/SSHHosts/Remote), entries, cursor, offset, + // visible-index (фильтр), marks, history, cursor memory; Load() как Cmd с genID + // render.go (кэш колонок/строк) + preview/ // Loader (ctx, requestID, отмена), TextViewer (caret/visual/yank/scroll — общий для Info и F3) + modal/ // Modal interface{Update, View, ID}; confirm, input, help, theme, progress, notice; стек + jobs/ // Job manager: copy/move/delete/archive/extract (local+remote) с единым progress/throttle/cancel/background + overlay/ // image overlay actor (async decode, kitty/ueberzugpp) + ssh/ // host list, connect/add/delete flow (отдаёт команды панели) + session.go, theme.go, external.go (editor/opener/exec с confirm) +``` + +Принципы: +- **View чистая**: никаких записей в stdout, процессов или I/O. +- **Каждое async-сообщение** несёт `(paneID|jobID, requestID)`; устаревшие отбрасываются в одном месте. +- **Команды** (copy, move и т. д.) описываются как `Action{ID, Keys, Help, Enabled(ctx), Run}`, а footer и help генерируются из реестра. +- **fs-слой** через интерфейс `VFS` (Local, Archive, SFTP): уйдут `if pane.InRemote() … else …` в 20+ местах. +- **Порядок рефакторинга** (с тестами на каждом шаге, сейчас в ui тестов 0): (1) поставить характеризационные тесты на Update (по образцу временных из этого анализа); (2) вынести `panel` + фильтр + навигационная транзакция; (3) `mode` + удаление флагов; (4) `jobs`; (5) `modal`; (6) `preview` + `overlay`; (7) SSH. + +--- + +## 6. Мёртвый код + +`deadcode ./...` (golang.org/x/tools), в моей зоне (с `-test` то же самое): + +| Символ | Место | +|---|---| +| `Model.cycleTheme` | `ui/model.go:2885` (заменён theme selector) + `theme.Next` (`theme/theme.go:76`) | +| `renderTitleBar` | `ui/model.go:3684`: вместе с ним пропала отрисовка `m.status` (P1-1) | +| `renderConfirmActions` | `ui/model.go:4128` | +| `renderProgressActions` | `ui/model.go:4470` | +| `operationCmd`, `moveCmd` | `ui/model.go:4655`, `:5059` | +| `transferSourceLabel` | `ui/model.go:5279` | +| `isEditableEntry` | `ui/model.go:5517` | +| `vfs.CopyPath`, `CopyPathWithProgress`, `MovePath`, `MovePathWithProgress` | `fs/ops.go:51`, `:177`, `:181`, `:185` (нет и в тестах) | +| `vfs.JoinPath`, `vfs.IsNotExist` | `fs/scan.go:265`, `:273` | +| `isRemoteHostEntry` | `ui/ssh.go:15` [SSH] | +| (remote) `CopyDirBetweenRemotes`, `SftpToFileInfo`, `NewWalkDirEntry`, `ResolveAddr`, `SSHConfigPath`, `HostsFilePath`, `GetSSHDir`, `ConfigFileExists`, `ValidateHost` | `fs/remote/*` [SSH] | + +Найдено вручную (достижимо формально, фактически нет): +- `pendingOperation.cmd()` ветки `opDelete`/`opPermanentDelete` и функции `trashPathsCmd`, `deletePathsPermanentCmd`: локальное удаление всегда идёт через `startDeleteJob`. +- Обработка `opMsg` для `opCopy`, `opMove`, `opDelete`, `opPermanentDelete` (`:450-488`) и связанный пост-reload курсора для copy/move (`:521-531`): эти opMsg никто не отправляет. +- `opArchive` в `operationDoneLabel`/`operationVerb`/`progressTitle`, `opView` (opMsg `opView` никто не шлёт). +- Ветка `case key.Matches(msg, m.keys.Visual)` в Browse (`:1095`) и Visual в view mode (`:849-853`). +- Ветка `"Existing targets"` в `renderModalBodyLine` (`:4024`). +- `renderImageInlinePreview` всегда возвращает `""`; `PreviewOptions.ImagePreviewWidth/Height` не задаются. +- Поля `Model.busy`, `Model.status` (пишутся, но не читаются), `copyJobState.overwrite`. +- `BrowserPane.EnsureMarked`, `HasHistory`, `HasFuture`, `HistoryDepth`, `FutureDepth`: вызовов нет (grep), deadcode их не ловит, потому что это экспортируемые методы. +- Ветка `else if pane.InArchive()` в `refreshAllPanes` (`:1680`) идентична `else`. +- Собственные `min`/`max`: builtin'ы в Go 1.26. +- Конфиг: `confirm_delete`, `follow_symlinks`, `show_title_bar`; ключи `auto_refresh*` в `vcom.toml`. + +--- + +## 7. Пересечения с зоной SSH (для второго аналитика) + +- Enter, edit или exec на remote-файле открывает или запускает **локальный** файл с тем же путём (P1-12). +- Mirror разделяет один `*SSHClient` между панелями; локальный mirror не закрывает клиентов (P1-14). +- `preSSHPath` один на модель; `sshConnectMsg` монтирует хост в текущую активную панель (раздел 3). +- `isModalCloseKey` считает `q` закрытием, поэтому в SSH-форме нельзя набрать `q` в имени хоста или пользователя; плюс `translateKeyMsg` портит кириллицу в полях. +- Синхронный SFTP ReadDir и Lstat в Update (`reloadRemotePane`, `handleTransfer`). +- Утечка `/tmp/vcom-remote-images/*` при устаревших previewMsg; скачивание **целой** удалённой картинки при каждом наведении без отмены. +- Ошибки reload remote в обработчиках завершения подавлены через `_ =`. + +--- + +## 8. Как проверялось + +- Временные тесты: `scratchpad/t/ui_analysis_test.go` (package ui) и `scratchpad/t/fs_analysis_test.go` (package vfs), подключались через `go test -overlay`; репозиторий не изменялся (`git status` чистый). +- Фикстуры: каталог из 20 000 файлов, Go-файл на 64 КБ, PNG 6000×4000 (124 МБ), FIFO, симлинк на каталог. +- Инструменты: `go build`, `go vet`, `go test -race ./...` (зелёные), `deadcode` и `deadcode -test`. diff --git a/plans/rework/02-design.md b/plans/rework/02-design.md new file mode 100644 index 0000000..2ec4e10 --- /dev/null +++ b/plans/rework/02-design.md @@ -0,0 +1,1197 @@ +# 02. Дизайн: целевая архитектура и UX vcom + +Вход: `01-analysis-network.md` (ссылки вида **N-P0-3**), `01-analysis-ui-core.md` (ссылки вида **U-P1-5**), +решения владельца (Go + Bubble Tea v1, функции сохраняем, ломать внутренние API можно). +План работ по этапам: `03-tasks.md`. Тест-стенд аналитиков сохранён в `plans/rework/testbed/*.go.txt` +(не компилируется, перенос в код — задача 0.1). + +Приоритеты, которые решают все спорные места дизайна: +1. **Никакой потери данных.** Ни одна операция не уничтожает существующие данные, пока новые не записаны полностью. + Ни одна операция не ходит по симлинку, если её не просили. +2. **UI никогда не блокируется на I/O.** `Update` и `View` не делают файловых, сетевых и процессных вызовов. +3. **Сеть надёжна.** Таймауты на всё, обнаружение мёртвого соединения, переподключение, отмена, атомарная запись. +4. **Код можно поддерживать и тестировать.** Один путь для каждой операции, без веток `if remote`. + +--- + +## 0. Ключевые решения (кратко) + +| # | Решение | Почему | +|---|---|---| +| D1 | Единый интерфейс `vfs.FS` (Local, SFTP, Archive). Панель хранит `FS + путь`. В UI нет ни одного прямого вызова `os.*`; это проверяет тест на импорты | Закрывает весь класс «забыли if remote» (N-P0-1, N-P0-2, N-P1-11, N-P1-15, U-P0-2) по построению, а не по дисциплине | +| D2 | Один движок `transfer` (plan → execute) для copy, move и unpack. Запись только через temp + atomic rename. Каталоги **сливаются**, дерево каталога никогда не удаляется ради перезаписи | Пять реализаций копирования сводятся к одной, у которой одна семантика. Закрывает N-P0-4…7, N-P1-7…10, N-P1-13, N-P1-17, U-P1-11 | +| D3 | `ssh/conn.Pool`: refcount-аренда (`Lease`), keepalive с таймаутом, явные состояния, переподключение, дедлайны на handshake. Никто, кроме пула, не закрывает соединение | N-P0-8, N-P1-2, N-P1-3, N-P1-12 | +| D4 | Фоновые операции — `jobs.Manager`, независимый от Bubble Tea. Прогресс — «последнее значение» с троттлингом 10 Гц. Вопросы к пользователю (конфликт, ошибка, host key, пароль) — через `Ask`, который блокирует только goroutine джобы | Нет backpressure, нет «потерянного» re-arm канала, джобы тестируются без UI | +| D5 | Новый UI пишется в `internal/tui` рядом со старым (`internal/ui`) и включается флагом `--ui=next`. После паритета старый UI и `internal/fs*` удаляются целиком | Каждый этап собирается и работает, разработчики UI не мешают друг другу и хотфиксам | +| D6 | Явная машина режимов: `Screen` (Browse, Info, View) + фокус вьюера + стек модалок + строка фильтра. Владелец ввода определяется одной функцией | Убирает 7 bool-флагов и недостижимые ветки (U-P1-16, раздел 3 отчёта) | +| D7 | Каждый async-ответ несёт `Ticket{key, gen}`. Принимается только текущий; всё остальное отбрасывается в одном месте до любых побочных эффектов | U-P1-13, N-P2-8 | +| D8 | `View()` чистая. Мышь и image overlay — «эффекты», которые сверяются после каждого `Update` и применяются командами. Картинки рисует отдельный актор, который пишет в терминал через общий с рендерером mutex | Убирает побочные эффекты и блокировки из `View` (U-P1-9, раздел «Image overlay») | +| D9 | Удаление по умолчанию — в корзину. Безвозвратное удаление — отдельная клавиша, всегда с подтверждением, кнопка по умолчанию «Отмена» | U-P0-4 | +| D10 | Клавиши описаны в одном реестре действий по контекстам. Раскладка ЙЦУКЕН транслируется только при поиске команды, поля ввода получают оригинальный символ | U-P1-5, U-P1-16 | +| D11 | Конфиг ищется только в XDG/`-config`/`$VCOM_CONFIG`. Тема пишется точечной правкой одной строки с атомарной записью, комментарии сохраняются. Сессия переезжает в `$XDG_STATE_HOME` | Раздел «Конфиг и сессия» отчёта UI | +| D12 | Остаёмся на Bubble Tea v1.3.x до конца рework. Слои (keys, modal, layout) изолированы так, чтобы переход на v2 потом затронул только `internal/tui` | Не смешивать две большие миграции | + +--- + +## 1. Структура пакетов + +``` +cmd/vcom/ main: флаги, логирование, конфиг, сигналы, запуск, teardown +internal/ + paths/ XDG-каталоги (config/state/cache), правила sudo, run-dir процесса + atomicfile/ WriteFile: temp + fsync + rename + fsync каталога (только локальная ФС) + logx/ slog: уровень, файл в state-dir, ротация + config/ схема, загрузка (неизвестные ключи → предупреждения), поиск, SetKey (точечная правка) + state/ session.toml: панели, история, cursor memory (с ограничением), миграция со старого пути + theme/ палитры + маппинг chroma-стиля для КАЖДОЙ темы + vfs/ интерфейс FS, FileInfo, ошибки, Location, общие хелперы (Walk, RemoveTree, DirSize, + SameFile, Within), ReadOnly-обёртка + localfs/ LocalFS (renameat2 NOREPLACE, ленивый statx birth time, корзина freedesktop) + sftpfs/ SFTPFS поверх conn.Conn + archivefs/ read-only FS по индексу zip/tar/tar.gz + потоковый transfer.Source + vfstest/ conformance-набор для любой FS + FaultFS (инъекция ошибок, задержек, блокировок) + ssh/ + sshconfig/ разрешение хоста по ~/.ssh/config (kevinburke/ssh_config), хранилище своих хостов (hosts.dat) + conn/ Dialer, Conn, Pool, Prompter, keepalive, reconnect, Exec с ctx + transfer/ Prepare (plan), Execute, WriteAtomic, политики, Report, Source + archive/ форматы: индекс и чтение zip/tar/tgz, создание архива поверх vfs + jobs/ Manager фоновых задач: прогресс, отмена, Ask/Answer, события + preview/ Build(ctx, req) по видам, chroma-форматтер без фона, лимиты, внешние утилиты с таймаутом, LRU + imgview/ актор картинок: kitty/ueberzugpp/none, async decode+scale, SyncTTY + tui/ App (tea.Model), режимы, роутинг, layout, эффекты, Tracker, файлы фич + keys/ ActionID, контексты, привязки, раскладка, chord, генерация help/footer + panel/ модель панели + рендер с кэшами + viewer/ TextViewer: scroll/caret/visual/yank (по ячейкам, только видимое окно) + modal/ Modal, Stack, Dialog (структурный), Input, List, Progress, Conflict, Prompt + notify/ центр уведомлений, статус-строка, журнал сообщений + testutil/ + sshtest/ SSH/SFTP-сервер в процессе + toxic-прокси (из стенда аналитиков) + fstree/ построение и сравнение деревьев (mode, mtime, symlink) + teadriver/ Driver для тестов Update/View любой tea.Model (и старого UI, и нового) +``` + +Зависимости строго сверху вниз: `tui → {jobs, transfer, preview, imgview, archive, vfs/*, ssh/*, config, state}`; +`transfer → vfs`; `sftpfs → conn → sshconfig`; `archivefs → archive → vfs`. Пакеты ниже `tui` не импортируют +Bubble Tea и lipgloss (исключение — `theme`, где лежат цвета). + +Старые пакеты (`internal/ui`, `internal/fs`, `internal/fs/remote`, `internal/homedir`) живут до этапа 7 и затем удаляются. +Старый `internal/fs` называется `package vfs`; новый `internal/vfs` — тоже `vfs`. Пути импорта разные, в одном файле +их не смешиваем. + +Новые зависимости: `github.com/kevinburke/ssh_config` (парсер ssh_config), `golang.org/x/image/draw` (масштабирование +картинок). Обе вендорятся. Добавляет их **только** задача, которой они нужны (2B.1 и 5C.1), чтобы не было конфликтов в +`vendor/modules.txt`. + +--- + +## 2. `internal/vfs` + +### 2.1 Типы и интерфейс + +```go +package vfs + +type Kind uint8 +const (KindLocal Kind = iota; KindSFTP; KindArchive) + +// VolumeID: равные VolumeID означают «одно пространство имён файлов» (best effort). +// local: "local"; sftp: "ssh:" + SHA256-отпечаток host key (НЕ строка HostName — N-P0-5); +// archive: "archive:" + VolumeID внешней ФС + ":" + путь архива. +type VolumeID string + +type Caps struct { + ReadOnly bool // archivefs: все мутирующие методы → ErrReadOnly + AtomicReplace bool // Rename(..., Replace) атомарен (local: rename(2); sftp: posix-rename@openssh.com) + NoReplace bool // Rename(..., NoReplace) атомарен (local: renameat2 RENAME_NOREPLACE; sftp: SSH_FXP_RENAME v3) + Symlinks, Chmod, Chtimes bool + Fsync bool // local: да; sftp: fsync@openssh.com + Trash bool // local: да; sftp: нет (на первой итерации) + Exec bool // можно запускать файлы (только local) +} + +type FileInfo struct { + Name string + Size int64 + Mode fs.FileMode // как Lstat: ModeSymlink, ModeDir, ModeNamedPipe, ... + ModTime time.Time + Target *FileInfo // для симлинка: Stat цели; nil, если ссылка битая или цель не разрешалась + LinkErr error // почему Target == nil +} +func (fi FileInfo) IsDir() bool // Mode.IsDir() +func (fi FileInfo) IsSymlink() bool +func (fi FileInfo) NavigableDir() bool // IsDir() || (IsSymlink() && Target != nil && Target.IsDir()) +func (fi FileInfo) IsRegularLike() bool // regular или симлинк на regular + +type RenameMode uint8 +const (NoReplace RenameMode = iota; Replace) + +type CreateMode uint8 +const (CreateExcl CreateMode = iota; CreateTrunc) // движок использует только CreateExcl (temp-файлы) + +type File interface { + io.Reader; io.Writer; io.ReaderAt; io.Closer + Stat() (FileInfo, error) + Sync() error // ErrUnsupported, если !Caps.Fsync +} + +type FS interface { + Kind() Kind + Volume() VolumeID + Caps() Caps + Label() string // для UI: "local", "bob@prod", "foo.zip" + Paths() PathOps // правила путей: posix (sftp, archive) или filepath (local) + + Stat(ctx context.Context, p string) (FileInfo, error) + Lstat(ctx context.Context, p string) (FileInfo, error) + // ReadDir: семантика lstat; для симлинков реализация заполняет Target (local: Stat; + // sftp: параллельные Stat с лимитом 16). Порядок не гарантирован, сортирует панель. + ReadDir(ctx context.Context, p string) ([]FileInfo, error) + ReadLink(ctx context.Context, p string) (string, error) + RealPath(ctx context.Context, p string) (string, error) + + Open(ctx context.Context, p string) (File, error) + Create(ctx context.Context, p string, perm fs.FileMode, mode CreateMode) (File, error) + Mkdir(ctx context.Context, p string, perm fs.FileMode) error + Remove(ctx context.Context, p string) error // файл, симлинк или ПУСТОЙ каталог; по ссылкам не ходит + Rename(ctx context.Context, from, to string, mode RenameMode) error + Symlink(ctx context.Context, target, p string) error + Chmod(ctx context.Context, p string, mode fs.FileMode) error + Chtimes(ctx context.Context, p string, atime, mtime time.Time) error +} + +type PathOps interface { + Join(elem ...string) string; Dir(p string) string; Base(p string) string + Clean(p string) string; IsAbs(p string) bool; Sep() byte +} + +// Опциональные возможности (через type assertion): +type Trasher interface { Trash(ctx context.Context, p string) error } +type BirthTimer interface { BirthTime(ctx context.Context, p string) (time.Time, bool) } +type Execer interface { // только sftpfs поверх conn с exec; для server-side оптимизаций transfer + Exec(ctx context.Context, argv []string) (stdout []byte, err error) // аргументы экранирует реализация +} + +// Location — «где стоит панель / куда пишет операция». +type Location struct { FS FS; Path string } +func (l Location) Same(o Location) bool // Volume равны и Clean(Path) равны +``` + +Ошибки — сентинелы, проверяемые через `errors.Is`: `ErrNotExist`, `ErrExist`, `ErrPermission`, `ErrReadOnly`, +`ErrUnsupported`, `ErrConnLost` (соединение умерло, операцию можно повторить после reconnect), `ErrCancelled` +(= `context.Canceled`). SFTP-статусы и errno маппятся в них внутри реализации, поэтому UI и transfer не знают о +`*sftp.StatusError`. + +**Ctx во всех методах.** LocalFS почти везде его игнорирует (кроме длинных операций), SFTPFS по нему отменяет ожидание +(см. 3.4). Поэтому сигнатуры единые и тесты одни. + +### 2.2 Общие хелперы (одна реализация для всех FS) + +```go +// Walk: обход через Lstat, симлинки НЕ разыменовываются. Порядок: родитель раньше детей, внутри каталога по имени. +func Walk(ctx context.Context, fsys FS, root string, fn WalkFunc) error +type WalkFunc func(p string, fi FileInfo, err error) error // err != nil → ошибка чтения p; fn решает: SkipDir/вернуть + +// RemoveTree: Lstat корня; симлинк или файл → Remove; каталог → post-order Remove. Никогда не ходит по ссылкам (N-P0-3). +// progress вызывается после каждого удалённого элемента (троттлинг делает jobs). +func RemoveTree(ctx context.Context, fsys FS, p string, progress func(removed int)) error + +type SizeResult struct { Bytes int64; Files, Dirs, Unreadable int } +// DirSize: ошибка корня возвращается; ошибки вложенных каталогов считаются в Unreadable (N-P1-14). +func DirSize(ctx context.Context, fsys FS, p string, progress func(SizeResult)) (SizeResult, error) + +// SameFile: local+local → os.SameFile; одинаковый Volume → равенство RealPath; иначе false. +func SameFile(ctx context.Context, a FS, pa string, b FS, pb string) (bool, error) +// Within: true, если child == parent или лежит внутри (по RealPath/EvalSymlinks, только при одном Volume). +func Within(ctx context.Context, fsys FS, child, parent string) (bool, error) + +func ReadOnly(fsys FS) FS // обёртка: Caps.ReadOnly = true, мутации → ErrReadOnly +``` + +### 2.3 LocalFS (`vfs/localfs`) +- `Rename(NoReplace)` — `unix.Renameat2(..., RENAME_NOREPLACE)`; при `EINVAL`/`ENOSYS` (ФС не поддерживает) — + `link()+unlink()` для файлов, для каталогов `Lstat`-проверка + `rename` (узкое TOCTOU-окно, задокументировать). +- `ReadDir` — `os.ReadDir` + `Info()`; birth time не считается (11 мс из 32 на 20k), отдаётся через `BirthTimer` + только если включена колонка `created` или сортировка по ней. +- `Open` отказывает не-regular файлам для чтения содержимого? Нет: `Open` честный, проверка `IsRegular` — в preview и + transfer (там спецфайлы пропускаются), чтобы FIFO и устройства не читались (U-P1-10). +- `Trash` — freedesktop: home trash, если `st_dev` совпадает; иначе `$topdir/.Trash/$uid` (проверка sticky и не + симлинк) или `$topdir/.Trash-$uid`. `.trashinfo` создаётся через `O_EXCL` (коллизии имён — суффикс), `Path=` + URL-кодируется, `DeletionDate` в локальном времени. Под sudo используется корзина **эффективного** пользователя + (N-P2-12, U-P2 MoveToTrash). + +### 2.4 SFTPFS (`vfs/sftpfs`) +- Держит `*conn.Lease`; каждый вызов берёт текущий `*sftp.Client` через `conn.Client()` (atomic, см. 3.3). +- `Volume()` = `"ssh:" + hostKeyFingerprint`. Два алиаса одного сервера дают один Volume (N-P0-5). +- `Rename(Replace)` → `PosixRename` (если нет расширения — `Caps.AtomicReplace=false`, и transfer делает + rename-в-сторону: `dst → dst.vcom-old-*`, `tmp → dst`, удалить old; при сбое — откат). `Rename(NoReplace)` → `Rename` + (SSH_FXP_RENAME v3 у OpenSSH не перезаписывает). +- `Symlink`: OpenSSH и pkg/sftp-сервер **по-разному** трактуют порядок аргументов SSH_FXP_SYMLINK. Реализация + определяет это по `Conn.ServerVersion()` (OpenSSH → swap). Тест-стенд использует pkg/sftp-сервер, поэтому нужен + отдельный интеграционный тест против настоящего `sshd`, если он есть в системе (тег `integration`, см. 9.3). +- Ожидание с отменой: `call(ctx, func() error)` выполняет вызов, а при `ctx.Done()` возвращает `ErrCancelled` + сразу. Висящий вызов завершится сам при ответе или при закрытии соединения watchdog-ом (3.4). Результат такого + вызова выбрасывается. Утечки goroutine ограничены: пул закрывает мёртвое соединение за ≤ 25 с. +- Ошибки «соединение закрыто» (`sftp.ErrSSHFxConnectionLost`, `io.EOF` на канале) → `ErrConnLost`. + +### 2.5 ArchiveFS (`vfs/archivefs`) +- Монтирование = **индекс**, а не распаковка в `/tmp`. Индекс строится async-джобой (для tar.gz это один проход + распаковки с прогрессом и отменой). Пути внутри — виртуальные posix (`/dir/file`), временных каталогов нет вообще, + поэтому P0-2 (запись «в архив», которая на деле уходила в temp) невозможен в принципе. +- `Caps.ReadOnly = true`. Все мутации → `ErrReadOnly`. +- `Open(member)`: zip — прямой доступ (`zip.Reader` поверх `ReaderAt` архива); tar/tgz — последовательный проход до + члена (дорого, но используется только для превью и одиночного открытия). +- Массовое копирование из архива (F5 изнутри архива, Unpack) идёт через `archive.Source`: один проход по архиву + (см. 5.4). +- Архив на не-локальной FS сначала скачивается в cache (джоба с прогрессом), затем монтируется. +- Защита: zip-slip (`..`, абсолютные пути) отбрасывается при индексации; лимит на число членов (1 млн) и на суммарный + размер, показываемый перед распаковкой. + +--- + +## 3. `internal/ssh` + +### 3.1 `sshconfig`: разрешение хоста +```go +type Endpoint struct { + Alias string // как пользователь назвал хост + User string + Host string // HostName; если в конфиге нет — Alias (N-P1-5) + Port int + IdentityFiles []string; IdentitiesOnly bool + ProxyJump []Endpoint // поддержка на этапе 8 (ssh.Client.Dial через хопы) + ServerAliveInterval time.Duration; ServerAliveCountMax int + ConnectTimeout time.Duration + Password string // только для хостов, добавленных в vcom (hosts.dat) +} +func (e Endpoint) Key() string // "user@host:port" — ключ пула; алиасы с одинаковым user@host:port делят соединение + +type Resolver struct{ /* ~/.ssh/config через kevinburke/ssh_config: Host *, Include, key=value, кавычки */ } +func (r *Resolver) Hosts() []HostEntry // для списка хостов (явные Host без шаблонов) + свои из hosts.dat +func (r *Resolver) Resolve(alias string) (Endpoint, error) + +type Store struct{} // hosts.dat (как сейчас, шифрованный); Save — через atomicfile +``` + +### 3.2 `conn`: Dialer, Conn, Pool +```go +type HostIdentity struct { KeyType, FingerprintSHA256 string } + +type Prompter interface { // реализует UI через jobs.Ask; в тестах — заглушка + HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) + Password(ctx context.Context, ep Endpoint) (string, error) + KeyboardInteractive(ctx context.Context, ep Endpoint, instr string, qs []string, echo []bool) ([]string, error) + Passphrase(ctx context.Context, keyPath string) ([]byte, error) +} +type HostKeyDecision uint8 // Reject | AcceptOnce | AcceptAndSave + +type State uint8 // Connecting, Ready, Lost, Closed + +type Conn struct { /* ssh.Client, atomic.Pointer[sftp.Client], gen, state, caps */ } +func (c *Conn) Client() (*sftp.Client, error) // ErrConnLost, если state != Ready +func (c *Conn) Identity() HostIdentity +func (c *Conn) State() State +func (c *Conn) Caps() ConnCaps // posix-rename, fsync, statvfs, hardlink; exec (проба лениво) +func (c *Conn) Exec(ctx context.Context, argv []string, limit int64) ([]byte, int, error) // ctx → signal KILL + Close + +type Lease struct{} +func (l *Lease) Conn() *Conn +func (l *Lease) FS() vfs.FS // SFTPFS на этой аренде +func (l *Lease) Acquire() *Lease // ещё одна ссылка на то же соединение (mirror, джоба) +func (l *Lease) Release() // идемпотентно + +type Pool struct{} +type PoolOptions struct { + Prompter Prompter + HandshakeTimeout time.Duration // 20s по умолчанию; весь путь TCP+kex+auth+sftp init + KeepaliveInterval time.Duration // 15s (или ServerAliveInterval из конфига) + KeepaliveTimeout time.Duration // 10s на один ответ + KeepaliveMaxMiss int // 2 (или ServerAliveCountMax) + IdleClose time.Duration // 60s: соединение без аренд закрывается + OnEvent func(Event) // ConnStateChanged{Key, State, Err}; main проводит в program.Send +} +func NewPool(r *sshconfig.Resolver, o PoolOptions) *Pool +func (p *Pool) Acquire(ctx context.Context, ep Endpoint) (*Lease, error) // singleflight по Key: двойной Enter = одно соединение +func (p *Pool) Reconnect(ctx context.Context, key string) error // backoff 1,2,4..30s, ≤5 попыток +func (p *Pool) Close() error +``` + +### 3.3 Правила владения и жизненного цикла (N-P0-8, N-P1-12) +- Соединение закрывает **только пул**: при `refcount == 0` и истечении `IdleClose`, при `Close()` на выходе или при + переходе в `Lost`. Панели, джобы, превью и подсчёт размера держат `Lease`. +- Поля `Conn` не обнуляются. `*sftp.Client` хранится в `atomic.Pointer`, после закрытия возвращает свои ошибки, + которые мапятся в `ErrConnLost`. Гонка из `TestCloseRace` невозможна по построению. +- Reconnect создаёт новый `ssh.Client`/`sftp.Client` в том же `Conn` (растёт `gen`). Аренды остаются валидными. + Операции, начатые на старом поколении, получают `ErrConnLost`. +- Mirror, переход между панелями, фоновая джоба делают `lease.Acquire()` и `Release()` в конце. Выход из хоста в + одной панели не ломает другую. + +### 3.4 Таймауты и обнаружение смерти (N-P1-2, N-P1-3) +- **Dial:** `net.Dialer.DialContext(ctx)`, затем `conn.SetDeadline(now+HandshakeTimeout)` на kex, auth и + `sftp.NewClient` (ожидание VERSION); после успеха дедлайн снимается. Отмена `ctx` закрывает `net.Conn` + (`context.AfterFunc`). Goroutine подключения владеет результатом: если ctx уже отменён, она сама закрывает клиента + (утечка из add-host Esc исчезает). +- **Keepalive:** goroutine на соединение, `SendRequest("keepalive@openssh.com", true)` с таймером. Нет ответа + `KeepaliveMaxMiss` раз подряд → `sshClient.Close()` (все висящие запросы сразу получают ошибку) → `State=Lost` → + событие `ConnStateChanged`. +- **Watchdog операций:** если SFTP-вызов висит дольше 30 с (метаданные) или нет прогресса в потоке 30 с, делается + внеочередной keepalive с таймаутом 5 с; нет ответа → `Lost`. +- **Exec:** `ctx` → `session.Signal(KILL)` + `session.Close()`; вывод ограничен `limit` (по умолчанию 1 МиБ). + +### 3.5 Host key, auth, sftp-опции +- **HostKeyAlgorithms** (N-P1-4): до Dial читаем known_hosts для `[host]:port`/`host` (через проб-вызов + `knownhosts` callback с фиктивным ключом → `KeyError.Want`) и ставим `ClientConfig.HostKeyAlgorithms` в порядке + известных типов (RSA → `rsa-sha2-512`, `rsa-sha2-256`). Тревога «ключ изменился» — только если совпал тип, а ключ + другой. +- **Неизвестный хост:** `Prompter.HostKey` → модалка с отпечатком SHA256: «Принять и сохранить / Только сейчас / + Отказать». Запись в known_hosts — через `atomicfile` (append через temp-копию). Под sudo файл чужой → пишем только + в память на сессию и предупреждаем (N-P2-14). +- **Auth chain:** agent (одно соединение с агентом на процесс, закрывается на выходе; N-P2-1) → все `IdentityFiles` + (зашифрованный ключ → `Prompter.Passphrase`) → стандартные ключи (если не `IdentitiesOnly`) → пароль из hosts.dat + или `Prompter.Password` → keyboard-interactive через `Prompter` (вопросы показываются как есть, 2FA работает; N-P2-2). +- **SFTP-клиент** (N-P1-6): `sftp.NewClientPipe` с `UseConcurrentWrites(true)`, `UseConcurrentReads(true)`, + `MaxConcurrentRequestsPerFile(64)`. Запись через `File.ReadFrom(r)`, где `r` — ctx-reader с методом `Size()` + (иначе pkg/sftp выбирает последовательный путь). + +--- + +## 4. `internal/transfer` + +### 4.1 Типы +```go +type Op uint8 // Copy, Move +type ConflictPolicy uint8 // Ask, Overwrite, Skip, OverwriteOlder (перезаписать, если источник новее), KeepBoth +type SymlinkPolicy uint8 // CopyLinks (по умолчанию), FollowLinks +type ErrorPolicy uint8 // Ask (по умолчанию), SkipAll, Abort +type FsyncPolicy uint8 // FsyncReplace (по умолчанию: fsync перед заменой существующего файла), FsyncAlways, FsyncNever + +type Options struct { + Conflict ConflictPolicy; Symlinks SymlinkPolicy; OnError ErrorPolicy; Fsync FsyncPolicy + PreserveMode, PreserveTimes bool // true по умолчанию +} + +// Source — откуда берутся элементы. FSSource — обычные файлы; archive.Source — члены архива (один проход). +type Source interface { + Label() string + Walk(ctx context.Context, fn func(Item) error) error // фаза plan + Stream(ctx context.Context, items []Item, fn func(Item, io.Reader) error) error // фаза execute, в порядке источника +} +func FSSource(fsys vfs.FS, paths []string, sym SymlinkPolicy) Source // экспонирует FS для move/rename + +type ItemKind uint8 // File, Dir, Symlink, Special (пропускается с предупреждением) +type Item struct { + Rel string // путь относительно DstDir, posix + Kind ItemKind + Size int64 + Mode fs.FileMode + ModTime time.Time + LinkTarget string + Existing *vfs.FileInfo // что лежит в цели (Lstat), nil — ничего + Root int // индекс верхнеуровневого источника +} + +type Request struct { Op Op; From Source; To vfs.FS; ToDir string; Opts Options } + +type Conflict struct { Item Item; Kind ConflictKind } // ConflictKind: FileFile, TypeMismatch (файл↔каталог, ссылка↔каталог) +type Resolution struct { Action ResolveAction; ApplyToAll bool } // Overwrite | Skip | KeepBoth | Abort + +type Plan struct { + Req Request + Items []Item + TotalFiles int; TotalBytes int64 + Conflicts []Conflict + Warnings []string // спецфайлы, найденные .vcom-part-* мусора от прошлых сбоев + SameConn bool // From и To — одна аренда одного соединения (или обе local) +} + +type Progress struct { + Phase Phase // Scanning, Copying, Removing, Finishing + FilesDone, FilesTotal int; BytesDone, BytesTotal int64 + Current string; CurrentDone, CurrentSize int64 +} + +type Hooks struct { + Progress func(Progress) // вызывается часто, троттлинг делает jobs + Resolve func(ctx context.Context, c Conflict) (Resolution, error) + OnError func(ctx context.Context, e ItemError) (ErrorAction, error) // Retry | Skip | SkipAll | Abort +} + +type ItemError struct { Item Item; Op string; Err error } +type Report struct { + Done, Skipped, Failed int; Bytes int64 + Errors []ItemError + Cancelled bool + Affected []vfs.Location // каталоги, которые изменились (для перечитки панелей) + Err error // фатальная ошибка (план невалиден, цель read-only, соединение потеряно и Abort) +} + +func Prepare(ctx context.Context, req Request, progress func(Progress)) (*Plan, error) +func Execute(ctx context.Context, plan *Plan, h Hooks) Report + +// WriteAtomic — единственный способ записать файл в цель (используют transfer, archive.Create, remote edit). +func WriteAtomic(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) error +type WriteOptions struct { Perm fs.FileMode; ModTime time.Time; Replace bool; Fsync bool } +``` + +### 4.2 Prepare (plan): что проверяется до первой записи +1. `To` не read-only, `ToDir` существует и это каталог (не `ssh://`-список хостов: это вообще не `Location`; N-P2-10). +2. Для каждого корня: если источник и `ToDir/base` — **один файл** (`vfs.SameFile`), отказ «источник и цель совпадают» + (N-P0-5, N-P0-6). Если `ToDir` лежит внутри каталога-источника (`vfs.Within`, по RealPath/EvalSymlinks), отказ + «нельзя копировать каталог в самого себя». +3. Обход источника (`Walk`, Lstat) один раз: файлы, каталоги, симлинки, спецфайлы, размеры (N-P2-5). +4. Для каждого каталога-источника, у которого в цели есть одноимённый каталог, — один `ReadDir` цели (1 RTT на каталог, + а не на файл). Получаем `Existing` для всех элементов и список `Conflicts`. +5. Итог: `TotalFiles/TotalBytes` честные (N-P1-13, `TestCopyStatsBytes`). + +Plan строится внутри джобы (фаза Scanning с прогрессом и отменой), поэтому UI не ждёт даже на 2000 remote-источниках +(N-P1-1, `handleTransfer` Lstat в Update). + +### 4.3 Execute: семантика (одинаковая для всех пар FS) +- **Файл:** `WriteAtomic(To, dst)` = `Create(dir/.vcom-part-<8hex>-, CreateExcl)` → копирование через ctx-reader + (проверка `ctx.Err()` на каждом чанке, подсчёт байт) → `Close` (ошибка Close — ошибка элемента; N-P2-6) → + `Chmod`/`Chtimes` → `Sync`, если политика требует → `Rename(tmp, dst, NoReplace | Replace)`. + При любой ошибке или отмене temp удаляется. **Старый файл заменяется только самим rename** (N-P0-4, + `TestOverwriteThenDrop`). Даже если SameFile не распознал совпадение (chroot, localhost по ssh), источник не + обрезается: он сначала полностью читается во временный файл. +- **Элемент, запланированный как «новый»**, переименовывается с `NoReplace`. Если цель появилась после plan + (`ErrExist`), это конфликт, и он решается политикой (Ask спрашивает). +- **Каталог:** слияние (N-P0-7, `TestLocalOverwriteDirDeletesExtra`). Создаётся с `0700`, после заполнения + выставляются настоящие права и mtime (post-order; N-P1-17, `TestLocalCopyReadOnlyDir`). Существующий каталог не + трогается, кроме mtime/mode при `Preserve*`. +- **Перезапись никогда не удаляет дерево каталогов.** Конфликт `TypeMismatch` (файл ↔ каталог) допускает только + Skip / KeepBoth / Abort. +- **Симлинк:** `CopyLinks` → `ReadLink` + `Symlink` в temp-имя + rename. Битые ссылки переносятся как ссылки без + ошибки (`TestUploadDirWithBrokenSymlink`, `TestDownloadDirWithBrokenSymlink`). `FollowLinks` → копируется цель, + цикл ловится по глубине (40) и множеству посещённых RealPath. +- **Спецфайлы** (FIFO, сокет, устройство) пропускаются, попадают в `Warnings` и в отчёт. +- **Права:** `mode & 0o777` плюс sticky. setuid/setgid сбрасываются при смене Volume. Владелец не сохраняется. +- **Ошибка элемента:** `OnError` (Ask: Retry / Skip / Skip all / Abort). `ErrConnLost` → вопрос «Соединение потеряно: + Переподключиться и повторить / Прервать»; Retry вызывает `pool.Reconnect` и повторяет элемент (temp-схема делает + повтор безопасным). +- **Отмена** (N-P1-7, `TestCancelSingleFile`): ctx-reader прерывает поток; `context.AfterFunc(ctx, f.Close)` снимает + висящий сетевой вызов. После цикла — повторная проверка `ctx.Err()`, поэтому итог «отменено», а не «успех». Temp + текущего файла удаляется. Уже завершённые элементы остаются (это ожидаемо и видно в отчёте). +- **Move:** + - `SameConn` (обе local на одном устройстве, или одна аренда SSH) → `Rename` целиком верхнеуровневого элемента, + если для него нет конфликтов. Local `EXDEV` → переход на copy+delete. + - Иначе по элементам: скопировать → сверить размер → удалить источник элемента (`Remove`, без обхода по ссылкам). + Каталог-источник удаляется `Remove` только если он пуст, то есть всё его содержимое перенесено. Пропущенные или + упавшие элементы **остаются в источнике** (N-P0-3 в части move, N-P1-8 «ссылка теряется»). + - Shell `mv`/`cp` в same-host пути не используются (N-P1-10). Разные пользователи одного хоста — разные аренды, + значит `SameConn=false` и поток идёт через клиента: владелец файлов правильный. +- **Server-side copy** (оптимизация, задача 3.6): при `SameConn` и `Caps.Exec` копирование верхнеуровневого + **каталога**, которого нет в цели, делается `cp -a -- src ToDir/.vcom-part--name` и затем + `Rename(NoReplace)` в итоговое имя. Отмена — kill + `RemoveTree(temp)`. Прогресс — неопределённый + (`BytesDone` зачисляется по завершении). Если exec недоступен или `cp` вернул ошибку — обычный поток, один раз. +- **Прогресс:** `Hooks.Progress` вызывается из ctx-reader на каждый чанк и после каждого элемента. Троттлинг (10 Гц) + и коалесинг — в `jobs`, не здесь. +- **Affected:** `ToDir` и затронутые подкаталоги; при Move — ещё каталоги источника. + +### 4.4 Почему так закрываются баги стенда +| Тест стенда | Механизм | +|---|---| +| `TestOverwriteThenDrop`, `TestLocalOverwriteFailureLosesDest` | temp + rename, старая цель не трогается до rename | +| `TestSameFileViaAliasTruncates`, `TestLocalOverwriteViaSymlinkAlias` | SameFile по Volume(host key)+RealPath / os.SameFile; плюс temp + rename | +| `TestLocalOverwriteDirDeletesExtra`, `TestSameHostCpIntoExistingDir` | слияние каталогов; нет shell `cp`/`mv` в существующую цель | +| `TestUploadDirWithBrokenSymlink`, `TestDownloadDirWithBrokenSymlink` | CopyLinks | +| `TestPermsMtimeLost`, `TestLocalMtime` | Preserve* | +| `TestCancelSingleFile` | ctx-reader + финальная проверка ctx | +| `TestLocalCopyReadOnlyDir` | 0700 → chmod post-order | +| `TestCopyStatsBytes` | Prepare считает байты | +| `TestRemoveRecursiveSymlinkToDir` | `vfs.RemoveTree` с Lstat | + +--- + +## 5. `internal/archive` и `internal/preview`, `internal/imgview` + +### 5.1 archive: создание (U-P0-1) +```go +type Format uint8 // Zip, Tar, TarGz +func Name(srcNames []string, f Format) string // foo.tar.gz → zip даёт foo.zip (а не foo.tar.zip; U-P2) +func Create(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string, f Format, + h transfer.Hooks) transfer.Report +``` +- Перед стартом: `archivePath` не равен ни одному источнику и не лежит внутри источника-каталога (`vfs.SameFile`, + `vfs.Within`). Если файл существует — конфликт (Ask: Перезаписать / Другое имя / Отмена), имя по умолчанию + предлагается с суффиксом `name (1).zip`. +- Запись через `transfer.WriteAtomic` (temp + rename): частичный архив при ошибке или отмене удаляется, источник + никогда не обрезается. Ошибки `Close()` у zip/tar/gzip writer — ошибка операции (N-P2-13). +- Источник может быть на любой FS, цель тоже (архивирование на remote работает). +- Симлинки пишутся как симлинки (tar: `TypeSymlink`; zip: Unix-mode с `S_IFLNK` и путём в теле). + +### 5.2 archive: чтение +```go +type Index struct { Format Format; Entries []Entry /* posix-путь, mode, size, mtime, link */ } +func BuildIndex(ctx context.Context, r io.ReaderAt, size int64, f Format, progress func(n int)) (*Index, error) +func NewSource(fsys vfs.FS, archivePath string, idx *Index, members []string) transfer.Source // один проход +``` + +### 5.3 Unpack +Unpack = `transfer.Execute` с `archive.NewSource(...)` → **любая** цель (local/remote), конфликты и temp + rename +как у copy (U-P1-11: больше нет тихой перезаписи и записи сквозь существующие симлинки цели: rename заменяет саму +ссылку, а каталоги-предки создаются движком через `Mkdir` с Lstat-проверкой, что это каталог, а не ссылка). + +### 5.4 preview +```go +type Request struct { + Loc vfs.Location; Info vfs.FileInfo + MaxBytes int64; MaxLines, DirLimit int + Theme string; Icons IconMode +} +type Result struct { + Kind Kind // Empty, Directory, Text, Image, PDF, Audio, Video, Binary, Special, Error + Meta Metadata + Lines []string // уже подсвеченные (SGR без фона), по одной строке экрана без переноса + Plain []string // те же строки без SGR — для caret/yank + Dir []vfs.FileInfo // не больше DirLimit + Image *ImageRef // Loc + размер + формат; декодирует imgview + Truncated bool + Err error +} +func Build(ctx context.Context, req Request) Result // чистая функция, без глобального состояния +``` +- Не-regular файлы не читаются: Kind=Special и метаданные (U-P1-10: FIFO, `/dev/tty`, `/dev/zero`). +- Внешние утилиты: `exec.CommandContext` с таймаутом 3 с; `pdftotext -l 3` (только первые страницы), вывод + ограничен `MaxBytes`. Утилиты ищутся один раз при старте. +- Подсветка: свой chroma-formatter (пишет SGR только для foreground/bold/italic), без regexp-постобработки (минус + `stripBackgroundSGR` и минус ~190 мс на 64 КиБ). ctx проверяется каждые 256 токенов. Подсвечиваются максимум + `MaxLines` (3000) строк. +- Маппинг тема → chroma-стиль — таблица в `theme` для **всех** тем; тест проверяет, что у каждой темы есть маппинг + (U-P2 «7 из 22»). +- Remote-картинки: скачиваются только если размер ≤ `preview.max_remote_image_bytes` (20 МиБ), в cache с ключом + `(Volume, path, size, mtime)`; LRU по суммарному размеру (200 МиБ), чистка на старте. Больше лимита — только + метаданные (N-P1-16). +- LRU результатов (32 записи) по ключу `(Volume, path, size, mtime, theme, kind)`. + +### 5.5 imgview (overlay картинок) +```go +type SyncTTY struct{ /* *os.File + sync.Mutex; реализует term.File: Read, Write, Close, Fd */ } +// main: tea.NewProgram(app, tea.WithOutput(tty)) — рендерер Bubble Tea пишет кадр одним Write под тем же mutex. + +type Backend uint8 // None, Kitty, Ueberzug +type Desired struct { Visible bool; Image preview.ImageRef; Rect Rect; Gen uint64 } + +type Actor struct{} +func Start(tty *SyncTTY, b Backend) *Actor +func (a *Actor) Apply(d Desired) // неблокирующий: слот «последнее желаемое состояние» + сигнал +func (a *Actor) Stop() // в teardown, убивает ueberzugpp, чистит kitty-изображения +``` +- Goroutine актора берёт последнее `Desired`, отменяет устаревшую работу, декодирует (`image.DecodeConfig` → + отказ, если больше 50 Мпикс), масштабирует (`x/image/draw` ApproxBiLinear) и выводит. +- Kitty: escape-последовательности пишутся под mutex `SyncTTY` одним блоком `ESC7 CUP APC… ESC8` (курсор не + сдвигается, рендерер не сбивается). Если терминал локальный (нет `SSH_TTY`), передача через `t=t` (временный PNG, + терминал читает файл сам): без base64 на 100+ МБ. Под tmux kitty выключен, если `preview.image_backend` явно не + `kitty` (тогда используется passthrough). +- ueberzugpp: запись в stdin неблокирующая (отдельный writer с таймаутом 200 мс; завис → kill и `None` с + уведомлением). +- Backend выбирается при старте: `preview.image_backend = auto|kitty|ueberzugpp|none`; auto: kitty при + `TERM=xterm-kitty`/`KITTY_WINDOW_ID`/`TERM_PROGRAM∈{WezTerm,ghostty}` и не в tmux, иначе ueberzugpp, если найден. + +--- + +## 6. `internal/jobs` + +```go +type ID uint64 +type Kind string // "copy", "move", "delete", "trash", "archive", "unpack", "mount", "dirsize", "connect", "edit-upload" +type State uint8 // Queued, Running, Waiting (ждёт ответа пользователя), Done, Failed, Cancelled + +type Progress struct { Phase string; FilesDone, FilesTotal int; BytesDone, BytesTotal int64; Current string } + +type Snapshot struct { + ID ID; Kind Kind; Title string; State State + Progress Progress; Started time.Time; Background bool + Result any // transfer.Report и т. п. для Done/Failed +} + +type Question struct { + Job ID; QID uint64 + Payload any // transfer.Conflict, transfer.ItemError, conn.HostKeyQuestion, conn.PasswordQuestion, ... +} + +type Event interface{ isEvent() } +// Started{Snapshot}, ProgressTick{[]Snapshot} (≤10 Гц, только изменившиеся), +// Asked{Question}, Finished{Snapshot} + +type Handle struct{} +func (h *Handle) SetProgress(p Progress) // O(1), «последнее значение» +func (h *Handle) Ask(ctx context.Context, payload any) (any, error) // блокирует goroutine джобы, State=Waiting + +type Func func(ctx context.Context, h *Handle) (result any, err error) + +type Manager struct{} +func New(notify func(Event), maxParallel int) *Manager // main: notify = program.Send(jobEventMsg{e}) +func (m *Manager) Start(k Kind, title string, fn Func, holds ...Releaser) ID // holds: аренды/монтирования, Release в конце +func (m *Manager) Answer(q uint64, answer any) +func (m *Manager) Cancel(id ID) +func (m *Manager) SetBackground(id ID, bg bool) +func (m *Manager) Snapshot() []Snapshot +func (m *Manager) Active() int +func (m *Manager) Shutdown(ctx context.Context) error // Cancel всех, ждать до ctx (temp-файлы успевают удалиться) +``` +- Все goroutine запускаются через `safeGo` с recover → `Finished{State: Failed, err: panic}` + лог. +- Параллельно выполняется до `maxParallel` джоб (по умолчанию 2), остальные в очереди. Это убирает + «Transfer is already running» после подтверждения. +- `notify` вызывается из goroutine менеджера. Bubble Tea `Send` блокируется до чтения, но частота событий ограничена + (10 Гц + start/finish/ask), поэтому backpressure на копирование нет (было: канал 256 и полный View на каждый файл). + +--- + +## 7. UI: `internal/tui` + +### 7.1 Модель +```go +type Screen uint8 +const (ScreenBrowse Screen = iota; ScreenInfo; ScreenView) + +type App struct { + cfg *config.Config; pal theme.Palette; styles *Styles // стили строятся один раз на тему + keys *keys.Registry + screen Screen + viewBack Screen // куда вернуться из ScreenView + panels [2]*panel.Model + active int + filter *FilterEdit // != nil, пока редактируется строка фильтра (владелец ввода) + viewer viewer.Model // текст/картинка/прочее для Info и View; Focus: Scroll | Caret | Visual + nativeSelect bool // Ctrl+T: мышь отдана терминалу (только Info/View) + modals modal.Stack + notify notify.Center + jobs *jobs.Manager + pool *conn.Pool + img *imgview.Actor + req Tracker + layout Layout // считается в WindowSizeMsg и при смене Screen/фильтра + applied Effects // что уже применено: мышь, overlay + deps Deps // фабрики: LocalFS, Resolver, Clipboard, Editor/Opener, Clock — подменяются в тестах +} +``` +- Модель — `*App` везде (pointer receiver, `Update` возвращает тот же указатель; U-P2 «Model/*Model»). +- Cmd-функции **никогда не захватывают `*App`**. Они захватывают только неизменяемые входные данные (`Location`, + опции, `Ticket`, аренду). + +### 7.2 Машина состояний + +Состояние = `Screen` × `viewer.Focus` × `nativeSelect` × `filter != nil` × стек модалок. Допустимые комбинации +задаются инвариантами, которые проверяет `App.checkInvariants()` (вызывается в тестах после каждого `Update`): +- `viewer.Focus != Scroll` ⇒ `Screen ∈ {Info, View}` и `viewer.Kind == Text`; +- `nativeSelect` ⇒ `Screen ∈ {Info, View}`; +- `filter != nil` ⇒ `Screen ∈ {Browse, Info}` и модалок нет; +- в `ScreenView` фильтр не редактируется. + +Переходы (все через `app.setScreen` / `app.setFocus`, которые обновляют layout и запрашивают превью): + +| Из | Событие | В | Побочные действия | +|---|---|---|---| +| Browse | `o`/F9 | Info | layout, запрос превью | +| Info | `o`/F9/`q`/Esc (фокус Scroll) | Browse | focus=Scroll, nativeSelect=false | +| Info | `i` (текст) | Info, Caret | курсор на первую видимую строку | +| Info/View, Caret | `v` | Visual | якорь = курсор | +| Visual | `v`/Esc | Caret | — | +| Visual | `y` | Caret | yank выделения, вспышка | +| Info, Caret | Esc/`q` | Info, Scroll | — | +| Browse/Info | F3/`v` (файл) | View, `viewBack`=текущий | для текста focus=Scroll | +| Browse/Info | F3/`v` (каталог) | — | уведомление «не файл» | +| View, Caret/Visual | Esc | на шаг назад по фокусу | — | +| View | `q`/F3, или Esc при Scroll | `viewBack` | focus=Scroll, nativeSelect=false | +| Info/View | Ctrl+T | nativeSelect=true | мышь выкл.; в статусе «выделение мышью терминала: Ctrl+T/Esc» | +| nativeSelect | Ctrl+T/Esc | nativeSelect=false | мышь вкл. | +| Browse/Info | `/` | filter edit | — | +| filter edit | Enter | фильтр зафиксирован | — | +| filter edit | Esc | фильтр снят | — | +| любой | открыть модалку | push | screen не меняется | +| модалка | закрыть | pop | — | +| смена каталога в панели | — | фильтр и метки панели сброшены | — | +| превью пришло, Kind≠Text при Caret | только если Ticket текущий | focus=Scroll | — | + +### 7.3 Кто владеет вводом (одна функция) +```go +func (a *App) inputOwner() keys.Context { + switch { + case a.modals.Len() > 0: return a.modals.Top().Context() // ModalDialog | ModalInput | ModalList | ModalProgress + case a.filter != nil: return keys.CtxFilterEdit + case a.screen == ScreenView: return viewerCtx(a.viewer.Focus) // CtxViewScroll | CtxCaret | CtxVisual + case a.screen == ScreenInfo && a.viewer.Focus != viewer.Scroll: return viewerCtx(a.viewer.Focus) + case a.screen == ScreenInfo: return keys.CtxInfo // Browse + i, Ctrl+T, Ctrl+E/Y + default: return keys.CtxBrowse + } +} +``` +- **Мышь** маршрутизируется так же: при открытой модалке все события мыши получает модалка (колесо прокручивает, + клик по кнопке нажимает, клик вне модалки игнорируется). Под модалкой ничего не меняется. +- **Hit-test** по `Layout` (одни и те же прямоугольники для рендера, мыши и overlay): `layout.PaneRows[i]`, + `layout.Preview`, `layout.PreviewBody`, `layout.CopyPathIcon`, `layout.Status`. Индекс строки → `panel.visible[...]`, + поэтому клик при фильтре попадает в видимую строку (U-P1-4). + +### 7.4 Роутинг клавиш (`tui/keys`) +```go +type ActionID string // "nav.down", "file.copy", "viewer.visual", ... +type Context uint8 // CtxBrowse, CtxInfo, CtxFilterEdit, CtxViewScroll, CtxCaret, CtxVisual, + // CtxModalDialog, CtxModalInput, CtxModalList, CtxModalProgress +type Binding struct { Keys []string; Help string; Footer bool } + +type Registry struct{} // map[Context]map[ActionID]Binding + глобальные; загружается из DefaultBindings() +func (r *Registry) Resolve(ctx Context, msg tea.KeyMsg) (ActionID, bool) +func (r *Registry) Help(ctx Context) []Section // help и footer генерируются отсюда +``` +- `Resolve` для **командных** контекстов: сначала оригинальная клавиша, затем транслированная из ЙЦУКЕН + (`й→q, ц→w…`, с регистром). Для **текстовых** контекстов (`CtxFilterEdit`, `CtxModalInput`) перехватываются только + `enter, esc, tab, shift+tab, up, down, ctrl+c, ctrl+u`, всё остальное в оригинальном виде уходит в `textinput` + (U-P1-5: «папка» остаётся «папка»; в SSH-форме можно набрать `q`). +- Chord-префиксы (`yy` в Caret) — маленький буфер в `Registry` на контекст. Сбрасывается любой не продолжающей + клавишей или сменой контекста. Глобального `pendingY` больше нет. +- Привязки по умолчанию разложены по файлам фич (`keys/bindings_browse.go`, `bindings_ops.go`, `bindings_viewer.go`, + `bindings_ssh.go`, …), `DefaultBindings()` их собирает; тест проверяет, что в одном контексте нет двух действий на + одну клавишу. Так параллельные разработчики не конфликтуют в одном файле. +- Обработчики действий — `map[ActionID]func(*App) tea.Cmd` в файлах фич. Каждое действие объявляет + `Enabled(*App) error`: проверяется перед выполнением (ошибка → уведомление «Недоступно: архив только для чтения») + и используется для приглушения в footer/help. Пример: `file.copy` недоступен, если цель — список хостов или + read-only FS; `file.run` — если `!Caps.Exec`. +- Тест-страж: в `internal/tui/**` (кроме `keys`) запрещено сравнивать `msg.String() ==` и вызывать `key.Matches`. + +### 7.5 Модальный стек (`tui/modal`) +```go +type Modal interface { + ID() uint64 + Context() keys.Context + Update(msg tea.Msg) (Outcome, tea.Cmd) // Outcome: Keep | Close{Value any} + View(maxW, maxH int, s *Styles) string // сам скроллится, если не помещается (help, theme на малых терминалах) +} +type Stack struct{} // Push(m, onClose func(*App, any) tea.Cmd), Top, Pop, Len, CloseByID + +type Dialog struct { // структурный, без эвристик по тексту (костыль #14) + Title string + Fields []KV // «Источник: …», «Цель: …», «Объём: 12 файлов, 340 МБ» + Warnings []string // «3 конфликта», «2 помеченных скрыты фильтром и НЕ войдут» + Buttons []Button // {Label, Key, Value, Danger, Default} +} +``` +Виды: `Dialog` (confirm, delete, quit), `Input` (mkdir, rename, ssh-форма; несколько полей), `List` (тема с +живым превью, сортировка, хосты, джобы, журнал, help), `Progress` (джоба), `Conflict`, `Prompt` (host key, +пароль/вопросы keyboard-interactive). Уведомления — **не** модалки (см. 7.6), поэтому таймер не может закрыть чужую +модалку (костыль #13). + +### 7.6 Уведомления и статус (U-P1-1) +```go +type Level uint8 // Info, Success, Warn, Error +type Center struct{} +func (c *Center) Push(l Level, text string) uint64 // id +func (c *Center) Current(now time.Time) (Note, bool) +func (c *Center) Log() []Note // кольцо на 200 записей +``` +- Раскладка снизу: **статус-строка** (всегда видна) + footer с подсказками (если `ui.show_footer`). +- Статус-строка: слева — бейдж режима (`INFO`, `VIEW`, `CARET`, `VISUAL`, `FILTER`, `SELECT`) и текущее уведомление + цветом уровня; справа — индикатор джоб (`⟳ copy 45% · +1 в очереди`) и, если есть, состояние соединения активной + панели (`⚠ prod: отключено`). +- TTL: Info/Success 3 с, Warn 6 с, Error — до следующего нажатия, но не меньше 3 с. Таймер — `tea.Tick` с id + уведомления: сообщение закрывает только своё уведомление. +- `L` открывает журнал сообщений (List-модалка). + +### 7.7 Async I/O: Tracker и generation +```go +type ReqKey struct { Kind ReqKind; Pane int; Extra string } // ReqList, ReqPreview, ReqPreviewDebounce, ReqDirSize(path), ReqMount, ... +type Ticket struct { Key ReqKey; Gen uint64 } +type Tracker struct{} +func (t *Tracker) Begin(k ReqKey) (Ticket, context.Context) // отменяет предыдущий ctx того же ключа, Gen++ +func (t *Tracker) Accept(tk Ticket) bool // текущий ли; если да — снимает ключ +func (t *Tracker) CancelAll(kind ReqKind) +``` +- **Каждый** async-msg содержит `Ticket`. В начале `Update`: `if !a.req.Accept(msg.Ticket) { return a, nil }` — до + любых побочных эффектов (U-P1-13: устаревшее превью больше не выключает caret и не теряет temp-файл). +- Листинг: `panel.Navigate(loc, focusName)` → `ReqList` → Cmd `ReadDir` → `listingMsg{Ticket, Loc, Infos, Err}`. + Применение — **транзакция** (U-P1-8): при успехе атомарно меняются `Location`, entries, history и курсор; при + ошибке панель не меняется и показывается уведомление. Если текущий каталог исчез при refresh — подъём к ближайшему + существующему родителю (цепочка Cmd). +- Превью: перемещение курсора → `ReqPreviewDebounce` + `tea.Tick(100ms)` → если тик текущий, запускается + `ReqPreview` с `preview.Build`. Одно превью в полёте на приложение, предыдущее отменяется через ctx (N-P1-16). +- Подсчёт размера (Space) — джоба `dirsize` (с отменой; при уходе из каталога продолжает считать, результат кладётся + в кэш размеров по `Location`, а не «в текущую строку»). +- Подключение SSH — джоба `connect`, привязанная к **панели, где нажали Enter** (N-P2-8). Повторный Enter во время + подключения игнорируется (`Enabled`). + +### 7.8 Панель (`tui/panel`) +```go +type Mount struct { + FS vfs.FS + Root string + Return *vfs.Location // куда выйти по `..` из корня (каталог с архивом / локальный путь до SSH) + release func() // Lease.Release / archive mount unref +} +type Source uint8 // SourceDir, SourceHosts (список SSH-хостов — не FS и не цель операций) + +type Model struct { + ID int + Source Source + Mounts []Mount // стек: local → archive → archive-в-архиве; или remote + Path string // в FS верхнего Mount + entries []Entry // отсортированы; Entry = vfs.FileInfo + вычисленные поля (категория, ключ сортировки, иконка) + visible []int // индексы после фильтра (+ «..») + cursor, offset int // в пространстве visible + marks map[string]struct{} // по имени; сбрасываются при смене каталога, НЕ при Tab + filter string + history, future []Snapshot // Snapshot = {Mounts (с Acquire), Path, Focus} + cursorMemory *lru.Map[string,string] // ≤ 200; ключ = Volume+path + sizes map[string]vfs.SizeResult // результаты Space + conn ConnBadge // Ready | Lost | Reconnecting (для remote) + loading bool + rowCache rowCache +} +func (p *Model) Location() vfs.Location +func (p *Model) Selected() (Entry, bool) // всегда из visible +func (p *Model) Targets() (entries []Entry, hiddenMarked int) // помеченные ∩ видимые, иначе курсор +func (p *Model) Apply(loc vfs.Location, infos []vfs.FileInfo, focus string) // применение транзакции +func (p *Model) Reload(infos []vfs.FileInfo) // сохраняет курсор по имени; промах → тот же индекс (ограниченный) +``` +- Сортировка и `ShowHidden`/`DirsFirst` одинаковы для всех FS (N-P2-7). Ключи сортировки (`lower(name)`) + считаются один раз при загрузке. +- Симлинк на каталог: `NavigableDir()` → вход по Enter/`l` (U-P1-2). Категория `executable` только у + `IsRegularLike()` с битом x. +- После операции: `Report.Affected` → `App.invalidate(locs)` перечитывает **каждую** панель, чья `Location` + совпадает (`Same`), каждая со **своим** курсором (U-P1-7, N-P1-11). Удалённый под курсором элемент → курсор остаётся + на том же индексе, то есть на соседнем элементе. +- Mirror (`p`): пассивная панель получает копию стека `Mounts` с `Acquire()` у каждой аренды/монтирования и тот же + `Path` (U-P1-14, N-P1-12). +- Выход из Mount по `..` в его корне: `release()` и переход в `Return` с курсором на имени архива / хоста. + +### 7.9 Эффекты (мышь, overlay) и чистый View +После каждого `Update` вызывается `a.reconcile() tea.Cmd`: +```go +type Effects struct { Mouse bool; Overlay imgview.Desired } +func (a *App) desired() Effects { + return Effects{ + Mouse: !a.nativeSelect, + Overlay: imgview.Desired{ + Visible: (a.screen == ScreenInfo || a.screen == ScreenView) && a.viewer.Kind == preview.Image && a.modals.Len() == 0, + Image: a.viewer.Image, Rect: a.layout.PreviewBody, Gen: a.viewer.Gen, + }, + } +} +``` +Если `desired != applied`, выпускается одна команда (`tea.EnableMouseCellMotion`/`DisableMouse`, `img.Apply`). +Мышь после внешнего процесса (редактор, запуск) восстанавливается тем же механизмом: `applied.Mouse` сбрасывается в +«неизвестно» в обработчике `execDoneMsg` (U-P1-3, костыль #6). `View()` только читает состояние. + +### 7.10 Кэш рендера (цель: ≤ 2 мс на кадр при 2×20k записей) +- `Styles` — все `lipgloss.Style` строятся один раз при смене темы. В рендере `NewStyle()` не вызывается. +- `panel.rowCache`: ключ `(entriesGen, idx, selected, marked, hovered, active, width, themeGen)` → строка; размер ≈ + 4× видимых строк. `columnSpec` — по `(width, columns, icons)`. +- `visible` пересчитывается только при смене entries или фильтра (а не в каждом кадре, как `filteredPane`). +- Вьюер рендерит **только видимое окно** строк. Caret и visual накладываются на эти строки по ячейкам + (`ansi.Cut`/`uniseg`), колонка курсора хранится в графемах и переводится в ячейки (U-P2 CJK). «Безопасный reset» + строится из стиля через `termenv`-профиль, вывод lipgloss не парсится (U-P0-3). Тесты рендера идут в двух профилях: + `Ascii` и `TrueColor`. +- `viewport.SetContent` на весь файл в каждом кадре больше нет. +- Статус-строка и footer кэшируются по `(width, ctx, noteID, jobsGen, themeGen)`. + +### 7.11 Фоновые джобы в UI +- `jobEventMsg` обрабатывается в одном месте: `Started` → если джоба foreground, открыть `Progress`-модалку; + `ProgressTick` → обновить снапшоты (модалка и статус-строка читают их); `Asked` → открыть `Conflict`/`Prompt` + (если джоба в фоне — уведомление «Джоба ждёт ответа: B» и мигающий индикатор); `Finished` → уведомление с + итогом («Скопировано 12, пропущено 1, ошибок 2 — L для подробностей»), `invalidate(Report.Affected)`. +- `B` — список джоб (List-модалка): открыть прогресс, отменить, показать отчёт. +- Выход при активных джобах: диалог «Идут N операций: [Отменить и выйти] [Назад]». При подтверждении + `jobs.Shutdown(3s)` → teardown. + +### 7.12 Внешние процессы +- **Edit (F4/Enter на тексте):** local → `tea.ExecProcess($VISUAL/$EDITOR)`; аргументы разбираются через + `shlex`-подобный разбор с кавычками (U-P2 `strings.Fields`). Remote → джоба: скачать в run-dir (запомнить + size+mtime) → редактор → если содержимое изменилось: `Stat` remote; size/mtime изменились → диалог + «Файл на сервере изменился: [Перезаписать] [Сохранить копию рядом] [Отменить]» → `transfer.WriteAtomic` (N-P0-2). +- **Open (xdg-open):** local — `Start` + `Wait` в goroutine (без зомби; U-P1-15); remote — сначала скачать + в run-dir; правки не синхронизируются, о чём говорит уведомление. +- **Run:** Enter на исполняемом файле **не запускает** его, а открывает меню «Запустить / Редактировать / + Просмотр / Отмена». Запуск только при `Caps.Exec` (local), через `ExecProcess` с паузой «Нажмите Enter» после + выхода (U-P1-3, N-P0-2). + +### 7.13 Тест-страж «UI не трогает ФС напрямую» +`internal/tui/imports_test.go` разбирает импорты всех файлов `internal/tui/**` (`go/parser`) и падает, если +встречает `os`, `os/exec`, `io/fs`, `path/filepath`, `syscall`, `vcom/internal/vfs/localfs`, `github.com/pkg/sftp`. +Allowlist: `tui/external.go` (`os/exec` для редактора/открытия), `tui/deps.go` (фабрики). Так «забыли if remote» +перестаёт компилироваться в тесте, а не ловится ревью. + +--- + +## 8. Финальная раскладка клавиш + +Принципы: F-клавиши как в MC; vim-движения везде одинаковые; одна клавиша в одном контексте = одно действие; +разрушительные действия либо требуют подтверждения, либо не имеют «случайной» клавиши. + +### 8.1 Browse (и Info, пока вьюер не в фокусе) +| Клавиши | Действие | Изменение относительно v0.2.7 | +|---|---|---| +| ↑/`k`, ↓/`j` | курсор | — | +| PgUp/`Ctrl+B`, PgDn/`Ctrl+F` | страница | PgDn раньше не работал (U-P1-6) | +| `Ctrl+U`, `Ctrl+D` | полстраницы | новое | +| Home/`g`, End/`G` | в начало / в конец | `g` был сортировкой | +| Enter | открыть: каталог/архив — войти; текст — редактировать; исполняемый — меню Run; прочее — xdg-open; хост — подключиться | исполняемые больше не запускаются сразу | +| →/`l` | войти в каталог/архив (на файле — ничего) | `l` был «переключить панель» | +| ←/`h`/Backspace | в родительский каталог | `h` был «переключить панель» | +| Tab | переключить панель | — | +| Alt+←/`[`, Alt+→/`]` | история назад/вперёд | `[`/`]` новые (Alt-стрелки ловят не все терминалы) | +| Insert | пометить и вниз | новое (как в MC) | +| Shift+↑/`K`, Shift+↓/`J` | пометить с движением | — | +| Esc | снять фильтр, затем снять метки (по слоям) | Esc никогда не выходит | +| Space | размер каталога (выделенного или помеченных) | — | +| `/` | фильтр | — | +| `.` | скрытые файлы | — | +| `S` | меню сортировки (поле + обратный порядок) | был `g` (цикл) | +| `o`/F9 | Info вкл/выкл | — | +| F3/`v` | просмотр (View) | `v` больше не конфликтует с Visual | +| F2/`r` | переименовать | — | +| F4 | редактировать | F4 был «архив» (MC-стиль: F4 = edit) | +| `a` | создать архив | F4 убран | +| `e`/F11 | распаковать | — | +| F5/`c` | копировать | — | +| F6/`m` | переместить | — | +| F7/`n` | создать каталог | — | +| F8/Delete/`x` | в корзину | раньше по умолчанию безвозвратно (U-P0-4) | +| Shift+F8/Shift+Delete/`X` | удалить безвозвратно (всегда подтверждение, по умолчанию «Отмена») | новое | +| `y` | скопировать путь(и) в буфер (OSC52 + системный буфер) | был только в Info | +| `p` | mirror: пассивная панель в то же место | — | +| `s`/F12 | список SSH-хостов вкл/выкл | — | +| `Ctrl+R` | перечитать панели | — | +| `t` | выбор темы | — | +| `B` | список фоновых джоб | новое | +| `L` | журнал сообщений | новое | +| F1/`?` | справка | — | +| `q`/F10 | в Info — закрыть Info; в Browse — выход (с подтверждением; `q q` выходит быстро) | раньше `q` выходил сразу из любого режима (U-P1-16) | +| `Ctrl+C` | как Esc; в Browse без фильтра/меток — выход (с подтверждением) | в Info больше не «копировать путь» | + +Только в **Info**: `i` — фокус во вьюер (caret), `Ctrl+E`/`Ctrl+Y` — прокрутка превью, `Ctrl+T` — выделение +мышью терминала, колесо над превью — прокрутка превью. + +### 8.2 Вьюер (View; Info с фокусом) +| Клавиши | Scroll | Caret | Visual | +|---|---|---|---| +| `j`/`k`/↑/↓ | строка | курсор | расширить | +| `h`/`l`/←/→ | гориз. прокрутка (без переноса) | курсор | расширить | +| `w`/`b`/`e`, `0`/`^`/`$` | — | слово / строка | расширить | +| `g`/`G`, PgUp/PgDn, `Ctrl+U/D/B/F` | навигация | навигация | расширить | +| `i` | → Caret | — | — | +| `v` | → Visual (с текущей строки) | → Visual | → Caret | +| `y` / `yy` | — | `yy` — строка | `y` — выделение → Caret | +| `W` | перенос строк вкл/выкл | то же | то же | +| Esc | View: закрыть; Info: в Browse-фокус | → Scroll (View) / снять фокус (Info) | → Caret | +| `q`/F3 | закрыть View / снять фокус Info | то же | то же | +| `Ctrl+T` | выделение мышью терминала | то же | то же | + +Картинка в View: `q`/Esc/F3 — закрыть. + +### 8.3 Строка фильтра (текстовый контекст) +Любой символ (в т. ч. кириллица) → в поле; Enter — зафиксировать; Esc/`Ctrl+C` — снять; ↑/↓ — двигать курсор панели, +не выходя из поля. + +### 8.4 Модалки +| Вид | Клавиши | +|---|---| +| Dialog | Enter — кнопка в фокусе; Tab/←/→ — фокус; горячие клавиши кнопок (`y`/`n`/`o`/`s`/`k`…); Esc/`Ctrl+C`/`q` — отмена. Безвозвратное удаление: фокус по умолчанию на «Отмена», подтверждение — `y` или Tab+Enter | +| Input | текст (оригинальная раскладка); Enter — OK; Esc/`Ctrl+C` — отмена; Tab/Shift+Tab — поле; `Ctrl+U` — очистить поле. `q` — обычная буква | +| List | ↑/↓/`j`/`k`, PgUp/PgDn, Home/End, Enter — выбрать; Esc/`q` — закрыть; в теме — живое превью, Esc откатывает | +| Progress | Esc/`b`/`q` — в фон; `c`/`Ctrl+C` — «Отменить операцию?» (Enter/`y` — отменить, Esc/`n` — продолжить) | +| Conflict | `o` перезаписать, `O` перезаписать все, `s` пропустить, `S` пропустить все, `u` перезаписать, если новее (для всех), `k` оставить обе (переименовать новую), Esc — прервать джобу | +| Help | ↑/↓/PgUp/PgDn — прокрутка; Esc/`q`/F1/`?` — закрыть | + +### 8.5 Мышь +ЛКМ — выбор строки (по `visible`) и активация панели; двойной ЛКМ — как Enter (исполняемые → меню Run); ПКМ — Info +вкл/выкл; колесо — прокрутка той области, над которой курсор. Клик по иконке «копировать путь» — только внутри её +точного прямоугольника из `Layout`. При модалке мышь получает только модалка. + +### 8.6 Разрешение конфликтов (сводка) +| Клавиша | Было | Стало | +|---|---|---| +| `v` | View перехватывал Visual везде | Browse: View; вьюер: Visual | +| `q` | выход из программы из любого режима | закрыть слой; выход только из корня Browse с подтверждением | +| `c` | Copy и Cancel прогресса (`c` дважды отменял копирование) | Browse: Copy; Progress: запрос отмены с подтверждением | +| `h`/`l` | переключить панель (а ←/→ — родитель/войти) | родитель/войти, как ←/→; Tab — переключить | +| `g` | сортировка | в начало; сортировка — `S` | +| `Ctrl+C` | выход / копирование пути / игнор по режимам | как Esc; в корне Browse — выход | +| `y` | путь в Info, перехватывался раньше всех | путь в Browse/Info; yank во вьюере | +| F4 | архив | редактировать; архив — `a` | +| Delete/F8 | безвозвратно по умолчанию | корзина; безвозвратно — Shift+Delete/Shift+F8/`X` | +| PgDn | не назначен | назначен | +| ЙЦУКЕН | транслировался и в полях ввода | только для команд | + +--- + +## 9. Конфиг, сессия, логи, временные файлы + +### 9.1 Пути (`internal/paths`) +- Конфиг: `-config PATH` → `$VCOM_CONFIG` → `$XDG_CONFIG_HOME/vcom/vcom.toml` → `~/.config/vcom/vcom.toml`. + **`./vcom.toml` и `./config/vcom.toml` убраны** (чужой конфиг из cwd и его перезапись). Если на старте найден + `./vcom.toml`, а XDG-конфига нет, в журнал пишется подсказка (не загружается). +- Состояние: `$XDG_STATE_HOME/vcom/` (`session.toml`, `vcom.log`). known_hosts остаётся в `~/.ssh`. + Миграция: если есть старый `~/.config/vcom/session.toml`, он читается один раз и переносится. +- Кэш и временное: `$XDG_CACHE_HOME/vcom/run-/` (0700) — remote-превью, файлы для edit/open, kitty `t=t`. + На старте удаляются `run-*` с мёртвым pid (это закрывает мусор после `kill -9`/паники; U-P1-15). +- **sudo:** чтение конфига и `~/.ssh` — из home вызвавшего пользователя (удобство); **запись** (state, cache, + корзина, known_hosts) — только в каталоги эффективного пользователя. Нет файлов root в `~user` (U-P2 sudo). + +### 9.2 Запись +- `atomicfile.WriteFile(path, data, perm)`: temp в том же каталоге → write → fsync → rename → fsync каталога. + Используется для конфига, сессии, hosts.dat, known_hosts (U «Конфиг и сессия»: обрезанный TOML). +- **Тема** (`config.SetKey(path, "ui", "theme", value)`): точечная правка строки `theme = ...` в секции `[ui]` с + сохранением комментариев, порядка и неизвестных ключей. Нет ключа → вставка в конец секции; нет секции → в конец + файла; нет файла → создаётся XDG-конфиг с одной секцией. После правки результат парсится, при ошибке запись + отменяется. Если конфиг при старте не распарсился, SetKey отказывает. `toml.Marshal(cfg)` поверх файла пользователя + больше не вызывается. +- Битый конфиг **не** роняет запуск: старт с умолчаниями + ошибка в статус-строке и журнале. Неизвестные ключи → + предупреждение (strict decode в отдельном проходе), не ошибка. +- Мёртвые опции: `show_title_bar`, `app_title` — удалить (принимаются и игнорируются с предупреждением); + `confirm_delete` — реализовать (только для корзины); `follow_symlinks` — реализовать как + `transfer.Symlinks=FollowLinks` по умолчанию в диалоге; `center_width_percent` → переименовать в + `ui.preview_width_percent` (ширина превью в Info, по умолчанию 50, старое имя — алиас с предупреждением); + `auto_refresh*` — убрать из примера `vcom.toml` (реализация — опционально в этапе 8). +- Новые опции: `behavior.confirm_quit = true`, `transfer.on_conflict = "ask"`, `transfer.preserve = true`, + `transfer.fsync = "replace"`, `transfer.max_parallel_jobs = 2`, `preview.image_backend = "auto"`, + `preview.max_remote_image_bytes`, `ssh.keepalive_interval`, `ssh.connect_timeout`. +- Сессия: сохраняется на выходе, по сигналу и раз в 30 с при изменениях (Cmd, не в Update). Remote- и archive-панели + восстанавливаются в последний локальный каталог перед ними (без автоподключения на старте). `cursor_memory` ≤ 200 + записей, без путей cache. + +### 9.3 Логи (`internal/logx`) +- `log/slog` (text handler) в `$XDG_STATE_HOME/vcom/vcom.log`, файл 0600, каталог 0700. +- Уровень: `--log-level=debug|info|warn|error` или `VCOM_LOG`; по умолчанию `warn`. `--debug` = `debug`. +- Ротация на старте: если файл > 5 МиБ → `vcom.log.1` (старый `.1` удаляется). Один файл, а не новый на каждый + запуск. +- Нажатия клавиш и progress — только на `debug`. Пароли, passphrase и ответы keyboard-interactive не логируются + никогда (тест на redaction). +- 178 `log.Printf` из `model.go` уходят вместе со старым UI. + +### 9.4 Запуск и завершение (`cmd/vcom`) +1. flags → logx → config (ошибка не фатальна) → state → `run-dir` (+ чистка) → `SyncTTY` → pool, jobs, imgview → + `tui.New(deps)` → `tea.NewProgram(app, WithAltScreen, WithMouseCellMotion, WithOutput(tty))`. +2. `signal.Notify(SIGTERM, SIGHUP, SIGINT-вне-raw)` → `program.Send(quitMsg{force:true})`. +3. `defer teardown()` выполняется **после** `program.Run()` в любом случае (нормальный выход, паника, + перехваченная Bubble Tea, сигнал): `jobs.Shutdown(3s)`, `state.Save`, `img.Stop`, `pool.Close`, удаление + `run-dir`. + +--- + +## 10. Как закрывается каждая P0/P1 проблема + +Этапы — из `03-tasks.md`. «S1» — хотфикс на старом коде (если делается), окончательное решение — в указанном этапе. + +### 10.1 Сеть (`01-analysis-network.md`) +| ID | Проблема | Решение в дизайне | Этап | +|---|---|---|---| +| N-P0-1 | Rename в remote-панели трогает локальный файл | все операции через `panel.Location().FS`; тест-страж импортов (7.13) | S1 → 6.2 | +| N-P0-2 | Enter/F4 на remote-файле → локальный файл | Edit через скачивание/загрузку с проверкой конфликта; Run только при `Caps.Exec`; Open через run-dir (7.12) | S1 → 6.4/6.6 | +| N-P0-3 | Удаление remote-симлинка стирает цель | `vfs.RemoveTree` с Lstat, общий для всех FS, conformance-тест | S1 → 2A | +| N-P0-4 | Перезапись разрушает цель до записи | `transfer.WriteAtomic` (temp + rename, cleanup) | 3 | +| N-P0-5 | Тот же файл через алиасы обнуляется | Volume = host key fingerprint; SameFile; temp + rename | 2B, 3 | +| N-P0-6 | Локальный симлинк-алиас цели | os.SameFile + EvalSymlinks в Prepare; temp + rename | 3 | +| N-P0-7 | Перезапись каталога удаляет лишнее | слияние каталогов; дерево никогда не удаляется ради перезаписи | 3 | +| N-P0-8 | Гонка Close() | Pool + Lease refcount, atomic client, поля не обнуляются | 2B | +| N-P1-1 | Синхронный SFTP в Update | всё через Cmd + Ticket; Prepare в джобе; тест с блокирующей FaultFS | 6.1 | +| N-P1-2 | Мёртвое соединение | keepalive с таймаутом → Lost → событие; watchdog; Reconnect; UI-бейдж | 2B, 6.4 | +| N-P1-3 | Нет таймаута handshake, утечка при отмене | deadline на весь handshake; ctx закрывает net.Conn; владелец результата закрывает поздний клиент | 2B | +| N-P1-4 | Ложный «host key changed» | HostKeyAlgorithms из known_hosts | 2B | +| N-P1-5 | Host без HostName → localhost; `=`; `Host *` | kevinburke/ssh_config; HostName по умолчанию = alias | 2B | +| N-P1-6 | Медленный upload | concurrent reads/writes + ctx-reader с `Size()` | 2B, 3 | +| N-P1-7 | Отмена не работает внутри файла | ctx-reader, AfterFunc(Close), Exec kill, финальная проверка ctx | 3 | +| N-P1-8 | Симлинки при передаче | CopyLinks по умолчанию, битые — как ссылки, спецфайлы — в предупреждения; move не теряет ссылки | 3 | +| N-P1-9 | Права и mtime теряются | Preserve* | 3 | +| N-P1-10 | Same-host cp/mv вкладывает | нет shell mv; same-conn Rename; server cp только в temp-имя + rename (3.6) | 3 | +| N-P1-11 | После remote-delete панели читаются как локальные | `invalidate(Affected)` по Location, перечитка через FS панели | 6.2 | +| N-P1-12 | Mirror делит клиента и закрывает его | `Lease.Acquire` при mirror; закрывает только пул | 2B, 6.6 | +| N-P1-13 | Прогресс врёт | Prepare считает файлы и байты; байты из ctx-reader; троттлинг в jobs | 3, 4 | +| N-P1-14 | Размер каталога глотает ошибки | `vfs.DirSize` возвращает ошибку корня и `Unreadable`; UI показывает «≥ X (N недоступно)» | 2A, 6.6 | +| N-P1-15 | Archive/Unpack игнорируют remote | archive.Create поверх vfs; Unpack = archive.Source → transfer в любую FS | 5A, 6.5 | +| N-P1-16 | Remote-превью без ограничений | debounce, одно превью в полёте, ctx, лимит размера картинок, кэш | 5B, 6.3 | +| N-P1-17 | Копирование read-only каталога | каталоги 0700 → chmod post-order | 3 | + +P2 (кратко): агент — одно соединение на процесс (2B); auth chain + Prompter (2B, 6.4); `SameAs` без User → ключ пула +содержит user (2B); MkdirAll на файл и двойной обход → один Prepare (3); ошибки Close + fsync (3); remote-листинг без +сортировки и symlink-dir → общая панель (6.1); sshConnectMsg в чужую панель → джоба привязана к панели (6.4); мёртвый +код → удаляется с пакетом (7); цель `ssh://` → `SourceHosts` не цель (6.2); выход во время передачи → quit-диалог + +Shutdown (6.2); MoveToTrash EXDEV/URL → localfs.Trash (2A); ошибки Close архивов → WriteAtomic (5A); TOFU молча → +Prompter.HostKey (2B, 6.4); Exec без таймаута → ctx + limit (2B). + +### 10.2 UI и ядро (`01-analysis-ui-core.md`) +| ID | Проблема | Решение в дизайне | Этап | +|---|---|---|---| +| U-P0-1 | Архивация уничтожает исходник | проверка SameFile/Within + WriteAtomic + конфликт имени | S1 → 5A | +| U-P0-2 | Операции в архив-панель пишут во temp | ArchiveFS без temp-каталогов, `Caps.ReadOnly`, `Enabled()` у действий | 5A, 6.5 | +| U-P0-3 | Паника caret при Ascii-профиле | вьюер не парсит вывод lipgloss; тесты в Ascii и TrueColor | S1 → 6.3 | +| U-P0-4 | Удаление безвозвратно по умолчанию | корзина по умолчанию; Shift+Del — безвозвратно, фокус на «Отмена»; `n` отменяет; `confirm_delete` работает | S1 → 6.2 | +| U-P1-1 | Статус не виден | статус-строка + notify.Center + журнал `L` | S1 → 6.1 | +| U-P1-2 | Симлинки на каталоги | `FileInfo.Target`, `NavigableDir`, executable только для regular | 2A, 6.1 | +| U-P1-3 | Enter запускает исполняемые | меню Run; мышь восстанавливается через эффекты | 6.6 | +| U-P1-4 | Фильтр и мышь/операции | `visible []int`, hit-test по Layout, сброс фильтра при смене каталога, скрытые метки не входят (предупреждение) | 6.1 | +| U-P1-5 | Кириллица в полях | трансляция только в командных контекстах | S1 → 6.1 | +| U-P1-6 | PgDn не назначен | назначен (+ Ctrl+F/B/D/U) | S1 → 6.1 | +| U-P1-7 | Курсор пассивной панели сбрасывается | у каждой панели свой preserve; промах → тот же индекс | 6.1/6.2 | +| U-P1-8 | Path и Entries расходятся | навигационная транзакция; подъём к существующему родителю; нет temp-путей в истории | 6.1 | +| U-P1-9 | Блокирующий I/O в Update/View | async листинг, async индекс архива, imgview-актор, конфиг/сессия в Cmd, icon-mode с таймаутом | 5, 6 | +| U-P1-10 | Превью FIFO/устройств, утилиты без таймаута | IsRegular, CommandContext 3 с, `pdftotext -l 3`, ctx | 5B | +| U-P1-11 | Распаковка перезаписывает молча | Unpack через transfer: конфликты, temp + rename, не пишет сквозь ссылки | 5A, 3 | +| U-P1-12 | Enter/edit на remote → локальный | = N-P0-2 | S1 → 6.4/6.6 | +| U-P1-13 | Устаревшие async-сообщения | Tracker/Ticket, Accept до побочных эффектов; id у уведомлений | 6.1 | +| U-P1-14 | Mirror ломает панели | копия стека Mounts с Acquire | 6.6 | +| U-P1-15 | Нет cleanup при сигнале/панике; зомби xdg-open | signal → quitMsg; teardown после Run; чистка run-* на старте; Wait | 2C, 6.6, 7 | +| U-P1-16 | Конфликты клавиш, `msg.String()` | реестр по контекстам (раздел 8), тест-страж | 6.1 | + +U-P2 (кратко): `yankFlashLine` и ширина символов → вьюер по ячейкам (6.3); иконки ASCII/emoji → иконки из одного +источника с учётом `icon_mode`, без emoji (6.1); `kindLabel` → preview.Meta (5B); `RenamePath` с `/` → ошибка +валидации имени (6.2); help без операций → генерация из реестра (6.1); `confirm_overwrite` → `transfer.on_conflict` +(2C, 6.2); `cursorMemory` растёт → LRU 200 (6.1); `ArchiveName` → `archive.Name` (5A); двойная распаковка ради +счётчика → индекс (5A); логи → logx (2C); `strings.Title`, свои `min`/`max` → уходят с old ui (7). + +### 10.3 Костыли из отчёта UI (раздел 4) → чем заменяются +1 флаги → `Screen`+Focus (7.2); 2 translateKeyMsg → keys.Registry (7.4); 3 `msg.String()` → тест-страж; 4 дубли +навигации текста → viewer; 5 `pendingY` → chord-буфер; 6 мышь → эффекты (7.9); 7–9 overlay/магические отступы/hit-test → +imgview + Layout; 10 overlayCenter → modal.Stack со скроллом; 11 парсинг lipgloss → styles/termenv; 12 stripBackgroundSGR → +свой formatter; 13 таймеры без id → notify id; 14 модалка-строка → Dialog; 15 `"ssh://"` → `SourceHosts`; 16–17 +archiveJob для delete, opMsg → jobs.Kind и один путь; 18 `_ = reloadPane` → invalidate; 19 логи → logx; 20 горутины в +Cmd + захват модели → jobs.Manager + Cmd без `*App`; 21 Model/*Model → `*App`; 22 copyPath → из viewer; 23 мёртвый код → +этап 7; 24 previewMsg → Ticket; 25 kittyTried → выбор backend на старте. + +--- + +## 11. Стратегия тестирования + +### 11.1 Уровни +| Уровень | Что | Где | +|---|---|---| +| Unit | хелперы vfs (Walk, RemoveTree, DirSize, SameFile, Within), PathOps, transfer (plan, конфликты, политики) на LocalFS + FaultFS, archive (индекс, slip, создание), preview.Build (виды, лимиты, FIFO), config.SetKey (комментарии, отсутствующая секция, битый файл), atomicfile, keys.Registry (контексты, ЙЦУКЕН, chord), notify, Tracker, panel (фильтр, курсор, метки, Reload), viewer (caret/visual по ячейкам, Ascii-профиль) | рядом с пакетом | +| Conformance | один набор `vfstest.Run(t, factory)` для LocalFS, SFTPFS (через стенд), ArchiveFS (read-only подмножество): Lstat/ReadDir с симлинками, Remove не ходит по ссылкам, Rename NoReplace/Replace, Create Excl, Chmod/Chtimes, маппинг ошибок | `vfs/vfstest`, вызовы из `localfs`, `sftpfs`, `archivefs` | +| Стенд SSH | conn (handshake timeout, freeze, cut, keepalive → Lost, reconnect, host key algos, TOFU через Prompter, race Close), sftpfs, transfer local↔remote↔remote, отмена, throughput при RTT 20 мс | `testutil/sshtest`; тесты в `ssh/conn`, `vfs/sftpfs`, `transfer` | +| UI характеризационные | `teadriver.Driver`: `Press("j")`, `Type("папка")`, `Mouse(x,y)`, `Settle()` (выполняет Cmd до тишины с таймаутом), `Screen()` (View без ANSI), `Invariants()` | `tui/*_test.go` (драйвер в `testutil/teadriver`) | +| Интеграция с настоящим sshd | порядок аргументов symlink, posix-rename, fsync@openssh | тег `integration`, пропускается, если нет `/usr/sbin/sshd`; в CI не обязателен | + +### 11.2 Стенд (из `plans/rework/testbed/`) +`internal/testutil/sshtest` (обычный пакет, не `_test.go`, чтобы импортировался из разных пакетов): +```go +type Server struct { Addr string; HostKeys []ssh.Signer; Root string } +type Options struct { Password string; HostKeys []ssh.Signer; NoExec bool /* ForceCommand internal-sftp */; Chroot string } +func Start(t testing.TB, o Options) *Server +type Proxy struct { Addr string } +func NewProxy(t testing.TB, target string) *Proxy +func (p *Proxy) SetDelay(d time.Duration); func (p *Proxy) Freeze(on bool); func (p *Proxy) CutAfter(n int64); func (p *Proxy) KillAll() +func IsolatedHome(t testing.TB) string // HOME → TempDir, SSH_AUTH_SOCK = "" +``` +Старые repro-тесты (B1–B12, локальные 6) переносятся как **приёмочные** тесты новых API (`transfer`, `vfs`, `conn`) +с теми же именами, поэтому видно, какой баг каким тестом закрыт. + +### 11.3 FaultFS +```go +type Op string // "readdir", "open", "create", "write", "rename", ... +type FaultFS struct { vfs.FS; Hook func(op Op, p string) error } // Hook может вернуть ошибку, спать или ждать канал +``` +Используется для ENOSPC на N-й записи, ошибки Close, отмены посреди файла и **блокировки** ReadDir в UI-тестах +(«`Update` возвращается, пока ReadDir висит; `q` работает»). + +### 11.4 UI-тесты, обязательные для приёмки этапа 6 +- навигация, фильтр + клик мышью, PgDn, история, курсор пассивной панели после операции; +- copy/move/delete/trash/mkdir/rename в local и (через стенд) в remote-панели: эффект на ФС проверяется по диску + стенда, а не по экрану; +- remote rename/Enter/F4 не трогает локальный файл с тем же путём (N-P0-1/2); +- устаревший `listingMsg`/`previewMsg` не меняет состояние; +- инварианты машины режимов после каждого шага случайной последовательности клавиш (fuzz по таблице действий, 10k шагов, + seed в логе); +- кириллица в mkdir/фильтре; `q` в SSH-форме; +- рендер в Ascii и TrueColor профилях без паники. + +### 11.5 CI +`.github/workflows/ci.yml`: `gofmt -l` пусто, `go vet ./...`, `go test -race -count=1 ./...` (стенд работает в +процессе, внешней сети не нужно), проверка, что `go mod vendor` не даёт diff. Бенчмарки (`BenchmarkView20k`, +`BenchmarkPreviewGo64K`, throughput) — не гейт, а ручной контроль; плюс тест `AllocsPerRun` для кадра из кэша (гейт с +запасом ×2). diff --git a/plans/rework/03-tasks.md b/plans/rework/03-tasks.md new file mode 100644 index 0000000..dfbc125 --- /dev/null +++ b/plans/rework/03-tasks.md @@ -0,0 +1,453 @@ +# 03. План работ для разработчика + +Дизайн: `02-design.md` (ссылки «§N»). Баги: `01-analysis-network.md` (**N-…**), `01-analysis-ui-core.md` (**U-…**). +Стенд аналитиков: `plans/rework/testbed/*.go.txt`. + +## Правила для каждого этапа и задачи +- После каждой задачи: `go build ./...`, `go vet ./...`, `go test -race -count=1 ./...` зелёные; `gofmt -l .` пусто. + Старый UI (`internal/ui`) продолжает работать до этапа 7. +- Новые пакеты не импортируют старые (`internal/fs`, `internal/fs/remote`, `internal/ui`, `internal/homedir`). + Старые пакеты могут временно импортировать новые (так делают 2C и хотфиксы). +- Приёмка = названные тесты существуют и проходят. Тест на баг называется по имени из стенда, если оно было + (`TestOverwriteThenDrop` и т. д.), иначе `Test_<что>` (например `TestNP01_RemoteRenameUsesRemoteFS`). +- Новые зависимости добавляет **только** указанная задача (2B.1: `kevinburke/ssh_config`; 5C.1: `golang.org/x/image`), + вместе с `go mod vendor` в том же коммите. +- Размер: S — до дня, M — 2–4 дня, L — неделя и больше. + +## Карта этапов и параллельность + +``` +Этап 0 (последовательно, 1 разработчик) + │ + ├──► Этап 1 хотфиксы старого кода (internal/ui, internal/fs*) ─────────────► релиз v0.2.8 [параллельно 2–5] + │ + └──► 2.0 интерфейс vfs (S, блокирует остальное) + ├──► 2A LocalFS + хелперы + conformance ─┐ + ├──► 2B ssh: config, conn, pool, sftpfs ─┤ 2A ‖ 2B ‖ 2C + └──► 2C config/state/paths/logx │ + ▼ + 3 transfer (после 2A; 3.7 после 2B) ‖ 4 jobs ‖ 5A archive (после 2A) ‖ 5B preview ‖ 5C imgview + │ + ▼ + 6.1 каркас нового UI (internal/tui, флаг --ui=next) — последовательно + ├──► 6.2 операции ├──► 6.3 вьюер/превью ├──► 6.4 SSH ├──► 6.5 архивы ├──► 6.6 прочее + └──────────────── все пять параллельно, разные файлы ────────────────┘ + ▼ + 6.7 приёмочный набор UI + fuzz инвариантов + бенчмарки + ▼ + 7 переключение, удаление старого кода, документация → релиз v0.3.0 + ▼ + 8 опционально: ProxyJump, автообновление, remote-корзина, параллельный Walk +``` + +Горячие файлы (там возможны конфликты, порядок мержа указан): +- `go.mod`, `go.sum`, `vendor/` — 2B.1, затем 5C.1. +- `cmd/vcom/main.go` — 2C.4 → 6.1.6 → 7.1. +- `internal/ui/model.go` — только этап 1 и 2C.3 (одна функция `finalizeTheme`): 2C.3 мержится после этапа 1. +- `internal/tui/app.go`, `internal/tui/update.go` — меняются в 6.1; в 6.2–6.6 каждая фича добавляет свои файлы + (`ops_*.go`, `viewer_*.go`, `ssh_*.go`, `archive_*.go`, `misc_*.go`) и свои `keys/bindings_<фича>.go`; + регистрация обработчиков — через `init`-free функцию `registerXxx(r *actionTable)`, которую вызывает `app.go` + (одна строка на фичу, добавляется в 6.1 заранее как заглушки). + +--- + +## Этап 0. Тестовый фундамент (последовательно; ~M) + +### 0.1 Перенести стенд SSH/SFTP в `internal/testutil/sshtest` (M) ✅ done (commit 05da3c0) +- **Цель:** стенд аналитиков становится переиспользуемым пакетом (§11.2). +- **Файлы:** новый `internal/testutil/sshtest/{server.go,proxy.go,home.go}`; источник — + `plans/rework/testbed/remote_harness_test.go.txt`. +- **Сделать:** API из §11.2 (`Start`, `Options{Password, HostKeys, NoExec, Chroot}`, `NewProxy` с + `SetDelay/Freeze/CutAfter/KillAll`, `IsolatedHome`, `GenKeys`). Exec: `exit-status` и stderr; `NoExec` отклоняет + exec (как `ForceCommand internal-sftp`). Все goroutine завершаются по `t.Cleanup`. +- **Приёмка:** `TestServerSFTPRoundTrip` (подключение `x/crypto/ssh` + `pkg/sftp` к серверу, запись/чтение файла); + `TestProxyDelay` (RTT ≥ задержки); `TestProxyFreeze` (запрос не завершается, пока freeze, и завершается после + снятия); `TestProxyCut` (соединение рвётся после N байт). `go test -race` без утечек goroutine (`goleak` не + добавляем; проверка: `runtime.NumGoroutine` возвращается к базовому ±2 после Cleanup). + +### 0.2 `internal/testutil/fstree` (S) ✅ done (commit ffcc8f5) +- **Цель:** описывать и сравнивать деревья в тестах transfer/archive. +- **Файлы:** `internal/testutil/fstree/fstree.go`. +- **Сделать:** `Build(t, root, spec)` (spec: файлы с содержимым/размером/mode/mtime, каталоги, симлинки, FIFO); + `Snapshot(t, root) Tree`; `Equal(t, want, got, opts{Mode, MTime, Links})` с понятным diff. +- **Приёмка:** `TestFstreeRoundTrip` (Build → Snapshot → Equal), включая симлинк и каталог 0555. + +### 0.3 `internal/testutil/teadriver` + smoke-тесты старого UI (M) ✅ done (commit 1f6f400) +- **Цель:** драйвер для прогонки `Update`/`View` с сообщениями; набор поведенческих тестов, которые переживут + переписывание (проверяют клавиши → эффект на диске и на экране, а не внутренности). +- **Файлы:** `internal/testutil/teadriver/driver.go`, `internal/ui/smoke_test.go`. +- **Сделать:** `New(t, model, w, h)`, `Press(keys ...string)`, `Type(text)`, `Mouse(x, y, button)`, + `Settle(timeout)` (выполняет возвращённые Cmd в goroutine, разворачивает `tea.BatchMsg`/`sequenceMsg`, подаёт + результаты обратно в `Update`, пока очередь не опустеет; Cmd вида `tea.Tick` с задержкой > 1 с не ждёт), + `Screen()` (View без ANSI), `Model()`. Профиль lipgloss принудительно Ascii в драйвере, отдельный хелпер + `WithProfile(TrueColor)`. +- **Smoke (старый UI, только local, на `t.TempDir()`):** навигация в каталог и назад; F7 mkdir; F5 копирование файла + (Enter в confirm); F2 rename; `/` фильтр сужает список; F8 + подтверждение удаляет файл. Тесты, которые сейчас + падают из-за известных багов (PgDn, кириллица), пишутся как `t.Skip("U-P1-6: fixed in 1.6")` — снимаются в + задачах-исправлениях. +- **Приёмка:** `go test ./internal/ui -run Smoke` зелёный; драйвер покрыт `TestDriverSettleBatch`. + +### 0.4 CI (S) ✅ done (commit 829b123) +- **Файлы:** `.github/workflows/ci.yml` (+ `Makefile` с целями `test`, `race`, `lint`). +- **Сделать:** `gofmt -l .` пусто, `go vet ./...`, `go test -race -count=1 ./...`, проверка `go mod vendor` без diff + (`git diff --exit-code vendor go.mod go.sum`). `release.yml` вызывает те же шаги. +- **Приёмка:** CI зелёный на ветке; намеренно неформатированный файл валит job (проверить локально). + +--- + +## Этап 1. Хотфиксы на старом коде (параллельно этапам 2–5; ~M; релиз v0.2.8) + +Цель — убрать потерю данных у пользователей v0.2.7, пока идёт rework. Код этапа выбрасывается на этапе 7, поэтому +минимальные правки, без рефакторинга. Файлы: только `internal/ui/*.go`, `internal/fs/*.go`, `internal/fs/remote/*.go`. +Задачи 1.x можно делать в любом порядке; все трогают `model.go`, поэтому — один разработчик или последовательные +маленькие PR. + +| # | Задача | Приёмка (тест в `internal/ui` или `internal/fs*`) | Баги | +|---|---|---|---| +| 1.1 | Показать `m.status` в строке над footer (одна строка, цвет по префиксу ошибки) ✅ done (commit 5113754) | `TestStatusVisible`: после F7 с существующим именем текст ошибки есть в `Screen()` | U-P1-1 | +| 1.2 | Заблокировать в remote-панели rename, Enter/F3-open/edit/execute на файлах, archive, unpack; заблокировать copy/move/unpack/archive, если **пассивная** панель в архиве или в `ssh://` (`canWriteTo`) ✅ done (commit 2f3491c) | `TestNP01_RemoteRenameBlocked`, `TestNP02_RemoteEnterDoesNotTouchLocal` (локальный файл с тем же путём не изменён, внешний процесс не запущен — подставной opener), `TestUP02_NoWriteIntoArchivePane` | N-P0-1, N-P0-2, N-P1-15, U-P0-2, N-P2-10 | +| 1.3 | `RemoveRecursive`: Lstat корня, симлинк → `Remove`; в `walk` корень через Lstat ✅ done (commit 8d6fe48) | перенесённый `TestRemoveRecursiveSymlinkToDir` (на стенде 0.1) | N-P0-3 | +| 1.4 | Удаление по умолчанию в корзину; `n` закрывает диалог; `confirm_delete=false` пропускает подтверждение только для корзины ✅ done (commit f575659) | `TestUP04_DeleteDefaultsToTrash`, `TestUP04_NCancels` | U-P0-4 | +| 1.5 | Caret-рендер без `bgCode[2:len-1]` ✅ done (commit 6696fea) | `TestUP03_CaretAsciiNoPanic` (профиль Ascii) | U-P0-3 | +| 1.6 | `translateKeyMsg` только для поиска команд; PgDn назначен; `q` при Info/фильтре/выделении закрывает слой, а не выходит ✅ done (commit 2ba00b0) | снять Skip со smoke PgDn и кириллицы; `TestUP116_QClosesInfo` | U-P1-5, U-P1-6, U-P1-16 (часть) | +| 1.7 | Архивация: отказ, если имя архива совпадает с источником или лежит внутри него; существующий архив → confirm ✅ done (commit fbaffb4) | `TestUP01_ArchiveDoesNotDestroySource` | U-P0-1 | +| 1.8 | `SSHClient`: mutex на `Close`, клиент в `atomic.Pointer`, методы не читают поле дважды; `goParent`/mirror не закрывают клиента, если он используется другой панелью или джобой (счётчик пользователей на клиенте) ✅ done (commit dc3d1b7) | перенесённый `TestCloseRace` под `-race` без DATA RACE и паники | N-P0-8, N-P1-12 (часть) | +| 1.9 | Релиз v0.2.8: CHANGELOG с перечнем исправлений ✅ done (commit 0a98a75) (тег/публикация — за мейнтейнером) | — | — | + +--- + +## Этап 2. VFS, SSH, конфиг + +### 2.0 Интерфейс `internal/vfs` (S; **блокирует** 2A, 2B.5, 3, 5A, 5B) ✅ done (commit 2db51e9) +- **Цель:** зафиксировать контракт §2.1 до реализации. +- **Файлы:** `internal/vfs/{fs.go,fileinfo.go,errors.go,paths.go,location.go,readonly.go}`. +- **Сделать:** типы и интерфейсы §2.1 (`FS`, `File`, `FileInfo`, `Caps`, `VolumeID`, `RenameMode`, `CreateMode`, + `PathOps` posix/native, `Location.Same`, сентинелы ошибок, `Trasher`, `BirthTimer`, `Execer`), `ReadOnly(fs)`. +- **Приёмка:** `TestReadOnlyRejectsMutations` (на фейковой FS все мутации → `ErrReadOnly`), `TestPosixPathOps`. + +### 2A. LocalFS и общие хелперы (M–L; 1 разработчик; параллельно 2B и 2C) + +**2A.1 `vfs/localfs`** — §2.3. ✅ done (commit c3de5a0; conformance — 9d5b6bf) +- Файлы: `internal/vfs/localfs/{localfs.go,rename_linux.go,rename_other.go,birth_linux.go}`. +- Приёмка: `vfstest` conformance (2A.3) зелёный; `TestRenameNoReplaceExisting` (→ `ErrExist`, цель не изменена); + `TestReadDirSymlinkTarget` (симлинк на каталог: `NavigableDir()==true`; битая ссылка: `Target==nil`, `LinkErr!=nil`) + — закрывает U-P1-2 на уровне данных; `TestReadDirNoBirthByDefault`. + +**2A.2 Хелперы `vfs`**: `Walk`, `RemoveTree`, `DirSize`, `SameFile`, `Within` (§2.2). ✅ done (commit 5132daa) +- Файлы: `internal/vfs/{walk.go,remove.go,size.go,same.go}`. +- Приёмка: `TestRemoveTreeSymlinkToDirKeepsTarget` (local) и тот же тест в conformance для SFTP (2B.5) — N-P0-3; + `TestDirSizeRootError`, `TestDirSizeCountsUnreadable` — N-P1-14; `TestSameFileSymlinkAlias` (`~/alias -> ~/real`) — + N-P0-6; `TestWithinViaSymlink`; `TestWalkDoesNotFollowLinks`; `TestRemoveTreeCancel`. + +**2A.3 `vfs/vfstest`**: conformance + FaultFS (§11.1, §11.3). ✅ done (commit 9d5b6bf) +- Файлы: `internal/vfs/vfstest/{conformance.go,faultfs.go}`; вызов в `localfs/conformance_test.go`. +- Приёмка: набор покрывает Lstat/Stat/ReadDir с симлинками, Create Excl, Rename обоих режимов, Remove (файл, ссылка, + пустой и непустой каталог → ошибка), Chmod/Chtimes, маппинг ошибок; `TestFaultFSBlocksAndReleases`. + +**2A.4 Корзина `localfs.Trash`** (freedesktop, topdir, URL-кодирование, O_EXCL, sudo → эффективный пользователь). ✅ done (commit 39e8264) +- Файлы: `internal/vfs/localfs/trash.go`. +- Приёмка: `TestTrashHome`, `TestTrashInfoURLEncoded` (пробел, кириллица), `TestTrashNameCollision`, + `TestTrashTopdir` (через подставной `statDev`, чтобы не требовать второй ФС) — N-P2-12, U-P2 MoveToTrash. + +### 2B. SSH: config, conn, pool, SFTPFS (L; 1 разработчик, лучше с сетевым опытом; параллельно 2A и 2C) + +**2B.1 `ssh/sshconfig`** (+ зависимость `github.com/kevinburke/ssh_config`, vendor). +- Файлы: `internal/ssh/sshconfig/{resolver.go,store.go}`; `store.go` — перенос `HostStore` (hosts.dat) с записью через + `atomicfile` (если 2C.1 ещё не смержен — временно локальная функция, заменить после). +- Приёмка: перенесённый `TestConfigNoHostName` (HostName = alias) и случаи `HostName=10.0.0.1`, `Host *` с `User` и + `IdentityFile`, `Include`, кавычки, несколько `IdentityFile`, `#` внутри значения — N-P1-5; `TestEndpointKeyIncludesUser` + — N-P2-3. + +**2B.2 `ssh/conn` Dialer** — §3.4 (dial), §3.5. +- Файлы: `internal/ssh/conn/{dial.go,hostkey.go,auth.go,prompter.go}`. +- Приёмка (стенд): `TestHandshakeTimeout` (прокси freeze сразу после TCP: ошибка за ≤ `HandshakeTimeout`+1 с) — + N-P1-3; `TestDialCancelClosesLateClient` (ctx отменён посреди handshake, после разморозки клиент закрыт, goroutine + не утекли); перенесённый `TestHostKeyAlgoMismatch` (known_hosts только с ed25519, сервер ed25519+ecdsa → успешное + подключение) — N-P1-4; `TestHostKeyChangedRejected`; `TestUnknownHostAsksPrompter` (AcceptAndSave пишет known_hosts, + Reject → ошибка) — N-P2-14; `TestAuthFallbackToAgentAfterIdentityRejected`, `TestKeyboardInteractiveUsesPrompter` — + N-P2-2; `TestAgentConnectionShared` (одно соединение с агентом на N подключений) — N-P2-1. + +**2B.3 `ssh/conn` Conn** — keepalive, состояния, reconnect, Exec, sftp-опции. +- Файлы: `internal/ssh/conn/{conn.go,keepalive.go,exec.go}`. +- Приёмка: перенесённый `TestFreezeHangs` превращается в `TestFreezeDetectedAsLost` (freeze → `State()==Lost` и + событие за ≤ interval×(miss+1)+timeout; висящий `ReadDir` возвращает `ErrConnLost`) — N-P1-2; + `TestReconnectAfterCut` (cut → Lost → `Reconnect` → `ReadDir` работает, `gen` вырос); `TestExecCancelKills` + (`sleep 60` отменяется за < 1 с), `TestExecOutputLimit` — N-P2-15, N-P1-7 (exec). + +**2B.4 `ssh/conn` Pool + Lease** — §3.2, §3.3. +- Файлы: `internal/ssh/conn/pool.go`. +- Приёмка: перенесённый `TestCloseRace` в форме `TestLeaseReleaseRace` (параллельные `ReadDir` и `Release`/`Acquire`/ + `Close` пула под `-race`) — N-P0-8; `TestAcquireSingleflight` (10 параллельных Acquire → 1 dial) — N-P2-8 (двойной + Enter); `TestIdleClose`; `TestMirrorLeaseSurvivesRelease` (две аренды, одна отпущена — вторая работает) — N-P1-12. + +**2B.5 `vfs/sftpfs`** — §2.4. +- Файлы: `internal/vfs/sftpfs/{sftpfs.go,errors.go,symlink.go}`; `conformance_test.go` на стенде. +- Приёмка: conformance (2A.3) на стенде зелёный, включая `RemoveTree` по симлинку на каталог; `TestVolumeByHostKey` + (два Endpoint с разными HostName на один сервер → равные `Volume()`) — N-P0-5; `TestCallCancelReturnsFast` (freeze, + ctx отменён → возврат < 100 мс); `TestUploadThroughputLatency` (4 МиБ при RTT 20 мс: upload ≤ 0,5 с) — N-P1-6; + интеграционный `TestSymlinkOrderOpenSSH` под тегом `integration`. + +### 2C. Конфиг, состояние, пути, логи (M; 1 разработчик; параллельно 2A и 2B) + +**2C.1 `paths` + `atomicfile`.** ✅ done (commit 1c57f92) +- Файлы: `internal/paths/paths.go`, `internal/atomicfile/atomicfile.go`. +- Приёмка: `TestConfigLookupIgnoresCwd` (в cwd лежит `vcom.toml` → не используется); `TestSudoWritePathsEffectiveUser` + (через подставной `geteuid`/`SUDO_USER`); `TestRunDirSweepDeadPID`; `TestAtomicWriteCrashLeavesOld` (fill возвращает + ошибку → старый файл цел, temp удалён). + +**2C.2 `config`: загрузка, предупреждения, SetKey.** ✅ done (commit 28fd86b) +- Файлы: `internal/config/{config.go,lookup.go,setkey.go}`. +- Приёмка: `TestSetKeyPreservesComments` (на копии реального `vcom.toml`: меняется только строка `theme`); + `TestSetKeyMissingSection`, `TestSetKeyNoFile` (создаётся XDG-файл), `TestSetKeyRefusesBrokenFile`; + `TestLoadUnknownKeysWarns`; `TestLoadBrokenConfigFallsBackToDefaults` (возвращает defaults + ошибку, не exit); + алиас `center_width_percent` → `preview_width_percent`; новые ключи §9.2 с дефолтами. + +**2C.3 `state` + перевод старого UI на новую запись.** ✅ done (commit 4ed81ef) +- Файлы: `internal/state/session.go`; правка `internal/config/session.go` (обёртки над `state`) и + `internal/ui/model.go::finalizeTheme` (вместо `config.Save` → `config.SetKey`). **Мержить после этапа 1.** +- Приёмка: `TestSessionAtomic`, `TestSessionMigratesFromOldPath`, `TestCursorMemoryCapped` (≤ 200, без cache-путей); + smoke старого UI: выбор темы не меняет комментарии в конфиге. + +**2C.4 `logx` + `main`.** ✅ done (commit 0f9314c) +- Файлы: `internal/logx/logx.go`, `cmd/vcom/main.go` (флаги `--log-level`, `--debug`, `VCOM_LOG`; лог в state-dir; + ротация; signal → `program.Send(tea.Quit())` для старого UI; teardown после `Run`). +- Приёмка: `TestRotateOver5MiB`, `TestLogFilePerms` (0600/0700), `TestRedactSecrets` (атрибуты `password`, + `passphrase`, `answers` не попадают в вывод). Старые `log.Printf` в `internal/ui` остаются (уйдут на этапе 7), но + пишут через slog-адаптер и на уровне debug. + +--- + +## Этап 3. Движок `internal/transfer` (L; 1–2 разработчика; после 2.0 и 2A; 3.7 — после 2B.5; параллельно 4 и 5) + +Все тесты этапа идут на LocalFS + FaultFS; 3.7 повторяет ключевые сценарии на стенде для local↔remote и +remote↔remote. + +### 3.1 Prepare (M) ✅ done (commit 76ae6c3) +- **Файлы:** `internal/transfer/{types.go,source.go,prepare.go}`. +- **Сделать:** §4.1, §4.2: `FSSource`, проверки (read-only цель, SameFile, Within), один обход, `ReadDir` целевых + каталогов, `Existing`, `Conflicts`, честные `TotalFiles/TotalBytes`, `Warnings` (спецфайлы, старые `.vcom-part-*`). +- **Приёмка:** перенесённый `TestCopyStatsBytes` → `TestPrepareCountsBytes` — N-P1-13; `TestPrepareRejectsSameFile` + (в т. ч. через симлинк-алиас каталога) — N-P0-6; `TestPrepareRejectsIntoItself`; `TestPrepareConflictsPerFile`; + `TestPrepareReadDirPerDirNotPerFile` (FaultFS считает вызовы: на 1000 файлов в 1 каталоге — 1 ReadDir цели) — + N-P2-4/5; `TestPrepareCancel`. + +### 3.2 WriteAtomic и копирование (M) ✅ done (commit 86c110f) +- **Файлы:** `internal/transfer/{atomic.go,execute.go,reader.go}`. +- **Сделать:** §4.3 для File/Dir/Symlink/Special, Preserve*, Fsync, ctx-reader с `Size()`, ошибки Close. +- **Приёмка:** перенесённые `TestLocalOverwriteFailureLosesDest` → `TestOverwriteFailureKeepsDest` (FaultFS: ошибка на + середине записи → старая цель цела, temp удалён) — N-P0-4; `TestCloseErrorIsItemError` — N-P2-6; + `TestLocalOverwriteDirDeletesExtra` → `TestDirMergeKeepsExtra` — N-P0-7; `TestLocalCopyReadOnlyDir` → + `TestCopyReadOnlyDir` — N-P1-17; `TestLocalMtime` + `TestPermsPreserved` — N-P1-9; `TestBrokenSymlinkCopiedAsLink`, + `TestSymlinkToDirCopiedAsLink`, `TestFollowLinksCycle` — N-P1-8; `TestFifoSkippedWithWarning`; `TestNoTempLeftovers` + (после любого теста в цели нет `.vcom-part-*`). + +### 3.3 Конфликты и ошибки (M) ✅ done (commit 88c6743; код — в 86c110f) +- **Файлы:** `internal/transfer/{conflict.go,errors.go}`. +- **Сделать:** политики Ask/Overwrite/Skip/OverwriteOlder/KeepBoth (`name (1).ext`), `TypeMismatch` без Overwrite, + ApplyToAll, `NoReplace` для «новых» + runtime-конфликт при `ErrExist`, `ErrorPolicy` с Retry/Skip/SkipAll/Abort. +- **Приёмка:** `TestConflictAskApplyToAll`, `TestConflictTypeMismatchNeverDeletesDir`, `TestKeepBothNaming`, + `TestTargetAppearedAfterPlanIsConflict`, `TestErrorRetryThenSuccess`, `TestErrorSkipAllContinues`, `TestReportCounts`. + +### 3.4 Отмена (S) ✅ done (commit 058616d; код — в 86c110f) +- **Файлы:** `internal/transfer/execute.go`, `reader.go`. +- **Приёмка:** перенесённый `TestCancelSingleFile` → `TestCancelMidFileReportsCancelled` (отмена на 150 мс: возврат + ≤ 200 мс, `Report.Cancelled`, temp удалён, старая цель цела) — N-P1-7; `TestCancelDuringPrepare`. + +### 3.5 Move (M) ✅ done (commit b3f9452) +- **Файлы:** `internal/transfer/move.go`. +- **Сделать:** §4.3 Move: same-conn rename верхнеуровневого элемента без конфликтов, EXDEV → copy+delete, поэлементное + удаление источника только после успешного копирования, `Remove` пустых каталогов. +- **Приёмка:** `TestMoveSameVolumeIsRename` (inode сохранился), `TestMoveSkippedItemStaysInSource`, + `TestMoveFailedItemStaysInSource`, `TestMoveDirWithSymlinkKeepsLink` — N-P1-8 (move), `TestMoveNeverFollowsSourceLinks` + — N-P0-3 (move), `TestMoveAffectedIncludesSource`. + +### 3.6 Server-side copy (S–M; опционально, можно отложить в этап 8) +- **Файлы:** `internal/transfer/serverside.go`. +- **Приёмка (стенд):** `TestServerSideCopyIntoTempThenRename`, `TestSameHostCpIntoExistingDir` (перенесённый: в цели + есть `proj/` → нет `proj/proj`, идёт обычное слияние) — N-P1-10; `TestServerSideCancelRemovesTemp`; + `TestNoExecFallsBackOnce` (сервер `NoExec` → один fallback без повторов). + +### 3.7 Remote-приёмка на стенде (M; после 2B.5) +- **Файлы:** `internal/transfer/remote_test.go`. +- **Приёмка:** перенесённые `TestOverwriteThenDrop` (cut посреди перезаписи → старый файл на сервере цел, обрубка нет) — + N-P0-4; `TestSameFileViaAliasTruncates` → `TestSameFileViaAliasRejected` (и при обходе проверки — файл не обрезан) — + N-P0-5; `TestUploadDirWithBrokenSymlink`, `TestDownloadDirWithBrokenSymlink` — N-P1-8; `TestPermsMtimeLost` → + `TestRemotePermsMtimePreserved` — N-P1-9; `TestRemoteToRemoteDifferentUsersNotSameConn` — N-P1-10; + `TestConnLostAsksRetry` (cut → `OnError` с `ErrConnLost` → Retry с reconnect → копирование завершается) — N-P1-2. + +--- + +## Этап 4. `internal/jobs` (M; параллельно 3 и 5) +- **Файлы:** `internal/jobs/{manager.go,handle.go,events.go}`. +- **Сделать:** §6: очередь с `maxParallel`, latest-wins прогресс, тикер 10 Гц, `Ask/Answer`, `holds` (Release в конце), + `safeGo` с recover, `Shutdown`. +- **Приёмка:** `TestProgressCoalesced` (100k `SetProgress` → ≤ 11 `ProgressTick` за секунду, копирование не тормозит: + джоба завершается за < 100 мс без читателя событий, кроме `notify`); `TestAskBlocksOnlyJob`; `TestCancelWhileWaiting`; + `TestPanicBecomesFailed`; `TestHoldsReleasedOnAllPaths`; `TestQueueRespectsMaxParallel`; `TestShutdownWaitsCleanup`. + Закрывает: прогресс без троттлинга и backpressure (U раздел 2), «Transfer is already running» (U раздел 3), хрупкий + re-arm канала (N «Потокобезопасность»). + +--- + +## Этап 5. Архивы, превью, картинки (три независимых потока; параллельно 3 и 4) + +### 5A. `internal/archive` + `vfs/archivefs` (L; после 2.0, 2A; Create/Unpack-тесты — после 3.2) +- **5A.1 Индекс и чтение:** ✅ done (commit af453aa) `internal/archive/{format.go,index.go,source.go}`. Приёмка: `TestIndexZip`, `TestIndexTarGz` + (с прогрессом и отменой), `TestZipSlipRejected`, `TestMemberLimit`, `TestSourceSinglePass` (FaultFS/счётчик: архив + читается один раз при выгрузке N членов). +- **5A.2 `vfs/archivefs`:** ✅ done (commit 2b1b9b0) `internal/vfs/archivefs/archivefs.go`. Приёмка: read-only conformance-подмножество; + `TestArchiveFSMutationsReadOnly` — U-P0-2; `TestNoTempDirOnMount` (в `os.TempDir()` ничего не появилось). +- **5A.3 Create:** ✅ done (commit b8cf3ae) `internal/archive/create.go`. Приёмка: перенесённый `TestUP01_ArchiveDoesNotDestroySource` + (data.tar → tar в тот же каталог: отказ/другое имя, источник цел) — U-P0-1; `TestArchiveIntoSourceDirRejected`; + `TestArchiveCancelRemovesPartial`; `TestArchiveCloseErrorReported` — N-P2-13; `TestArchiveNameTarGzToZip` — U-P2; + `TestArchiveToRemote` (стенд, после 2B.5) — N-P1-15; `TestArchiveSymlinksPreserved`. +- **5A.4 Unpack через transfer:** ✅ done (commit 2cfd411; код Unpack — в af453aa) Приёмка: `TestUnpackConflictAsks` (существующий файл → конфликт, не перезапись) — + U-P1-11; `TestUnpackDoesNotWriteThroughSymlink` (в цели `foo -> /elsewhere`, член `foo/x` → ссылка не пройдена); + `TestUnpackToRemote` (стенд) — N-P1-15. + +### 5B. `internal/preview` (M; после 2.0) ✅ done (commit 5d36b76) +- **Файлы:** `internal/preview/{build.go,text.go,highlight.go,dir.go,media.go,image.go,cache.go,tools.go}`; + `internal/theme/chroma.go` (маппинг для всех тем). +- **Приёмка:** `TestFifoNotRead` (FIFO → Kind=Special за < 50 мс) — U-P1-10; `TestToolTimeout` (подставной + `pdftotext`, который спит 10 с → результат с ошибкой за ≤ 3,5 с); `TestBuildCancelled`; `TestHighlightNoBackgroundSGR`; + `BenchmarkPreviewGo64K` (цель ≤ 40 мс; было 190); `TestEveryThemeHasChromaStyle` — U-P2; `TestRemoteImageSizeLimit` — + N-P1-16; `TestDirPreviewLimited`; `TestKindLabel` — U-P2. + +### 5C. `internal/imgview` (M; без зависимостей от других новых пакетов, кроме `preview.ImageRef`) +- **5C.1** ✅ done (commit 6c13b19) (+ зависимость `golang.org/x/image`, vendor) — `internal/imgview/{actor.go,synctty.go,kitty.go,ueberzug.go,scale.go}`. +- **Приёмка:** `TestSyncTTYNoInterleave` (параллельные кадры и kitty-блоки на `bytes.Buffer`-обёртке не перемешиваются); + `TestActorLatestWins` (100 `Apply` подряд → декодируется ≤ 2); `TestRejectHugeImage` (DecodeConfig > 50 Мпикс → + отказ без полного декода); `TestUeberzugStuckIsKilled` (подставной процесс, не читающий stdin → отключение за ≤ 300 мс, + `Apply` не блокируется); `BenchmarkKittyPayload6000x4000` (цель ≤ 150 мс; было 973) — U-P1-9. + +--- + +## Этап 6. Новый UI `internal/tui` (флаг `--ui=next`) + +### 6.1 Каркас (L; последовательно, 1–2 разработчика в тесном контакте; **блокирует** 6.2–6.6) +| # | Задача | Файлы | Приёмка | Баги | +|---|---|---|---|---| +| 6.1.1 | `keys`: ActionID, контексты, Registry, ЙЦУКЕН только для командных контекстов, chord-буфер, Help/Footer; `bindings_browse.go` с таблицей §8.1 | `internal/tui/keys/*` | `TestNoDuplicateKeysPerContext`, `TestLayoutTranslationCommandsOnly`, `TestTextContextPassesRunes` (`папка`), `TestChordYY`, `TestHelpGeneratedFromRegistry` | U-P1-5, U-P1-16 | +| 6.1.2 | `notify` + статус-строка + журнал `L` | `internal/tui/notify/*`, `internal/tui/status.go` | `TestNoteTTLByLevel`, `TestTimerClosesOnlyOwnNote`, `TestStatusLineShowsError` (через драйвер) | U-P1-1, костыль #13 | +| 6.1.3 | `modal`: Stack, Dialog (структурный), Input, List, скролл высоких модалок, мышь только в модалку | `internal/tui/modal/*` | `TestDialogButtonsAndHotkeys`, `TestModalScrollsOnSmallTerminal` (72×18), `TestMouseUnderModalIgnored` | костыли #10, #14 | +| 6.1.4 | `panel`: Mount-стек, entries, visible, курсор, метки, фильтр, история, cursor memory LRU, Reload с preserve, рендер с кэшами | `internal/tui/panel/*` | `TestFilterVisibleIndexAndMouse` (клик по 2-й видимой строке выбирает её) — U-P1-4; `TestFilterResetOnDirChange`; `TestMarksKeptOnTab`; `TestTargetsExcludeHiddenMarks`; `TestReloadKeepsCursorPerPane` и `TestDeletedItemCursorStaysAtIndex` — U-P1-7; `TestSymlinkDirNavigable` — U-P1-2; `BenchmarkRender20k` (≤ 2 мс) | U-P1-2, U-P1-4, U-P1-7 | +| 6.1.5 | `App`: Screen/Focus, переходы §7.2, `inputOwner`, Layout + hit-test, Tracker, reconcile эффектов (мышь), навигационная транзакция с async ReadDir, подъём к существующему родителю, тема (List с живым превью + `config.SetKey` в Cmd), help, quit-диалог, Deps для тестов | `internal/tui/{app.go,update.go,view.go,modes.go,layout.go,tracker.go,effects.go,deps.go,nav.go,theme_select.go,help.go,quit.go}` | `TestUpdateNeverBlocks` (FaultFS блокирует ReadDir: Update возвращается < 10 мс, Esc и `q` обрабатываются) — N-P1-1, U-P1-9; `TestStaleListingIgnored`, `TestStalePreviewDoesNotExitCaret` — U-P1-13; `TestNavErrorKeepsPanel` и `TestVanishedDirClimbsUp` — U-P1-8; `TestQClosesLayersThenConfirmsQuit` — U-P1-16; `TestPgDn` — U-P1-6; `TestInvariantsAfterEachStep`; `TestThemeSelectPreservesConfigComments` | N-P1-1, U-P1-6, U-P1-8, U-P1-13, U-P1-16 | +| 6.1.6 | `main`: `--ui=next` (по умолчанию старый UI), SyncTTY, pool/jobs/imgview в Deps, teardown | `cmd/vcom/main.go` | ручная проверка + `TestImportsGuard` (§7.13) в `internal/tui` | — | + +Заглушки регистрации фич (`registerOps`, `registerViewer`, `registerSSH`, `registerArchive`, `registerMisc`) создаются +в 6.1.5 пустыми, чтобы 6.2–6.6 не правили `app.go`. + +### 6.2 Файловые операции (L; параллельно 6.3–6.6) ✅ done (commit 280f388) +- **Файлы:** `internal/tui/{ops_transfer.go,ops_delete.go,ops_mkdir_rename.go,ops_dirsize.go,ops_jobs.go,invalidate.go}`, + `internal/tui/modal/{progress.go,conflict.go}`, `internal/tui/keys/bindings_ops.go`. +- **Сделать:** copy/move: Enabled (цель — `SourceDir`, не read-only), джоба Prepare → Dialog (объём, конфликты, + политика, предупреждение о скрытых метках) → Execute с Progress-модалкой, Conflict/Error через Ask, фон (`Esc`/`b`), + отмена с подтверждением (`c`); trash/permanent delete (§8.1, §8.4); mkdir/rename через FS панели с валидацией имени + (`/` → ошибка); Space → джоба dirsize, «≥ X (N недоступно)»; `B` — список джоб; `invalidate(Affected)`; quit при + активных джобах. +- **Приёмка (драйвер; local + стенд):** `TestNP01_RemoteRenameUsesRemoteFS` (локальный одноимённый файл не тронут) — + N-P0-1; `TestNP111_RemoteDeleteReloadsRemote` — N-P1-11; `TestCopyConflictDialogAndSkip`; `TestProgressCCAsksConfirm` + (`c` дважды не отменяет без `y`) — U-P1-16; `TestDeleteDefaultTrash`, `TestPermanentDeleteDefaultsToCancel`, + `TestRemoteDeleteNoTrashShowsPermanentDialog` — U-P0-4; `TestTwoJobsParallel`; `TestQuitWithJobsCancelsAndCleans` + (нет `.vcom-part-*`) — N-P2-11; `TestHostsListNotATarget` — N-P2-10; `TestRenameRejectsSlash` — U-P2; + `TestPassiveCursorKeptAfterCopy` — U-P1-7; `TestDirSizeShowsUnreadable` — N-P1-14. + +### 6.3 Вьюер, превью, картинки (L; параллельно) ✅ done +- **Файлы:** `internal/tui/viewer/*`, `internal/tui/{viewer_actions.go,preview_req.go,clipboard.go}`, + `internal/tui/keys/bindings_viewer.go`. +- **Сделать:** Info/View, debounce + Tracker для превью (§7.7), TextViewer (scroll/caret/visual/yank, по ячейкам, + только видимое окно, `W` перенос), `Ctrl+T` nativeSelect через эффекты, imgview через reconcile (§7.9), `y`/`yy` + в буфер (OSC52 + atotto). +- **Приёмка:** `TestUP03_CaretAsciiAndTrueColorNoPanic` — U-P0-3; `TestVisualReachableFromViewAndInfo` — U-P1-16 (`v`); + `TestCaretCJKColumns` — U-P2; `TestPreviewDebounceSingleFlight` (быстрые 50 `j` → ≤ 2 Build) — N-P1-16; + `TestOverlayHiddenUnderModal`, `TestViewIsPure` (View 1000 раз не вызывает Deps и не пишет в TTY); + `TestMouseRestoredAfterExternalProcess` — U-P1-3; `BenchmarkCaretMove64K` (≤ 1 мс; было 9,7). + +### 6.4 SSH (L; параллельно) +- **Файлы:** `internal/tui/{ssh_hosts.go,ssh_connect.go,ssh_prompts.go,ssh_badge.go,remote_edit.go}`, + `internal/tui/keys/bindings_ssh.go`. +- **Сделать:** `SourceHosts` (список из Resolver + свои), `s`/F12; connect-джоба, привязанная к панели, Prompter через + Ask (host key, пароль, keyboard-interactive, passphrase); add/delete host; бейдж и уведомление по `ConnStateChanged`, + reconnect по Enter/`Ctrl+R` в панели Lost; remote edit (§7.12) с проверкой конфликта; выход из хоста = Release аренды. +- **Приёмка (стенд):** `TestConnectMountsIntoOriginPane` (Tab во время подключения) — N-P2-8; `TestDoubleEnterOneConn`; + `TestAddHostCancelNoLeak` — N-P1-3; `TestConnLostBadgeAndReconnect` — N-P1-2; `TestNP02_RemoteEditUploadsBack` и + `TestRemoteEditConflictAsks` — N-P0-2/U-P1-12; `TestNP02_RemoteRunDisabled`; `TestQTypableInSSHForm` — U раздел 7; + `TestLeaveHostKeepsMirrorAlive` — N-P1-12. + +### 6.5 Архивы (M; параллельно; после 5A) ✅ done (commit b5bad66) +- **Файлы:** `internal/tui/{archive_mount.go,archive_create.go,archive_unpack.go}`, `internal/tui/keys/bindings_archive.go`. +- **Сделать:** Enter на архиве → джоба mount (индекс, прогресс, отмена) → `Mount{archivefs}`; remote-архив → + скачивание в cache → mount; `a` → List форматов → имя (Input с предложенным `archive.Name`) → `archive.Create` + джобой; `e`/F11 → Unpack через transfer в пассивную панель. +- **Приёмка:** `TestUP02_ArchivePaneReadOnlyActionsDisabled` — U-P0-2; `TestEnterArchiveNonBlocking` (большой tar.gz: + Update не ждёт) — U-P1-9; `TestUnpackToRemotePane` — N-P1-15; `TestArchiveSameDirDoesNotDestroySource` — U-P0-1; + `TestLeaveArchiveCursorOnArchive`. + +### 6.6 Прочее (M; параллельно) ✅ done (commit 066d349) +- **Файлы:** `internal/tui/{mirror.go,external.go,run_menu.go,sort_menu.go,yank_path.go,session.go,signals.go}`, + `internal/tui/keys/bindings_misc.go`. +- **Сделать:** mirror с Acquire (§7.8); Enter-диспетчер (§7.12): edit/open/Run-меню; xdg-open с `Wait`; `S` меню + сортировки; `.`; `y` путь; сессия (сохранение на выходе, по сигналу и раз в 30 с при изменениях, Cmd); signals → + quitMsg. +- **Приёмка:** `TestUP114_MirrorArchiveAndRemote` (mirror → закрыть в активной → пассивная живая) — U-P1-14, N-P1-12; + `TestEnterExecutableOpensRunMenu` — U-P1-3; `TestNoZombieAfterOpen` — U-P1-15; `TestSessionRestoresLocalForRemote`; + `TestSignalSavesSession`. + +### 6.7 Приёмочный набор и паритет (M; после 6.2–6.6) +- **Файлы:** `internal/tui/acceptance_test.go`, `internal/tui/fuzz_test.go`, `internal/tui/bench_test.go`. +- **Сделать:** перенести smoke 0.3 на новый UI (с учётом новых клавиш); fuzz-прогон 10k случайных действий из реестра + с проверкой инвариантов и отсутствия паники (seed в выводе); чек-лист паритета функций (две панели, Info/View, + F-клавиши + vim, SSH, архивы, темы, фильтр, история, caret/visual, mirror, корзина, сессия) — каждая строка ссылается на + тест. +- **Приёмка:** всё зелёное под `-race`; `BenchmarkView20k` ≤ 2 мс/кадр, `TestFrameAllocsCached` (гейт); ручной прогон + `--ui=next` в kitty, в другом терминале с ueberzugpp и в tmux без картинок. + +--- + +## Этап 7. Переключение и удаление старого (M; последовательно) +| # | Задача | Приёмка | +|---|---|---| +| 7.1 | Новый UI по умолчанию; флаг `--ui` удалить | smoke зелёный | +| 7.2 | Удалить `internal/ui`, `internal/fs`, `internal/fs/remote`, `internal/homedir`, `internal/config/session.go`-обёртки; убрать `theme.Next` и прочий мёртвый код из обоих отчётов (U раздел 6, N-P2-9) | `deadcode ./...` (golang.org/x/tools) не выдаёт символов из `internal/` (кроме тестовых хелперов), сборка и тесты зелёные | +| 7.3 | Пример `vcom.toml`: новые ключи, без мёртвых опций, с комментариями | `TestExampleConfigLoadsWithoutWarnings` | +| 7.4 | Документация: README (таблица клавиш §8, пути конфига §9.1, миграция с v0.2.x: изменённые клавиши F4/`g`/`h`/`l`/Delete), `docs/architecture.md` (по §1–§7), `docs/project-description.md` | ревью | +| 7.5 | Релиз v0.3.0: CHANGELOG, PKGBUILD/flake/deb/rpm версии | release workflow зелёный | + +--- + +## Этап 8. Опционально (после v0.3.0, задачи независимы) +- 8.1 ProxyJump (`ssh.Client.Dial` по цепочке; стенд: два сервера) — N-P1-5 (остаток). +- 8.2 Автообновление панелей: опрос mtime текущего каталога local-панелей раз в N с (`behavior.auto_refresh`). +- 8.3 Remote-корзина (`~/.local/share/Trash` на сервере через rename) — `Caps.Trash` для sftpfs. +- 8.4 Параллельный `vfs.Walk` для remote (упорядоченная выдача, 8 воркеров) — ускорение Prepare. +- 8.5 Server-side copy (если 3.6 отложена). +- 8.6 Оценка перехода на Bubble Tea v2 (затрагивает только `internal/tui`). + +--- + +## Сводка: какой этап какие баги закрывает + +| Этап | Баги | +|---|---| +| 1 (временно) | N-P0-1, N-P0-2, N-P0-3, N-P0-8 (частично), N-P1-15, U-P0-1, U-P0-2, U-P0-3, U-P0-4, U-P1-1, U-P1-5, U-P1-6, U-P1-16 (частично) | +| 2A | N-P0-3, N-P1-14 (данные), U-P1-2 (данные), N-P2-12 | +| 2B | N-P0-5 (Volume), N-P0-8, N-P1-2, N-P1-3, N-P1-4, N-P1-5, N-P1-6, N-P1-12 (пул), N-P2-1/2/3/14/15 | +| 2C | конфиг/сессия: атомарность, cwd-конфиг, комментарии; логи; U-P1-15 (частично) | +| 3 | N-P0-4, N-P0-5, N-P0-6, N-P0-7, N-P1-7, N-P1-8, N-P1-9, N-P1-10, N-P1-13, N-P1-17, N-P2-4/5/6 | +| 4 | N-P1-13 (троттлинг), backpressure прогресса, очередь джоб | +| 5A | U-P0-1, U-P0-2, U-P1-11, N-P1-15, N-P2-13 | +| 5B | U-P1-10, N-P1-16, U-P2 (chroma, kindLabel) | +| 5C | U-P1-9 (overlay), раздел «Image overlay» | +| 6.1 | N-P1-1, U-P1-1, U-P1-2, U-P1-4, U-P1-5, U-P1-6, U-P1-7, U-P1-8, U-P1-13, U-P1-16 | +| 6.2 | N-P0-1, N-P1-11, U-P0-4, N-P2-10, N-P2-11 | +| 6.3 | U-P0-3, N-P1-16, U-P2 (CJK, yankFlash) | +| 6.4 | N-P0-2, U-P1-12, N-P1-2 (UI), N-P1-3 (UI), N-P2-8 | +| 6.5 | U-P0-2, N-P1-15, U-P1-9 (архив) | +| 6.6 | U-P1-3, U-P1-14, N-P1-12, U-P1-15 | +| 7 | весь мёртвый код (U раздел 6, N-P2-9), мёртвые опции конфига | + +## Как распределить на 3 разработчиков (пример) +- **Разработчик A (ядро ФС):** 0.1–0.4 → 2.0 → 2A → 3 → 5A → 6.2 → 6.5. +- **Разработчик B (сеть):** этап 1 (параллельно 0, после 0.3) → 2B → 3.7 → 6.4. +- **Разработчик C (UI/инфраструктура):** 2C → 4 → 5B → 5C → 6.1 → 6.3 → 6.6. +- 6.7 и этап 7 — вместе, по завершении. Критический путь: 0 → 2.0 → 2A → 3 → 6.1 → 6.2 → 6.7 → 7. diff --git a/plans/rework/04-dev-log-B.md b/plans/rework/04-dev-log-B.md new file mode 100644 index 0000000..e23901d --- /dev/null +++ b/plans/rework/04-dev-log-B.md @@ -0,0 +1,225 @@ +# 04-B. Журнал разработчика B (сеть, `internal/ssh`): отклонения от плана + +Отдельный файл, чтобы не конфликтовать с `04-dev-log.md` при мерже. Ветка разработки — worktree от +`rework/stabilize`. + +## 2B.1 `ssh/sshconfig` + +- **Атомарная запись.** `internal/atomicfile` (2C.1) ещё нет, поэтому временно `internal/ssh/internal/atomicwrite` + (temp + fsync + rename + fsync каталога). Используется в `Store` и для known_hosts (2B.2). TODO: заменить на + `atomicfile.WriteFile` после мержа 2C.1 и удалить пакет. **Сделано** после 2B.5: `Store` и known_hosts пишут + через `internal/atomicfile.WriteFile` (заодно получили сохранение владельца под sudo и запись сквозь симлинк + на dotfile), временный пакет удалён. +- **kevinburke/ssh_config используется не напрямую по файлу.** Библиотека (v1.6.0) сама: (а) считает началом + комментария любой `#`, даже внутри значения и кавычек (`IdentityFile ~/.ssh/key#1` ломается — ровно N-P1-5); + (б) разрешает `Include` от `os/user.Current().HomeDir`, игнорируя `HOME` (ломает изоляцию тестов и sudo); + (в) падает на всём файле при `Match user/exec/canonical/...`; (г) сравнивает Host с учётом регистра. + Поэтому `flatten.go` склеивает конфиг и все `Include` в один текст: комментарии снимаются по правилам OpenSSH + (`#` в начале слова вне кавычек), оставшиеся `#` экранируются символом U+E000 и возвращаются после `Get`; + `Include` инлайнится (относительно `~/.ssh` из `Options.Home`, глубина ≤ 5), после вставки восстанавливается + объемлющий `Host`-контекст; `Match all` и `Match host a,b` → `Host`, остальные `Match` → блок, который + никогда не совпадает (+ `Warnings()`); шаблоны Host и alias приводятся к нижнему регистру. Библиотеке остаются + разбор строк, кавычки, `key=value` и сопоставление шаблонов (first match wins). +- **`NewResolver(Options)`** вместо `Resolver{}`: `Options{ConfigPath, Home, LocalUser, Store}` — чтобы `paths` + (2C) мог передать home вызвавшего пользователя под sudo, а тесты — временный каталог. Ошибка разбора не + фатальна: возвращается вместе с рабочим Resolver (знает только хосты из Store). +- **Store API:** `OpenStore(dir)`, `Hosts/Find/Put/Remove`; `Put` заменяет хост с тем же именем (раньше + `AddHost` дублировал). Формат hosts.dat совместим, **кроме поля password**: старый код писал сырой шифротекст + как JSON-строку, `json.Marshal` портил невалидный UTF-8 (→ U+FFFD), и сохранённые пароли после перезапуска + молча не расшифровывались. Теперь поле — base64 шифротекста; при чтении пробуются оба варианта. Повреждённый + `.hosts-key` больше не перезаписывается молча новым ключом (это делало hosts.dat нечитаемым навсегда) — ошибка. +- `Endpoint` дополнен `Addr()` и `Label()`; `ProxyJump` разбирается (`[user@]host[:port]`, хопы разрешаются через + тот же конфиг), но подключение через хопы — этап 8. `IdentityFile none` пропускается; токены `%h %d %u %r %%` + раскрываются в `HostName`/`IdentityFile`. + +## 2B.2 `ssh/conn` Dialer + +- **Dialer не экспортируется.** Внутренний `dialer` (один на Pool, т.е. на процесс: держит общее соединение с + агентом и принятые на сессию host keys) настраивается через `DialOptions{Prompter, HandshakeTimeout, Home, + KnownHostsFiles, KnownHostsWrite, AgentSocket, DefaultIdentityFiles, Warn}`; `PoolOptions` встраивает + `DialOptions` (2B.4). Снаружи соединение получают только через `Pool.Acquire`. +- **Дедлайн handshake на паузе, пока ждём Prompter** (host key, пароль, KI, passphrase): иначе пользователь, + думающий дольше 20 с, получал бы таймаут. После ответа таймер взводится заново на полный `HandshakeTimeout`. + `ConnectTimeout` из ssh_config ограничивает только TCP connect (как в OpenSSH). +- **SFTP:** `sftp.NewClient(sshClient, UseConcurrentWrites, UseConcurrentReads, MaxConcurrentRequestsPerFile(64))` + вместо `NewClientPipe` — те же опции, меньше кода; ожидание VERSION идёт под тем же дедлайном. +- **Порядок ключей:** явные `IdentityFile` (если ключ уже есть в агенте — подпись агентом) → остальные ключи агента → + `~/.ssh/id_{ed25519,ecdsa,rsa}` (последние два шага — только без `IdentitiesOnly`). В дизайне агент стоял первым; + явный ключ первым ближе к OpenSSH и не съедает `MaxAuthTries` сервера ключами агента. Все ключи — в одном + методе `publickey` (x/crypto пробует каждое имя метода один раз; два `PublicKeys` подряд — второй игнорируется). +- **Зашифрованный ключ:** если известна публичная половина (встроена в формат OpenSSH или лежит в `.pub`), + passphrase спрашивается только когда сервер принял ключ (lazy signer), до 3 попыток. Отмена в Prompter + прерывает аутентификацию целиком (так устроен x/crypto: ошибка подписи = ошибка auth). +- **Пароль/KI:** пароль из hosts.dat используется один раз (метод `password` или одиночный скрытый вопрос KI); + всё остальное — через Prompter как есть (2FA). Без Prompter и без пароля эти методы не предлагаются. +- **Host key.** Неизвестный ключ без Prompter → отказ (`ErrHostKeyRejected`), а не молчаливый TOFU. Ключ другого + типа, чем записанные, — «неизвестный» (`changed=false`, `known` заполнен). Изменившийся ключ того же типа → + Prompter с `changed=true`; Reject → `*HostKeyError` (unwrap → `ErrHostKeyChanged`); AcceptOnce/AcceptAndSave для + изменившегося ключа → доверие только на сессию (строку в known_hosts не переписываем, это `ssh-keygen -R`). + Ошибка — тип `*HostKeyError{Host, Identity, Known, Changed}` для UI. +- **sudo / known_hosts:** если файл (или каталог, если файла нет) принадлежит не эффективному uid, либо запись не + удалась, либо `KnownHostsWrite: "-"`, ключ доверяется только в памяти и вызывается `Warn`. Чтение по умолчанию + ещё и из `/etc/ssh/ssh_known_hosts`. +- Тест `TestKeyboardInteractiveUsesPrompter` использует свой мини-сервер в `helpers_test.go` (у `sshtest` нет KI); + `sshtest` не трогал, чтобы не выходить из своей зоны. + +## 2B.3 `ssh/conn` Conn + +- **`ErrConnLost`/`ErrClosed` живут в `conn`**, а не в `vfs`: `conn` не может импортировать `vfs` (его пишет + разработчик A, и `sftpfs → conn` — обратное направление). `sftpfs` (2B.5) маппит `conn.ErrConnLost` → + `vfs.ErrConnLost`. Для классификации ошибок SFTP есть `(*Conn).MapErr(err)`: `sftp.ErrSSHFxConnectionLost`, + `net.ErrClosed` → `ErrConnLost` всегда; `io.EOF`/`ErrUnexpectedEOF` — только если состояние уже не `Ready` + (EOF чтения файла — не обрыв). +- **`Conn.Close` не экспортирован** (`close()`), закрывает только Pool — по D3/§3.3 это гарантия на уровне API, а не + дисциплины. +- **Смерть обнаруживается двумя путями:** keepalive (`interval × (maxMiss+1) + timeout` в худшем случае) и + `ssh.Client.Wait()` (обрыв TCP/`CutAfter` → `Lost` сразу, без ожидания keepalive). +- **Watchdog операций** (§3.4) разделён: `Conn.Probe(ctx, timeout)` — внеочередной keepalive, нет ответа → `Lost`; + решение «вызов висит дольше 30 с» принимает `sftpfs.call` (2B.5). +- **`Reconnect` — одна попытка** на уровне `Conn` (backoff — в `Pool.Reconnect`, 2B.4); вызовы сериализуются, на + `Ready` — no-op. Новый host key при переподключении → ошибка `ErrIdentityChanged` (иначе `Volume()` = отпечаток + ключа перестал бы быть правдой). События: `Connecting` → `Ready`/`Lost`, и `Closed` при закрытии пулом. +- **Exec:** `Exec(ctx, argv, limit) ([]byte, int, error)` — аргументы экранируются (`conn.Quote`), ненулевой код → + `*ExitError{Code, Stderr(≤4 КиБ)}` вместе с кодом; превышение лимита убивает команду (`SIGKILL` + закрытие + сессии) и возвращает усечённый вывод с `ErrOutputLimit`. `Caps()` не содержит `Exec` (нужен round trip), вместо + этого `ExecSupported(ctx)` — проба `true`, кэшируется только определённый ответ. +- Тест-сервер `sshtest` не обрабатывает `signal`; отмена проверяется по клиенту (возврат < 1 с, соединение живо), + процесс `sleep` на стороне стенда добивается при остановке сервера. + +## 2B.4 `ssh/conn` Pool + Lease + +- **`NewPool(PoolOptions)`** вместо `NewPool(resolver, opts)`: `Acquire` получает уже разрешённый `Endpoint`, + резолвер пулу не нужен (UI вызывает `resolver.Resolve(alias)`, затем `pool.Acquire`). `PoolOptions` встраивает + `DialOptions` и добавляет `ReconnectBackoff []time.Duration` (по умолчанию 1,2,4,8 с между ≤ 5 попытками; в + тестах — миллисекунды). +- **`Lease.FS()` нет** — `conn` не может импортировать `vfs`/`sftpfs` (цикл `sftpfs → conn`). В 2B.5 будет + `sftpfs.New(lease)`. Вместо этого у Lease есть `Conn()` и сокращение `Client()`. +- **Singleflight с отменой:** dial идёт в контексте пула; каждый ждущий `Acquire` уходит по своему ctx; когда ушли + все — dial отменяется. Если dial всё же завершился без ждущих, соединение паркуется и закрывается через + `IdleClose` (не утекает). `Pool.Close` отменяет текущие dial и ждёт их goroutine. +- **`Acquire` на `Lost`-соединении** делает одну попытку `Reconnect` с ctx вызывающего (повторный Enter на хост + после сна ноутбука). Ошибки host key (`ErrHostKeyChanged/Rejected`, `ErrIdentityChanged`) прекращают backoff. +- `IdleClose < 0` — закрыть сразу после последнего `Release`. `Release` идемпотентен на уровне каждой аренды: + лишние вызовы не отбирают чужие ссылки. После `Pool.Close` аренды безопасны: `Client()` → `ErrClosed`, + `Acquire` → `ErrPoolClosed`. + +## 2B.5 `vfs/sftpfs` + +- **Конструктор `sftpfs.New(lease)`** забирает аренду; `(*FS).Release()` отдаёт её пулу (у `vfs.FS` нет Close). + Доступ к соединению — `Lease()`, `Conn()` (состояние, reconnect). Помимо `vfs.FS` реализован `vfs.Execer` + (`ErrUnsupported`, если сервер не даёт exec). +- **Порядок аргументов SYMLINK — без swap.** pkg/sftp-клиент сериализует пакет в порядке OpenSSH (target, link), и + pkg/sftp-сервер читает так же, поэтому `cl.Symlink(target, link)` верен для обоих; определять сервер по + `ServerVersion()` не нужно. Проверено интеграционным `TestSymlinkOrderOpenSSH` против настоящего + `/usr/sbin/sshd` (тег `integration`; sshd запускается от текущего пользователя на свободном порту, при + невозможности — skip). Под тем же тегом весь conformance-набор прогоняется на OpenSSH — зелёный. +- **`Caps.NoReplace` только для OpenSSH** (там SSH_FXP_RENAME = link+unlink, не перезаписывает). pkg/sftp-сервер + делает `rename(2)` и перезаписывает цель, поэтому `Rename(NoReplace)` всегда делает Lstat-проверку цели + (на OpenSSH она лишь даёт чистый `ErrExist`, атомарность обеспечивает сервер). Без posix-rename + `Rename(Replace)` при существующей цели тоже отдаёт `ErrExist` — transfer делает rename-в-сторону. +- **`ErrExist`:** SFTP v3 отвечает `SSH_FX_FAILURE`; для Create(Excl)/Mkdir/Rename/Symlink при FAILURE + проверяется Lstat цели (подсказка A). +- **RealPath:** REALPATH OpenSSH разрешает симлинки — используется он. REALPATH pkg/sftp-сервера только чистит + путь (причём `..` лексически, до симлинков), поэтому для не-OpenSSH путь разрешается на клиенте по компонентам + (Lstat/ReadLink, ≤ 40 ссылок). Это нужно `vfs.SameFile/Within` (N-P0-5/6) и conformance. +- **Ошибки:** `conn.ErrConnLost`/`conn.ErrClosed` → `fmt.Errorf("%w: %w", vfs.ErrConnLost, err)` (матчится и + `vfs`, и `conn`); `SSH_FX_OP_UNSUPPORTED` → `vfs.ErrUnsupported`; ENOENT/EACCES уже приходят как + `fs.ErrNotExist/ErrPermission`; `io.EOF` из `Read` не оборачивается. +- **Отмена и watchdog:** все метаданные идут через `call(ctx)`: отмена возвращает сразу, результат брошенного + вызова выбрасывается (файл, открытый брошенным `Open/Create`, закрывается). Через 30 с ожидания — + `Conn.Probe(5 с)`; мёртвое соединение → `Lost` → висящий вызов получает `ErrConnLost`. Операции над открытым + `File` ctx не принимают (§2.4/§4.3: отмену внутри файла делает transfer через ctx-reader и Close). +- **Throughput:** `File` реализует `ReadFrom`/`WriteTo` (делегирует pkg/sftp с concurrent writes/reads), поэтому + `io.Copy` из `*os.File` идёт параллельно: 4 МиБ при RTT 20 мс — upload ≈ 0,13 с, download ≈ 0,19 с (было ~2,6 с). +- `Create(CreateExcl)` применяет `perm` через fsetstat; `CreateTrunc` режим существующего файла не меняет. + `Mkdir` делает chmod, только если `perm != 0755` (умолчание сервера). + +## Этап 4 `internal/jobs` + +- **Без зависимостей:** пакет импортирует только stdlib (никакого Bubble Tea и `transfer`). `Result any` и + `Question.Payload any` — как в §6; transfer-джоба будет адаптером в UI. +- **Доставка событий:** один dispatcher-goroutine на менеджер, запускается при первом событии и завершается, когда + очередь событий пуста (нет вечной goroutine — `noLeak` без `Shutdown` не нужен). `notify` может блокироваться + (как `program.Send`): события копятся в срезе менеджера, джобы не ждут. Порядок событий сохраняется; + `Finished` — последнее событие джобы (тик собирается под тем же mutex, что и `Finished`). +- **Тикер 10 Гц** живёт, только пока есть активные джобы; в тик попадают только изменившиеся (dirty) снапшоты. + Переход Queued → Running и `SetBackground` тоже помечают снапшот dirty и уходят ближайшим тиком. +- **Сверх §6:** `Snapshot.Err` (причина Failed/Cancelled), событие `Unasked{Question}` (вопрос снят без ответа — + UI закрывает диалог), `Manager.Get(id)`, `Handle.ID()`, `State.Finished()`, `ErrShutdown`. Завершённые джобы + хранятся для списка `B`, не больше 100 последних. +- **Семантика итога:** `err == nil` → Done; `errors.Is(err, context.Canceled)` → Cancelled; иначе Failed; паника + в fn → Failed с текстом паники (стек — в slog). Паника в `notify` или в `Release` логируется и не ломает + менеджер. `Ask` с отменённым собственным ctx снимает вопрос, а джоба продолжает работу; отмена джобы снимает все + её вопросы. `Answer` на неизвестный/снятый вопрос — no-op. +- **Shutdown(ctx):** отменяет очередь (holds освобождаются сразу) и работающие джобы, ждёт их возврата и доставки + всех событий; по дедлайну возвращает `ctx.Err()`. `Start` после Shutdown сразу даёт Cancelled с `ErrShutdown` + (holds освобождаются). + +## 3.7 Remote-приёмка transfer на стенде + +- Файл `internal/transfer/remote_test.go` (код `transfer` не менялся). Стенд: `sshtest` + `conn.Pool` с быстрым + keepalive (100 мс × 2 + 100 мс) + `sftpfs`. Тесты: `TestOverwriteThenDrop` (N-P0-4), `TestSameFileViaAliasRejected` + (N-P0-5; и с обходом Prepare файл цел), `TestUploadDirWithBrokenSymlink`/`TestDownloadDirWithBrokenSymlink` + (N-P1-8), `TestRemotePermsMtimePreserved` (N-P1-9), `TestRemoteToRemoteDifferentUsersNotSameConn` (N-P1-10/N-P2-3: + слияние без `proj/proj`, move = copy+delete), `TestConnLostAsksRetry` (N-P1-2: cut → `OnError(ErrConnLost)` → + `Pool.Reconnect` → Retry → файл цел), плюс `TestRemoteCancelMidFile` (возврат ≈ 0,2 с, temp удалён) и + `TestRemoteFreezeMidFileThenCancel`. +- **Заморозка + отмена:** `File.Close` в pkg/sftp ждёт тот же mutex, что и идущий `ReadFrom`, а запрос CLOSE по + замороженному каналу не получает ответа, поэтому `AfterFunc(Close)` сам по себе висящую запись не освобождает. + Execute возвращается, когда пул признаёт соединение мёртвым (keepalive / `ssh.Client.Wait`): в тесте ≈ 0,2–0,4 с, + с умолчаниями (15 с × 2 + 10 с) — до ~40 с. Цель при этом цела. Ускорять можно только агрессивнее keepalive + во время передачи — оставил как есть (поведение по §3.4). +- **Находка для A (не исправлял, код transfer не мой):** после обрыва temp-файл `.vcom-part-*` остаётся на сервере + (удалить по мёртвому соединению нельзя), а `Prepare` предупреждает об остатках только в каталогах, которые он + листает (слияние каталогов); для одиночного файла в корне `ToDir` (≤ 4 корня → Lstat вместо ReadDir) остаток не + замечается. Варианты: после Retry с новым поколением соединения удалять temp прошлой попытки (executor знает его + имя), или листать `ToDir` при наличии `partPrefix`-подозрений. Тест `TestOverwriteThenDrop` это только логирует. + +## Латентность отмены на замёрзшей сети (после 3.7) + +- **Сторожок отмены в `sftpfs.File`:** файл запоминает ctx, с которым его открыли (`Open/Create`), и регистрирует + `context.AfterFunc`. При отмене ждём `cancelGrace` (300 мс); если операция файла (Read/Write/ReadFrom/WriteTo/ + Close/Stat/Sync) всё ещё идёт — `Conn.Probe(cancelProbeTimeout = 1,5 с)`. Нет ответа на keepalive → `Lost`, + транспорт закрыт, pkg/sftp сразу возвращает ошибку (и `ReadFrom`, и висящий `Close`). Живая, но медленная сеть + отвечает на probe — ничего не рвём (`TestRemoteSlowLinkCancelKeepsConn`, RTT 300 мс). Регистрация снимается в + `Close`. Это не требует изменений в `transfer`: движок и так открывает файлы с ctx джобы. +- Итог при дефолтном keepalive (15 с × 2 + 10 с): freeze посреди файла → cancel → возврат ≈ 1,8 с (upload и + download; было до ~40 с). Тесты: `TestRemoteFreezeCancelDefaultKeepalive` (transfer, ≤ 3 с, старая цель цела), + `TestFileCancelReleasesStuckRead`, `TestFileCancelLiveLinkUntouched` (sftpfs). +- **Компромисс:** на очень медленном канале с большой очередью неотправленных данных ответ на keepalive может + прийти позже 1,5 с, и соединение будет признано потерянным после отмены (только после отмены — без отмены + сторожок не работает). Последствие — reconnect при следующем действии, данные не страдают. Значения — переменные + пакета, их легко поднять. + +## 6.1 Каркас нового UI `internal/tui` + +- **Пакеты:** `tui` (App), `tui/keys`, `tui/notify`, `tui/modal`, `tui/panel`, плюс два вспомогательных сверх плана: + `tui/style` (все lipgloss-стили строятся один раз на тему, `Gen` входит в ключи кэшей — §7.10) и `tui/geom` + (`Rect` — общий для layout, рендера и hit-test). `tui/viewer` в 6.1 — минимальная модель (Kind/Focus/Gen, + прокрутка, построчный caret/visual), чтобы машина состояний и тесты 6.1 работали; 6.3 заменяет рендер. +- **Контексты keys** сверх §7.4: `CtxModalConflict`, `CtxModalPrompt` (под 6.2/6.4; Prompt — текстовый). Клавиша + Shift+F8 — это `f20` (так её шлёт xterm; у Bubble Tea v1 нет имени `shift+f8`), Shift+Delete в v1 не различается — + остаётся `X`. Горячие клавиши кнопок Dialog матчатся самим Dialog (в т. ч. в ЙЦУКЕН через `keys.Translate`) и + имеют приоритет над `q` = отмена, поэтому «q q» в диалоге выхода выходит. +- **Modal API:** `Key(action, rawKey)` + `Mouse(msg, relX, relY, w, h, styles)` + `View`, без `ID()` — id выдаёт + `Stack.Push`, `onClose func(Outcome) tea.Cmd` (замыкание на `*App` выполняется синхронно в Update, не в Cmd). +- **Уведомления:** `Center` не считает время сам: `Push` → App планирует `tea.Tick(TTL, noteExpiredMsg{id})` → + `Expire(id)` скрывает только свою заметку; Error дополнительно ждёт нажатия (`KeyPressed`). +- **Panel:** история хранит снимки со стеком mount-ов, но без отдельного `Acquire` на каждый снимок: при выходе из + mount-а (архив/хост) снимки, ссылающиеся на него, выбрасываются, и mount освобождается, когда его не держит ни + текущее место, ни история (вперёд в закрытый архив не вернуться — проще и без утечек). Mirror (`MirrorOf`) + делает `Acquire` у каждого mount-а. Размеры каталогов (`sizes`) и бейдж соединения — поля для 6.2/6.4. +- **Точки расширения App** (чтобы 6.2–6.6 не трогали `app.go`): `register(actionTable)` и + `registerHooks(*App)` в `register_*.go`; `a.handle(fn)` для своих сообщений; `a.onJob(fn)` для событий + jobs; `a.openFile` — Enter на не-каталоге (6.5 архивы, 6.6 edit/run/open); `a.invalidate(locs)` после операций; + `a.openModal`, `a.notify`, `a.navigate`, `a.req` (Tracker, `ReqFeature` + `Extra` для своих запросов). Действие + без обработчика показывает «…: not available yet». +- **Превью по умолчанию** (`Deps.Preview`, до 5B/6.3): голова текстового файла через `vfs.FS.Open`, иначе метаданные. +- **Imports guard** проверяет не-тестовые файлы (`_test.go` пропускаются — тестам нужны `os`/`localfs` для стенда); + allowlist `deps.go`, `external.go`. Дополнительно `TestNoRawKeyMatching`: вне `keys/` нет `x.String() == "…"` и + `key.Matches` (§7.4). +- **main:** `--ui=next` (по умолчанию `old`). Pool (keepalive/таймаут из `[ssh]`), jobs (`max_parallel_jobs`, + notify → `program.Send(tui.JobEvent(e))` через atomic-указатель на программу), Resolver + Store в `Deps`; + teardown после `Run`: `jobs.Shutdown(3 с)`, `pool.Close()`. SyncTTY и imgview — после 5C (их пакетов ещё нет). + Сессия нового UI — 6.6. Ручной прогон в pty в этой среде невозможен (нет терминала, отвечающего на запрос цвета + фона lipgloss); проверено драйвером. diff --git a/plans/rework/04-dev-log.md b/plans/rework/04-dev-log.md new file mode 100644 index 0000000..2a4ed95 --- /dev/null +++ b/plans/rework/04-dev-log.md @@ -0,0 +1,394 @@ +# 04. Журнал разработчика: отклонения от плана + +Короткие записи о местах, где план (`03-tasks.md`) пришлось уточнить или поменять. + +## Этап 0 + +- **0.1 `sshtest`.** Сверх API из §11.2 добавлены: `Options.AuthorizedKeys` (pubkey-auth для будущих тестов + `ssh/conn`), `Server.ClientConfig/Dial/DropConnections/Port`, `Proxy.Sent/Close/Port`, `WriteRandom`. + `Options.Chroot` реализован как рабочий каталог SFTP (`sftp.WithServerWorkingDirectory`) и cwd для exec: + относительные пути разрешаются внутри, но абсолютные выходят наружу — это не граница безопасности (настоящий + chroot для `pkg/sftp` потребовал бы своих request-handlers; для тестов не нужен). `CutAfter(n)` считает + n байт client→server **от момента вызова**, срабатывает один раз и рвёт все текущие соединения; новые + соединения после обрыва принимаются (нужно для тестов reconnect). Задержка `SetDelay` — односторонняя, в обе + стороны (RTT ≈ 2·d). +- **0.4 CI.** `gofmt -l .` из плана задел бы `vendor/` (там 10 неотформатированных файлов сторонних модулей), + поэтому проверяются только наши файлы (`git ls-files '*.go' | grep -v ^vendor/` + неотслеживаемые). + Три файла (`config/session.go`, `fs/ops.go`, `ui/model.go`) были неотформатированы — отформатированы в коммите + 0.4. В `Makefile` стоит `.NOTPARALLEL`, потому что `vendor-check` перезаписывает `vendor/`, а `make -j` + (у разработчика `make` — алиас на `make -j24`) запускал сборку параллельно с этим. `release.yml` вызывает + `ci.yml` через `workflow_call` вместо копии шагов. + +## Этап 1 + +- **1.1.** Кроме строки статуса: локальный `vfs.MakeDir` теперь падает на существующем имени (`os.Mkdir` для + последнего компонента). Иначе приёмочный сценарий «F7 с существующим именем → ошибка» невозможен: `MkdirAll` + молча «успевал». Строка фильтра занимает тот же слот, что и статус, — раньше она добавляла строку сверх высоты + терминала. Уровень сообщения (ошибка/предупреждение) определяется по словам в тексте: статус — свободная строка в + ~200 местах, протаскивать уровень везде в хотфиксе не стоит (в новом UI будет `notify` с уровнем, §7.6). +- **1.2.** Для теста N-P0-2 введён хук `startProcess` (подставной opener для `xdg-open`); `ExecProcess` (редактор, + запуск) ловит teadriver (`Execs()`), не запуская. Дополнительно заблокированы mkdir в списке хостов `ssh://` и + copy/move *из* списка хостов (та же причина, что N-P2-10). +- **1.7.** Помимо проверки «архив = источник / внутри источника» `CreateArchive` пишет во временный файл рядом с + целью и делает rename только при успехе: частичный архив при ошибке/отмене не остаётся, старый архив при неудаче + не портится (из «как исправлять» U-P0-1). Правка в одном месте (`CreateArchive`), функции форматов не тронуты. +- **1.8.** Вместо `atomic.Pointer` поля `sshConn`/`sftpCli` сделаны неизменяемыми после `Connect`: `Close` под + mutex только выставляет `atomic.Bool closed` и закрывает клиентов (pkg/sftp и x/crypto/ssh после Close + возвращают ошибки, а не паникуют). Это даёт ту же гарантию (нет записи полей → нет гонки, нет nil-разыменования) + меньшей правкой. Счётчик пользователей: `Connect` возвращает клиента с 1 пользователем (панель), `Acquire` — + mirror и remote copy/delete джобы, `Release` вместо `Close` в `goParent`, mirror, `exitSSHMode`; последний + `Release` закрывает. Превью и dir-size по-прежнему без ссылки — после закрытия они получают ошибку, не панику. +- **1.9.** Подготовлен релиз: `CHANGELOG.md` (создан), версия v0.2.8 в `model.go`, README, PKGBUILD и + `flake.nix` (там была устаревшая 0.2.6). Тег не ставился и ничего не пушилось — по правилам работы это делает + мейнтейнер (`git tag v0.2.8` на нужном коммите после мержа). + +## Разработчик A, этап 2 + +- **2.0 контракт `vfs`.** Интерфейс ровно по §2.1, без изменений сигнатур. Уточнения (аддитивные): + `ErrNotExist/ErrExist/ErrPermission` — это `fs.ErrNotExist/ErrExist/ErrPermission`, `ErrUnsupported` — + `errors.ErrUnsupported`, `ErrCancelled` — `context.Canceled`: `*os.PathError` от локального диска совпадает без + обёрток, и реализациям достаточно вернуть/обернуть эти значения. Добавлены `vfs.PosixPaths`/`vfs.NativePaths` + (реализации `PathOps`), `vfs.IsWithin(ops, child, parent)` (лексическая проверка, без симлинков), `SkipDir/SkipAll` + (= `fs.SkipDir/SkipAll`), `Kind.String`, `Location.String`. `ReadOnly(fs)` кроме мутаций скрывает `Trash`/`Exec`, + пропускает `BirthTime`, а `File` из `Open` отказывает в `Write` с `ErrReadOnly`. `Lstat` для симлинка заполняет + `Target`/`LinkErr` так же, как `ReadDir` (в дизайне это сказано только про `ReadDir`; conformance это проверяет). +- **Подсказка для 2B.5 (SFTPFS).** Conformance требует `ErrExist` для `Create(CreateExcl)`, `Mkdir` и + `Rename(NoReplace)` на существующей цели и `ErrNotExist` для отсутствующих путей. SFTP v3 отвечает на EEXIST + `SSH_FX_FAILURE`, поэтому в sftpfs нужен маппинг «FAILURE → Lstat цели → ErrExist». Подтест `RenameReplace` + пропускается при `!Caps.AtomicReplace`, `Chmod`/`Chtimes`/симлинковые — при отсутствии соответствующих `Caps`. + `Chtimes` проверяется с точностью до секунды. Read-only FS (`archivefs`) `vfstest.Run` пока пропускает целиком: + нужен вариант с готовой фикстурой, добавить в 5A. +- **2A.1.** Сверх списка файлов — `birth_other.go` (сборка не под Linux). Для `TestReadDirNoBirthByDefault` statx + вызывается через переменную-хук `statx`. `Chmod`/`Chtimes` идут по ссылкам (как `os.Chmod`); движок не применяет их + к симлинкам. +- **2A.2.** `SameFile` для local+local определяет «local» по `Kind()==KindLocal` у обеих FS и зовёт `os.Stat` + (dev+inode, ловит и hardlink/bind-mount); отсутствующий путь — `false, nil`. `Within` разрешает ещё не существующий + `child` по ближайшему существующему предку (нужно для «куда пишем»). `DirSize`: `Bytes` — сумма lstat-размеров всех + не-каталогов (симлинк считается своим размером), `Dirs` — без корня. `RemoveTree` останавливается на первой ошибке. +- **2A.3.** `FaultFS.Hook` — сигнатура §11.3. Добавлены готовые хуки `FailNth(op, n, err)` и `Gate` + (`Hook(ops...)`, канал `Entered`, `Release`) для «ReadDir висит» в UI-тестах. `FaultFS` реализует `Trasher` + (форвард или `ErrUnsupported`) и `BirthTimer`. Conformance прогоняется и на `FaultFS{localfs}` с пустым хуком. +- **2A.4.** Старый `internal/fs.MoveToTrash` теперь делегирует в `localfs.Trash` (старым пакетам разрешено + импортировать новые) — N-P2-12 закрыт и в текущем UI. Имя при коллизии — `name.2`, `name.3`…; осиротевший файл в + `files/` без `.trashinfo` тоже занимает имя. Корзина в корне тома требует, чтобы `.Trash` был настоящим каталогом + со sticky-битом; симлинк игнорируется. Каталог home-корзины пока вычисляется локально в `trash.go` + (эффективный пользователь); после 2C.1 — через `paths`. +- **2C.1 `paths`.** API: `ConfigFile(explicit) (path, found, err)`, `DefaultConfigFile`, `StrayCwdConfig`, + `OldSessionFile`, `StateDir`, `CacheDir`, `DataHome`, `ReadHome`/`WriteHome`, `SudoUser`, `EnsureDir`, + `CreateRunDir`/`SweepRunDirs`/`RemoveRunDir`. Под sudo (euid 0 и `SUDO_USER` ≠ root) унаследованные + `XDG_STATE/CACHE/DATA_HOME` для записи игнорируются (их оставляет `sudo -E`, и они указывают в `~user`), берётся + home эффективного uid. Новый конфиг под sudo создаётся у эффективного пользователя; при чтении после XDG/`~user` + проверяется и он. Тест-хуки — package-level `sys` (getenv/geteuid/getpid/lookup/alive), а не параметры функций. + `localfs.Trash` берёт home-корзину из `paths.DataHome`. +- **2C.1 `atomicfile`.** Сверх §9.2: `Write(path, perm, fill)` (нужен для теста «fill вернул ошибку»), запись + **сквозь симлинк** (конфиг из dotfiles не превращается в обычный файл), сохранение прав существующего файла и — под + root — его владельца (иначе rename под sudo оставлял бы root-файл в `~user`, например при выборе темы). + fsync каталога best-effort (на некоторых ФС не поддерживается). +- **2C.2 `config`.** Сигнатура `Load(explicit) (Config, LoadInfo, error)`; `LoadInfo{Path, Found, Warnings}`; есть + `Parse(data)` для тестов. Невалидное значение не ломает загрузку: заменяется умолчанием с предупреждением (в плане + — только про битый TOML; иначе одна опечатка в `pane_gap` выбрасывала весь конфиг). `SetKey` возвращает путь + (`(string, error)`): старому UI он нужен для `configPath` после создания XDG-файла; принимает + string/bool/int/float; сохраняет стиль кавычек (`'...'`), хвостовой комментарий и CRLF; многострочные строки, + массивы и inline-таблицы в редактируемом значении отклоняет. `show_title_bar` удалён из схемы (предупреждение), + а `app_title` **оставлен** в схеме с предупреждением «deprecated»: старый UI ещё рисует его в заголовке, уйдёт на + этапе 7. `auto_refresh*` — известные устаревшие ключи (предупреждение без «unknown»). Пример `vcom.toml` в репо + переписан с комментариями и новыми секциями `[transfer]`, `[ssh]`; README обновлён (порядок поиска, логи). + Старый UI: ошибка конфига показывается в статус-строке (`Model.WithStatus`), неизвестная тема больше не роняет + старт (откат на тему по умолчанию). Новые ключи §9.2 старым UI пока не читаются. +- **2C.3.** `config.Save` удалён (его единственный пользователь — тема — теперь `config.SetKey`). + `config.SessionState/PaneSession` — алиасы типов `state.Session/PaneSession`. Лимит `cursor_memory`: в карте нет + порядка использования, поэтому при > 200 сохраняются сначала записи на пути текущей панели (предки и потомки), + затем остальные по алфавиту; выбрасываются пути в cache-dir и во временных `vcom-archive-*`/`vcom-remote-*`. + Под sudo старый `session.toml` после миграции не удаляется (он в `~user`). Smoke-тесты старого UI: + `TestSmokeThemeSelectKeepsConfigComments`, `TestSmokeSessionInStateDir`. +- **2C.4.** SIGINT/SIGTERM Bubble Tea обрабатывает сам; `main` добавляет SIGHUP (+SIGTERM) → `program.Send(tea.Quit())`. + Teardown после `Run` вызывает новый идемпотентный `ui.Model.Shutdown()` (сохранение сессии, архивные mount-ы, + overlay, temp-картинка; клавиша `q` теперь зовёт его же), затем удаляет run-dir. Run-dir создаётся уже сейчас + (со сборкой мёртвых `run-*`), хотя старый UI им ещё не пользуется — его временные файлы останутся в `os.TempDir()` + до этапа 6/7. Старые `log.Printf` идут через адаптер (`logx.RedirectStdLog`) на уровне debug; на уровне по + умолчанию (warn) не пишутся вовсе. Redaction — по имени атрибута (`password`, `passphrase`, `answers`, `answer`, + `secret`, `token`, без учёта регистра); свободный текст старых `log.Printf` не фильтруется (они только на debug). + +## Разработчик C, QA-фиксы v0.2.8 + +Точечные фиксы по `05-qa-v0.2.8.md` в старом коде (`internal/ui`, `internal/fs`, `internal/fs/remote`). С каждого +исправленного бага снят `t.Skip("BUG QA-n")`; дополнительные тесты — `internal/ui/qa_fixes_test.go`, +`internal/fs/qa_fixes_test.go`, `internal/fs/remote/qa_fixes_test.go`, `internal/fs/remote/knownhosts_test.go`. + +- **QA-11 (known_hosts).** `knownhosts.New` принимает только файлы и падает целиком на первой плохой строке. + Решение (`internal/fs/remote/knownhosts.go`): содержимое пишется во временный файл, при ошибке разбора номер строки + берётся из сообщения `knownhosts: :: …`, строка заменяется на `#`, повтор (не больше числа строк). Так + отбрасывается ровно то, что не принимает сам парсер x/crypto (неизвестный алгоритм, битый хэш, пустой шаблон), + а не наша приблизительная проверка. Каждая пропущенная строка — `log.Printf("[SSH] …:N: skipping known_hosts line")` + (лог vcom в `/tmp/vcom-logs`). Исходный `known_hosts` не меняется, TOFU дописывает в него как раньше. + Безопасность: если хост записан *только* строками, которые мы пропустили (например, только `ssh-mldsa44-ed25519`), + TOFU не принимает другой ключ молча — отказ с объяснением (шаблоны хостов пропущенных строк проверяются через + второй db с ключом-заглушкой). `@revoked`/`@cert-authority` с неизвестным ключом просто пропускаются. + **HostKeyAlgorithms:** в старом клиенте не задавался, и x/crypto по умолчанию предпочитает ECDSA: хост, записанный + только ed25519-ключом (типично), выглядел бы «REMOTE HOST IDENTIFICATION HAS CHANGED» сразу после этого фикса + (тест `TestKnownHostsPrefersRecordedAlgorithm` без этой части падает именно так). Теперь, как в OpenSSH, первыми + предлагаются алгоритмы ключей, уже записанных для хоста, затем остальные из фиксированного списка поддерживаемых + x/crypto (ed25519, ecdsa-256/384/521, rsa-sha2-512/256, ssh-rsa). Тип пропущенной строки туда попасть не может: + список берётся из ключей, которые x/crypto распарсил. При наличии `@cert-authority` в файле список не задаётся + (CA-ключи нельзя отличить от ключей хоста в `KeyError.Want`) — поведение как раньше. +- **QA-1 (корзина на другом разделе).** Сначала сделал `$topdir/.Trash-$uid` в `MoveToTrash`, но по указанию + координатора откатил до коммита: корзину целиком переписал разработчик A (`internal/vfs/localfs.Trash`, на неё + делегирует `internal/fs.MoveToTrash`), правка внутренностей мешала бы мержу. **`internal/fs/ops.go` не изменён.** + Оставлена UI-часть: если задача удаления в корзину получила ошибку на каком-то элементе, в том же потоке + открывается подтверждение «Cannot move to trash. Delete permanently?» с причиной и числом оставшихся элементов + (не попавший в корзину и все следующие; уже перемещённые не трогаются). Enter/y — безвозвратно, Esc/n — файлы + остаются. Срабатывает на любую ошибку корзины, не только EXDEV: при сломанной корзине тоже лучше предложить + явный выбор, чем молча отказать; удаление без явного подтверждения невозможно. Почему не copy в домашнюю корзину: + долго и рискованно для больших каталогов (частичная копия при ошибке/отмене), а `$topdir`-корзина — задача новой + реализации. `TestQATrashCrossDevice` остаётся со Skip до мержа `localfs.Trash`. +- **QA-5, QA-8** не трогал — закрываются новой корзиной разработчика A; в CHANGELOG записаны в Known issues + для старого кода (уберутся при мерже). Skip в их тестах оставлены. +- **QA-3.** В режиме фильтра печатные клавиши (`KeyRunes`, пробел) всегда идут в строку; навигация — только + стрелками/PgUp/PgDn. +- **QA-4.** В SSH-форме `?` вводится в поле; справку открывает F1; `?` закрывает уже открытую справку (поля в этот + момент скрыты). Подсказка формы — «F1 for help». +- **QA-10.** Новый `SSHClient.MkdirNew`: `Lstat` цели → `ErrExist`, иначе `MkdirAll(parent)` + `Mkdir`. + `MkdirAll` не менял (им пользуются копирование и др.). +- **QA-9.** `path.Clean` в начале `RemoveRecursive`. +- **QA-6, QA-7.** Временный архив — `.vcom-tmp-` (короткое имя фиксированной длины; префикс оставлен, на + него завязаны проверки «не осталось temp-файлов»). Права: при замене — права старого архива, для нового — + `0666 &^ umask` (umask читается из `/proc/self/status`, не через `syscall.Umask`, который на мгновение меняет его + всему процессу; fallback 022). Пока архив пишется, temp остаётся 0600. +- **QA-2.** Выбран запрет: `p` в архив-панели — «Mirror is not supported inside an archive», пассивная панель не + меняется. Read-only-зеркало потребовало бы делить archive mount между панелями (кто чистит temp при выходе) — не + для хотфикса. Проверка QA-теста дополнена: принимается и отказ, и read-only. +- `sshtest.IsolatedHome` теперь задаёт и `XDG_DATA_HOME`, чтобы ни один тест не мог дойти до настоящей корзины. + +## Разработчик A, этап 3 + +- **Объём.** Сделаны 3.1–3.5. 3.6 (server-side copy) отложена по решению координатора; 3.7 (стенд) ждёт sftpfs + (2B.5). Код политик конфликтов/ошибок и отмены вошёл в коммит 3.2 (без них `Execute` не собрать), коммиты 3.3 и 3.4 + добавляют их приёмочные тесты. +- **Имена констант.** В §4.1 `ConflictPolicy` и `ErrorPolicy` обе содержат `Ask`, а `Skip`/`Abort` встречаются в трёх + перечислениях — в одном пакете Go это не скомпилируется. Итог: `ConflictPolicy` = `Ask, Overwrite, Skip, + OverwriteOlder, KeepBoth`; `ErrorPolicy` = `ErrorAsk, ErrorSkipAll, ErrorAbort`; `ResolveAction` = + `ResolveOverwrite/ResolveSkip/ResolveKeepBoth/ResolveAbort`; ответ на ошибку `ErrorAction` = `ErrorRetry, ErrorSkip, + ErrorSkipRest, ErrorStop`. Добавлен `DefaultOptions()` (Preserve* = true; нулевое значение `Options` их выключает). +- **Item.** Сверх §4.1: `Src` (путь в FS источника — нужен для move/rename и Open), `Warning` (источник помечает + деградацию: петля симлинков, битая ссылка при FollowLinks), `ScanErr` (каталог не прочитался при Prepare — элемент + падает в Execute по политике ошибок, Retry для него = Skip). +- **Source.** Кроме `Walk/Stream` — опциональные `Opener` (`Open(ctx, Item)`; FSSource реализует) и `FSBacked` + (`FS()`, `Roots()`). Execute с `Opener` открывает файл заново на каждую попытку, поэтому Retry после ошибки чтения + работает; для чисто потоковых источников (будущий `archive.Source`) повторное чтение невозможно — Retry вернёт ошибку + «источник нельзя прочитать дважды». Move требует `FSBacked`. `Request.Opts.Symlinks` имеет приоритет над аргументом + `FSSource(..., sym)`; для Move всегда `CopyLinks` (move не ходит по ссылкам). Файлы `.vcom-part-*` в источнике не + копируются. +- **Prepare.** До 4 корней — `Lstat` каждого в цели, больше — один `ReadDir(ToDir)`. Цель-симлинк на каталог для + исходного каталога — `TypeMismatch` (слияние через ссылку писало бы в чужое место). +- **WriteAtomic.** Порядок: write → `Sync` (если нужно) → `Close` → `Chmod` → `Chtimes` → `Rename` (в §4.3 Sync стоит + после Close, что невозможно на `File`). Temp создаётся `0600`, итоговые права ставятся перед rename; `Perm=0` → 0644. + Без `Caps.AtomicReplace` замена идёт через `dst → .vcom-old-*`, `tmp → dst`, удаление old, откат при сбое (проверено + обёрткой, запрещающей `Replace`). Имя temp укорачивается под NAME_MAX. `context.AfterFunc` закрывает файл при отмене + (снимает висящую сетевую запись) — локально этот путь не проверить, проверка в 3.7. Внутри движка запись и commit + разделены (`writeTemp`/`commit`), чтобы runtime-конфликт при `ErrExist` решался без повторного чтения источника. +- **Прогресс.** Троттлинг сделан и в transfer: `Hooks.ProgressInterval` (по умолчанию 50 мс), принудительный вызов в + начале и в конце каждой фазы. jobs по-прежнему может коалесить до 10 Гц. `BytesDone` считает обработанные байты + (скопированные плюс пропущенные или упавшие), поэтому к концу равен `BytesTotal` из Prepare. +- **Report.** Добавлено `Warnings`. `Done/Skipped` считают файлы и ссылки (Skipped — ещё спецфайлы и содержимое + пропущенных каталогов), каталоги в `Done` не входят; `Failed` — любой упавший элемент. `Bytes` — байты завершённых + файлов, включая перенесённые через rename. +- **Права.** `PreserveMode=false` → 0644 для файлов и 0755 для каталогов (а не umask). Существующему каталогу цели при + `PreserveMode` выставляется режим источника (как в §4.3). +- **Move.** Сверх §4.3: при `SameConn` файлы, сливаемые в уже существующий каталог, тоже переносятся через `Rename` + (NoReplace, или Replace при Overwrite, если он атомарен); любой отказ (EXDEV и т. п.) ведёт к копированию. Перед + удалением источника сверяется число прочитанных байт с `Item.Size`. Ошибка удаления файла-источника идёт по политике + ошибок (`Op="remove"`); непустой каталог-источник, который должен был опустеть, попадает в `Report.Errors` без + вопроса. При отмене и Abort каталоги источника не удаляются. +- **Остатки temp после обрыва (находка B в 3.7, коммит edf196a).** Если запись упала и temp-файл не удалось удалить + (соединение мертво), executor запоминает его имя и удаляет снова при Retry (обычно пул переподключился внутри + `OnError`) и в конце `Execute`. Что так и не удалилось — в `Report.Warnings`. Prepare теперь **всегда** листает + `ToDir` одним `ReadDir` (раньше при ≤ 4 корнях — `Lstat` каждого), поэтому остатки `.vcom-part-*` рядом с одиночным + файлом тоже попадают в `Plan.Warnings`. Цена — один листинг `ToDir` на операцию. `TestOverwriteThenDrop` теперь + строгий (temp назван в отчёте, следующий Prepare его сообщает), добавлены `TestOverwriteThenDropRetryLeavesNoTemp` + (стенд) и `TestRetryRemovesTempOfFailedAttempt` (локально). + +## Разработчик A, этап 5 + +- **5A.1 archive.** `Index{Format, Entries, TotalBytes, Rejected}`, `Entry{Path, Mode, Size, ModTime, Link, + Implicit}`. Сверх §5.2: `BuildIndexLimits` и `Limits{MaxMembers, MaxBytes}` (лимит размера объявленных данных; + в дизайне его только «показывают» — здесь можно ещё и отказать), `IndexFile(ctx, fsys, path, progress)`, + `DetectFormat`, `Unpack(...)` (Prepare+Execute). Отбрасываются не только `..`/абсолютные имена, но и члены **под + симлинком или файлом того же архива** (в любом порядке членов) — иначе при распаковке запись прошла бы сквозь + только что созданную ссылку. Недостающие родительские каталоги синтезируются (`Implicit`). Дубликаты имён в tar — + побеждает последний (как у tar). Hard link в tar индексируется как спецфайл и при распаковке пропускается. + `GODEBUG=zipinsecurepath/tarinsecurepath=0` не ломают индекс (небезопасные имена отбрасываются сами). +- **Порядок в `archive.Source.Stream`.** Каталоги, ссылки и спецфайлы отдаются первыми (из индекса), затем содержимое + файлов — в порядке архива за одно открытие; поэтому executor не встречает файл раньше его каталога. Архивный + источник — чисто потоковый (без `Opener`), Retry после ошибки чтения члена невозможен (см. этап 3). +- **5A.2 archivefs.** `Mount(ctx, outer, path, progress)`, `New(outer, path, idx)`, `Index()/ArchivePath()/Outer()`. + Ссылки разрешаются внутри архива; абсолютные и выходящие за корень архива считаются битыми. `Open` члена: zip — + напрямую, tar/tgz — последовательный проход (`archive.OpenMember`); `ReadAt` назад переоткрывает член. Внешний файл + не держится открытым (нет `Close` у FS). Добавлен `vfstest.RunReadOnly(t, fsys, root)` + фикстура + `vfstest.ReadOnlyFixture` (закрыт пункт из этапа 2: read-only conformance); прогоняется на zip/tar/tar.gz и на + `vfs.ReadOnly(localfs)`. +- **5A.3 Create.** Сигнатура §5.1. Существующий архив — `Hooks.Resolve` (Overwrite / KeepBoth → `name (1).tar.gz` / + Skip / Abort); без `Resolve` — отказ `ErrExist`. Публичный `archive.FreeName` для UI. Ошибка открытия источника идёт + через `OnError` (Retry/Skip/Stop), ошибка **посреди** файла прерывает весь архив (заголовок tar уже обещал размер). + Файл, изменивший размер во время архивации, — ошибка. Записывается с `Fsync`. Тесты на стенде (`TestArchiveToRemote`, + `TestUnpackToRemote`) — в `internal/archive/remote_test.go` через `sshtest` + `sftpfs`. +- **5B preview.** + - **Подсветка окна.** Главная стоимость — лексер chroma (regexp2): ~130 мс на 64 КиБ Go, а форматтер ничтожен. + Поэтому добавлен `Request.HighlightLines` (по умолчанию 400): подсвечиваются первые N строк, остальное — plain + (`Result.Highlighted`). Итог `BenchmarkPreviewGo64K` ≈ 20 мс (было 190). Вьюер (6.3) может запросить больше строк + фоном. Мягкий гейт `TestPreviewGo64KFast` (≤ 400 мс с учётом `-race`). + - **SGR.** Форматтер пишет truecolor `38;2;r;g;b` (+bold/italic/underline). Деградацию до 256/16 цветов для + Ascii-профилей должен делать UI (6.x). + - **Иконки.** `Request.Icons` из §5.4 не сделан: рендер иконок — дело UI, `Result.Dir` отдаёт `vfs.FileInfo`. + - **Утилиты.** Только для local FS. Для remote PDF/медиа показывается пояснение (скачивать их ради превью дизайн не + просил). Запуск в своей группе процессов с kill всей группы и `WaitDelay`, иначе `sh` с дочерним `sleep` + держит stdout и `Wait` висит. + - **Кэши.** `ImageCache` (LRU по размеру, 200 МиБ, переживает перезапуск, недокачанные `.tmp-*` удаляет на старте) и + `Cache` результатов (32, ключ включает тему и лимиты; ошибки не кэшируются). + - **Метка вида.** `KindLabel`: directory/symlink/fifo/socket/device/расширение/`file`. + - **Темы.** `theme.ChromaStyle` для всех 19 тем (`internal/theme/chroma.go`). Старый `fs.chromaStyleName` не тронут + (старый код). +- **5C.1 imgview.** + - **Зависимость.** `golang.org/x/image` взят **v0.39.0**, а не последний: v0.40+ тянет x/text v0.37+ и x/sys v0.49, + что задело бы весь `vendor/`. В `go.mod` одна новая строка; `go mod tidy` хотел ещё сделать прямыми + `kevinburke/ssh_config` и `termenv` — не стал (не моя зона, на vendor-check не влияет). + - **API.** `Start(Options) *Actor` вместо `Start(tty, b)`: опции — ячейка в пикселях (иначе спрашивается у TTY + через TIOCGWINSZ), `TmpDir` для kitty `t=t`, `Tmux`, команда ueberzugpp, `OnEvent`. Добавлены `Detect(setting, + getenv)` и `Actor.Backend()`. + - **Устаревшая работа.** Декодирование нельзя прервать посреди, поэтому актор после декода проверяет, не пришло ли + новое состояние, и отбрасывает результат. + - **Kitty.** Сырой RGBA (`f=32`, без PNG-кодирования) кусками по 4096 base64, или через файл (`t=t`). + - **ueberzugpp.** Свой `os.Pipe` с `SetWriteDeadline(200 мс)` вместо отдельного writer-а. + - **Бенчмарк.** `BenchmarkKittyPayload6000x4000` ≈ 200 мс (цель ≤ 150, было 973). ~180 мс из них — декодер JPEG + stdlib на 24 Мпикс; масштаб + упаковка ≈ 10 мс (`BenchmarkKittyPayloadDecoded6000x4000`). Быстрее только со + сторонним декодером или DCT-даунскейлом — не делал. Работа идёт в горутине актора, UI не ждёт. + - **Тест «застрявший ueberzugpp».** Проверяет отключение за ≤ 3 с от первого `Apply` (сначала нужно заполнить буфер + канала длинными путями), каждый `Apply` — < 5 мс, процесс-помощник убит. Сам дедлайн записи — 200 мс. +- **Чужие изменения в рабочем дереве.** Во время 5C в основном дереве появились незакоммиченные правки + `.gitignore`, `cmd/vcom/main.go`, `cmd/vcom/qa_signal_test.go` (не мои, похоже, параллельный мерж QA). Я их не + трогал и в свои коммиты не включал. + +## Разработчик A, QA v0.2.8 RC2 (QA-13…QA-19) + +- **QA-13.** `atomicfile.Write` проверяет `access(W_OK)` у существующей цели и возвращает EACCES, как обычная запись. + Это касается всех пользователей atomicfile: конфига, сессии, hosts.dat, known_hosts. Root проходит проверку, как и + при обычной записи. +- **QA-14.** `SetKey` правит секцию, заданную в корне: точечными ключами (`ui.theme = …`; недостающий ключ + добавляется той же формой после последнего `ui.*`) или однострочной inline-таблицей (`ui = { … }`; недостающий ключ + дописывается внутрь). Многострочная inline-таблица (в TOML 1.0 она невалидна) и вложенные значения внутри + inline-таблицы — отказ без изменения файла. +- **QA-15.** Исправлено с двух сторон: + - `main` передаёт UI путь `info.Path`, если `-config`/`$VCOM_CONFIG` заданы, даже когда файла ещё нет; + - `paths.DefaultConfigFile` возвращает `$VCOM_CONFIG`, если он задан. + Тестовый помощник тестировщика `newModelLikeMain` по-прежнему копирует старую логику main («только если файл + найден»). Для `$VCOM_CONFIG` тест проходит за счёт второго исправления. Случай `-config` в UI-тестах не + воспроизводится (флаг есть только в main) — помощник стоит обновить. +- **QA-19.** Тема: `finalizeTheme` сам пишет итоговый статус, селектор его не перетирает. Сообщение о битом конфиге в + main начинается с «Config error:», поэтому статус-строка (уровень определяется по словам) красит его как ошибку. +- **QA-16.** `applySession` применяет сессию, которую вернул `state.Load`, даже вместе с ошибкой миграции; ошибка — + в статус («Session error: …»). +- **QA-17.** Задача корзины не останавливается на первом отказе: остальные элементы уходят в корзину, а предложение + безвозвратного удаления касается только отказавших. Безвозвратное удаление по-прежнему останавливается на первой + ошибке. +- **QA-18.** Сделано (дёшево): mirror в панель внутри архива (локальная и remote-ветка) снимает её archive-mount-ы и + удаляет их temp-каталоги. В Known issues не понадобилось. + +## Разработчик A, этап 6 + +- **Правки в общих файлах (минимум).** + - `app.go`: одно поле `ops *opsState` (состояние джоб UI: модалки прогресса и вопросов). + - `panel`: поле `Entry.SizeLabel` и метод `SetSizeLabel` — размер каталога в колонке размера; живёт до следующего + листинга. + - `app_test.go` (тест каркаса): «не реализованное действие» теперь проверяется на `S` (меню сортировки), потому + что F5 реализован. +- **Джобы в UI (`ops_jobs.go`).** + - `startJob/startJobOpts`: прогресс-модалку открывает сам UI сразу при старте, `SetBackground` синхронизирован с + её закрытием/открытием. + - Вопросы джобы — через `Handle.Ask` с payload-типами `askPlan`, `askConflict`, `askItemError`, `askConfirm`. UI + открывает Dialog и отвечает `Manager.Answer`. `Unasked` закрывает модалку вопроса. Чужие payload (будущие + SSH-промпты 6.4) игнорируются. + - `Finished` вызывает `onFinish` джобы, по умолчанию — сводку `transfer.Report` + `invalidate(Affected)`. + - Мой хук `onJob` делает `len(jobHooks) > 0`, поэтому запасной `reportJob` каркаса для чужих джоб больше не + срабатывает. Джобам 6.4 нужен свой хук (или общий default) — сказать B. +- **Copy/move.** Одна джоба: Prepare → вопрос с планом → Execute. + - В диалоге плана есть выбор политики при конфликтах: спросить / перезаписать все / пропустить существующие / + перезаписать более старые. Политика по умолчанию — из `transfer.on_conflict`. + - Прогресс-модалка: `b`/`Esc`/`Enter` — в фон; `c` открывает подтверждение поверх неё (по умолчанию «Continue»), + поэтому `c c` не отменяет. + - Джоба держит ссылки на mount-ы обеих панелей (`Mount.Acquire`), чтобы выход из хоста не рвал передачу. +- **Удаление.** + - Корзина: диалог только при `confirm_delete`, по умолчанию «Move to trash». Отказы корзины (QA-17) собираются, и + для них одних предлагается безвозвратное удаление. + - Безвозвратное удаление: кнопка `d`, по умолчанию «Cancel». Ошибки идут через Retry/Skip/Skip all/Abort. + - На FS без корзины (SSH) F8 сразу открывает диалог безвозвратного удаления с пояснением. +- **Mkdir/rename.** Обычные `tea.Cmd` (не джобы) через FS панели. Имя проверяется: пустое, `/`, `.`, `..` — ошибка; + вложенный mkdir `a/b` тоже отказ. После операции активная панель перечитывается с курсором на новом имени, другая — + `reload` (её курсор сохраняется). +- **Размер каталога** считается джобой в фоне, без модалки. Результат — метка в колонке размера (`≥` при недоступных + подкаталогах) и уведомление «≥ X (N unreadable)». +- **Сверх плана.** Список джоб `B` (Enter возвращает выполняющуюся джобу на передний план). +- **Не сделано в 6.2.** Отдельный файл `invalidate.go` не понадобился: `a.invalidate` уже есть в каркасе (`nav.go`). +- **Тесты на стенде.** `TestNP01_RemoteRenameUsesRemoteFS`, `TestNP111_RemoteDeleteReloadsRemote`, + `TestCopyToRemotePane`, `TestUnpackToRemotePane` — в `internal/tui/{ops_remote_test.go,archive_test.go}`. + Remote-панель монтируется напрямую через `panel.NewMount(sftpfs…)` (UI подключения — это 6.4). +- **6.5 архивы.** + - **Remote-архив не скачивается в cache.** Он индексируется и читается через `archivefs` прямо поверх удалённой FS: + это работает, но каждое открытие члена tar.gz — поток по сети. Скачивание в cache можно добавить, когда понадобится. + - **Куда пишется архив.** `a` создаёт архив в каталоге **активной** панели (рядом с источниками). Внутри архива `a` + недоступно. + - **`e`/F11 внутри архива** работает как копирование отмеченных членов в другую панель (через FSSource над + archivefs). + - **Цепочка `openFile`.** Enter на архиве перехватывается обёрткой: предыдущий обработчик вызывается для остальных + файлов. 6.6 (edit/run/open) должна так же оборачивать уже установленный `openFile`, а не заменять его. +- **6.6.** + - **Правки в общих файлах.** + - `app.go`: поле `misc *miscState` и вызов `a.miscInit()` в `Init` (тикер сохранения сессии). + - `deps.go`: поля `Exec` (запуск foreground-программ, в тестах синхронно), `Opener`, `RunDir`, `Getenv`, + `Clipboard`, `Session`, `SaveSession`. `DefaultDeps` загружает сессию (`state.Load`) и берёт из неё стартовые + каталоги, если они существуют. + - `panel/session.go` (новый файл в пакете B): `LocalPlace`, `MemoryOf`, `SeedMemory`. + - `main`: `startNext(…, runDir)`; SIGHUP для нового UI шлёт `tui.Signal()`; teardown зовёт `(*tui.App).Shutdown()` + (сохранение сессии, идемпотентно). + - Тест каркаса `TestNavigationHistoryAndParent` теперь проверяет «нет обработчика» через `dispatch` неизвестного + `ActionID`: все клавиши каркаса уже реализованы. + - **Enter на файле.** Мой обработчик оборачивает `openFile` из 6.5: архивы отдаются ему, остальное — + `openRegular`: + - исполняемый файл (только при `Caps.Exec`, т. е. local) → меню Run / Edit / View / Cancel; + - иначе голова файла читается в Cmd: текст → редактор, не-текст → xdg-open; + - в архиве (read-only) текст тоже уходит в xdg-open через локальную копию. + - **Run.** `sh -c '"$0"; …; read _'` в каталоге панели, с паузой «Press Enter» и кодом выхода. + - **Remote edit** (по поручению координатора, хотя в плане он в 6.4; файл `external_edit.go`, без пересечения с + будущим `remote_edit.go` B): + 1. джоба скачивает файл в `RunDir/edit-/`, запоминая size, mtime, режим и sha256; + 2. запускается редактор; + 3. джоба загрузки: копия не изменилась — ничего не пишется; изменилась — `Stat` сервера; если size/mtime + другие — диалог «Overwrite / Save a copy beside (по умолчанию) / Keep local copy»; + 4. запись через `transfer.WriteAtomic` с режимом исходного файла. Копия рядом получает имя `archive.FreeName` → + `name (1).ext`. Временный каталог удаляется после успешной загрузки или если правок не было. + - **Open.** Для удалённых и архивных файлов — сначала скачивание в run-dir, плюс уведомление «changes are not + synced back». + - **Mirror.** Через `panel.MirrorOf` (каждый mount — своя ссылка через `Acquire`) для local, archive и remote. + Перечитывание источника — в Cmd с тикетом. Ссылка mount-а остаётся, пока он в истории панели (дизайн 6.1), поэтому + тест проверяет «≥ 1 ссылки у зеркальной панели», а не точный счётчик. + - **Сортировка (S)** сохраняется в конфиг через `SetKey` (`browser.sort.by`/`reverse`, `browser.dirs_first`). + - **Буфер обмена (y):** atotto, при неудаче — OSC 52 в stderr (как в старом UI). + - **Сессия.** Без изменений в формате `state`. Remote/archive-панель сохраняется как локальный каталог, из + которого в неё вошли (`LocalPlace`), с фокусом на имени архива. Сохраняется раз в 30 с при изменениях (Cmd), по + `tui.Signal` (Cmd, затем выход) и в `Shutdown`. + +- **6.3 viewer/preview/imgview.** + - `DefaultDeps` подключает настоящий `preview.Cache`/`Build`, внешние утилиты и `ImageCache` (200 МиБ). + `preview.Request` получает полный `Location` файла, лимиты, тему и видимость скрытых файлов; старый + небольшой `PreviewFunc` оставлен для изолированных UI-тестов. В `viewer.Content` передаются и подсвеченные, + и plain-строки: caret/visual/yank не копируют ANSI. + - TextViewer хранит caret и visual в графемах, переводит их в terminal cells и рендерит только видимое окно. + Реализованы горизонтальная прокрутка, `w/b/e/0/^/$`, полстраницы, `W`, yank строки/выделения. Wrap использует + фактические сегменты `ansi.Hardwrap`, а не `ceil(width)`: CJK и resize не уводят caret за viewport. + Добавлены регрессии для CJK, границ графем, wrapped jump/scroll, word motions между строками, Ascii/TrueColor. + - Preview при смене выделения отменяет предыдущий запрос уже в начале debounce; результат дополнительно сверяется + с `previewFor`. Закрытие View отменяет и запрос, и debounce. + - `imgview.Actor` подключён к reconcile через `Deps.Image`. У `Desired` есть монотонный `Seq`: команды Bubble Tea + могут выполняться в другом порядке, но устаревший Apply не покажет картинку поверх модалки или после закрытия. + `main` использует общий `SyncTTY`, останавливает actor в teardown и ставит в очередь события backend, возникшие + до запуска event loop. + - Приёмочные тесты из плана добавлены: debounce 50 движений → один Build, overlay под модалкой, чистый View, + Visual из Info/View, восстановление мыши, CJK и Ascii/TrueColor. `BenchmarkCaretMove64K` — около 22 мкс. diff --git a/plans/rework/05-qa-v0.2.8.md b/plans/rework/05-qa-v0.2.8.md new file mode 100644 index 0000000..8a8b6e0 --- /dev/null +++ b/plans/rework/05-qa-v0.2.8.md @@ -0,0 +1,328 @@ +# 05. QA: проверка v0.2.8 перед релизом + +Ветка: `rework/stabilize` @ `945ae80` (этапы 0 и 1). Проверял независимо от тестов разработчика: читал диф +`main..HEAD` по `internal/fs`, `internal/fs/remote`, `internal/ui`, пытался сломать каждый фикс через граничные случаи +и соседние пути, прогнал основные сценарии через `teadriver` и `sshtest`. Код продукта не менял. + +Новые тесты (только тесты): +- `internal/fs/qa_archive_trash_test.go` — архивация (все форматы, отмена, права, длинные имена, симлинк-источник), + корзина (имена, коллизии, `.trashinfo`, XDG, другой раздел), `MakeDir`. +- `internal/fs/remote/qa_remote_test.go` — `RemoveRecursive` на всех видах симлинков, `Close` во время передач, + конкурентные `Acquire/Release`. +- `internal/ui/qa_hotfix_test.go` — ввод текста во всех полях (кириллица, q/n/y/j/k/?), q/Esc во всех слоях, архив + через UI во всех форматах + перезапись, mirror из архива, caret на всех профилях, строка статуса, корзина из UI. +- `internal/ui/qa_regression_test.go` — регрессии: F5/F6 с перезаписью и без, F7, сортировка, скрытые, PgUp/PgDn, + history, mirror, info, view, тема; remote: листинг, copy local↔remote (файл и каталог), delete remote + (файл/каталог/симлинк на каталог), запрет локальных действий в SSH-панели, фоновая передача + выход с хоста, + mirror + фоновое удаление + выход из обеих панелей. + +Всего добавлено 45 тестов (с подтестами — больше 70 случаев); 12 из них — `t.Skip("BUG QA-n: …")` на реальные баги. + +## Итог прогонов + +| Команда | Результат | +|---|---| +| `make ci` (gofmt, vet, vendor-check, build, `go test -race -count=1`) | зелёный | +| `go test -race -count=3 ./...` | зелёный (до и после добавления QA-тестов) | +| `go test -race -count=3 -cpu=1,2 ./...` | зелёный | +| `go test -race -count=10` на чувствительных ко времени тестах (`QARemote*`, `NP112`, `NP0*`, `sshtest`, `fs/remote`) | зелёный | + +**Флейков не обнаружено.** DATA RACE и паник нет, в том числе в `TestQACloseDuringTransfers` (3 параллельных `Close` +во время upload/download/exec/remove) и в UI-сценариях с mirror и фоновой джобой. + +## Заявленные фиксы: результат проверки + +| Баг | Что проверено сверх тестов разработчика | Вердикт | +|---|---|---| +| N-P0-1 rename в SSH | F2 и `r` в SSH-панели; панель списка хостов | закрыт | +| N-P0-2 Enter/edit/open в SSH | Enter на `.conf`, `.zip`, исполняемом файле; F11/`e`, F4/`a` на remote; ни одного `ExecProcess`/xdg-open, локальный файл не изменён | закрыт | +| N-P0-3 удаление remote-симлинка | симлинки битый, на файл, относительный, на `..`; каталог с вложенными симлинками на внешний каталог и файл; через UI (F8 на `link`) | закрыт; для пути со слешем на конце см. QA-9 (P2, из UI недостижимо) | +| N-P1-15 archive/unpack с SSH | обе стороны: активная remote и пассивная remote | закрыт | +| N-P2-10 запись в `ssh://` | F5/F6/F4 в список хостов; F7 в списке хостов | закрыт | +| N-P0-8 гонка Close (часть) | `Close` ×3 параллельно с upload/download/`RemoveRecursive`/`ExecWithProgress`/`MkdirAll` под `-race` | закрыт | +| N-P1-12 mirror (часть) | 50 параллельных `Acquire/Release`; двойной `Release` не паникует; фоновая копия remote→local с задержкой в прокси, затем выход с хоста: клиент жив до конца джобы, файл скопирован полностью, после джобы клиент закрыт; mirror + фоновое удаление + выход из обеих панелей: удаление завершено, клиент закрыт | закрыт | +| U-P0-1 архив уничтожает источник | `report.zip`→zip и `data.tar`→tar в тот же каталог; `data.tar`→tar.gz и `data.gz`→tar.gz (разрешено, источник цел); содержимое zip/tar/tar.gz корректно (кириллица в именах); отмена для всех трёх форматов сохраняет старый архив без temp-файлов; повторная архивация с подтверждением для всех форматов; источник-симлинк на каталог, архив внутри цели — архив себя не содержит | закрыт; побочные эффекты temp+rename — QA-6, QA-7 (P2) | +| U-P0-2 запись в архив-панель | F5/F6/F4/F11 в пассивную архив-панель | закрыт для прямого пути; обход через mirror — QA-2 (P2) | +| U-P0-3 caret без цветов | Ascii/ANSI/ANSI256/TrueColor на минимальном размере 72×18, движение `j l w v e b k`, затем F3 поверх; высота экрана не меняется | закрыт | +| U-P0-4 удаление в корзину | мультивыделение с пробелами, кириллицей и каталогом; `D,D` возвращает в корзину; режим не «протекает» между диалогами; сломанная корзина → ошибка видна, файл цел; `confirm_delete=false` не пропускает подтверждение для remote (там удаление безвозвратное); `т`/`н` (n/y в русской раскладке) | закрыт, но корзина по умолчанию не работает на другом разделе — QA-1 (P1) | +| U-P1-1 строка статуса | многострочная ошибка склеивается в одну строку, длинная обрезается, высота сохраняется на Ascii/ANSI/TrueColor | закрыт | +| U-P1-5 кириллица в полях | mkdir, rename, фильтр (список реально сужается), SSH-форма (имя, хост) | закрыт; но в фильтре нельзя набрать `j`/`k` (QA-3), в SSH-форме `?` (QA-4) | +| U-P1-6 PgDn | PgDn/PgUp в браузере | закрыт | +| U-P1-16 q (часть) | q и Esc в 9 слоях: help, тема, view, info, caret, confirm delete, выбор формата архива, confirm copy, выделение — ни разу не выходит из программы и всё закрывает; q в mkdir/rename/SSH-форме набирается как текст | закрыт | + +## Найденные баги + +Нумерация QA-n; приоритеты по шкале анализа (P0 — потеря данных/крах, P1 — неверное поведение, P2 — мелочи). + +### QA-1 (P1). Удаление по умолчанию не работает для файлов на другом разделе +- **Где:** `internal/fs/ops.go:312` (`MoveToTrash`: только `os.Rename`, при `EXDEV` — ошибка); стало заметно из-за + `internal/ui/model.go:2538` (корзина теперь по умолчанию, U-P0-4). +- **Шаги:** `$HOME` на `/home`, файл на другой ФС (`/tmp` на tmpfs, `/mnt/…`, USB, второй диск). F8 → Enter. +- **Ожидаемое:** файл в корзине (`$topdir/.Trash-$uid` по спецификации или copy+delete) или, как минимум, предложение + удалить безвозвратно. +- **Фактическое:** `cannot move to trash: rename …: invalid cross-device link`, файл на месте. Пользователь должен + догадаться нажать `D`. В v0.2.7 то же действие удаляло файл. Данные не теряются, ошибка видна в строке статуса. +- **Контекст:** у аналитиков это записано (01-analysis-ui-core.md:176, network:384) и запланировано на 2A, но после смены + умолчания в 1.4 это регрессия для пользователя v0.2.8. На машине мейнтейнера `/tmp` — tmpfs, `/home` — nvme. +- **Тест:** `internal/fs/qa_archive_trash_test.go` `TestQATrashCrossDevice`. + +### QA-11 (P1, есть с v0.2.7). Одна строка с неизвестным алгоритмом в `known_hosts` ломает все SSH-подключения +- **Где:** `internal/fs/remote/client.go:174-176`: ошибка `knownhosts.New` фатальна. +- **Шаги:** в `~/.ssh/known_hosts` есть строка с типом ключа, который `x/crypto/ssh` не знает (например, + `ssh-mldsa44-ed25519` из OpenSSH 10). Подключиться к любому хосту. +- **Ожидаемое:** незнакомые строки пропускаются (как в OpenSSH), подключение идёт. +- **Фактическое:** `host key verification: parse known_hosts: … unknown key algorithm: ssh-mldsa44-ed25519`. SSH не + работает вообще. **В `~/.ssh/known_hosts` мейнтейнера такая строка есть (строка 4)**: тест, который случайно прочитал + настоящий файл, упал именно с этой ошибкой (ничего не записал: ошибка на разборе). Это не регрессия v0.2.8, но в + хотфикс-релизе SSH у мейнтейнера не заработает. +- **Тест:** `internal/ui/qa_regression_test.go` `TestQAKnownHostsUnknownAlgorithm`. + +### QA-2 (P2). Mirror из архив-панели даёт обычную записываемую панель во временном каталоге +- **Где:** `internal/ui/model.go:2620-2626` (`handleMirrorPane`, ветка `InArchive`: копируется только `Path`, без + mount архива). +- **Шаги:** войти в `box.zip` в левой панели, нажать `p`. Правая панель показывает `/tmp/vcom-archive-XXXX` как обычный + локальный каталог. +- **Ожидаемое:** правая панель тоже read-only (или mirror из архива запрещён). +- **Фактическое:** `canWriteTo(правая)` = nil. В ней работают F7, F2, F8, редактирование, копирование из архива; + всё это пропадает при выходе из архива (`RemoveAll` temp), а панель остаётся на удалённом каталоге. Пробовал довести + до потери пользовательского файла: после выхода из архива F6 реального файла в «мёртвую» панель падает с + `no such file or directory`, файл цел. То есть теряются только правки внутри распакованной копии — поэтому P2, а не P0. +- **Тест:** `internal/ui/qa_hotfix_test.go` `TestQAMirrorFromArchiveKeepsReadOnly`. + +### QA-3 (P1, есть с v0.2.7). В фильтр нельзя ввести `j` и `k` +- **Где:** `internal/ui/model.go:1015-1020`: в обработчике фильтра `keys.Up`/`keys.Down` (`k`/`j`) проверяются до + передачи в textinput. +- **Шаги:** `/`, набрать `jpg`. +- **Ожидаемое:** запрос `jpg`. **Фактическое:** запрос `pg`, курсор сдвинулся. Фильтр по `jpg`, `kotlin`, `json` + невозможен. Фикс U-P1-5 («кириллица в фильтре») это не задел, но сценарий «фильтр работает с любым текстом» сломан. +- **Тест:** `TestQAFilterAcceptsJK`. + +### QA-4 (P2). `?` и F1 в форме SSH переключают справку и не попадают в поле +- **Где:** `internal/ui/model.go:1562-1568` (`modalSSHConnect`: `keys.Help` и `"?"` раньше `default`). +- **Шаги:** `s` → «+ Add host» → в поле Password набрать `pa?ss`. +- **Ожидаемое:** `pa?ss`. **Фактическое:** `pass`, справка мигает. Пароль с `?` ввести нельзя (q в форме исправлен + в 1.6, `?` — тот же класс). +- **Тест:** `TestQASSHFormPasswordQuestionMark`. + +### QA-5 (P2, известно). `.trashinfo` не по спецификации XDG +- **Где:** `internal/fs/ops.go:323` (`Path=` без percent-encoding), `ops.go:286` (`XDG_DATA_HOME` игнорируется). +- **Фактическое:** имя с переводом строки ломает `.trashinfo` (`Path=` обрезается); пробелы/кириллица не кодируются — + восстановление из корзины другими инструментами может не сработать; при заданном `XDG_DATA_HOME` vcom и рабочий стол + пишут в разные корзины. С корзиной по умолчанию это стало важнее. +- **Тесты:** `TestQATrashInfoPathEncoded`, `TestQATrashHonoursXDGDataHome`. + +### QA-6 (P2). Перезапись архива меняет права на 0644 +- **Где:** `internal/fs/archive.go:354` (`os.Chmod(tmpPath, 0o644)`). +- **Шаги:** существует `secret.zip` с правами 0600, архивировать поверх с подтверждением. +- **Ожидаемое:** права сохранены (или по umask). **Фактическое:** 0644, архив стал читаемым для всех. +- **Тест:** `TestQAArchiveOverwriteKeepsPermissions`. + +### QA-7 (P2). Архив с длинным именем не создаётся +- **Где:** `internal/fs/archive.go:344` (temp-имя `.vcom-tmp--<имя>` длиннее имени на ~20 байт). +- **Шаги:** файл с именем 240 байт + `.txt`, архивировать в zip (имя архива 244 байта — допустимо). +- **Фактическое:** `file name too long`. В v0.2.7 работало. +- **Тест:** `TestQAArchiveLongName`. + +### QA-8 (P2). Коллизия в корзине с битым симлинком затирает его +- **Где:** `internal/fs/ops.go:303` (проверка занятости имени через `os.Stat`, который идёт по ссылке). +- **Шаги:** удалить в корзину битый симлинк `x`, затем файл с тем же именем `x`. +- **Ожидаемое:** в корзине два элемента. **Фактическое:** один, симлинк затёрт `rename`. +- **Тест:** `TestQATrashCollisionWithBrokenSymlink`. + +### QA-9 (P2). `RemoveRecursive("link/")` идёт по ссылке +- **Где:** `internal/fs/remote/client.go:528`: `Lstat` пути со слешем на конце на POSIX-сервере разрешает ссылку. +- **Шаги:** `RemoveRecursive(link + "/")`, где `link` → каталог. **Фактическое:** содержимое цели удалено. +- **Достижимость:** из UI сейчас нет (пути собираются через `path.Join`, слеш на конце не остаётся). Стоит + `path.Clean` в начале функции. +- **Тест:** `TestQARemoveRecursiveSymlinkTrailingSlash`. + +### QA-10 (P2). F7 с существующим именем в SSH-панели «успешен» +- **Где:** `internal/ui/model.go:5312` (`mkdirCmd` → `Client.MkdirAll`). +- **Ожидаемое:** ошибка, как локально после 1.1 (CHANGELOG: «Creating a directory that already exists reports an + error»). **Фактическое:** `Created …/taken`. CHANGELOG обещает больше, чем сделано. +- **Тест:** `TestQARemoteMkdirExisting`. + +## Наблюдения без отдельного id + +- `goParent` после `Release` оставляет хост помеченным «connected», если клиентом пользуется другая панель или джоба. + Это корректно. Но `exitSSHMode` ставит `connectedHosts=false` безусловно — значок в списке хостов может врать, + пока работает mirror. Мелочь. +- `Close` ждёт keepalive-горутину под `closeMu`. При «замёрзшей» сети `SendRequest` может висеть, и последний `Release` + из `Update` (выход с хоста) заблокирует UI. Так было и до фикса (N-P1-8/9 — этап 2B). +- `ssh.activeClients` нигде не заполняется: код закрытия в `exitSSHMode`/`executeSSHHostDelete` мёртвый. Это не баг. +- Переход Enter по remote-симлинку на каталог теперь выдаёт «Opening remote files is not supported». Раньше это тоже + не работало (remote-записи для симлинков — не каталоги), регрессии нет. + +## Вердикт + +Все заявленные фиксы этапа 1 (N-P0-1/2/3, N-P1-15, N-P2-10, части N-P0-8/N-P1-12, U-P0-1..4, U-P1-1/5/6, часть +U-P1-16) **подтверждены** и выдержали попытки обойти их через соседние пути. Регрессий в основных сценариях +(local и remote) нет, CI зелёный, флейков нет. **P0 не найдено.** + +**v0.2.8 можно выпускать.** До тега рекомендую закрыть два P1, оба небольшие: +1. **QA-1**: при `EXDEV` в `MoveToTrash` делать fallback (copy+delete в `~/.local/share/Trash` или + `$topdir/.Trash-$uid`), либо при ошибке корзины предлагать в том же диалоге безвозвратное удаление. Иначе + новое умолчание «в корзину» ломает F8 за пределами раздела `$HOME`. Если не исправлять, это нужно записать в CHANGELOG + как известное ограничение. +2. **QA-11**: если `knownhosts.New` не разобрал файл, не отказывать в подключении — пропускать незнакомые строки. + Это не регрессия, но SSH у мейнтейнера сейчас не работает вовсе (OpenSSH 10 пишет PQ-ключи в known_hosts). + +Остальное (QA-2..QA-10) не блокирует релиз; QA-3 (j/k в фильтре) и QA-10 (несоответствие CHANGELOG) стоит взять в +следующий хотфикс или в этап 6. CHANGELOG стоит поправить: для F7 указать, что ошибка на существующем имени пока +только для локальных панелей. + +--- + +## Повторная проверка (RC2) + +Ветка `rework/stabilize` @ `058616d`: это `4bb60d0` плюс один тестовый коммит transfer (3.4). Проверены: +- QA-фиксы разработчика C (QA-1 UI, 2, 3, 4, 6, 7, 9, 10, 11); +- корзина `localfs.Trash` (fs-часть QA-1, QA-5, QA-8); +- изменения 2C, которые использует старый UI: config/SetKey, state/session, paths, atomicfile, logx, сигналы в `main`. + +Новые пакеты `internal/vfs`, `internal/ssh`, `internal/transfer` глубоко не тестировал: прогнаны только их собственные тесты. + +Новые тесты: +- `cmd/vcom/qa_signal_test.go` — настоящий `run()` в дочернем процессе на pty (`script`), SIGTERM ×12. **Внимание:** + `.gitignore` содержит шаблон `vcom`, а он игнорирует весь каталог `cmd/vcom/`. Файл добавлен через `git add -f`, и + новые файлы в `cmd/vcom` у всех будут молча не попадать в коммиты. +- `internal/config/qa_rc2_test.go` — SetKey: симлинк, read-only, точечные ключи и inline-таблица, неудачная правка не + портит файл, BOM; Load: каталог или нечитаемый файл вместо конфига, отсутствующий `$VCOM_CONFIG`. +- `internal/state/qa_rc2_test.go` — пустой/битый session.toml, битый старый, симлинк, миграция в недоступный + state-каталог. +- `internal/ui/qa_rc2_test.go` — неизвестная тема, битый конфиг + смена темы, `$VCOM_CONFIG` + тема, битая сессия, + миграция сессии через UI, обходы QA-1/2/3/4/10, видимость ошибки сохранения темы. +- Поправлен мой `TestQATrashCrossDevice`. С новой корзиной он стал реально класть файл в `/dev/shm/.Trash-1000` и + оставлял там мусор `on-other-fs.txt*`. Теперь файл получает уникальное имя и удаляется вместе со своим + `.trashinfo`, а `.Trash-$uid` удаляется, если его создал тест. Мусор уже удалён, но версия теста в + `rework/stabilize` будет мусорить при каждом прогоне (в других worktree уже насорила), пока исправление не смержат. + +### Прогоны + +| Команда | Результат | +|---|---| +| `make ci` | зелёный | +| `go test -race -count=3 ./...` (до и после добавления RC2-тестов) | зелёный, флейков нет | +| Ручной e2e: собранный `vcom` в pty, `kill -TERM` / `kill -HUP` | HUP: выход, сессия сохранена, run-dir удалён. TERM: **2 зависания из 9** (QA-12) | + +### QA-фиксы: результат повторной проверки + +| Баг | Проверено | Итог | +|---|---|---| +| QA-1 | корзина на другом разделе (topdir `/dev/shm/.Trash-1000`), сломанная корзина → предложение удалить безвозвратно, имя 250 байт (корзина отказывает → предложение, Esc сохраняет файл) | закрыт; побочный эффект — QA-17 | +| QA-2 | mirror из архива отклоняется | закрыт; соседний путь (mirror *в* архив-панель) — QA-18 | +| QA-3 | в фильтр набираются `j k J K`, цифры, пробел, кириллица; стрелки двигают курсор | закрыт | +| QA-4 | `?` набирается во всех 5 полях SSH-формы, F1 открывает и закрывает справку | закрыт | +| QA-5, QA-8 | мои тесты сняты со skip и проходят | закрыт | +| QA-6, QA-7 | мои тесты проходят | закрыт | +| QA-9 | `link/` | закрыт | +| QA-10 | F7 в SSH: существующий каталог/файл → ошибка; вложенное и кириллическое имя создаются | закрыт | +| QA-11 | строка `ssh-mldsa44-ed25519` пропускается | закрыт. На машине мейнтейнера не проверял (не подключаюсь к его хостам) | + +### Новые баги + +#### QA-12 (P1, регрессия 2C — блокирует). SIGTERM иногда навсегда вешает vcom +- **Где:** `cmd/vcom/main.go:83-92` подписывается на `SIGTERM` (и `SIGHUP`) и шлёт `tea.Quit`. Bubble Tea сам ловит + SIGTERM (`vendor/github.com/charmbracelet/bubbletea/tea.go:286-302`) и шлёт `QuitMsg` в небуферизованный `p.msgs`, + не проверяя `ctx`. Если первым дошёл `tea.Quit` из `main`, цикл событий уже завершён, горутина Bubble Tea + навсегда висит на отправке, а `Program.shutdown` (`tea.go:814`) ждёт её в `handlers.shutdown()`. +- **Шаги:** запустить vcom в терминале, `kill ` (systemd/logout/`kill` по умолчанию). +- **Ожидаемое:** выход, терминал восстановлен, сессия сохранена (это и обещает CHANGELOG RC2). +- **Фактическое:** в 2 из 9 ручных запусков и в 4 из 12 запусков теста процесс не завершился. Дамп горутин (SIGQUIT): + `main.run → Program.Run → shutdown → channelHandlers.shutdown → WaitGroup.Wait`, а + `handleSignals.func1` стоит в `chan send`. Терминал остаётся в alt-screen/raw, сессия не сохранена, run-dir не + удалён, помогает только `kill -9`. В v0.2.7 SIGTERM обрабатывал только Bubble Tea, и vcom выходил всегда. +- **Фикс (для разработчика):** не подписываться на SIGTERM в `main`, оставить там только SIGHUP. Либо отключить + обработчик Bubble Tea (`tea.WithoutSignalHandler()`) и обрабатывать оба сигнала в `main`. +- **Тест:** `cmd/vcom/qa_signal_test.go` `TestQASigtermExitsAndSavesSession`. Медленный (~95 с из-за таймаута + запроса цвета терминала в pty), стоит на skip. + +#### QA-13 (P2). SetKey переписывает read-only конфиг +- **Где:** `internal/atomicfile/atomicfile.go:40-52`: temp+rename не смотрит на отсутствие права записи у файла. +- **Шаги:** `chmod 444 ~/.config/vcom/vcom.toml`, выбрать тему. +- **Ожидаемое:** файл не меняется, ошибка. В v0.2.7 было EACCES. +- **Фактическое:** файл переписан, права 0444 сохранены. Конфиг через симлинк в read-only каталог (home-manager, + /nix/store) по-прежнему защищён: temp-файл создать нельзя. +- **Тест:** `internal/config/qa_rc2_test.go` `TestQASetKeyReadOnlyConfig`. + +#### QA-14 (P2). Тема не сохраняется при `ui.theme = …` в корне или `ui = { theme = … }` +- **Где:** `internal/config/setkey.go:86-152`: `editTOML` ищет только `[ui]`, дописывает вторую таблицу `[ui]`, и + `verify` отвергает результат. +- **Фактическое:** ошибка `table ui already exists` / `key ui should be a table`. Файл не портится (проверено в + `TestQASetKeyFailureLeavesFileIntact`), но из-за QA-19 пользователь не узнаёт, что тема не сохранилась. +- **Тест:** `TestQASetKeyDottedAndInlineForms`. + +#### QA-15 (P2). При `-config`/`$VCOM_CONFIG` на ещё не существующий файл тема пишется в `~/.config/vcom/vcom.toml` +- **Где:** `cmd/vcom/main.go:41-43` передаёт в UI путь, только если файл найден. `SetKey("")` пишет по пути по + умолчанию, хотя `LoadInfo.Path` уже содержит нужный путь. +- **Фактическое:** создаётся `~/.config/vcom/vcom.toml`. Следующий запуск читает `$VCOM_CONFIG` (файла нет), и тема + потеряна. +- **Тест:** `internal/ui/qa_rc2_test.go` `TestQAThemeSavedToExplicitMissingConfig`. Тест повторяет логику `main` + (`newModelLikeMain`). + +#### QA-16 (P2). Сессия не восстанавливается, если миграция в state-каталог не удалась +- **Где:** `state.Load` возвращает прочитанную старую сессию вместе с ошибкой сохранения. `ui.applySession` + (`model.go:5453-5457`) при любой ошибке выбрасывает сессию. +- **Шаги:** старый `~/.config/vcom/session.toml`, `XDG_STATE_HOME` недоступен для записи. +- **Фактическое:** панели открываются на стартовых путях. Старый файл не удаляется (это правильно). +- **Тесты:** `TestQAOldSessionRestoredWhenStateDirReadOnly` (ui); поведение `state.Load` зафиксировано в + `internal/state/qa_rc2_test.go` `TestQASessionMigrationUnwritableStateDir` (проходит). + +#### QA-17 (P2). Предложение «удалить безвозвратно» захватывает элементы, которые корзина приняла бы +- **Где:** `model.go:5314`: `trashFailed = sources[i:]` — неудачный элемент и все следующие за ним. +- **Шаги:** выделить файл, который корзина отвергает (имя 250 байт: `.trashinfo` длиннее NAME_MAX), и обычный + `b.txt`, F8 → Enter. +- **Ожидаемое:** `b.txt` уходит в корзину, а безвозвратное удаление предлагается только для первого файла. +- **Фактическое:** диалог «Not in trash: 2». Подтверждение удаляет `b.txt` безвозвратно. Без подтверждения ничего не + удаляется, поэтому P2. Но диалог подталкивает удалить то, что можно было восстановить. +- **Тест:** `TestQATrashOfferOnlyForRefusedItems`. + +#### QA-18 (P2, есть с v0.2.7). Mirror *в* панель, которая находится в архиве +- **Где:** `handleMirrorPane`, локальная ветка (`model.go:2667-2669`): чистит только remote-mount’ы, архивный mount + пассивной панели остаётся. +- **Фактическое:** пассивная панель показывает настоящий каталог, но остаётся «в архиве». Запись туда запрещена, + Backspace никогда не закрывает архив (корень архива — temp-каталог), temp-каталог висит до выхода. Данные не + теряются. +- **Тест:** `TestQAMirrorIntoArchivePane`. + +#### QA-19 (P2). Ошибка сохранения темы не видна +- **Где:** `model.go:1645-1648`: после `finalizeTheme` выбор темы перезаписывает статус «save failed» строкой + «Theme: X». +- **Фактическое:** при битом конфиге (с RC2 vcom с ним запускается), при QA-13/QA-14 и при любой другой ошибке + пользователь видит «Theme: X», хотя тема не сохранена. Сам битый конфиг не трогается (проверено: + `TestQABrokenConfigNotOverwrittenByTheme`). +- **Тест:** `TestQAThemeSaveFailureVisible`. + +### Проверено без замечаний (2C) +- Битый конфиг: vcom стартует с дефолтами, ошибка видна на экране. Мелочь: сообщение `… incomplete number (using + defaults)` не содержит слов из `statusErrorWords`, поэтому показано как обычный статус, а не красным. +- Неизвестная тема: старт с темой по умолчанию, причина на экране; выбор темы чинит файл, комментарии и прочие + ключи сохраняются. +- Конфиг-симлинк (dotfiles): ссылка сохраняется, правится цель, права цели сохраняются. +- `./vcom.toml` из cwd не загружается (тест разработчика); `$VCOM_CONFIG` на отсутствующий файл корректно отражён в + `LoadInfo`; каталог или нечитаемый файл вместо конфига — дефолты и ошибка. +- Сессия: пустой и битый файл не мешают старту, выход записывает валидную сессию; битый старый файл не мигрирует и + не удаляется; симлинк сохраняется; права 0600, каталог 0700; миграция со старого пути через UI работает, старый + файл удаляется. +- sudo: прочитал `paths` и тест разработчика `TestSudoWritePathsEffectiveUser`: state/cache/trash/known_hosts + пишутся под effective user, при `sudo -E` унаследованные `XDG_*` для записи игнорируются, старый session + пользователя не удаляется. Настоящий sudo не запускал. Замечание: под sudo смена темы правит конфиг **вызвавшего** + пользователя (`~bob/.config/vcom/vcom.toml`). Владелец сохраняется (`atomicfile` делает chown), но это расходится с + doc-комментарием `paths`: «config is READ from the invoking user's home». +- logx: файл 0600, каталог 0700, ротация на старте; в вызовах `log.Printf` старого UI секретов не нашёл. +- SIGHUP: сессия сохраняется, run-dir удаляется. +- После паники в `Update` `Program.Run` возвращает nil-модель, `shutdown(nil)` ничего не делает, и сессия не + сохраняется. Doc-комментарий `run()` обещает teardown «or a panic Bubble Tea recovered from». Так было и в v0.2.7; + стоит поправить комментарий или сохранять сессию из `recover`. + +### Вердикт RC2 + +Все QA-фиксы v0.2.8 (QA-1..QA-11) **подтверждены**, обойти их не удалось. CI и `-race -count=3` зелёные, флейков нет. + +**RC2 к релизу не готов из-за одного бага — QA-12 (P1, регрессия 2C):** vcom зависает на SIGTERM примерно в трети +случаев, а именно эту обработку сигналов CHANGELOG RC2 заявляет как новую возможность. Фикс в одну строку: убрать +`syscall.SIGTERM` из `signal.Notify` в `main.go`. После него QA-12 нужно перепроверить тестом +`TestQASigtermExitsAndSavesSession` (снять skip). + +QA-13..QA-19 — P2, потери данных нет. Желательно до релиза исправить QA-19: без него не видны QA-13/14/15. Остальное +можно отложить. Ещё стоит поправить `.gitignore` (`/vcom` вместо `vcom`), чтобы не игнорировался `cmd/vcom/`. diff --git a/plans/rework/testbed/fs_analysis_test.go.txt b/plans/rework/testbed/fs_analysis_test.go.txt new file mode 100644 index 0000000..37a3b3d --- /dev/null +++ b/plans/rework/testbed/fs_analysis_test.go.txt @@ -0,0 +1,81 @@ +package vfs + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" +) + +var scratch = os.Getenv("VCOM_SCRATCH") + +func TestArchiveSelfTruncate(t *testing.T) { + d := filepath.Join(scratch, "arch1") + os.RemoveAll(d) + os.MkdirAll(d, 0o755) + src := filepath.Join(d, "data.tar") + os.WriteFile(src, make([]byte, 100000), 0o644) + name := ArchiveName([]string{src}, "tar") + target := filepath.Join(d, name) + err := CreateArchive(context.Background(), []string{src}, target, nil) + st, _ := os.Stat(src) + t.Logf("archive data.tar as tar into same dir: name=%s err=%v source size now=%d (was 100000)", name, err, st.Size()) +} + +func TestArchiveSelfInclude(t *testing.T) { + d := filepath.Join(scratch, "arch2") + os.RemoveAll(d) + os.MkdirAll(filepath.Join(d, "proj"), 0o755) + os.WriteFile(filepath.Join(d, "proj", "a.bin"), make([]byte, 1<<20), 0o644) + target := filepath.Join(d, "proj", "proj.zip") // passive pane inside source dir + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + err := CreateArchive(ctx, []string{filepath.Join(d, "proj")}, target, nil) + st, _ := os.Stat(target) + t.Logf("archive proj into proj/: err=%v archive size=%d", err, st.Size()) + os.RemoveAll(d) +} + +func TestExtractOverwrite(t *testing.T) { + d := filepath.Join(scratch, "arch3") + os.RemoveAll(d) + os.MkdirAll(filepath.Join(d, "src"), 0o755) + os.WriteFile(filepath.Join(d, "src", "f.txt"), []byte("NEW"), 0o644) + arc := filepath.Join(d, "a.zip") + CreateArchive(context.Background(), []string{filepath.Join(d, "src", "f.txt")}, arc, nil) + os.MkdirAll(filepath.Join(d, "dst"), 0o755) + os.WriteFile(filepath.Join(d, "dst", "f.txt"), []byte("PRECIOUS"), 0o644) + err := ExtractArchiveToDir(context.Background(), arc, filepath.Join(d, "dst"), nil) + b, _ := os.ReadFile(filepath.Join(d, "dst", "f.txt")) + t.Logf("extract over existing file: err=%v content=%q", err, b) +} + +func BenchmarkListDir20k(b *testing.B) { + for i := 0; i < b.N; i++ { + ListDir(filepath.Join(scratch, "big"), ListOptions{ShowHidden: true, DirsFirst: true, SortBy: "name"}) + } +} + +func BenchmarkReadDirOnly20k(b *testing.B) { + for i := 0; i < b.N; i++ { + es, _ := os.ReadDir(filepath.Join(scratch, "big")) + for _, e := range es { + e.Info() + } + } +} + +func BenchmarkPreviewHighlight64k(b *testing.B) { + p := filepath.Join(scratch, "big.go") + for i := 0; i < b.N; i++ { + BuildPreview(Entry{Name: "big.go", Path: p, Extension: "go"}, PreviewOptions{MaxPreviewBytes: 65536, ThemeName: "catppuccin-mocha"}) + } +} + +func BenchmarkPreviewDir20k(b *testing.B) { + p := filepath.Join(scratch, "big") + for i := 0; i < b.N; i++ { + BuildPreview(Entry{Name: "big", Path: p, IsDir: true}, PreviewOptions{MaxPreviewBytes: 65536, DirectoryPreviewLimit: 80}) + } +} diff --git a/plans/rework/testbed/fs_bugs_local_test.go.txt b/plans/rework/testbed/fs_bugs_local_test.go.txt new file mode 100644 index 0000000..fa76c59 --- /dev/null +++ b/plans/rework/testbed/fs_bugs_local_test.go.txt @@ -0,0 +1,97 @@ +package vfs + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" +) + +func w(t *testing.T, p string, s string) { + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +// Overwrite of a directory replaces it entirely (extra dst files deleted). +func TestLocalOverwriteDirDeletesExtra(t *testing.T) { + d := t.TempDir() + w(t, filepath.Join(d, "src", "proj", "a.txt"), "new") + w(t, filepath.Join(d, "dst", "proj", "keep.txt"), "user data") + _, err := CopyPath(filepath.Join(d, "src", "proj"), filepath.Join(d, "dst"), true) + _, e := os.Stat(filepath.Join(d, "dst", "proj", "keep.txt")) + t.Logf("err=%v keep.txt exists=%v", err, e == nil) + if e != nil { + t.Errorf("BUG CONFIRMED: overwrite wiped files that only existed in destination dir") + } +} + +// Old destination deleted BEFORE copying; failure leaves nothing. +func TestLocalOverwriteFailureLosesDest(t *testing.T) { + d := t.TempDir() + w(t, filepath.Join(d, "src", "f.txt"), "new") + os.Chmod(filepath.Join(d, "src", "f.txt"), 0o000) // unreadable -> copy fails + w(t, filepath.Join(d, "dst", "f.txt"), "OLD VALUABLE") + _, err := CopyPath(filepath.Join(d, "src", "f.txt"), filepath.Join(d, "dst"), true) + _, e := os.Stat(filepath.Join(d, "dst", "f.txt")) + t.Logf("err=%v dst exists=%v", err, e == nil) + if e != nil { + t.Errorf("BUG CONFIRMED: failed overwrite deleted the old destination") + } +} + +// Read-only source dir cannot be copied (dst dir created 0555 before filling). +func TestLocalCopyReadOnlyDir(t *testing.T) { + d := t.TempDir() + w(t, filepath.Join(d, "src", "ro", "a.txt"), "x") + os.Chmod(filepath.Join(d, "src", "ro"), 0o555) + defer os.Chmod(filepath.Join(d, "src", "ro"), 0o755) + _, err := CopyPath(filepath.Join(d, "src", "ro"), filepath.Join(d, "dst"), false) + t.Logf("err=%v", err) + if err != nil { + t.Errorf("BUG CONFIRMED: copying read-only dir fails: %v", err) + } + os.Chmod(filepath.Join(d, "dst", "ro"), 0o755) +} + +// samePath does not resolve symlinks: dst dir is a symlink to src's dir -> overwrite deletes source. +func TestLocalOverwriteViaSymlinkAlias(t *testing.T) { + d := t.TempDir() + w(t, filepath.Join(d, "real", "f.txt"), "ONLY COPY") + os.Symlink(filepath.Join(d, "real"), filepath.Join(d, "alias")) + _, err := CopyPath(filepath.Join(d, "real", "f.txt"), filepath.Join(d, "alias"), true) + _, e := os.Stat(filepath.Join(d, "real", "f.txt")) + t.Logf("err=%v source exists=%v", err, e == nil) + if e != nil { + t.Errorf("BUG CONFIRMED: source destroyed when target dir is a symlink alias") + } +} + +// mtime not preserved locally either. +func TestLocalMtime(t *testing.T) { + d := t.TempDir() + p := filepath.Join(d, "src", "f.txt") + w(t, p, "x") + old := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + os.Chtimes(p, old, old) + os.MkdirAll(filepath.Join(d, "dst"), 0o755) + out, _ := CopyPath(p, filepath.Join(d, "dst"), false) + st, _ := os.Stat(out) + if !st.ModTime().Equal(old) { + t.Errorf("BUG CONFIRMED: mtime not preserved: %v", st.ModTime()) + } +} + +// Dir copy stats have BytesTotal=0 -> byte progress meaningless. +func TestCopyStatsBytes(t *testing.T) { + d := t.TempDir() + w(t, filepath.Join(d, "src", "a"), "1234567890") + st, _ := CopyStats(filepath.Join(d, "src")) + t.Logf("stats=%+v", st) + if st.BytesTotal == 0 { + t.Errorf("BUG CONFIRMED: CopyStats for dir has BytesTotal=0") + } + _ = context.Background +} diff --git a/plans/rework/testbed/remote_bugs_test.go.txt b/plans/rework/testbed/remote_bugs_test.go.txt new file mode 100644 index 0000000..068691a --- /dev/null +++ b/plans/rework/testbed/remote_bugs_test.go.txt @@ -0,0 +1,286 @@ +package remote + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" +) + +func setup(t *testing.T) (*testServer, *SSHClient, string) { + setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + c := mustConnect(t, hostFor(srv.addr, "127.0.0.1")) + return srv, c, t.TempDir() +} + +// B1: deleting a remote symlink that points to a directory wipes the target dir. +func TestRemoveRecursiveSymlinkToDir(t *testing.T) { + _, c, dir := setup(t) + target := filepath.Join(dir, "precious") + writeFile(t, filepath.Join(target, "a.txt"), 10, 0o644) + writeFile(t, filepath.Join(target, "sub", "b.txt"), 10, 0o644) + link := filepath.Join(dir, "link") + os.Symlink(target, link) + + err := c.RemoveRecursive(link) + t.Logf("RemoveRecursive(link) err=%v", err) + left, _ := filepath.Glob(filepath.Join(target, "*")) + t.Logf("target contents after deleting the LINK: %v", left) + if len(left) == 0 { + t.Errorf("BUG CONFIRMED: deleting symlink removed contents of the target directory") + } +} + +// B2: upload of a dir containing a broken symlink aborts the whole transfer. +func TestUploadDirWithBrokenSymlink(t *testing.T) { + _, c, dir := setup(t) + src := filepath.Join(dir, "src") + writeFile(t, filepath.Join(src, "a.txt"), 10, 0o644) + os.Symlink("/nonexistent/zzz", filepath.Join(src, "broken")) + writeFile(t, filepath.Join(src, "z_after.txt"), 10, 0o644) + os.Symlink(filepath.Join(src), filepath.Join(src, "loopdir")) + err := c.CopyDirToRemote(src, filepath.Join(dir, "dst")) + t.Logf("upload err=%v", err) + if err != nil { + t.Errorf("BUG CONFIRMED: dir upload aborted by symlink: %v", err) + } +} + +func TestDownloadDirWithBrokenSymlink(t *testing.T) { + _, c, dir := setup(t) + src := filepath.Join(dir, "src") + writeFile(t, filepath.Join(src, "a.txt"), 10, 0o644) + os.Symlink("/nonexistent/zzz", filepath.Join(src, "broken")) + writeFile(t, filepath.Join(src, "z_after.txt"), 10, 0o644) + err := c.CopyDirFromRemote(src, filepath.Join(dir, "dst")) + t.Logf("download err=%v", err) + if err != nil { + t.Errorf("BUG CONFIRMED: dir download aborted by broken symlink: %v", err) + } + // symlink to file: dereferenced? +} + +// B3: permissions and mtime are not preserved. +func TestPermsMtimeLost(t *testing.T) { + _, c, dir := setup(t) + src := filepath.Join(dir, "run.sh") + writeFile(t, src, 100, 0o755) + old := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + os.Chtimes(src, old, old) + up := filepath.Join(dir, "up", "run.sh") + if err := c.CopyFileToRemote(src, up); err != nil { + t.Fatal(err) + } + down := filepath.Join(dir, "down", "run.sh") + if err := c.CopyFileFromRemote(src, down); err != nil { + t.Fatal(err) + } + for _, p := range []string{up, down} { + st, _ := os.Stat(p) + t.Logf("%s mode=%v mtime=%v", p, st.Mode(), st.ModTime()) + if st.Mode().Perm() != 0o755 || !st.ModTime().Equal(old) { + t.Errorf("BUG CONFIRMED: mode/mtime not preserved for %s", p) + } + } +} + +// B4: same file reached through two different host aliases is truncated to 0. +func TestSameFileViaAliasTruncates(t *testing.T) { + setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + c1 := mustConnect(t, hostFor(srv.addr, "127.0.0.1")) + c2 := mustConnect(t, hostFor(srv.addr, "localhost")) + dir := t.TempDir() + f := filepath.Join(dir, "data.bin") + writeFile(t, f, 1<<20, 0o644) + err := CopyFileBetweenRemotes(c1, c2, f, f) + st, _ := os.Stat(f) + t.Logf("err=%v size after=%d (was %d)", err, st.Size(), 1<<20) + if st.Size() != 1<<20 { + t.Errorf("BUG CONFIRMED: file destroyed (size %d)", st.Size()) + } +} + +// B5: Close() concurrently with use -> data race / nil deref. +func TestCloseRace(t *testing.T) { + _, c, dir := setup(t) + done := make(chan struct{}) + panicked := make(chan any, 1) + go func() { + defer func() { + if r := recover(); r != nil { + panicked <- r + } + close(done) + }() + for i := 0; i < 2000; i++ { + c.ReadDir(dir) + } + }() + time.Sleep(5 * time.Millisecond) + c.Close() + <-done + select { + case r := <-panicked: + t.Errorf("BUG CONFIRMED: panic during concurrent Close: %v", r) + default: + } +} + +// B6: network freeze -> calls hang indefinitely; keepalive does not notice. +func TestFreezeHangs(t *testing.T) { + setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + p := startProxy(t, srv.addr, 0) + c := mustConnect(t, hostFor(p.addr, "127.0.0.1")) + dir := t.TempDir() + p.frozen.Store(true) + res := make(chan error, 1) + go func() { _, err := c.ReadDir(dir); res <- err }() + select { + case err := <-res: + t.Logf("returned err=%v", err) + case <-time.After(8 * time.Second): + t.Errorf("BUG CONFIRMED: ReadDir blocked >8s on frozen link; IsConnected()=%v", c.IsConnected()) + } + p.frozen.Store(false) +} + +// B7: upload throughput is limited to one 32KiB packet per RTT. +func TestUploadThroughputLatency(t *testing.T) { + setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + p := startProxy(t, srv.addr, 10*time.Millisecond) // ~20ms RTT + c := mustConnect(t, hostFor(p.addr, "127.0.0.1")) + dir := t.TempDir() + src := filepath.Join(dir, "big.bin") + writeFile(t, src, 4<<20, 0o644) + + t0 := time.Now() + if err := c.CopyFileToRemote(src, filepath.Join(dir, "up1.bin")); err != nil { + t.Fatal(err) + } + seqUp := time.Since(t0) + + t0 = time.Now() + if err := c.CopyFileFromRemote(src, filepath.Join(dir, "down1.bin")); err != nil { + t.Fatal(err) + } + down := time.Since(t0) + + fast, err := sftp.NewClient(c.sshConn, sftp.UseConcurrentWrites(true)) + if err != nil { + t.Fatal(err) + } + defer fast.Close() + t0 = time.Now() + lf, _ := os.Open(src) + rf, _ := fast.Create(filepath.Join(dir, "up2.bin")) + rf.ReadFrom(lf) + rf.Close() + lf.Close() + concUp := time.Since(t0) + t.Logf("4MiB @20ms RTT: upload(current)=%v download(current)=%v upload(UseConcurrentWrites)=%v", seqUp, down, concUp) +} + +// B8: overwrite + connection drop destroys the old destination and leaves a partial file. +func TestOverwriteThenDrop(t *testing.T) { + setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + p := startProxy(t, srv.addr, 0) + c := mustConnect(t, hostFor(p.addr, "127.0.0.1")) + dir := t.TempDir() + dst := filepath.Join(dir, "important.db") + writeFile(t, dst, 2<<20, 0o644) + oldContent, _ := os.ReadFile(dst) + src := filepath.Join(dir, "new.db") + writeFile(t, src, 8<<20, 0o644) + p.cutAfter.Store(p.sent.Load() + 1<<20) + err := c.CopyFileToRemote(src, dst) + time.Sleep(200 * time.Millisecond) + now, _ := os.ReadFile(dst) + t.Logf("err=%v; dst size before=%d after=%d", err, len(oldContent), len(now)) + if !bytes.Equal(now, oldContent) { + t.Errorf("BUG CONFIRMED: old destination lost, partial file (%d bytes) left behind", len(now)) + } +} + +// B9: known_hosts has only the ed25519 key (as OpenSSH writes it), server also +// offers ECDSA -> Go negotiates ECDSA first -> false "IDENTIFICATION HAS CHANGED". +func TestHostKeyAlgoMismatch(t *testing.T) { + home := setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + _, port, _ := strings.Cut(srv.addr, ":") + _ = port + line := knownhosts.Line([]string{knownhosts.Normalize(srv.addr)}, ed.PublicKey()) + os.WriteFile(filepath.Join(home, ".ssh", "known_hosts"), []byte(line+"\n"), 0o600) + _, err := Connect(hostFor(srv.addr, "127.0.0.1")) + t.Logf("connect err=%v", err) + if err != nil && strings.Contains(err.Error(), "HAS CHANGED") { + t.Errorf("BUG CONFIRMED: false MITM alarm for a host with a valid known ed25519 key") + } + _ = ssh.KeyAlgoED25519 +} + +// B10: ssh config Host without HostName -> Addr() == ":22" (dials localhost). +func TestConfigNoHostName(t *testing.T) { + p := filepath.Join(t.TempDir(), "config") + os.WriteFile(p, []byte("Host myserver.example.com\n User bob\nHost alias\n HostName=10.0.0.1\n"), 0o600) + hosts := parseSSHConfigFile(p) + for _, h := range hosts { + t.Logf("name=%q hostname=%q addr=%q", h.Name, h.HostName, h.Addr()) + if h.HostName == "" { + t.Errorf("BUG CONFIRMED: host %q has empty HostName, Addr=%q", h.Name, h.Addr()) + } + } +} + +// B11: cancellation is not observed inside a single big file. +func TestCancelSingleFile(t *testing.T) { + setupHome(t) + ed, ec := genKeys(t) + srv := startServer(t, ed, ec) + p := startProxy(t, srv.addr, 5*time.Millisecond) + c := mustConnect(t, hostFor(p.addr, "127.0.0.1")) + dir := t.TempDir() + src := filepath.Join(dir, "src") + writeFile(t, filepath.Join(src, "big.bin"), 3<<20, 0o644) + ctx, cancel := context.WithCancel(context.Background()) + go func() { time.Sleep(150 * time.Millisecond); cancel() }() + t0 := time.Now() + err := c.CopyDirToRemoteProgress(src, filepath.Join(dir, "dst"), nil, ctx) + el := time.Since(t0) + st, statErr := os.Stat(filepath.Join(dir, "dst", "big.bin")) + var sz int64 + if statErr == nil { + sz = st.Size() + } + t.Logf("cancel at 150ms; returned after %v err=%v; dst file size=%d", el, err, sz) + if el > time.Second { + t.Errorf("BUG CONFIRMED: cancel ignored for %v (until file finished)", el) + } +} + +// B12: DirectorySize on unreachable path returns 0 without error. +func TestDirSizeSwallowsError(t *testing.T) { + _, c, dir := setup(t) + sz, err := c.DirectorySize(filepath.Join(dir, "does-not-exist")) + t.Logf("size=%d err=%v", sz, err) + if err == nil { + t.Errorf("BUG CONFIRMED: error swallowed, size=%d", sz) + } +} diff --git a/plans/rework/testbed/remote_harness_test.go.txt b/plans/rework/testbed/remote_harness_test.go.txt new file mode 100644 index 0000000..f283432 --- /dev/null +++ b/plans/rework/testbed/remote_harness_test.go.txt @@ -0,0 +1,259 @@ +package remote + +// Test harness: in-process SSH server (password auth, sftp subsystem backed +// by the real OS filesystem, exec via sh -c) plus a TCP "toxic" proxy that can +// add latency, freeze traffic, or cut the connection after N bytes. + +import ( + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "encoding/binary" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +type testServer struct { + addr string + ln net.Listener + hostKeys []ssh.Signer +} + +func genKeys(t *testing.T) (ssh.Signer, ssh.Signer) { + _, edPriv, _ := ed25519.GenerateKey(rand.Reader) + ed, err := ssh.NewSignerFromKey(edPriv) + if err != nil { + t.Fatal(err) + } + ecPriv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + ec, err := ssh.NewSignerFromKey(ecPriv) + if err != nil { + t.Fatal(err) + } + return ed, ec +} + +func startServer(t *testing.T, hostKeys ...ssh.Signer) *testServer { + t.Helper() + cfg := &ssh.ServerConfig{ + PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { + if string(pass) == "pw" { + return nil, nil + } + return nil, fmt.Errorf("denied") + }, + } + for _, k := range hostKeys { + cfg.AddHostKey(k) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := &testServer{addr: ln.Addr().String(), ln: ln, hostKeys: hostKeys} + go func() { + for { + nc, err := ln.Accept() + if err != nil { + return + } + go s.handle(nc, cfg) + } + }() + t.Cleanup(func() { ln.Close() }) + return s +} + +func (s *testServer) handle(nc net.Conn, cfg *ssh.ServerConfig) { + _, chans, reqs, err := ssh.NewServerConn(nc, cfg) + if err != nil { + nc.Close() + return + } + go ssh.DiscardRequests(reqs) + for nch := range chans { + if nch.ChannelType() != "session" { + nch.Reject(ssh.UnknownChannelType, "no") + continue + } + ch, creqs, err := nch.Accept() + if err != nil { + continue + } + go func() { + for req := range creqs { + switch req.Type { + case "subsystem": + if len(req.Payload) > 4 && string(req.Payload[4:]) == "sftp" { + req.Reply(true, nil) + srv, _ := sftp.NewServer(ch) + go func() { srv.Serve(); ch.Close() }() + continue + } + req.Reply(false, nil) + case "exec": + cmdLen := binary.BigEndian.Uint32(req.Payload) + cmdStr := string(req.Payload[4 : 4+cmdLen]) + req.Reply(true, nil) + go func() { + c := exec.Command("sh", "-c", cmdStr) + c.Stdout = ch + c.Stderr = ch.Stderr() + code := 0 + if err := c.Run(); err != nil { + code = 1 + if ee, ok := err.(*exec.ExitError); ok { + code = ee.ExitCode() + } + } + st := make([]byte, 4) + binary.BigEndian.PutUint32(st, uint32(code)) + ch.SendRequest("exit-status", false, st) + ch.Close() + }() + default: + req.Reply(false, nil) + } + } + }() + } +} + +// toxicProxy forwards TCP to target; can delay, freeze, or cut after N bytes +// (client->server direction). +type toxicProxy struct { + addr string + delay time.Duration + frozen atomic.Bool + cutAfter atomic.Int64 // 0 = never; bytes client->server before hard close + sent atomic.Int64 + mu sync.Mutex + conns []net.Conn +} + +func startProxy(t *testing.T, target string, delay time.Duration) *toxicProxy { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &toxicProxy{addr: ln.Addr().String(), delay: delay} + t.Cleanup(func() { ln.Close(); p.killAll() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + u, err := net.Dial("tcp", target) + if err != nil { + c.Close() + continue + } + p.mu.Lock() + p.conns = append(p.conns, c, u) + p.mu.Unlock() + go p.pipe(c, u, true) + go p.pipe(u, c, false) + } + }() + return p +} + +func (p *toxicProxy) killAll() { + p.mu.Lock() + defer p.mu.Unlock() + for _, c := range p.conns { + c.Close() + } +} + +type chunk struct { + b []byte + at time.Time +} + +func (p *toxicProxy) pipe(src, dst net.Conn, upstream bool) { + q := make(chan chunk, 4096) + go func() { + for c := range q { + if d := time.Until(c.at); d > 0 { + time.Sleep(d) + } + for p.frozen.Load() { + time.Sleep(10 * time.Millisecond) + } + if _, err := dst.Write(c.b); err != nil { + return + } + } + }() + buf := make([]byte, 64*1024) + for { + n, err := src.Read(buf) + if n > 0 { + if upstream { + total := p.sent.Add(int64(n)) + if lim := p.cutAfter.Load(); lim > 0 && total > lim { + p.killAll() + close(q) + return + } + } + b := append([]byte(nil), buf[:n]...) + q <- chunk{b: b, at: time.Now().Add(p.delay)} + } + if err != nil { + close(q) + return + } + } +} + +// setupHome points HOME at a temp dir so known_hosts writes are isolated. +func setupHome(t *testing.T) string { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("SSH_AUTH_SOCK", "") + os.MkdirAll(filepath.Join(home, ".ssh"), 0o700) + return home +} + +func hostFor(addr, hostname string) SSHHost { + _, port, _ := net.SplitHostPort(addr) + return SSHHost{Name: hostname, HostName: hostname, Port: port, User: "u", Password: "pw"} +} + +func mustConnect(t *testing.T, h SSHHost) *SSHClient { + t.Helper() + c, err := Connect(h) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { c.Close() }) + return c +} + +func writeFile(t *testing.T, p string, size int, mode os.FileMode) { + t.Helper() + os.MkdirAll(filepath.Dir(p), 0o755) + b := make([]byte, size) + rand.Read(b) + if err := os.WriteFile(p, b, mode); err != nil { + t.Fatal(err) + } + os.Chmod(p, mode) +} + +var _ = io.EOF diff --git a/plans/rework/testbed/remote_samehost_test.go.txt b/plans/rework/testbed/remote_samehost_test.go.txt new file mode 100644 index 0000000..d6db36a --- /dev/null +++ b/plans/rework/testbed/remote_samehost_test.go.txt @@ -0,0 +1,30 @@ +package remote + +import ( + "os" + "path/filepath" + "testing" +) + +// Reproduces model.go same-host branch: Exec("cp -r src dst") / Exec("mv src dst") +// where dst = targetDir/base(src) already exists as a directory. +func TestSameHostCpIntoExistingDir(t *testing.T) { + _, c, dir := setup(t) + src := filepath.Join(dir, "A", "proj") + writeFile(t, filepath.Join(src, "new.txt"), 5, 0o644) + dst := filepath.Join(dir, "B", "proj") + writeFile(t, filepath.Join(dst, "old.txt"), 5, 0o644) + out, err := c.Exec("cp -r " + ShellQuote(src) + " " + ShellQuote(dst)) + t.Logf("cp out=%q err=%v", out, err) + if _, e := os.Stat(filepath.Join(dst, "proj", "new.txt")); e == nil { + t.Errorf("BUG CONFIRMED: cp -r nested source into %s/proj/ instead of merging", dst) + } + src2 := filepath.Join(dir, "A", "proj2") + writeFile(t, filepath.Join(src2, "x.txt"), 5, 0o644) + dst2 := filepath.Join(dir, "B", "proj2") + os.MkdirAll(dst2, 0o755) + _, err = c.Exec("mv " + ShellQuote(src2) + " " + ShellQuote(dst2)) + if _, e := os.Stat(filepath.Join(dst2, "proj2", "x.txt")); e == nil { + t.Errorf("BUG CONFIRMED: mv moved source into %s/proj2/ (err=%v)", dst2, err) + } +} diff --git a/plans/rework/testbed/ui_analysis_test.go.txt b/plans/rework/testbed/ui_analysis_test.go.txt new file mode 100644 index 0000000..312baed --- /dev/null +++ b/plans/rework/testbed/ui_analysis_test.go.txt @@ -0,0 +1,264 @@ +package ui + +import ( + "fmt" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" + + "vcom/internal/config" + vfs "vcom/internal/fs" +) + +var scratch = os.Getenv("VCOM_SCRATCH") + +func newTestModel(t testing.TB, left, right string) Model { + t.Helper() + os.Setenv("XDG_CONFIG_HOME", filepath.Join(scratch, "xdg")) + os.Setenv("HOME", filepath.Join(scratch, "home")) + os.MkdirAll(filepath.Join(scratch, "home"), 0o755) + cfg := config.Default() + cfg.UI.IconMode = "ascii" + cfg.Startup.LeftPath = left + cfg.Startup.RightPath = right + m, err := NewModel(cfg, "") + if err != nil { + t.Fatal(err) + } + mm, _ := m.Update(tea.WindowSizeMsg{Width: 200, Height: 60}) + return asM(mm) +} + +func kk(s string) tea.KeyMsg { + switch s { + case "enter": + return tea.KeyMsg{Type: tea.KeyEnter} + case "esc": + return tea.KeyMsg{Type: tea.KeyEsc} + case "pgdown": + return tea.KeyMsg{Type: tea.KeyPgDown} + } + return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} +} + +// 1. Caret mode panics when color profile is Ascii (NO_COLOR / non-tty). +func TestCaretPanicAscii(t *testing.T) { + lipgloss.SetColorProfile(termenv.Ascii) + m := newTestModel(t, scratch, scratch) + m.previewData = vfs.Preview{Kind: vfs.PreviewKindText, Body: "hello\nworld", PlainBody: "hello\nworld"} + m.infoMode = true + defer func() { + if r := recover(); r != nil { + t.Logf("CONFIRMED PANIC in caret mode with Ascii profile: %v", r) + } + }() + m.toggleCaretMode() + t.Logf("no panic") +} + +// 2. PgDown does nothing. +func TestPageDown(t *testing.T) { + m := newTestModel(t, filepath.Join(scratch, "big"), scratch) + before := m.left.Cursor + mm, _ := m.Update(kk("pgdown")) + t.Logf("PgDown: cursor before=%d after=%d", before, asM(mm).left.Cursor) +} + +// 3. Cyrillic typed into rename modal is converted to latin. +func TestCyrillicInMkdir(t *testing.T) { + m := newTestModel(t, scratch, scratch) + m.openMkdirModal() + var mm tea.Model = m + for _, r := range "папка" { + mm, _ = asM(mm).Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) + } + t.Logf("typed 'папка' into mkdir modal -> input value=%q", asM(mm).modal.input.Value()) +} + +// 4. 'q' in normal mode quits even when filter/info is active. +func TestQQuits(t *testing.T) { + m := newTestModel(t, scratch, scratch) + m.infoMode = true + _, cmd := m.Update(kk("q")) + if cmd != nil { + msg := cmd() + _, isQuit := msg.(tea.QuitMsg) + t.Logf("q with info pane open -> quit=%v", isQuit) + } +} + +// 5. Symlinked directory: category and enter. +func TestSymlinkDir(t *testing.T) { + d := filepath.Join(scratch, "symt") + os.RemoveAll(d) + os.MkdirAll(filepath.Join(d, "realdir"), 0o755) + os.Symlink(filepath.Join(d, "realdir"), filepath.Join(d, "linkdir")) + entries, _ := vfs.ListDir(d, vfs.ListOptions{ShowHidden: true, DirsFirst: true, SortBy: "name"}) + for _, e := range entries { + t.Logf("entry %q isDir=%v category=%s", e.Name, e.IsDir, e.Category()) + } +} + +// 6. Filter + mouse click mismatch. +func TestFilterMouse(t *testing.T) { + d := filepath.Join(scratch, "filt") + os.RemoveAll(d) + os.MkdirAll(d, 0o755) + for _, n := range []string{"a1", "b1", "b2", "c1", "zz-target"} { + os.WriteFile(filepath.Join(d, n), []byte("x"), 0o644) + } + m := newTestModel(t, d, d) + m.filterQuery = "zz" + m.filterPaneID = PaneLeft + // visible rows: ".." then "zz-target" (2nd row) at y = 3 + 1 + mm, _ := m.Update(tea.MouseMsg{X: 5, Y: 4, Action: tea.MouseActionPress, Button: tea.MouseButtonLeft}) + mm2 := asM(mm); sel, _ := mm2.left.Selected() + t.Logf("filter=zz, clicked 2nd visible row (zz-target), real selection=%q", sel.Name) +} + +// 7. Filter not reset on directory change, and cursor on hidden entry. +func TestFilterHiddenSelection(t *testing.T) { + d := filepath.Join(scratch, "filt") + m := newTestModel(t, d, d) + m.left.Cursor = 2 // b1 + m.filterQuery = "nomatch" + m.filterPaneID = PaneLeft + m.snapFilterCursor() + sel, _ := m.left.Selected() + fp := m.filteredPane(m.left) + t.Logf("filter with no match: visible=%d, real selected=%q (operations would target it)", len(fp.Entries), sel.Name) +} + +// 8. Preview stale for empty dir ("Nothing selected" never applied). +func TestEmptyDirPreview(t *testing.T) { + d := filepath.Join(scratch, "emptyroot") + os.MkdirAll(d, 0o755) + m := newTestModel(t, scratch, scratch) + m.previewData = vfs.Preview{Kind: vfs.PreviewKindText, Title: "OLD"} + m.left.Entries = nil + msg := m.loadPreviewCmd()() + mm, _ := m.Update(msg) + t.Logf("empty pane preview title after previewMsg: %q", asM(mm).previewData.Title) +} + +// 9. Passive pane cursor reset after operation reload. +func TestPassiveCursorReset(t *testing.T) { + d := filepath.Join(scratch, "big") + m := newTestModel(t, filepath.Join(scratch, "filt"), d) + m.right.Cursor = 500 + _ = m.reloadPane(PaneRight, selectedName(&m.left)) + t.Logf("passive pane cursor after reload with active selection name: 500 -> %d", m.right.Cursor) +} + +// 10. FIFO preview blocks. +func TestFifoPreview(t *testing.T) { + p := filepath.Join(scratch, "fifo") + os.Remove(p) + if err := syscall.Mkfifo(p, 0o644); err != nil { + t.Skip(err) + } + info, _ := os.Lstat(p) + e := vfs.Entry{Name: "fifo", Path: p, Mode: info.Mode()} + done := make(chan struct{}) + go func() { vfs.BuildPreview(e, vfs.PreviewOptions{MaxPreviewBytes: 65536}); close(done) }() + select { + case <-done: + t.Logf("fifo preview returned") + case <-time.After(2 * time.Second): + t.Logf("CONFIRMED: BuildPreview on FIFO blocked >2s (goroutine leak)") + } +} + +// 11. Delete toggle default +func TestDeleteDefault(t *testing.T) { + d := filepath.Join(scratch, "filt") + m := newTestModel(t, d, d) + m.left.Cursor = 1 + m.handleDelete() + t.Logf("delete modal title=%q deleteKind=%s", m.modal.title, m.deleteKind) + _, _ = m.handleModalKey(kk("n")) + t.Logf("after 'n' modal kind still=%d (0=closed)", m.modal.kind) +} + +func benchModel(b *testing.B) Model { + return newTestModel(b, filepath.Join(scratch, "big"), filepath.Join(scratch, "big")) +} + +func BenchmarkView20k(b *testing.B) { + lipgloss.SetColorProfile(termenv.TrueColor) + m := benchModel(b) + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = m.View() + } +} + +func BenchmarkView20kFiltered(b *testing.B) { + lipgloss.SetColorProfile(termenv.TrueColor) + m := benchModel(b) + m.filterQuery = "file_1" + m.filterPaneID = PaneLeft + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = m.View() + } +} + +func BenchmarkKeyDownUpdateView(b *testing.B) { + lipgloss.SetColorProfile(termenv.TrueColor) + m := benchModel(b) + b.ResetTimer() + var mm tea.Model = m + for i := 0; i < b.N; i++ { + mm, _ = asM(mm).Update(kk("j")) + _ = mm.View() + } +} + +func BenchmarkReloadPane20k(b *testing.B) { + m := benchModel(b) + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = m.reloadPane(PaneLeft, "") + } +} + +func BenchmarkCaretMove64k(b *testing.B) { + lipgloss.SetColorProfile(termenv.TrueColor) + m := newTestModel(b, scratch, scratch) + src, _ := os.ReadFile(filepath.Join(scratch, "big.go")) + p := vfs.BuildPreview(vfs.Entry{Name: "big.go", Path: filepath.Join(scratch, "big.go"), Extension: "go", Size: int64(len(src))}, vfs.PreviewOptions{MaxPreviewBytes: 65536, ThemeName: "catppuccin-mocha"}) + m.infoMode = true + m.resizePreview() + m.applyPreview(p) + m.toggleCaretMode() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.moveTextCursorLine(1) + } +} + +func BenchmarkKittyPayload(b *testing.B) { + path := filepath.Join(scratch, "big.png") + for i := 0; i < b.N; i++ { + _, _, err := loadKittyPayload(path, overlayRect{width: 80, height: 40}) + if err != nil { + b.Fatal(err) + } + } +} + +var _ = fmt.Sprintf + +func asM(x tea.Model) Model { + if p, ok := x.(*Model); ok { + return *p + } + return x.(Model) +} diff --git a/vcom-0.2.5-1-x86_64.pkg.tar.zst b/vcom-0.2.5-1-x86_64.pkg.tar.zst deleted file mode 100644 index c099bd0..0000000 Binary files a/vcom-0.2.5-1-x86_64.pkg.tar.zst and /dev/null differ diff --git a/vcom-0.2.5.tar.gz b/vcom-0.2.5.tar.gz deleted file mode 100644 index c3d87a9..0000000 Binary files a/vcom-0.2.5.tar.gz and /dev/null differ diff --git a/vcom.toml b/vcom.toml index ea51e44..5d2229d 100644 --- a/vcom.toml +++ b/vcom.toml @@ -1,17 +1,21 @@ +# vcom reference configuration. +# Copy to ~/.config/vcom/vcom.toml (or $XDG_CONFIG_HOME/vcom/vcom.toml) and edit. +# Every key is optional; missing keys keep their defaults. + [startup] +# Start directories; empty means the home directory (a saved session wins). left_path = '' right_path = '' [ui] -app_title = 'vcom' +# Theme name; `t` in vcom opens the selector and rewrites only this line. theme = 'github-dark' -icon_mode = 'auto' -show_title_bar = true +icon_mode = 'auto' # auto | nerd | ascii show_footer = true border = 'rounded' path_display = 'smart' -pane_gap = 1 -center_width_percent = 30 +pane_gap = 1 # 0..4 +preview_width_percent = 50 # preview width in the Info screen, 20..80 [browser] show_hidden = true @@ -19,14 +23,14 @@ dirs_first = true human_readable_size = true [browser.sort] -by = 'name' +by = 'name' # name | modified | size | created | extension reverse = false [browser.columns] name = true size = true modified = true -created = false +created = false # birth time; computed only when this column is on permissions = false extension = false @@ -35,11 +39,22 @@ show_metadata = true wrap_text = false max_preview_bytes = 65536 directory_preview_limit = 80 +image_backend = 'auto' # auto | kitty | ueberzugpp | none +max_remote_image_bytes = 20971520 [behavior] -confirm_delete = true +confirm_delete = true # ask before moving to the trash confirm_overwrite = true calculate_dir_size_on_space = true -follow_symlinks = false -auto_refresh = true -auto_refresh_interval = 5 +follow_symlinks = false # default of "follow links" in the copy dialog +confirm_quit = true + +[transfer] +on_conflict = 'ask' # ask | overwrite | skip | newer | rename +preserve = true # keep permissions and modification times +fsync = 'replace' # replace | always | never +max_parallel_jobs = 2 + +[ssh] +keepalive_interval = '15s' +connect_timeout = '20s' diff --git a/vendor/github.com/kevinburke/ssh_config/.gitignore b/vendor/github.com/kevinburke/ssh_config/.gitignore new file mode 100644 index 0000000..46620af --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/.gitignore @@ -0,0 +1 @@ +/coverage.out diff --git a/vendor/github.com/kevinburke/ssh_config/.mailmap b/vendor/github.com/kevinburke/ssh_config/.mailmap new file mode 100644 index 0000000..253406b --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/.mailmap @@ -0,0 +1 @@ +Kevin Burke Kevin Burke diff --git a/vendor/github.com/kevinburke/ssh_config/AUTHORS.txt b/vendor/github.com/kevinburke/ssh_config/AUTHORS.txt new file mode 100644 index 0000000..7510398 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/AUTHORS.txt @@ -0,0 +1,13 @@ +Carlos A Becker +Claude Opus 4.6 +Dustin Spicuzza +Eugene Terentev +Kevin Burke +Mark Nevill +Neil Williams +Scott Lessans +Sergey Lukjanov +Simon Josefsson +Wayne Ashley Berry +santosh653 <70637961+santosh653@users.noreply.github.com> +sio2boss diff --git a/vendor/github.com/kevinburke/ssh_config/CHANGELOG.md b/vendor/github.com/kevinburke/ssh_config/CHANGELOG.md new file mode 100644 index 0000000..8670983 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/CHANGELOG.md @@ -0,0 +1,65 @@ +# Changes + +## Version 1.6 (released February 16, 2026) + +- Support `~` as the user's home directory in `Include` directives, matching +the behavior described in ssh_config(5). Thanks to Neil Williams for the report +(#31). + +- Strip surrounding double quotes from parsed values. OpenSSH allows values +like `IdentityFile "/path/to/file"`, but Get/GetAll previously returned the +quotes as literal characters. Quotes are now stripped from the returned value +while preserving the original text for faithful roundtripping via String() and +MarshalText(). Thanks to Furkan Türkal for the report (#61). + +- Default to a space before `#` in end-of-line comments. When a Host or KV is +created programmatically with an EOLComment, the output previously had no space +before the `#` (e.g. `Host foo#comment`). A single space is now inserted by +default. Thanks to Yonghui Cheng for the report (#50). + +## Version 1.5 (released February 14, 2026) + +- Implement Match support. Most of the Match spec is implemented, including +`Match host`, `Match originalhost`, `Match user`, `Match localuser`, and `Match +all`. `Match exec` is not yet implemented. + +- Add SECURITY.md + +- Add Dependabot configuration + +## Version 1.4 (released August 19, 2025) + +- Remove .gitattributes file (which was used to test different line endings, and +caused issues in some build environments). Store tests/dos-lines as CRLF in git +directly instead. + +## Version 1.3 (released February 20, 2025) + +- Add go.mod file (although this project has no dependencies). + +- config: add UserSettings.ConfigFinder + +- Various updates to CI and build environment + +## Version 1.2 (released March 31, 2022) + +- config: add DecodeBytes to directly read a byte array. + +- Strip trailing whitespace from Host declarations and key/value pairs. +Previously, if a Host declaration or a value had trailing whitespace, that +whitespace would have been included as part of the value. This led to unexpected +consequences. For example: + +``` +Host example # A comment + HostName example.com # Another comment +``` + +Prior to version 1.2, the value for Host would have been "example " and the +value for HostName would have been "example.com ". Both of these are +unintuitive. + +Instead, we strip the trailing whitespace in the configuration, which leads to +more intuitive behavior. + +- Add fuzz tests. diff --git a/vendor/github.com/kevinburke/ssh_config/LICENSE b/vendor/github.com/kevinburke/ssh_config/LICENSE new file mode 100644 index 0000000..b9a770a --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/LICENSE @@ -0,0 +1,49 @@ +Copyright (c) 2017 Kevin Burke. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +=================== + +The lexer and parser borrow heavily from github.com/pelletier/go-toml. The +license for that project is copied below. + +The MIT License (MIT) + +Copyright (c) 2013 - 2017 Thomas Pelletier, Eric Anderton + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/kevinburke/ssh_config/Makefile b/vendor/github.com/kevinburke/ssh_config/Makefile new file mode 100644 index 0000000..aa946eb --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/Makefile @@ -0,0 +1,34 @@ +BUMP_VERSION := $(GOPATH)/bin/bump_version +WRITE_MAILMAP := $(GOPATH)/bin/write_mailmap + +lint: + go vet ./... + go run honnef.co/go/tools/cmd/staticcheck@latest ./... + go run github.com/kevinburke/differ@latest gofmt -s -w . + +test: + @# the timeout helps guard against infinite recursion + go test -timeout=250ms ./... + +race-test: + go test -timeout=500ms -race ./... + +coverage: + go test -trimpath -timeout=250ms -coverprofile=coverage.out -covermode=atomic ./... + go tool cover -func=coverage.out + +$(BUMP_VERSION): + go get -u github.com/kevinburke/bump_version + +$(WRITE_MAILMAP): + go get -u github.com/kevinburke/write_mailmap + +release: test | $(BUMP_VERSION) + $(BUMP_VERSION) --tag-prefix=v minor config.go + +force: ; + +AUTHORS.txt: force | $(WRITE_MAILMAP) + $(WRITE_MAILMAP) > AUTHORS.txt + +authors: AUTHORS.txt diff --git a/vendor/github.com/kevinburke/ssh_config/README.md b/vendor/github.com/kevinburke/ssh_config/README.md new file mode 100644 index 0000000..705605e --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/README.md @@ -0,0 +1,92 @@ +# ssh_config + +This is a Go parser for `ssh_config` files. Importantly, this parser attempts +to preserve comments in a given file, so you can manipulate a `ssh_config` file +from a program, if your heart desires. + +It's designed to be used with the excellent +[x/crypto/ssh](https://golang.org/x/crypto/ssh) package, which handles SSH +negotiation but isn't very easy to configure. + +The `ssh_config` `Get()` and `GetStrict()` functions will attempt to read values +from `$HOME/.ssh/config` and fall back to `/etc/ssh/ssh_config`. The first +argument is the host name to match on, and the second argument is the key you +want to retrieve. + +```go +port := ssh_config.Get("myhost", "Port") +``` + +Certain directives can occur multiple times for a host (such as `IdentityFile`), +so you should use the `GetAll` or `GetAllStrict` directive to retrieve those +instead. + +```go +files := ssh_config.GetAll("myhost", "IdentityFile") +``` + +You can also load a config file and read values from it. + +```go +var config = ` +Host *.test + Compression yes +` + +cfg, err := ssh_config.Decode(strings.NewReader(config)) +fmt.Println(cfg.Get("example.test", "Port")) +``` + +Some SSH arguments have default values - for example, the default value for +`KeyboardAuthentication` is `"yes"`. If you call Get(), and no value for the +given Host/keyword pair exists in the config, we'll return a default for the +keyword if one exists. + +### Manipulating SSH config files + +Here's how you can manipulate an SSH config file, and then write it back to +disk. + +```go +f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) +cfg, _ := ssh_config.Decode(f) +for _, host := range cfg.Hosts { + fmt.Println("patterns:", host.Patterns) + for _, node := range host.Nodes { + // Manipulate the nodes as you see fit, or use a type switch to + // distinguish between Empty, KV, and Include nodes. + fmt.Println(node.String()) + } +} + +// Print the config to stdout: +fmt.Println(cfg.String()) +``` + +## Spec compliance + +Wherever possible we try to implement the specification as documented in +the `ssh_config` manpage. Unimplemented features should be present in the +[issues][issues] list. + +Notably, the `Match` directive is currently unsupported. + +[issues]: https://github.com/kevinburke/ssh_config/issues + +## Errata + +This is the second [comment-preserving configuration parser][blog] I've written, after +[an /etc/hosts parser][hostsfile]. Eventually, I will write one for every Linux +file format. + +[blog]: https://kev.inburke.com/kevin/more-comment-preserving-configuration-parsers/ +[hostsfile]: https://github.com/kevinburke/hostsfile + +## Sponsorships + +Thank you very much to Tailscale and Indeed for sponsoring development of this +library. [Sponsors][sponsors] will get their names featured in the README. + +You can also reach out about a consulting engagement: https://burke.services + +[sponsors]: https://github.com/sponsors/kevinburke diff --git a/vendor/github.com/kevinburke/ssh_config/SECURITY.md b/vendor/github.com/kevinburke/ssh_config/SECURITY.md new file mode 100644 index 0000000..adc2c5a --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/SECURITY.md @@ -0,0 +1,63 @@ +# ssh_config security policy + +## Supported Versions + +As of September 2025, we're not aware of any security problems with ssh_config, +past or present. That said, we recommend always using the latest version of +ssh_config, and of the Go programming language, to ensure you have the most +recent security fixes. + +## Reporting a Vulnerability + +We take security vulnerabilities seriously. If you discover a security vulnerability in ssh_config, please report it responsibly by following these steps: + +### How to Report + +Please follow the instructions outlined here to report a vulnerability +privately: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability + +If these are insufficient - it is not hard to find Kevin's contact information +on the Internet. + +### What to Include + +When reporting a vulnerability, please include a clear description of the vulnerability, steps to reproduce the issue, the potential impact, as well as any fixes you might have. + +### Response Timeline + +I'll try to acknowledge and patch the issue as quickly as possible. + +Security advisories for this project will be published through: +- GitHub Security Advisories on this repository +- an Issue on this repository +- The project's release notes +- Go vulnerability databases + +If you are using `ssh_config` and would like to be on a "pre-release" +distribution list for coordinating releases, please contact Kevin directly. + +### Security Considerations + +When using ssh_config, please be aware of these security considerations. + +#### File System Access + +This library reads SSH configuration files from the file system. Try to ensure +proper file permissions on SSH config files (typically 600 or 644), and be +cautious when parsing config files from untrusted sources. + +#### Input Validation + +The parser handles user-provided SSH configuration data. While we try our best +to parse the data appropriately, malformed configuration files could potentially +cause issues. Please try to validate and sanitize any configuration data from +external sources. + +#### Dependencies + +This project does not have any third party dependencies. Please try to keep your +Go version up to date. + +## Acknowledgments + +We appreciate security researchers and users who responsibly disclose vulnerabilities. Contributors who report valid security issues will be acknowledged in our security advisories (unless they prefer to remain anonymous). diff --git a/vendor/github.com/kevinburke/ssh_config/config.go b/vendor/github.com/kevinburke/ssh_config/config.go new file mode 100644 index 0000000..6365b41 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/config.go @@ -0,0 +1,878 @@ +// Package ssh_config provides tools for manipulating SSH config files. +// +// Importantly, this parser attempts to preserve comments in a given file, so +// you can manipulate a `ssh_config` file from a program, if your heart desires. +// +// The Get() and GetStrict() functions will attempt to read values from +// $HOME/.ssh/config, falling back to /etc/ssh/ssh_config. The first argument is +// the host name to match on ("example.com"), and the second argument is the key +// you want to retrieve ("Port"). The keywords are case insensitive. +// +// port := ssh_config.Get("myhost", "Port") +// +// You can also manipulate an SSH config file and then print it or write it back +// to disk. +// +// f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) +// cfg, _ := ssh_config.Decode(f) +// for _, host := range cfg.Hosts { +// fmt.Println("patterns:", host.Patterns) +// for _, node := range host.Nodes { +// fmt.Println(node.String()) +// } +// } +// +// // Write the cfg back to disk: +// fmt.Println(cfg.String()) +package ssh_config + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + osuser "os/user" + "path/filepath" + "regexp" + "runtime" + "strings" + "sync" +) + +const version = "1.6.0" + +var _ = version + +type configFinder func() string + +// UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config +// files are parsed and cached the first time Get() or GetStrict() is called. +type UserSettings struct { + IgnoreErrors bool + customConfig *Config + customConfigFinder configFinder + systemConfig *Config + systemConfigFinder configFinder + userConfig *Config + userConfigFinder configFinder + loadConfigs sync.Once + onceErr error +} + +func homedir() string { + user, err := osuser.Current() + if err == nil { + return user.HomeDir + } else { + return os.Getenv("HOME") + } +} + +func userConfigFinder() string { + return filepath.Join(homedir(), ".ssh", "config") +} + +// DefaultUserSettings is the default UserSettings and is used by Get and +// GetStrict. It checks both $HOME/.ssh/config and /etc/ssh/ssh_config for keys, +// and it will return parse errors (if any) instead of swallowing them. +var DefaultUserSettings = &UserSettings{ + IgnoreErrors: false, + systemConfigFinder: systemConfigFinder, + userConfigFinder: userConfigFinder, +} + +func systemConfigFinder() string { + return filepath.Join("/", "etc", "ssh", "ssh_config") +} + +func findVal(c *Config, alias, key string) (string, error) { + if c == nil { + return "", nil + } + val, err := c.Get(alias, key) + if err != nil || val == "" { + return "", err + } + if err := validate(key, val); err != nil { + return "", err + } + return val, nil +} + +func findAll(c *Config, alias, key string) ([]string, error) { + if c == nil { + return nil, nil + } + return c.GetAll(alias, key) +} + +// Get finds the first value for key within a declaration that matches the +// alias. Get returns the empty string if no value was found, or if IgnoreErrors +// is false and we could not parse the configuration file. Use GetStrict to +// disambiguate the latter cases. +// +// The match for key is case insensitive. +// +// Get is a wrapper around DefaultUserSettings.Get. +func Get(alias, key string) string { + return DefaultUserSettings.Get(alias, key) +} + +// GetAll retrieves zero or more directives for key for the given alias. GetAll +// returns nil if no value was found, or if IgnoreErrors is false and we could +// not parse the configuration file. Use GetAllStrict to disambiguate the +// latter cases. +// +// In most cases you want to use Get or GetStrict, which returns a single value. +// However, a subset of ssh configuration values (IdentityFile, for example) +// allow you to specify multiple directives. +// +// The match for key is case insensitive. +// +// GetAll is a wrapper around DefaultUserSettings.GetAll. +func GetAll(alias, key string) []string { + return DefaultUserSettings.GetAll(alias, key) +} + +// GetStrict finds the first value for key within a declaration that matches the +// alias. If key has a default value and no matching configuration is found, the +// default will be returned. For more information on default values and the way +// patterns are matched, see the manpage for ssh_config. +// +// The returned error will be non-nil if and only if a user's configuration file +// or the system configuration file could not be parsed, and u.IgnoreErrors is +// false. +// +// GetStrict is a wrapper around DefaultUserSettings.GetStrict. +func GetStrict(alias, key string) (string, error) { + return DefaultUserSettings.GetStrict(alias, key) +} + +// GetAllStrict retrieves zero or more directives for key for the given alias. +// +// In most cases you want to use Get or GetStrict, which returns a single value. +// However, a subset of ssh configuration values (IdentityFile, for example) +// allow you to specify multiple directives. +// +// The returned error will be non-nil if and only if a user's configuration file +// or the system configuration file could not be parsed, and u.IgnoreErrors is +// false. +// +// GetAllStrict is a wrapper around DefaultUserSettings.GetAllStrict. +func GetAllStrict(alias, key string) ([]string, error) { + return DefaultUserSettings.GetAllStrict(alias, key) +} + +// Get finds the first value for key within a declaration that matches the +// alias. Get returns the empty string if no value was found, or if IgnoreErrors +// is false and we could not parse the configuration file. Use GetStrict to +// disambiguate the latter cases. +// +// The match for key is case insensitive. +func (u *UserSettings) Get(alias, key string) string { + val, err := u.GetStrict(alias, key) + if err != nil { + return "" + } + return val +} + +// GetAll retrieves zero or more directives for key for the given alias. GetAll +// returns nil if no value was found, or if IgnoreErrors is false and we could +// not parse the configuration file. Use GetStrict to disambiguate the latter +// cases. +// +// The match for key is case insensitive. +func (u *UserSettings) GetAll(alias, key string) []string { + val, _ := u.GetAllStrict(alias, key) + return val +} + +// GetStrict finds the first value for key within a declaration that matches the +// alias. If key has a default value and no matching configuration is found, the +// default will be returned. For more information on default values and the way +// patterns are matched, see the manpage for ssh_config. +// +// error will be non-nil if and only if a user's configuration file or the +// system configuration file could not be parsed, and u.IgnoreErrors is false. +func (u *UserSettings) GetStrict(alias, key string) (string, error) { + u.doLoadConfigs() + //lint:ignore S1002 I prefer it this way + if u.onceErr != nil && u.IgnoreErrors == false { + return "", u.onceErr + } + // TODO this is getting repetitive + if u.customConfig != nil { + val, err := findVal(u.customConfig, alias, key) + if err != nil || val != "" { + return val, err + } + } + val, err := findVal(u.userConfig, alias, key) + if err != nil || val != "" { + return val, err + } + val2, err2 := findVal(u.systemConfig, alias, key) + if err2 != nil || val2 != "" { + return val2, err2 + } + return Default(key), nil +} + +// GetAllStrict retrieves zero or more directives for key for the given alias. +// If key has a default value and no matching configuration is found, the +// default will be returned. For more information on default values and the way +// patterns are matched, see the manpage for ssh_config. +// +// The returned error will be non-nil if and only if a user's configuration file +// or the system configuration file could not be parsed, and u.IgnoreErrors is +// false. +func (u *UserSettings) GetAllStrict(alias, key string) ([]string, error) { + u.doLoadConfigs() + //lint:ignore S1002 I prefer it this way + if u.onceErr != nil && u.IgnoreErrors == false { + return nil, u.onceErr + } + if u.customConfig != nil { + val, err := findAll(u.customConfig, alias, key) + if err != nil || val != nil { + return val, err + } + } + val, err := findAll(u.userConfig, alias, key) + if err != nil || val != nil { + return val, err + } + val2, err2 := findAll(u.systemConfig, alias, key) + if err2 != nil || val2 != nil { + return val2, err2 + } + // TODO: IdentityFile has multiple default values that we should return. + if def := Default(key); def != "" { + return []string{def}, nil + } + return []string{}, nil +} + +// ConfigFinder will invoke f to try to find a ssh config file in a custom +// location on disk, instead of in /etc/ssh or $HOME/.ssh. f should return the +// name of a file containing SSH configuration. +// +// ConfigFinder must be invoked before any calls to Get or GetStrict and panics +// if f is nil. Most users should not need to use this function. +func (u *UserSettings) ConfigFinder(f func() string) { + if f == nil { + panic("cannot call ConfigFinder with nil function") + } + u.customConfigFinder = f +} + +func (u *UserSettings) doLoadConfigs() { + u.loadConfigs.Do(func() { + var filename string + var err error + if u.customConfigFinder != nil { + filename = u.customConfigFinder() + u.customConfig, err = parseFile(filename) + // IsNotExist should be returned because a user specified this + // function - not existing likely means they made an error + if err != nil { + u.onceErr = err + } + return + } + if u.userConfigFinder == nil { + filename = userConfigFinder() + } else { + filename = u.userConfigFinder() + } + u.userConfig, err = parseFile(filename) + //lint:ignore S1002 I prefer it this way + if err != nil && os.IsNotExist(err) == false { + u.onceErr = err + return + } + if u.systemConfigFinder == nil { + filename = systemConfigFinder() + } else { + filename = u.systemConfigFinder() + } + u.systemConfig, err = parseFile(filename) + //lint:ignore S1002 I prefer it this way + if err != nil && os.IsNotExist(err) == false { + u.onceErr = err + return + } + }) +} + +func parseFile(filename string) (*Config, error) { + return parseWithDepth(filename, 0) +} + +func parseWithDepth(filename string, depth uint8) (*Config, error) { + b, err := os.ReadFile(filename) + if err != nil { + return nil, err + } + return decodeBytes(b, isSystem(filename), depth) +} + +func isSystem(filename string) bool { + // TODO: not sure this is the best way to detect a system repo + return strings.HasPrefix(filepath.Clean(filename), "/etc/ssh") +} + +// Decode reads r into a Config, or returns an error if r could not be parsed as +// an SSH config file. +func Decode(r io.Reader) (*Config, error) { + b, err := io.ReadAll(r) + if err != nil { + return nil, err + } + return decodeBytes(b, false, 0) +} + +// DecodeBytes reads b into a Config, or returns an error if r could not be +// parsed as an SSH config file. +func DecodeBytes(b []byte) (*Config, error) { + return decodeBytes(b, false, 0) +} + +func decodeBytes(b []byte, system bool, depth uint8) (c *Config, err error) { + defer func() { + if r := recover(); r != nil { + if _, ok := r.(runtime.Error); ok { + panic(r) + } + if e, ok := r.(error); ok && e == ErrDepthExceeded { + err = e + return + } + err = errors.New(r.(string)) + } + }() + + c = parseSSH(lexSSH(b), system, depth) + return c, err +} + +// Config represents an SSH config file. +type Config struct { + // A list of hosts to match against. The file begins with an implicit + // "Host *" declaration matching all hosts. + Hosts []*Host + depth uint8 + position Position +} + +// Get finds the first value in the configuration that matches the alias and +// contains key. Get returns the empty string if no value was found, or if the +// Config contains an invalid conditional Include value. +// +// The match for key is case insensitive. +func (c *Config) Get(alias, key string) (string, error) { + lowerKey := strings.ToLower(key) + for _, host := range c.Hosts { + if !host.Matches(alias) { + continue + } + for _, node := range host.Nodes { + switch t := node.(type) { + case *Empty: + continue + case *KV: + // "keys are case insensitive" per the spec + lkey := strings.ToLower(t.Key) + if lkey == lowerKey { + return t.Value, nil + } + case *Include: + val := t.Get(alias, key) + if val != "" { + return val, nil + } + default: + return "", fmt.Errorf("unknown Node type %v", t) + } + } + } + return "", nil +} + +// GetAll returns all values in the configuration that match the alias and +// contains key, or nil if none are present. +func (c *Config) GetAll(alias, key string) ([]string, error) { + lowerKey := strings.ToLower(key) + all := []string(nil) + for _, host := range c.Hosts { + if !host.Matches(alias) { + continue + } + for _, node := range host.Nodes { + switch t := node.(type) { + case *Empty: + continue + case *KV: + // "keys are case insensitive" per the spec + lkey := strings.ToLower(t.Key) + if lkey == lowerKey { + all = append(all, t.Value) + } + case *Include: + val, _ := t.GetAll(alias, key) + if len(val) > 0 { + all = append(all, val...) + } + default: + return nil, fmt.Errorf("unknown Node type %v", t) + } + } + } + + return all, nil +} + +// String returns a string representation of the Config file. +func (c Config) String() string { + return marshal(c).String() +} + +func (c Config) MarshalText() ([]byte, error) { + return marshal(c).Bytes(), nil +} + +func marshal(c Config) *bytes.Buffer { + var buf bytes.Buffer + for i := range c.Hosts { + buf.WriteString(c.Hosts[i].String()) + } + return &buf +} + +// Pattern is a pattern in a Host declaration. Patterns are read-only values; +// create a new one with NewPattern(). +type Pattern struct { + str string // Its appearance in the file, not the value that gets compiled. + regex *regexp.Regexp + not bool // True if this is a negated match +} + +// String prints the string representation of the pattern. +func (p Pattern) String() string { + if p.not { + return "!" + p.str + } + return p.str +} + +// Copied from regexp.go with * and ? removed. +var specialBytes = []byte(`\.+()|[]{}^$`) + +func special(b byte) bool { + return bytes.IndexByte(specialBytes, b) >= 0 +} + +// NewPattern creates a new Pattern for matching hosts. NewPattern("*") creates +// a Pattern that matches all hosts. +// +// From the manpage, a pattern consists of zero or more non-whitespace +// characters, `*' (a wildcard that matches zero or more characters), or `?' (a +// wildcard that matches exactly one character). For example, to specify a set +// of declarations for any host in the ".co.uk" set of domains, the following +// pattern could be used: +// +// Host *.co.uk +// +// The following pattern would match any host in the 192.168.0.[0-9] network range: +// +// Host 192.168.0.? +func NewPattern(s string) (*Pattern, error) { + if s == "" { + return nil, errors.New("ssh_config: empty pattern") + } + negated := false + if s[0] == '!' { + negated = true + s = s[1:] + } + var buf bytes.Buffer + buf.WriteByte('^') + for i := 0; i < len(s); i++ { + // A byte loop is correct because all metacharacters are ASCII. + switch b := s[i]; b { + case '*': + buf.WriteString(".*") + case '?': + buf.WriteString(".?") + default: + // borrowing from QuoteMeta here. + if special(b) { + buf.WriteByte('\\') + } + buf.WriteByte(b) + } + } + buf.WriteByte('$') + r, err := regexp.Compile(buf.String()) + if err != nil { + return nil, err + } + return &Pattern{str: s, regex: r, not: negated}, nil +} + +// Host describes a Host or Match directive and the keywords that follow it. +type Host struct { + // A list of host patterns that should match this host. + Patterns []*Pattern + // A Node is either a key/value pair or a comment line. + Nodes []Node + // EOLComment is the comment (if any) terminating the Host line. + EOLComment string + // Whitespace if any between the Host declaration and a trailing comment. + spaceBeforeComment string + + hasEquals bool + leadingSpace int // TODO: handle spaces vs tabs here. + // The file starts with an implicit "Host *" declaration. + implicit bool + // isMatch is true if this block was created by a Match directive. + isMatch bool + // matchKeyword stores the original text after "Match" (e.g. "Host" or + // "all") so we can round-trip correctly. + matchKeyword string +} + +// Matches returns true if the Host matches for the given alias. For +// a description of the rules that provide a match, see the manpage for +// ssh_config. +func (h *Host) Matches(alias string) bool { + found := false + for i := range h.Patterns { + if h.Patterns[i].regex.MatchString(alias) { + if h.Patterns[i].not { + // Negated match. "A pattern entry may be negated by prefixing + // it with an exclamation mark (`!'). If a negated entry is + // matched, then the Host entry is ignored, regardless of + // whether any other patterns on the line match. Negated matches + // are therefore useful to provide exceptions for wildcard + // matches." + return false + } + found = true + } + } + return found +} + +// String prints h as it would appear in a config file. Minor tweaks may be +// present in the whitespace in the printed file. +func (h *Host) String() string { + var buf strings.Builder + //lint:ignore S1002 I prefer to write it this way + if h.implicit == false { + buf.WriteString(strings.Repeat(" ", int(h.leadingSpace))) + if h.isMatch { + buf.WriteString("Match") + if h.hasEquals { + buf.WriteString(" = ") + } else { + buf.WriteString(" ") + } + buf.WriteString(h.matchKeyword) + if !strings.EqualFold(h.matchKeyword, "all") { + buf.WriteString(" ") + for i, pat := range h.Patterns { + buf.WriteString(pat.String()) + if i < len(h.Patterns)-1 { + buf.WriteString(" ") + } + } + } + } else { + buf.WriteString("Host") + if h.hasEquals { + buf.WriteString(" = ") + } else { + buf.WriteString(" ") + } + for i, pat := range h.Patterns { + buf.WriteString(pat.String()) + if i < len(h.Patterns)-1 { + buf.WriteString(" ") + } + } + } + if h.EOLComment != "" { + if h.spaceBeforeComment != "" { + buf.WriteString(h.spaceBeforeComment) + } else { + buf.WriteByte(' ') + } + buf.WriteByte('#') + buf.WriteString(h.EOLComment) + } + buf.WriteByte('\n') + } + for i := range h.Nodes { + buf.WriteString(h.Nodes[i].String()) + buf.WriteByte('\n') + } + return buf.String() +} + +// Node represents a line in a Config. +type Node interface { + Pos() Position + String() string +} + +// KV is a line in the config file that contains a key, a value, and possibly +// a comment. +type KV struct { + Key string + Value string + // Whitespace after the value but before any comment + spaceAfterValue string + Comment string + hasEquals bool + leadingSpace int // Space before the key. TODO handle spaces vs tabs. + position Position + // rawValue preserves the original value text (including surrounding double + // quotes, if any) so that String() can roundtrip the config file faithfully. + rawValue string +} + +// Pos returns k's Position. +func (k *KV) Pos() Position { + return k.position +} + +// String prints k as it was parsed in the config file. +func (k *KV) String() string { + if k == nil { + return "" + } + equals := " " + if k.hasEquals { + equals = " = " + } + val := k.Value + if k.rawValue != "" { + val = k.rawValue + } + line := strings.Repeat(" ", int(k.leadingSpace)) + k.Key + equals + val + if k.Comment != "" { + if k.spaceAfterValue != "" { + line += k.spaceAfterValue + } else { + line += " " + } + line += "#" + k.Comment + } else { + line += k.spaceAfterValue + } + return line +} + +// Empty is a line in the config file that contains only whitespace or comments. +type Empty struct { + Comment string + leadingSpace int // TODO handle spaces vs tabs. + position Position +} + +// Pos returns e's Position. +func (e *Empty) Pos() Position { + return e.position +} + +// String prints e as it was parsed in the config file. +func (e *Empty) String() string { + if e == nil { + return "" + } + if e.Comment == "" { + return "" + } + return fmt.Sprintf("%s#%s", strings.Repeat(" ", int(e.leadingSpace)), e.Comment) +} + +// Include holds the result of an Include directive, including the config files +// that have been parsed as part of that directive. At most 5 levels of Include +// statements will be parsed. +type Include struct { + // Comment is the contents of any comment at the end of the Include + // statement. + Comment string + // an include directive can include several different files, and wildcards + directives []string + + mu sync.Mutex + // 1:1 mapping between matches and keys in files array; matches preserves + // ordering + matches []string + // actual filenames are listed here + files map[string]*Config + leadingSpace int + position Position + depth uint8 + hasEquals bool +} + +const maxRecurseDepth = 5 + +// ErrDepthExceeded is returned if too many Include directives are parsed. +// Usually this indicates a recursive loop (an Include directive pointing to the +// file it contains). +var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded") + +func removeDups(arr []string) []string { + // Use map to record duplicates as we find them. + encountered := make(map[string]bool, len(arr)) + result := make([]string, 0) + + for v := range arr { + //lint:ignore S1002 I prefer it this way + if encountered[arr[v]] == false { + encountered[arr[v]] = true + result = append(result, arr[v]) + } + } + return result +} + +// NewInclude creates a new Include with a list of file globs to include. +// Configuration files are parsed greedily (e.g. as soon as this function runs). +// Any error encountered while parsing nested configuration files will be +// returned. +func NewInclude(directives []string, hasEquals bool, pos Position, comment string, system bool, depth uint8) (*Include, error) { + if depth > maxRecurseDepth { + return nil, ErrDepthExceeded + } + inc := &Include{ + Comment: comment, + directives: directives, + files: make(map[string]*Config), + position: pos, + leadingSpace: pos.Col - 1, + depth: depth, + hasEquals: hasEquals, + } + // no need for inc.mu.Lock() since nothing else can access this inc + matches := make([]string, 0) + for i := range directives { + var path string + if filepath.IsAbs(directives[i]) { + path = directives[i] + } else if system { + path = filepath.Join("/etc/ssh", directives[i]) + } else if strings.HasPrefix(directives[i], "~/") { + path = filepath.Join(homedir(), directives[i][2:]) + } else { + path = filepath.Join(homedir(), ".ssh", directives[i]) + } + theseMatches, err := filepath.Glob(path) + if err != nil { + return nil, err + } + matches = append(matches, theseMatches...) + } + matches = removeDups(matches) + inc.matches = matches + for i := range matches { + config, err := parseWithDepth(matches[i], depth) + if err != nil { + return nil, err + } + inc.files[matches[i]] = config + } + return inc, nil +} + +// Pos returns the position of the Include directive in the larger file. +func (i *Include) Pos() Position { + return i.position +} + +// Get finds the first value in the Include statement matching the alias and the +// given key. +func (inc *Include) Get(alias, key string) string { + inc.mu.Lock() + defer inc.mu.Unlock() + // TODO: we search files in any order which is not correct + for i := range inc.matches { + cfg := inc.files[inc.matches[i]] + if cfg == nil { + panic("nil cfg") + } + val, err := cfg.Get(alias, key) + if err == nil && val != "" { + return val + } + } + return "" +} + +// GetAll finds all values in the Include statement matching the alias and the +// given key. +func (inc *Include) GetAll(alias, key string) ([]string, error) { + inc.mu.Lock() + defer inc.mu.Unlock() + var vals []string + + // TODO: we search files in any order which is not correct + for i := range inc.matches { + cfg := inc.files[inc.matches[i]] + if cfg == nil { + panic("nil cfg") + } + val, err := cfg.GetAll(alias, key) + if err == nil && len(val) != 0 { + // In theory if SupportsMultiple was false for this key we could + // stop looking here. But the caller has asked us to find all + // instances of the keyword (and could use Get() if they wanted) so + // let's keep looking. + vals = append(vals, val...) + } + } + return vals, nil +} + +// String prints out a string representation of this Include directive. Note +// included Config files are not printed as part of this representation. +func (inc *Include) String() string { + equals := " " + if inc.hasEquals { + equals = " = " + } + line := fmt.Sprintf("%sInclude%s%s", strings.Repeat(" ", int(inc.leadingSpace)), equals, strings.Join(inc.directives, " ")) + if inc.Comment != "" { + line += " #" + inc.Comment + } + return line +} + +var matchAll *Pattern + +func init() { + var err error + matchAll, err = NewPattern("*") + if err != nil { + panic(err) + } +} + +func newConfig() *Config { + return &Config{ + Hosts: []*Host{ + { + implicit: true, + Patterns: []*Pattern{matchAll}, + Nodes: make([]Node, 0), + }, + }, + depth: 0, + } +} diff --git a/vendor/github.com/kevinburke/ssh_config/lexer.go b/vendor/github.com/kevinburke/ssh_config/lexer.go new file mode 100644 index 0000000..11680b4 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/lexer.go @@ -0,0 +1,240 @@ +package ssh_config + +import ( + "bytes" +) + +// Define state functions +type sshLexStateFn func() sshLexStateFn + +type sshLexer struct { + inputIdx int + input []rune // Textual source + + buffer []rune // Runes composing the current token + tokens chan token + line int + col int + endbufferLine int + endbufferCol int +} + +func (s *sshLexer) lexComment(previousState sshLexStateFn) sshLexStateFn { + return func() sshLexStateFn { + growingString := "" + for next := s.peek(); next != '\n' && next != eof; next = s.peek() { + if next == '\r' && s.follow("\r\n") { + break + } + growingString += string(next) + s.next() + } + s.emitWithValue(tokenComment, growingString) + s.skip() + return previousState + } +} + +// lex the space after an equals sign in a function +func (s *sshLexer) lexRspace() sshLexStateFn { + for { + next := s.peek() + if !isSpace(next) { + break + } + s.skip() + } + return s.lexRvalue +} + +func (s *sshLexer) lexEquals() sshLexStateFn { + for { + next := s.peek() + if next == '=' { + s.emit(tokenEquals) + s.skip() + return s.lexRspace + } + // TODO error handling here; newline eof etc. + if !isSpace(next) { + break + } + s.skip() + } + return s.lexRvalue +} + +func (s *sshLexer) lexKey() sshLexStateFn { + growingString := "" + + for r := s.peek(); isKeyChar(r); r = s.peek() { + // simplified a lot here + if isSpace(r) || r == '=' { + s.emitWithValue(tokenKey, growingString) + s.skip() + return s.lexEquals + } + growingString += string(r) + s.next() + } + s.emitWithValue(tokenKey, growingString) + return s.lexEquals +} + +func (s *sshLexer) lexRvalue() sshLexStateFn { + growingString := "" + for { + next := s.peek() + switch next { + case '\r': + if s.follow("\r\n") { + s.emitWithValue(tokenString, growingString) + s.skip() + return s.lexVoid + } + case '\n': + s.emitWithValue(tokenString, growingString) + s.skip() + return s.lexVoid + case '#': + s.emitWithValue(tokenString, growingString) + s.skip() + return s.lexComment(s.lexVoid) + case eof: + s.next() + } + if next == eof { + break + } + growingString += string(next) + s.next() + } + s.emit(tokenEOF) + return nil +} + +func (s *sshLexer) read() rune { + r := s.peek() + if r == '\n' { + s.endbufferLine++ + s.endbufferCol = 1 + } else { + s.endbufferCol++ + } + s.inputIdx++ + return r +} + +func (s *sshLexer) next() rune { + r := s.read() + + if r != eof { + s.buffer = append(s.buffer, r) + } + return r +} + +func (s *sshLexer) lexVoid() sshLexStateFn { + for { + next := s.peek() + switch next { + case '#': + s.skip() + return s.lexComment(s.lexVoid) + case '\r': + fallthrough + case '\n': + s.emit(tokenEmptyLine) + s.skip() + continue + } + + if isSpace(next) { + s.skip() + } + + if isKeyStartChar(next) { + return s.lexKey + } + + // removed IsKeyStartChar and lexKey. probably will need to readd + + if next == eof { + s.next() + break + } + } + + s.emit(tokenEOF) + return nil +} + +func (s *sshLexer) ignore() { + s.buffer = make([]rune, 0) + s.line = s.endbufferLine + s.col = s.endbufferCol +} + +func (s *sshLexer) skip() { + s.next() + s.ignore() +} + +func (s *sshLexer) emit(t tokenType) { + s.emitWithValue(t, string(s.buffer)) +} + +func (s *sshLexer) emitWithValue(t tokenType, value string) { + tok := token{ + Position: Position{s.line, s.col}, + typ: t, + val: value, + } + s.tokens <- tok + s.ignore() +} + +func (s *sshLexer) peek() rune { + if s.inputIdx >= len(s.input) { + return eof + } + + r := s.input[s.inputIdx] + return r +} + +func (s *sshLexer) follow(next string) bool { + inputIdx := s.inputIdx + for _, expectedRune := range next { + if inputIdx >= len(s.input) { + return false + } + r := s.input[inputIdx] + inputIdx++ + if expectedRune != r { + return false + } + } + return true +} + +func (s *sshLexer) run() { + for state := s.lexVoid; state != nil; { + state = state() + } + close(s.tokens) +} + +func lexSSH(input []byte) chan token { + runes := bytes.Runes(input) + l := &sshLexer{ + input: runes, + tokens: make(chan token), + line: 1, + col: 1, + endbufferLine: 1, + endbufferCol: 1, + } + go l.run() + return l.tokens +} diff --git a/vendor/github.com/kevinburke/ssh_config/parser.go b/vendor/github.com/kevinburke/ssh_config/parser.go new file mode 100644 index 0000000..c524d0e --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/parser.go @@ -0,0 +1,270 @@ +package ssh_config + +import ( + "fmt" + "strings" + "unicode" +) + +type sshParser struct { + flow chan token + config *Config + tokensBuffer []token + currentTable []string + seenTableKeys []string + // /etc/ssh parser or local parser - used to find the default for relative + // filepaths in the Include directive + system bool + depth uint8 +} + +type sshParserStateFn func() sshParserStateFn + +// Formats and panics an error message based on a token +func (p *sshParser) raiseErrorf(tok *token, msg string) { + // TODO this format is ugly + panic(tok.Position.String() + ": " + msg) +} + +func (p *sshParser) raiseError(tok *token, err error) { + if err == ErrDepthExceeded { + panic(err) + } + // TODO this format is ugly + panic(tok.Position.String() + ": " + err.Error()) +} + +func (p *sshParser) run() { + for state := p.parseStart; state != nil; { + state = state() + } +} + +func (p *sshParser) peek() *token { + if len(p.tokensBuffer) != 0 { + return &(p.tokensBuffer[0]) + } + + tok, ok := <-p.flow + if !ok { + return nil + } + p.tokensBuffer = append(p.tokensBuffer, tok) + return &tok +} + +func (p *sshParser) getToken() *token { + if len(p.tokensBuffer) != 0 { + tok := p.tokensBuffer[0] + p.tokensBuffer = p.tokensBuffer[1:] + return &tok + } + tok, ok := <-p.flow + if !ok { + return nil + } + return &tok +} + +func (p *sshParser) parseStart() sshParserStateFn { + tok := p.peek() + + // end of stream, parsing is finished + if tok == nil { + return nil + } + + switch tok.typ { + case tokenComment, tokenEmptyLine: + return p.parseComment + case tokenKey: + return p.parseKV + case tokenEOF: + return nil + default: + p.raiseErrorf(tok, fmt.Sprintf("unexpected token %q\n", tok)) + } + return nil +} + +func (p *sshParser) parseKV() sshParserStateFn { + key := p.getToken() + hasEquals := false + val := p.getToken() + if val.typ == tokenEquals { + hasEquals = true + val = p.getToken() + } + comment := "" + tok := p.peek() + if tok == nil { + tok = &token{typ: tokenEOF} + } + if tok.typ == tokenComment && tok.Position.Line == val.Position.Line { + tok = p.getToken() + comment = tok.val + } + if strings.ToLower(key.val) == "match" { + return p.parseMatch(val, hasEquals, comment) + } + if strings.ToLower(key.val) == "host" { + strPatterns := strings.Split(val.val, " ") + patterns := make([]*Pattern, 0) + for i := range strPatterns { + if strPatterns[i] == "" { + continue + } + pat, err := NewPattern(strPatterns[i]) + if err != nil { + p.raiseErrorf(val, fmt.Sprintf("Invalid host pattern: %v", err)) + return nil + } + patterns = append(patterns, pat) + } + // val.val at this point could be e.g. "example.com " + hostval := strings.TrimRightFunc(val.val, unicode.IsSpace) + spaceBeforeComment := val.val[len(hostval):] + val.val = hostval + p.config.Hosts = append(p.config.Hosts, &Host{ + Patterns: patterns, + Nodes: make([]Node, 0), + EOLComment: comment, + spaceBeforeComment: spaceBeforeComment, + hasEquals: hasEquals, + }) + return p.parseStart + } + lastHost := p.config.Hosts[len(p.config.Hosts)-1] + if strings.ToLower(key.val) == "include" { + inc, err := NewInclude(strings.Split(val.val, " "), hasEquals, key.Position, comment, p.system, p.depth+1) + if err == ErrDepthExceeded { + p.raiseError(val, err) + return nil + } + if err != nil { + p.raiseErrorf(val, fmt.Sprintf("Error parsing Include directive: %v", err)) + return nil + } + lastHost.Nodes = append(lastHost.Nodes, inc) + return p.parseStart + } + shortval := strings.TrimRightFunc(val.val, unicode.IsSpace) + spaceAfterValue := val.val[len(shortval):] + unquoted := shortval + if len(shortval) >= 2 && shortval[0] == '"' && shortval[len(shortval)-1] == '"' { + unquoted = shortval[1 : len(shortval)-1] + } + kv := &KV{ + Key: key.val, + Value: unquoted, + rawValue: shortval, + spaceAfterValue: spaceAfterValue, + Comment: comment, + hasEquals: hasEquals, + leadingSpace: key.Position.Col - 1, + position: key.Position, + } + lastHost.Nodes = append(lastHost.Nodes, kv) + return p.parseStart +} + +func (p *sshParser) parseMatch(val *token, hasEquals bool, comment string) sshParserStateFn { + // val.val contains everything after "Match ", e.g. "Host *.example.com" + // or "all". + trimmed := strings.TrimRightFunc(val.val, unicode.IsSpace) + spaceBeforeComment := val.val[len(trimmed):] + fields := strings.Fields(trimmed) + if len(fields) == 0 { + p.raiseErrorf(val, "ssh_config: Match directive requires at least one criterion") + return nil + } + criterion := strings.ToLower(fields[0]) + + switch criterion { + case "all": + // "Match all" is equivalent to "Host *" — matches everything. + p.config.Hosts = append(p.config.Hosts, &Host{ + Patterns: []*Pattern{matchAll}, + Nodes: make([]Node, 0), + EOLComment: comment, + spaceBeforeComment: spaceBeforeComment, + hasEquals: hasEquals, + isMatch: true, + matchKeyword: fields[0], // preserve original case + }) + return p.parseStart + + case "host": + patterns := make([]*Pattern, 0) + for _, s := range fields[1:] { + if s == "" { + continue + } + pat, err := NewPattern(s) + if err != nil { + p.raiseErrorf(val, fmt.Sprintf("Invalid host pattern: %v", err)) + return nil + } + patterns = append(patterns, pat) + } + if len(patterns) == 0 { + p.raiseErrorf(val, "ssh_config: Match Host requires at least one pattern") + return nil + } + p.config.Hosts = append(p.config.Hosts, &Host{ + Patterns: patterns, + Nodes: make([]Node, 0), + EOLComment: comment, + spaceBeforeComment: spaceBeforeComment, + hasEquals: hasEquals, + isMatch: true, + matchKeyword: fields[0], // preserve original case + }) + return p.parseStart + + case "exec": + // Match Exec runs arbitrary commands. Supporting it would allow + // untrusted SSH config files to execute code on the parsing + // machine. Reject it explicitly. + p.raiseErrorf(val, "ssh_config: Match Exec is not supported") + return nil + + default: + p.raiseErrorf(val, fmt.Sprintf("ssh_config: unsupported Match criterion %q", criterion)) + return nil + } +} + +func (p *sshParser) parseComment() sshParserStateFn { + comment := p.getToken() + lastHost := p.config.Hosts[len(p.config.Hosts)-1] + lastHost.Nodes = append(lastHost.Nodes, &Empty{ + Comment: comment.val, + // account for the "#" as well + leadingSpace: comment.Position.Col - 2, + position: comment.Position, + }) + return p.parseStart +} + +func parseSSH(flow chan token, system bool, depth uint8) *Config { + // Ensure we consume tokens to completion even if parser exits early + defer func() { + for range flow { + } + }() + + result := newConfig() + result.position = Position{1, 1} + parser := &sshParser{ + flow: flow, + config: result, + tokensBuffer: make([]token, 0), + currentTable: make([]string, 0), + seenTableKeys: make([]string, 0), + system: system, + depth: depth, + } + parser.run() + return result +} diff --git a/vendor/github.com/kevinburke/ssh_config/position.go b/vendor/github.com/kevinburke/ssh_config/position.go new file mode 100644 index 0000000..e0b5e3f --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/position.go @@ -0,0 +1,25 @@ +package ssh_config + +import "fmt" + +// Position of a document element within a SSH document. +// +// Line and Col are both 1-indexed positions for the element's line number and +// column number, respectively. Values of zero or less will cause Invalid(), +// to return true. +type Position struct { + Line int // line within the document + Col int // column within the line +} + +// String representation of the position. +// Displays 1-indexed line and column numbers. +func (p Position) String() string { + return fmt.Sprintf("(%d, %d)", p.Line, p.Col) +} + +// Invalid returns whether or not the position is valid (i.e. with negative or +// null values) +func (p Position) Invalid() bool { + return p.Line <= 0 || p.Col <= 0 +} diff --git a/vendor/github.com/kevinburke/ssh_config/token.go b/vendor/github.com/kevinburke/ssh_config/token.go new file mode 100644 index 0000000..a0ecbb2 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/token.go @@ -0,0 +1,49 @@ +package ssh_config + +import "fmt" + +type token struct { + Position + typ tokenType + val string +} + +func (t token) String() string { + switch t.typ { + case tokenEOF: + return "EOF" + } + return fmt.Sprintf("%q", t.val) +} + +type tokenType int + +const ( + eof = -(iota + 1) +) + +const ( + tokenError tokenType = iota + tokenEOF + tokenEmptyLine + tokenComment + tokenKey + tokenEquals + tokenString +) + +func isSpace(r rune) bool { + return r == ' ' || r == '\t' +} + +func isKeyStartChar(r rune) bool { + return !(isSpace(r) || r == '\r' || r == '\n' || r == eof) +} + +// I'm not sure that this is correct +func isKeyChar(r rune) bool { + // Keys start with the first character that isn't whitespace or [ and end + // with the last non-whitespace character before the equals sign. Keys + // cannot contain a # character." + return !(r == '\r' || r == '\n' || r == eof || r == '=') +} diff --git a/vendor/github.com/kevinburke/ssh_config/validators.go b/vendor/github.com/kevinburke/ssh_config/validators.go new file mode 100644 index 0000000..5977f90 --- /dev/null +++ b/vendor/github.com/kevinburke/ssh_config/validators.go @@ -0,0 +1,186 @@ +package ssh_config + +import ( + "fmt" + "strconv" + "strings" +) + +// Default returns the default value for the given keyword, for example "22" if +// the keyword is "Port". Default returns the empty string if the keyword has no +// default, or if the keyword is unknown. Keyword matching is case-insensitive. +// +// Default values are provided by OpenSSH_7.4p1 on a Mac. +func Default(keyword string) string { + return defaults[strings.ToLower(keyword)] +} + +// Arguments where the value must be "yes" or "no" and *only* yes or no. +var yesnos = map[string]bool{ + strings.ToLower("BatchMode"): true, + strings.ToLower("CanonicalizeFallbackLocal"): true, + strings.ToLower("ChallengeResponseAuthentication"): true, + strings.ToLower("CheckHostIP"): true, + strings.ToLower("ClearAllForwardings"): true, + strings.ToLower("Compression"): true, + strings.ToLower("EnableSSHKeysign"): true, + strings.ToLower("ExitOnForwardFailure"): true, + strings.ToLower("ForwardAgent"): true, + strings.ToLower("ForwardX11"): true, + strings.ToLower("ForwardX11Trusted"): true, + strings.ToLower("GatewayPorts"): true, + strings.ToLower("GSSAPIAuthentication"): true, + strings.ToLower("GSSAPIDelegateCredentials"): true, + strings.ToLower("HostbasedAuthentication"): true, + strings.ToLower("IdentitiesOnly"): true, + strings.ToLower("KbdInteractiveAuthentication"): true, + strings.ToLower("NoHostAuthenticationForLocalhost"): true, + strings.ToLower("PasswordAuthentication"): true, + strings.ToLower("PermitLocalCommand"): true, + strings.ToLower("PubkeyAuthentication"): true, + strings.ToLower("RhostsRSAAuthentication"): true, + strings.ToLower("RSAAuthentication"): true, + strings.ToLower("StreamLocalBindUnlink"): true, + strings.ToLower("TCPKeepAlive"): true, + strings.ToLower("UseKeychain"): true, + strings.ToLower("UsePrivilegedPort"): true, + strings.ToLower("VisualHostKey"): true, +} + +var uints = map[string]bool{ + strings.ToLower("CanonicalizeMaxDots"): true, + strings.ToLower("CompressionLevel"): true, // 1 to 9 + strings.ToLower("ConnectionAttempts"): true, + strings.ToLower("ConnectTimeout"): true, + strings.ToLower("NumberOfPasswordPrompts"): true, + strings.ToLower("Port"): true, + strings.ToLower("ServerAliveCountMax"): true, + strings.ToLower("ServerAliveInterval"): true, +} + +func mustBeYesOrNo(lkey string) bool { + return yesnos[lkey] +} + +func mustBeUint(lkey string) bool { + return uints[lkey] +} + +func validate(key, val string) error { + lkey := strings.ToLower(key) + if mustBeYesOrNo(lkey) && (val != "yes" && val != "no") { + return fmt.Errorf("ssh_config: value for key %q must be 'yes' or 'no', got %q", key, val) + } + if mustBeUint(lkey) { + _, err := strconv.ParseUint(val, 10, 64) + if err != nil { + return fmt.Errorf("ssh_config: %v", err) + } + } + return nil +} + +var defaults = map[string]string{ + strings.ToLower("AddKeysToAgent"): "no", + strings.ToLower("AddressFamily"): "any", + strings.ToLower("BatchMode"): "no", + strings.ToLower("CanonicalizeFallbackLocal"): "yes", + strings.ToLower("CanonicalizeHostname"): "no", + strings.ToLower("CanonicalizeMaxDots"): "1", + strings.ToLower("ChallengeResponseAuthentication"): "yes", + strings.ToLower("CheckHostIP"): "yes", + // TODO is this still the correct cipher + strings.ToLower("Cipher"): "3des", + strings.ToLower("Ciphers"): "chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc", + strings.ToLower("ClearAllForwardings"): "no", + strings.ToLower("Compression"): "no", + strings.ToLower("CompressionLevel"): "6", + strings.ToLower("ConnectionAttempts"): "1", + strings.ToLower("ControlMaster"): "no", + strings.ToLower("EnableSSHKeysign"): "no", + strings.ToLower("EscapeChar"): "~", + strings.ToLower("ExitOnForwardFailure"): "no", + strings.ToLower("FingerprintHash"): "sha256", + strings.ToLower("ForwardAgent"): "no", + strings.ToLower("ForwardX11"): "no", + strings.ToLower("ForwardX11Timeout"): "20m", + strings.ToLower("ForwardX11Trusted"): "no", + strings.ToLower("GatewayPorts"): "no", + strings.ToLower("GlobalKnownHostsFile"): "/etc/ssh/ssh_known_hosts /etc/ssh/ssh_known_hosts2", + strings.ToLower("GSSAPIAuthentication"): "no", + strings.ToLower("GSSAPIDelegateCredentials"): "no", + strings.ToLower("HashKnownHosts"): "no", + strings.ToLower("HostbasedAuthentication"): "no", + + strings.ToLower("HostbasedKeyTypes"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", + strings.ToLower("HostKeyAlgorithms"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", + // HostName has a dynamic default (the value passed at the command line). + + strings.ToLower("IdentitiesOnly"): "no", + strings.ToLower("IdentityFile"): "~/.ssh/identity", + + // IPQoS has a dynamic default based on interactive or non-interactive + // sessions. + + strings.ToLower("KbdInteractiveAuthentication"): "yes", + + strings.ToLower("KexAlgorithms"): "curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1", + strings.ToLower("LogLevel"): "INFO", + strings.ToLower("MACs"): "umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1", + + strings.ToLower("NoHostAuthenticationForLocalhost"): "no", + strings.ToLower("NumberOfPasswordPrompts"): "3", + strings.ToLower("PasswordAuthentication"): "yes", + strings.ToLower("PermitLocalCommand"): "no", + strings.ToLower("Port"): "22", + + strings.ToLower("PreferredAuthentications"): "gssapi-with-mic,hostbased,publickey,keyboard-interactive,password", + strings.ToLower("Protocol"): "2", + strings.ToLower("ProxyUseFdpass"): "no", + strings.ToLower("PubkeyAcceptedKeyTypes"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", + strings.ToLower("PubkeyAuthentication"): "yes", + strings.ToLower("RekeyLimit"): "default none", + strings.ToLower("RhostsRSAAuthentication"): "no", + strings.ToLower("RSAAuthentication"): "yes", + + strings.ToLower("ServerAliveCountMax"): "3", + strings.ToLower("ServerAliveInterval"): "0", + strings.ToLower("StreamLocalBindMask"): "0177", + strings.ToLower("StreamLocalBindUnlink"): "no", + strings.ToLower("StrictHostKeyChecking"): "ask", + strings.ToLower("TCPKeepAlive"): "yes", + strings.ToLower("Tunnel"): "no", + strings.ToLower("TunnelDevice"): "any:any", + strings.ToLower("UpdateHostKeys"): "no", + strings.ToLower("UseKeychain"): "no", + strings.ToLower("UsePrivilegedPort"): "no", + + strings.ToLower("UserKnownHostsFile"): "~/.ssh/known_hosts ~/.ssh/known_hosts2", + strings.ToLower("VerifyHostKeyDNS"): "no", + strings.ToLower("VisualHostKey"): "no", + strings.ToLower("XAuthLocation"): "/usr/X11R6/bin/xauth", +} + +// these identities are used for SSH protocol 2 +var defaultProtocol2Identities = []string{ + "~/.ssh/id_dsa", + "~/.ssh/id_ecdsa", + "~/.ssh/id_ed25519", + "~/.ssh/id_rsa", +} + +// these directives support multiple items that can be collected +// across multiple files +var pluralDirectives = map[string]bool{ + "CertificateFile": true, + "IdentityFile": true, + "DynamicForward": true, + "RemoteForward": true, + "SendEnv": true, + "SetEnv": true, +} + +// SupportsMultiple reports whether a directive can be specified multiple times. +func SupportsMultiple(key string) bool { + return pluralDirectives[strings.ToLower(key)] +} diff --git a/vendor/golang.org/x/image/LICENSE b/vendor/golang.org/x/image/LICENSE new file mode 100644 index 0000000..2a7cf70 --- /dev/null +++ b/vendor/golang.org/x/image/LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/image/PATENTS b/vendor/golang.org/x/image/PATENTS new file mode 100644 index 0000000..7330990 --- /dev/null +++ b/vendor/golang.org/x/image/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/image/draw/draw.go b/vendor/golang.org/x/image/draw/draw.go new file mode 100644 index 0000000..42d5d7e --- /dev/null +++ b/vendor/golang.org/x/image/draw/draw.go @@ -0,0 +1,67 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package draw provides image composition functions. +// +// See "The Go image/draw package" for an introduction to this package: +// http://golang.org/doc/articles/image_draw.html +// +// This package is a superset of and a drop-in replacement for the image/draw +// package in the standard library. +package draw + +// This file just contains the API exported by the image/draw package in the +// standard library. Other files in this package provide additional features. + +import ( + "image" + "image/draw" +) + +// Draw calls DrawMask with a nil mask. +func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op) { + draw.Draw(dst, r, src, sp, draw.Op(op)) +} + +// DrawMask aligns r.Min in dst with sp in src and mp in mask and then +// replaces the rectangle r in dst with the result of a Porter-Duff +// composition. A nil mask is treated as opaque. +func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op) { + draw.DrawMask(dst, r, src, sp, mask, mp, draw.Op(op)) +} + +// Drawer contains the Draw method. +type Drawer = draw.Drawer + +// FloydSteinberg is a Drawer that is the Src Op with Floyd-Steinberg error +// diffusion. +var FloydSteinberg Drawer = floydSteinberg{} + +type floydSteinberg struct{} + +func (floydSteinberg) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point) { + draw.FloydSteinberg.Draw(dst, r, src, sp) +} + +// Image is an image.Image with a Set method to change a single pixel. +type Image = draw.Image + +// RGBA64Image extends both the Image and image.RGBA64Image interfaces with a +// SetRGBA64 method to change a single pixel. SetRGBA64 is equivalent to +// calling Set, but it can avoid allocations from converting concrete color +// types to the color.Color interface type. +type RGBA64Image = draw.RGBA64Image + +// Op is a Porter-Duff compositing operator. +type Op = draw.Op + +const ( + // Over specifies ``(src in mask) over dst''. + Over Op = draw.Over + // Src specifies ``src in mask''. + Src Op = draw.Src +) + +// Quantizer produces a palette for an image. +type Quantizer = draw.Quantizer diff --git a/vendor/golang.org/x/image/draw/impl.go b/vendor/golang.org/x/image/draw/impl.go new file mode 100644 index 0000000..fcd1994 --- /dev/null +++ b/vendor/golang.org/x/image/draw/impl.go @@ -0,0 +1,8426 @@ +// generated by "go run gen.go". DO NOT EDIT. + +package draw + +import ( + "image" + "image/color" + "math" + + "golang.org/x/image/math/f64" +) + +func (z nnInterpolator) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) { + // Try to simplify a Scale to a Copy when DstMask is not specified. + // If DstMask is not nil, Copy will call Scale back with same dr and sr, and cause stack overflow. + if dr.Size() == sr.Size() && (opts == nil || opts.DstMask == nil) { + Copy(dst, dr.Min, src, sr, op, opts) + return + } + + var o Options + if opts != nil { + o = *opts + } + + // adr is the affected destination pixels. + adr := dst.Bounds().Intersect(dr) + adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP) + if adr.Empty() || sr.Empty() { + return + } + // Make adr relative to dr.Min. + adr = adr.Sub(dr.Min) + if op == Over && o.SrcMask == nil && opaque(src) { + op = Src + } + + // sr is the source pixels. If it extends beyond the src bounds, + // we cannot use the type-specific fast paths, as they access + // the Pix fields directly without bounds checking. + // + // Similarly, the fast paths assume that the masks are nil. + if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) { + switch op { + case Over: + z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o) + case Src: + z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o) + } + } else if _, ok := src.(*image.Uniform); ok { + Draw(dst, dr, src, src.Bounds().Min, op) + } else { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.NRGBA: + z.scale_RGBA_NRGBA_Over(dst, dr, adr, src, sr, &o) + case *image.RGBA: + z.scale_RGBA_RGBA_Over(dst, dr, adr, src, sr, &o) + case image.RGBA64Image: + z.scale_RGBA_RGBA64Image_Over(dst, dr, adr, src, sr, &o) + default: + z.scale_RGBA_Image_Over(dst, dr, adr, src, sr, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.scale_RGBA64Image_RGBA64Image_Over(dst, dr, adr, src, sr, &o) + } + default: + switch src := src.(type) { + default: + z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o) + } + } + case Src: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.Gray: + z.scale_RGBA_Gray_Src(dst, dr, adr, src, sr, &o) + case *image.NRGBA: + z.scale_RGBA_NRGBA_Src(dst, dr, adr, src, sr, &o) + case *image.RGBA: + z.scale_RGBA_RGBA_Src(dst, dr, adr, src, sr, &o) + case *image.YCbCr: + switch src.SubsampleRatio { + default: + z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio444: + z.scale_RGBA_YCbCr444_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio422: + z.scale_RGBA_YCbCr422_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio420: + z.scale_RGBA_YCbCr420_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio440: + z.scale_RGBA_YCbCr440_Src(dst, dr, adr, src, sr, &o) + } + case image.RGBA64Image: + z.scale_RGBA_RGBA64Image_Src(dst, dr, adr, src, sr, &o) + default: + z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.scale_RGBA64Image_RGBA64Image_Src(dst, dr, adr, src, sr, &o) + } + default: + switch src := src.(type) { + default: + z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o) + } + } + } + } +} + +func (z nnInterpolator) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) { + // Try to simplify a Transform to a Copy. + if s2d[0] == 1 && s2d[1] == 0 && s2d[3] == 0 && s2d[4] == 1 { + dx := int(s2d[2]) + dy := int(s2d[5]) + if float64(dx) == s2d[2] && float64(dy) == s2d[5] { + Copy(dst, image.Point{X: sr.Min.X + dx, Y: sr.Min.X + dy}, src, sr, op, opts) + return + } + } + + var o Options + if opts != nil { + o = *opts + } + + dr := transformRect(&s2d, &sr) + // adr is the affected destination pixels. + adr := dst.Bounds().Intersect(dr) + adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP) + if adr.Empty() || sr.Empty() { + return + } + if op == Over && o.SrcMask == nil && opaque(src) { + op = Src + } + + d2s := invert(&s2d) + // bias is a translation of the mapping from dst coordinates to src + // coordinates such that the latter temporarily have non-negative X + // and Y coordinates. This allows us to write int(f) instead of + // int(math.Floor(f)), since "round to zero" and "round down" are + // equivalent when f >= 0, but the former is much cheaper. The X-- + // and Y-- are because the TransformLeaf methods have a "sx -= 0.5" + // adjustment. + bias := transformRect(&d2s, &adr).Min + bias.X-- + bias.Y-- + d2s[2] -= float64(bias.X) + d2s[5] -= float64(bias.Y) + // Make adr relative to dr.Min. + adr = adr.Sub(dr.Min) + // sr is the source pixels. If it extends beyond the src bounds, + // we cannot use the type-specific fast paths, as they access + // the Pix fields directly without bounds checking. + // + // Similarly, the fast paths assume that the masks are nil. + if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) { + switch op { + case Over: + z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + case Src: + z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + } else if u, ok := src.(*image.Uniform); ok { + transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op) + } else { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.NRGBA: + z.transform_RGBA_NRGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.RGBA: + z.transform_RGBA_RGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.RGBA64Image: + z.transform_RGBA_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + default: + z.transform_RGBA_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.transform_RGBA64Image_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + } + default: + switch src := src.(type) { + default: + z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + } + } + case Src: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.Gray: + z.transform_RGBA_Gray_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.NRGBA: + z.transform_RGBA_NRGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.RGBA: + z.transform_RGBA_RGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.YCbCr: + switch src.SubsampleRatio { + default: + z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio444: + z.transform_RGBA_YCbCr444_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio422: + z.transform_RGBA_YCbCr422_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio420: + z.transform_RGBA_YCbCr420_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio440: + z.transform_RGBA_YCbCr440_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + case image.RGBA64Image: + z.transform_RGBA_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + default: + z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.transform_RGBA64Image_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + default: + switch src := src.(type) { + default: + z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + } + } + } +} + +func (nnInterpolator) scale_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.Gray, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx) - src.Rect.Min.X) + pr := uint32(src.Pix[pi]) * 0x101 + out := uint8(pr >> 8) + dst.Pix[d+0] = out + dst.Pix[d+1] = out + dst.Pix[d+2] = out + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) scale_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4 + pa := uint32(src.Pix[pi+3]) * 0x101 + pr := uint32(src.Pix[pi+0]) * pa / 0xff + pg := uint32(src.Pix[pi+1]) * pa / 0xff + pb := uint32(src.Pix[pi+2]) * pa / 0xff + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4 + pa := uint32(src.Pix[pi+3]) * 0x101 + pr := uint32(src.Pix[pi+0]) * pa / 0xff + pg := uint32(src.Pix[pi+1]) * pa / 0xff + pb := uint32(src.Pix[pi+2]) * pa / 0xff + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4 + pr := uint32(src.Pix[pi+0]) * 0x101 + pg := uint32(src.Pix[pi+1]) * 0x101 + pb := uint32(src.Pix[pi+2]) * 0x101 + pa := uint32(src.Pix[pi+3]) * 0x101 + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx)-src.Rect.Min.X)*4 + pr := uint32(src.Pix[pi+0]) * 0x101 + pg := uint32(src.Pix[pi+1]) * 0x101 + pb := uint32(src.Pix[pi+2]) * 0x101 + pa := uint32(src.Pix[pi+3]) * 0x101 + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X) + pj := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) scale_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X) + pj := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) scale_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X) + pj := ((sr.Min.Y+int(sy))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) scale_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pi := (sr.Min.Y+int(sy)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx) - src.Rect.Min.X) + pj := ((sr.Min.Y+int(sy))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) scale_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy)) + pa1 := (0xffff - uint32(p.A)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy)) + dst.Pix[d+0] = uint8(p.R >> 8) + dst.Pix[d+1] = uint8(p.G >> 8) + dst.Pix[d+2] = uint8(p.B >> 8) + dst.Pix[d+3] = uint8(p.A >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA() + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := (2*uint64(dx) + 1) * sw / dw2 + pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA() + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (nnInterpolator) scale_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := (2*uint64(dx) + 1) * sw / dw2 + p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + pa1 := 0xffff - uint32(p.A) + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } + } +} + +func (nnInterpolator) scale_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := (2*uint64(dx) + 1) * sw / dw2 + p := src.RGBA64At(sr.Min.X+int(sx), sr.Min.Y+int(sy)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + if dstMask != nil { + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } else { + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p) + } + } + } +} + +func (nnInterpolator) scale_Image_Image_Over(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := (2*uint64(dx) + 1) * sw / dw2 + pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + pa1 := 0xffff - pa + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } +} + +func (nnInterpolator) scale_Image_Image_Src(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + dw2 := uint64(dr.Dx()) * 2 + dh2 := uint64(dr.Dy()) * 2 + sw := uint64(sr.Dx()) + sh := uint64(sr.Dy()) + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := (2*uint64(dy) + 1) * sh / dh2 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := (2*uint64(dx) + 1) * sw / dw2 + pr, pg, pb, pa := src.At(sr.Min.X+int(sx), sr.Min.Y+int(sy)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx), smp.Y+sr.Min.Y+int(sy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + if dstMask != nil { + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } else { + dstColorRGBA64.R = uint16(pr) + dstColorRGBA64.G = uint16(pg) + dstColorRGBA64.B = uint16(pb) + dstColorRGBA64.A = uint16(pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } +} + +func (nnInterpolator) transform_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Gray, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0 - src.Rect.Min.X) + pr := uint32(src.Pix[pi]) * 0x101 + out := uint8(pr >> 8) + dst.Pix[d+0] = out + dst.Pix[d+1] = out + dst.Pix[d+2] = out + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) transform_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + pa := uint32(src.Pix[pi+3]) * 0x101 + pr := uint32(src.Pix[pi+0]) * pa / 0xff + pg := uint32(src.Pix[pi+1]) * pa / 0xff + pb := uint32(src.Pix[pi+2]) * pa / 0xff + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + pa := uint32(src.Pix[pi+3]) * 0x101 + pr := uint32(src.Pix[pi+0]) * pa / 0xff + pg := uint32(src.Pix[pi+1]) * pa / 0xff + pb := uint32(src.Pix[pi+2]) * pa / 0xff + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + pr := uint32(src.Pix[pi+0]) * 0x101 + pg := uint32(src.Pix[pi+1]) * 0x101 + pb := uint32(src.Pix[pi+2]) * 0x101 + pa := uint32(src.Pix[pi+3]) * 0x101 + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + pr := uint32(src.Pix[pi+0]) * 0x101 + pg := uint32(src.Pix[pi+1]) * 0x101 + pb := uint32(src.Pix[pi+2]) * 0x101 + pa := uint32(src.Pix[pi+3]) * 0x101 + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + pj := (sy0-src.Rect.Min.Y)*src.CStride + (sx0 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) transform_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + pj := (sy0-src.Rect.Min.Y)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) transform_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + pj := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) transform_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pi := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + pj := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + (sx0 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pr := (pyy1 + 91881*pcr1) >> 8 + pg := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pb := (pyy1 + 116130*pcb1) >> 8 + if pr < 0 { + pr = 0 + } else if pr > 0xffff { + pr = 0xffff + } + if pg < 0 { + pg = 0 + } else if pg > 0xffff { + pg = 0xffff + } + if pb < 0 { + pb = 0 + } else if pb > 0xffff { + pb = 0xffff + } + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (nnInterpolator) transform_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + p := src.RGBA64At(sx0, sy0) + pa1 := (0xffff - uint32(p.A)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + p := src.RGBA64At(sx0, sy0) + dst.Pix[d+0] = uint8(p.R >> 8) + dst.Pix[d+1] = uint8(p.G >> 8) + dst.Pix[d+2] = uint8(p.B >> 8) + dst.Pix[d+3] = uint8(p.A >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pr, pg, pb, pa := src.At(sx0, sy0).RGBA() + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pr, pg, pb, pa := src.At(sx0, sy0).RGBA() + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (nnInterpolator) transform_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + p := src.RGBA64At(sx0, sy0) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + pa1 := 0xffff - uint32(p.A) + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } + } +} + +func (nnInterpolator) transform_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + p := src.RGBA64At(sx0, sy0) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + if dstMask != nil { + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } else { + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p) + } + } + } +} + +func (nnInterpolator) transform_Image_Image_Over(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pr, pg, pb, pa := src.At(sx0, sy0).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + pa1 := 0xffff - pa + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } +} + +func (nnInterpolator) transform_Image_Image_Src(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + pr, pg, pb, pa := src.At(sx0, sy0).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + if dstMask != nil { + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } else { + dstColorRGBA64.R = uint16(pr) + dstColorRGBA64.G = uint16(pg) + dstColorRGBA64.B = uint16(pb) + dstColorRGBA64.A = uint16(pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } +} + +func (z ablInterpolator) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) { + // Try to simplify a Scale to a Copy when DstMask is not specified. + // If DstMask is not nil, Copy will call Scale back with same dr and sr, and cause stack overflow. + if dr.Size() == sr.Size() && (opts == nil || opts.DstMask == nil) { + Copy(dst, dr.Min, src, sr, op, opts) + return + } + + var o Options + if opts != nil { + o = *opts + } + + // adr is the affected destination pixels. + adr := dst.Bounds().Intersect(dr) + adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP) + if adr.Empty() || sr.Empty() { + return + } + // Make adr relative to dr.Min. + adr = adr.Sub(dr.Min) + if op == Over && o.SrcMask == nil && opaque(src) { + op = Src + } + + // sr is the source pixels. If it extends beyond the src bounds, + // we cannot use the type-specific fast paths, as they access + // the Pix fields directly without bounds checking. + // + // Similarly, the fast paths assume that the masks are nil. + if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) { + switch op { + case Over: + z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o) + case Src: + z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o) + } + } else if _, ok := src.(*image.Uniform); ok { + Draw(dst, dr, src, src.Bounds().Min, op) + } else { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.NRGBA: + z.scale_RGBA_NRGBA_Over(dst, dr, adr, src, sr, &o) + case *image.RGBA: + z.scale_RGBA_RGBA_Over(dst, dr, adr, src, sr, &o) + case image.RGBA64Image: + z.scale_RGBA_RGBA64Image_Over(dst, dr, adr, src, sr, &o) + default: + z.scale_RGBA_Image_Over(dst, dr, adr, src, sr, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.scale_RGBA64Image_RGBA64Image_Over(dst, dr, adr, src, sr, &o) + } + default: + switch src := src.(type) { + default: + z.scale_Image_Image_Over(dst, dr, adr, src, sr, &o) + } + } + case Src: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.Gray: + z.scale_RGBA_Gray_Src(dst, dr, adr, src, sr, &o) + case *image.NRGBA: + z.scale_RGBA_NRGBA_Src(dst, dr, adr, src, sr, &o) + case *image.RGBA: + z.scale_RGBA_RGBA_Src(dst, dr, adr, src, sr, &o) + case *image.YCbCr: + switch src.SubsampleRatio { + default: + z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio444: + z.scale_RGBA_YCbCr444_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio422: + z.scale_RGBA_YCbCr422_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio420: + z.scale_RGBA_YCbCr420_Src(dst, dr, adr, src, sr, &o) + case image.YCbCrSubsampleRatio440: + z.scale_RGBA_YCbCr440_Src(dst, dr, adr, src, sr, &o) + } + case image.RGBA64Image: + z.scale_RGBA_RGBA64Image_Src(dst, dr, adr, src, sr, &o) + default: + z.scale_RGBA_Image_Src(dst, dr, adr, src, sr, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.scale_RGBA64Image_RGBA64Image_Src(dst, dr, adr, src, sr, &o) + } + default: + switch src := src.(type) { + default: + z.scale_Image_Image_Src(dst, dr, adr, src, sr, &o) + } + } + } + } +} + +func (z ablInterpolator) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) { + // Try to simplify a Transform to a Copy. + if s2d[0] == 1 && s2d[1] == 0 && s2d[3] == 0 && s2d[4] == 1 { + dx := int(s2d[2]) + dy := int(s2d[5]) + if float64(dx) == s2d[2] && float64(dy) == s2d[5] { + Copy(dst, image.Point{X: sr.Min.X + dx, Y: sr.Min.X + dy}, src, sr, op, opts) + return + } + } + + var o Options + if opts != nil { + o = *opts + } + + dr := transformRect(&s2d, &sr) + // adr is the affected destination pixels. + adr := dst.Bounds().Intersect(dr) + adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP) + if adr.Empty() || sr.Empty() { + return + } + if op == Over && o.SrcMask == nil && opaque(src) { + op = Src + } + + d2s := invert(&s2d) + // bias is a translation of the mapping from dst coordinates to src + // coordinates such that the latter temporarily have non-negative X + // and Y coordinates. This allows us to write int(f) instead of + // int(math.Floor(f)), since "round to zero" and "round down" are + // equivalent when f >= 0, but the former is much cheaper. The X-- + // and Y-- are because the TransformLeaf methods have a "sx -= 0.5" + // adjustment. + bias := transformRect(&d2s, &adr).Min + bias.X-- + bias.Y-- + d2s[2] -= float64(bias.X) + d2s[5] -= float64(bias.Y) + // Make adr relative to dr.Min. + adr = adr.Sub(dr.Min) + // sr is the source pixels. If it extends beyond the src bounds, + // we cannot use the type-specific fast paths, as they access + // the Pix fields directly without bounds checking. + // + // Similarly, the fast paths assume that the masks are nil. + if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) { + switch op { + case Over: + z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + case Src: + z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + } else if u, ok := src.(*image.Uniform); ok { + transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op) + } else { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.NRGBA: + z.transform_RGBA_NRGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.RGBA: + z.transform_RGBA_RGBA_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.RGBA64Image: + z.transform_RGBA_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + default: + z.transform_RGBA_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.transform_RGBA64Image_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + } + default: + switch src := src.(type) { + default: + z.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, &o) + } + } + case Src: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.Gray: + z.transform_RGBA_Gray_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.NRGBA: + z.transform_RGBA_NRGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.RGBA: + z.transform_RGBA_RGBA_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case *image.YCbCr: + switch src.SubsampleRatio { + default: + z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio444: + z.transform_RGBA_YCbCr444_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio422: + z.transform_RGBA_YCbCr422_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio420: + z.transform_RGBA_YCbCr420_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + case image.YCbCrSubsampleRatio440: + z.transform_RGBA_YCbCr440_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + case image.RGBA64Image: + z.transform_RGBA_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + default: + z.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + z.transform_RGBA64Image_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + default: + switch src := src.(type) { + default: + z.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, &o) + } + } + } + } +} + +func (ablInterpolator) scale_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.Gray, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s00ru := uint32(src.Pix[s00i]) * 0x101 + s00r := float64(s00ru) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s10ru := uint32(src.Pix[s10i]) * 0x101 + s10r := float64(s10ru) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s01ru := uint32(src.Pix[s01i]) * 0x101 + s01r := float64(s01ru) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s11ru := uint32(src.Pix[s11i]) * 0x101 + s11r := float64(s11ru) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + pr := uint32(s11r) + out := uint8(pr >> 8) + dst.Pix[d+0] = out + dst.Pix[d+1] = out + dst.Pix[d+2] = out + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) scale_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff + s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff + s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff + s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff + s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff + s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff + s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff + s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff + s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.NRGBA, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff + s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff + s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff + s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff + s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff + s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff + s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff + s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff + s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s00ru := uint32(src.Pix[s00i+0]) * 0x101 + s00gu := uint32(src.Pix[s00i+1]) * 0x101 + s00bu := uint32(src.Pix[s00i+2]) * 0x101 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s10ru := uint32(src.Pix[s10i+0]) * 0x101 + s10gu := uint32(src.Pix[s10i+1]) * 0x101 + s10bu := uint32(src.Pix[s10i+2]) * 0x101 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s01ru := uint32(src.Pix[s01i+0]) * 0x101 + s01gu := uint32(src.Pix[s01i+1]) * 0x101 + s01bu := uint32(src.Pix[s01i+2]) * 0x101 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s11ru := uint32(src.Pix[s11i+0]) * 0x101 + s11gu := uint32(src.Pix[s11i+1]) * 0x101 + s11bu := uint32(src.Pix[s11i+2]) * 0x101 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.RGBA, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s00ru := uint32(src.Pix[s00i+0]) * 0x101 + s00gu := uint32(src.Pix[s00i+1]) * 0x101 + s00bu := uint32(src.Pix[s00i+2]) * 0x101 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s10ru := uint32(src.Pix[s10i+0]) * 0x101 + s10gu := uint32(src.Pix[s10i+1]) * 0x101 + s10bu := uint32(src.Pix[s10i+2]) * 0x101 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx0)-src.Rect.Min.X)*4 + s01ru := uint32(src.Pix[s01i+0]) * 0x101 + s01gu := uint32(src.Pix[s01i+1]) * 0x101 + s01bu := uint32(src.Pix[s01i+2]) * 0x101 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(sx1)-src.Rect.Min.X)*4 + s11ru := uint32(src.Pix[s11i+0]) * 0x101 + s11gu := uint32(src.Pix[s11i+1]) * 0x101 + s11bu := uint32(src.Pix[s11i+2]) * 0x101 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s00j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s10j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s01j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s11j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) scale_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s00j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s10j := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s01j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s11j := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) scale_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s00j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s10j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s01j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx0))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s11j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(sx1))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) scale_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, src *image.YCbCr, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s00j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sr.Min.Y+int(sy0)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s10j := ((sr.Min.Y+int(sy0))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + s01j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx0) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sr.Min.Y+int(sy1)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + s11j := ((sr.Min.Y+int(sy1))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(sx1) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) scale_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)) + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)) + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)) + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)) + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + pa1 := (0xffff - uint32(p.A)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)) + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)) + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)) + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)) + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + dst.Pix[d+0] = uint8(p.R >> 8) + dst.Pix[d+1] = uint8(p.G >> 8) + dst.Pix[d+2] = uint8(p.B >> 8) + dst.Pix[d+3] = uint8(p.A >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA() + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA() + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA() + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA() + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA() + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA() + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA() + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA() + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (ablInterpolator) scale_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s00u.R = uint16(uint32(s00u.R) * ma / 0xffff) + s00u.G = uint16(uint32(s00u.G) * ma / 0xffff) + s00u.B = uint16(uint32(s00u.B) * ma / 0xffff) + s00u.A = uint16(uint32(s00u.A) * ma / 0xffff) + } + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s10u.R = uint16(uint32(s10u.R) * ma / 0xffff) + s10u.G = uint16(uint32(s10u.G) * ma / 0xffff) + s10u.B = uint16(uint32(s10u.B) * ma / 0xffff) + s10u.A = uint16(uint32(s10u.A) * ma / 0xffff) + } + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s01u.R = uint16(uint32(s01u.R) * ma / 0xffff) + s01u.G = uint16(uint32(s01u.G) * ma / 0xffff) + s01u.B = uint16(uint32(s01u.B) * ma / 0xffff) + s01u.A = uint16(uint32(s01u.A) * ma / 0xffff) + } + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s11u.R = uint16(uint32(s11u.R) * ma / 0xffff) + s11u.G = uint16(uint32(s11u.G) * ma / 0xffff) + s11u.B = uint16(uint32(s11u.B) * ma / 0xffff) + s11u.A = uint16(uint32(s11u.A) * ma / 0xffff) + } + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + pa1 := 0xffff - uint32(p.A) + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } + } +} + +func (ablInterpolator) scale_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s00u.R = uint16(uint32(s00u.R) * ma / 0xffff) + s00u.G = uint16(uint32(s00u.G) * ma / 0xffff) + s00u.B = uint16(uint32(s00u.B) * ma / 0xffff) + s00u.A = uint16(uint32(s00u.A) * ma / 0xffff) + } + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s10u.R = uint16(uint32(s10u.R) * ma / 0xffff) + s10u.G = uint16(uint32(s10u.G) * ma / 0xffff) + s10u.B = uint16(uint32(s10u.B) * ma / 0xffff) + s10u.A = uint16(uint32(s10u.A) * ma / 0xffff) + } + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s01u.R = uint16(uint32(s01u.R) * ma / 0xffff) + s01u.G = uint16(uint32(s01u.G) * ma / 0xffff) + s01u.B = uint16(uint32(s01u.B) * ma / 0xffff) + s01u.A = uint16(uint32(s01u.A) * ma / 0xffff) + } + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s11u.R = uint16(uint32(s11u.R) * ma / 0xffff) + s11u.G = uint16(uint32(s11u.G) * ma / 0xffff) + s11u.B = uint16(uint32(s11u.B) * ma / 0xffff) + s11u.A = uint16(uint32(s11u.A) * ma / 0xffff) + } + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + if dstMask != nil { + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } else { + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p) + } + } + } +} + +func (ablInterpolator) scale_Image_Image_Over(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s00ru = s00ru * ma / 0xffff + s00gu = s00gu * ma / 0xffff + s00bu = s00bu * ma / 0xffff + s00au = s00au * ma / 0xffff + } + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s10ru = s10ru * ma / 0xffff + s10gu = s10gu * ma / 0xffff + s10bu = s10bu * ma / 0xffff + s10au = s10au * ma / 0xffff + } + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s01ru = s01ru * ma / 0xffff + s01gu = s01gu * ma / 0xffff + s01bu = s01bu * ma / 0xffff + s01au = s01au * ma / 0xffff + } + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s11ru = s11ru * ma / 0xffff + s11gu = s11gu * ma / 0xffff + s11bu = s11bu * ma / 0xffff + s11au = s11au * ma / 0xffff + } + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + pa1 := 0xffff - pa + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } +} + +func (ablInterpolator) scale_Image_Image_Src(dst Image, dr, adr image.Rectangle, src image.Image, sr image.Rectangle, opts *Options) { + sw := int32(sr.Dx()) + sh := int32(sr.Dy()) + yscale := float64(sh) / float64(dr.Dy()) + xscale := float64(sw) / float64(dr.Dx()) + swMinus1, shMinus1 := sw-1, sh-1 + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + sy := float64((float64(dy)+0.5)*yscale) - 0.5 + // If sy < 0, we will clamp sy0 to 0 anyway, so it doesn't matter if + // we say int32(sy) instead of int32(math.Floor(sy)). Similarly for + // sx, below. + sy0 := int32(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy1 := sy0 + 1 + if sy < 0 { + sy0, sy1 = 0, 0 + yFrac0, yFrac1 = 0, 1 + } else if sy1 > shMinus1 { + sy0, sy1 = shMinus1, shMinus1 + yFrac0, yFrac1 = 1, 0 + } + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + sx := float64((float64(dx)+0.5)*xscale) - 0.5 + sx0 := int32(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx1 := sx0 + 1 + if sx < 0 { + sx0, sx1 = 0, 0 + xFrac0, xFrac1 = 0, 1 + } else if sx1 > swMinus1 { + sx0, sx1 = swMinus1, swMinus1 + xFrac0, xFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy0)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s00ru = s00ru * ma / 0xffff + s00gu = s00gu * ma / 0xffff + s00bu = s00bu * ma / 0xffff + s00au = s00au * ma / 0xffff + } + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy0)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy0)).RGBA() + s10ru = s10ru * ma / 0xffff + s10gu = s10gu * ma / 0xffff + s10bu = s10bu * ma / 0xffff + s10au = s10au * ma / 0xffff + } + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sr.Min.X+int(sx0), sr.Min.Y+int(sy1)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx0), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s01ru = s01ru * ma / 0xffff + s01gu = s01gu * ma / 0xffff + s01bu = s01bu * ma / 0xffff + s01au = s01au * ma / 0xffff + } + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sr.Min.X+int(sx1), sr.Min.Y+int(sy1)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(sx1), smp.Y+sr.Min.Y+int(sy1)).RGBA() + s11ru = s11ru * ma / 0xffff + s11gu = s11gu * ma / 0xffff + s11bu = s11bu * ma / 0xffff + s11au = s11au * ma / 0xffff + } + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + if dstMask != nil { + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } else { + dstColorRGBA64.R = uint16(pr) + dstColorRGBA64.G = uint16(pg) + dstColorRGBA64.B = uint16(pb) + dstColorRGBA64.A = uint16(pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } +} + +func (ablInterpolator) transform_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Gray, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0 - src.Rect.Min.X) + s00ru := uint32(src.Pix[s00i]) * 0x101 + s00r := float64(s00ru) + s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1 - src.Rect.Min.X) + s10ru := uint32(src.Pix[s10i]) * 0x101 + s10r := float64(s10ru) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0 - src.Rect.Min.X) + s01ru := uint32(src.Pix[s01i]) * 0x101 + s01r := float64(s01ru) + s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1 - src.Rect.Min.X) + s11ru := uint32(src.Pix[s11i]) * 0x101 + s11r := float64(s11ru) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + pr := uint32(s11r) + out := uint8(pr >> 8) + dst.Pix[d+0] = out + dst.Pix[d+1] = out + dst.Pix[d+2] = out + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) transform_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff + s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff + s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff + s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff + s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff + s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff + s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff + s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff + s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00ru := uint32(src.Pix[s00i+0]) * s00au / 0xff + s00gu := uint32(src.Pix[s00i+1]) * s00au / 0xff + s00bu := uint32(src.Pix[s00i+2]) * s00au / 0xff + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10ru := uint32(src.Pix[s10i+0]) * s10au / 0xff + s10gu := uint32(src.Pix[s10i+1]) * s10au / 0xff + s10bu := uint32(src.Pix[s10i+2]) * s10au / 0xff + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01ru := uint32(src.Pix[s01i+0]) * s01au / 0xff + s01gu := uint32(src.Pix[s01i+1]) * s01au / 0xff + s01bu := uint32(src.Pix[s01i+2]) * s01au / 0xff + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11ru := uint32(src.Pix[s11i+0]) * s11au / 0xff + s11gu := uint32(src.Pix[s11i+1]) * s11au / 0xff + s11bu := uint32(src.Pix[s11i+2]) * s11au / 0xff + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s00ru := uint32(src.Pix[s00i+0]) * 0x101 + s00gu := uint32(src.Pix[s00i+1]) * 0x101 + s00bu := uint32(src.Pix[s00i+2]) * 0x101 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s10ru := uint32(src.Pix[s10i+0]) * 0x101 + s10gu := uint32(src.Pix[s10i+1]) * 0x101 + s10bu := uint32(src.Pix[s10i+2]) * 0x101 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s01ru := uint32(src.Pix[s01i+0]) * 0x101 + s01gu := uint32(src.Pix[s01i+1]) * 0x101 + s01bu := uint32(src.Pix[s01i+2]) * 0x101 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s11ru := uint32(src.Pix[s11i+0]) * 0x101 + s11gu := uint32(src.Pix[s11i+1]) * 0x101 + s11bu := uint32(src.Pix[s11i+2]) * 0x101 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s00ru := uint32(src.Pix[s00i+0]) * 0x101 + s00gu := uint32(src.Pix[s00i+1]) * 0x101 + s00bu := uint32(src.Pix[s00i+2]) * 0x101 + s00au := uint32(src.Pix[s00i+3]) * 0x101 + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10i := (sy0-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s10ru := uint32(src.Pix[s10i+0]) * 0x101 + s10gu := uint32(src.Pix[s10i+1]) * 0x101 + s10bu := uint32(src.Pix[s10i+2]) * 0x101 + s10au := uint32(src.Pix[s10i+3]) * 0x101 + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01i := (sy1-src.Rect.Min.Y)*src.Stride + (sx0-src.Rect.Min.X)*4 + s01ru := uint32(src.Pix[s01i+0]) * 0x101 + s01gu := uint32(src.Pix[s01i+1]) * 0x101 + s01bu := uint32(src.Pix[s01i+2]) * 0x101 + s01au := uint32(src.Pix[s01i+3]) * 0x101 + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11i := (sy1-src.Rect.Min.Y)*src.Stride + (sx1-src.Rect.Min.X)*4 + s11ru := uint32(src.Pix[s11i+0]) * 0x101 + s11gu := uint32(src.Pix[s11i+1]) * 0x101 + s11bu := uint32(src.Pix[s11i+2]) * 0x101 + s11au := uint32(src.Pix[s11i+3]) * 0x101 + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s00j := (sy0-src.Rect.Min.Y)*src.CStride + (sx0 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s10j := (sy0-src.Rect.Min.Y)*src.CStride + (sx1 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s01j := (sy1-src.Rect.Min.Y)*src.CStride + (sx0 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s11j := (sy1-src.Rect.Min.Y)*src.CStride + (sx1 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) transform_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s00j := (sy0-src.Rect.Min.Y)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s10j := (sy0-src.Rect.Min.Y)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s01j := (sy1-src.Rect.Min.Y)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s11j := (sy1-src.Rect.Min.Y)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) transform_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s00j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s10j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s01j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + ((sx0)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s11j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + ((sx1)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) transform_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00i := (sy0-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s00j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + (sx0 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s00yy1 := int(src.Y[s00i]) * 0x10101 + s00cb1 := int(src.Cb[s00j]) - 128 + s00cr1 := int(src.Cr[s00j]) - 128 + s00ru := (s00yy1 + 91881*s00cr1) >> 8 + s00gu := (s00yy1 - 22554*s00cb1 - 46802*s00cr1) >> 8 + s00bu := (s00yy1 + 116130*s00cb1) >> 8 + if s00ru < 0 { + s00ru = 0 + } else if s00ru > 0xffff { + s00ru = 0xffff + } + if s00gu < 0 { + s00gu = 0 + } else if s00gu > 0xffff { + s00gu = 0xffff + } + if s00bu < 0 { + s00bu = 0 + } else if s00bu > 0xffff { + s00bu = 0xffff + } + + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s10i := (sy0-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s10j := ((sy0)/2-src.Rect.Min.Y/2)*src.CStride + (sx1 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s10yy1 := int(src.Y[s10i]) * 0x10101 + s10cb1 := int(src.Cb[s10j]) - 128 + s10cr1 := int(src.Cr[s10j]) - 128 + s10ru := (s10yy1 + 91881*s10cr1) >> 8 + s10gu := (s10yy1 - 22554*s10cb1 - 46802*s10cr1) >> 8 + s10bu := (s10yy1 + 116130*s10cb1) >> 8 + if s10ru < 0 { + s10ru = 0 + } else if s10ru > 0xffff { + s10ru = 0xffff + } + if s10gu < 0 { + s10gu = 0 + } else if s10gu > 0xffff { + s10gu = 0xffff + } + if s10bu < 0 { + s10bu = 0 + } else if s10bu > 0xffff { + s10bu = 0xffff + } + + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s01i := (sy1-src.Rect.Min.Y)*src.YStride + (sx0 - src.Rect.Min.X) + s01j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + (sx0 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s01yy1 := int(src.Y[s01i]) * 0x10101 + s01cb1 := int(src.Cb[s01j]) - 128 + s01cr1 := int(src.Cr[s01j]) - 128 + s01ru := (s01yy1 + 91881*s01cr1) >> 8 + s01gu := (s01yy1 - 22554*s01cb1 - 46802*s01cr1) >> 8 + s01bu := (s01yy1 + 116130*s01cb1) >> 8 + if s01ru < 0 { + s01ru = 0 + } else if s01ru > 0xffff { + s01ru = 0xffff + } + if s01gu < 0 { + s01gu = 0 + } else if s01gu > 0xffff { + s01gu = 0xffff + } + if s01bu < 0 { + s01bu = 0 + } else if s01bu > 0xffff { + s01bu = 0xffff + } + + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s11i := (sy1-src.Rect.Min.Y)*src.YStride + (sx1 - src.Rect.Min.X) + s11j := ((sy1)/2-src.Rect.Min.Y/2)*src.CStride + (sx1 - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + s11yy1 := int(src.Y[s11i]) * 0x10101 + s11cb1 := int(src.Cb[s11j]) - 128 + s11cr1 := int(src.Cr[s11j]) - 128 + s11ru := (s11yy1 + 91881*s11cr1) >> 8 + s11gu := (s11yy1 - 22554*s11cb1 - 46802*s11cr1) >> 8 + s11bu := (s11yy1 + 116130*s11cb1) >> 8 + if s11ru < 0 { + s11ru = 0 + } else if s11ru > 0xffff { + s11ru = 0xffff + } + if s11gu < 0 { + s11gu = 0 + } else if s11gu > 0xffff { + s11gu = 0xffff + } + if s11bu < 0 { + s11bu = 0 + } else if s11bu > 0xffff { + s11bu = 0xffff + } + + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (ablInterpolator) transform_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sx0, sy0) + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sx1, sy0) + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sx0, sy1) + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sx1, sy1) + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + pa1 := (0xffff - uint32(p.A)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + uint32(p.R)) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + uint32(p.G)) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + uint32(p.B)) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + uint32(p.A)) >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sx0, sy0) + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sx1, sy0) + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sx0, sy1) + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sx1, sy1) + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + dst.Pix[d+0] = uint8(p.R >> 8) + dst.Pix[d+1] = uint8(p.G >> 8) + dst.Pix[d+2] = uint8(p.B >> 8) + dst.Pix[d+3] = uint8(p.A >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA() + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA() + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA() + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA() + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + pa1 := (0xffff - pa) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA() + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA() + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA() + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA() + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + dst.Pix[d+0] = uint8(pr >> 8) + dst.Pix[d+1] = uint8(pg >> 8) + dst.Pix[d+2] = uint8(pb >> 8) + dst.Pix[d+3] = uint8(pa >> 8) + } + } +} + +func (ablInterpolator) transform_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sx0, sy0) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + s00u.R = uint16(uint32(s00u.R) * ma / 0xffff) + s00u.G = uint16(uint32(s00u.G) * ma / 0xffff) + s00u.B = uint16(uint32(s00u.B) * ma / 0xffff) + s00u.A = uint16(uint32(s00u.A) * ma / 0xffff) + } + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sx1, sy0) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA() + s10u.R = uint16(uint32(s10u.R) * ma / 0xffff) + s10u.G = uint16(uint32(s10u.G) * ma / 0xffff) + s10u.B = uint16(uint32(s10u.B) * ma / 0xffff) + s10u.A = uint16(uint32(s10u.A) * ma / 0xffff) + } + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sx0, sy1) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA() + s01u.R = uint16(uint32(s01u.R) * ma / 0xffff) + s01u.G = uint16(uint32(s01u.G) * ma / 0xffff) + s01u.B = uint16(uint32(s01u.B) * ma / 0xffff) + s01u.A = uint16(uint32(s01u.A) * ma / 0xffff) + } + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sx1, sy1) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA() + s11u.R = uint16(uint32(s11u.R) * ma / 0xffff) + s11u.G = uint16(uint32(s11u.G) * ma / 0xffff) + s11u.B = uint16(uint32(s11u.B) * ma / 0xffff) + s11u.A = uint16(uint32(s11u.A) * ma / 0xffff) + } + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + } + pa1 := 0xffff - uint32(p.A) + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } + } +} + +func (ablInterpolator) transform_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00u := src.RGBA64At(sx0, sy0) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + s00u.R = uint16(uint32(s00u.R) * ma / 0xffff) + s00u.G = uint16(uint32(s00u.G) * ma / 0xffff) + s00u.B = uint16(uint32(s00u.B) * ma / 0xffff) + s00u.A = uint16(uint32(s00u.A) * ma / 0xffff) + } + s00r := float64(s00u.R) + s00g := float64(s00u.G) + s00b := float64(s00u.B) + s00a := float64(s00u.A) + s10u := src.RGBA64At(sx1, sy0) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA() + s10u.R = uint16(uint32(s10u.R) * ma / 0xffff) + s10u.G = uint16(uint32(s10u.G) * ma / 0xffff) + s10u.B = uint16(uint32(s10u.B) * ma / 0xffff) + s10u.A = uint16(uint32(s10u.A) * ma / 0xffff) + } + s10r := float64(s10u.R) + s10g := float64(s10u.G) + s10b := float64(s10u.B) + s10a := float64(s10u.A) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01u := src.RGBA64At(sx0, sy1) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA() + s01u.R = uint16(uint32(s01u.R) * ma / 0xffff) + s01u.G = uint16(uint32(s01u.G) * ma / 0xffff) + s01u.B = uint16(uint32(s01u.B) * ma / 0xffff) + s01u.A = uint16(uint32(s01u.A) * ma / 0xffff) + } + s01r := float64(s01u.R) + s01g := float64(s01u.G) + s01b := float64(s01u.B) + s01a := float64(s01u.A) + s11u := src.RGBA64At(sx1, sy1) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA() + s11u.R = uint16(uint32(s11u.R) * ma / 0xffff) + s11u.G = uint16(uint32(s11u.G) * ma / 0xffff) + s11u.B = uint16(uint32(s11u.B) * ma / 0xffff) + s11u.A = uint16(uint32(s11u.A) * ma / 0xffff) + } + s11r := float64(s11u.R) + s11g := float64(s11u.G) + s11b := float64(s11u.B) + s11a := float64(s11u.A) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + p := color.RGBA64{uint16(s11r), uint16(s11g), uint16(s11b), uint16(s11a)} + if dstMask != nil { + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + p.R = uint16(uint32(p.R) * ma / 0xffff) + p.G = uint16(uint32(p.G) * ma / 0xffff) + p.B = uint16(uint32(p.B) * ma / 0xffff) + p.A = uint16(uint32(p.A) * ma / 0xffff) + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + uint32(p.R)) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + uint32(p.G)) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + uint32(p.B)) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + uint32(p.A)) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } else { + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), p) + } + } + } +} + +func (ablInterpolator) transform_Image_Image_Over(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + s00ru = s00ru * ma / 0xffff + s00gu = s00gu * ma / 0xffff + s00bu = s00bu * ma / 0xffff + s00au = s00au * ma / 0xffff + } + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA() + s10ru = s10ru * ma / 0xffff + s10gu = s10gu * ma / 0xffff + s10bu = s10bu * ma / 0xffff + s10au = s10au * ma / 0xffff + } + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA() + s01ru = s01ru * ma / 0xffff + s01gu = s01gu * ma / 0xffff + s01bu = s01bu * ma / 0xffff + s01au = s01au * ma / 0xffff + } + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA() + s11ru = s11ru * ma / 0xffff + s11gu = s11gu * ma / 0xffff + s11bu = s11bu * ma / 0xffff + s11au = s11au * ma / 0xffff + } + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + } + pa1 := 0xffff - pa + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } +} + +func (ablInterpolator) transform_Image_Image_Src(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, opts *Options) { + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + sx -= 0.5 + sx0 := int(sx) + xFrac0 := sx - float64(sx0) + xFrac1 := 1 - xFrac0 + sx0 += bias.X + sx1 := sx0 + 1 + if sx0 < sr.Min.X { + sx0, sx1 = sr.Min.X, sr.Min.X + xFrac0, xFrac1 = 0, 1 + } else if sx1 >= sr.Max.X { + sx0, sx1 = sr.Max.X-1, sr.Max.X-1 + xFrac0, xFrac1 = 1, 0 + } + + sy -= 0.5 + sy0 := int(sy) + yFrac0 := sy - float64(sy0) + yFrac1 := 1 - yFrac0 + sy0 += bias.Y + sy1 := sy0 + 1 + if sy0 < sr.Min.Y { + sy0, sy1 = sr.Min.Y, sr.Min.Y + yFrac0, yFrac1 = 0, 1 + } else if sy1 >= sr.Max.Y { + sy0, sy1 = sr.Max.Y-1, sr.Max.Y-1 + yFrac0, yFrac1 = 1, 0 + } + + s00ru, s00gu, s00bu, s00au := src.At(sx0, sy0).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy0).RGBA() + s00ru = s00ru * ma / 0xffff + s00gu = s00gu * ma / 0xffff + s00bu = s00bu * ma / 0xffff + s00au = s00au * ma / 0xffff + } + s00r := float64(s00ru) + s00g := float64(s00gu) + s00b := float64(s00bu) + s00a := float64(s00au) + s10ru, s10gu, s10bu, s10au := src.At(sx1, sy0).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy0).RGBA() + s10ru = s10ru * ma / 0xffff + s10gu = s10gu * ma / 0xffff + s10bu = s10bu * ma / 0xffff + s10au = s10au * ma / 0xffff + } + s10r := float64(s10ru) + s10g := float64(s10gu) + s10b := float64(s10bu) + s10a := float64(s10au) + s10r = float64(xFrac1*s00r) + float64(xFrac0*s10r) + s10g = float64(xFrac1*s00g) + float64(xFrac0*s10g) + s10b = float64(xFrac1*s00b) + float64(xFrac0*s10b) + s10a = float64(xFrac1*s00a) + float64(xFrac0*s10a) + s01ru, s01gu, s01bu, s01au := src.At(sx0, sy1).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx0, smp.Y+sy1).RGBA() + s01ru = s01ru * ma / 0xffff + s01gu = s01gu * ma / 0xffff + s01bu = s01bu * ma / 0xffff + s01au = s01au * ma / 0xffff + } + s01r := float64(s01ru) + s01g := float64(s01gu) + s01b := float64(s01bu) + s01a := float64(s01au) + s11ru, s11gu, s11bu, s11au := src.At(sx1, sy1).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sx1, smp.Y+sy1).RGBA() + s11ru = s11ru * ma / 0xffff + s11gu = s11gu * ma / 0xffff + s11bu = s11bu * ma / 0xffff + s11au = s11au * ma / 0xffff + } + s11r := float64(s11ru) + s11g := float64(s11gu) + s11b := float64(s11bu) + s11a := float64(s11au) + s11r = float64(xFrac1*s01r) + float64(xFrac0*s11r) + s11g = float64(xFrac1*s01g) + float64(xFrac0*s11g) + s11b = float64(xFrac1*s01b) + float64(xFrac0*s11b) + s11a = float64(xFrac1*s01a) + float64(xFrac0*s11a) + s11r = float64(yFrac1*s10r) + float64(yFrac0*s11r) + s11g = float64(yFrac1*s10g) + float64(yFrac0*s11g) + s11b = float64(yFrac1*s10b) + float64(yFrac0*s11b) + s11a = float64(yFrac1*s10a) + float64(yFrac0*s11a) + pr := uint32(s11r) + pg := uint32(s11g) + pb := uint32(s11b) + pa := uint32(s11a) + if dstMask != nil { + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr = pr * ma / 0xffff + pg = pg * ma / 0xffff + pb = pb * ma / 0xffff + pa = pa * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } else { + dstColorRGBA64.R = uint16(pr) + dstColorRGBA64.G = uint16(pg) + dstColorRGBA64.B = uint16(pb) + dstColorRGBA64.A = uint16(pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } +} + +func (z *kernelScaler) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) { + if z.dw != int32(dr.Dx()) || z.dh != int32(dr.Dy()) || z.sw != int32(sr.Dx()) || z.sh != int32(sr.Dy()) { + z.kernel.Scale(dst, dr, src, sr, op, opts) + return + } + + var o Options + if opts != nil { + o = *opts + } + + // adr is the affected destination pixels. + adr := dst.Bounds().Intersect(dr) + adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP) + if adr.Empty() || sr.Empty() { + return + } + // Make adr relative to dr.Min. + adr = adr.Sub(dr.Min) + if op == Over && o.SrcMask == nil && opaque(src) { + op = Src + } + + if _, ok := src.(*image.Uniform); ok && o.DstMask == nil && o.SrcMask == nil && sr.In(src.Bounds()) { + Draw(dst, dr, src, src.Bounds().Min, op) + return + } + + // Create a temporary buffer: + // scaleX distributes the source image's columns over the temporary image. + // scaleY distributes the temporary image's rows over the destination image. + var tmp [][4]float64 + if z.pool.New != nil { + tmpp := z.pool.Get().(*[][4]float64) + defer z.pool.Put(tmpp) + tmp = *tmpp + } else { + tmp = z.makeTmpBuf() + } + + // sr is the source pixels. If it extends beyond the src bounds, + // we cannot use the type-specific fast paths, as they access + // the Pix fields directly without bounds checking. + // + // Similarly, the fast paths assume that the masks are nil. + if o.SrcMask != nil || !sr.In(src.Bounds()) { + z.scaleX_Image(tmp, src, sr, &o) + } else { + switch src := src.(type) { + case *image.Gray: + z.scaleX_Gray(tmp, src, sr, &o) + case *image.NRGBA: + z.scaleX_NRGBA(tmp, src, sr, &o) + case *image.RGBA: + z.scaleX_RGBA(tmp, src, sr, &o) + case *image.YCbCr: + switch src.SubsampleRatio { + default: + z.scaleX_Image(tmp, src, sr, &o) + case image.YCbCrSubsampleRatio444: + z.scaleX_YCbCr444(tmp, src, sr, &o) + case image.YCbCrSubsampleRatio422: + z.scaleX_YCbCr422(tmp, src, sr, &o) + case image.YCbCrSubsampleRatio420: + z.scaleX_YCbCr420(tmp, src, sr, &o) + case image.YCbCrSubsampleRatio440: + z.scaleX_YCbCr440(tmp, src, sr, &o) + } + case image.RGBA64Image: + z.scaleX_RGBA64Image(tmp, src, sr, &o) + default: + z.scaleX_Image(tmp, src, sr, &o) + } + } + + if o.DstMask != nil { + switch op { + case Over: + z.scaleY_Image_Over(dst, dr, adr, tmp, &o) + case Src: + z.scaleY_Image_Src(dst, dr, adr, tmp, &o) + } + } else { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + z.scaleY_RGBA_Over(dst, dr, adr, tmp, &o) + case RGBA64Image: + z.scaleY_RGBA64Image_Over(dst, dr, adr, tmp, &o) + default: + z.scaleY_Image_Over(dst, dr, adr, tmp, &o) + } + case Src: + switch dst := dst.(type) { + case *image.RGBA: + z.scaleY_RGBA_Src(dst, dr, adr, tmp, &o) + case RGBA64Image: + z.scaleY_RGBA64Image_Src(dst, dr, adr, tmp, &o) + default: + z.scaleY_Image_Src(dst, dr, adr, tmp, &o) + } + } + } +} + +func (q *Kernel) Transform(dst Image, s2d f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) { + var o Options + if opts != nil { + o = *opts + } + + dr := transformRect(&s2d, &sr) + // adr is the affected destination pixels. + adr := dst.Bounds().Intersect(dr) + adr, o.DstMask = clipAffectedDestRect(adr, o.DstMask, o.DstMaskP) + if adr.Empty() || sr.Empty() { + return + } + if op == Over && o.SrcMask == nil && opaque(src) { + op = Src + } + d2s := invert(&s2d) + // bias is a translation of the mapping from dst coordinates to src + // coordinates such that the latter temporarily have non-negative X + // and Y coordinates. This allows us to write int(f) instead of + // int(math.Floor(f)), since "round to zero" and "round down" are + // equivalent when f >= 0, but the former is much cheaper. The X-- + // and Y-- are because the TransformLeaf methods have a "sx -= 0.5" + // adjustment. + bias := transformRect(&d2s, &adr).Min + bias.X-- + bias.Y-- + d2s[2] -= float64(bias.X) + d2s[5] -= float64(bias.Y) + // Make adr relative to dr.Min. + adr = adr.Sub(dr.Min) + + if u, ok := src.(*image.Uniform); ok && o.DstMask != nil && o.SrcMask != nil && sr.In(src.Bounds()) { + transform_Uniform(dst, dr, adr, &d2s, u, sr, bias, op) + return + } + + xscale := abs(d2s[0]) + if s := abs(d2s[1]); xscale < s { + xscale = s + } + yscale := abs(d2s[3]) + if s := abs(d2s[4]); yscale < s { + yscale = s + } + + // sr is the source pixels. If it extends beyond the src bounds, + // we cannot use the type-specific fast paths, as they access + // the Pix fields directly without bounds checking. + // + // Similarly, the fast paths assume that the masks are nil. + if o.DstMask != nil || o.SrcMask != nil || !sr.In(src.Bounds()) { + switch op { + case Over: + q.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case Src: + q.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + } else { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.NRGBA: + q.transform_RGBA_NRGBA_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case *image.RGBA: + q.transform_RGBA_RGBA_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case image.RGBA64Image: + q.transform_RGBA_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + default: + q.transform_RGBA_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + q.transform_RGBA64Image_RGBA64Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + default: + switch src := src.(type) { + default: + q.transform_Image_Image_Over(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + } + case Src: + switch dst := dst.(type) { + case *image.RGBA: + switch src := src.(type) { + case *image.Gray: + q.transform_RGBA_Gray_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case *image.NRGBA: + q.transform_RGBA_NRGBA_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case *image.RGBA: + q.transform_RGBA_RGBA_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case *image.YCbCr: + switch src.SubsampleRatio { + default: + q.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case image.YCbCrSubsampleRatio444: + q.transform_RGBA_YCbCr444_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case image.YCbCrSubsampleRatio422: + q.transform_RGBA_YCbCr422_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case image.YCbCrSubsampleRatio420: + q.transform_RGBA_YCbCr420_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + case image.YCbCrSubsampleRatio440: + q.transform_RGBA_YCbCr440_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + case image.RGBA64Image: + q.transform_RGBA_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + default: + q.transform_RGBA_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + case RGBA64Image: + switch src := src.(type) { + case image.RGBA64Image: + q.transform_RGBA64Image_RGBA64Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + default: + switch src := src.(type) { + default: + q.transform_Image_Image_Src(dst, dr, adr, &d2s, src, sr, bias, xscale, yscale, &o) + } + } + } + } +} + +func (z *kernelScaler) scaleX_Gray(tmp [][4]float64, src *image.Gray, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.Stride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + pru := uint32(src.Pix[pi]) * 0x101 + pr += float64(float64(pru) * c.weight) + } + pr *= s.invTotalWeightFFFF + tmp[t] = [4]float64{ + pr, + pr, + pr, + 1, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_NRGBA(tmp [][4]float64, src *image.NRGBA, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb, pa float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(c.coord)-src.Rect.Min.X)*4 + pau := uint32(src.Pix[pi+3]) * 0x101 + pru := uint32(src.Pix[pi+0]) * pau / 0xff + pgu := uint32(src.Pix[pi+1]) * pau / 0xff + pbu := uint32(src.Pix[pi+2]) * pau / 0xff + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + pa += float64(float64(pau) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + pa * s.invTotalWeightFFFF, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_RGBA(tmp [][4]float64, src *image.RGBA, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb, pa float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.Stride + (sr.Min.X+int(c.coord)-src.Rect.Min.X)*4 + pru := uint32(src.Pix[pi+0]) * 0x101 + pgu := uint32(src.Pix[pi+1]) * 0x101 + pbu := uint32(src.Pix[pi+2]) * 0x101 + pau := uint32(src.Pix[pi+3]) * 0x101 + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + pa += float64(float64(pau) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + pa * s.invTotalWeightFFFF, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_YCbCr444(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + pj := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.CStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + 1, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_YCbCr422(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + pj := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.CStride + ((sr.Min.X+int(c.coord))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + 1, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_YCbCr420(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + pj := ((sr.Min.Y+int(y))/2-src.Rect.Min.Y/2)*src.CStride + ((sr.Min.X+int(c.coord))/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + 1, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_YCbCr440(tmp [][4]float64, src *image.YCbCr, sr image.Rectangle, opts *Options) { + t := 0 + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pi := (sr.Min.Y+int(y)-src.Rect.Min.Y)*src.YStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + pj := ((sr.Min.Y+int(y))/2-src.Rect.Min.Y/2)*src.CStride + (sr.Min.X + int(c.coord) - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + 1, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_RGBA64Image(tmp [][4]float64, src image.RGBA64Image, sr image.Rectangle, opts *Options) { + t := 0 + srcMask, smp := opts.SrcMask, opts.SrcMaskP + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb, pa float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pu := src.RGBA64At(sr.Min.X+int(c.coord), sr.Min.Y+int(y)) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(c.coord), smp.Y+sr.Min.Y+int(y)).RGBA() + pu.R = uint16(uint32(pu.R) * ma / 0xffff) + pu.G = uint16(uint32(pu.G) * ma / 0xffff) + pu.B = uint16(uint32(pu.B) * ma / 0xffff) + pu.A = uint16(uint32(pu.A) * ma / 0xffff) + } + pr += float64(float64(pu.R) * c.weight) + pg += float64(float64(pu.G) * c.weight) + pb += float64(float64(pu.B) * c.weight) + pa += float64(float64(pu.A) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + pa * s.invTotalWeightFFFF, + } + t++ + } + } +} + +func (z *kernelScaler) scaleX_Image(tmp [][4]float64, src image.Image, sr image.Rectangle, opts *Options) { + t := 0 + srcMask, smp := opts.SrcMask, opts.SrcMaskP + for y := int32(0); y < z.sh; y++ { + for _, s := range z.horizontal.sources { + var pr, pg, pb, pa float64 + for _, c := range z.horizontal.contribs[s.i:s.j] { + pru, pgu, pbu, pau := src.At(sr.Min.X+int(c.coord), sr.Min.Y+int(y)).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+sr.Min.X+int(c.coord), smp.Y+sr.Min.Y+int(y)).RGBA() + pru = pru * ma / 0xffff + pgu = pgu * ma / 0xffff + pbu = pbu * ma / 0xffff + pau = pau * ma / 0xffff + } + pr += float64(float64(pru) * c.weight) + pg += float64(float64(pgu) * c.weight) + pb += float64(float64(pbu) * c.weight) + pa += float64(float64(pau) * c.weight) + } + tmp[t] = [4]float64{ + pr * s.invTotalWeightFFFF, + pg * s.invTotalWeightFFFF, + pb * s.invTotalWeightFFFF, + pa * s.invTotalWeightFFFF, + } + t++ + } + } +} + +func (z *kernelScaler) scaleY_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) { + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + d := (dr.Min.Y+adr.Min.Y-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+int(dx)-dst.Rect.Min.X)*4 + for _, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { + var pr, pg, pb, pa float64 + for _, c := range z.vertical.contribs[s.i:s.j] { + p := &tmp[c.coord*z.dw+dx] + pr += float64(p[0] * c.weight) + pg += float64(p[1] * c.weight) + pb += float64(p[2] * c.weight) + pa += float64(p[3] * c.weight) + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + pr0 := uint32(ftou(pr * s.invTotalWeight)) + pg0 := uint32(ftou(pg * s.invTotalWeight)) + pb0 := uint32(ftou(pb * s.invTotalWeight)) + pa0 := uint32(ftou(pa * s.invTotalWeight)) + pa1 := (0xffff - uint32(pa0)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8) + d += dst.Stride + } + } +} + +func (z *kernelScaler) scaleY_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) { + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + d := (dr.Min.Y+adr.Min.Y-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+int(dx)-dst.Rect.Min.X)*4 + for _, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { + var pr, pg, pb, pa float64 + for _, c := range z.vertical.contribs[s.i:s.j] { + p := &tmp[c.coord*z.dw+dx] + pr += float64(p[0] * c.weight) + pg += float64(p[1] * c.weight) + pb += float64(p[2] * c.weight) + pa += float64(p[3] * c.weight) + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + dst.Pix[d+0] = uint8(ftou(pr*s.invTotalWeight) >> 8) + dst.Pix[d+1] = uint8(ftou(pg*s.invTotalWeight) >> 8) + dst.Pix[d+2] = uint8(ftou(pb*s.invTotalWeight) >> 8) + dst.Pix[d+3] = uint8(ftou(pa*s.invTotalWeight) >> 8) + d += dst.Stride + } + } +} + +func (z *kernelScaler) scaleY_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) { + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { + var pr, pg, pb, pa float64 + for _, c := range z.vertical.contribs[s.i:s.j] { + p := &tmp[c.coord*z.dw+dx] + pr += float64(p[0] * c.weight) + pg += float64(p[1] * c.weight) + pb += float64(p[2] * c.weight) + pa += float64(p[3] * c.weight) + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy)) + pr0 := uint32(ftou(pr * s.invTotalWeight)) + pg0 := uint32(ftou(pg * s.invTotalWeight)) + pb0 := uint32(ftou(pb * s.invTotalWeight)) + pa0 := uint32(ftou(pa * s.invTotalWeight)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA() + pr0 = pr0 * ma / 0xffff + pg0 = pg0 * ma / 0xffff + pb0 = pb0 * ma / 0xffff + pa0 = pa0 * ma / 0xffff + } + pa1 := 0xffff - pa0 + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr0) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg0) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb0) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa0) + dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColorRGBA64) + } + } +} + +func (z *kernelScaler) scaleY_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) { + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { + var pr, pg, pb, pa float64 + for _, c := range z.vertical.contribs[s.i:s.j] { + p := &tmp[c.coord*z.dw+dx] + pr += float64(p[0] * c.weight) + pg += float64(p[1] * c.weight) + pb += float64(p[2] * c.weight) + pa += float64(p[3] * c.weight) + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + if dstMask != nil { + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy)) + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA() + pr := uint32(ftou(pr*s.invTotalWeight)) * ma / 0xffff + pg := uint32(ftou(pg*s.invTotalWeight)) * ma / 0xffff + pb := uint32(ftou(pb*s.invTotalWeight)) * ma / 0xffff + pa := uint32(ftou(pa*s.invTotalWeight)) * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa) + dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColorRGBA64) + } else { + dstColorRGBA64.R = ftou(pr * s.invTotalWeight) + dstColorRGBA64.G = ftou(pg * s.invTotalWeight) + dstColorRGBA64.B = ftou(pb * s.invTotalWeight) + dstColorRGBA64.A = ftou(pa * s.invTotalWeight) + dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColorRGBA64) + } + } + } +} + +func (z *kernelScaler) scaleY_Image_Over(dst Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) { + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { + var pr, pg, pb, pa float64 + for _, c := range z.vertical.contribs[s.i:s.j] { + p := &tmp[c.coord*z.dw+dx] + pr += float64(p[0] * c.weight) + pg += float64(p[1] * c.weight) + pb += float64(p[2] * c.weight) + pa += float64(p[3] * c.weight) + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy)).RGBA() + pr0 := uint32(ftou(pr * s.invTotalWeight)) + pg0 := uint32(ftou(pg * s.invTotalWeight)) + pb0 := uint32(ftou(pb * s.invTotalWeight)) + pa0 := uint32(ftou(pa * s.invTotalWeight)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA() + pr0 = pr0 * ma / 0xffff + pg0 = pg0 * ma / 0xffff + pb0 = pb0 * ma / 0xffff + pa0 = pa0 * ma / 0xffff + } + pa1 := 0xffff - pa0 + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr0) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg0) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb0) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa0) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColor) + } + } +} + +func (z *kernelScaler) scaleY_Image_Src(dst Image, dr, adr image.Rectangle, tmp [][4]float64, opts *Options) { + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + for dy, s := range z.vertical.sources[adr.Min.Y:adr.Max.Y] { + var pr, pg, pb, pa float64 + for _, c := range z.vertical.contribs[s.i:s.j] { + p := &tmp[c.coord*z.dw+dx] + pr += float64(p[0] * c.weight) + pg += float64(p[1] * c.weight) + pb += float64(p[2] * c.weight) + pa += float64(p[3] * c.weight) + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + if dstMask != nil { + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy)).RGBA() + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(adr.Min.Y+dy)).RGBA() + pr := uint32(ftou(pr*s.invTotalWeight)) * ma / 0xffff + pg := uint32(ftou(pg*s.invTotalWeight)) * ma / 0xffff + pb := uint32(ftou(pb*s.invTotalWeight)) * ma / 0xffff + pa := uint32(ftou(pa*s.invTotalWeight)) * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColor) + } else { + dstColorRGBA64.R = ftou(pr * s.invTotalWeight) + dstColorRGBA64.G = ftou(pg * s.invTotalWeight) + dstColorRGBA64.B = ftou(pb * s.invTotalWeight) + dstColorRGBA64.A = ftou(pa * s.invTotalWeight) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(adr.Min.Y+dy), dstColor) + } + } + } +} + +func (q *Kernel) transform_RGBA_Gray_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Gray, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.Stride + (kx - src.Rect.Min.X) + pru := uint32(src.Pix[pi]) * 0x101 + pr += float64(float64(pru) * w) + } + } + } + } + out := uint8(fffftou(pr) >> 8) + dst.Pix[d+0] = out + dst.Pix[d+1] = out + dst.Pix[d+2] = out + dst.Pix[d+3] = 0xff + } + } +} + +func (q *Kernel) transform_RGBA_NRGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4 + pau := uint32(src.Pix[pi+3]) * 0x101 + pru := uint32(src.Pix[pi+0]) * pau / 0xff + pgu := uint32(src.Pix[pi+1]) * pau / 0xff + pbu := uint32(src.Pix[pi+2]) * pau / 0xff + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + pr0 := uint32(fffftou(pr)) + pg0 := uint32(fffftou(pg)) + pb0 := uint32(fffftou(pb)) + pa0 := uint32(fffftou(pa)) + pa1 := (0xffff - uint32(pa0)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_NRGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.NRGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4 + pau := uint32(src.Pix[pi+3]) * 0x101 + pru := uint32(src.Pix[pi+0]) * pau / 0xff + pgu := uint32(src.Pix[pi+1]) * pau / 0xff + pbu := uint32(src.Pix[pi+2]) * pau / 0xff + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = uint8(fffftou(pa) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_RGBA_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4 + pru := uint32(src.Pix[pi+0]) * 0x101 + pgu := uint32(src.Pix[pi+1]) * 0x101 + pbu := uint32(src.Pix[pi+2]) * 0x101 + pau := uint32(src.Pix[pi+3]) * 0x101 + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + pr0 := uint32(fffftou(pr)) + pg0 := uint32(fffftou(pg)) + pb0 := uint32(fffftou(pb)) + pa0 := uint32(fffftou(pa)) + pa1 := (0xffff - uint32(pa0)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_RGBA_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.RGBA, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.Stride + (kx-src.Rect.Min.X)*4 + pru := uint32(src.Pix[pi+0]) * 0x101 + pgu := uint32(src.Pix[pi+1]) * 0x101 + pbu := uint32(src.Pix[pi+2]) * 0x101 + pau := uint32(src.Pix[pi+3]) * 0x101 + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = uint8(fffftou(pa) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_YCbCr444_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X) + pj := (ky-src.Rect.Min.Y)*src.CStride + (kx - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + } + } + } + } + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (q *Kernel) transform_RGBA_YCbCr422_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X) + pj := (ky-src.Rect.Min.Y)*src.CStride + ((kx)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + } + } + } + } + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (q *Kernel) transform_RGBA_YCbCr420_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X) + pj := ((ky)/2-src.Rect.Min.Y/2)*src.CStride + ((kx)/2 - src.Rect.Min.X/2) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + } + } + } + } + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (q *Kernel) transform_RGBA_YCbCr440_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.YCbCr, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pi := (ky-src.Rect.Min.Y)*src.YStride + (kx - src.Rect.Min.X) + pj := ((ky)/2-src.Rect.Min.Y/2)*src.CStride + (kx - src.Rect.Min.X) + + // This is an inline version of image/color/ycbcr.go's YCbCr.RGBA method. + pyy1 := int(src.Y[pi]) * 0x10101 + pcb1 := int(src.Cb[pj]) - 128 + pcr1 := int(src.Cr[pj]) - 128 + pru := (pyy1 + 91881*pcr1) >> 8 + pgu := (pyy1 - 22554*pcb1 - 46802*pcr1) >> 8 + pbu := (pyy1 + 116130*pcb1) >> 8 + if pru < 0 { + pru = 0 + } else if pru > 0xffff { + pru = 0xffff + } + if pgu < 0 { + pgu = 0 + } else if pgu > 0xffff { + pgu = 0xffff + } + if pbu < 0 { + pbu = 0 + } else if pbu > 0xffff { + pbu = 0xffff + } + + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + } + } + } + } + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = 0xff + } + } +} + +func (q *Kernel) transform_RGBA_RGBA64Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pu := src.RGBA64At(kx, ky) + pr += float64(float64(pu.R) * w) + pg += float64(float64(pu.G) * w) + pb += float64(float64(pu.B) * w) + pa += float64(float64(pu.A) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + pr0 := uint32(fffftou(pr)) + pg0 := uint32(fffftou(pg)) + pb0 := uint32(fffftou(pb)) + pa0 := uint32(fffftou(pa)) + pa1 := (0xffff - uint32(pa0)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_RGBA64Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pu := src.RGBA64At(kx, ky) + pr += float64(float64(pu.R) * w) + pg += float64(float64(pu.G) * w) + pb += float64(float64(pu.B) * w) + pa += float64(float64(pu.A) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = uint8(fffftou(pa) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_Image_Over(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pru, pgu, pbu, pau := src.At(kx, ky).RGBA() + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + pr0 := uint32(fffftou(pr)) + pg0 := uint32(fffftou(pg)) + pb0 := uint32(fffftou(pb)) + pa0 := uint32(fffftou(pa)) + pa1 := (0xffff - uint32(pa0)) * 0x101 + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr0) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg0) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb0) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa0) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA_Image_Src(dst *image.RGBA, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := (dr.Min.Y+int(dy)-dst.Rect.Min.Y)*dst.Stride + (dr.Min.X+adr.Min.X-dst.Rect.Min.X)*4 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pru, pgu, pbu, pau := src.At(kx, ky).RGBA() + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + dst.Pix[d+0] = uint8(fffftou(pr) >> 8) + dst.Pix[d+1] = uint8(fffftou(pg) >> 8) + dst.Pix[d+2] = uint8(fffftou(pb) >> 8) + dst.Pix[d+3] = uint8(fffftou(pa) >> 8) + } + } +} + +func (q *Kernel) transform_RGBA64Image_RGBA64Image_Over(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pu := src.RGBA64At(kx, ky) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA() + pu.R = uint16(uint32(pu.R) * ma / 0xffff) + pu.G = uint16(uint32(pu.G) * ma / 0xffff) + pu.B = uint16(uint32(pu.B) * ma / 0xffff) + pu.A = uint16(uint32(pu.A) * ma / 0xffff) + } + pr += float64(float64(pu.R) * w) + pg += float64(float64(pu.G) * w) + pb += float64(float64(pu.B) * w) + pa += float64(float64(pu.A) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + pr0 := uint32(fffftou(pr)) + pg0 := uint32(fffftou(pg)) + pb0 := uint32(fffftou(pb)) + pa0 := uint32(fffftou(pa)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr0 = pr0 * ma / 0xffff + pg0 = pg0 * ma / 0xffff + pb0 = pb0 * ma / 0xffff + pa0 = pa0 * ma / 0xffff + } + pa1 := 0xffff - pa0 + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr0) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg0) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb0) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa0) + dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } + } +} + +func (q *Kernel) transform_RGBA64Image_RGBA64Image_Src(dst RGBA64Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.RGBA64Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := color.RGBA64{} + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pu := src.RGBA64At(kx, ky) + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA() + pu.R = uint16(uint32(pu.R) * ma / 0xffff) + pu.G = uint16(uint32(pu.G) * ma / 0xffff) + pu.B = uint16(uint32(pu.B) * ma / 0xffff) + pu.A = uint16(uint32(pu.A) * ma / 0xffff) + } + pr += float64(float64(pu.R) * w) + pg += float64(float64(pu.G) * w) + pb += float64(float64(pu.B) * w) + pa += float64(float64(pu.A) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + if dstMask != nil { + q := dst.RGBA64At(dr.Min.X+int(dx), dr.Min.Y+int(dy)) + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr := uint32(fffftou(pr)) * ma / 0xffff + pg := uint32(fffftou(pg)) * ma / 0xffff + pb := uint32(fffftou(pb)) * ma / 0xffff + pa := uint32(fffftou(pa)) * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(uint32(q.R)*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(uint32(q.G)*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(uint32(q.B)*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(uint32(q.A)*pa1/0xffff + pa) + dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } else { + dstColorRGBA64.R = fffftou(pr) + dstColorRGBA64.G = fffftou(pg) + dstColorRGBA64.B = fffftou(pb) + dstColorRGBA64.A = fffftou(pa) + dst.SetRGBA64(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColorRGBA64) + } + } + } +} + +func (q *Kernel) transform_Image_Image_Over(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pru, pgu, pbu, pau := src.At(kx, ky).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA() + pru = pru * ma / 0xffff + pgu = pgu * ma / 0xffff + pbu = pbu * ma / 0xffff + pau = pau * ma / 0xffff + } + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + pr0 := uint32(fffftou(pr)) + pg0 := uint32(fffftou(pg)) + pb0 := uint32(fffftou(pb)) + pa0 := uint32(fffftou(pa)) + if dstMask != nil { + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr0 = pr0 * ma / 0xffff + pg0 = pg0 * ma / 0xffff + pb0 = pb0 * ma / 0xffff + pa0 = pa0 * ma / 0xffff + } + pa1 := 0xffff - pa0 + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr0) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg0) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb0) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa0) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } +} + +func (q *Kernel) transform_Image_Image_Src(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src image.Image, sr image.Rectangle, bias image.Point, xscale, yscale float64, opts *Options) { + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + xHalfWidth, xKernelArgScale := q.Support, 1.0 + if xscale > 1 { + xHalfWidth *= xscale + xKernelArgScale = 1 / xscale + } + yHalfWidth, yKernelArgScale := q.Support, 1.0 + if yscale > 1 { + yHalfWidth *= yscale + yKernelArgScale = 1 / yscale + } + + xWeights := make([]float64, 1+2*int(math.Ceil(xHalfWidth))) + yWeights := make([]float64, 1+2*int(math.Ceil(yHalfWidth))) + + srcMask, smp := opts.SrcMask, opts.SrcMaskP + dstMask, dmp := opts.DstMask, opts.DstMaskP + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx := float64(d2s[0]*dxf) + float64(d2s[1]*dyf) + d2s[2] + sy := float64(d2s[3]*dxf) + float64(d2s[4]*dyf) + d2s[5] + if !(image.Point{int(sx) + bias.X, int(sy) + bias.Y}).In(sr) { + continue + } + + // TODO: adjust the bias so that we can use int(f) instead + // of math.Floor(f) and math.Ceil(f). + sx += float64(bias.X) + sx -= 0.5 + ix := int(math.Floor(sx - xHalfWidth)) + if ix < sr.Min.X { + ix = sr.Min.X + } + jx := int(math.Ceil(sx + xHalfWidth)) + if jx > sr.Max.X { + jx = sr.Max.X + } + + totalXWeight := 0.0 + for kx := ix; kx < jx; kx++ { + xWeight := 0.0 + if t := abs((sx - float64(kx)) * xKernelArgScale); t < q.Support { + xWeight = q.At(t) + } + xWeights[kx-ix] = xWeight + totalXWeight += xWeight + } + for x := range xWeights[:jx-ix] { + xWeights[x] /= totalXWeight + } + + sy += float64(bias.Y) + sy -= 0.5 + iy := int(math.Floor(sy - yHalfWidth)) + if iy < sr.Min.Y { + iy = sr.Min.Y + } + jy := int(math.Ceil(sy + yHalfWidth)) + if jy > sr.Max.Y { + jy = sr.Max.Y + } + + totalYWeight := 0.0 + for ky := iy; ky < jy; ky++ { + yWeight := 0.0 + if t := abs((sy - float64(ky)) * yKernelArgScale); t < q.Support { + yWeight = q.At(t) + } + yWeights[ky-iy] = yWeight + totalYWeight += yWeight + } + for y := range yWeights[:jy-iy] { + yWeights[y] /= totalYWeight + } + + var pr, pg, pb, pa float64 + for ky := iy; ky < jy; ky++ { + if yWeight := yWeights[ky-iy]; yWeight != 0 { + for kx := ix; kx < jx; kx++ { + if w := xWeights[kx-ix] * yWeight; w != 0 { + pru, pgu, pbu, pau := src.At(kx, ky).RGBA() + if srcMask != nil { + _, _, _, ma := srcMask.At(smp.X+kx, smp.Y+ky).RGBA() + pru = pru * ma / 0xffff + pgu = pgu * ma / 0xffff + pbu = pbu * ma / 0xffff + pau = pau * ma / 0xffff + } + pr += float64(float64(pru) * w) + pg += float64(float64(pgu) * w) + pb += float64(float64(pbu) * w) + pa += float64(float64(pau) * w) + } + } + } + } + + if pr > pa { + pr = pa + } + if pg > pa { + pg = pa + } + if pb > pa { + pb = pa + } + + if dstMask != nil { + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + _, _, _, ma := dstMask.At(dmp.X+dr.Min.X+int(dx), dmp.Y+dr.Min.Y+int(dy)).RGBA() + pr := uint32(fffftou(pr)) * ma / 0xffff + pg := uint32(fffftou(pg)) * ma / 0xffff + pb := uint32(fffftou(pb)) * ma / 0xffff + pa := uint32(fffftou(pa)) * ma / 0xffff + pa1 := 0xffff - ma + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } else { + dstColorRGBA64.R = fffftou(pr) + dstColorRGBA64.G = fffftou(pg) + dstColorRGBA64.B = fffftou(pb) + dstColorRGBA64.A = fffftou(pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } +} diff --git a/vendor/golang.org/x/image/draw/scale.go b/vendor/golang.org/x/image/draw/scale.go new file mode 100644 index 0000000..aef200b --- /dev/null +++ b/vendor/golang.org/x/image/draw/scale.go @@ -0,0 +1,525 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:generate go run gen.go + +package draw + +import ( + "image" + "image/color" + "math" + "sync" + + "golang.org/x/image/math/f64" +) + +// Copy copies the part of the source image defined by src and sr and writes +// the result of a Porter-Duff composition to the part of the destination image +// defined by dst and the translation of sr so that sr.Min translates to dp. +func Copy(dst Image, dp image.Point, src image.Image, sr image.Rectangle, op Op, opts *Options) { + var o Options + if opts != nil { + o = *opts + } + dr := sr.Add(dp.Sub(sr.Min)) + if o.DstMask == nil { + DrawMask(dst, dr, src, sr.Min, o.SrcMask, o.SrcMaskP.Add(sr.Min), op) + } else { + NearestNeighbor.Scale(dst, dr, src, sr, op, opts) + } +} + +// Scaler scales the part of the source image defined by src and sr and writes +// the result of a Porter-Duff composition to the part of the destination image +// defined by dst and dr. +// +// A Scaler is safe to use concurrently. +type Scaler interface { + Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) +} + +// Transformer transforms the part of the source image defined by src and sr +// and writes the result of a Porter-Duff composition to the part of the +// destination image defined by dst and the affine transform m applied to sr. +// +// For example, if m is the matrix +// +// m00 m01 m02 +// m10 m11 m12 +// +// then the src-space point (sx, sy) maps to the dst-space point +// (m00*sx + m01*sy + m02, m10*sx + m11*sy + m12). +// +// A Transformer is safe to use concurrently. +type Transformer interface { + Transform(dst Image, m f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options) +} + +// Options are optional parameters to Copy, Scale and Transform. +// +// A nil *Options means to use the default (zero) values of each field. +type Options struct { + // Masks limit what parts of the dst image are drawn to and what parts of + // the src image are drawn from. + // + // A dst or src mask image having a zero alpha (transparent) pixel value in + // the respective coordinate space means that dst pixel is entirely + // unaffected or that src pixel is considered transparent black. A full + // alpha (opaque) value means that the dst pixel is maximally affected or + // the src pixel contributes maximally. The default values, nil, are + // equivalent to fully opaque, infinitely large mask images. + // + // The DstMask is otherwise known as a clip mask, and its pixels map 1:1 to + // the dst image's pixels. DstMaskP in DstMask space corresponds to + // image.Point{X:0, Y:0} in dst space. For example, when limiting + // repainting to a 'dirty rectangle', use that image.Rectangle and a zero + // image.Point as the DstMask and DstMaskP. + // + // The SrcMask's pixels map 1:1 to the src image's pixels. SrcMaskP in + // SrcMask space corresponds to image.Point{X:0, Y:0} in src space. For + // example, when drawing font glyphs in a uniform color, use an + // *image.Uniform as the src, and use the glyph atlas image and the + // per-glyph offset as SrcMask and SrcMaskP: + // Copy(dst, dp, image.NewUniform(color), image.Rect(0, 0, glyphWidth, glyphHeight), &Options{ + // SrcMask: glyphAtlas, + // SrcMaskP: glyphOffset, + // }) + DstMask image.Image + DstMaskP image.Point + SrcMask image.Image + SrcMaskP image.Point + + // TODO: a smooth vs sharp edges option, for arbitrary rotations? +} + +// Interpolator is an interpolation algorithm, when dst and src pixels don't +// have a 1:1 correspondence. +// +// Of the interpolators provided by this package: +// - NearestNeighbor is fast but usually looks worst. +// - CatmullRom is slow but usually looks best. +// - ApproxBiLinear has reasonable speed and quality. +// +// The time taken depends on the size of dr. For kernel interpolators, the +// speed also depends on the size of sr, and so are often slower than +// non-kernel interpolators, especially when scaling down. +type Interpolator interface { + Scaler + Transformer +} + +// Kernel is an interpolator that blends source pixels weighted by a symmetric +// kernel function. +type Kernel struct { + // Support is the kernel support and must be >= 0. At(t) is assumed to be + // zero when t >= Support. + Support float64 + // At is the kernel function. It will only be called with t in the + // range [0, Support). + At func(t float64) float64 +} + +// Scale implements the Scaler interface. +func (q *Kernel) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) { + q.newScaler(dr.Dx(), dr.Dy(), sr.Dx(), sr.Dy(), false).Scale(dst, dr, src, sr, op, opts) +} + +// NewScaler returns a Scaler that is optimized for scaling multiple times with +// the same fixed destination and source width and height. +func (q *Kernel) NewScaler(dw, dh, sw, sh int) Scaler { + return q.newScaler(dw, dh, sw, sh, true) +} + +func (q *Kernel) newScaler(dw, dh, sw, sh int, usePool bool) Scaler { + z := &kernelScaler{ + kernel: q, + dw: int32(dw), + dh: int32(dh), + sw: int32(sw), + sh: int32(sh), + horizontal: newDistrib(q, int32(dw), int32(sw)), + vertical: newDistrib(q, int32(dh), int32(sh)), + } + if usePool { + z.pool.New = func() interface{} { + tmp := z.makeTmpBuf() + return &tmp + } + } + return z +} + +var ( + // NearestNeighbor is the nearest neighbor interpolator. It is very fast, + // but usually gives very low quality results. When scaling up, the result + // will look 'blocky'. + NearestNeighbor = Interpolator(nnInterpolator{}) + + // ApproxBiLinear is a mixture of the nearest neighbor and bi-linear + // interpolators. It is fast, but usually gives medium quality results. + // + // It implements bi-linear interpolation when upscaling and a bi-linear + // blend of the 4 nearest neighbor pixels when downscaling. This yields + // nicer quality than nearest neighbor interpolation when upscaling, but + // the time taken is independent of the number of source pixels, unlike the + // bi-linear interpolator. When downscaling a large image, the performance + // difference can be significant. + ApproxBiLinear = Interpolator(ablInterpolator{}) + + // BiLinear is the tent kernel. It is slow, but usually gives high quality + // results. + BiLinear = &Kernel{1, func(t float64) float64 { + return 1 - t + }} + + // CatmullRom is the Catmull-Rom kernel. It is very slow, but usually gives + // very high quality results. + // + // It is an instance of the more general cubic BC-spline kernel with parameters + // B=0 and C=0.5. See Mitchell and Netravali, "Reconstruction Filters in + // Computer Graphics", Computer Graphics, Vol. 22, No. 4, pp. 221-228. + CatmullRom = &Kernel{2, func(t float64) float64 { + if t < 1 { + return float64((float64(1.5*t)-2.5)*t*t) + 1 + } + return float64((float64(float64(float64(-0.5*t)+2.5)*t)-4)*t) + 2 + }} + + // TODO: a Kaiser-Bessel kernel? +) + +type nnInterpolator struct{} + +type ablInterpolator struct{} + +type kernelScaler struct { + kernel *Kernel + dw, dh, sw, sh int32 + horizontal, vertical distrib + pool sync.Pool +} + +func (z *kernelScaler) makeTmpBuf() [][4]float64 { + return make([][4]float64, z.dw*z.sh) +} + +// source is a range of contribs, their inverse total weight, and that ITW +// divided by 0xffff. +type source struct { + i, j int32 + invTotalWeight float64 + invTotalWeightFFFF float64 +} + +// contrib is the weight of a column or row. +type contrib struct { + coord int32 + weight float64 +} + +// distrib measures how source pixels are distributed over destination pixels. +type distrib struct { + // sources are what contribs each column or row in the source image owns, + // and the total weight of those contribs. + sources []source + // contribs are the contributions indexed by sources[s].i and sources[s].j. + contribs []contrib +} + +// newDistrib returns a distrib that distributes sw source columns (or rows) +// over dw destination columns (or rows). +func newDistrib(q *Kernel, dw, sw int32) distrib { + scale := float64(sw) / float64(dw) + halfWidth, kernelArgScale := q.Support, 1.0 + // When shrinking, broaden the effective kernel support so that we still + // visit every source pixel. + if scale > 1 { + halfWidth *= scale + kernelArgScale = 1 / scale + } + + // Make the sources slice, one source for each column or row, and temporarily + // appropriate its elements' fields so that invTotalWeight is the scaled + // coordinate of the source column or row, and i and j are the lower and + // upper bounds of the range of destination columns or rows affected by the + // source column or row. + n, sources := int32(0), make([]source, dw) + for x := range sources { + center := float64((float64(x)+0.5)*scale) - 0.5 + i := int32(math.Floor(center - halfWidth)) + if i < 0 { + i = 0 + } + j := int32(math.Ceil(center + halfWidth)) + if j > sw { + j = sw + if j < i { + j = i + } + } + sources[x] = source{i: i, j: j, invTotalWeight: center} + n += j - i + } + + contribs := make([]contrib, 0, n) + for k, b := range sources { + totalWeight := 0.0 + l := int32(len(contribs)) + for coord := b.i; coord < b.j; coord++ { + t := abs((b.invTotalWeight - float64(coord)) * kernelArgScale) + if t >= q.Support { + continue + } + weight := q.At(t) + if weight == 0 { + continue + } + totalWeight += weight + contribs = append(contribs, contrib{coord, weight}) + } + totalWeight = 1 / totalWeight + sources[k] = source{ + i: l, + j: int32(len(contribs)), + invTotalWeight: totalWeight, + invTotalWeightFFFF: totalWeight / 0xffff, + } + } + + return distrib{sources, contribs} +} + +// abs is like math.Abs, but it doesn't care about negative zero, infinities or +// NaNs. +func abs(f float64) float64 { + if f < 0 { + f = -f + } + return f +} + +// ftou converts the range [0.0, 1.0] to [0, 0xffff]. +func ftou(f float64) uint16 { + i := int32(float64(0xffff*f) + 0.5) + if i > 0xffff { + return 0xffff + } + if i > 0 { + return uint16(i) + } + return 0 +} + +// fffftou converts the range [0.0, 65535.0] to [0, 0xffff]. +func fffftou(f float64) uint16 { + i := int32(f + 0.5) + if i > 0xffff { + return 0xffff + } + if i > 0 { + return uint16(i) + } + return 0 +} + +// invert returns the inverse of m. +// +// TODO: move this into the f64 package, once we work out the convention for +// matrix methods in that package: do they modify the receiver, take a dst +// pointer argument, or return a new value? +func invert(m *f64.Aff3) f64.Aff3 { + m00 := +m[3*1+1] + m01 := -m[3*0+1] + m02 := +float64(m[3*1+2]*m[3*0+1]) - float64(m[3*1+1]*m[3*0+2]) + m10 := -m[3*1+0] + m11 := +m[3*0+0] + m12 := +float64(m[3*1+0]*m[3*0+2]) - float64(m[3*1+2]*m[3*0+0]) + + det := float64(m00*m11) - float64(m10*m01) + + return f64.Aff3{ + m00 / det, + m01 / det, + m02 / det, + m10 / det, + m11 / det, + m12 / det, + } +} + +func matMul(p, q *f64.Aff3) f64.Aff3 { + return f64.Aff3{ + float64(p[3*0+0]*q[3*0+0]) + float64(p[3*0+1]*q[3*1+0]), + float64(p[3*0+0]*q[3*0+1]) + float64(p[3*0+1]*q[3*1+1]), + float64(p[3*0+0]*q[3*0+2]) + float64(p[3*0+1]*q[3*1+2]) + p[3*0+2], + float64(p[3*1+0]*q[3*0+0]) + float64(p[3*1+1]*q[3*1+0]), + float64(p[3*1+0]*q[3*0+1]) + float64(p[3*1+1]*q[3*1+1]), + float64(p[3*1+0]*q[3*0+2]) + float64(p[3*1+1]*q[3*1+2]) + p[3*1+2], + } +} + +// transformRect returns a rectangle dr that contains sr transformed by s2d. +func transformRect(s2d *f64.Aff3, sr *image.Rectangle) (dr image.Rectangle) { + ps := [...]image.Point{ + {sr.Min.X, sr.Min.Y}, + {sr.Max.X, sr.Min.Y}, + {sr.Min.X, sr.Max.Y}, + {sr.Max.X, sr.Max.Y}, + } + for i, p := range ps { + sxf := float64(p.X) + syf := float64(p.Y) + dx := int(math.Floor(float64(s2d[0]*sxf) + float64(s2d[1]*syf) + s2d[2])) + dy := int(math.Floor(float64(s2d[3]*sxf) + float64(s2d[4]*syf) + s2d[5])) + + // The +1 adjustments below are because an image.Rectangle is inclusive + // on the low end but exclusive on the high end. + + if i == 0 { + dr = image.Rectangle{ + Min: image.Point{dx + 0, dy + 0}, + Max: image.Point{dx + 1, dy + 1}, + } + continue + } + + if dr.Min.X > dx { + dr.Min.X = dx + } + dx++ + if dr.Max.X < dx { + dr.Max.X = dx + } + + if dr.Min.Y > dy { + dr.Min.Y = dy + } + dy++ + if dr.Max.Y < dy { + dr.Max.Y = dy + } + } + return dr +} + +func clipAffectedDestRect(adr image.Rectangle, dstMask image.Image, dstMaskP image.Point) (image.Rectangle, image.Image) { + if dstMask == nil { + return adr, nil + } + if r, ok := dstMask.(image.Rectangle); ok { + return adr.Intersect(r.Sub(dstMaskP)), nil + } + // TODO: clip to dstMask.Bounds() if the color model implies that out-of-bounds means 0 alpha? + return adr, dstMask +} + +func transform_Uniform(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Uniform, sr image.Rectangle, bias image.Point, op Op) { + switch op { + case Over: + switch dst := dst.(type) { + case *image.RGBA: + pr, pg, pb, pa := src.C.RGBA() + pa1 := (0xffff - pa) * 0x101 + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := dst.PixOffset(dr.Min.X+adr.Min.X, dr.Min.Y+int(dy)) + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8) + dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8) + dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8) + dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8) + } + } + + default: + pr, pg, pb, pa := src.C.RGBA() + pa1 := 0xffff - pa + dstColorRGBA64 := &color.RGBA64{} + dstColor := color.Color(dstColorRGBA64) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA() + dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr) + dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg) + dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb) + dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa) + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } + + case Src: + switch dst := dst.(type) { + case *image.RGBA: + pr, pg, pb, pa := src.C.RGBA() + pr8 := uint8(pr >> 8) + pg8 := uint8(pg >> 8) + pb8 := uint8(pb >> 8) + pa8 := uint8(pa >> 8) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + d := dst.PixOffset(dr.Min.X+adr.Min.X, dr.Min.Y+int(dy)) + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + dst.Pix[d+0] = pr8 + dst.Pix[d+1] = pg8 + dst.Pix[d+2] = pb8 + dst.Pix[d+3] = pa8 + } + } + + default: + pr, pg, pb, pa := src.C.RGBA() + dstColorRGBA64 := &color.RGBA64{ + uint16(pr), + uint16(pg), + uint16(pb), + uint16(pa), + } + dstColor := color.Color(dstColorRGBA64) + + for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ { + dyf := float64(dr.Min.Y+int(dy)) + 0.5 + for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ { + dxf := float64(dr.Min.X+int(dx)) + 0.5 + sx0 := int(float64(d2s[0]*dxf)+float64(d2s[1]*dyf)+d2s[2]) + bias.X + sy0 := int(float64(d2s[3]*dxf)+float64(d2s[4]*dyf)+d2s[5]) + bias.Y + if !(image.Point{sx0, sy0}).In(sr) { + continue + } + dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor) + } + } + } + } +} + +func opaque(m image.Image) bool { + o, ok := m.(interface { + Opaque() bool + }) + return ok && o.Opaque() +} diff --git a/vendor/golang.org/x/image/math/f64/f64.go b/vendor/golang.org/x/image/math/f64/f64.go new file mode 100644 index 0000000..a1f7fc0 --- /dev/null +++ b/vendor/golang.org/x/image/math/f64/f64.go @@ -0,0 +1,37 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package f64 implements float64 vector and matrix types. +package f64 // import "golang.org/x/image/math/f64" + +// Vec2 is a 2-element vector. +type Vec2 [2]float64 + +// Vec3 is a 3-element vector. +type Vec3 [3]float64 + +// Vec4 is a 4-element vector. +type Vec4 [4]float64 + +// Mat3 is a 3x3 matrix in row major order. +// +// m[3*r + c] is the element in the r'th row and c'th column. +type Mat3 [9]float64 + +// Mat4 is a 4x4 matrix in row major order. +// +// m[4*r + c] is the element in the r'th row and c'th column. +type Mat4 [16]float64 + +// Aff3 is a 3x3 affine transformation matrix in row major order, where the +// bottom row is implicitly [0 0 1]. +// +// m[3*r + c] is the element in the r'th row and c'th column. +type Aff3 [6]float64 + +// Aff4 is a 4x4 affine transformation matrix in row major order, where the +// bottom row is implicitly [0 0 0 1]. +// +// m[4*r + c] is the element in the r'th row and c'th column. +type Aff4 [12]float64 diff --git a/vendor/golang.org/x/image/riff/riff.go b/vendor/golang.org/x/image/riff/riff.go new file mode 100644 index 0000000..38dc0e5 --- /dev/null +++ b/vendor/golang.org/x/image/riff/riff.go @@ -0,0 +1,193 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package riff implements the Resource Interchange File Format, used by media +// formats such as AVI, WAVE and WEBP. +// +// A RIFF stream contains a sequence of chunks. Each chunk consists of an 8-byte +// header (containing a 4-byte chunk type and a 4-byte chunk length), the chunk +// data (presented as an io.Reader), and some padding bytes. +// +// A detailed description of the format is at +// http://www.tactilemedia.com/info/MCI_Control_Info.html +package riff // import "golang.org/x/image/riff" + +import ( + "errors" + "io" + "io/ioutil" + "math" +) + +var ( + errMissingPaddingByte = errors.New("riff: missing padding byte") + errMissingRIFFChunkHeader = errors.New("riff: missing RIFF chunk header") + errListSubchunkTooLong = errors.New("riff: list subchunk too long") + errShortChunkData = errors.New("riff: short chunk data") + errShortChunkHeader = errors.New("riff: short chunk header") + errStaleReader = errors.New("riff: stale reader") +) + +// u32 decodes the first four bytes of b as a little-endian integer. +func u32(b []byte) uint32 { + return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 +} + +const chunkHeaderSize = 8 + +// FourCC is a four character code. +type FourCC [4]byte + +// LIST is the "LIST" FourCC. +var LIST = FourCC{'L', 'I', 'S', 'T'} + +// NewReader returns the RIFF stream's form type, such as "AVI " or "WAVE", and +// its chunks as a *Reader. +func NewReader(r io.Reader) (formType FourCC, data *Reader, err error) { + var buf [chunkHeaderSize]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + if err == io.EOF || err == io.ErrUnexpectedEOF { + err = errMissingRIFFChunkHeader + } + return FourCC{}, nil, err + } + if buf[0] != 'R' || buf[1] != 'I' || buf[2] != 'F' || buf[3] != 'F' { + return FourCC{}, nil, errMissingRIFFChunkHeader + } + return NewListReader(u32(buf[4:]), r) +} + +// NewListReader returns a LIST chunk's list type, such as "movi" or "wavl", +// and its chunks as a *Reader. +func NewListReader(chunkLen uint32, chunkData io.Reader) (listType FourCC, data *Reader, err error) { + if chunkLen < 4 { + return FourCC{}, nil, errShortChunkData + } + z := &Reader{r: chunkData} + if _, err := io.ReadFull(chunkData, z.buf[:4]); err != nil { + if err == io.EOF || err == io.ErrUnexpectedEOF { + err = errShortChunkData + } + return FourCC{}, nil, err + } + z.totalLen = chunkLen - 4 + return FourCC{z.buf[0], z.buf[1], z.buf[2], z.buf[3]}, z, nil +} + +// Reader reads chunks from an underlying io.Reader. +type Reader struct { + r io.Reader + err error + + totalLen uint32 + chunkLen uint32 + + chunkReader *chunkReader + buf [chunkHeaderSize]byte + padded bool +} + +// Next returns the next chunk's ID, length and data. It returns io.EOF if there +// are no more chunks. The io.Reader returned becomes stale after the next Next +// call, and should no longer be used. +// +// It is valid to call Next even if all of the previous chunk's data has not +// been read. +func (z *Reader) Next() (chunkID FourCC, chunkLen uint32, chunkData io.Reader, err error) { + if z.err != nil { + return FourCC{}, 0, nil, z.err + } + + // Drain the rest of the previous chunk. + if z.chunkLen != 0 { + want := z.chunkLen + var got int64 + got, z.err = io.Copy(ioutil.Discard, z.chunkReader) + if z.err == nil && uint32(got) != want { + z.err = errShortChunkData + } + if z.err != nil { + return FourCC{}, 0, nil, z.err + } + } + z.chunkReader = nil + if z.padded { + if z.totalLen == 0 { + z.err = errListSubchunkTooLong + return FourCC{}, 0, nil, z.err + } + z.totalLen-- + _, z.err = io.ReadFull(z.r, z.buf[:1]) + if z.err != nil { + if z.err == io.EOF { + z.err = errMissingPaddingByte + } + return FourCC{}, 0, nil, z.err + } + } + + // We are done if we have no more data. + if z.totalLen == 0 { + z.err = io.EOF + return FourCC{}, 0, nil, z.err + } + + // Read the next chunk header. + if z.totalLen < chunkHeaderSize { + z.err = errShortChunkHeader + return FourCC{}, 0, nil, z.err + } + z.totalLen -= chunkHeaderSize + if _, z.err = io.ReadFull(z.r, z.buf[:chunkHeaderSize]); z.err != nil { + if z.err == io.EOF || z.err == io.ErrUnexpectedEOF { + z.err = errShortChunkHeader + } + return FourCC{}, 0, nil, z.err + } + chunkID = FourCC{z.buf[0], z.buf[1], z.buf[2], z.buf[3]} + z.chunkLen = u32(z.buf[4:]) + if z.chunkLen > z.totalLen { + z.err = errListSubchunkTooLong + return FourCC{}, 0, nil, z.err + } + z.padded = z.chunkLen&1 == 1 + z.chunkReader = &chunkReader{z} + return chunkID, z.chunkLen, z.chunkReader, nil +} + +type chunkReader struct { + z *Reader +} + +func (c *chunkReader) Read(p []byte) (int, error) { + if c != c.z.chunkReader { + return 0, errStaleReader + } + z := c.z + if z.err != nil { + if z.err == io.EOF { + return 0, errStaleReader + } + return 0, z.err + } + + n := int(z.chunkLen) + if n == 0 { + return 0, io.EOF + } + if n < 0 { + // Converting uint32 to int overflowed. + n = math.MaxInt32 + } + if n > len(p) { + n = len(p) + } + n, err := z.r.Read(p[:n]) + z.totalLen -= uint32(n) + z.chunkLen -= uint32(n) + if err != io.EOF { + z.err = err + } + return n, err +} diff --git a/vendor/golang.org/x/image/vp8/decode.go b/vendor/golang.org/x/image/vp8/decode.go new file mode 100644 index 0000000..2aa9fee --- /dev/null +++ b/vendor/golang.org/x/image/vp8/decode.go @@ -0,0 +1,403 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package vp8 implements a decoder for the VP8 lossy image format. +// +// The VP8 specification is RFC 6386. +package vp8 // import "golang.org/x/image/vp8" + +// This file implements the top-level decoding algorithm. + +import ( + "errors" + "image" + "io" +) + +// limitReader wraps an io.Reader to read at most n bytes from it. +type limitReader struct { + r io.Reader + n int +} + +// ReadFull reads exactly len(p) bytes into p. +func (r *limitReader) ReadFull(p []byte) error { + if len(p) > r.n { + return io.ErrUnexpectedEOF + } + n, err := io.ReadFull(r.r, p) + r.n -= n + return err +} + +// FrameHeader is a frame header, as specified in section 9.1. +type FrameHeader struct { + KeyFrame bool + VersionNumber uint8 + ShowFrame bool + FirstPartitionLen uint32 + Width int + Height int + XScale uint8 + YScale uint8 +} + +const ( + nSegment = 4 + nSegmentProb = 3 +) + +// segmentHeader holds segment-related header information. +type segmentHeader struct { + useSegment bool + updateMap bool + relativeDelta bool + quantizer [nSegment]int8 + filterStrength [nSegment]int8 + prob [nSegmentProb]uint8 +} + +const ( + nRefLFDelta = 4 + nModeLFDelta = 4 +) + +// filterHeader holds filter-related header information. +type filterHeader struct { + simple bool + level int8 + sharpness uint8 + useLFDelta bool + refLFDelta [nRefLFDelta]int8 + modeLFDelta [nModeLFDelta]int8 + perSegmentLevel [nSegment]int8 +} + +// mb is the per-macroblock decode state. A decoder maintains mbw+1 of these +// as it is decoding macroblocks left-to-right and top-to-bottom: mbw for the +// macroblocks in the row above, and one for the macroblock to the left. +type mb struct { + // pred is the predictor mode for the 4 bottom or right 4x4 luma regions. + pred [4]uint8 + // nzMask is a mask of 8 bits: 4 for the bottom or right 4x4 luma regions, + // and 2 + 2 for the bottom or right 4x4 chroma regions. A 1 bit indicates + // that region has non-zero coefficients. + nzMask uint8 + // nzY16 is a 0/1 value that is 1 if the macroblock used Y16 prediction and + // had non-zero coefficients. + nzY16 uint8 +} + +// Decoder decodes VP8 bitstreams into frames. Decoding one frame consists of +// calling Init, DecodeFrameHeader and then DecodeFrame in that order. +// A Decoder can be re-used to decode multiple frames. +type Decoder struct { + // r is the input bitsream. + r limitReader + // scratch is a scratch buffer. + scratch [8]byte + // img is the YCbCr image to decode into. + img *image.YCbCr + // mbw and mbh are the number of 16x16 macroblocks wide and high the image is. + mbw, mbh int + // frameHeader is the frame header. When decoding multiple frames, + // frames that aren't key frames will inherit the Width, Height, + // XScale and YScale of the most recent key frame. + frameHeader FrameHeader + // Other headers. + segmentHeader segmentHeader + filterHeader filterHeader + // The image data is divided into a number of independent partitions. + // There is 1 "first partition" and between 1 and 8 "other partitions" + // for coefficient data. + fp partition + op [8]partition + nOP int + // Quantization factors. + quant [nSegment]quant + // DCT/WHT coefficient decoding probabilities. + tokenProb [nPlane][nBand][nContext][nProb]uint8 + useSkipProb bool + skipProb uint8 + // Loop filter parameters. + filterParams [nSegment][2]filterParam + perMBFilterParams []filterParam + + // The eight fields below relate to the current macroblock being decoded. + // + // Segment-based adjustments. + segment int + // Per-macroblock state for the macroblock immediately left of and those + // macroblocks immediately above the current macroblock. + leftMB mb + upMB []mb + // Bitmasks for which 4x4 regions of coeff contain non-zero coefficients. + nzDCMask, nzACMask uint32 + // Predictor modes. + usePredY16 bool // The libwebp C code calls this !is_i4x4_. + predY16 uint8 + predC8 uint8 + predY4 [4][4]uint8 + + // The two fields below form a workspace for reconstructing a macroblock. + // Their specific sizes are documented in reconstruct.go. + coeff [1*16*16 + 2*8*8 + 1*4*4]int16 + ybr [1 + 16 + 1 + 8][32]uint8 +} + +// NewDecoder returns a new Decoder. +func NewDecoder() *Decoder { + return &Decoder{} +} + +// Init initializes the decoder to read at most n bytes from r. +func (d *Decoder) Init(r io.Reader, n int) { + d.r = limitReader{r, n} +} + +// DecodeFrameHeader decodes the frame header. +func (d *Decoder) DecodeFrameHeader() (fh FrameHeader, err error) { + // All frame headers are at least 3 bytes long. + b := d.scratch[:3] + if err = d.r.ReadFull(b); err != nil { + return + } + d.frameHeader.KeyFrame = (b[0] & 1) == 0 + d.frameHeader.VersionNumber = (b[0] >> 1) & 7 + d.frameHeader.ShowFrame = (b[0]>>4)&1 == 1 + d.frameHeader.FirstPartitionLen = uint32(b[0])>>5 | uint32(b[1])<<3 | uint32(b[2])<<11 + if !d.frameHeader.KeyFrame { + return d.frameHeader, nil + } + // Frame headers for key frames are an additional 7 bytes long. + b = d.scratch[:7] + if err = d.r.ReadFull(b); err != nil { + return + } + // Check the magic sync code. + if b[0] != 0x9d || b[1] != 0x01 || b[2] != 0x2a { + err = errors.New("vp8: invalid format") + return + } + d.frameHeader.Width = int(b[4]&0x3f)<<8 | int(b[3]) + d.frameHeader.Height = int(b[6]&0x3f)<<8 | int(b[5]) + d.frameHeader.XScale = b[4] >> 6 + d.frameHeader.YScale = b[6] >> 6 + d.mbw = (d.frameHeader.Width + 0x0f) >> 4 + d.mbh = (d.frameHeader.Height + 0x0f) >> 4 + d.segmentHeader = segmentHeader{ + prob: [3]uint8{0xff, 0xff, 0xff}, + } + d.tokenProb = defaultTokenProb + d.segment = 0 + return d.frameHeader, nil +} + +// ensureImg ensures that d.img is large enough to hold the decoded frame. +func (d *Decoder) ensureImg() { + if d.img != nil { + p0, p1 := d.img.Rect.Min, d.img.Rect.Max + if p0.X == 0 && p0.Y == 0 && p1.X >= 16*d.mbw && p1.Y >= 16*d.mbh { + return + } + } + m := image.NewYCbCr(image.Rect(0, 0, 16*d.mbw, 16*d.mbh), image.YCbCrSubsampleRatio420) + d.img = m.SubImage(image.Rect(0, 0, d.frameHeader.Width, d.frameHeader.Height)).(*image.YCbCr) + d.perMBFilterParams = make([]filterParam, d.mbw*d.mbh) + d.upMB = make([]mb, d.mbw) +} + +// parseSegmentHeader parses the segment header, as specified in section 9.3. +func (d *Decoder) parseSegmentHeader() { + d.segmentHeader.useSegment = d.fp.readBit(uniformProb) + if !d.segmentHeader.useSegment { + d.segmentHeader.updateMap = false + return + } + d.segmentHeader.updateMap = d.fp.readBit(uniformProb) + if d.fp.readBit(uniformProb) { + d.segmentHeader.relativeDelta = !d.fp.readBit(uniformProb) + for i := range d.segmentHeader.quantizer { + d.segmentHeader.quantizer[i] = int8(d.fp.readOptionalInt(uniformProb, 7)) + } + for i := range d.segmentHeader.filterStrength { + d.segmentHeader.filterStrength[i] = int8(d.fp.readOptionalInt(uniformProb, 6)) + } + } + if !d.segmentHeader.updateMap { + return + } + for i := range d.segmentHeader.prob { + if d.fp.readBit(uniformProb) { + d.segmentHeader.prob[i] = uint8(d.fp.readUint(uniformProb, 8)) + } else { + d.segmentHeader.prob[i] = 0xff + } + } +} + +// parseFilterHeader parses the filter header, as specified in section 9.4. +func (d *Decoder) parseFilterHeader() { + d.filterHeader.simple = d.fp.readBit(uniformProb) + d.filterHeader.level = int8(d.fp.readUint(uniformProb, 6)) + d.filterHeader.sharpness = uint8(d.fp.readUint(uniformProb, 3)) + d.filterHeader.useLFDelta = d.fp.readBit(uniformProb) + if d.filterHeader.useLFDelta && d.fp.readBit(uniformProb) { + for i := range d.filterHeader.refLFDelta { + d.filterHeader.refLFDelta[i] = int8(d.fp.readOptionalInt(uniformProb, 6)) + } + for i := range d.filterHeader.modeLFDelta { + d.filterHeader.modeLFDelta[i] = int8(d.fp.readOptionalInt(uniformProb, 6)) + } + } + if d.filterHeader.level == 0 { + return + } + if d.segmentHeader.useSegment { + for i := range d.filterHeader.perSegmentLevel { + strength := d.segmentHeader.filterStrength[i] + if d.segmentHeader.relativeDelta { + strength += d.filterHeader.level + } + d.filterHeader.perSegmentLevel[i] = strength + } + } else { + d.filterHeader.perSegmentLevel[0] = d.filterHeader.level + } + d.computeFilterParams() +} + +// parseOtherPartitions parses the other partitions, as specified in section 9.5. +func (d *Decoder) parseOtherPartitions() error { + const maxNOP = 1 << 3 + var partLens [maxNOP]int + d.nOP = 1 << d.fp.readUint(uniformProb, 2) + + // The final partition length is implied by the remaining chunk data + // (d.r.n) and the other d.nOP-1 partition lengths. Those d.nOP-1 partition + // lengths are stored as 24-bit uints, i.e. up to 16 MiB per partition. + n := 3 * (d.nOP - 1) + partLens[d.nOP-1] = d.r.n - n + if partLens[d.nOP-1] < 0 { + return io.ErrUnexpectedEOF + } + if n > 0 { + buf := make([]byte, n) + if err := d.r.ReadFull(buf); err != nil { + return err + } + for i := 0; i < d.nOP-1; i++ { + pl := int(buf[3*i+0]) | int(buf[3*i+1])<<8 | int(buf[3*i+2])<<16 + if pl > partLens[d.nOP-1] { + return io.ErrUnexpectedEOF + } + partLens[i] = pl + partLens[d.nOP-1] -= pl + } + } + + // We check if the final partition length can also fit into a 24-bit uint. + // Strictly speaking, this isn't part of the spec, but it guards against a + // malicious WEBP image that is too large to ReadFull the encoded DCT + // coefficients into memory, whether that's because the actual WEBP file is + // too large, or whether its RIFF metadata lists too large a chunk. + if 1<<24 <= partLens[d.nOP-1] { + return errors.New("vp8: too much data to decode") + } + + buf := make([]byte, d.r.n) + if err := d.r.ReadFull(buf); err != nil { + return err + } + for i, pl := range partLens { + if i == d.nOP { + break + } + d.op[i].init(buf[:pl]) + buf = buf[pl:] + } + return nil +} + +// parseOtherHeaders parses header information other than the frame header. +func (d *Decoder) parseOtherHeaders() error { + // Initialize and parse the first partition. + firstPartition := make([]byte, d.frameHeader.FirstPartitionLen) + if err := d.r.ReadFull(firstPartition); err != nil { + return err + } + d.fp.init(firstPartition) + if d.frameHeader.KeyFrame { + // Read and ignore the color space and pixel clamp values. They are + // specified in section 9.2, but are unimplemented. + d.fp.readBit(uniformProb) + d.fp.readBit(uniformProb) + } + d.parseSegmentHeader() + d.parseFilterHeader() + if err := d.parseOtherPartitions(); err != nil { + return err + } + d.parseQuant() + if !d.frameHeader.KeyFrame { + // Golden and AltRef frames are specified in section 9.7. + // TODO(nigeltao): implement. Note that they are only used for video, not still images. + return errors.New("vp8: Golden / AltRef frames are not implemented") + } + // Read and ignore the refreshLastFrameBuffer bit, specified in section 9.8. + // It applies only to video, and not still images. + d.fp.readBit(uniformProb) + d.parseTokenProb() + d.useSkipProb = d.fp.readBit(uniformProb) + if d.useSkipProb { + d.skipProb = uint8(d.fp.readUint(uniformProb, 8)) + } + if d.fp.unexpectedEOF { + return io.ErrUnexpectedEOF + } + return nil +} + +// DecodeFrame decodes the frame and returns it as an YCbCr image. +// The image's contents are valid up until the next call to Decoder.Init. +func (d *Decoder) DecodeFrame() (*image.YCbCr, error) { + d.ensureImg() + if err := d.parseOtherHeaders(); err != nil { + return nil, err + } + // Reconstruct the rows. + for mbx := 0; mbx < d.mbw; mbx++ { + d.upMB[mbx] = mb{} + } + for mby := 0; mby < d.mbh; mby++ { + d.leftMB = mb{} + for mbx := 0; mbx < d.mbw; mbx++ { + skip := d.reconstruct(mbx, mby) + fs := d.filterParams[d.segment][btou(!d.usePredY16)] + fs.inner = fs.inner || !skip + d.perMBFilterParams[d.mbw*mby+mbx] = fs + } + } + if d.fp.unexpectedEOF { + return nil, io.ErrUnexpectedEOF + } + for i := 0; i < d.nOP; i++ { + if d.op[i].unexpectedEOF { + return nil, io.ErrUnexpectedEOF + } + } + // Apply the loop filter. + // + // Even if we are using per-segment levels, section 15 says that "loop + // filtering must be skipped entirely if loop_filter_level at either the + // frame header level or macroblock override level is 0". + if d.filterHeader.level != 0 { + if d.filterHeader.simple { + d.simpleFilter() + } else { + d.normalFilter() + } + } + return d.img, nil +} diff --git a/vendor/golang.org/x/image/vp8/filter.go b/vendor/golang.org/x/image/vp8/filter.go new file mode 100644 index 0000000..e34a811 --- /dev/null +++ b/vendor/golang.org/x/image/vp8/filter.go @@ -0,0 +1,273 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// filter2 modifies a 2-pixel wide or 2-pixel high band along an edge. +func filter2(pix []byte, level, index, iStep, jStep int) { + for n := 16; n > 0; n, index = n-1, index+iStep { + p1 := int(pix[index-2*jStep]) + p0 := int(pix[index-1*jStep]) + q0 := int(pix[index+0*jStep]) + q1 := int(pix[index+1*jStep]) + if abs(p0-q0)<<1+abs(p1-q1)>>1 > level { + continue + } + a := 3*(q0-p0) + clamp127(p1-q1) + a1 := clamp15((a + 4) >> 3) + a2 := clamp15((a + 3) >> 3) + pix[index-1*jStep] = clamp255(p0 + a2) + pix[index+0*jStep] = clamp255(q0 - a1) + } +} + +// filter246 modifies a 2-, 4- or 6-pixel wide or high band along an edge. +func filter246(pix []byte, n, level, ilevel, hlevel, index, iStep, jStep int, fourNotSix bool) { + for ; n > 0; n, index = n-1, index+iStep { + p3 := int(pix[index-4*jStep]) + p2 := int(pix[index-3*jStep]) + p1 := int(pix[index-2*jStep]) + p0 := int(pix[index-1*jStep]) + q0 := int(pix[index+0*jStep]) + q1 := int(pix[index+1*jStep]) + q2 := int(pix[index+2*jStep]) + q3 := int(pix[index+3*jStep]) + if abs(p0-q0)<<1+abs(p1-q1)>>1 > level { + continue + } + if abs(p3-p2) > ilevel || + abs(p2-p1) > ilevel || + abs(p1-p0) > ilevel || + abs(q1-q0) > ilevel || + abs(q2-q1) > ilevel || + abs(q3-q2) > ilevel { + continue + } + if abs(p1-p0) > hlevel || abs(q1-q0) > hlevel { + // Filter 2 pixels. + a := 3*(q0-p0) + clamp127(p1-q1) + a1 := clamp15((a + 4) >> 3) + a2 := clamp15((a + 3) >> 3) + pix[index-1*jStep] = clamp255(p0 + a2) + pix[index+0*jStep] = clamp255(q0 - a1) + } else if fourNotSix { + // Filter 4 pixels. + a := 3 * (q0 - p0) + a1 := clamp15((a + 4) >> 3) + a2 := clamp15((a + 3) >> 3) + a3 := (a1 + 1) >> 1 + pix[index-2*jStep] = clamp255(p1 + a3) + pix[index-1*jStep] = clamp255(p0 + a2) + pix[index+0*jStep] = clamp255(q0 - a1) + pix[index+1*jStep] = clamp255(q1 - a3) + } else { + // Filter 6 pixels. + a := clamp127(3*(q0-p0) + clamp127(p1-q1)) + a1 := (27*a + 63) >> 7 + a2 := (18*a + 63) >> 7 + a3 := (9*a + 63) >> 7 + pix[index-3*jStep] = clamp255(p2 + a3) + pix[index-2*jStep] = clamp255(p1 + a2) + pix[index-1*jStep] = clamp255(p0 + a1) + pix[index+0*jStep] = clamp255(q0 - a1) + pix[index+1*jStep] = clamp255(q1 - a2) + pix[index+2*jStep] = clamp255(q2 - a3) + } + } +} + +// simpleFilter implements the simple filter, as specified in section 15.2. +func (d *Decoder) simpleFilter() { + for mby := 0; mby < d.mbh; mby++ { + for mbx := 0; mbx < d.mbw; mbx++ { + f := d.perMBFilterParams[d.mbw*mby+mbx] + if f.level == 0 { + continue + } + l := int(f.level) + yIndex := (mby*d.img.YStride + mbx) * 16 + if mbx > 0 { + filter2(d.img.Y, l+4, yIndex, d.img.YStride, 1) + } + if f.inner { + filter2(d.img.Y, l, yIndex+0x4, d.img.YStride, 1) + filter2(d.img.Y, l, yIndex+0x8, d.img.YStride, 1) + filter2(d.img.Y, l, yIndex+0xc, d.img.YStride, 1) + } + if mby > 0 { + filter2(d.img.Y, l+4, yIndex, 1, d.img.YStride) + } + if f.inner { + filter2(d.img.Y, l, yIndex+d.img.YStride*0x4, 1, d.img.YStride) + filter2(d.img.Y, l, yIndex+d.img.YStride*0x8, 1, d.img.YStride) + filter2(d.img.Y, l, yIndex+d.img.YStride*0xc, 1, d.img.YStride) + } + } + } +} + +// normalFilter implements the normal filter, as specified in section 15.3. +func (d *Decoder) normalFilter() { + for mby := 0; mby < d.mbh; mby++ { + for mbx := 0; mbx < d.mbw; mbx++ { + f := d.perMBFilterParams[d.mbw*mby+mbx] + if f.level == 0 { + continue + } + l, il, hl := int(f.level), int(f.ilevel), int(f.hlevel) + yIndex := (mby*d.img.YStride + mbx) * 16 + cIndex := (mby*d.img.CStride + mbx) * 8 + if mbx > 0 { + filter246(d.img.Y, 16, l+4, il, hl, yIndex, d.img.YStride, 1, false) + filter246(d.img.Cb, 8, l+4, il, hl, cIndex, d.img.CStride, 1, false) + filter246(d.img.Cr, 8, l+4, il, hl, cIndex, d.img.CStride, 1, false) + } + if f.inner { + filter246(d.img.Y, 16, l, il, hl, yIndex+0x4, d.img.YStride, 1, true) + filter246(d.img.Y, 16, l, il, hl, yIndex+0x8, d.img.YStride, 1, true) + filter246(d.img.Y, 16, l, il, hl, yIndex+0xc, d.img.YStride, 1, true) + filter246(d.img.Cb, 8, l, il, hl, cIndex+0x4, d.img.CStride, 1, true) + filter246(d.img.Cr, 8, l, il, hl, cIndex+0x4, d.img.CStride, 1, true) + } + if mby > 0 { + filter246(d.img.Y, 16, l+4, il, hl, yIndex, 1, d.img.YStride, false) + filter246(d.img.Cb, 8, l+4, il, hl, cIndex, 1, d.img.CStride, false) + filter246(d.img.Cr, 8, l+4, il, hl, cIndex, 1, d.img.CStride, false) + } + if f.inner { + filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0x4, 1, d.img.YStride, true) + filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0x8, 1, d.img.YStride, true) + filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0xc, 1, d.img.YStride, true) + filter246(d.img.Cb, 8, l, il, hl, cIndex+d.img.CStride*0x4, 1, d.img.CStride, true) + filter246(d.img.Cr, 8, l, il, hl, cIndex+d.img.CStride*0x4, 1, d.img.CStride, true) + } + } + } +} + +// filterParam holds the loop filter parameters for a macroblock. +type filterParam struct { + // The first three fields are thresholds used by the loop filter to smooth + // over the edges and interior of a macroblock. level is used by both the + // simple and normal filters. The inner level and high edge variance level + // are only used by the normal filter. + level, ilevel, hlevel uint8 + // inner is whether the inner loop filter cannot be optimized out as a + // no-op for this particular macroblock. + inner bool +} + +// computeFilterParams computes the loop filter parameters, as specified in +// section 15.4. +func (d *Decoder) computeFilterParams() { + for i := range d.filterParams { + baseLevel := d.filterHeader.level + if d.segmentHeader.useSegment { + baseLevel = d.segmentHeader.filterStrength[i] + if d.segmentHeader.relativeDelta { + baseLevel += d.filterHeader.level + } + } + + for j := range d.filterParams[i] { + p := &d.filterParams[i][j] + p.inner = j != 0 + level := baseLevel + if d.filterHeader.useLFDelta { + // The libwebp C code has a "TODO: only CURRENT is handled for now." + level += d.filterHeader.refLFDelta[0] + if j != 0 { + level += d.filterHeader.modeLFDelta[0] + } + } + if level <= 0 { + p.level = 0 + continue + } + if level > 63 { + level = 63 + } + ilevel := level + if d.filterHeader.sharpness > 0 { + if d.filterHeader.sharpness > 4 { + ilevel >>= 2 + } else { + ilevel >>= 1 + } + if x := int8(9 - d.filterHeader.sharpness); ilevel > x { + ilevel = x + } + } + if ilevel < 1 { + ilevel = 1 + } + p.ilevel = uint8(ilevel) + p.level = uint8(2*level + ilevel) + if d.frameHeader.KeyFrame { + if level < 15 { + p.hlevel = 0 + } else if level < 40 { + p.hlevel = 1 + } else { + p.hlevel = 2 + } + } else { + if level < 15 { + p.hlevel = 0 + } else if level < 20 { + p.hlevel = 1 + } else if level < 40 { + p.hlevel = 2 + } else { + p.hlevel = 3 + } + } + } + } +} + +// intSize is either 32 or 64. +const intSize = 32 << (^uint(0) >> 63) + +func abs(x int) int { + // m := -1 if x < 0. m := 0 otherwise. + m := x >> (intSize - 1) + + // In two's complement representation, the negative number + // of any number (except the smallest one) can be computed + // by flipping all the bits and add 1. This is faster than + // code with a branch. + // See Hacker's Delight, section 2-4. + return (x ^ m) - m +} + +func clamp15(x int) int { + if x < -16 { + return -16 + } + if x > 15 { + return 15 + } + return x +} + +func clamp127(x int) int { + if x < -128 { + return -128 + } + if x > 127 { + return 127 + } + return x +} + +func clamp255(x int) uint8 { + if x < 0 { + return 0 + } + if x > 255 { + return 255 + } + return uint8(x) +} diff --git a/vendor/golang.org/x/image/vp8/idct.go b/vendor/golang.org/x/image/vp8/idct.go new file mode 100644 index 0000000..929af2c --- /dev/null +++ b/vendor/golang.org/x/image/vp8/idct.go @@ -0,0 +1,98 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// This file implements the inverse Discrete Cosine Transform and the inverse +// Walsh Hadamard Transform (WHT), as specified in sections 14.3 and 14.4. + +func clip8(i int32) uint8 { + if i < 0 { + return 0 + } + if i > 255 { + return 255 + } + return uint8(i) +} + +func (z *Decoder) inverseDCT4(y, x, coeffBase int) { + const ( + c1 = 85627 // 65536 * cos(pi/8) * sqrt(2). + c2 = 35468 // 65536 * sin(pi/8) * sqrt(2). + ) + var m [4][4]int32 + for i := 0; i < 4; i++ { + a := int32(z.coeff[coeffBase+0]) + int32(z.coeff[coeffBase+8]) + b := int32(z.coeff[coeffBase+0]) - int32(z.coeff[coeffBase+8]) + c := (int32(z.coeff[coeffBase+4])*c2)>>16 - (int32(z.coeff[coeffBase+12])*c1)>>16 + d := (int32(z.coeff[coeffBase+4])*c1)>>16 + (int32(z.coeff[coeffBase+12])*c2)>>16 + m[i][0] = a + d + m[i][1] = b + c + m[i][2] = b - c + m[i][3] = a - d + coeffBase++ + } + for j := 0; j < 4; j++ { + dc := m[0][j] + 4 + a := dc + m[2][j] + b := dc - m[2][j] + c := (m[1][j]*c2)>>16 - (m[3][j]*c1)>>16 + d := (m[1][j]*c1)>>16 + (m[3][j]*c2)>>16 + z.ybr[y+j][x+0] = clip8(int32(z.ybr[y+j][x+0]) + (a+d)>>3) + z.ybr[y+j][x+1] = clip8(int32(z.ybr[y+j][x+1]) + (b+c)>>3) + z.ybr[y+j][x+2] = clip8(int32(z.ybr[y+j][x+2]) + (b-c)>>3) + z.ybr[y+j][x+3] = clip8(int32(z.ybr[y+j][x+3]) + (a-d)>>3) + } +} + +func (z *Decoder) inverseDCT4DCOnly(y, x, coeffBase int) { + dc := (int32(z.coeff[coeffBase+0]) + 4) >> 3 + for j := 0; j < 4; j++ { + for i := 0; i < 4; i++ { + z.ybr[y+j][x+i] = clip8(int32(z.ybr[y+j][x+i]) + dc) + } + } +} + +func (z *Decoder) inverseDCT8(y, x, coeffBase int) { + z.inverseDCT4(y+0, x+0, coeffBase+0*16) + z.inverseDCT4(y+0, x+4, coeffBase+1*16) + z.inverseDCT4(y+4, x+0, coeffBase+2*16) + z.inverseDCT4(y+4, x+4, coeffBase+3*16) +} + +func (z *Decoder) inverseDCT8DCOnly(y, x, coeffBase int) { + z.inverseDCT4DCOnly(y+0, x+0, coeffBase+0*16) + z.inverseDCT4DCOnly(y+0, x+4, coeffBase+1*16) + z.inverseDCT4DCOnly(y+4, x+0, coeffBase+2*16) + z.inverseDCT4DCOnly(y+4, x+4, coeffBase+3*16) +} + +func (d *Decoder) inverseWHT16() { + var m [16]int32 + for i := 0; i < 4; i++ { + a0 := int32(d.coeff[384+0+i]) + int32(d.coeff[384+12+i]) + a1 := int32(d.coeff[384+4+i]) + int32(d.coeff[384+8+i]) + a2 := int32(d.coeff[384+4+i]) - int32(d.coeff[384+8+i]) + a3 := int32(d.coeff[384+0+i]) - int32(d.coeff[384+12+i]) + m[0+i] = a0 + a1 + m[8+i] = a0 - a1 + m[4+i] = a3 + a2 + m[12+i] = a3 - a2 + } + out := 0 + for i := 0; i < 4; i++ { + dc := m[0+i*4] + 3 + a0 := dc + m[3+i*4] + a1 := m[1+i*4] + m[2+i*4] + a2 := m[1+i*4] - m[2+i*4] + a3 := dc - m[3+i*4] + d.coeff[out+0] = int16((a0 + a1) >> 3) + d.coeff[out+16] = int16((a3 + a2) >> 3) + d.coeff[out+32] = int16((a0 - a1) >> 3) + d.coeff[out+48] = int16((a3 - a2) >> 3) + out += 64 + } +} diff --git a/vendor/golang.org/x/image/vp8/partition.go b/vendor/golang.org/x/image/vp8/partition.go new file mode 100644 index 0000000..72288bd --- /dev/null +++ b/vendor/golang.org/x/image/vp8/partition.go @@ -0,0 +1,129 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// Each VP8 frame consists of between 2 and 9 bitstream partitions. +// Each partition is byte-aligned and is independently arithmetic-encoded. +// +// This file implements decoding a partition's bitstream, as specified in +// chapter 7. The implementation follows libwebp's approach instead of the +// specification's reference C implementation. For example, we use a look-up +// table instead of a for loop to recalibrate the encoded range. + +var ( + lutShift = [127]uint8{ + 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + } + lutRangeM1 = [127]uint8{ + 127, + 127, 191, + 127, 159, 191, 223, + 127, 143, 159, 175, 191, 207, 223, 239, + 127, 135, 143, 151, 159, 167, 175, 183, 191, 199, 207, 215, 223, 231, 239, 247, + 127, 131, 135, 139, 143, 147, 151, 155, 159, 163, 167, 171, 175, 179, 183, 187, + 191, 195, 199, 203, 207, 211, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251, + 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, + 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, + 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, + 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, + } +) + +// uniformProb represents a 50% probability that the next bit is 0. +const uniformProb = 128 + +// partition holds arithmetic-coded bits. +type partition struct { + // buf is the input bytes. + buf []byte + // r is how many of buf's bytes have been consumed. + r int + // rangeM1 is range minus 1, where range is in the arithmetic coding sense, + // not the Go language sense. + rangeM1 uint32 + // bits and nBits hold those bits shifted out of buf but not yet consumed. + bits uint32 + nBits uint8 + // unexpectedEOF tells whether we tried to read past buf. + unexpectedEOF bool +} + +// init initializes the partition. +func (p *partition) init(buf []byte) { + p.buf = buf + p.r = 0 + p.rangeM1 = 254 + p.bits = 0 + p.nBits = 0 + p.unexpectedEOF = false +} + +// readBit returns the next bit. +func (p *partition) readBit(prob uint8) bool { + if p.nBits < 8 { + if p.r >= len(p.buf) { + p.unexpectedEOF = true + return false + } + // Expression split for 386 compiler. + x := uint32(p.buf[p.r]) + p.bits |= x << (8 - p.nBits) + p.r++ + p.nBits += 8 + } + split := (p.rangeM1*uint32(prob))>>8 + 1 + bit := p.bits >= split<<8 + if bit { + p.rangeM1 -= split + p.bits -= split << 8 + } else { + p.rangeM1 = split - 1 + } + if p.rangeM1 < 127 { + shift := lutShift[p.rangeM1] + p.rangeM1 = uint32(lutRangeM1[p.rangeM1]) + p.bits <<= shift + p.nBits -= shift + } + return bit +} + +// readUint returns the next n-bit unsigned integer. +func (p *partition) readUint(prob, n uint8) uint32 { + var u uint32 + for n > 0 { + n-- + if p.readBit(prob) { + u |= 1 << n + } + } + return u +} + +// readInt returns the next n-bit signed integer. +func (p *partition) readInt(prob, n uint8) int32 { + u := p.readUint(prob, n) + b := p.readBit(prob) + if b { + return -int32(u) + } + return int32(u) +} + +// readOptionalInt returns the next n-bit signed integer in an encoding +// where the likely result is zero. +func (p *partition) readOptionalInt(prob, n uint8) int32 { + if !p.readBit(prob) { + return 0 + } + return p.readInt(prob, n) +} diff --git a/vendor/golang.org/x/image/vp8/pred.go b/vendor/golang.org/x/image/vp8/pred.go new file mode 100644 index 0000000..58c2689 --- /dev/null +++ b/vendor/golang.org/x/image/vp8/pred.go @@ -0,0 +1,201 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// This file implements parsing the predictor modes, as specified in chapter +// 11. + +func (d *Decoder) parsePredModeY16(mbx int) { + var p uint8 + if !d.fp.readBit(156) { + if !d.fp.readBit(163) { + p = predDC + } else { + p = predVE + } + } else if !d.fp.readBit(128) { + p = predHE + } else { + p = predTM + } + for i := 0; i < 4; i++ { + d.upMB[mbx].pred[i] = p + d.leftMB.pred[i] = p + } + d.predY16 = p +} + +func (d *Decoder) parsePredModeC8() { + if !d.fp.readBit(142) { + d.predC8 = predDC + } else if !d.fp.readBit(114) { + d.predC8 = predVE + } else if !d.fp.readBit(183) { + d.predC8 = predHE + } else { + d.predC8 = predTM + } +} + +func (d *Decoder) parsePredModeY4(mbx int) { + for j := 0; j < 4; j++ { + p := d.leftMB.pred[j] + for i := 0; i < 4; i++ { + prob := &predProb[d.upMB[mbx].pred[i]][p] + if !d.fp.readBit(prob[0]) { + p = predDC + } else if !d.fp.readBit(prob[1]) { + p = predTM + } else if !d.fp.readBit(prob[2]) { + p = predVE + } else if !d.fp.readBit(prob[3]) { + if !d.fp.readBit(prob[4]) { + p = predHE + } else if !d.fp.readBit(prob[5]) { + p = predRD + } else { + p = predVR + } + } else if !d.fp.readBit(prob[6]) { + p = predLD + } else if !d.fp.readBit(prob[7]) { + p = predVL + } else if !d.fp.readBit(prob[8]) { + p = predHD + } else { + p = predHU + } + d.predY4[j][i] = p + d.upMB[mbx].pred[i] = p + } + d.leftMB.pred[j] = p + } +} + +// predProb are the probabilities to decode a 4x4 region's predictor mode given +// the predictor modes of the regions above and left of it. +// These values are specified in section 11.5. +var predProb = [nPred][nPred][9]uint8{ + { + {231, 120, 48, 89, 115, 113, 120, 152, 112}, + {152, 179, 64, 126, 170, 118, 46, 70, 95}, + {175, 69, 143, 80, 85, 82, 72, 155, 103}, + {56, 58, 10, 171, 218, 189, 17, 13, 152}, + {114, 26, 17, 163, 44, 195, 21, 10, 173}, + {121, 24, 80, 195, 26, 62, 44, 64, 85}, + {144, 71, 10, 38, 171, 213, 144, 34, 26}, + {170, 46, 55, 19, 136, 160, 33, 206, 71}, + {63, 20, 8, 114, 114, 208, 12, 9, 226}, + {81, 40, 11, 96, 182, 84, 29, 16, 36}, + }, + { + {134, 183, 89, 137, 98, 101, 106, 165, 148}, + {72, 187, 100, 130, 157, 111, 32, 75, 80}, + {66, 102, 167, 99, 74, 62, 40, 234, 128}, + {41, 53, 9, 178, 241, 141, 26, 8, 107}, + {74, 43, 26, 146, 73, 166, 49, 23, 157}, + {65, 38, 105, 160, 51, 52, 31, 115, 128}, + {104, 79, 12, 27, 217, 255, 87, 17, 7}, + {87, 68, 71, 44, 114, 51, 15, 186, 23}, + {47, 41, 14, 110, 182, 183, 21, 17, 194}, + {66, 45, 25, 102, 197, 189, 23, 18, 22}, + }, + { + {88, 88, 147, 150, 42, 46, 45, 196, 205}, + {43, 97, 183, 117, 85, 38, 35, 179, 61}, + {39, 53, 200, 87, 26, 21, 43, 232, 171}, + {56, 34, 51, 104, 114, 102, 29, 93, 77}, + {39, 28, 85, 171, 58, 165, 90, 98, 64}, + {34, 22, 116, 206, 23, 34, 43, 166, 73}, + {107, 54, 32, 26, 51, 1, 81, 43, 31}, + {68, 25, 106, 22, 64, 171, 36, 225, 114}, + {34, 19, 21, 102, 132, 188, 16, 76, 124}, + {62, 18, 78, 95, 85, 57, 50, 48, 51}, + }, + { + {193, 101, 35, 159, 215, 111, 89, 46, 111}, + {60, 148, 31, 172, 219, 228, 21, 18, 111}, + {112, 113, 77, 85, 179, 255, 38, 120, 114}, + {40, 42, 1, 196, 245, 209, 10, 25, 109}, + {88, 43, 29, 140, 166, 213, 37, 43, 154}, + {61, 63, 30, 155, 67, 45, 68, 1, 209}, + {100, 80, 8, 43, 154, 1, 51, 26, 71}, + {142, 78, 78, 16, 255, 128, 34, 197, 171}, + {41, 40, 5, 102, 211, 183, 4, 1, 221}, + {51, 50, 17, 168, 209, 192, 23, 25, 82}, + }, + { + {138, 31, 36, 171, 27, 166, 38, 44, 229}, + {67, 87, 58, 169, 82, 115, 26, 59, 179}, + {63, 59, 90, 180, 59, 166, 93, 73, 154}, + {40, 40, 21, 116, 143, 209, 34, 39, 175}, + {47, 15, 16, 183, 34, 223, 49, 45, 183}, + {46, 17, 33, 183, 6, 98, 15, 32, 183}, + {57, 46, 22, 24, 128, 1, 54, 17, 37}, + {65, 32, 73, 115, 28, 128, 23, 128, 205}, + {40, 3, 9, 115, 51, 192, 18, 6, 223}, + {87, 37, 9, 115, 59, 77, 64, 21, 47}, + }, + { + {104, 55, 44, 218, 9, 54, 53, 130, 226}, + {64, 90, 70, 205, 40, 41, 23, 26, 57}, + {54, 57, 112, 184, 5, 41, 38, 166, 213}, + {30, 34, 26, 133, 152, 116, 10, 32, 134}, + {39, 19, 53, 221, 26, 114, 32, 73, 255}, + {31, 9, 65, 234, 2, 15, 1, 118, 73}, + {75, 32, 12, 51, 192, 255, 160, 43, 51}, + {88, 31, 35, 67, 102, 85, 55, 186, 85}, + {56, 21, 23, 111, 59, 205, 45, 37, 192}, + {55, 38, 70, 124, 73, 102, 1, 34, 98}, + }, + { + {125, 98, 42, 88, 104, 85, 117, 175, 82}, + {95, 84, 53, 89, 128, 100, 113, 101, 45}, + {75, 79, 123, 47, 51, 128, 81, 171, 1}, + {57, 17, 5, 71, 102, 57, 53, 41, 49}, + {38, 33, 13, 121, 57, 73, 26, 1, 85}, + {41, 10, 67, 138, 77, 110, 90, 47, 114}, + {115, 21, 2, 10, 102, 255, 166, 23, 6}, + {101, 29, 16, 10, 85, 128, 101, 196, 26}, + {57, 18, 10, 102, 102, 213, 34, 20, 43}, + {117, 20, 15, 36, 163, 128, 68, 1, 26}, + }, + { + {102, 61, 71, 37, 34, 53, 31, 243, 192}, + {69, 60, 71, 38, 73, 119, 28, 222, 37}, + {68, 45, 128, 34, 1, 47, 11, 245, 171}, + {62, 17, 19, 70, 146, 85, 55, 62, 70}, + {37, 43, 37, 154, 100, 163, 85, 160, 1}, + {63, 9, 92, 136, 28, 64, 32, 201, 85}, + {75, 15, 9, 9, 64, 255, 184, 119, 16}, + {86, 6, 28, 5, 64, 255, 25, 248, 1}, + {56, 8, 17, 132, 137, 255, 55, 116, 128}, + {58, 15, 20, 82, 135, 57, 26, 121, 40}, + }, + { + {164, 50, 31, 137, 154, 133, 25, 35, 218}, + {51, 103, 44, 131, 131, 123, 31, 6, 158}, + {86, 40, 64, 135, 148, 224, 45, 183, 128}, + {22, 26, 17, 131, 240, 154, 14, 1, 209}, + {45, 16, 21, 91, 64, 222, 7, 1, 197}, + {56, 21, 39, 155, 60, 138, 23, 102, 213}, + {83, 12, 13, 54, 192, 255, 68, 47, 28}, + {85, 26, 85, 85, 128, 128, 32, 146, 171}, + {18, 11, 7, 63, 144, 171, 4, 4, 246}, + {35, 27, 10, 146, 174, 171, 12, 26, 128}, + }, + { + {190, 80, 35, 99, 180, 80, 126, 54, 45}, + {85, 126, 47, 87, 176, 51, 41, 20, 32}, + {101, 75, 128, 139, 118, 146, 116, 128, 85}, + {56, 41, 15, 176, 236, 85, 37, 9, 62}, + {71, 30, 17, 119, 118, 255, 17, 18, 138}, + {101, 38, 60, 138, 55, 70, 43, 26, 142}, + {146, 36, 19, 30, 171, 255, 97, 27, 20}, + {138, 45, 61, 62, 219, 1, 81, 188, 64}, + {32, 41, 20, 117, 151, 142, 20, 21, 163}, + {112, 19, 12, 61, 195, 128, 48, 4, 24}, + }, +} diff --git a/vendor/golang.org/x/image/vp8/predfunc.go b/vendor/golang.org/x/image/vp8/predfunc.go new file mode 100644 index 0000000..bd554ae --- /dev/null +++ b/vendor/golang.org/x/image/vp8/predfunc.go @@ -0,0 +1,553 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// This file implements the prediction functions, as specified in chapter 12. +// +// For each macroblock (of 1x16x16 luma and 2x8x8 chroma coefficients), the +// luma values are either predicted as one large 16x16 region or 16 separate +// 4x4 regions. The chroma values are always predicted as one 8x8 region. +// +// For 4x4 regions, the target block's predicted values (Xs) are a function of +// its previously-decoded top and left border values, as well as a number of +// pixels from the top-right: +// +// a b c d e f g h +// p X X X X +// q X X X X +// r X X X X +// s X X X X +// +// The predictor modes are: +// - DC: all Xs = (b + c + d + e + p + q + r + s + 4) / 8. +// - TM: the first X = (b + p - a), the second X = (c + p - a), and so on. +// - VE: each X = the weighted average of its column's top value and that +// value's neighbors, i.e. averages of abc, bcd, cde or def. +// - HE: similar to VE except rows instead of columns, and the final row is +// an average of r, s and s. +// - RD, VR, LD, VL, HD, HU: these diagonal modes ("Right Down", "Vertical +// Right", etc) are more complicated and are described in section 12.3. +// All Xs are clipped to the range [0, 255]. +// +// For 8x8 and 16x16 regions, the target block's predicted values are a +// function of the top and left border values without the top-right overhang, +// i.e. without the 8x8 or 16x16 equivalent of f, g and h. Furthermore: +// - There are no diagonal predictor modes, only DC, TM, VE and HE. +// - The DC mode has variants for macroblocks in the top row and/or left +// column, i.e. for macroblocks with mby == 0 || mbx == 0. +// - The VE and HE modes take only the column top or row left values; they do +// not smooth that top/left value with its neighbors. + +// nPred is the number of predictor modes, not including the Top/Left versions +// of the DC predictor mode. +const nPred = 10 + +const ( + predDC = iota + predTM + predVE + predHE + predRD + predVR + predLD + predVL + predHD + predHU + predDCTop + predDCLeft + predDCTopLeft +) + +func checkTopLeftPred(mbx, mby int, p uint8) uint8 { + if p != predDC { + return p + } + if mbx == 0 { + if mby == 0 { + return predDCTopLeft + } + return predDCLeft + } + if mby == 0 { + return predDCTop + } + return predDC +} + +var predFunc4 = [...]func(*Decoder, int, int){ + predFunc4DC, + predFunc4TM, + predFunc4VE, + predFunc4HE, + predFunc4RD, + predFunc4VR, + predFunc4LD, + predFunc4VL, + predFunc4HD, + predFunc4HU, + nil, + nil, + nil, +} + +var predFunc8 = [...]func(*Decoder, int, int){ + predFunc8DC, + predFunc8TM, + predFunc8VE, + predFunc8HE, + nil, + nil, + nil, + nil, + nil, + nil, + predFunc8DCTop, + predFunc8DCLeft, + predFunc8DCTopLeft, +} + +var predFunc16 = [...]func(*Decoder, int, int){ + predFunc16DC, + predFunc16TM, + predFunc16VE, + predFunc16HE, + nil, + nil, + nil, + nil, + nil, + nil, + predFunc16DCTop, + predFunc16DCLeft, + predFunc16DCTopLeft, +} + +func predFunc4DC(z *Decoder, y, x int) { + sum := uint32(4) + for i := 0; i < 4; i++ { + sum += uint32(z.ybr[y-1][x+i]) + } + for j := 0; j < 4; j++ { + sum += uint32(z.ybr[y+j][x-1]) + } + avg := uint8(sum / 8) + for j := 0; j < 4; j++ { + for i := 0; i < 4; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc4TM(z *Decoder, y, x int) { + delta0 := -int32(z.ybr[y-1][x-1]) + for j := 0; j < 4; j++ { + delta1 := delta0 + int32(z.ybr[y+j][x-1]) + for i := 0; i < 4; i++ { + delta2 := delta1 + int32(z.ybr[y-1][x+i]) + z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255)) + } + } +} + +func predFunc4VE(z *Decoder, y, x int) { + a := int32(z.ybr[y-1][x-1]) + b := int32(z.ybr[y-1][x+0]) + c := int32(z.ybr[y-1][x+1]) + d := int32(z.ybr[y-1][x+2]) + e := int32(z.ybr[y-1][x+3]) + f := int32(z.ybr[y-1][x+4]) + abc := uint8((a + 2*b + c + 2) / 4) + bcd := uint8((b + 2*c + d + 2) / 4) + cde := uint8((c + 2*d + e + 2) / 4) + def := uint8((d + 2*e + f + 2) / 4) + for j := 0; j < 4; j++ { + z.ybr[y+j][x+0] = abc + z.ybr[y+j][x+1] = bcd + z.ybr[y+j][x+2] = cde + z.ybr[y+j][x+3] = def + } +} + +func predFunc4HE(z *Decoder, y, x int) { + s := int32(z.ybr[y+3][x-1]) + r := int32(z.ybr[y+2][x-1]) + q := int32(z.ybr[y+1][x-1]) + p := int32(z.ybr[y+0][x-1]) + a := int32(z.ybr[y-1][x-1]) + ssr := uint8((s + 2*s + r + 2) / 4) + srq := uint8((s + 2*r + q + 2) / 4) + rqp := uint8((r + 2*q + p + 2) / 4) + apq := uint8((a + 2*p + q + 2) / 4) + for i := 0; i < 4; i++ { + z.ybr[y+0][x+i] = apq + z.ybr[y+1][x+i] = rqp + z.ybr[y+2][x+i] = srq + z.ybr[y+3][x+i] = ssr + } +} + +func predFunc4RD(z *Decoder, y, x int) { + s := int32(z.ybr[y+3][x-1]) + r := int32(z.ybr[y+2][x-1]) + q := int32(z.ybr[y+1][x-1]) + p := int32(z.ybr[y+0][x-1]) + a := int32(z.ybr[y-1][x-1]) + b := int32(z.ybr[y-1][x+0]) + c := int32(z.ybr[y-1][x+1]) + d := int32(z.ybr[y-1][x+2]) + e := int32(z.ybr[y-1][x+3]) + srq := uint8((s + 2*r + q + 2) / 4) + rqp := uint8((r + 2*q + p + 2) / 4) + qpa := uint8((q + 2*p + a + 2) / 4) + pab := uint8((p + 2*a + b + 2) / 4) + abc := uint8((a + 2*b + c + 2) / 4) + bcd := uint8((b + 2*c + d + 2) / 4) + cde := uint8((c + 2*d + e + 2) / 4) + z.ybr[y+0][x+0] = pab + z.ybr[y+0][x+1] = abc + z.ybr[y+0][x+2] = bcd + z.ybr[y+0][x+3] = cde + z.ybr[y+1][x+0] = qpa + z.ybr[y+1][x+1] = pab + z.ybr[y+1][x+2] = abc + z.ybr[y+1][x+3] = bcd + z.ybr[y+2][x+0] = rqp + z.ybr[y+2][x+1] = qpa + z.ybr[y+2][x+2] = pab + z.ybr[y+2][x+3] = abc + z.ybr[y+3][x+0] = srq + z.ybr[y+3][x+1] = rqp + z.ybr[y+3][x+2] = qpa + z.ybr[y+3][x+3] = pab +} + +func predFunc4VR(z *Decoder, y, x int) { + r := int32(z.ybr[y+2][x-1]) + q := int32(z.ybr[y+1][x-1]) + p := int32(z.ybr[y+0][x-1]) + a := int32(z.ybr[y-1][x-1]) + b := int32(z.ybr[y-1][x+0]) + c := int32(z.ybr[y-1][x+1]) + d := int32(z.ybr[y-1][x+2]) + e := int32(z.ybr[y-1][x+3]) + ab := uint8((a + b + 1) / 2) + bc := uint8((b + c + 1) / 2) + cd := uint8((c + d + 1) / 2) + de := uint8((d + e + 1) / 2) + rqp := uint8((r + 2*q + p + 2) / 4) + qpa := uint8((q + 2*p + a + 2) / 4) + pab := uint8((p + 2*a + b + 2) / 4) + abc := uint8((a + 2*b + c + 2) / 4) + bcd := uint8((b + 2*c + d + 2) / 4) + cde := uint8((c + 2*d + e + 2) / 4) + z.ybr[y+0][x+0] = ab + z.ybr[y+0][x+1] = bc + z.ybr[y+0][x+2] = cd + z.ybr[y+0][x+3] = de + z.ybr[y+1][x+0] = pab + z.ybr[y+1][x+1] = abc + z.ybr[y+1][x+2] = bcd + z.ybr[y+1][x+3] = cde + z.ybr[y+2][x+0] = qpa + z.ybr[y+2][x+1] = ab + z.ybr[y+2][x+2] = bc + z.ybr[y+2][x+3] = cd + z.ybr[y+3][x+0] = rqp + z.ybr[y+3][x+1] = pab + z.ybr[y+3][x+2] = abc + z.ybr[y+3][x+3] = bcd +} + +func predFunc4LD(z *Decoder, y, x int) { + a := int32(z.ybr[y-1][x+0]) + b := int32(z.ybr[y-1][x+1]) + c := int32(z.ybr[y-1][x+2]) + d := int32(z.ybr[y-1][x+3]) + e := int32(z.ybr[y-1][x+4]) + f := int32(z.ybr[y-1][x+5]) + g := int32(z.ybr[y-1][x+6]) + h := int32(z.ybr[y-1][x+7]) + abc := uint8((a + 2*b + c + 2) / 4) + bcd := uint8((b + 2*c + d + 2) / 4) + cde := uint8((c + 2*d + e + 2) / 4) + def := uint8((d + 2*e + f + 2) / 4) + efg := uint8((e + 2*f + g + 2) / 4) + fgh := uint8((f + 2*g + h + 2) / 4) + ghh := uint8((g + 2*h + h + 2) / 4) + z.ybr[y+0][x+0] = abc + z.ybr[y+0][x+1] = bcd + z.ybr[y+0][x+2] = cde + z.ybr[y+0][x+3] = def + z.ybr[y+1][x+0] = bcd + z.ybr[y+1][x+1] = cde + z.ybr[y+1][x+2] = def + z.ybr[y+1][x+3] = efg + z.ybr[y+2][x+0] = cde + z.ybr[y+2][x+1] = def + z.ybr[y+2][x+2] = efg + z.ybr[y+2][x+3] = fgh + z.ybr[y+3][x+0] = def + z.ybr[y+3][x+1] = efg + z.ybr[y+3][x+2] = fgh + z.ybr[y+3][x+3] = ghh +} + +func predFunc4VL(z *Decoder, y, x int) { + a := int32(z.ybr[y-1][x+0]) + b := int32(z.ybr[y-1][x+1]) + c := int32(z.ybr[y-1][x+2]) + d := int32(z.ybr[y-1][x+3]) + e := int32(z.ybr[y-1][x+4]) + f := int32(z.ybr[y-1][x+5]) + g := int32(z.ybr[y-1][x+6]) + h := int32(z.ybr[y-1][x+7]) + ab := uint8((a + b + 1) / 2) + bc := uint8((b + c + 1) / 2) + cd := uint8((c + d + 1) / 2) + de := uint8((d + e + 1) / 2) + abc := uint8((a + 2*b + c + 2) / 4) + bcd := uint8((b + 2*c + d + 2) / 4) + cde := uint8((c + 2*d + e + 2) / 4) + def := uint8((d + 2*e + f + 2) / 4) + efg := uint8((e + 2*f + g + 2) / 4) + fgh := uint8((f + 2*g + h + 2) / 4) + z.ybr[y+0][x+0] = ab + z.ybr[y+0][x+1] = bc + z.ybr[y+0][x+2] = cd + z.ybr[y+0][x+3] = de + z.ybr[y+1][x+0] = abc + z.ybr[y+1][x+1] = bcd + z.ybr[y+1][x+2] = cde + z.ybr[y+1][x+3] = def + z.ybr[y+2][x+0] = bc + z.ybr[y+2][x+1] = cd + z.ybr[y+2][x+2] = de + z.ybr[y+2][x+3] = efg + z.ybr[y+3][x+0] = bcd + z.ybr[y+3][x+1] = cde + z.ybr[y+3][x+2] = def + z.ybr[y+3][x+3] = fgh +} + +func predFunc4HD(z *Decoder, y, x int) { + s := int32(z.ybr[y+3][x-1]) + r := int32(z.ybr[y+2][x-1]) + q := int32(z.ybr[y+1][x-1]) + p := int32(z.ybr[y+0][x-1]) + a := int32(z.ybr[y-1][x-1]) + b := int32(z.ybr[y-1][x+0]) + c := int32(z.ybr[y-1][x+1]) + d := int32(z.ybr[y-1][x+2]) + sr := uint8((s + r + 1) / 2) + rq := uint8((r + q + 1) / 2) + qp := uint8((q + p + 1) / 2) + pa := uint8((p + a + 1) / 2) + srq := uint8((s + 2*r + q + 2) / 4) + rqp := uint8((r + 2*q + p + 2) / 4) + qpa := uint8((q + 2*p + a + 2) / 4) + pab := uint8((p + 2*a + b + 2) / 4) + abc := uint8((a + 2*b + c + 2) / 4) + bcd := uint8((b + 2*c + d + 2) / 4) + z.ybr[y+0][x+0] = pa + z.ybr[y+0][x+1] = pab + z.ybr[y+0][x+2] = abc + z.ybr[y+0][x+3] = bcd + z.ybr[y+1][x+0] = qp + z.ybr[y+1][x+1] = qpa + z.ybr[y+1][x+2] = pa + z.ybr[y+1][x+3] = pab + z.ybr[y+2][x+0] = rq + z.ybr[y+2][x+1] = rqp + z.ybr[y+2][x+2] = qp + z.ybr[y+2][x+3] = qpa + z.ybr[y+3][x+0] = sr + z.ybr[y+3][x+1] = srq + z.ybr[y+3][x+2] = rq + z.ybr[y+3][x+3] = rqp +} + +func predFunc4HU(z *Decoder, y, x int) { + s := int32(z.ybr[y+3][x-1]) + r := int32(z.ybr[y+2][x-1]) + q := int32(z.ybr[y+1][x-1]) + p := int32(z.ybr[y+0][x-1]) + pq := uint8((p + q + 1) / 2) + qr := uint8((q + r + 1) / 2) + rs := uint8((r + s + 1) / 2) + pqr := uint8((p + 2*q + r + 2) / 4) + qrs := uint8((q + 2*r + s + 2) / 4) + rss := uint8((r + 2*s + s + 2) / 4) + sss := uint8(s) + z.ybr[y+0][x+0] = pq + z.ybr[y+0][x+1] = pqr + z.ybr[y+0][x+2] = qr + z.ybr[y+0][x+3] = qrs + z.ybr[y+1][x+0] = qr + z.ybr[y+1][x+1] = qrs + z.ybr[y+1][x+2] = rs + z.ybr[y+1][x+3] = rss + z.ybr[y+2][x+0] = rs + z.ybr[y+2][x+1] = rss + z.ybr[y+2][x+2] = sss + z.ybr[y+2][x+3] = sss + z.ybr[y+3][x+0] = sss + z.ybr[y+3][x+1] = sss + z.ybr[y+3][x+2] = sss + z.ybr[y+3][x+3] = sss +} + +func predFunc8DC(z *Decoder, y, x int) { + sum := uint32(8) + for i := 0; i < 8; i++ { + sum += uint32(z.ybr[y-1][x+i]) + } + for j := 0; j < 8; j++ { + sum += uint32(z.ybr[y+j][x-1]) + } + avg := uint8(sum / 16) + for j := 0; j < 8; j++ { + for i := 0; i < 8; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc8TM(z *Decoder, y, x int) { + delta0 := -int32(z.ybr[y-1][x-1]) + for j := 0; j < 8; j++ { + delta1 := delta0 + int32(z.ybr[y+j][x-1]) + for i := 0; i < 8; i++ { + delta2 := delta1 + int32(z.ybr[y-1][x+i]) + z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255)) + } + } +} + +func predFunc8VE(z *Decoder, y, x int) { + for j := 0; j < 8; j++ { + for i := 0; i < 8; i++ { + z.ybr[y+j][x+i] = z.ybr[y-1][x+i] + } + } +} + +func predFunc8HE(z *Decoder, y, x int) { + for j := 0; j < 8; j++ { + for i := 0; i < 8; i++ { + z.ybr[y+j][x+i] = z.ybr[y+j][x-1] + } + } +} + +func predFunc8DCTop(z *Decoder, y, x int) { + sum := uint32(4) + for j := 0; j < 8; j++ { + sum += uint32(z.ybr[y+j][x-1]) + } + avg := uint8(sum / 8) + for j := 0; j < 8; j++ { + for i := 0; i < 8; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc8DCLeft(z *Decoder, y, x int) { + sum := uint32(4) + for i := 0; i < 8; i++ { + sum += uint32(z.ybr[y-1][x+i]) + } + avg := uint8(sum / 8) + for j := 0; j < 8; j++ { + for i := 0; i < 8; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc8DCTopLeft(z *Decoder, y, x int) { + for j := 0; j < 8; j++ { + for i := 0; i < 8; i++ { + z.ybr[y+j][x+i] = 0x80 + } + } +} + +func predFunc16DC(z *Decoder, y, x int) { + sum := uint32(16) + for i := 0; i < 16; i++ { + sum += uint32(z.ybr[y-1][x+i]) + } + for j := 0; j < 16; j++ { + sum += uint32(z.ybr[y+j][x-1]) + } + avg := uint8(sum / 32) + for j := 0; j < 16; j++ { + for i := 0; i < 16; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc16TM(z *Decoder, y, x int) { + delta0 := -int32(z.ybr[y-1][x-1]) + for j := 0; j < 16; j++ { + delta1 := delta0 + int32(z.ybr[y+j][x-1]) + for i := 0; i < 16; i++ { + delta2 := delta1 + int32(z.ybr[y-1][x+i]) + z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255)) + } + } +} + +func predFunc16VE(z *Decoder, y, x int) { + for j := 0; j < 16; j++ { + for i := 0; i < 16; i++ { + z.ybr[y+j][x+i] = z.ybr[y-1][x+i] + } + } +} + +func predFunc16HE(z *Decoder, y, x int) { + for j := 0; j < 16; j++ { + for i := 0; i < 16; i++ { + z.ybr[y+j][x+i] = z.ybr[y+j][x-1] + } + } +} + +func predFunc16DCTop(z *Decoder, y, x int) { + sum := uint32(8) + for j := 0; j < 16; j++ { + sum += uint32(z.ybr[y+j][x-1]) + } + avg := uint8(sum / 16) + for j := 0; j < 16; j++ { + for i := 0; i < 16; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc16DCLeft(z *Decoder, y, x int) { + sum := uint32(8) + for i := 0; i < 16; i++ { + sum += uint32(z.ybr[y-1][x+i]) + } + avg := uint8(sum / 16) + for j := 0; j < 16; j++ { + for i := 0; i < 16; i++ { + z.ybr[y+j][x+i] = avg + } + } +} + +func predFunc16DCTopLeft(z *Decoder, y, x int) { + for j := 0; j < 16; j++ { + for i := 0; i < 16; i++ { + z.ybr[y+j][x+i] = 0x80 + } + } +} diff --git a/vendor/golang.org/x/image/vp8/quant.go b/vendor/golang.org/x/image/vp8/quant.go new file mode 100644 index 0000000..da43616 --- /dev/null +++ b/vendor/golang.org/x/image/vp8/quant.go @@ -0,0 +1,98 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// This file implements parsing the quantization factors. + +// quant are DC/AC quantization factors. +type quant struct { + y1 [2]uint16 + y2 [2]uint16 + uv [2]uint16 +} + +// clip clips x to the range [min, max] inclusive. +func clip(x, min, max int32) int32 { + if x < min { + return min + } + if x > max { + return max + } + return x +} + +// parseQuant parses the quantization factors, as specified in section 9.6. +func (d *Decoder) parseQuant() { + baseQ0 := d.fp.readUint(uniformProb, 7) + dqy1DC := d.fp.readOptionalInt(uniformProb, 4) + const dqy1AC = 0 + dqy2DC := d.fp.readOptionalInt(uniformProb, 4) + dqy2AC := d.fp.readOptionalInt(uniformProb, 4) + dquvDC := d.fp.readOptionalInt(uniformProb, 4) + dquvAC := d.fp.readOptionalInt(uniformProb, 4) + for i := 0; i < nSegment; i++ { + q := int32(baseQ0) + if d.segmentHeader.useSegment { + if d.segmentHeader.relativeDelta { + q += int32(d.segmentHeader.quantizer[i]) + } else { + q = int32(d.segmentHeader.quantizer[i]) + } + } + d.quant[i].y1[0] = dequantTableDC[clip(q+dqy1DC, 0, 127)] + d.quant[i].y1[1] = dequantTableAC[clip(q+dqy1AC, 0, 127)] + d.quant[i].y2[0] = dequantTableDC[clip(q+dqy2DC, 0, 127)] * 2 + d.quant[i].y2[1] = dequantTableAC[clip(q+dqy2AC, 0, 127)] * 155 / 100 + if d.quant[i].y2[1] < 8 { + d.quant[i].y2[1] = 8 + } + // The 117 is not a typo. The dequant_init function in the spec's Reference + // Decoder Source Code (http://tools.ietf.org/html/rfc6386#section-9.6 Page 145) + // says to clamp the LHS value at 132, which is equal to dequantTableDC[117]. + d.quant[i].uv[0] = dequantTableDC[clip(q+dquvDC, 0, 117)] + d.quant[i].uv[1] = dequantTableAC[clip(q+dquvAC, 0, 127)] + } +} + +// The dequantization tables are specified in section 14.1. +var ( + dequantTableDC = [128]uint16{ + 4, 5, 6, 7, 8, 9, 10, 10, + 11, 12, 13, 14, 15, 16, 17, 17, + 18, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 25, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, + 37, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 46, 47, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, + 59, 60, 61, 62, 63, 64, 65, 66, + 67, 68, 69, 70, 71, 72, 73, 74, + 75, 76, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 88, 89, + 91, 93, 95, 96, 98, 100, 101, 102, + 104, 106, 108, 110, 112, 114, 116, 118, + 122, 124, 126, 128, 130, 132, 134, 136, + 138, 140, 143, 145, 148, 151, 154, 157, + } + dequantTableAC = [128]uint16{ + 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, + 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, + 52, 53, 54, 55, 56, 57, 58, 60, + 62, 64, 66, 68, 70, 72, 74, 76, + 78, 80, 82, 84, 86, 88, 90, 92, + 94, 96, 98, 100, 102, 104, 106, 108, + 110, 112, 114, 116, 119, 122, 125, 128, + 131, 134, 137, 140, 143, 146, 149, 152, + 155, 158, 161, 164, 167, 170, 173, 177, + 181, 185, 189, 193, 197, 201, 205, 209, + 213, 217, 221, 225, 229, 234, 239, 245, + 249, 254, 259, 264, 269, 274, 279, 284, + } +) diff --git a/vendor/golang.org/x/image/vp8/reconstruct.go b/vendor/golang.org/x/image/vp8/reconstruct.go new file mode 100644 index 0000000..67e4c36 --- /dev/null +++ b/vendor/golang.org/x/image/vp8/reconstruct.go @@ -0,0 +1,442 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// This file implements decoding DCT/WHT residual coefficients and +// reconstructing YCbCr data equal to predicted values plus residuals. +// +// There are 1*16*16 + 2*8*8 + 1*4*4 coefficients per macroblock: +// - 1*16*16 luma DCT coefficients, +// - 2*8*8 chroma DCT coefficients, and +// - 1*4*4 luma WHT coefficients. +// Coefficients are read in lots of 16, and the later coefficients in each lot +// are often zero. +// +// The YCbCr data consists of 1*16*16 luma values and 2*8*8 chroma values, +// plus previously decoded values along the top and left borders. The combined +// values are laid out as a [1+16+1+8][32]uint8 so that vertically adjacent +// samples are 32 bytes apart. In detail, the layout is: +// +// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// . . . . . . . a b b b b b b b b b b b b b b b b c c c c . . . . 0 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 1 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 2 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 3 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 4 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 5 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 6 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 7 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 8 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 9 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 10 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 11 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 12 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 13 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 14 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 15 +// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 16 +// . . . . . . . e f f f f f f f f . . . . . . . g h h h h h h h h 17 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 18 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 19 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 20 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 21 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 22 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 23 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 24 +// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 25 +// +// Y, B and R are the reconstructed luma (Y) and chroma (B, R) values. +// The Y values are predicted (either as one 16x16 region or 16 4x4 regions) +// based on the row above's Y values (some combination of {abc} or {dYC}) and +// the column left's Y values (either {ad} or {bY}). Similarly, B and R values +// are predicted on the row above and column left of their respective 8x8 +// region: {efi} for B, {ghj} for R. +// +// For uppermost macroblocks (i.e. those with mby == 0), the {abcefgh} values +// are initialized to 0x81. Otherwise, they are copied from the bottom row of +// the macroblock above. The {c} values are then duplicated from row 0 to rows +// 4, 8 and 12 of the ybr workspace. +// Similarly, for leftmost macroblocks (i.e. those with mbx == 0), the {adeigj} +// values are initialized to 0x7f. Otherwise, they are copied from the right +// column of the macroblock to the left. +// For the top-left macroblock (with mby == 0 && mbx == 0), {aeg} is 0x81. +// +// When moving from one macroblock to the next horizontally, the {adeigj} +// values can simply be copied from the workspace to itself, shifted by 8 or +// 16 columns. When moving from one macroblock to the next vertically, +// filtering can occur and hence the row values have to be copied from the +// post-filtered image instead of the pre-filtered workspace. + +const ( + bCoeffBase = 1*16*16 + 0*8*8 + rCoeffBase = 1*16*16 + 1*8*8 + whtCoeffBase = 1*16*16 + 2*8*8 +) + +const ( + ybrYX = 8 + ybrYY = 1 + ybrBX = 8 + ybrBY = 18 + ybrRX = 24 + ybrRY = 18 +) + +// prepareYBR prepares the {abcdefghij} elements of ybr. +func (d *Decoder) prepareYBR(mbx, mby int) { + if mbx == 0 { + for y := 0; y < 17; y++ { + d.ybr[y][7] = 0x81 + } + for y := 17; y < 26; y++ { + d.ybr[y][7] = 0x81 + d.ybr[y][23] = 0x81 + } + } else { + for y := 0; y < 17; y++ { + d.ybr[y][7] = d.ybr[y][7+16] + } + for y := 17; y < 26; y++ { + d.ybr[y][7] = d.ybr[y][15] + d.ybr[y][23] = d.ybr[y][31] + } + } + if mby == 0 { + for x := 7; x < 28; x++ { + d.ybr[0][x] = 0x7f + } + for x := 7; x < 16; x++ { + d.ybr[17][x] = 0x7f + } + for x := 23; x < 32; x++ { + d.ybr[17][x] = 0x7f + } + } else { + for i := 0; i < 16; i++ { + d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+i] + } + for i := 0; i < 8; i++ { + d.ybr[17][8+i] = d.img.Cb[(8*mby-1)*d.img.CStride+8*mbx+i] + } + for i := 0; i < 8; i++ { + d.ybr[17][24+i] = d.img.Cr[(8*mby-1)*d.img.CStride+8*mbx+i] + } + if mbx == d.mbw-1 { + for i := 16; i < 20; i++ { + d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+15] + } + } else { + for i := 16; i < 20; i++ { + d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+i] + } + } + } + for y := 4; y < 16; y += 4 { + d.ybr[y][24] = d.ybr[0][24] + d.ybr[y][25] = d.ybr[0][25] + d.ybr[y][26] = d.ybr[0][26] + d.ybr[y][27] = d.ybr[0][27] + } +} + +// btou converts a bool to a 0/1 value. +func btou(b bool) uint8 { + if b { + return 1 + } + return 0 +} + +// pack packs four 0/1 values into four bits of a uint32. +func pack(x [4]uint8, shift int) uint32 { + u := uint32(x[0])<<0 | uint32(x[1])<<1 | uint32(x[2])<<2 | uint32(x[3])<<3 + return u << uint(shift) +} + +// unpack unpacks four 0/1 values from a four-bit value. +var unpack = [16][4]uint8{ + {0, 0, 0, 0}, + {1, 0, 0, 0}, + {0, 1, 0, 0}, + {1, 1, 0, 0}, + {0, 0, 1, 0}, + {1, 0, 1, 0}, + {0, 1, 1, 0}, + {1, 1, 1, 0}, + {0, 0, 0, 1}, + {1, 0, 0, 1}, + {0, 1, 0, 1}, + {1, 1, 0, 1}, + {0, 0, 1, 1}, + {1, 0, 1, 1}, + {0, 1, 1, 1}, + {1, 1, 1, 1}, +} + +var ( + // The mapping from 4x4 region position to band is specified in section 13.3. + bands = [17]uint8{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0} + // Category probabilities are specified in section 13.2. + // Decoding categories 1 and 2 are done inline. + cat3456 = [4][12]uint8{ + {173, 148, 140, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {176, 155, 140, 135, 0, 0, 0, 0, 0, 0, 0, 0}, + {180, 157, 141, 134, 130, 0, 0, 0, 0, 0, 0, 0}, + {254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0}, + } + // The zigzag order is: + // 0 1 5 6 + // 2 4 7 12 + // 3 8 11 13 + // 9 10 14 15 + zigzag = [16]uint8{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15} +) + +// parseResiduals4 parses a 4x4 region of residual coefficients, as specified +// in section 13.3, and returns a 0/1 value indicating whether there was at +// least one non-zero coefficient. +// r is the partition to read bits from. +// plane and context describe which token probability table to use. context is +// either 0, 1 or 2, and equals how many of the macroblock left and macroblock +// above have non-zero coefficients. +// quant are the DC/AC quantization factors. +// skipFirstCoeff is whether the DC coefficient has already been parsed. +// coeffBase is the base index of d.coeff to write to. +func (d *Decoder) parseResiduals4(r *partition, plane int, context uint8, quant [2]uint16, skipFirstCoeff bool, coeffBase int) uint8 { + prob, n := &d.tokenProb[plane], 0 + if skipFirstCoeff { + n = 1 + } + p := prob[bands[n]][context] + if !r.readBit(p[0]) { + return 0 + } + for n != 16 { + n++ + if !r.readBit(p[1]) { + p = prob[bands[n]][0] + continue + } + var v uint32 + if !r.readBit(p[2]) { + v = 1 + p = prob[bands[n]][1] + } else { + if !r.readBit(p[3]) { + if !r.readBit(p[4]) { + v = 2 + } else { + v = 3 + r.readUint(p[5], 1) + } + } else if !r.readBit(p[6]) { + if !r.readBit(p[7]) { + // Category 1. + v = 5 + r.readUint(159, 1) + } else { + // Category 2. + v = 7 + 2*r.readUint(165, 1) + r.readUint(145, 1) + } + } else { + // Categories 3, 4, 5 or 6. + b1 := r.readUint(p[8], 1) + b0 := r.readUint(p[9+b1], 1) + cat := 2*b1 + b0 + tab := &cat3456[cat] + v = 0 + for i := 0; tab[i] != 0; i++ { + v *= 2 + v += r.readUint(tab[i], 1) + } + v += 3 + (8 << cat) + } + p = prob[bands[n]][2] + } + z := zigzag[n-1] + c := int32(v) * int32(quant[btou(z > 0)]) + if r.readBit(uniformProb) { + c = -c + } + d.coeff[coeffBase+int(z)] = int16(c) + if n == 16 || !r.readBit(p[0]) { + return 1 + } + } + return 1 +} + +// parseResiduals parses the residuals and returns whether inner loop filtering +// should be skipped for this macroblock. +func (d *Decoder) parseResiduals(mbx, mby int) (skip bool) { + partition := &d.op[mby&(d.nOP-1)] + plane := planeY1SansY2 + quant := &d.quant[d.segment] + + // Parse the DC coefficient of each 4x4 luma region. + if d.usePredY16 { + nz := d.parseResiduals4(partition, planeY2, d.leftMB.nzY16+d.upMB[mbx].nzY16, quant.y2, false, whtCoeffBase) + d.leftMB.nzY16 = nz + d.upMB[mbx].nzY16 = nz + d.inverseWHT16() + plane = planeY1WithY2 + } + + var ( + nzDC, nzAC [4]uint8 + nzDCMask, nzACMask uint32 + coeffBase int + ) + + // Parse the luma coefficients. + lnz := unpack[d.leftMB.nzMask&0x0f] + unz := unpack[d.upMB[mbx].nzMask&0x0f] + for y := 0; y < 4; y++ { + nz := lnz[y] + for x := 0; x < 4; x++ { + nz = d.parseResiduals4(partition, plane, nz+unz[x], quant.y1, d.usePredY16, coeffBase) + unz[x] = nz + nzAC[x] = nz + nzDC[x] = btou(d.coeff[coeffBase] != 0) + coeffBase += 16 + } + lnz[y] = nz + nzDCMask |= pack(nzDC, y*4) + nzACMask |= pack(nzAC, y*4) + } + lnzMask := pack(lnz, 0) + unzMask := pack(unz, 0) + + // Parse the chroma coefficients. + lnz = unpack[d.leftMB.nzMask>>4] + unz = unpack[d.upMB[mbx].nzMask>>4] + for c := 0; c < 4; c += 2 { + for y := 0; y < 2; y++ { + nz := lnz[y+c] + for x := 0; x < 2; x++ { + nz = d.parseResiduals4(partition, planeUV, nz+unz[x+c], quant.uv, false, coeffBase) + unz[x+c] = nz + nzAC[y*2+x] = nz + nzDC[y*2+x] = btou(d.coeff[coeffBase] != 0) + coeffBase += 16 + } + lnz[y+c] = nz + } + nzDCMask |= pack(nzDC, 16+c*2) + nzACMask |= pack(nzAC, 16+c*2) + } + lnzMask |= pack(lnz, 4) + unzMask |= pack(unz, 4) + + // Save decoder state. + d.leftMB.nzMask = uint8(lnzMask) + d.upMB[mbx].nzMask = uint8(unzMask) + d.nzDCMask = nzDCMask + d.nzACMask = nzACMask + + // Section 15.1 of the spec says that "Steps 2 and 4 [of the loop filter] + // are skipped... [if] there is no DCT coefficient coded for the whole + // macroblock." + return nzDCMask == 0 && nzACMask == 0 +} + +// reconstructMacroblock applies the predictor functions and adds the inverse- +// DCT transformed residuals to recover the YCbCr data. +func (d *Decoder) reconstructMacroblock(mbx, mby int) { + if d.usePredY16 { + p := checkTopLeftPred(mbx, mby, d.predY16) + predFunc16[p](d, 1, 8) + for j := 0; j < 4; j++ { + for i := 0; i < 4; i++ { + n := 4*j + i + y := 4*j + 1 + x := 4*i + 8 + mask := uint32(1) << uint(n) + if d.nzACMask&mask != 0 { + d.inverseDCT4(y, x, 16*n) + } else if d.nzDCMask&mask != 0 { + d.inverseDCT4DCOnly(y, x, 16*n) + } + } + } + } else { + for j := 0; j < 4; j++ { + for i := 0; i < 4; i++ { + n := 4*j + i + y := 4*j + 1 + x := 4*i + 8 + predFunc4[d.predY4[j][i]](d, y, x) + mask := uint32(1) << uint(n) + if d.nzACMask&mask != 0 { + d.inverseDCT4(y, x, 16*n) + } else if d.nzDCMask&mask != 0 { + d.inverseDCT4DCOnly(y, x, 16*n) + } + } + } + } + p := checkTopLeftPred(mbx, mby, d.predC8) + predFunc8[p](d, ybrBY, ybrBX) + if d.nzACMask&0x0f0000 != 0 { + d.inverseDCT8(ybrBY, ybrBX, bCoeffBase) + } else if d.nzDCMask&0x0f0000 != 0 { + d.inverseDCT8DCOnly(ybrBY, ybrBX, bCoeffBase) + } + predFunc8[p](d, ybrRY, ybrRX) + if d.nzACMask&0xf00000 != 0 { + d.inverseDCT8(ybrRY, ybrRX, rCoeffBase) + } else if d.nzDCMask&0xf00000 != 0 { + d.inverseDCT8DCOnly(ybrRY, ybrRX, rCoeffBase) + } +} + +// reconstruct reconstructs one macroblock and returns whether inner loop +// filtering should be skipped for it. +func (d *Decoder) reconstruct(mbx, mby int) (skip bool) { + if d.segmentHeader.updateMap { + if !d.fp.readBit(d.segmentHeader.prob[0]) { + d.segment = int(d.fp.readUint(d.segmentHeader.prob[1], 1)) + } else { + d.segment = int(d.fp.readUint(d.segmentHeader.prob[2], 1)) + 2 + } + } + if d.useSkipProb { + skip = d.fp.readBit(d.skipProb) + } + // Prepare the workspace. + for i := range d.coeff { + d.coeff[i] = 0 + } + d.prepareYBR(mbx, mby) + // Parse the predictor modes. + d.usePredY16 = d.fp.readBit(145) + if d.usePredY16 { + d.parsePredModeY16(mbx) + } else { + d.parsePredModeY4(mbx) + } + d.parsePredModeC8() + // Parse the residuals. + if !skip { + skip = d.parseResiduals(mbx, mby) + } else { + if d.usePredY16 { + d.leftMB.nzY16 = 0 + d.upMB[mbx].nzY16 = 0 + } + d.leftMB.nzMask = 0 + d.upMB[mbx].nzMask = 0 + d.nzDCMask = 0 + d.nzACMask = 0 + } + // Reconstruct the YCbCr data and copy it to the image. + d.reconstructMacroblock(mbx, mby) + for i, y := (mby*d.img.YStride+mbx)*16, 0; y < 16; i, y = i+d.img.YStride, y+1 { + copy(d.img.Y[i:i+16], d.ybr[ybrYY+y][ybrYX:ybrYX+16]) + } + for i, y := (mby*d.img.CStride+mbx)*8, 0; y < 8; i, y = i+d.img.CStride, y+1 { + copy(d.img.Cb[i:i+8], d.ybr[ybrBY+y][ybrBX:ybrBX+8]) + copy(d.img.Cr[i:i+8], d.ybr[ybrRY+y][ybrRX:ybrRX+8]) + } + return skip +} diff --git a/vendor/golang.org/x/image/vp8/token.go b/vendor/golang.org/x/image/vp8/token.go new file mode 100644 index 0000000..da99cf0 --- /dev/null +++ b/vendor/golang.org/x/image/vp8/token.go @@ -0,0 +1,381 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8 + +// This file contains token probabilities for decoding DCT/WHT coefficients, as +// specified in chapter 13. + +func (d *Decoder) parseTokenProb() { + for i := range d.tokenProb { + for j := range d.tokenProb[i] { + for k := range d.tokenProb[i][j] { + for l := range d.tokenProb[i][j][k] { + if d.fp.readBit(tokenProbUpdateProb[i][j][k][l]) { + d.tokenProb[i][j][k][l] = uint8(d.fp.readUint(uniformProb, 8)) + } + } + } + } + } +} + +// The plane enumeration is specified in section 13.3. +const ( + planeY1WithY2 = iota + planeY2 + planeUV + planeY1SansY2 + nPlane +) + +const ( + nBand = 8 + nContext = 3 + nProb = 11 +) + +// Token probability update probabilities are specified in section 13.4. +var tokenProbUpdateProb = [nPlane][nBand][nContext][nProb]uint8{ + { + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255}, + {249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255}, + {234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255}, + {250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, + { + { + {217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255}, + {234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255}, + }, + { + {255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, + { + { + {186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255}, + {234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255}, + {251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255}, + }, + { + {255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, + { + { + {248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255}, + {248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255}, + {248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, +} + +// Default token probabilities are specified in section 13.5. +var defaultTokenProb = [nPlane][nBand][nContext][nProb]uint8{ + { + { + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + {253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128}, + {189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128}, + {106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128}, + }, + { + {1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128}, + {181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128}, + {78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128}, + }, + { + {1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128}, + {184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128}, + {77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128}, + }, + { + {1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128}, + {170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128}, + {37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128}, + }, + { + {1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128}, + {207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128}, + {102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128}, + }, + { + {1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128}, + {177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128}, + {80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128}, + }, + { + {1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + }, + { + { + {198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62}, + {131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1}, + {68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128}, + }, + { + {1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128}, + {184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128}, + {81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128}, + }, + { + {1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128}, + {99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128}, + {23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128}, + }, + { + {1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128}, + {109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128}, + {44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128}, + }, + { + {1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128}, + {94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128}, + {22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128}, + }, + { + {1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128}, + {124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128}, + {35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128}, + }, + { + {1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128}, + {121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128}, + {45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128}, + }, + { + {1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128}, + {203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128}, + {137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128}, + }, + }, + { + { + {253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128}, + {175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128}, + {73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128}, + }, + { + {1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128}, + {239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128}, + {155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128}, + }, + { + {1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128}, + {201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128}, + {69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128}, + }, + { + {1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128}, + {223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128}, + {141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128}, + }, + { + {1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128}, + {190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128}, + {149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + {1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + {1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128}, + {213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128}, + {55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + }, + { + { + {202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255}, + {126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128}, + {61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128}, + }, + { + {1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128}, + {166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128}, + {39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128}, + }, + { + {1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128}, + {124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128}, + {24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128}, + }, + { + {1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128}, + {149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128}, + {28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128}, + }, + { + {1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128}, + {123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128}, + {20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128}, + }, + { + {1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128}, + {168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128}, + {47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128}, + }, + { + {1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128}, + {141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128}, + {42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128}, + }, + { + {1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + }, +} diff --git a/vendor/golang.org/x/image/vp8l/decode.go b/vendor/golang.org/x/image/vp8l/decode.go new file mode 100644 index 0000000..4319487 --- /dev/null +++ b/vendor/golang.org/x/image/vp8l/decode.go @@ -0,0 +1,603 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package vp8l implements a decoder for the VP8L lossless image format. +// +// The VP8L specification is at: +// https://developers.google.com/speed/webp/docs/riff_container +package vp8l // import "golang.org/x/image/vp8l" + +import ( + "bufio" + "errors" + "image" + "image/color" + "io" +) + +var ( + errInvalidCodeLengths = errors.New("vp8l: invalid code lengths") + errInvalidHuffmanTree = errors.New("vp8l: invalid Huffman tree") +) + +// colorCacheMultiplier is the multiplier used for the color cache hash +// function, specified in section 4.2.3. +const colorCacheMultiplier = 0x1e35a7bd + +// distanceMapTable is the look-up table for distanceMap. +var distanceMapTable = [120]uint8{ + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, + 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a, + 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, + 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03, + 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, + 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e, + 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, + 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f, + 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, + 0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41, + 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, + 0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} + +// distanceMap maps a LZ77 backwards reference distance to a two-dimensional +// pixel offset, specified in section 4.2.2. +func distanceMap(w int32, code uint32) int32 { + if int32(code) > int32(len(distanceMapTable)) { + return int32(code) - int32(len(distanceMapTable)) + } + distCode := int32(distanceMapTable[code-1]) + yOffset := distCode >> 4 + xOffset := 8 - distCode&0xf + if d := yOffset*w + xOffset; d >= 1 { + return d + } + return 1 +} + +// decoder holds the bit-stream for a VP8L image. +type decoder struct { + r io.ByteReader + bits uint32 + nBits uint32 +} + +// read reads the next n bits from the decoder's bit-stream. +func (d *decoder) read(n uint32) (uint32, error) { + for d.nBits < n { + c, err := d.r.ReadByte() + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + d.bits |= uint32(c) << d.nBits + d.nBits += 8 + } + u := d.bits & (1<>= n + d.nBits -= n + return u, nil +} + +// decodeTransform decodes the next transform and the width of the image after +// transformation (or equivalently, before inverse transformation), specified +// in section 3. +func (d *decoder) decodeTransform(w int32, h int32) (t transform, newWidth int32, err error) { + t.oldWidth = w + t.transformType, err = d.read(2) + if err != nil { + return transform{}, 0, err + } + switch t.transformType { + case transformTypePredictor, transformTypeCrossColor: + t.bits, err = d.read(3) + if err != nil { + return transform{}, 0, err + } + t.bits += 2 + t.pix, err = d.decodePix(nTiles(w, t.bits), nTiles(h, t.bits), 0, false) + if err != nil { + return transform{}, 0, err + } + case transformTypeSubtractGreen: + // No-op. + case transformTypeColorIndexing: + nColors, err := d.read(8) + if err != nil { + return transform{}, 0, err + } + nColors++ + t.bits = 0 + switch { + case nColors <= 2: + t.bits = 3 + case nColors <= 4: + t.bits = 2 + case nColors <= 16: + t.bits = 1 + } + w = nTiles(w, t.bits) + pix, err := d.decodePix(int32(nColors), 1, 4*256, false) + if err != nil { + return transform{}, 0, err + } + for p := 4; p < len(pix); p += 4 { + pix[p+0] += pix[p-4] + pix[p+1] += pix[p-3] + pix[p+2] += pix[p-2] + pix[p+3] += pix[p-1] + } + // The spec says that "if the index is equal or larger than color_table_size, + // the argb color value should be set to 0x00000000 (transparent black)." + // We re-slice up to 256 4-byte pixels. + t.pix = pix[:4*256] + } + return t, w, nil +} + +// repeatsCodeLength is the minimum code length for repeated codes. +const repeatsCodeLength = 16 + +// These magic numbers are specified at the end of section 5.2.2. +// The 3-length arrays apply to code lengths >= repeatsCodeLength. +var ( + codeLengthCodeOrder = [19]uint8{ + 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + } + repeatBits = [3]uint8{2, 3, 7} + repeatOffsets = [3]uint8{3, 3, 11} +) + +// decodeCodeLengths decodes a Huffman tree's code lengths which are themselves +// encoded via a Huffman tree, specified in section 5.2.2. +func (d *decoder) decodeCodeLengths(dst []uint32, codeLengthCodeLengths []uint32) error { + h := hTree{} + if err := h.build(codeLengthCodeLengths); err != nil { + return err + } + + maxSymbol := len(dst) + useLength, err := d.read(1) + if err != nil { + return err + } + if useLength != 0 { + n, err := d.read(3) + if err != nil { + return err + } + n = 2 + 2*n + ms, err := d.read(n) + if err != nil { + return err + } + maxSymbol = int(ms) + 2 + if maxSymbol > len(dst) { + return errInvalidCodeLengths + } + } + + // The spec says that "if code 16 [meaning repeat] is used before + // a non-zero value has been emitted, a value of 8 is repeated." + prevCodeLength := uint32(8) + + for symbol := 0; symbol < len(dst); { + if maxSymbol == 0 { + break + } + maxSymbol-- + codeLength, err := h.next(d) + if err != nil { + return err + } + if codeLength < repeatsCodeLength { + dst[symbol] = codeLength + symbol++ + if codeLength != 0 { + prevCodeLength = codeLength + } + continue + } + + repeat, err := d.read(uint32(repeatBits[codeLength-repeatsCodeLength])) + if err != nil { + return err + } + repeat += uint32(repeatOffsets[codeLength-repeatsCodeLength]) + if symbol+int(repeat) > len(dst) { + return errInvalidCodeLengths + } + // A code length of 16 repeats the previous non-zero code. + // A code length of 17 or 18 repeats zeroes. + cl := uint32(0) + if codeLength == 16 { + cl = prevCodeLength + } + for ; repeat > 0; repeat-- { + dst[symbol] = cl + symbol++ + } + } + return nil +} + +// decodeHuffmanTree decodes a Huffman tree into h. +func (d *decoder) decodeHuffmanTree(h *hTree, alphabetSize uint32) error { + useSimple, err := d.read(1) + if err != nil { + return err + } + if useSimple != 0 { + nSymbols, err := d.read(1) + if err != nil { + return err + } + nSymbols++ + firstSymbolLengthCode, err := d.read(1) + if err != nil { + return err + } + firstSymbolLengthCode = 7*firstSymbolLengthCode + 1 + var symbols [2]uint32 + symbols[0], err = d.read(firstSymbolLengthCode) + if err != nil { + return err + } + if nSymbols == 2 { + symbols[1], err = d.read(8) + if err != nil { + return err + } + } + return h.buildSimple(nSymbols, symbols, alphabetSize) + } + + nCodes, err := d.read(4) + if err != nil { + return err + } + nCodes += 4 + if int(nCodes) > len(codeLengthCodeOrder) { + return errInvalidHuffmanTree + } + codeLengthCodeLengths := [len(codeLengthCodeOrder)]uint32{} + for i := uint32(0); i < nCodes; i++ { + codeLengthCodeLengths[codeLengthCodeOrder[i]], err = d.read(3) + if err != nil { + return err + } + } + codeLengths := make([]uint32, alphabetSize) + if err = d.decodeCodeLengths(codeLengths, codeLengthCodeLengths[:]); err != nil { + return err + } + return h.build(codeLengths) +} + +const ( + huffGreen = 0 + huffRed = 1 + huffBlue = 2 + huffAlpha = 3 + huffDistance = 4 + nHuff = 5 +) + +// hGroup is an array of 5 Huffman trees. +type hGroup [nHuff]hTree + +// decodeHuffmanGroups decodes the one or more hGroups used to decode the pixel +// data. If one hGroup is used for the entire image, then hPix and hBits will +// be zero. If more than one hGroup is used, then hPix contains the meta-image +// that maps tiles to hGroup index, and hBits contains the log-2 tile size. +func (d *decoder) decodeHuffmanGroups(w int32, h int32, topLevel bool, ccBits uint32) ( + hGroups []hGroup, hPix []byte, hBits uint32, err error) { + + maxHGroupIndex := 0 + if topLevel { + useMeta, err := d.read(1) + if err != nil { + return nil, nil, 0, err + } + if useMeta != 0 { + hBits, err = d.read(3) + if err != nil { + return nil, nil, 0, err + } + hBits += 2 + hPix, err = d.decodePix(nTiles(w, hBits), nTiles(h, hBits), 0, false) + if err != nil { + return nil, nil, 0, err + } + for p := 0; p < len(hPix); p += 4 { + i := int(hPix[p])<<8 | int(hPix[p+1]) + if maxHGroupIndex < i { + maxHGroupIndex = i + } + } + } + } + hGroups = make([]hGroup, maxHGroupIndex+1) + for i := range hGroups { + for j, alphabetSize := range alphabetSizes { + if j == 0 && ccBits > 0 { + alphabetSize += 1 << ccBits + } + if err := d.decodeHuffmanTree(&hGroups[i][j], alphabetSize); err != nil { + return nil, nil, 0, err + } + } + } + return hGroups, hPix, hBits, nil +} + +const ( + nLiteralCodes = 256 + nLengthCodes = 24 + nDistanceCodes = 40 +) + +var alphabetSizes = [nHuff]uint32{ + nLiteralCodes + nLengthCodes, + nLiteralCodes, + nLiteralCodes, + nLiteralCodes, + nDistanceCodes, +} + +// decodePix decodes pixel data, specified in section 5.2.2. +func (d *decoder) decodePix(w int32, h int32, minCap int32, topLevel bool) ([]byte, error) { + // Decode the color cache parameters. + ccBits, ccShift, ccEntries := uint32(0), uint32(0), ([]uint32)(nil) + useColorCache, err := d.read(1) + if err != nil { + return nil, err + } + if useColorCache != 0 { + ccBits, err = d.read(4) + if err != nil { + return nil, err + } + if ccBits < 1 || 11 < ccBits { + return nil, errors.New("vp8l: invalid color cache parameters") + } + ccShift = 32 - ccBits + ccEntries = make([]uint32, 1<>hBits) + (x >> hBits)) + hg = &hGroups[uint32(hPix[i])<<8|uint32(hPix[i+1])] + } + + green, err := hg[huffGreen].next(d) + if err != nil { + return nil, err + } + switch { + case green < nLiteralCodes: + // We have a literal pixel. + red, err := hg[huffRed].next(d) + if err != nil { + return nil, err + } + blue, err := hg[huffBlue].next(d) + if err != nil { + return nil, err + } + alpha, err := hg[huffAlpha].next(d) + if err != nil { + return nil, err + } + pix[p+0] = uint8(red) + pix[p+1] = uint8(green) + pix[p+2] = uint8(blue) + pix[p+3] = uint8(alpha) + p += 4 + + x++ + if x == w { + x, y = 0, y+1 + } + lookupHG = hMask != 0 && x&hMask == 0 + + case green < nLiteralCodes+nLengthCodes: + // We have a LZ77 backwards reference. + length, err := d.lz77Param(green - nLiteralCodes) + if err != nil { + return nil, err + } + distSym, err := hg[huffDistance].next(d) + if err != nil { + return nil, err + } + distCode, err := d.lz77Param(distSym) + if err != nil { + return nil, err + } + dist := distanceMap(w, distCode) + pEnd := p + 4*int(length) + q := p - 4*int(dist) + qEnd := pEnd - 4*int(dist) + if p < 0 || len(pix) < pEnd || q < 0 || len(pix) < qEnd { + return nil, errors.New("vp8l: invalid LZ77 parameters") + } + for ; p < pEnd; p, q = p+1, q+1 { + pix[p] = pix[q] + } + + x += int32(length) + for x >= w { + x, y = x-w, y+1 + } + lookupHG = hMask != 0 + + default: + // We have a color cache lookup. First, insert previous pixels + // into the cache. Note that VP8L assumes ARGB order, but the + // Go image.RGBA type is in RGBA order. + for ; cachedP < p; cachedP += 4 { + argb := uint32(pix[cachedP+0])<<16 | + uint32(pix[cachedP+1])<<8 | + uint32(pix[cachedP+2])<<0 | + uint32(pix[cachedP+3])<<24 + ccEntries[(argb*colorCacheMultiplier)>>ccShift] = argb + } + green -= nLiteralCodes + nLengthCodes + if int(green) >= len(ccEntries) { + return nil, errors.New("vp8l: invalid color cache index") + } + argb := ccEntries[green] + pix[p+0] = uint8(argb >> 16) + pix[p+1] = uint8(argb >> 8) + pix[p+2] = uint8(argb >> 0) + pix[p+3] = uint8(argb >> 24) + p += 4 + + x++ + if x == w { + x, y = 0, y+1 + } + lookupHG = hMask != 0 && x&hMask == 0 + } + } + return pix, nil +} + +// lz77Param returns the next LZ77 parameter: a length or a distance, specified +// in section 4.2.2. +func (d *decoder) lz77Param(symbol uint32) (uint32, error) { + if symbol < 4 { + return symbol + 1, nil + } + extraBits := (symbol - 2) >> 1 + offset := (2 + symbol&1) << extraBits + n, err := d.read(extraBits) + if err != nil { + return 0, err + } + return offset + n + 1, nil +} + +// decodeHeader decodes the VP8L header from r. +func decodeHeader(r io.Reader) (d *decoder, w int32, h int32, err error) { + rr, ok := r.(io.ByteReader) + if !ok { + rr = bufio.NewReader(r) + } + d = &decoder{r: rr} + magic, err := d.read(8) + if err != nil { + return nil, 0, 0, err + } + if magic != 0x2f { + return nil, 0, 0, errors.New("vp8l: invalid header") + } + width, err := d.read(14) + if err != nil { + return nil, 0, 0, err + } + width++ + height, err := d.read(14) + if err != nil { + return nil, 0, 0, err + } + height++ + _, err = d.read(1) // Read and ignore the hasAlpha hint. + if err != nil { + return nil, 0, 0, err + } + version, err := d.read(3) + if err != nil { + return nil, 0, 0, err + } + if version != 0 { + return nil, 0, 0, errors.New("vp8l: invalid version") + } + return d, int32(width), int32(height), nil +} + +// DecodeConfig decodes the color model and dimensions of a VP8L image from r. +func DecodeConfig(r io.Reader) (image.Config, error) { + _, w, h, err := decodeHeader(r) + if err != nil { + return image.Config{}, err + } + return image.Config{ + ColorModel: color.NRGBAModel, + Width: int(w), + Height: int(h), + }, nil +} + +// Decode decodes a VP8L image from r. +func Decode(r io.Reader) (image.Image, error) { + d, w, h, err := decodeHeader(r) + if err != nil { + return nil, err + } + // Decode the transforms. + var ( + nTransforms int + transforms [nTransformTypes]transform + transformsSeen [nTransformTypes]bool + originalW = w + ) + for { + more, err := d.read(1) + if err != nil { + return nil, err + } + if more == 0 { + break + } + var t transform + t, w, err = d.decodeTransform(w, h) + if err != nil { + return nil, err + } + if transformsSeen[t.transformType] { + return nil, errors.New("vp8l: repeated transform") + } + transformsSeen[t.transformType] = true + transforms[nTransforms] = t + nTransforms++ + } + // Decode the transformed pixels. + pix, err := d.decodePix(w, h, 0, true) + if err != nil { + return nil, err + } + // Apply the inverse transformations. + for i := nTransforms - 1; i >= 0; i-- { + t := &transforms[i] + pix = inverseTransforms[t.transformType](t, pix, h) + } + return &image.NRGBA{ + Pix: pix, + Stride: 4 * int(originalW), + Rect: image.Rect(0, 0, int(originalW), int(h)), + }, nil +} diff --git a/vendor/golang.org/x/image/vp8l/huffman.go b/vendor/golang.org/x/image/vp8l/huffman.go new file mode 100644 index 0000000..36368a8 --- /dev/null +++ b/vendor/golang.org/x/image/vp8l/huffman.go @@ -0,0 +1,245 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8l + +import ( + "io" +) + +// reverseBits reverses the bits in a byte. +var reverseBits = [256]uint8{ + 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, + 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, + 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, + 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, + 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, + 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, + 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, + 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, + 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, + 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, + 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, + 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, + 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, + 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, + 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, + 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, +} + +// hNode is a node in a Huffman tree. +type hNode struct { + // symbol is the symbol held by this node. + symbol uint32 + // children, if positive, is the hTree.nodes index of the first of + // this node's two children. Zero means an uninitialized node, + // and -1 means a leaf node. + children int32 +} + +const leafNode = -1 + +// lutSize is the log-2 size of an hTree's look-up table. +const lutSize, lutMask = 7, 1<<7 - 1 + +// hTree is a Huffman tree. +type hTree struct { + // nodes are the nodes of the Huffman tree. During construction, + // len(nodes) grows from 1 up to cap(nodes) by steps of two. + // After construction, len(nodes) == cap(nodes), and both equal + // 2*theNumberOfSymbols - 1. + nodes []hNode + // lut is a look-up table for walking the nodes. The x in lut[x] is + // the next lutSize bits in the bit-stream. The low 8 bits of lut[x] + // equals 1 plus the number of bits in the next code, or 0 if the + // next code requires more than lutSize bits. The high 24 bits are: + // - the symbol, if the code requires lutSize or fewer bits, or + // - the hTree.nodes index to start the tree traversal from, if + // the next code requires more than lutSize bits. + lut [1 << lutSize]uint32 +} + +// insert inserts into the hTree a symbol whose encoding is the least +// significant codeLength bits of code. +func (h *hTree) insert(symbol uint32, code uint32, codeLength uint32) error { + if symbol > 0xffff || codeLength > 0xfe { + return errInvalidHuffmanTree + } + baseCode := uint32(0) + if codeLength > lutSize { + baseCode = uint32(reverseBits[(code>>(codeLength-lutSize))&0xff]) >> (8 - lutSize) + } else { + baseCode = uint32(reverseBits[code&0xff]) >> (8 - codeLength) + for i := 0; i < 1<<(lutSize-codeLength); i++ { + h.lut[baseCode|uint32(i)< 0; { + codeLength-- + if int(n) > len(h.nodes) { + return errInvalidHuffmanTree + } + switch h.nodes[n].children { + case leafNode: + return errInvalidHuffmanTree + case 0: + if len(h.nodes) == cap(h.nodes) { + return errInvalidHuffmanTree + } + // Create two empty child nodes. + h.nodes[n].children = int32(len(h.nodes)) + h.nodes = h.nodes[:len(h.nodes)+2] + } + n = uint32(h.nodes[n].children) + 1&(code>>codeLength) + jump-- + if jump == 0 && h.lut[baseCode] == 0 { + h.lut[baseCode] = n << 8 + } + } + + switch h.nodes[n].children { + case leafNode: + // No-op. + case 0: + // Turn the uninitialized node into a leaf. + h.nodes[n].children = leafNode + default: + return errInvalidHuffmanTree + } + h.nodes[n].symbol = symbol + return nil +} + +// codeLengthsToCodes returns the canonical Huffman codes implied by the +// sequence of code lengths. +func codeLengthsToCodes(codeLengths []uint32) ([]uint32, error) { + maxCodeLength := uint32(0) + for _, cl := range codeLengths { + if maxCodeLength < cl { + maxCodeLength = cl + } + } + const maxAllowedCodeLength = 15 + if len(codeLengths) == 0 || maxCodeLength > maxAllowedCodeLength { + return nil, errInvalidHuffmanTree + } + histogram := [maxAllowedCodeLength + 1]uint32{} + for _, cl := range codeLengths { + histogram[cl]++ + } + currCode, nextCodes := uint32(0), [maxAllowedCodeLength + 1]uint32{} + for cl := 1; cl < len(nextCodes); cl++ { + currCode = (currCode + histogram[cl-1]) << 1 + nextCodes[cl] = currCode + } + codes := make([]uint32, len(codeLengths)) + for symbol, cl := range codeLengths { + if cl > 0 { + codes[symbol] = nextCodes[cl] + nextCodes[cl]++ + } + } + return codes, nil +} + +// build builds a canonical Huffman tree from the given code lengths. +func (h *hTree) build(codeLengths []uint32) error { + // Calculate the number of symbols. + var nSymbols, lastSymbol uint32 + for symbol, cl := range codeLengths { + if cl != 0 { + nSymbols++ + lastSymbol = uint32(symbol) + } + } + if nSymbols == 0 { + return errInvalidHuffmanTree + } + h.nodes = make([]hNode, 1, 2*nSymbols-1) + // Handle the trivial case. + if nSymbols == 1 { + if len(codeLengths) <= int(lastSymbol) { + return errInvalidHuffmanTree + } + return h.insert(lastSymbol, 0, 0) + } + // Handle the non-trivial case. + codes, err := codeLengthsToCodes(codeLengths) + if err != nil { + return err + } + for symbol, cl := range codeLengths { + if cl > 0 { + if err := h.insert(uint32(symbol), codes[symbol], cl); err != nil { + return err + } + } + } + return nil +} + +// buildSimple builds a Huffman tree with 1 or 2 symbols. +func (h *hTree) buildSimple(nSymbols uint32, symbols [2]uint32, alphabetSize uint32) error { + h.nodes = make([]hNode, 1, 2*nSymbols-1) + for i := uint32(0); i < nSymbols; i++ { + if symbols[i] >= alphabetSize { + return errInvalidHuffmanTree + } + if err := h.insert(symbols[i], i, nSymbols-1); err != nil { + return err + } + } + return nil +} + +// next returns the next Huffman-encoded symbol from the bit-stream d. +func (h *hTree) next(d *decoder) (uint32, error) { + var n uint32 + // Read enough bits so that we can use the look-up table. + if d.nBits < lutSize { + c, err := d.r.ReadByte() + if err != nil { + if err == io.EOF { + // There are no more bytes of data, but we may still be able + // to read the next symbol out of the previously read bits. + goto slowPath + } + return 0, err + } + d.bits |= uint32(c) << d.nBits + d.nBits += 8 + } + // Use the look-up table. + n = h.lut[d.bits&lutMask] + if b := n & 0xff; b != 0 { + b-- + d.bits >>= b + d.nBits -= b + return n >> 8, nil + } + n >>= 8 + d.bits >>= lutSize + d.nBits -= lutSize + +slowPath: + for h.nodes[n].children != leafNode { + if d.nBits == 0 { + c, err := d.r.ReadByte() + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + d.bits = uint32(c) + d.nBits = 8 + } + n = uint32(h.nodes[n].children) + 1&d.bits + d.bits >>= 1 + d.nBits-- + } + return h.nodes[n].symbol, nil +} diff --git a/vendor/golang.org/x/image/vp8l/transform.go b/vendor/golang.org/x/image/vp8l/transform.go new file mode 100644 index 0000000..06543da --- /dev/null +++ b/vendor/golang.org/x/image/vp8l/transform.go @@ -0,0 +1,299 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package vp8l + +// This file deals with image transforms, specified in section 3. + +// nTiles returns the number of tiles needed to cover size pixels, where each +// tile's side is 1<> bits +} + +const ( + transformTypePredictor = 0 + transformTypeCrossColor = 1 + transformTypeSubtractGreen = 2 + transformTypeColorIndexing = 3 + nTransformTypes = 4 +) + +// transform holds the parameters for an invertible transform. +type transform struct { + // transformType is the type of the transform. + transformType uint32 + // oldWidth is the width of the image before transformation (or + // equivalently, after inverse transformation). The color-indexing + // transform can reduce the width. For example, a 50-pixel-wide + // image that only needs 4 bits (half a byte) per color index can + // be transformed into a 25-pixel-wide image. + oldWidth int32 + // bits is the log-2 size of the transform's tiles, for the predictor + // and cross-color transforms. 8>>bits is the number of bits per + // color index, for the color-index transform. + bits uint32 + // pix is the tile values, for the predictor and cross-color + // transforms, and the color palette, for the color-index transform. + pix []byte +} + +var inverseTransforms = [nTransformTypes]func(*transform, []byte, int32) []byte{ + transformTypePredictor: inversePredictor, + transformTypeCrossColor: inverseCrossColor, + transformTypeSubtractGreen: inverseSubtractGreen, + transformTypeColorIndexing: inverseColorIndexing, +} + +func inversePredictor(t *transform, pix []byte, h int32) []byte { + if t.oldWidth == 0 || h == 0 { + return pix + } + // The first pixel's predictor is mode 0 (opaque black). + pix[3] += 0xff + p, mask := int32(4), int32(1)<> t.bits) * tilesPerRow + predictorMode := t.pix[q+1] & 0x0f + q += 4 + for x := int32(1); x < t.oldWidth; x++ { + if x&mask == 0 { + predictorMode = t.pix[q+1] & 0x0f + q += 4 + } + switch predictorMode { + case 0: // Opaque black. + pix[p+3] += 0xff + + case 1: // L. + pix[p+0] += pix[p-4] + pix[p+1] += pix[p-3] + pix[p+2] += pix[p-2] + pix[p+3] += pix[p-1] + + case 2: // T. + pix[p+0] += pix[top+0] + pix[p+1] += pix[top+1] + pix[p+2] += pix[top+2] + pix[p+3] += pix[top+3] + + case 3: // TR. + pix[p+0] += pix[top+4] + pix[p+1] += pix[top+5] + pix[p+2] += pix[top+6] + pix[p+3] += pix[top+7] + + case 4: // TL. + pix[p+0] += pix[top-4] + pix[p+1] += pix[top-3] + pix[p+2] += pix[top-2] + pix[p+3] += pix[top-1] + + case 5: // Average2(Average2(L, TR), T). + pix[p+0] += avg2(avg2(pix[p-4], pix[top+4]), pix[top+0]) + pix[p+1] += avg2(avg2(pix[p-3], pix[top+5]), pix[top+1]) + pix[p+2] += avg2(avg2(pix[p-2], pix[top+6]), pix[top+2]) + pix[p+3] += avg2(avg2(pix[p-1], pix[top+7]), pix[top+3]) + + case 6: // Average2(L, TL). + pix[p+0] += avg2(pix[p-4], pix[top-4]) + pix[p+1] += avg2(pix[p-3], pix[top-3]) + pix[p+2] += avg2(pix[p-2], pix[top-2]) + pix[p+3] += avg2(pix[p-1], pix[top-1]) + + case 7: // Average2(L, T). + pix[p+0] += avg2(pix[p-4], pix[top+0]) + pix[p+1] += avg2(pix[p-3], pix[top+1]) + pix[p+2] += avg2(pix[p-2], pix[top+2]) + pix[p+3] += avg2(pix[p-1], pix[top+3]) + + case 8: // Average2(TL, T). + pix[p+0] += avg2(pix[top-4], pix[top+0]) + pix[p+1] += avg2(pix[top-3], pix[top+1]) + pix[p+2] += avg2(pix[top-2], pix[top+2]) + pix[p+3] += avg2(pix[top-1], pix[top+3]) + + case 9: // Average2(T, TR). + pix[p+0] += avg2(pix[top+0], pix[top+4]) + pix[p+1] += avg2(pix[top+1], pix[top+5]) + pix[p+2] += avg2(pix[top+2], pix[top+6]) + pix[p+3] += avg2(pix[top+3], pix[top+7]) + + case 10: // Average2(Average2(L, TL), Average2(T, TR)). + pix[p+0] += avg2(avg2(pix[p-4], pix[top-4]), avg2(pix[top+0], pix[top+4])) + pix[p+1] += avg2(avg2(pix[p-3], pix[top-3]), avg2(pix[top+1], pix[top+5])) + pix[p+2] += avg2(avg2(pix[p-2], pix[top-2]), avg2(pix[top+2], pix[top+6])) + pix[p+3] += avg2(avg2(pix[p-1], pix[top-1]), avg2(pix[top+3], pix[top+7])) + + case 11: // Select(L, T, TL). + l0 := int32(pix[p-4]) + l1 := int32(pix[p-3]) + l2 := int32(pix[p-2]) + l3 := int32(pix[p-1]) + c0 := int32(pix[top-4]) + c1 := int32(pix[top-3]) + c2 := int32(pix[top-2]) + c3 := int32(pix[top-1]) + t0 := int32(pix[top+0]) + t1 := int32(pix[top+1]) + t2 := int32(pix[top+2]) + t3 := int32(pix[top+3]) + l := abs(c0-t0) + abs(c1-t1) + abs(c2-t2) + abs(c3-t3) + t := abs(c0-l0) + abs(c1-l1) + abs(c2-l2) + abs(c3-l3) + if l < t { + pix[p+0] += uint8(l0) + pix[p+1] += uint8(l1) + pix[p+2] += uint8(l2) + pix[p+3] += uint8(l3) + } else { + pix[p+0] += uint8(t0) + pix[p+1] += uint8(t1) + pix[p+2] += uint8(t2) + pix[p+3] += uint8(t3) + } + + case 12: // ClampAddSubtractFull(L, T, TL). + pix[p+0] += clampAddSubtractFull(pix[p-4], pix[top+0], pix[top-4]) + pix[p+1] += clampAddSubtractFull(pix[p-3], pix[top+1], pix[top-3]) + pix[p+2] += clampAddSubtractFull(pix[p-2], pix[top+2], pix[top-2]) + pix[p+3] += clampAddSubtractFull(pix[p-1], pix[top+3], pix[top-1]) + + case 13: // ClampAddSubtractHalf(Average2(L, T), TL). + pix[p+0] += clampAddSubtractHalf(avg2(pix[p-4], pix[top+0]), pix[top-4]) + pix[p+1] += clampAddSubtractHalf(avg2(pix[p-3], pix[top+1]), pix[top-3]) + pix[p+2] += clampAddSubtractHalf(avg2(pix[p-2], pix[top+2]), pix[top-2]) + pix[p+3] += clampAddSubtractHalf(avg2(pix[p-1], pix[top+3]), pix[top-1]) + } + p, top = p+4, top+4 + } + } + return pix +} + +func inverseCrossColor(t *transform, pix []byte, h int32) []byte { + var greenToRed, greenToBlue, redToBlue int32 + p, mask, tilesPerRow := int32(0), int32(1)<> t.bits) * tilesPerRow + for x := int32(0); x < t.oldWidth; x++ { + if x&mask == 0 { + redToBlue = int32(int8(t.pix[q+0])) + greenToBlue = int32(int8(t.pix[q+1])) + greenToRed = int32(int8(t.pix[q+2])) + q += 4 + } + red := pix[p+0] + green := pix[p+1] + blue := pix[p+2] + red += uint8(uint32(greenToRed*int32(int8(green))) >> 5) + blue += uint8(uint32(greenToBlue*int32(int8(green))) >> 5) + blue += uint8(uint32(redToBlue*int32(int8(red))) >> 5) + pix[p+0] = red + pix[p+2] = blue + p += 4 + } + } + return pix +} + +func inverseSubtractGreen(t *transform, pix []byte, h int32) []byte { + for p := 0; p < len(pix); p += 4 { + green := pix[p+1] + pix[p+0] += green + pix[p+2] += green + } + return pix +} + +func inverseColorIndexing(t *transform, pix []byte, h int32) []byte { + if t.bits == 0 { + for p := 0; p < len(pix); p += 4 { + i := 4 * uint32(pix[p+1]) + pix[p+0] = t.pix[i+0] + pix[p+1] = t.pix[i+1] + pix[p+2] = t.pix[i+2] + pix[p+3] = t.pix[i+3] + } + return pix + } + + vMask, xMask, bitsPerPixel := uint32(0), int32(0), uint32(8>>t.bits) + switch t.bits { + case 1: + vMask, xMask = 0x0f, 0x01 + case 2: + vMask, xMask = 0x03, 0x03 + case 3: + vMask, xMask = 0x01, 0x07 + } + + d, p, v, dst := 0, 0, uint32(0), make([]byte, 4*t.oldWidth*h) + for y := int32(0); y < h; y++ { + for x := int32(0); x < t.oldWidth; x++ { + if x&xMask == 0 { + v = uint32(pix[p+1]) + p += 4 + } + + i := 4 * (v & vMask) + dst[d+0] = t.pix[i+0] + dst[d+1] = t.pix[i+1] + dst[d+2] = t.pix[i+2] + dst[d+3] = t.pix[i+3] + d += 4 + + v >>= bitsPerPixel + } + } + return dst +} + +func abs(x int32) int32 { + if x < 0 { + return -x + } + return x +} + +func avg2(a, b uint8) uint8 { + return uint8((int32(a) + int32(b)) / 2) +} + +func clampAddSubtractFull(a, b, c uint8) uint8 { + x := int32(a) + int32(b) - int32(c) + if x < 0 { + return 0 + } + if x > 255 { + return 255 + } + return uint8(x) +} + +func clampAddSubtractHalf(a, b uint8) uint8 { + x := int32(a) + (int32(a)-int32(b))/2 + if x < 0 { + return 0 + } + if x > 255 { + return 255 + } + return uint8(x) +} diff --git a/vendor/golang.org/x/image/webp/decode.go b/vendor/golang.org/x/image/webp/decode.go new file mode 100644 index 0000000..15dc0ee --- /dev/null +++ b/vendor/golang.org/x/image/webp/decode.go @@ -0,0 +1,282 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package webp + +import ( + "bytes" + "errors" + "image" + "image/color" + "io" + + "golang.org/x/image/riff" + "golang.org/x/image/vp8" + "golang.org/x/image/vp8l" +) + +var errInvalidFormat = errors.New("webp: invalid format") + +var ( + fccALPH = riff.FourCC{'A', 'L', 'P', 'H'} + fccVP8 = riff.FourCC{'V', 'P', '8', ' '} + fccVP8L = riff.FourCC{'V', 'P', '8', 'L'} + fccVP8X = riff.FourCC{'V', 'P', '8', 'X'} + fccWEBP = riff.FourCC{'W', 'E', 'B', 'P'} +) + +func decode(r io.Reader, configOnly bool) (image.Image, image.Config, error) { + formType, riffReader, err := riff.NewReader(r) + if err != nil { + return nil, image.Config{}, err + } + if formType != fccWEBP { + return nil, image.Config{}, errInvalidFormat + } + + var ( + alpha []byte + alphaStride int + wantAlpha bool + seenVP8X bool + widthMinusOne uint32 + heightMinusOne uint32 + buf [10]byte + ) + for { + chunkID, chunkLen, chunkData, err := riffReader.Next() + if err == io.EOF { + err = errInvalidFormat + } + if err != nil { + return nil, image.Config{}, err + } + + switch chunkID { + case fccALPH: + if !wantAlpha { + return nil, image.Config{}, errInvalidFormat + } + wantAlpha = false + // Read the Pre-processing | Filter | Compression byte. + if _, err := io.ReadFull(chunkData, buf[:1]); err != nil { + if err == io.EOF { + err = errInvalidFormat + } + return nil, image.Config{}, err + } + alpha, alphaStride, err = readAlpha(chunkData, widthMinusOne, heightMinusOne, buf[0]&0x03) + if err != nil { + return nil, image.Config{}, err + } + unfilterAlpha(alpha, alphaStride, (buf[0]>>2)&0x03) + + case fccVP8: + if wantAlpha || int32(chunkLen) < 0 { + return nil, image.Config{}, errInvalidFormat + } + d := vp8.NewDecoder() + d.Init(chunkData, int(chunkLen)) + fh, err := d.DecodeFrameHeader() + if err != nil { + return nil, image.Config{}, err + } + if configOnly { + return nil, image.Config{ + ColorModel: color.YCbCrModel, + Width: fh.Width, + Height: fh.Height, + }, nil + } + m, err := d.DecodeFrame() + if err != nil { + return nil, image.Config{}, err + } + if alpha != nil { + return &image.NYCbCrA{ + YCbCr: *m, + A: alpha, + AStride: alphaStride, + }, image.Config{}, nil + } + return m, image.Config{}, nil + + case fccVP8L: + if alpha != nil { + return nil, image.Config{}, errInvalidFormat + } + if configOnly { + c, err := vp8l.DecodeConfig(chunkData) + return nil, c, err + } + m, err := vp8l.Decode(chunkData) + return m, image.Config{}, err + + case fccVP8X: + if seenVP8X { + return nil, image.Config{}, errInvalidFormat + } + seenVP8X = true + if chunkLen != 10 { + return nil, image.Config{}, errInvalidFormat + } + if _, err := io.ReadFull(chunkData, buf[:10]); err != nil { + return nil, image.Config{}, err + } + const ( + animationBit = 1 << 1 + xmpMetadataBit = 1 << 2 + exifMetadataBit = 1 << 3 + alphaBit = 1 << 4 + iccProfileBit = 1 << 5 + ) + wantAlpha = (buf[0] & alphaBit) != 0 + widthMinusOne = uint32(buf[4]) | uint32(buf[5])<<8 | uint32(buf[6])<<16 + heightMinusOne = uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16 + if uint64(widthMinusOne+1)*uint64(heightMinusOne+1) > 1<<32-1 { + // The product of _Canvas Width_ and _Canvas Height_ MUST be + // at most 2^32 - 1. + // https://www.rfc-editor.org/rfc/rfc9649.html#section-2.7-12 + return nil, image.Config{}, errInvalidFormat + } + if configOnly { + if wantAlpha { + return nil, image.Config{ + ColorModel: color.NYCbCrAModel, + Width: int(widthMinusOne) + 1, + Height: int(heightMinusOne) + 1, + }, nil + } + return nil, image.Config{ + ColorModel: color.YCbCrModel, + Width: int(widthMinusOne) + 1, + Height: int(heightMinusOne) + 1, + }, nil + } + } + } +} + +func readAlpha(chunkData io.Reader, widthMinusOne, heightMinusOne uint32, compression byte) ( + alpha []byte, alphaStride int, err error) { + + switch compression { + case 0: + w := int(widthMinusOne) + 1 + h := int(heightMinusOne) + 1 + alpha = make([]byte, w*h) + if _, err := io.ReadFull(chunkData, alpha); err != nil { + return nil, 0, err + } + return alpha, w, nil + + case 1: + // Read the VP8L-compressed alpha values. First, synthesize a 5-byte VP8L header: + // a 1-byte magic number, a 14-bit widthMinusOne, a 14-bit heightMinusOne, + // a 1-bit (ignored, zero) alphaIsUsed and a 3-bit (zero) version. + // TODO(nigeltao): be more efficient than decoding an *image.NRGBA just to + // extract the green values to a separately allocated []byte. Fixing this + // will require changes to the vp8l package's API. + if widthMinusOne > 0x3fff || heightMinusOne > 0x3fff { + return nil, 0, errors.New("webp: invalid format") + } + alphaImage, err := vp8l.Decode(io.MultiReader( + bytes.NewReader([]byte{ + 0x2f, // VP8L magic number. + uint8(widthMinusOne), + uint8(widthMinusOne>>8) | uint8(heightMinusOne<<6), + uint8(heightMinusOne >> 2), + uint8(heightMinusOne >> 10), + }), + chunkData, + )) + if err != nil { + return nil, 0, err + } + // The green values of the inner NRGBA image are the alpha values of the + // outer NYCbCrA image. + pix := alphaImage.(*image.NRGBA).Pix + alpha = make([]byte, len(pix)/4) + for i := range alpha { + alpha[i] = pix[4*i+1] + } + return alpha, int(widthMinusOne) + 1, nil + } + return nil, 0, errInvalidFormat +} + +func unfilterAlpha(alpha []byte, alphaStride int, filter byte) { + if len(alpha) == 0 || alphaStride == 0 { + return + } + switch filter { + case 1: // Horizontal filter. + for i := 1; i < alphaStride; i++ { + alpha[i] += alpha[i-1] + } + for i := alphaStride; i < len(alpha); i += alphaStride { + // The first column is equivalent to the vertical filter. + alpha[i] += alpha[i-alphaStride] + + for j := 1; j < alphaStride; j++ { + alpha[i+j] += alpha[i+j-1] + } + } + + case 2: // Vertical filter. + // The first row is equivalent to the horizontal filter. + for i := 1; i < alphaStride; i++ { + alpha[i] += alpha[i-1] + } + + for i := alphaStride; i < len(alpha); i++ { + alpha[i] += alpha[i-alphaStride] + } + + case 3: // Gradient filter. + // The first row is equivalent to the horizontal filter. + for i := 1; i < alphaStride; i++ { + alpha[i] += alpha[i-1] + } + + for i := alphaStride; i < len(alpha); i += alphaStride { + // The first column is equivalent to the vertical filter. + alpha[i] += alpha[i-alphaStride] + + // The interior is predicted on the three top/left pixels. + for j := 1; j < alphaStride; j++ { + c := int(alpha[i+j-alphaStride-1]) + b := int(alpha[i+j-alphaStride]) + a := int(alpha[i+j-1]) + x := a + b - c + if x < 0 { + x = 0 + } else if x > 255 { + x = 255 + } + alpha[i+j] += uint8(x) + } + } + } +} + +// Decode reads a WEBP image from r and returns it as an image.Image. +func Decode(r io.Reader) (image.Image, error) { + m, _, err := decode(r, false) + if err != nil { + return nil, err + } + return m, nil +} + +// DecodeConfig returns the color model and dimensions of a WEBP image without +// decoding the entire image. +func DecodeConfig(r io.Reader) (image.Config, error) { + _, c, err := decode(r, true) + return c, err +} + +func init() { + image.RegisterFormat("webp", "RIFF????WEBPVP8", Decode, DecodeConfig) +} diff --git a/vendor/golang.org/x/image/webp/doc.go b/vendor/golang.org/x/image/webp/doc.go new file mode 100644 index 0000000..e321c85 --- /dev/null +++ b/vendor/golang.org/x/image/webp/doc.go @@ -0,0 +1,9 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package webp implements a decoder for WEBP images. +// +// WEBP is defined at: +// https://developers.google.com/speed/webp/docs/riff_container +package webp // import "golang.org/x/image/webp" diff --git a/vendor/modules.txt b/vendor/modules.txt index f0061b2..de7dafa 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -45,6 +45,9 @@ github.com/dlclark/regexp2/syntax # github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f ## explicit; go 1.16 github.com/erikgeiser/coninput +# github.com/kevinburke/ssh_config v1.6.0 +## explicit; go 1.18 +github.com/kevinburke/ssh_config # github.com/kr/fs v0.1.0 ## explicit github.com/kr/fs @@ -99,6 +102,14 @@ golang.org/x/crypto/ssh golang.org/x/crypto/ssh/agent golang.org/x/crypto/ssh/internal/bcrypt_pbkdf golang.org/x/crypto/ssh/knownhosts +# golang.org/x/image v0.39.0 +## explicit; go 1.25.0 +golang.org/x/image/draw +golang.org/x/image/math/f64 +golang.org/x/image/riff +golang.org/x/image/vp8 +golang.org/x/image/vp8l +golang.org/x/image/webp # golang.org/x/sys v0.43.0 ## explicit; go 1.25.0 golang.org/x/sys/cpu