diff --git a/.env.example b/.env.example deleted file mode 100644 index 5ddc1037..00000000 --- a/.env.example +++ /dev/null @@ -1,16 +0,0 @@ - -# macOS only -# TAURI_DEV_HOST="0.0.0.0" # needed on macOS -APPLE_SIGNING_IDENTITY= -APPLE_ID= -APPLE_PASSWORD= -APPLE_TEAM_ID= - -# Windows only -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= -AZURE_TENANT_ID= - -# Updates -TAURI_SIGNING_PRIVATE_KEY= -TAURI_SIGNING_PRIVATE_KEY_PASSWORD= \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..cd09ade8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# Every text file is checked out with LF line endings, on Windows too. The generated bindings +# and the catalogs are compared with freshly generated ones (build/check.sh), and a checkout +# with CRLF would make every file differ. +* text=auto eol=lf diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 00000000..cabecbc2 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,7 @@ +# actionlint's settings (build/check.sh api runs it). +self-hosted-runner: + # GitHub hosts these runners, but actionlint 1.7.12 doesn't know their labels yet, and would + # report them as unknown. + labels: + - ubuntu-26.04 + - ubuntu-26.04-arm diff --git a/.github/rclone-1.png b/.github/rclone-1.png deleted file mode 100644 index a4d33b4b..00000000 Binary files a/.github/rclone-1.png and /dev/null differ diff --git a/.github/rclone-2.png b/.github/rclone-2.png deleted file mode 100644 index 6a5744c0..00000000 Binary files a/.github/rclone-2.png and /dev/null differ diff --git a/.github/rclone-mobile.png b/.github/rclone-mobile.png deleted file mode 100644 index f9621166..00000000 Binary files a/.github/rclone-mobile.png and /dev/null differ diff --git a/.github/rclone-video.png b/.github/rclone-video.png deleted file mode 100644 index 62a57028..00000000 Binary files a/.github/rclone-video.png and /dev/null differ diff --git a/.github/showcase.png b/.github/showcase.png new file mode 100644 index 00000000..577bd925 Binary files /dev/null and b/.github/showcase.png differ diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..a29c9d13 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,280 @@ +name: build + +# Builds and packages the six targets. The ci workflow and the release workflows both call it, so +# what ci checks is what a release publishes. +# +# With release set, the packages are signed (each OS gets only its own secrets), one failed target +# stops the rest, and the artifacts are named dist--, which the release workflows +# read. Without it, the packages are unsigned and the artifacts are named rcui--. +# +# With a version, the build and its packages take that version in place of package.json's +# (release-beta uses it for its numbered betas). +on: + workflow_call: + inputs: + release: + description: sign the packages, with the caller's secrets (secrets inherit) + type: boolean + default: false + version: + description: the version to build, in place of package.json's + type: string + default: '' + +permissions: + contents: read + +jobs: + build: + name: Build (${{ matrix.goos }}/${{ matrix.goarch }}) + strategy: + fail-fast: ${{ inputs.release }} + matrix: + include: + # macOS 15 on Apple silicon, which also builds the Intel app. GitHub retired its macOS 14 + # runners on November 2, 2026. + - { runner: macos-15, goos: darwin, goarch: arm64 } + - { runner: macos-15, goos: darwin, goarch: amd64 } + - { runner: windows-latest, goos: windows, goarch: amd64 } + - { runner: windows-11-arm, goos: windows, goarch: arm64 } + # Linux builds in Debian 13, the oldest Linux that the app supports. A binary needs the + # glibc and the GTK it was built against, or newer, so this one also runs on Ubuntu + # 26.04 and the rest. GitHub has no Debian runners, so it runs in a container. + - { runner: ubuntu-24.04, container: 'debian:13', goos: linux, goarch: amd64 } + - { runner: ubuntu-24.04-arm, container: 'debian:13', goos: linux, goarch: arm64 } + runs-on: ${{ matrix.runner }} + # Empty for macOS and Windows, which build on the runner itself. + container: ${{ matrix.container }} + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + # build.sh and package.sh read it. Empty, they take package.json's version. + APP_VERSION: ${{ inputs.version }} + steps: + - name: Linux build and packaging dependencies + # The container is a bare Debian, so this step comes first. It installs git for the + # checkout, a C compiler and pkg-config for cgo, GTK 4 and WebKitGTK 6.0 (Wails' default + # stack), gtk4-layer-shell, which rcui links, and the tools that packaging uses. Nothing + # mounts the AppImage, so FUSE isn't needed. + if: runner.os == 'Linux' + run: | + apt-get update + apt-get install -y --no-install-recommends git ca-certificates curl xz-utils file \ + build-essential pkg-config libgtk-4-dev libwebkitgtk-6.0-dev libgtk4-layer-shell-dev + + - uses: actions/checkout@v5 + with: + persist-credentials: false + - name: Let git read the checkout + # The container runs as root and the checkout belongs to the runner's user, so git + # refuses the repository, and go build fails when it stamps the binary with the commit. + # The checkout action only trusts the folder while it runs. + if: runner.os == 'Linux' + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/setup-node@v5 + with: + node-version: '24' + cache: npm + - run: npm ci + + - name: Apple certificate + if: inputs.release && matrix.goos == 'darwin' + shell: bash + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + run: | + echo "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12 + security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain + security default-keychain -s build.keychain + security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain + security set-keychain-settings -t 3600 -u build.keychain + security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign + security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" build.keychain + rm certificate.p12 + # The valid identities only: an expired certificate, or one of another type, has none. + identities=$(security find-identity -v -p codesigning build.keychain) + id=$(awk -F'"' '/Developer ID Application/ {print $2; exit}' <<<"$identities") + if [ -z "$id" ]; then + echo "$identities" + echo "::error::APPLE_CERTIFICATE has no valid Developer ID Application identity" + exit 1 + fi + echo "APPLE_SIGNING_IDENTITY=$id" >> "$GITHUB_ENV" + + # The Windows signing tool, at a fixed version and its own lock file. Rust first: the Arm + # runner may have none. + - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable + if: inputs.release && matrix.goos == 'windows' + - name: Windows signing tool + if: inputs.release && matrix.goos == 'windows' + run: cargo install trusted-signing-cli --version 0.11.0 --locked + + - name: NSIS + # NSIS's strlen_8192 build, so that the uninstaller can take \bin off a PATH + # longer than 1024 characters (project.nsi). It goes first on PATH on both runners, + # because windows-latest's own makensis is the standard build, and windows-11-arm may + # have none. NSIS is an x86 program, which Windows on Arm runs emulated. The strlen_8192 + # zip holds only makensis and the stubs, so it is extracted over NSIS's standard zip, + # which has the rest. + if: runner.os == 'Windows' + shell: pwsh + env: + NSIS_VERSION: '3.12' + NSIS_SHA256: 56581f90db321581c5381193d796fffcf2d24b2f8fed2160a6c6a3baa67f2c4f + NSIS_STRLEN_8192_SHA256: 44ebb4bfd5b763e295855718dbcf374fc396d03870ea038a0844abcbe1ff0c3a + run: | + function Get-Pinned($name, $sha256) { + $zip = Join-Path $env:RUNNER_TEMP $name + curl.exe -fsSL -o $zip "https://downloads.sourceforge.net/project/nsis/NSIS%203/$env:NSIS_VERSION/$name" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $sum = (Get-FileHash -Algorithm SHA256 $zip).Hash + if ($sum -ne $sha256) { throw "$name has sha256 $sum, not $sha256" } + $zip + } + $nsis = Join-Path $env:RUNNER_TEMP "nsis-$env:NSIS_VERSION" + Expand-Archive (Get-Pinned "nsis-$env:NSIS_VERSION.zip" $env:NSIS_SHA256) -DestinationPath $env:RUNNER_TEMP + Expand-Archive (Get-Pinned "nsis-$env:NSIS_VERSION-strlen_8192.zip" $env:NSIS_STRLEN_8192_SHA256) -DestinationPath $nsis -Force + Add-Content $env:GITHUB_PATH $nsis + + - name: Build + shell: bash + env: + # A repository variable, not a secret, because the key can only add events. + POSTHOG_KEY: ${{ vars.POSTHOG_KEY }} + run: build/build.sh + - name: gtk4-layer-shell loads before libwayland-client + # gtk4-layer-shell replaces some of libwayland-client's functions with its own, and that + # only works when the dynamic linker loads it before libwayland-client. The linker loads + # the libraries that rcui names (NEEDED) in their order, and only then the libraries that + # those need. So rcui must name gtk4-layer-shell, and must not name libwayland-client + # before it. + if: runner.os == 'Linux' + # bash, because the container's default shell is sh, which has no <( ). + shell: bash + run: | + layer=0 wayland=0 i=0 + while read -r lib; do + i=$((i + 1)) + echo "$i $lib" + case $lib in + libgtk4-layer-shell.so.0) layer=$i ;; + libwayland-client.so.0) wayland=$i ;; + esac + done < <(readelf -d "build/bin/$GOOS-$GOARCH/rcui" | sed -n 's/.*(NEEDED).*\[\(.*\)\]$/\1/p') + if [ "$layer" = 0 ]; then + echo "::error::rcui doesn't link libgtk4-layer-shell.so.0" + exit 1 + fi + if [ "$wayland" != 0 ] && [ "$wayland" -lt "$layer" ]; then + echo "::error::rcui names libwayland-client.so.0 before libgtk4-layer-shell.so.0" + exit 1 + fi + - name: Vet + # After the build, because go vet embeds the pages that the build made. + shell: bash + run: build/build.sh --vet + + - name: Roles answer + # Runs the binary where the runner's CPU can run it, and checks that it has our update + # command and not rclone's selfupdate. + if: matrix.goarch == 'amd64' && runner.arch == 'X64' || matrix.goarch == 'arm64' && runner.arch == 'ARM64' + shell: bash + run: | + exe=build/bin/$GOOS-$GOARCH/rcui + [ "$GOOS" = windows ] && exe+=.exe + # expect PATTERN ARG... runs the binary with ARG... and fails unless a line of its output + # matches PATTERN. It reads the whole output before it greps, because grep -q exits at + # its first match, and a pipe that was still writing to it would fail under pipefail. + expect() { + local out + out=$("$exe" "${@:2}") + echo "$out" + grep -q "$1" <<<"$out" || { echo "::error::rcui ${*:2}: no line matches $1"; return 1; } + } + expect 'go/tags:.*noselfupdate' version + # build.sh sets the version through -ldflags -X, which Go ignores when the path is wrong. + expect "^yours: *Rclone UI [0-9]" update --check + # The production feed answers in a format this build reads, or isn't there yet (before + # the first stable release). A failed check prints no latest: line. + expect "^latest: " update --check + expect "Rclone UI" update --help + + - name: Package + # Signed in a release only. Each OS gets its own secrets and no other's: secrets can't + # appear in an if, so each is empty unless the release builds for its OS. + shell: bash + env: + # A release fails without its macOS secrets rather than sign ad hoc (package.sh). + APP_RELEASE_CHECK: ${{ inputs.release && '1' || '' }} + APPLE_ID: ${{ inputs.release && matrix.goos == 'darwin' && secrets.APPLE_ID || '' }} + APPLE_PASSWORD: ${{ inputs.release && matrix.goos == 'darwin' && secrets.APPLE_ID_PASSWORD || '' }} + APPLE_TEAM_ID: ${{ inputs.release && matrix.goos == 'darwin' && secrets.APPLE_TEAM_ID || '' }} + AZURE_CLIENT_ID: ${{ inputs.release && matrix.goos == 'windows' && secrets.AZURE_CLIENT_ID || '' }} + AZURE_CLIENT_SECRET: ${{ inputs.release && matrix.goos == 'windows' && secrets.AZURE_CLIENT_SECRET || '' }} + AZURE_TENANT_ID: ${{ inputs.release && matrix.goos == 'windows' && secrets.AZURE_TENANT_ID || '' }} + # Azure Trusted Signing, with the release's account and certificate profile. + SIGN_COMMAND: ${{ inputs.release && matrix.goos == 'windows' && 'trusted-signing-cli -e https://eus.codesigning.azure.net -a sign-1 -c Sign1 -d Rclone %1' || '' }} + APPIMAGE_EXTRACT_AND_RUN: 1 + run: build/package.sh + + - name: Portable zip answers + # Checks the portable zip. It must unpack to one folder that has the empty data folder, + # which makes the copy portable. rclone runs first, before anything else has made + # rclone.conf, and it must use the rclone.conf in the copy's folder and create it. Then + # update --check must say that the copy is portable. Windows' own tar (bsdtar) unpacks the + # zip. + if: runner.os == 'Windows' && (matrix.goarch == 'amd64' && runner.arch == 'X64' || matrix.goarch == 'arm64' && runner.arch == 'ARM64') + shell: bash + run: | + arch=x64 + [ "$GOARCH" = arm64 ] && arch=arm64 + zips=(build/dist/Rclone-UI-*-windows-"$arch"-portable.zip) + dir=$(cygpath -u "$RUNNER_TEMP")/portable + rm -rf "$dir" + mkdir -p "$dir" + "$(cygpath -S)/tar.exe" -xf "${zips[0]}" -C "$dir" + root="$dir/Rclone UI" + for f in rcui.exe bin/rclone.exe winfsp.msi README.txt LICENSE.txt THIRD_PARTY_NOTICES.txt; do + [ -f "$root/$f" ] || { echo "::error::the portable zip has no $f"; exit 1; } + done + [ -d "$root/data" ] || { echo "::error::the portable zip has no data folder"; exit 1; } + [ ! -e "$root/rclone.conf" ] || { echo "::error::the portable zip has an rclone.conf"; exit 1; } + out=$("$root/bin/rclone.exe" config file) + echo "$out" + got=$(tail -n 1 <<<"$out") + want=$(cygpath -w "$root/rclone.conf") + [ "$got" = "$want" ] || { echo "::error::the portable rclone uses $got, not $want"; exit 1; } + [ -f "$root/rclone.conf" ] || { echo "::error::the first run didn't create rclone.conf"; exit 1; } + out=$("$root/rcui.exe" update --check) + echo "$out" + grep -q '^yours: .*(portable)$' <<<"$out" || { echo "::error::update --check doesn't say the copy is portable"; exit 1; } + + - name: Authenticode signatures + # What a release ships signed: the installer (signed inside makensis), and the binaries + # package.sh signed before it. + if: inputs.release && runner.os == 'Windows' + shell: pwsh + run: | + $bin = "build/bin/$env:GOOS-$env:GOARCH" + $arch = if ($env:GOARCH -eq 'arm64') { 'arm64' } else { 'x64' } + $setup = (Get-ChildItem "build/dist/Rclone-UI-*-windows-$arch-setup.exe").FullName + foreach ($f in $setup, "$bin/rcui.exe", "$bin/bin/rclone.exe") { + $sig = Get-AuthenticodeSignature $f + if ($sig.Status -ne 'Valid') { throw "${f}: $($sig.Status): $($sig.StatusMessage)" } + "${f}: $($sig.SignerCertificate.Subject)" + } + + - name: AppImage answers + if: runner.os == 'Linux' + run: build/linux/check-appimage.sh build/dist/Rclone-UI-*.AppImage + + - uses: actions/upload-artifact@v4 + with: + name: ${{ inputs.release && 'dist' || 'rcui' }}-${{ matrix.goos }}-${{ matrix.goarch }} + path: build/dist/ + retention-days: 7 diff --git a/.github/workflows/ci-cloud.yml b/.github/workflows/ci-cloud.yml deleted file mode 100644 index 11801029..00000000 --- a/.github/workflows/ci-cloud.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: ci-cloud - -# Tests the cloud branch, and only the cloud branch: pull requests into it, and cloud itself on -# request. It runs the frontend's unit tests and build, the Rust build and tests, and the -# end-to-end suite. Pull requests from this repository run automatically; a fork's is run by hand -# once reviewed ("Run workflow" with refs/pull//merge). A run can only read the -# repository, and only cloud's own code saves to the cache. -on: - pull_request_target: - branches: [cloud] - workflow_dispatch: - inputs: - ref: - description: 'What to test: cloud, another branch, or refs/pull//merge' - required: true - default: cloud - -permissions: - contents: read - -jobs: - build: - if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest - container: rust:1-bookworm - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ inputs.ref || format('refs/pull/{0}/merge', github.event.pull_request.number) }} - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: npm --prefix frontend ci - - run: npm --prefix frontend run test:unit - - run: npm --prefix frontend run build - - uses: Swatinem/rust-cache@v2 - with: - workspaces: '. -> target' - save-if: ${{ github.event_name == 'workflow_dispatch' && inputs.ref == 'cloud' }} - - run: cargo build --release - - run: cargo test - - uses: actions/upload-artifact@v4 - with: - name: rclone-cloud-linux-x86_64-ci - path: target/release/rclone-cloud - - e2e: - if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ inputs.ref || format('refs/pull/{0}/merge', github.event.pull_request.number) }} - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: npm --prefix frontend ci - - run: npm --prefix frontend run build - - uses: Swatinem/rust-cache@v2 - with: - workspaces: '. -> target' - save-if: ${{ github.event_name == 'workflow_dispatch' && inputs.ref == 'cloud' }} - - run: cargo build - - name: Install rclone - run: curl -fsSL https://rclone.org/install.sh | sudo bash - - run: npx playwright install --with-deps chromium - - run: npm --prefix frontend run test:e2e - - uses: actions/upload-artifact@v4 - if: failure() - with: - name: playwright-report - path: frontend/test-results diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..34ba767b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,119 @@ +name: ci + +# Every push and pull request on main is tested on the three OSes and built for all six targets. +on: + push: + branches: [main] + pull_request: + branches: [main] + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + api: + name: API and generated code + # macOS 15 on Apple silicon. GitHub retired its macOS 14 runners on November 2, 2026. + runs-on: macos-15 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/setup-node@v5 + with: + node-version: '24' + cache: npm + - run: npm ci + - name: actionlint, tidy modules, notices, generated code + run: build/check.sh api + + frontend: + name: Frontend + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-node@v5 + with: + node-version: '24' + cache: npm + - run: npm ci + - name: tsc, biome, vitest + run: build/check.sh frontend + + test: + name: Go tests (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + # Ubuntu 26.04, because older Ubuntu releases don't package gtk4-layer-shell. + os: [ubuntu-26.04, macos-15, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - name: Linux build dependencies + # GTK 4 and WebKitGTK 6.0, which is Wails' default stack, and gtk4-layer-shell, which rcui + # links. The 26.04 runners have started without working name lookups ("Temporary failure + # resolving archive.ubuntu.com"), and once hung here for 25 minutes. So the step waits for + # a lookup to answer, tries three times, and gives up after 10 minutes. + if: runner.os == 'Linux' + timeout-minutes: 10 + run: | + for _ in $(seq 1 30); do getent hosts archive.ubuntu.com >/dev/null && break; sleep 2; done + for try in 1 2 3; do + if sudo apt-get update && sudo apt-get install -y libgtk-4-dev libwebkitgtk-6.0-dev libgtk4-layer-shell-dev; then + exit 0 + fi + echo "::warning::installing the build dependencies failed (try $try of 3)" + sleep 20 + done + exit 1 + - name: go vet + run: go vet ./... + - name: go test + run: go test -race ./... + + build: + name: Build + # The release's build and packaging, unsigned (build.yml). + uses: ./.github/workflows/build.yml + with: + release: false + + mounts-linux: + # Runs the mount tests that the test job skips, with RCUI_TEST_MOUNTS=1. They need fuse3 + # (rclone's FUSE mount calls fusermount3) and a usable /dev/fuse. + name: Mounts (Linux FUSE) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - name: FUSE + run: | + sudo apt-get update + sudo apt-get install -y fuse3 + test -c /dev/fuse + if [ ! -r /dev/fuse ] || [ ! -w /dev/fuse ]; then sudo chmod 0666 /dev/fuse; fi + ls -l /dev/fuse "$(command -v fusermount3)" + - name: Real mounts + env: + RCUI_TEST_MOUNTS: 1 + run: go test -race -v ./core/mounts/ diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml index 12efe080..e989fe96 100644 --- a/.github/workflows/release-beta.yml +++ b/.github/workflows/release-beta.yml @@ -1,8 +1,180 @@ name: release-beta + +# Releases the commit it runs on as the next beta of package.json's version (4.0.0-beta.1, then +# 4.0.0-beta.2). The app, the file names (Rclone-UI-4.0.0-beta.1-*), the release's title and its +# tag (v4.0.0-beta.1) all carry that version. +# +# It works like the release workflow, but it publishes the release at once as a pre-release, so +# there is no draft to publish by hand. Publishing is all it takes to offer the beta: +# - The beta channel looks up GitHub's newest pre-release with such a tag, and reads the feed +# that the release carries (app/update's newestBeta). So the newest beta is the one offered, +# and deleting a beta's release takes the channel back to the one before it. +# - The stable channel never sees it. That channel reads the feed of GitHub's latest release, +# and a pre-release is never the latest. +# +# package.json holds the version that the betas lead to, and this workflow numbers them: one more +# than the highest beta of that version that has a tag. The tag is made on GitHub as the release +# is published, so a failed run leaves none, and the next run takes the same number. A beta +# counts as older than the release of its version, so a version that is released can have no more +# betas: name the next version in package.json first. +# +# A dry run does all of it but the tag and the release: its files are the run's +# release-beta-dry-run artifact. on: workflow_dispatch: + inputs: + dry-run: + description: build and write the feed, but make no tag or release + required: false + default: false + type: boolean + +permissions: + contents: read + +# One run at a time, so that two runs never take the same number. +concurrency: + group: release-beta + cancel-in-progress: false + jobs: - note: + # Decides the version once, so that every job builds the same one. Before anything is built, it + # refuses a version that can't have a beta, and a beta whose release exists already (a draft + # that was left behind), which would make gh release create fail after every build. A dry run + # only warns. + prepare: + name: The beta's version runs-on: ubuntu-24.04 + permissions: + # The API lists draft releases only to a token that can write. + contents: write + outputs: + version: ${{ steps.version.outputs.version }} steps: - - run: echo "Start this workflow from the go-time branch." && exit 1 + - uses: actions/checkout@v5 + with: + persist-credentials: false + - name: The version, its tag and its release + id: version + env: + GH_TOKEN: ${{ github.token }} + DRY_RUN: ${{ inputs.dry-run }} + run: | + refuse() { if [ "$DRY_RUN" = true ]; then echo "::warning::$1"; else echo "::error::$1"; exit 1; fi; } + # package.json's version, without a pre-release part of its own. + base=$(node -p "require('./package.json').version"); base="${base%%[-+]*}" + if ! grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' <<<"$base"; then + echo "::error::package.json's version ($base) isn't three numbers" + exit 1 + fi + gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/v$base" >/dev/null 2>&1 && + refuse "v$base is released already, and a beta of it would be older than it: name the next version in package.json" + # One more than the highest beta of this version, by its tags. The list is assigned to a + # variable so that a failed listing fails the step, and isn't read as "no beta yet". + refs=$(gh api --paginate "repos/$GITHUB_REPOSITORY/git/matching-refs/tags/v$base-beta." --jq '.[].ref') + last=$(sed -n "s|^refs/tags/v${base//./\\.}-beta\.\([0-9][0-9]*\)$|\1|p" <<<"$refs" | sort -n | tail -n 1) + version="$base-beta.$((10#${last:-0} + 1))"; tag="v$version" + # Every page, so an old forgotten draft is seen too. + releases=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" --jq ".[] | select(.tag_name == \"$tag\") | .id") + [ -z "$releases" ] || + refuse "a release for $tag exists already (an unpublished draft?): delete it" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "ready to release $tag" + + build: + name: Build + needs: prepare + # Each target built, signed and packaged (build.yml) under the beta's version, as + # dist--. + uses: ./.github/workflows/build.yml + with: + release: true + version: ${{ needs.prepare.outputs.version }} + secrets: inherit + + vendor: + name: Vendored sources (Flatpak) + needs: prepare + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/setup-node@v5 + with: + node-version: '24' + cache: npm + - run: npm ci + - name: The vendored sources and the Flathub manifest + env: + VERSION: ${{ needs.prepare.outputs.version }} + run: | + npm run build + go -C tools run ./zstdassets -src ../dist -dst ../app/assets/dist + go mod vendor + vendor="Rclone-UI-$VERSION-vendor.tar.gz" + mkdir -p out + tar -czf "out/$vendor" vendor app/assets/dist + sed -e "s|@VERSION@|$VERSION|g" \ + -e "s|@COMMIT@|$GITHUB_SHA|g" \ + -e "s|@SHA256@|$(sha256sum "out/$vendor" | cut -d' ' -f1)|g" \ + build/flatpak/org.rclone.ui.yml > out/org.rclone.ui.yml + - uses: actions/upload-artifact@v4 + with: + name: dist-vendor + path: out/* + retention-days: 7 + + release: + name: Create the release + needs: [prepare, build, vendor] + runs-on: ubuntu-24.04 + permissions: + contents: write + env: + VERSION: ${{ needs.prepare.outputs.version }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/download-artifact@v4 + with: + pattern: dist-* + merge-multiple: true + path: dist + + - name: The feed + run: | + # The policy (which running versions must or should update) is build/release/policy.json. + go run ./build/release manifest -version "$VERSION" \ + -base-url "https://github.com/$GITHUB_REPOSITORY/releases/download/v$VERSION" \ + -rclone "$(go list -m -f '{{.Version}}' github.com/rclone/rclone)" \ + -notes "See https://github.com/$GITHUB_REPOSITORY/releases/tag/v$VERSION" dist + # Exactly the files a release publishes: no file under another app's names. + go run ./build/release check -version "$VERSION" dist + + - name: The dry run's files + if: ${{ inputs.dry-run }} + uses: actions/upload-artifact@v4 + with: + name: release-beta-dry-run + path: dist/ + retention-days: 7 + + - name: The pre-release + if: ${{ !inputs.dry-run }} + env: + GH_TOKEN: ${{ github.token }} + run: | + # Published, as a pre-release that is never the latest release: from here on the beta + # channel offers it. The tag goes on the commit built: without --target, gh would make + # it from the default branch's head. + gh release create "v$VERSION" --prerelease --latest=false --title "v$VERSION" \ + --notes "Rclone UI v$VERSION, a beta built from $GITHUB_SHA." \ + --target "$GITHUB_SHA" dist/* diff --git a/.github/workflows/release-cloud-docker.yml b/.github/workflows/release-cloud-docker.yml deleted file mode 100644 index e06c6858..00000000 --- a/.github/workflows/release-cloud-docker.yml +++ /dev/null @@ -1,70 +0,0 @@ -name: release-cloud-docker - -# Publishes the cloud branch's container image, and only the cloud branch's: no git tag and no -# GitHub release. Run it by hand ("Run workflow"): it builds cloud's latest commit and pushes -# ghcr.io//rclone-cloud as its Cargo.toml version, latest, and sha-. A version that -# is already published is refused: bump Cargo.toml on cloud to publish again. -on: - workflow_dispatch: - -permissions: - contents: read - packages: write - -jobs: - image: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: cloud - - name: The commit and its version - id: cloud - run: | - sha="$(git rev-parse HEAD)" - version="$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1)" - if [ -z "$version" ]; then - echo "::error::no version in Cargo.toml at $sha" - exit 1 - fi - echo "Publishing rclone-cloud $version from cloud at $sha" - { - echo "sha=$sha" - echo "short=${sha:0:7}" - echo "version=$version" - } >> "$GITHUB_OUTPUT" - - uses: docker/setup-qemu-action@v3 - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - name: A version already published is refused - env: - IMAGE: ghcr.io/${{ github.repository_owner }}/rclone-cloud:${{ steps.cloud.outputs.version }} - run: | - if docker buildx imagetools inspect "$IMAGE" >/dev/null 2>&1; then - echo "::error::$IMAGE is already published; bump the version in Cargo.toml on cloud" - exit 1 - fi - - uses: docker/metadata-action@v5 - id: meta - with: - images: ghcr.io/${{ github.repository_owner }}/rclone-cloud - tags: | - type=raw,value=${{ steps.cloud.outputs.version }} - type=raw,value=latest - type=raw,value=sha-${{ steps.cloud.outputs.short }} - labels: | - org.opencontainers.image.revision=${{ steps.cloud.outputs.sha }} - org.opencontainers.image.version=${{ steps.cloud.outputs.version }} - - uses: docker/build-push-action@v6 - with: - context: . - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max diff --git a/.github/workflows/release-cloud.yml b/.github/workflows/release-cloud.yml deleted file mode 100644 index 78f13daf..00000000 --- a/.github/workflows/release-cloud.yml +++ /dev/null @@ -1,185 +0,0 @@ -name: release-cloud - -# Releases the cloud branch, and only the cloud branch. Run it by hand ("Run workflow"): it builds -# cloud's latest commit at the version in its Cargo.toml, tags that commit cloud-v, and -# publishes the binaries and the update manifest on a GitHub release. The container image is -# release-cloud-docker's. -on: - workflow_dispatch: - -permissions: - contents: write - -jobs: - # Picks the commit to release, cloud's latest, which every job then builds, and reads its version. - # Creates the release and its tag on that commit. A version that is already released is refused: - # bump Cargo.toml on cloud to release again. - prepare: - runs-on: ubuntu-latest - outputs: - sha: ${{ steps.cloud.outputs.sha }} - short: ${{ steps.cloud.outputs.short }} - version: ${{ steps.cloud.outputs.version }} - tag: ${{ steps.cloud.outputs.tag }} - steps: - - name: The cloud branch and its version - id: cloud - env: - GH_TOKEN: ${{ github.token }} - run: | - sha="$(gh api "repos/$GITHUB_REPOSITORY/commits/cloud" --jq .sha)" - version="$(gh api -H 'Accept: application/vnd.github.raw' \ - "repos/$GITHUB_REPOSITORY/contents/Cargo.toml?ref=$sha" \ - | sed -n 's/^version = "\(.*\)"$/\1/p' | head -1)" - if [ -z "$version" ]; then - echo "::error::no version in Cargo.toml at $sha" - exit 1 - fi - tag="cloud-v$version" - if gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$tag" >/dev/null 2>&1; then - echo "::error::$tag is already released; bump the version in Cargo.toml on cloud" - exit 1 - fi - echo "Releasing $tag from cloud at $sha" - { - echo "sha=$sha" - echo "short=${sha:0:7}" - echo "version=$version" - echo "tag=$tag" - } >> "$GITHUB_OUTPUT" - - name: Create the release and its tag - uses: softprops/action-gh-release@v2 - with: - tag_name: ${{ steps.cloud.outputs.tag }} - target_commitish: ${{ steps.cloud.outputs.sha }} - make_latest: false - - binaries: - needs: prepare - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-24.04 - target: linux-x86_64 - - os: ubuntu-24.04-arm - target: linux-aarch64 - - os: macos-14 - target: macos-aarch64 - # Intel macOS is cross-compiled on the Apple Silicon runner. - - os: macos-14 - target: macos-x86_64 - rust_target: x86_64-apple-darwin - - os: windows-latest - target: windows-x86_64 - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ needs.prepare.outputs.sha }} - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: npm --prefix frontend ci - - run: npm --prefix frontend run build - - uses: Swatinem/rust-cache@v2 - with: - workspaces: '. -> target' - - if: ${{ !matrix.rust_target }} - run: cargo build --release - - name: Cross-compile - if: ${{ matrix.rust_target }} - env: - RUST_TARGET: ${{ matrix.rust_target }} - run: | - rustup target add "$RUST_TARGET" - cargo build --release --target "$RUST_TARGET" - mkdir -p target/release - cp "target/$RUST_TARGET/release/rclone-cloud" target/release/rclone-cloud - - name: Package - shell: bash - run: | - mkdir -p out/cloud - if [ "${{ runner.os }}" = "Windows" ]; then - cp target/release/rclone-cloud.exe out/cloud/rclone-cloud-${{ matrix.target }}.exe - else - cp target/release/rclone-cloud out/cloud/rclone-cloud-${{ matrix.target }} - fi - # Signs each binary with the minisign key in TAURI_SIGNING_PRIVATE_KEY. The server's updater - # (src/updater.rs) checks that signature before it installs an update. Only these binaries - # update themselves: in a container, the Docker image included, updates are off entirely, - # and a new version comes with a new image. - - name: Sign - shell: bash - env: - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} - run: | - for f in out/cloud/rclone-cloud-*; do - npx --yes @tauri-apps/cli@2 signer sign "$f" - done - ls -la out/cloud - - uses: actions/upload-artifact@v4 - with: - name: rclone-cloud-${{ matrix.target }} - path: out/cloud/* - # Attached to this version's release. The repository's Latest stays the desktop app's, which - # its updater reads from `releases/latest/download/latest.json`. - - name: Attach to the release - uses: softprops/action-gh-release@v2 - with: - tag_name: ${{ needs.prepare.outputs.tag }} - files: out/cloud/* - make_latest: false - - # Writes `cloud-latest.json`, which a running rclone-cloud reads to update itself: one entry per - # platform (`cloud--`) with the binary's URL and signature. It goes on this version's - # release and on the rolling `cloud-latest` release, whose URL never changes. A server in a - # container, the Docker image included, never reads it: updates are off there entirely. - manifest: - needs: [prepare, binaries] - runs-on: ubuntu-latest - steps: - - uses: actions/download-artifact@v4 - with: - pattern: rclone-cloud-* - path: artifacts - merge-multiple: true - - name: Write cloud-latest.json - shell: bash - env: - tag: ${{ needs.prepare.outputs.tag }} - version: ${{ needs.prepare.outputs.version }} - run: | - base="https://github.com/${GITHUB_REPOSITORY}/releases/download/${tag}" - platforms="{}" - for sig in artifacts/*.sig; do - bin="${sig%.sig}" - name="$(basename "$bin")" - key="${name#rclone-cloud-}" - key="cloud-${key%.exe}" - platforms="$(jq --arg k "$key" --arg u "${base}/${name}" --arg s "$(cat "$sig")" \ - '.[$k] = {url: $u, signature: $s}' <<<"$platforms")" - done - jq -n --arg v "$version" --arg d "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --argjson p "$platforms" \ - '{version: $v, notes: "See the release notes on GitHub.", pub_date: $d, platforms: $p}' \ - > cloud-latest.json - cat cloud-latest.json - - name: Keep it with the version - uses: softprops/action-gh-release@v2 - with: - tag_name: ${{ needs.prepare.outputs.tag }} - files: cloud-latest.json - make_latest: false - - name: Point the rolling release at it - uses: softprops/action-gh-release@v2 - with: - tag_name: cloud-latest - target_commitish: ${{ needs.prepare.outputs.sha }} - name: Rclone Cloud update pointer - body: | - Not a version. `cloud-latest.json` is what a running rclone-cloud reads to find its - newest release; the binaries are on the `cloud-v*` releases. - files: cloud-latest.json - make_latest: false - diff --git a/.github/workflows/release-native-winget.yml b/.github/workflows/release-native-winget.yml deleted file mode 100644 index 7af81286..00000000 --- a/.github/workflows/release-native-winget.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: release-native-winget - -on: - workflow_dispatch: - inputs: - version: - description: 'Release version without leading v, e.g. 3.5.4' - required: true - type: string - -permissions: - contents: read - -jobs: - publish: - runs-on: windows-latest - - steps: - - uses: vedantmgoyal9/winget-releaser@v2 - with: - identifier: RcloneUI.RcloneUI - version: ${{ inputs.version }} - release-tag: v${{ inputs.version }} - installers-regex: '^Rclone\.UI_(x64|arm64)\.exe$' - token: ${{ secrets.WINGET_ACC_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/release-native.yml b/.github/workflows/release-native.yml deleted file mode 100644 index c8c3db54..00000000 --- a/.github/workflows/release-native.yml +++ /dev/null @@ -1,192 +0,0 @@ -name: 'release-native' - -on: - workflow_dispatch - -jobs: - release-tauri: - permissions: - contents: write - strategy: - fail-fast: false - matrix: - include: - - platform: 'macos-latest' - args: '--target aarch64-apple-darwin' - arch: 'silicon' - type: 'aarch64' - assetPattern: '[name]_[arch][ext]' - - platform: 'macos-latest' - args: '--target x86_64-apple-darwin' - arch: 'silicon' - type: 'x86_64' - assetPattern: '[name]_[arch][ext]' - - platform: 'ubuntu-22.04' - args: '' - assetPattern: '[name]_[arch][ext]' - - platform: 'ubuntu-24.04' - args: "--config '{\"bundle\":{\"createUpdaterArtifacts\":false}}'" - assetPattern: '[name]_[arch]_ALTERNATE[ext]' - - platform: 'ubuntu-22.04-arm' - args: '' - assetPattern: '[name]_[arch][ext]' - - platform: 'windows-11-arm' - args: '--target x86_64-pc-windows-msvc' - arch: 'arm64' - type: 'x86_64' - assetPattern: '[name]_[arch][ext]' - - platform: "windows-11-arm" - args: "--target aarch64-pc-windows-msvc" - arch: 'arm64' - type: 'aarch64' - assetPattern: '[name]_[arch][ext]' - - runs-on: ${{ matrix.platform }} - env: - APPLE_ID: ${{ secrets.APPLE_ID }} - APPLE_ID_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} - steps: - - uses: actions/checkout@v4 - - - name: setup node - uses: actions/setup-node@v4 - with: - node-version: lts/* - cache: 'npm' - - - name: install Rust stable (linux only) - uses: dtolnay/rust-toolchain@stable - if: matrix.platform == 'ubuntu-22.04' || matrix.platform == 'ubuntu-22.04-arm' || matrix.platform == 'ubuntu-24.04' - - - name: install Rust stable (macos only) - uses: dtolnay/rust-toolchain@stable - if: matrix.platform == 'macos-latest' - with: - targets: ${{ matrix.type == 'aarch64' && 'aarch64-apple-darwin' || 'x86_64-apple-darwin' }} - - - name: install Rust stable (windows only) - uses: dtolnay/rust-toolchain@stable - if: matrix.platform == 'windows-11-arm' - with: - targets: ${{ matrix.type == 'aarch64' && 'aarch64-pc-windows-msvc' || 'x86_64-pc-windows-msvc' }} - - - name: Rust cache - uses: swatinem/rust-cache@v2 - with: - workspaces: './src-tauri -> target' - key: ${{ matrix.platform }} - - - name: install dependencies (linux only) - if: matrix.platform == 'ubuntu-22.04-arm' || matrix.platform == 'ubuntu-24.04' - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf - - - name: install dependencies (llinux only) - if: matrix.platform == 'ubuntu-22.04' - run: | - sudo apt-get update - - sudo apt-get install -y \ - build-essential \ - curl \ - wget \ - file \ - libgtk-3-dev \ - libxdo-dev \ - libssl-dev \ - libappindicator3-dev \ - librsvg2-dev \ - patchelf - - mkdir -p /tmp/ubuntu-packages - cd /tmp/ubuntu-packages - wget https://launchpadlibrarian.net/723972773/libwebkit2gtk-4.1-0_2.44.0-0ubuntu0.22.04.1_amd64.deb - wget https://launchpadlibrarian.net/723972761/libwebkit2gtk-4.1-dev_2.44.0-0ubuntu0.22.04.1_amd64.deb - wget https://launchpadlibrarian.net/723972770/libjavascriptcoregtk-4.1-0_2.44.0-0ubuntu0.22.04.1_amd64.deb - wget https://launchpadlibrarian.net/723972746/libjavascriptcoregtk-4.1-dev_2.44.0-0ubuntu0.22.04.1_amd64.deb - wget https://launchpadlibrarian.net/723972735/gir1.2-javascriptcoregtk-4.1_2.44.0-0ubuntu0.22.04.1_amd64.deb - wget https://launchpadlibrarian.net/723972739/gir1.2-webkit2-4.1_2.44.0-0ubuntu0.22.04.1_amd64.deb - wget https://launchpadlibrarian.net/606433947/libicu70_70.1-2ubuntu1_amd64.deb - wget https://launchpadlibrarian.net/606433941/libicu-dev_70.1-2ubuntu1_amd64.deb - wget https://launchpadlibrarian.net/606433945/icu-devtools_70.1-2ubuntu1_amd64.deb - wget https://launchpadlibrarian.net/595623693/libjpeg8_8c-2ubuntu10_amd64.deb - wget https://launchpadlibrarian.net/587202140/libjpeg-turbo8_2.1.2-0ubuntu1_amd64.deb - wget https://launchpadlibrarian.net/592959859/xdg-desktop-portal-gtk_1.14.0-1build1_amd64.deb - sudo apt-get install -y /tmp/ubuntu-packages/*.deb - - - name: install dependencies (linux arm only) - if: matrix.platform == 'ubuntu-22.04-arm' - run: | - sudo apt-get install -y xdg-utils libayatana-appindicator3-dev - - - name: install dependencies (windows only) - if: matrix.platform == 'windows-11-arm' - run: | - cargo install trusted-signing-cli - - - name: Override linuxdeploy (linux legacy only) - if: matrix.platform == 'ubuntu-22.04' - run: | - cargo install tauri-cli --git https://github.com/tauri-apps/tauri --branch feat/truly-portable-appimage --force - echo "Installed tauri-cli version:" - cargo tauri --version - - - name: install frontend dependencies - run: npm install - - - name: Import Apple Developer Certificate (macos only) - if: matrix.platform == 'macos-latest' - env: - APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} - APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} - run: | - echo $APPLE_CERTIFICATE | base64 --decode > certificate.p12 - security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain - security default-keychain -s build.keychain - security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain - security set-keychain-settings -t 3600 -u build.keychain - security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign - security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" build.keychain - security find-identity -v -p codesigning build.keychain - - - name: Verify Certificate (macos only) - if: matrix.platform == 'macos-latest' - run: | - CERT_INFO=$(security find-identity -v -p codesigning build.keychain | grep "Developer ID Application") - CERT_ID=$(echo "$CERT_INFO" | awk -F'"' '{print $2}') - echo "CERT_ID=$CERT_ID" >> $GITHUB_ENV - echo "Certificate imported." - - - uses: tauri-apps/tauri-action@v0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - # for windows signing - AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} - AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} - AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - - # for macos signing - APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} - APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - APPLE_SIGNING_IDENTITY: ${{ env.CERT_ID }} - - # for macos notarization - APPLE_ID: ${{ secrets.APPLE_ID }} - APPLE_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} - APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} - - # for updates - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} - TAURI_BUNDLER_NEW_APPIMAGE_FORMAT: true - with: - tagName: v__VERSION__ - releaseName: 'v__VERSION__' - releaseBody: "\"Rclone\n\n# Rclone UI v__VERSION__\n- Bug squashing & improvements.\n- **See the assets to download this version and install.**\n\n# Downloads\nBelow you can download the main releases. \n\n**If you already have Rclone UI installed, you can update simply by opening the Settings menu.**\n\n| | Linux | Mac | Windows |\n|--------------|---------|--------|-----|\n| 64 bit | [deb](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_amd64.deb)   [AppImage](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_amd64.AppImage)   [RPM](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_x86_64.rpm) | [Intel](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_x64.dmg) | [x64](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_x64.exe) |\n| ARM | [deb](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_arm64.deb)   [AppImage](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_aarch64.AppImage)   [RPM](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_aarch64.rpm) | [Apple Silicon](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_aarch64.dmg) | [Arm64](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_arm64.exe) |\n\n\n# Linux (ALTERNATE)\nMainly for testing or if you're running a cutting edge distro.\n\n| | deb | AppImage | RPM |\n|--------------|---------|--------|-----|\n| 64 bit | [Download](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_amd64_ALTERNATE.deb) | [Download](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_amd64_ALTERNATE.AppImage) | [Download](https://github.com/rclone-ui/rclone-ui/releases/download/v__VERSION__/Rclone.UI_x86_64_ALTERNATE.rpm) |" - assetNamePattern: ${{ matrix.assetPattern }} - releaseDraft: true - prerelease: false - args: ${{ matrix.args }} \ No newline at end of file diff --git a/.github/workflows/release-winget.yml b/.github/workflows/release-winget.yml new file mode 100644 index 00000000..358fdffc --- /dev/null +++ b/.github/workflows/release-winget.yml @@ -0,0 +1,33 @@ +name: release-winget + +# Updates Rclone.RcloneUI on WinGet to a release. Run it after you publish the release: WinGet +# downloads the installers from the release page, which a draft doesn't serve. +on: + workflow_dispatch: + inputs: + version: + description: 'Release version without leading v, e.g. 4.0.0' + required: true + type: string + +permissions: + contents: read + +jobs: + publish: + runs-on: windows-latest + + steps: + # It updates a package that exists in microsoft/winget-pkgs. Rclone.RcloneUI's first version + # is submitted by hand (komac or wingetcreate). The pull requests come from the org's fork, + # rclone/winget-pkgs, which WINGET_ACC_TOKEN must be able to push to. + - uses: vedantmgoyal9/winget-releaser@4ffc7888bffd451b357355dc214d43bb9f23917e # v2 + with: + identifier: Rclone.RcloneUI + fork-user: rclone + version: ${{ inputs.version }} + release-tag: v${{ inputs.version }} + # The installers only. The release's portable zips (-portable.zip) aren't installers, + # and the anchored pattern leaves them out. + installers-regex: '^Rclone-UI-.+-windows-(x64|arm64)-setup\.exe$' + token: ${{ secrets.WINGET_ACC_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..ca3f8a2a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,154 @@ +name: release + +# Releases a stable version of Rclone UI. It builds and packages the six targets under the +# release's file names (Rclone-UI--*), and writes the release's feed +# (rclone-ui-update.json, app/update's Feed). Betas come from the release-beta workflow. +# +# The release is a draft. You publish it on the release page and set it as the latest release +# there. The app's stable channel reads the latest release's feed, so that is what offers the +# update. Then run release-winget. +# +# A dry run does all of it except the tag and the release. Its files are the run's +# release-dry-run artifact. +on: + workflow_dispatch: + inputs: + dry-run: + description: build and write the feed, but make no tag or release + required: false + default: false + type: boolean + +permissions: + contents: read + +jobs: + # Refuses a version that is released already, before anything is built. An existing tag would + # take the release whatever its commit, and an existing release (even a draft) would make + # gh release create fail after every build. A dry run only warns. + prepare: + name: Refuse a version released already + runs-on: ubuntu-24.04 + permissions: + # The API lists draft releases only to a token that can write. + contents: write + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - name: The tag, the release and the metainfo entry + env: + GH_TOKEN: ${{ github.token }} + DRY_RUN: ${{ inputs.dry-run }} + run: | + refuse() { if [ "$DRY_RUN" = true ]; then echo "::warning::$1"; else echo "::error::$1"; exit 1; fi; } + version=$(node -p "require('./package.json').version"); tag="v$version" + case "$version" in + *-*) refuse "$version has a pre-release part: set a stable version in package.json (release-beta makes the betas, and numbers them itself)" ;; + esac + gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$tag" >/dev/null 2>&1 && + refuse "$tag exists already: bump package.json's version to release again" + # Every page, so an old forgotten draft is seen too. The list is assigned to a variable + # so that a failed listing fails the step, and isn't read as "no release". + releases=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" --jq ".[] | select(.tag_name == \"$tag\") | .id") + [ -z "$releases" ] || + refuse "a release for $tag exists already (an unpublished draft?): delete it, or bump the version" + grep -q ": add the release's entry" + echo "ready to release $tag" + + build: + name: Build + needs: prepare + # Each target built, signed and packaged (build.yml), as dist--. + uses: ./.github/workflows/build.yml + with: + release: true + secrets: inherit + + vendor: + name: Vendored sources (Flatpak) + needs: prepare + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/setup-node@v5 + with: + node-version: '24' + cache: npm + - run: npm ci + - name: The vendored sources and the Flathub manifest + run: | + npm run build + go -C tools run ./zstdassets -src ../dist -dst ../app/assets/dist + go mod vendor + version=$(node -p "require('./package.json').version") + vendor="Rclone-UI-$version-vendor.tar.gz" + mkdir -p out + tar -czf "out/$vendor" vendor app/assets/dist + sed -e "s|@VERSION@|$version|g" \ + -e "s|@COMMIT@|$GITHUB_SHA|g" \ + -e "s|@SHA256@|$(sha256sum "out/$vendor" | cut -d' ' -f1)|g" \ + build/flatpak/org.rclone.ui.yml > out/org.rclone.ui.yml + - uses: actions/upload-artifact@v4 + with: + name: dist-vendor + path: out/* + retention-days: 7 + + release: + name: Create the release + needs: [build, vendor] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: actions/download-artifact@v4 + with: + pattern: dist-* + merge-multiple: true + path: dist + + - name: The feed + id: feed + run: | + version=$(node -p "require('./package.json').version") + echo "version=$version" >> "$GITHUB_OUTPUT" + # The policy (which running versions must or should update) is build/release/policy.json. + go run ./build/release manifest -version "$version" \ + -base-url "https://github.com/${{ github.repository }}/releases/download/v$version" \ + -rclone "$(go list -m -f '{{.Version}}' github.com/rclone/rclone)" \ + -notes "See https://github.com/${{ github.repository }}/releases/tag/v$version" dist + # Exactly the files a release publishes: no file under another app's names. + go run ./build/release check -version "$version" dist + + - name: The dry run's files + if: ${{ inputs.dry-run }} + uses: actions/upload-artifact@v4 + with: + name: release-dry-run + path: dist/ + retention-days: 7 + + - name: The draft release + if: ${{ !inputs.dry-run }} + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.feed.outputs.version }} + run: | + # A draft, which you publish and set as the latest release on the release page. The tag + # goes on the commit built: without --target, gh would make it from the default + # branch's head when the draft is published. + gh release create "v$VERSION" --draft --title "v$VERSION" --notes "Rclone UI v$VERSION" \ + --target "$GITHUB_SHA" dist/* diff --git a/.github/workflows/translate.yml b/.github/workflows/translate.yml new file mode 100644 index 00000000..1ef057a8 --- /dev/null +++ b/.github/workflows/translate.yml @@ -0,0 +1,55 @@ +name: translate + +# Publishes the translation site (locales/translate) on GitHub Pages, at +# https://rclone.github.io/rclone-ui/. The site holds the texts of main, so it is built again when +# they change. The repository's Pages source must be "GitHub Actions". +on: + push: + branches: [main] + paths: + - locales/** + - package-lock.json + - .github/workflows/translate.yml + workflow_dispatch: + +# A deployment that has started is left to finish, as GitHub advises for Pages. +concurrency: + group: translate + cancel-in-progress: false + +permissions: + contents: read + +jobs: + build: + name: Build the site + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/setup-node@v5 + with: + node-version: '24' + cache: npm + - run: npm ci + - name: The site's tests + run: npx vitest run locales/translate + - run: npm run translate:build + - uses: actions/upload-pages-artifact@v5 + with: + path: locales/translate/dist + + deploy: + name: Publish on GitHub Pages + needs: build + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v5 diff --git a/.gitignore b/.gitignore index 346613b1..61795802 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ -# Logs -logs +/logs *.log npm-debug.log* yarn-debug.log* @@ -7,15 +6,17 @@ yarn-error.log* pnpm-debug.log* lerna-debug.log* -node_modules -dist -dist-ssr +/node_modules +/dist +/dist-ssr *.local # Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea +/.vscode/* +!/.vscode/extensions.json +/.idea +/.zed/ +/.claude/ .DS_Store *.suo *.ntvs* @@ -23,13 +24,16 @@ dist-ssr *.sln *.sw? -.env* -!.env.example -.cursorignore -.work -.work/* -scripts/release.md -src-tauri/binaries/* -!src-tauri/binaries/.gitkeep -/public/out.js -video +/.env* +/.cursorignore +/.work +/video/ + +# The embedded, compressed Vite build (tools/zstdassets) +/app/assets/dist/ +/build/bin/ +/build/dist/ +*.syso + +# The ads proposal, the presentation images and the tools that make them +/.showcase/ diff --git a/README.md b/README.md index 7628822b..cb0f145e 100644 --- a/README.md +++ b/README.md @@ -4,164 +4,87 @@
- The cross-platform GUI for Rclone + Rclone UI

- A light, transparent layer on top of rclone to manage your remotes & tasks in a more user-friendly way. + A light, transparent layer on top of rclone to manage your remotes & tasks.


+The official GUI for Rclone + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## Package Managers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` - -
App StoreTap here to open the Apple App Store
Google PlayTap here to open the Google Play Store
- ## Downloads - **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) - **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) - **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) - **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -## Docker/Homelab/Server Usage -Control your server, homelab, or mom's PC with **the easiest solution to manage remote **`rclone`** instances.** +## Contributing +We’ve been expecting you... + +Here are some good problems to tackle: +- Fix an open [**Issue**](https://github.com/rclone/rclone-ui/issues) +- Add your language to the translations +- Post about it somewhere, tell your friends! + +## Philosophy +You use `rclone` because you care about your data. This project puts great value on that and aims to provide a stable & enjoyable experience for both newbies and veterans. -[**Check out the guide for controlling remote instances.**](https://rcloneui.com/docs/ui/docker) +We achieve this by offering a focused set of features instead of trying to be a jack of all trades. After just a few minutes of using the app, you'll know whether it's right for you. -## Roadmap -> Finalized items have been moved to the "Features" section. -### [Check out the V3 discussion!](https://github.com/rclone-ui/rclone-ui/issues/18) +...and if it's not, check out [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta), which is geared toward power users and organizations. -## 1 Star = 1 Instant Coffee - +## 1 Star = 1 Bug Squashed + - - - Star History Chart + + + Star History Chart -## Contributing -Welcome, anon. We’ve been expecting you. - -Here are some good problems to tackle: -- Fix an open [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) -- Upgrade repository to Vite 7 & React 19 -- Introduce React Compiler - -🎁 **Merged PRs receive a Lifetime License!** -

- + English - + Chinese - + Japanese - + Polish - + German - + Spanish - + Romanian - + Pirate

diff --git a/README_CHINESE.md b/README_CHINESE.md index bbeb2806..5d77b64a 100644 --- a/README_CHINESE.md +++ b/README_CHINESE.md @@ -4,165 +4,87 @@
- Rclone 的跨平台 GUI + Rclone UI

- 在 rclone 之上提供一层轻量、透明的界面,用更友好的方式管理你的 Remotes & 任务。 + 在 rclone 之上提供一层轻量、透明的界面,用来管理你的远程存储和任务。


+Rclone 官方图形界面 + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## 包管理器 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` +## 下载 +- **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) +- **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) +- **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) +- **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -
App Store点击此处打开 Apple App Store
Google Play点击此处打开 Google Play 商店
+## 参与贡献 +我们一直在等你…… -## 下载 -- **Windows**(**[Arm](https://get.rcloneui.com/win-arm)**、**[x64](https://get.rcloneui.com/win)**) -- **macOS**(**[Apple Silicon](https://get.rcloneui.com/mac)**、**[Intel](https://get.rcloneui.com/mac64)**) -- **Linux**(**[AppImage](https://get.rcloneui.com/linux)**、**[deb](https://get.rcloneui.com/linux-deb)**、**[rpm](https://get.rcloneui.com/linux-rpm)**) -- **Linux `Arm`**(**[AppImage](https://get.rcloneui.com/linux-arm)**、**[deb](https://get.rcloneui.com/linux-deb-arm)**、**[rpm](https://get.rcloneui.com/linux-rpm-arm)**) +以下是一些值得解决的问题: +- 修复一个 [**Issue**](https://github.com/rclone/rclone-ui/issues) +- 把你的语言加入翻译 +- 写篇帖子介绍它,告诉你的朋友! -## Docker/Homelab/服务器使用 -使用 **最简单的方式** 管理远程 **`rclone`** 实例,控制你的服务器、Homelab 或家人的电脑。 +## 理念 +你用 `rclone`,是因为你在乎自己的数据。这个项目非常看重这一点,力求让新手和老手都能获得稳定、愉快的体验。 -[**查看远程实例控制指南。**](https://rcloneui.com/docs/ui/docker) +为此,我们专注于一组精选的功能,而不是什么都想做。只要用上几分钟,你就会知道它适不适合你。 -## 路线图 -> 已完成的内容已移至「功能」部分。 -### [来看看 V3 的讨论!](https://github.com/rclone-ui/rclone-ui/issues/37) +……如果不适合,可以看看 [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta),它面向高级用户和组织。 -## 1 Star = 1 杯速溶咖啡 - +## 1 Star = 消灭 1 个 Bug + - - - Star 历史图表 + + + Star History Chart -## 参与贡献 -欢迎,anon。我们一直在等你。 - -以下是一些值得解决的问题: -- 修复一个 [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) -- 将仓库升级到 Vite 7 和 React 19 -- 引入 React Compiler -- 将 Cron 逻辑迁移到 Rust - -🎁 **合并的 PR 可获终身许可证!** -

- + English - - Chinese + + Chinese - - Japanese + + Japanese - - Polish + + Polish - - German + + German - - Spanish + + Spanish - - Romanian + + Romanian - - Pirate + + Pirate

diff --git a/README_GERMAN.md b/README_GERMAN.md index 28d0580d..a049eb2c 100644 --- a/README_GERMAN.md +++ b/README_GERMAN.md @@ -4,165 +4,87 @@
- Das Rclone Control Center + Rclone UI

- Ein transparentes Layer über rclone, um deine Remotes & Tasks benutzerfreundlich zu verwalten. + Eine leichte, transparente Schicht über rclone, um deine Remotes & Aufgaben zu verwalten.


+Die offizielle GUI für Rclone + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## Package Managers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` - -
App StoreHier tippen, um den Apple App Store zu öffnen
Google PlayHier tippen, um den Google Play Store zu öffnen
- ## Downloads - **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) - **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) - **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) - **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -## Docker/Homelab/Server-Nutzung -Steuere deinen Server, dein Homelab oder den PC deiner Mutter mit **der einfachsten Lösung, Remote-**`rclone`**-Instanzen zu verwalten.** +## Contributing +Wir haben dich bereits erwartet... + +Hier ein paar spannende Aufgaben: +- Behebe ein offenes [**Issue**](https://github.com/rclone/rclone-ui/issues) +- Füge deine Sprache zu den Übersetzungen hinzu +- Schreib irgendwo darüber, erzähl es deinen Freunden! + +## Philosophie +Du nutzt `rclone`, weil dir deine Daten wichtig sind. Dieses Projekt legt großen Wert darauf und will Einsteigern wie alten Hasen ein stabiles und angenehmes Erlebnis bieten. -[**Sieh dir die Anleitung zur Steuerung von Remote-Instanzen an.**](https://rcloneui.com/docs/ui/docker) +Das erreichen wir mit einem fokussierten Funktionsumfang, statt eine eierlegende Wollmilchsau sein zu wollen. Schon nach wenigen Minuten mit der App weißt du, ob sie zu dir passt. -## Roadmap -> Abgeschlossene Items wurden in den Abschnitt „Features“ verschoben. -### [Check out the V3 discussion!](https://github.com/rclone-ui/rclone-ui/issues/37) +...und falls nicht, sieh dir [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta) an, das sich an Power-User und Organisationen richtet. -## 1 Star = 1 Instantkaffee - +## 1 Star = 1 zerquetschter Bug + - - - Star History Chart + + + Star History Chart -## Contributing -Willkommen, anon. Wir haben dich bereits erwartet. - -Hier ein paar spannende Aufgaben: -- Behebe ein offenes [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) -- Hebe das Repository auf Vite 7 & React 19 an -- Führe den React Compiler ein -- Verlege die Cron-Logik nach Rust - -🎁 **Für gemergte PRs gibt's eine Lifetime-Lizenz!** -

- - English + + English - + Chinese - + Japanese - + Polish - - German + + German - + Spanish - + Romanian - + Pirate

diff --git a/README_JAPANESE.md b/README_JAPANESE.md index 0bef8c6d..7a67ef5f 100644 --- a/README_JAPANESE.md +++ b/README_JAPANESE.md @@ -4,165 +4,87 @@
- Rclone のための cross-platform GUI + Rclone UI

- rclone の上に載る軽量で透明なレイヤー。Remote とタスクを、もっと user-friendly に管理できます。 + rclone の上に載る、軽量で透明なレイヤー。リモートとタスクを管理できます。


+Rclone 公式 GUI + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## パッケージマネージャー - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` +## ダウンロード +- **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) +- **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) +- **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) +- **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -
App Storeここをタップして Apple App Store を開く
Google Playここをタップして Google Play ストアを開く
+## コントリビューション +お待ちしていました…… -## ダウンロード -- **Windows**(**[Arm](https://get.rcloneui.com/win-arm)**、**[x64](https://get.rcloneui.com/win)**) -- **macOS**(**[Apple Silicon](https://get.rcloneui.com/mac)**、**[Intel](https://get.rcloneui.com/mac64)**) -- **Linux**(**[AppImage](https://get.rcloneui.com/linux)**、**[deb](https://get.rcloneui.com/linux-deb)**、**[rpm](https://get.rcloneui.com/linux-rpm)**) -- **Linux `Arm`**(**[AppImage](https://get.rcloneui.com/linux-arm)**、**[deb](https://get.rcloneui.com/linux-deb-arm)**、**[rpm](https://get.rcloneui.com/linux-rpm-arm)**) +取り組むと良い課題はこちらです: +- オープンな [**Issue**](https://github.com/rclone/rclone-ui/issues) を修正する +- 翻訳にあなたの言語を追加する +- どこかで紹介して、友だちにも教えてください! -## Docker/Homelab/サーバー利用 -**リモート **`rclone`** インスタンスを管理する最も簡単な方法**で、サーバー、Homelab、家族の PC を管理しましょう。 +## 理念 +あなたが `rclone` を使うのは、データを大切にしているからです。このプロジェクトはそれを何より重視し、初心者にもベテランにも、安定した快適な体験を届けることを目指しています。 -[**リモートインスタンスの管理ガイドをご覧ください。**](https://rcloneui.com/docs/ui/docker) +そのために、何でもこなそうとするのではなく、機能を絞り込んでいます。数分使えば、自分に合うかどうかがわかるはずです。 -## ロードマップ -> 完了した項目は「機能」セクションに移動しました。 -### [V3 のディスカッションをチェック](https://github.com/rclone-ui/rclone-ui/issues/37) +……合わなかったら、パワーユーザーや組織向けの [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta) をチェックしてみてください。 -## 1 Star = インスタントコーヒー 1 杯 - +## 1 Star = バグ 1 匹退治 + - - - スター履歴チャート + + + Star History Chart -## コントリビューション -ようこそ、anon。お待ちしていました。 - -取り組むと良い課題はこちらです: -- オープンな [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) を修正する -- リポジトリを Vite 7 と React 19 にアップグレードする -- React Compiler を導入する -- Cron ロジックを Rust に移行する - -🎁 **マージされた PR にはライフタイムライセンスを贈呈!** -

- - English + + English - + Chinese - - Japanese + + Japanese - + Polish - + German - + Spanish - + Romanian - + Pirate

diff --git a/README_PIRATE.md b/README_PIRATE.md index e069b43e..3270c958 100644 --- a/README_PIRATE.md +++ b/README_PIRATE.md @@ -4,165 +4,87 @@
- The cross-platform GUI fer Rclone, arrr! + Rclone UI, arrr!

- A trim, see-through layer atop rclone so ye can captain yer remotes & tasks like a true seadog. + A trim, see-through layer atop rclone so ye can captain yer remotes & tasks.


+Th' official GUI fer Rclone + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## Package Mangarrs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` - -
App StoreTap here t' open th' Apple App Store
Google PlayTap here t' open th' Google Play Store
- ## Downloads (hoist the booty!) - **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) - **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) - **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) - **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -## Docker/Homelab/Server, Ye Scallywag -Command yer server, homelab, or yer mum’s vessel with **the simplest way t’ manage remote **`rclone`** instances, arrr!** +## Contribootin' +We been awaitin' yer arrival... + +Some fine plunder t' tackle: +- Patch an open [**Issue**](https://github.com/rclone/rclone-ui/issues) +- Add yer own tongue t' th' translations +- Spread th' word in every port, tell yer crew! + +## Th' Pirate's Code +Ye sail with `rclone` 'cause ye guard yer treasure. This ship holds that dear, an' aims t' give landlubbers an' old salts alike a steady, merry voyage. -[**Check out th’ guide fer commandin’ remote instances.**](https://rcloneui.com/docs/ui/docker) +We manage it by stowin' a focused hold o' features, 'stead o' tryin' t' be a jack o' all trades. After but a few minutes aboard, ye'll know if she be th' ship fer ye. -## Chart o’ the Voyage (Roadmap) -> Plunder already claimed has been moved t’ the “Features” hold. -### [Spy the V3 Parley!](https://github.com/rclone-ui/rclone-ui/issues/37) +...an' if she ain't, train yer spyglass on [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta), built fer power users an' whole fleets. -## 1 Star = 1 Mug o’ Grog - +## 1 Star = 1 Bug Made t' Walk th' Plank + - - - Star History Chart (count the loot) + + + Star History Chart -## Contribootin' -Ahoy, matey. We been awaitin' yer arrival. - -Some fine plunder t' tackle: -- Patch an open [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) -- Hoist th' repo t' Vite 7 & React 19 -- Bring aboard th' React Compiler -- Shift th' Cron magic over t' Rust - -🎁 **Merged PRs earn ye a Lifetime Letter o' Marque!** -

- - English + + English - + Chinese - + Japanese - + Polish - + German - + Spanish - + Romanian - - Pirate + + Pirate

diff --git a/README_POLISH.md b/README_POLISH.md index 9b304678..27c810f6 100644 --- a/README_POLISH.md +++ b/README_POLISH.md @@ -4,165 +4,87 @@
- Cross-platform GUI dla Rclone + Rclone UI

- Lekka, przejrzysta nakładka na rclone pozwalająca wygodniej zarządzać zdalnymi zasobami i zadaniami. + Lekka, przejrzysta nakładka na rclone do zarządzania zdalnymi zasobami i zadaniami.


+Oficjalne GUI dla Rclone + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## Package Managers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` - -
App StoreKliknij tutaj, aby otworzyć Apple App Store
Google PlayKliknij tutaj, aby otworzyć Google Play Store
- ## Link do pobrania - **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) - **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) - **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) - **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -## Docker/Homelab/Użycie na serwerze -Kontroluj swój serwer, homelab lub komputer mamy za pomocą **najprostszego rozwiązania do zarządzania zdalnymi instancjami **`rclone`**.** +## Chcesz pomóc? +Spodziewaliśmy się Ciebie... + +Oto kilka ciekawych wyzwań: +- Napraw otwarty [**Issue**](https://github.com/rclone/rclone-ui/issues) +- Dodaj swój język do tłumaczeń +- Napisz o nim gdzieś, powiedz znajomym! + +## Filozofia +Używasz `rclone`, bo zależy Ci na Twoich danych. Ten projekt przywiązuje do tego dużą wagę i chce zapewnić stabilne i przyjemne doświadczenie zarówno nowicjuszom, jak i weteranom. -[**Sprawdź przewodnik po zarządzaniu zdalnymi instancjami.**](https://rcloneui.com/docs/ui/docker) +Osiągamy to, oferując przemyślany zestaw funkcji, zamiast próbować robić wszystko naraz. Już po kilku minutach korzystania z aplikacji będziesz wiedzieć, czy jest dla Ciebie. -## Co dalej? -> Wszystkie ukonczone zadania zostały przeniesione do sekcji "Funkcje". -### [Zobacz dyskusję o wersji 3!](https://github.com/rclone-ui/rclone-ui/issues/37) +...a jeśli nie, zajrzyj do [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta), stworzonego z myślą o zaawansowanych użytkownikach i organizacjach. -## 1 gwiazdka = 1 kawa - +## 1 gwiazdka = 1 naprawiony bug + - - - Historia gwiazdek na Github + + + Star History Chart -## Chcesz pomóc? -Witaj, anon. Spodziewaliśmy się Ciebie. - -Oto kilka ciekawych wyzwań: -- Napraw otwarty [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) -- Zaktualizuj repozytorium do Vite 7 i React 19 -- Wprowadź React Compiler -- Przenieś logikę Cron do Rust - -🎁 **Zmergowane PR-y otrzymują licencję dożywotnią!** -

- - English + + English - + Chinese - + Japanese - - Polish + + Polish - + German - + Spanish - + Romanian - + Pirate

diff --git a/README_ROMANIAN.md b/README_ROMANIAN.md index 605a438a..0f41b987 100644 --- a/README_ROMANIAN.md +++ b/README_ROMANIAN.md @@ -4,165 +4,87 @@
- Interfața Desktop pentru Rclone + Rclone UI

- Un layer transparent peste rclone pentru a gestiona Remotes & Tasks într-un mod mai user-friendly. + Un layer ușor și transparent peste rclone, pentru a-ți gestiona remote-urile și task-urile.


+Aplicația oficială pentru Rclone + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## Package Managers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` - -
App StoreApasă aici pentru a deschide Apple App Store
Google PlayApasă aici pentru a deschide Google Play Store
- ## Descarcă - **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) - **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) - **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) - **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -## Docker/Homelab/Server -Controlează serverul, homelab-ul sau PC-ul maicatii cu **cea mai simplă soluție pentru a gestiona **`rclone`** la distanță.** +## Contribuții +Te-așteptam... + +Iată câteva probleme bune de abordat: +- Rezolvă un [**Issue**](https://github.com/rclone/rclone-ui/issues) deschis +- Adaugă limba ta la traduceri +- Scrie despre el undeva, spune-le prietenilor! + +## Filozofie +Folosești `rclone` pentru că îți pasă de datele tale. Proiectul ăsta pune mare preț pe asta și vrea să ofere o experiență stabilă și plăcută, atât începătorilor, cât și veteranilor. -[**Vezi aici ghidul pentru controlul instanțelor la distanță.**](https://rcloneui.com/docs/ui/docker) +Reușim asta printr-un set de funcții bine ales, în loc să încercăm să facem de toate. După doar câteva minute cu aplicația, o să știi dacă e potrivită pentru tine. -## Roadmap -> Itemi finalizati au fost mutați în secțiunea „Features”. -### [Vezi discuția pentru V3!](https://github.com/rclone-ui/rclone-ui/issues/37) +...iar dacă nu e, aruncă o privire la [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta), gândit pentru utilizatori avansați și organizații. -## 1 Star = 1 Cafea Instant - +## 1 Star = 1 Bug Eliminat + - - - Star History Chart + + + Star History Chart -## Contribuții -Bine ai venit, anon. Te-așteptam. - -Iată câteva probleme bune de abordat: -- Rezolvă un [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) deschis -- Actualizează repository-ul la Vite 7 & React 19 -- Introdu React Compiler -- Mută logica Cron în Rust - -🎁 **PR-urile acceptate primesc o licență gratis!** -

- - English + + English - + Chinese - + Japanese - + Polish - + German - + Spanish - - Romanian + + Romanian - + Pirate

diff --git a/README_SPANISH.md b/README_SPANISH.md index 5fae9bca..0b79527a 100644 --- a/README_SPANISH.md +++ b/README_SPANISH.md @@ -4,165 +4,87 @@
- La GUI multiplataforma para Rclone + Rclone UI

- Una capa ligera y transparente sobre rclone para gestionar tus Remotes & tareas de forma más amigable. + Una capa ligera y transparente sobre rclone para gestionar tus remotos y tareas.


+La GUI oficial de Rclone + +
+

Discord   - - Downloads on Github + + Downloads on Github


- - The GUI for Rclone - - -## Package Managers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flathub - -```bash -flatpak install com.rcloneui.RcloneUI -``` - -
Homebrew - -```bash -brew install --cask rclone-ui -``` - -
Scoop - -```bash -scoop bucket add extras && scoop install rclone-ui -``` - -
Chocolatey - -```bash -choco install rclone-ui -``` - -
WinGet - -```bash -winget install --id=RcloneUI.RcloneUI -e -``` - -
NPM - -```bash -npx rclone-ui -``` - -
App StoreToca aquí para abrir Apple App Store
Google PlayToca aquí para abrir Google Play Store
- ## Descargas - **Windows** (**[Arm](https://get.rcloneui.com/win-arm)**, **[x64](https://get.rcloneui.com/win)**) - **macOS** (**[Apple Silicon](https://get.rcloneui.com/mac)**, **[Intel](https://get.rcloneui.com/mac64)**) - **Linux** (**[AppImage](https://get.rcloneui.com/linux)**, **[deb](https://get.rcloneui.com/linux-deb)**, **[rpm](https://get.rcloneui.com/linux-rpm)**) - **Linux `Arm`** (**[AppImage](https://get.rcloneui.com/linux-arm)**, **[deb](https://get.rcloneui.com/linux-deb-arm)**, **[rpm](https://get.rcloneui.com/linux-rpm-arm)**) -## Docker/Homelab/Servidor -Controla tu servidor, homelab o el PC de tu madre con **la solución más fácil para gestionar instancias remotas de **`rclone`**.** +## Contribuciones +Te estábamos esperando... + +Aquí tienes algunos retos interesantes: +- Arregla un [**Issue**](https://github.com/rclone/rclone-ui/issues) abierto +- Añade tu idioma a las traducciones +- Habla de él en algún sitio, ¡cuéntaselo a tus amigos! + +## Filosofía +Usas `rclone` porque te importan tus datos. Este proyecto le da mucho valor a eso y busca ofrecer una experiencia estable y agradable tanto a novatos como a veteranos. -[**Consulta la guía para controlar instancias remotas.**](https://rcloneui.com/docs/ui/docker) +Lo conseguimos con un conjunto de funciones bien elegido, en lugar de intentar hacerlo todo. Tras unos minutos usando la app, sabrás si es para ti. -## Hoja de ruta -> Los elementos finalizados se han movido a la sección «Funciones». -### [¡Echa un vistazo a la discusión de la V3!](https://github.com/rclone-ui/rclone-ui/issues/37) +...y si no lo es, echa un vistazo a [Rclone Cloud](https://github.com/rclone/rclone-cloud-beta), pensado para usuarios avanzados y organizaciones. -## 1 estrella = 1 café instantáneo - +## 1 estrella = 1 bug aplastado + - - - Gráfico del historial de estrellas + + + Star History Chart -## Contribuciones -Bienvenido, anon. Te estábamos esperando. - -Aquí tienes algunos retos interesantes: -- Arregla un [**Issue**](https://github.com/rclone-ui/rclone-ui/issues) abierto -- Actualiza el repositorio a Vite 7 y React 19 -- Introduce React Compiler -- Mueve la lógica de Cron a Rust - -🎁 **¡Los PR fusionados reciben una licencia de por vida!** -

- - English + + English - + Chinese - + Japanese - + Polish - + German - - Spanish + + Spanish - + Romanian - + Pirate

diff --git a/app/app.go b/app/app.go new file mode 100644 index 00000000..5565f6e8 --- /dev/null +++ b/app/app.go @@ -0,0 +1,635 @@ +// Package app is the UI role. It is the Wails application that owns the windows, the launcher, the +// tray, the menus, deep links, the single-instance lock, autostart, notifications and the update +// flow. It also runs the core inside the same process (see core.go). Pages call it through the +// bound services in services.go, which lib/shell wraps. +// +// The tray is created before the app runs, and the launcher right after it, both before the core +// starts. That way a failed boot always leaves the user a way to quit. +package app + +import ( + "context" + "crypto/sha256" + _ "embed" + "encoding/hex" + "flag" + "fmt" + "io" + "log/slog" + "os" + "os/signal" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/events" + + "github.com/rclone/rclone-ui/app/assets" + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/deeplink" + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/launcher" + "github.com/rclone/rclone-ui/app/launcher/engine/providers" + "github.com/rclone/rclone-ui/app/launcher/host" + "github.com/rclone/rclone-ui/app/launcher/view/linux/gnome" + "github.com/rclone/rclone-ui/app/menus" + "github.com/rclone/rclone-ui/app/pathlink" + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/app/tray" + "github.com/rclone/rclone-ui/app/update" + "github.com/rclone/rclone-ui/app/windows" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/agents" + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/logs" + "github.com/rclone/rclone-ui/core/telemetry" + "github.com/rclone/rclone-ui/core/version" +) + +//go:embed appicon.png +var appIcon []byte + +// appID is the name the OS knows the app by. It is the GTK application ID and the base of the +// single-instance lock's name. Under Flatpak it must be the Flatpak app ID, because the sandbox +// only lets the app own D-Bus names under that ID. +func appID() string { + if id := os.Getenv("FLATPAK_ID"); id != "" { + return id + } + return "org.rclone.ui" +} + +// uniqueID is the name of the single-instance lock. There is one lock per data directory, so a +// copy on another data directory (--data-dir) doesn't hand its launch over to the installed app +// and doesn't receive that app's links. The copy on sharedDir, the OS's default data directory, +// takes the app's ID. A portable copy passes no sharedDir, so it never shares a lock. +func uniqueID(dataDir, sharedDir string) string { + id := appID() + if dataDir == "" { + return id + } + key := func(dir string) string { + if abs, err := filepath.Abs(dir); err == nil { + dir = abs + } + dir = filepath.Clean(dir) + if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { + dir = strings.ToLower(dir) // file systems on these OSes ignore case + } + return dir + } + dir := key(dataDir) + if sharedDir != "" && dir == key(sharedDir) { + return id + } + sum := sha256.Sum256([]byte(dir)) + // An element of a D-Bus name can't start with a digit. + return id + ".d" + hex.EncodeToString(sum[:8]) +} + +// options are the flags of `rcui ui`, plus an optional rclone:// link. +type options struct { + dataDir string + hidden bool + link string + // open is a route to open in a window right away, as in `rcui ui --open /test`. A relaunch + // uses it to reopen the window that asked for the relaunch. + open string + // after is the ID of a process to wait for before starting. A relaunch sets it to the process + // it replaces, which holds the single-instance lock and the data folder until it exits. + after int +} + +func parseOptions(args []string) (options, error) { + var o options + fs := flag.NewFlagSet("rcui ui", flag.ContinueOnError) + fs.SetOutput(io.Discard) + fs.StringVar(&o.dataDir, "data-dir", "", "the data directory (default: the core's)") + fs.BoolVar(&o.hidden, "hidden", false, "start without the startup window") + fs.StringVar(&o.open, "open", "", "open a window at this route") + fs.IntVar(&o.after, "after", 0, "wait for this process to exit first") + // macOS passes -psn_ to an app started by a quarantined first launch. It isn't one of + // our flags, and parsing it would make the app exit. + args = slices.DeleteFunc(slices.Clone(args), func(a string) bool { return strings.HasPrefix(a, "-psn_") }) + var rest []string + for len(args) > 0 { + if err := fs.Parse(args); err != nil { + return o, err + } + args = fs.Args() + if len(args) == 0 { + break + } + // This is a link or a stray argument. Skip it and keep parsing. + rest = append(rest, args[0]) + args = args[1:] + } + o.link = deeplink.FromArgs(rest) + return o, nil +} + +type ui struct { + app *application.App + log *slog.Logger + logs *logs.Log + opts options + dataDir string + exe string + production bool + + windows *windows.Manager + launcher *host.Host + tray *tray.Tray + // store is the one copy of the core's state that the tray and the launcher show. + store *corestate.Store + notifier *notifier + updates *updateFlow + + cores coreHost + // apis are the core's APIs that pages call. They are bound before the core starts. + apis *core.APIs + // agents is the MCP server that lets AI agents use the app, while the settings turn it on. + agents *agents.Server + + quitMu sync.Mutex + quitting atomic.Bool + // sessionEnding is set when the OS is ending the session (a logout, a restart or a shutdown) + // and the app has agreed to let it end (see shouldQuit and wndProc). + sessionEnding atomic.Bool + + links links + + startupOnce sync.Once + noStartup atomic.Bool + firstReady sync.Once + + applied uiSettings // the core's settings as the UI last applied them +} + +// Run runs the UI role and returns the process's exit code. +func Run(args []string) int { + opts, err := parseOptions(args) + if err != nil { + fmt.Fprintln(os.Stderr, "rcui ui:", err) + return 2 + } + if opts.after > 0 { + platform.WaitForExit(opts.after, time.Minute) + } + u := &ui{opts: opts, production: production} + if err := u.setup(); err != nil { + fmt.Fprintln(os.Stderr, "rcui ui:", err) + return 1 + } + defer func() { _ = u.logs.Close() }() + if err := u.app.Run(); err != nil { + u.log.Error("the app stopped", "error", err) + return 1 + } + return 0 +} + +func (u *ui) setup() error { + platform.FixPath() + linuxEnvironment() + + defaultDir, err := datadir.Default() + u.dataDir = u.opts.dataDir + if u.dataDir == "" { + if err != nil { + return err + } + u.dataDir = defaultDir + } + sharedDir := defaultDir + if _, portable := datadir.Portable(); portable { + sharedDir = "" + } + level := "" + if !u.production { + level = "debug" + } + l, err := logs.Open(logs.Options{ + Path: filepath.Join(u.dataDir, datadir.LogsDir, "rcui.log"), + Stderr: !u.production, + Level: level, + }) + if err != nil { + return fmt.Errorf("could not open the log: %w", err) + } + u.logs = l + // The app speaks the system's language until the core has read the language setting + // (core/settings), which is before any window opens but after the first dialogs can show. + u.applied.language = i18n.SetLanguage("") + // The APIs read the log and the data folder at once, so they are created once both are known, + // before the services that bind them. + u.apis = core.NewAPIs(core.APIOptions{Emit: u.emitToCaller, Log: l, DataDir: u.dataDir}) + keepCrashes(filepath.Dir(l.Path())) + // A panic that was recovered is logged with its stack. Each such line is also sent as a + // crash report, when the user shares them. + slog.SetDefault(slog.New(telemetry.TapPanics(l.Handler(), u.apis.Panic))) + u.log = logs.Logger(logs.CompUI, "") + u.log.Info("starting", "version", version.App, "os", runtime.GOOS, "arch", runtime.GOARCH, "production", u.production) + + exe, err := platform.Executable() + if err != nil { + return err + } + u.exe = exe + // The agents' server stays stopped until the settings turn it on (loadSettings). + u.agents = agents.New(agents.Options{ + APIs: u.apis, Log: logs.Logger(logs.CompUI, "agents"), DataDir: u.dataDir, Version: version.App, + OpenWindow: func(route string) error { return u.windows.Open(route) }, + Changed: func(st agents.Status) { u.app.Event.Emit(EventAgentsChanged, st) }, + }) + u.notifier = newNotifier(u.log, func(route string) { + if err := u.windows.Open(route); err != nil { + u.log.Error("could not open a toast's window", "route", route, "error", err) + } + }) + u.updates = &updateFlow{u: u, enabled: u.production || testFeed() != "", engine: update.Options{FeedURL: testFeed()}} + + u.app = application.New(application.Options{ + Name: "Rclone UI", + Description: i18n.T("Cross-platform GUI for rclone & S3"), + Icon: appIcon, + Services: u.services(), + Assets: application.AssetOptions{ + Handler: assets.Handler(), + DisableLogging: true, + }, + Mac: application.MacOptions{ + ActivationPolicy: application.ActivationPolicyAccessory, + }, + Windows: application.WindowsOptions{ + DisableQuitOnLastWindowClosed: true, + WebviewUserDataPath: filepath.Join(u.dataDir, "webview"), + AdditionalBrowserArgs: []string{"--ignore-gpu-blocklist"}, + DisabledFeatures: []string{"msWebOOUI"}, + WndProcInterceptor: u.wndProc, + }, + Linux: application.LinuxOptions{ + DisableQuitOnLastWindowClosed: true, + ApplicationID: appID(), + }, + SingleInstance: &application.SingleInstanceOptions{ + UniqueID: uniqueID(u.dataDir, sharedDir), + OnSecondInstanceLaunch: u.secondInstance, + }, + Flags: u.flags(), + ShouldQuit: u.shouldQuit, + OnShutdown: u.onShutdown, + DisableDefaultSignalHandler: true, + Logger: u.log.With("src", "wails"), + LogLevel: slog.LevelWarn, + PanicHandler: func(p *application.PanicDetails) { + u.log.Error("panic", "error", p.Error, "stack", p.StackTrace) + }, + ErrorHandler: u.wailsError, + WarningHandler: func(msg string) { u.log.Warn("wails", "warning", msg) }, + }) + + u.windows = windows.New(u.app, u.log, u.production) + // Which windows are used, in the usage data that the user shares (core/telemetry). + u.windows.Opened = u.apis.Screen + u.store = corestate.New(corestate.APIReader(u.apis), u.log.With("src", "corestate")) + u.launcher = host.New(host.Options{ + App: u.app, + Log: u.log, + Store: u.store, + APIs: u.apis, + Production: u.production, + Open: u.windows.Open, + Reveal: func(path string) error { return u.reveal(path, true) }, + OpenURL: u.openURL, + Notify: u.notifier.send, + Quit: func() { u.quit(false) }, + Acks: gnome.Acks{Has: u.acknowledged, Add: u.acknowledge}, + }) + u.tray = tray.New(u.app, tray.Actions{ + ShowLauncher: u.launcher.Show, + Open: func() { go u.trayOpen(context.Background()) }, + OpenWindow: func(url string) { + if err := u.windows.Open(url); err != nil { + u.log.Error("could not open a window", "route", url, "error", err) + } + }, + // Opening the browser can wait on a command, and a menu click must not block. + GitHub: func() { + go func() { + if err := u.openURL(providers.GitHubURL); err != nil { + u.log.Error("could not open a URL", "url", providers.GitHubURL, "error", err) + } + }() + }, + Quit: func() { go u.quit(false) }, + }, platform.IsLinuxMint()) + u.store.Subscribe(u.showInTray) + menus.Set(u.app) + + u.app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + go u.started() + }) + u.app.Event.OnApplicationEvent(events.Common.ApplicationLaunchedWithUrl, func(e *application.ApplicationEvent) { + if link := e.Context().URL(); link != "" { + go u.openLink(link) + } + }) + // On macOS, opening the app again from Finder, Spotlight or Launchpad while it runs doesn't + // start a second instance. It sends a reopen event instead. Show the launcher, as a second + // launch does on other systems, because the menu bar icon may be hidden behind the notch. + u.app.Event.OnApplicationEvent(events.Mac.ApplicationShouldHandleReopen, func(*application.ApplicationEvent) { + u.launcher.Show() + }) + u.handleSignals() + return nil +} + +func (u *ui) started() { + u.waitForScreens(5 * time.Second) + if m := platform.FlatpakMissing(); m.Any() { + u.flatpakGate(m) + return + } + if err := u.launcher.Create(); err != nil { + u.log.Error("could not create the launcher", "error", err) + } + // Use the default shortcut until the core's settings replace it (see loadSettings), so the + // launcher can be reached even when the core never starts. + if err := u.launcher.SetShortcut(launcher.DefaultShortcut); err != nil { + u.log.Error("could not register the launcher shortcut", "error", err) + } + u.notifier.start() + // Only a release build on the app's own data does this. A development build, or a copy that + // runs on another data directory (for tests or a scratch run), must never take over the + // installed app's login item or its rclone:// links. A portable copy runs on its own data + // folder, so it registers itself for the links, as the README in its zip says. + if u.production && u.opts.dataDir == "" { + u.registerScheme() + // An enabled rclone link is updated when the app has moved. + if err := pathlink.Refresh(); err != nil { + u.log.Warn("could not refresh the rclone link", "error", err) + } + } + + u.startCore() + + // Links wait until the screens are known. A link that arrived earlier is opened now, together + // with the launch's own link. (macOS reports a launch link as an event, which can arrive + // before this point.) + if u.opts.link != "" { + u.openLink(u.opts.link) + } + u.links.release(u.handleLink) + if u.opts.hidden { + u.noStartup.Store(true) + } + if u.opts.open != "" { + u.noStartup.Store(true) + if err := u.windows.Open(u.opts.open); err != nil { + u.log.Error("could not open the window", "route", u.opts.open, "error", err) + } + } + u.devEval() +} + +// waitForScreens waits until Wails knows the screens. On macOS, Wails reads them in its own +// didFinishLaunching handler, which races with ApplicationStarted. Every window is placed on a +// screen, so no window can be created before the screens are known. +func (u *ui) waitForScreens(limit time.Duration) { + deadline := time.Now().Add(limit) + for len(u.app.Screen.GetAll()) == 0 && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if len(u.app.Screen.GetAll()) == 0 { + u.log.Warn("no screens known yet; windows may fail to open") + } +} + +// flatpakGate runs when the Flatpak lacks a permission it needs: access to the host's files, to +// the autostart folder and, on GNOME, to GNOME Shell's extensions. It explains the problem, +// offers the command that grants them, and exits. A user who granted disk access before the app +// needed the rest has to run the command again. +func (u *ui) flatpakGate(m platform.Missing) { + cmd := platform.FlatpakOverride() + msg := i18n.T("You are running the flatpak version of Rclone UI, which is sandboxed.") + "\n\n" + flatpakNeeds(m) + + "\n\n" + cmd + "\n\n" + i18n.T("Restart Rclone UI afterwards.") + // i18n: The title of the dialog that asks for the Flatpak's permissions. + title := i18n.T("Flatpak Permissions Required") + // i18n: A button that copies the command that grants the Flatpak's permissions, then quits the app. + if interaction.Ask(interaction.Warning, title, msg, i18n.T("Copy Command & Exit"), i18n.T("Exit")) { + u.app.Clipboard.SetText(cmd) + } + u.exit() +} + +// flatpakNeeds returns the part of flatpakGate's message that lists the missing permissions. +func flatpakNeeds(m platform.Missing) string { + var needs []string + if m.Disk { + needs = append(needs, i18n.T("Disk access to manage your files")) + } + if m.Autostart { + needs = append(needs, i18n.T("Access to your autostart folder, to start when you log in")) + } + if m.GNOME { + needs = append(needs, i18n.T("Access to GNOME's extensions to place the Launcher")) + } + // i18n: Followed by a list of the permissions that the Flatpak needs. + head := i18n.T("Rclone UI needs:") + if !m.Disk { + // i18n: Followed by a list of the permissions that the Flatpak needs, after an update that needs more. + head = i18n.T("Rclone UI now also needs:") + } + // i18n: Followed by the command. "It" or "them" are the permissions listed above. + grant := i18n.N("Please grant it with this command, in your terminal:", + "Please grant them with this command, in your terminal:", len(needs)) + return head + "\n\n• " + strings.Join(needs, "\n• ") + "\n\n" + grant +} + +// registerScheme registers this executable for rclone:// links where no installer does it. +func (u *ui) registerScheme() { + if platform.IsFlatpak() { + return + } + exe := u.exe + switch runtime.GOOS { + case "linux": + exe = os.Getenv("APPIMAGE") + if exe == "" { + return // deb and rpm declare the scheme in their .desktop file + } + case "darwin": + return + } + if err := deeplink.Register(exe); err != nil { + u.log.Warn("could not register rclone:// links", "error", err) + } +} + +// coreDown clears what the core was running, because it stopped along with the core. The store +// forgets it for both the tray and the launcher, so no dead mount is listed as active and no stop +// button stays enabled. +func (u *ui) coreDown() { + u.store.CoreDown() +} + +// showStartup opens the startup window once, when the core is first ready or when it failed. It +// does nothing if a deep link, --hidden or the "Show Startup screen" setting (see loadSettings) +// turned it off. +func (u *ui) showStartup() { + if u.noStartup.Load() || u.quitting.Load() { + return + } + u.startupOnce.Do(func() { + if err := u.windows.Open("/startup"); err != nil { + u.log.Error("could not open the startup window", "error", err) + return + } + // On Linux the window shows only once. "Show Startup screen" is turned off after the + // first time. + if runtime.GOOS == "linux" { + go u.hideStartupFromNow(context.Background()) + } + }) +} + +// openLink handles a deep link once the boot knows the screens (see started). A link that arrives +// earlier waits until then. +func (u *ui) openLink(raw string) { u.links.add(raw, u.handleLink) } + +// handleLink opens a deep link's window. It returns true once the window is open. +func (u *ui) handleLink(raw string) bool { + link, ok := deeplink.Parse(raw) + if !ok { + u.log.Warn("ignored an unknown link", "link", raw) + return false + } + if up := link.Update; up != nil { + u.log.Info("update link", "version", up.Version, "channel", up.Channel) + go u.updates.requested(context.Background(), UpdateRequest{Version: up.Version, Channel: up.Channel}) + return true + } + u.log.Info("deep link", "route", link.URL) + if err := u.windows.Open(link.URL); err != nil { + u.log.Error("could not open the link's window", "error", err) + return false + } + // A link at start replaces the startup window. If the link's window failed to open, the + // startup window still shows. + u.noStartup.Store(true) + return true +} + +// links holds the deep links on their way to handleLink. They wait until release is called, +// because no window can open before the screens are known. Windows and Linux report a launch link +// both as an argument and as an event, so a link seen twice within a few seconds is handled +// once. The few seconds count from when its window opened, so a link whose window failed is +// tried again when it is reported again. +type links struct { + mu sync.Mutex // held while a link is handled, so two reports of the same link don't race + open bool + pending []string + last string + lastAt time.Time +} + +func (l *links) add(raw string, handle func(string) bool) { + l.mu.Lock() + defer l.mu.Unlock() + if !l.open { + l.pending = append(l.pending, raw) + return + } + l.handle(raw, handle) +} + +// release handles the waiting links in order, and makes every later link be handled right away. +func (l *links) release(handle func(string) bool) { + l.mu.Lock() + defer l.mu.Unlock() + l.open = true + pending := l.pending + l.pending = nil + for _, raw := range pending { + l.handle(raw, handle) + } +} + +func (l *links) handle(raw string, handle func(string) bool) { + if raw == l.last && time.Since(l.lastAt) < 5*time.Second { + return + } + if handle(raw) { + l.last, l.lastAt = raw, time.Now() + } +} + +func (u *ui) secondInstance(data application.SecondInstanceData) { + if link := deeplink.FromArgs(data.Args); link != "" { + u.openLink(link) + return + } + // `rcui mcp` starts the app hidden when it finds none. When the app was running after all, + // nothing should show. + if slices.Contains(data.Args, "--hidden") { + return + } + u.launcher.Show() +} + +func (u *ui) hideWindows() { + for _, w := range u.app.Window.GetAll() { + w.Hide() + } +} + +// handleSignals makes SIGINT and SIGTERM quit through the quit flow, without asking. A second +// signal exits at once. +func (u *ui) handleSignals() { + ch := make(chan os.Signal, 2) + signal.Notify(ch, os.Interrupt, syscall.SIGTERM) + go func() { + <-ch + u.log.Info("signal received; quitting") + go u.quit(true) + <-ch + os.Exit(1) + }() +} + +// flags returns the values that pages read synchronously (see lib/shell and Flags.GetFlag). +func (u *ui) flags() map[string]any { + home, _ := os.UserHomeDir() + return map[string]any{ + "version": version.App, + "production": u.production, + "homeDir": home, + "dataDir": u.dataDir, + "defaultShortcut": launcher.DefaultShortcut, + // The app's language for this system, which a window starts in until it has read the + // language setting (lib/i18n.ts). + "systemLanguage": i18n.System(), + "languages": i18n.Languages(), + } +} + +// linuxEnvironment works around an NVIDIA bug. With some drivers, explicit sync breaks WebKitGTK +// on X11. +func linuxEnvironment() { + if runtime.GOOS != "linux" { + return + } + _, dri := os.Stat("/dev/dri") + if dri == nil && os.Getenv("WAYLAND_DISPLAY") == "" && os.Getenv("XDG_SESSION_TYPE") == "x11" && + os.Getenv("__NV_DISABLE_EXPLICIT_SYNC") == "" { + _ = os.Setenv("__NV_DISABLE_EXPLICIT_SYNC", "1") + } +} diff --git a/app/app_test.go b/app/app_test.go new file mode 100644 index 00000000..fa702223 --- /dev/null +++ b/app/app_test.go @@ -0,0 +1,114 @@ +package app + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/rclone/rclone-ui/app/platform" +) + +func TestParseOptionsSkipsPSN(t *testing.T) { + if _, err := parseOptions([]string{"-psn_0_123456"}); err != nil { + t.Fatalf("alone: %v", err) + } + o, err := parseOptions([]string{"-psn_0_123456", "rclone://add-template?cmd=sync", "--hidden"}) + if err != nil { + t.Fatalf("before a link: %v", err) + } + if o.link != "rclone://add-template?cmd=sync" || !o.hidden { + t.Fatalf("link %q, hidden %v", o.link, o.hidden) + } + if _, err := parseOptions([]string{"--nope"}); err == nil { + t.Fatal("an unknown flag passed") + } +} + +func TestUniqueID(t *testing.T) { + t.Setenv("FLATPAK_ID", "") + def := filepath.Join(t.TempDir(), "org.rclone.ui") + if got := uniqueID("", def); got != "org.rclone.ui" { + t.Errorf("no data dir: %q", got) + } + if got := uniqueID(def+string(filepath.Separator), def); got != "org.rclone.ui" { + t.Errorf("the default data dir: %q", got) + } + scratch := t.TempDir() + a, b := uniqueID(filepath.Join(scratch, "a"), def), uniqueID(filepath.Join(scratch, "b"), def) + if a == b || !strings.HasPrefix(a, "org.rclone.ui.d") || !strings.HasPrefix(b, "org.rclone.ui.d") { + t.Errorf("two scratch dirs: %q, %q", a, b) + } + if again := uniqueID(filepath.Join(scratch, "x", "..", "a"), def); again != a { + t.Errorf("the same dir spelled otherwise: %q, %q", again, a) + } + for _, r := range strings.TrimPrefix(a, "org.rclone.ui.d") { + if !strings.ContainsRune("0123456789abcdef", r) { + t.Fatalf("%q isn't a D-Bus name", a) + } + } + // A portable copy shares its lock with no other copy, even on its default data dir. + portable := filepath.Join(scratch, "Rclone UI", "data") + if got := uniqueID(portable, ""); !strings.HasPrefix(got, "org.rclone.ui.d") { + t.Errorf("a portable copy: %q", got) + } + if other := uniqueID(filepath.Join(scratch, "copy", "data"), ""); other == uniqueID(portable, "") { + t.Errorf("two portable copies share %q", other) + } + t.Setenv("FLATPAK_ID", "org.example.Flatpak") + if got := uniqueID(filepath.Join(scratch, "a"), def); !strings.HasPrefix(got, "org.example.Flatpak.d") { + t.Errorf("Flatpak: %q is not under the app id", got) + } +} + +func TestFlatpakNeeds(t *testing.T) { + const one, many = "\n\nPlease grant it with this command, in your terminal:", + "\n\nPlease grant them with this command, in your terminal:" + for _, c := range []struct { + m platform.Missing + want string + }{ + {platform.Missing{Disk: true}, "Rclone UI needs:\n\n• Disk access to manage your files" + one}, + {platform.Missing{Disk: true, Autostart: true}, "Rclone UI needs:\n\n• Disk access to manage your files\n• Access to your autostart folder, to start when you log in" + many}, + {platform.Missing{Disk: true, Autostart: true, GNOME: true}, "Rclone UI needs:\n\n• Disk access to manage your files\n• Access to your autostart folder, to start when you log in\n" + + "• Access to GNOME's extensions to place the Launcher" + many}, + {platform.Missing{GNOME: true}, "Rclone UI now also needs:\n\n• Access to GNOME's extensions to place the Launcher" + one}, + {platform.Missing{Autostart: true}, "Rclone UI now also needs:\n\n• Access to your autostart folder, to start when you log in" + one}, + } { + if got := flatpakNeeds(c.m); got != c.want { + t.Errorf("%+v:\n got %q\nwant %q", c.m, got, c.want) + } + } +} + +// TestLinksWaitForTheScreens also checks that a link seen twice is handled once, and that a link +// whose window failed to open is tried again. +func TestLinksWaitForTheScreens(t *testing.T) { + var l links + var opened []string + fail := map[string]bool{} + handle := func(raw string) bool { + opened = append(opened, raw) + return !fail[raw] + } + l.add("rclone://a", handle) + l.add("rclone://a", handle) + if len(opened) != 0 { + t.Fatalf("handled before the screens: %v", opened) + } + l.release(handle) + if strings.Join(opened, ",") != "rclone://a" { + t.Fatalf("after release: %v", opened) + } + l.add("rclone://a", handle) + if len(opened) != 1 { + t.Fatalf("a duplicate was handled: %v", opened) + } + fail["rclone://b"] = true + l.add("rclone://b", handle) + delete(fail, "rclone://b") + l.add("rclone://b", handle) + l.add("rclone://b", handle) + if strings.Join(opened, ",") != "rclone://a,rclone://b,rclone://b" { + t.Fatalf("a failed link: %v", opened) + } +} diff --git a/src-tauri/icons/128x128.png b/app/appicon.png similarity index 100% rename from src-tauri/icons/128x128.png rename to app/appicon.png diff --git a/app/assets/assets.go b/app/assets/assets.go new file mode 100644 index 00000000..31568e28 --- /dev/null +++ b/app/assets/assets.go @@ -0,0 +1,99 @@ +// Package assets serves the pages (the Vite build) to the webviews. Release builds +// (-tags production) embed app/assets/dist. The build fills that folder with the Vite output +// compressed by tools/zstdassets, as .zst, or as the original file when compressing didn't +// save space. Each file is decompressed on each request. Other builds serve dist/ from disk, or +// proxy Vite's dev server when FRONTEND_DEVSERVER_URL is set. A path without an extension that +// doesn't name a file (including a folder) is treated as a route and gets index.html. +package assets + +import ( + "bytes" + "errors" + "io/fs" + "mime" + "net/http" + "path" + "strings" + "time" +) + +// ZstdSuffix marks a compressed file in the embedded tree. +const ZstdSuffix = ".zst" + +// loader returns a file's bytes, or fs.ErrNotExist when there is no such file. +type loader func(name string) ([]byte, error) + +// spa serves files by path, and index.html for any path without an extension (the pages' routes, +// such as /settings or /startup). It sets the Content-Type from the extension. +type spa struct { + load loader + modTime time.Time +} + +func (s spa) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + name := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/") + if name == "" { + name = "index.html" + } + data, err := s.load(name) + if errors.Is(err, fs.ErrNotExist) && path.Ext(name) == "" { + name = "index.html" + data, err = s.load(name) + } + switch { + case errors.Is(err, fs.ErrNotExist): + http.NotFound(w, r) + return + case err != nil: + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", ContentType(name, data)) + if name == "index.html" { + w.Header().Set("Cache-Control", "no-cache") + } + http.ServeContent(w, r, name, s.modTime, bytes.NewReader(data)) +} + +// types lists the extensions whose type the OS tables get wrong or don't have. For example, the +// Windows registry may say text/plain for .js, which WebView2 refuses for a module script. +var types = map[string]string{ + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json", + ".map": "application/json", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".ico": "image/x-icon", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".ttf": "font/ttf", + ".otf": "font/otf", + ".wasm": "application/wasm", + ".txt": "text/plain; charset=utf-8", + ".webmanifest": "application/manifest+json", + ".mp4": "video/mp4", + ".webm": "video/webm", +} + +// ContentType returns a file's type from its extension, or else detects it from the file's bytes. +func ContentType(name string, data []byte) string { + ext := strings.ToLower(path.Ext(name)) + if t, ok := types[ext]; ok { + return t + } + if t := mime.TypeByExtension(ext); t != "" { + return t + } + return http.DetectContentType(data) +} diff --git a/app/assets/assets_test.go b/app/assets/assets_test.go new file mode 100644 index 00000000..147b6110 --- /dev/null +++ b/app/assets/assets_test.go @@ -0,0 +1,97 @@ +package assets + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/fstest" + "time" + + "github.com/klauspost/compress/zstd" +) + +func zst(t *testing.T, s string) []byte { + t.Helper() + enc, err := zstd.NewWriter(nil) + if err != nil { + t.Fatal(err) + } + return enc.EncodeAll([]byte(s), nil) +} + +func TestCompressedHandler(t *testing.T) { + tree := fstest.MapFS{ + "index.html.zst": {Data: zst(t, "app")}, + "assets/main-1a2b.js.zst": {Data: zst(t, "console.log(1)")}, + "icon.png": {Data: []byte("\x89PNG\r\n\x1a\nraw")}, + } + h := newCompressed(tree, time.Now()) + cases := []struct { + path, body, ctype string + code int + }{ + {"/", "app", "text/html; charset=utf-8", 200}, + {"/settings", "app", "text/html; charset=utf-8", 200}, + {"/templates/", "app", "text/html; charset=utf-8", 200}, + {"/assets/main-1a2b.js", "console.log(1)", "text/javascript; charset=utf-8", 200}, + {"/icon.png", "\x89PNG\r\n\x1a\nraw", "image/png", 200}, + {"/missing.js", "", "", 404}, + } + for _, c := range cases { + for range 2 { // each request decompresses the file again + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, c.path, nil)) + body, _ := io.ReadAll(rec.Body) + if rec.Code != c.code { + t.Errorf("%s: code %d, want %d", c.path, rec.Code, c.code) + continue + } + if c.code != 200 { + continue + } + if string(body) != c.body || rec.Header().Get("Content-Type") != c.ctype { + t.Errorf("%s: %q (%s), want %q (%s)", c.path, body, rec.Header().Get("Content-Type"), c.body, c.ctype) + } + } + } +} + +func TestCompressedFolderIsARoute(t *testing.T) { + tree := fstest.MapFS{ + "index.html.zst": {Data: zst(t, "app")}, + "icons/providers/drive.svg.zst": {Data: zst(t, "")}, + } + h := newCompressed(tree, time.Now()) + for _, path := range []string{"/icons", "/icons/", "/icons/providers"} { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + if body, _ := io.ReadAll(rec.Body); rec.Code != 200 || string(body) != "app" { + t.Errorf("%s: %d %q", path, rec.Code, body) + } + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/nope.js", nil)) + if rec.Code != 404 { + t.Errorf("/nope.js: %d", rec.Code) + } +} + +func TestStoredFileRange(t *testing.T) { + tree := fstest.MapFS{"clip.mp4": {Data: []byte("0123456789")}} + h := newCompressed(tree, time.Now()) + req := httptest.NewRequest(http.MethodGet, "/clip.mp4", nil) + req.Header.Set("Range", "bytes=2-5") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if body, _ := io.ReadAll(rec.Body); rec.Code != http.StatusPartialContent || string(body) != "2345" { + t.Errorf("%d %q", rec.Code, body) + } +} + +func TestContentTypeSniffs(t *testing.T) { + if got := ContentType("LICENSE", []byte("plain words")); !strings.HasPrefix(got, "text/plain") { + t.Errorf("sniffed %q", got) + } +} diff --git a/app/assets/compressed.go b/app/assets/compressed.go new file mode 100644 index 00000000..8e038934 --- /dev/null +++ b/app/assets/compressed.go @@ -0,0 +1,32 @@ +package assets + +import ( + "errors" + "io/fs" + "net/http" + "time" + + "github.com/klauspost/compress/zstd" +) + +// newCompressed serves a tree of .zst files (and uncompressed files), decompressing a file +// on each request. A window loads each file once, and caching them would keep the decompressed +// build in memory for as long as the app runs. A folder is reported as not found, so its path is +// treated as a route. +func newCompressed(tree fs.FS, modTime time.Time) http.Handler { + dec, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(0)) + if err != nil { + panic(err) // fails only with invalid options + } + load := func(name string) ([]byte, error) { + packed, err := readFile(tree, name+ZstdSuffix) + if errors.Is(err, fs.ErrNotExist) { + return readFile(tree, name) + } + if err != nil { + return nil, err + } + return dec.DecodeAll(packed, nil) + } + return spa{load: load, modTime: modTime} +} diff --git a/app/assets/disk.go b/app/assets/disk.go new file mode 100644 index 00000000..389b2059 --- /dev/null +++ b/app/assets/disk.go @@ -0,0 +1,26 @@ +//go:build !production + +package assets + +import ( + "net/http" + "os" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// Handler serves dist/ from disk, or the folder in RCUI_DIST_DIR. Files are read on every request, +// so a rebuild shows up on reload. When FRONTEND_DEVSERVER_URL is set (Vite on port 9245), Wails +// proxies the dev server instead. +func Handler() http.Handler { + if os.Getenv("FRONTEND_DEVSERVER_URL") != "" { + return application.AssetFileServerFS(os.DirFS(".")) + } + dir := os.Getenv("RCUI_DIST_DIR") + if dir == "" { + dir = "dist" + } + tree := os.DirFS(dir) + return spa{load: func(name string) ([]byte, error) { return readFile(tree, name) }, modTime: time.Now()} +} diff --git a/app/assets/embed.go b/app/assets/embed.go new file mode 100644 index 00000000..fb69ca20 --- /dev/null +++ b/app/assets/embed.go @@ -0,0 +1,21 @@ +//go:build production + +package assets + +import ( + "embed" + "io/fs" + "net/http" + "time" +) + +//go:embed all:dist +var dist embed.FS + +func Handler() http.Handler { + sub, err := fs.Sub(dist, "dist") + if err != nil { + panic(err) // can't fail, because the embed directive includes dist + } + return newCompressed(sub, time.Now()) +} diff --git a/app/assets/readfile.go b/app/assets/readfile.go new file mode 100644 index 00000000..da64404b --- /dev/null +++ b/app/assets/readfile.go @@ -0,0 +1,19 @@ +package assets + +import ( + "io/fs" + "path" +) + +// readFile reads a regular file from tree. A directory is reported as not found. +func readFile(tree fs.FS, name string) ([]byte, error) { + name = path.Clean(name) + st, err := fs.Stat(tree, name) + if err != nil { + return nil, err + } + if st.IsDir() { + return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist} + } + return fs.ReadFile(tree, name) +} diff --git a/app/autostart/appimage_linux.go b/app/autostart/appimage_linux.go new file mode 100644 index 00000000..8eeb3809 --- /dev/null +++ b/app/autostart/appimage_linux.go @@ -0,0 +1,27 @@ +package autostart + +import ( + "os" + "path/filepath" + "strings" +) + +// appImage returns $APPIMAGE when this process runs from that AppImage's mount ($APPDIR), using +// the same rule as pathlink. It returns "" for any other install. +func appImage() string { + img, dir := os.Getenv("APPIMAGE"), os.Getenv("APPDIR") + if img == "" || dir == "" { + return "" + } + exe, err := os.Executable() + if err != nil { + return "" + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + if !strings.HasPrefix(exe, filepath.Clean(dir)+"/") { + return "" + } + return img +} diff --git a/app/autostart/appimage_other.go b/app/autostart/appimage_other.go new file mode 100644 index 00000000..11513a2f --- /dev/null +++ b/app/autostart/appimage_other.go @@ -0,0 +1,5 @@ +//go:build !linux + +package autostart + +func appImage() string { return "" } diff --git a/app/autostart/autostart.go b/app/autostart/autostart.go new file mode 100644 index 00000000..6bada5d4 --- /dev/null +++ b/app/autostart/autostart.go @@ -0,0 +1,97 @@ +// Package autostart starts the app at login through Wails' autostart, which uses SMAppService or a +// LaunchAgent on macOS, HKCU\…\Run on Windows, and an XDG autostart entry on Linux. +// +// Under an AppImage, this package writes the XDG entry itself (see entry.go), because Wails' entry +// names the executable inside the AppImage's mount, which has a new path at every start. It does +// the same under Flatpak, writing to the host's autostart folder, because Wails' entry would end +// up in the sandbox's config folder, which the session never reads. +package autostart + +import ( + "crypto/sha256" + "encoding/hex" + "path/filepath" + "strings" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/datadir" +) + +// Identifier is the name of the app's registration. It is the launchd label (the bundle's +// SMAppService entry doesn't need one), the Run value on Windows, and the .desktop file name on +// Linux. +const Identifier = "org.rclone.ui" + +// identifier returns the name of this copy's registration. A portable copy gets a name of its own +// (portableIdentifier), because Windows keeps one Run value per name. With the app's name, +// turning on Start at login in a portable copy would replace an installed copy's entry, and the +// other way round. +func identifier() string { + if root, ok := datadir.Portable(); ok { + return portableIdentifier(root) + } + return Identifier +} + +// portableIdentifier names the registration of the portable copy in root after a hash of the +// folder, so that every portable copy has its own. Windows ignores the case of a path, so the +// hash does too. +func portableIdentifier(root string) string { + sum := sha256.Sum256([]byte(strings.ToLower(filepath.Clean(root)))) + return Identifier + ".portable-" + hex.EncodeToString(sum[:4]) +} + +// own returns the entry that this package writes itself (see entry.go), or nil where Wails' +// registration starts the app. +func own() (*entry, error) { + var e entry + var err error + switch img := appImage(); { + case img != "": + e, err = appImageEntry(img) + case platform.IsFlatpak(): + e, err = flatpakEntry() + default: + return nil, nil + } + if err != nil { + return nil, err + } + return &e, nil +} + +func Enable(app *application.App) error { + e, err := own() + if err != nil { + return err + } + if e != nil { + return e.write() + } + return app.Autostart.EnableWithOptions(application.AutostartOptions{Identifier: identifier()}) +} + +func Disable(app *application.App) error { + e, err := own() + if err != nil { + return err + } + if e == nil { + return app.Autostart.Disable() + } + return e.remove() +} + +func IsEnabled(app *application.App) (bool, error) { + e, err := own() + switch { + case err != nil: + return false, err + case e != nil: + return e.enabled() + default: + return app.Autostart.IsEnabled() + } +} diff --git a/app/autostart/autostart_test.go b/app/autostart/autostart_test.go new file mode 100644 index 00000000..bbc3d271 --- /dev/null +++ b/app/autostart/autostart_test.go @@ -0,0 +1,24 @@ +package autostart + +import ( + "path/filepath" + "strings" + "testing" +) + +func TestPortableIdentifier(t *testing.T) { + root := t.TempDir() + a := portableIdentifier(filepath.Join(root, "Rclone UI")) + b := portableIdentifier(filepath.Join(root, "Other copy")) + if a == b || a == Identifier || !strings.HasPrefix(a, Identifier+".portable-") { + t.Fatalf("names %q and %q", a, b) + } + if again := portableIdentifier(filepath.Join(root, "RCLONE UI")); again != a { + t.Errorf("the same folder in capitals: %q, want %q", again, a) + } + for _, r := range a { + if !strings.ContainsRune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-", r) { + t.Fatalf("%q has %q, which Wails refuses", a, r) + } + } +} diff --git a/app/autostart/entry.go b/app/autostart/entry.go new file mode 100644 index 00000000..957fa269 --- /dev/null +++ b/app/autostart/entry.go @@ -0,0 +1,152 @@ +package autostart + +import ( + "errors" + "os" + "path/filepath" + "strings" + + "github.com/rclone/rclone-ui/app/deeplink" + "github.com/rclone/rclone-ui/app/platform" +) + +// This file writes the XDG autostart entries that this package manages itself (see the package +// comment). Under an AppImage, it is the file that Wails would write, +// /autostart/org.rclone.ui.desktop, but with the AppImage in Exec. +// Under Flatpak, the entry goes in the host's autostart folder (the startup gate asks for access +// to it, see platform.FlatpakMissing). It starts the app through flatpak run, because +// /app/bin/rcui exists only inside the sandbox. The code builds on every OS so that the tests run +// everywhere. + +type entry struct { + file string + argv []string +} + +// configDir is the XDG config folder: $XDG_CONFIG_HOME, or ~/.config. +func configDir(xdgConfigHome string) (string, error) { + if xdgConfigHome != "" { + return xdgConfigHome, nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".config"), nil +} + +// entryFile returns the path of the entry that Wails writes, which is also the one written under +// an AppImage. +func entryFile() (string, error) { + dir, err := configDir(os.Getenv("XDG_CONFIG_HOME")) + if err != nil { + return "", err + } + return filepath.Join(dir, "autostart", Identifier+".desktop"), nil +} + +func appImageEntry(img string) (entry, error) { + file, err := entryFile() + if err != nil { + return entry{}, err + } + return entry{file: file, argv: []string{img}}, nil +} + +// flatpakEntry returns an entry in the host's autostart folder that starts the Flatpak at login. +// When the session sets XDG_CONFIG_HOME, Flatpak passes it in as HOST_XDG_CONFIG_HOME, and $HOME +// is the host's. The file is .flatpak.desktop, so that it never is the entry of a +// package install of the app (org.rclone.ui.desktop), which has the same ID. +func flatpakEntry() (entry, error) { + dir, err := configDir(os.Getenv("HOST_XDG_CONFIG_HOME")) + if err != nil { + return entry{}, err + } + id := os.Getenv("FLATPAK_ID") + if id == "" { + id = platform.FlatpakAppID + } + return entry{ + file: filepath.Join(dir, "autostart", id+".flatpak.desktop"), + argv: []string{"flatpak", "run", id}, + }, nil +} + +func (e entry) execLine() string { + quoted := make([]string, len(e.argv)) + for i, a := range e.argv { + quoted[i] = deeplink.QuoteExec(a) + } + return "Exec=" + strings.Join(quoted, " ") +} + +func (e entry) write() error { + if err := os.MkdirAll(filepath.Dir(e.file), 0o755); err != nil { + return err + } + contents := strings.Join([]string{ + "[Desktop Entry]", + "Type=Application", + "Name=Rclone UI", + e.execLine(), + "X-GNOME-Autostart-enabled=true", + "Hidden=false", + "NoDisplay=false", + "Terminal=false", + "", + }, "\n") + return os.WriteFile(e.file, []byte(contents), 0o644) +} + +// remove removes the entry. A missing entry is not an error. +func (e entry) remove() error { return removeFile(e.file) } + +func removeFile(file string) error { + if err := os.Remove(file); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +// enabled reports whether the entry runs its command line at login. That means the file exists +// with that Exec line, and the desktop hasn't turned it off. +func (e entry) enabled() (bool, error) { + b, err := os.ReadFile(e.file) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + contents := string(b) + has := false + for line := range strings.SplitSeq(contents, "\n") { + if strings.TrimSpace(line) == e.execLine() { + has = true + break + } + } + return has && !disabled(contents), nil +} + +// disabled reports whether a desktop turned an autostart entry off, either with Hidden=true (the +// XDG way) or with X-GNOME-Autostart-enabled=false (GNOME's switches). +func disabled(contents string) bool { + for line := range strings.SplitSeq(contents, "\n") { + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + switch key, value = strings.TrimSpace(key), strings.TrimSpace(value); key { + case "Hidden": + if value == "true" { + return true + } + case "X-GNOME-Autostart-enabled": + if value == "false" { + return true + } + } + } + return false +} diff --git a/app/autostart/entry_test.go b/app/autostart/entry_test.go new file mode 100644 index 00000000..6c7adc5f --- /dev/null +++ b/app/autostart/entry_test.go @@ -0,0 +1,103 @@ +package autostart + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestAppImageEntry(t *testing.T) { + config := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", config) + file := filepath.Join(config, "autostart", "org.rclone.ui.desktop") + img := "/home/me/My Apps/Rclone UI 100%.AppImage" + e, err := appImageEntry(img) + if err != nil { + t.Fatal(err) + } + if e.file != file { + t.Fatalf("the entry is at %s", e.file) + } + if on, err := e.enabled(); err != nil || on { + t.Fatalf("no entry: %v, %v", on, err) + } + if err := e.write(); err != nil { + t.Fatal(err) + } + if on, err := e.enabled(); err != nil || !on { + t.Fatalf("written: %v, %v", on, err) + } + other, _ := appImageEntry("/home/me/Other.AppImage") + if on, _ := other.enabled(); on { + t.Error("the entry starts another AppImage") + } + b, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + contents := string(b) + if !strings.Contains(contents, "\nExec=\"/home/me/My Apps/Rclone UI 100%%.AppImage\"\n") { + t.Errorf("the entry is\n%s", contents) + } + for _, off := range [][2]string{ + {"Hidden=false", "Hidden=true"}, + {"X-GNOME-Autostart-enabled=true", "X-GNOME-Autostart-enabled=false"}, + } { + if err := os.WriteFile(file, []byte(strings.Replace(contents, off[0], off[1], 1)), 0o644); err != nil { + t.Fatal(err) + } + if on, err := e.enabled(); err != nil || on { + t.Errorf("%s: %v, %v", off[1], on, err) + } + } + if err := e.remove(); err != nil { + t.Fatal(err) + } + if on, err := e.enabled(); err != nil || on { + t.Errorf("removed: %v, %v", on, err) + } + if err := e.remove(); err != nil { + t.Errorf("removing no entry: %v", err) + } +} + +func TestFlatpakEntry(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) // os.UserHomeDir on Windows + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".var", "app", "org.rclone.ui", "config")) + t.Setenv("HOST_XDG_CONFIG_HOME", "") + t.Setenv("FLATPAK_ID", "org.rclone.ui") + + e, err := flatpakEntry() + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(home, ".config", "autostart", "org.rclone.ui.flatpak.desktop"); e.file != want { + t.Errorf("the entry is at %s, want %s", e.file, want) + } + if err := e.write(); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(e.file) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), "\nExec=\"flatpak\" \"run\" \"org.rclone.ui\"\n") { + t.Errorf("the entry is\n%s", b) + } + if on, err := e.enabled(); err != nil || !on { + t.Errorf("written: %v, %v", on, err) + } + // An entry that Wails wrote in the sandbox doesn't count as the host's entry. + sandbox, _ := appImageEntry("/app/bin/rcui") + if on, _ := sandbox.enabled(); on { + t.Error("the sandbox has an entry") + } + + t.Setenv("HOST_XDG_CONFIG_HOME", filepath.Join(home, "conf")) + if e, _ := flatpakEntry(); e.file != filepath.Join(home, "conf", "autostart", "org.rclone.ui.flatpak.desktop") { + t.Errorf("with the host's XDG_CONFIG_HOME the entry is at %s", e.file) + } +} diff --git a/app/build_dev.go b/app/build_dev.go new file mode 100644 index 00000000..9a64b7b7 --- /dev/null +++ b/app/build_dev.go @@ -0,0 +1,123 @@ +//go:build !production + +package app + +import ( + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/windows" +) + +// production is true in a release build, which embeds the pages, has no devtools and registers +// deep links. +const production = false + +func (u *ui) devServices() []application.Service { + return []application.Service{service(u, &DevService{})} +} + +// testFeed returns the update feed that a development build checks in place of the real one +// (RCUI_UPDATE_FEED), or "" for none. +func testFeed() string { return os.Getenv("RCUI_UPDATE_FEED") } + +// DevService answers the pages' own dialogs in a development run that a script drives (see +// devEval). A release build doesn't have it. +type DevService struct{} + +// scriptedAnswer, when set, answers the pages' own dialogs. It returns the next line of the +// answers file, and false when there is none. +var scriptedAnswer func(title, message string, prompt bool) (string, bool) + +// Scripted returns the answer that the script gives to a page's dialog: ok, cancel, extra or +// text:. It returns nil when no script answers, and the page then waits for the user. +func (s *DevService) Scripted(title, message string, prompt bool) *string { + if scriptedAnswer == nil { + return nil + } + if answer, ok := scriptedAnswer(title, message, prompt); ok { + return &answer + } + return nil +} + +// devEval runs scripts dropped in RCUI_DEV_EVAL in a window's page, so that a development run can +// be driven without the mouse. A file named ..js runs once in that window and is +// then removed. When the name has no dot before .js, it runs in the window of the --open route. +// What a script logs reaches the UI's log through the pages' console forwarding. +func (u *ui) devEval() { + if d := os.Getenv("RCUI_DEV_LAUNCHER"); d != "" { + u.launcher.DevScript(d) + } + dir := os.Getenv("RCUI_DEV_EVAL") + if dir == "" { + return + } + if err := os.MkdirAll(dir, 0o700); err != nil { + u.log.Error("dev eval", "error", err) + return + } + // Dialogs are answered from /answers, one line per dialog, in order. Each line is ok, + // cancel, extra, or text: for a prompt. When no lines are left, a native dialog gets + // cancel. A page's own dialog stays open instead, so that a script can press its buttons. + var mu sync.Mutex + next := func(title, message string, prompt bool) string { + mu.Lock() + defer mu.Unlock() + answer := "" + path := filepath.Join(dir, "answers") + if b, err := os.ReadFile(path); err == nil { + lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n") + if len(lines) > 0 && lines[0] != "" { + answer = lines[0] + _ = os.WriteFile(path, []byte(strings.Join(lines[1:], "\n")), 0o600) + } + } + u.log.Info("dev eval: dialog", "title", title, "message", message, "prompt", prompt, "answer", answer) + return answer + } + scriptedAnswer = func(title, message string, prompt bool) (string, bool) { + answer := next(title, message, prompt) + return answer, answer != "" + } + interaction.Scripted = func(d interaction.Dialog, prompt bool) (interaction.Answer, string) { + answer := next(d.Title, d.Message, prompt) + switch { + case strings.HasPrefix(answer, "text:"): + return interaction.AnswerOK, strings.TrimPrefix(answer, "text:") + case answer == "ok": + return interaction.AnswerOK, "" + case answer == "extra": + return interaction.AnswerExtra, "" + } + return interaction.AnswerCancel, "" + } + go func() { + for range time.Tick(300 * time.Millisecond) { + files, _ := filepath.Glob(filepath.Join(dir, "*.js")) + for _, f := range files { + code, err := os.ReadFile(f) + _ = os.Remove(f) + if err != nil { + continue + } + name, _ := windows.ForRoute(u.opts.open) + if base := strings.TrimSuffix(filepath.Base(f), ".js"); strings.Contains(base, ".") { + name = base[:strings.Index(base, ".")] + } + w, ok := u.windows.Get(name) + if !ok { + u.log.Warn("dev eval: no such window", "window", name) + continue + } + w.ExecJS("(async () => { try { " + string(code) + " } catch (e) { console.error('[eval]', String(e && e.stack || e)) } })()") + } + } + }() +} diff --git a/app/build_production.go b/app/build_production.go new file mode 100644 index 00000000..340e1532 --- /dev/null +++ b/app/build_production.go @@ -0,0 +1,16 @@ +//go:build production + +package app + +import "github.com/wailsapp/wails/v3/pkg/application" + +// production is true in a release build, which embeds the pages, has no devtools and registers +// deep links. +const production = true + +func (u *ui) devEval() {} + +func (u *ui) devServices() []application.Service { return nil } + +// testFeed returns "", because a release build always checks the real update feed. +func testFeed() string { return "" } diff --git a/app/configunlock.go b/app/configunlock.go new file mode 100644 index 00000000..4ff49041 --- /dev/null +++ b/app/configunlock.go @@ -0,0 +1,51 @@ +package app + +import ( + "context" + "time" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/core/config" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/rclone" +) + +// unlockConfig asks for the config's password when the core started with an encrypted config +// file and has no saved password or password command for it. If the user cancels, the config +// stays locked. It can be unlocked later with the Remotes window's config file button. +func (u *ui) unlockConfig(ctx context.Context) { + api := u.apis.Config + ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) + defer cancel() + c, err := api.Get(ctx) + if err != nil { + u.log.Warn("could not read the config", "error", err) + return + } + if c.Status != config.StatusNeedsPassword { + return + } + // Windows' prompt shows one line of about 45 characters, so the message is short, and a retry + // shows only why the password failed. + message := i18n.T("Enter the password of your rclone config.") + // i18n: The title of the prompt for the password that encrypts the rclone config file. + title := i18n.T("Config Password") + for { + password, ok, err := interaction.Prompt(title, message, "", true) + if err != nil || !ok || password == "" { + return + } + if _, err := api.Unlock(ctx, password, false); err != nil { + message = rclone.ErrorOf(err).Localized().Message + continue + } + // i18n: Asked after the config was unlocked. The buttons are "Save" and "Don't save". + save := i18n.T("Save the password in the system keychain?") + if interaction.Ask(interaction.Question, title, save, i18n.T("Save"), i18n.T("Don't save")) { + if _, err := api.Unlock(ctx, password, true); err != nil { + u.log.Warn("could not save the config password", "error", err) + } + } + return + } +} diff --git a/app/core.go b/app/core.go new file mode 100644 index 00000000..aa5baed6 --- /dev/null +++ b/app/core.go @@ -0,0 +1,222 @@ +package app + +import ( + "context" + "errors" + "os" + "os/exec" + "strconv" + "sync" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/db" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/version" +) + +// coreHost holds the core, which runs in this process. It is started once the app runs and +// stopped once as the app exits. +type coreHost struct { + mu sync.Mutex + core *core.Core + status CoreStatus + // failed is why the core couldn't start, which the status gives in the app's language. + failed error + // stopEvents stops passing the core's events on. + stopEvents func() +} + +func (u *ui) startCore() { + u.setCoreStatus(CoreStatus{State: CoreStarting}) + var hostEnv []string + if platform.AppDir() != "" { + hostEnv = platform.HostEnv() + } + c, err := core.Start(core.Options{ + DataDir: u.opts.dataDir, + RunDir: os.Getenv("APP_RUN_DIR"), + Log: u.logs, + HostEnv: hostEnv, + APIs: u.apis, + }) + if err != nil { + u.coreFailed(err) + return + } + u.cores.mu.Lock() + u.cores.core = c + u.cores.stopEvents = c.Subscribe(u.coreEvent) + u.cores.mu.Unlock() + u.setCoreStatus(CoreStatus{State: CoreReady, Version: version.App}) + u.coreReady() + if crashed, interrupted := c.Crashed(); crashed { + go u.crashNotice(interrupted) + } +} + +// coreFailed shows why the core can't run and offers to start the app again or to quit. Starting +// again means a new process, because the state rclone set up in this one would remain. +func (u *ui) coreFailed(err error) { + u.log.Error("the core can't run", "error", err) + // The Startup window shows the error, so it is in the app's language. + u.cores.mu.Lock() + u.cores.failed = err + u.cores.mu.Unlock() + u.setCoreStatus(CoreStatus{State: CoreFailed, Error: i18n.Localize(err)}) + u.coreDown() + u.showStartup() + u.updates.startUp() + title := i18n.T("Rclone UI Can't Start") + switch failedChoice(err) { + case showDataFolder: + if interaction.Ask(interaction.Error, title, i18n.Localize(err), i18n.T("Show Data Folder"), i18n.T("Quit")) { + // The app quits after showing the folder, because the folder can't be deleted while + // the app keeps its log and its lock there. + if err := u.reveal(u.dataDir, true); err != nil { + u.log.Error("could not show the data folder", "error", err) + } + } + case tryAgain: + if interaction.Ask(interaction.Error, title, i18n.Localize(err), i18n.T("Try Again"), i18n.T("Quit")) { + u.relaunch("") + return + } + } + u.quit(true) +} + +const ( + tryAgain = "try again" + showDataFolder = "show data folder" +) + +// failedChoice picks what coreFailed's dialog offers besides quitting. A database made with +// another schema fails at every start until its data folder is deleted, so trying again would +// only fail again. +func failedChoice(err error) string { + if errors.Is(err, db.ErrSchemaChanged) { + return showDataFolder + } + return tryAgain +} + +// coreReady runs once the core is ready. The settings decide the shortcut, the tray icon, the +// update channel and whether the startup window shows. A proxy that can't connect is reported +// first. +func (u *ui) coreReady() { + go func() { + u.loadSettings(context.Background()) + u.checkProxy(context.Background()) + u.updates.startUp() + u.firstReady.Do(u.showStartup) + u.unlockConfig(context.Background()) + }() + u.store.CoreReady(context.Background()) + u.launcher.CoreReady() +} + +// crashNotice reports that the previous run quit unexpectedly, and how many transfers it +// interrupted. A click opens History. +func (u *ui) crashNotice(interrupted int) { + // i18n: The body of the notification that Rclone UI quit unexpectedly: it is running again. + body := i18n.T("It was started again.") + if interrupted > 0 { + body = i18n.N("%d transfer was interrupted.", "%d transfers were interrupted.", interrupted, interrupted) + } + u.notifier.show(toast{title: i18n.T("Rclone UI quit unexpectedly"), body: body, route: "/history"}) +} + +// stopCore stops the core once, for a quit, an update or the end of the session. With restart +// set, the core records what is running so that it comes back at the next start. +func (u *ui) stopCore(ctx context.Context, restart bool) { + u.cores.mu.Lock() + c, stop := u.cores.core, u.cores.stopEvents + u.cores.mu.Unlock() + if c == nil { + return + } + if stop != nil { + stop() + } + u.coreDown() + c.Shutdown(ctx, restart) + u.setCoreStatus(CoreStatus{State: CoreStopped}) +} + +// theCore returns the running core. It is nil before the core starts, or when it failed. +func (u *ui) theCore() *core.Core { + u.cores.mu.Lock() + defer u.cores.mu.Unlock() + return u.cores.core +} + +// CoreState is the state of the core that the windows see. It is a named type, so the bindings +// give the pages an enum to compare with. +type CoreState string + +const ( + CoreStarting CoreState = "starting" + CoreReady CoreState = "ready" + CoreFailed CoreState = "failed" + CoreStopped CoreState = "stopped" +) + +func (u *ui) setCoreStatus(s CoreStatus) { + u.cores.mu.Lock() + u.cores.status = s + u.cores.mu.Unlock() + // The error is logged in English where it happens (see coreFailed), and s has it in the app's + // language for the Startup window. + u.log.Info("core", "state", s.State) + u.app.Event.Emit(EventCoreState, s) +} + +// coreStatus returns the core's state, with its error in the app's language of the moment. +func (u *ui) coreStatus() CoreStatus { + u.cores.mu.Lock() + defer u.cores.mu.Unlock() + s := u.cores.status + if s.State == CoreFailed && u.cores.failed != nil { + s.Error = i18n.Localize(u.cores.failed) + } + return s +} + +func (u *ui) coreEvent(ev bus.Event) { + u.relayCoreEvent(ev) + u.store.Event(context.Background(), ev) + if d, ok := ev.Data.(bus.NotifyOSData); ok { + // The core has already decided that this toast shows. A toast that falls back to a dialog + // (see notifier.fallBack) waits for the user, so it is shown in a goroutine. + go u.notifier.show(toast{title: d.Title, body: d.Body, route: d.Route, toastOnly: d.ToastOnly}) + } + switch ev.Name { + case bus.SettingsChanged, bus.Resync: + go u.loadSettings(context.Background()) + } +} + +// relaunch starts a new process that waits for this one to exit, then quits this one. The new +// process opens the route in open, or no window if it is "". The core stops as the app exits, +// as it does for a quit. +func (u *ui) relaunch(open string) { + args := []string{"ui", "--hidden", "--after", strconv.Itoa(os.Getpid())} + if u.opts.dataDir != "" { + args = append(args, "--data-dir", u.opts.dataDir) + } + if open != "" { + args = append(args, "--open", open) + } + cmd := exec.Command(u.exe, args...) + cmd.SysProcAttr = platform.DetachedProcess() + if err := cmd.Start(); err != nil { + u.log.Error("could not start the app again", "error", err) + interaction.Message(interaction.Error, "Rclone UI", i18n.T("Rclone UI could not start again: %v. Start it yourself.", err)) + } else { + _ = cmd.Process.Release() + } + u.quit(true) +} diff --git a/app/core_test.go b/app/core_test.go new file mode 100644 index 00000000..e018ef31 --- /dev/null +++ b/app/core_test.go @@ -0,0 +1,40 @@ +package app + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "testing" + + "github.com/rclone/rclone-ui/core/db" +) + +// TestSchemaChangeOffersTheDataFolder uses the error that db.Open returns for a file without the +// schema's hash, wrapped as the core's boot wraps it. +func TestSchemaChangeOffersTheDataFolder(t *testing.T) { + path := filepath.Join(t.TempDir(), "app.db") + d, err := db.Open(context.Background(), path) + if err != nil { + t.Fatal(err) + } + if _, err := d.W.Exec(`DELETE FROM meta WHERE key = 'schema'`); err != nil { + t.Fatal(err) + } + if err := d.Close(); err != nil { + t.Fatal(err) + } + _, err = db.Open(context.Background(), path) + if err == nil { + t.Fatal("a file without the schema's hash was opened") + } + if got := failedChoice(fmt.Errorf("database: %w", err)); got != showDataFolder { + t.Fatalf("a changed schema offers %q", got) + } + if got := failedChoice(fmt.Errorf("database: %w", db.ErrNotWAL)); got != tryAgain { + t.Fatalf("another failure offers %q", got) + } + if got := failedChoice(errors.New("run directory: denied")); got != tryAgain { + t.Fatalf("another failure offers %q", got) + } +} diff --git a/app/corestate/corestate.go b/app/corestate/corestate.go new file mode 100644 index 00000000..ab773428 --- /dev/null +++ b/app/corestate/corestate.go @@ -0,0 +1,459 @@ +// Package corestate keeps the shell's one copy of what the core runs: the remotes, the mounts, +// serves, VFS caches and tunnel, the transfers with their progress, and the serve types. The tray +// and the launcher both read it. The core's events trigger a read of the part they changed, and +// each subscriber is told which parts changed. +package corestate + +import ( + "context" + "fmt" + "log/slog" + "maps" + "runtime/debug" + "slices" + "sync" + "sync/atomic" + "time" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/vfs" +) + +type Reader interface { + Remotes(ctx context.Context) ([]engine.Remote, error) + Mounts(ctx context.Context) ([]mounts.MountRow, error) + Serves(ctx context.Context) ([]serves.ServeRow, error) + Vfs(ctx context.Context) ([]vfs.VFS, error) + // Tunnel reports whether the remote tunnel is on or starting. + Tunnel(ctx context.Context) (bool, error) + ActiveTransfers(ctx context.Context) ([]transfers.Transfer, error) + // EndedTransfers returns the last limit transfers that ended, newest first. + EndedTransfers(ctx context.Context, limit int) ([]transfers.Transfer, error) + ServeTypes(ctx context.Context) ([]string, error) +} + +// Part is a set of the parts of the state, which tells a subscriber what changed. +type Part uint8 + +const ( + Remotes Part = 1 << iota + // Running are the mounts, the serves, the VFS caches and the tunnel. + Running + // Transfers are the open transfers and the recent failed ones. + Transfers + // Progress is the running transfers' progress, which the core reports every second. + Progress + // Types are the serve types. + Types + + All = Remotes | Running | Transfers | Progress | Types +) + +// Snapshot is the state as last read. Its slices and map are never changed once they are in a +// snapshot, so a caller can keep them, but must not change them. +type Snapshot struct { + // Ready is true while the core is running. Everything else is empty while it isn't. + Ready bool + Remotes []engine.Remote + Mounts []mounts.MountRow + Serves []serves.ServeRow + Vfs []vfs.VFS + // Tunnel is true while the remote tunnel is on or starting. + Tunnel bool + // Transfers are the queued and running transfers, with their latest progress (Live). + Transfers []transfers.Transfer + // Failed are the transfers that failed among the last ones to end, newest first. + Failed []transfers.Transfer + // Live is the latest progress of the running transfers, by id. An entry goes once its + // transfer has ended. + Live map[string]bus.TransferProgress + ServeTypes []string + // Loaded is when the whole state was last read. + Loaded time.Time +} + +const ( + callTimeout = 10 * time.Second + // endedRead is how many of the last ended transfers are read to find the failed ones. + endedRead = 20 +) + +type Store struct { + r Reader + log *slog.Logger + + // Only one read of each kind runs at a time, so an older result never overwrites a newer one. + remotesRead, runningRead, transfersRead serial + + mu sync.Mutex + // run counts the core's runs, so the result of a read from a run that has ended is + // discarded. snap.Ready is true while the core is running. + run uint64 + snap Snapshot + + // subs are called in turn on one goroutine (dispatch) with the parts that changed since + // their last call. pending gathers those parts, and wake starts the next round. + subs []subscriber + nextSub int + pending Part + wake chan struct{} + dispatch sync.Once +} + +type subscriber struct { + id int + fn func(changed Part) +} + +// New creates a Store that reads from r. Nothing is read until CoreReady. +func New(r Reader, log *slog.Logger) *Store { + return &Store{r: r, log: log, wake: make(chan struct{}, 1)} +} + +func (s *Store) CoreReady(ctx context.Context) { + s.mu.Lock() + s.snap.Ready = true + s.run++ + s.mu.Unlock() + s.spawn("ready", func() { s.refresh(ctx) }) +} + +// CoreDown clears everything read from the core when the core stops or fails. Whatever was +// running stopped with it, so nothing is listed as running until CoreReady. A read that is still +// in flight is discarded, because its run is over. +func (s *Store) CoreDown() { + s.mu.Lock() + s.run++ + s.snap = Snapshot{} + s.mu.Unlock() + s.notify(All) +} + +// Event handles an event from the core, which the app passes on. The part of the state that the +// event changed is read again. A progress event is merged into the transfers at once. +func (s *Store) Event(ctx context.Context, ev bus.Event) { + if ev.Name == bus.TransfersProgress { + if d, ok := ev.Data.(bus.TransfersProgressData); ok { + s.setProgress(d.Items) + } + return + } + s.spawn("changed", func() { s.changed(ctx, ev.Name) }) +} + +func (s *Store) Snapshot() Snapshot { + s.mu.Lock() + defer s.mu.Unlock() + return s.snap +} + +func (s *Store) RefreshIfOlder(ctx context.Context, age time.Duration) { + s.mu.Lock() + stale := s.snap.Ready && time.Since(s.snap.Loaded) > age + s.mu.Unlock() + if stale { + s.spawn("refresh", func() { s.refresh(ctx) }) + } +} + +// Subscribe calls fn with the parts that changed, each time the state changes, until stop is +// called. Every subscriber is called in turn on one goroutine, and changes that come while it +// runs are gathered into its next call. fn reads Snapshot for the state, so its last call always +// shows the latest state. +func (s *Store) Subscribe(fn func(changed Part)) (stop func()) { + s.mu.Lock() + id := s.nextSub + s.nextSub++ + s.subs = append(s.subs, subscriber{id: id, fn: fn}) + s.mu.Unlock() + s.dispatch.Do(func() { go s.dispatchLoop() }) + return func() { + s.mu.Lock() + defer s.mu.Unlock() + s.subs = slices.DeleteFunc(s.subs, func(sub subscriber) bool { return sub.id == id }) + } +} + +func (s *Store) notify(p Part) { + s.mu.Lock() + s.pending |= p + s.mu.Unlock() + select { + case s.wake <- struct{}{}: + default: // a round is already due, and it will see p + } +} + +func (s *Store) dispatchLoop() { + for range s.wake { + s.mu.Lock() + p := s.pending + s.pending = 0 + subs := slices.Clone(s.subs) + s.mu.Unlock() + if p == 0 { + continue + } + for _, sub := range subs { + s.call(sub.fn, p) + } + } +} + +// call calls a subscriber. A panic there would end the app, so it is logged instead. +func (s *Store) call(fn func(Part), p Part) { + defer func() { + if v := recover(); v != nil { + s.log.Error("a subscriber of the core's state panicked", "panic", fmt.Sprint(v), "stack", string(debug.Stack())) + } + }() + fn(p) +} + +// spawn runs fn on its own goroutine. An unrecovered panic there would end the app, so spawn +// logs it instead, and only fn's work is lost. +func (s *Store) spawn(name string, fn func()) { + go func() { + defer func() { + if v := recover(); v != nil { + s.log.Error("the core's state recovered from a panic", "where", name, "panic", fmt.Sprint(v), "stack", string(debug.Stack())) + } + }() + fn() + }() +} + +func (s *Store) changed(ctx context.Context, name string) { + switch name { + case bus.RemotesChanged: + s.refreshRemotes(ctx) + case bus.MountsChanged, bus.ServesChanged, bus.TunnelChanged: + s.refreshRunning(ctx) + case bus.TransfersChanged: + s.refreshTransfers(ctx) + case bus.Resync, bus.ConfigChanged: + s.refresh(ctx) + } +} + +func (s *Store) setProgress(items map[string]bus.TransferProgress) { + s.mu.Lock() + if !s.snap.Ready { + s.mu.Unlock() + return + } + live := maps.Clone(s.snap.Live) + if live == nil { + live = make(map[string]bus.TransferProgress, len(items)) + } + maps.Copy(live, items) + s.snap.Live = live + s.snap.Transfers, _ = withProgress(s.snap.Transfers, items) + s.mu.Unlock() + s.notify(Progress) +} + +// withProgress returns ts with the progress from items added. A queued transfer that has progress +// is marked as running. Transfers missing from items stay as they are, and the next read of the +// transfers drops the ones that ended. changed is false when no transfer had progress. +func withProgress(ts []transfers.Transfer, items map[string]bus.TransferProgress) (out []transfers.Transfer, changed bool) { + out = make([]transfers.Transfer, len(ts)) + for i, t := range ts { + out[i] = t + p, ok := items[t.ID] + if !ok { + continue + } + out[i].Live = &p + if t.State == transfers.StateQueued { + out[i].State = transfers.StateRunning + } + changed = true + } + return out, changed +} + +// liveOf returns the progress of the open transfers ts: what the read found, or else the latest +// progress from before for a transfer that is still open. The entries of the transfers that ended +// are dropped. +func liveOf(ts []transfers.Transfer, before map[string]bus.TransferProgress) map[string]bus.TransferProgress { + live := make(map[string]bus.TransferProgress, len(ts)) + for _, t := range ts { + if t.Live != nil { + live[t.ID] = *t.Live + } else if p, ok := before[t.ID]; ok { + live[t.ID] = p + } + } + return live +} + +// current returns the core's current run, and whether the core is running. +func (s *Store) current() (run uint64, ok bool) { + s.mu.Lock() + defer s.mu.Unlock() + return s.run, s.snap.Ready +} + +// land stores the result of a read from run, if run is still the current one, and tells the +// subscribers that part changed. +func (s *Store) land(run uint64, part Part, set func(d *Snapshot)) { + s.mu.Lock() + ours := s.snap.Ready && s.run == run + if ours { + set(&s.snap) + } + s.mu.Unlock() + if ours { + s.notify(part) + } +} + +func (s *Store) refresh(ctx context.Context) { + run, ok := s.current() + if !ok { + return + } + s.refreshRemotes(ctx) + s.refreshRunning(ctx) + s.refreshTransfers(ctx) + s.refreshTypes(ctx) + s.mu.Lock() + if s.snap.Ready && s.run == run { + s.snap.Loaded = time.Now() + } + s.mu.Unlock() +} + +// serial runs one read of a kind at a time. A read requested while another runs waits for it. It +// is skipped if a newer read is requested in the meantime, because the newer read will see every +// change that the skipped one would have. +type serial struct { + mu sync.Mutex + gen atomic.Uint64 +} + +func (r *serial) do(read func()) { + gen := r.gen.Add(1) + r.mu.Lock() + defer r.mu.Unlock() + if r.gen.Load() != gen { + return + } + read() +} + +func (s *Store) refreshRemotes(ctx context.Context) { + s.remotesRead.do(func() { s.readRemotes(ctx) }) +} + +func (s *Store) readRemotes(ctx context.Context) { + run, ok := s.current() + if !ok { + return + } + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + remotes, err := s.r.Remotes(ctx) + if err != nil { + s.log.Debug("could not read the remotes", "error", err) + return + } + s.land(run, Remotes, func(d *Snapshot) { d.Remotes = remotes }) +} + +func (s *Store) refreshRunning(ctx context.Context) { + s.runningRead.do(func() { s.readRunning(ctx) }) +} + +func (s *Store) readRunning(ctx context.Context) { + run, ok := s.current() + if !ok { + return + } + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + ms, err := s.r.Mounts(ctx) + if err != nil { + s.log.Debug("could not read the mounts", "error", err) + return + } + ss, err := s.r.Serves(ctx) + if err != nil { + s.log.Debug("could not read the serves", "error", err) + return + } + caches, err := s.r.Vfs(ctx) + if err != nil { + s.log.Debug("could not read the VFS caches", "error", err) + return + } + tunnel, err := s.r.Tunnel(ctx) + if err != nil { + s.log.Debug("could not read the tunnel", "error", err) + return + } + s.land(run, Running, func(d *Snapshot) { d.Mounts, d.Serves, d.Vfs, d.Tunnel = ms, ss, caches, tunnel }) +} + +func (s *Store) refreshTransfers(ctx context.Context) { + s.transfersRead.do(func() { s.readTransfers(ctx) }) +} + +func (s *Store) readTransfers(ctx context.Context) { + run, ok := s.current() + if !ok { + return + } + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + active, err := s.r.ActiveTransfers(ctx) + if err != nil { + s.log.Debug("could not read the transfers", "error", err) + return + } + // if the ended transfers can't be read, keep the failed ones read before + var failed []transfers.Transfer + ended, endedErr := s.r.EndedTransfers(ctx, endedRead) + if endedErr != nil { + s.log.Debug("could not read the ended transfers", "error", endedErr) + } + for _, t := range ended { + if t.State == transfers.StateFailed { + failed = append(failed, t) + } + } + s.land(run, Transfers, func(d *Snapshot) { + d.Live = liveOf(active, d.Live) + d.Transfers, _ = withProgress(active, d.Live) + if endedErr == nil { + d.Failed = failed + } + }) +} + +// refreshTypes reads the serve types once in each of the core's runs, because they don't change. +func (s *Store) refreshTypes(ctx context.Context) { + run, ok := s.current() + if !ok { + return + } + s.mu.Lock() + known := s.snap.ServeTypes != nil + s.mu.Unlock() + if known { + return + } + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + types, err := s.r.ServeTypes(ctx) + if err != nil { + s.log.Debug("could not read the serve types", "error", err) + return + } + s.land(run, Types, func(d *Snapshot) { d.ServeTypes = types }) +} diff --git a/app/corestate/corestate_test.go b/app/corestate/corestate_test.go new file mode 100644 index 00000000..7aa3bd35 --- /dev/null +++ b/app/corestate/corestate_test.go @@ -0,0 +1,247 @@ +package corestate + +import ( + "context" + "log/slog" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/children" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/vfs" +) + +// fakeCore is a fake core. Its first Mounts call waits for release and returns a starting mount. +// Every later call returns the mount as running. Its transfers are what active holds. Everything +// else is empty. +type fakeCore struct { + calls atomic.Int32 + entered chan struct{} + release chan struct{} + + mu sync.Mutex + active []transfers.Transfer +} + +func (c *fakeCore) Mounts(context.Context) ([]mounts.MountRow, error) { + state := children.StatusRunning + if c.calls.Add(1) == 1 { + close(c.entered) + <-c.release + state = children.StatusStarting + } + return []mounts.MountRow{{ID: "m1", State: string(state)}}, nil +} + +func (c *fakeCore) ActiveTransfers(context.Context) ([]transfers.Transfer, error) { + c.mu.Lock() + defer c.mu.Unlock() + return c.active, nil +} + +func (*fakeCore) Remotes(context.Context) ([]engine.Remote, error) { return nil, nil } +func (*fakeCore) Serves(context.Context) ([]serves.ServeRow, error) { return nil, nil } +func (*fakeCore) Vfs(context.Context) ([]vfs.VFS, error) { return nil, nil } +func (*fakeCore) Tunnel(context.Context) (bool, error) { return false, nil } +func (*fakeCore) ServeTypes(context.Context) ([]string, error) { return nil, nil } +func (*fakeCore) EndedTransfers(context.Context, int) ([]transfers.Transfer, error) { + return nil, nil +} + +func newCore() *fakeCore { + return &fakeCore{entered: make(chan struct{}), release: make(chan struct{})} +} + +// ready returns a Store over c with the core running and nothing read yet. +func ready(c Reader) *Store { + s := New(c, slog.New(slog.DiscardHandler)) + s.snap.Ready, s.run = true, 1 + return s +} + +func eventually(t *testing.T, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("waited too long for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// TestRunningReadsInOrder: two changes in a row read the running items twice. The first read's +// older result never overwrites the second's. +func TestRunningReadsInOrder(t *testing.T) { + c := newCore() + s := ready(c) + + var wg sync.WaitGroup + wg.Go(func() { s.refreshRunning(context.Background()) }) + <-c.entered + wg.Go(func() { s.refreshRunning(context.Background()) }) + // the second read is requested before the first returns + time.Sleep(50 * time.Millisecond) + close(c.release) + wg.Wait() + + got := s.Snapshot().Mounts + if len(got) != 1 || got[0].State != string(children.StatusRunning) { + t.Fatalf("mounts %v, want m1 running", got) + } +} + +func TestCoreDownForgetsTheCore(t *testing.T) { + s := ready(newCore()) + s.snap.Mounts = []mounts.MountRow{{ID: "m0"}} + s.snap.Live = map[string]bus.TransferProgress{"t1": {Pct: 5}} + s.snap.Loaded = time.Now() + var told atomic.Uint32 + s.Subscribe(func(p Part) { told.Store(uint32(p)) }) + + s.CoreDown() + eventually(t, "the subscriber", func() bool { return Part(told.Load()) == All }) + if snap := s.Snapshot(); snap.Ready || len(snap.Mounts) != 0 || len(snap.Live) != 0 || !snap.Loaded.IsZero() { + t.Fatalf("after the core went: %+v", snap) + } +} + +// TestCoreDownDropsAReadInFlight: a read that began before the core stopped doesn't land, not +// even once the core is ready again, because it belongs to the run that ended. +func TestCoreDownDropsAReadInFlight(t *testing.T) { + c := newCore() + s := ready(c) + + var wg sync.WaitGroup + wg.Go(func() { s.readRunning(context.Background()) }) + <-c.entered + s.CoreDown() + s.mu.Lock() + s.snap.Ready, s.run = true, s.run+1 // the next run, without its own reads + s.mu.Unlock() + close(c.release) + wg.Wait() + + if got := s.Snapshot().Mounts; len(got) != 0 { + t.Fatalf("the old run's read landed: %v", got) + } +} + +// TestSubscriberSeesLatestSnapshot: a subscriber that is slow gets the changes made in the +// meantime in one later call, and that call's snapshot shows the latest state. +func TestSubscriberSeesLatestSnapshot(t *testing.T) { + s := ready(newCore()) + first := make(chan struct{}) + release := make(chan struct{}) + var mu sync.Mutex + var calls []Part + var last []int + s.Subscribe(func(p Part) { + mu.Lock() + calls = append(calls, p) + n := len(calls) + last = nil + for _, tr := range s.Snapshot().Transfers { + last = append(last, len(tr.Sources)) + } + mu.Unlock() + if n == 1 { + close(first) + <-release + } + }) + s.land(1, Remotes, func(*Snapshot) {}) + <-first + // three changes while the subscriber is busy + for n := 1; n <= 3; n++ { + s.land(1, Transfers, func(d *Snapshot) { + d.Transfers = []transfers.Transfer{{ID: "t1", Sources: make([]string, n)}} + }) + } + s.setProgress(map[string]bus.TransferProgress{"t1": {Pct: 7}}) + close(release) + eventually(t, "the second call", func() bool { + mu.Lock() + defer mu.Unlock() + return len(calls) == 2 + }) + time.Sleep(20 * time.Millisecond) + mu.Lock() + defer mu.Unlock() + if len(calls) != 2 || calls[0] != Remotes || calls[1] != Transfers|Progress { + t.Fatalf("calls %v", calls) + } + if len(last) != 1 || last[0] != 3 { + t.Fatalf("the last call saw %v, want the third transfers' read", last) + } + if p := s.Snapshot().Transfers[0].Live; p == nil || p.Pct != 7 { + t.Fatalf("the progress was not merged: %v", p) + } +} + +// TestTransfersChangedPrunesLive: when a transfer ends, the next read of the transfers drops its +// progress and keeps the progress of the transfers that still run. +func TestTransfersChangedPrunesLive(t *testing.T) { + c := newCore() + s := ready(c) + c.active = []transfers.Transfer{{ID: "t1", State: transfers.StateRunning}, {ID: "t2", State: transfers.StateQueued}} + s.readTransfers(context.Background()) + s.Event(context.Background(), bus.Event{Name: bus.TransfersProgress, Data: bus.TransfersProgressData{ + Items: map[string]bus.TransferProgress{"t1": {Pct: 40}, "t2": {Pct: 10}}, + }}) + snap := s.Snapshot() + if len(snap.Live) != 2 || snap.Transfers[1].State != transfers.StateRunning { + t.Fatalf("after the progress: %+v", snap) + } + + c.mu.Lock() + c.active = c.active[1:] // t1 ended + c.mu.Unlock() + s.Event(context.Background(), bus.Event{Name: bus.TransfersChanged, Data: bus.TransfersChangedData{ID: "t1", State: "completed"}}) + eventually(t, "the read of the transfers", func() bool { return len(s.Snapshot().Live) == 1 }) + snap = s.Snapshot() + if p, ok := snap.Live["t2"]; !ok || p.Pct != 10 || len(snap.Transfers) != 1 || snap.Transfers[0].Live == nil { + t.Fatalf("after t1 ended: %+v", snap) + } +} + +func TestWithProgress(t *testing.T) { + ts := []transfers.Transfer{ + {ID: "t1", State: transfers.StateRunning}, + {ID: "t2", State: transfers.StateQueued}, + {ID: "t3", State: transfers.StateQueued}, + } + out, changed := withProgress(ts, map[string]bus.TransferProgress{ + "t1": {Pct: 42}, + "t2": {Pct: 1}, + "gone": {Pct: 99}, + }) + if !changed || out[0].Live.Pct != 42 || out[1].Live.Pct != 1 || out[1].State != transfers.StateRunning { + t.Fatalf("changed %v: %v", changed, out) + } + if out[2].Live != nil || ts[0].Live != nil || ts[1].State != transfers.StateQueued { + t.Error("the rows read were changed, or an unnamed one given numbers") + } + if _, changed := withProgress(ts, map[string]bus.TransferProgress{"gone": {}}); changed { + t.Error("changed with no numbers for its rows") + } +} + +func TestSumProgress(t *testing.T) { + eta := int64(9) + if got := SumProgress([]*bus.TransferProgress{{Bytes: 1, TotalBytes: 4, Eta: &eta}, {}}); got.Pct != 25 || got.Left != 0 || got.Running != 2 { + t.Errorf("an unknown ETA: %+v", got) + } + if got := SumProgress([]*bus.TransferProgress{{Bytes: 1, TotalBytes: 4, Eta: &eta}}); got.Left != 9*time.Second { + t.Errorf("a known ETA: %+v", got) + } + if got := SumProgress([]*bus.TransferProgress{{}, nil}); got.Pct != -1 || got.Running != 1 { + t.Errorf("no totals: %+v", got) + } +} diff --git a/app/corestate/progress.go b/app/corestate/progress.go new file mode 100644 index 00000000..a400c45d --- /dev/null +++ b/app/corestate/progress.go @@ -0,0 +1,46 @@ +package corestate + +import ( + "time" + + "github.com/rclone/rclone-ui/core/bus" +) + +// Sum is the combined progress of the running transfers. +type Sum struct { + // Running is how many transfers have progress. + Running int + // Pct is the percentage of their bytes done, or -1 while none of them knows its total. + Pct int + // Speed is their combined speed in bytes per second. + Speed float64 + // Left is the time until the last of them ends, or 0 while any of them can't tell. + Left time.Duration +} + +func SumProgress(ps []*bus.TransferProgress) Sum { + out := Sum{Pct: -1} + var done, total, eta int64 + known := true + for _, p := range ps { + if p == nil { + continue + } + out.Running++ + done += p.Bytes + total += p.TotalBytes + out.Speed += p.Speed + if p.Eta != nil { + eta = max(eta, *p.Eta) + } else { + known = false + } + } + if total > 0 { + out.Pct = int(min(done*100/total, 100)) + } + if out.Running > 0 && known { + out.Left = time.Duration(eta) * time.Second + } + return out +} diff --git a/app/corestate/reader.go b/app/corestate/reader.go new file mode 100644 index 00000000..e2ed5977 --- /dev/null +++ b/app/corestate/reader.go @@ -0,0 +1,60 @@ +package corestate + +import ( + "context" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/tunnel" + "github.com/rclone/rclone-ui/core/vfs" +) + +// APIReader reads the core's state through the APIs that the pages call too. +func APIReader(apis *core.APIs) Reader { return apiReader{apis} } + +type apiReader struct{ apis *core.APIs } + +func (r apiReader) Remotes(ctx context.Context) ([]engine.Remote, error) { + list, err := r.apis.Remotes.List(ctx) + if err != nil { + return nil, err + } + out := make([]engine.Remote, 0, len(list)) + for _, rm := range list { + var features map[string]bool + if rm.Fsinfo != nil { + features = rm.Fsinfo.Features + } + out = append(out, engine.Remote{Name: rm.Name, Type: rm.Type, Features: features}) + } + return out, nil +} + +func (r apiReader) Mounts(ctx context.Context) ([]mounts.MountRow, error) { + return r.apis.Mounts.List(ctx, false) +} + +func (r apiReader) Serves(ctx context.Context) ([]serves.ServeRow, error) { + return r.apis.Serves.List(ctx) +} + +func (r apiReader) Vfs(ctx context.Context) ([]vfs.VFS, error) { return r.apis.Vfs.List(ctx) } + +func (r apiReader) Tunnel(ctx context.Context) (bool, error) { + st, err := r.apis.Tunnel.Status(ctx) + return st.State != tunnel.StateOff, err +} + +func (r apiReader) ActiveTransfers(ctx context.Context) ([]transfers.Transfer, error) { + return r.apis.Transfers.ListActive(ctx) +} + +func (r apiReader) EndedTransfers(ctx context.Context, limit int) ([]transfers.Transfer, error) { + page, err := r.apis.Transfers.ListEnded(ctx, transfers.EndedQuery{Limit: limit}) + return page.Items, err +} + +func (r apiReader) ServeTypes(context.Context) ([]string, error) { return r.apis.Serves.Types(), nil } diff --git a/app/crashlog.go b/app/crashlog.go new file mode 100644 index 00000000..c9268ba5 --- /dev/null +++ b/app/crashlog.go @@ -0,0 +1,28 @@ +package app + +import ( + "os" + "path/filepath" + "runtime/debug" +) + +// crashLogLimit is the size above which crash.log starts over at the next start. +const crashLogLimit = 1 << 20 + +// keepCrashes makes the Go runtime write a fatal crash to crash.log, in the logs folder: a panic +// that nothing recovered, on any goroutine, or a fatal error. The app's own log can't hold it, +// because the log is closed by the time the panic ends the process. Recovered panics are in the +// app's log. +func keepCrashes(dir string) { + path := filepath.Join(dir, "crash.log") + flags := os.O_WRONLY | os.O_CREATE | os.O_APPEND + if fi, err := os.Stat(path); err == nil && fi.Size() > crashLogLimit { + flags |= os.O_TRUNC + } + f, err := os.OpenFile(path, flags, 0o600) + if err != nil { + return + } + defer f.Close() // SetCrashOutput keeps its own copy of the file + _ = debug.SetCrashOutput(f, debug.CrashOptions{}) +} diff --git a/app/crashlog_test.go b/app/crashlog_test.go new file mode 100644 index 00000000..3c7310b6 --- /dev/null +++ b/app/crashlog_test.go @@ -0,0 +1,49 @@ +package app + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// TestKeepCrashes runs the test binary again, to crash it with a panic on another goroutine. +func TestKeepCrashes(t *testing.T) { + if dir := os.Getenv("RCUI_TEST_CRASH_DIR"); dir != "" { + keepCrashes(dir) + go panic("the crash this test expects") + // The crash must be the child's only way out. If the test returned here, the child could + // exit with success before the panic ends it. + select {} + } + dir := t.TempDir() + path := filepath.Join(dir, "crash.log") + crash := func() string { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestKeepCrashes$") + cmd.Env = append(os.Environ(), "RCUI_TEST_CRASH_DIR="+dir) + if err := cmd.Run(); err == nil { + t.Fatal("the child exited without crashing") + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) + } + + if got := crash(); strings.Count(got, "panic: the crash this test expects") != 1 { + t.Fatalf("crash.log should hold the panic once:\n%s", got) + } + if got := crash(); strings.Count(got, "panic: the crash this test expects") != 2 { + t.Fatalf("a second crash should be appended:\n%s", got) + } + + if err := os.WriteFile(path, []byte(strings.Repeat("x", crashLogLimit+1)), 0o600); err != nil { + t.Fatal(err) + } + if got := crash(); strings.HasPrefix(got, "x") { + t.Fatalf("a file above the limit should start over, it is %d bytes", len(got)) + } +} diff --git a/app/deeplink/deeplink.go b/app/deeplink/deeplink.go new file mode 100644 index 00000000..2f25789f --- /dev/null +++ b/app/deeplink/deeplink.go @@ -0,0 +1,85 @@ +// Package deeplink parses `rclone://` links and registers the scheme on systems where no +// installer does. +package deeplink + +import ( + "net/url" + "strings" +) + +const Scheme = "rclone" + +// Link is what a deep link asks for: either a route, which decides its window, or an update. +type Link struct { + // URL is the route to open, such as "/templates?action=add&cmd=…". + URL string + // Update is an update that `rcui update` passes to the running app. It is nil for a route. + Update *Update +} + +type Update struct { + // Version is the release to install. "" means the latest on the channel. + Version string + // Channel is "stable" or "beta". "" means the user's setting. + Channel string +} + +// UpdateLink returns the link that `rcui update` passes to the running app, asking it to install +// version from channel. +func UpdateLink(version, channel string) string { + q := url.Values{} + if version != "" { + q.Set("version", version) + } + if channel != "" { + q.Set("channel", channel) + } + return Scheme + "://update?" + q.Encode() +} + +// IsLink reports whether s is an rclone:// link. The scheme is case-insensitive. +func IsLink(s string) bool { + return strings.HasPrefix(strings.ToLower(s), Scheme+":") +} + +// FromArgs returns the first deep link in args, or "". +func FromArgs(args []string) string { + for _, a := range args { + if IsLink(a) { + return a + } + } + return "" +} + +// Parse parses a link of the form `add-template?cmd=…&name=…` or `update?version=…&channel=…`. +// It returns false for anything else. It accepts any number of slashes after the scheme, and a +// trailing slash before the query (`add-template/?cmd=…`), which some platforms add. +func Parse(raw string) (Link, bool) { + if !IsLink(raw) { + return Link{}, false + } + rest := strings.TrimLeft(raw[len(Scheme)+1:], "/") + route, query, _ := strings.Cut(rest, "?") + domain, _, _ := strings.Cut(route, "/") + params, err := url.ParseQuery(query) + if err != nil { + // A malformed query still opens the window, without its fields. + params = url.Values{} + } + switch strings.ToLower(domain) { + case "add-template": + search := url.Values{} + search.Set("action", "add") + if cmd := strings.TrimSpace(params.Get("cmd")); cmd != "" { + search.Set("cmd", cmd) + } + if name := strings.TrimSpace(params.Get("name")); name != "" { + search.Set("name", name) + } + return Link{URL: "/templates?" + search.Encode()}, true + case "update": + return Link{Update: &Update{Version: params.Get("version"), Channel: params.Get("channel")}}, true + } + return Link{}, false +} diff --git a/app/deeplink/deeplink_test.go b/app/deeplink/deeplink_test.go new file mode 100644 index 00000000..2c2bf812 --- /dev/null +++ b/app/deeplink/deeplink_test.go @@ -0,0 +1,70 @@ +package deeplink + +import ( + "net/url" + "testing" +) + +func TestParse(t *testing.T) { + cases := []struct { + raw string + ok bool + cmd, name string + }{ + {"rclone://add-template?cmd=copy%20--fast-list&name=Nightly", true, "copy --fast-list", "Nightly"}, + {"rclone:add-template?cmd=sync", true, "sync", ""}, + {"rclone:///add-template/?cmd=x&name=%20%20", true, "x", ""}, + {"RCLONE://Add-Template?name=only", true, "", "only"}, + {"rclone://add-template", true, "", ""}, + {"rclone://something-else?x=1", false, "", ""}, + {"https://add-template?cmd=x", false, "", ""}, + {"", false, "", ""}, + } + for _, c := range cases { + l, ok := Parse(c.raw) + if ok != c.ok { + t.Errorf("Parse(%q) ok = %v, want %v", c.raw, ok, c.ok) + continue + } + if !ok { + continue + } + u, err := url.Parse(l.URL) + if err != nil || u.Path != "/templates" { + t.Errorf("Parse(%q).URL = %q", c.raw, l.URL) + continue + } + q := u.Query() + if q.Get("action") != "add" || q.Get("cmd") != c.cmd || q.Get("name") != c.name { + t.Errorf("Parse(%q) query = %v, want cmd %q name %q", c.raw, q, c.cmd, c.name) + } + if _, has := q["name"]; has && c.name == "" { + t.Errorf("Parse(%q) kept an empty name", c.raw) + } + } +} + +func TestFromArgs(t *testing.T) { + if got := FromArgs([]string{"--flag", "rclone://add-template?cmd=x"}); got != "rclone://add-template?cmd=x" { + t.Errorf("FromArgs = %q", got) + } + if got := FromArgs([]string{"ui", "--data-dir", "/x"}); got != "" { + t.Errorf("FromArgs found %q", got) + } +} + +func TestUpdateLink(t *testing.T) { + for _, c := range []struct{ version, channel string }{{"4.0.2", "stable"}, {"", "beta"}, {"", ""}} { + raw := UpdateLink(c.version, c.channel) + if !IsLink(raw) { + t.Fatalf("%q is not a link", raw) + } + link, ok := Parse(raw) + if !ok || link.Update == nil || link.URL != "" { + t.Fatalf("Parse(%q) = %+v, %v", raw, link, ok) + } + if link.Update.Version != c.version || link.Update.Channel != c.channel { + t.Errorf("Parse(%q) = %+v", raw, *link.Update) + } + } +} diff --git a/app/deeplink/exec.go b/app/deeplink/exec.go new file mode 100644 index 00000000..33e121c2 --- /dev/null +++ b/app/deeplink/exec.go @@ -0,0 +1,16 @@ +package deeplink + +import "strings" + +// execEscapes escapes a quoted argument of the Exec key in a .desktop file, following the Desktop +// Entry specification. Inside the quotes, a double quote, a backtick, `$` and `\` each get a +// backslash. Then the general string escaping, which is applied first when reading, doubles every +// backslash. `%` is doubled too, or it would be read as a field code. So a literal backslash +// becomes four backslashes, and a `$` becomes `\\$`. +var execEscapes = strings.NewReplacer(`\`, `\\\\`, `"`, `\\"`, "`", "\\\\`", `$`, `\\$`, `%`, `%%`) + +// QuoteExec quotes a path as one argument of the Exec key in a .desktop file (Linux). A field code +// such as %u goes after it, outside the quotes. +func QuoteExec(path string) string { + return `"` + execEscapes.Replace(path) + `"` +} diff --git a/app/deeplink/exec_test.go b/app/deeplink/exec_test.go new file mode 100644 index 00000000..95fa2019 --- /dev/null +++ b/app/deeplink/exec_test.go @@ -0,0 +1,19 @@ +package deeplink + +import "testing" + +func TestQuoteExec(t *testing.T) { + for in, want := range map[string]string{ + "/opt/rcui.AppImage": `"/opt/rcui.AppImage"`, + "/home/me/My Apps/rcui.AppImage": `"/home/me/My Apps/rcui.AppImage"`, + "/home/me/100%/rcui.AppImage": `"/home/me/100%%/rcui.AppImage"`, + `/home/me/b\c/rcui.AppImage`: `"/home/me/b\\\\c/rcui.AppImage"`, + `/home/me/"q"/rcui.AppImage`: `"/home/me/\\"q\\"/rcui.AppImage"`, + "/home/me/$HOME/rcui.AppImage": `"/home/me/\\$HOME/rcui.AppImage"`, + "/home/me/a`b/rcui.AppImage": "\"/home/me/a\\\\`b/rcui.AppImage\"", + } { + if got := QuoteExec(in); got != want { + t.Errorf("QuoteExec(%q) = %s, want %s", in, got, want) + } + } +} diff --git a/app/deeplink/register_darwin.go b/app/deeplink/register_darwin.go new file mode 100644 index 00000000..7606a579 --- /dev/null +++ b/app/deeplink/register_darwin.go @@ -0,0 +1,5 @@ +package deeplink + +// Register does nothing on macOS. The bundle's Info.plist (CFBundleURLTypes) registers the scheme +// with Launch Services, so there is nothing to do at run time. +func Register(string) error { return nil } diff --git a/app/deeplink/register_linux.go b/app/deeplink/register_linux.go new file mode 100644 index 00000000..2e9e1b6d --- /dev/null +++ b/app/deeplink/register_linux.go @@ -0,0 +1,62 @@ +package deeplink + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/platform" +) + +// handlerFile is the app's x-scheme-handler entry in the user's applications folder. +const handlerFile = "org.rclone.ui-handler.desktop" + +// Register makes exe open rclone:// links for this user. It writes a hidden .desktop entry in +// $XDG_DATA_HOME/applications and runs `xdg-mime default`. deb and rpm declare the scheme in their +// own .desktop file, so this is for the AppImage, whose path is only known at run time. The entry +// is rewritten at every start in case the file moved. +func Register(exe string) error { + if exe == "" { + return errors.New("no executable to register") + } + data := os.Getenv("XDG_DATA_HOME") + if data == "" { + home, err := os.UserHomeDir() + if err != nil { + return err + } + data = filepath.Join(home, ".local", "share") + } + dir := filepath.Join(data, "applications") + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + entry := strings.Join([]string{ + "[Desktop Entry]", + "Type=Application", + "Name=Rclone UI", + "Exec=" + QuoteExec(exe) + " %u", + "Terminal=false", + "NoDisplay=true", + "MimeType=x-scheme-handler/" + Scheme + ";", + "", + }, "\n") + path := filepath.Join(dir, handlerFile) + if old, err := os.ReadFile(path); err != nil || string(old) != entry { + if err := os.WriteFile(path, []byte(entry), 0o644); err != nil { + return err + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + // Run the host's tools in the host's environment, because under an AppImage they would read + // the AppImage's data directories. + if err := platform.HostCommand(ctx, "xdg-mime", "default", handlerFile, "x-scheme-handler/"+Scheme).Run(); err != nil { + return err + } + _ = platform.HostCommand(ctx, "update-desktop-database", dir).Run() + return nil +} diff --git a/app/deeplink/register_windows.go b/app/deeplink/register_windows.go new file mode 100644 index 00000000..8573f905 --- /dev/null +++ b/app/deeplink/register_windows.go @@ -0,0 +1,39 @@ +package deeplink + +import ( + "fmt" + + "golang.org/x/sys/windows/registry" +) + +// Register makes exe open rclone:// links for this user (in HKCU\Software\Classes\rclone). It runs +// at every start, so per-user installs and portable copies get links without an installer. When +// a machine has several copies, the one that started last opens the links. The NSIS installer's +// own entry, which is per machine, is left alone. +func Register(exe string) error { + root, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\`+Scheme, registry.ALL_ACCESS) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + if err := root.SetStringValue("", "URL:"+Scheme+" protocol"); err != nil { + return err + } + if err := root.SetStringValue("URL Protocol", ""); err != nil { + return err + } + icon, _, err := registry.CreateKey(root, "DefaultIcon", registry.ALL_ACCESS) + if err != nil { + return err + } + defer func() { _ = icon.Close() }() + if err := icon.SetStringValue("", fmt.Sprintf(`"%s",0`, exe)); err != nil { + return err + } + cmd, _, err := registry.CreateKey(root, `shell\open\command`, registry.ALL_ACCESS) + if err != nil { + return err + } + defer func() { _ = cmd.Close() }() + return cmd.SetStringValue("", fmt.Sprintf(`"%s" "%%1"`, exe)) +} diff --git a/app/dock_darwin.go b/app/dock_darwin.go new file mode 100644 index 00000000..a2df10bd --- /dev/null +++ b/app/dock_darwin.go @@ -0,0 +1,15 @@ +package app + +import "github.com/wailsapp/wails/v3/pkg/services/dock" + +var macDock = dock.New() + +// showInDock shows the app's icon in the Dock and the app switcher, or hides it so that the app +// lives in the menu bar only. It waits for the main thread, so it must not be called from there. +func showInDock(show bool) { + if show { + macDock.ShowAppIcon() + } else { + macDock.HideAppIcon() + } +} diff --git a/app/dock_other.go b/app/dock_other.go new file mode 100644 index 00000000..51a8e03b --- /dev/null +++ b/app/dock_other.go @@ -0,0 +1,5 @@ +//go:build !darwin + +package app + +func showInDock(bool) {} diff --git a/app/events.go b/app/events.go new file mode 100644 index 00000000..240b97d8 --- /dev/null +++ b/app/events.go @@ -0,0 +1,114 @@ +package app + +import ( + "context" + "github.com/rclone/rclone-ui/core/agents" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/launcher/view/linux" + "github.com/rclone/rclone-ui/app/pathlink" + "github.com/rclone/rclone-ui/app/windows" + "github.com/rclone/rclone-ui/core/browse" + "github.com/rclone/rclone-ui/core/bus" +) + +// The events that the UI sends to the pages. lib/shell listens for them. +const ( + // EventCoreState carries the core's status (CoreStatus) on every change. + EventCoreState = "core:state" + // EventUpdateState reports the progress of the update flow (UpdateState). + EventUpdateState = "update:state" + // EventAutostartChanged carries whether the app starts at login, after a window changed it. + // The other windows that show the switch then update. A change made in the OS's own settings + // sends nothing, and the pages read it again when their window gets the focus. + EventAutostartChanged = "autostart:changed" + // EventPathLinkChanged carries the state of "Add rclone to PATH" (pathlink.State), after a + // window turned it on or off. + EventPathLinkChanged = "pathlink:changed" + // EventAgentsChanged carries the state of the agents' server (agents.Status), after it + // started, stopped or failed to start. + EventAgentsChanged = "agents:changed" +) + +// The events are registered with their data types, so that the generated bindings give the pages +// typed events. The core's events are its bus events, each with the payload that its publisher +// puts on the bus. The last ones are events that a call sends back to the window that made it, +// such as a listing's rows. +func init() { + application.RegisterEvent[CoreStatus](EventCoreState) + application.RegisterEvent[string](windows.EventRoute) + application.RegisterEvent[application.Void](windows.EventCloseAsked) + application.RegisterEvent[UpdateState](EventUpdateState) + application.RegisterEvent[bool](EventAutostartChanged) + application.RegisterEvent[pathlink.State](EventPathLinkChanged) + application.RegisterEvent[agents.Status](EventAgentsChanged) + application.RegisterEvent[linux.Frame](linux.EventRender) + application.RegisterEvent[linux.Query](linux.EventQuery) + application.RegisterEvent[application.Void](linux.EventShown) + application.RegisterEvent[application.Void](linux.EventHidden) + + application.RegisterEvent[application.Void](bus.Resync) + application.RegisterEvent[bus.TransfersChangedData](bus.TransfersChanged) + application.RegisterEvent[bus.TransfersProgressData](bus.TransfersProgress) + application.RegisterEvent[bus.RemotesChangedData](bus.RemotesChanged) + application.RegisterEvent[bus.RemotesHealthData](bus.RemotesHealth) + application.RegisterEvent[bus.RemotesSessionData](bus.RemotesSession) + application.RegisterEvent[bus.MountsChangedData](bus.MountsChanged) + application.RegisterEvent[bus.ServesChangedData](bus.ServesChanged) + application.RegisterEvent[application.Void](bus.TemplatesChanged) + application.RegisterEvent[application.Void](bus.WatchersChanged) + application.RegisterEvent[application.Void](bus.SchedulesChanged) + application.RegisterEvent[application.Void](bus.AutomountsChanged) + application.RegisterEvent[application.Void](bus.FavoritesChanged) + application.RegisterEvent[application.Void](bus.NotificationsChanged) + application.RegisterEvent[application.Void](bus.SettingsChanged) + application.RegisterEvent[bus.PrefsChangedData](bus.PrefsChanged) + application.RegisterEvent[application.Void](bus.ConfigChanged) + application.RegisterEvent[bus.TunnelChangedData](bus.TunnelChanged) + application.RegisterEvent[bus.FilesChangedData](bus.FilesChanged) + + application.RegisterEvent[browse.Rows](browse.EventRows) + application.RegisterEvent[browse.FolderSize](browse.EventSize) + application.RegisterEvent[browse.UsageProgress](browse.EventUsage) +} + +// relayCoreEvent passes one of the core's events on to every window, with its payload unchanged. +// Desktop notifications are handled by the UI alone, so the windows don't get them. +func (u *ui) relayCoreEvent(ev bus.Event) { + if ev.Name == bus.NotifyOS { + return + } + if ev.Data == nil { + u.app.Event.Emit(ev.Name) + return + } + u.app.Event.Emit(ev.Name, ev.Data) +} + +// emitToCaller sends an event from a call to the window that made the call (ctx is the call's +// context). When the call didn't come from a window, the event goes to every window. +func (u *ui) emitToCaller(ctx context.Context, name string, data any) { + if w, ok := windows.Caller(ctx); ok { + w.DispatchWailsEvent(&application.CustomEvent{Name: name, Data: data}) + return + } + u.app.Event.Emit(name, data) +} + +type CoreStatus struct { + State CoreState `json:"state"` + // Error explains why the core is not ready. + Error string `json:"error"` + Version string `json:"version"` +} + +type UpdateState struct { + // Phase is "idle", "checking", "downloading", "installing" or "error". + Phase string `json:"phase"` + Version string `json:"version"` + // Done and Total count the download's bytes. Total is 0 when unknown. + Done int64 `json:"done"` + Total int64 `json:"total"` + Error string `json:"error"` +} diff --git a/app/hostopen.go b/app/hostopen.go new file mode 100644 index 00000000..c304fefe --- /dev/null +++ b/app/hostopen.go @@ -0,0 +1,101 @@ +package app + +import ( + "context" + "fmt" + "net/url" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + "unicode" + + "github.com/rclone/rclone-ui/app/platform" +) + +// openURL opens a URL in the default browser. Under an AppImage, xdg-open runs in the host's +// environment (see platform.HostCommand), because the browser it starts would fail with the +// AppImage's libraries. +func (u *ui) openURL(raw string) error { + if err := browsable(raw); err != nil { + return err + } + if platform.AppDir() != "" { + return hostOpen(raw) + } + return u.app.Browser.OpenURL(raw) +} + +// browsable accepts only web and mail links. open, xdg-open and Windows' FileProtocolHandler can +// also run programs and open files, and they read a leading "-" as an option. The URLs that pages +// open aren't all constants. For example, the URL for an OAuth step comes from the core. +func browsable(raw string) error { + if strings.HasPrefix(raw, "-") || strings.ContainsFunc(raw, unicode.IsControl) { + return fmt.Errorf("not a URL the browser may open: %q", raw) + } + u, err := url.Parse(raw) + if err != nil { + return fmt.Errorf("not a URL the browser may open: %w", err) + } + switch strings.ToLower(u.Scheme) { + case "http", "https": + if u.Host == "" { + return fmt.Errorf("not a URL the browser may open: %q has no host", raw) + } + case "mailto": + default: + return fmt.Errorf("not a URL the browser may open: %q", raw) + } + return nil +} + +// reveal shows a file or folder in the file manager, selected when selectFile is set. A folder is +// opened rather than selected, because Wails selects only files. The exception is a bundle on +// macOS (such as an .app), which `open` would launch, so it is selected in its parent folder. +// Under an AppImage, the host's xdg-open opens the folder (or a file's parent folder) with nothing +// selected. +func (u *ui) reveal(path string, selectFile bool) error { + if platform.AppDir() != "" { + dir := path + if st, err := os.Stat(path); err == nil && !st.IsDir() { + dir = filepath.Dir(path) + } + return hostOpen(dir) + } + if selectFile && runtime.GOOS == "darwin" && maybeBundle(path) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + abs, err := filepath.Abs(path) + if err != nil { + return err + } + return exec.CommandContext(ctx, "open", "-R", abs).Run() + } + return u.app.Env.OpenFileManager(path, selectFile) +} + +// maybeBundle reports whether path is a folder that macOS may treat as a bundle, such as an app +// or a preference pane. That is any folder whose name has an extension. A plain folder with such a +// name is then shown in its parent rather than opened, which is harmless. +func maybeBundle(path string) bool { + st, err := os.Stat(path) + if err != nil || !st.IsDir() { + return false + } + name := filepath.Base(filepath.Clean(path)) + ext := filepath.Ext(name) + return ext != "" && ext != name +} + +// hostOpen runs the host's xdg-open on target without waiting for it, because xdg-open may wait +// for the program it starts. +func hostOpen(target string) error { + cmd := platform.HostCommand(context.Background(), "xdg-open", target) + if err := cmd.Start(); err != nil { + return err + } + go func() { _ = cmd.Wait() }() + return nil +} diff --git a/app/interaction/activate_darwin.go b/app/interaction/activate_darwin.go new file mode 100644 index 00000000..0a9ecf70 --- /dev/null +++ b/app/interaction/activate_darwin.go @@ -0,0 +1,20 @@ +package interaction + +/* +#cgo CFLAGS: -mmacosx-version-min=12.0 -x objective-c +#cgo LDFLAGS: -mmacosx-version-min=12.0 -framework Cocoa +#import + +static void rcuiActivate(void) { + [NSApp activateIgnoringOtherApps:YES]; +} +*/ +import "C" + +import "github.com/wailsapp/wails/v3/pkg/application" + +// activate brings the app to the front before a dialog opens. The app runs as an accessory, +// often with no window, so otherwise the dialog would open behind the app the user is in. +func activate() { + application.InvokeSync(func() { C.rcuiActivate() }) +} diff --git a/app/interaction/activate_other.go b/app/interaction/activate_other.go new file mode 100644 index 00000000..b9d25222 --- /dev/null +++ b/app/interaction/activate_other.go @@ -0,0 +1,6 @@ +//go:build !darwin + +package interaction + +// activate does nothing, because dialogs on Windows and Linux come to the front by themselves. +func activate() {} diff --git a/app/interaction/dialog_wails.go b/app/interaction/dialog_wails.go new file mode 100644 index 00000000..f8f1b9d1 --- /dev/null +++ b/app/interaction/dialog_wails.go @@ -0,0 +1,47 @@ +//go:build darwin || linux + +package interaction + +import "github.com/wailsapp/wails/v3/pkg/application" + +// show uses Wails' dialogs. On macOS that is an NSAlert. On Linux it is a GTK 4 window that Wails +// builds as a message dialog, where Escape and closing the window both choose the button marked +// as the cancel button. show always marks one, so every way of closing the dialog reports a +// button, and an answer always arrives. +func show(d Dialog) Answer { + app := application.Get() + var dlg *application.MessageDialog + switch d.Kind { + case Warning: + dlg = app.Dialog.Warning() + case Error: + dlg = app.Dialog.Error() + case Question: + dlg = app.Dialog.Question() + default: + dlg = app.Dialog.Info() + } + dlg.SetTitle(d.Title).SetMessage(d.Message) + answers := make(chan Answer, 1) + add := func(label string, a Answer, isDefault, isCancel bool) { + b := dlg.AddButton(label) + b.IsDefault, b.IsCancel = isDefault, isCancel + b.OnClick(func() { + select { + case answers <- a: + default: + } + }) + } + // Buttons are added from left to right, so the default ends up on the right. + if d.Extra != "" { + add(d.Extra, AnswerExtra, false, false) + } + if d.Cancel != "" { + add(d.Cancel, AnswerCancel, false, true) + } + add(d.OK, AnswerOK, true, d.Cancel == "") + activate() + dlg.Show() + return <-answers +} diff --git a/app/interaction/dialog_windows.go b/app/interaction/dialog_windows.go new file mode 100644 index 00000000..4bccb27e --- /dev/null +++ b/app/interaction/dialog_windows.go @@ -0,0 +1,98 @@ +package interaction + +import ( + "errors" + + "github.com/ncruces/zenity" + "github.com/wailsapp/wails/v3/pkg/application" +) + +// show uses Wails' question dialog, because that is the one Wails shows as a Windows task dialog +// when it has buttons of its own (#5794). A task dialog sizes its buttons to their labels, where a +// plain message box keeps the standard size and cuts a longer label short ("Skip This Version"). +// It also puts itself above every window when it opens, including the Startup window and the +// launcher, which stay on top and would hide a plain message box. Before Wails' application is +// made, zenity's message box shows the dialog. Every caller runs once the application has started, +// because until then Wails would show nothing. +func show(d Dialog) Answer { + app := application.Get() + if app == nil { + return showZenity(d) + } + // Wails shows the app's own icon for any icon it's given, so the bytes don't matter. + dlg := app.Dialog.Question().SetTitle(d.Title).SetMessage(d.Message).SetIcon([]byte{0}) + answers := make(chan Answer, 1) + add := func(label string, a Answer, isDefault, isCancel bool) { + b := dlg.AddButton(label) + b.IsDefault, b.IsCancel = isDefault, isCancel + b.OnClick(func() { + select { + case answers <- a: + default: + } + }) + } + // Windows puts the default button first. Escape and the close button choose the button + // marked as the cancel button, so one is always marked, and an answer always arrives. + add(d.OK, AnswerOK, true, d.Cancel == "") + if d.Extra != "" { + add(d.Extra, AnswerExtra, false, false) + } + if d.Cancel != "" { + add(d.Cancel, AnswerCancel, false, true) + } + activate() + dlg.Show() + select { + case a := <-answers: + return a + default: + // No button reported, which only happens if the dialog couldn't be shown. + return AnswerCancel + } +} + +// ShowPlain shows d in a plain Win32 message box, which needs nothing from Wails, and waits for +// the answer. It is for when Wails itself failed, as when WebView2 doesn't start, and it may be +// called from the main thread then. A message box's buttons keep the standard width, so their +// labels must be short ("Download", not "Download WebView2"). +func ShowPlain(d Dialog) Answer { return present(d, showZenity) } + +// showZenity shows the dialog with zenity's Win32 message box, which can relabel its buttons. +func showZenity(d Dialog) Answer { + opts := []zenity.Option{zenity.Title(d.Title), zenity.OKLabel(d.OK)} + switch d.Kind { + case Warning: + opts = append(opts, zenity.WarningIcon) + case Error: + opts = append(opts, zenity.ErrorIcon) + case Question: + opts = append(opts, zenity.QuestionIcon) + default: + opts = append(opts, zenity.InfoIcon) + } + if d.Cancel == "" && d.Extra == "" { + // With one button, closing the box gives the same answer. + _ = zenity.Info(d.Message, opts...) + return AnswerOK + } + if d.Extra != "" { + opts = append(opts, zenity.ExtraButton(d.Extra)) + } + var err error + if d.Cancel == "" { + // OK and Extra only. A question box would add its own Cancel button (Yes, No and + // Cancel), while a message box has just two (Yes and No). + err = zenity.Info(d.Message, opts...) + } else { + err = zenity.Question(d.Message, append(opts, zenity.CancelLabel(d.Cancel))...) + } + switch { + case err == nil: + return AnswerOK + case errors.Is(err, zenity.ErrExtraButton): + return AnswerExtra + default: + return AnswerCancel + } +} diff --git a/app/interaction/interaction.go b/app/interaction/interaction.go new file mode 100644 index 00000000..f9009efd --- /dev/null +++ b/app/interaction/interaction.go @@ -0,0 +1,95 @@ +// Package interaction asks the user questions with native dialogs. It shows messages and +// questions with the app's own button labels (such as Relaunch/Exit or Quit/Cancel), and a prompt +// for text or a password. Every call blocks until the user answers, so it must never be made from +// the main thread. The one exception is ShowPlain on Windows, for when Wails itself failed. +package interaction + +import ( + "sync/atomic" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// Kind is the dialog's icon. +type Kind string + +const ( + Info Kind = "info" + Warning Kind = "warning" + Error Kind = "error" + Question Kind = "question" +) + +type Dialog struct { + Kind Kind + Title string + Message string + // OK is the default button ("OK", in the app's language, when empty). + OK string + // Cancel is the button that Escape and closing the dialog choose. When it is empty there is no + // Cancel button, and closing the dialog chooses OK. + Cancel string + // Extra is an optional third button. + Extra string +} + +// Answer is the chosen button. +type Answer int + +const ( + AnswerOK Answer = iota + AnswerCancel + AnswerExtra +) + +// open counts the dialogs and prompts that are showing. +var open atomic.Int32 + +// Open reports whether a dialog or a prompt is showing. On Windows, a window that is put on top +// while one shows would cover it, so the Startup window stays an ordinary window then. +func Open() bool { return open.Load() > 0 } + +// showing counts a dialog or a prompt while it shows. Call the function it returns once it closes. +func showing() (closed func()) { + open.Add(1) + return func() { open.Add(-1) } +} + +func Show(d Dialog) Answer { return present(d, show) } + +// present fills in d's defaults, then shows it with display and waits for the answer. A dev +// build's script may answer instead. +func present(d Dialog, display func(Dialog) Answer) Answer { + if d.OK == "" { + // i18n: The default button of a dialog that only informs. + d.OK = i18n.T("OK") + } + if d.Kind == "" { + d.Kind = Info + } + if a, _, ok := scripted(d, false); ok { + return a + } + defer showing()() + return display(d) +} + +// Ask shows a question with an OK and a Cancel button. It returns true for OK. +func Ask(kind Kind, title, message, ok, cancel string) bool { + return Show(Dialog{Kind: kind, Title: title, Message: message, OK: ok, Cancel: cancel}) == AnswerOK +} + +func Message(kind Kind, title, message string) { + Show(Dialog{Kind: kind, Title: title, Message: message}) +} + +// Prompt asks for a line of text, and sensitive hides what is typed. ok is false when the user +// cancelled. On Linux it is a GTK 4 window of the app's own, inside the process. macOS uses +// osascript, and Windows uses a Win32 dialog. +func Prompt(title, message, def string, sensitive bool) (value string, ok bool, err error) { + if a, text, ok := scripted(Dialog{Kind: Question, Title: title, Message: message}, true); ok { + return text, a == AnswerOK, nil + } + defer showing()() + return prompt(title, message, def, sensitive) +} diff --git a/app/interaction/prompt_linux.go b/app/interaction/prompt_linux.go new file mode 100644 index 00000000..3cb60349 --- /dev/null +++ b/app/interaction/prompt_linux.go @@ -0,0 +1,355 @@ +//go:build linux + +package interaction + +// The prompt on Linux is a GTK 4 window of the app's own. It calls the GTK that Wails has already +// loaded into the process, through purego, so there is no C code of our own and the package +// builds, and can be vetted, on any machine. Each function is declared with its C signature +// beside it. A gboolean is passed and read as an int32, because it is a C int. Strings are copied +// to C only for the length of a call, so every function that takes one must copy it, and all of +// the functions below do. + +import ( + "errors" + "fmt" + "log/slog" + "runtime/debug" + "sync" + + "github.com/ebitengine/purego" + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/core/i18n" +) + +const ( + gtkOrientationHorizontal = 0 // GtkOrientation + gtkOrientationVertical = 1 + gtkAlignEnd = 2 // GtkAlign + keyEscape = 0xff1b // GDK_KEY_Escape +) + +// gtk4 +var ( + gtkIsInitialized func() int32 // gboolean gtk_is_initialized (void) + gtkWindowNew func() uintptr // GtkWidget *gtk_window_new (void) + gtkWindowSetTitle func(w uintptr, title string) // void (GtkWindow*, const char*) + gtkWindowSetModal func(w uintptr, on int32) // void (GtkWindow*, gboolean) + gtkWindowSetResizable func(w uintptr, on int32) // void (GtkWindow*, gboolean) + gtkWindowSetChild func(w, child uintptr) // void (GtkWindow*, GtkWidget*) + gtkWindowSetDefaultWidget func(w, child uintptr) // void (GtkWindow*, GtkWidget*) + gtkWindowPresent func(w uintptr) // void (GtkWindow*) + gtkWindowDestroy func(w uintptr) // void (GtkWindow*) + gtkBoxNew func(orientation, spacing int32) uintptr // GtkWidget *(GtkOrientation, int) + gtkBoxAppend func(box, child uintptr) // void (GtkBox*, GtkWidget*) + gtkBoxSetHomogeneous func(box uintptr, on int32) // void (GtkBox*, gboolean) + gtkWidgetSetMarginTop func(w uintptr, margin int32) // void (GtkWidget*, int) + gtkWidgetSetMarginBottom func(w uintptr, margin int32) // void (GtkWidget*, int) + gtkWidgetSetMarginStart func(w uintptr, margin int32) // void (GtkWidget*, int) + gtkWidgetSetMarginEnd func(w uintptr, margin int32) // void (GtkWidget*, int) + gtkWidgetSetHalign func(w uintptr, align int32) // void (GtkWidget*, GtkAlign) + gtkWidgetAddCSSClass func(w uintptr, class string) // void (GtkWidget*, const char*) + gtkWidgetAddController func(w, controller uintptr) // void (GtkWidget*, GtkEventController*); takes ownership + gtkWidgetGrabFocus func(w uintptr) int32 // gboolean (GtkWidget*) + gtkLabelNew func(text string) uintptr // GtkWidget *(const char*) + gtkLabelSetWrap func(l uintptr, on int32) // void (GtkLabel*, gboolean) + gtkLabelSetMaxWidthChars func(l uintptr, n int32) // void (GtkLabel*, int) + gtkLabelSetXalign func(l uintptr, x float32) // void (GtkLabel*, float) + gtkEntryNew func() uintptr // GtkWidget *(void) + gtkPasswordEntryNew func() uintptr // GtkWidget *(void) + gtkPasswordEntrySetShowPeek func(e uintptr, on int32) // void gtk_password_entry_set_show_peek_icon (GtkPasswordEntry*, gboolean) + gtkEditableSetText func(e uintptr, text string) // void (GtkEditable*, const char*) + gtkEditableGetText func(e uintptr) string // const char *(GtkEditable*); owned by the widget, and purego copies it + gtkButtonNewWithMnemonic func(label string) uintptr // GtkWidget *(const char*) + gtkEventControllerKeyNew func() uintptr // GtkEventController *(void) +) + +// glib and gobject +var ( + gMainContextDefault func() uintptr // GMainContext *g_main_context_default (void) + gMainContextIsOwner func(ctx uintptr) int32 // gboolean g_main_context_is_owner (GMainContext*) + // gulong g_signal_connect_data (gpointer, const gchar*, GCallback, gpointer, GClosureNotify, GConnectFlags) + gSignalConnectData func(instance uintptr, signal string, handler, data, destroy uintptr, flags int32) uint64 +) + +// The signal handlers, as C function pointers from purego.NewCallback. They are made once, in +// load, because purego never frees a callback. Each one is given the prompt's id as its user data. +var ( + // void (GtkWidget*, gpointer), for OK's "clicked" and the entry's "activate" + onOK uintptr + // void (GtkButton*, gpointer), for Cancel's "clicked" + onCancel uintptr + // gboolean (GtkEventControllerKey*, guint keyval, guint keycode, GdkModifierType, gpointer), + // for the key controller's "key-pressed" + onKey uintptr + // gboolean (GtkWindow*, gpointer), for the window's "close-request" + onClose uintptr +) + +var ( + loadOnce sync.Once + errLoad error +) + +// load binds the functions above and makes the signal handlers, once. Wails links GTK 4 into +// the app, so dlopen returns the GTK that is already loaded rather than a second copy. +func load() error { + loadOnce.Do(func() { errLoad = bindGTK() }) + return errLoad +} + +func bindGTK() (err error) { + defer func() { + // RegisterLibFunc panics when a symbol is missing. + if r := recover(); r != nil { + err = fmt.Errorf("binding GTK 4: %v", r) + } + }() + open := func(name string) (uintptr, error) { + h, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + return 0, fmt.Errorf("loading %s: %w", name, err) + } + return h, nil + } + gtk, err := open("libgtk-4.so.1") + if err != nil { + return err + } + glib, err := open("libglib-2.0.so.0") + if err != nil { + return err + } + gobject, err := open("libgobject-2.0.so.0") + if err != nil { + return err + } + bind := func(lib uintptr, fn any, name string) { purego.RegisterLibFunc(fn, lib, name) } + + bind(gtk, >kIsInitialized, "gtk_is_initialized") + bind(gtk, >kWindowNew, "gtk_window_new") + bind(gtk, >kWindowSetTitle, "gtk_window_set_title") + bind(gtk, >kWindowSetModal, "gtk_window_set_modal") + bind(gtk, >kWindowSetResizable, "gtk_window_set_resizable") + bind(gtk, >kWindowSetChild, "gtk_window_set_child") + bind(gtk, >kWindowSetDefaultWidget, "gtk_window_set_default_widget") + bind(gtk, >kWindowPresent, "gtk_window_present") + bind(gtk, >kWindowDestroy, "gtk_window_destroy") + bind(gtk, >kBoxNew, "gtk_box_new") + bind(gtk, >kBoxAppend, "gtk_box_append") + bind(gtk, >kBoxSetHomogeneous, "gtk_box_set_homogeneous") + bind(gtk, >kWidgetSetMarginTop, "gtk_widget_set_margin_top") + bind(gtk, >kWidgetSetMarginBottom, "gtk_widget_set_margin_bottom") + bind(gtk, >kWidgetSetMarginStart, "gtk_widget_set_margin_start") + bind(gtk, >kWidgetSetMarginEnd, "gtk_widget_set_margin_end") + bind(gtk, >kWidgetSetHalign, "gtk_widget_set_halign") + bind(gtk, >kWidgetAddCSSClass, "gtk_widget_add_css_class") + bind(gtk, >kWidgetAddController, "gtk_widget_add_controller") + bind(gtk, >kWidgetGrabFocus, "gtk_widget_grab_focus") + bind(gtk, >kLabelNew, "gtk_label_new") + bind(gtk, >kLabelSetWrap, "gtk_label_set_wrap") + bind(gtk, >kLabelSetMaxWidthChars, "gtk_label_set_max_width_chars") + bind(gtk, >kLabelSetXalign, "gtk_label_set_xalign") + bind(gtk, >kEntryNew, "gtk_entry_new") + bind(gtk, >kPasswordEntryNew, "gtk_password_entry_new") + bind(gtk, >kPasswordEntrySetShowPeek, "gtk_password_entry_set_show_peek_icon") + bind(gtk, >kEditableSetText, "gtk_editable_set_text") + bind(gtk, >kEditableGetText, "gtk_editable_get_text") + bind(gtk, >kButtonNewWithMnemonic, "gtk_button_new_with_mnemonic") + bind(gtk, >kEventControllerKeyNew, "gtk_event_controller_key_new") + bind(glib, &gMainContextDefault, "g_main_context_default") + bind(glib, &gMainContextIsOwner, "g_main_context_is_owner") + bind(gobject, &gSignalConnectData, "g_signal_connect_data") + + // Every handler does its work inside guard, through withPrompt, because a panic can't unwind + // through GTK's C frames. + onOK = purego.NewCallback(func(_, data uintptr) { + withPrompt(data, "ok", func(p *promptWindow) { + p.end(answer{value: gtkEditableGetText(p.entry), ok: true}, true) + }) + }) + onCancel = purego.NewCallback(func(_, data uintptr) { + withPrompt(data, "cancel", func(p *promptWindow) { p.end(answer{}, true) }) + }) + onKey = purego.NewCallback(func(_ uintptr, keyval, _, _ uint32, data uintptr) uintptr { + if keyval != keyEscape { + return 0 // the key goes on to GTK + } + withPrompt(data, "escape", func(p *promptWindow) { p.end(answer{}, true) }) + return 1 + }) + onClose = purego.NewCallback(func(_, data uintptr) uintptr { + withPrompt(data, "close", func(p *promptWindow) { p.end(answer{}, false) }) + return 0 // GTK destroys the window itself + }) + return nil +} + +type answer struct { + value string + ok bool + err error +} + +// promptWindow is an open prompt. Apart from its place in prompts, it is only used on the main +// thread. +type promptWindow struct { + id uintptr + window, entry uintptr + answers chan<- answer + done bool // the answer was sent, so any later signal does nothing +} + +// prompts holds the open prompts by their id, which their signal handlers are given in place of a +// Go pointer. A handler that runs after its prompt ended finds nothing. +var ( + promptsMu sync.Mutex + prompts = map[uintptr]*promptWindow{} + lastPrompt uintptr +) + +// prompt shows a GTK 4 window on the main thread and waits for its answer here. GTK 4 has no +// gtk_dialog_run, so the window answers through a channel. Waiting on the main thread would stop +// the main loop that runs the window, and before the app runs there is no main loop, so both +// return an error instead of hanging. +func prompt(title, message, def string, sensitive bool) (string, bool, error) { + if err := load(); err != nil { + return "", false, err + } + app := application.Get() + if app == nil || gtkIsInitialized() == 0 { + return "", false, errors.New("the prompt can't open before the app runs") + } + // GApplication holds the default main context for as long as it runs, on the main thread. + if gMainContextIsOwner(gMainContextDefault()) != 0 { + return "", false, errors.New("the prompt can't wait on the main thread") + } + answers := make(chan answer, 1) // room for the one answer, so the main thread never waits + activate() + application.InvokeAsync(func() { openPrompt(title, message, def, sensitive, answers) }) + select { + case a := <-answers: + return a.value, a.ok, a.err + case <-app.Context().Done(): + return "", false, errors.New("the app quit before the prompt was answered") + } +} + +// openPrompt builds the prompt and shows it, on the main thread: a modal window with the message, +// an entry holding def, and Cancel and OK buttons. OK is the default, and Enter in the entry +// chooses it. Escape and closing the window cancel. GTK 4 can't keep a window above the others or +// choose where it goes, so the compositor places it. +func openPrompt(title, message, def string, sensitive bool, answers chan<- answer) { + promptsMu.Lock() + lastPrompt++ + p := &promptWindow{id: lastPrompt, answers: answers} + prompts[p.id] = p + promptsMu.Unlock() + p.guard("open", func() { + p.window = gtkWindowNew() + gtkWindowSetTitle(p.window, title) + gtkWindowSetModal(p.window, 1) + gtkWindowSetResizable(p.window, 0) + + box := gtkBoxNew(gtkOrientationVertical, 12) + gtkWidgetSetMarginTop(box, 18) + gtkWidgetSetMarginBottom(box, 18) + gtkWidgetSetMarginStart(box, 18) + gtkWidgetSetMarginEnd(box, 18) + + label := gtkLabelNew(message) + gtkLabelSetWrap(label, 1) + gtkLabelSetMaxWidthChars(label, 60) + gtkLabelSetXalign(label, 0) + gtkBoxAppend(box, label) + + // A password entry hides what is typed, and its eye icon shows it again. + if sensitive { + p.entry = gtkPasswordEntryNew() + gtkPasswordEntrySetShowPeek(p.entry, 1) + } else { + p.entry = gtkEntryNew() + } + gtkEditableSetText(p.entry, def) + gtkBoxAppend(box, p.entry) + + buttons := gtkBoxNew(gtkOrientationHorizontal, 6) + gtkBoxSetHomogeneous(buttons, 1) + gtkWidgetSetHalign(buttons, gtkAlignEnd) + gtkWidgetSetMarginTop(buttons, 6) + // i18n: A prompt's button. The underscore marks the letter that Alt presses it with: keep one. + cancel := gtkButtonNewWithMnemonic(i18n.T("_Cancel")) + // i18n: A prompt's button. The underscore marks the letter that Alt presses it with: keep one. + ok := gtkButtonNewWithMnemonic(i18n.T("_OK")) + gtkWidgetAddCSSClass(ok, "suggested-action") + gtkBoxAppend(buttons, cancel) + gtkBoxAppend(buttons, ok) + gtkBoxAppend(box, buttons) + gtkWindowSetChild(p.window, box) + gtkWindowSetDefaultWidget(p.window, ok) + + // The entry's "activate" is Enter. It chooses OK directly, rather than through the default + // widget, so OK can't be chosen twice. + connect(ok, "clicked", onOK, p.id) + connect(p.entry, "activate", onOK, p.id) + connect(cancel, "clicked", onCancel, p.id) + connect(p.window, "close-request", onClose, p.id) + // The key controller is on the window and sees a key only after the entry has passed on + // it, so Escape still ends an input method's composition first. + keys := gtkEventControllerKeyNew() + connect(keys, "key-pressed", onKey, p.id) + gtkWidgetAddController(p.window, keys) + + gtkWindowPresent(p.window) + gtkWidgetGrabFocus(p.entry) + }) +} + +func connect(obj uintptr, signal string, handler, id uintptr) { + _ = gSignalConnectData(obj, signal, handler, id, 0, 0) +} + +// withPrompt runs body for the prompt with this id, inside guard. It does nothing when the prompt +// has ended. +func withPrompt(id uintptr, name string, body func(p *promptWindow)) { + promptsMu.Lock() + p := prompts[id] + promptsMu.Unlock() + if p != nil { + p.guard(name, func() { body(p) }) + } +} + +// end sends the answer, once, and forgets the prompt. destroy closes the window. It is false when +// GTK is closing the window already. +func (p *promptWindow) end(a answer, destroy bool) { + if p.done { + return + } + p.done = true + p.answers <- a + promptsMu.Lock() + delete(prompts, p.id) + promptsMu.Unlock() + if destroy && p.window != 0 { + gtkWindowDestroy(p.window) + } +} + +// guard runs body, which builds the prompt or handles one of its signals, on the main thread. A +// panic can't be allowed to unwind through GTK's C frames, because that would crash the app and +// stop every mount and transfer with it. So guard recovers the panic, logs it, and ends the prompt +// with an error, which the waiting caller receives. +func (p *promptWindow) guard(name string, body func()) { + defer func() { + r := recover() + if r == nil { + return + } + slog.Error("interaction: the prompt panicked", "callback", name, "panic", r, "stack", string(debug.Stack())) + // Closing the window can't be allowed to panic again either. + defer func() { _ = recover() }() + p.end(answer{err: fmt.Errorf("the prompt failed: %v", r)}, true) + }() + body() +} diff --git a/app/interaction/prompt_zenity.go b/app/interaction/prompt_zenity.go new file mode 100644 index 00000000..1678a62a --- /dev/null +++ b/app/interaction/prompt_zenity.go @@ -0,0 +1,34 @@ +//go:build !linux + +package interaction + +import ( + "errors" + + "github.com/ncruces/zenity" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// prompt asks through ncruces/zenity. It uses osascript on macOS and a Win32 dialog on Windows. +// Both would label their buttons in English (zenity's) or in the system's language (macOS's), so +// the buttons are given the app's own labels. +func prompt(title, message, def string, sensitive bool) (string, bool, error) { + opts := []zenity.Option{ + zenity.Title(title), zenity.EntryText(def), + zenity.OKLabel(i18n.T("OK")), zenity.CancelLabel(i18n.T("Cancel")), + } + if sensitive { + opts = append(opts, zenity.HideText()) + } + activate() + defer raise(title)() + value, err := zenity.Entry(message, opts...) + if errors.Is(err, zenity.ErrCanceled) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return value, true, nil +} diff --git a/app/interaction/raise_other.go b/app/interaction/raise_other.go new file mode 100644 index 00000000..8ca01f26 --- /dev/null +++ b/app/interaction/raise_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package interaction + +// raise does nothing outside Windows (see raise_windows.go), because macOS keeps osascript's prompt +// in front by itself. +func raise(string) (stop func()) { return func() {} } diff --git a/app/interaction/raise_windows.go b/app/interaction/raise_windows.go new file mode 100644 index 00000000..abb3de15 --- /dev/null +++ b/app/interaction/raise_windows.go @@ -0,0 +1,80 @@ +package interaction + +import ( + "os" + "sync" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + user32 = windows.NewLazySystemDLL("user32.dll") + procGetWindowText = user32.NewProc("GetWindowTextW") + procSetWindowPos = user32.NewProc("SetWindowPos") + procSetForeground = user32.NewProc("SetForegroundWindow") +) + +// raise keeps the prompt titled title above every other window while it shows, until the function +// it returns is called. zenity's prompt is an ordinary window, and the app's Startup window and +// launcher may open on top of it, so that nobody would see it. zenity has no option for this, so +// raise finds the prompt among this process's windows once it opens, and puts it on top. +func raise(title string) (stop func()) { + done := make(chan struct{}) + go func() { + pid := uint32(os.Getpid()) + for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); { + if h := findWindow(pid, title); h != 0 { + const hwndTopmost = ^uintptr(0) // HWND_TOPMOST, (HWND)-1 + const swpNoMove, swpNoSize = 0x0002, 0x0001 + _, _, _ = procSetWindowPos.Call(uintptr(h), hwndTopmost, 0, 0, 0, 0, swpNoMove|swpNoSize) + _, _, _ = procSetForeground.Call(uintptr(h)) + return + } + select { + case <-done: + return + case <-time.After(50 * time.Millisecond): + } + } + }() + return func() { close(done) } +} + +// search is what findWindow looks for, and what it found. enumWindow reads it, and searchMu keeps +// one search at a time. +var ( + searchMu sync.Mutex + search struct { + pid uint32 + title string + found windows.HWND + } + enumWindows = sync.OnceValue(func() uintptr { + // One callback for the process's life: Windows has a few thousand of them per process, + // and every NewCallback takes one for good. + return windows.NewCallback(func(h windows.HWND, _ uintptr) uintptr { + var owner uint32 + if _, err := windows.GetWindowThreadProcessId(h, &owner); err != nil || owner != search.pid || !windows.IsWindowVisible(h) { + return 1 + } + buf := make([]uint16, 256) + n, _, _ := procGetWindowText.Call(uintptr(h), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) + if windows.UTF16ToString(buf[:n]) == search.title { + search.found = h + return 0 + } + return 1 + }) + }) +) + +// findWindow returns the visible window of process pid whose title is title, or 0. +func findWindow(pid uint32, title string) windows.HWND { + searchMu.Lock() + defer searchMu.Unlock() + search.pid, search.title, search.found = pid, title, 0 + _ = windows.EnumWindows(enumWindows(), nil) + return search.found +} diff --git a/app/interaction/scripted_dev.go b/app/interaction/scripted_dev.go new file mode 100644 index 00000000..cf07b930 --- /dev/null +++ b/app/interaction/scripted_dev.go @@ -0,0 +1,17 @@ +//go:build !production + +package interaction + +// Scripted, when set, answers every dialog instead of the user. Development runs that are driven +// by scripts use it (see devEval in package app). prompt is true when text is asked for, and text +// is the answer to the prompt. A release build has no Scripted. +var Scripted func(d Dialog, prompt bool) (a Answer, text string) + +// scripted returns the script's answer to d, and false when no script answers. +func scripted(d Dialog, prompt bool) (Answer, string, bool) { + if Scripted == nil { + return 0, "", false + } + a, text := Scripted(d, prompt) + return a, text, true +} diff --git a/app/interaction/scripted_production.go b/app/interaction/scripted_production.go new file mode 100644 index 00000000..16130876 --- /dev/null +++ b/app/interaction/scripted_production.go @@ -0,0 +1,5 @@ +//go:build production + +package interaction + +func scripted(Dialog, bool) (Answer, string, bool) { return 0, "", false } diff --git a/app/launcher/dev.go b/app/launcher/dev.go new file mode 100644 index 00000000..5bc576df --- /dev/null +++ b/app/launcher/dev.go @@ -0,0 +1,74 @@ +//go:build !production + +package launcher + +import ( + "fmt" + "strings" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +// Development scripting (RCUI_DEV_LAUNCHER): these functions drive the launcher the way its view +// would, without a keyboard. Like the rest of the launcher, they run on the main thread. + +// DevType replaces the text, as typing would. +func (l *Launcher) DevType(text string) { + if l.view != nil { + l.view.SetQuery(text, false) + } + l.onQuery(text) +} + +func (l *Launcher) DevKey(k view.KeyEvent) bool { return l.onKey(k) } + +func (l *Launcher) DevHover(row int) { l.onHover(row) } + +func (l *Launcher) DevClick(row int) { l.onClick(row) } + +func (l *Launcher) DevDrop(paths []string) { l.onDrop(paths) } + +// DevState describes what the launcher shows: its text, the rows drawn and the selection. +func (l *Launcher) DevState() string { + var b strings.Builder + fmt.Fprintf(&b, "visible=%v text=%q busy=%v", l.Visible(), l.text, l.busy) + if l.status.Kind != view.StatusNone { + fmt.Fprintf(&b, " status=%q", l.status.Text) + } + if len(l.dropped) > 0 { + fmt.Fprintf(&b, " header=%q", droppedHeader(l.dropped)) + } + if l.panel != nil { + fmt.Fprintf(&b, " panel=%q", l.panel.result.Title) + if l.panel.question != "" { + fmt.Fprintf(&b, " question=%q", l.panel.question) + } + for i, a := range l.panel.actions { + mark := " " + if i == l.panel.sel { + mark = ">" + } + fmt.Fprintf(&b, "\n %s %s", mark, a.Name) + } + return b.String() + } + end := drawnEnd(l.spans(), l.off) + for i := l.off; i < end; i++ { + r := l.results[i] + if startsGroup(l.results, i) { + fmt.Fprintf(&b, "\n [%s]", r.Group) + } + mark := " " + if i == l.sel { + mark = ">" + } + fmt.Fprintf(&b, "\n %s %-3s %s", mark, l.rowHint(i), r.Title) + if r.Tail != "" { + fmt.Fprintf(&b, " [%s]", r.Tail) + } + } + if len(l.results) > end { + fmt.Fprintf(&b, "\n … %d more", len(l.results)-end) + } + return b.String() +} diff --git a/app/launcher/engine/engine.go b/app/launcher/engine/engine.go new file mode 100644 index 00000000..3934c3fc --- /dev/null +++ b/app/launcher/engine/engine.go @@ -0,0 +1,128 @@ +package engine + +import ( + "context" + "fmt" + "sync" + "time" +) + +// The timing of a query's snapshots. The first is sent once the quick providers have answered (or +// after firstFlush). After that, at most one is sent every flushEvery while slow providers +// (listings) are still working. +const ( + firstFlush = 16 * time.Millisecond + flushEvery = 32 * time.Millisecond +) + +type Engine struct { + providers []Provider + // Panicked is called when a provider panics. The panic is recovered either way: that provider + // returns no results, and the query continues with the others. Panicked runs on the provider's + // goroutine before the stack unwinds, so it can record the panic's stack trace. It may be nil. + Panicked func(where string, v any) +} + +func New(providers ...Provider) *Engine { + return &Engine{providers: providers} +} + +// Run runs q. emit receives the full ranked list each time, and final is true on the last call. +// Cancelling ctx (for a newer query) stops Run, and emit is not called after that. +func (e *Engine) Run(ctx context.Context, q Query, d *Data, usage Usage, emit func(results []Result, final bool)) { + var ( + mu sync.Mutex + // Each provider's results go in their own slot, so ties rank in the order the providers are + // listed, not in the order they answer. + found = make([][]Result, len(e.providers)) + pending = len(e.providers) + quickLeft = 0 + changed = make(chan struct{}, 1) + quickDone = make(chan struct{}) + ) + for _, p := range e.providers { + if _, slow := p.(Streamer); !slow { + quickLeft++ + } + } + if quickLeft == 0 { + close(quickDone) + } + signal := func() { + select { + case changed <- struct{}{}: + default: + } + } + for i, p := range e.providers { + go func(i int, p Provider) { + var rs []Result + s, slow := p.(Streamer) + defer func() { + if v := recover(); v != nil { + rs = nil + if e.Panicked != nil { + e.Panicked(fmt.Sprintf("provider %T", p), v) + } + } + mu.Lock() + found[i] = rs + pending-- + if !slow { + if quickLeft--; quickLeft == 0 { + close(quickDone) + } + } + mu.Unlock() + signal() + }() + if slow { + rs = s.QueryStream(ctx, q, d, func(part []Result) { + mu.Lock() + found[i] = part + mu.Unlock() + signal() + }) + } else { + rs = p.Query(ctx, q, d) + } + }(i, p) + } + snapshot := func() ([]Result, bool) { + mu.Lock() + defer mu.Unlock() + var all []Result + for _, rs := range found { + all = append(all, rs...) + } + return Rank(q, all, usage, time.Now()), pending == 0 + } + select { + case <-ctx.Done(): + return + case <-quickDone: + case <-time.After(firstFlush): + } + rs, final := snapshot() + if ctx.Err() != nil { + return + } + emit(rs, final) + for !final { + select { + case <-ctx.Done(): + return + case <-changed: + } + select { + case <-ctx.Done(): + return + case <-time.After(flushEvery): + } + rs, final = snapshot() + if ctx.Err() != nil { + return + } + emit(rs, final) + } +} diff --git a/app/launcher/engine/engine_test.go b/app/launcher/engine/engine_test.go new file mode 100644 index 00000000..b8103b0b --- /dev/null +++ b/app/launcher/engine/engine_test.go @@ -0,0 +1,95 @@ +package engine + +import ( + "context" + "fmt" + "slices" + "sync" + "testing" +) + +type streamer struct{ release chan struct{} } + +func (streamer) Query(context.Context, Query, *Data) []Result { return nil } + +func (s streamer) QueryStream(ctx context.Context, _ Query, _ *Data, partial func([]Result)) []Result { + one := []Result{{ID: "s:1", Title: "one"}} + partial(one) + select { + case <-ctx.Done(): + return nil + case <-s.release: + } + return append(one, Result{ID: "s:2", Title: "two"}) +} + +// TestRunStreams: a Streamer's partial results are sent in a snapshot before its final ones. +func TestRunStreams(t *testing.T) { + s := streamer{release: make(chan struct{})} + var early, last []string + released := false + New(s).Run(context.Background(), Query{}, &Data{}, nil, func(rs []Result, final bool) { + titles := make([]string, len(rs)) + for i, r := range rs { + titles[i] = r.Title + } + switch { + case final: + last = titles + case len(rs) == 1 && !released: + early, released = titles, true + close(s.release) + } + }) + if !slices.Equal(early, []string{"one"}) || !slices.Equal(last, []string{"one", "two"}) { + t.Fatalf("early %q, last %q", early, last) + } +} + +type fixed []Result + +func (f fixed) Query(context.Context, Query, *Data) []Result { return f } + +type broken struct{} + +func (broken) Query(context.Context, Query, *Data) []Result { panic("a provider broke") } + +type brokenStreamer struct{} + +func (brokenStreamer) Query(context.Context, Query, *Data) []Result { return nil } + +func (brokenStreamer) QueryStream(_ context.Context, _ Query, _ *Data, partial func([]Result)) []Result { + partial([]Result{{ID: "half", Title: "half"}}) + panic("a listing broke") +} + +// TestAProviderThatPanics: a provider's panic is reported and it returns no results. The other +// providers still answer the query, up to its final snapshot. +func TestAProviderThatPanics(t *testing.T) { + e := New(fixed{{ID: "ok", Title: "ok"}}, broken{}, brokenStreamer{}) + var reported []string + var mu sync.Mutex + e.Panicked = func(where string, v any) { + mu.Lock() + reported = append(reported, where+": "+fmt.Sprint(v)) + mu.Unlock() + } + var last []string + done := false + e.Run(context.Background(), Query{}, &Data{}, nil, func(rs []Result, final bool) { + last, done = nil, final + for _, r := range rs { + last = append(last, r.Title) + } + }) + if !done || !slices.Equal(last, []string{"ok"}) { + t.Fatalf("final %v: %q", done, last) + } + mu.Lock() + defer mu.Unlock() + slices.Sort(reported) + want := []string{"provider engine.broken: a provider broke", "provider engine.brokenStreamer: a listing broke"} + if !slices.Equal(reported, want) { + t.Errorf("reported %q", reported) + } +} diff --git a/app/launcher/engine/providers/clipboard.go b/app/launcher/engine/providers/clipboard.go new file mode 100644 index 00000000..796c2ec4 --- /dev/null +++ b/app/launcher/engine/providers/clipboard.go @@ -0,0 +1,58 @@ +package providers + +import ( + "context" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Clipboard suggests what was just copied, on the empty query: a link to download, or a path to +// browse. When the clipboard can't be read without asking the user (macOS), only the fact that it +// holds a link is known. The action then reads the clipboard once the user has chosen it. +type Clipboard struct{} + +func (Clipboard) Query(_ context.Context, q engine.Query, d *engine.Data) []engine.Result { + if !q.Empty() || len(q.Dropped) > 0 { + return nil + } + if q.Clipboard.Text == "" { + if !q.Clipboard.Link { + return nil + } + return []engine.Result{{ + ID: "clip:link", Key: "clip:download", Title: i18n.T("Download the Link You Copied"), Subtitle: i18n.T("From the clipboard."), + Icon: icons.Download, Pinned: true, Group: engine.GroupSuggested, + Actions: []engine.Action{{ID: "download", Name: openName("Download"), Icon: icons.Download, Opens: true, + Run: func(_ context.Context, env engine.Env) error { + // if it isn't a link after all, the window opens empty + link, _, _ := engine.ReadClip(env.ClipboardText(), nil, "") + env.OpenWindow("Download", withParams("/download", "initialUrl", link)) + return nil + }}}, + }} + } + link, p, ok := engine.ReadClip(q.Clipboard.Text, d.Remotes, d.Home) + switch { + case !ok: + return nil + case link != "": + return []engine.Result{{ + ID: "clip:link", Key: "clip:download", Title: downloadOp.on(urlLabel(link)).Local(), Subtitle: link, + Icon: icons.Download, Pinned: true, Group: engine.GroupSuggested, + Actions: []engine.Action{open("download", "Download", "/download", icons.Download, "initialUrl", link)}, + }} + } + arg := pathArg(p) + return []engine.Result{{ + // i18n: %s is a path that was copied to the clipboard. + ID: "clip:path", Key: "clip:browse", Title: i18n.T("Browse %s", p.Short()), Subtitle: i18n.T("Copied: %s", arg), + Icon: icons.Folder, Pinned: true, Group: engine.GroupSuggested, + Actions: []engine.Action{ + browse(arg), + named(open("copy", "Copy", "/copy", icons.Copy, "initialSource", arg), i18n.T("Copy From")), + copyText("copy-path", i18n.T("Copy Path"), arg), + }, + }} +} diff --git a/app/launcher/engine/providers/common.go b/app/launcher/engine/providers/common.go new file mode 100644 index 00000000..c44d8a0f --- /dev/null +++ b/app/launcher/engine/providers/common.go @@ -0,0 +1,211 @@ +// Package providers holds the launcher's providers, one file per domain: the operations, what is +// running (mounts, serves, VFS caches), the remotes, typed paths and their folders, and the app's +// own screens. The windows they open and the query parameters they pass are the ones that the +// pages read. +package providers + +import ( + "context" + "net/url" + "slices" + "strings" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" +) + +// All returns every provider that a typed query uses, in the order used to break ties. c lists +// folders. +func All(c *Completion) []engine.Provider { + return []engine.Provider{Operations{}, Running{}, Remotes{}, Navigation{}, Paths{}, c, Clipboard{}} +} + +// Drops returns the providers used while files are dropped on the launcher. They offer places +// where the files can go. +func Drops(c *Completion) []engine.Provider { + return []engine.Provider{c, Dropped{}} +} + +// open returns an action that opens window name at route with params (empty ones are left out). +func open(id, name, route string, icon icons.Name, params ...string) engine.Action { + return engine.Action{ID: id, Name: openName(name), Icon: icon, Opens: true, Run: func(_ context.Context, env engine.Env) error { + env.OpenWindow(name, withParams(route, params...)) + return nil + }} +} + +// openName returns the name of the action that opens a window, such as "Open Settings", in the +// app's language. Each window has a message of its own, so that a language can say it its way. +func openName(window string) string { + switch window { + case "Wizard": + return i18n.T("Open Wizard") + case "Copy": + return i18n.T("Open Copy") + case "Move": + return i18n.T("Open Move") + case "Sync": + return i18n.T("Open Sync") + case "Bisync": + return i18n.T("Open Bisync") + case "Delete": + return i18n.T("Open Delete") + case "Purge": + return i18n.T("Open Purge") + case "Download": + return i18n.T("Open Download") + case "Mount": + return i18n.T("Open Mount") + case "Serve": + return i18n.T("Open Serve") + case "Settings": + return i18n.T("Open Settings") + case "Notifications": + return i18n.T("Open Notifications") + case "MobileRemoteControl": + return i18n.T("Open Remote Control") + case "History": + return i18n.T("Open History") + case "Templates": + return i18n.T("Open Templates") + case "Watchers": + return i18n.T("Open Watchers") + case "Schedules": + return i18n.T("Open Schedules") + case "Guides": + return i18n.T("Open Guides") + case "Automounts": + return i18n.T("Open Automounts") + } + // i18n: An action that opens a window. %s is the window's name, for a window that has no message of its own. + return i18n.T("Open %s", window) +} + +// withParams returns route with the key/value pairs as its query, leaving out empty values. A key +// given more than once is repeated (for several sources). +func withParams(route string, kv ...string) string { + v := url.Values{} + for i := 0; i+1 < len(kv); i += 2 { + if kv[i+1] != "" { + v.Add(kv[i], kv[i+1]) + } + } + if s := v.Encode(); s != "" { + return route + "?" + s + } + return route +} + +// browse returns an action that opens the Commander at p (a full path, which may be a remote's +// root). +func browse(p string) engine.Action { + // i18n: An action that shows a folder's files in the Commander. + return engine.Action{ID: "browse", Name: i18n.T("Browse"), Icon: icons.Folder, Opens: true, Run: func(_ context.Context, env engine.Env) error { + env.OpenFull("Commander", withParams("/commander", "path", p)) + return nil + }} +} + +// copyText returns an action that copies text to the clipboard and shows a notification. name is +// the action's name, in the app's language. +func copyText(id, name, text string) engine.Action { + return engine.Action{ID: id, Name: name, Icon: icons.Clipboard, Run: func(_ context.Context, env engine.Env) error { + env.Clipboard(text) + // i18n: The title of the notification that something was copied to the clipboard. + env.Notify(i18n.T("Copied"), text) + return nil + }} +} + +// asks reports whether a typed word (of two letters or more) is the start of one of words, in +// the app's language or in English. For example, "br" asks for browse. Results that a word asks +// for ("Browse gdrive" for each remote) are offered only then, because otherwise they would crowd +// out the rows they repeat. +func asks(q engine.Query, words i18n.Text) bool { + local, english := engine.Words(words) + all := slices.Concat(local, english) + for _, t := range q.Terms { + if len([]rune(t)) < 2 { + continue + } + for _, w := range all { + if strings.HasPrefix(strings.ToLower(w), strings.ToLower(t)) { + return true + } + } + } + return false +} + +// only reports whether the query is one of words alone, as a drill-in leaves it ("vfs "). +func only(q engine.Query, words ...string) bool { + return len(q.Paths) == 0 && q.URL == "" && len(q.Terms) == 1 && + slices.ContainsFunc(words, func(w string) bool { return strings.EqualFold(q.Terms[0], w) }) +} + +// command returns the first of words, which is a command typed in the query box ("browse"), in +// the app's language and in English. A drill-in types it in the app's language. +func command(words i18n.Text) (local, english string) { + l, e := engine.Words(words) + if len(l) > 0 { + local = l[0] + } + if len(e) > 0 { + english = e[0] + } + return local, english +} + +// inGroup puts the results in rs that have no group yet into group g. +func inGroup(g string, rs []engine.Result) []engine.Result { + for i := range rs { + if rs[i].Group == "" { + rs[i].Group = g + } + } + return rs +} + +// back returns the last row of a drill-in, which goes back to the empty query with the launcher +// still up. It isn't matched against the query and isn't kept in the history. +func back() engine.Result { + // i18n: The launcher's row that goes back from a list to the first one. + name := i18n.T("Back") + return engine.Result{ID: "nav:back", Title: name, Subtitle: i18n.T("Return to the menu."), Icon: icons.Back, Score: 1, Always: true, + Actions: []engine.Action{{ID: "back", Name: name, Icon: icons.Back, KeepOpen: true, + Run: func(_ context.Context, env engine.Env) error { + env.SetQuery("") + return nil + }}}} +} + +// historyKey returns the history key for an item from the core ("remote:gdrive"). +func historyKey(kind, name string) string { + return kind + ":" + name +} + +// pathKey returns the history key of a path. A folder has the same key with or without its +// trailing separator, whether it was typed (Browse) or completed. +func pathKey(p string) string { + if n := len(p); n > 1 && (p[n-1] == '/' || p[n-1] == '\\') { + p = p[:n-1] + } + return historyKey("path", p) +} + +func countLabel(n int) string { + // i18n: The grey count at the right of a launcher's row: how many of its items are running. + return i18n.N("%d active", "%d active", n, n) +} + +// pathArg returns a path in the form that an operation's page expects. +func pathArg(p engine.Path) string { return p.Text } + +// scoreFor returns the score for a path's result, so remote paths can rank above local ones. +func scoreFor(p engine.Path, remote, local int) int { + if p.Local { + return local + } + return remote +} diff --git a/app/launcher/engine/providers/completion.go b/app/launcher/engine/providers/completion.go new file mode 100644 index 00000000..37c36c36 --- /dev/null +++ b/app/launcher/engine/providers/completion.go @@ -0,0 +1,246 @@ +package providers + +import ( + "context" + "sort" + "strings" + "sync" + "time" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/app/launcher/match" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +var errNoCore = errs.New("the core is not ready") + +// The completion's limits: how long it waits for typing to stop before listing, and the maximum +// number of entries it offers. +const ( + completionDelay = 120 * time.Millisecond + completionMax = 30 +) + +// Completion lists the folder of the path being typed and offers the entries whose names match +// the name being typed. Tab puts the selected one in the query. A folder's listing is streamed: +// its first page is offered at once, and the rest as they arrive. One listing per folder serves +// every query typed in that folder, so further typing lists the folder only once and doesn't +// restart a slow listing. Typing in another folder stops an unfinished listing. Listings are kept +// until Reset, which is called when the launcher hides. +type Completion struct { + mu sync.Mutex + listings map[string]*listing + ctx context.Context // the parent context of the listings, cancelled by Reset + cancel context.CancelFunc + delay time.Duration +} + +// listing holds one folder's entries as they arrive. +type listing struct { + mu sync.Mutex + entries []engine.Entry + done bool + update chan struct{} // closed at each change, then replaced + stop context.CancelFunc +} + +func NewCompletion() *Completion { + c := &Completion{delay: completionDelay} + c.Reset() + return c +} + +func (c *Completion) Reset() { + c.mu.Lock() + defer c.mu.Unlock() + if c.cancel != nil { + c.cancel() + } + c.ctx, c.cancel = context.WithCancel(context.Background()) + c.listings = map[string]*listing{} +} + +func (c *Completion) Query(ctx context.Context, q engine.Query, d *engine.Data) []engine.Result { + return c.QueryStream(ctx, q, d, func([]engine.Result) {}) +} + +// QueryStream offers the entries of the folder being typed in. Each time a page arrives, it passes +// the entries listed so far. ctx belongs to the query, so a newer query stops the waiting but not +// the listing. +func (c *Completion) QueryStream(ctx context.Context, q engine.Query, d *engine.Data, partial func([]engine.Result)) []engine.Result { + if q.Typing == nil || d.List == nil { + return nil + } + dir, prefix := split(q.Typing.Text) + l := c.listing(dir) + if l == nil { + // a new folder is listed once typing in it pauses + select { + case <-ctx.Done(): + return nil + case <-time.After(c.delay): + } + l = c.start(dir, d.List) + } + for { + l.mu.Lock() + entries, done, update := l.entries, l.done, l.update + l.mu.Unlock() + rs := results(*q.Typing, d, dir, prefix, entries, q.Dropped) + if done { + return rs + } + if len(rs) > 0 { + partial(rs) + } + select { + case <-ctx.Done(): + return nil + case <-update: + } + } +} + +func (c *Completion) listing(dir string) *listing { + c.mu.Lock() + defer c.mu.Unlock() + return c.listings[dir] +} + +// start lists dir, or joins a listing of dir that started in the meantime. It stops unfinished +// listings of other folders, because the user has moved on from them. A listing that fails is +// discarded, so the next query tries again. +func (c *Completion) start(dir string, list func(context.Context, string, func([]engine.Entry)) error) *listing { + c.mu.Lock() + defer c.mu.Unlock() + if l := c.listings[dir]; l != nil { + return l + } + for other, l := range c.listings { + l.mu.Lock() + unfinished := !l.done + l.mu.Unlock() + if unfinished { + l.stop() + delete(c.listings, other) + } + } + ctx, stop := context.WithCancel(c.ctx) + l := &listing{update: make(chan struct{}), stop: stop} + c.listings[dir] = l + go func() { + err := list(ctx, dir, func(page []engine.Entry) { l.add(page, false) }) + if err != nil || ctx.Err() != nil { + c.mu.Lock() + if c.listings[dir] == l { + delete(c.listings, dir) + } + c.mu.Unlock() + } + l.add(nil, true) + stop() + }() + return l +} + +// add appends a page, or marks the listing as ended when done is true. Either way it wakes the +// waiting queries. +func (l *listing) add(page []engine.Entry, done bool) { + l.mu.Lock() + defer l.mu.Unlock() + l.entries = append(l.entries, page...) + l.done = l.done || done + close(l.update) + l.update = make(chan struct{}) +} + +// results returns the entries of dir (in the path at) whose names match prefix, with folders +// first and at most completionMax of them. When files are dropped, only folders are returned, as +// places for the files to go. +func results(at engine.Path, d *engine.Data, dir, prefix string, entries []engine.Entry, dropped []engine.Path) []engine.Result { + type scored struct { + e engine.Entry + score int + pos []int + } + var picks []scored + for _, e := range entries { + if strings.HasPrefix(e.Name, ".") && !strings.HasPrefix(prefix, ".") || len(dropped) > 0 && !e.Dir { + continue + } + m, ok := match.Match(prefix, e.Name) + if !ok { + continue + } + s := m.Score + if e.Dir { + s += 10 // folders first, since a typed path goes through them + } + picks = append(picks, scored{e, s, m.Positions}) + } + sort.SliceStable(picks, func(i, j int) bool { return picks[i].score > picks[j].score }) + if len(picks) > completionMax { + picks = picks[:completionMax] + } + out := make([]engine.Result, 0, len(picks)) + for i, p := range picks { + full := dir + p.e.Name + if len(dropped) > 0 { + full += "/" + out = append(out, engine.Result{ + ID: "complete:" + full, Key: historyKey("drop:path", full), Title: p.e.Name + "/", + // i18n: Under a folder, as a place for what was dropped on the launcher. %s is a file's name, or "3 items". + Subtitle: i18n.T("Copy %s here", droppedLabel(dropped)), + Icon: icons.Folder, Score: 120 + p.score - i, Always: true, Complete: full, + Actions: []engine.Action{transferTo("copy", "Copy", dropped, full), transferTo("move", "Move", dropped, full)}, + }) + out[len(out)-1].SetMatch(p.pos) + continue + } + icon := icons.File + if p.e.Dir { + full += "/" + icon = icons.Folder + } + entry := engine.Path{Text: full, Local: at.Local, Remote: at.Remote, Features: at.Features} + copyPath := copyText("copy-path", i18n.T("Copy Path"), full) + // Enter browses a folder, or copies a file's path + actions := append([]engine.Action{copyPath}, pathActions(entry, d, false)...) + if p.e.Dir { + actions = append(pathActions(entry, d, true), copyPath) + } + out = append(out, engine.Result{ + ID: "complete:" + full, Key: pathKey(full), Title: p.e.Name + dirSuffix(p.e.Dir), Subtitle: full, Icon: icon, + Score: 120 + p.score - i, Always: true, Complete: full, Actions: actions, Group: engine.GroupFiles, + }) + out[len(out)-1].SetMatch(p.pos) + } + return out +} + +// split splits a typed path into its folder (with the separator) and the name being typed in it. +// "gdrive:Pho" → "gdrive:", "Pho"; "gdrive:a/b" → "gdrive:a/", "b"; "/tmp/x" → "/tmp/", "x". +func split(p string) (dir, name string) { + i := strings.LastIndexAny(p, "/\\") + if c := strings.Index(p, ":"); c > i && !(c == 1 && len(p) > 2) { + i = c + } + if i < 0 { + return p, "" + } + return p[:i+1], p[i+1:] +} + +func dirSuffix(dir bool) string { + if dir { + return "/" + } + return "" +} + +func named(a engine.Action, name string) engine.Action { + a.Name = name + return a +} diff --git a/app/launcher/engine/providers/dropped.go b/app/launcher/engine/providers/dropped.go new file mode 100644 index 00000000..2317d619 --- /dev/null +++ b/app/launcher/engine/providers/dropped.go @@ -0,0 +1,121 @@ +package providers + +import ( + "context" + "path/filepath" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Dropped offers what can be done with files dropped on the launcher. They can be copied or moved +// to where the text says (a typed path, a remote, or a folder listed by completion), or to a +// place chosen in the operation's window. A single dropped folder can also be browsed, synced or +// served. +type Dropped struct{} + +func (Dropped) Query(_ context.Context, q engine.Query, d *engine.Data) []engine.Result { + if len(q.Dropped) == 0 { + return nil + } + label := droppedLabel(q.Dropped) + folder := len(q.Dropped) == 1 && isDir(q.Dropped[0].Text) + var out []engine.Result + if len(q.Paths) > 0 { + // a destination was typed, so it comes first + dest := pathArg(q.Paths[len(q.Paths)-1]) + short := q.Paths[len(q.Paths)-1].Short() + // i18n: %[1]s is what was dropped on the launcher (a file's name, or "3 items"), and %[2]s where it goes. + copyTo := i18n.T("Copy %[1]s to %[2]s", label, short) + out = append(out, + droppedResult("copy-to", copyTo, dest, icons.Copy, 200, transferTo("copy", "Copy", q.Dropped, dest), transferTo("move", "Move", q.Dropped, dest)), + droppedResult("move-to", i18n.T("Move %[1]s to %[2]s", label, short), dest, icons.Move, 190, transferTo("move", "Move", q.Dropped, dest)), + ) + if folder { + out = append(out, droppedResult("sync-to", i18n.T("Sync %[1]s to %[2]s", label, short), dest, icons.Sync, 180, transferTo("sync", "Sync", q.Dropped, dest))) + } + } else { + // offer the remotes as destinations: typing a name picks one, and Tab goes into it + for _, r := range d.Remotes { + root := r.Name + ":" + // i18n: %s is a remote's type, such as "drive" or "s3". + sub := i18n.T("To the %s remote. Press Tab to open subfolders.", r.Type) + res := droppedResult("remote:"+r.Name, i18n.T("Copy %[1]s to %[2]s", label, root), sub, icons.Remote, 100, + transferTo("copy", "Copy", q.Dropped, root), transferTo("move", "Move", q.Dropped, root)) + res.Key = historyKey("drop:remote", r.Name) + res.Keywords = []string{r.Name, r.Type} + res.Complete = root + out = append(out, res) + } + } + // i18n: %s is what was dropped on the launcher: a file's name, or "3 items". The window that opens asks where it goes. + copyWhere := i18n.T("Copy %s to…", label) + out = append(out, + droppedResult("copy", copyWhere, i18n.T("Choose where, in the Copy window."), icons.Copy, 60, transferTo("copy", "Copy", q.Dropped, "")), + droppedResult("move", i18n.T("Move %s to…", label), i18n.T("Choose where, in the Move window."), icons.Move, 58, transferTo("move", "Move", q.Dropped, "")), + ) + if folder { + f := q.Dropped[0].Text + s := open("serve", "Serve", "/serve", icons.Serve, "initialSource", f) + s.Name = i18n.T("Serve") + out = append(out, + droppedResult("sync", i18n.T("Sync %s to…", label), i18n.T("Choose where, in the Sync window."), icons.Sync, 56, transferTo("sync", "Sync", q.Dropped, "")), + droppedResult("serve", + // i18n: %s is the name of the folder that was dropped on the launcher. + i18n.T("Serve %s", label), + i18n.T("Over HTTP, WebDAV, SFTP and more."), icons.Serve, 54, s), + droppedResult("browse", i18n.T("Browse %s", label), i18n.T("Open it in the Commander."), icons.Folder, 52, browse(f)), + ) + } + return out +} + +func droppedResult(id, title, subtitle string, icon icons.Name, score int, actions ...engine.Action) engine.Result { + return engine.Result{ID: "drop:" + id, Key: "drop:" + id, Title: title, Subtitle: subtitle, Icon: icon, + Score: score, Actions: actions} +} + +// transferTo returns an action that opens the operation's window with the dropped files as its +// sources, and dest as its destination when there is one. name is the operation's window. +func transferTo(id, name string, sources []engine.Path, dest string) engine.Action { + params := make([]string, 0, 2*len(sources)+2) + for _, s := range sources { + params = append(params, "initialSource", s.Text) + } + params = append(params, "initialDestination", dest) + a := open(id, name, "/"+id, map[string]icons.Name{"copy": icons.Copy, "move": icons.Move, "sync": icons.Sync}[id], params...) + a.Name = transferName(id, dest != "") + return a +} + +// transferName returns the name of the action that sends dropped files with operation id, to a +// destination when here is set ("Copy Here"), or else to one chosen in its window ("Copy"). +func transferName(id string, here bool) string { + switch { + case id == "move" && here: + // i18n: An action that moves the files that were dropped on the launcher into the selected folder. + return i18n.T("Move Here") + case id == "move": + return i18n.T("Move") + case id == "sync" && here: + return i18n.T("Sync Here") + case id == "sync": + return i18n.T("Sync") + case here: + // i18n: An action that copies the files that were dropped on the launcher into the selected folder. + return i18n.T("Copy Here") + } + return i18n.T("Copy") +} + +// droppedLabel describes what was dropped: the file's name (a string), or the number of items (a +// message). The rows pass it as a value to their own messages, which translate a message value +// along with themselves. +func droppedLabel(ps []engine.Path) any { + if len(ps) == 1 { + return filepath.Base(ps[0].Text) + } + // i18n: What was dropped on the launcher, inside a longer line such as "Copy 3 items to gdrive:". + return i18n.MN("%d item", "%d items", len(ps), len(ps)) +} diff --git a/app/launcher/engine/providers/isdir.go b/app/launcher/engine/providers/isdir.go new file mode 100644 index 00000000..08b8cb83 --- /dev/null +++ b/app/launcher/engine/providers/isdir.go @@ -0,0 +1,9 @@ +package providers + +import "os" + +// isDir reports whether a dropped path is a folder. A path that no longer exists is not. +func isDir(p string) bool { + st, err := os.Stat(p) + return err == nil && st.IsDir() +} diff --git a/app/launcher/engine/providers/navigation.go b/app/launcher/engine/providers/navigation.go new file mode 100644 index 00000000..b8d960ba --- /dev/null +++ b/app/launcher/engine/providers/navigation.go @@ -0,0 +1,120 @@ +package providers + +import ( + "context" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Navigation offers the app's own screens, GitHub and Quit. +type Navigation struct{} + +// GitHubURL is the repository's page. The GitHub entry opens it here and in the tray menu. +const GitHubURL = "https://github.com/rclone/rclone-ui" + +// screen is one of the rows that Navigation offers, with its title and its search words as +// messages (see engine.Result.Say). A zero title keeps the row's own, which is a name. +type screen struct { + row engine.Result + title, words i18n.Text +} + +// screens returns the rows of the app's screens, in the order that breaks their ties. +func screens() []screen { + return []screen{{ + row: engine.Result{ID: "nav:settings", Key: "nav:settings", Subtitle: i18n.T("Appearance, language, updates, proxy and more."), Icon: icons.Settings, Score: 34, + Actions: []engine.Action{open("open", "Settings", "/settings", icons.Settings)}}, + title: i18n.M("Settings"), + // i18n: Search words for the launcher's Settings row, separated by commas. Add any word that people would type to find it. + words: i18n.M("settings, preferences, proxy, about"), + }, { + row: engine.Result{ID: "nav:notifications", Key: "nav:notifications", Subtitle: i18n.T("Get notified on Slack, Discord, Telegram, email or a webhook."), Icon: icons.Bell, Score: 26, + Actions: []engine.Action{open("open", "Notifications", "/notifications", icons.Bell)}}, + title: i18n.M("Notifications"), + // i18n: Search words for the launcher's Notifications row, separated by commas. Add any word that people would type to find it. + words: i18n.M("notifications, alerts, webhooks, email"), + }, { + row: engine.Result{ID: "nav:mobileRemoteControl", Key: "nav:mobileRemoteControl", Subtitle: i18n.T("Use rclone from your phone."), Icon: icons.Mobile, Score: 25, + Actions: []engine.Action{open("open", "MobileRemoteControl", "/mobileRemoteControl", icons.Mobile)}}, + // i18n: The screen that lets a phone use Rclone UI: the Mobile & Remote Control window, by its short name. + title: i18n.M("Remote Control"), + // i18n: Search words for the launcher's Remote Control row, separated by commas. Add any word that people would type to find it. + words: i18n.M("remote control, mobile, phone, tunnel, qr"), + }, { + row: engine.Result{ID: "nav:commander", Key: "nav:commander", Subtitle: i18n.T("Browse remotes and this computer side by side."), Icon: icons.Commander, Score: 32, + Actions: []engine.Action{{ID: "open", Name: i18n.T("Open Commander"), Icon: icons.Commander, Opens: true, Run: func(_ context.Context, env engine.Env) error { + env.OpenFull("Commander", "/commander") + return nil + }}}}, + // i18n: The app's two-pane file manager. + title: i18n.M("Commander"), + // i18n: Search words for the launcher's Commander row, separated by commas. Add any word that people would type to find it. + words: i18n.M("commander, explorer, navigator, navigate, browse, files"), + }, { + // GitHub is a name, so its title isn't translated. Its search words are. + row: engine.Result{ID: "nav:github", Key: "nav:github", Title: "GitHub", Subtitle: i18n.T("Open an issue or star the GitHub repo (we appreciate it)."), Icon: icons.GitHub, Score: 32, + Actions: []engine.Action{{ID: "open", Name: i18n.T("Open GitHub"), Icon: icons.Browser, Run: func(_ context.Context, env engine.Env) error { + env.OpenURL(GitHubURL) + return nil + }}}}, + // i18n: Search words for the launcher's GitHub row, separated by commas. Add any word that people would type to find it. + words: i18n.M("github, issue, bug, feature"), + }, { + row: engine.Result{ID: "nav:history", Key: "nav:history", Subtitle: i18n.T("Your running and past transfers."), Icon: icons.Transfers, Score: 30, + Actions: []engine.Action{open("open", "History", "/history", icons.Transfers)}}, + title: i18n.M("History"), + // i18n: Search words for the launcher's History row, separated by commas. Add any word that people would type to find it. + words: i18n.M("history, transfers, jobs, tasks"), + }, { + row: engine.Result{ID: "nav:templates", Key: "nav:templates", Subtitle: i18n.T("Save your settings and apply them quickly."), Icon: icons.Templates, Score: 28, + Actions: []engine.Action{open("open", "Templates", "/templates", icons.Templates)}}, + title: i18n.M("Templates"), + // i18n: Search words for the launcher's Templates row, separated by commas. Add any word that people would type to find it. + words: i18n.M("templates, examples, presets"), + }, { + row: engine.Result{ID: "nav:watchers", Key: "nav:watchers", Subtitle: i18n.T("Keep two folders the same, like Dropbox."), Icon: icons.Watchers, Score: 27, + Actions: []engine.Action{open("open", "Watchers", "/watchers", icons.Watchers)}}, + title: i18n.M("Watchers"), + // i18n: Search words for the launcher's Watchers row, separated by commas. Add any word that people would type to find it. + words: i18n.M("watchers, watch, keep in sync, dropbox, folders"), + }, { + row: engine.Result{ID: "nav:schedules", Key: "nav:schedules", Subtitle: i18n.T("Run a copy, a sync or another operation at set times."), Icon: icons.Schedules, Score: 27, + Actions: []engine.Action{open("open", "Schedules", "/schedules", icons.Schedules)}}, + title: i18n.M("Schedules"), + // i18n: Search words for the launcher's Schedules row, separated by commas. Add any word that people would type to find it. + words: i18n.M("schedules, schedule, cron, every day, nightly, backup, timer"), + }, { + row: engine.Result{ID: "nav:guides", Key: "nav:guides", Subtitle: i18n.T("Learn more about what you can do with Rclone UI."), Icon: icons.Guides, Score: 29, + Actions: []engine.Action{open("open", "Guides", "/guides", icons.Guides)}}, + title: i18n.M("Guides"), + // i18n: Search words for the launcher's Guides row, separated by commas. Add any word that people would type to find it. + words: i18n.M("guides, help, how to, learn, tutorial, docs, getting started"), + }, { + row: engine.Result{ID: "nav:automounts", Key: "nav:automounts", Subtitle: i18n.T("Mount a remote each time Rclone UI starts."), Icon: icons.Automounts, Score: 27, + Actions: []engine.Action{open("open", "Automounts", "/automounts", icons.Automounts)}}, + title: i18n.M("Automounts"), + // i18n: Search words for the launcher's Automounts row, separated by commas. Add any word that people would type to find it. + words: i18n.M("automounts, automount, auto mount, mount at login, startup"), + }, { + // no history key, so Quit is never suggested + row: engine.Result{ID: "nav:quit", Subtitle: i18n.T("Quit the application."), Icon: icons.Quit, Score: 20, + Actions: []engine.Action{{ID: "quit", Name: i18n.T("Quit"), Icon: icons.Quit, Run: func(_ context.Context, env engine.Env) error { + env.Quit() + return nil + }}}}, + title: i18n.M("Quit"), + // i18n: Search words for the launcher's Quit row, separated by commas. Add any word that people would type to find it. + words: i18n.M("quit, exit, close"), + }} +} + +func (Navigation) Query(context.Context, engine.Query, *engine.Data) []engine.Result { + list := screens() + out := make([]engine.Result, 0, len(list)) + for _, s := range list { + out = append(out, s.row.Say(s.title, s.words)) + } + return inGroup(engine.GroupApp, out) +} diff --git a/app/launcher/engine/providers/operations.go b/app/launcher/engine/providers/operations.go new file mode 100644 index 00000000..fc78bc97 --- /dev/null +++ b/app/launcher/engine/providers/operations.go @@ -0,0 +1,349 @@ +package providers + +import ( + "context" + "net/url" + "path" + "strings" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Operations offers the operation pages (copy, move, sync, bisync, delete, purge, download, mount, +// serve), opened with the typed paths, and cleanup, which runs in the launcher. The empty query +// lists none of them: "Run" opens the Wizard, which asks what the user wants to do and +// finds the operation for it. Typing finds each operation by name. +type Operations struct{} + +// wizard returns "Run", which opens the Wizard. +func wizard() engine.Result { + return engine.Result{ + ID: "op:wizard", Key: "op:wizard", Icon: icons.Wizard, Score: 50, + Subtitle: i18n.T("Copy, Sync, Move, Bisync, and other rclone operations."), + Actions: []engine.Action{open("open", "Wizard", "/wizard", icons.Wizard)}, + }.Say( + // i18n: The launcher's row that opens the Wizard, which asks what to do and finds the operation for it. + i18n.M("Run"), + // i18n: Search words for the launcher's Run row, separated by commas. Add any word that people would type to find it. + i18n.M("wizard, run, operation, start, new")) +} + +// op is an operation page. Its messages name it in its rows. +type op struct { + id, window, route string + icon icons.Name + name, desc i18n.Text + // words are the search words, separated by commas (see engine.Result.Say). + words i18n.Text + // on names the operation on a path, or on a transfer's paths: "Copy gdrive:Photos". + on func(what string) i18n.Text + score int // ranks the operations that a query matches equally + // pair, from and to are set for an operation from a source to a destination. pair names it + // on both ("Copy gdrive:a → /b"), from on its source and to on its destination. + pair func(src, dst string) i18n.Text + from, to func(p string) i18n.Text +} + +var ( + copyOp = op{id: "copy", window: "Copy", route: "/copy", icon: icons.Copy, score: 50, + // i18n: The Copy operation, which copies files from a source to a destination. + name: i18n.M("Copy"), + desc: i18n.M("Copy files from a source to a destination without deleting destination files."), + // i18n: Search words for the launcher's Copy row, separated by commas. Add any word that people would type to find it. + words: i18n.M("copy, cp"), + on: func(w string) i18n.Text { return i18n.M("Copy %s", w) }, + pair: func(a, b string) i18n.Text { return i18n.M("Copy %s → %s", a, b) }, + from: func(p string) i18n.Text { return i18n.M("Copy from %s", p) }, + to: func(p string) i18n.Text { return i18n.M("Copy to %s", p) }} + moveOp = op{id: "move", window: "Move", route: "/move", icon: icons.Move, score: 48, + name: i18n.M("Move"), + desc: i18n.M("Move files from a source to a destination and delete them from the source."), + // i18n: Search words for the launcher's Move row, separated by commas. Add any word that people would type to find it. + words: i18n.M("move, mv"), + on: func(w string) i18n.Text { return i18n.M("Move %s", w) }, + pair: func(a, b string) i18n.Text { return i18n.M("Move %s → %s", a, b) }, + from: func(p string) i18n.Text { return i18n.M("Move from %s", p) }, + to: func(p string) i18n.Text { return i18n.M("Move to %s", p) }} + syncOp = op{id: "sync", window: "Sync", route: "/sync", icon: icons.Sync, score: 46, + name: i18n.M("Sync"), + desc: i18n.M("Make destination match source (deletes extra files)."), + // i18n: Search words for the launcher's Sync row, separated by commas. Add any word that people would type to find it. + words: i18n.M("sync, synchronise, synchronize"), + on: func(w string) i18n.Text { return i18n.M("Sync %s", w) }, + pair: func(a, b string) i18n.Text { return i18n.M("Sync %s → %s", a, b) }, + from: func(p string) i18n.Text { return i18n.M("Sync from %s", p) }, + to: func(p string) i18n.Text { return i18n.M("Sync to %s", p) }} + bisyncOp = op{id: "bisync", window: "Bisync", route: "/bisync", icon: icons.Bisync, score: 44, + name: i18n.M("Bisync"), + desc: i18n.M("Keeps two folders the same, in both directions."), + // i18n: Search words for the launcher's Bisync row, separated by commas. Add any word that people would type to find it. + words: i18n.M("bisync, two-way"), + on: func(w string) i18n.Text { return i18n.M("Bisync %s", w) }, + pair: func(a, b string) i18n.Text { return i18n.M("Bisync %s ↔ %s", a, b) }, + from: func(p string) i18n.Text { return i18n.M("Bisync from %s", p) }, + to: func(p string) i18n.Text { return i18n.M("Bisync to %s", p) }} + deleteOp = op{id: "delete", window: "Delete", route: "/delete", icon: icons.Delete, score: 38, + name: i18n.M("Delete"), + desc: i18n.M("Delete files or folders from a remote or local path."), + // i18n: Search words for the launcher's Delete row, separated by commas. Add any word that people would type to find it. + words: i18n.M("delete, remove, rm"), + on: func(w string) i18n.Text { return i18n.M("Delete %s", w) }} + purgeOp = op{id: "purge", window: "Purge", route: "/purge", icon: icons.Purge, score: 36, + name: i18n.M("Purge"), + desc: i18n.M("Purge an entire path from a remote, deleting everything."), + // i18n: Search words for the launcher's Purge row, separated by commas. Add any word that people would type to find it. + words: i18n.M("purge, empty"), + on: func(w string) i18n.Text { return i18n.M("Purge %s", w) }} + downloadOp = op{id: "download", window: "Download", route: "/download", icon: icons.Download, score: 45, + name: i18n.M("Download"), + desc: i18n.M("Download a URL directly into a remote or local path."), + // i18n: Search words for the launcher's Download row, separated by commas. Add any word that people would type to find it. + words: i18n.M("download, url, copyurl, copyto"), + on: func(w string) i18n.Text { return i18n.M("Download %s", w) }} + mountOp = op{id: "mount", window: "Mount", route: "/mount", icon: icons.Mount, score: 42, + // i18n: The Mount operation, which mounts a remote as a local folder or drive. + name: i18n.M("Mount"), + desc: i18n.M("Mount a remote to the local filesystem with VFS options."), + // i18n: Search words for the launcher's Mount row, separated by commas. Add any word that people would type to find it. + words: i18n.M("mount"), + on: func(w string) i18n.Text { return i18n.M("Mount %s", w) }} + serveOp = op{id: "serve", window: "Serve", route: "/serve", icon: icons.Serve, score: 40, + // i18n: The Serve operation, which serves a remote over HTTP, WebDAV, SFTP and more. + name: i18n.M("Serve"), + desc: i18n.M("Serve a remote over HTTP, WebDAV, SFTP, FTP and Restic."), + // i18n: Search words for the launcher's Serve row, separated by commas. Add any word that people would type to find it. + words: i18n.M("serve, http, webdav, sftp, ftp, restic, dlna, nfs, s3"), + on: func(w string) i18n.Text { return i18n.M("Serve %s", w) }} +) + +// opByID returns the operation page with that id. A transfer's Operation uses the same ids. +func opByID(id string) (op, bool) { + for _, o := range []op{copyOp, moveOp, syncOp, bisyncOp, deleteOp, purgeOp, downloadOp, mountOp, serveOp} { + if o.id == id { + return o, true + } + } + return op{}, false +} + +// pairOps are the operations from a source to a destination. +var pairOps = []op{copyOp, moveOp, syncOp, bisyncOp} + +// from returns an action that opens o's window with p as its source. name is its label in the ⌘K +// panel. +func from(o op, p engine.Path, name string) engine.Action { + return named(open(o.id, o.window, o.route, o.icon, "initialSource", pathArg(p)), name) +} + +// Query returns the operations. Without paths or a URL, it also returns "Run". With paths, it +// offers each operation on them (as a pair for two or more). With a URL, it offers to download it. +func (Operations) Query(_ context.Context, q engine.Query, d *engine.Data) []engine.Result { + var out []engine.Result + if len(q.Paths) == 0 && q.URL == "" { + out = append(out, wizard()) + } + for _, o := range pairOps { + out = append(out, transferResults(o, q)...) + } + out = append(out, singleResults(deleteOp, q, func(engine.Path) bool { return true })...) + out = append(out, singleResults(purgeOp, q, func(p engine.Path) bool { return p.Can("Purge") })...) + out = append(out, singleResults(mountOp, q, func(engine.Path) bool { return true })...) + out = append(out, serveResults(q, d)...) + out = append(out, downloadResults(q)...) + out = append(out, cleanupResults(q, d)...) + return inGroup(engine.GroupOperations, out) +} + +// generic returns an operation's own result, which opens its window empty. The empty query gets +// none: "Run" stands for them there. +func generic(o op, q engine.Query) []engine.Result { + if q.Empty() { + return nil + } + return []engine.Result{o.result(engine.Result{ + ID: "op:" + o.id, Key: "op:" + o.id, Score: o.score, + Actions: []engine.Action{open("open", o.window, o.route, o.icon)}, + }, o.name)} +} + +// result returns r as one of o's rows: titled title, with o's description, icon and search words. +func (o op) result(r engine.Result, title i18n.Text) engine.Result { + r.Subtitle, r.Icon = o.desc.Local(), o.icon + return r.Say(title, o.words) +} + +func transferResults(o op, q engine.Query) []engine.Result { + if len(q.Paths) == 0 { + return generic(o, q) + } + var out []engine.Result + if len(q.Paths) >= 2 { + src, dst := q.Paths[0], q.Paths[len(q.Paths)-1] + out = append(out, o.result(engine.Result{ + ID: "op:" + o.id + ":pair", Key: "op:" + o.id, Score: 200, + Actions: []engine.Action{open("open", o.window, o.route, o.icon, "initialSource", pathArg(src), "initialDestination", pathArg(dst))}, + }, o.pair(src.Short(), dst.Short()))) + } + for i, p := range q.Paths { + role, label, score := "initialSource", o.from(p.Short()), scoreFor(p, 160, 140) + if len(q.Paths) >= 2 && i == len(q.Paths)-1 { + role, label, score = "initialDestination", o.to(p.Short()), 155 + } + out = append(out, o.result(engine.Result{ + ID: "op:" + o.id + ":" + role + ":" + p.Text, Key: "op:" + o.id, Score: score, + Actions: []engine.Action{open("open", o.window, o.route, o.icon, role, pathArg(p))}, + }, label)) + } + return out +} + +// singleResults returns an operation on one path at a time, for the paths that ok accepts. +func singleResults(o op, q engine.Query, ok func(engine.Path) bool) []engine.Result { + if len(q.Paths) == 0 { + return generic(o, q) + } + var out []engine.Result + for _, p := range q.Paths { + if !ok(p) { + continue + } + out = append(out, o.result(engine.Result{ + ID: "op:" + o.id + ":" + p.Text, Key: "op:" + o.id, Score: scoreFor(p, 150, 140), + Actions: []engine.Action{open("open", o.window, o.route, o.icon, "initialSource", pathArg(p))}, + }, o.on(p.Short()))) + } + return out +} + +// serveResults returns Serve for each path, over the type named by a word ("serve webdav +// gdrive:"). +func serveResults(q engine.Query, d *engine.Data) []engine.Result { + typ := "" + for _, t := range q.Terms { + for _, st := range d.ServeTypes { + if strings.EqualFold(t, st) { + typ = st + } + } + } + if len(q.Paths) == 0 { + return generic(serveOp, q) + } + var out []engine.Result + for _, p := range q.Paths { + label := serveOp.on(p.Short()) + if typ != "" { + // i18n: %[1]s is a path, and %[2]s a protocol such as WEBDAV. + label = i18n.M("Serve %[1]s over %[2]s", p.Short(), strings.ToUpper(typ)) + } + out = append(out, serveOp.result(engine.Result{ + ID: "op:serve:" + typ + ":" + p.Text, Key: "op:serve", Score: scoreFor(p, 160, 140), + Actions: []engine.Action{open("open", "Serve", "/serve", icons.Serve, "initialSource", pathArg(p), "initialType", typ)}, + }, label)) + } + return out +} + +// downloadResults returns downloads of the typed URL into each typed path. Either can be left +// out and chosen later in the window. +func downloadResults(q engine.Query) []engine.Result { + if q.URL == "" && len(q.Paths) == 0 { + return generic(downloadOp, q) + } + label := urlLabel(q.URL) + var out []engine.Result + for _, p := range q.Paths { + t, score := i18n.M("Download to %s", p.Short()), scoreFor(p, 160, 150) + if q.URL != "" { + // i18n: %[1]s is the file that a link points to, and %[2]s where it goes. + t, score = i18n.M("Download %[1]s to %[2]s", label, p.Short()), scoreFor(p, 200, 190) + } + out = append(out, downloadOp.result(engine.Result{ + ID: "op:download:" + p.Text, Key: "op:download", Score: score, Always: q.URL != "", + Actions: []engine.Action{open("open", "Download", "/download", icons.Download, "initialUrl", q.URL, "initialDestination", pathArg(p))}, + }, t)) + } + if q.URL != "" && len(q.Paths) == 0 { + r := downloadOp.result(engine.Result{ + ID: "op:download:url", Key: "op:download", Score: 170, Always: true, + Actions: []engine.Action{open("open", "Download", "/download", icons.Download, "initialUrl", q.URL)}, + }, downloadOp.on(label)) + r.Subtitle = q.URL + out = append(out, r) + } + return out +} + +// urlLabel returns the last name in a URL's path, or its host. +func urlLabel(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return raw + } + if base := path.Base(u.Path); base != "" && base != "/" && base != "." { + return base + } + return u.Host +} + +// cleanupResults returns Cleanup for each remote that supports it: the typed ones, or all of them +// when a word is typed. If none supports it, a typed word gets a Cleanup row that says so. No row +// has a history key, because a single pick would move Cleanup above Browse for the typed remote, +// and Enter would then ask to delete. +func cleanupResults(q engine.Query, d *engine.Data) []engine.Result { + desc := i18n.T("Clean up a remote: empty its trash, or delete old versions of files.") + // i18n: Search words for the launcher's Cleanup rows, separated by commas. Add any word that people would type to find them. + words := i18n.M("cleanup, clean, trash") + var remotes []string + if len(q.Paths) > 0 { + seen := map[string]bool{} + for _, p := range q.Paths { + if p.Can("CleanUp") && !seen[p.Remote] { + seen[p.Remote] = true + remotes = append(remotes, p.Remote) + } + } + } else if len(q.Terms) > 0 { + for _, r := range d.Remotes { + if r.Features["CleanUp"] { + remotes = append(remotes, r.Name) + } + } + } + var out []engine.Result + for _, r := range remotes { + // i18n: %s is a remote's name. + title := i18n.M("Clean up %s", r) + out = append(out, engine.Result{ + ID: "op:cleanup:" + r, Subtitle: desc, Icon: icons.Cleanup, Score: 150, Actions: []engine.Action{cleanup(r)}, + }.Say(title, words)) + } + if len(remotes) == 0 && len(q.Paths) == 0 && len(q.Terms) > 0 { + // i18n: The cleanup operation, which empties a remote's trash and removes old file versions. + title := i18n.M("Cleanup") + out = append(out, engine.Result{ + ID: "op:cleanup", Subtitle: i18n.T("None of the remotes here can be cleaned up."), Icon: icons.Cleanup, Score: 36, + }.Say(title, words)) + } + return out +} + +// cleanup returns an action that starts rclone's cleanup of remote as a transfer, so the History +// page can follow it. It asks for confirmation first, because what it deletes can't be recovered. +func cleanup(remote string) engine.Action { + return engine.Action{ID: "cleanup", Name: i18n.T("Cleanup"), Icon: icons.Cleanup, Stay: true, + Confirm: i18n.T("Clean up %s? Trash and old file versions will be removed for good.", remote), + Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Transfers + if c == nil { + return errNoCore + } + if _, err := c.StartCleanup(ctx, remote+":"); err != nil { + return err + } + env.Status(engine.StatusDone, i18n.T("Cleanup of %s: started.", remote)) + return nil + }} +} diff --git a/app/launcher/engine/providers/operations_test.go b/app/launcher/engine/providers/operations_test.go new file mode 100644 index 00000000..423b1e29 --- /dev/null +++ b/app/launcher/engine/providers/operations_test.go @@ -0,0 +1,36 @@ +package providers + +import ( + "strings" + "testing" +) + +// TestCleanupAsks: Cleanup, as a row or in a panel, asks before it deletes anything. No Cleanup +// row is kept in the history, so a typed remote still offers Browse first. +func TestCleanupAsks(t *testing.T) { + const want = "Clean up gdrive? Trash and old file versions will be removed for good." + for _, text := range []string{"c", "cl", "clean", "trash", "gdrive", "gdrive:", "cleanup gdrive:"} { + rs := run(t, text, data(), nil) + asked := 0 + for _, r := range rs { + if strings.HasPrefix(r.ID, "op:cleanup") && r.Key != "" { + t.Errorf("%q: %q has the history key %q", text, r.Title, r.Key) + } + for _, a := range r.Actions { + if a.ID != "cleanup" { + continue + } + asked++ + if a.Confirm != want { + t.Errorf("%q: %q's Cleanup asks %q", text, r.Title, a.Confirm) + } + } + } + if asked == 0 { + t.Errorf("%q: no Cleanup in %q", text, titles(rs)) + } + } + if got := first(run(t, "gdrive", data(), nil)); got != "Browse gdrive:" { + t.Errorf("gdrive: first is %q", got) + } +} diff --git a/app/launcher/engine/providers/paths.go b/app/launcher/engine/providers/paths.go new file mode 100644 index 00000000..73bcffee --- /dev/null +++ b/app/launcher/engine/providers/paths.go @@ -0,0 +1,82 @@ +package providers + +import ( + "context" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Paths offers each typed path. The default action browses it in the Commander, and the ⌘K panel +// lists every operation that can start from it. +type Paths struct{} + +func (Paths) Query(_ context.Context, q engine.Query, d *engine.Data) []engine.Result { + var out []engine.Result + for _, p := range q.Paths { + arg := pathArg(p) + // i18n: %s is a remote's name. + subtitle := i18n.T("Browse files and folders in %s.", p.Remote) + if p.Local { + subtitle = i18n.T("Browse files and folders on this machine.") + } + // i18n: %s is a path. + title := i18n.M("Browse %s", p.Short()) + out = append(out, engine.Result{ + ID: "path:" + arg, Key: pathKey(arg), Subtitle: subtitle, Icon: icons.Folder, Score: 165, + Actions: append(pathActions(p, d, true), copyText("copy-path", i18n.T("Copy Path"), arg)), + }.Say(title, pathWords)) + } + return inGroup(engine.GroupFiles, out) +} + +var ( + // i18n: Search words for the launcher's row that browses a typed path, separated by commas. Add any word that people would type to find it. + pathWords = i18n.M("browse, open, view, files") +) + +// pathActions returns every operation that can start from p. It is used for the ⌘K panel of a +// typed path, a remote and a listed entry. A file (dir false) gets only the operations that accept +// a file. The caller adds the action that copies the path, because it chooses its name. +func pathActions(p engine.Path, d *engine.Data, dir bool) []engine.Action { + arg := pathArg(p) + var out []engine.Action + if dir { + out = append(out, browse(arg)) + } + // i18n: Actions on a path, which open the operation's window with the path as its source. + out = append(out, from(copyOp, p, i18n.T("Copy From")), from(moveOp, p, i18n.T("Move From"))) + if dir { + out = append(out, + from(syncOp, p, i18n.T("Sync From")), + from(bisyncOp, p, i18n.T("Bisync From")), + // i18n: An action on a folder, which opens the Download window with the folder as where the file goes. + named(open("download", "Download", "/download", icons.Download, "initialDestination", arg), i18n.T("Download Here")), + from(mountOp, p, i18n.T("Mount")), + from(serveOp, p, i18n.T("Serve")), + ) + } + out = append(out, from(deleteOp, p, i18n.T("Delete"))) + if dir && p.Can("Purge") { + out = append(out, from(purgeOp, p, i18n.T("Purge"))) + } + if p.Can("CleanUp") { + out = append(out, cleanup(p.Remote)) + } + if !p.Local { + out = append(out, remotesWindow("edit", i18n.T("Edit Remote"), "edit", p.Remote)) + if dir { + out = append(out, newAutomount(p.Text)) + } + } + if p.Local { + // i18n: An action that shows a file or folder in the file manager (Finder, Explorer). + out = append(out, engine.Action{ID: "reveal", Name: i18n.T("Reveal"), Icon: icons.Reveal, + Run: func(_ context.Context, env engine.Env) error { + env.Reveal(p.Text) + return nil + }}) + } + return out +} diff --git a/app/launcher/engine/providers/progress.go b/app/launcher/engine/providers/progress.go new file mode 100644 index 00000000..feaef44a --- /dev/null +++ b/app/launcher/engine/providers/progress.go @@ -0,0 +1,79 @@ +package providers + +import ( + "fmt" + "math" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/core/i18n" +) + +// progressLine formats the progress as the transfers row shows it: "42% · 12 MB/s · 3 min left". +// Unknown parts are left out, and it returns "" when nothing is known. +func progressLine(p corestate.Sum) string { + var parts []string + if p.Pct >= 0 { + parts = append(parts, fmt.Sprintf("%d%%", p.Pct)) + } + if p.Speed >= 1 { + parts = append(parts, Size(int64(p.Speed))+"/s") + } + if p.Left > 0 { + parts = append(parts, left(p.Left)) + } + return strings.Join(parts, " · ") +} + +// Size formats a number of bytes the way the pages do (1024 bytes to a KB): "512 B", "1.5 MB", +// "12 GB". +func Size(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%d B", n) + } + v, i := float64(n)/unit, 0 + for v >= unit && i < 3 { + v /= unit + i++ + } + suffix := []string{"KB", "MB", "GB", "TB"}[i] + if v < 10 { + return strings.TrimSuffix(fmt.Sprintf("%.1f", v), ".0") + " " + suffix + } + return fmt.Sprintf("%.0f %s", v, suffix) +} + +// left formats the time a transfer has left: "less than a minute left", "3 min left", +// "2 h 5 min left". +func left(d time.Duration) string { + if d < time.Minute { + return i18n.T("less than a minute left") + } + mins := int(math.Ceil(d.Minutes())) + if mins < 60 { + // i18n: The time a transfer has left, in minutes. + return i18n.N("%d min left", "%d min left", mins, mins) + } + if h := mins / 60; mins%60 == 0 { + // i18n: The time a transfer has left, in hours. + return i18n.N("%d h left", "%d h left", h, h) + } + // i18n: The time a transfer has left, in hours (%[1]d) and minutes (%[2]d). + return i18n.T("%[1]d h %[2]d min left", mins/60, mins%60) +} + +// ago formats how long ago t was: "just now", "10 min ago", "3 h ago". +func ago(t, now time.Time) string { + switch d := now.Sub(t); { + case d < time.Minute: + return i18n.T("just now") + case d < time.Hour: + m := int(d.Minutes()) + return i18n.N("%d min ago", "%d min ago", m, m) + default: + h := int(d.Hours()) + return i18n.N("%d h ago", "%d h ago", h, h) + } +} diff --git a/app/launcher/engine/providers/providers_test.go b/app/launcher/engine/providers/providers_test.go new file mode 100644 index 00000000..7a619ca7 --- /dev/null +++ b/app/launcher/engine/providers/providers_test.go @@ -0,0 +1,965 @@ +package providers + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "reflect" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/vfs" +) + +// ms returns t in milliseconds since the epoch, the unit of a transfer's times. +func ms(t time.Time) *int64 { + v := t.UnixMilli() + return &v +} + +// eta returns a transfer's seconds left. +func eta(s int64) *int64 { return &s } + +// data returns a core state with three remotes (one of which can clean up and purge), a mount, a +// serve, two VFS caches, and a folder to complete in. +func data() *engine.Data { + return &engine.Data{ + Remotes: []engine.Remote{ + {Name: "gdrive", Type: "drive", Features: map[string]bool{"CleanUp": true, "Purge": true}}, + {Name: "s3-backup", Type: "s3"}, + {Name: "My Box", Type: "box"}, + }, + Mounts: []mounts.MountRow{ + {ID: "m1", Source: "gdrive:", MountPoint: "/Volumes/gdrive", State: "running"}, + }, + Serves: []serves.ServeRow{ + {ID: "s1", Type: "http", Source: "s3-backup:", Addr: "127.0.0.1:8080", State: "running"}, + }, + Vfs: []vfs.VFS{ + {ID: "m1", Kind: "mount", Fs: "gdrive:", Name: "/Volumes/gdrive"}, + {ID: "s1", Kind: "serve", Fs: "s3-backup:", Name: "http 127.0.0.1:8080"}, + }, + ServeTypes: []string{"dlna", "ftp", "http", "nfs", "restic", "s3", "sftp", "webdav"}, + List: func(_ context.Context, dir string, page func([]engine.Entry)) error { + if dir != "gdrive:" { + return nil + } + page([]engine.Entry{ + {Name: "Photos", Path: "gdrive:Photos", Dir: true}, + {Name: "Projects", Path: "gdrive:Projects", Dir: true}, + }) + page([]engine.Entry{ + {Name: "photo.jpg", Path: "gdrive:photo.jpg"}, + {Name: ".hidden", Path: "gdrive:.hidden", Dir: true}, + }) + return nil + }, + } +} + +// run runs text through every provider and returns the final ranked results. +func run(t *testing.T, text string, d *engine.Data, usage engine.Usage) []engine.Result { + t.Helper() + c := NewCompletion() + c.delay = 0 + e := engine.New(Operations{}, Running{}, Remotes{}, Navigation{}, Paths{}, c) + q := engine.Parse(text, d.Remotes, d.Home) + var last []engine.Result + done := false + e.Run(context.Background(), q, d, usage, func(rs []engine.Result, final bool) { last, done = rs, final }) + if !done { + t.Fatalf("%q: no final snapshot", text) + } + return last +} + +func titles(rs []engine.Result) []string { + out := make([]string, len(rs)) + for i, r := range rs { + out[i] = r.Title + } + return out +} + +// TestEmptyQueryListsTheGroups: the running items come first, then "Run" (which stands +// for the operations), the remotes and the app's screens, each group under its label. +func TestEmptyQueryListsTheGroups(t *testing.T) { + rs := run(t, "", data(), nil) + got := titles(rs) + want := []string{"gdrive: → /Volumes/gdrive", "HTTP s3-backup: · 127.0.0.1:8080", + "Run", "VFS", + "gdrive", "s3-backup", "My Box", "Show Remotes", "New Remote", + "Settings", "Commander", "GitHub", "History", "Guides", "Templates", "Watchers", "Schedules", "Automounts", "Notifications", "Remote Control", "Quit"} + if !reflect.DeepEqual(got, want) { + t.Errorf("empty query:\n got %q\nwant %q", got, want) + } + var groups []string + for _, r := range rs { + if len(groups) == 0 || groups[len(groups)-1] != r.Group { + groups = append(groups, r.Group) + } + } + if want := []string{engine.GroupActive, engine.GroupOperations, engine.GroupRemotes, engine.GroupApp}; !slices.Equal(groups, want) { + t.Errorf("groups %q, want %q", groups, want) + } + idle := data() + idle.Mounts, idle.Serves = nil, nil + if rs := run(t, "", idle, nil); rs[0].Title != "Run" { + t.Errorf("nothing running: first %q", rs[0].Title) + } +} + +// TestRecentsComeFirst: results that the history says are used come first in their group. The +// operations stay out of the empty query however much they are used. +func TestRecentsComeFirst(t *testing.T) { + now := time.Now() + usage := engine.Usage{ + "op:sync": {Count: 5, Last: now.Add(-time.Hour)}, + "remote:s3-backup": {Count: 3, Last: now.Add(-2 * time.Hour)}, + "remote:gdrive": {Count: 1, Last: now}, // a single use isn't a habit + } + got := titles(run(t, "", data(), usage)) + remotes := slices.Index(got, "s3-backup") + if remotes < 0 || got[remotes+1] != "gdrive" || slices.Contains(got, "Sync") { + t.Errorf("recents first: got %q", got) + } +} + +// TestOperationsWhenTyped: a word finds the operations that the empty query leaves out, and +// "Run" is found by its own words. +func TestOperationsWhenTyped(t *testing.T) { + if got := titles(run(t, "sync", data(), nil)); len(got) == 0 || got[0] != "Sync" { + t.Errorf("sync: got %q", got) + } + if got := titles(run(t, "wizard", data(), nil)); len(got) == 0 || got[0] != "Run" { + t.Errorf("wizard: got %q", got) + } +} + +// TestActiveIsCapped: with more than four running items, the empty query lists three, plus a row +// that shows all of them, as "active" does. +func TestActiveIsCapped(t *testing.T) { + d := data() + for _, id := range []string{"m2", "m3", "m4"} { + d.Mounts = append(d.Mounts, mounts.MountRow{ID: id, Source: id + ":", MountPoint: "/Volumes/" + id, State: "running"}) + } + rs := run(t, "", d, nil) + var active []string + for _, r := range rs { + if r.Group == engine.GroupActive { + active = append(active, r.Title) + } + } + if len(active) != activeMax || active[activeMax-1] != "Show All Running" { + t.Fatalf("active: %q", active) + } + got := titles(run(t, "active ", d, nil)) + if len(got) != 6 || got[len(got)-1] != "Back" || slices.Contains(got, "Show All Running") { + t.Errorf("active: %q", got) + } +} + +// TestTransfersAreActive: the queued and running transfers are one row, first among the running +// items, which opens the History window. "stop" offers to stop them, and to stop everything, +// saying what will stop. +func TestTransfersAreActive(t *testing.T) { + d := data() + d.Transfers = []transfers.Transfer{ + {ID: "t1", State: "running", Operation: "copy", Sources: []string{"gdrive:Photos"}, Destination: "/tmp/photos"}, + {ID: "t2", State: "queued", Operation: "delete", Sources: []string{"s3-backup:old"}}, + } + rs := run(t, "", d, nil) + if rs[0].Title != "2 Transfers" || rs[0].Subtitle != "1 running, 1 queued" || rs[0].Group != engine.GroupActive { + t.Errorf("first: %q, %q, %q", rs[0].Title, rs[0].Subtitle, rs[0].Group) + } + if a, _ := rs[0].Default(); a.Name != "Open History" { + t.Errorf("default: %q", a.Name) + } + d.Transfers = d.Transfers[:1] + if rs := run(t, "", d, nil); rs[0].Title != "Copy gdrive:Photos → /tmp/photos" || rs[0].Subtitle != "Running" { + t.Errorf("one transfer: %q, %q", rs[0].Title, rs[0].Subtitle) + } + got := run(t, "stop", d, nil) + everything := slices.IndexFunc(got, func(r engine.Result) bool { return r.Title == "Stop Everything" }) + if everything < 0 || !slices.Contains(titles(got), "Stop Transfer") { + t.Fatalf("stop: %q", titles(got)) + } + a, _ := got[everything].Default() + if a.Confirm != "Stop a transfer, a serve and a mount?" || !a.Stay { + t.Errorf("stop everything asks %q (stays %v)", a.Confirm, a.Stay) + } + idle := data() + idle.Mounts, idle.Serves = nil, nil + if _, ok := StopEverything(idle); ok { + t.Error("nothing runs: nothing to stop") + } + // The tunnel stops too, so the question names it. + idle.Tunnel = true + if r, ok := StopEverything(idle); !ok || r.Actions[0].Confirm != "Stop the remote tunnel?" { + t.Errorf("the tunnel is on: %v, %+v", ok, r) + } +} + +// TestTransfersSayHowFar: once the core reports progress, the transfers row shows the combined +// progress instead of "Running". +func TestTransfersSayHowFar(t *testing.T) { + d := data() + d.Transfers = []transfers.Transfer{{ID: "t1", State: "running", Operation: "sync", Sources: []string{"/tmp/photos"}, + Destination: "gdrive:Photos", Live: &bus.TransferProgress{Bytes: 42 << 20, TotalBytes: 100 << 20, Speed: 12 << 20, Eta: eta(170)}}} + rs := run(t, "", d, nil) + if rs[0].Title != "Sync /tmp/photos → gdrive:Photos" || rs[0].Subtitle != "42% · 12 MB/s · 3 min left" { + t.Errorf("one: %q, %q", rs[0].Title, rs[0].Subtitle) + } + d.Transfers = append(d.Transfers, + transfers.Transfer{ID: "t2", State: "running", Operation: "copy", Sources: []string{"gdrive:a"}, Destination: "/tmp/a", + Live: &bus.TransferProgress{Bytes: 8 << 20, TotalBytes: 100 << 20, Speed: 1 << 19}}, + transfers.Transfer{ID: "t3", State: "queued", Operation: "copy", Sources: []string{"gdrive:b"}, Destination: "/tmp/b"}) + if rs := run(t, "", d, nil); rs[0].Subtitle != "2 running, 1 queued · 25% · 12 MB/s" { + t.Errorf("several: %q", rs[0].Subtitle) + } +} + +// TestFailedTransfers: a transfer that failed in the last day gets its own row among the running +// items, which opens its details. An older failure doesn't, and neither does a success. +func TestFailedTransfers(t *testing.T) { + d := data() + now := time.Now() + d.Failed = []transfers.Transfer{ + {ID: "f1", State: "failed", Operation: "sync", Sources: []string{"/tmp/Photos"}, Destination: "gdrive:Photos", + Error: "12 files couldn't be copied\nmore", EndedAt: ms(now.Add(-10 * time.Minute))}, + {ID: "f2", State: "failed", Operation: "delete", Sources: []string{"s3-backup:old"}, EndedAt: ms(now.Add(-25 * time.Hour))}, + // A watcher's run is left out: it runs every minute, and has its own window. + {ID: "f3", State: "failed", Operation: "bisync", Sources: []string{"/tmp/a"}, Destination: "/tmp/b", + Origin: transfers.Origin{Kind: transfers.OriginWatcher}, EndedAt: ms(now.Add(-time.Minute))}, + // A retry of a watcher's run is the user's own, so it is listed. + {ID: "f4", State: "failed", Operation: "bisync", Sources: []string{"/tmp/a"}, Destination: "/tmp/b", + Origin: transfers.Origin{Kind: transfers.OriginWatcher}, RetryOf: "f3", EndedAt: ms(now.Add(-time.Minute))}, + } + rs := run(t, "", d, nil) + if slices.ContainsFunc(rs, func(r engine.Result) bool { return r.ID == "run:failed:f3" }) { + t.Error("a watcher's failed run is listed") + } + if !slices.ContainsFunc(rs, func(r engine.Result) bool { return r.ID == "run:failed:f4" }) { + t.Error("a failed retry of a watcher's run is not listed") + } + i := slices.IndexFunc(rs, func(r engine.Result) bool { return r.ID == "run:failed:f1" }) + if i < 0 || rs[i].Title != "Sync failed: /tmp/Photos → gdrive:Photos" || rs[i].Group != engine.GroupActive || + rs[i].Subtitle != "Failed 10 min ago: 12 files couldn't be copied" { + t.Fatalf("failed: %q", titles(rs)) + } + if slices.ContainsFunc(rs, func(r engine.Result) bool { return r.ID == "run:failed:f2" }) { + t.Error("a failure older than a day is listed") + } + e := &env{} + a, _ := rs[i].Default() + if err := a.Run(context.Background(), e); err != nil || !slices.Equal(e.calls, []string{"window History /history?id=f1"}) { + t.Errorf("open: %v, %q", err, e.calls) + } + if got := titles(run(t, "failed", d, nil)); !slices.Contains(got, "Sync failed: /tmp/Photos → gdrive:Photos") { + t.Errorf("failed: %q", got) + } + if got := titles(run(t, "s3-backup:", d, nil)); slices.Contains(got, "Sync failed: /tmp/Photos → gdrive:Photos") { + t.Errorf("another path: %q", got) + } +} + +// TestProgressLine: the known parts of the progress, in a short line. +func TestProgressLine(t *testing.T) { + for _, c := range []struct { + p corestate.Sum + want string + }{ + {corestate.Sum{Pct: -1}, ""}, + {corestate.Sum{Pct: 0}, "0%"}, + {corestate.Sum{Pct: 99, Speed: 900, Left: 20 * time.Second}, "99% · 900 B/s · less than a minute left"}, + {corestate.Sum{Pct: -1, Speed: 3 << 30, Left: 125 * time.Minute}, "3 GB/s · 2 h 5 min left"}, + {corestate.Sum{Pct: 5, Left: 2 * time.Hour}, "5% · 2 h left"}, + } { + if got := progressLine(c.p); got != c.want { + t.Errorf("%+v: %q, want %q", c.p, got, c.want) + } + } +} + +// TestOpensMarksTheWindows: an action is marked Opens exactly when it opens one of the app's +// windows, so the launcher can make the app active for it. +func TestOpensMarksTheWindows(t *testing.T) { + d := data() + seen := 0 + for _, text := range []string{"", "gdrive:", "copy gdrive: /tmp", "https://example.com/f.zip gdrive:", "vfs ", "stop", "edit", "browse", "auto"} { + for _, r := range run(t, text, d, nil) { + for _, a := range r.Actions { + if a.Run == nil { + continue + } + e := &env{clip: "https://example.com/x.zip"} + _ = a.Run(context.Background(), e) + opened := slices.ContainsFunc(e.calls, func(c string) bool { + return strings.HasPrefix(c, "window ") || strings.HasPrefix(c, "full ") + }) + if opened != a.Opens { + t.Errorf("%q › %q: opens a window %v, marked Opens %v", r.Title, a.Name, opened, a.Opens) + } + seen++ + } + } + } + if seen < 50 { + t.Fatalf("only %d actions run", seen) + } +} + +func TestFirstResult(t *testing.T) { + cases := []struct{ text, first string }{ + {"copy", "Copy"}, + {"c", "Copy"}, + {"sync", "Sync"}, + {"copy gdrive: /tmp", "Copy gdrive: → /tmp"}, + // Sync is one-way and deletes, so it uses Copy's arrow, not Bisync's + {"sync gdrive: /tmp", "Sync gdrive: → /tmp"}, + {"bisync gdrive: /tmp", "Bisync gdrive: ↔ /tmp"}, + {"gdrive: /tmp", "Copy gdrive: → /tmp"}, + {"https://example.com/f.zip gdrive:", "Download f.zip to gdrive:"}, + {"example.com/archive.tar", "Download archive.tar"}, + {"serve webdav gdrive:", "Serve gdrive: over WEBDAV"}, + {"settings", "Settings"}, + {"quit", "Quit"}, + {"gdr", "gdrive"}, + {"my box", "Browse My Box:"}, + } + for _, c := range cases { + rs := run(t, c.text, data(), nil) + if len(rs) == 0 || rs[0].Title != c.first { + t.Errorf("%q: first is %q, want %q (all: %q)", c.text, first(rs), c.first, titles(rs)) + } + } +} + +func first(rs []engine.Result) string { + if len(rs) == 0 { + return "" + } + return rs[0].Title +} + +func TestContains(t *testing.T) { + cases := []struct { + text string + has []string + not []string + }{ + // "mount gdrive:" offers Mount on the typed path + {"mount gdrive:", []string{"Mount gdrive:"}, nil}, + // a path typed alone gets every operation that can start from it + {"gdrive:", []string{"Browse gdrive:", "Copy from gdrive:", "Move from gdrive:", "Sync from gdrive:", "Bisync from gdrive:", + "Mount gdrive:", "Serve gdrive:", "Download to gdrive:", "Delete gdrive:", "Purge gdrive:", "Clean up gdrive", + "Edit gdrive", "New automount for gdrive"}, nil}, + {"s3-backup:", []string{"Browse s3-backup:"}, []string{"Purge s3-backup:", "Cleanup s3-backup"}}, + {"/tmp", []string{"Browse /tmp", "Copy from /tmp", "Mount /tmp", "Download to /tmp"}, []string{"Purge /tmp", "Edit /tmp"}}, + {"cleanup", []string{"Clean up gdrive"}, []string{"Cleanup s3-backup", "Cleanup"}}, + {"vfs", []string{"Forget the VFS cache of gdrive:", "Forget Every VFS Cache", "Back"}, nil}, + {"mount", []string{"Mount", "gdrive: → /Volumes/gdrive", "Unmount /Volumes/gdrive"}, nil}, + {"serve", []string{"Serve", "HTTP s3-backup: · 127.0.0.1:8080", "Stop HTTP s3-backup:"}, nil}, + {"stop", []string{"gdrive: → /Volumes/gdrive", "Unmount /Volumes/gdrive", "HTTP s3-backup: · 127.0.0.1:8080", + "Stop HTTP s3-backup:"}, []string{"Unmount All", "Stop All Serves"}}, + // the Browse drill-in lists each remote, and Back + {"browse", []string{"Browse gdrive", "Browse s3-backup", "Browse My Box", "Back"}, []string{"gdrive"}}, + {"browse gd", []string{"Browse gdrive"}, []string{"Back"}}, + {"gdr", []string{"gdrive"}, []string{"Browse gdrive", "Edit gdrive"}}, + {"edit", []string{"Edit gdrive", "Edit s3-backup", "Edit My Box"}, nil}, + {"auto mount", []string{"New automount for gdrive"}, nil}, + {"copy", nil, []string{"Back"}}, + {"schedules", []string{"Schedules"}, nil}, + } + for _, c := range cases { + got := titles(run(t, c.text, data(), nil)) + for _, h := range c.has { + if !slices.Contains(got, h) { + t.Errorf("%q: missing %q in %q", c.text, h, got) + } + } + for _, n := range c.not { + if slices.Contains(got, n) { + t.Errorf("%q: unexpected %q in %q", c.text, n, got) + } + } + } +} + +// TestToolbarCommands: every command is found by its name and by its keywords. +func TestToolbarCommands(t *testing.T) { + cases := []struct{ text, title string }{ + {"copy", "Copy"}, {"cp", "Copy"}, + {"move", "Move"}, {"mv", "Move"}, + {"sync", "Sync"}, {"synchronize", "Sync"}, + {"bisync", "Bisync"}, + {"mount", "Mount"}, + {"serve", "Serve"}, {"webdav", "Serve"}, + {"download", "Download"}, {"url", "Download"}, + {"cleanup", "Clean up gdrive"}, {"clean", "Clean up gdrive"}, + {"browse", "Browse gdrive"}, {"explore", "Browse gdrive"}, + {"delete", "Delete"}, {"rm", "Delete"}, + {"purge", "Purge"}, {"empty", "Purge"}, + {"settings", "Settings"}, {"preferences", "Settings"}, {"proxy", "Settings"}, + {"notifications", "Notifications"}, {"webhook", "Notifications"}, + {"mobile", "Remote Control"}, {"phone", "Remote Control"}, {"remote control", "Remote Control"}, + {"commander", "Commander"}, {"navigate", "Commander"}, {"explorer", "Commander"}, + {"github", "GitHub"}, {"issue", "GitHub"}, + {"transfers", "History"}, {"history", "History"}, + {"templates", "Templates"}, + {"watchers", "Watchers"}, {"dropbox", "Watchers"}, + {"schedules", "Schedules"}, {"cron", "Schedules"}, {"nightly", "Schedules"}, + {"new remote", "New Remote"}, {"create", "New Remote"}, + {"edit", "Edit gdrive"}, + {"auto mount", "New automount for gdrive"}, + {"show remotes", "Show Remotes"}, {"remotes", "Show Remotes"}, {"config", "Show Remotes"}, + {"quit", "Quit"}, {"exit", "Quit"}, + {"vfs", "Forget Every VFS Cache"}, {"forget", "Forget Every VFS Cache"}, + } + for _, c := range cases { + if got := titles(run(t, c.text, data(), nil)); !slices.Contains(got, c.title) { + t.Errorf("%q: missing %q in %q", c.text, c.title, got) + } + } + // the rows shown when there is nothing to list: no remote can clean up, none to browse, no + // cache + d := data() + d.Remotes, d.Vfs = nil, nil + for text, want := range map[string]string{"cleanup": "Cleanup", "browse": "Browse", "vfs": "VFS"} { + if got := titles(run(t, text, d, nil)); !slices.Contains(got, want) { + t.Errorf("%q with nothing: missing %q in %q", text, want, got) + } + } +} + +// TestPanels: a remote, a path and a listed folder each offer every operation that can start from +// them. +func TestPanels(t *testing.T) { + panel := func(text, title string) []string { + t.Helper() + for _, r := range run(t, text, data(), nil) { + if r.Title == title { + names := make([]string, len(r.Actions)) + for i, a := range r.Actions { + names[i] = a.Name + } + return names + } + } + t.Fatalf("%q: no %q", text, title) + return nil + } + all := []string{"Browse", "Copy From", "Move From", "Sync From", "Bisync From", "Download Here", "Mount", "Serve", "Delete"} + cases := []struct { + text, title string + want []string + }{ + {"gdr", "gdrive", append(all, "Purge", "Cleanup", "Edit Remote", "New Automount", "Copy Name")}, + {"s3-backup:x", "Browse s3-backup:x", append(all, "Edit Remote", "New Automount", "Copy Path")}, + {"/tmp", "Browse /tmp", append(all, "Reveal", "Copy Path")}, + {"gdrive:Pho", "Photos/", append(all, "Purge", "Cleanup", "Edit Remote", "New Automount", "Copy Path")}, + {"gdrive:photo.", "photo.jpg", []string{"Copy Path", "Copy From", "Move From", "Delete", "Cleanup", "Edit Remote"}}, + } + for _, c := range cases { + if got := panel(c.text, c.title); !slices.Equal(got, c.want) { + t.Errorf("%q %q:\n got %q\nwant %q", c.text, c.title, got, c.want) + } + } +} + +func TestCompletion(t *testing.T) { + rs := run(t, "gdrive:pho", data(), nil) + var entries []engine.Result + for _, r := range rs { + if strings.HasPrefix(r.ID, "complete:") { + entries = append(entries, r) + } + } + got := titles(entries) + if !slices.Equal(got, []string{"Photos/", "photo.jpg"}) { + t.Fatalf("entries %q", got) + } + if entries[0].Complete != "gdrive:Photos/" || !reflect.DeepEqual(entries[0].Match(), []int{0, 1, 2}) { + t.Errorf("Photos: complete %q, match %v", entries[0].Complete, entries[0].Match()) + } + // a hidden entry is offered only when its dot is typed, and nothing is offered for a path that + // isn't being typed + if got := titles(run(t, "gdrive:.h", data(), nil)); !slices.Contains(got, ".hidden/") { + t.Errorf("dot typed: %q", got) + } + for _, r := range run(t, "gdrive: ", data(), nil) { + if strings.HasPrefix(r.ID, "complete:") { + t.Errorf("a path followed by a space is not being typed: %q", r.Title) + } + } +} + +// slowList is a listing that sends its first page at once and the second after release. It +// counts how often it is called, and closes stopped if its context ends first. +type slowList struct { + calls atomic.Int32 + release chan struct{} + stopped chan struct{} + fail bool +} + +func newSlowList() *slowList { + return &slowList{release: make(chan struct{}), stopped: make(chan struct{})} +} + +func (l *slowList) list(ctx context.Context, dir string, page func([]engine.Entry)) error { + l.calls.Add(1) + page([]engine.Entry{{Name: "first", Path: dir + "first", Dir: true}}) + select { + case <-ctx.Done(): + close(l.stopped) + return ctx.Err() + case <-l.release: + } + if l.fail { + return errors.New("unreachable") + } + page([]engine.Entry{{Name: "fine", Path: dir + "fine"}}) + return nil +} + +// typing returns a query that is typing the path text. +func typing(text string) engine.Query { + return engine.Query{Typing: &engine.Path{Text: text, Remote: "gdrive"}} +} + +// TestCompletionStreams: the first page is offered before the listing ends, and the rest once it +// ends. +func TestCompletionStreams(t *testing.T) { + c := NewCompletion() + c.delay = 0 + l := newSlowList() + d := &engine.Data{List: l.list} + partials := make(chan []string, 4) + final := make(chan []string, 1) + go func() { + rs := c.QueryStream(context.Background(), typing("gdrive:f"), d, func(rs []engine.Result) { partials <- titles(rs) }) + final <- titles(rs) + }() + if got := <-partials; !slices.Equal(got, []string{"first/"}) { + t.Fatalf("first page: %q", got) + } + close(l.release) + if got := <-final; !slices.Equal(got, []string{"first/", "fine"}) { + t.Fatalf("whole listing: %q", got) + } +} + +// TestCompletionSharesListing: further typing in a folder joins its listing rather than starting +// another, even when the newer query cancelled the earlier one. +func TestCompletionSharesListing(t *testing.T) { + c := NewCompletion() + c.delay = 0 + l := newSlowList() + d := &engine.Data{List: l.list} + ctx, cancel := context.WithCancel(context.Background()) + got := make(chan struct{}) + go func() { + c.QueryStream(ctx, typing("gdrive:f"), d, func([]engine.Result) { close(got) }) + }() + <-got + cancel() // the next keystroke + done := make(chan []string, 1) + go func() { + done <- titles(c.QueryStream(context.Background(), typing("gdrive:fi"), d, func([]engine.Result) {})) + }() + close(l.release) + if rs := <-done; !slices.Equal(rs, []string{"fine", "first/"}) && !slices.Equal(rs, []string{"first/", "fine"}) { + t.Fatalf("results %q", rs) + } + if n := l.calls.Load(); n != 1 { + t.Fatalf("listed %d times", n) + } + // a finished listing is reused for the folder until Reset + c.QueryStream(context.Background(), typing("gdrive:"), d, func([]engine.Result) {}) + if n := l.calls.Load(); n != 1 { + t.Fatalf("listed %d times after it finished", n) + } +} + +// TestCompletionStopsOtherFolder: typing in another folder stops the unfinished listing of the +// first one, and a listing that failed is tried again. +func TestCompletionStopsOtherFolder(t *testing.T) { + c := NewCompletion() + c.delay = 0 + first := newSlowList() + got := make(chan struct{}) + go c.QueryStream(context.Background(), typing("gdrive:a/"), &engine.Data{List: first.list}, func([]engine.Result) { + select { + case <-got: + default: + close(got) + } + }) + <-got + second := newSlowList() + close(second.release) + c.QueryStream(context.Background(), typing("gdrive:b/"), &engine.Data{List: second.list}, func([]engine.Result) {}) + select { + case <-first.stopped: + case <-time.After(time.Second): + t.Fatal("the first folder's listing went on") + } + + failing := newSlowList() + failing.fail = true + close(failing.release) + d := &engine.Data{List: failing.list} + c.QueryStream(context.Background(), typing("gdrive:c/"), d, func([]engine.Result) {}) + c.QueryStream(context.Background(), typing("gdrive:c/"), d, func([]engine.Result) {}) + if n := failing.calls.Load(); n != 2 { + t.Fatalf("a failed listing was asked %d times, want it tried again", n) + } +} + +// env records the calls that actions make. +type env struct { + calls []string + yes bool + clip string +} + +func (e *env) ClipboardText() string { return e.clip } + +func (e *env) OpenWindow(name, url string) { e.calls = append(e.calls, "window "+name+" "+url) } +func (e *env) OpenFull(name, url string) { e.calls = append(e.calls, "full "+name+" "+url) } +func (e *env) SetQuery(text string) { e.calls = append(e.calls, "query "+text) } +func (e *env) Clipboard(text string) { e.calls = append(e.calls, "clipboard "+text) } +func (e *env) Reveal(path string) { e.calls = append(e.calls, "reveal "+path) } +func (e *env) OpenURL(url string) { e.calls = append(e.calls, "url "+url) } +func (e *env) Notify(title, body string) { e.calls = append(e.calls, "notify "+title+": "+body) } +func (e *env) Status(kind engine.StatusKind, text string) { + if kind == engine.StatusDone { + e.calls = append(e.calls, "done "+text) + } +} +func (e *env) Ask(question, yes string) bool { + e.calls = append(e.calls, "ask "+question) + return e.yes +} +func (e *env) Quit() { e.calls = append(e.calls, "quit") } +func (e *env) Core() engine.Services { return engine.Services{} } + +func TestDefaultActions(t *testing.T) { + cases := []struct{ text, title, call string }{ + {"copy gdrive: /tmp", "Copy gdrive: → /tmp", "window Copy /copy?initialDestination=%2Ftmp&initialSource=gdrive%3A"}, + {"move /tmp", "Move from /tmp", "window Move /move?initialSource=%2Ftmp"}, + {"https://example.com/f.zip gdrive:", "Download f.zip to gdrive:", "window Download /download?initialDestination=gdrive%3A&initialUrl=https%3A%2F%2Fexample.com%2Ff.zip"}, + {"serve webdav gdrive:", "Serve gdrive: over WEBDAV", "window Serve /serve?initialSource=gdrive%3A&initialType=webdav"}, + {"gdrive:Photos", "Browse gdrive:Photos", "full Commander /commander?path=gdrive%3APhotos"}, + {"edit gdrive", "Edit gdrive", "window Remotes /remotes?action=edit&remote=gdrive"}, + {"new remote", "New Remote", "window Remotes /remotes?action=create"}, + {"mount", "gdrive: → /Volumes/gdrive", "reveal /Volumes/gdrive"}, + {"commander", "Commander", "full Commander /commander"}, + {"", "VFS", "query vfs "}, + } + for _, c := range cases { + var r *engine.Result + for _, x := range run(t, c.text, data(), nil) { + if x.Title == c.title { + r = &x + break + } + } + if r == nil { + t.Errorf("%q: no %q", c.text, c.title) + continue + } + a, ok := r.Default() + if !ok { + if c.call != "" { + t.Errorf("%q: %q has no action", c.text, c.title) + } + continue + } + e := &env{} + if _, err := runAction(a, e); err != nil && c.call != "" { + t.Errorf("%q: %v", c.text, err) + } + if c.call != "" && (len(e.calls) == 0 || e.calls[0] != c.call) { + t.Errorf("%q: %q did %q, want %q", c.text, c.title, e.calls, c.call) + } + } +} + +func TestStopsAskFirst(t *testing.T) { + for _, text := range []string{"mount", "stop"} { + for _, r := range run(t, text, data(), nil) { + for _, a := range r.Actions { + if (a.ID == "stop" || a.ID == "stop-all") && a.Confirm == "" { + t.Errorf("%q: %q's %q doesn't ask first", text, r.Title, a.Name) + } + } + } + } +} + +// TestQuitIsNeverARecent: Quit has no history key, so however often it is picked, an empty query +// never suggests it. +func TestQuitIsNeverARecent(t *testing.T) { + now := time.Now() + usage := engine.Usage{"nav:quit": {Count: 9, Last: now}} // as if Quit had been picked often + rs := run(t, "", data(), usage) + if rs[0].Title == "Quit" { + t.Errorf("quit suggested: %q", titles(rs)) + } + for _, r := range append(rs, run(t, "quit", data(), nil)...) { + if r.Title == "Quit" && r.Key != "" { + t.Errorf("Quit has the history key %q", r.Key) + } + } +} + +// TestCompletionKeys: a completed folder is stored in the history under the same key as the typed +// folder, with or without a trailing separator. A folder offered for dropped files has its own +// key. +func TestCompletionKeys(t *testing.T) { + keys := map[string]string{} + for _, r := range run(t, "gdrive:Pho", data(), nil) { + keys[r.Title] = r.Key + } + if keys["Photos/"] != "path:gdrive:Photos" || keys["photo.jpg"] != "path:gdrive:photo.jpg" { + t.Errorf("completed: %q", keys) + } + for _, text := range []string{"gdrive:Photos", "gdrive:Photos/"} { + for _, r := range run(t, text, data(), nil) { + if r.Title == "Browse "+text && r.Key != "path:gdrive:Photos" { + t.Errorf("%q: %q", text, r.Key) + } + } + } + if got := pathKey("/"); got != "path:/" { + t.Errorf("the root: %q", got) + } + d := data() + q := engine.Parse("gdrive:", d.Remotes, d.Home) + q.Dropped = []engine.Path{{Text: "/nowhere/a.jpg", Local: true}} + c := NewCompletion() + c.delay = 0 + for _, r := range c.Query(context.Background(), q, d) { + if want := "drop:path:gdrive:" + r.Title; r.Key != want { + t.Errorf("drop destination %q: %q, want %q", r.Title, r.Key, want) + } + } +} + +// TestCopyAddress: Copy Address copies only the serve's address, as the Serve page does, and +// says so in the notification. +func TestCopyAddress(t *testing.T) { + d := data() + d.Serves[0].Args = operations.ServeArgs{Type: "http", Options: operations.Groups{Serve: catalog.Group{"user": []byte(`"me"`), "pass": []byte(`"secret"`)}}} + copied := 0 + for _, r := range run(t, "serve", d, nil) { + for _, a := range r.Actions { + if a.Name != "Copy Address" { + continue + } + copied++ + e := &env{} + if _, err := runAction(a, e); err != nil { + t.Fatal(err) + } + addr := d.Serves[0].Addr + want := []string{"clipboard " + addr, "notify Address Copied: " + addr + " copied to clipboard"} + if !slices.Equal(e.calls, want) { + t.Errorf("%q: did %q, want %q", r.Title, e.calls, want) + } + } + } + if copied == 0 { + t.Fatal("no Copy Address") + } +} + +// TestDropped: dropped files go to a remote, a typed path, or a place chosen later. A single +// folder can also be synced, served and browsed. Completion lists only folders, as destinations. +func TestDropped(t *testing.T) { + d := data() + files := []engine.Path{{Text: "/nowhere/a.jpg", Local: true}, {Text: "/nowhere/b.jpg", Local: true}} + q := engine.Parse("", d.Remotes, d.Home) + q.Dropped = files + got := titles(Dropped{}.Query(context.Background(), q, d)) + if !slices.Contains(got, "Copy 2 items to gdrive:") || !slices.Contains(got, "Move 2 items to…") || slices.Contains(got, "Sync 2 items to…") { + t.Fatalf("two files: %q", got) + } + + dir := t.TempDir() + q.Dropped = []engine.Path{{Text: dir, Local: true}} + got = titles(Dropped{}.Query(context.Background(), q, d)) + name := filepath.Base(dir) + for _, want := range []string{"Sync " + name + " to…", "Serve " + name, "Browse " + name} { + if !slices.Contains(got, want) { + t.Errorf("a folder: %q lacks %q", got, want) + } + } + + q = engine.Parse("gdrive:", d.Remotes, d.Home) + q.Dropped = files + c := NewCompletion() + c.delay = 0 + var dests []string + for _, r := range c.Query(context.Background(), q, d) { + dests = append(dests, r.Title) + a, _ := r.Default() + e := &env{} + _, _ = runAction(a, e) + if want := "window Copy /copy?initialDestination=gdrive%3A" + strings.TrimSuffix(r.Title, "/") + "%2F&initialSource=%2Fnowhere%2Fa.jpg&initialSource=%2Fnowhere%2Fb.jpg"; len(e.calls) != 1 || e.calls[0] != want { + t.Errorf("%s: %q", r.Title, e.calls) + } + } + if !slices.Equal(dests, []string{"Photos/", "Projects/"}) { + t.Fatalf("completion's destinations: %q", dests) + } +} + +// TestClipboard: a link or path that was just copied is suggested first on the empty query. A +// link whose text isn't known yet is read when chosen. Anything else, or a typed query, gets no +// suggestion. +func TestClipboard(t *testing.T) { + d := data() + ask := func(clip engine.Clip, text string) []engine.Result { + q := engine.Parse(text, d.Remotes, d.Home) + q.Clipboard = clip + return Clipboard{}.Query(context.Background(), q, d) + } + if got := titles(ask(engine.Clip{Text: "https://example.com/a/movie.mkv"}, "")); !slices.Equal(got, []string{"Download movie.mkv"}) { + t.Errorf("link: %q", got) + } + if got := titles(ask(engine.Clip{Text: "gdrive:Photos/2024"}, "")); !slices.Equal(got, []string{"Browse gdrive:Photos/2024"}) { + t.Errorf("path: %q", got) + } + for _, text := range []string{"report.pdf", "two\nlines", "hello world"} { + if got := ask(engine.Clip{Text: text}, ""); len(got) != 0 { + t.Errorf("%q: %q", text, titles(got)) + } + } + if got := ask(engine.Clip{Text: "https://example.com/x"}, "co"); len(got) != 0 { + t.Errorf("a query typed: %q", titles(got)) + } + rs := ask(engine.Clip{Link: true}, "") + if len(rs) != 1 || rs[0].Title != "Download the Link You Copied" || !rs[0].Pinned { + t.Fatalf("an unread link: %+v", rs) + } + e := &env{clip: "https://example.com/x.zip"} + a, _ := rs[0].Default() + _, _ = runAction(a, e) + if len(e.calls) != 1 || e.calls[0] != "window Download /download?initialUrl=https%3A%2F%2Fexample.com%2Fx.zip" { + t.Fatalf("read when chosen: %q", e.calls) + } + // pinned above the empty query's recent results + ranked := engine.Rank(engine.Query{}, append(ask(engine.Clip{Text: "https://example.com/a/movie.mkv"}, ""), + engine.Result{ID: "r", Key: "r", Title: "Recent"}), engine.Usage{"r": {Count: 5, Last: time.Now()}}, time.Now()) + if ranked[0].Title != "Download movie.mkv" { + t.Errorf("ranked: %q", titles(ranked)) + } +} + +// runAction runs a, as the launcher does once any question is answered. +func runAction(a engine.Action, e *env) (bool, error) { + if a.Run == nil { + return true, nil + } + return true, a.Run(context.Background(), e) +} + +// TestOpenInBrowser: a serve on every interface opens at 127.0.0.1, and one on a specific address +// opens at that address. +func TestOpenInBrowser(t *testing.T) { + for _, c := range []struct{ addr, want string }{ + {":8080", "http://127.0.0.1:8080"}, + {"0.0.0.0:8083", "http://127.0.0.1:8083"}, + {"[::]:8084", "http://127.0.0.1:8084"}, + {"127.0.0.1:8081", "http://127.0.0.1:8081"}, + {"192.168.1.5:8082", "http://192.168.1.5:8082"}, + } { + d := data() + d.Serves[0].Addr = c.addr + got := "" + for _, r := range run(t, "serve", d, nil) { + if r.ID != "run:serve:s1" { + continue + } + for _, a := range r.Actions { + if a.ID != "browser" { + continue + } + e := &env{} + if _, err := runAction(a, e); err != nil { + t.Fatal(err) + } + got = strings.TrimPrefix(e.calls[0], "url ") + } + } + if got != c.want { + t.Errorf("%s: opened %q, want %q", c.addr, got, c.want) + } + } +} + +// TestRowsMatchBothLanguages: in another language (the test language, Pseudo, stands in for +// one), the rows are drawn translated, and typing finds them by their English titles and search +// words as well as by their translated ones. A drill-in types its word in the app's language. +func TestRowsMatchBothLanguages(t *testing.T) { + i18n.SetLanguage(i18n.Pseudo) + t.Cleanup(func() { i18n.SetLanguage(i18n.English) }) + for _, c := range []struct{ typed, want string }{ + {"copy", "[Çópý]"}, // an operation's English title + {"çópý", "[Çópý]"}, // and its translation + {"settings", "[Séttíñgs]"}, // a screen's English title + {"preferences", "[Séttíñgs]"}, // and an English search word + {"préféréñçés", "[Séttíñgs]"}, // and its translation + {"new remote", "[Ñéw Rémóté]"}, // two English words + {"edit gdrive", "[Édít gdrive]"}, // a command word and a name + {"unmount", "[Úñmóúñt /Volumes/gdrive]"}, + } { + if got := titles(run(t, c.typed, data(), nil)); !slices.Contains(got, c.want) { + t.Errorf("%q: %q lacks %q", c.typed, got, c.want) + } + } + if got := titles(run(t, "browse", data(), nil)); !slices.Contains(got, "[Brówsé gdrive]") { + t.Errorf("browse: %q lacks the remotes to browse", got) + } + + d := data() + for i := range 5 { + d.Mounts = append(d.Mounts, mounts.MountRow{ID: fmt.Sprint("m", i+2), Source: "s3-backup:", MountPoint: fmt.Sprint("/m", i)}) + } + rs := run(t, "", d, nil) + i := slices.IndexFunc(rs, func(r engine.Result) bool { return r.ID == "run:all" }) + if i < 0 { + t.Fatalf("no row that lists everything running: %q", titles(rs)) + } + e := &env{} + a, _ := rs[i].Default() + _, _ = runAction(a, e) + if len(e.calls) != 1 || !strings.HasPrefix(e.calls[0], "query ") { + t.Fatalf("show all: %q", e.calls) + } + typed := strings.TrimPrefix(e.calls[0], "query ") + if !strings.HasPrefix(typed, "[áçtívé") { + t.Errorf("the drill-in typed %q, not its word in the app's language", typed) + } + for _, q := range []string{typed, "active "} { + if got := titles(run(t, q, d, nil)); !slices.Contains(got, "[Báçk]") { + t.Errorf("%q: no way back in %q", q, got) + } + } +} diff --git a/app/launcher/engine/providers/remotes.go b/app/launcher/engine/providers/remotes.go new file mode 100644 index 00000000..33df9851 --- /dev/null +++ b/app/launcher/engine/providers/remotes.go @@ -0,0 +1,173 @@ +package providers + +import ( + "context" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/app/launcher/match" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Remotes offers the remotes (Browse, with the other actions in the ⌘K panel), editing a remote, +// and the remotes list and new remote screens in the Remotes window. +type Remotes struct{} + +// The words that list every remote as a command: "browse" (a drill-in), "edit" and "automount". +// Each is a message of words separated by commas, which a translation gives in its language. +var ( + // i18n: Words that, typed in the launcher, list every remote to browse, separated by commas. The first one is the command itself. + browseWords = i18n.M("browse, explore, open, view, files") + // i18n: Words that, typed in the launcher, list every remote to edit, separated by commas. + editWords = i18n.M("edit, change, update") + // i18n: Words that, typed in the launcher, list every remote to mount when Rclone UI starts, separated by commas. + autoMountWords = i18n.M("auto, automount, startup") +) + +var ( + // i18n: Search words for the launcher's Show Remotes row, separated by commas. Add any word that people would type to find it. + listWords = i18n.M("remotes, list, show, config") + // i18n: Search words for the launcher's New Remote row, separated by commas. Add any word that people would type to find it. + newWords = i18n.M("new, remote, create, add") +) + +// Query lists the remotes that a word matches (or, for an empty query, the ones used often), and +// the remotes' settings. +func (Remotes) Query(_ context.Context, q engine.Query, d *engine.Data) []engine.Result { + return inGroup(engine.GroupRemotes, remotes(q, d)) +} + +func remotes(q engine.Query, d *engine.Data) []engine.Result { + out := []engine.Result{ + engine.Result{ID: "remote:list", Key: "remote:list", Subtitle: i18n.T("Show all configured remotes."), + Icon: icons.Remotes, Score: 32, Actions: []engine.Action{remotesWindow("open", i18n.T("Open Remotes"), "", "")}, + }.Say(i18n.M("Show Remotes"), listWords), + engine.Result{ID: "remote:new", Key: "remote:new", Subtitle: i18n.T("Create a new remote."), + Icon: icons.NewRemote, Score: 28, Actions: []engine.Action{remotesWindow("open", i18n.T("Open Remotes"), "create", "")}, + }.Say(i18n.M("New Remote"), newWords), + } + if len(q.Paths) > 0 { + // A remote typed as a path gets its settings here. Other providers offer the operations. + seen := map[string]bool{} + for _, p := range q.Paths { + if p.Local || seen[p.Remote] { + continue + } + seen[p.Remote] = true + out = append(out, editResult(p.Remote, d), autoMountResult(p.Remote, d)) + } + return out + } + browsing := asks(q, browseWords) + for _, r := range d.Remotes { + res := remoteResult(r, d) + if browsing { + // For browse, each remote is shown as "Browse gdrive" instead of its usual row, which + // the browse words find with its name: "explore gd". + res.Score = 140 + res = res.Say(i18n.M("Browse %s", r.Name), i18n.Text{}) + local, english := engine.Words(browseWords) + for _, w := range local[min(1, len(local)):] { + res.Keywords = append(res.Keywords, w+" "+r.Name) + } + for _, w := range english[1:] { + res.English = append(res.English, w+" "+r.Name) + } + } + out = append(out, res) + if asks(q, editWords) { + out = append(out, editResult(r.Name, d)) + } + if asks(q, autoMountWords) { + out = append(out, autoMountResult(r.Name, d)) + } + } + if browsing && len(d.Remotes) == 0 { + out = append(out, engine.Result{ID: "remote:browse", Key: "remote:browse", + Subtitle: i18n.T("Add a remote to browse its files."), Icon: icons.Folder, Score: 37, + Actions: []engine.Action{remotesWindow("new", i18n.T("New Remote"), "create", "")}, + }.Say(i18n.M("Browse"), browseWords)) + } + if local, english := command(browseWords); only(q, local, english) { + out = append(out, back()) + } + // A remote's name typed after a command ("copy gdr"): Tab completes it to the remote's root. + if w := q.TypingWord; w != "" && len(q.Terms) > 1 { + for _, r := range d.Remotes { + m, ok := match.Match(w, r.Name) + if !ok { + continue + } + c := engine.Result{ + ID: "remote:complete:" + r.Name, Key: historyKey("remote", r.Name), Title: r.Name + ":", + // i18n: %s is a remote's root, such as "gdrive:". Tab puts it in the search box. + Subtitle: i18n.T("Complete to %s", r.Name+":"), Icon: icons.Remote, Score: 90 + m.Score, Always: true, + Complete: r.Name + ":", Actions: []engine.Action{browse(r.Name + ":")}, + } + c.SetMatch(m.Positions) + out = append(out, c) + } + } + return out +} + +// remoteResult returns a remote's result. Its default action browses it, and the ⌘K panel lists +// everything else that can start from its root. +func remoteResult(r engine.Remote, d *engine.Data) engine.Result { + root := r.Name + ":" + p := engine.Path{Text: root, Remote: r.Name, Features: r.Features} + res := engine.Result{ + ID: "remote:" + r.Name, Key: historyKey("remote", r.Name), Title: r.Name, Subtitle: r.Type, + Icon: icons.Remote, Keywords: []string{r.Type}, Score: 100, + Actions: append(pathActions(p, d, true), copyText("copy-name", i18n.T("Copy Name"), root)), Complete: root, + } + // "browse gdrive" finds the remote, in the app's language and in English. + local, english := command(browseWords) + res.Keywords = append(res.Keywords, local+" "+r.Name) + if english != local { + res.English = append(res.English, english+" "+r.Name) + } + return res +} + +func editResult(name string, d *engine.Data) engine.Result { + // i18n: %s is a remote's name. + title := i18n.M("Edit %s", name) + // i18n: Search words for the launcher's row that edits a remote, separated by commas. Add any word that people would type to find it. + words := i18n.M("edit, change, update, remote, settings") + return engine.Result{ID: "remote:edit:" + name, Key: historyKey("edit", name), + Subtitle: i18n.T("Edit a remote."), Icon: icons.Edit, Score: 140, + // i18n: An action that opens a remote's settings, to change them. + Actions: []engine.Action{remotesWindow("edit", i18n.T("Edit"), "edit", name)}, + }.Say(title, words) +} + +func autoMountResult(name string, d *engine.Data) engine.Result { + // i18n: %s is a remote's name. An automount mounts it each time Rclone UI starts. + title := i18n.M("New automount for %s", name) + // i18n: Search words for the launcher's row that adds an automount of a remote, separated by commas. Add any word that people would type to find it. + words := i18n.M("mount, auto, automount, startup") + return engine.Result{ID: "remote:automount:" + name, Key: historyKey("automount", name), + Subtitle: i18n.T("Mount it each time Rclone UI starts."), Icon: icons.Automounts, Score: 140, + Actions: []engine.Action{newAutomount(name + ":")}, + }.Say(title, words) +} + +// newAutomount returns an action that opens the Automounts window with a new automount of source, +// a remote's root or a folder in it. +func newAutomount(source string) engine.Action { + return engine.Action{ID: "automount", Name: i18n.T("New Automount"), Icon: icons.Automounts, Opens: true, + Run: func(_ context.Context, env engine.Env) error { + env.OpenWindow("Automounts", withParams("/automounts", "action", "create", "source", source)) + return nil + }} +} + +// remotesWindow returns an action that opens the Remotes window, with an action on a remote. name +// is the action's name, in the app's language. +func remotesWindow(id, name, action, remote string) engine.Action { + return engine.Action{ID: id, Name: name, Icon: icons.Remotes, Opens: true, Run: func(_ context.Context, env engine.Env) error { + env.OpenWindow("Remotes", withParams("/remotes", "action", action, "remote", remote)) + return nil + }} +} diff --git a/app/launcher/engine/providers/running.go b/app/launcher/engine/providers/running.go new file mode 100644 index 00000000..23a574b8 --- /dev/null +++ b/app/launcher/engine/providers/running.go @@ -0,0 +1,670 @@ +package providers + +import ( + "context" + "errors" + "net" + "slices" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/children" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" +) + +// Running offers what the core is running: its transfers, mounts and serves, listed in the Active +// group (also on the empty query) with the actions for each, plus the transfers that failed in +// the last day and the VFS caches. The rows that stop them show when a word asks for them +// ("stop", "unmount") or when the history says they are used. +type Running struct{} + +// activeMax is the maximum number of running items that the empty query lists. Any more are +// shown in a drill-in ("active "). +const activeMax = 4 + +// A failed transfer is listed for failedFor after it ended. The empty query lists only the +// failedMax newest ones. +const ( + failedFor = 24 * time.Hour + failedMax = 3 +) + +// activeWords list every running item. The first is the drill-in that lists all of them. +var ( + // i18n: Words that, typed in the launcher, list everything that is running, separated by commas. The launcher types the first one itself, so it must be one word. + activeWords = i18n.M("active, running") +) + +func (Running) Query(_ context.Context, q engine.Query, d *engine.Data) []engine.Result { + var out []engine.Result + out = append(out, transferRunResults(q, d)...) + out = append(out, mountResults(q, d)...) + out = append(out, serveRunResults(q, d)...) + if r, ok := StopEverything(d); ok && len(q.Paths) == 0 { + out = append(out, r) + } + for i := range out { + out[i].Group = engine.GroupActive + } + if q.Empty() { + out = capActive(out) + } + out = append(out, failedResults(q, d, time.Now())...) + if local, english := engine.Words(activeWords); only(q, slices.Concat(local, english)...) { + out = append(out, back()) + } + return append(out, vfsResults(q, d)...) +} + +// watcherRun reports whether t is a watcher's own run. A watcher runs every minute and has its own +// window, so its runs are left out of the launcher's rows, as they are of the tray's. A retry +// from History is the user's own run, so it is shown, as the transfer service treats it. +func watcherRun(t transfers.Transfer) bool { + return t.Origin.Kind == transfers.OriginWatcher && t.RetryOf == "" +} + +// failedResults returns the transfers that failed in the last day, newest first. Each one opens +// its details in the History window: "Sync failed: Photos → gdrive:Photos". +func failedResults(q engine.Query, d *engine.Data, now time.Time) []engine.Result { + var out []engine.Result + for _, t := range d.Failed { + if t.EndedAt == nil || watcherRun(t) { + continue + } + ended := time.UnixMilli(*t.EndedAt) + if now.Sub(ended) > failedFor { + continue + } + if !reads(q, t.Destination) && !slices.ContainsFunc(t.Sources, func(s string) bool { return reads(q, s) }) { + continue + } + if q.Empty() && len(out) == failedMax { + break + } + what := operationName(t.Operation) + // i18n: A failed transfer. %s is its operation, such as "Sync". + name := i18n.M("%s failed", what) + if paths := transferPaths(t); paths != "" { + // i18n: A failed transfer. %[1]s is its operation, such as "Sync", and %[2]s its paths. + name = i18n.M("%[1]s failed: %[2]s", what, paths) + } + // i18n: When a transfer failed. %s is how long ago, such as "10 min ago". + sub := i18n.T("Failed %s.", ago(ended, now)) + if msg, _, _ := strings.Cut(strings.TrimSpace(t.Error), "\n"); msg != "" { + // i18n: When a transfer failed, and why. %[1]s is how long ago, such as "10 min ago", and %[2]s the error. + sub = i18n.T("Failed %[1]s: %[2]s", ago(ended, now), msg) + } + r := engine.Result{ + ID: "run:failed:" + t.ID, Subtitle: sub, Icon: icons.Failed, + Keywords: []string{string(t.Operation)}, Score: 131, Group: engine.GroupActive, + Actions: []engine.Action{open("open", "History", "/history", icons.Transfers, "id", t.ID)}, + } + // i18n: Search words for the launcher's rows of failed transfers, separated by commas. Add any word that people would type to find them. + out = append(out, r.Say(name, i18n.M("failed, error, history, transfers"))) + } + return out +} + +// capActive limits the empty query's running items to activeMax rows. When there are more, it +// keeps the first few and adds a row that shows all of them. +func capActive(rs []engine.Result) []engine.Result { + n := 0 + for _, r := range rs { + if !r.Recent { + n++ + } + } + if n <= activeMax { + return rs + } + var out []engine.Result + kept := 0 + for _, r := range rs { + if !r.Recent { + if kept == activeMax-1 { + continue + } + kept++ + } + out = append(out, r) + } + more := n - kept + return append(out, engine.Result{ + ID: "run:all", Title: i18n.T("Show All Running"), Subtitle: i18n.N("%d more running.", "%d more running.", more, more), Tail: countLabel(n), + Icon: icons.Search, Score: 1, Group: engine.GroupActive, + Actions: []engine.Action{{ID: "list", Name: i18n.T("Show All"), Icon: icons.Search, KeepOpen: true, + Run: func(_ context.Context, env engine.Env) error { + word, _ := command(activeWords) + env.SetQuery(word + " ") + return nil + }}}, + }) +} + +// transferRunResults returns the queued and running transfers as one row that opens the History +// window, and a row that stops them, shown when asked for. +func transferRunResults(q engine.Query, d *engine.Data) []engine.Result { + var ts []transfers.Transfer + for _, t := range d.Transfers { + if watcherRun(t) { + continue + } + if reads(q, t.Destination) || slices.ContainsFunc(t.Sources, func(s string) bool { return reads(q, s) }) { + ts = append(ts, t) + } + } + if len(ts) == 0 { + return nil + } + running := 0 + for _, t := range ts { + if t.State == transfers.StateRunning { + running++ + } + } + var live []*bus.TransferProgress + for _, t := range ts { + if t.State == transfers.StateRunning { + live = append(live, t.Live) + } + } + // their progress, once the core reports it: "42% · 12 MB/s · 3 min left" + progress := progressLine(corestate.SumProgress(live)) + queued := len(ts) - running + title := i18n.MN("%d Transfer", "%d Transfers", len(ts), len(ts)) + var subtitle string + switch { + case len(ts) == 1: + title = transferTitle(ts[0]) + // i18n: The state of a transfer that waits for its turn. + subtitle = i18n.T("Queued") + if running == 1 { + // i18n: The state of a transfer that runs. + subtitle = i18n.T("Running") + } + case queued == 0: + subtitle = i18n.N("%d running", "%d running", running, running) + case running == 0: + subtitle = i18n.N("%d queued", "%d queued", queued, queued) + default: + // i18n: How many transfers run, and how many wait for their turn. + subtitle = i18n.T("%[1]d running, %[2]d queued", running, queued) + } + // The state is a label, with no period, so that a language's own punctuation isn't mixed + // with ours. + switch { + case progress == "": + case len(ts) == 1: + subtitle = progress + default: + subtitle += " · " + progress + } + // i18n: Search words for the launcher's rows of the running transfers, separated by commas. Add any word that people would type to find them. + words := i18n.M("transfers, history, jobs, stop, cancel") + stop := stopTransfers(ts) + return []engine.Result{ + engine.Result{ + ID: "run:transfers", Key: historyKey("transfers", "running"), Subtitle: subtitle, + Icon: icons.Transfers, Score: 132, + Actions: []engine.Action{open("open", "History", "/history", icons.Transfers), stop.Action}, + }.Say(title, words).Say(i18n.Text{}, activeWords), + engine.Result{ + ID: "run:transfers:stop", Key: historyKey("stoptransfers", "running"), Subtitle: title.Local(), + Icon: icons.Stop, Score: 125, Recent: true, Actions: []engine.Action{stop.Action}, + }.Say(stop.title, words), + } +} + +// transferTitle describes what a transfer does: "Copy gdrive:Photos → /Users/me/Photos". +func transferTitle(t transfers.Transfer) i18n.Text { + paths := transferPaths(t) + if paths == "" { + return operationName(t.Operation) + } + if o, ok := opByID(string(t.Operation)); ok { + return o.on(paths) + } + switch t.Operation { + case operations.OperationSave: + return i18n.M("Save %s", paths) + case operations.OperationRename: + return i18n.M("Rename %s", paths) + case operations.OperationDeleteFolder: + return i18n.M("Delete Folder %s", paths) + case operations.OperationCleanup: + return i18n.M("Clean up %s", paths) + } + // i18n: A transfer whose operation has no name. %s is its paths. + return i18n.M("Transfer %s", paths) +} + +// operationName names a transfer's operation: "Copy", "Delete Folder". +func operationName(o operations.Operation) i18n.Text { + if op, ok := opByID(string(o)); ok { + return op.name + } + switch o { + case operations.OperationSave: + // i18n: The operation that saves a file that was edited in the app. + return i18n.M("Save") + case operations.OperationRename: + return i18n.M("Rename") + case operations.OperationDeleteFolder: + return i18n.M("Delete Folder") + case operations.OperationCleanup: + return i18n.M("Cleanup") + } + // i18n: A transfer whose operation has no name. + return i18n.M("Transfer") +} + +// transferPaths describes a transfer's paths: "gdrive:Photos → /Users/me/Photos", "gdrive:old". +func transferPaths(t transfers.Transfer) string { + out := "" + if s := t.Sources; len(s) > 0 { + out = engine.Path{Text: s[0]}.Short() + if more := len(s) - 1; more > 0 { + // i18n: The sources of a transfer. %s is the first one's path. + out = i18n.N("%s and %d more", "%s and %d more", more, out, more) + } + } + if dst := t.Destination; dst != "" { + out = strings.TrimSpace(out + " → " + engine.Path{Text: dst}.Short()) + } + return out +} + +// stopAction is an action that stops something, with the title of its row. +type stopAction struct { + engine.Action + title i18n.Text +} + +// stopTransfers returns an action that stops the transfers ts, after asking for confirmation. +func stopTransfers(ts []transfers.Transfer) stopAction { + n := len(ts) + name, question := i18n.M("Stop All Transfers"), i18n.N("Stop %d transfer?", "Stop %d transfers?", n, n) + if n == 1 { + name = i18n.M("Stop Transfer") + // i18n: %s is a transfer, such as "Copy gdrive:Photos → /Users/me/Photos". + question = i18n.T("Stop %s?", transferTitle(ts[0])) + } + return stopAction{title: name, Action: engine.Action{ID: "stop", Name: name.Local(), Icon: icons.Stop, Stay: true, Confirm: question, + Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Transfers + if c == nil { + return errNoCore + } + working, done := i18n.T("Stopping a transfer…"), i18n.T("Stopped a transfer.") + if n > 1 { + working = i18n.N("Stopping %d transfer…", "Stopping %d transfers…", n, n) + done = i18n.N("Stopped %d transfer.", "Stopped %d transfers.", n, n) + } + env.Status(engine.StatusWorking, working) + var failed []error + for _, t := range ts { + if err := stopTransfer(ctx, c, t.ID); err != nil { + failed = append(failed, err) + } + } + if err := errors.Join(failed...); err != nil { + return err + } + env.Status(engine.StatusDone, done) + return nil + }}} +} + +// stopTransfer stops one transfer. A transfer that ended in the meantime counts as stopped. +func stopTransfer(ctx context.Context, c engine.Transfers, id string) error { + err := c.Stop(ctx, id) + if errors.Is(err, transfers.ErrNotRunning) { + return nil + } + return err +} + +// StopEverything returns the Stop Everything row. Its action stops every transfer (a watcher's or +// a schedule's run included), serve and mount that the core runs, and the remote tunnel. It first +// asks a question that names what is running according to d, with the same phrase as the quit +// dialog. It returns false when nothing is running. The launcher's stop button uses it too. +func StopEverything(d *engine.Data) (engine.Result, bool) { + running := core.Running{Transfers: len(d.Transfers), Mounts: len(d.Mounts), Serves: len(d.Serves), Tunnel: d.Tunnel} + if running == (core.Running{}) { + return engine.Result{}, false + } + what := running.Phrase() + // i18n: The launcher's row and action that stop everything that is running. + title := i18n.M("Stop Everything") + a := engine.Action{ID: "stop-everything", Name: title.Local(), Icon: icons.StopAll, Stay: true, + // i18n: %s names what is running: "2 transfers, a serve and 3 mounts". + Confirm: i18n.T("Stop %s?", what), Run: stopEverything} + // i18n: Search words for the launcher's Stop Everything row, separated by commas. Add any word that people would type to find it. + words := i18n.M("stop, everything, all, emergency, panic, kill") + return engine.Result{ + // i18n: %s names what is running: "2 transfers, a serve and 3 mounts". + ID: "run:everything", Key: "run:stop-everything", Subtitle: i18n.T("Stop %s.", what), + Icon: icons.StopAll, Score: 118, Recent: true, Group: engine.GroupActive, Actions: []engine.Action{a}, + }.Say(title, words), true +} + +// stopEverything asks the core to stop everything it runs. The core makes its own list of what is +// running, so what started after the question was asked stops too. The status then shows the +// core's summary of what stopped. +func stopEverything(ctx context.Context, env engine.Env) error { + c := env.Core().Everything + if c == nil { + return errNoCore + } + env.Status(engine.StatusWorking, i18n.T("Stopping everything…")) + sum, err := c.StopAll(ctx) + if err != nil { + return err + } + env.Status(engine.StatusDone, sum.Done().Local()) + return nil +} + +// reads reports whether a running item that reads source matches one of the typed paths. When +// no path is typed, every item matches. +func reads(q engine.Query, source string) bool { + if len(q.Paths) == 0 { + return true + } + for _, p := range q.Paths { + if strings.HasPrefix(source, strings.TrimSuffix(p.Text, "/")) { + return true + } + } + return false +} + +var ( + // i18n: Search words for the launcher's rows of running mounts, separated by commas. Add any word that people would type to find them. + mountWords = i18n.M("mount, mounted, unmount, stop, open") + // i18n: Search words for the launcher's rows of running serves, separated by commas. Add any word that people would type to find them. + serveWords = i18n.M("serve, serving, stop, address") +) + +func mountResults(q engine.Query, d *engine.Data) []engine.Result { + var out []engine.Result + for _, m := range d.Mounts { + if !reads(q, m.Source) { + continue + } + // i18n: The state of a mount that is ready. + state := i18n.T("Mounted") + if m.State != string(children.StatusRunning) { + // i18n: The state of a mount or a serve that is starting. + state = i18n.T("Starting") + } + if m.Error != "" { + state = m.Error + } + // i18n: An action that opens a mounted folder in the file manager. + reveal := engine.Action{ID: "open", Name: i18n.T("Open"), Icon: icons.Open, Run: func(_ context.Context, env engine.Env) error { + env.Reveal(m.MountPoint) + return nil + }} + actions := []engine.Action{ + reveal, stopMount(m), + copyText("copy-point", i18n.T("Copy Mount Point"), m.MountPoint), + copyText("copy-source", i18n.T("Copy Source"), m.Source), browse(m.Source), + } + // i18n: %s is the folder or drive that a remote is mounted at. + unmount := i18n.M("Unmount %s", m.MountPoint) + out = append(out, engine.Result{ + ID: "run:mount:" + m.ID, Key: historyKey("mount", m.Source+" "+m.MountPoint), + Title: m.Source + " → " + m.MountPoint, Subtitle: state, Icon: icons.Mount, Score: 130, Actions: actions, + }.Say(i18n.Text{}, mountWords).Say(i18n.Text{}, activeWords), engine.Result{ + // the Stop row makes the stop available without the ⌘K panel + ID: "run:mount:stop:" + m.ID, Key: historyKey("unmount", m.Source+" "+m.MountPoint), + Subtitle: m.Source, Icon: icons.Stop, Score: 125, Recent: true, Actions: []engine.Action{stopMount(m)}, + }.Say(unmount, mountWords)) + } + if n := len(d.Mounts); n > 1 && len(q.Paths) == 0 { + title := i18n.M("Unmount All") + // i18n: Search words for the launcher's Unmount All row, separated by commas. Add any word that people would type to find it. + words := i18n.M("unmount, stop, mounts, all") + out = append(out, engine.Result{ + ID: "run:mount:all", Key: "mount:stop-all", Icon: icons.Stop, Tail: countLabel(n), Score: 120, Recent: true, + Actions: []engine.Action{{ID: "stop-all", Name: title.Local(), Icon: icons.Stop, Stay: true, + Confirm: i18n.N("Unmount all %d mounts?", "Unmount all %d mounts?", n, n), + Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Mounts + if c == nil { + return errNoCore + } + env.Status(engine.StatusWorking, i18n.T("Unmounting everything…")) + err := c.StopAll(ctx) + if err == nil { + env.Status(engine.StatusDone, i18n.T("Every mount is stopped.")) + } + return err + }}}, + }.Say(title, words)) + } + return out +} + +func stopMount(m mounts.MountRow) engine.Action { + // i18n: The action that stops a mount. + return engine.Action{ID: "stop", Name: i18n.T("Unmount"), Icon: icons.Stop, Stay: true, + // i18n: %s is the folder or drive that a remote is mounted at. + Confirm: i18n.T("Unmount %s?", m.MountPoint), + Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Mounts + if c == nil { + return errNoCore + } + env.Status(engine.StatusWorking, i18n.T("Unmounting %s…", m.MountPoint)) + err := c.Stop(ctx, m.ID) + if err == nil { + env.Status(engine.StatusDone, i18n.T("Unmounted %s.", m.MountPoint)) + } + return err + }} +} + +func serveRunResults(q engine.Query, d *engine.Data) []engine.Result { + var out []engine.Result + for _, v := range d.Serves { + if !reads(q, v.Source) { + continue + } + // i18n: The state of a serve that is ready. + state := i18n.T("Serving") + if v.State != string(children.StatusRunning) { + state = i18n.T("Starting") + } + if v.Error != "" { + state = v.Error + } + actions := []engine.Action{copyAddress(v), stopServe(v)} + if t := strings.ToLower(v.Type); t == "http" || t == "webdav" { + u := serveURL(v.Addr) + actions = append(actions, engine.Action{ID: "browser", Name: i18n.T("Open in Browser"), Icon: icons.Browser, + Run: func(_ context.Context, env engine.Env) error { + env.OpenURL(u) + return nil + }}) + } + typ := strings.ToLower(v.Type) + // i18n: %s is a serve: its protocol and what it serves, such as "HTTP gdrive:". + stop := i18n.M("Stop %s", strings.ToUpper(v.Type)+" "+v.Source) + out = append(out, engine.Result{ + ID: "run:serve:" + v.ID, Key: historyKey("serve", v.Type+" "+v.Source), + Title: strings.ToUpper(v.Type) + " " + v.Source + " · " + v.Addr, Subtitle: state, + Icon: icons.Serve, Keywords: []string{typ}, Score: 129, Actions: actions, + }.Say(i18n.Text{}, serveWords).Say(i18n.Text{}, activeWords), engine.Result{ + ID: "run:serve:stop:" + v.ID, Key: historyKey("stopserve", v.Type+" "+v.Source), + Subtitle: v.Addr, Icon: icons.Stop, Keywords: []string{typ}, Score: 125, Recent: true, + Actions: []engine.Action{stopServe(v)}, + }.Say(stop, serveWords)) + } + if n := len(d.Serves); n > 1 && len(q.Paths) == 0 { + title := i18n.M("Stop All Serves") + // i18n: Search words for the launcher's Stop All Serves row, separated by commas. Add any word that people would type to find it. + words := i18n.M("stop, serves, all") + out = append(out, engine.Result{ + ID: "run:serve:all", Key: "serve:stop-all", Icon: icons.Stop, Tail: countLabel(n), Score: 120, Recent: true, + Actions: []engine.Action{{ID: "stop-all", Name: title.Local(), Icon: icons.Stop, Stay: true, + Confirm: i18n.N("Stop all %d serves?", "Stop all %d serves?", n, n), + Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Serves + if c == nil { + return errNoCore + } + env.Status(engine.StatusWorking, i18n.T("Stopping every serve…")) + err := c.StopAll(ctx) + if err == nil { + env.Status(engine.StatusDone, i18n.T("Every serve is stopped.")) + } + return err + }}}, + }.Say(title, words)) + } + return out +} + +// copyAddress returns an action that copies the serve's address to the clipboard, as the Serve +// page does. +func copyAddress(v serves.ServeRow) engine.Action { + return engine.Action{ID: "copy", Name: i18n.T("Copy Address"), Icon: icons.Clipboard, Run: func(_ context.Context, env engine.Env) error { + env.Clipboard(v.Addr) + env.Notify(i18n.T("Address Copied"), i18n.T("%s copied to clipboard", v.Addr)) + return nil + }} +} + +func stopServe(v serves.ServeRow) engine.Action { + // i18n: The action that stops a serve. + return engine.Action{ID: "stop", Name: i18n.T("Stop"), Icon: icons.Stop, Stay: true, + // i18n: %[1]s is what is served, such as "gdrive:", and %[2]s its protocol, such as HTTP. + Confirm: i18n.T("Stop serving %[1]s over %[2]s?", v.Source, strings.ToUpper(v.Type)), + Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Serves + if c == nil { + return errNoCore + } + // i18n: %s is the address that a serve listens at, such as 127.0.0.1:8080. + env.Status(engine.StatusWorking, i18n.T("Stopping the serve at %s…", v.Addr)) + err := c.Stop(ctx, v.ID) + if err == nil { + env.Status(engine.StatusDone, i18n.T("Stopped the serve at %s.", v.Addr)) + } + return err + }} +} + +// serveURL returns a serve's address in a form this machine's browser can open. A serve that +// listens on every interface is reached at 127.0.0.1. +func serveURL(addr string) string { + if strings.Contains(addr, "://") { + return addr + } + host, port, err := net.SplitHostPort(addr) + if err != nil { + return "http://" + addr + } + if host == "" || host == "0.0.0.0" || host == "::" { + host = "127.0.0.1" + } + return "http://" + net.JoinHostPort(host, port) +} + +var ( + // i18n: Search words for the launcher's VFS cache rows, separated by commas. VFS is rclone's virtual file system. Add any word that people would type to find them. + vfsWords = i18n.M("vfs, cache, forget") +) + +func vfsResults(q engine.Query, d *engine.Data) []engine.Result { + var out []engine.Result + for _, v := range d.Vfs { + if !reads(q, v.Fs) { + continue + } + // i18n: %s is the remote whose cache it is, such as "gdrive:". + title := i18n.M("Forget the VFS cache of %s", v.Fs) + out = append(out, engine.Result{ + ID: "run:vfs:" + v.ID, Key: historyKey("vfs", v.Fs), + Subtitle: vfsOwner(v.Kind) + " · " + v.Name, Icon: icons.VFS, Score: 130, Recent: true, + Actions: []engine.Action{forget(v.ID, v.Fs)}, + }.Say(title, vfsWords)) + } + if n := len(d.Vfs); n > 1 && len(q.Paths) == 0 { + out = append(out, engine.Result{ + ID: "run:vfs:all", Key: "vfs:forget-all", Icon: icons.VFS, Tail: countLabel(n), Score: 120, Recent: true, + Actions: []engine.Action{forget("", "")}, + }.Say(i18n.M("Forget Every VFS Cache"), vfsWords)) + } + // The VFS item leads to the caches on an empty query. When no cache is in use, it shows for a + // typed word too, to say so. VFS is rclone's name, so its title isn't translated. + vfs := engine.Result{ID: "run:vfs", Key: "vfs", Title: "VFS", Subtitle: i18n.T("Forget the local cache for one or all remotes."), + Icon: icons.VFS, Score: 35}.Say(i18n.Text{}, vfsWords) + if len(d.Vfs) == 0 { + vfs.Subtitle = i18n.T("No VFS cache in use.") + } else { + vfs.Tail = countLabel(len(d.Vfs)) + vfs.Actions = []engine.Action{{ID: "list", Name: i18n.T("Show Caches"), Icon: icons.VFS, KeepOpen: true, + Run: func(_ context.Context, env engine.Env) error { + env.SetQuery("vfs ") + return nil + }}} + } + if len(q.Paths) == 0 && (q.Empty() || len(d.Vfs) == 0) { + out = append(out, vfs) + } + for i := range out { + out[i].Group = engine.GroupOperations + } + if only(q, "vfs") { + out = append(out, back()) + } + return out +} + +// vfsOwner names what uses a VFS cache: a mount or a serve. +func vfsOwner(kind string) string { + switch kind { + case "mount": + // i18n: What uses a VFS cache, shown in lower case before its name: "mount · /Volumes/gdrive". + return i18n.T("mount") + case "serve": + // i18n: What uses a VFS cache, shown in lower case before its name: "serve · http 127.0.0.1:8080". + return i18n.T("serve") + } + return kind +} + +// forget returns an action that forgets the VFS cache with id, of the remote fs. An empty id +// forgets every cache. +func forget(id, fs string) engine.Action { + working, done := i18n.T("Forgetting every VFS cache…"), i18n.T("Forgot every VFS cache.") + if id != "" { + // i18n: %s is the remote whose cache it is, such as "gdrive:". + working, done = i18n.T("Forgetting the VFS cache of %s…", fs), i18n.T("Forgot the VFS cache of %s.", fs) + } + // i18n: The action that clears a VFS cache. + return engine.Action{ID: "forget", Name: i18n.T("Forget"), Icon: icons.VFS, Stay: true, Run: func(ctx context.Context, env engine.Env) error { + c := env.Core().Vfs + if c == nil { + return errNoCore + } + env.Status(engine.StatusWorking, working) + if err := c.Forget(ctx, id); err != nil { + return err + } + env.Status(engine.StatusDone, done) + return nil + }} +} diff --git a/app/launcher/engine/query.go b/app/launcher/engine/query.go new file mode 100644 index 00000000..782574f6 --- /dev/null +++ b/app/launcher/engine/query.go @@ -0,0 +1,231 @@ +package engine + +import ( + "path/filepath" + "regexp" + "sort" + "strings" + "unicode" +) + +var ( + // A word that looks like a domain counts as an https URL when a path, a port or a query + // follows the name: "example.com/x", "files.host.io:8080/a". A name alone ("report.pdf") is + // a plain word. + domainRE = regexp.MustCompile(`^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}[/:?]\S*$`) + // a Windows drive path: "C:\x", "c:/x" + driveRE = regexp.MustCompile(`^[a-zA-Z]:[\\/]`) +) + +// Parse parses text. home is the folder that ~ stands for, or "" for none. +func Parse(text string, remotes []Remote, home string) Query { + q := Query{Text: text, TypingFrom: len(text)} + byName := map[string]Remote{} + for _, r := range remotes { + byName[strings.ToLower(r.Name)] = r + } + toks := tokenize(text, remotes) + for i, t := range toks { + word := t.text + if !t.quoted { + word = strings.TrimRight(word, ".,;!?") // strip sentence punctuation, unless quoted + } + // the caret is at the end of the last word, unless a space or a closing quote follows it + typing := i == len(toks)-1 && (t.open || !t.quoted && t.start+len(t.text) == len(text)) + if typing { + q.TypingFrom = t.start + } + if p, ok := readPath(word, byName, home); ok { + q.Paths = append(q.Paths, p) + if typing { + p := p + q.Typing = &p + } + continue + } + if q.URL == "" && !t.quoted { + if u, ok := readURL(word); ok { + q.URL = u + continue + } + } + if w := strings.TrimSpace(word); w != "" { + q.Terms = append(q.Terms, w) + if typing { + q.TypingWord = w + } + } + } + return q +} + +// token is a word of the text. quoted means it was in quotes (which aren't included in text). +// open means its quote wasn't closed, so it runs to the end of the text. start is where the word +// starts in the text, including its opening quote. +type token struct { + text string + quoted bool + open bool + start int +} + +// tokenize splits text into words. A quoted string is one word, and so is a remote name that +// contains spaces (the longest one that matches and is followed by the end, a space or a colon). +func tokenize(text string, remotes []Remote) []token { + var spaced []string + for _, r := range remotes { + if strings.ContainsAny(r.Name, " \t") { + spaced = append(spaced, r.Name) + } + } + sort.Slice(spaced, func(i, j int) bool { return len(spaced[i]) > len(spaced[j]) }) + var out []token + s := text + for { + s = strings.TrimLeftFunc(s, unicode.IsSpace) + if s == "" { + return out + } + start := len(text) - len(s) + if q := s[0]; q == '"' || q == '\'' || q == '`' { + end := strings.IndexByte(s[1:], q) + if end < 0 { + // still being typed: the rest of the text, spaces included, is the word + return append(out, token{text: s[1:], quoted: true, open: true, start: start}) + } + out = append(out, token{text: s[1 : end+1], quoted: true, start: start}) + s = s[end+2:] + continue + } + if name, ok := spacedRemote(s, spaced); ok { + rest := s[len(name):] + end := strings.IndexFunc(rest, unicode.IsSpace) + if end < 0 { + end = len(rest) + } + out = append(out, token{text: s[:len(name)+end], start: start}) + s = rest[end:] + continue + } + end := strings.IndexFunc(s, unicode.IsSpace) + if end < 0 { + end = len(s) + } + out = append(out, token{text: s[:end], start: start}) + s = s[end:] + } +} + +func spacedRemote(s string, names []string) (string, bool) { + for _, n := range names { + if len(s) < len(n) || !strings.EqualFold(s[:len(n)], n) { + continue + } + rest := s[len(n):] + if rest == "" || rest[0] == ':' || unicode.IsSpace(rune(rest[0])) { + return s[:len(n)], true + } + } + return "", false +} + +// readPath reads a word as a path. A path is a known remote's name alone, the name with a colon +// and a path after it, or a local path (/x, C:\x, and ~ or ~/x in home). A relative path (./x, +// ../x) doesn't count, because the core would resolve it against the app's working folder. +// Neither does ~user/x, nor ~ when there is no home folder. +func readPath(word string, remotes map[string]Remote, home string) (Path, bool) { + if word == "" { + return Path{}, false + } + if r, ok := remotes[strings.ToLower(word)]; ok { + return Path{Text: r.Name + ":", Remote: r.Name, Features: r.Features}, true + } + if word[0] == '~' { + if p, ok := inHome(word[1:], home); ok { + return Path{Text: p, Local: true}, true + } + return Path{}, false + } + if driveRE.MatchString(word) || strings.HasPrefix(word, "/") { + return Path{Text: word, Local: true}, true + } + name, rest, ok := strings.Cut(word, ":") + if !ok || name == "" || strings.HasPrefix(rest, "//") { + return Path{}, false + } + r, known := remotes[strings.ToLower(name)] + if !known { + return Path{}, false + } + return Path{Text: r.Name + ":" + rest, Remote: r.Name, Features: r.Features}, true +} + +// inHome resolves rest (what follows a ~) inside home. It keeps a trailing separator, which +// completion needs. It returns false for ~user/x, and when there is no home folder. +func inHome(rest, home string) (string, bool) { + if home == "" { + return "", false + } + if rest == "" { + return home, true + } + if rest[0] != '/' && rest[0] != filepath.Separator { + return "", false + } + p := filepath.Join(home, rest) + if last := rest[len(rest)-1]; (last == '/' || last == filepath.Separator) && !strings.HasSuffix(p, string(filepath.Separator)) { + p += string(filepath.Separator) + } + return p, true +} + +// ReadClip reads the clipboard's text as a single web link or a single path (a local path may +// contain spaces). It returns false for anything else. +func ReadClip(text string, remotes []Remote, home string) (url string, p Path, ok bool) { + text = strings.TrimSpace(text) + if text == "" || len(text) > 2048 || strings.ContainsAny(text, "\r\n") { + return "", Path{}, false + } + // Only accept a link with a scheme. Otherwise copied text like "report.pdf" would look like a + // domain. + if l := strings.ToLower(text); (strings.HasPrefix(l, "https://") || strings.HasPrefix(l, "http://")) && !strings.ContainsAny(text, " \t") { + return text, Path{}, true + } + byName := map[string]Remote{} + for _, r := range remotes { + byName[strings.ToLower(r.Name)] = r + } + if p, ok := readPath(text, byName, home); ok { + return "", p, true + } + return "", Path{}, false +} + +func readURL(word string) (string, bool) { + if strings.Contains(word, "://") { + return word, true + } + if domainRE.MatchString(word) && !strings.Contains(word, "..") { + return "https://" + word, true + } + return "", false +} + +// shorten keeps a deep path readable by showing the root, its first folder, "…" and the last two +// names. +func shorten(p string) string { + root := "" + rest := p + if i := strings.Index(p, ":"); i >= 0 && !driveRE.MatchString(p) { + root, rest = p[:i+1], p[i+1:] + } + lead := "" + if strings.HasPrefix(rest, "/") { + lead, rest = "/", strings.TrimLeft(rest, "/") + } + parts := strings.Split(strings.TrimRight(rest, "/"), "/") + if len(parts) <= 4 { + return p + } + return root + lead + parts[0] + "/…/" + parts[len(parts)-2] + "/" + parts[len(parts)-1] +} diff --git a/app/launcher/engine/query_test.go b/app/launcher/engine/query_test.go new file mode 100644 index 00000000..c5338b36 --- /dev/null +++ b/app/launcher/engine/query_test.go @@ -0,0 +1,105 @@ +package engine + +import ( + "path/filepath" + "runtime" + "slices" + "testing" +) + +var testRemotes = []Remote{{Name: "gdrive", Type: "drive"}, {Name: "My Box", Type: "box"}} + +// TestParseHome: ~ is replaced by the given home, so the core reads a full path. +func TestParseHome(t *testing.T) { + home := filepath.Join(string(filepath.Separator), "home", "me") + sep := string(filepath.Separator) + cases := []struct{ text, home, want string }{ + {"~", home, home}, + {"~/", home, home + sep}, + {"~/Photos", home, filepath.Join(home, "Photos")}, + {"~/Photos/", home, filepath.Join(home, "Photos") + sep}, + {"~/a/b", home, filepath.Join(home, "a", "b")}, + {"/x", "", "/x"}, + {`C:\x`, "", `C:\x`}, + {"~", "", ""}, + {"~/Photos", "", ""}, + {"~user/x", home, ""}, + {"./x", home, ""}, + {"../x", home, ""}, + } + if runtime.GOOS == "windows" { + cases = append(cases, struct{ text, home, want string }{`~\Photos`, home, filepath.Join(home, "Photos")}) + } else { + cases = append(cases, struct{ text, home, want string }{`~\Photos`, home, ""}) + } + for _, c := range cases { + q := Parse(c.text, testRemotes, c.home) + got := "" + if len(q.Paths) == 1 { + got = q.Paths[0].Text + if !q.Paths[0].Local { + t.Errorf("%q: not local", c.text) + } + } + if got != c.want { + t.Errorf("%q with home %q: path %q, want %q", c.text, c.home, got, c.want) + } + } + if _, p, ok := ReadClip("~/My Photos", nil, home); !ok || p.Text != filepath.Join(home, "My Photos") { + t.Errorf("the clipboard's ~: %q, %v", p.Text, ok) + } + if _, _, ok := ReadClip("~/My Photos", nil, ""); ok { + t.Error("the clipboard's ~ without a home") + } +} + +// TestParseOpenQuote: an unclosed quote is the word being typed, spaces included, and completion +// replaces it starting from the quote. A closed quote isn't being typed, and keeps its +// punctuation. +func TestParseOpenQuote(t *testing.T) { + q := Parse(`copy "gdrive:My Folder/in`, testRemotes, "") + if q.TypingFrom != 5 || q.Typing == nil || q.Typing.Text != "gdrive:My Folder/in" || + len(q.Paths) != 1 || !slices.Equal(q.Terms, []string{"copy"}) { + t.Fatalf("open: from %d, typing %v, paths %v, terms %q", q.TypingFrom, q.Typing, q.Paths, q.Terms) + } + q = Parse(`copy "gdrive:My `, testRemotes, "") + if q.TypingFrom != 5 || q.Typing == nil || q.Typing.Text != "gdrive:My " { + t.Errorf("open, ending in a space: from %d, typing %v", q.TypingFrom, q.Typing) + } + for _, text := range []string{`copy "gdrive:My Folder/"`, `copy "gdrive:My Folder/" `} { + q = Parse(text, testRemotes, "") + if q.TypingFrom != len(text) || q.Typing != nil || len(q.Paths) != 1 || q.Paths[0].Text != "gdrive:My Folder/" { + t.Errorf("%q: from %d, typing %v, paths %v", text, q.TypingFrom, q.Typing, q.Paths) + } + } + q = Parse(`"gdrive:Hello!" gdrive:Hi!`, testRemotes, "") + if len(q.Paths) != 2 || q.Paths[0].Text != "gdrive:Hello!" || q.Paths[1].Text != "gdrive:Hi" { + t.Errorf("punctuation: %v", q.Paths) + } + for text, from := range map[string]int{"copy gdr": 5, "copy ": 5, "": 0, "my box:x": 0, "copy my box:x": 5} { + if q := Parse(text, testRemotes, ""); q.TypingFrom != from { + t.Errorf("%q: from %d, want %d", text, q.TypingFrom, from) + } + } +} + +func TestParseURL(t *testing.T) { + cases := map[string]string{ + "https://example.com": "https://example.com", + "example.com/archive.tar": "https://example.com/archive.tar", + "files.host.io:8080/a": "https://files.host.io:8080/a", + "example.com?q=1": "https://example.com?q=1", + "example.com": "", + "report.pdf": "", + "a..b.com/x": "", + } + for text, want := range cases { + q := Parse(text, testRemotes, "") + if q.URL != want { + t.Errorf("%q: URL %q, want %q", text, q.URL, want) + } + if want == "" && !slices.Equal(q.Terms, []string{text}) { + t.Errorf("%q: terms %q", text, q.Terms) + } + } +} diff --git a/app/launcher/engine/rank.go b/app/launcher/engine/rank.go new file mode 100644 index 00000000..c7b0ffb7 --- /dev/null +++ b/app/launcher/engine/rank.go @@ -0,0 +1,224 @@ +package engine + +import ( + "slices" + "sort" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/launcher/match" +) + +// How much the history counts. Each past pick adds a little, a recent pick adds more, and a pick +// made after the same query adds more again. Recent results are listed first for an empty +// query. +const ( + usePerPick = 2 + usePicksCounted = 10 + recentMinPicks = 2 + recentWithin = 30 * 24 * time.Hour + recentMax = 5 + recentBoost = 1_000_000 // puts a recent result before every default one + sameQueryBoost = 20 + maxResults = 50 +) + +func recency(last, now time.Time) int { + switch age := now.Sub(last); { + case age < 24*time.Hour: + return 30 + case age < 3*24*time.Hour: + return 20 + case age < 7*24*time.Hour: + return 10 + case age < recentWithin: + return 3 + } + return 0 +} + +func boost(u Use, query string, now time.Time) int { + if u.Count == 0 { + return 0 + } + b := min(u.Count, usePicksCounted)*usePerPick + recency(u.Last, now) + query = normalizeQuery(query) + for _, q := range u.Queries { + if query != "" && normalizeQuery(q) == query { + b += sameQueryBoost + break + } + } + return b +} + +func normalizeQuery(q string) string { return strings.Join(strings.Fields(strings.ToLower(q)), " ") } + +// of returns no history for a result with no key (Quit), even if something is stored under "". +func (u Usage) of(key string) Use { + if key == "" { + return Use{} + } + return u[key] +} + +func isRecent(u Use, now time.Time) bool { + return u.Count >= recentMinPicks && now.Sub(u.Last) < recentWithin +} + +// Rank filters and orders results for q. When words are typed, each result must match them in +// its title or a keyword (unless Always is set). The match counts most, and a match in the title +// beats one in a keyword. The user's history comes next, then how much of the title the match +// covers. The provider's score only breaks ties, except when paths are typed, where it ranks +// what can be done with them. An empty query keeps the providers' defaults in their order and +// moves up to five recent results above them. +func Rank(q Query, results []Result, usage Usage, now time.Time) []Result { + pattern := strings.Join(q.Terms, " ") + var out []Result + for _, r := range results { + u := usage.of(r.Key) + switch { + case q.Empty(): + if r.Recent && !isRecent(u, now) { + continue + } + r.Score = r.Score*weightBase + boost(u, "", now) + case pattern == "" || r.Always: + r.Score = r.Score*weightBase + boost(u, q.Text, now)*weightUse + default: + m, ok := matchResult(&r, pattern) + if !ok { + continue + } + score := m*weightMatch + boost(u, q.Text, now)*weightUse + if len(q.Paths) > 0 { + score += r.Score * weightBase + } else { + score += coverage(r) + r.Score/10 + } + r.Score = score + } + out = append(out, r) + } + if q.Empty() { + out = liftRecents(out, usage, now) + for i := range out { + if out[i].Pinned { + out[i].Score = 2 * recentBoost + } + } + } + out = dedupe(out) + sort.SliceStable(out, func(i, j int) bool { return out[i].Score > out[j].Score }) + if len(out) > maxResults { + out = out[:maxResults] + } + return grouped(q, out) +} + +// grouped lists ranked results group by group, keeping the ranked order within each group. For +// the empty query, the groups follow groupOrder, then any other group, then results with no +// group. For a typed query, the groups are ordered by their best result, so the first row is +// still the best match. +func grouped(q Query, rs []Result) []Result { + place := map[string]int{} + if q.Empty() { + for i, g := range groupOrder { + place[g] = i + } + } + for _, r := range rs { + if _, ok := place[r.Group]; !ok && (r.Group != "" || !q.Empty()) { + place[r.Group] = len(place) + } + } + last := len(place) // where the empty query puts results with no group + at := func(g string) int { + if i, ok := place[g]; ok { + return i + } + return last + } + sort.SliceStable(rs, func(i, j int) bool { return at(rs[i].Group) < at(rs[j].Group) }) + return rs +} + +const ( + weightMatch = 100 + weightUse = 50 + weightBase = 10 +) + +// matchResult matches pattern against r's title (whose matched positions are drawn bold), its +// keywords, and their English (which is never drawn). A keyword match counts for less, and never +// as exact, so a result whose title also matches comes first. +func matchResult(r *Result, pattern string) (int, bool) { + best, ok := match.Match(pattern, r.Title) + score := best.Score + if ok { + r.match = best.Positions + } + for _, k := range slices.Concat(r.Keywords, r.English) { + m, kok := match.Match(pattern, k) + if !kok { + continue + } + s := m.Score + if match.Exact(pattern, k) { + s -= match.ExactBonus + } + s = s * 3 / 4 + if !ok || s > score { + score, ok = s, true + } + } + return score, ok +} + +// coverage returns how much of the title the match covers, from 0 to 100. For example, "c" covers +// more of "Copy" than of "Cleanup gdrive". +func coverage(r Result) int { + n := len([]rune(r.Title)) + if n == 0 { + return 0 + } + return len(r.match) * 100 / n +} + +// liftRecents puts the five most used recent results first. +func liftRecents(rs []Result, usage Usage, now time.Time) []Result { + type pick struct { + i int + score int + } + var picks []pick + for i, r := range rs { + if u := usage.of(r.Key); isRecent(u, now) { + picks = append(picks, pick{i, boost(u, "", now)}) + } + } + sort.SliceStable(picks, func(a, b int) bool { return picks[a].score > picks[b].score }) + for n, p := range picks { + if n >= recentMax { + break + } + rs[p.i].Score = recentBoost + p.score + } + return rs +} + +func dedupe(rs []Result) []Result { + best := map[string]int{} + var out []Result + for _, r := range rs { + if i, ok := best[r.ID]; ok { + if r.Score > out[i].Score { + out[i] = r + } + continue + } + best[r.ID] = len(out) + out = append(out, r) + } + return out +} diff --git a/app/launcher/engine/rank_test.go b/app/launcher/engine/rank_test.go new file mode 100644 index 00000000..a066a0da --- /dev/null +++ b/app/launcher/engine/rank_test.go @@ -0,0 +1,132 @@ +package engine + +import ( + "reflect" + "slices" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// TestKeylessResultsHaveNoHistory: a result with no key is ranked as if it was never picked, even +// if the history has an entry under "". +func TestKeylessResultsHaveNoHistory(t *testing.T) { + now := time.Now() + results := []Result{ + {ID: "a", Title: "Alpha", Score: 3}, + {ID: "b", Title: "Beta", Score: 2}, + {ID: "k", Key: "op:k", Title: "Kappa", Score: 1}, + } + withEmpty := Usage{"": {Count: 9, Last: now, Queries: []string{"a"}}} + for _, q := range []Query{{}, {Text: "a", Terms: []string{"a"}}} { + got := Rank(q, results, withEmpty, now) + want := Rank(q, results, nil, now) + if !reflect.DeepEqual(got, want) { + t.Errorf("query %q: an entry under \"\" changed the ranking:\n got %+v\nwant %+v", q.Text, got, want) + } + for _, r := range got { + if r.Score >= recentBoost { + t.Errorf("query %q: %q lifted as a recent (score %d)", q.Text, r.Title, r.Score) + } + } + } +} + +func inLanguage(t *testing.T, lang string) { + t.Helper() + i18n.SetLanguage(lang) + t.Cleanup(func() { i18n.SetLanguage(i18n.English) }) +} + +func ids(rs []Result) []string { + out := make([]string, len(rs)) + for i, r := range rs { + out[i] = r.ID + } + return out +} + +// TestSayMatchesBothLanguages: typing finds a row by its title and its search words in the app's +// language and in English. Only a match in the drawn title is drawn bold. The test language +// (Pseudo) stands in for a translation: "Copy" is "[Çópý]" there. +func TestSayMatchesBothLanguages(t *testing.T) { + inLanguage(t, i18n.Pseudo) + now := time.Now() + results := []Result{ + Result{ID: "copy", Score: 2}.Say(i18n.M("Copy"), i18n.M("duplicate, cp")), + Result{ID: "move", Score: 1}.Say(i18n.M("Move"), i18n.M("rename, mv")), + // A title that is a name is kept, and only the search words are translated. + Result{ID: "remote", Title: "gdrive"}.Say(i18n.Text{}, i18n.M("browse")), + } + if got := results[0].Title; got != "[Çópý]" { + t.Fatalf("title %q, want the translated title", got) + } + if got := results[2].Title; got != "gdrive" { + t.Fatalf("a name's title became %q", got) + } + for _, c := range []struct { + typed string + want []string + bold bool // the match is in the drawn title + }{ + {"copy", []string{"copy"}, false}, // the English title + {"çópý", []string{"copy"}, true}, // the translated title + {"çó", []string{"copy"}, true}, // its start + {"duplicate", []string{"copy"}, false}, // an English search word + {"dúplíçá", []string{"copy"}, false}, // a translated search word + {"cp", []string{"copy"}, false}, // a word that both languages share + {"rename", []string{"move"}, false}, + {"brówsé", []string{"remote"}, false}, + {"browse", []string{"remote"}, false}, + {"gdr", []string{"remote"}, true}, + {"paste", nil, false}, + } { + q := Query{Text: c.typed, Terms: []string{c.typed}} + got := Rank(q, results, nil, now) + if !slices.Equal(ids(got), c.want) { + t.Errorf("%q found %q, want %q", c.typed, ids(got), c.want) + continue + } + if len(got) > 0 && (len(got[0].Match()) > 0) != c.bold { + t.Errorf("%q: bold runes %v, want bold %v", c.typed, got[0].Match(), c.bold) + } + } +} + +// TestSayInEnglish: in English, the English terms are the drawn ones, so none is kept twice. +func TestSayInEnglish(t *testing.T) { + inLanguage(t, i18n.English) + r := Result{ID: "copy"}.Say(i18n.M("Copy"), i18n.M("copy, cp")) + if r.Title != "Copy" || !slices.Equal(r.Keywords, []string{"copy", "cp"}) || len(r.English) != 0 { + t.Errorf("title %q, keywords %q, English %q", r.Title, r.Keywords, r.English) + } +} + +// TestWordsSplitsOnEveryComma: a translation may separate its search words with its own commas. +func TestWordsSplitsOnEveryComma(t *testing.T) { + for in, want := range map[string][]string{ + "copy, cp": {"copy", "cp"}, + "复制,拷贝、cp": {"复制", "拷贝", "cp"}, + " a , , b ": {"a", "b"}, + "keep in sync": {"keep in sync"}, + "": nil, + } { + if got := splitWords(in); !slices.Equal(got, want) { + t.Errorf("splitWords(%q) = %q, want %q", in, got, want) + } + } +} + +// TestGroupTitles: every group has a label of its own. +func TestGroupTitles(t *testing.T) { + inLanguage(t, i18n.Pseudo) + seen := map[string]bool{} + for _, g := range groupOrder { + title := GroupTitle(g) + if title == g || seen[title] { + t.Errorf("group %q is shown as %q", g, title) + } + seen[title] = true + } +} diff --git a/app/launcher/engine/services.go b/app/launcher/engine/services.go new file mode 100644 index 00000000..555fc347 --- /dev/null +++ b/app/launcher/engine/services.go @@ -0,0 +1,34 @@ +package engine + +import ( + "context" + + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/transfers" +) + +// Services are the parts of the core that actions call. The fields are nil while the core isn't +// running. +type Services struct { + Mounts Stopper + Serves Stopper + Vfs interface { + Forget(ctx context.Context, id string) error + } + Transfers Transfers + // Everything is Stop Everything, which stops what the core runs (see core.Core.StopAll). + Everything interface { + StopAll(ctx context.Context) (core.StopSummary, error) + } +} + +type Stopper interface { + Stop(ctx context.Context, id string) error + StopAll(ctx context.Context) error +} + +type Transfers interface { + Stop(ctx context.Context, id string) error + // StartCleanup starts the cleanup of remote (`gdrive:`) as a transfer. + StartCleanup(ctx context.Context, remote string) (transfers.Started, error) +} diff --git a/app/launcher/engine/types.go b/app/launcher/engine/types.go new file mode 100644 index 00000000..6f4f5aac --- /dev/null +++ b/app/launcher/engine/types.go @@ -0,0 +1,309 @@ +// Package engine holds the launcher's logic, which is the same on every platform. It parses a +// query, asks the providers for results, ranks them (with fuzzy matching and the user's history) +// and runs the action that the user picks. It knows nothing about windows. The launcher passes it +// data and an Env. +package engine + +import ( + "context" + "slices" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/vfs" +) + +type Query struct { + Text string + // Terms are the words that aren't paths or a URL, in order. + Terms []string + Paths []Path + // URL is the first word that looks like a URL ("https://…", or "example.com/x" with https + // added). + URL string + // Typing is the path that the caret is at the end of (with no space after it), for + // completion. + Typing *Path + // TypingWord is the word that the caret is at the end of, when it isn't a path or a URL. + TypingWord string + // TypingFrom is the position in Text where the word being typed starts, including its + // opening quote. A completion replaces the text from there. It is len(Text) when no word is + // being typed (the text ends with a space or a closing quote). + TypingFrom int + // Dropped are the files dropped on the launcher. The actions apply to them, and the text + // chooses where they go. + Dropped []Path + Clipboard Clip +} + +// Clip is what the launcher knows about the clipboard when it shows. That is either its text, or +// only that it holds a link when reading it would prompt the user (macOS's pasteboard privacy). +// In that case the action reads the clipboard when it runs. +type Clip struct { + Text string + Link bool +} + +func (q Query) Empty() bool { return len(q.Terms) == 0 && len(q.Paths) == 0 && q.URL == "" } + +type Path struct { + // Text is the path as typed, without quotes. A bare remote name keeps its colon ("gdrive:"). + Text string + // Remote is the remote's name, or "" for a local path. + Remote string + Local bool + // Features are the remote's features (FsInfo.features), which say what it can do. + Features map[string]bool +} + +// Can reports whether the path's remote supports feature ("CleanUp", "Purge"). A local path +// never does. +func (p Path) Can(feature string) bool { return !p.Local && p.Features[feature] } + +func (p Path) Short() string { return shorten(p.Text) } + +// Result is one row that the launcher offers. +type Result struct { + // ID is unique within a snapshot. + ID string + // Key is the key that the user's history is stored under ("remote:gdrive", "op:copy"). + Key string + // Title is drawn, in the app's language. + Title string + // Keywords are matched as well as the title, in the app's language. Only matches in the title + // are drawn bold. + Keywords []string + // English holds the title and the keywords in English, when the app shows another language. + // They are matched like keywords and never drawn, so that typing "copy" finds Copy in every + // language. Say fills them. + English []string + Subtitle string + Icon icons.Name + // Tail is grey text on the right, such as a mount point or "3 active". + Tail string + // Score is set by the provider. It says how good a result this is before the query's + // matching and the history are added. + Score int + // Actions are what can be done with the result. The first one runs on Enter. + Actions []Action + // Always skips matching against the query's words. Completion entries use it, because their + // path already selected them. + Always bool + // Recent marks a result that the empty query shows only when the history says it was used. + Recent bool + // Complete is the text that Tab puts in place of the path being typed (a folder entry, a + // remote's root), or "" for none. + Complete string + // Pinned results come first on the empty query, before the recent ones. + Pinned bool + // Group is one of the Group constants, or "" for none. + Group string + + match []int // set by ranking +} + +// Say sets r's title and adds its search words from two messages: in the app's language, and in +// English where that differs. A zero title keeps r's Title, which suits a title that is a name. +// words is one message that lists the search words separated by commas ("copy, cp"), so a +// translation can list as many words as its language needs. +func (r Result) Say(title, words i18n.Text) Result { + if !title.IsZero() { + r.Title = title.Local() + r.English = english(r.English, []string{r.Title}, []string{title.String()}) + } + local, en := Words(words) + r.Keywords = append(r.Keywords, local...) + r.English = english(r.English, local, en) + return r +} + +func english(list, local, en []string) []string { + for _, w := range en { + if !slices.Contains(local, w) && !slices.Contains(list, w) { + list = append(list, w) + } + } + return list +} + +func Words(words i18n.Text) (local, english []string) { + return splitWords(words.Local()), splitWords(words.String()) +} + +// splitWords splits a list of search words on commas, which may be a language's own (Chinese +// "," and "、"). +func splitWords(list string) []string { + var out []string + for _, w := range strings.FieldsFunc(list, func(r rune) bool { return r == ',' || r == ',' || r == '、' }) { + if w = strings.TrimSpace(w); w != "" { + out = append(out, w) + } + } + return out +} + +// The groups that results are listed in. These values name the groups in the code only. +// GroupTitle returns the label that a group is shown with. +const ( + GroupSuggested = "Suggested" + GroupActive = "Active" + GroupOperations = "Operations" + GroupRemotes = "Remotes" + GroupFiles = "Files" + GroupApp = "App" +) + +// groupOrder is the order in which the empty query shows the groups. +var groupOrder = []string{GroupSuggested, GroupActive, GroupOperations, GroupRemotes, GroupFiles, GroupApp} + +func GroupTitle(group string) string { + switch group { + case GroupSuggested: + // i18n: A group of the launcher's rows: what the clipboard suggests. + return i18n.T("Suggested") + case GroupActive: + // i18n: A group of the launcher's rows: what is running now. + return i18n.T("Active") + case GroupOperations: + // i18n: A group of the launcher's rows: copy, sync, mount, and so on. + return i18n.T("Operations") + case GroupRemotes: + // i18n: A group of the launcher's rows: the configured remotes. + return i18n.T("Remotes") + case GroupFiles: + // i18n: A group of the launcher's rows: typed paths and their folders. + return i18n.T("Files") + case GroupApp: + // i18n: A group of the launcher's rows: the app's own screens. + return i18n.T("App") + } + return group +} + +// Match returns the positions of the title's runes that the query matched. +func (r Result) Match() []int { return r.match } + +// SetMatch sets the runes drawn bold, for a result that ranking doesn't match (Always). +func (r *Result) SetMatch(pos []int) { r.match = pos } + +func (r Result) Default() (Action, bool) { + if len(r.Actions) > 0 { + return r.Actions[0], true + } + return Action{}, false +} + +type Action struct { + ID string + Name string // shown in the ⌘K panel and in the footer's ⏎ hint + Icon icons.Name + // KeepOpen leaves the launcher up (a drill-in that changes the query). + KeepOpen bool + // Opens marks an action that opens one of the app's windows (Env.OpenWindow, OpenFull). The + // launcher prepares the focus first (the platform's Activate) while the user's key press is + // being handled, so the window comes up with the focus. + Opens bool + // Stay runs the action with the launcher up, for an action that opens no window. Its progress + // and its outcome are shown in the status corner (Env.Status). So is a failure, and only there. + Stay bool + // Confirm, when set, is a question asked in the launcher before the action runs. Only + // actions that stop or delete something ask, and they are drawn in red. + Confirm string + Run func(ctx context.Context, env Env) error +} + +type StatusKind int + +const ( + // StatusWorking means the action is in progress: "Unmounting /Volumes/gdrive…". + StatusWorking StatusKind = iota + 1 + // StatusDone is the outcome: "Unmounted /Volumes/gdrive". + StatusDone +) + +// Env is everything an action may do. The launcher implements it, and tests record the calls. +type Env interface { + // OpenWindow opens (or reuses) a window for a page at url. + OpenWindow(name, url string) + // OpenFull opens a window for a page at the size of the screen (the Commander). + OpenFull(name, url string) + // SetQuery replaces the text and keeps the launcher open. + SetQuery(text string) + Clipboard(text string) + // Reveal shows a path in the file manager. + Reveal(path string) + OpenURL(url string) + Notify(title, body string) + // Status shows what a Stay action is doing, or that it is done, in the launcher's status + // corner. A status from an earlier action, or one sent after the launcher closed, is dropped. + // A failure is reported by returning an error from the action instead. + Status(kind StatusKind, text string) + // ClipboardText reads the clipboard after the user asked for it. + ClipboardText() string + Quit() + Core() Services +} + +type Provider interface { + // Query returns results for q using d, or nothing. For an empty query it returns what it + // offers by default (including its Recent results). It must return promptly once ctx is + // done. + Query(ctx context.Context, q Query, d *Data) []Result +} + +// Streamer is a provider whose results grow while it works, such as the pages of a listing. It +// passes everything found so far to partial each time, and returns the final list. The engine +// uses it instead of Query and treats it as slow, so its results come in a later snapshot rather +// than delaying the first one. +type Streamer interface { + QueryStream(ctx context.Context, q Query, d *Data, partial func([]Result)) []Result +} + +// Data is what the providers read: the core's state, as cached by the launcher. +type Data struct { + // Home is this machine's home folder, which ~ stands for in a typed path. + Home string + Remotes []Remote + Mounts []mounts.MountRow + Serves []serves.ServeRow + Vfs []vfs.VFS + // Tunnel is true while the remote tunnel is on or starting. + Tunnel bool + // Transfers are the queued and running transfers. Running ones have their Live progress as + // last read. + Transfers []transfers.Transfer + // Failed are the transfers that failed among the last ones to end, newest first, as last + // read. A provider decides which are recent enough to show. + Failed []transfers.Transfer + ServeTypes []string + // List lists a folder and passes each page of entries to page as it arrives. It is nil when + // the core isn't running. + List func(ctx context.Context, dir string, page func([]Entry)) error +} + +type Remote struct { + Name, Type string + Features map[string]bool +} + +type Entry struct { + Name string + // Path is the entry's full path, written in the same form as the folder's root. + Path string + Dir bool +} + +// Usage is the history. It records how often and when each key was picked, and for which +// queries. +type Usage map[string]Use + +type Use struct { + Count int + Last time.Time + Queries []string +} diff --git a/app/launcher/env.go b/app/launcher/env.go new file mode 100644 index 00000000..4c16f753 --- /dev/null +++ b/app/launcher/env.go @@ -0,0 +1,173 @@ +package launcher + +import ( + "context" + "log/slog" + "maps" + "sync" + "time" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/core/i18n" + launcherpb "github.com/rclone/rclone-ui/core/launcher" + "github.com/rclone/rclone-ui/core/rclone" +) + +// env is the environment that an action runs in. It gives the action access to the platform and +// the core. +type env struct { + l *Launcher + action engine.Action + // seq is the sequence number of the status that the action last showed in the corner (main + // thread). When the action ends, it clears only that status. + seq uint64 +} + +func (e *env) OpenWindow(name, url string) { e.l.p.OpenWindow(name, url) } +func (e *env) OpenFull(name, url string) { e.l.p.OpenFull(name, url) } +func (e *env) Clipboard(text string) { e.l.p.Clipboard(text) } +func (e *env) Reveal(path string) { e.l.p.Reveal(path) } +func (e *env) OpenURL(url string) { e.l.p.OpenURL(url) } +func (e *env) Notify(title, body string) { e.l.p.Notify(title, body) } +func (e *env) Quit() { e.l.p.Quit() } +func (e *env) Core() engine.Services { return e.l.state.Services() } + +// Status shows a Stay action's progress or outcome in the status corner. It only does so if the +// corner is listening to this action, which means it is the last action run and the launcher +// hasn't closed since. Otherwise the status is dropped. Called off the main thread. +func (e *env) Status(kind engine.StatusKind, text string) { + l := e.l + l.p.MainSync(func() { + if l.acting != e { + return + } + k := view.StatusLoading + if kind == engine.StatusDone { + k = view.StatusDone + } + e.seq = l.setStatus(view.Status{Kind: k, Text: text}) + }) +} + +// finish ends the action. If the corner is listening to it, its progress message is cleared, or +// a failure is shown there in red. Otherwise a failure is only logged (the caller logs every +// failure). Called off the main thread. +func (e *env) finish(err error) { + l := e.l + l.p.MainSync(func() { + if l.acting != e { + return + } + l.acting = nil + switch { + case err != nil: + // i18n: The launcher's status when an action failed. %[1]s is the action's name, such as "Unmount", and %[2]s the error. + text := i18n.T("%[1]s failed: %[2]s", e.action.Name, rclone.ErrorOf(err).Localized().Message) + l.setStatus(view.Status{Kind: view.StatusError, Text: text}) + case l.statusSeq == e.seq && l.status.Kind == view.StatusLoading: + l.clearStatus() + } + }) +} + +// ClipboardText reads the clipboard after the user chose a result that needs it. Called off the +// main thread, like all actions. +func (e *env) ClipboardText() string { + if e.l.p.ClipboardText == nil { + return "" + } + return e.l.p.ClipboardText() +} + +// SetQuery is used for drill-in actions. The launcher stays up and runs the query for the new +// text. +func (e *env) SetQuery(text string) { + l := e.l + l.p.Main(func() { + l.panel = nil + l.text = text + if l.view != nil { + if !l.view.Visible() { + l.Show() + } + l.view.SetQuery(text, false) + } + l.run() + }) +} + +// History is the launcher's usage history, which the core stores. +type History interface { + Usage(ctx context.Context) ([]launcherpb.Usage, error) + Record(ctx context.Context, key, query string) error +} + +// usageStore caches the usage history that the core stores. It is read when the launcher shows, +// and written after each pick: the cache at once, then the core. +type usageStore struct { + history History // nil when there is no history (in tests) + log *slog.Logger + + mu sync.Mutex + usage engine.Usage +} + +func newUsageStore(history History, log *slog.Logger) *usageStore { + return &usageStore{history: history, log: log, usage: engine.Usage{}} +} + +// load reads the history again, in the background. +func (s *usageStore) load() { + if s.history == nil { + return + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + usage, err := s.history.Usage(ctx) + if err != nil { + s.log.Debug("could not read the launcher's history", "error", err) + return + } + u := engine.Usage{} + for _, x := range usage { + u[x.Key] = engine.Use{Count: int(x.Count), Last: time.UnixMilli(x.LastUsed), Queries: x.Queries} + } + s.mu.Lock() + s.usage = u + s.mu.Unlock() + }() +} + +func (s *usageStore) snapshot() engine.Usage { + s.mu.Lock() + defer s.mu.Unlock() + out := make(engine.Usage, len(s.usage)) + maps.Copy(out, s.usage) + return out +} + +// record records that key was picked after typing query. +func (s *usageStore) record(key, query string) { + s.mu.Lock() + u := s.usage[key] + u.Count++ + u.Last = time.Now() + if query != "" { + u.Queries = append([]string{query}, u.Queries...) + if len(u.Queries) > 5 { + u.Queries = u.Queries[:5] + } + } + s.usage[key] = u + s.mu.Unlock() + if s.history == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := s.history.Record(ctx, key, query); err != nil { + s.log.Debug("could not record a launcher pick", "error", err) + } +} diff --git a/app/launcher/host/core.go b/app/launcher/host/core.go new file mode 100644 index 00000000..90bd2987 --- /dev/null +++ b/app/launcher/host/core.go @@ -0,0 +1,40 @@ +package host + +import ( + "context" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/browse" + "github.com/rclone/rclone-ui/core/transfers" +) + +// coreAPIs lists folders for completion and provides the services that actions call. The core's +// state doesn't come through it: the launcher reads that from the store. +type coreAPIs struct{ apis *core.APIs } + +func (r coreAPIs) List(ctx context.Context, dir string, page func([]engine.Entry)) error { + return r.apis.ListFolder(ctx, dir, func(rows []browse.Row) { + entries := make([]engine.Entry, len(rows)) + for i, row := range rows { + entries[i] = engine.Entry{Name: row.Name, Path: row.Path, Dir: row.IsDir || row.IsBucket} + } + page(entries) + }) +} + +func (r coreAPIs) Services() engine.Services { + return engine.Services{Mounts: r.apis.Mounts, Serves: r.apis.Serves, Vfs: r.apis.Vfs, + Transfers: launcherTransfers{r.apis.Transfers, r.apis}, Everything: r.apis} +} + +// launcherTransfers holds the transfer actions of the launcher: the pages' API, and the core's +// cleanup, which the pages can't start. +type launcherTransfers struct { + *transfers.API + apis *core.APIs +} + +func (t launcherTransfers) StartCleanup(ctx context.Context, remote string) (transfers.Started, error) { + return t.apis.StartCleanup(ctx, remote) +} diff --git a/app/launcher/host/dev.go b/app/launcher/host/dev.go new file mode 100644 index 00000000..9e207eca --- /dev/null +++ b/app/launcher/host/dev.go @@ -0,0 +1,88 @@ +//go:build !production + +package host + +import ( + "bufio" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +// DevScript runs launcher scripts that are dropped in dir (RCUI_DEV_LAUNCHER). A script is a file +// named .cmd with one command per line. It runs once and is then removed. The commands +// are: show, hide, type , key >, hover , +// click , drop … (paths without spaces), sleep , and state (which is logged). +// Only a development build has it. +func (h *Host) DevScript(dir string) { + log := h.o.Log + if err := os.MkdirAll(dir, 0o700); err != nil { + log.Error("dev launcher", "error", err) + return + } + keys := map[string]view.Key{"up": view.KeyUp, "down": view.KeyDown, "enter": view.KeyEnter, + "esc": view.KeyEsc, "tab": view.KeyTab, "actions": view.KeyActions} + go func() { + for range time.Tick(200 * time.Millisecond) { + files, _ := filepath.Glob(filepath.Join(dir, "*.cmd")) + sort.Strings(files) + for _, f := range files { + data, err := os.ReadFile(f) + _ = os.Remove(f) + if err != nil { + continue + } + sc := bufio.NewScanner(strings.NewReader(string(data))) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + verb, arg, _ := strings.Cut(line, " ") + switch verb { + case "show": + application.InvokeSync(h.l.Show) + case "hide": + application.InvokeSync(h.l.Hide) + case "type": + application.InvokeSync(func() { h.l.DevType(arg) }) + case "key": + k := view.KeyEvent{Key: keys[arg]} + if c, ok := strings.CutPrefix(arg, "row:"); ok && c != "" { + k = view.KeyEvent{Key: view.KeyRow, Char: []rune(c)[0]} + } + application.InvokeSync(func() { h.l.DevKey(k) }) + case "hover", "click": + row, _ := strconv.Atoi(arg) + application.InvokeSync(func() { + if verb == "hover" { + h.l.DevHover(row) + } else { + h.l.DevClick(row) + } + }) + case "drop": + paths := strings.Fields(arg) + application.InvokeSync(func() { h.l.DevDrop(paths) }) + case "sleep": + d, _ := time.ParseDuration(arg) + time.Sleep(d) + case "state": + var s string + application.InvokeSync(func() { s = h.l.DevState() }) + log.Info("dev launcher: state\n" + s) + default: + log.Warn("dev launcher: unknown command", "line", line) + } + } + } + } + }() +} diff --git a/app/launcher/host/host.go b/app/launcher/host/host.go new file mode 100644 index 00000000..72be277a --- /dev/null +++ b/app/launcher/host/host.go @@ -0,0 +1,243 @@ +// Package host builds the launcher for the UI role and lets the role drive it from any goroutine. +// It joins the launcher's engine, the store of the core's state, the core's APIs and this OS's +// view (see host_.go). The launcher's state lives on the main thread, and Host moves each call +// there. +package host + +import ( + "fmt" + "log/slog" + "runtime/debug" + "sync" + "sync/atomic" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/launcher" + "github.com/rclone/rclone-ui/app/launcher/state" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/app/launcher/view/linux" + "github.com/rclone/rclone-ui/app/launcher/view/linux/gnome" + "github.com/rclone/rclone-ui/core" +) + +type Options struct { + App *application.App + // Log is the UI's log. The launcher logs with src=launcher. + Log *slog.Logger + // Store is the one copy of the core's state, which the tray shows too. + Store *corestate.Store + APIs *core.APIs + // Production is true in a release build. A development build lets the web inspector open on + // the launcher's page. + Production bool + // Open opens the window for a route. The route decides the window's name and size. + Open func(url string) error + // Reveal shows a path selected in its folder, and OpenURL opens a URL in the browser. + Reveal, OpenURL func(string) error + // Notify shows a desktop notification, and Quit runs the quit flow. Both may wait for the + // user, so the launcher calls them on a goroutine of their own. + Notify func(title, body string) + Quit func() + // Acks are the pages' acknowledgements, where GNOME's extension records that it was enabled + // once (see gnome.Ensure). + Acks gnome.Acks +} + +type Host struct { + o Options + l *launcher.Launcher + shortcut *launcher.Shortcut + log *slog.Logger + view view.View // main thread + // page is the launcher's view on Linux, which a page draws. It is nil elsewhere, and until + // the view exists. + page atomic.Pointer[linux.View] + readyOnce sync.Once + // suspended counts the quits and updates under way (see Suspend). While it is above zero, the + // launcher stays hidden and its shortcut and Show do nothing, because the core may stop at any + // moment. + suspended atomic.Int32 +} + +// New builds the launcher without its view, which Create makes once the app runs. +func New(o Options) *Host { + h := &Host{o: o, log: o.Log.With("src", "launcher")} + open := func(_, url string) { + if err := o.Open(url); err != nil { + h.log.Error("could not open a window", "route", url, "error", err) + } + } + p := launcher.Platform{ + // Open takes the window's name and size from the route, so the name passed here is unused. + OpenWindow: open, + OpenFull: open, + Clipboard: func(text string) { o.App.Clipboard.SetText(text) }, + // Show the path selected in its folder rather than opening it, because opening a program + // (an .exe or an .app) would run it. + Reveal: func(path string) { + if err := o.Reveal(path); err != nil { + h.log.Error("could not show a path", "path", path, "error", err) + } + }, + OpenURL: func(url string) { + if err := o.OpenURL(url); err != nil { + h.log.Error("could not open a URL", "url", url, "error", err) + } + }, + // A toast shown as a dialog (when toasts aren't allowed) waits for the user, so it must not + // run on the caller's thread. + Notify: func(title, body string) { go o.Notify(title, body) }, + Activate: activate, + Quit: func() { go o.Quit() }, + Main: application.InvokeAsync, + MainSync: func(fn func()) { + if err := mainSync(fn); err != nil { + h.log.Error("the launcher failed on the main thread", "error", err) + } + }, + Mod: mod, + ClipboardText: h.clipboardText, + ClipboardPeek: h.clipboardPeek, + } + h.l = launcher.New(p, h.log, state.New(o.Store, coreAPIs{o.APIs}), o.APIs.Launcher) + h.shortcut = launcher.NewShortcut(o.App, h.log, h.pressed) + return h +} + +// clipboardText returns the clipboard's text, or "". Call it off the main thread, because Wails +// reads the clipboard on the main thread. +func (h *Host) clipboardText() string { + t, _ := h.o.App.Clipboard.Text() + return t +} + +// Create builds the view, hidden. If the platform can't create it, the launcher stays unavailable +// and the error explains why. +func (h *Host) Create() error { + var err error + if perr := mainSync(func() { + v, e := h.newView(h.l.Events()) + if e != nil { + err = e + return + } + h.view = v + h.l.Attach(v) + if md, ok := v.(interface{ Mode() string }); ok { + h.log.Info("launcher window", "mode", md.Mode()) + } + }); perr != nil { + return perr + } + return err +} + +// Page returns the launcher's view on Linux, which a page draws (see linux.PageService). It +// returns nil on macOS and Windows, and until the view exists. +func (h *Host) Page() *linux.View { + if h == nil { + return nil + } + return h.page.Load() +} + +// invokeSync is application.InvokeSync. Tests replace it, because no app runs in tests. +var invokeSync = application.InvokeSync + +// mainSync runs fn on the main thread and waits for it. A panic in fn is returned as an error. +// Wails recovers a panic in the function passed to InvokeSync and ends the wait, but it passes the +// panic only to its PanicHandler. Without the recover here, the caller would never learn that +// Create failed. +func mainSync(fn func()) error { + var err error + invokeSync(recovering(fn, &err)) + return err +} + +// recovering wraps fn so that a panic is stored in *err, with the stack. +func recovering(fn func(), err *error) func() { + return func() { + defer func() { + if r := recover(); r != nil { + *err = fmt.Errorf("panic: %v\n%s", r, debug.Stack()) + } + }() + fn() + } +} + +// pressed handles the shortcut by toggling the launcher. On Wayland the compositor may pass an +// activation token for the press, which the window uses to take the focus. A press that hides the +// launcher doesn't keep its token, because the next Show (from the tray) would present a stale one. +func (h *Host) pressed(token string) { application.InvokeAsync(func() { h.toggle(token) }) } + +// toggle does pressed's work on the main thread. +func (h *Host) toggle(token string) { + if h.suspended.Load() > 0 { + return + } + if a, ok := h.view.(view.Activator); ok && token != "" && !h.l.Visible() { + a.SetActivationToken(token) + } + h.l.Toggle() +} + +func (h *Host) Show() { + application.InvokeAsync(func() { + if h.suspended.Load() > 0 { + return + } + h.l.Show() + }) +} + +// Suspend hides the launcher and keeps it hidden, with its shortcut doing nothing, until Resume. +// It is used when a quit or an update is about to stop the core, and nothing should start in the +// meantime. Each Suspend has a matching Resume. (A quit that is asked for during an update's +// question has its own pair.) +func (h *Host) Suspend() { + if h == nil { + return + } + h.suspended.Add(1) + application.InvokeAsync(h.l.Hide) +} + +// Resume undoes a Suspend, after the quit or the update was cancelled or failed. +func (h *Host) Resume() { + if h == nil { + return + } + h.suspended.Add(-1) +} + +// LanguageChanged draws the launcher again in the app's language, when the language setting +// changes. +func (h *Host) LanguageChanged() { + if h == nil { + return + } + application.InvokeAsync(h.l.LanguageChanged) +} + +// SetShortcut replaces the launcher's global shortcut, and "" removes it. If the OS refuses the +// shortcut, SetShortcut returns an error and keeps the previous one. +func (h *Host) SetShortcut(shortcut string) error { return h.shortcut.Set(shortcut) } + +// SetStaysOpen sets whether the launcher stays open when the user clicks outside it. +func (h *Host) SetStaysOpen(stays bool) { h.l.SetStaysOpen(stays) } + +// CoreReady runs this OS's one-time setup (see ready in host_.go) the first time the core is +// ready in a run. The setup runs on the main thread, where the view lives. CoreReady doesn't read +// the core's state, because the store does that. +func (h *Host) CoreReady() { + application.InvokeAsync(func() { + h.readyOnce.Do(func() { + if h.view != nil { + h.ready(h.view) + } + }) + }) +} diff --git a/app/launcher/host/host_darwin.go b/app/launcher/host/host_darwin.go new file mode 100644 index 00000000..b4d7f849 --- /dev/null +++ b/app/launcher/host/host_darwin.go @@ -0,0 +1,31 @@ +//go:build darwin + +package host + +import ( + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/app/launcher/view/darwin" +) + +// mod is the modifier key as drawn in the rows' shortcuts. +const mod = "⌘" + +// activate makes the app active when an action opens a window from the launcher's panel, because +// the panel itself never activates the app. +var activate = darwin.ActivateApp + +// newView creates the launcher's panel with Cocoa. It must run on the main thread. +func (h *Host) newView(ev view.Events) (view.View, error) { return darwin.New(ev) } + +// ready runs once per run, when the core is ready. The launcher needs nothing more here. +func (h *Host) ready(view.View) {} + +// clipboardPeek returns what the launcher may learn about the clipboard without macOS asking the +// user (pasteboard privacy, in macOS 15.4 and later), plus the clipboard's change count. That is +// only whether it holds a link, unless reading it is silent (on an older macOS, or when the user +// always allows it). +func (h *Host) clipboardPeek() (engine.Clip, string) { + text, link, count := darwin.PeekClipboard() + return engine.Clip{Text: text, Link: link}, count +} diff --git a/app/launcher/host/host_linux.go b/app/launcher/host/host_linux.go new file mode 100644 index 00000000..cdbab7c7 --- /dev/null +++ b/app/launcher/host/host_linux.go @@ -0,0 +1,55 @@ +//go:build linux + +package host + +import ( + "context" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/app/launcher/view/linux" + "github.com/rclone/rclone-ui/app/launcher/view/linux/gnome" +) + +// mod is the modifier key as drawn in the rows' shortcuts. +const mod = "Ctrl+" + +// activate is nil, because the launcher's window takes the focus itself. There is no +// non-activating panel on Linux. +var activate func() + +// newView creates the launcher's window: a window of the app whose page draws the launcher (see +// app/launcher/view/linux). It must run on the main thread. +func (h *Host) newView(ev view.Events) (view.View, error) { + win := h.o.App.Window.NewWithOptions(linux.WindowOptions(!h.o.Production)) + plat, err := linux.NewPlatform(win) + if err != nil { + win.Close() + return nil, err + } + after := func(d time.Duration, fn func()) { time.AfterFunc(d, fn) } + v := linux.New(linux.Wrap(win), plat, ev, application.InvokeAsync, after) + linux.Attach(win, v) + h.page.Store(v) + return v, nil +} + +// ready runs once per run, when the core is ready. On GNOME, only a shell extension can place the +// launcher's window, so it makes sure that extension is installed and enabled. A Flatpak can talk +// to GNOME Shell, because the app doesn't start on GNOME without that permission (flatpakGate in +// app/app.go). +func (h *Host) ready(v view.View) { + if lv, ok := v.(*linux.View); ok && lv.PlacedByShell() { + go gnome.Ensure(context.Background(), h.o.Log, h.o.Acks) + } +} + +// clipboardPeek returns what the launcher may learn about the clipboard. Here that is its text, +// because reading it doesn't prompt the user. +func (h *Host) clipboardPeek() (engine.Clip, string) { + t := h.clipboardText() + return engine.Clip{Text: t}, t +} diff --git a/app/launcher/host/host_test.go b/app/launcher/host/host_test.go new file mode 100644 index 00000000..12744510 --- /dev/null +++ b/app/launcher/host/host_test.go @@ -0,0 +1,86 @@ +package host + +import ( + "log/slog" + "slices" + "strings" + "testing" + "time" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/launcher" + "github.com/rclone/rclone-ui/app/launcher/state" + "github.com/rclone/rclone-ui/app/launcher/view/viewtest" + "github.com/rclone/rclone-ui/core" +) + +// TestMainSyncRecovers checks that a panic on the main thread is returned as an error naming the +// panic. The replacement for InvokeSync behaves like Wails' version: it recovers a panic and ends +// the wait, but doesn't pass the panic to the caller. +func TestMainSyncRecovers(t *testing.T) { + was := invokeSync + t.Cleanup(func() { invokeSync = was }) + invokeSync = func(fn func()) { + done := make(chan struct{}) + go func() { + defer close(done) + defer func() { _ = recover() }() + fn() + }() + <-done + } + + got := make(chan error, 1) + go func() { got <- mainSync(func() { panic("the view broke") }) }() + select { + case err := <-got: + if err == nil || !strings.Contains(err.Error(), "the view broke") { + t.Fatalf("the error doesn't name the panic: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("mainSync waits forever after a panic") + } + + ran := false + if err := mainSync(func() { ran = true }); err != nil || !ran { + t.Fatalf("a plain call: ran %v, error %v", ran, err) + } +} + +// tokenView is a launcher window that accepts the compositor's activation tokens, as on Wayland. +type tokenView struct { + *viewtest.Fake + tokens []string +} + +func (v *tokenView) SetActivationToken(token string) { v.tokens = append(v.tokens, token) } + +// TestPressKeepsATokenOnlyToShow checks that the shortcut's token goes to the window only when the +// press shows the launcher, because a token from a press that hides it would be stale at the next +// Show. While a quit or an update keeps the launcher suspended, a press does nothing. +func TestPressKeepsATokenOnlyToShow(t *testing.T) { + log := slog.New(slog.DiscardHandler) + apis := core.NewAPIs(core.APIOptions{}) + src := state.New(corestate.New(corestate.APIReader(apis), log), coreAPIs{apis}) + l := launcher.New(launcher.Platform{Main: func(func()) {}, MainSync: func(fn func()) { fn() }}, log, src, nil) + v := &tokenView{Fake: &viewtest.Fake{}} + l.Attach(v) + h := &Host{l: l, view: v, log: log} + + h.toggle("one") // shows + h.toggle("two") // hides + h.toggle("") // shows, with no token + if !v.Shown || !slices.Equal(v.tokens, []string{"one"}) { + t.Fatalf("shown %v, tokens %q", v.Shown, v.tokens) + } + h.suspended.Add(1) + h.toggle("three") + if !v.Shown || len(v.tokens) != 1 { + t.Fatalf("suspended: shown %v, tokens %q", v.Shown, v.tokens) + } + h.suspended.Add(-1) + h.toggle("four") + if v.Shown || len(v.tokens) != 1 { + t.Fatalf("resumed: shown %v, tokens %q", v.Shown, v.tokens) + } +} diff --git a/app/launcher/host/host_windows.go b/app/launcher/host/host_windows.go new file mode 100644 index 00000000..6c5ce2a8 --- /dev/null +++ b/app/launcher/host/host_windows.go @@ -0,0 +1,31 @@ +//go:build windows + +package host + +import ( + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/view" + winview "github.com/rclone/rclone-ui/app/launcher/view/windows" +) + +// mod is the modifier key as drawn in the rows' shortcuts. +const mod = "Ctrl+" + +// activate passes the foreground to the window that an action opens. The launcher's window +// doesn't give the foreground back when it hides, so this brings the new window to the front as it +// appears. +var activate = winview.HandOff + +// newView creates the launcher's window with Win32 and Direct2D. It must run on the main thread. +func (h *Host) newView(ev view.Events) (view.View, error) { return winview.New(ev) } + +// ready runs on the main thread once per run, when the core is ready. It makes the window's +// panics go to the app's log. +func (h *Host) ready(view.View) { winview.SetLog(h.o.Log) } + +// clipboardPeek returns what the launcher may learn about the clipboard. Here that is its text, +// because reading it doesn't prompt the user. +func (h *Host) clipboardPeek() (engine.Clip, string) { + t := h.clipboardText() + return engine.Clip{Text: t}, t +} diff --git a/app/launcher/icons/gen/main.go b/app/launcher/icons/gen/main.go new file mode 100644 index 00000000..e618b90f --- /dev/null +++ b/app/launcher/icons/gen/main.go @@ -0,0 +1,95 @@ +// Command gen writes icons_gen.go. For every Name in icons.go, it stores the regular variant of +// that Zappicon glyph as an SVG document. It reads the variant's ES module (the paths' `d` and +// fill rule) and adds the same half-unit stroke that the pages' global.css adds, so the +// launcher's glyphs have the same weight as the pages' icons. +package main + +import ( + "bytes" + "fmt" + "go/format" + "os" + "path/filepath" + "regexp" + "sort" + "strings" +) + +var ( + nameRE = regexp.MustCompile(`Name = "([a-z0-9-]+)"`) + elRE = regexp.MustCompile(`\{[^}]*\}`) + dRE = regexp.MustCompile(`d: "([^"]+)"`) +) + +func main() { + // go generate runs in app/launcher/icons. + src, err := os.ReadFile("icons.go") + check(err) + seen := map[string]bool{} + var names []string + for _, m := range nameRE.FindAllSubmatch(src, -1) { + if n := string(m[1]); !seen[n] { + seen[n] = true + names = append(names, n) + } + } + sort.Strings(names) + variants := filepath.Join("..", "..", "..", "node_modules", "@zappicon", "react", "dist", "variants") + + var b bytes.Buffer + b.WriteString("// Code generated by gen from @zappicon/react; DO NOT EDIT.\n\npackage icons\n\nvar svgs = map[Name]string{\n") + for _, n := range names { + doc, err := svg(filepath.Join(variants, n+".es.js")) + check(err) + fmt.Fprintf(&b, "\t%q: %q,\n", n, doc) + } + b.WriteString("}\n") + out, err := format.Source(b.Bytes()) + check(err) + check(os.WriteFile("icons_gen.go", out, 0o644)) +} + +// svg returns the regular variant of the glyph in module file f. +func svg(f string) (string, error) { + src, err := os.ReadFile(f) + if err != nil { + return "", err + } + s := string(src) + i := strings.Index(s, `["regular",`) + if i < 0 { + return "", fmt.Errorf("%s: no regular variant", f) + } + s = s[i:] + // the variant ends where the next one starts + if j := strings.Index(s[1:], "\n [\""); j >= 0 { + s = s[:j+1] + } + var b strings.Builder + b.WriteString(``) + paths := 0 + for _, e := range elRE.FindAllString(s, -1) { + d := dRE.FindStringSubmatch(e) + if d == nil { + continue + } + rule := "nonzero" + if strings.Contains(e, `fillRule: "evenodd"`) { + rule = "evenodd" + } + fmt.Fprintf(&b, ``, rule, d[1]) + paths++ + } + if paths == 0 { + return "", fmt.Errorf("%s: no paths in the regular variant", f) + } + b.WriteString(``) + return b.String(), nil +} + +func check(err error) { + if err != nil { + fmt.Fprintln(os.Stderr, "gen:", err) + os.Exit(1) + } +} diff --git a/app/launcher/icons/icons.go b/app/launcher/icons/icons.go new file mode 100644 index 00000000..385fffb6 --- /dev/null +++ b/app/launcher/icons/icons.go @@ -0,0 +1,72 @@ +// Package icons holds the launcher's glyphs, which are the regular variants of Zappicon icons. +// They are SVG documents that each view draws with its OS's own renderer, so they stay sharp at +// any scale and can be tinted per row. gen (go generate) writes icons_gen.go from +// node_modules/@zappicon/react, for the names below. +package icons + +import ( + "maps" + "slices" + "strings" +) + +//go:generate go run ./gen + +// Name identifies a glyph by the name of its Zappicon file. +type Name string + +// The launcher's glyphs, named by what they stand for. After adding one, run go generate. +const ( + Copy Name = "page" + Move Name = "arrow-right-square" + Sync Name = "arrows-rotate" + Bisync Name = "repeat" + Download Name = "download-bracket" + Mount Name = "hard-drive" + Serve Name = "tower-broadcast" + Delete Name = "trash" + Purge Name = "trash-simple" + Cleanup Name = "archive-box" + VFS Name = "database" + Settings Name = "gear" + Commander Name = "layout-1" + Transfers Name = "inbox" + Failed Name = "exclamation-triangle" + Templates Name = "layer-group" + Watchers Name = "folder-connection" + Schedules Name = "clock" + Automounts Name = "play-circle" + Wizard Name = "compass" + Guides Name = "graduation-cap" + NewRemote Name = "plus" + Remotes Name = "server-simple" + Bell Name = "bell" + Mobile Name = "mobile" + Remote Name = "cloud" + Folder Name = "folder" + File Name = "file" + GitHub Name = "code" + Quit Name = "power-off" + Stop Name = "stop" + StopAll Name = "ban" + Open Name = "arrow-up-right-square" + Link Name = "link-simple" + Back Name = "arrow-left-small" + Search Name = "search" + Edit Name = "pen" + Clipboard Name = "clipboard" + Reveal Name = "eye" + Browser Name = "globe-simple" +) + +// SVG returns the glyph's document (24×24, black, to be tinted), or "" for an unknown name. +func SVG(n Name) string { return svgs[n] } + +// All returns every glyph's name, sorted. +func All() []Name { return slices.Sorted(maps.Keys(svgs)) } + +// Tinted returns the glyph's document in a colour (#rrggbb), for the views that can't tint a +// black image themselves. It returns "" for an unknown name. +func Tinted(n Name, colour string) string { + return strings.ReplaceAll(svgs[n], `"#000"`, `"`+colour+`"`) +} diff --git a/app/launcher/icons/icons_gen.go b/app/launcher/icons/icons_gen.go new file mode 100644 index 00000000..40eae701 --- /dev/null +++ b/app/launcher/icons/icons_gen.go @@ -0,0 +1,46 @@ +// Code generated by gen from @zappicon/react; DO NOT EDIT. + +package icons + +var svgs = map[Name]string{ + "archive-box": "", + "arrow-left-small": "", + "arrow-right-square": "", + "arrow-up-right-square": "", + "arrows-rotate": "", + "ban": "", + "bell": "", + "clipboard": "", + "clock": "", + "cloud": "", + "code": "", + "compass": "", + "database": "", + "download-bracket": "", + "exclamation-triangle": "", + "eye": "", + "file": "", + "folder": "", + "folder-connection": "", + "gear": "", + "globe-simple": "", + "graduation-cap": "", + "hard-drive": "", + "inbox": "", + "layer-group": "", + "layout-1": "", + "link-simple": "", + "mobile": "", + "page": "", + "pen": "", + "play-circle": "", + "plus": "", + "power-off": "", + "repeat": "", + "search": "", + "server-simple": "", + "stop": "", + "tower-broadcast": "", + "trash": "", + "trash-simple": "", +} diff --git a/app/launcher/icons/icons_test.go b/app/launcher/icons/icons_test.go new file mode 100644 index 00000000..90b770c5 --- /dev/null +++ b/app/launcher/icons/icons_test.go @@ -0,0 +1,21 @@ +package icons + +import ( + "strings" + "testing" +) + +// TestTinted: every black in the glyph is replaced by the given colour, and an unknown name has no +// glyph. +func TestTinted(t *testing.T) { + got := Tinted(Copy, "#ffffff") + if got == "" || strings.Contains(got, `"#000"`) || !strings.Contains(got, `"#ffffff"`) { + t.Fatalf("tinted: %s", got) + } + if want := strings.ReplaceAll(SVG(Copy), `"#000"`, `"#ffffff"`); got != want { + t.Fatalf("tinted:\n got %s\nwant %s", got, want) + } + if got := Tinted("no-such-glyph", "#ffffff"); got != "" { + t.Fatalf("an unknown name: %q", got) + } +} diff --git a/app/launcher/launcher.go b/app/launcher/launcher.go new file mode 100644 index 00000000..72c555a5 --- /dev/null +++ b/app/launcher/launcher.go @@ -0,0 +1,983 @@ +// Package launcher is the command palette that opens with the global shortcut. It lists commands, +// remotes, paths and what is running. The engine (engine, providers) finds results for a query, +// state keeps a copy of the core's state, and a view (view/) draws the window with the OS's +// own toolkit. Launcher sits between them and makes every decision: the selection, the keys, the +// ⌘K panel, completion, and when to hide. Its state lives on the main thread, because the view's +// events arrive there and the engine's results are sent there. +package launcher + +import ( + "context" + "fmt" + "log/slog" + "os" + "path/filepath" + "runtime/debug" + "slices" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/engine/providers" + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/app/launcher/match" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +// Platform is what the app gives the launcher: ways to open windows, the OS's services, and access +// to the main thread. +type Platform struct { + OpenWindow func(name, url string) + OpenFull func(name, url string) + Clipboard func(text string) + Reveal func(path string) + OpenURL func(url string) + Notify func(title, body string) + // Activate prepares the focus for a window that an action opens, just before the launcher + // hides. It runs on the main thread while the user's key press or click is being handled, + // because that is when the OS lets an app take the focus. On macOS it makes the app active + // (macOS 14 and later refuse an activation requested later). On Windows it hands the focus + // over: the foreground isn't given back to the app the user was in, and the new window comes + // to the front as it opens. Nil when it isn't needed. + Activate func() + Quit func() + // Main runs fn on the main thread. Called from another thread, fn runs as soon as the main + // thread gets to it. Called on the main thread, fn runs at once, before Main returns (Wails' + // dispatch runs it inline), so the main thread can't use Main to defer fn. MainSync also runs + // fn on the main thread, but waits for it. On the main thread it runs fn inline as well. + Main func(fn func()) + MainSync func(fn func()) + // Mod is the modifier shown in the row shortcuts: "⌘" or "Ctrl+". + Mod string + // ClipboardPeek returns what can be learned about the clipboard without asking the user: its + // text, or only that it holds a link (macOS asks the user before an app reads it). It also + // returns an id that tells one copy from the next. Called off the main thread. Nil means no + // clipboard suggestion. + ClipboardPeek func() (clip engine.Clip, id string) + // ClipboardText reads the clipboard's text after the user asked for it. Called off the main + // thread. + ClipboardText func() string +} + +// Source is the state that the launcher reads and acts on. The app passes a state.State. +type Source interface { + Data() *engine.Data + Services() engine.Services + RefreshIfOlder(ctx context.Context, age time.Duration) + // FollowProgress turns on or off the tracking of running transfers' progress. It is on while + // the launcher is shown. Each change counts as a state change, at most once a second. + FollowProgress(on bool) + // OnChange registers fn to be called, on any goroutine, when the state changes. + OnChange(fn func()) +} + +const ( + blurGrace = 300 * time.Millisecond // a blur this soon after Show comes from the show itself + spinnerAfter = 500 * time.Millisecond + staleAfter = 30 * time.Second // state older than this is reloaded when the launcher shows + doneFor = 4 * time.Second // how long the status corner shows that an action succeeded + failedFor = 12 * time.Second // how long it shows that an action failed + // clipboardWait is how long Show waits for the clipboard before running the query without it. + // Reading the clipboard may wait on the app that owns it (X11, Wayland). + clipboardWait = 50 * time.Millisecond +) + +type Launcher struct { + p Platform + log *slog.Logger + state Source + usage *usageStore + engine *engine.Engine // runs typed queries + drops *engine.Engine // runs while files are dropped, and only offers where they can go + complete *providers.Completion + view view.View + home string // this machine's home folder, which ~ stands for; "" if there is none + + // staysOpen keeps the launcher open when it loses the keyboard (see SetStaysOpen). + staysOpen atomic.Bool + + // on the main thread only + text string + query engine.Query // the query that results belong to + results []engine.Result + cursor // the selection in results, and the first row drawn + fresh bool // results belong to the current text (false between an edit and its first results) + // enter is set when Enter was pressed before the text's first results arrived. The first row + // of those results runs when they arrive. + enter bool + busy bool + started time.Time + panel *panel + shownAt time.Time + at *view.Placement + // status is shown in the status corner. statusSeq tells one status from the next, so a timer + // clears only its own. acting is the one action the corner listens to: the last one run, until + // the launcher closes. running is true when something is running, which enables the + // stop-everything button. + status view.Status + statusSeq uint64 + acting *env + running bool + cancel context.CancelFunc + seq uint64 + // dropped holds the files dropped on the launcher, until Esc or Hide + dropped []engine.Path + // clip is what was known about the clipboard at the last Show, and clipID tells it apart from + // the next copy. clipUsed is the copy whose suggestion was run, so it isn't offered again. + clip engine.Clip + clipID, clipUsed string +} + +// cursor is the selection in a list and the first row drawn. +type cursor struct{ sel, off int } + +// panel is either the ⌘K panel, which lists a result's actions filtered by what is typed in it, or +// a question asked before an action runs, whose rows are the action and Cancel. +type panel struct { + result engine.Result + all []engine.Action // the actions before filtering + actions []engine.Action + cursor + saved string // the query, restored when the panel closes + question string // the question the panel asks; "" for the ⌘K panel +} + +// cancelID is the ID of the Cancel row of a question (see ask). +const cancelID = "cancel" + +func New(p Platform, log *slog.Logger, h Source, history History) *Launcher { + c := providers.NewCompletion() + home, _ := os.UserHomeDir() // with no home folder, ~ isn't a path + l := &Launcher{p: p, log: log, state: h, usage: newUsageStore(history, log), + engine: engine.New(providers.All(c)...), drops: engine.New(providers.Drops(c)...), complete: c, home: home} + l.engine.Panicked, l.drops.Panicked = l.panicked, l.panicked + h.OnChange(func() { p.Main(l.stateChanged) }) + return l +} + +// panicked logs a panic that the launcher recovered from, with its stack. It runs in the +// deferred recover, while the panic's frames are still on the stack. +func (l *Launcher) panicked(where string, v any) { + l.log.Error("the launcher recovered from a panic", "where", where, "panic", fmt.Sprint(v), "stack", string(debug.Stack())) +} + +// goSafe runs fn on its own goroutine. An unrecovered panic there would end the whole app, +// including the core that runs inside it. goSafe logs the panic instead, and only fn's work +// is lost. +func (l *Launcher) goSafe(where string, fn func()) { + go func() { + defer func() { + if v := recover(); v != nil { + l.panicked(where, v) + } + }() + fn() + }() +} + +func (l *Launcher) Attach(v view.View) { l.view = v } + +func (l *Launcher) Events() view.Events { + return view.Events{ + Query: l.onQuery, + Key: l.onKey, + Hover: l.onHover, + Click: l.onClick, + Scroll: l.onScroll, + Moved: func(at view.Placement) { l.at = &at }, + Blur: l.onBlur, + Drop: l.onDrop, + StopAll: l.onStopAll, + Panicked: l.panicked, + } +} + +// Visible reports whether the launcher is shown. Main thread. +func (l *Launcher) Visible() bool { return l.view != nil && l.view.Visible() } + +// Show shows the launcher with its text selected, and runs the query again. Main thread. +func (l *Launcher) Show() { + if l.view == nil { + return + } + l.state.RefreshIfOlder(context.Background(), staleAfter) + l.usage.load() + if l.panel != nil { + // Shown again while a panel was open: restore the query, as when the panel closes. + l.text = l.panel.saved + l.panel = nil + } + l.view.Show(l.at) + l.view.SetQuery(l.text, true) + l.shownAt = time.Now() + l.state.FollowProgress(true) + l.peekClipboardAndRun() +} + +// peekClipboardAndRun runs the query once the clipboard is known, so its suggestion can be +// included. If the clipboard takes longer than clipboardWait, the query runs without it, and +// runs again once the clipboard is known. +func (l *Launcher) peekClipboardAndRun() { + if l.p.ClipboardPeek == nil { + l.run() + return + } + // Until the results arrive, the rows drawn are from the last Show. They are no longer current, + // and results from an older query that are still on their way are ignored. + l.seq++ + l.fresh, l.busy = false, true + type peek struct { + clip engine.Clip + id string + } + got := make(chan peek, 1) + l.goSafe("clipboard peek", func() { + var p peek + // if the peek panics, the clipboard counts as unknown + defer func() { got <- p }() + p.clip, p.id = l.p.ClipboardPeek() + }) + go func() { + set := func(p peek) bool { + changed := p.id != l.clipID || p.clip != l.clip + l.clip, l.clipID = p.clip, p.id + return changed + } + select { + case p := <-got: + l.p.Main(func() { + set(p) + l.run() + }) + case <-time.After(clipboardWait): + l.p.Main(l.run) + p := <-got + l.p.Main(func() { + if set(p) && l.Visible() && l.panel == nil { + l.rerun() + } + }) + } + }() +} + +// Hide hides the launcher and keeps its text. Main thread. +func (l *Launcher) Hide() { + if !l.Visible() { + return + } + if l.cancel != nil { + l.cancel() + } + l.enter = false + l.complete.Reset() + if l.panel != nil { + l.text = l.panel.saved + l.panel = nil + } + if l.dropped != nil { + // The dropped files belong to this Show only. The next Show starts with an empty text. + l.dropped, l.text = nil, "" + } + // Once closed, the status corner stops listening to actions. An action that is still running + // finishes without updating it. + l.acting = nil + l.statusSeq++ + l.status = view.Status{} + l.state.FollowProgress(false) + l.view.Hide() +} + +// Toggle shows the launcher, or hides it. Main thread. +func (l *Launcher) Toggle() { + if l.Visible() { + l.Hide() + } else { + l.Show() + } +} + +func (l *Launcher) onQuery(text string) { + l.text, l.enter = text, false + if l.panel != nil { + l.filterPanel() + return + } + l.run() +} + +// run runs the query for the current text. The old rows stay until the first results arrive, +// usually within a frame or two. The spinner shows only if the results take longer than +// spinnerAfter. +func (l *Launcher) run() { l.answer(false) } + +// rerun runs the same text again because something around it changed, such as a clipboard that +// became known late. Meanwhile the rows drawn still belong to the text, so Enter runs the row the +// user sees. The new results keep the selection on the same result. Only a selection that is +// still on the first row moves to whatever comes first now. If the rows drawn belong to an older +// text, rerun is the same as run. +func (l *Launcher) rerun() { l.answer(l.fresh) } + +// stateChanged runs the query again after the core's state changed (a mount started, a transfer +// ended), keeping the selection on the same result. +func (l *Launcher) stateChanged() { + if !l.Visible() { + return + } + _, l.running = providers.StopEverything(l.state.Data()) + if l.panel != nil { + l.render() + return + } + l.rerun() +} + +// LanguageChanged draws the launcher again in the app's language. The providers translate the +// rows when they make them, and render translates the launcher's own text, so the query runs +// again. A hidden launcher runs it when it shows. Main thread. +func (l *Launcher) LanguageChanged() { + if !l.Visible() { + return + } + if l.panel != nil { + // A question or a row's actions were made in the old language, so they close. + l.closePanel() + } + l.rerun() +} + +func (l *Launcher) answer(keep bool) { + if l.cancel != nil { + l.cancel() + } + ctx, cancel := context.WithCancel(context.Background()) + l.cancel = cancel + l.seq++ + id := l.seq + d := l.state.Data() // the launcher's own copy, so it can set Home on it + d.Home = l.home + q := engine.Parse(l.text, d.Remotes, d.Home) + q.Dropped = l.dropped + e := l.engine + if len(l.dropped) > 0 { + e = l.drops + } + if l.clipID == "" || l.clipID != l.clipUsed { + q.Clipboard = l.clip + } + usage := l.usage.snapshot() + l.started, l.busy = time.Now(), true + if !keep { + l.fresh = false + } + l.goSafe("query", func() { e.Run(ctx, q, d, usage, l.answered(id, q, d, keep)) }) + time.AfterFunc(spinnerAfter, func() { + l.p.Main(func() { + if id == l.seq && l.busy && l.panel == nil { + l.render() + } + }) + }) +} + +// answered returns the engine's emit function for query run id (of q, over d). It sends each +// snapshot to the main thread, where only the newest run's results are used. +func (l *Launcher) answered(id uint64, q engine.Query, d *engine.Data, keep bool) func([]engine.Result, bool) { + answered := false + return func(rs []engine.Result, final bool) { + l.p.Main(func() { + if id != l.seq { + return // a newer query has started + } + first := !answered + answered = true + var kept string + if r, ok := l.selected(); ok && keep && first && l.sel > 0 { + kept = r.ID + } + l.query, l.results, l.fresh, l.busy = q, rs, true, !final + _, l.running = providers.StopEverything(d) + switch { + case kept != "": + l.sel = max(slices.IndexFunc(rs, func(r engine.Result) bool { return r.ID == kept }), 0) + case first: + l.cursor = cursor{} + } + l.clamp() + if l.panel == nil { + l.render() + } + if first && l.enter { + // An Enter typed ahead runs here, in a block that the main thread runs after the + // key press was handled. On macOS the window that the row opens may then come up + // without the focus, because macOS 14 and later may refuse Activate outside the + // user's event. This is a known limit: the key press can't wait for the results. + l.enter = false + l.activate() + } + }) + } +} + +// cur returns the list that the keys and the mouse work on, and its length. That is the panel's +// actions while the panel is open, and the results otherwise. +func (l *Launcher) cur() (*cursor, int) { + if l.panel != nil { + return &l.panel.cursor, len(l.panel.actions) + } + return &l.cursor, len(l.results) +} + +// spans returns the heights of cur's rows. A result that starts a group is taller, because the +// group's label is drawn above it. +func (l *Launcher) spans() []float64 { + _, n := l.cur() + out := make([]float64, n) + for i := range out { + out[i] = view.RowH + if l.panel == nil && startsGroup(l.results, i) { + out[i] += view.GroupH + } + } + return out +} + +// startsGroup reports whether rs[i] is the first result of its group, which gets the group's label. +func startsGroup(rs []engine.Result, i int) bool { + return rs[i].Group != "" && (i == 0 || rs[i-1].Group != rs[i].Group) +} + +func (l *Launcher) clamp() { + c, n := l.cur() + if c.sel >= n { + c.sel = max(n-1, 0) + } +} + +func (l *Launcher) onKey(k view.KeyEvent) bool { + switch k.Key { + case view.KeyDown, view.KeyUp: + l.move(k.Key == view.KeyDown) + case view.KeyEnter: + if l.panel == nil && !l.fresh { + // Typed and entered quickly: the rows drawn still belong to an older text. + l.enter = true + break + } + l.activate() + case view.KeyEsc: + l.enter = false + switch { + case l.panel != nil: + l.closePanel() + case l.dropped != nil: + // The first Esc clears the dropped files. The next one hides the launcher. + l.dropped, l.text = nil, "" + l.view.SetQuery("", false) + l.run() + default: + l.Hide() + } + case view.KeyClose: + // Hide also closes the panel and clears the dropped files. + l.enter = false + l.Hide() + case view.KeyTab: + l.completeSelected() + case view.KeyActions: + if l.panel != nil { + l.closePanel() + } else { + l.openPanel() + } + case view.KeyRow: + if k.Char == '.' { // ⌘., the stop-everything button + l.onStopAll() + break + } + // If there is no such row, the key goes to the text box and the menus. Keys such as ⌘Z + // and ⌘Q never select rows (see view.RowLetters). + c, n := l.cur() + i := rowIndex(k.Char) + if i < 0 || i >= n { + return false + } + c.sel = i + l.activate() + default: + return false + } + return true +} + +func (l *Launcher) move(down bool) { + c, n := l.cur() + if n == 0 { + return + } + if down { + c.sel = (c.sel + 1) % n + } else { + c.sel = (c.sel + n - 1) % n + } + l.render() +} + +// onHover selects the row under the pointer, except a partly drawn last row. Selecting that row +// would scroll the list under a pointer that hasn't moved. +func (l *Launcher) onHover(row int) { + c, _ := l.cur() + if i := row + c.off; i < wholeEnd(l.spans(), c.off) && i != c.sel { + c.sel = i + l.render() + } +} + +func (l *Launcher) onClick(row int) { + c, n := l.cur() + if i := row + c.off; i < n { + c.sel = i + l.activate() + } +} + +// onScroll scrolls the list by n rows and keeps the selection among the rows that are fully +// drawn. A pointer that hasn't moved doesn't select the row that scrolls under it. +func (l *Launcher) onScroll(n int) { + c, _ := l.cur() + spans := l.spans() + top := max(min(c.off+n, lastPage(spans)), 0) + if top == c.off { + return + } + c.off = top + c.sel = min(max(c.sel, top), wholeEnd(spans, top)-1) + l.render() +} + +// onStopAll handles the stop-everything button and ⌘. by asking for confirmation in the launcher. +func (l *Launcher) onStopAll() { + r, ok := providers.StopEverything(l.state.Data()) + if !ok { + l.setStatus(view.Status{Kind: view.StatusDone, Text: i18n.T("Nothing is running.")}) + return + } + query := l.text + if l.panel != nil { + query = l.panel.saved + } + a, _ := r.Default() + l.ask(r, a, query) +} + +// onDrop handles files dropped on the launcher. The launcher then offers places where they can +// go, and the text chooses among them. +func (l *Launcher) onDrop(paths []string) { + if len(paths) == 0 { + return + } + l.panel = nil + l.dropped = make([]engine.Path, len(paths)) + for i, p := range paths { + l.dropped[i] = engine.Path{Text: p, Local: true} + } + l.text = "" + l.view.SetQuery("", false) + l.run() +} + +func (l *Launcher) onBlur() { + if l.staysOpen.Load() || !l.Visible() || time.Since(l.shownAt) < blurGrace { + return + } + l.Hide() +} + +// SetStaysOpen sets whether the launcher stays open when the user clicks outside it. Any +// goroutine may call it. +func (l *Launcher) SetStaysOpen(stays bool) { l.staysOpen.Store(stays) } + +// rowIndex returns the row that ⌘ with c runs: 1–9 first, then the letters. It returns -1 for +// none. +func rowIndex(c rune) int { + c = unicode.ToLower(c) + if c >= '1' && c <= '9' { + return int(c - '1') + } + if i := strings.IndexRune(view.RowLetters, c); i >= 0 { + return 9 + i + } + return -1 +} + +// rowHint returns the shortcut text shown on row i. +func (l *Launcher) rowHint(i int) string { + switch { + case i < 9: + return l.p.Mod + strconv.Itoa(i+1) + case i < 9+len(view.RowLetters): + return l.p.Mod + strings.ToUpper(string(view.RowLetters[i-9])) + } + return "" +} + +func (l *Launcher) selected() (engine.Result, bool) { + if l.sel < 0 || l.sel >= len(l.results) { + return engine.Result{}, false + } + return l.results[l.sel], true +} + +// completeSelected replaces the path (or word) being typed with the selected result's +// completion, such as a folder entry or a remote's root. The replacement starts where the query +// says the word starts. It does nothing until the text's own results arrive, because until then +// the selection and that start position belong to an older text. +// +// A path with spaces is only one word when quoted. So a completion that contains a space is +// quoted, and so is one that replaces a word starting with a quote. The quote character is one +// that the path doesn't contain, since that would end the path early (quotes have no escapes). +// After a folder the quote stays open, so the user can keep typing (or press Tab) inside it. +// After a file the quote is closed and followed by a space for the next word. +func (l *Launcher) completeSelected() { + r, ok := l.selected() + if l.panel != nil || !l.fresh || !ok || r.Complete == "" { + return + } + from := min(l.query.TypingFrom, len(l.text)) + base, word := l.text[:from], l.text[from:] + done := r.Complete + const quotes = "\"'`" + quote := "" + switch { + case word != "" && strings.ContainsRune(quotes, rune(word[0])): + quote = word[:1] + case strings.ContainsAny(done, " \t"): + quote = `"` + } + if quote != "" && strings.Contains(done, quote) { + for _, q := range quotes { + if !strings.ContainsRune(done, q) { + quote = string(q) + break + } + } + } + if quote != "" { + done = quote + done + if !folder(r.Complete) { + done += quote + " " + } + } + l.text = base + done + l.view.SetQuery(l.text, false) + l.run() +} + +// folder reports whether a completion is a folder (or a remote's root) that the path continues +// into. +func folder(p string) bool { + return strings.HasSuffix(p, "/") || strings.HasSuffix(p, "\\") || strings.HasSuffix(p, ":") +} + +func (l *Launcher) openPanel() { + l.enter = false + r, ok := l.selected() + if !ok || len(r.Actions) == 0 { + return + } + l.panel = &panel{result: r, all: r.Actions, actions: r.Actions, saved: l.text} + l.text = "" + l.view.SetQuery("", false) + l.render() +} + +// ask shows a's question in the launcher, as a panel with a and Cancel. query is restored when +// the panel closes. +func (l *Launcher) ask(r engine.Result, a engine.Action, query string) { + l.enter = false + choices := []engine.Action{a, {ID: cancelID, Name: i18n.T("Cancel"), Icon: icons.Back}} + l.panel = &panel{result: r, all: choices, actions: choices, saved: query, question: a.Confirm} + l.text = "" + l.view.SetQuery("", false) + l.render() +} + +func (l *Launcher) closePanel() { + if l.panel == nil { + return + } + l.text = l.panel.saved + l.panel = nil + l.view.SetQuery(l.text, false) + l.render() +} + +func (l *Launcher) filterPanel() { + p := l.panel + p.actions = nil + for _, a := range p.all { + if _, ok := match.Match(l.text, a.Name); ok { + p.actions = append(p.actions, a) + } + } + p.sel = 0 + l.render() +} + +// activate runs the selected result's default action, or the panel's selected action. In a +// question, the action's row runs it without asking again, and Cancel closes the question. +func (l *Launcher) activate() { + if p := l.panel; p != nil { + if p.sel >= len(p.actions) { + return + } + switch a := p.actions[p.sel]; { + case p.question == "": + l.act(p.result, a, p.saved) + case a.ID == cancelID: + l.closePanel() + default: + l.perform(p.result, a, p.saved) + } + return + } + r, ok := l.selected() + if !ok { + return + } + if a, ok := r.Default(); ok && a.Run != nil { + l.act(r, a, l.text) + } +} + +// act runs a for r, asking for confirmation first if a has a question. +func (l *Launcher) act(r engine.Result, a engine.Action, query string) { + if a.Confirm != "" { + l.ask(r, a, query) + return + } + l.perform(r, a, query) +} + +// perform runs a for r. The launcher hides first, so that a window the action opens gets the +// focus. A drill-in action (KeepOpen) leaves the launcher up. So does an action that runs in +// place (Stay), which goes back to the results. The status corner then shows only this action's +// progress, result or failure, until another action runs or the launcher closes. +func (l *Launcher) perform(r engine.Result, a engine.Action, query string) { + e := &env{l: l, action: a} + switch { + case a.Stay: + l.closePanel() + l.acting = e + e.seq = l.setStatus(view.Status{Kind: view.StatusLoading, Text: a.Name + "…"}) + case !a.KeepOpen: + if a.Opens && l.p.Activate != nil { + l.p.Activate() + } + l.Hide() + } + l.goSafe("action "+a.ID, func() { + if a.Run == nil { + return + } + err := l.runAction(a, e) + e.finish(err) + if err != nil { + l.log.Error("a launcher action failed", "result", r.Title, "action", a.Name, "error", err) + return + } + if r.Key != "" { + l.usage.record(r.Key, query) + } + }) + if strings.HasPrefix(r.Key, "clip:") { + l.clipUsed = l.clipID // this copy's suggestion has been used + } +} + +// errBroke is the error returned for an action that panicked. The panic itself is reported. +var errBroke = errs.New("something went wrong") + +// runAction runs a. If a panics, the panic is reported and runAction returns errBroke. +func (l *Launcher) runAction(a engine.Action, e *env) (err error) { + defer func() { + if v := recover(); v != nil { + l.panicked("action "+a.ID, v) + err = errBroke + } + }() + return a.Run(context.Background(), e) +} + +// setStatus shows s in the status corner and returns a sequence number that tells it apart from +// the next status. A success or failure is cleared after a while. A progress message stays until +// the action reports something new. +func (l *Launcher) setStatus(s view.Status) uint64 { + l.statusSeq++ + seq := l.statusSeq + l.status = s + var after time.Duration + switch s.Kind { + case view.StatusDone: + after = doneFor + case view.StatusError: + after = failedFor + } + if after > 0 { + time.AfterFunc(after, func() { + l.p.Main(func() { + if l.statusSeq == seq { + l.clearStatus() + } + }) + }) + } + l.render() + return seq +} + +func (l *Launcher) clearStatus() { + l.statusSeq++ + l.status = view.Status{} + l.render() +} + +// render draws the results (or the panel) with the selection in view. +func (l *Launcher) render() { + if l.view == nil { + return + } + // i18n: The placeholder of the launcher's search box. + s := view.Snapshot{Placeholder: i18n.T("Search commands, remotes, or paste a URL"), Status: l.status, Running: l.running} + if len(l.dropped) > 0 { + // i18n: The placeholder of the launcher's search box while files are dropped on it. + s.Placeholder = i18n.T("Where to? Type a remote or a folder") + s.Header = droppedHeader(l.dropped) + } + spans := l.spans() + if p := l.panel; p != nil { + s.Placeholder = i18n.T("Search actions…") + // i18n: The header of the list of a row's actions. %s is the row's title. + s.Header = i18n.T("Actions for %s", p.result.Title) + // i18n: Hints at the launcher's foot, after their keys: Enter runs the action, Esc goes back. + s.Footer = []view.Hint{{Keys: "⏎", Label: i18n.T("Run")}, {Keys: "esc", Label: i18n.T("Back")}} + if p.question != "" { + // The question replaces the placeholder in the query box, in its large type, since + // typing there answers it. + s.Placeholder, s.Header = p.question, "" + // i18n: Hints at the launcher's foot, after their keys, while it asks a question: Enter chooses the answer, Esc cancels. + s.Footer = []view.Hint{{Keys: "⏎", Label: i18n.T("Choose")}, {Keys: "esc", Label: i18n.T("Cancel")}} + } + p.off = inView(p.sel, p.off, spans) + end := drawnEnd(spans, p.off) + for i := p.off; i < end; i++ { + a := p.actions[i] + s.Rows = append(s.Rows, view.Row{Icon: a.Icon, Title: a.Name, Hint: l.rowHint(i), Danger: a.Confirm != ""}) + } + s.Selected = p.sel - p.off + s.More = p.off > 0 || end < len(p.actions) + l.view.Render(s) + return + } + l.off = inView(l.sel, l.off, spans) + end := drawnEnd(spans, l.off) + for i := l.off; i < end; i++ { + r := l.results[i] + row := view.Row{Icon: r.Icon, Title: r.Title, Bold: r.Match(), Subtitle: r.Subtitle, Tail: r.Tail, Hint: l.rowHint(i)} + if startsGroup(l.results, i) { + row.Group = engine.GroupTitle(r.Group) + } + if a, ok := r.Default(); ok && a.Confirm != "" { + row.Danger = true + } + s.Rows = append(s.Rows, row) + } + s.Selected = l.sel - l.off + s.More = l.off > 0 || end < len(l.results) + if len(s.Rows) == 0 { + s.Selected = -1 + } + if r, ok := l.selected(); ok { + if a, ok := r.Default(); ok && a.Run != nil { + s.Footer = append(s.Footer, view.Hint{Keys: "⏎", Label: a.Name}) + } + if len(r.Actions) > 1 { + // i18n: A hint at the launcher's foot, after its key: it lists the row's actions. + s.Footer = append(s.Footer, view.Hint{Keys: l.p.Mod + "K", Label: i18n.T("Actions")}) + } + if r.Complete != "" { + // i18n: A hint at the launcher's foot, after the Tab key: it completes the typed path. + s.Footer = append(s.Footer, view.Hint{Keys: "⇥", Label: i18n.T("Complete")}) + } + } + if s.Status.Kind == view.StatusNone && l.busy && time.Since(l.started) >= spinnerAfter { + s.Status = view.Status{Kind: view.StatusLoading, Text: i18n.T("Loading…")} + } + l.view.Render(s) +} + +// inView returns the first row to draw, starting from off, for rows with the heights in spans. It +// moves off as little as possible so that sel is fully drawn and no empty space is left below +// the last row. +func inView(sel, off int, spans []float64) int { + off = min(off, lastPage(spans), sel) + for off < sel && wholeEnd(spans, off) <= sel { + off++ + } + return max(off, 0) +} + +// drawnEnd returns the end of the rows drawn from off. These are the rows that start within the +// list's height. The last one may be cut off at the bottom. +func drawnEnd(spans []float64, off int) int { + end, h := off, 0.0 + for end < len(spans) && h < view.MaxListH { + h += spans[end] + end++ + } + return end +} + +// wholeEnd returns the end of the rows that are fully drawn from off. +func wholeEnd(spans []float64, off int) int { + end, h := off, 0.0 + for end < len(spans) && h+spans[end] <= view.MaxListH { + h += spans[end] + end++ + } + return end +} + +// lastPage returns the first row drawn when the list is scrolled to the end. It is the earliest +// row from which all the remaining rows fit. +func lastPage(spans []float64) int { + i, h := len(spans), 0.0 + for i > 0 && h+spans[i-1] <= view.MaxListH { + h += spans[i-1] + i-- + } + return i +} + +// droppedHeader returns the line shown above the rows while files are dropped. It names the files. +func droppedHeader(ps []engine.Path) string { + var names []string + for i, p := range ps { + if i == 3 { + names = append(names, "…") + break + } + names = append(names, filepath.Base(p.Text)) + } + if len(ps) == 1 { + // i18n: The line above the launcher's rows while a file is dropped on it. %s is its name. + return i18n.T("Dropped: %s", names[0]) + } + // i18n: The line above the launcher's rows while files are dropped on it. The last value is their names. + return i18n.N("%d item dropped: %s", "%d items dropped: %s", len(ps), len(ps), strings.Join(names, ", ")) +} diff --git a/app/launcher/launcher_test.go b/app/launcher/launcher_test.go new file mode 100644 index 00000000..52ede453 --- /dev/null +++ b/app/launcher/launcher_test.go @@ -0,0 +1,930 @@ +package launcher + +import ( + "context" + "errors" + "io" + "log/slog" + "path/filepath" + "slices" + "sync/atomic" + "testing" + "time" + + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/app/launcher/view/viewtest" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/mounts" +) + +// The search box's placeholders, as the launcher shows them in English. +const ( + placeholder = "Search commands, remotes, or paste a URL" + dropPlaceholder = "Where to? Type a remote or a folder" +) + +// source is a fake core with two remotes, plus a mount when mounted is set. list lists folders. +// everything, when set, is its Stop Everything. +type source struct { + mounted bool + list func(ctx context.Context, dir string, page func([]engine.Entry)) error + everything *stopAll +} + +func (s source) Data() *engine.Data { + d := &engine.Data{ + Remotes: []engine.Remote{ + {Name: "gdrive", Type: "drive"}, + {Name: "s3", Type: "s3"}, + }, + List: s.list, + } + if s.mounted { + d.Mounts = []mounts.MountRow{{ID: "m1", Source: "gdrive:", MountPoint: "/Volumes/gdrive", State: "running"}} + } + return d +} +func (s source) Services() engine.Services { + if s.everything == nil { + return engine.Services{} + } + return engine.Services{Everything: s.everything} +} +func (source) RefreshIfOlder(context.Context, time.Duration) {} +func (source) FollowProgress(bool) {} +func (source) OnChange(func()) {} + +// stopAll is a fake Stop Everything, which counts its calls and stops a mount. +type stopAll struct{ calls atomic.Int32 } + +func (s *stopAll) StopAll(context.Context) (core.StopSummary, error) { + s.calls.Add(1) + return core.StopSummary{Running: core.Running{Mounts: 1}}, nil +} + +// harness runs a launcher on its own fake main thread, with a fake view. +type harness struct { + t *testing.T + l *Launcher + v *viewtest.Fake + calls chan string + main chan func() + done chan struct{} + // activated counts the calls to Platform.Activate + activated atomic.Int32 +} + +func newHarness(t *testing.T) *harness { + h := &harness{t: t, v: &viewtest.Fake{}, calls: make(chan string, 32), main: make(chan func()), done: make(chan struct{})} + go func() { + for { + select { + case fn := <-h.main: + fn() + case <-h.done: + return + } + } + }() + t.Cleanup(func() { close(h.done) }) + record := func(s string) { + select { + case h.calls <- s: + default: + } + } + p := Platform{ + OpenWindow: func(name, url string) { record("window " + name + " " + url) }, + OpenFull: func(name, url string) { record("full " + name + " " + url) }, + Clipboard: func(text string) { record("clipboard " + text) }, + Reveal: func(path string) { record("reveal " + path) }, + OpenURL: func(url string) { record("url " + url) }, + Notify: func(title, body string) { record("notify " + title + ": " + body) }, + Activate: func() { h.activated.Add(1) }, + Quit: func() { record("quit") }, + Main: func(fn func()) { + go func() { + select { + case h.main <- fn: + case <-h.done: + } + }() + }, + MainSync: func(fn func()) { done := make(chan struct{}); h.main <- func() { fn(); close(done) }; <-done }, + Mod: "⌘", + } + h.l = New(p, slog.New(slog.NewTextHandler(io.Discard, nil)), source{}, nil) + h.v.Events = h.l.Events() + h.l.Attach(h.v) + return h +} + +// do runs fn on the launcher's main thread. +func (h *harness) do(fn func()) { + done := make(chan struct{}) + h.main <- func() { fn(); close(done) } + <-done +} + +// settle waits until the rows drawn are for the current text, and returns their titles. +func (h *harness) settle() []string { + h.t.Helper() + deadline := time.Now().Add(2 * time.Second) + for { + var ok bool + var titles []string + h.do(func() { ok = h.l.fresh && !h.l.busy; titles = h.v.Titles() }) + if ok { + return titles + } + if time.Now().After(deadline) { + h.t.Fatalf("no answer for %q", h.l.text) + } + time.Sleep(5 * time.Millisecond) + } +} + +func (h *harness) typeText(s string) []string { + h.do(func() { h.v.Type(s) }) + return h.settle() +} + +func (h *harness) press(k view.Key, c rune) bool { + var took bool + h.do(func() { took = h.v.Press(view.KeyEvent{Key: k, Char: c}) }) + return took +} + +func (h *harness) call() string { + h.t.Helper() + select { + case c := <-h.calls: + return c + case <-time.After(2 * time.Second): + h.t.Fatal("no call") + return "" + } +} + +func TestShowTypeAndRun(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + rows := h.settle() + if len(rows) == 0 || rows[0] != "Run" { + t.Fatalf("shown: %q", rows) + } + if f := h.v.Last.Footer; len(f) == 0 || f[0].Label != "Open Wizard" { + t.Errorf("footer %v", f) + } + rows = h.typeText("mo") + if rows[0] != "Move" || rows[1] != "Mount" { + t.Fatalf("mo: %q", rows) + } + h.press(view.KeyDown, 0) + if h.v.Last.Selected != 1 { + t.Errorf("down: selected %d", h.v.Last.Selected) + } + // a new query starts at the top + h.typeText("mou") + if h.v.Last.Selected != 0 { + t.Errorf("new query: selected %d", h.v.Last.Selected) + } + h.typeText("copy") + h.press(view.KeyEnter, 0) + if c := h.call(); c != "window Copy /copy" { + t.Errorf("enter: %q", c) + } + if h.v.Shown { + t.Error("the launcher stays up after opening a window") + } +} + +func TestRowShortcuts(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + if h.v.Last.Rows[1].Hint != "⌘2" { + t.Errorf("hint %q", h.v.Last.Rows[1].Hint) + } + h.press(view.KeyRow, '1') + if c := h.call(); c != "window Wizard /wizard" { + t.Errorf("⌘1: %q", c) + } + if rowIndex('k') != -1 || rowIndex('a') != -1 || rowIndex('b') != 9 { + t.Error("row letters") + } + // the clipboard, actions, app and text box keys never run a row + for _, c := range "acvxkqwhmyz" { + if rowIndex(c) != -1 { + t.Errorf("⌘%c runs a row", c) + } + } +} + +func TestActionPanel(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.typeText("gdr") + if h.v.Last.Rows[0].Title != "gdrive" { + t.Fatalf("gdr: %q", h.v.Titles()) + } + h.press(view.KeyActions, 0) + if h.v.Last.Header != "Actions for gdrive" || h.v.Query != "" { + t.Fatalf("panel: header %q, query %q", h.v.Last.Header, h.v.Query) + } + if !slices.Contains(h.v.Titles(), "Copy From") { + t.Errorf("actions %q", h.v.Titles()) + } + h.do(func() { h.v.Type("edit") }) + if got := h.v.Titles(); len(got) != 1 || got[0] != "Edit Remote" { + t.Errorf("filtered: %q", got) + } + h.press(view.KeyEsc, 0) + if h.v.Last.Header != "" || h.v.Query != "gdr" || !h.v.Shown { + t.Errorf("esc closes the panel: header %q, query %q, shown %v", h.v.Last.Header, h.v.Query, h.v.Shown) + } + h.press(view.KeyActions, 0) + h.do(func() { h.v.Type("edit") }) + h.press(view.KeyEnter, 0) + if c := h.call(); c != "window Remotes /remotes?action=edit&remote=gdrive" { + t.Errorf("panel action: %q", c) + } +} + +// TestScroll: the wheel scrolls the rows and keeps the selection among the rows drawn. Long lists +// in the panel scroll too. +func TestScroll(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + var all []string + h.do(func() { + for _, r := range h.l.results { + all = append(all, r.Title) + } + }) + if len(all) <= view.MaxRows+3 { + t.Fatalf("too few results to scroll: %q", all) + } + drawn := func() (string, int) { + var first string + var sel int + h.do(func() { first, sel = h.v.Last.Rows[0].Title, h.v.Last.Selected }) + return first, sel + } + scroll := func(n int) { h.do(func() { h.v.Events.Scroll(n) }) } + + scroll(3) + if first, sel := drawn(); first != all[3] || sel != 0 { + t.Errorf("down 3: first %q, selected row %d", first, sel) + } + scroll(-1) // the selection, still on all[3], stays where it is + if first, sel := drawn(); first != all[2] || sel != 1 { + t.Errorf("up 1: first %q, selected row %d", first, sel) + } + scroll(100) + var last int + h.do(func() { last = lastPage(h.l.spans()) }) + if first, _ := drawn(); first != all[last] { + t.Errorf("to the end: first %q, want %q", first, all[last]) + } + h.do(func() { h.v.Events.Hover(1) }) + var picked string + h.do(func() { picked = h.l.results[h.l.sel].Title }) + if _, sel := drawn(); sel != 1 || picked != all[last+1] { + t.Errorf("hover after a scroll: selected row %d, %q", sel, picked) + } + + // the panel: a remote has more actions than fit + h.do(h.l.Show) + h.typeText("gdr") + h.press(view.KeyActions, 0) + var actions []string + h.do(func() { + for _, a := range h.l.panel.actions { + actions = append(actions, a.Name) + } + }) + if len(actions) <= view.MaxRows { + t.Fatalf("panel: %q", actions) + } + scroll(100) + if first, sel := drawn(); first != actions[len(actions)-view.MaxRows] || sel != 0 { + t.Errorf("panel to the end: first %q, selected row %d", first, sel) + } + h.do(func() { h.v.Events.Click(view.MaxRows - 1) }) + if c := h.call(); c != "clipboard gdrive:" { + t.Errorf("the panel's last action clicked: %q", c) + } +} + +func TestTabCompletesARemote(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.typeText("copy gdr") + var at int + h.do(func() { + for i, r := range h.l.results { + if r.Title == "gdrive:" { + at = i + } + } + h.l.sel = at + }) + h.press(view.KeyTab, 0) + if h.v.Query != "copy gdrive:" { + t.Errorf("tab: %q", h.v.Query) + } +} + +func TestBlur(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + h.do(func() { h.v.Events.Blur() }) + if !h.v.Shown { + t.Fatal("a blur right after showing is the show's own") + } + h.do(func() { h.l.shownAt = time.Now().Add(-time.Second) }) + h.do(func() { h.v.Events.Blur() }) + if h.v.Shown { + t.Error("a later blur hides") + } + + // With the setting on, a blur leaves the launcher open, and Hide still closes it. + h.l.SetStaysOpen(true) + h.do(h.l.Show) + h.settle() + h.do(func() { h.l.shownAt = time.Now().Add(-time.Second) }) + h.do(func() { h.v.Events.Blur() }) + if !h.v.Shown { + t.Fatal("a blur closed a launcher that is set to stay open") + } + h.do(h.l.Hide) + if h.v.Shown { + t.Error("Hide left the launcher open") + } +} + +// selectRow selects the result titled title, and reports whether there is one. +func (h *harness) selectRow(title string) bool { + found := false + h.do(func() { + for i, r := range h.l.results { + if r.Title == title { + h.l.sel, found = i, true + } + } + }) + return found +} + +// noCall fails if any platform call is made within a short time. +func (h *harness) noCall(what string) { + h.t.Helper() + select { + case c := <-h.calls: + h.t.Errorf("%s: %q", what, c) + case <-time.After(100 * time.Millisecond): + } +} + +// TestStopAsksInTheLauncher: an action that stops something asks for confirmation in the +// launcher first. Cancel (or Esc) goes back to the results. Confirming runs the action with the +// launcher still up, and the outcome appears in the status corner. +func TestStopAsksInTheLauncher(t *testing.T) { + h := newHarness(t) + everything := &stopAll{} + h.do(func() { h.l.state = source{mounted: true, everything: everything} }) + h.do(h.l.Show) + h.typeText("mount") + if !h.selectRow("gdrive: → /Volumes/gdrive") { + t.Fatalf("no mount row: %q", h.v.Titles()) + } + h.press(view.KeyActions, 0) + h.do(func() { h.v.Type("unmount") }) + h.press(view.KeyEnter, 0) + if h.v.Last.Placeholder != "Unmount /Volumes/gdrive?" || !slices.Equal(h.v.Titles(), []string{"Unmount", "Cancel"}) || !h.v.Last.Rows[0].Danger { + t.Fatalf("question: %q, %q", h.v.Last.Placeholder, h.v.Titles()) + } + h.noCall("asked: the stop ran") + h.press(view.KeyEsc, 0) + if !h.v.Shown || h.v.Last.Placeholder != placeholder || h.v.Query != "mount" { + t.Fatalf("esc: shown %v, placeholder %q, query %q", h.v.Shown, h.v.Last.Placeholder, h.v.Query) + } + + // the stop row asks too, and Enter confirms and runs it with the launcher up + h.settle() + if !h.selectRow("Unmount /Volumes/gdrive") { + t.Fatalf("no Unmount row: %q", h.v.Titles()) + } + h.press(view.KeyEnter, 0) + if h.v.Last.Placeholder != "Unmount /Volumes/gdrive?" { + t.Fatalf("question: %q", h.v.Last.Placeholder) + } + h.press(view.KeyEnter, 0) + // read on the main thread, because the stop fails at once and draws its failure there + var shown bool + var shownPlaceholder, query string + h.do(func() { shown, shownPlaceholder, query = h.v.Shown, h.v.Last.Placeholder, h.v.Query }) + if !shown || shownPlaceholder != placeholder || query != "mount" { + t.Fatalf("answered: shown %v, placeholder %q, query %q", shown, shownPlaceholder, query) + } + // there is no core here, so the stop fails and shows the error in red + deadline := time.Now().Add(2 * time.Second) + for { + var st view.Status + h.do(func() { st = h.v.Last.Status }) + if st.Kind == view.StatusError { + if st.Text != "Unmount failed: the core is not ready" { + t.Errorf("status %q", st.Text) + } + break + } + if time.Now().After(deadline) { + t.Fatalf("no failure in the corner: %+v", st) + } + time.Sleep(5 * time.Millisecond) + } + h.noCall("a failure with the launcher up: a dialog") +} + +// TestOpeningAWindowActivates: an action that opens a window makes the app active during the key +// press. An action that doesn't (such as a copy) leaves the focus in the user's previous app. +func TestOpeningAWindowActivates(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.typeText("copy") + h.press(view.KeyEnter, 0) + if c := h.call(); c != "window Copy /copy" || h.activated.Load() != 1 { + t.Fatalf("Open Copy: %q, activated %d", c, h.activated.Load()) + } + h.do(h.l.Show) + h.typeText("gdr") + h.press(view.KeyActions, 0) + h.do(func() { h.v.Type("copy name") }) + h.press(view.KeyEnter, 0) + if c := h.call(); c != "clipboard gdrive:" || h.activated.Load() != 1 { + t.Errorf("Copy Name: %q, activated %d", c, h.activated.Load()) + } +} + +// TestTheCornerListensToOneAction: the status corner shows only the last action run. An earlier +// action, or one still running when the launcher closes, ends without a status or notification. +func TestTheCornerListensToOneAction(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + stay := func(name string, release chan struct{}) (engine.Result, engine.Action) { + a := engine.Action{ID: name, Name: name, Stay: true, Run: func(_ context.Context, env engine.Env) error { + env.Status(engine.StatusWorking, name+" working") + <-release + env.Status(engine.StatusDone, name+" done") + return errors.New(name + " broke") + }} + return engine.Result{ID: name, Title: name, Actions: []engine.Action{a}}, a + } + status := func() view.Status { + var st view.Status + h.do(func() { st = h.v.Last.Status }) + return st + } + waitFor := func(text string) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for status().Text != text { + if time.Now().After(deadline) { + t.Fatalf("status %q, want %q", status().Text, text) + } + time.Sleep(5 * time.Millisecond) + } + } + first, second := make(chan struct{}), make(chan struct{}) + h.do(func() { r, a := stay("first", first); h.l.perform(r, a, "") }) + waitFor("first working") + h.do(func() { r, a := stay("second", second); h.l.perform(r, a, "") }) + waitFor("second working") + close(first) + time.Sleep(50 * time.Millisecond) + if st := status(); st.Text != "second working" { + t.Fatalf("the first action, run before, was heard: %+v", st) + } + close(second) + waitFor("second failed: second broke") + if status().Kind != view.StatusError { + t.Errorf("a failure: %+v", status()) + } + + third := make(chan struct{}) + h.do(func() { r, a := stay("third", third); h.l.perform(r, a, "") }) + waitFor("third working") + h.do(h.l.Hide) + close(third) + h.noCall("an action ending with the launcher closed") + h.do(h.l.Show) + h.settle() + if st := status(); st.Kind != view.StatusNone { + t.Errorf("shown again: %+v", st) + } +} + +// TestStopEverything: the stop button is enabled while something runs. It (and ⌘.) asks for +// confirmation, saying how much it stops, and Cancel closes the question. Confirming makes one +// call to the core's StopAll, and the status corner says what stopped. +func TestStopEverything(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + if h.v.Last.Running { + t.Fatal("nothing runs: the stop button is armed") + } + h.do(func() { h.v.Events.StopAll() }) + if h.v.Last.Status.Text != "Nothing is running." { + t.Errorf("stop with nothing running: %+v", h.v.Last.Status) + } + everything := &stopAll{} + h.do(func() { h.l.state = source{mounted: true, everything: everything} }) + h.typeText("co") + if !h.v.Last.Running { + t.Fatal("a mount runs: the stop button isn't armed") + } + h.do(func() { h.v.Events.StopAll() }) + if h.v.Last.Placeholder != "Stop a mount?" || !slices.Equal(h.v.Titles(), []string{"Stop Everything", "Cancel"}) { + t.Fatalf("question: %q, %q", h.v.Last.Placeholder, h.v.Titles()) + } + h.press(view.KeyDown, 0) + h.press(view.KeyEnter, 0) + if h.v.Last.Placeholder != placeholder || h.v.Query != "co" { + t.Fatalf("cancelled: placeholder %q, query %q", h.v.Last.Placeholder, h.v.Query) + } + if !h.press(view.KeyRow, '.') || h.v.Last.Placeholder != "Stop a mount?" { + t.Fatalf("⌘.: placeholder %q", h.v.Last.Placeholder) + } + h.noCall("asked: anything ran") + if everything.calls.Load() != 0 { + t.Fatal("asked: StopAll ran") + } + h.press(view.KeyEnter, 0) + deadline := time.Now().Add(2 * time.Second) + for { + var st view.Status + h.do(func() { st = h.v.Last.Status }) + if st.Text == "Stopped a mount." { + break + } + if time.Now().After(deadline) { + t.Fatalf("status %+v after confirming", st) + } + time.Sleep(5 * time.Millisecond) + } + if n := everything.calls.Load(); n != 1 { + t.Fatalf("StopAll ran %d times", n) + } +} + +// TestEnterWaitsForTheAnswer: Enter pressed before the text's first results arrive runs the first +// row of those results, not of the older rows drawn. +func TestEnterWaitsForTheAnswer(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + h.do(func() { + h.v.Type("move") + h.v.Press(view.KeyEvent{Key: view.KeyEnter}) + }) + if c := h.call(); c != "window Move /move" { + t.Fatalf("enter: %q", c) + } + // an edit after the Enter cancels it + h.do(h.l.Show) + h.settle() + h.do(func() { + h.v.Type("copy") + h.v.Press(view.KeyEvent{Key: view.KeyEnter}) + h.v.Type("sync") + }) + h.settle() + h.noCall("Enter, then an edit") +} + +func TestTildeBrowsesHome(t *testing.T) { + h := newHarness(t) + home := filepath.Join(string(filepath.Separator), "home", "me") + h.do(func() { h.l.home = home }) + h.do(h.l.Show) + if rows := h.typeText("~"); !slices.Contains(rows, "Browse "+home) { + t.Errorf("~: %q", rows) + } +} + +// TestTabThroughAFolderWithSpaces: Tab on a folder with a space opens a quote and leaves it +// open, and the next Tab continues inside it. +func TestTabThroughAFolderWithSpaces(t *testing.T) { + h := newHarness(t) + h.do(func() { + h.l.state = source{list: func(_ context.Context, dir string, page func([]engine.Entry)) error { + switch dir { + case "gdrive:": + page([]engine.Entry{{Name: "My Folder", Path: "gdrive:My Folder", Dir: true}}) + case "gdrive:My Folder/": + page([]engine.Entry{{Name: "inside", Path: "gdrive:My Folder/inside", Dir: true}}) + } + return nil + }} + }) + h.do(h.l.Show) + h.typeText("copy gdrive:My") + if !h.selectRow("My Folder/") { + t.Fatalf("no My Folder/: %q", h.v.Titles()) + } + h.press(view.KeyTab, 0) + if h.v.Query != `copy "gdrive:My Folder/` { + t.Fatalf("first Tab: %q", h.v.Query) + } + h.settle() + if !h.selectRow("inside/") { + t.Fatalf("no inside/: %q", h.v.Titles()) + } + h.press(view.KeyTab, 0) + if h.v.Query != `copy "gdrive:My Folder/inside/` { + t.Fatalf("second Tab: %q", h.v.Query) + } +} + +// TestTabThroughAFolderWithAQuote: a folder whose name contains a quote is completed inside a +// different kind of quote, so the path stays whole. +func TestTabThroughAFolderWithAQuote(t *testing.T) { + h := newHarness(t) + h.do(func() { + h.l.state = source{list: func(_ context.Context, dir string, page func([]engine.Entry)) error { + if dir == "gdrive:" { + page([]engine.Entry{{Name: `My "Best" Photos`, Path: `gdrive:My "Best" Photos`, Dir: true}}) + } + return nil + }} + }) + h.do(h.l.Show) + for _, typed := range []string{"copy gdrive:My", `copy "gdrive:My`} { + h.typeText(typed) + if !h.selectRow(`My "Best" Photos/`) { + t.Fatalf("%s: no folder: %q", typed, h.v.Titles()) + } + h.press(view.KeyTab, 0) + if h.v.Query != `copy 'gdrive:My "Best" Photos/` { + t.Fatalf("%s: Tab: %q", typed, h.v.Query) + } + h.settle() + var typing string + h.do(func() { + if p := h.l.query.Typing; p != nil { + typing = p.Text + } + }) + if typing != `gdrive:My "Best" Photos/` { + t.Errorf("%s: the path read %q", typed, typing) + } + } +} + +// TestDrop: dropped files are named at the top of the launcher, and the text chooses where they +// go. Enter opens Copy with all of them. Esc clears them, and the next Esc hides. +func TestDrop(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + h.do(func() { h.v.Events.Drop([]string{"/tmp/a.jpg", "/tmp/b.jpg"}) }) + rows := h.settle() + if h.v.Last.Header != "2 items dropped: a.jpg, b.jpg" || h.v.Last.Placeholder != dropPlaceholder { + t.Fatalf("header %q, placeholder %q", h.v.Last.Header, h.v.Last.Placeholder) + } + if !slices.Contains(rows, "Copy 2 items to gdrive:") || !slices.Contains(rows, "Copy 2 items to…") || slices.Contains(rows, "Copy") { + t.Fatalf("dropped: %q", rows) + } + rows = h.typeText("gdrive:Backup") + if rows[0] != "Copy 2 items to gdrive:Backup" || rows[1] != "Move 2 items to gdrive:Backup" { + t.Fatalf("typed a destination: %q", rows) + } + h.press(view.KeyEnter, 0) + want := "window Copy /copy?initialDestination=gdrive%3ABackup&initialSource=%2Ftmp%2Fa.jpg&initialSource=%2Ftmp%2Fb.jpg" + if c := h.call(); c != want { + t.Fatalf("enter: %q", c) + } + + h.do(h.l.Show) + if rows := h.settle(); rows[0] != "Run" || h.v.Last.Header != "" { + t.Fatalf("the next showing kept the drop: %q, %q", rows, h.v.Last.Header) + } + h.do(func() { h.v.Events.Drop([]string{"/tmp/a.jpg"}) }) + h.settle() + if h.v.Last.Header != "Dropped: a.jpg" { + t.Fatalf("one file: %q", h.v.Last.Header) + } + h.press(view.KeyEsc, 0) + if rows := h.settle(); !h.v.Shown || h.v.Last.Header != "" || rows[0] != "Run" { + t.Fatalf("Esc lets the files go, keeping the launcher: shown %v, %q", h.v.Shown, rows) + } + h.press(view.KeyEsc, 0) + if h.v.Shown { + t.Fatal("the second Esc hides") + } +} + +// TestClipboard: a link that was just copied comes first for the empty query. Once used, it isn't +// offered again until the clipboard changes. +func TestClipboard(t *testing.T) { + h := newHarness(t) + clip, id := engine.Clip{Text: "https://example.com/files/movie.mkv"}, "1" + h.l.p.ClipboardPeek = func() (engine.Clip, string) { return clip, id } + h.do(h.l.Show) + if rows := h.settle(); rows[0] != "Download movie.mkv" { + t.Fatalf("shown: %q", rows) + } + if rows := h.typeText("co"); slices.Contains(rows, "Download movie.mkv") { + t.Fatalf("a query hides it: %q", rows) + } + h.typeText("") + h.press(view.KeyEnter, 0) + if c := h.call(); c != "window Download /download?initialUrl=https%3A%2F%2Fexample.com%2Ffiles%2Fmovie.mkv" { + t.Fatalf("enter: %q", c) + } + h.do(h.l.Show) + if rows := h.settle(); rows[0] == "Download movie.mkv" { + t.Fatal("offered again for the same copy") + } + h.do(h.l.Hide) + id = "2" + h.do(h.l.Show) + if rows := h.settle(); rows[0] != "Download movie.mkv" { + t.Fatalf("a new copy: %q", rows) + } +} + +// TestRowShortcutWithoutARow: ⌘ with a row letter that has no row isn't handled by the launcher, +// so the text box and the menus get it. The same holds in the panel. +func TestRowShortcutWithoutARow(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + rows := h.typeText("copy") + if rowIndex('u') < len(rows) { + t.Fatalf("⌘U has a row: %q", rows) + } + if h.press(view.KeyRow, 'u') { + t.Error("⌘U with no such row was taken") + } + h.typeText("gdr") + h.press(view.KeyActions, 0) + if h.press(view.KeyRow, 'u') { + t.Error("⌘U with no such action was taken") + } + if !h.v.Shown || h.v.Last.Header != "Actions for gdrive" { + t.Errorf("the panel moved: shown %v, header %q", h.v.Shown, h.v.Last.Header) + } + h.noCall("⌘U") + if !h.press(view.KeyRow, '1') { + t.Error("⌘1 on the panel's first action wasn't taken") + } +} + +// TestCloseDismisses: closing the window (Alt+F4) hides the launcher at once, while Esc would only +// close the panel or clear the dropped files. The query comes back at the next Show. +func TestCloseDismisses(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.typeText("gdr") + h.press(view.KeyActions, 0) + if !h.press(view.KeyClose, 0) || h.v.Shown { + t.Fatalf("closed over the panel: shown %v", h.v.Shown) + } + h.do(h.l.Show) + h.settle() + if h.v.Query != "gdr" || h.v.Last.Header != "" { + t.Errorf("shown again: query %q, header %q", h.v.Query, h.v.Last.Header) + } + h.do(func() { h.v.Events.Drop([]string{"/tmp/a.jpg"}) }) + h.settle() + if h.press(view.KeyClose, 0); h.v.Shown { + t.Fatal("closed with files dropped: still shown") + } +} + +// TestShowOverThePanel: showing the launcher again while the panel is open closes the panel and +// restores the query. +func TestShowOverThePanel(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.typeText("gdr") + h.press(view.KeyActions, 0) + h.do(func() { h.v.Type("edit") }) + h.do(h.l.Show) + h.settle() + if h.v.Query != "gdr" || h.v.Last.Header != "" { + t.Errorf("query %q, header %q", h.v.Query, h.v.Last.Header) + } +} + +// TestLateClipboardKeepsTheSelection: a clipboard that becomes known only after the first results +// adds its suggestion without moving the selection off the row the user picked. Enter pressed in +// the meantime runs the row that is drawn as selected. +func TestLateClipboardKeepsTheSelection(t *testing.T) { + h := newHarness(t) + release := make(chan struct{}) + h.l.p.ClipboardPeek = func() (engine.Clip, string) { + <-release + return engine.Clip{Text: "https://example.com/files/movie.mkv"}, "1" + } + h.do(h.l.Show) + rows := h.settle() + if rows[0] != "Run" { + t.Fatalf("before the clipboard: %q", rows) + } + h.press(view.KeyDown, 0) + h.press(view.KeyDown, 0) + picked := rows[2] + if picked != "gdrive" { + t.Fatalf("third row %q, want gdrive", picked) + } + close(release) + deadline := time.Now().Add(2 * time.Second) + for { + if rows = h.settle(); rows[0] == "Download movie.mkv" { + break + } + if time.Now().After(deadline) { + t.Fatalf("no suggestion: %q", rows) + } + time.Sleep(5 * time.Millisecond) + } + var selected string + h.do(func() { selected = h.l.results[h.l.sel].Title }) + if selected != picked { + t.Errorf("selected %q, want %q", selected, picked) + } + + // Enter while the clipboard is still being read runs the row drawn as selected + h.do(func() { + h.l.rerun() + if !h.l.fresh { + t.Error("the rows drawn stopped being the text's") + } + h.v.Press(view.KeyEvent{Key: view.KeyEnter}) + }) + if c := h.call(); c != "full Commander /commander?path=gdrive%3A" { + t.Errorf("enter: %q", c) + } +} + +// TestAnActionThatPanics: an action that panics fails, the failure is shown in the corner, and +// the launcher keeps working. +func TestAnActionThatPanics(t *testing.T) { + h := newHarness(t) + h.do(h.l.Show) + h.settle() + a := engine.Action{ID: "broken", Name: "Broken", Stay: true, Run: func(context.Context, engine.Env) error { + var m map[string]int + m["x"]++ + return nil + }} + h.do(func() { h.l.perform(engine.Result{ID: "broken", Title: "Broken", Actions: []engine.Action{a}}, a, "") }) + deadline := time.Now().Add(2 * time.Second) + for { + var st view.Status + h.do(func() { st = h.v.Last.Status }) + if st.Kind == view.StatusError { + if st.Text != "Broken failed: something went wrong" { + t.Errorf("status %q", st.Text) + } + break + } + if time.Now().After(deadline) { + t.Fatalf("no failure in the corner: %+v", st) + } + time.Sleep(5 * time.Millisecond) + } + if rows := h.typeText("copy"); rows[0] != "Copy" { + t.Errorf("after the panic: %q", rows) + } +} + +// following records whether transfer progress is being followed. +type following struct { + source + on *atomic.Bool +} + +func (f following) FollowProgress(on bool) { f.on.Store(on) } + +func TestProgressIsFollowedWhileUp(t *testing.T) { + h := newHarness(t) + on := &atomic.Bool{} + h.do(func() { h.l.state = following{on: on} }) + h.do(h.l.Show) + h.settle() + if !on.Load() { + t.Fatal("shown: not followed") + } + h.do(h.l.Hide) + if on.Load() { + t.Fatal("hidden: still followed") + } +} diff --git a/app/launcher/match/match.go b/app/launcher/match/match.go new file mode 100644 index 00000000..a7f9c601 --- /dev/null +++ b/app/launcher/match/match.go @@ -0,0 +1,218 @@ +// Package match does the launcher's fuzzy matching. A pattern matches when its letters appear in +// order anywhere in a text. Matches are scored so that the ones a person most likely means come +// first (at the start of a word, as a run of letters, or at the start of the text). The matched +// positions are returned so they can be drawn bold. +package match + +import ( + "strings" + "unicode" +) + +// Scores. A matched letter is worth scoreMatch, and its position can add a bonus. Every letter +// skipped between two matched ones costs a little, and the first skipped letter costs more. +const ( + scoreMatch = 16 + gapStart = -3 + gapExtension = -1 + bonusBoundary = 8 // at the start of a word: after a space, `-`, `_`, `/`, `:` or `.` + bonusCamel = 7 // an upper-case letter after a lower-case one + bonusConsecutive = 4 // right after the previous matched letter + bonusFirstChar = 2 // multiplier for the bonus of the pattern's first letter + bonusPrefix = 20 // the match starts at the start of the text + bonusWholeWord = 12 // the pattern is a whole word of the text +) + +// ExactBonus is added when the pattern matches the whole text. +const ExactBonus = 100 + +// Exact reports whether pattern equals text, ignoring case and surrounding spaces. Such a match +// earns ExactBonus. +func Exact(pattern, text string) bool { + return strings.EqualFold(strings.TrimSpace(pattern), strings.TrimSpace(text)) +} + +// Result is a match: its score and the positions of the matched runes in the text, in order. +type Result struct { + Score int + Positions []int +} + +// Match finds each of pattern's words in text as letters in order, ignoring case. ok is false +// unless every word matches. An empty pattern matches with score 0. +func Match(pattern, text string) (Result, bool) { + words := strings.Fields(pattern) + if len(words) == 0 { + return Result{}, true + } + t := []rune(text) + lower := make([]rune, len(t)) + for i, r := range t { + lower[i] = unicode.ToLower(r) + } + var total Result + seen := map[int]bool{} + for _, w := range words { + r, ok := matchWord([]rune(strings.ToLower(w)), t, lower) + if !ok { + return Result{}, false + } + total.Score += r.Score + for _, p := range r.Positions { + if !seen[p] { + seen[p] = true + total.Positions = append(total.Positions, p) + } + } + } + if Exact(pattern, text) { + total.Score += ExactBonus + } + sortInts(total.Positions) + return total, true +} + +// matchWord matches one word. It finds the first place where all its letters appear in order, +// then tightens the match backwards from the end to the shortest span ending there, and scores +// it. +func matchWord(p, text, lower []rune) (Result, bool) { + if len(p) == 0 { + return Result{}, true + } + // forward pass: find the earliest position where the last letter can match + pi, end := 0, -1 + for i, r := range lower { + if r == p[pi] { + pi++ + if pi == len(p) { + end = i + break + } + } + } + if end < 0 { + return Result{}, false + } + // A contiguous occurrence at the start of a word beats the first scattered one ("cp" is + // scattered in "Copy" but a word in "cp files"), so look for the best contiguous one too. + best, bestScore := []int(nil), -1<<30 + if pos, ok := contiguous(p, text, lower); ok { + best, bestScore = pos, score(text, lower, pos, len(p)) + } + // backward pass from end: find the latest start that still matches, for the shortest span + start := end + pi = len(p) - 1 + for i := end; i >= 0; i-- { + if lower[i] == p[pi] { + pi-- + if pi < 0 { + start = i + break + } + } + } + pos := make([]int, 0, len(p)) + pi = 0 + for i := start; i <= end && pi < len(p); i++ { + if lower[i] == p[pi] { + pos = append(pos, i) + pi++ + } + } + if s := score(text, lower, pos, len(p)); s > bestScore { + best, bestScore = pos, s + } + return Result{Score: bestScore, Positions: best}, true +} + +// contiguous finds p as a run of letters at its best position: the first one at the start of a +// word if there is one, and otherwise the first one. +func contiguous(p, text, lower []rune) ([]int, bool) { + first := -1 + for i := 0; i+len(p) <= len(lower); i++ { + ok := true + for k := range p { + if lower[i+k] != p[k] { + ok = false + break + } + } + if !ok { + continue + } + if first < 0 { + first = i + } + if boundary(text, i) > 0 { + first = i + break + } + } + if first < 0 { + return nil, false + } + pos := make([]int, len(p)) + for k := range p { + pos[k] = first + k + } + return pos, true +} + +func score(text, lower []rune, pos []int, n int) int { + s := 0 + for k, i := range pos { + b := boundary(text, i) + if k == 0 { + b *= bonusFirstChar + } + s += scoreMatch + b + if k > 0 { + gap := i - pos[k-1] - 1 + if gap == 0 { + s += bonusConsecutive + } else { + s += gapStart + gapExtension*(gap-1) + } + } + } + if len(pos) > 0 && pos[0] == 0 { + s += bonusPrefix + } + if len(pos) == n && n > 0 { + last := pos[len(pos)-1] + contiguousRun := last-pos[0] == n-1 + endsWord := last+1 == len(lower) || !isWord(lower[last+1]) + if contiguousRun && boundary(text, pos[0]) > 0 && endsWord { + s += bonusWholeWord + } + } + return s +} + +// boundary returns the bonus that a match at i earns for its position: bonusBoundary at the start +// of a word, bonusCamel at a camelCase hump or at a digit after a letter, and 0 elsewhere. +func boundary(text []rune, i int) int { + if i == 0 { + return bonusBoundary + } + prev, cur := text[i-1], text[i] + switch { + case !isWord(prev): + return bonusBoundary + case unicode.IsLower(prev) && unicode.IsUpper(cur): + return bonusCamel + case unicode.IsLetter(prev) && unicode.IsDigit(cur): + return bonusCamel + } + return 0 +} + +func isWord(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } + +func sortInts(a []int) { + for i := 1; i < len(a); i++ { + for j := i; j > 0 && a[j] < a[j-1]; j-- { + a[j], a[j-1] = a[j-1], a[j] + } + } +} diff --git a/app/launcher/match/match_test.go b/app/launcher/match/match_test.go new file mode 100644 index 00000000..f70f657b --- /dev/null +++ b/app/launcher/match/match_test.go @@ -0,0 +1,109 @@ +package match + +import ( + "reflect" + "sort" + "testing" +) + +func TestMatchPositions(t *testing.T) { + cases := []struct { + pattern, text string + ok bool + pos []int + }{ + {"", "Copy", true, nil}, + {"cp", "Copy", true, []int{0, 2}}, + {"mo", "Move", true, []int{0, 1}}, + {"mo", "New Remote", true, []int{6, 7}}, + {"gdr", "Browse gdrive:", true, []int{7, 8, 9}}, + {"copy gd", "Copy gdrive: → /tmp", true, []int{0, 1, 2, 3, 5, 6}}, + {"xyz", "Copy", false, nil}, + {"MOUNT", "Mount gdrive:", true, []int{0, 1, 2, 3, 4}}, + {"sr", "Show Remotes", true, []int{0, 5}}, + } + for _, c := range cases { + r, ok := Match(c.pattern, c.text) + if ok != c.ok { + t.Errorf("Match(%q, %q) ok = %v", c.pattern, c.text, ok) + continue + } + if ok && !reflect.DeepEqual(r.Positions, c.pos) { + t.Errorf("Match(%q, %q) positions = %v, want %v", c.pattern, c.text, r.Positions, c.pos) + } + } +} + +// rank orders texts by their score for pattern, best first. Ties keep their order. +func rank(pattern string, texts []string) []string { + type scored struct { + text string + score int + } + var out []scored + for _, s := range texts { + if r, ok := Match(pattern, s); ok { + out = append(out, scored{s, r.Score}) + } + } + sort.SliceStable(out, func(i, j int) bool { return out[i].score > out[j].score }) + names := make([]string, len(out)) + for i, s := range out { + names[i] = s.text + } + return names +} + +func TestMatchRanking(t *testing.T) { + commands := []string{"Bisync", "Copy", "Download", "Move", "Mount", "New Remote", "Serve", "Settings", "Show Remotes", "Sync"} + cases := []struct { + pattern string + first []string // the leading results, in order + }{ + {"copy", []string{"Copy"}}, + {"mo", []string{"Move", "Mount"}}, + {"sync", []string{"Sync", "Bisync"}}, + {"set", []string{"Settings"}}, + {"rem", []string{"New Remote", "Show Remotes"}}, + {"s", []string{"Serve", "Settings", "Show Remotes", "Sync"}}, + } + for _, c := range cases { + got := rank(c.pattern, commands) + if len(got) < len(c.first) || !reflect.DeepEqual(got[:len(c.first)], c.first) { + t.Errorf("rank(%q) = %v, want it to start with %v", c.pattern, got, c.first) + } + } +} + +func TestExactBeatsPrefix(t *testing.T) { + exact, _ := Match("sync", "Sync") + prefix, _ := Match("sync", "Synchronise") + inner, _ := Match("sync", "Bisync") + if !(exact.Score > prefix.Score && prefix.Score > inner.Score) { + t.Errorf("scores exact %d, prefix %d, inner %d", exact.Score, prefix.Score, inner.Score) + } +} + +// TestExactAddsExactBonus: a pattern that equals the whole text, ignoring case and spaces, scores +// ExactBonus more than the same letters matched in a longer text. +func TestExactAddsExactBonus(t *testing.T) { + for _, c := range []struct { + pattern, text string + exact bool + }{ + {"sync", "Sync", true}, + {" SYNC ", "sync", true}, + {"sync", "Sync ", true}, + {"sync", "Synced", false}, + {"syn", "Sync", false}, + } { + if got := Exact(c.pattern, c.text); got != c.exact { + t.Errorf("Exact(%q, %q) = %v", c.pattern, c.text, got) + } + } + exact, _ := Match("Sync", "Sync") + longer, _ := Match("Sync", "Sync x") + if exact.Score-longer.Score != ExactBonus { + t.Errorf("exact %d, the same letters in a longer text %d", exact.Score, longer.Score) + } +} diff --git a/app/launcher/portaltrigger.go b/app/launcher/portaltrigger.go new file mode 100644 index 00000000..cb418b14 --- /dev/null +++ b/app/launcher/portaltrigger.go @@ -0,0 +1,66 @@ +package launcher + +import "strings" + +// waylandSession reports whether the desktop is a Wayland session, using the same rule as Wails: +// XDG_SESSION_TYPE when it is set, and otherwise whether WAYLAND_DISPLAY is set. +func waylandSession(getenv func(string) string) bool { + switch strings.ToLower(getenv("XDG_SESSION_TYPE")) { + case "wayland": + return true + case "x11": + return false + } + return getenv("WAYLAND_DISPLAY") != "" +} + +// portalTrigger converts a Wails accelerator ("CmdOrCtrl+Shift+/") into the preferred trigger +// for the GlobalShortcuts portal ("CTRL+SHIFT+slash"). The modifiers use the portal's names and +// order, and the key uses its XKB keysym name. The trigger is only a preference, because the +// compositor and the user decide the actual keys. +func portalTrigger(accel string) string { + // Accelerator writes a "+" key as "plus", so every "+" is a separator. + parts := strings.Split(accel, "+") + key := parts[len(parts)-1] + has := map[string]bool{} + for _, m := range parts[:len(parts)-1] { + switch strings.ToLower(m) { + case "cmdorctrl", "ctrl": + has["CTRL"] = true + case "alt": + has["ALT"] = true + case "shift": + has["SHIFT"] = true + case "super": + has["LOGO"] = true + } + } + var out []string + for _, m := range []string{"CTRL", "ALT", "SHIFT", "LOGO"} { + if has[m] { + out = append(out, m) + } + } + if name, ok := keysyms[strings.ToLower(key)]; ok { + key = name + } else { + key = strings.ToLower(key) + } + return strings.Join(append(out, key), "+") +} + +// keysyms maps the keys that Accelerator writes to their XKB names, for keys whose name isn't the +// character itself. +var keysyms = map[string]string{ + ";": "semicolon", "=": "equal", ",": "comma", "-": "minus", ".": "period", "/": "slash", + "`": "grave", "[": "bracketleft", `\`: "backslash", "]": "bracketright", "'": "apostrophe", + "+": "plus", "plus": "plus", + "backspace": "BackSpace", "tab": "Tab", "return": "Return", "enter": "Return", + "escape": "Escape", "space": "space", "page up": "Prior", "page down": "Next", "end": "End", + "home": "Home", "left": "Left", "up": "Up", "right": "Right", "down": "Down", + "delete": "Delete", + "f1": "F1", "f2": "F2", "f3": "F3", "f4": "F4", "f5": "F5", "f6": "F6", "f7": "F7", "f8": "F8", + "f9": "F9", "f10": "F10", "f11": "F11", "f12": "F12", "f13": "F13", "f14": "F14", "f15": "F15", + "f16": "F16", "f17": "F17", "f18": "F18", "f19": "F19", "f20": "F20", "f21": "F21", "f22": "F22", + "f23": "F23", "f24": "F24", +} diff --git a/app/launcher/portaltrigger_test.go b/app/launcher/portaltrigger_test.go new file mode 100644 index 00000000..16001632 --- /dev/null +++ b/app/launcher/portaltrigger_test.go @@ -0,0 +1,41 @@ +package launcher + +import "testing" + +// TestPortalTrigger: shortcuts from Settings, converted by Accelerator, become the portal's +// preferred triggers. +func TestPortalTrigger(t *testing.T) { + for _, c := range []struct{ shortcut, want string }{ + {DefaultShortcut, "CTRL+SHIFT+slash"}, + {"Ctrl+Alt+K", "CTRL+ALT+k"}, + {"Command+Shift+Space", "SHIFT+LOGO+space"}, + {"Alt+F5", "ALT+F5"}, + {"CmdOrCtrl+Shift+ArrowUp", "CTRL+SHIFT+Up"}, + {"Ctrl++", "CTRL+plus"}, + {"Shift+Alt+Digit1", "ALT+SHIFT+1"}, + } { + acc, err := Accelerator(c.shortcut) + if err != nil { + t.Fatalf("%s: %v", c.shortcut, err) + } + if got := portalTrigger(acc); got != c.want { + t.Errorf("%s (%s): got %q, want %q", c.shortcut, acc, got, c.want) + } + } +} + +func TestWaylandSession(t *testing.T) { + for _, c := range []struct { + env map[string]string + want bool + }{ + {map[string]string{"XDG_SESSION_TYPE": "wayland"}, true}, + {map[string]string{"XDG_SESSION_TYPE": "x11", "WAYLAND_DISPLAY": "wayland-0"}, false}, + {map[string]string{"WAYLAND_DISPLAY": "wayland-0"}, true}, + {map[string]string{}, false}, + } { + if got := waylandSession(func(k string) string { return c.env[k] }); got != c.want { + t.Errorf("%v: got %v", c.env, got) + } + } +} diff --git a/app/launcher/shortcut.go b/app/launcher/shortcut.go new file mode 100644 index 00000000..415f01e2 --- /dev/null +++ b/app/launcher/shortcut.go @@ -0,0 +1,215 @@ +package launcher + +import ( + "fmt" + "log/slog" + "strings" + "sync" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/core/errs" +) + +const DefaultShortcut = "CmdOrCtrl+Shift+/" + +// Accelerator converts a shortcut from the format stored in the settings into Wails' accelerator +// syntax. The settings use the syntax that the Settings recorder writes ("Command+Shift+/", +// "Ctrl+Alt+K", "CmdOrCtrl+Shift+ArrowUp"). The Wails forms are "Super+Shift+/", "Ctrl+Alt+k" and +// "CmdOrCtrl+Shift+up". Command, Cmd, Meta and Super mean the Command key on macOS and the +// Windows/Super key elsewhere. +func Accelerator(shortcut string) (string, error) { + s := strings.TrimSpace(shortcut) + if s == "" { + return "", errs.New("empty shortcut") + } + // "+" can itself be the key, as in "Ctrl++", where it follows the modifier's "+". + var parts []string + if before, ok := strings.CutSuffix(s, "++"); ok { + parts = append(strings.Split(before, "+"), "plus") + } else { + parts = strings.Split(s, "+") + } + if len(parts) < 2 { + return "", errs.Errorf("shortcut %q has no modifier", shortcut) + } + out := make([]string, 0, len(parts)) + seen := map[string]bool{} + for _, m := range parts[:len(parts)-1] { + mod, ok := modifiers[strings.ToLower(strings.TrimSpace(m))] + if !ok { + // i18n: %[1]q is a keyboard shortcut, and %[2]q the part of it that should be a modifier key (Ctrl, Alt, Shift…). + return "", errs.Errorf("shortcut %[1]q: %[2]q is not a modifier", shortcut, m) + } + if !seen[mod] { + seen[mod] = true + out = append(out, mod) + } + } + key, err := keyName(strings.TrimSpace(parts[len(parts)-1])) + if err != nil { + return "", fmt.Errorf("shortcut %q: %w", shortcut, err) + } + return strings.Join(append(out, key), "+"), nil +} + +var modifiers = map[string]string{ + "cmdorctrl": "CmdOrCtrl", + "commandorcontrol": "CmdOrCtrl", + "commandorctrl": "CmdOrCtrl", + "cmdorcontrol": "CmdOrCtrl", + "command": "Super", + "cmd": "Super", + "meta": "Super", + "super": "Super", + "control": "Ctrl", + "ctrl": "Ctrl", + "alt": "Alt", + "option": "Alt", + "optionoralt": "Alt", + "altgr": "Alt", + "shift": "Shift", +} + +// keyName converts a key name from the settings' syntax (a character, "Slash", "KeyA", "Digit1", +// "ArrowUp", "F5", …) to Wails' syntax. +func keyName(k string) (string, error) { + if k == "" { + return "", errs.New("no key") + } + lower := strings.ToLower(k) + if named, ok := namedKeys[lower]; ok { + return named, nil + } + switch { + case len(lower) == 4 && strings.HasPrefix(lower, "key") && lower[3] >= 'a' && lower[3] <= 'z': + return lower[3:], nil + case len(lower) == 6 && strings.HasPrefix(lower, "digit") && lower[5] >= '0' && lower[5] <= '9': + return lower[5:], nil + case len(lower) >= 2 && len(lower) <= 3 && lower[0] == 'f' && isDigits(lower[1:]): + return lower, nil + case len([]rune(k)) == 1: + if k == "+" { + return "plus", nil + } + return lower, nil + } + return "", errs.Errorf("%q is not a key", k) +} + +func isDigits(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return s != "" +} + +var namedKeys = map[string]string{ + "slash": "/", + "backslash": `\`, + "backquote": "`", + "minus": "-", + "equal": "=", + "bracketleft": "[", + "bracketright": "]", + "semicolon": ";", + "quote": "'", + "comma": ",", + "period": ".", + "plus": "plus", + "space": "space", + "enter": "enter", + "return": "return", + "tab": "tab", + "escape": "escape", + "esc": "escape", + "backspace": "backspace", + "delete": "delete", + "home": "home", + "end": "end", + "pageup": "page up", + "pagedown": "page down", + "arrowup": "up", + "arrowdown": "down", + "arrowleft": "left", + "arrowright": "right", + "up": "up", + "down": "down", + "left": "left", + "right": "right", +} + +// Shortcut is the launcher's global shortcut, which calls fn. fn receives the compositor's +// activation token for the key press when there is one (on Wayland), and "" otherwise. +type Shortcut struct { + log *slog.Logger + fn func(token string) + bind binder + mu sync.Mutex + held string // the registered accelerator +} + +// binder registers an accelerator with the OS. It uses Wails' global shortcuts, or on Wayland the +// launcher's own portal session (shortcut_linux.go), which passes on the activation token. +type binder interface { + register(accel string, fn func(token string)) error + unregister(accel string) error +} + +// wailsBinder uses Wails' global shortcuts, which don't provide a token. +type wailsBinder struct{ app *application.App } + +func (b wailsBinder) register(accel string, fn func(token string)) error { + return b.app.GlobalShortcut.Register(accel, func() { fn("") }) +} + +func (b wailsBinder) unregister(accel string) error { return b.app.GlobalShortcut.Unregister(accel) } + +func NewShortcut(app *application.App, log *slog.Logger, fn func(token string)) *Shortcut { + return &Shortcut{log: log, fn: fn, bind: newBinder(app, log)} +} + +// Set replaces the shortcut, and "" removes it. shortcut uses the syntax that Settings +// records. If the OS refuses the new shortcut, the previous one stays in place and Set +// returns the reason. Settings saves a shortcut only after it is registered. +func (s *Shortcut) Set(shortcut string) error { + next := "" + if shortcut != "" { + acc, err := Accelerator(shortcut) + if err != nil { + return err + } + next = acc + } + s.mu.Lock() + defer s.mu.Unlock() + prev := s.held + if next == prev { + return nil + } + if prev != "" { + if err := s.bind.unregister(prev); err != nil { + s.log.Warn("could not release the launcher shortcut", "shortcut", prev, "error", err) + } + } + if next != "" { + if err := s.bind.register(next, s.fn); err != nil { + if prev == "" { + return err + } + if rerr := s.bind.register(prev, s.fn); rerr != nil { + // Neither shortcut is registered now, so none is held, and the error reports + // both failures. + s.held = "" + s.log.Error("could not restore the launcher shortcut", "shortcut", prev, "error", rerr) + return errs.Errorf("%w (and the previous shortcut could not be restored: %v)", err, rerr) + } + return err + } + } + s.held = next + s.log.Info("launcher shortcut set", "shortcut", shortcut, "accelerator", next) + return nil +} diff --git a/app/launcher/shortcut_linux.go b/app/launcher/shortcut_linux.go new file mode 100644 index 00000000..32423d78 --- /dev/null +++ b/app/launcher/shortcut_linux.go @@ -0,0 +1,351 @@ +//go:build linux + +package launcher + +// Adapted from Wails v3.1.0 pkg/application/global_shortcut_linux_portal.go (MIT). It +// uses the same GlobalShortcuts session, for the launcher's single shortcut, but keeps something +// that Wails drops: the activation token sent with each key press (xdg-desktop-portal 1.21). +// That token is the only thing that lets a Wayland window take the focus. + +import ( + "fmt" + "log/slog" + "os" + "strings" + "sync" + "time" + + "github.com/godbus/dbus/v5" + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +// newBinder returns Wails' global shortcuts on X11 (a key grab), and the launcher's own portal +// session on Wayland. +func newBinder(app *application.App, log *slog.Logger) binder { + if waylandSession(os.Getenv) { + return &portalBinder{log: log, want: make(chan *binding, 1)} + } + return wailsBinder{app} +} + +const ( + portalService = "org.freedesktop.portal.Desktop" + portalPath = dbus.ObjectPath("/org/freedesktop/portal/desktop") + portalShortcuts = "org.freedesktop.portal.GlobalShortcuts" + portalRequest = "org.freedesktop.portal.Request" + portalSession = "org.freedesktop.portal.Session" + shortcutID = "launcher" + // portalWait is how long a portal request may take. Binding may wait for the user to answer + // a dialog shown by the desktop. + portalWait = 5 * time.Minute + // answerWait is how long register waits for the portal's answer. A portal without global + // shortcuts, or one that refuses outright, answers well within this time. A desktop that asks + // the user may not, and startup shouldn't wait for the user. + answerWait = 2 * time.Second +) + +// portalBinder binds the launcher's shortcut through xdg-desktop-portal's GlobalShortcuts. The +// portal answers asynchronously and may ask the user, so register queues the binding (the latest +// request wins) and waits up to answerWait for the portal's answer. A refusal within that time +// is returned as register's error, so Settings never saves a shortcut that the desktop refused. +// A later refusal is only logged. The trigger is only a preference, because the desktop and the +// user decide the actual keys. +type portalBinder struct { + log *slog.Logger + want chan *binding // holds at most one binding: the latest one requested + once sync.Once + + mu sync.Mutex + fn func(token string) +} + +// binding is an accelerator to bind ("" for none) and the channel that receives the portal's +// answer. +type binding struct { + accel string + done chan error // buffered, and answered once +} + +func newBinding(accel string) *binding { return &binding{accel: accel, done: make(chan error, 1)} } + +// answer sends the binding's outcome. It does nothing for a nil binding or one that was already +// answered. +func (r *binding) answer(err error) { + if r == nil || r.done == nil { + return + } + r.done <- err + r.done = nil +} + +func (b *portalBinder) register(accel string, fn func(token string)) error { + b.mu.Lock() + b.fn = fn + b.mu.Unlock() + r := newBinding(accel) + done := r.done + b.queue(r) + select { + case err := <-done: + return err + case <-time.After(answerWait): + b.log.Info("launcher shortcut: the portal hasn't answered yet", "shortcut", accel) + return nil + } +} + +func (b *portalBinder) unregister(string) error { + b.queue(newBinding("")) + return nil +} + +// queue replaces the binding that is waiting with r. The replaced binding is no longer wanted, +// so it is answered with nil rather than a refusal. +func (b *portalBinder) queue(r *binding) { + b.once.Do(func() { go b.run() }) + for { + select { + case b.want <- r: + return + default: + select { + case stale := <-b.want: + stale.answer(nil) + default: + } + } + } +} + +// fire handles a key press by calling the shortcut's function, with the activation token when the +// portal sends one. +func (b *portalBinder) fire(options map[string]dbus.Variant) { + token := "" + if v, ok := options["activation_token"]; ok { + token, _ = v.Value().(string) + } + b.mu.Lock() + fn := b.fn + b.mu.Unlock() + if fn != nil { + fn(token) + } +} + +// run owns the D-Bus connection and the portal session for the life of the process, and answers +// each binding. Bindings requested in quick succession (a release, then the new shortcut) are +// combined into one. +func (b *portalBinder) run() { + conn, err := dbus.ConnectSessionBus() + if err != nil { + b.log.Error("launcher shortcut: no session bus", "error", err) + err = fmt.Errorf("no session bus: %w", err) + for r := range b.want { + if r.accel == "" { + r.answer(nil) + } else { + r.answer(err) + } + } + return + } + defer func() { _ = conn.Close() }() + p := &portal{conn: conn, pending: map[dbus.ObjectPath]chan portalResponse{}} + if names := conn.Names(); len(names) > 0 { + p.sender = strings.ReplaceAll(strings.TrimPrefix(names[0], ":"), ".", "_") + } + // Responses and key presses arrive on one channel. It is read on its own goroutine, separate + // from the calls that wait for responses. + sigs := make(chan *dbus.Signal, 32) + conn.Signal(sigs) + _ = conn.AddMatchSignal(dbus.WithMatchInterface(portalRequest), dbus.WithMatchMember("Response")) + _ = conn.AddMatchSignal(dbus.WithMatchInterface(portalShortcuts), dbus.WithMatchMember("Activated")) + go func() { + for sig := range sigs { + p.signal(sig, b.fire) + } + }() + + var session dbus.ObjectPath + debounce := time.NewTimer(time.Hour) + debounce.Stop() + var next *binding + for { + select { + case r := <-b.want: + next.answer(nil) // replaced before it was bound + next = r + debounce.Reset(150 * time.Millisecond) + case <-debounce.C: + if session != "" { + p.close(session) + session = "" + } + if next == nil || next.accel == "" { + next.answer(nil) + continue + } + s, err := p.createSession() + if err != nil { + b.log.Error("launcher shortcut: the desktop's portal has no global shortcuts", "error", err) + next.answer(errs.Errorf("the desktop's portal has no global shortcuts: %w", err)) + continue + } + session = s + trigger := portalTrigger(next.accel) + if err := p.bind(session, trigger); err != nil { + b.log.Error("launcher shortcut: not bound", "shortcut", next.accel, "error", err) + // i18n: %s is a keyboard shortcut, in the desktop's syntax. + next.answer(errs.Errorf("the desktop didn't bind %s: %w", trigger, err)) + continue + } + b.log.Info("launcher shortcut bound by the portal", "trigger", trigger) + next.answer(nil) + } + } +} + +type portalResponse struct { + code uint32 // 0 granted, 1 cancelled by the user, 2 ended + results map[string]dbus.Variant +} + +// portal makes the GlobalShortcuts calls, which follow the portal's Request/Response pattern. +type portal struct { + conn *dbus.Conn + sender string // the connection's unique name, in the form used in request paths + seq int + + mu sync.Mutex + pending map[dbus.ObjectPath]chan portalResponse +} + +func (p *portal) token(prefix string) string { + p.seq++ + return fmt.Sprintf("rcui_%s_%d", prefix, p.seq) +} + +// call invokes a portal method and waits for its Response. The request's path is known before +// the call (from handle_token), so a Response that arrives before the call returns isn't missed. +func (p *portal) call(method string, options map[string]dbus.Variant, args ...any) (portalResponse, error) { + token := p.token("req") + options["handle_token"] = dbus.MakeVariant(token) + expected := dbus.ObjectPath("/org/freedesktop/portal/desktop/request/" + p.sender + "/" + token) + ch := make(chan portalResponse, 1) + p.wait(expected, ch) + defer p.forget(expected) + var handle dbus.ObjectPath + if err := p.conn.Object(portalService, portalPath).Call(portalShortcuts+"."+method, 0, + append(args, options)...).Store(&handle); err != nil { + return portalResponse{}, err + } + if handle != expected { // older portals choose the request path themselves + p.wait(handle, ch) + defer p.forget(handle) + } + select { + case r := <-ch: + return r, nil + case <-time.After(portalWait): + return portalResponse{}, fmt.Errorf("no answer to %s", method) + } +} + +func (p *portal) wait(path dbus.ObjectPath, ch chan portalResponse) { + p.mu.Lock() + p.pending[path] = ch + p.mu.Unlock() +} + +func (p *portal) forget(path dbus.ObjectPath) { + p.mu.Lock() + delete(p.pending, path) + p.mu.Unlock() +} + +func (p *portal) createSession() (dbus.ObjectPath, error) { + r, err := p.call("CreateSession", map[string]dbus.Variant{"session_handle_token": dbus.MakeVariant(p.token("session"))}) + if err != nil { + return "", err + } + if r.code != 0 { + return "", fmt.Errorf("CreateSession refused (response %d)", r.code) + } + // The spec says "s", but some portals send an object path. + switch v := r.results["session_handle"].Value().(type) { + case string: + return dbus.ObjectPath(v), nil + case dbus.ObjectPath: + return v, nil + } + return "", fmt.Errorf("CreateSession gave no session") +} + +// bind requests the launcher's shortcut in session, with trigger as its preferred keys. +func (p *portal) bind(session dbus.ObjectPath, trigger string) error { + type shortcut struct { + ID string + Props map[string]dbus.Variant + } + list := []shortcut{{ID: shortcutID, Props: map[string]dbus.Variant{ + // i18n: The description of the launcher's shortcut, which the desktop shows in its keyboard settings. + "description": dbus.MakeVariant(i18n.T("Open the Rclone UI launcher")), + "preferred_trigger": dbus.MakeVariant(trigger), + }}} + r, err := p.call("BindShortcuts", map[string]dbus.Variant{}, session, list, "") + if err != nil { + return err + } + if r.code != 0 { + return fmt.Errorf("the portal didn't grant it (response %d)", r.code) + } + return nil +} + +// close ends session, which also removes its binding. +func (p *portal) close(session dbus.ObjectPath) { + _ = p.conn.Object(portalService, session).Call(portalSession+".Close", 0).Err +} + +// signal sends a Response to the call that is waiting for it, and sends a press of the +// launcher's shortcut to fire. The press arrives as Activated(o session, s id, t timestamp, +// a{sv} options). +func (p *portal) signal(sig *dbus.Signal, fire func(map[string]dbus.Variant)) { + switch { + case strings.HasSuffix(sig.Name, ".Response"): + p.mu.Lock() + ch, ok := p.pending[sig.Path] + p.mu.Unlock() + if !ok { + return + } + var r portalResponse + if len(sig.Body) >= 1 { + r.code, _ = sig.Body[0].(uint32) + } + if len(sig.Body) >= 2 { + r.results, _ = sig.Body[1].(map[string]dbus.Variant) + } + select { + case ch <- r: + default: + } + case strings.HasSuffix(sig.Name, ".Activated"): + if len(sig.Body) < 2 { + return + } + if id, _ := sig.Body[1].(string); id != shortcutID { + return + } + options := map[string]dbus.Variant{} + if len(sig.Body) >= 4 { + if o, ok := sig.Body[3].(map[string]dbus.Variant); ok { + options = o + } + } + fire(options) + } +} diff --git a/app/launcher/shortcut_other.go b/app/launcher/shortcut_other.go new file mode 100644 index 00000000..49b5905b --- /dev/null +++ b/app/launcher/shortcut_other.go @@ -0,0 +1,13 @@ +//go:build !linux + +package launcher + +import ( + "log/slog" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// newBinder returns Wails' global shortcuts. On macOS and Windows the process that received the +// hotkey can take the focus without a token. +func newBinder(app *application.App, _ *slog.Logger) binder { return wailsBinder{app} } diff --git a/app/launcher/shortcut_test.go b/app/launcher/shortcut_test.go new file mode 100644 index 00000000..63791d07 --- /dev/null +++ b/app/launcher/shortcut_test.go @@ -0,0 +1,87 @@ +package launcher + +import ( + "errors" + "io" + "log/slog" + "strings" + "testing" +) + +// fakeBinder registers every accelerator except those in refuse. +type fakeBinder struct { + refuse map[string]bool + held map[string]bool +} + +func (b *fakeBinder) register(accel string, _ func(string)) error { + if b.refuse[accel] { + return errors.New("taken") + } + b.held[accel] = true + return nil +} + +func (b *fakeBinder) unregister(accel string) error { + delete(b.held, accel) + return nil +} + +// TestShortcutRefused: a refused shortcut leaves the previous one in place. When the previous one +// can't be restored either, none is held and the error says so. +func TestShortcutRefused(t *testing.T) { + b := &fakeBinder{refuse: map[string]bool{}, held: map[string]bool{}} + s := &Shortcut{log: slog.New(slog.NewTextHandler(io.Discard, nil)), fn: func(string) {}, bind: b} + if err := s.Set("Ctrl+Alt+K"); err != nil || s.held != "Ctrl+Alt+k" { + t.Fatalf("set: %v, held %q", err, s.held) + } + b.refuse["Ctrl+Alt+j"] = true + if err := s.Set("Ctrl+Alt+J"); err == nil || s.held != "Ctrl+Alt+k" || !b.held["Ctrl+Alt+k"] { + t.Fatalf("refused: %v, held %q, registered %v", err, s.held, b.held) + } + b.refuse["Ctrl+Alt+k"] = true + err := s.Set("Ctrl+Alt+J") + if err == nil || !strings.Contains(err.Error(), "previous shortcut") { + t.Errorf("neither: %v", err) + } + if s.held != "" || len(b.held) != 0 { + t.Errorf("neither: held %q, registered %v", s.held, b.held) + } + delete(b.refuse, "Ctrl+Alt+k") + if err := s.Set("Ctrl+Alt+K"); err != nil || !b.held["Ctrl+Alt+k"] { + t.Errorf("set again: %v, registered %v", err, b.held) + } +} + +func TestAccelerator(t *testing.T) { + cases := map[string]string{ + "CmdOrCtrl+Shift+/": "CmdOrCtrl+Shift+/", + "CommandOrControl+Shift+/": "CmdOrCtrl+Shift+/", + "Command+Shift+/": "Super+Shift+/", + "Ctrl+Alt+K": "Ctrl+Alt+k", + "Shift+F5": "Shift+f5", + "Command+ArrowUp": "Super+up", + "Ctrl+Space": "Ctrl+space", + "Alt+PageDown": "Alt+page down", + "Ctrl+Shift+KeyA": "Ctrl+Shift+a", + "Ctrl+Digit1": "Ctrl+1", + "Ctrl+Slash": "Ctrl+/", + "Ctrl++": "Ctrl+plus", + "Ctrl+Plus": "Ctrl+plus", + "Control+Option+Escape": "Ctrl+Alt+escape", + " Shift + Command + Enter ": "Shift+Super+enter", + "Command+Ctrl+Command+`": "Super+Ctrl+`", + "Meta+F12": "Super+f12", + } + for in, want := range cases { + got, err := Accelerator(in) + if err != nil || got != want { + t.Errorf("Accelerator(%q) = %q, %v; want %q", in, got, err, want) + } + } + for _, bad := range []string{"", "K", "Hyper+K", "Ctrl+", "Ctrl+Nope", "Ctrl+F99x"} { + if got, err := Accelerator(bad); err == nil { + t.Errorf("Accelerator(%q) = %q, want an error", bad, got) + } + } +} diff --git a/app/launcher/state/state.go b/app/launcher/state/state.go new file mode 100644 index 00000000..deb77ad7 --- /dev/null +++ b/app/launcher/state/state.go @@ -0,0 +1,161 @@ +// Package state is the launcher's Source over the shell's store of the core's state +// (app/corestate). It turns the store's snapshot into the providers' data, adds what only the +// launcher uses (folder listing and the core's services), and tells the launcher when the state +// changes. The progress of running transfers counts as a change only while the launcher is up, and +// at most once a second. +package state + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/launcher/engine" +) + +// Core is what the launcher reaches in the core besides the state: listing a folder, and the +// services that actions call. +type Core interface { + // List lists dir and passes each page of entries to page as it arrives. + List(ctx context.Context, dir string, page func([]engine.Entry)) error + Services() engine.Services +} + +const ( + maxListed = 2000 // the most entries of a folder that completion considers + // progressEvery is how often progress of running transfers may update what the launcher + // shows + progressEvery = time.Second +) + +type State struct { + store *corestate.Store + core Core + + mu sync.Mutex + onChange func() // called after the store's state changes + + // Progress of running transfers is followed while the launcher is up (FollowProgress). + // progressAt is when a progress change was last reported. A change that comes too soon is + // reported later, once (progressDue). + progressOn bool + progressAt time.Time + progressDue bool +} + +func New(store *corestate.Store, c Core) *State { + h := &State{store: store, core: c} + store.Subscribe(h.storeChanged) + return h +} + +// storeChanged tells the launcher that the state changed. Progress alone is told only while the +// launcher follows it, and at most once every progressEvery. +func (h *State) storeChanged(changed corestate.Part) { + if changed == corestate.Progress { + h.mu.Lock() + tell := h.progressOn && h.tellProgressLocked() + h.mu.Unlock() + if !tell { + return + } + } + h.changedState() +} + +// OnChange registers fn to be called (on the store's subscriber goroutine, or a timer's) each +// time the state changes. +func (h *State) OnChange(fn func()) { + h.mu.Lock() + h.onChange = fn + h.mu.Unlock() +} + +// changedState calls the function registered with OnChange. +func (h *State) changedState() { + h.mu.Lock() + fn := h.onChange + h.mu.Unlock() + if fn != nil { + fn() + } +} + +// Data returns the core's state, as last read. +func (h *State) Data() *engine.Data { + s := h.store.Snapshot() + d := &engine.Data{ + Remotes: s.Remotes, Mounts: s.Mounts, Serves: s.Serves, Vfs: s.Vfs, Tunnel: s.Tunnel, + Transfers: s.Transfers, Failed: s.Failed, ServeTypes: s.ServeTypes, + } + if s.Ready { + d.List = h.list + } + return d +} + +// Services returns the core's services for the actions. It is empty while the core isn't +// running. +func (h *State) Services() engine.Services { + if !h.store.Snapshot().Ready { + return engine.Services{} + } + return h.core.Services() +} + +func (h *State) RefreshIfOlder(ctx context.Context, age time.Duration) { + h.store.RefreshIfOlder(ctx, age) +} + +func (h *State) FollowProgress(on bool) { + h.mu.Lock() + h.progressOn = on + h.mu.Unlock() +} + +// tellProgressLocked reports whether a progress change should be reported now. A change that comes +// less than progressEvery after the last report is reported once that time has passed. h.mu must +// be held. +func (h *State) tellProgressLocked() bool { + wait := time.Until(h.progressAt.Add(progressEvery)) + if wait <= 0 { + h.progressAt = time.Now() + return true + } + if !h.progressDue { + h.progressDue = true + time.AfterFunc(wait, func() { + h.mu.Lock() + h.progressDue = false + h.progressAt = time.Now() + h.mu.Unlock() + h.changedState() + }) + } + return false +} + +// errEnough stops a listing once it has maxListed entries. +var errEnough = fmt.Errorf("enough entries") + +// list lists dir, up to maxListed entries, and passes each page to page as it arrives. +func (h *State) list(ctx context.Context, dir string, page func([]engine.Entry)) error { + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + n := 0 + err := h.core.List(ctx, dir, func(entries []engine.Entry) { + if n >= maxListed || len(entries) == 0 { + return + } + page(entries) + if n += len(entries); n >= maxListed { + cancel(errEnough) + } + }) + if context.Cause(ctx) == errEnough { + return nil + } + return err +} diff --git a/app/launcher/state/state_test.go b/app/launcher/state/state_test.go new file mode 100644 index 00000000..9996af86 --- /dev/null +++ b/app/launcher/state/state_test.go @@ -0,0 +1,111 @@ +package state + +import ( + "context" + "log/slog" + "sync/atomic" + "testing" + "time" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/vfs" +) + +// fakeCore is a fake core with one running transfer and nothing else. +type fakeCore struct{} + +func (fakeCore) ActiveTransfers(context.Context) ([]transfers.Transfer, error) { + return []transfers.Transfer{{ID: "t1", State: transfers.StateRunning}}, nil +} +func (fakeCore) Remotes(context.Context) ([]engine.Remote, error) { return nil, nil } +func (fakeCore) Mounts(context.Context) ([]mounts.MountRow, error) { return nil, nil } +func (fakeCore) Serves(context.Context) ([]serves.ServeRow, error) { return nil, nil } +func (fakeCore) Vfs(context.Context) ([]vfs.VFS, error) { return nil, nil } +func (fakeCore) Tunnel(context.Context) (bool, error) { return false, nil } +func (fakeCore) ServeTypes(context.Context) ([]string, error) { return nil, nil } +func (fakeCore) EndedTransfers(context.Context, int) ([]transfers.Transfer, error) { + return nil, nil +} +func (fakeCore) List(context.Context, string, func([]engine.Entry)) error { return nil } +func (fakeCore) Services() engine.Services { return engine.Services{Vfs: noVfs{}} } + +type noVfs struct{} + +func (noVfs) Forget(context.Context, string) error { return nil } + +// eventually fails the test unless ok becomes true within two seconds. +func eventually(t *testing.T, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("waited too long for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// TestServicesOnlyWhileReady: while the core isn't running, no core action and no folder listing +// is available. +func TestServicesOnlyWhileReady(t *testing.T) { + store := corestate.New(fakeCore{}, slog.New(slog.DiscardHandler)) + h := New(store, fakeCore{}) + if s := h.Services(); s.Vfs != nil || h.Data().List != nil { + t.Fatal("the services of a core that isn't running") + } + store.CoreReady(context.Background()) + if s := h.Services(); s.Vfs == nil || h.Data().List == nil { + t.Fatal("no services for a running core") + } + store.CoreDown() + if s := h.Services(); s.Vfs != nil || h.Data().List != nil { + t.Fatal("the services of a core that went") + } +} + +// TestProgressIsToldOnceASecond: progress that arrives faster than progressEvery is reported once, +// after that time has passed. Progress that nobody follows still lands, but isn't reported. +func TestProgressIsToldOnceASecond(t *testing.T) { + store := corestate.New(fakeCore{}, slog.New(slog.DiscardHandler)) + h := New(store, fakeCore{}) + var told atomic.Int32 + h.OnChange(func() { told.Add(1) }) + store.CoreReady(context.Background()) + eventually(t, "the transfers", func() bool { return len(h.Data().Transfers) == 1 }) + h.FollowProgress(true) + time.Sleep(50 * time.Millisecond) // the reads' own reports + base := told.Load() + progress := func(pct int) { + store.Event(context.Background(), bus.Event{Name: bus.TransfersProgress, Data: bus.TransfersProgressData{ + Items: map[string]bus.TransferProgress{"t1": {Pct: pct}}, + }}) + } + progress(0) + eventually(t, "the first report", func() bool { return told.Load() == base+1 }) + for pct := range 5 { + progress(pct) + } + time.Sleep(progressEvery / 2) + if got := told.Load() - base; got != 1 { + t.Fatalf("at once: told %d times", got) + } + time.Sleep(progressEvery/2 + 200*time.Millisecond) + if got := told.Load() - base; got != 2 { + t.Fatalf("after a second: told %d times", got) + } + if got := h.Data().Transfers[0].Live.Pct; got != 4 { + t.Errorf("the last numbers: %d%%", got) + } + h.FollowProgress(false) + progress(50) + eventually(t, "the numbers", func() bool { return h.Data().Transfers[0].Live.Pct == 50 }) + time.Sleep(progressEvery + 200*time.Millisecond) + if got := told.Load() - base; got != 2 { + t.Errorf("numbers nobody follows were reported: told %d times", got) + } +} diff --git a/app/launcher/view/darwin/clipboard.go b/app/launcher/view/darwin/clipboard.go new file mode 100644 index 00000000..76eadd23 --- /dev/null +++ b/app/launcher/view/darwin/clipboard.go @@ -0,0 +1,128 @@ +//go:build darwin + +package darwin + +// Reading the clipboard on macOS. From macOS 15.4, reading the general pasteboard outside of a +// paste prompts the user. This is pasteboard privacy, controlled by the "Paste from Other Apps" +// setting. Detecting what kind of content the pasteboard holds doesn't prompt, and neither does +// reading its change count. So the launcher only detects whether there is a link, and reads the +// link when the user chooses the suggestion. + +import ( + "runtime" + "strconv" + "sync" + "time" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/ebitengine/purego/objc" +) + +// Values of NSPasteboardAccessBehavior (macOS 15.4). +const ( + accessAlwaysAllow = 2 + accessAlwaysDeny = 3 +) + +// detectWait is how long a peek waits for the pasteboard's pattern detection, which replies on +// its own queue. +const detectWait = 200 * time.Millisecond + +var ( + clipOnce sync.Once + webURL objc.ID // NSPasteboardDetectionPatternProbableWebURL, or 0 before macOS 15.4 + + poolOnce sync.Once + poolPush func() uintptr + poolPop func(uintptr) +) + +func poolSetup() { + if objcLib, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_GLOBAL|purego.RTLD_NOW); err == nil { + purego.RegisterLibFunc(&poolPush, objcLib, "objc_autoreleasePoolPush") + purego.RegisterLibFunc(&poolPop, objcLib, "objc_autoreleasePoolPop") + } +} + +// autoreleased runs fn inside its own autorelease pool, on a single OS thread. Off the main +// thread there is no pool, so anything fn autoreleases would leak. A pool belongs to the thread +// that pushed it, but a goroutine that blocks, such as detectLink waiting for the pasteboard, can +// resume on another thread. Popping the pool there would pop that thread's pools, or none, and +// cause a crash later. So the goroutine stays locked to its thread from the push to the pop. +func autoreleased(fn func()) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + poolOnce.Do(poolSetup) + if poolPush == nil { + fn() + return + } + pool := poolPush() + defer poolPop(pool) + fn() +} + +func clipSetup() { + if appKit, err := purego.Dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", purego.RTLD_GLOBAL|purego.RTLD_NOW); err == nil { + if addr, err := purego.Dlsym(appKit, "NSPasteboardDetectionPatternProbableWebURL"); err == nil && addr != 0 { + webURL = **(**objc.ID)(unsafe.Pointer(&addr)) // the NSString that the constant holds + } + } +} + +// PeekClipboard returns what the launcher can learn about the clipboard without macOS prompting +// the user: the change count, which tells one copy apart from the next, and whether it holds a +// link. When reading doesn't prompt, it also returns the text. That is the case before macOS 15.4, +// or when the user always allows Rclone UI to paste. It can be called from any thread. +func PeekClipboard() (text string, link bool, count string) { + autoreleased(func() { text, link, count = peek() }) + return text, link, count +} + +func peek() (text string, link bool, count string) { + clipOnce.Do(clipSetup) + pb := msg(class("NSPasteboard"), "generalPasteboard") + count = strconv.Itoa(objc.Send[int](pb, sel("changeCount"))) + access := -1 // no pasteboard privacy, so reading doesn't prompt + if msgBool(pb, "respondsToSelector:", sel("accessBehavior")) { + access = objc.Send[int](pb, sel("accessBehavior")) + } + switch access { + case -1, accessAlwaysAllow: + if s := msg(pb, "stringForType:", nsString("public.utf8-plain-text")); s != 0 { + text = goString(s) + } + return text, false, count + case accessAlwaysDeny: + return "", false, count + } + return "", detectLink(pb), count +} + +func detectLink(pb objc.ID) bool { + if webURL == 0 || !msgBool(pb, "respondsToSelector:", sel("detectPatternsForPatterns:completionHandler:")) { + return false + } + return detect(func(done objc.Block) { + msg(pb, "detectPatternsForPatterns:completionHandler:", msg(class("NSSet"), "setWithObject:", webURL), done) + }) +} + +// detect gives each call its own completion handler. A late reply, which arrives after its peek +// gave up, then can't be taken as the reply to the next peek, which may be about a different copy. +func detect(ask func(done objc.Block)) bool { + found := make(chan bool, 1) + done := objc.NewBlock(func(_ objc.Block, patterns, _ objc.ID) { + guard("detectPatterns", func() { found <- patterns != 0 && msgBool(patterns, "containsObject:", webURL) }) + }) + // The pasteboard keeps its own copy of the block until it replies. + defer done.Release() + ask(done) + select { + case f := <-found: + return f + case <-time.After(detectWait): + return false + } +} diff --git a/app/launcher/view/darwin/clipboard_test.go b/app/launcher/view/darwin/clipboard_test.go new file mode 100644 index 00000000..c2461caf --- /dev/null +++ b/app/launcher/view/darwin/clipboard_test.go @@ -0,0 +1,86 @@ +//go:build darwin + +package darwin + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/ebitengine/purego" + "github.com/ebitengine/purego/objc" +) + +// TestLateDetectionIsItsOwn checks that a detection which replies after its peek gave up isn't +// taken as the reply to the next peek. +func TestLateDetectionIsItsOwn(t *testing.T) { + clipOnce.Do(clipSetup) + if webURL == 0 { + t.Skip("no pasteboard detection before macOS 15.4") + } + autoreleased(func() { + link := msg(class("NSSet"), "setWithObject:", webURL) + var late objc.Block + if detect(func(done objc.Block) { late = done.Copy() }) { + t.Fatal("found a link with no answer") + } + defer late.Release() + if !detect(func(done objc.Block) { done.Invoke(link, objc.ID(0)) }) { + t.Fatal("a link answered isn't found") + } + got := detect(func(done objc.Block) { + late.Invoke(link, objc.ID(0)) // the first peek's late reply, which found a link + done.Invoke(objc.ID(0), objc.ID(0)) + }) + if got { + t.Error("the earlier peek's answer was taken for this one's") + } + }) +} + +// TestAutoreleasedStaysOnOneThread checks that a goroutine which blocks inside the pool, while +// other goroutines keep the scheduler busy, pops the pool on the thread that pushed it. +func TestAutoreleasedStaysOnOneThread(t *testing.T) { + lib, err := purego.Dlopen("/usr/lib/libSystem.B.dylib", purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + t.Fatal(err) + } + var threadID func(thread uintptr, id *uint64) int32 + purego.RegisterLibFunc(&threadID, lib, "pthread_threadid_np") + current := func() uint64 { + var id uint64 + if threadID(0, &id) != 0 { + t.Fatal("pthread_threadid_np failed") + } + return id + } + + ctx, cancel := context.WithCancel(context.Background()) + var busy sync.WaitGroup + for range 8 { + busy.Go(func() { + for ctx.Err() == nil { + for i := range int(1e5) { + _ = i * i + } + } + }) + } + defer func() { + cancel() + busy.Wait() + }() + + for i := range 50 { + var before, after uint64 + autoreleased(func() { + before = current() + time.Sleep(20 * time.Millisecond) + after = current() + }) + if before != after { + t.Fatalf("run %d: the pool was pushed on thread %d and popped on %d", i, before, after) + } + } +} diff --git a/app/launcher/view/darwin/cocoa.go b/app/launcher/view/darwin/cocoa.go new file mode 100644 index 00000000..d7e42443 --- /dev/null +++ b/app/launcher/view/darwin/cocoa.go @@ -0,0 +1,144 @@ +//go:build darwin + +package darwin + +// This package calls Cocoa from Go through purego's objc runtime, without any Objective-C +// sources. It follows three rules: +// - Methods implemented in Go take only simple arguments. Struct parameters aren't supported, +// so the package can't implement drawRect:. +// - Calls never pass more than eight arguments. Apple's arm64 ABI packs small arguments on the +// stack, and purego doesn't. +// - Every call runs on the main thread. + +import ( + "runtime" + "sync" + "unsafe" + + "github.com/ebitengine/purego/objc" +) + +type nsPoint struct{ X, Y float64 } +type nsSize struct{ W, H float64 } +type nsRect struct { + Origin nsPoint + Size nsSize +} +type nsRange struct{ Loc, Len uint } + +func rect(x, y, w, h float64) nsRect { return nsRect{nsPoint{x, y}, nsSize{w, h}} } + +var sels sync.Map + +// sel caches selectors, because registering one takes the runtime's lock. +func sel(name string) objc.SEL { + if s, ok := sels.Load(name); ok { + return s.(objc.SEL) + } + s := objc.RegisterName(name) + sels.Store(name, s) + return s +} + +func class(name string) objc.ID { return objc.ID(objc.GetClass(name)) } + +func msg(id objc.ID, name string, args ...any) objc.ID { return id.Send(sel(name), args...) } + +func msgBool(id objc.ID, name string, args ...any) bool { + return objc.Send[bool](id, sel(name), args...) +} + +func msgRect(id objc.ID, name string, args ...any) nsRect { + return objc.Send[nsRect](id, sel(name), args...) +} + +func msgPoint(id objc.ID, name string, args ...any) nsPoint { + return objc.Send[nsPoint](id, sel(name), args...) +} + +func alloc(cls string) objc.ID { return msg(class(cls), "alloc") } + +func nsString(s string) objc.ID { + b := append([]byte(s), 0) + id := msg(class("NSString"), "stringWithUTF8String:", unsafe.Pointer(&b[0])) + runtime.KeepAlive(b) + return id +} + +func goString(id objc.ID) string { + if id == 0 { + return "" + } + n := objc.Send[uint](id, sel("lengthOfBytesUsingEncoding:"), uint(4)) // UTF-8 + if n == 0 { + return "" + } + p := objc.Send[*byte](id, sel("UTF8String")) + if p == nil { + return "" + } + return string(unsafe.Slice(p, n)) +} + +func nsData(b []byte) objc.ID { + id := msg(class("NSData"), "dataWithBytes:length:", unsafe.Pointer(&b[0]), uint(len(b))) + runtime.KeepAlive(b) + return id +} + +func color(name string) objc.ID { return msg(class("NSColor"), name) } + +func font(size float64, bold bool) objc.ID { + if bold { + return msg(class("NSFont"), "boldSystemFontOfSize:", size) + } + return msg(class("NSFont"), "systemFontOfSize:", size) +} + +func label(size float64) objc.ID { + l := msg(class("NSTextField"), "labelWithString:", nsString("")) + msg(l, "setFont:", font(size, false)) + msg(l, "setLineBreakMode:", uint(4)) // truncate the tail + return l +} + +// attributed returns s with the runes at the indexes in bold drawn in bold. The caller releases it. +func attributed(s string, size float64, col objc.ID, bold []int) objc.ID { + attrs := msg(class("NSMutableDictionary"), "dictionary") + msg(attrs, "setObject:forKey:", font(size, false), nsString("NSFont")) + msg(attrs, "setObject:forKey:", col, nsString("NSColor")) + as := msg(alloc("NSMutableAttributedString"), "initWithString:attributes:", nsString(s), attrs) + if len(bold) == 0 { + return as + } + // NSString ranges count UTF-16 code units. + u16 := make([]uint, 0, len(s)+1) + n := uint(0) + for _, r := range s { + u16 = append(u16, n) + if r >= 0x10000 { + n += 2 + } else { + n++ + } + } + u16 = append(u16, n) + isBold := make(map[int]bool, len(bold)) + for _, i := range bold { + isBold[i] = true + } + bf := font(size, true) + for i := 0; i < len(u16)-1; { + if !isBold[i] { + i++ + continue + } + j := i + for j < len(u16)-1 && isBold[j] { + j++ + } + msg(as, "addAttribute:value:range:", nsString("NSFont"), bf, nsRange{u16[i], u16[j] - u16[i]}) + i = j + } + return as +} diff --git a/app/launcher/view/darwin/view.go b/app/launcher/view/darwin/view.go new file mode 100644 index 00000000..25e6048b --- /dev/null +++ b/app/launcher/view/darwin/view.go @@ -0,0 +1,774 @@ +//go:build darwin + +// Package darwin is the launcher window on macOS, written in Go on top of Cocoa. The window is a +// non-activating panel, so it can take keyboard focus without activating the app, which macOS +// may refuse to do. It uses Liquid Glass on macOS 26 and an always-active blur on earlier versions. +package darwin + +import ( + "errors" + "strings" + + "github.com/ebitengine/purego/objc" + + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/core/i18n" +) + +// View is the launcher panel. There is one per process, and Cocoa callbacks find it through +// current. +type View struct { + ev view.Events + + panel, content, field, header objc.ID + // list holds the rows and their group labels, and clips them at its bottom edge, so the last + // row of a long list is drawn only in part. + list objc.ID + groupLabels []objc.ID // one label per row, shown above the row when it starts a group + rows []row + icons map[icons.Name]objc.ID + // footer holds the footer line, which shows the hints or a status. It has two slots. + // slots[active] holds the line shown now, and the other slot holds the line it replaced + // (see view.Swaps). + footer objc.ID + slots [2]slot + active int + line view.Line + stop objc.ID + stopHover bool + // language is the language that the panel's own labels were last set in (see label). + language string + + snap view.Snapshot + visible bool + left, top float64 // the top-left corner, in screen points + settingFrame bool // set while the view moves the panel, so the move isn't reported + hoverX, hoverY float64 // the last known pointer position, in screen points + scrolled float64 // the fraction of a row scrolled but not yet reported + blocks []objc.Block // kept for the life of the process + // When the panel loses keyboard focus while a mouse button is down, the cause may be a click + // elsewhere or a drag starting there. The panel then waits for the button to be released + // before reporting the blur, so the drag can still be dropped on it. dragOver is set while a + // drag is over the panel, and waitTimer checks the buttons while the panel waits. + dragOver bool + waitTimer objc.ID + waitTick objc.Block +} + +type row struct { + box, icon, title, sub, tail, hint objc.ID +} + +type slot struct { + box, spinner, label objc.ID +} + +var current *View + +// guard runs the Go side of a Cocoa callback. A panic can't unwind through the Objective-C frames +// that called it, because the process would abort, taking the core with it. So guard recovers the +// panic, reports it through Events.Panicked, and the launcher keeps running. +func guard(where string, fn func()) { + defer recovered(where) + fn() +} + +// guarded is guard for a callback that returns a value. It returns otherwise after a panic. +func guarded[T any](where string, otherwise T, fn func() T) (out T) { + out = otherwise + defer recovered(where) + return fn() +} + +// recovered must be deferred. +func recovered(where string) { + if v := recover(); v != nil && current != nil && current.ev.Panicked != nil { + current.ev.Panicked("launcher view: "+where, v) + } +} + +var ( + panelClass, contentClass, hoverClass, stopClass objc.Class +) + +// New builds the panel, hidden. It must be called once, on the main thread. +func New(ev view.Events) (*View, error) { + if current != nil { + return nil, errors.New("the launcher's window exists already") + } + if err := registerClasses(); err != nil { + return nil, err + } + v := &View{ev: ev, icons: map[icons.Name]objc.ID{}} + current = v + v.build() + return v, nil +} + +func registerClasses() error { + var err error + panelClass, err = objc.RegisterClass("RcuiLauncherPanel", objc.GetClass("NSPanel"), nil, nil, []objc.MethodDef{ + {Cmd: sel("canBecomeKeyWindow"), Fn: func(objc.ID, objc.SEL) bool { return true }}, + {Cmd: sel("canBecomeMainWindow"), Fn: func(objc.ID, objc.SEL) bool { return false }}, + }) + if err != nil { + return err + } + contentClass, err = objc.RegisterClass("RcuiLauncherContent", objc.GetClass("NSView"), nil, nil, []objc.MethodDef{ + {Cmd: sel("isFlipped"), Fn: func(objc.ID, objc.SEL) bool { return true }}, + {Cmd: sel("acceptsFirstMouse:"), Fn: func(objc.ID, objc.SEL, objc.ID) bool { return true }}, + {Cmd: sel("mouseDown:"), Fn: func(_ objc.ID, _ objc.SEL, e objc.ID) { guard("mouseDown", func() { current.mouseDown(e) }) }}, + {Cmd: sel("scrollWheel:"), Fn: func(_ objc.ID, _ objc.SEL, e objc.ID) { guard("scrollWheel", func() { current.scrollWheel(e) }) }}, + // NSDraggingDestination, for files dragged onto the panel. + {Cmd: sel("draggingEntered:"), Fn: func(objc.ID, objc.SEL, objc.ID) uint { + return guarded("draggingEntered", dragNone, func() uint { return current.dragEntered() }) + }}, + {Cmd: sel("draggingUpdated:"), Fn: func(objc.ID, objc.SEL, objc.ID) uint { return dragCopy }}, + {Cmd: sel("draggingExited:"), Fn: func(objc.ID, objc.SEL, objc.ID) { guard("draggingExited", func() { current.dragOver = false }) }}, + {Cmd: sel("prepareForDragOperation:"), Fn: func(objc.ID, objc.SEL, objc.ID) bool { return true }}, + {Cmd: sel("performDragOperation:"), Fn: func(_ objc.ID, _ objc.SEL, info objc.ID) bool { + return guarded("performDragOperation", false, func() bool { return current.drop(info) }) + }}, + }) + if err != nil { + return err + } + hoverClass, err = objc.RegisterClass("RcuiLauncherHover", objc.GetClass("NSObject"), nil, nil, []objc.MethodDef{ + {Cmd: sel("mouseMoved:"), Fn: func(_ objc.ID, _ objc.SEL, e objc.ID) { guard("mouseMoved", func() { current.mouseMoved(e) }) }}, + {Cmd: sel("mouseEntered:"), Fn: func(objc.ID, objc.SEL, objc.ID) {}}, + {Cmd: sel("mouseExited:"), Fn: func(objc.ID, objc.SEL, objc.ID) { guard("mouseExited", func() { current.stopLook(false) }) }}, + }) + if err != nil { + return err + } + stopClass, err = objc.RegisterClass("RcuiLauncherStop", objc.GetClass("NSObject"), nil, nil, []objc.MethodDef{ + {Cmd: sel("stopAll:"), Fn: func(objc.ID, objc.SEL, objc.ID) { + guard("stopAll", func() { + if current.ev.StopAll != nil { + current.ev.StopAll() + } + }) + }}, + }) + return err +} + +func (v *View) build() { + full := view.FullHeight() + view.HeaderH + // The panel is titled rather than borderless. A transparent borderless window gets its shadow + // from a surface drawn afterwards, which has square edges and flashes. A hidden full-size + // title bar keeps the panel frameless and lets AppKit draw the rounded outline and shadow. + const titled, nonactivating, fullSize = 1, 1 << 7, 1 << 15 + v.panel = msg(objc.ID(panelClass).Send(sel("alloc")), "initWithContentRect:styleMask:backing:defer:", + rect(0, 0, view.Width, full), uint(titled|nonactivating|fullSize), uint(2), false) + msg(v.panel, "setTitlebarAppearsTransparent:", true) + msg(v.panel, "setTitleVisibility:", 1) + for b := range uint(3) { // close, minimise, zoom + msg(msg(v.panel, "standardWindowButton:", b), "setHidden:", true) + } + msg(v.panel, "setLevel:", 3) // floating + msg(v.panel, "setCollectionBehavior:", uint(1|1<<8)) // every Space, over full-screen apps + msg(v.panel, "setFloatingPanel:", true) + msg(v.panel, "setBecomesKeyOnlyIfNeeded:", false) + msg(v.panel, "setHidesOnDeactivate:", false) + msg(v.panel, "setReleasedWhenClosed:", false) + msg(v.panel, "setMovableByWindowBackground:", false) + msg(v.panel, "setOpaque:", false) + msg(v.panel, "setBackgroundColor:", color("clearColor")) + msg(v.panel, "setHasShadow:", true) + + // The content goes inside the glass, because only there does AppKit apply the glass's + // legibility treatment. + v.content = msg(objc.ID(contentClass).Send(sel("alloc")), "initWithFrame:", rect(0, 0, view.Width, full)) + msg(v.content, "setAutoresizingMask:", uint(2|16)) // width, height + if g := class("NSGlassEffectView"); g != 0 { + glass := msg(msg(g, "alloc"), "initWithFrame:", rect(0, 0, view.Width, full)) + msg(glass, "setCornerRadius:", view.Radius) + msg(glass, "setWantsLayer:", true) + msg(msg(glass, "layer"), "setCornerRadius:", view.Radius) + msg(msg(glass, "layer"), "setMasksToBounds:", true) + msg(glass, "setContentView:", v.content) + msg(v.panel, "setContentView:", glass) + } else { + fx := msg(alloc("NSVisualEffectView"), "initWithFrame:", rect(0, 0, view.Width, full)) + msg(fx, "setMaterial:", 6) // popover + msg(fx, "setState:", 1) // always active + msg(fx, "setBlendingMode:", 0) // behind the window + msg(fx, "setWantsLayer:", true) + msg(msg(fx, "layer"), "setCornerRadius:", view.Radius) + msg(msg(fx, "layer"), "setMasksToBounds:", true) + msg(fx, "addSubview:", v.content) + msg(v.panel, "setContentView:", fx) + } + + v.field = msg(alloc("NSTextField"), "initWithFrame:", rect(18, view.FieldTop, view.FieldW, 30)) + msg(v.field, "setBezeled:", false) + msg(v.field, "setBordered:", false) + msg(v.field, "setDrawsBackground:", false) + msg(v.field, "setFocusRingType:", 1) // none + msg(v.field, "setFont:", font(22, false)) + msg(v.field, "setAutoresizingMask:", uint(2)) + msg(v.content, "addSubview:", v.field) + + v.buildStop() + + v.header = label(12) + msg(v.header, "setTextColor:", color("secondaryLabelColor")) + msg(v.header, "setFrame:", rect(18, view.QueryH, view.Width-36, 16)) + msg(v.content, "addSubview:", v.header) + + v.list = msg(objc.ID(contentClass).Send(sel("alloc")), "initWithFrame:", rect(0, view.QueryH, view.Width, view.MaxListH)) + msg(v.list, "setWantsLayer:", true) + msg(msg(v.list, "layer"), "setMasksToBounds:", true) + if msgBool(v.list, "respondsToSelector:", sel("setClipsToBounds:")) { + msg(v.list, "setClipsToBounds:", true) + } + msg(v.content, "addSubview:", v.list) + for range view.MaxRows { + sec := label(11) + msg(sec, "setFont:", msg(class("NSFont"), "systemFontOfSize:weight:", 11.0, 0.3)) // semibold + msg(sec, "setTextColor:", color("secondaryLabelColor")) + msg(sec, "setHidden:", true) + msg(v.list, "addSubview:", sec) + v.groupLabels = append(v.groupLabels, sec) + r := row{box: msg(objc.ID(contentClass).Send(sel("alloc")), "initWithFrame:", rect(view.Padding, 0, view.Width-2*view.Padding, view.RowH-4))} + msg(r.box, "setWantsLayer:", true) + msg(msg(r.box, "layer"), "setCornerRadius:", 10.0) + r.icon = msg(alloc("NSImageView"), "initWithFrame:", rect(14, (view.RowH-4-view.IconSize)/2, view.IconSize, view.IconSize)) + r.title = label(15) + r.sub = label(12) + r.tail = label(12) + msg(r.tail, "setAlignment:", 2) // right + r.hint = label(12) + msg(r.hint, "setAlignment:", 2) + inner := view.Width - 2*view.Padding + msg(r.title, "setFrame:", rect(46, 4, inner-46-250, 20)) + msg(r.sub, "setFrame:", rect(46, 24, inner-46-250, 16)) + msg(r.tail, "setFrame:", rect(inner-250, (view.RowH-4-16)/2, 180, 16)) + msg(r.hint, "setFrame:", rect(inner-64, (view.RowH-4-16)/2, 50, 16)) + for _, sub := range []objc.ID{r.icon, r.title, r.sub, r.tail, r.hint} { + msg(r.box, "addSubview:", sub) + } + msg(r.box, "setHidden:", true) + msg(v.list, "addSubview:", r.box) + v.rows = append(v.rows, r) + } + v.buildFooter() + + // Hover uses a tracking area, which works whether or not the panel is the key window. + hover := msg(objc.ID(hoverClass).Send(sel("alloc")), "init") + const moved, enteredExited, always, inVisibleRect = 0x02, 0x01, 0x80, 0x200 + area := msg(alloc("NSTrackingArea"), "initWithRect:options:owner:userInfo:", nsRect{}, + uint(moved|enteredExited|always|inVisibleRect), hover, objc.ID(0)) + msg(v.content, "addTrackingArea:", area) + + // The launcher sees keys before the text field does. Keys it doesn't handle, such as typing, + // go on to the field. + keys := objc.NewBlock(func(_ objc.Block, e objc.ID) objc.ID { + return guarded("key", e, func() objc.ID { + if msg(e, "window") != v.panel { + return e + } + if v.key(e) { + return 0 + } + return e + }) + }) + msg(class("NSEvent"), "addLocalMonitorForEventsMatchingMask:handler:", uint64(1<<10), keys) + + center := msg(class("NSNotificationCenter"), "defaultCenter") + observe := func(name string, object objc.ID, fn func()) { + b := objc.NewBlock(func(_ objc.Block, _ objc.ID) { guard(name, fn) }) + msg(center, "addObserverForName:object:queue:usingBlock:", nsString(name), object, objc.ID(0), b) + v.blocks = append(v.blocks, b) + } + observe("NSControlTextDidChangeNotification", v.field, func() { + if v.ev.Query != nil { + v.ev.Query(goString(msg(v.field, "stringValue"))) + } + }) + observe("NSWindowDidResignKeyNotification", v.panel, v.resigned) + msg(v.content, "registerForDraggedTypes:", msg(class("NSArray"), "arrayWithObject:", nsString("public.file-url"))) + v.waitTick = objc.NewBlock(func(_ objc.Block, _ objc.ID) { guard("checkButtons", v.checkButtons) }) + observe("NSWindowDidMoveNotification", v.panel, v.moved) + v.blocks = append(v.blocks, keys) +} + +// buildFooter builds the footer line: two slots in a box that is Slide taller above and below, +// so a line that moves in or out stays inside it. +func (v *View) buildFooter() { + v.footer = msg(objc.ID(contentClass).Send(sel("alloc")), "initWithFrame:", rect(18, 0, view.FooterW, 18+2*view.Slide)) + msg(v.content, "addSubview:", v.footer) + for i := range v.slots { + sl := slot{box: msg(objc.ID(contentClass).Send(sel("alloc")), "initWithFrame:", rect(0, view.Slide, view.FooterW, 18))} + msg(sl.box, "setWantsLayer:", true) + sl.spinner = msg(alloc("NSProgressIndicator"), "initWithFrame:", rect(0, 1, view.SpinSize, view.SpinSize)) + msg(sl.spinner, "setStyle:", 1) // spinning + msg(sl.spinner, "setControlSize:", 1) // small + msg(sl.spinner, "setDisplayedWhenStopped:", false) + sl.label = label(12) + msg(sl.box, "addSubview:", sl.spinner) + msg(sl.box, "addSubview:", sl.label) + msg(v.footer, "addSubview:", sl.box) + if i != v.active { + msg(sl.box, "setAlphaValue:", 0.0) + } + v.slots[i] = sl + } + v.fill(v.slots[v.active], v.line) +} + +// fill puts line in sl. A status is also set as the tooltip, because its text may be cut off. +func (v *View) fill(sl slot, line view.Line) { + text, col, left := line.Hints, color("secondaryLabelColor"), 0.0 + switch line.Status.Kind { + case view.StatusLoading: + text, left = line.Status.Text, view.StatusLeft-18 + case view.StatusDone: + text, col = line.Status.Text, color("systemGreenColor") + case view.StatusError: + text, col = line.Status.Text, color("systemRedColor") + } + if left > 0 { + msg(sl.spinner, "startAnimation:", objc.ID(0)) + } else { + msg(sl.spinner, "stopAnimation:", objc.ID(0)) + } + msg(sl.label, "setFrame:", rect(left, 0, view.FooterW-left, 18)) + msg(sl.label, "setStringValue:", nsString(text)) + msg(sl.label, "setTextColor:", col) + tip := "" + if line.Status.Kind != view.StatusNone { + tip = text + } + msg(sl.label, "setToolTip:", nsString(tip)) +} + +// showLine shows the footer line for s. When view.Swaps allows it, the old line moves up and out +// while the new one moves up from below. +func (v *View) showLine(s view.Snapshot) { + line := view.FooterLine(s) + switch { + case line == v.line: + return + case !view.Swaps(v.line, line): + v.fill(v.slots[v.active], line) + v.line = line + return + } + v.line = line + out, in := v.slots[v.active], v.slots[1-v.active] + v.active = 1 - v.active + v.fill(in, line) + msg(in.box, "setAlphaValue:", 0.0) + msg(in.box, "setFrameOrigin:", nsPoint{0, 2 * view.Slide}) + animations := class("NSAnimationContext") + msg(animations, "beginGrouping") + ctx := msg(animations, "currentContext") + msg(ctx, "setDuration:", view.SwapFor.Seconds()) + msg(ctx, "setTimingFunction:", msg(class("CAMediaTimingFunction"), "functionWithName:", nsString("easeOut"))) + msg(msg(out.box, "animator"), "setAlphaValue:", 0.0) + msg(msg(out.box, "animator"), "setFrameOrigin:", nsPoint{0, 0}) + msg(msg(in.box, "animator"), "setAlphaValue:", 1.0) + msg(msg(in.box, "animator"), "setFrameOrigin:", nsPoint{0, view.Slide}) + msg(animations, "endGrouping") +} + +func (v *View) buildStop() { + v.stop = msg(alloc("NSButton"), "initWithFrame:", rect(view.StopLeft, 0, view.StopSize, view.StopSize)) + msg(v.stop, "setBordered:", false) + msg(v.stop, "setTitle:", nsString("")) + msg(v.stop, "setImagePosition:", uint(1)) // image only + if img := v.icon(icons.StopAll); img != 0 { + small := msg(img, "copy") + msg(small, "setSize:", nsSize{14, 14}) + msg(v.stop, "setImage:", small) + } + msg(v.stop, "setWantsLayer:", true) + msg(msg(v.stop, "layer"), "setCornerRadius:", view.StopSize/2) + msg(v.stop, "setTarget:", msg(objc.ID(stopClass).Send(sel("alloc")), "init")) + msg(v.stop, "setAction:", sel("stopAll:")) + v.stopLook(false) + msg(v.content, "addSubview:", v.stop) +} + +func (v *View) stopLook(hover bool) { + if v.stop == 0 { + return + } + v.stopHover = hover + tint, disc, alpha := color("secondaryLabelColor"), color("labelColor"), 0.07 + if v.snap.Running { + tint, disc, alpha = color("systemRedColor"), color("systemRedColor"), 0.16 + } + if hover { + alpha *= 2 + } + msg(v.stop, "setContentTintColor:", tint) + msg(msg(v.stop, "layer"), "setBackgroundColor:", msg(msg(disc, "colorWithAlphaComponent:", alpha), "CGColor")) +} + +func (v *View) Show(at *view.Placement) { + screens := msg(class("NSScreen"), "screens") + if at != nil && onScreen(screens, at.Left+view.Width/2, at.Top-view.QueryH/2) { + v.left, v.top = at.Left, at.Top + } else { + vf := mouseScreen(screens) + dx, dy := view.Centred(vf.Size.W, vf.Size.H, 1) + v.left = vf.Origin.X + dx + v.top = vf.Origin.Y + vf.Size.H - dy // AppKit's y grows upward + } + v.visible = true + // Record the current pointer position, so rows appearing under it don't count as a move and + // don't change the selection. + m := msgPoint(class("NSEvent"), "mouseLocation") + v.hoverX, v.hoverY = m.X, m.Y + v.scrolled = 0 + v.layout() + msg(v.panel, "makeKeyAndOrderFront:", objc.ID(0)) + msg(v.panel, "makeFirstResponder:", v.field) +} + +func (v *View) Hide() { + v.visible = false + v.stopWaiting() + msg(v.panel, "orderOut:", objc.ID(0)) +} + +// resigned handles the panel losing keyboard focus. It reports the blur at once, unless a mouse +// button is down (see View.dragOver). +func (v *View) resigned() { + if !v.visible || v.ev.Blur == nil { + return + } + if objc.Send[uint](class("NSEvent"), sel("pressedMouseButtons")) == 0 { + v.ev.Blur() + return + } + if v.waitTimer == 0 { + v.waitTimer = msg(class("NSTimer"), "timerWithTimeInterval:repeats:block:", 0.05, true, v.waitTick) + // Use the common modes so the timer also runs during a drag session's tracking loop. + msg(msg(class("NSRunLoop"), "mainRunLoop"), "addTimer:forMode:", v.waitTimer, nsString("kCFRunLoopCommonModes")) + } +} + +// checkButtons reports the blur that waited, unless a drop gave the panel focus again. +func (v *View) checkButtons() { + if v.dragOver || objc.Send[uint](class("NSEvent"), sel("pressedMouseButtons")) != 0 { + return + } + v.stopWaiting() + if v.visible && !msgBool(v.panel, "isKeyWindow") && v.ev.Blur != nil { + v.ev.Blur() + } +} + +func (v *View) stopWaiting() { + if v.waitTimer != 0 { + msg(v.waitTimer, "invalidate") + v.waitTimer = 0 + } + v.dragOver = false +} + +// dragCopy is NSDragOperationCopy. Dropped files are copied or moved, depending on what the user +// then picks. dragNone is NSDragOperationNone, which refuses them. +const ( + dragCopy = 1 + dragNone = 0 +) + +func (v *View) dragEntered() uint { + v.dragOver = true + return dragCopy +} + +func (v *View) drop(info objc.ID) bool { + v.dragOver = false + urls := msg(msg(info, "draggingPasteboard"), "readObjectsForClasses:options:", + msg(class("NSArray"), "arrayWithObject:", class("NSURL")), objc.ID(0)) + var paths []string + for i := uint(0); urls != 0 && i < objc.Send[uint](urls, sel("count")); i++ { + if u := msg(urls, "objectAtIndex:", i); msgBool(u, "isFileURL") { + paths = append(paths, goString(msg(u, "path"))) + } + } + if len(paths) == 0 { + return false + } + v.stopWaiting() + msg(v.panel, "makeKeyAndOrderFront:", objc.ID(0)) + msg(v.panel, "makeFirstResponder:", v.field) + if v.ev.Drop != nil { + v.ev.Drop(paths) + } + return true +} + +func (v *View) Visible() bool { return v.visible } + +func (v *View) SetQuery(text string, selectAll bool) { + msg(v.field, "setStringValue:", nsString(text)) + if selectAll { + msg(v.field, "selectText:", objc.ID(0)) + return + } + if ed := msg(v.field, "currentEditor"); ed != 0 { + n := objc.Send[uint](msg(v.field, "stringValue"), sel("length")) + msg(ed, "setSelectedRange:", nsRange{n, 0}) + } +} + +// label translates the view's own labels. Render calls it, so they follow a change of language. +// The panel's title doesn't show, but VoiceOver reads it. +func (v *View) label() { + if lang := i18n.Language(); lang != v.language { + v.language = lang + msg(v.panel, "setTitle:", nsString(i18n.T("Launcher"))) + msg(v.stop, "setToolTip:", nsString(i18n.T("Stop everything (⌘.)"))) + msg(v.stop, "setAccessibilityLabel:", nsString(i18n.T("Stop everything"))) + } +} + +func (v *View) Render(s view.Snapshot) { + v.snap = s + v.label() + msg(v.field, "setPlaceholderString:", nsString(s.Placeholder)) + v.stopLook(v.stopHover) + msg(v.header, "setHidden:", s.Header == "") + msg(v.header, "setStringValue:", nsString(s.Header)) + top := view.RowsTop(s.Header != "") + for i, r := range v.rows { + sec := v.groupLabels[i] + if i >= len(s.Rows) { + msg(r.box, "setHidden:", true) + msg(sec, "setHidden:", true) + continue + } + y := view.RowTop(s, i) - top // relative to the list + x := s.Rows[i] + msg(sec, "setHidden:", x.Group == "") + if x.Group != "" { + msg(sec, "setStringValue:", nsString(x.Group)) + msg(sec, "setFrame:", rect(18, y-view.GroupH+5, view.Width-36, 16)) + } + v.drawRow(r, x, i == s.Selected, y) + } + v.showLine(s) + v.layout() +} + +func (v *View) drawRow(r row, x view.Row, selected bool, y float64) { + msg(r.box, "setHidden:", false) + msg(r.box, "setFrame:", rect(view.Padding, y, view.Width-2*view.Padding, view.RowH-4)) + text, sub, icon := color("labelColor"), color("secondaryLabelColor"), color("labelColor") + if x.Danger { + icon = color("systemRedColor") + } + bg := objc.ID(0) + if selected { + text, sub = color("whiteColor"), msg(color("whiteColor"), "colorWithAlphaComponent:", 0.8) + icon = text + bg = msg(color("controlAccentColor"), "CGColor") + if x.Danger { + bg = msg(color("systemRedColor"), "CGColor") + } + } + msg(msg(r.box, "layer"), "setBackgroundColor:", bg) + as := attributed(x.Title, 15, text, x.Bold) + msg(r.title, "setAttributedStringValue:", as) + msg(as, "release") + inner := view.Width - 2*view.Padding + if x.Subtitle == "" { + msg(r.title, "setFrame:", rect(46, (view.RowH-4-20)/2, inner-46-250, 20)) + } else { + msg(r.title, "setFrame:", rect(46, 4, inner-46-250, 20)) + } + msg(r.sub, "setStringValue:", nsString(x.Subtitle)) + msg(r.sub, "setTextColor:", sub) + msg(r.tail, "setStringValue:", nsString(x.Tail)) + msg(r.tail, "setTextColor:", sub) + msg(r.hint, "setStringValue:", nsString(x.Hint)) + msg(r.hint, "setTextColor:", sub) + msg(r.icon, "setImage:", v.icon(x.Icon)) + msg(r.icon, "setContentTintColor:", icon) +} + +func (v *View) icon(n icons.Name) objc.ID { + if img, ok := v.icons[n]; ok { + return img + } + var img objc.ID + if svg := icons.SVG(n); svg != "" { + img = msg(alloc("NSImage"), "initWithData:", nsData([]byte(svg))) + if img != 0 { + msg(img, "setTemplate:", true) + msg(img, "setSize:", nsSize{view.IconSize, view.IconSize}) + } + } + v.icons[n] = img + return img +} + +func (v *View) layout() { + s := v.snap + h := view.Height(s) + msg(v.list, "setFrame:", rect(0, view.RowsTop(s.Header != ""), view.Width, view.ListH(s))) + foot := view.FooterTop(s) + msg(v.footer, "setFrameOrigin:", nsPoint{18, foot - view.Slide}) + msg(v.stop, "setFrame:", rect(view.StopLeft, view.StopTop(s), view.StopSize, view.StopSize)) + v.settingFrame = true + if v.visible { + msg(v.panel, "setFrame:display:", rect(v.left, v.top-h, view.Width, h), true) + msg(v.panel, "invalidateShadow") + } else { + f := msgRect(v.panel, "frame") + msg(v.panel, "setFrame:display:", rect(f.Origin.X, f.Origin.Y+f.Size.H-h, view.Width, h), false) + } + v.settingFrame = false +} + +func (v *View) moved() { + if !v.visible || v.settingFrame { + return + } + f := msgRect(v.panel, "frame") + v.left, v.top = f.Origin.X, f.Origin.Y+f.Size.H + if v.ev.Moved != nil { + v.ev.Moved(view.Placement{Left: v.left, Top: v.top}) + } +} + +// key returns false to leave the key to the text field. While an input method such as Pinyin or +// Kotoeri is composing, every key goes to the field: Enter commits the candidate, the arrows and +// Tab choose one, and Esc cancels. +func (v *View) key(e objc.ID) bool { + if v.ev.Key == nil { + return false + } + if ed := msg(v.field, "currentEditor"); ed != 0 && msgBool(ed, "hasMarkedText") { + return false + } + code := objc.Send[uint16](e, sel("keyCode")) + flags := objc.Send[uint](e, sel("modifierFlags")) + cmd := flags&(1<<20) != 0 + k := view.KeyEvent{} + switch { + case code == 53: + k.Key = view.KeyEsc + case code == 36 || code == 76: + k.Key = view.KeyEnter + case code == 125: + k.Key = view.KeyDown + case code == 126: + k.Key = view.KeyUp + case code == 48 && flags&(1<<17) == 0: // tab, not shift-tab + k.Key = view.KeyTab + case cmd: + chars := []rune(strings.ToLower(goString(msg(e, "charactersIgnoringModifiers")))) + if len(chars) != 1 { + return false + } + if chars[0] == 'k' { + k.Key = view.KeyActions + } else { + k.Key, k.Char = view.KeyRow, chars[0] + } + default: + return false + } + return v.ev.Key(k) +} + +func (v *View) mouseMoved(e objc.ID) { + if !v.visible { + return + } + if !msgBool(v.panel, "isKeyWindow") { + msg(v.panel, "makeKeyAndOrderFront:", objc.ID(0)) + } + // Only real mouse movement selects a row, so compare screen coordinates. The panel appearing, + // or rows shifting under a still pointer, doesn't move the selection. + m := msgPoint(class("NSEvent"), "mouseLocation") + if m.X == v.hoverX && m.Y == v.hoverY { + return + } + v.hoverX, v.hoverY = m.X, m.Y + p := msgPoint(v.content, "convertPoint:fromView:", msgPoint(e, "locationInWindow"), objc.ID(0)) + if on := view.InStop(p.X, p.Y, v.snap); on != v.stopHover { + v.stopLook(on) + } + if i := v.rowAt(p.Y); i >= 0 && v.ev.Hover != nil { + v.ev.Hover(i) + } +} + +func (v *View) mouseDown(e objc.ID) { + p := msgPoint(v.content, "convertPoint:fromView:", msgPoint(e, "locationInWindow"), objc.ID(0)) + if i := v.rowAt(p.Y); i >= 0 { + if v.ev.Click != nil { + v.ev.Click(i) + } + return + } + msg(v.panel, "performWindowDragWithEvent:", e) +} + +// scrollWheel counts each wheel line as one row, and adds trackpad points up to rows. +func (v *View) scrollWheel(e objc.ID) { + if !v.visible || v.ev.Scroll == nil { + return + } + dy := objc.Send[float64](e, sel("scrollingDeltaY")) + if msgBool(e, "hasPreciseScrollingDeltas") { + dy /= view.RowH + } + // A positive delta moves the content down, which brings the rows above into view. + v.scrolled -= dy + n := int(v.scrolled) + v.scrolled -= float64(n) + if n != 0 { + v.ev.Scroll(n) + } +} + +// rowAt returns the drawn row at y, measured from the panel's top, or -1. +func (v *View) rowAt(y float64) int { return view.RowAt(y, v.snap) } + +// mouseScreen returns the visible frame of the screen that has the mouse. +func mouseScreen(screens objc.ID) nsRect { + m := msgPoint(class("NSEvent"), "mouseLocation") + for i := uint(0); i < objc.Send[uint](screens, sel("count")); i++ { + s := msg(screens, "objectAtIndex:", i) + f := msgRect(s, "frame") + if m.X >= f.Origin.X && m.X < f.Origin.X+f.Size.W && m.Y >= f.Origin.Y && m.Y < f.Origin.Y+f.Size.H { + return msgRect(s, "visibleFrame") + } + } + return msgRect(msg(class("NSScreen"), "mainScreen"), "visibleFrame") +} + +func onScreen(screens objc.ID, x, y float64) bool { + for i := uint(0); i < objc.Send[uint](screens, sel("count")); i++ { + f := msgRect(msg(screens, "objectAtIndex:", i), "visibleFrame") + if x >= f.Origin.X && x < f.Origin.X+f.Size.W && y >= f.Origin.Y && y < f.Origin.Y+f.Size.H { + return true + } + } + return false +} + +// ActivateApp makes the app active. Call it on the main thread while a key press or click from +// the user is being handled. From macOS 14, an app that asks to be activated is only activated at +// that moment (cooperative activation). The panel never activates the app, because it is +// non-activating. +func ActivateApp() { + app := msg(class("NSApplication"), "sharedApplication") + if msgBool(app, "respondsToSelector:", sel("activate")) { + msg(app, "activate") + return + } + msg(app, "activateIgnoringOtherApps:", true) +} diff --git a/app/launcher/view/geometry.go b/app/launcher/view/geometry.go new file mode 100644 index 00000000..f200f4d9 --- /dev/null +++ b/app/launcher/view/geometry.go @@ -0,0 +1,137 @@ +package view + +import "strings" + +// The launcher's geometry, shared by the three views. Sizes are in macOS points, which match +// device-independent pixels on Windows and logical pixels in GTK, so the launcher is the same +// size everywhere. Each view decides for itself how to lay out the contents of a row. +const ( + Width = 700.0 + QueryH = 56.0 // the band the query box sits in + HeaderH = 24.0 // the line above the rows, when there is one + RowH = 48.0 + GroupH = 24.0 // a group's label, above its first row + FooterH = 30.0 // the hints along the bottom + Padding = 8.0 // beside the rows, and below the footer + Radius = 14.0 // the window's corners + IconSize = 20.0 // a row's icon, square + // MaxListH is the most height the rows can take. A longer list is cut off there, and its last + // visible row is drawn only in part. + MaxListH = MaxRows * RowH + // FieldTop is the top of the query box within the query band. The box is 30 tall and FieldW + // wide, starting 18 from the left. + FieldTop = 14.0 + FieldW = Width - 36 + // The stop-everything button is a StopSize square in the bottom right corner, on the footer + // line (see StopTop). + StopSize = 22.0 + StopLeft = Width - 12 - StopSize + // The footer line (see FooterLine) starts 18 from the left and is FooterW wide, ending before + // the stop button. It shows the hints or a status. A loading status starts with the spinner, + // a SpinSize square, and its text starts at StatusLeft. + FooterW = StopLeft - 12 - 18 + SpinSize = 16.0 + StatusLeft = 18 + SpinSize + 6 + // Slide is how far a footer line moves during the swap animation (see SwapFor). The old line + // moves up and out, and the new line moves up from below into its place. + Slide = 8.0 +) + +func RowSpan(r Row) float64 { + if r.Group != "" { + return GroupH + RowH + } + return RowH +} + +func ListH(s Snapshot) float64 { + if s.More { + return MaxListH + } + h := 0.0 + for _, r := range s.Rows { + h += RowSpan(r) + } + return min(h, MaxListH) +} + +func Height(s Snapshot) float64 { + h := QueryH + ListH(s) + FooterH + Padding + if s.Header != "" { + h += HeaderH + } + return h +} + +// FullHeight returns the window height with a full list and no header. +func FullHeight() float64 { return QueryH + MaxListH + FooterH + Padding } + +// RowsTop returns the top of the list, measured from the top of the window. +func RowsTop(header bool) float64 { + if header { + return QueryH + HeaderH + } + return QueryH +} + +// RowTop returns the top of row i, measured from the top of the window. When the row has a group +// label, the row starts below it. A row that starts at ListBottom or lower isn't drawn, and a row +// that ends below ListBottom is cut off there. +func RowTop(s Snapshot, i int) float64 { + y := RowsTop(s.Header != "") + for j := 0; j < i && j < len(s.Rows); j++ { + y += RowSpan(s.Rows[j]) + } + if i < len(s.Rows) && s.Rows[i].Group != "" { + y += GroupH + } + return y +} + +// ListBottom returns the bottom of the list, measured from the top of the window. Anything below +// it is cut off. +func ListBottom(s Snapshot) float64 { return RowsTop(s.Header != "") + ListH(s) } + +// RowAt returns the drawn row at height y, measured from the top of the window, or -1. A group +// label doesn't count as part of its row, and neither does the cut-off part of a row. +func RowAt(y float64, s Snapshot) int { + if y >= ListBottom(s) { + return -1 + } + for i := range s.Rows { + if top := RowTop(s, i); y >= top && y < top+RowH { + return i + } + } + return -1 +} + +// FooterTop returns the top of the footer line, which is 18 tall, measured from the top of the +// window. +func FooterTop(s Snapshot) float64 { return Height(s) - FooterH } + +// StopTop returns the top of the stop-everything button, which is centred on the footer line. +func StopTop(s Snapshot) float64 { return FooterTop(s) + 9 - StopSize/2 } + +// InStop reports whether (x, y), measured from the window's top-left corner, is on the +// stop-everything button. +func InStop(x, y float64, s Snapshot) bool { + top := StopTop(s) + return x >= StopLeft && x < StopLeft+StopSize && y >= top && y < top+StopSize +} + +// Centred returns where to put the window's top-left corner in an area that is w by h, measured +// from the area's top-left corner. The area's units are scale times the geometry's units. The top +// is where a window with every row would be centred, so the window grows downward and never +// jumps. If the area is too short for that, the window goes at the top. +func Centred(w, h, scale float64) (dx, dy float64) { + return (w - Width*scale) / 2, max((h-FullHeight()*scale)/2, 0) +} + +func FooterText(hints []Hint) string { + parts := make([]string, 0, len(hints)) + for _, h := range hints { + parts = append(parts, h.Keys+" "+h.Label) + } + return strings.Join(parts, " ") +} diff --git a/app/launcher/view/geometry_test.go b/app/launcher/view/geometry_test.go new file mode 100644 index 00000000..7ea883cd --- /dev/null +++ b/app/launcher/view/geometry_test.go @@ -0,0 +1,153 @@ +package view + +import "testing" + +func rows(n int) []Row { return make([]Row, n) } + +func TestHeightAndRows(t *testing.T) { + if got := Height(Snapshot{}); got != 94 { + t.Errorf("Height(none) = %v", got) + } + if got := Height(Snapshot{Header: "x", Rows: rows(2)}); got != QueryH+HeaderH+2*RowH+FooterH+Padding { + t.Errorf("Height(2, header) = %v", got) + } + if got := Height(Snapshot{Header: "x", Rows: rows(MaxRows)}); got != 56+24+8*48+30+8 { + t.Errorf("full height %v", got) + } + if FullHeight() != Height(Snapshot{Rows: rows(MaxRows)}) { + t.Errorf("FullHeight %v", FullHeight()) + } + for _, c := range []struct { + y float64 + rows int + header bool + want int + }{ + {10, 3, false, -1}, + {QueryH - 1, 3, false, -1}, + {QueryH, 3, false, 0}, + {QueryH + RowH - 1, 3, false, 0}, + {QueryH + RowH, 3, false, 1}, + {QueryH + 3*RowH, 3, false, -1}, // the footer + {QueryH + 10, 3, true, -1}, // the header line + {QueryH + HeaderH, 3, true, 0}, + } { + s := Snapshot{Rows: rows(c.rows)} + if c.header { + s.Header = "x" + } + if got := RowAt(c.y, s); got != c.want { + t.Errorf("RowAt(%v, %d, %v) = %d, want %d", c.y, c.rows, c.header, got, c.want) + } + } + if RowsTop(false) != QueryH || RowsTop(true) != QueryH+HeaderH { + t.Error("RowsTop") + } + if FieldTop+30 > QueryH || 18+FieldW > Width { + t.Errorf("field at %v, %v wide", FieldTop, FieldW) + } + for _, s := range []Snapshot{{}, {Header: "x", Rows: rows(3)}, {Rows: rows(1), More: true}} { + top := StopTop(s) + if top < ListBottom(s) || top+StopSize > Height(s) || StopLeft+StopSize > Width { + t.Errorf("stop button at %v, %v in %v (rows end %v)", StopLeft, top, Height(s), ListBottom(s)) + } + if !InStop(StopLeft+1, top+1, s) || InStop(StopLeft-1, top+1, s) || InStop(StopLeft+1, top+StopSize, s) { + t.Error("InStop") + } + } +} + +func TestGroupLabels(t *testing.T) { + s := Snapshot{Rows: []Row{{Group: "Active"}, {}, {Group: "Operations"}}} + if got := ListH(s); got != 3*RowH+2*GroupH { + t.Errorf("ListH = %v", got) + } + if RowTop(s, 0) != QueryH+GroupH || RowTop(s, 1) != QueryH+GroupH+RowH || RowTop(s, 2) != QueryH+2*GroupH+2*RowH { + t.Errorf("RowTop: %v %v %v", RowTop(s, 0), RowTop(s, 1), RowTop(s, 2)) + } + for _, c := range []struct { + y float64 + want int + }{ + {QueryH + 1, -1}, // the first label + {QueryH + GroupH, 0}, + {QueryH + GroupH + RowH, 1}, + {QueryH + GroupH + 2*RowH + 1, -1}, // the second label + {QueryH + 2*GroupH + 2*RowH, 2}, + } { + if got := RowAt(c.y, s); got != c.want { + t.Errorf("RowAt(%v) = %d, want %d", c.y, got, c.want) + } + } + // Eight rows and a label: the eighth row is cut off, and the list is MaxListH tall no matter + // what is drawn. + long := Snapshot{Rows: append([]Row{{Group: "Active"}}, rows(7)...), More: true} + if ListH(long) != MaxListH || Height(long) != FullHeight() { + t.Errorf("a longer list: ListH %v, Height %v", ListH(long), Height(long)) + } + last := RowTop(long, 7) + if last >= ListBottom(long) || last+RowH <= ListBottom(long) { + t.Fatalf("the last row at %v, the list ending at %v", last, ListBottom(long)) + } + if RowAt(last+1, long) != 7 || RowAt(ListBottom(long), long) != -1 { + t.Error("the cut row: its part drawn is there, the rest isn't") + } +} + +func TestCentred(t *testing.T) { + full := FullHeight() + for _, c := range []struct { + w, h, scale float64 + dx, dy float64 + }{ + {1920, 1000, 1, (1920 - 700) / 2, (1000 - full) / 2}, + {1920, 1048, 1, 610, (1048 - full) / 2}, + {2560, 1400, 1.5, (2560 - 1050) / 2, (1400 - 1.5*full) / 2}, // 150%: 1050 pixels wide + {1920, 300, 1, 610, 0}, // too short, so at the top + } { + dx, dy := Centred(c.w, c.h, c.scale) + if dx != c.dx || dy != c.dy { + t.Errorf("Centred(%v, %v, %v) = %v, %v; want %v, %v", c.w, c.h, c.scale, dx, dy, c.dx, c.dy) + } + } +} + +func TestFooterText(t *testing.T) { + got := FooterText([]Hint{{Keys: "⏎", Label: "Open"}, {Keys: "Ctrl+K", Label: "Actions"}}) + if got != "⏎ Open Ctrl+K Actions" { + t.Errorf("footer %q", got) + } + if got := FooterText(nil); got != "" { + t.Errorf("no hints: %q", got) + } +} + +func TestFooterLine(t *testing.T) { + hints := Snapshot{Footer: []Hint{{Keys: "⏎", Label: "Open"}}} + working := Snapshot{Footer: hints.Footer, Status: Status{Kind: StatusLoading, Text: "Unmounting…"}} + done := Snapshot{Footer: hints.Footer, Status: Status{Kind: StatusDone, Text: "Unmounted."}} + if l := FooterLine(hints); l.Hints != "⏎ Open" || l.Status.Kind != StatusNone { + t.Errorf("hints: %+v", l) + } + if l := FooterLine(working); l.Hints != "" || l.Status != working.Status { + t.Errorf("a status: %+v", l) + } + other := Snapshot{Footer: []Hint{{Keys: "⏎", Label: "Browse"}}} + for _, c := range []struct { + from, to Snapshot + swaps bool + }{ + {hints, working, true}, + {working, done, true}, + {done, hints, true}, + {hints, other, false}, + {working, working, false}, + } { + if got := Swaps(FooterLine(c.from), FooterLine(c.to)); got != c.swaps { + t.Errorf("Swaps(%+v, %+v) = %v", FooterLine(c.from), FooterLine(c.to), got) + } + } + if StatusLeft+100 > 18+FooterW || 18+FooterW > StopLeft { + t.Errorf("footer line %v wide, status text at %v, stop button at %v", FooterW, StatusLeft, StopLeft) + } +} diff --git a/app/launcher/view/linux/gnome/ensure_linux.go b/app/launcher/view/linux/gnome/ensure_linux.go new file mode 100644 index 00000000..43efd3b8 --- /dev/null +++ b/app/launcher/view/linux/gnome/ensure_linux.go @@ -0,0 +1,185 @@ +//go:build linux + +package gnome + +import ( + "bytes" + "context" + "errors" + "io/fs" + "log/slog" + "os" + "path/filepath" + "slices" + "time" + + "github.com/godbus/dbus/v5" + + "github.com/rclone/rclone-ui/app/platform" +) + +const ( + shellExtensions = platform.GnomeShellExtensions + shellExtensionsPath = dbus.ObjectPath("/org/gnome/Shell/Extensions") +) + +// Ensure installs and enables the extension without asking. GNOME doesn't let an app place its +// own window, so the extension places the launcher's window. The files come from the package +// (deb or rpm) or from the user's copy, which is kept in sync with this build. The shell's D-Bus +// service can only enable an extension that the shell has loaded. The shell loads extensions at +// login, so an extension it hasn't loaded is added to its enabled list for the next login. On a +// desktop other than GNOME, Ensure does nothing. +func Ensure(ctx context.Context, log *slog.Logger, acks Acks) { + ctx, cancel := context.WithTimeout(ctx, time.Minute) + defer cancel() + conn, err := dbus.ConnectSessionBus() + if err != nil { + return + } + defer func() { _ = conn.Close() }() + shell := conn.Object(shellExtensions, shellExtensionsPath) + var info map[string]dbus.Variant + if err := shell.CallWithContext(ctx, shellExtensions+".GetExtensionInfo", 0, UUID).Store(&info); err != nil { + log.Info("the launcher's window is placed by the compositor: no GNOME Shell", "error", err) + return + } + if err := syncUserCopy(log); err != nil { + log.Error("could not install the launcher's GNOME extension", "error", err) + return + } + state := 0 + if v, ok := info["state"]; ok { + state = extensionState(v.Value()) + } + switch { + case state == extensionActive: + acks.Add(ctx, enabledAck) + case acks.Has(ctx, enabledAck): + // It was enabled once already, so if it is off now, the user turned it off. + case state != 0: + var ok bool + if err := shell.CallWithContext(ctx, shellExtensions+".EnableExtension", 0, UUID).Store(&ok); err != nil || !ok { + log.Warn("could not enable the launcher's GNOME extension", "state", state, "error", err) + return + } + log.Info("enabled the launcher's GNOME extension") + acks.Add(ctx, enabledAck) + default: + if err := enableAtLogin(ctx); err != nil { + // This is a Flatpak, or gsettings is missing. The first start after the next login + // enables the extension, because the shell will have loaded it by then. (A Flatpak + // can talk to the shell, because the Flatpak gate requires that on GNOME.) + log.Info("the launcher's GNOME extension is enabled at a later start", "error", err) + return + } + log.Info("the launcher's GNOME extension runs from the next login") + acks.Add(ctx, enabledAck) + } +} + +// syncUserCopy writes or removes the user's copy of the extension, as UserCopy decides. The change +// takes effect at the next login. +func syncUserCopy(log *slog.Logger) error { + dir, err := userDir() + if err != nil { + return err + } + system, user := systemVersion(), versionIn(dir) + switch UserCopy(system, user, Ours()) { + case Write: + return install(dir) + case Remove: + if err := os.RemoveAll(dir); err != nil { + return err + } + log.Info("removed the user's copy of the launcher's GNOME extension: the package's is as new", + "user", user, "package", system) + } + return nil +} + +// systemVersion returns the version of the copy that a package (deb or rpm) installed for every +// user, and that is removed with the package. It returns -1 when there is none. A Flatpak sees its +// runtime's data directories, never the host's. +func systemVersion() int { + dirs := os.Getenv("XDG_DATA_DIRS") + if dirs == "" { + dirs = "/usr/local/share:/usr/share" + } + for _, d := range filepath.SplitList(dirs) { + if v := versionIn(filepath.Join(d, "gnome-shell", "extensions", UUID)); v >= 0 { + return v + } + } + return -1 +} + +// versionIn returns the version of the copy in dir, or -1 when there is none. +func versionIn(dir string) int { + data, err := os.ReadFile(filepath.Join(dir, "metadata.json")) + if err != nil { + return -1 + } + return Version(data) +} + +// userDir returns the folder for the user's copy. Inside a Flatpak, XDG_DATA_HOME points to the +// app's own folder, so ~/.local/share is used instead (the app has access to the home folder). +func userDir() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + base := os.Getenv("XDG_DATA_HOME") + if base == "" || platform.IsFlatpak() { + base = filepath.Join(home, ".local", "share") + } + return filepath.Join(base, "gnome-shell", "extensions", UUID), nil +} + +// install writes the extension's files to dir, skipping files that already match this build's. +func install(dir string) error { + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + return fs.WalkDir(Files, ".", func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + data, err := Files.ReadFile(path) + if err != nil { + return err + } + dst := filepath.Join(dir, path) + if old, err := os.ReadFile(dst); err == nil && bytes.Equal(old, data) { + return nil + } + return os.WriteFile(dst, data, 0o644) + }) +} + +// enableAtLogin adds the extension to GNOME's list of enabled extensions (org.gnome.shell +// enabled-extensions), which the shell reads at login. +func enableAtLogin(ctx context.Context) error { + if platform.IsFlatpak() { + // The sandbox has its own gsettings, separate from the desktop's. Writing to them would + // succeed and change nothing. + return errors.New("a Flatpak's gsettings are its own") + } + // Run the host's gsettings in the host's environment, because an AppImage's schemas aren't + // GNOME's. + get := platform.HostCommand(ctx, "gsettings", "get", "org.gnome.shell", "enabled-extensions") + if get.Err != nil { + return errors.New("no gsettings") + } + out, err := get.Output() + if err != nil { + return err + } + list := parseStrv(string(out)) + if slices.Contains(list, UUID) { + return nil + } + return platform.HostCommand(ctx, "gsettings", "set", "org.gnome.shell", "enabled-extensions", + formatStrv(append(list, UUID))).Run() +} diff --git a/app/launcher/view/linux/gnome/extension.js b/app/launcher/view/linux/gnome/extension.js new file mode 100644 index 00000000..99f784b1 --- /dev/null +++ b/app/launcher/view/linux/gnome/extension.js @@ -0,0 +1,120 @@ +// The Rclone UI launcher's GNOME Shell extension (GNOME 45 and later). +// +// On Wayland, the compositor decides where windows go, and GNOME's compositor doesn't support +// layer-shell, so apps can't place their own windows there. This extension places the launcher +// window. It centres the window horizontally on the monitor with the pointer, with its top where a +// launcher with every row would be centred, so the window grows downward. If the user dragged the +// window, it goes back to where they left it. The window is kept above other windows, shown on +// every workspace and focused. Rclone UI installs the extension (ensure_linux.go in this folder), +// and the view it works with is in app/launcher/view/linux. + +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; + +// Details of the launcher window: its title, the GTK application ids that Rclone UI runs under +// (the same id in a package and in the Flatpak), and its width and full height with every row, +// in its own pixels. They must match app/launcher/view/linux/layout.go, and its tests check that they do. +const TITLE = 'Rclone UI Launcher'; +const APP_IDS = ['org.rclone.ui']; +const WIDTH = 700; +const FULL_HEIGHT = 478; + +export default class RcloneUILauncher extends Extension { + enable() { + // Where the user dragged the launcher: a monitor and the offset from the top-left of its + // work area. null means centre it. + this._dragged = null; + this._waiting = new Map(); // window actor → its signal handlers, until its first frame + this._handlers = [ + global.display.connect('window-created', (_display, window) => this._created(window)), + global.display.connect('grab-op-end', (_display, window) => this._moved(window)), + ]; + } + + disable() { + for (const id of this._handlers) + global.display.disconnect(id); + for (const actor of [...this._waiting.keys()]) + this._forget(actor); + this._handlers = []; + this._dragged = null; + } + + // Reports whether a window is the launcher. It must have the launcher's title and come from + // Rclone UI, according to its GTK application id. The view sets the app's id on the window, + // as GtkApplication does for the app's other windows. Any client can claim any id, but a + // sandboxed client (Flatpak, Snap) can't hide its sandbox's id. So a sandboxed window only + // counts when its sandbox id matches the id it claims. This stops another sandboxed app from + // taking the launcher's place above other windows and getting focus. + _ours(window) { + if (!window || window.get_title() !== TITLE) + return false; + const id = window.get_gtk_application_id(); + if (!APP_IDS.includes(id)) + return false; + const sandboxed = window.get_sandboxed_app_id(); + return !sandboxed || sandboxed === id; + } + + // Each Show creates a new window, because GTK unmaps it on Hide. The window is identified and + // placed at its first frame. By then the client has set its title and application id, which a + // Wayland window may not have when it is created, and the window has its size. GNOME's + // opening animation starts the window transparent, so its first position isn't visible. + _created(window) { + const actor = window.get_compositor_private(); + if (!actor) { + if (this._ours(window)) + this._place(window); + return; + } + this._waiting.set(actor, [ + actor.connect('first-frame', () => { + this._forget(actor); + if (this._ours(window)) + this._place(window); + }), + actor.connect('destroy', () => this._forget(actor)), + ]); + } + + _forget(actor) { + const ids = this._waiting.get(actor); + if (!ids) + return; + this._waiting.delete(actor); + for (const id of ids) + actor.disconnect(id); + } + + _place(window) { + const frame = window.get_frame_rect(); + // The window's pixels per launcher pixel, which is its scale in whichever layout mode + // GNOME uses. + const scale = frame.width > 0 ? frame.width / WIDTH : 1; + let x, y; + if (this._dragged && this._dragged.monitor < global.display.get_n_monitors()) { + const area = Main.layoutManager.getWorkAreaForMonitor(this._dragged.monitor); + x = area.x + this._dragged.x; + y = area.y + this._dragged.y; + } else { + const area = Main.layoutManager.getWorkAreaForMonitor(global.display.get_current_monitor()); + x = area.x + Math.round((area.width - frame.width) / 2); + y = area.y + Math.max(0, Math.round((area.height - FULL_HEIGHT * scale) / 2)); + } + window.move_frame(true, x, y); + window.make_above(); + window.stick(); + Main.activateWindow(window); + } + + // The user dragged the window, so it opens there next time, as long as that monitor is + // still connected. + _moved(window) { + if (!this._ours(window)) + return; + const monitor = window.get_monitor(); + const area = Main.layoutManager.getWorkAreaForMonitor(monitor); + const frame = window.get_frame_rect(); + this._dragged = {monitor, x: frame.x - area.x, y: frame.y - area.y}; + } +} diff --git a/app/launcher/view/linux/gnome/gnome.go b/app/launcher/view/linux/gnome/gnome.go new file mode 100644 index 00000000..0ca7bddb --- /dev/null +++ b/app/launcher/view/linux/gnome/gnome.go @@ -0,0 +1,68 @@ +// Package gnome holds the files of the launcher's GNOME Shell extension (extension.js). The +// extension places the launcher window on GNOME, where apps can't place their own windows. The +// files are embedded so that every package of the app (deb, rpm, AppImage, Flatpak) can install +// the extension for the user. Ensure installs and enables it once the core is ready. +package gnome + +import ( + "embed" + "encoding/json" +) + +// UUID is the extension's UUID, as set in metadata.json. +const UUID = "launcher@rclone.org" + +// Files holds the extension's files under their file names. They are installed in +// ~/.local/share/gnome-shell/extensions//. +// +//go:embed metadata.json extension.js +var Files embed.FS + +// Version returns the "version" field from a copy of the extension's metadata.json. The version +// goes up with every change to the files. It returns 0 for metadata without a version, or that +// can't be parsed. +func Version(metadata []byte) int { + var m struct { + Version int `json:"version"` + } + if json.Unmarshal(metadata, &m) != nil { + return 0 + } + return m.Version +} + +// Ours returns the version of the copy embedded in this build. +func Ours() int { + data, _ := Files.ReadFile("metadata.json") + return Version(data) +} + +// Action is what to do with the user's copy of the extension (see UserCopy). +type Action int + +const ( + // Keep leaves the user's copy as it is, or leaves it absent. + Keep Action = iota + // Write replaces the user's copy with this build's, writing the files that differ. + Write + // Remove deletes the user's copy, so that the package's copy runs. + Remove +) + +// UserCopy decides what to do with the user's copy of the extension. It takes the versions of the +// copy a package installed for all users (system), the user's copy (user) and this build's copy +// (ours). A version of -1 means that copy isn't installed. GNOME runs the user's copy instead of +// the package's, so the user's copy should only exist while it is the newer one. The result is +// that the newer of the package's and this build's copies runs, and a user copy left by a newer +// build is kept. +func UserCopy(system, user, ours int) Action { + switch { + case system >= ours && user >= 0 && user <= system: + return Remove // it would hide the package's copy, which is at least as new + case system >= ours: + return Keep // no user copy, or one from a newer build + case user <= ours: + return Write + } + return Keep // a copy from a newer build +} diff --git a/app/launcher/view/linux/gnome/gnome_test.go b/app/launcher/view/linux/gnome/gnome_test.go new file mode 100644 index 00000000..e6ee4680 --- /dev/null +++ b/app/launcher/view/linux/gnome/gnome_test.go @@ -0,0 +1,67 @@ +package gnome + +import ( + "encoding/json" + "testing" +) + +// TestMetadata checks that the extension's metadata parses, has the right UUID, lists the GNOME +// versions it runs on, and has a version so that a newer copy can replace an older one. +func TestMetadata(t *testing.T) { + raw, err := Files.ReadFile("metadata.json") + if err != nil { + t.Fatal(err) + } + var m struct { + UUID string `json:"uuid"` + Name string `json:"name"` + Version []string `json:"shell-version"` + } + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + if m.UUID != UUID || m.Name == "" || len(m.Version) == 0 { + t.Fatalf("metadata %+v", m) + } + if Ours() < 1 { + t.Fatalf("version %d", Ours()) + } + if _, err := Files.ReadFile("extension.js"); err != nil { + t.Fatal(err) + } +} + +func TestVersion(t *testing.T) { + for in, want := range map[string]int{`{"version": 3}`: 3, `{}`: 0, `{"version": "x"}`: 0, `not json`: 0} { + if got := Version([]byte(in)); got != want { + t.Errorf("Version(%s) = %d, want %d", in, got, want) + } + } +} + +// TestUserCopy checks that the user's copy is only kept while it is newer than the package's, and +// that the newer of the package's and this build's copies runs. +func TestUserCopy(t *testing.T) { + const none = -1 + for _, c := range []struct { + system, user, ours int + want Action + }{ + {none, none, 2, Write}, // no package, so install this build's copy + {none, 1, 2, Write}, // an older copy is updated + {none, 2, 2, Write}, // the same version, with its files checked + {none, 3, 2, Keep}, // a copy from a newer build + {2, none, 2, Keep}, // the package's copy runs + {2, 0, 2, Remove}, // a stale copy hiding the package's copy + {3, 2, 2, Remove}, // the package's copy is newer + {2, 2, 2, Remove}, // the same version as the package's, so remove it + {2, 3, 2, Keep}, // a copy from a newer build + {1, none, 2, Write}, // an older package, so install this build's copy + {1, 1, 2, Write}, // updated + {0, none, 2, Write}, // a package from before versions + } { + if got := UserCopy(c.system, c.user, c.ours); got != c.want { + t.Errorf("UserCopy(%d, %d, %d) = %d, want %d", c.system, c.user, c.ours, got, c.want) + } + } +} diff --git a/app/launcher/view/linux/gnome/metadata.json b/app/launcher/view/linux/gnome/metadata.json new file mode 100644 index 00000000..89515597 --- /dev/null +++ b/app/launcher/view/linux/gnome/metadata.json @@ -0,0 +1,8 @@ +{ + "uuid": "launcher@rclone.org", + "name": "Rclone UI Launcher", + "description": "Places Rclone UI's launcher on the screen, keeps it above the other windows and gives it the focus, which GNOME lets no app do for itself.", + "version": 1, + "shell-version": ["45", "46", "47", "48", "49", "50", "51"], + "url": "https://github.com/rclone/rclone-ui" +} diff --git a/app/launcher/view/linux/gnome/shell.go b/app/launcher/view/linux/gnome/shell.go new file mode 100644 index 00000000..46e2b52b --- /dev/null +++ b/app/launcher/view/linux/gnome/shell.go @@ -0,0 +1,67 @@ +package gnome + +import ( + "context" + "strings" +) + +// Acks reads and records the acknowledgements that the app keeps in the pages' +// "acknowledgements" pref. Ensure records one once the extension has been enabled, so that it +// enables the extension only once. If the user turns it off afterwards, that choice is respected. +type Acks struct { + // Has reports whether key was recorded. It returns true when the list can't be read. + Has func(ctx context.Context, key string) bool + Add func(ctx context.Context, key string) +} + +const enabledAck = "gnomeLauncherExtension" + +// These helpers parse GNOME's replies for Ensure (see ensure_linux.go). They live in their own +// file so that their tests run on any OS. + +// GNOME Shell's extension states (its ExtensionState), as GetExtensionInfo reports them. +const ( + extensionActive = 1 + extensionInactive = 2 +) + +// extensionState reads the "state" that GetExtensionInfo returns. It is a double, because the +// shell's JavaScript sends numbers that way. It returns 0 when there is no state, which means the +// shell hasn't loaded the extension. +func extensionState(v any) int { + switch n := v.(type) { + case float64: + return int(n) + case int32: + return int(n) + case uint32: + return int(n) + case int64: + return int(n) + } + return 0 +} + +// parseStrv parses a GSettings string list in the form gsettings prints it: ['a', 'b'], or @as [] +// when empty. +func parseStrv(s string) []string { + s = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "@as")) + s = strings.TrimSuffix(strings.TrimPrefix(s, "["), "]") + var out []string + for item := range strings.SplitSeq(s, ",") { + item = strings.TrimSpace(item) + if len(item) >= 2 && (item[0] == '\'' || item[0] == '"') && item[len(item)-1] == item[0] { + out = append(out, item[1:len(item)-1]) + } + } + return out +} + +// formatStrv writes a string list for gsettings set. Extension UUIDs have no quotes in them. +func formatStrv(list []string) string { + quoted := make([]string, len(list)) + for i, s := range list { + quoted[i] = "'" + s + "'" + } + return "[" + strings.Join(quoted, ", ") + "]" +} diff --git a/app/launcher/view/linux/gnome/shell_test.go b/app/launcher/view/linux/gnome/shell_test.go new file mode 100644 index 00000000..dab1945a --- /dev/null +++ b/app/launcher/view/linux/gnome/shell_test.go @@ -0,0 +1,33 @@ +package gnome + +import ( + "slices" + "testing" +) + +func TestStrv(t *testing.T) { + for _, c := range []struct { + in string + want []string + }{ + {"@as []\n", nil}, + {"['ding@rastersoft.com', 'ubuntu-dock@ubuntu.com']\n", []string{"ding@rastersoft.com", "ubuntu-dock@ubuntu.com"}}, + {"['one@x']", []string{"one@x"}}, + } { + if got := parseStrv(c.in); !slices.Equal(got, c.want) { + t.Errorf("%q: got %q", c.in, got) + } + } + list := []string{"a@b", "launcher@rclone.org"} + if got := parseStrv(formatStrv(list)); !slices.Equal(got, list) { + t.Errorf("round trip: %q", got) + } +} + +// TestExtensionState checks that the state GNOME sends as a double is read, and that an extension +// the shell hasn't loaded has no state. +func TestExtensionState(t *testing.T) { + if extensionState(float64(1)) != extensionActive || extensionState(uint32(2)) != extensionInactive || extensionState(nil) != 0 { + t.Fatal("states") + } +} diff --git a/app/launcher/view/linux/layout.go b/app/launcher/view/linux/layout.go new file mode 100644 index 00000000..d676139d --- /dev/null +++ b/app/launcher/view/linux/layout.go @@ -0,0 +1,24 @@ +package linux + +// The view's arithmetic, kept apart from GTK so that it is tested on every platform. + +import ( + "math" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +// topMargin returns the distance from the top of a monitor that is h tall to a centred layer +// surface. It is where a window with every row would be centred, so the window grows downward +// and never jumps. +func topMargin(h int32) int { + _, dy := view.Centred(0, float64(h), 1) + return int(dy) +} + +// dragMargins returns the new margins of a layer surface when the pointer has moved by (dx, dy) +// since the button was pressed. The margins move by the same amount, but never past the +// monitor's top or left edge. +func dragMargins(left, top int, dx, dy float64) (int, int) { + return max(left+int(math.Round(dx)), 0), max(top+int(math.Round(dy)), 0) +} diff --git a/app/launcher/view/linux/link_linux.go b/app/launcher/view/linux/link_linux.go new file mode 100644 index 00000000..91cdc6e4 --- /dev/null +++ b/app/launcher/view/linux/link_linux.go @@ -0,0 +1,19 @@ +//go:build linux && cgo + +package linux + +// The app links gtk4-layer-shell, so the dynamic loader loads it with the app, ahead of +// libwayland-client, which GTK loads. The library stands in for some of libwayland's calls, and +// that only works when it is loaded first (see its linking.md). So it can't be loaded at run time +// with dlopen, as the rest of the launcher's libraries are. The calls themselves go through purego +// (platform_linux.go), which finds the library already loaded. The variable below refers to one of +// its functions, so the linker keeps the library even when it drops unused ones (--as-needed). +// CI checks the order of the binary's libraries. + +/* +#cgo pkg-config: gtk4-layer-shell-0 +#include + +void *rcui_layer_shell_link = (void *)gtk_layer_is_supported; +*/ +import "C" diff --git a/app/launcher/view/linux/platform_linux.go b/app/launcher/view/linux/platform_linux.go new file mode 100644 index 00000000..02da39d8 --- /dev/null +++ b/app/launcher/view/linux/platform_linux.go @@ -0,0 +1,581 @@ +//go:build linux + +package linux + +// This file places the launcher's window and gives it the keyboard. It calls GTK 4, GDK's X11 +// and Wayland backends, Xlib and gtk4-layer-shell through purego. These are libraries that the +// app has already loaded, so dlopen returns them rather than loading second copies. In GTK 4, +// GDK is part of libgtk-4. Each function is declared with its C signature beside it. A gboolean +// result is read as an int32, because it is a C int. + +import ( + "errors" + "fmt" + "sync" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +// Enum values from gtk4-layer-shell. +const ( + layerOverlay = 3 // GtkLayerShellLayer, above full-screen windows + edgeLeft = 0 // GtkLayerShellEdge + edgeTop = 2 + keyboardExclusive = 1 // GtkLayerShellKeyboardMode + keyboardOnDemand = 2 // layer-shell protocol 4 and later +) + +// Values from Xlib. +const ( + xaAtom = 4 // XA_ATOM + propModeReplace = 0 + xButtonsMask = 1<<8 | 1<<9 | 1<<10 // Button1Mask to Button3Mask + allDesktops = 0xFFFFFFFF // the _NET_WM_DESKTOP of a window on every workspace +) + +// namespace is the layer surface's namespace, which compositors use in their rules. +const namespace = "rclone-ui-launcher" + +// rect is a GdkRectangle, such as a monitor's work area. +type rect struct{ X, Y, W, H int32 } + +func (r rect) contains(x, y float64) bool { + return x >= float64(r.X) && x < float64(r.X+r.W) && y >= float64(r.Y) && y < float64(r.Y+r.H) +} + +// GTK 4 and GLib +var ( + gdkDisplayGetDefault func() uintptr // GdkDisplay *gdk_display_get_default (void) + gTypeNameFromInstance func(instance uintptr) string // const gchar *g_type_name_from_instance (GTypeInstance*) + gObjectRef func(obj uintptr) uintptr // gpointer g_object_ref (gpointer) + gObjectUnref func(obj uintptr) // void g_object_unref (gpointer) + gtkWidgetRealize func(w uintptr) // void gtk_widget_realize (GtkWidget*) + gtkWidgetGetRealized func(w uintptr) int32 // gboolean gtk_widget_get_realized (GtkWidget*) + gtkWidgetGetMapped func(w uintptr) int32 // gboolean gtk_widget_get_mapped (GtkWidget*) + gtkWidgetQueueDraw func(w uintptr) // void gtk_widget_queue_draw (GtkWidget*); a commit applies layer changes + gtkNativeGetSurface func(native uintptr) uintptr // GdkSurface *gtk_native_get_surface (GtkNative*) + gtkWindowPresent func(w uintptr) // void gtk_window_present (GtkWindow*) + gtkWindowPresentWithTime func(w uintptr, t uint32) // void gtk_window_present_with_time (GtkWindow*, guint32) + gtkWindowSetStartupID func(w uintptr, id string) // void gtk_window_set_startup_id (GtkWindow*, const char*) + gtkWindowSetTitle func(w uintptr, title string) // void gtk_window_set_title (GtkWindow*, const char*) + gdkDisplayGetMonitors func(d uintptr) uintptr // GListModel *gdk_display_get_monitors (GdkDisplay*) + gListModelGetNItems func(list uintptr) uint32 // guint g_list_model_get_n_items (GListModel*) + gListModelGetItem func(list uintptr, i uint32) uintptr // gpointer g_list_model_get_item (GListModel*, guint), a new reference + gdkMonitorGetGeometry func(m uintptr, r *rect) // void gdk_monitor_get_geometry (GdkMonitor*, GdkRectangle*) + gdkMonitorIsValid func(m uintptr) int32 // gboolean gdk_monitor_is_valid (GdkMonitor*) + gdkDisplayMonitorAtSurface func(d, s uintptr) uintptr // GdkMonitor *gdk_display_get_monitor_at_surface (GdkDisplay*, GdkSurface*) +) + +// GDK's X11 backend and Xlib +var ( + gdkX11MonitorGetWorkarea func(m uintptr, r *rect) // void gdk_x11_monitor_get_workarea (GdkMonitor*, GdkRectangle*) + gdkX11DisplayGetXDisplay func(d uintptr) uintptr // Display *gdk_x11_display_get_xdisplay (GdkDisplay*) + gdkX11SurfaceGetXID func(s uintptr) uintptr // Window gdk_x11_surface_get_xid (GdkSurface*) + gdkX11GetServerTime func(s uintptr) uint32 // guint32 gdk_x11_get_server_time (GdkSurface*) + gdkX11SetSkipTaskbar func(s uintptr, on bool) // void gdk_x11_surface_set_skip_taskbar_hint (GdkSurface*, gboolean) + gdkX11SetSkipPager func(s uintptr, on bool) // void gdk_x11_surface_set_skip_pager_hint (GdkSurface*, gboolean) + gdkX11MoveToDesktop func(s uintptr, d uint32) // void gdk_x11_surface_move_to_desktop (GdkSurface*, guint32) + xDefaultRootWindow func(dpy uintptr) uintptr // Window XDefaultRootWindow (Display*) + // Bool XQueryPointer (Display*, Window, Window *root, Window *child, int *root_x, int *root_y, + // int *win_x, int *win_y, unsigned int *mask) + xQueryPointer func(dpy, w uintptr, root, child *uintptr, rootX, rootY, winX, winY *int32, mask *uint32) int32 + xInternAtom func(dpy uintptr, name string, onlyIfExists bool) uintptr // Atom XInternAtom (Display*, const char*, Bool) + // int XChangeProperty (Display*, Window, Atom property, Atom type, int format, int mode, + // const unsigned char *data, int nelements) + xChangeProperty func(dpy, w, property, kind uintptr, format, mode int32, data unsafe.Pointer, n int32) int32 + xFlush func(dpy uintptr) int32 // int XFlush (Display*) +) + +// gtk4-layer-shell +var ( + layerIsSupported func() int32 // gboolean gtk_layer_is_supported (void) + layerProtocolVersion func() uint32 // guint gtk_layer_get_protocol_version (void) + layerInitForWindow func(w uintptr) // void gtk_layer_init_for_window (GtkWindow*) + layerSetNamespace func(w uintptr, ns string) // void gtk_layer_set_namespace (GtkWindow*, const char*) + layerSetLayer func(w uintptr, layer int32) // void gtk_layer_set_layer (GtkWindow*, GtkLayerShellLayer) + layerSetMonitor func(w, monitor uintptr) // void gtk_layer_set_monitor (GtkWindow*, GdkMonitor*) + layerSetAnchor func(w uintptr, edge int32, on bool) // void gtk_layer_set_anchor (GtkWindow*, GtkLayerShellEdge, gboolean) + layerSetMargin func(w uintptr, edge, size int32) // void gtk_layer_set_margin (GtkWindow*, GtkLayerShellEdge, int) + layerSetKeyboardMode func(w uintptr, mode int32) // void gtk_layer_set_keyboard_mode (GtkWindow*, GtkLayerShellKeyboardMode) +) + +// The libraries, bound once. layerBound reports whether gtk4-layer-shell was found. The app links +// it (link_linux.go), so only a build without cgo, which is for development, can lack it. x11Bound +// reports whether Xlib was found. +var ( + bindOnce sync.Once + bindErr error + layerBound bool + x11Bound bool +) + +func bind() error { + bindOnce.Do(func() { bindErr = bindAll() }) + return bindErr +} + +func bindAll() (err error) { + defer func() { + if r := recover(); r != nil { // purego panics when a symbol is missing + err = fmt.Errorf("GTK 4 lacks a function the launcher needs: %v", r) + } + }() + open := func(name string) (uintptr, error) { + h, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + return 0, fmt.Errorf("the launcher can't load %s: %w", name, err) + } + return h, nil + } + gtk, err := open("libgtk-4.so.1") + if err != nil { + return err + } + gobject, err := open("libgobject-2.0.so.0") + if err != nil { + return err + } + gio, err := open("libgio-2.0.so.0") + if err != nil { + return err + } + bind := func(fn any, lib uintptr, name string) { purego.RegisterLibFunc(fn, lib, name) } + bind(&gdkDisplayGetDefault, gtk, "gdk_display_get_default") + bind(&gTypeNameFromInstance, gobject, "g_type_name_from_instance") + bind(&gObjectRef, gobject, "g_object_ref") + bind(&gObjectUnref, gobject, "g_object_unref") + bind(>kWidgetRealize, gtk, "gtk_widget_realize") + bind(>kWidgetGetRealized, gtk, "gtk_widget_get_realized") + bind(>kWidgetGetMapped, gtk, "gtk_widget_get_mapped") + bind(>kWidgetQueueDraw, gtk, "gtk_widget_queue_draw") + bind(>kNativeGetSurface, gtk, "gtk_native_get_surface") + bind(>kWindowPresent, gtk, "gtk_window_present") + bind(>kWindowPresentWithTime, gtk, "gtk_window_present_with_time") + bind(>kWindowSetStartupID, gtk, "gtk_window_set_startup_id") + bind(>kWindowSetTitle, gtk, "gtk_window_set_title") + bind(&gdkDisplayGetMonitors, gtk, "gdk_display_get_monitors") + bind(&gListModelGetNItems, gio, "g_list_model_get_n_items") + bind(&gListModelGetItem, gio, "g_list_model_get_item") + bind(&gdkMonitorGetGeometry, gtk, "gdk_monitor_get_geometry") + bind(&gdkMonitorIsValid, gtk, "gdk_monitor_is_valid") + bind(&gdkDisplayMonitorAtSurface, gtk, "gdk_display_get_monitor_at_surface") + // GTK is built with its X11 backend almost everywhere. Without it, or without Xlib, the + // launcher works on Wayland only. + if x11, err := purego.Dlopen("libX11.so.6", purego.RTLD_NOW|purego.RTLD_GLOBAL); err == nil { + x11Bound = bindX11(gtk, x11) + } + if lib, err := purego.Dlopen("libgtk4-layer-shell.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL); err == nil { + bind(&layerIsSupported, lib, "gtk_layer_is_supported") + bind(&layerProtocolVersion, lib, "gtk_layer_get_protocol_version") + bind(&layerInitForWindow, lib, "gtk_layer_init_for_window") + bind(&layerSetNamespace, lib, "gtk_layer_set_namespace") + bind(&layerSetLayer, lib, "gtk_layer_set_layer") + bind(&layerSetMonitor, lib, "gtk_layer_set_monitor") + bind(&layerSetAnchor, lib, "gtk_layer_set_anchor") + bind(&layerSetMargin, lib, "gtk_layer_set_margin") + bind(&layerSetKeyboardMode, lib, "gtk_layer_set_keyboard_mode") + layerBound = true + } + return nil +} + +func bindX11(gtk, x11 uintptr) (ok bool) { + defer func() { + if recover() != nil { + ok = false + } + }() + purego.RegisterLibFunc(&gdkX11MonitorGetWorkarea, gtk, "gdk_x11_monitor_get_workarea") + purego.RegisterLibFunc(&gdkX11DisplayGetXDisplay, gtk, "gdk_x11_display_get_xdisplay") + purego.RegisterLibFunc(&gdkX11SurfaceGetXID, gtk, "gdk_x11_surface_get_xid") + purego.RegisterLibFunc(&gdkX11GetServerTime, gtk, "gdk_x11_get_server_time") + purego.RegisterLibFunc(&gdkX11SetSkipTaskbar, gtk, "gdk_x11_surface_set_skip_taskbar_hint") + purego.RegisterLibFunc(&gdkX11SetSkipPager, gtk, "gdk_x11_surface_set_skip_pager_hint") + purego.RegisterLibFunc(&gdkX11MoveToDesktop, gtk, "gdk_x11_surface_move_to_desktop") + purego.RegisterLibFunc(&xDefaultRootWindow, x11, "XDefaultRootWindow") + purego.RegisterLibFunc(&xQueryPointer, x11, "XQueryPointer") + purego.RegisterLibFunc(&xInternAtom, x11, "XInternAtom") + purego.RegisterLibFunc(&xChangeProperty, x11, "XChangeProperty") + purego.RegisterLibFunc(&xFlush, x11, "XFlush") + return true +} + +type platform struct { + win *application.WebviewWindow + window uintptr // the GtkWindow + display uintptr // the GdkDisplay + mode Mode + + // left and top are the window's top-left corner: where the view put an X11 window, or a + // layer surface's margins. + left, top int + + // A layer surface is centred on the monitor that the compositor chooses, until the user drags + // it. From then on it stays on the monitor it was dragged on (placed, which holds a + // reference), at its margins. monitorH is the height of the monitor that it was last centred + // on, and dragFrom is where the pointer pressed for a drag. + placed uintptr + monitorH int32 + dragFromX, dragFromY float64 +} + +// NewPlatform returns the platform of win, the launcher's window, which must be hidden and never +// shown yet. It decides how the window is shown. On a Wayland compositor that supports +// layer-shell, it makes the window a layer surface. That must happen before GTK realizes the +// window, because the surface is created then. It must run on the main thread. +func NewPlatform(win *application.WebviewWindow) (Platform, error) { + if err := bind(); err != nil { + return nil, err + } + p := &platform{win: win, window: uintptr(win.NativeWindow()), display: gdkDisplayGetDefault()} + if p.window == 0 || p.display == 0 { + return nil, errors.New("the launcher's window has no GTK window or display") + } + // Wails gives a frameless window no title, and the GNOME extension recognises the launcher by + // its title. + gtkWindowSetTitle(p.window, Title) + switch kind := gTypeNameFromInstance(p.display); kind { + case "GdkWaylandDisplay": + p.mode = ModeWayland + // gtk_layer_is_supported asks the compositor, so the display must be open, which it is. + if layerBound && layerIsSupported() != 0 && gtkWidgetGetRealized(p.window) == 0 { + p.mode = ModeLayer + // The surface goes above full-screen windows, with its top edge anchored. It is + // centred horizontally, or placed from the left once dragged, and it takes the + // keyboard when shown. + layerInitForWindow(p.window) + layerSetNamespace(p.window, namespace) + layerSetLayer(p.window, layerOverlay) + layerSetAnchor(p.window, edgeTop, true) + layerSetKeyboardMode(p.window, keyboardExclusive) + } + case "GdkX11Display": + if !x11Bound { + return nil, errors.New("the launcher can't use X11: GTK lacks its X11 backend, or Xlib is missing") + } + p.mode = ModeX11 + // The window needs its X window before it is shown, for the hints that X11 window + // managers read when it maps (see hints). + gtkWidgetRealize(p.window) + default: + return nil, fmt.Errorf("the launcher doesn't support GTK's %s", kind) + } + return p, nil +} + +func (p *platform) Mode() Mode { return p.mode } + +func (p *platform) BeforeShow(at *view.Placement, token string) { + switch p.mode { + case ModeX11: + px, py := p.pointer() + if at != nil && p.onScreen(at.Left+view.Width/2, at.Top+view.QueryH/2) { + p.left, p.top = int(at.Left), int(at.Top) + } else { + wa := p.workArea(px, py) + dx, dy := view.Centred(float64(wa.W), float64(wa.H), 1) + p.left, p.top = int(wa.X)+int(dx), int(wa.Y)+int(dy) + } + p.hints() + p.win.SetPosition(p.left, p.top) + case ModeLayer: + p.placeLayer(at) + case ModeWayland: + if token != "" { + // GTK activates the window with the token (xdg-activation). The compositor gives the + // keyboard to a window that presents the token from the user's own key press. + gtkWindowSetStartupID(p.window, token) + } + } +} + +func (p *platform) AfterShow() { + switch p.mode { + case ModeX11: + // Set the position again, because some window managers place a window when it maps. Then + // present the window with the X server's current time. The shortcut arrives from outside + // GTK, so GTK has no event time to use, and a window manager refuses the keyboard to a + // request that is older than the user's last action. + p.win.SetPosition(p.left, p.top) + if s := gtkNativeGetSurface(p.window); s != 0 { + gdkX11MoveToDesktop(s, allDesktops) + gtkWindowPresentWithTime(p.window, gdkX11GetServerTime(s)) + return + } + case ModeLayer: + p.fitLayer() + } + gtkWindowPresent(p.window) +} + +func (p *platform) Resized(visible bool) { + if visible && p.mode == ModeX11 { + p.win.SetPosition(p.left, p.top) + } +} + +// Focused switches a layer surface's keyboard mode to on-demand where the protocol allows it +// (version 4), once the surface has the keyboard. A click on another window can then take the +// keyboard, and the launcher hides when it loses it, as it does everywhere else. The mode is +// exclusive until then, so the surface gets the keyboard when it is shown. +func (p *platform) Focused() { + if p.mode != ModeLayer { + return + } + p.fitLayer() + if layerProtocolVersion() >= 4 { + layerSetKeyboardMode(p.window, keyboardOnDemand) + gtkWidgetQueueDraw(p.window) + } +} + +func (p *platform) Held() bool { + if p.mode != ModeX11 { + return false + } + _, _, mask, ok := p.queryPointer() + return ok && mask&xButtonsMask != 0 +} + +func (p *platform) Moved() (view.Placement, bool) { + if p.mode != ModeX11 { + return view.Placement{}, false // Wayland doesn't say where windows are + } + x, y := p.win.Position() + if x == p.left && y == p.top { + return view.Placement{}, false // the view moved it + } + p.left, p.top = x, y + return view.Placement{Left: float64(x), Top: float64(y)}, true +} + +// DragStart starts moving a layer surface. From now on the surface is placed by its left and top +// margins on its current monitor. While it is shown, only its anchor and margins change. The +// monitor is set the next time it is shown (see setMonitor), and it stays on that monitor from +// then on. +func (p *platform) DragStart(x, y float64) { + p.dragFromX, p.dragFromY = x, y + if p.placed != 0 { + return + } + m := p.monitorOfWindow() + if m == 0 { + return + } + var g rect + gdkMonitorGetGeometry(m, &g) + p.placed = gObjectRef(m) + dx, _ := view.Centred(float64(g.W), float64(g.H), 1) + p.left = int(dx) // where centring placed it + layerSetAnchor(p.window, edgeLeft, true) + layerSetMargin(p.window, edgeLeft, int32(p.left)) +} + +// DragTo moves the surface by the same distance as the pointer has moved from where it was +// pressed in the window. The compositor moves the surface a moment later, so a move reported in +// between is still measured from the old position. The moves that follow make up for it. +func (p *platform) DragTo(x, y float64) { + if p.placed == 0 { + return + } + left, top := dragMargins(p.left, p.top, x-p.dragFromX, y-p.dragFromY) + if left == p.left && top == p.top { + return + } + p.left, p.top = left, top + layerSetMargin(p.window, edgeLeft, int32(left)) + layerSetMargin(p.window, edgeTop, int32(top)) + gtkWidgetQueueDraw(p.window) +} + +func (p *platform) DragEnd() (view.Placement, bool) { + if p.placed == 0 { + return view.Placement{}, false + } + return view.Placement{Left: float64(p.left), Top: float64(p.top)}, true +} + +// placeLayer sets where the layer surface appears. If the user dragged it and the monitor they +// dragged it to is still connected, it goes back there. Otherwise it is centred horizontally on +// the monitor that the compositor chooses, which is the one in use, with its top where a window +// with every row would be centred. That monitor isn't known until the surface maps, so the height +// of the last monitor is used until then, and fitLayer corrects it. +func (p *platform) placeLayer(at *view.Placement) { + if at != nil && p.placed != 0 && gdkMonitorIsValid(p.placed) != 0 { + p.left, p.top = int(at.Left), int(at.Top) + p.setMonitor(p.placed) + layerSetAnchor(p.window, edgeLeft, true) + layerSetMargin(p.window, edgeLeft, int32(p.left)) + } else { + p.unplace() + if p.monitorH == 0 { + if m := p.firstMonitor(); m != 0 { + var g rect + gdkMonitorGetGeometry(m, &g) + p.monitorH = g.H + gObjectUnref(m) + } + } + p.top = topMargin(p.monitorH) + } + layerSetMargin(p.window, edgeTop, int32(p.top)) + layerSetKeyboardMode(p.window, keyboardExclusive) +} + +// unplace centres the layer surface again, on the monitor that the compositor chooses. +func (p *platform) unplace() { + if p.placed != 0 { + gObjectUnref(p.placed) + p.placed = 0 + } + p.setMonitor(0) + layerSetAnchor(p.window, edgeLeft, false) + layerSetMargin(p.window, edgeLeft, 0) +} + +// setMonitor puts the layer surface on monitor m, or lets the compositor choose when m is 0. It +// only does this while the surface is hidden, which is when the view places it. +// gtk4-layer-shell moves a mapped surface to another monitor by remapping it, which flickers and +// takes the pointer away from a drag in progress. A visible surface stays where it is until it is +// next shown. +func (p *platform) setMonitor(m uintptr) { + if gtkWidgetGetMapped(p.window) == 0 { + layerSetMonitor(p.window, m) + } +} + +// fitLayer corrects the top margin of a centred layer surface for the monitor it appeared on. +func (p *platform) fitLayer() { + if p.placed != 0 { + return + } + m := p.monitorOfWindow() + if m == 0 { + return + } + var g rect + gdkMonitorGetGeometry(m, &g) + if g.H == p.monitorH { + return + } + p.monitorH = g.H + p.top = topMargin(g.H) + layerSetMargin(p.window, edgeTop, int32(p.top)) + gtkWidgetQueueDraw(p.window) +} + +// monitorOfWindow returns the monitor that the shown window is on, or 0. +func (p *platform) monitorOfWindow() uintptr { + s := gtkNativeGetSurface(p.window) + if s == 0 { + return 0 + } + return gdkDisplayMonitorAtSurface(p.display, s) +} + +// firstMonitor returns the first monitor, with a reference that the caller drops, or 0. GTK 4 +// has no primary monitor. +func (p *platform) firstMonitor() uintptr { + list := gdkDisplayGetMonitors(p.display) + if list == 0 || gListModelGetNItems(list) == 0 { + return 0 + } + return gListModelGetItem(list, 0) +} + +// eachMonitor calls fn with each monitor until it returns true. +func (p *platform) eachMonitor(fn func(m uintptr) bool) { + list := gdkDisplayGetMonitors(p.display) + if list == 0 { + return + } + for i := range gListModelGetNItems(list) { + m := gListModelGetItem(list, i) + if m == 0 { + continue + } + done := fn(m) + gObjectUnref(m) + if done { + return + } + } +} + +// workArea returns the work area of the monitor at (x, y), or else of the first monitor. On X11, +// GDK reads it from the window manager. +func (p *platform) workArea(x, y int32) rect { + var wa, first rect + found, haveFirst := false, false + p.eachMonitor(func(m uintptr) bool { + var g rect + gdkMonitorGetGeometry(m, &g) + var area rect + gdkX11MonitorGetWorkarea(m, &area) + if !haveFirst { + first, haveFirst = area, true + } + if g.contains(float64(x), float64(y)) { + wa, found = area, true + return true + } + return false + }) + if !found { + return first + } + return wa +} + +// onScreen reports whether (x, y) is inside the work area of any monitor. A position where the +// user left the window is only reused while its screen is still connected. +func (p *platform) onScreen(x, y float64) bool { + on := false + p.eachMonitor(func(m uintptr) bool { + var wa rect + gdkX11MonitorGetWorkarea(m, &wa) + on = wa.contains(x, y) + return on + }) + return on +} + +// pointer returns the pointer's position in root coordinates. +func (p *platform) pointer() (x, y int32) { + x, y, _, _ = p.queryPointer() + return x, y +} + +// queryPointer asks the X server where the pointer is, and which of its buttons are down. +func (p *platform) queryPointer() (x, y int32, mask uint32, ok bool) { + dpy := gdkX11DisplayGetXDisplay(p.display) + if dpy == 0 { + return 0, 0, 0, false + } + var root, child uintptr + var wx, wy int32 + ok = xQueryPointer(dpy, xDefaultRootWindow(dpy), &root, &child, &x, &y, &wx, &wy, &mask) != 0 + return x, y, mask, ok +} + +// hints sets what X11 window managers read when the window maps: it is a dialog, and it isn't +// listed in the taskbar or the pager. GDK keeps the two hints and writes them again whenever the +// window maps, so they go through GDK. Staying above the other windows is the window's +// AlwaysOnTop, and appearing on every workspace is set once it shows (AfterShow). +func (p *platform) hints() { + s := gtkNativeGetSurface(p.window) + dpy := gdkX11DisplayGetXDisplay(p.display) + if s == 0 || dpy == 0 { + return + } + gdkX11SetSkipTaskbar(s, true) + gdkX11SetSkipPager(s, true) + dialog := uint64(xInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", false)) + xChangeProperty(dpy, gdkX11SurfaceGetXID(s), xInternAtom(dpy, "_NET_WM_WINDOW_TYPE", false), xaAtom, 32, + propModeReplace, unsafe.Pointer(&dialog), 1) + xFlush(dpy) +} diff --git a/app/launcher/view/linux/service.go b/app/launcher/view/linux/service.go new file mode 100644 index 00000000..0f57d0eb --- /dev/null +++ b/app/launcher/view/linux/service.go @@ -0,0 +1,58 @@ +package linux + +import "errors" + +// PageService receives what the user does on the launcher's page (src/pages/Launcher), and passes +// it on to the view. The app binds it on every OS, so that the bindings are the same everywhere. +// The launcher is native on macOS and Windows, where no page calls it, and its methods do nothing. +type PageService struct { + // View returns the launcher's view, or nil where the launcher has no page or until the view + // exists. + View func() *View +} + +var errNoPage = errors.New("the launcher isn't drawn by a page here") + +func (s *PageService) Ready() (Init, error) { + if v := s.View(); v != nil { + return v.Ready(), nil + } + return Init{}, errNoPage +} + +// Query receives the query box's text after an edit, with the number of the edit. +func (s *PageService) Query(text string, seq int) { s.with(func(v *View) { v.Query(text, seq) }) } + +// Key receives a key that the page leaves to the launcher: up, down, enter, esc, tab, actions, +// or row with the character that was pressed with Ctrl. +func (s *PageService) Key(key, char string) { s.with(func(v *View) { v.Key(key, char) }) } + +// Hover receives the row under the pointer when the pointer moves over the rows. +func (s *PageService) Hover(row int) { s.with(func(v *View) { v.Hover(row) }) } + +func (s *PageService) Click(row int) { s.with(func(v *View) { v.Click(row) }) } + +// Scroll receives the rows scrolled with the wheel or the touchpad. Positive is down. +func (s *PageService) Scroll(rows int) { s.with(func(v *View) { v.Scroll(rows) }) } + +func (s *PageService) StopAll() { s.with(func(v *View) { v.StopAll() }) } + +// Pressed receives whether a pointer button is down in the window. +func (s *PageService) Pressed(down bool) { s.with(func(v *View) { v.Pressed(down) }) } + +// DragOver receives whether files are being dragged over the window. +func (s *PageService) DragOver(over bool) { s.with(func(v *View) { v.DragOver(over) }) } + +// DragStart receives a press that starts moving a layer surface, at (x, y) in the window. +func (s *PageService) DragStart(x, y float64) { s.with(func(v *View) { v.DragStart(x, y) }) } + +// DragMove receives the pointer's position while a layer surface moves. +func (s *PageService) DragMove(x, y float64) { s.with(func(v *View) { v.DragMove(x, y) }) } + +func (s *PageService) DragEnd() { s.with(func(v *View) { v.DragEnd() }) } + +func (s *PageService) with(fn func(v *View)) { + if v := s.View(); v != nil { + fn(v) + } +} diff --git a/app/launcher/view/linux/service_test.go b/app/launcher/view/linux/service_test.go new file mode 100644 index 00000000..0912ba3a --- /dev/null +++ b/app/launcher/view/linux/service_test.go @@ -0,0 +1,23 @@ +package linux + +import "testing" + +// TestPageServiceWithoutAView checks that the page's calls do nothing where the launcher has no +// page (macOS and Windows), or before its view exists, and that Ready says why. +func TestPageServiceWithoutAView(t *testing.T) { + s := &PageService{View: func() *View { return nil }} + if _, err := s.Ready(); err != errNoPage { + t.Fatalf("Ready: %v", err) + } + s.Query("x", 1) + s.Key("enter", "") + s.Hover(0) + s.Click(0) + s.Scroll(1) + s.StopAll() + s.Pressed(true) + s.DragOver(true) + s.DragStart(1, 2) + s.DragMove(3, 4) + s.DragEnd() +} diff --git a/app/launcher/view/linux/view.go b/app/launcher/view/linux/view.go new file mode 100644 index 00000000..098e7105 --- /dev/null +++ b/app/launcher/view/linux/view.go @@ -0,0 +1,511 @@ +// Package linux is the launcher window on Linux. It is a window of the app like the others, whose +// page (src/pages/Launcher) draws the launcher's Snapshot. The launcher is native on macOS and +// Windows. On Linux a page lets the app use GTK 4, which is what Wails uses there. +// +// The view sends the page what to draw as events to that window alone (Render, SetQuery, Show and +// Hide). The page reports what the user does through PageService (service.go), and the view +// passes it on to the launcher on the main thread. +// +// Wayland doesn't let an ordinary window choose where it goes, whether it stays above other +// windows, or when it takes focus. When the compositor supports layer-shell (KDE Plasma, COSMIC, +// Hyprland, Sway and the other wlroots compositors), the window is a layer surface, like other +// launchers there. GNOME doesn't support layer-shell, so there the window is an ordinary one, and +// the launcher's GNOME Shell extension (in gnome/) places and focuses it. On X11 the view places +// the window itself and keeps it above the others (see platform_linux.go). +package linux + +import ( + "math" + "sync" + "time" + + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/app/launcher/view" +) + +// Title is the window's title. The GNOME extension (gnome/extension.js) uses it to recognise the +// launcher window. +const Title = "Rclone UI Launcher" + +const ( + EventRender = "launcher:render" // a Frame + EventQuery = "launcher:query" // a Query + EventShown = "launcher:shown" // the window was shown: focus the query box + EventHidden = "launcher:hidden" // the window was hidden: finish any animation +) + +type Mode string + +const ( + ModeX11 Mode = "x11" // an X11 window, which the view places + ModeLayer Mode = "layer-shell" // a Wayland layer surface + ModeWayland Mode = "wayland" // an ordinary Wayland window, which the desktop shell places +) + +type Window interface { + Show() + Hide() + SetSize(width, height int) + // Send sends an event to this window's page alone. + Send(name string, data any) +} + +// Platform places the window and gives it the keyboard. Every method runs on the main thread. +type Platform interface { + Mode() Mode + // BeforeShow places the hidden window at at, if that spot is still on a screen, or else + // centres it on the screen in use. token is the Wayland activation token, "" for none. + BeforeShow(at *view.Placement, token string) + // AfterShow runs once the window is shown, and asks for the keyboard. + AfterShow() + // Resized runs after the window's height changes. A shown X11 window keeps its top edge. + Resized(visible bool) + Focused() + // Held reports whether a pointer button is down anywhere on the screen. Only X11 can tell. + Held() bool + // Moved reports where the user moved the window, after the window reported a move. It is + // false when the view moved it itself, or when the desktop doesn't say where windows are. + Moved() (view.Placement, bool) + // DragStart, DragTo and DragEnd move a layer surface, because compositors don't move those. + // The points are the pointer's, measured from the window's top-left corner. DragEnd reports + // where the surface was left. + DragStart(x, y float64) + DragTo(x, y float64) + DragEnd() (view.Placement, bool) +} + +// Layout is where the page puts things for one Snapshot, measured from the window's top-left +// corner. The view works it out from the launcher's geometry (view/geometry.go), so the page +// draws exactly what the window's size allows. +type Layout struct { + Height float64 `json:"height"` + RowsTop float64 `json:"rowsTop"` + ListH float64 `json:"listH"` + RowTops []float64 `json:"rowTops"` + FooterTop float64 `json:"footerTop"` + StopTop float64 `json:"stopTop"` +} + +// Frame is what the page draws. Swap reports that the footer line animates in from the one before +// (view.Swaps). +type Frame struct { + Snapshot view.Snapshot `json:"snapshot"` + Layout Layout `json:"layout"` + Line view.Line `json:"line"` + Swap bool `json:"swap"` +} + +// Query is a text that the launcher sets in the query box. Seq is the number of the page's last +// edit that the launcher had seen when it set the text (see View.Query). A page that has been +// typed in since keeps its own text, because the launcher's is out of date. +type Query struct { + Text string `json:"text"` + SelectAll bool `json:"selectAll"` + Seq int `json:"seq"` +} + +// Geometry holds the launcher's sizes, in pixels, for the page. +type Geometry struct { + Width float64 `json:"width"` + QueryH float64 `json:"queryH"` + HeaderH float64 `json:"headerH"` + RowH float64 `json:"rowH"` + GroupH float64 `json:"groupH"` + FooterH float64 `json:"footerH"` + Padding float64 `json:"padding"` + IconSize float64 `json:"iconSize"` + FieldTop float64 `json:"fieldTop"` + FieldW float64 `json:"fieldW"` + StopSize float64 `json:"stopSize"` + StopLeft float64 `json:"stopLeft"` + FooterW float64 `json:"footerW"` + SpinSize float64 `json:"spinSize"` + StatusLeft float64 `json:"statusLeft"` + Slide float64 `json:"slide"` + SwapMs int `json:"swapMs"` +} + +// Init is what the page needs when it loads. It includes what the view last sent, so a page that +// loads after the launcher rendered still draws the same. +type Init struct { + Geometry Geometry `json:"geometry"` + // Icons holds each glyph's SVG document by name, drawn in currentColor so the page can tint it. + Icons map[string]string `json:"icons"` + // Mode tells the page who drags the window: the page drags a layer surface (DragStart), and + // the window manager drags any other window. + Mode Mode `json:"mode"` + // RowLetters are the letters that run rows with Ctrl (view.RowLetters), after the digits. + // The page leaves Ctrl with any other letter to the query box. + RowLetters string `json:"rowLetters"` + Frame Frame `json:"frame"` + Query Query `json:"query"` + Visible bool `json:"visible"` +} + +var geometry = Geometry{ + Width: view.Width, QueryH: view.QueryH, HeaderH: view.HeaderH, RowH: view.RowH, + GroupH: view.GroupH, FooterH: view.FooterH, Padding: view.Padding, IconSize: view.IconSize, + FieldTop: view.FieldTop, FieldW: view.FieldW, StopSize: view.StopSize, StopLeft: view.StopLeft, + FooterW: view.FooterW, SpinSize: view.SpinSize, StatusLeft: view.StatusLeft, Slide: view.Slide, + SwapMs: int(view.SwapFor.Milliseconds()), +} + +var glyphs = sync.OnceValue(func() map[string]string { + out := map[string]string{} + for _, n := range icons.All() { + out[string(n)] = icons.Tinted(n, "currentColor") + } + return out +}) + +func layoutOf(s view.Snapshot) Layout { + tops := make([]float64, len(s.Rows)) + for i := range s.Rows { + tops[i] = view.RowTop(s, i) + } + return Layout{ + Height: view.Height(s), + RowsTop: view.RowsTop(s.Header != ""), + ListH: view.ListH(s), + RowTops: tops, + FooterTop: view.FooterTop(s), + StopTop: view.StopTop(s), + } +} + +// Timing for the Blur wait (see FocusLost). +const ( + blurPoll = 50 * time.Millisecond // how often it checks + blurGrace = 250 * time.Millisecond // how long it waits after a button is released or a drag leaves +) + +// View is the launcher window. Its view.View methods run on the main thread. The page's methods +// (Ready, Query, Key and the rest) may be called from any goroutine. +type View struct { + win Window + plat Platform + ev view.Events + main func(func()) + after func(time.Duration, func()) + + mu sync.Mutex // guards state, which Ready reads from a service call + state Init + + visible bool + token string + line view.Line // the footer line that the page shows + seq int // the number of the page's last edit (see Query) + + // The Blur wait. blurGen counts the waits, so a stopped wait's pending check does nothing. + blurGen int + blurFrom time.Time + dragOver bool // files are dragged over the window, as the page reports + pressed bool // a pointer button is down in the window, as the page reports + dragging bool // a layer surface is being dragged +} + +// New returns the view of win, which plat places. main runs a function on the main thread, and +// after runs one there after a delay. +func New(win Window, plat Platform, ev view.Events, main func(func()), after func(time.Duration, func())) *View { + return &View{ + win: win, plat: plat, ev: ev, main: main, after: after, + state: Init{ + Geometry: geometry, Mode: plat.Mode(), RowLetters: view.RowLetters, + Frame: Frame{Snapshot: view.Snapshot{Selected: -1}}, + }, + } +} + +func (v *View) Mode() string { return string(v.plat.Mode()) } + +// PlacedByShell reports whether the window is an ordinary Wayland window, which only the desktop +// shell can place, keep above other windows and focus. On GNOME, the launcher's extension (in +// gnome/) does this. +func (v *View) PlacedByShell() bool { return v.plat.Mode() == ModeWayland } + +// SetActivationToken sets the compositor's token for the shortcut press (the portal's +// activation_token). On Wayland, the next Show uses it to take the keyboard. +func (v *View) SetActivationToken(token string) { v.token = token } + +func (v *View) Show(at *view.Placement) { + v.visible = true + v.setVisible(true) + v.plat.BeforeShow(at, v.token) + v.token = "" + v.win.Show() + v.plat.AfterShow() + v.win.Send(EventShown, nil) +} + +func (v *View) Hide() { + v.visible = false + v.setVisible(false) + v.dragging, v.dragOver, v.pressed = false, false, false + v.stopBlur() + v.win.Hide() + v.win.Send(EventHidden, nil) +} + +func (v *View) Visible() bool { return v.visible } + +func (v *View) Render(s view.Snapshot) { + line := view.FooterLine(s) + f := Frame{Snapshot: s, Layout: layoutOf(s), Line: line, Swap: v.visible && view.Swaps(v.line, line)} + v.line = line + v.mu.Lock() + v.state.Frame = f + v.mu.Unlock() + v.win.Send(EventRender, f) + v.win.SetSize(int(view.Width), int(math.Ceil(f.Layout.Height))) + v.plat.Resized(v.visible) +} + +func (v *View) SetQuery(text string, selectAll bool) { + q := Query{Text: text, SelectAll: selectAll, Seq: v.seq} + v.mu.Lock() + v.state.Query = q + v.mu.Unlock() + v.win.Send(EventQuery, q) +} + +func (v *View) setVisible(on bool) { + v.mu.Lock() + v.state.Visible = on + v.mu.Unlock() +} + +func (v *View) Ready() Init { + v.mu.Lock() + defer v.mu.Unlock() + in := v.state + in.Icons = glyphs() + return in +} + +// The page's keys, as the page names them (src/pages/Launcher/keys.ts). +var pageKeys = map[string]view.Key{ + "up": view.KeyUp, + "down": view.KeyDown, + "enter": view.KeyEnter, + "esc": view.KeyEsc, + "tab": view.KeyTab, + "actions": view.KeyActions, + "row": view.KeyRow, +} + +// Query receives the query box's text after an edit. The page numbers its edits, and seq is this +// one's number. SetQuery sends the number back with the text that the launcher sets, so the page +// can tell when it has been typed in since (see the Query type). +func (v *View) Query(text string, seq int) { + v.call("query", func() { + v.seq = seq + if v.ev.Query != nil { + v.ev.Query(text) + } + }) +} + +// Key receives a key that the page leaves to the launcher. char is the character of a "row" key: +// a digit, a letter or a full stop pressed with Ctrl. +func (v *View) Key(key, char string) { + k, ok := pageKeys[key] + if !ok { + return + } + e := view.KeyEvent{Key: k} + if k == view.KeyRow { + r := []rune(char) + if len(r) != 1 { + return + } + e.Char = r[0] + } + v.call("key", func() { + if v.visible && v.ev.Key != nil { + v.ev.Key(e) + } + }) +} + +func (v *View) Hover(row int) { + v.call("hover", func() { + if v.visible && v.ev.Hover != nil { + v.ev.Hover(row) + } + }) +} + +func (v *View) Click(row int) { + v.call("click", func() { + if v.visible && v.ev.Click != nil { + v.ev.Click(row) + } + }) +} + +func (v *View) Scroll(rows int) { + v.call("scroll", func() { + if v.visible && rows != 0 && v.ev.Scroll != nil { + v.ev.Scroll(rows) + } + }) +} + +func (v *View) StopAll() { + v.call("stop all", func() { + if v.ev.StopAll != nil { + v.ev.StopAll() + } + }) +} + +// Pressed receives whether a pointer button is down in the window. The Blur wait waits while it +// is, because a drag may be starting. +func (v *View) Pressed(down bool) { + v.call("pressed", func() { + v.pressed = down + if !down { + v.blurFrom = time.Now() + } + }) +} + +// DragOver receives whether files are being dragged over the window. The Blur wait waits while +// they are, so they can still be dropped. +func (v *View) DragOver(over bool) { + v.call("drag over", func() { + v.dragOver = over + if !over { + v.blurFrom = time.Now() + } + }) +} + +func (v *View) DragStart(x, y float64) { + v.call("drag start", func() { + if v.visible && v.plat.Mode() == ModeLayer { + v.dragging = true + v.plat.DragStart(x, y) + } + }) +} + +func (v *View) DragMove(x, y float64) { + v.call("drag move", func() { + if v.dragging { + v.plat.DragTo(x, y) + } + }) +} + +func (v *View) DragEnd() { + v.call("drag end", func() { + if !v.dragging { + return + } + v.dragging = false + if at, ok := v.plat.DragEnd(); ok && v.ev.Moved != nil { + v.ev.Moved(at) + } + }) +} + +func (v *View) Focused() { + v.call("focus", func() { + v.stopBlur() + if v.visible { + v.plat.Focused() + } + }) +} + +// FocusLost reports that the window lost the keyboard (Blur), but only once it is clear that the +// user has left the window. It waits while a pointer button is down, because a drag may be +// starting in another window to drop files here. It also waits while files are dragged over the +// window, and for blurGrace after either ends. X11 reports a button pressed anywhere, but Wayland +// only one pressed on this window, so on Wayland the grace period gives a drag from elsewhere time +// to arrive. +func (v *View) FocusLost() { + v.call("focus lost", func() { + if !v.visible || v.ev.Blur == nil { + return + } + v.blurFrom = time.Now() + v.blurGen++ + v.waitBlur(v.blurGen) + }) +} + +func (v *View) waitBlur(gen int) { + v.after(blurPoll, func() { v.call("blur", func() { v.blurCheck(gen) }) }) +} + +func (v *View) blurCheck(gen int) { + if gen != v.blurGen || !v.visible { + return + } + if v.dragOver || v.pressed || v.plat.Held() { + v.blurFrom = time.Now() + v.waitBlur(gen) + return + } + if time.Since(v.blurFrom) < blurGrace { + v.waitBlur(gen) + return + } + v.blurGen++ // the wait is over; Blur may call Hide + if v.ev.Blur != nil { + v.ev.Blur() + } +} + +func (v *View) stopBlur() { v.blurGen++ } + +func (v *View) Moved() { + v.call("moved", func() { + if !v.visible { + return + } + if at, ok := v.plat.Moved(); ok && v.ev.Moved != nil { + v.ev.Moved(at) + } + }) +} + +// Dropped takes the keyboard back before it passes the files on. +func (v *View) Dropped(paths []string) { + v.call("dropped", func() { + v.dragOver = false + if !v.visible || len(paths) == 0 || v.ev.Drop == nil { + return + } + v.plat.AfterShow() + v.win.Send(EventShown, nil) + v.ev.Drop(paths) + }) +} + +// Closed handles a request to close the window, such as Alt+F4. The window is only ever hidden, +// so the launcher dismisses itself instead. +func (v *View) Closed() { + v.call("close", func() { + if v.ev.Key != nil { + v.ev.Key(view.KeyEvent{Key: view.KeyClose}) + } + }) +} + +func (v *View) call(name string, body func()) { + v.main(func() { + defer func() { + if p := recover(); p != nil { + if v.ev.Panicked != nil { + v.ev.Panicked("launcher page "+name, p) + return + } + panic(p) + } + }() + body() + }) +} diff --git a/app/launcher/view/linux/view_test.go b/app/launcher/view/linux/view_test.go new file mode 100644 index 00000000..e8816f56 --- /dev/null +++ b/app/launcher/view/linux/view_test.go @@ -0,0 +1,243 @@ +package linux + +import ( + "testing" + "time" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +type fakeWindow struct { + shown bool + height int + sent []sent +} + +type sent struct { + name string + data any +} + +func (w *fakeWindow) Show() { w.shown = true } +func (w *fakeWindow) Hide() { w.shown = false } +func (w *fakeWindow) SetSize(_, height int) { w.height = height } +func (w *fakeWindow) Send(name string, d any) { w.sent = append(w.sent, sent{name, d}) } + +func (w *fakeWindow) last(name string) (any, bool) { + for i := len(w.sent) - 1; i >= 0; i-- { + if w.sent[i].name == name { + return w.sent[i].data, true + } + } + return nil, false +} + +type fakePlatform struct { + mode Mode + held bool + presented int + moved *view.Placement +} + +func (p *fakePlatform) Mode() Mode { return p.mode } +func (p *fakePlatform) BeforeShow(*view.Placement, string) {} +func (p *fakePlatform) AfterShow() { p.presented++ } +func (p *fakePlatform) Resized(bool) {} +func (p *fakePlatform) Focused() {} +func (p *fakePlatform) Held() bool { return p.held } +func (p *fakePlatform) DragStart(float64, float64) {} +func (p *fakePlatform) DragTo(float64, float64) {} +func (p *fakePlatform) DragEnd() (view.Placement, bool) { return view.Placement{}, false } +func (p *fakePlatform) Moved() (view.Placement, bool) { + if p.moved == nil { + return view.Placement{}, false + } + return *p.moved, true +} + +// timers holds the functions that the view runs after a delay, for the test to run when it likes. +type timers struct{ due []func() } + +func (t *timers) after(_ time.Duration, fn func()) { t.due = append(t.due, fn) } + +// run runs the functions that are due, and those that they schedule, n rounds at most. +func (t *timers) run(n int) { + for range n { + due := t.due + t.due = nil + for _, fn := range due { + fn() + } + } +} + +func newTestView(ev view.Events) (*View, *fakeWindow, *fakePlatform, *timers) { + w, p, t := &fakeWindow{}, &fakePlatform{mode: ModeX11}, &timers{} + return New(w, p, ev, func(fn func()) { fn() }, t.after), w, p, t +} + +// Render sends the page the snapshot with its layout, and sizes the window to fit it. The footer +// animates only while the window is shown, and only for the changes that view.Swaps names. +func TestRender(t *testing.T) { + v, w, _, _ := newTestView(view.Events{}) + s := view.Snapshot{Rows: []view.Row{{Title: "Copy"}, {Group: "App", Title: "Settings"}}, Selected: 0} + v.Render(s) + f, _ := w.last(EventRender) + frame := f.(Frame) + if frame.Swap { + t.Error("a hidden window's footer animates") + } + if want := []float64{view.QueryH, view.QueryH + view.RowH + view.GroupH}; frame.Layout.RowTops[0] != want[0] || frame.Layout.RowTops[1] != want[1] { + t.Errorf("row tops %v, want %v", frame.Layout.RowTops, want) + } + if w.height != int(view.Height(s)) { + t.Errorf("height %d, want %v", w.height, view.Height(s)) + } + + v.Show(nil) + s.Status = view.Status{Kind: view.StatusLoading, Text: "Listing…"} + v.Render(s) + f, _ = w.last(EventRender) + if !f.(Frame).Swap { + t.Error("a status doesn't animate in") + } + if got := v.Ready().Frame.Line.Status.Text; got != "Listing…" { + t.Errorf("Ready's footer %q", got) + } +} + +// A text that the launcher sets carries the number of the page's last edit that it had seen. +func TestQueryNumbers(t *testing.T) { + var got string + v, w, _, _ := newTestView(view.Events{Query: func(text string) { got = text }}) + v.Query("co", 7) + if got != "co" { + t.Fatalf("the launcher got %q", got) + } + v.SetQuery("copy", true) + q, _ := w.last(EventQuery) + if want := (Query{Text: "copy", SelectAll: true, Seq: 7}); q.(Query) != want { + t.Errorf("query %+v, want %+v", q, want) + } + if v.Ready().Query.Seq != 7 { + t.Error("Ready doesn't have the last edit's number") + } +} + +// The page's keys reach the launcher only while it is shown. A row key needs its one character. +func TestKeys(t *testing.T) { + var keys []view.KeyEvent + v, _, _, _ := newTestView(view.Events{Key: func(k view.KeyEvent) bool { keys = append(keys, k); return true }}) + v.Key("down", "") + if len(keys) != 0 { + t.Fatal("a hidden launcher got a key") + } + v.Show(nil) + v.Key("down", "") + v.Key("row", "b") + v.Key("row", "") // no character + v.Key("unknown", "x") // not a key the page sends + v.Closed() + want := []view.KeyEvent{{Key: view.KeyDown}, {Key: view.KeyRow, Char: 'b'}, {Key: view.KeyClose}} + if len(keys) != len(want) { + t.Fatalf("keys %v, want %v", keys, want) + } + for i := range want { + if keys[i] != want[i] { + t.Errorf("key %d is %v, want %v", i, keys[i], want[i]) + } + } +} + +// Blur waits while files are dragged over the window or a button is down, then for the grace +// period, and a regained focus cancels it. +func TestBlurWait(t *testing.T) { + blurred := 0 + v, _, p, timers := newTestView(view.Events{Blur: func() { blurred++ }}) + v.Show(nil) + + v.FocusLost() + v.DragOver(true) + timers.run(3) + if blurred != 0 { + t.Fatal("blurred while files were dragged over the window") + } + v.DragOver(false) + p.held = true + timers.run(3) + if blurred != 0 { + t.Fatal("blurred while a button was down") + } + p.held = false + v.blurFrom = time.Now().Add(-blurGrace) // the grace period is over + timers.run(1) + if blurred != 1 { + t.Fatalf("blurred %d times, want 1", blurred) + } + + v.FocusLost() + v.Focused() + v.blurFrom = time.Now().Add(-blurGrace) + timers.run(3) + if blurred != 1 { + t.Error("a regained focus didn't cancel the Blur") + } +} + +// Dropped files take the keyboard back and go to the launcher, but not while it is hidden. +func TestDropped(t *testing.T) { + var dropped []string + v, _, p, _ := newTestView(view.Events{Drop: func(paths []string) { dropped = paths }}) + v.Dropped([]string{"/tmp/a"}) + if dropped != nil { + t.Fatal("a hidden launcher took a drop") + } + v.Show(nil) + before := p.presented + v.Dropped([]string{"/tmp/a"}) + if len(dropped) != 1 || p.presented != before+1 { + t.Errorf("dropped %v, presented %d times", dropped, p.presented-before) + } +} + +// A move that the platform reports goes to the launcher. One that the view made itself doesn't. +func TestMoved(t *testing.T) { + var at *view.Placement + v, _, p, _ := newTestView(view.Events{Moved: func(pl view.Placement) { at = &pl }}) + v.Show(nil) + v.Moved() + if at != nil { + t.Fatal("the view's own move was reported") + } + p.moved = &view.Placement{Left: 40, Top: 50} + v.Moved() + if at == nil || *at != *p.moved { + t.Errorf("moved to %v, want %v", at, p.moved) + } +} + +// A panic in a callback from the page goes to Panicked rather than up through the service call. +func TestPanicked(t *testing.T) { + var where string + v, _, _, _ := newTestView(view.Events{ + Query: func(string) { panic("boom") }, + Panicked: func(w string, _ any) { where = w }, + }) + v.Query("x", 1) + if where != "launcher page query" { + t.Errorf("Panicked got %q", where) + } +} + +// A layer surface's margins follow the pointer, but never past the monitor's top or left edge. +func TestDragMargins(t *testing.T) { + if l, tp := dragMargins(100, 50, 12.4, -8.6); l != 112 || tp != 41 { + t.Errorf("got %d, %d", l, tp) + } + if l, tp := dragMargins(5, 5, -20, -20); l != 0 || tp != 0 { + t.Errorf("got %d, %d past the edges", l, tp) + } + if got := topMargin(1080); got != int((1080-view.FullHeight())/2) { + t.Errorf("top margin %d", got) + } +} diff --git a/app/launcher/view/linux/wails.go b/app/launcher/view/linux/wails.go new file mode 100644 index 00000000..a9200a6d --- /dev/null +++ b/app/launcher/view/linux/wails.go @@ -0,0 +1,59 @@ +package linux + +import ( + "math" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/events" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +// WindowOptions returns the options of the launcher's window. It is created hidden, as tall as a +// full list, and is only ever hidden, never closed. devTools allows the web inspector, in +// development builds. +func WindowOptions(devTools bool) application.WebviewWindowOptions { + return application.WebviewWindowOptions{ + Name: "Launcher", + Title: Title, + URL: "/launcher", + Hidden: true, + Width: int(view.Width), + Height: int(math.Ceil(view.FullHeight())), + Frameless: true, + DisableResize: true, + AlwaysOnTop: true, + EnableFileDrop: true, + Zoom: 1, + ZoomControlEnabled: false, + DevToolsEnabled: devTools, + DefaultContextMenuDisabled: !devTools, + } +} + +func Wrap(w *application.WebviewWindow) Window { return wailsWindow{w} } + +type wailsWindow struct{ w *application.WebviewWindow } + +func (w wailsWindow) Show() { w.w.Show() } +func (w wailsWindow) Hide() { w.w.Hide() } +func (w wailsWindow) SetSize(width, height int) { w.w.SetSize(width, height) } + +func (w wailsWindow) Send(name string, data any) { + w.w.DispatchWailsEvent(&application.CustomEvent{Name: name, Data: data}) +} + +// Attach passes w's events to v: the keyboard coming and going, a move, dropped files, and a +// request to close the window, which only hides the launcher. +func Attach(w *application.WebviewWindow, v *View) { + w.OnWindowEvent(events.Common.WindowFocus, func(*application.WindowEvent) { v.Focused() }) + w.OnWindowEvent(events.Common.WindowLostFocus, func(*application.WindowEvent) { v.FocusLost() }) + w.OnWindowEvent(events.Common.WindowDidMove, func(*application.WindowEvent) { v.Moved() }) + w.OnWindowEvent(events.Common.WindowFilesDropped, func(e *application.WindowEvent) { + v.Dropped(e.Context().DroppedFiles()) + }) + w.RegisterHook(events.Common.WindowClosing, func(e *application.WindowEvent) { + e.Cancel() + v.Closed() + }) +} diff --git a/app/launcher/view/view.go b/app/launcher/view/view.go new file mode 100644 index 00000000..d30f000f --- /dev/null +++ b/app/launcher/view/view.go @@ -0,0 +1,170 @@ +// Package view defines the contract between the launcher and the window that each platform +// draws it in. The launcher makes every decision: the selection, what a key does, when to hide +// and where to open. A view draws a Snapshot and reports what the user does. Every method runs on +// the main thread, and every event is called on it. +package view + +import ( + "time" + + "github.com/rclone/rclone-ui/app/launcher/icons" +) + +type View interface { + // Show gives the window keyboard focus. A nil at centres the window on the screen that has + // the mouse. Otherwise the window opens at at, if that spot is still on a screen. + Show(at *Placement) + // Hide keeps the query box's text. + Hide() + // Render resizes the window to fit the rows and keeps the top edge in place. + Render(s Snapshot) + // SetQuery puts the caret at the end of the text unless selectAll is set. + SetQuery(text string, selectAll bool) + Visible() bool +} + +// Activator is a view that can take focus using the activation token that the compositor +// issued for the shortcut press (Wayland's xdg-activation). The Linux view implements it when +// its window is a native Wayland window. +type Activator interface { + // SetActivationToken sets the token to use for the next Show. + SetActivationToken(token string) +} + +type Events struct { + Query func(text string) + // Key offers a key to the launcher. Returning false passes it on to the query box. + Key func(k KeyEvent) bool + // Hover is called only when the mouse moves, not when rows shift under a pointer that stays + // still. + Hover func(row int) + Click func(row int) + // Scroll receives the number of rows scrolled. Positive is down. + Scroll func(rows int) + Moved func(at Placement) + // Blur is called when the window loses keyboard focus. A view may delay it while a mouse + // button is down, so that a drag that started in another window can still be dropped on + // this one. + Blur func() + Drop func(paths []string) + // StopAll is called when the stop-everything button is pressed, even when nothing is running. + StopAll func() + // Panicked receives a panic that the view recovered in a toolkit callback, with where it + // happened and the panic value. The view must recover there because a panic can't unwind + // through the toolkit's frames. It is called from the deferred recover, so the panicking + // frames are still on the stack for the report. It may be called on any thread. + Panicked func(where string, v any) +} + +type Key int + +const ( + KeyNone Key = iota + KeyUp + KeyDown + KeyEnter + KeyEsc + KeyTab + // KeyActions is ⌘K (Ctrl+K on Windows and Linux). + KeyActions + // KeyRow is ⌘ (Ctrl) with a digit or a letter. KeyEvent.Char holds which one. + KeyRow + // KeyClose is sent when the window is closed, with Alt+F4 or the window manager's close + // button. It dismisses the launcher even in states that Esc would only step back from. + KeyClose +) + +// KeyEvent is a key press. Char holds the lower-case character of a KeyRow. +type KeyEvent struct { + Key Key + Char rune +} + +// Placement is where the user left the window, as its left and top edges in the view's own +// screen coordinates. +type Placement struct { + Left float64 `json:"left"` + Top float64 `json:"top"` +} + +type Snapshot struct { + Placeholder string `json:"placeholder"` + // Header, when set, is a line above the rows that names the item whose actions are shown. + Header string `json:"header"` + // Rows are the rows to draw: as many rows of the list as fit in MaxListH. + Rows []Row `json:"rows"` + // Selected is the highlighted row, -1 for none. + Selected int `json:"selected"` + // More reports that the list has more rows than those drawn. The list then keeps its full + // height, so the window doesn't change size while scrolling. + More bool `json:"more"` + Footer []Hint `json:"footer"` + // Status, when set, replaces the hints in the footer. + Status Status `json:"status"` + // Running makes the stop-everything button red rather than muted. + Running bool `json:"running"` +} + +type Row struct { + // Group is the label of the group that starts at this row, drawn above it. It is empty + // when the row doesn't start a group. + Group string `json:"group"` + Icon icons.Name `json:"icon"` + Title string `json:"title"` + Bold []int `json:"bold"` // indexes of the runes in Title that matched the query, drawn bold + Subtitle string `json:"subtitle"` + Tail string `json:"tail"` // grey text at the right: "3 active", a mount point + Hint string `json:"hint"` // the row's shortcut: "⌘1" + // Danger marks a row that stops or deletes something. Its icon and its selection are red. + Danger bool `json:"danger"` +} + +type Status struct { + Kind StatusKind `json:"kind"` + Text string `json:"text"` +} + +type StatusKind int + +const ( + StatusNone StatusKind = iota + StatusLoading + StatusDone + StatusError +) + +type Line struct { + Status Status `json:"status"` // StatusNone means the hints are shown + Hints string `json:"hints"` +} + +func FooterLine(s Snapshot) Line { + if s.Status.Kind != StatusNone { + return Line{Status: s.Status} + } + return Line{Hints: FooterText(s.Footer)} +} + +// Swaps reports whether the footer animates from line a to line b. It animates when either line +// is a status. A change from hints to other hints doesn't animate. +func Swaps(a, b Line) bool { + return a != b && (a.Status.Kind != StatusNone || b.Status.Kind != StatusNone) +} + +// SwapFor is how long the footer animation takes. It eases out. +const SwapFor = 200 * time.Millisecond + +// Hint is a key and what it does, such as {"⏎", "Browse"}. +type Hint struct { + Keys string `json:"keys"` + Label string `json:"label"` +} + +// RowLetters are the letters that run rows with ⌘ (Ctrl), after ⌘1–9. They leave out A, C, V +// and X (clipboard), K (actions), and the keys used by the app and the text box: Q (quit), W +// (close), H (hide), M (minimise), Z and Y (undo, redo). +const RowLetters = "bdefgijlnoprstu" + +// MaxRows is the most rows a view shows at once, or fewer when group labels sit between them. +// The user reaches the rest by moving the selection or scrolling. +const MaxRows = 8 diff --git a/app/launcher/view/viewtest/fake.go b/app/launcher/view/viewtest/fake.go new file mode 100644 index 00000000..74fa7d39 --- /dev/null +++ b/app/launcher/view/viewtest/fake.go @@ -0,0 +1,49 @@ +// Package viewtest has a fake launcher view for tests. +package viewtest + +import "github.com/rclone/rclone-ui/app/launcher/view" + +type Fake struct { + Events view.Events + Shown bool + At *view.Placement + Last view.Snapshot + Renders int + Query string + Selected bool // the query was set with all of its text selected +} + +func (f *Fake) Show(at *view.Placement) { f.Shown, f.At = true, at } + +func (f *Fake) Hide() { f.Shown = false } + +func (f *Fake) Render(s view.Snapshot) { f.Last, f.Renders = s, f.Renders+1 } + +// SetQuery stores the text. Like a real query box, it doesn't call Events.Query for text that was +// set by code. +func (f *Fake) SetQuery(text string, selectAll bool) { f.Query, f.Selected = text, selectAll } + +func (f *Fake) Visible() bool { return f.Shown } + +// Type replaces the text, as the user would, and calls Events.Query. +func (f *Fake) Type(text string) { + f.Query = text + if f.Events.Query != nil { + f.Events.Query(text) + } +} + +func (f *Fake) Press(k view.KeyEvent) bool { + if f.Events.Key == nil { + return false + } + return f.Events.Key(k) +} + +func (f *Fake) Titles() []string { + t := make([]string, len(f.Last.Rows)) + for i, r := range f.Last.Rows { + t[i] = r.Title + } + return t +} diff --git a/app/launcher/view/windows/accessible.go b/app/launcher/view/windows/accessible.go new file mode 100644 index 00000000..75ca7b15 --- /dev/null +++ b/app/launcher/view/windows/accessible.go @@ -0,0 +1,95 @@ +//go:build windows + +package windows + +import ( + "unsafe" + + "golang.org/x/sys/windows" +) + +// The rows are drawn directly, so a screen reader can't read them. A live region lets Win32 UI +// have text announced without implementing its own UI Automation provider. The view uses a STATIC +// child window whose text is the selected row. It is marked as a live region through +// IAccPropServices, and the view sends EVENT_OBJECT_LIVEREGIONCHANGED on each change. UIA's own +// UiaRaiseNotificationEvent would need a custom provider, because the provider returned by +// UiaHostProviderFromHwnd can't raise events. + +var ( + clsidAccPropServices = windows.GUID{Data1: 0xb5f8350b, Data2: 0x0548, Data3: 0x48b1, Data4: [8]byte{0xa6, 0xee, 0x88, 0xbd, 0x00, 0xb4, 0xa5, 0xe7}} + iidIAccPropServices = windows.GUID{Data1: 0x6e26e776, Data2: 0x04f0, Data3: 0x495d, Data4: [8]byte{0x80, 0xe4, 0x33, 0x30, 0x35, 0x2e, 0x31, 0x69}} + liveSettingProperty = windows.GUID{Data1: 0xc12bcd8e, Data2: 0x2a8e, Data3: 0x4950, Data4: [8]byte{0x8a, 0xe7, 0x36, 0x25, 0x11, 0x1d, 0x58, 0xeb}} +) + +const ( + eventObjectLiveRegionChanged = 0x8019 + objidClient = 0xFFFFFFFC // -4 + childidSelf = 0 + liveAssertive = 2 // announced at once, as the selection moves + vtI4 = 3 + clsctxInprocServer = 1 + ssNoPrefix = 0x0080 +) + +// liveRegion is the STATIC window that a screen reader reads the selected row from. +type liveRegion struct { + hwnd uintptr + props uintptr // IAccPropServices, created on the first announcement + marked bool // the STATIC has been marked as a live region + said string +} + +// newLiveRegion creates the STATIC window. It is one pixel in the window's corner, which DWM +// rounds off, and has the same colour as the band behind it (WM_CTLCOLORSTATIC). It isn't hidden, +// because screen readers skip hidden windows. +func newLiveRegion(parent, instance uintptr) *liveRegion { + class, _ := windows.UTF16PtrFromString("STATIC") + empty, _ := windows.UTF16PtrFromString("") + h, _, _ := procCreateWindowExW.Call(0, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(empty)), + wsChild|wsVisible|ssNoPrefix, 0, 0, 1, 1, parent, 0, instance, 0) + return &liveRegion{hwnd: h} +} + +// say has text announced once. The same text is not announced again, such as after a render that +// didn't move the selection. +func (l *liveRegion) say(text string) { + if l == nil || l.hwnd == 0 || text == l.said { + return + } + l.said = text + if text == "" || !l.mark() { + return + } + setWindowText(l.hwnd, text) + _, _, _ = procNotifyWinEvent.Call(eventObjectLiveRegionChanged, l.hwnd, objidClient, childidSelf) +} + +// forget makes the next announcement happen even if it repeats the last one. It is called when +// the launcher is hidden. +func (l *liveRegion) forget() { + if l != nil { + l.said = "" + } +} + +// mark marks the STATIC as a live region, because screen readers ignore the event from a window +// that isn't one. +func (l *liveRegion) mark() bool { + if l.marked { + return true + } + if l.props == 0 { + // COM is already initialized on the UI thread, because WebView2 needs it. Initializing + // it again is harmless. + _ = windows.CoInitializeEx(0, windows.COINIT_APARTMENTTHREADED) + hr, _, _ := procCoCreateInstance.Call(uintptr(unsafe.Pointer(&clsidAccPropServices)), 0, clsctxInprocServer, + uintptr(unsafe.Pointer(&iidIAccPropServices)), uintptr(unsafe.Pointer(&l.props))) + if failed(hr) || l.props == 0 { + l.props = 0 + return false + } + } + v := variant{VT: vtI4, Val: liveAssertive} + l.marked = !failed(setHwndProp(l.props, l.hwnd, objidClient, childidSelf, &liveSettingProperty, &v)) + return l.marked +} diff --git a/app/launcher/view/windows/accessible_amd64.go b/app/launcher/view/windows/accessible_amd64.go new file mode 100644 index 00000000..33a7c43e --- /dev/null +++ b/app/launcher/view/windows/accessible_amd64.go @@ -0,0 +1,20 @@ +//go:build windows && amd64 + +package windows + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +// setHwndProp calls IAccPropServices::SetHwndProp (vtable slot 6) with (hwnd, idObject, idChild, +// MSAAPROPID, VARIANT), where the last two are passed by value. On x64, a struct larger than eight +// bytes that is passed by value is sent as a pointer to a 16-byte-aligned copy. +func setHwndProp(svc, hwnd, idObject, idChild uintptr, prop *windows.GUID, v *variant) uintptr { + p, val := aligned16(*prop), aligned16(*v) + r, _, _ := syscall.SyscallN(method(svc, 6), svc, hwnd, idObject, idChild, + uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(val))) + return r +} diff --git a/app/launcher/view/windows/accessible_arm64.go b/app/launcher/view/windows/accessible_arm64.go new file mode 100644 index 00000000..a36b3503 --- /dev/null +++ b/app/launcher/view/windows/accessible_arm64.go @@ -0,0 +1,22 @@ +//go:build windows && arm64 + +package windows + +import ( + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +// setHwndProp calls IAccPropServices::SetHwndProp (vtable slot 6) with (hwnd, idObject, idChild, +// MSAAPROPID, VARIANT), where the last two are passed by value. On arm64, a struct of 16 bytes or +// less, such as the GUID, is passed in two general registers. A larger struct, such as the +// VARIANT, is passed as a pointer to a copy. +func setHwndProp(svc, hwnd, idObject, idChild uintptr, prop *windows.GUID, v *variant) uintptr { + words := (*[2]uint64)(unsafe.Pointer(prop)) + val := aligned16(*v) + r, _, _ := syscall.SyscallN(method(svc, 6), svc, hwnd, idObject, idChild, + uintptr(words[0]), uintptr(words[1]), uintptr(unsafe.Pointer(val))) + return r +} diff --git a/app/launcher/view/windows/d2d.go b/app/launcher/view/windows/d2d.go new file mode 100644 index 00000000..ba4be7ac --- /dev/null +++ b/app/launcher/view/windows/d2d.go @@ -0,0 +1,408 @@ +//go:build windows + +package windows + +import ( + "fmt" + "syscall" + "unsafe" + + "github.com/ebitengine/purego" + "golang.org/x/sys/windows" + + "github.com/rclone/rclone-ui/app/launcher/icons" +) + +// COM methods are called through the object's vtable. The index is the method's position in its +// interface declaration, counting the methods of the interfaces it derives from, starting with the +// three from IUnknown. Calls whose arguments are all integers and pointers go through +// syscall.SyscallN, and every pointer is converted inside the call expression so that it stays +// alive and doesn't move. Calls that pass floats go through purego (see bound), which puts them in +// the float registers that arm64 expects. Their Go pointers are typed so that purego keeps them +// alive. + +func method(obj uintptr, index int) uintptr { + o := *(***[128]uintptr)(unsafe.Pointer(&obj)) + return (*o)[index] +} + +// release releases a reference (IUnknown::Release, vtable slot 2). +func release(obj uintptr) { + if obj != 0 { + _, _, _ = syscall.SyscallN(method(obj, 2), obj) + } +} + +func failed(hr uintptr) bool { return int32(hr) < 0 } + +// d2derrRecreateTarget means the device was lost, so the render target and its resources must be +// rebuilt. +const d2derrRecreateTarget = 0x8899000C + +var ( + iidD2D1Factory = windows.GUID{Data1: 0x06152247, Data2: 0x6f50, Data3: 0x465a, Data4: [8]byte{0x92, 0x45, 0x11, 0x8b, 0xfd, 0x3b, 0x60, 0x07}} + iidDWriteFactory = windows.GUID{Data1: 0xb859ee5a, Data2: 0xd838, Data3: 0x4b5b, Data4: [8]byte{0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48}} + iidD2D1DeviceContext5 = windows.GUID{Data1: 0x7836d248, Data2: 0x68cc, Data3: 0x4df6, Data4: [8]byte{0xb9, 0xe8, 0xde, 0x99, 0x1b, 0xf6, 0x2e, 0xb7}} +) + +// Direct2D and DirectWrite structures, laid out as in their C headers. +type ( + rectF struct{ Left, Top, Right, Bottom float32 } + roundedRect struct { + Rect rectF + RadiusX, RadiusY float32 + } + ellipse struct{ X, Y, RadiusX, RadiusY float32 } + matrix3x2 struct{ M11, M12, M21, M22, Dx, Dy float32 } + sizeU struct{ Width, Height uint32 } + + renderTargetProps struct { + Type uint32 + Format uint32 // D2D1_PIXEL_FORMAT.format + AlphaMode uint32 // D2D1_PIXEL_FORMAT.alphaMode + DpiX, DpiY float32 + Usage uint32 + MinLevel uint32 + } + hwndRenderTargetProps struct { + Hwnd uintptr + Width, Height uint32 // D2D1_SIZE_U + PresentOptions uint32 + } + trimming struct{ Granularity, Delimiter, DelimiterCount uint32 } +) + +var identity = matrix3x2{M11: 1, M22: 1} + +const ( + dxgiFormatB8G8R8A8 = 87 + alphaPremultiplied = 1 + alphaIgnore = 3 + antialiasGrayscale = 2 // D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE + antialiasAliased = 1 // D2D1_ANTIALIAS_MODE_ALIASED, so clip edges fall on whole pixels + fontWeightNormal = 400 + fontWeightSemiBold = 600 + fontWeightBold = 700 + textAlignLeading = 0 + textAlignTrailing = 1 + paragraphCenter = 2 + wordWrapNone = 1 + trimmingCharacter = 1 + svgViewport = 24.0 // Zappicon's viewBox + textFormatTitleSize = 15 + textFormatSmallSize = 12 + textFormatLabelSize = 11 // group labels, one size smaller than the small text, as on macOS + textFormatFamilyName = "Segoe UI" +) + +// D2D1_PRESENT_OPTIONS. presentRetainContents keeps the frame after it is shown, so the next +// frame can draw only what changed. presentImmediately shows the frame at once, rather than +// waiting for the screen refresh on the thread that runs every window of the app. +const ( + presentRetainContents = 1 + presentImmediately = 2 +) + +// floatCalls holds the COM methods that take floats. Each is bound with purego once per function +// pointer, because binding is slow and the vtable entries are the same for every object of a +// class. +type floatCalls struct { + createTextFormat map[uintptr]func(this uintptr, family *uint16, collection uintptr, weight, style, stretch uint32, size float32, locale *uint16, out *uintptr) int32 + createTextLayout map[uintptr]func(this uintptr, text *uint16, length uint32, format uintptr, maxWidth, maxHeight float32, out *uintptr) int32 + byValue byValueCalls // methods that pass a two-float struct, which differ per architecture +} + +func bound[F any](cache map[uintptr]F, fn uintptr) F { + if f, ok := cache[fn]; ok { + return f + } + var f F + purego.RegisterFunc(&f, fn) + cache[fn] = f + return f +} + +// svgKey identifies an icon in one colour, because Direct2D SVG documents include their colours. +type svgKey struct { + icon icons.Name + colour string +} + +// gfx is the view's Direct2D and DirectWrite state. The factories, text formats and text layouts +// live as long as the view. The render target and the resources it created (the brush and the SVG +// documents) are rebuilt when the device is lost or the DPI changes. +type gfx struct { + factory, dwrite uintptr + // text formats for a row title, small text, right-aligned small text and group labels + title, small, tail, label uintptr + layouts layoutCache + + rt uintptr // ID2D1HwndRenderTarget + dc5 uintptr // ID2D1DeviceContext5 of rt, for SVG, or 0 before Windows 10 1703 + brush uintptr // ID2D1SolidColorBrush, recoloured for each fill + svgs map[svgKey]uintptr + // whole is set when the target's pixels don't hold the last frame, because the target is new + // or was resized, so the next frame must draw everything. drawing is set between begin and + // end. + whole, drawing bool + + calls floatCalls +} + +func newGfx() (*gfx, error) { + g := &gfx{svgs: map[svgKey]uintptr{}, layouts: layoutCache{release: release}, calls: floatCalls{ + createTextFormat: map[uintptr]func(uintptr, *uint16, uintptr, uint32, uint32, uint32, float32, *uint16, *uintptr) int32{}, + createTextLayout: map[uintptr]func(uintptr, *uint16, uint32, uintptr, float32, float32, *uintptr) int32{}, + byValue: newByValueCalls(), + }} + if err := procD2D1CreateFactory.Find(); err != nil { + return nil, fmt.Errorf("direct2d: %w", err) + } + // D2D1_FACTORY_TYPE_SINGLE_THREADED, because only the UI thread draws + hr, _, _ := procD2D1CreateFactory.Call(0, uintptr(unsafe.Pointer(&iidD2D1Factory)), 0, uintptr(unsafe.Pointer(&g.factory))) + if failed(hr) { + return nil, fmt.Errorf("direct2d factory: %#x", uint32(hr)) + } + // DWRITE_FACTORY_TYPE_SHARED + hr, _, _ = procDWriteCreateFactory.Call(0, uintptr(unsafe.Pointer(&iidDWriteFactory)), uintptr(unsafe.Pointer(&g.dwrite))) + if failed(hr) { + release(g.factory) + return nil, fmt.Errorf("directwrite factory: %#x", uint32(hr)) + } + var err error + if g.title, err = g.textFormat(textFormatTitleSize, fontWeightNormal, textAlignLeading); err == nil { + if g.small, err = g.textFormat(textFormatSmallSize, fontWeightNormal, textAlignLeading); err == nil { + if g.tail, err = g.textFormat(textFormatSmallSize, fontWeightNormal, textAlignTrailing); err == nil { + g.label, err = g.textFormat(textFormatLabelSize, fontWeightSemiBold, textAlignLeading) + } + } + } + if err != nil { + for _, o := range []uintptr{g.title, g.small, g.tail, g.dwrite, g.factory} { + release(o) + } + return nil, err + } + return g, nil +} + +func (g *gfx) textFormat(size float32, weight, align uint32) (uintptr, error) { + family, _ := windows.UTF16PtrFromString(textFormatFamilyName) + locale, _ := windows.UTF16PtrFromString("en-us") + var f uintptr + // IDWriteFactory::CreateTextFormat, vtable 15 (fontSize is a FLOAT) + call := bound(g.calls.createTextFormat, method(g.dwrite, 15)) + // DWRITE_FONT_STYLE_NORMAL 0, DWRITE_FONT_STRETCH_NORMAL 5, and no collection, which means + // the system font collection + if hr := call(g.dwrite, family, 0, weight, 0, 5, size, locale, &f); hr < 0 || f == 0 { + return 0, fmt.Errorf("text format: %#x", uint32(hr)) + } + // IDWriteTextFormat::SetTextAlignment 3, SetParagraphAlignment 4, SetWordWrapping 5 + _, _, _ = syscall.SyscallN(method(f, 3), f, uintptr(align)) + _, _, _ = syscall.SyscallN(method(f, 4), f, paragraphCenter) + _, _, _ = syscall.SyscallN(method(f, 5), f, wordWrapNone) + var sign uintptr + // IDWriteFactory::CreateEllipsisTrimmingSign, vtable 20 + hr, _, _ := syscall.SyscallN(method(g.dwrite, 20), g.dwrite, f, uintptr(unsafe.Pointer(&sign))) + if !failed(hr) && sign != 0 { + t := trimming{Granularity: trimmingCharacter} + // IDWriteTextFormat::SetTrimming, vtable 9; the format keeps its own reference to the sign + _, _, _ = syscall.SyscallN(method(f, 9), f, uintptr(unsafe.Pointer(&t)), sign) + release(sign) + } + return f, nil +} + +// target creates the render target if there isn't one. It is transparent when the acrylic +// backdrop shows through (glass), and opaque otherwise. +func (g *gfx) target(hwnd uintptr, dpi uint32, glass bool) bool { + if g.rt != 0 { + return true + } + c := clientRect(hwnd) + alpha := uint32(alphaIgnore) + if glass { + alpha = alphaPremultiplied + } + props := renderTargetProps{Format: dxgiFormatB8G8R8A8, AlphaMode: alpha, DpiX: float32(dpi), DpiY: float32(dpi)} + hprops := hwndRenderTargetProps{Hwnd: hwnd, Width: uint32(max(c.width(), 1)), Height: uint32(max(c.height(), 1)), + PresentOptions: presentRetainContents | presentImmediately} + // ID2D1Factory::CreateHwndRenderTarget, vtable 14 + hr, _, _ := syscall.SyscallN(method(g.factory, 14), g.factory, uintptr(unsafe.Pointer(&props)), + uintptr(unsafe.Pointer(&hprops)), uintptr(unsafe.Pointer(&g.rt))) + if failed(hr) || g.rt == 0 { + g.rt = 0 + return false + } + // ClearType needs an opaque background. + if glass { + // ID2D1RenderTarget::SetTextAntialiasMode, vtable 34 + _, _, _ = syscall.SyscallN(method(g.rt, 34), g.rt, antialiasGrayscale) + } + white := colorF{1, 1, 1, 1} + // ID2D1RenderTarget::CreateSolidColorBrush, vtable 8 + hr, _, _ = syscall.SyscallN(method(g.rt, 8), g.rt, uintptr(unsafe.Pointer(&white)), 0, uintptr(unsafe.Pointer(&g.brush))) + if failed(hr) { + g.discard() + return false + } + // IUnknown::QueryInterface, vtable 0. SVG needs the device context from Windows 10 1703. + hr, _, _ = syscall.SyscallN(method(g.rt, 0), g.rt, uintptr(unsafe.Pointer(&iidD2D1DeviceContext5)), uintptr(unsafe.Pointer(&g.dc5))) + if failed(hr) { + g.dc5 = 0 + } + g.whole = true + return true +} + +func (g *gfx) discard() { + for k, d := range g.svgs { + release(d) + delete(g.svgs, k) + } + release(g.brush) + release(g.dc5) + release(g.rt) + g.brush, g.dc5, g.rt = 0, 0, 0 +} + +func (g *gfx) resize(w, h int32) { + if g.rt == 0 { + return + } + s := sizeU{uint32(max(w, 1)), uint32(max(h, 1))} + // ID2D1HwndRenderTarget::Resize, vtable 58 + _, _, _ = syscall.SyscallN(method(g.rt, 58), g.rt, uintptr(unsafe.Pointer(&s))) + g.whole = true +} + +// frame starts a frame that draws everything. Text layouts that the frame doesn't draw are +// released. +func (g *gfx) frame() { + g.whole = false + g.layouts.frame() +} + +// begin starts a frame that draws only the dirty area, which it clears to c. The rest keeps the +// pixels of the last frame (presentRetainContents). The clip limits Clear to the dirty area. +func (g *gfx) begin(dirty rectF, c colorF) { + // ID2D1RenderTarget::BeginDraw 48, SetTransform 30, Clear 47 + _, _, _ = syscall.SyscallN(method(g.rt, 48), g.rt) + g.drawing = true + _, _, _ = syscall.SyscallN(method(g.rt, 30), g.rt, uintptr(unsafe.Pointer(&identity))) + g.clip(dirty) + _, _, _ = syscall.SyscallN(method(g.rt, 47), g.rt, uintptr(unsafe.Pointer(&c))) +} + +// end finishes the frame. It returns false when the device was lost and the target must be +// created again. +func (g *gfx) end() bool { + g.unclip() + // ID2D1RenderTarget::EndDraw, vtable 49 (no tags) + hr, _, _ := syscall.SyscallN(method(g.rt, 49), g.rt, 0, 0) + g.drawing = false + return uint32(hr) != d2derrRecreateTarget +} + +func (g *gfx) colour(c colorF) { + // ID2D1SolidColorBrush::SetColor, vtable 8 + _, _, _ = syscall.SyscallN(method(g.brush, 8), g.brush, uintptr(unsafe.Pointer(&c))) +} + +func (g *gfx) fillRounded(r rectF, radius float32, c colorF) { + g.colour(c) + rr := roundedRect{Rect: r, RadiusX: radius, RadiusY: radius} + // ID2D1RenderTarget::FillRoundedRectangle, vtable 19 + _, _, _ = syscall.SyscallN(method(g.rt, 19), g.rt, uintptr(unsafe.Pointer(&rr)), g.brush) +} + +func (g *gfx) fillEllipse(e ellipse, c colorF) { + g.colour(c) + // ID2D1RenderTarget::FillEllipse, vtable 21 + _, _, _ = syscall.SyscallN(method(g.rt, 21), g.rt, uintptr(unsafe.Pointer(&e)), g.brush) +} + +// clip limits drawing to r until unclip. Each clip must be paired with an unclip before end, or +// EndDraw fails. Direct2D applies the transform that is set when the clip is pushed. Between draws +// that is the identity, so the transform that icon sets later doesn't move the clip. +func (g *gfx) clip(r rectF) { + // ID2D1RenderTarget::PushAxisAlignedClip, vtable 45 + _, _, _ = syscall.SyscallN(method(g.rt, 45), g.rt, uintptr(unsafe.Pointer(&r)), antialiasAliased) +} + +func (g *gfx) unclip() { + // ID2D1RenderTarget::PopAxisAlignedClip, vtable 46 + _, _, _ = syscall.SyscallN(method(g.rt, 46), g.rt) +} + +// text caches the layout (see layoutCache), because a layout doesn't depend on where the text is +// drawn or in what colour. +func (g *gfx) text(format uintptr, s string, r rectF, c colorF, bold []textRange) { + if s == "" { + return + } + w, h := r.Right-r.Left, r.Bottom-r.Top + layout := g.layouts.get(newTextKey(format, s, w, h, bold), func() uintptr { return g.textLayout(format, s, w, h, bold) }) + if layout == 0 { + return + } + g.colour(c) + // ID2D1RenderTarget::DrawTextLayout, vtable 28 (the origin is a D2D1_POINT_2F by value) + g.drawTextLayout(r.Left, r.Top, layout) +} + +// textLayout returns 0 when DirectWrite fails. +func (g *gfx) textLayout(format uintptr, s string, w, h float32, bold []textRange) uintptr { + u, err := windows.UTF16FromString(s) + if err != nil || len(u) < 2 { + return 0 + } + n := uint32(len(u) - 1) // without the NUL + var layout uintptr + // IDWriteFactory::CreateTextLayout, vtable 18 (maxWidth and maxHeight are FLOATs) + call := bound(g.calls.createTextLayout, method(g.dwrite, 18)) + if hr := call(g.dwrite, &u[0], n, format, w, h, &layout); hr < 0 || layout == 0 { + return 0 + } + for _, b := range bold { + // IDWriteTextLayout::SetFontWeight, vtable 32. DWRITE_TEXT_RANGE passed by value fits in + // one register. + _, _, _ = syscall.SyscallN(method(layout, 32), layout, fontWeightBold, uintptr(b.packed())) + } + return layout +} + +// icon draws the glyph in colour (#rrggbb) at x, y, size DIPs square. +func (g *gfx) icon(n icons.Name, colour string, x, y, size float32) { + if g.dc5 == 0 || n == "" { + return + } + k := svgKey{n, colour} + doc, ok := g.svgs[k] + if !ok { + doc = g.svgDocument(icons.Tinted(n, colour)) + g.svgs[k] = doc + } + if doc == 0 { + return + } + s := size / svgViewport + m := matrix3x2{M11: s, M22: s, Dx: x, Dy: y} + // ID2D1RenderTarget::SetTransform 30; ID2D1DeviceContext5::DrawSvgDocument 116 + _, _, _ = syscall.SyscallN(method(g.rt, 30), g.rt, uintptr(unsafe.Pointer(&m))) + _, _, _ = syscall.SyscallN(method(g.dc5, 116), g.dc5, doc) + _, _, _ = syscall.SyscallN(method(g.rt, 30), g.rt, uintptr(unsafe.Pointer(&identity))) +} + +// svgDocument returns 0 when Direct2D rejects svg. +func (g *gfx) svgDocument(svg string) uintptr { + if svg == "" { + return 0 + } + stream := memStream([]byte(svg)) + if stream == 0 { + return 0 + } + defer release(stream) + return g.createSvgDocument(stream, svgViewport, svgViewport) +} diff --git a/app/launcher/view/windows/d2d_amd64.go b/app/launcher/view/windows/d2d_amd64.go new file mode 100644 index 00000000..ad935f5e --- /dev/null +++ b/app/launcher/view/windows/d2d_amd64.go @@ -0,0 +1,36 @@ +//go:build windows && amd64 + +package windows + +import ( + "math" + "syscall" + "unsafe" +) + +// On amd64, a struct of two floats passed by value is eight bytes in one integer register (the +// Windows x64 convention), so these calls only need syscall.SyscallN. + +type byValueCalls struct{} + +func newByValueCalls() byValueCalls { return byValueCalls{} } + +// pack2 packs a D2D1_POINT_2F or D2D1_SIZE_F into the register value that holds it. +func pack2(a, b float32) uintptr { + return uintptr(math.Float32bits(a)) | uintptr(math.Float32bits(b))<<32 +} + +func (g *gfx) drawTextLayout(x, y float32, layout uintptr) { + // ID2D1RenderTarget::DrawTextLayout, vtable 28: (origin, layout, brush, D2D1_DRAW_TEXT_OPTIONS_NONE) + _, _, _ = syscall.SyscallN(method(g.rt, 28), g.rt, pack2(x, y), layout, g.brush, 0) +} + +func (g *gfx) createSvgDocument(stream uintptr, w, h float32) uintptr { + var doc uintptr + // ID2D1DeviceContext5::CreateSvgDocument, vtable 115: (stream, viewportSize, out) + hr, _, _ := syscall.SyscallN(method(g.dc5, 115), g.dc5, stream, pack2(w, h), uintptr(unsafe.Pointer(&doc))) + if failed(hr) { + return 0 + } + return doc +} diff --git a/app/launcher/view/windows/d2d_arm64.go b/app/launcher/view/windows/d2d_arm64.go new file mode 100644 index 00000000..acf54e2d --- /dev/null +++ b/app/launcher/view/windows/d2d_arm64.go @@ -0,0 +1,33 @@ +//go:build windows && arm64 + +package windows + +// On arm64, a struct of two floats passed by value is a homogeneous floating-point aggregate. It +// is passed in two float registers, just like two float arguments. Go's syscalls never load float +// registers, so these calls go through purego. + +type byValueCalls struct { + drawTextLayout map[uintptr]func(this uintptr, x, y float32, layout, brush uintptr, options uint32) + createSvg map[uintptr]func(this, stream uintptr, w, h float32, out *uintptr) int32 +} + +func newByValueCalls() byValueCalls { + return byValueCalls{ + drawTextLayout: map[uintptr]func(uintptr, float32, float32, uintptr, uintptr, uint32){}, + createSvg: map[uintptr]func(uintptr, uintptr, float32, float32, *uintptr) int32{}, + } +} + +func (g *gfx) drawTextLayout(x, y float32, layout uintptr) { + // ID2D1RenderTarget::DrawTextLayout, vtable 28: (origin, layout, brush, D2D1_DRAW_TEXT_OPTIONS_NONE) + bound(g.calls.byValue.drawTextLayout, method(g.rt, 28))(g.rt, x, y, layout, g.brush, 0) +} + +func (g *gfx) createSvgDocument(stream uintptr, w, h float32) uintptr { + var doc uintptr + // ID2D1DeviceContext5::CreateSvgDocument, vtable 115: (stream, viewportSize, out) + if hr := bound(g.calls.byValue.createSvg, method(g.dc5, 115))(g.dc5, stream, w, h, &doc); hr < 0 { + return 0 + } + return doc +} diff --git a/app/launcher/view/windows/layout.go b/app/launcher/view/windows/layout.go new file mode 100644 index 00000000..4f74726e --- /dev/null +++ b/app/launcher/view/windows/layout.go @@ -0,0 +1,320 @@ +// Package windows is the launcher window on Windows, written in Go on top of Win32. The window is +// borderless but keeps DWM's frame, so it gets the shadow, the rounded corners of Windows 11 and, +// from 22H2, the acrylic backdrop behind the rows. A native EDIT control handles typing and input +// methods. It sits on an opaque band, because GDI can't draw dark text on glass. Direct2D and +// DirectWrite draw the rows and the icons. A live region announces the selected row to screen +// readers. +// +// There is no cgo. Win32 and COM are called through x/sys/windows, and purego handles the few COM +// calls that pass floats in registers, because Go's own Windows syscalls never load the float +// registers on arm64. +// +// This file holds the parts that don't call Win32. It builds on every platform, so its tests can +// run on any machine. +package windows + +import ( + "encoding/binary" + "fmt" + "math" + "sort" + "strings" + "time" + "unicode/utf16" + "unsafe" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +func px(dip, scale float64) int32 { return int32(math.Round(dip * scale)) } + +// drawDpi returns the DPI that the launcher draws at on a monitor with the given DPI and work +// area, in pixels. Windows' text size setting enlarges the whole launcher, as WebView2 enlarges +// the pages of the app's other windows. The enlargement is limited to what fits the work area. +func drawDpi(monitorDpi uint32, textScale float64, workW, workH int32) uint32 { + base := float64(monitorDpi) / 96 + scale := base * textScale + if workW > 0 && workH > 0 { + scale = min(scale, float64(workW)/view.Width, float64(workH)/view.FullHeight()) + } + return uint32(math.Round(max(scale, base) * 96)) +} + +const ( + vkTab = 0x09 + vkReturn = 0x0D + vkEscape = 0x1B + vkUp = 0x26 + vkDown = 0x28 + vkPeriod = 0xBE // VK_OEM_PERIOD, the key that types "." on most layouts +) + +// keyFor returns false to leave the key to the query box. Ctrl takes the place of ⌘, so Ctrl+. +// stops everything, as ⌘. does on macOS. Ctrl with Alt is AltGr on many layouts and types a +// character, so the launcher never takes it. +func keyFor(vk uint32, ctrl, shift, alt bool) (view.KeyEvent, bool) { + switch { + case vk == vkEscape: + return view.KeyEvent{Key: view.KeyEsc}, true + case vk == vkReturn: + return view.KeyEvent{Key: view.KeyEnter}, true + case vk == vkUp: + return view.KeyEvent{Key: view.KeyUp}, true + case vk == vkDown: + return view.KeyEvent{Key: view.KeyDown}, true + case vk == vkTab && !shift: + return view.KeyEvent{Key: view.KeyTab}, true + case !ctrl || alt: + return view.KeyEvent{}, false + case vk == 'K': + return view.KeyEvent{Key: view.KeyActions}, true + case vk >= '0' && vk <= '9': + return view.KeyEvent{Key: view.KeyRow, Char: rune(vk)}, true + case vk >= 'A' && vk <= 'Z': + return view.KeyEvent{Key: view.KeyRow, Char: rune(vk-'A') + 'a'}, true + case vk == vkPeriod: + return view.KeyEvent{Key: view.KeyRow, Char: '.'}, true + } + return view.KeyEvent{}, false +} + +// colorF is a D2D1_COLOR_F: red, green, blue and alpha from 0 to 1. +type colorF struct{ R, G, B, A float32 } + +type palette struct { + // surface is the colour of the band behind the query box, and of the whole window when there + // is no acrylic. + surface colorF + text, secondary colorF + separator colorF // the hairline under the query band + icon string // #rrggbb + muted string // #rrggbb, the secondary text colour over the surface, for a glyph + // Windows 11's red and green for text and glyphs. critical is used for the icon of a danger + // row, for the stop button while something is running, and for a failed status. success is + // used for a status that succeeded. + critical, success colorF + danger colorF // the highlight of a selected danger row, under the white onAccent text +} + +// onAccent holds the text colours of the selected row on the accent colour. They are the same in +// both modes. +var onAccent = struct { + text, secondary colorF + icon string +}{colorF{1, 1, 1, 1}, colorF{1, 1, 1, 0.8}, "#ffffff"} + +// paletteFor takes its colours from Windows 11's own flyout surfaces. +func paletteFor(dark bool) palette { + red := colorF{0.769, 0.169, 0.110, 1} // #c42b1c + if dark { + return palette{ + surface: colorF{0.125, 0.125, 0.125, 1}, // #202020 + text: colorF{1, 1, 1, 1}, + secondary: colorF{1, 1, 1, 0.6}, + separator: colorF{1, 1, 1, 0.08}, + icon: "#e6e6e6", + muted: "#a6a6a6", + critical: colorF{1, 0.6, 0.643, 1}, // #ff99a4 + success: colorF{0.424, 0.796, 0.373, 1}, // #6ccb5f + danger: red, + } + } + return palette{ + surface: colorF{0.976, 0.976, 0.976, 1}, // #f9f9f9 + text: colorF{0.1, 0.1, 0.1, 1}, + secondary: colorF{0, 0, 0, 0.6}, + separator: colorF{0, 0, 0, 0.08}, + icon: "#1f1f1f", + muted: "#646464", + critical: red, + success: colorF{0.059, 0.482, 0.059, 1}, // #0f7b0f + danger: red, + } +} + +// colorRef converts c to a GDI COLORREF (0x00bbggrr) for the query box. Alpha is dropped. +func colorRef(c colorF) uint32 { + b := func(f float32) uint32 { return uint32(math.Round(float64(f) * 255)) } + return b(c.R) | b(c.G)<<8 | b(c.B)<<16 +} + +// hex converts c to #rrggbb for a glyph. Alpha is dropped. +func hex(c colorF) string { + r := colorRef(c) + return fmt.Sprintf("#%02x%02x%02x", r&0xFF, r>>8&0xFF, r>>16&0xFF) +} + +// announcement returns what a screen reader says for the selected row. +func announcement(s view.Snapshot) string { + if s.Selected < 0 || s.Selected >= len(s.Rows) { + return "" + } + r := s.Rows[s.Selected] + parts := make([]string, 0, 4) + for _, p := range []string{r.Group, r.Title, r.Subtitle, r.Tail} { + if p != "" { + parts = append(parts, p) + } + } + return strings.Join(parts, ", ") +} + +// textRange is a run of text measured in UTF-16 code units, as DirectWrite counts them. +type textRange struct { + start, length uint32 +} + +// packed returns the range as a DWRITE_TEXT_RANGE passed by value: two UINT32s in one register. +func (r textRange) packed() uint64 { return uint64(r.start) | uint64(r.length)<<32 } + +// boldRanges converts the bold runes of s, given as rune indexes by the launcher, into UTF-16 +// runs. A rune outside the BMP takes two units, and adjacent runes are merged into one run. +func boldRanges(s string, bold []int) []textRange { + if len(bold) == 0 { + return nil + } + runes := []rune(s) + offsets := make([]uint32, len(runes)+1) + for i, r := range runes { + n := uint32(1) + if utf16.RuneLen(r) == 2 { + n = 2 + } + offsets[i+1] = offsets[i] + n + } + idx := append([]int(nil), bold...) + sort.Ints(idx) + var out []textRange + for _, i := range idx { + if i < 0 || i >= len(runes) { + continue + } + start, end := offsets[i], offsets[i+1] + if last := len(out) - 1; last >= 0 && out[last].start+out[last].length >= start { + if e := out[last].start + out[last].length; end > e { + out[last].length += end - e + } + continue + } + out = append(out, textRange{start: start, length: end - start}) + } + return out +} + +// wordStart returns the position that Ctrl+Backspace deletes back to from caret, in UTF-16 +// units. It skips the spaces before the caret, then the word before them. +func wordStart(text []uint16, caret int) int { + if caret > len(text) { + caret = len(text) + } + i := caret + for i > 0 && isSpace(text[i-1]) { + i-- + } + for i > 0 && !isSpace(text[i-1]) { + i-- + } + return i +} + +func isSpace(u uint16) bool { return u == ' ' || u == '\t' } + +// dropGrace is how long a blur waits after the mouse button is released over the window (see +// blurDue). +const dropGrace = 250 * time.Millisecond + +// blurDue reports whether a blur that is waiting on the mouse should go ahead. It waits while a +// button is down, because a drag holds the button down the whole time and may end over the +// window. It also waits for dropGrace after the button is released over the window, because a +// drag may have just ended there. The drop (WM_DROPFILES) arrives after the button release, +// because the app the drag came from posts it. +func blurDue(down, over bool, up time.Duration) bool { + return !down && (!over || up >= dropGrace) +} + +// textKey identifies a text layout by its text, format, box size and bold runs (packed). +type textKey struct { + format uintptr + text string + w, h float32 + bold string +} + +func newTextKey(format uintptr, text string, w, h float32, bold []textRange) textKey { + b := make([]byte, 0, 8*len(bold)) + for _, r := range bold { + b = binary.LittleEndian.AppendUint32(b, r.start) + b = binary.LittleEndian.AppendUint32(b, r.length) + } + return textKey{format: format, text: text, w: w, h: h, bold: string(b)} +} + +// layoutCache keeps the text layouts that were drawn. A frame that only moves the spinner or the +// footer line doesn't recreate them, and neither does a new snapshot for its unchanged rows. Each +// full frame (see frame) starts a new generation. Layouts that the previous frame drew but this one +// doesn't are released. +type layoutCache struct { + cur, last map[textKey]uintptr + release func(uintptr) +} + +// get returns 0 when build fails. +func (c *layoutCache) get(k textKey, build func() uintptr) uintptr { + if l, ok := c.cur[k]; ok { + return l + } + l, ok := c.last[k] + if ok { + delete(c.last, k) + } else if l = build(); l == 0 { + return 0 + } + if c.cur == nil { + c.cur = map[textKey]uintptr{} + } + c.cur[k] = l + return l +} + +// frame starts a full frame and releases the layouts that the previous frame didn't draw. +func (c *layoutCache) frame() { + for _, l := range c.last { + c.release(l) + } + clear(c.last) + c.cur, c.last = c.last, c.cur +} + +// swapProgress is a cubic ease-out from 0 to 1 over view.SwapFor. +func swapProgress(elapsed time.Duration) float32 { + t := min(max(float64(elapsed)/float64(view.SwapFor), 0), 1) + return float32(1 - math.Pow(1-t, 3)) +} + +// spinnerDot returns the position of dot i relative to the spinner's centre, in DIPs. The first +// dot is at the top. +func spinnerDot(i int) (x, y float32) { + a := float64(i)*2*math.Pi/8 - math.Pi/2 + return float32(6 * math.Cos(a)), float32(6 * math.Sin(a)) +} + +// variant is a VARIANT holding a VT_I4. It has the type, three reserved words, the value, and the +// rest of the union (24 bytes on 64-bit Windows). +type variant struct { + VT uint16 + _ [3]uint16 + Val int32 + _ int32 + _ uint64 +} + +// aligned16 copies v to memory aligned to 16 bytes. The x64 convention requires this for a struct +// that is passed by value as a pointer to a copy, and Go's allocator doesn't guarantee it for every +// size. +func aligned16[T any](v T) *T { + buf := make([]byte, unsafe.Sizeof(v)+15) + off := (16 - uintptr(unsafe.Pointer(&buf[0]))%16) % 16 + p := (*T)(unsafe.Pointer(&buf[off])) + *p = v + return p +} diff --git a/app/launcher/view/windows/layout_test.go b/app/launcher/view/windows/layout_test.go new file mode 100644 index 00000000..caefa696 --- /dev/null +++ b/app/launcher/view/windows/layout_test.go @@ -0,0 +1,261 @@ +package windows + +import ( + "reflect" + "testing" + "time" + "unicode/utf16" + "unsafe" + + "github.com/rclone/rclone-ui/app/launcher/view" +) + +func TestKeyFor(t *testing.T) { + for _, c := range []struct { + vk uint32 + ctrl, shift, alt bool + want view.KeyEvent + ok bool + }{ + {vkEscape, false, false, false, view.KeyEvent{Key: view.KeyEsc}, true}, + {vkReturn, false, false, false, view.KeyEvent{Key: view.KeyEnter}, true}, + {vkUp, false, false, false, view.KeyEvent{Key: view.KeyUp}, true}, + {vkDown, false, false, false, view.KeyEvent{Key: view.KeyDown}, true}, + {vkTab, false, false, false, view.KeyEvent{Key: view.KeyTab}, true}, + {vkTab, false, true, false, view.KeyEvent{}, false}, // shift-tab + {'K', true, false, false, view.KeyEvent{Key: view.KeyActions}, true}, + {'3', true, false, false, view.KeyEvent{Key: view.KeyRow, Char: '3'}, true}, + {'B', true, false, false, view.KeyEvent{Key: view.KeyRow, Char: 'b'}, true}, + {'B', false, false, false, view.KeyEvent{}, false}, // typing + {'Q', true, false, true, view.KeyEvent{}, false}, // AltGr+Q types @ + {0x70, true, false, false, view.KeyEvent{}, false}, // Ctrl+F1 + // Ctrl+. stops everything. A . alone, or with AltGr, is typed. + {vkPeriod, true, false, false, view.KeyEvent{Key: view.KeyRow, Char: '.'}, true}, + {vkPeriod, false, false, false, view.KeyEvent{}, false}, + {vkPeriod, true, false, true, view.KeyEvent{}, false}, + } { + got, ok := keyFor(c.vk, c.ctrl, c.shift, c.alt) + if ok != c.ok || got != c.want { + t.Errorf("keyFor(%#x, ctrl=%v shift=%v alt=%v) = %+v, %v", c.vk, c.ctrl, c.shift, c.alt, got, ok) + } + } +} + +func TestBoldRanges(t *testing.T) { + for _, c := range []struct { + s string + bold []int + want []textRange + }{ + {"Move", nil, nil}, + {"Move", []int{0, 1}, []textRange{{0, 2}}}, + {"Show Remotes", []int{7, 8, 5}, []textRange{{5, 1}, {7, 2}}}, + // 😀 is two UTF-16 units, so the runes after it are shifted by one + {"😀 docs", []int{0, 2, 3}, []textRange{{0, 2}, {3, 2}}}, + {"ab", []int{5, -1, 1, 1}, []textRange{{1, 1}}}, + } { + if got := boldRanges(c.s, c.bold); !reflect.DeepEqual(got, c.want) { + t.Errorf("boldRanges(%q, %v) = %v, want %v", c.s, c.bold, got, c.want) + } + } + if got := (textRange{start: 3, length: 2}).packed(); got != 3|2<<32 { + t.Fatalf("packed = %#x", got) + } +} + +func TestWordStart(t *testing.T) { + text := utf16.Encode([]rune("copy gdrive: ")) + for _, c := range []struct{ caret, want int }{ + {len(text), 5}, // skips the spaces, then the word + {4, 0}, + {5, 0}, + {0, 0}, + {99, 5}, + } { + if got := wordStart(text, c.caret); got != c.want { + t.Errorf("wordStart(%d) = %d, want %d", c.caret, got, c.want) + } + } +} + +func TestBlurDue(t *testing.T) { + for _, c := range []struct { + down, over bool + up time.Duration + want bool + }{ + {true, true, 0, false}, + {true, false, time.Hour, false}, // still down, so a drag may come back + {false, false, 0, true}, + {false, true, 0, false}, + {false, true, dropGrace - time.Millisecond, false}, + {false, true, dropGrace, true}, + } { + if got := blurDue(c.down, c.over, c.up); got != c.want { + t.Errorf("blurDue(down=%v, over=%v, %v) = %v", c.down, c.over, c.up, got) + } + } +} + +// TestLayoutCache checks that a layout which a full frame doesn't draw is released at the next +// frame, and created again if it comes back. +func TestLayoutCache(t *testing.T) { + var made, released []uintptr + next := uintptr(0) + build := func() uintptr { next++; made = append(made, next); return next } + c := layoutCache{release: func(l uintptr) { released = append(released, l) }} + a, b := newTextKey(1, "a", 10, 16, nil), newTextKey(1, "b", 10, 16, []textRange{{0, 1}}) + if newTextKey(1, "b", 10, 16, nil) == b || newTextKey(2, "b", 10, 16, []textRange{{0, 1}}) == b { + t.Fatal("keys of different layouts are equal") + } + + c.frame() + la, lb := c.get(a, build), c.get(b, build) + if c.get(a, build) != la || len(made) != 2 { + t.Fatalf("made %v", made) + } + c.frame() // draws a only + if c.get(a, build) != la || len(released) != 0 { + t.Fatalf("a: made %v, released %v", made, released) + } + c.frame() // b wasn't drawn for a full frame + if len(released) != 1 || released[0] != lb { + t.Fatalf("released %v, want [%d]", released, lb) + } + if c.get(b, build) == lb || len(made) != 3 { + t.Fatalf("b again: made %v", made) + } + x := newTextKey(1, "x", 1, 1, nil) + if c.get(x, func() uintptr { return 0 }) != 0 { + t.Fatal("a failed layout") + } + if _, kept := c.cur[x]; kept { + t.Fatal("a failed layout is kept") + } +} + +func TestSwapProgress(t *testing.T) { + for _, c := range []struct { + elapsed time.Duration + want float32 + }{ + {-time.Millisecond, 0}, + {0, 0}, + {view.SwapFor / 2, 0.875}, + {view.SwapFor, 1}, + {2 * view.SwapFor, 1}, + } { + if got := swapProgress(c.elapsed); got != c.want { + t.Errorf("swapProgress(%v) = %v, want %v", c.elapsed, got, c.want) + } + } +} + +func TestSpinnerDot(t *testing.T) { + if x, y := spinnerDot(0); x > 1e-5 || x < -1e-5 || y != -6 { + t.Fatalf("dot 0 at %v, %v", x, y) + } + if x, y := spinnerDot(2); x != 6 || y > 1e-5 || y < -1e-5 { + t.Fatalf("dot 2 at %v, %v", x, y) + } +} + +func TestAnnouncement(t *testing.T) { + s := view.Snapshot{Rows: []view.Row{ + {Title: "Move", Subtitle: "Move files from a source to a destination"}, + {Title: "gdrive:Photos", Tail: "/Volumes/Photos"}, + {Group: "Running", Title: "Copy", Tail: "40%"}, + }} + for _, c := range []struct { + selected int + want string + }{ + {0, "Move, Move files from a source to a destination"}, + {1, "gdrive:Photos, /Volumes/Photos"}, + {2, "Running, Copy, 40%"}, + {-1, ""}, + {3, ""}, + } { + s.Selected = c.selected + if got := announcement(s); got != c.want { + t.Errorf("selected %d: got %q, want %q", c.selected, got, c.want) + } + } +} + +// TestColorRef checks GDI's byte order, which is blue, green, red. +func TestColorRef(t *testing.T) { + if got := colorRef(colorF{1, 0, 0, 1}); got != 0x0000ff { + t.Errorf("red: %#06x", got) + } + if got := colorRef(paletteFor(true).surface); got != 0x202020 { + t.Errorf("dark surface: %#06x", got) + } + if got := colorRef(paletteFor(false).surface); got != 0xf9f9f9 { + t.Errorf("light surface: %#06x", got) + } +} + +func TestPalette(t *testing.T) { + for _, c := range []struct { + dark bool + critical, success string + }{ + {false, "#c42b1c", "#0f7b0f"}, + {true, "#ff99a4", "#6ccb5f"}, + } { + p := paletteFor(c.dark) + if got := hex(p.critical); got != c.critical { + t.Errorf("dark=%v critical %s", c.dark, got) + } + if got := hex(p.success); got != c.success { + t.Errorf("dark=%v success %s", c.dark, got) + } + if got := hex(p.danger); got != "#c42b1c" || p.danger.A != 1 { + t.Errorf("dark=%v danger %s", c.dark, got) + } + } +} + +func TestVariantLayout(t *testing.T) { + var v variant + if s, o := unsafe.Sizeof(v), unsafe.Offsetof(v.Val); s != 24 || o != 8 { + t.Fatalf("size %d, value at %d", s, o) + } +} + +func TestAligned16(t *testing.T) { + for i := range 32 { + v := variant{VT: 3, Val: int32(i)} + p := aligned16(v) + if uintptr(unsafe.Pointer(p))%16 != 0 || *p != v { + t.Fatalf("copy %d at %p: %+v", i, p, *p) + } + var g [16]byte + g[0] = byte(i) + if q := aligned16(g); uintptr(unsafe.Pointer(q))%16 != 0 || *q != g { + t.Fatalf("guid copy %d at %p", i, q) + } + } +} + +func TestDrawDpi(t *testing.T) { + for _, c := range []struct { + name string + monitor uint32 + text float64 + workW, workH int32 + want uint32 + }{ + {"no text scale", 144, 1, 1686, 834, 144}, + {"text scale on a large screen", 96, 1.5, 2560, 1400, 144}, + {"both scales", 144, 1.25, 3840, 2100, 180}, + {"limited by the width of the work area", 96, 2.25, 1206, 824, 165}, + {"never below the monitor's own scale", 192, 1.5, 1206, 824, 192}, + {"an unknown work area", 120, 1.5, 0, 0, 180}, + } { + if got := drawDpi(c.monitor, c.text, c.workW, c.workH); got != c.want { + t.Errorf("%s: drawDpi = %d, want %d", c.name, got, c.want) + } + } +} diff --git a/app/launcher/view/windows/view.go b/app/launcher/view/windows/view.go new file mode 100644 index 00000000..8b8aa794 --- /dev/null +++ b/app/launcher/view/windows/view.go @@ -0,0 +1,991 @@ +//go:build windows + +package windows + +import ( + "errors" + "fmt" + "log/slog" + "math" + "runtime/debug" + "time" + "unicode/utf16" + "unsafe" + + "golang.org/x/sys/windows" + + "github.com/rclone/rclone-ui/app/launcher/icons" + "github.com/rclone/rclone-ui/app/launcher/view" + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/i18n" +) + +// View is the launcher window. There is one per process, and the window procedures find it +// through current. +type View struct { + ev view.Events + g *gfx + + hwnd, edit uintptr + editProc uintptr // the EDIT's own window procedure, which ours passes other messages to + font uintptr // the query box font, at dpi + band uintptr // the brush of the query band, behind the box + glass bool // the acrylic backdrop was applied, so the rows are drawn on a transparent window + dark bool // the system's app mode + pal palette + live *liveRegion + dpi uint32 // what the launcher draws at (see drawDpi) + monDpi uint32 // the monitor's own DPI + + snap view.Snapshot + visible bool + left, top int32 // the window's top-left, in screen pixels + prev uintptr // the window that was in the foreground before Show; Hide gives it back + settingFrame bool // set during our own move or resize + settingText bool // set during SetQuery, so the edit isn't taken for the user's + cursor point // the last known pointer position, in screen pixels + wheel int32 // wheel delta that doesn't yet add up to a whole row + dragFrom rect // the window rectangle when the user started dragging it + spin int // the spinner's current step + ticking bool + stopHover bool // the pointer is on the stop-everything button + // line is the footer line. While a swap runs, starting at swapStart, swapFrom is the line + // being replaced. + line, swapFrom view.Line + swapStart time.Time + swapping bool + + upAt time.Time // when the mouse button was released, while a blur waits on it (see waitMouse) + handOff bool // the next Hide passes the foreground on (see HandOff) + showHook uintptr // hook that watches for our windows being shown after a hand-off (see awaitWindow) +} + +var current *View + +var ( + wndProcCallback = windows.NewCallback(wndProc) + editProcCallback = windows.NewCallback(editProc) + windowShownCallback = windows.NewCallback(windowShown) +) + +// The wait for the window that a hand-off's action opens. handOffFor is in milliseconds. It covers +// the longest time the window takes to appear, which is when its page loads or after 2 seconds, +// plus time for the action to open it. +const ( + handOffTimer = 4 + handOffFor = 5000 +) + +var logger = slog.Default() + +// SetLog sends the window's panic logs to l. Call it on the main thread, where the callbacks run. +func SetLog(l *slog.Logger) { logger = l } + +const ( + className = "RcuiLauncher" + spinTimer = 1 + mouseTimer = 2 // waits for the mouse button after a blur, because a drag may still arrive + swapTimer = 3 // animates the footer swap + spinEvery = 80 // ms + swapEvery = 16 // ms per frame; Windows rounds timers up to its own interval, about 15.6 ms + spinDots = 8 + editID = 1 + queryFontPt = 20.0 // DIPs +) + +var transparent = colorF{} + +// New builds the window, hidden. It must be called once, on the main thread. +func New(ev view.Events) (*View, error) { + if current != nil { + return nil, errors.New("the launcher's window exists already") + } + g, err := newGfx() + if err != nil { + return nil, err + } + v := &View{ev: ev, g: g, dpi: 96} + current = v + if err := v.build(); err != nil { + current = nil + return nil, err + } + return v, nil +} + +func (v *View) build() error { + instance, _, _ := procGetModuleHandleW.Call(0) + cursor, _, _ := procLoadCursorW.Call(0, idcArrow) + name, _ := windows.UTF16PtrFromString(className) + wc := wndClassEx{ + Size: uint32(unsafe.Sizeof(wndClassEx{})), + Style: csHRedraw | csVRedraw, + WndProc: wndProcCallback, + Instance: instance, + Cursor: cursor, + ClassName: name, + } + if r, _, err := procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc))); r == 0 { + return fmt.Errorf("register the launcher's window class: %w", err) + } + // The title doesn't show, since the window has no title bar, but screen readers read it. It + // keeps the language that the app started in. + title, _ := windows.UTF16PtrFromString(i18n.T("Launcher")) + // The window has a thick frame, although none of it shows (see WM_NCCALCSIZE). The frame keeps + // DWM's shadow, rounded corners and backdrop, which a bare popup doesn't get. As a tool window, + // it has no taskbar button and no Alt+Tab entry. + hwnd, _, err := procCreateWindowExW.Call(wsExToolWindow|wsExTopmost, uintptr(unsafe.Pointer(name)), + uintptr(unsafe.Pointer(title)), wsPopup|wsThickFrame|wsClipChildren, + 0, 0, uintptr(px(view.Width, 1)), uintptr(px(view.Height(view.Snapshot{}), 1)), 0, 0, instance, 0) + if hwnd == 0 { + return fmt.Errorf("create the launcher's window: %w", err) + } + v.hwnd = hwnd + v.monDpi = windowDpi(hwnd) + v.dpi = v.monDpi + + _ = dwmSet(hwnd, dwmwaWindowCornerPreference, dwmwcpRound) + _ = dwmSet(hwnd, dwmwaTransitionsForceDisabled, 1) // appear at once, as a launcher should + // layout sets the frame area through which DWM shows the backdrop, because it changes with the + // height. + v.glass = dwmSet(hwnd, dwmwaSystemBackdropType, dwmsbtTransientWindow) + v.applyTheme() + setWindowPos(hwnd, 0, 0, 0, 0, 0, swpNoMove|swpNoSize|swpNoZOrder|swpNoActivate|swpFrameChanged) + + edit, _ := windows.UTF16PtrFromString("EDIT") + empty, _ := windows.UTF16PtrFromString("") + v.edit, _, err = procCreateWindowExW.Call(0, uintptr(unsafe.Pointer(edit)), uintptr(unsafe.Pointer(empty)), + wsChild|wsVisible|esAutoHScroll, 0, 0, 10, 10, hwnd, editID, instance, 0) + if v.edit == 0 { + return fmt.Errorf("create the launcher's query box: %w", err) + } + // let the launcher see keys before the box does + v.editProc, _, _ = procSetWindowLongPtrW.Call(v.edit, gwlpWndProc, editProcCallback) + v.live = newLiveRegion(hwnd, instance) + // Files dragged from Explorer arrive as WM_DROPFILES. The box, as a child window, passes them + // up. + _, _, _ = procDragAcceptFiles.Call(hwnd, 1) + v.setFont() + v.layout() + return nil +} + +// applyTheme follows the system's app mode. The frame's dark mode also sets the acrylic tint. +func (v *View) applyTheme() { + v.dark = !appsUseLightTheme() + v.pal = paletteFor(v.dark) + dark := uint32(0) + if v.dark { + dark = 1 + } + _ = dwmSet(v.hwnd, dwmwaUseImmersiveDarkMode, dark) + old := v.band + v.band = solidBrush(v.pal.surface) + deleteObject(old) + invalidate(v.hwnd, nil) + if v.edit != 0 { // passing a null window would invalidate every window + invalidate(v.edit, nil) + } +} + +func (v *View) setFont() { + old := v.font + v.font = queryFont(queryFontPt, v.dpi) + sendMessage(v.edit, wmSetFont, v.font, 1) + deleteObject(old) +} + +func (v *View) scale() float64 { return float64(v.dpi) / 96 } + +// useMonitor sets the DPI that the launcher draws at on mon, whose own DPI is monDpi. +func (v *View) useMonitor(mon uintptr, monDpi uint32) { + v.monDpi = monDpi + var w, h int32 + if work, ok := workArea(mon); ok { + w, h = work.width(), work.height() + } + v.dpi = drawDpi(monDpi, platform.TextScale(), w, h) +} + +func (v *View) Show(at *view.Placement) { + v.handOff = false + v.stopAwaiting() // the user wants the launcher now, not the window an action opens + was := v.dpi + var mon uintptr + if at != nil { + mon = monitorAt(point{int32(at.Left) + 1, int32(at.Top) + 1}, monitorToNull) + } + if mon != 0 { + v.left, v.top = int32(at.Left), int32(at.Top) + v.useMonitor(mon, monitorDpi(mon)) + } else { + mon = monitorAt(cursorPos(), monitorToNearest) + v.useMonitor(mon, monitorDpi(mon)) + if work, ok := workArea(mon); ok { + dx, dy := view.Centred(float64(work.width()), float64(work.height()), v.scale()) + v.left, v.top = work.Left+int32(math.Round(dx)), work.Top+int32(math.Round(dy)) + } + } + if v.dpi != was { + v.g.discard() + v.setFont() + } + v.visible = true + // Record the current pointer position, so rows appearing under it don't count as a move and + // don't change the selection. + v.cursor = cursorPos() + v.wheel = 0 + v.prev = foreground() + v.layout() + _, _, _ = procShowWindow.Call(v.hwnd, swShow) + forceForeground(v.hwnd) + setFocus(v.edit) + v.tick() +} + +// forceForeground makes hwnd, one of our windows, the foreground window. Windows allows this for +// the foreground process, or for the process that received the last input, such as the launcher's +// hotkey. If Windows refuses anyway, it first taps Alt, because Windows lets the foreground change +// while Alt is down, since it could be Alt+Tab. If that fails too, it attaches to the input of the +// foreground thread. +func forceForeground(hwnd uintptr) { + if setForeground(hwnd) && foreground() == hwnd { + return + } + // Use the left Alt, because the right one is AltGr on many layouts, which adds its own Ctrl. + keyTap(vkMenu, 0) + ok := setForeground(hwnd) + keyTap(vkMenu, keyeventfKeyUp) // the launcher blocks the menu activation this causes (WM_SYSCOMMAND) + if ok && foreground() == hwnd { + return + } + fg := foreground() + theirs, ours := windowThread(fg), uintptr(windows.GetCurrentThreadId()) + if fg == 0 || theirs == 0 || theirs == ours { + return + } + _, _, _ = procAttachThreadInput.Call(theirs, ours, 1) + _, _, _ = procBringWindowToTop.Call(hwnd) + _ = setForeground(hwnd) + _, _, _ = procAttachThreadInput.Call(theirs, ours, 0) +} + +// HandOff makes the next Hide pass the foreground to the window that the running action opens +// (Platform.Activate). Call it on the main thread while the key press or click that runs the +// action is being handled. The foreground isn't given back to the window the user was in, and the +// window that the action opens is brought to the front when it appears (see awaitWindow). +func HandOff() { + if v := current; v != nil && v.visible { + v.handOff = true + } +} + +// Hide gives the foreground back to the window that had it before Show, unless a hand-off is +// pending. It leaves the foreground alone when the launcher doesn't have it, because the user +// clicked somewhere else. +func (v *View) Hide() { + ours := foreground() == v.hwnd + handOff := v.handOff + v.handOff = false + v.visible = false // clear it before the deactivation that Hide causes, which isn't a blur + v.stopHover = false + v.endSwap() + _, _, _ = procKillTimer.Call(v.hwnd, mouseTimer) + _, _, _ = procShowWindow.Call(v.hwnd, swHide) + v.tick() + v.live.forget() + switch { + case !ours: + case handOff: + v.awaitWindow() + case v.prev != 0 && v.prev != v.hwnd && isWindow(v.prev): + _ = setForeground(v.prev) + } + v.prev = 0 +} + +// awaitWindow watches, for up to handOffFor, for the window that a hand-off's action opens. That +// window appears only once its page has loaded. By then the key release has gone to the window +// that Windows activated when the launcher hid. Windows may then refuse our window the foreground, +// because only the foreground process or the one with the last input may change it. windowShown +// then brings the window to the foreground. +func (v *View) awaitWindow() { + if v.showHook == 0 { + v.showHook = hookShows(windowShownCallback) + } + _, _, _ = procSetTimer.Call(v.hwnd, handOffTimer, handOffFor, 0) +} + +func (v *View) stopAwaiting() { + _, _, _ = procKillTimer.Call(v.hwnd, handOffTimer) + if v.showHook != 0 { + unhook(v.showHook) + v.showHook = 0 + } +} + +// windowShown is called when a window of this process is shown while awaitWindow is waiting. The +// first window other than the launcher that can take the foreground is the one the action opened. +// That window has already asked for the foreground itself (Show, then Focus). If Windows refused, +// windowShown brings it to the foreground the same way Show does for the launcher. +func windowShown(_, _, hwnd, object, child, _, _ uintptr) uintptr { + defer func() { + if p := recover(); p != nil { + panicked("a window shown", p) + } + }() + v := current + // object and child are LONGs, so only their low 32 bits are set + if v == nil || v.showHook == 0 || hwnd == v.hwnd || int32(object) != objidWindow || int32(child) != childidSelf || !activatable(hwnd) { + return 0 + } + v.stopAwaiting() + if foreground() != hwnd { + forceForeground(hwnd) + } + return 0 +} + +func (v *View) Visible() bool { return v.visible } + +func (v *View) SetQuery(text string, selectAll bool) { + v.settingText = true + setWindowText(v.edit, text) + v.settingText = false + if selectAll { + sendMessage(v.edit, emSetSel, 0, ^uintptr(0)) + return + } + n := uintptr(len(windowText(v.edit))) + sendMessage(v.edit, emSetSel, n, n) +} + +func (v *View) Render(s view.Snapshot) { + if s.Placeholder != v.snap.Placeholder { + if p, err := windows.UTF16PtrFromString(s.Placeholder); err == nil { + // show the placeholder even while the box has the caret + _, _, _ = procSendMessageW.Call(v.edit, emSetCueBanner, 1, uintptr(unsafe.Pointer(p))) + } + } + v.snap = s + v.setLine(view.FooterLine(s)) + v.tick() + v.layout() + invalidate(v.hwnd, nil) + if v.visible { + v.live.say(announcement(s)) + } +} + +// setLine makes l the footer line, animated when view.Swaps allows it. A swap that starts while +// another one runs starts from the line that was coming in. +func (v *View) setLine(l view.Line) { + if v.visible && view.Swaps(v.line, l) { + v.swapFrom, v.swapStart = v.line, time.Now() + if !v.swapping { + v.swapping = true + _, _, _ = procSetTimer.Call(v.hwnd, swapTimer, swapEvery, 0) + } + } + v.line = l +} + +func (v *View) endSwap() { + if v.swapping { + v.swapping = false + _, _, _ = procKillTimer.Call(v.hwnd, swapTimer) + } +} + +func (v *View) tick() { + want := v.visible && v.snap.Status.Kind == view.StatusLoading + if want == v.ticking { + return + } + v.ticking = want + if want { + _, _, _ = procSetTimer.Call(v.hwnd, spinTimer, spinEvery, 0) + } else { + _, _, _ = procKillTimer.Call(v.hwnd, spinTimer) + } +} + +func (v *View) layout() { + s := v.scale() + w, h := px(view.Width, s), px(view.Height(v.snap), s) + v.settingFrame = true + if v.visible { + setWindowPos(v.hwnd, hwndTopmost, v.left, v.top, w, h, swpNoActivate) + } else { + setWindowPos(v.hwnd, 0, 0, 0, w, h, swpNoMove|swpNoZOrder|swpNoActivate) + } + v.settingFrame = false + if v.glass { + // The rows area is part of the frame, where DWM shows the acrylic through. The query band + // isn't, because GDI text has no alpha and would be transparent there. + extendFrame(v.hwnd, margins{0, 0, 0, h - px(view.QueryH, s)}) + } else { + extendFrame(v.hwnd, margins{1, 1, 1, 1}) // a thin frame is enough for DWM's shadow + } + setWindowPos(v.edit, 0, px(18, s), px(view.FieldTop, s), px(view.FieldW, s), px(30, s), swpNoZOrder|swpNoActivate) +} + +// spinnerBox returns the spinner's box in DIPs. +func spinnerBox(s view.Snapshot) rectF { + top := float32(view.FooterTop(s)) + 1 + return rectF{Left: 18, Top: top, Right: 18 + view.SpinSize, Bottom: top + view.SpinSize} +} + +// lineBox returns the footer line's box in DIPs, with room above and below for the swap animation. +func lineBox(s view.Snapshot) rectF { + top := float32(view.FooterTop(s)) + return rectF{Left: 18, Top: top - view.Slide, Right: 18 + view.FooterW, Bottom: top + 18 + view.Slide} +} + +// stopBox returns the stop-everything button's box, in DIPs. +func stopBox(s view.Snapshot) rectF { + top := float32(view.StopTop(s)) + return rectF{Left: view.StopLeft, Top: top, Right: view.StopLeft + view.StopSize, Bottom: top + view.StopSize} +} + +// invalidateBox makes the window repaint r, given in DIPs, with a margin for antialiased edges. +func (v *View) invalidateBox(r rectF) { + s := v.scale() + pr := rect{px(float64(r.Left), s) - 2, px(float64(r.Top), s) - 2, px(float64(r.Right), s) + 2, px(float64(r.Bottom), s) + 2} + invalidate(v.hwnd, &pr) +} + +// paint draws the part of the snapshot inside dirty, given in DIPs. The rest keeps the pixels of +// the last frame. +func (v *View) paint(dirty rectF) { + g := v.g + if !g.target(v.hwnd, v.dpi, v.glass) { + return + } + s, p := v.snap, v.pal + if all := v.dips(clientRect(v.hwnd)); g.whole || covers(dirty, all) { + dirty = all + g.frame() + } + bg := p.surface + if v.glass { + bg = transparent + } + g.begin(dirty, bg) + if band := (rectF{0, 0, view.Width, view.QueryH}); overlaps(dirty, band) { + if v.glass { + g.fillRounded(band, 0, p.surface) + } + g.fillRounded(rectF{0, view.QueryH - 1, view.Width, view.QueryH}, 0, p.separator) + } + if header := (rectF{18, view.QueryH, view.Width - 18, view.QueryH + 16}); s.Header != "" && overlaps(dirty, header) { + g.text(g.small, s.Header, header, p.secondary, nil) + } + if list := (rectF{0, float32(view.RowsTop(s.Header != "")), view.Width, float32(view.ListBottom(s))}); overlaps(dirty, list) { + v.paintList(list, dirty) + } + if overlaps(dirty, lineBox(s)) { + v.paintFooter() + } + if overlaps(dirty, stopBox(s)) { + v.paintStop() + } + if !g.end() { + g.discard() + invalidate(v.hwnd, nil) + } +} + +// dips converts r from client pixels to DIPs. +func (v *View) dips(r rect) rectF { + s := float32(v.scale()) + return rectF{float32(r.Left) / s, float32(r.Top) / s, float32(r.Right) / s, float32(r.Bottom) / s} +} + +func overlaps(a, b rectF) bool { + return a.Left < b.Right && b.Left < a.Right && a.Top < b.Bottom && b.Top < a.Bottom +} + +// covers reports whether a contains all of b. +func covers(a, b rectF) bool { + return a.Left <= b.Left && a.Top <= b.Top && a.Right >= b.Right && a.Bottom >= b.Bottom +} + +// paintList clips at the bottom of list, so the last row of a long list is drawn only in part. It +// leaves rows outside dirty as they are. +func (v *View) paintList(list, dirty rectF) { + s, g := v.snap, v.g + g.clip(list) + defer g.unclip() + for i, r := range s.Rows { + y := float32(view.RowTop(s, i)) + top := y // the top of its group label, when it has one + if r.Group != "" { + top -= view.GroupH + } + if top >= min(list.Bottom, dirty.Bottom) { // neither this row nor any after it is drawn + break + } + if y+view.RowH <= dirty.Top { + continue + } + if r.Group != "" { + label := y - view.GroupH + 5 + g.text(g.label, r.Group, rectF{18, label, view.Width - 18, label + 16}, v.pal.secondary, nil) + } + if y < list.Bottom { + v.paintRow(r, i == s.Selected, y) + } + } +} + +func (v *View) paintRow(r view.Row, selected bool, y float32) { + g := v.g + const inner = view.Width - 2*view.Padding + fg, sub, icon := v.pal.text, v.pal.secondary, v.pal.icon + if r.Danger { + icon = hex(v.pal.critical) + } + if selected { + fill := v.pal.danger + if !r.Danger { + hr, hg, hb := sysColor(colorHighlight) + fill = colorF{float32(hr) / 255, float32(hg) / 255, float32(hb) / 255, 1} + } + g.fillRounded(rectF{view.Padding, y, view.Padding + inner, y + view.RowH - 4}, 8, fill) + fg, sub, icon = onAccent.text, onAccent.secondary, onAccent.icon + } + box := float32(view.RowH - 4) + g.icon(r.Icon, icon, view.Padding+14, y+(box-view.IconSize)/2, view.IconSize) + titleW := float32(inner - 46 - 250) + x := float32(view.Padding + 46) + if r.Subtitle == "" { + g.text(g.title, r.Title, rectF{x, y + (box-20)/2, x + titleW, y + (box+20)/2}, fg, boldRanges(r.Title, r.Bold)) + } else { + g.text(g.title, r.Title, rectF{x, y + 4, x + titleW, y + 24}, fg, boldRanges(r.Title, r.Bold)) + g.text(g.small, r.Subtitle, rectF{x, y + 24, x + titleW, y + 40}, sub, nil) + } + mid := y + (box-16)/2 + g.text(g.tail, r.Tail, rectF{view.Padding + inner - 250, mid, view.Padding + inner - 70, mid + 16}, sub, nil) + g.text(g.tail, r.Hint, rectF{view.Padding + inner - 64, mid, view.Padding + inner - 14, mid + 16}, sub, nil) +} + +// paintFooter draws the footer line. During a swap, the old line moves up and out while the new +// one moves up from below into its place. +func (v *View) paintFooter() { + if v.swapping { + e := swapProgress(time.Since(v.swapStart)) + v.paintLine(v.swapFrom, -view.Slide*e, 1-e) + v.paintLine(v.line, view.Slide*(1-e), e) + } else { + v.paintLine(v.line, 0, 1) + } +} + +// paintLine draws a footer line dy below its resting place, at the given alpha. +func (v *View) paintLine(l view.Line, dy, alpha float32) { + p := v.pal + top := float32(view.FooterTop(v.snap)) + dy + x, c, text := float32(18), p.secondary, l.Status.Text + switch l.Status.Kind { + case view.StatusNone: + text = l.Hints + case view.StatusLoading: + v.paintSpinner(dy, alpha) + x = view.StatusLeft + case view.StatusDone: + c = p.success + case view.StatusError: + c = p.critical + } + c.A *= alpha + v.g.text(v.g.small, text, rectF{x, top, 18 + view.FooterW, top + 18}, c, nil) +} + +func (v *View) paintStop() { + b, p := stopBox(v.snap), v.pal + glyph, disc := p.muted, p.text + disc.A = 0.07 + if v.snap.Running { + glyph, disc = hex(p.critical), p.critical + disc.A = 0.16 + } + if v.stopHover { + disc.A *= 2 + } + const r, glyphSize = view.StopSize / 2, 14 + v.g.fillEllipse(ellipse{X: b.Left + r, Y: b.Top + r, RadiusX: r, RadiusY: r}, disc) + v.g.icon(icons.StopAll, glyph, b.Left+(view.StopSize-glyphSize)/2, b.Top+(view.StopSize-glyphSize)/2, glyphSize) +} + +// paintSpinner draws the spinner dy below its resting place, at the given alpha. The brightest +// dot moves on each tick. +func (v *View) paintSpinner(dy, alpha float32) { + b := spinnerBox(v.snap) + cx, cy := (b.Left+b.Right)/2, (b.Top+b.Bottom)/2+dy + for i := 0; i < spinDots; i++ { + x, y := spinnerDot(i) + age := (v.spin - i + spinDots) % spinDots + c := v.pal.text + c.A = (1 - float32(age)/float32(spinDots)*0.85) * alpha + v.g.fillEllipse(ellipse{X: cx + x, Y: cy + y, RadiusX: 1.6, RadiusY: 1.6}, c) + } +} + +// rowAtPixel returns the row at client y in pixels, or -1. +func (v *View) rowAtPixel(y int32) int { + return view.RowAt(float64(y)/v.scale(), v.snap) +} + +func (v *View) stopAtPixel(x, y int32) bool { + s := v.scale() + return view.InStop(float64(x)/s, float64(y)/s, v.snap) +} + +// setStopHover asks Windows to report when the pointer leaves the window, because the pointer may +// leave it from the button. +func (v *View) setStopHover(on bool) { + if on == v.stopHover { + return + } + v.stopHover = on + if on { + trackLeave(v.hwnd) + } + v.invalidateBox(stopBox(v.snap)) +} + +// mouseMoved selects a row only on real pointer movement. The window appearing, or rows shifting +// under a still pointer, doesn't move the selection. +func (v *View) mouseMoved(lp uintptr) { + if !v.visible { + return + } + v.setStopHover(v.stopAtPixel(lparamX(lp), lparamY(lp))) + p := cursorPos() + if p == v.cursor { + return + } + v.cursor = p + if i := v.rowAtPixel(lparamY(lp)); i >= 0 && v.ev.Hover != nil { + v.ev.Hover(i) + } +} + +// scroll scrolls as many rows per notch as the user's lines per notch setting. The smaller deltas +// from a touchpad add up to rows. +func (v *View) scroll(wp uintptr) { + lines := wheelLines() + if lines == 0 || v.ev.Scroll == nil { + return + } + if lines == wheelPageScroll { + lines = view.MaxRows + } + perRow := max(wheelDelta/int32(min(lines, wheelDelta)), 1) + v.wheel += wheelTurn(wp) + n := v.wheel / perRow + v.wheel -= n * perRow + if n != 0 { + v.ev.Scroll(int(-n)) // turning the wheel away from the user scrolls up + } +} + +// hitTest treats the rows and the stop button as client area, and everything else (the header, +// the footer and the band's margins) as the title bar, which Windows lets the user drag. The test +// for rows only checks y, because the margins beside the rows are client area too. The query box +// handles its own hit testing. +func (v *View) hitTest(lp uintptr) uintptr { + r := windowRect(v.hwnd) + x, y := lparamX(lp)-r.Left, lparamY(lp)-r.Top + if v.rowAtPixel(y) >= 0 || v.stopAtPixel(x, y) { + return htClient + } + return htCaption +} + +// key passes a key to the launcher and returns true when it was handled. +func (v *View) key(vk uintptr) bool { + ctrl, shift, alt := keyDown(vkControl), keyDown(vkShift), keyDown(vkMenu) + k, ok := keyFor(uint32(vk), ctrl, shift, alt) + if ok && v.ev.Key != nil && v.ev.Key(k) { + return true + } + if ctrl && !alt && vk == 'A' { // the EDIT has no built-in select-all + sendMessage(v.edit, emSetSel, 0, ^uintptr(0)) + return true + } + return false +} + +// deleteWord handles Ctrl+Backspace, which the EDIT would otherwise insert as a box character. +func (v *View) deleteWord() { + var start, end uint32 + _, _, _ = procSendMessageW.Call(v.edit, emGetSel, uintptr(unsafe.Pointer(&start)), uintptr(unsafe.Pointer(&end))) + if start != end { + v.replaceSelection("") + return + } + from := wordStart(windowText(v.edit), int(end)) + sendMessage(v.edit, emSetSel, uintptr(from), uintptr(end)) + v.replaceSelection("") +} + +func (v *View) replaceSelection(s string) { + p, _ := windows.UTF16PtrFromString(s) + _, _, _ = procSendMessageW.Call(v.edit, emReplaceSel, 1, uintptr(unsafe.Pointer(p))) +} + +func (v *View) queryChanged() { + if v.settingText || v.ev.Query == nil { + return + } + v.ev.Query(string(utf16.Decode(windowText(v.edit)))) +} + +// dpiChanged handles the window moving to a monitor with a different DPI. Show sizes the window +// for its monitor before Windows reports the change. After a drag across monitors, the window +// keeps the position that Windows suggests and is resized for the new DPI. +func (v *View) dpiChanged(wp, lp uintptr) { + dpi := lowWord(wp) + if dpi == v.monDpi { // Show already sized it for this monitor + return + } + suggested := *(**rect)(unsafe.Pointer(&lp)) + v.useMonitor(monitorAt(point{suggested.Left + 1, suggested.Top + 1}, monitorToNearest), dpi) + v.g.discard() + v.setFont() + if !v.settingFrame { + v.left, v.top = suggested.Left, suggested.Top + v.layout() + } + invalidate(v.hwnd, nil) +} + +// waitMouse runs every 50 ms while a blur waits on the mouse (see WM_ACTIVATE), until blurDue +// allows the blur. It waits because a drag may end over the window, with the drop arriving +// afterwards. By then the window may have the foreground again, because a drop takes it, and then +// there is nothing to blur. +func (v *View) waitMouse() { + down := mouseDown() + if down { + v.upAt = time.Time{} + } else if v.upAt.IsZero() { + v.upAt = time.Now() + } + if !blurDue(down, v.pointerOver(), time.Since(v.upAt)) { + return + } + _, _, _ = procKillTimer.Call(v.hwnd, mouseTimer) + if v.visible && foreground() != v.hwnd && v.ev.Blur != nil { + v.ev.Blur() + } +} + +func (v *View) pointerOver() bool { + p, r := cursorPos(), windowRect(v.hwnd) + return p.X >= r.Left && p.X < r.Right && p.Y >= r.Top && p.Y < r.Bottom +} + +func (v *View) moveStarted() { v.dragFrom = windowRect(v.hwnd) } + +// moveEnded ignores a click that didn't move the window. +func (v *View) moveEnded() { + r := windowRect(v.hwnd) + if r == v.dragFrom || !v.visible { + return + } + v.left, v.top = r.Left, r.Top + if v.ev.Moved != nil { + v.ev.Moved(view.Placement{Left: float64(r.Left), Top: float64(r.Top)}) + } +} + +// panicked handles a panic recovered in a callback from Windows. A panic can't unwind through +// those callbacks, because the process would end, taking the core and every mount and transfer +// with it. Every panic is logged. If a frame was interrupted, its render target may be in the +// middle of drawing, so the target is discarded. +func panicked(where string, p any) { + logger.Error("the launcher's window recovered from a panic", "in", where, "panic", fmt.Sprint(p), "stack", string(debug.Stack())) + if v := current; v != nil && v.g.drawing { + v.g.drawing = false + v.g.discard() + } +} + +func wndProc(hwnd, m, wp, lp uintptr) (r uintptr) { + defer func() { + if p := recover(); p != nil { + panicked("the window's procedure", p) + r = defWindowProc(hwnd, m, wp, lp) // as if the message weren't handled + } + }() + v := current + if v == nil || hwnd != v.hwnd { + return defWindowProc(hwnd, m, wp, lp) + } + switch m { + case wmNCCalcSize: + if wp != 0 { + return 0 // the client area is the whole window, so no frame shows + } + case wmNCHitTest: + return v.hitTest(lp) + case wmNCActivate: + // -1 changes the activation without painting a frame, since there isn't one + return defWindowProc(hwnd, m, wp, ^uintptr(0)) + case wmNCLButtonDbl: + return 0 // double-clicking the "title bar" doesn't maximise + case wmActivate: + if lowWord(wp) == waInactive { + switch { + case !v.visible || v.ev.Blur == nil: + case mouseDown(): + // A click elsewhere, or a drag starting there that may end here. The blur + // waits for the button (see waitMouse). + v.upAt = time.Time{} + _, _, _ = procSetTimer.Call(hwnd, mouseTimer, 50, 0) + default: + v.ev.Blur() + } + } else { + setFocus(v.edit) + } + return 0 + case wmSetFocus: + setFocus(v.edit) + return 0 + case wmSysCommand: + if wp&0xFFF0 == scKeyMenu { // Alt alone, from forceForeground's tap; there is no menu to open + return 0 + } + case wmSettingChange: + // "ImmersiveColorSet" means the app mode or the accent colour changed + if lp != 0 && windows.UTF16PtrToString(*(**uint16)(unsafe.Pointer(&lp))) == "ImmersiveColorSet" { + v.applyTheme() + } + return 0 + case wmClose: // Alt+F4 dismisses the launcher; the window lives as long as the app + if v.ev.Key != nil { + v.ev.Key(view.KeyEvent{Key: view.KeyClose}) + } + return 0 + case wmEraseBkgnd: + return 1 + case wmPaint: + var ps paintStruct + _, _, _ = procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + v.paint(v.dips(ps.Paint)) + _, _, _ = procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps))) + // Direct2D presents the whole client area, over the box. The box redraws itself on top + // at once, so DWM never shows the window without it. + redrawNow(v.edit) + return 0 + case wmSize: + v.g.resize(int32(lowWord(lp)), int32(highWord(lp))) + return 0 + case wmDropFiles: + paths := droppedFiles(wp) + _, _, _ = procKillTimer.Call(hwnd, mouseTimer) + if v.visible && len(paths) > 0 { + forceForeground(hwnd) + setFocus(v.edit) + if v.ev.Drop != nil { + v.ev.Drop(paths) + } + } + return 0 + case wmTimer: + switch wp { + case mouseTimer: + v.waitMouse() + case handOffTimer: // the window didn't appear, so a window shown later isn't it + v.stopAwaiting() + case spinTimer: + v.spin = (v.spin + 1) % spinDots + v.invalidateBox(spinnerBox(v.snap)) + case swapTimer: + if time.Since(v.swapStart) >= view.SwapFor { + v.endSwap() // this frame, drawn at the end of the swap, is the last + } + v.invalidateBox(lineBox(v.snap)) + } + return 0 + case wmCommand: + if highWord(wp) == enChange && lp == v.edit { + v.queryChanged() + } + return 0 + case wmCtlColorEdit: + // draw the box on the query band, in the mode's text colour + _, _, _ = procSetTextColor.Call(wp, uintptr(colorRef(v.pal.text))) + _, _, _ = procSetBkColor.Call(wp, uintptr(colorRef(v.pal.surface))) + return v.band + case wmCtlColorStatic: + // The live region's text is only for screen readers, so draw it in the band's colour. + _, _, _ = procSetTextColor.Call(wp, uintptr(colorRef(v.pal.surface))) + _, _, _ = procSetBkColor.Call(wp, uintptr(colorRef(v.pal.surface))) + return v.band + case wmMouseMove: + v.mouseMoved(lp) + return 0 + case wmMouseLeave: + v.setStopHover(false) + return 0 + case wmMouseWheel: + v.scroll(wp) + return 0 + case wmLButtonDown: + if v.stopAtPixel(lparamX(lp), lparamY(lp)) { + if v.ev.StopAll != nil { + v.ev.StopAll() + } + } else if i := v.rowAtPixel(lparamY(lp)); i >= 0 && v.ev.Click != nil { + v.ev.Click(i) + } + return 0 + case wmEnterSizeMove: + v.moveStarted() + case wmExitSizeMove: + v.moveEnded() + case wmDpiChanged: + v.dpiChanged(wp, lp) + return 0 + } + return defWindowProc(hwnd, m, wp, lp) +} + +func editProc(hwnd, m, wp, lp uintptr) (r uintptr) { + defer func() { + if p := recover(); p != nil { + panicked("the query box's procedure", p) + if v := current; v != nil && v.editProc != 0 { // fall back to the box's own handling + r, _, _ = procCallWindowProcW.Call(v.editProc, hwnd, m, wp, lp) + } + } + }() + v := current + if v == nil { + return defWindowProc(hwnd, m, wp, lp) + } + switch m { + case wmKeyDown: + if v.key(wp) { + peekChar(hwnd) + return 0 + } + case wmMouseWheel: // the box has keyboard focus, so wheel messages arrive here + v.scroll(wp) + return 0 + case wmChar: + switch wp { + case '\t', '\r', '\n', 0x1B: // keys the launcher handles; the box would beep + return 0 + case 0x7F: // Ctrl+Backspace + v.deleteWord() + return 0 + } + } + r, _, _ = procCallWindowProcW.Call(v.editProc, hwnd, m, wp, lp) + return r +} diff --git a/app/launcher/view/windows/win32.go b/app/launcher/view/windows/win32.go new file mode 100644 index 00000000..c98524e8 --- /dev/null +++ b/app/launcher/view/windows/win32.go @@ -0,0 +1,516 @@ +//go:build windows + +package windows + +import ( + "unsafe" + + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" +) + +// The Win32 functions that the view calls. LazyProc.Call is marked uintptrescapes, so it keeps a +// pointer that is converted in its argument list alive and in place. For that reason, those +// conversions are always written inside the call. +var ( + user32 = windows.NewLazySystemDLL("user32.dll") + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + gdi32 = windows.NewLazySystemDLL("gdi32.dll") + dwmapi = windows.NewLazySystemDLL("dwmapi.dll") + shcore = windows.NewLazySystemDLL("shcore.dll") + shlwapi = windows.NewLazySystemDLL("shlwapi.dll") + d2d1 = windows.NewLazySystemDLL("d2d1.dll") + dwrite = windows.NewLazySystemDLL("dwrite.dll") + ole32 = windows.NewLazySystemDLL("ole32.dll") + shell32 = windows.NewLazySystemDLL("shell32.dll") + + procRegisterClassExW = user32.NewProc("RegisterClassExW") + procCreateWindowExW = user32.NewProc("CreateWindowExW") + procDefWindowProcW = user32.NewProc("DefWindowProcW") + procCallWindowProcW = user32.NewProc("CallWindowProcW") + procSetWindowLongPtrW = user32.NewProc("SetWindowLongPtrW") + procShowWindow = user32.NewProc("ShowWindow") + procSetWindowPos = user32.NewProc("SetWindowPos") + procGetWindowRect = user32.NewProc("GetWindowRect") + procGetClientRect = user32.NewProc("GetClientRect") + procGetCursorPos = user32.NewProc("GetCursorPos") + procMonitorFromPoint = user32.NewProc("MonitorFromPoint") + procGetMonitorInfoW = user32.NewProc("GetMonitorInfoW") + procSetForegroundWindow = user32.NewProc("SetForegroundWindow") + procGetForegroundWindow = user32.NewProc("GetForegroundWindow") + procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId") + procAttachThreadInput = user32.NewProc("AttachThreadInput") + procBringWindowToTop = user32.NewProc("BringWindowToTop") + procSetFocus = user32.NewProc("SetFocus") + procIsWindow = user32.NewProc("IsWindow") + procSendMessageW = user32.NewProc("SendMessageW") + procPeekMessageW = user32.NewProc("PeekMessageW") + procInvalidateRect = user32.NewProc("InvalidateRect") + procBeginPaint = user32.NewProc("BeginPaint") + procEndPaint = user32.NewProc("EndPaint") + procSetTimer = user32.NewProc("SetTimer") + procKillTimer = user32.NewProc("KillTimer") + procGetKeyState = user32.NewProc("GetKeyState") + procGetSysColor = user32.NewProc("GetSysColor") + procLoadCursorW = user32.NewProc("LoadCursorW") + procGetDpiForWindow = user32.NewProc("GetDpiForWindow") + procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW") + procGetWindowTextW = user32.NewProc("GetWindowTextW") + procSetWindowTextW = user32.NewProc("SetWindowTextW") + procKeybdEvent = user32.NewProc("keybd_event") + procGetAsyncKeyState = user32.NewProc("GetAsyncKeyState") + procSystemParametersInfoW = user32.NewProc("SystemParametersInfoW") + procNotifyWinEvent = user32.NewProc("NotifyWinEvent") + procTrackMouseEvent = user32.NewProc("TrackMouseEvent") + procRedrawWindow = user32.NewProc("RedrawWindow") + procSetWinEventHook = user32.NewProc("SetWinEventHook") + procUnhookWinEvent = user32.NewProc("UnhookWinEvent") + procGetAncestor = user32.NewProc("GetAncestor") + procIsWindowVisible = user32.NewProc("IsWindowVisible") + procGetWindowLongPtrW = user32.NewProc("GetWindowLongPtrW") + + procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW") + + procCreateFontW = gdi32.NewProc("CreateFontW") + procDeleteObject = gdi32.NewProc("DeleteObject") + procSetTextColor = gdi32.NewProc("SetTextColor") + procSetBkColor = gdi32.NewProc("SetBkColor") + procCreateSolidBrush = gdi32.NewProc("CreateSolidBrush") + + procDwmSetWindowAttribute = dwmapi.NewProc("DwmSetWindowAttribute") + procDwmExtendFrameIntoClientArea = dwmapi.NewProc("DwmExtendFrameIntoClientArea") + + procGetDpiForMonitor = shcore.NewProc("GetDpiForMonitor") + + procSHCreateMemStream = shlwapi.NewProc("SHCreateMemStream") + + procD2D1CreateFactory = d2d1.NewProc("D2D1CreateFactory") + procDWriteCreateFactory = dwrite.NewProc("DWriteCreateFactory") + + procCoCreateInstance = ole32.NewProc("CoCreateInstance") + + procDragAcceptFiles = shell32.NewProc("DragAcceptFiles") + procDragQueryFileW = shell32.NewProc("DragQueryFileW") + procDragFinish = shell32.NewProc("DragFinish") +) + +const ( + wmSize = 0x0005 + wmActivate = 0x0006 + wmSetFocus = 0x0007 + wmPaint = 0x000F + wmClose = 0x0010 + wmEraseBkgnd = 0x0014 + wmSettingChange = 0x001A + wmSetFont = 0x0030 + wmNCCalcSize = 0x0083 + wmNCHitTest = 0x0084 + wmNCActivate = 0x0086 + wmNCLButtonDbl = 0x00A3 + wmKeyDown = 0x0100 + wmChar = 0x0102 + wmCommand = 0x0111 + wmSysCommand = 0x0112 + wmTimer = 0x0113 + wmCtlColorEdit = 0x0133 + wmCtlColorStatic = 0x0138 + wmDropFiles = 0x0233 + scKeyMenu = 0xF100 + wmMouseMove = 0x0200 + wmLButtonDown = 0x0201 + wmMouseWheel = 0x020A + wmEnterSizeMove = 0x0231 + wmExitSizeMove = 0x0232 + wmMouseLeave = 0x02A3 + wmDpiChanged = 0x02E0 + emGetSel = 0x00B0 + emSetSel = 0x00B1 + emReplaceSel = 0x00C2 + emSetCueBanner = 0x1501 + enChange = 0x0300 + waInactive = 0 + htClient = 1 + htCaption = 2 + pmRemove = 1 + gwlpWndProc = ^uintptr(3) // -4 + hwndTopmost = ^uintptr(0) // -1 + idcArrow = 32512 + colorHighlight = 13 + mdtEffectiveDpi = 0 + monitorToNull = 0 + monitorToNearest = 2 + vkShift = 0x10 + vkControl = 0x11 + vkMenu = 0x12 + vkLButton = 0x01 + vkRButton = 0x02 + + keyeventfKeyUp = 0x0002 + tmeLeave = 0x0002 + rdwInvalidate = 0x0001 + rdwUpdateNow = 0x0100 + + eventObjectShow = 0x8002 + objidWindow = 0 + gaRoot = 2 + gwlExStyle = ^uintptr(19) // -20 +) + +const ( + wsPopup = 0x80000000 + wsChild = 0x40000000 + wsVisible = 0x10000000 + wsClipChildren = 0x02000000 + wsThickFrame = 0x00040000 + wsExTopmost = 0x00000008 + wsExToolWindow = 0x00000080 + wsExNoActivate = 0x08000000 + esAutoHScroll = 0x0080 + csHRedraw = 0x0002 + csVRedraw = 0x0001 + swHide = 0 + swShow = 5 + swpNoSize = 0x0001 + swpNoMove = 0x0002 + swpNoZOrder = 0x0004 + swpNoActivate = 0x0010 + swpFrameChanged = 0x0020 +) + +const ( + dwmwaTransitionsForceDisabled = 3 + dwmwaUseImmersiveDarkMode = 20 + dwmwaWindowCornerPreference = 33 + dwmwaSystemBackdropType = 38 + dwmwcpRound = 2 + dwmsbtTransientWindow = 3 // acrylic +) + +type point struct{ X, Y int32 } + +type rect struct{ Left, Top, Right, Bottom int32 } + +func (r rect) width() int32 { return r.Right - r.Left } +func (r rect) height() int32 { return r.Bottom - r.Top } + +type wndClassEx struct { + Size uint32 + Style uint32 + WndProc uintptr + ClsExtra int32 + WndExtra int32 + Instance uintptr + Icon uintptr + Cursor uintptr + Background uintptr + MenuName *uint16 + ClassName *uint16 + IconSm uintptr +} + +type monitorInfo struct { + Size uint32 + Monitor rect + Work rect + Flags uint32 +} + +type paintStruct struct { + Hdc uintptr + Erase int32 + Paint rect + Restore int32 + IncUpdate int32 + Reserved [32]byte +} + +type msg struct { + Hwnd uintptr + Message uint32 + WParam uintptr + LParam uintptr + Time uint32 + Pt point + LPrivate uint32 +} + +type margins struct{ Left, Right, Top, Bottom int32 } + +type trackMouseEvent struct { + Size uint32 + Flags uint32 + Track uintptr + HoverTime uint32 +} + +// packPoint packs a POINT passed by value: two LONGs in one register, on both amd64 and arm64. +func packPoint(p point) uintptr { return uintptr(uint32(p.X)) | uintptr(uint32(p.Y))<<32 } + +func lowWord(v uintptr) uint32 { return uint32(v) & 0xFFFF } +func highWord(v uintptr) uint32 { return uint32(v>>16) & 0xFFFF } +func lparamX(v uintptr) int32 { return int32(int16(uint16(v))) } +func lparamY(v uintptr) int32 { return int32(int16(uint16(v >> 16))) } + +func defWindowProc(hwnd, m, wp, lp uintptr) uintptr { + r, _, _ := procDefWindowProcW.Call(hwnd, m, wp, lp) + return r +} + +// sendMessage sends a message that carries no pointers. Code that sends a pointer calls the proc +// directly, so the conversion happens inside the call that keeps it alive. +func sendMessage(hwnd, m, wp, lp uintptr) uintptr { + r, _, _ := procSendMessageW.Call(hwnd, m, wp, lp) + return r +} + +func windowRect(hwnd uintptr) rect { + var r rect + _, _, _ = procGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + return r +} + +func clientRect(hwnd uintptr) rect { + var r rect + _, _, _ = procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + return r +} + +func cursorPos() point { + var p point + _, _, _ = procGetCursorPos.Call(uintptr(unsafe.Pointer(&p))) + return p +} + +func setWindowPos(hwnd, after uintptr, x, y, w, h int32, flags uintptr) { + _, _, _ = procSetWindowPos.Call(hwnd, after, uintptr(x), uintptr(y), uintptr(w), uintptr(h), flags) +} + +func invalidate(hwnd uintptr, r *rect) { + _, _, _ = procInvalidateRect.Call(hwnd, uintptr(unsafe.Pointer(r)), 0) +} + +func keyDown(vk uintptr) bool { + r, _, _ := procGetKeyState.Call(vk) + return int16(r) < 0 +} + +func foreground() uintptr { + r, _, _ := procGetForegroundWindow.Call() + return r +} + +func setForeground(hwnd uintptr) bool { + r, _, _ := procSetForegroundWindow.Call(hwnd) + return r != 0 +} + +func windowThread(hwnd uintptr) uintptr { + r, _, _ := procGetWindowThreadProcessId.Call(hwnd, 0) + return r +} + +func isWindow(hwnd uintptr) bool { + r, _, _ := procIsWindow.Call(hwnd) + return r != 0 +} + +func setFocus(hwnd uintptr) { _, _, _ = procSetFocus.Call(hwnd) } + +func monitorAt(p point, flags uintptr) uintptr { + r, _, _ := procMonitorFromPoint.Call(packPoint(p), flags) + return r +} + +func workArea(monitor uintptr) (rect, bool) { + mi := monitorInfo{Size: uint32(unsafe.Sizeof(monitorInfo{}))} + r, _, _ := procGetMonitorInfoW.Call(monitor, uintptr(unsafe.Pointer(&mi))) + return mi.Work, r != 0 +} + +// monitorDpi returns the monitor's effective DPI, or 96 when Windows can't report it (before 8.1). +func monitorDpi(monitor uintptr) uint32 { + if procGetDpiForMonitor.Find() != nil { + return 96 + } + var x, y uint32 + r, _, _ := procGetDpiForMonitor.Call(monitor, mdtEffectiveDpi, uintptr(unsafe.Pointer(&x)), uintptr(unsafe.Pointer(&y))) + if int32(r) < 0 || x == 0 { + return 96 + } + return x +} + +// windowDpi returns the window's DPI, or 96 before Windows 10 1607. +func windowDpi(hwnd uintptr) uint32 { + if procGetDpiForWindow.Find() != nil { + return 96 + } + r, _, _ := procGetDpiForWindow.Call(hwnd) + if r == 0 { + return 96 + } + return uint32(r) +} + +func windowText(hwnd uintptr) []uint16 { + n, _, _ := procGetWindowTextLengthW.Call(hwnd) + buf := make([]uint16, n+1) + got, _, _ := procGetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), n+1) + return buf[:got] +} + +func setWindowText(hwnd uintptr, text string) { + p, err := windows.UTF16PtrFromString(text) + if err != nil { // the text contains a NUL, which the box can't show + return + } + _, _, _ = procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(p))) +} + +// dwmSet sets a DWORD-sized DWM attribute and reports whether Windows accepted it. +func dwmSet(hwnd uintptr, attr uintptr, value uint32) bool { + r, _, _ := procDwmSetWindowAttribute.Call(hwnd, attr, uintptr(unsafe.Pointer(&value)), unsafe.Sizeof(value)) + return int32(r) >= 0 +} + +func extendFrame(hwnd uintptr, m margins) { + _, _, _ = procDwmExtendFrameIntoClientArea.Call(hwnd, uintptr(unsafe.Pointer(&m))) +} + +// trackLeave asks Windows to post WM_MOUSELEAVE when the pointer leaves the window's client area, +// including when it moves onto the parts that hitTest treats as the title bar. The request only +// lasts for one leave, so each hover makes it again. +func trackLeave(hwnd uintptr) { + t := trackMouseEvent{Size: uint32(unsafe.Sizeof(trackMouseEvent{})), Flags: tmeLeave, Track: hwnd} + _, _, _ = procTrackMouseEvent.Call(uintptr(unsafe.Pointer(&t))) +} + +func redrawNow(hwnd uintptr) { + _, _, _ = procRedrawWindow.Call(hwnd, 0, 0, rdwInvalidate|rdwUpdateNow) +} + +// hookShows has fn called whenever a window of this process is shown (EVENT_OBJECT_SHOW), until +// unhook. The hook is out of context, so fn runs on this thread while it processes its messages. +// It returns 0 when Windows refuses. +func hookShows(fn uintptr) uintptr { + // WINEVENT_OUTOFCONTEXT is 0; thread 0 means any thread of the process + r, _, _ := procSetWinEventHook.Call(eventObjectShow, eventObjectShow, 0, fn, uintptr(windows.GetCurrentProcessId()), 0, 0) + return r +} + +// unhook removes a hookShows hook. Call it on the thread that set the hook. +func unhook(hook uintptr) { _, _, _ = procUnhookWinEvent.Call(hook) } + +func activatable(hwnd uintptr) bool { + if root, _, _ := procGetAncestor.Call(hwnd, gaRoot); root != hwnd { + return false + } + if shown, _, _ := procIsWindowVisible.Call(hwnd); shown == 0 { + return false + } + ex, _, _ := procGetWindowLongPtrW.Call(hwnd, gwlExStyle) + return ex&(wsExToolWindow|wsExNoActivate) == 0 +} + +func sysColor(index uintptr) (r, g, b uint8) { + c, _, _ := procGetSysColor.Call(index) + return uint8(c), uint8(c >> 8), uint8(c >> 16) +} + +// queryFont takes size in DIPs. It uses ClearType, which works because the box sits on an opaque +// band. +func queryFont(size float64, dpi uint32) uintptr { + const fwNormal, defaultCharset, cleartype = 400, 1, 5 + face, _ := windows.UTF16PtrFromString("Segoe UI") + h := -px(size, float64(dpi)/96) + r, _, _ := procCreateFontW.Call(uintptr(h), 0, 0, 0, fwNormal, 0, 0, 0, defaultCharset, 0, 0, cleartype, 0, + uintptr(unsafe.Pointer(face))) + return r +} + +func solidBrush(c colorF) uintptr { + r, _, _ := procCreateSolidBrush.Call(uintptr(colorRef(c))) + return r +} + +// mouseDown reports whether a mouse button is down, wherever the click is. It doesn't use +// GetKeyState, which only knows about this thread's input. +func mouseDown() bool { + for _, vk := range []uintptr{vkLButton, vkRButton} { + if r, _, _ := procGetAsyncKeyState.Call(vk); r&0x8000 != 0 { + return true + } + } + return false +} + +// Mouse wheel constants: the delta for one notch, and the system setting for how many lines a +// notch scrolls. At the ends of its range, the setting means no scrolling (0) or a whole page +// (wheelPageScroll). +const ( + wheelDelta = 120 + spiGetWheelScrollLines = 0x0068 + wheelPageScroll = 0xFFFFFFFF +) + +func wheelLines() uint32 { + n := uint32(3) + if r, _, _ := procSystemParametersInfoW.Call(spiGetWheelScrollLines, 0, uintptr(unsafe.Pointer(&n)), 0); r == 0 { + return 3 + } + return n +} + +// wheelTurn returns the delta of a WM_MOUSEWHEEL. Positive is away from the user. +func wheelTurn(wp uintptr) int32 { return int32(int16(uint16(wp >> 16))) } + +// droppedFiles returns the paths from a WM_DROPFILES drop and releases the drop. +func droppedFiles(drop uintptr) []string { + defer func() { _, _, _ = procDragFinish.Call(drop) }() + n, _, _ := procDragQueryFileW.Call(drop, 0xFFFFFFFF, 0, 0) + paths := make([]string, 0, n) + for i := uintptr(0); i < n; i++ { + size, _, _ := procDragQueryFileW.Call(drop, i, 0, 0) + buf := make([]uint16, size+1) + _, _, _ = procDragQueryFileW.Call(drop, i, uintptr(unsafe.Pointer(&buf[0])), size+1) + paths = append(paths, windows.UTF16ToString(buf)) + } + return paths +} + +// keyTap presses a key, or releases it when flags includes keyeventfKeyUp, as the keyboard would. +func keyTap(vk, flags uintptr) { _, _, _ = procKeybdEvent.Call(vk, 0, flags, 0) } + +// appsUseLightTheme reports the system's app mode (Settings › Personalisation › Colours). It +// returns light when Windows doesn't say, because that is the default. +func appsUseLightTheme() bool { + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE) + if err != nil { + return true + } + defer func() { _ = k.Close() }() + v, _, err := k.GetIntegerValue("AppsUseLightTheme") + return err != nil || v != 0 +} + +func deleteObject(h uintptr) { + if h != 0 { + _, _, _ = procDeleteObject.Call(h) + } +} + +// peekChar removes from the queue the character that a key just handled would type. +// TranslateMessage posted it before the key was dispatched to us. +func peekChar(hwnd uintptr) { + var m msg + _, _, _ = procPeekMessageW.Call(uintptr(unsafe.Pointer(&m)), hwnd, wmChar, wmChar, pmRemove) +} + +// memStream returns an IStream over data. SHCreateMemStream copies the data. +func memStream(data []byte) uintptr { + if len(data) == 0 { + return 0 + } + r, _, _ := procSHCreateMemStream.Call(uintptr(unsafe.Pointer(&data[0])), uintptr(len(data))) + return r +} diff --git a/app/menus/menus.go b/app/menus/menus.go new file mode 100644 index 00000000..ced117c8 --- /dev/null +++ b/app/menus/menus.go @@ -0,0 +1,111 @@ +// Package menus sets up the macOS menu bar with the App, Edit and Window menus, so that ⌘C, ⌘V, +// ⌘A, ⌘W and ⌘M work in the pages. It replaces Wails' default menu, whose View › Reload (⌘R) +// would reload a page while the user is working in it. Quit goes through the app's quit flow. +// +// Wails' role menus (application.AppMenu, EditMenu…) have English labels, so the menus are built +// here from items with the app's own labels, in the app's language. Each item keeps its role, +// which gives it the same AppKit action as Wails' own item (copy:, performMiniaturize:…), and the +// same shortcut. Set builds the menus again when the language changes. macOS adds a few items of +// its own (Edit › AutoFill, Start Dictation…, Emoji & Symbols, and the Services menu's items), +// which it shows in the system's language. +package menus + +import ( + "runtime" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// appName is the name that the App menu's items use, as macOS shows it in the menu bar. +const appName = "Rclone UI" + +// Set installs the menu bar on macOS, in the app's language. On other systems, windows have no +// menu. +func Set(app *application.App) { + if runtime.GOOS != "darwin" { + return + } + app.Menu.SetApplicationMenu(bar(app)) +} + +func bar(app *application.App) *application.Menu { + return application.NewMenuFromItems(appMenu(app), editMenu(), windowMenu()) +} + +// item returns a menu item with a role, which gives it its AppKit action, and a shortcut ("" for +// none). +func item(label string, role application.Role, accelerator string) *application.MenuItem { + it := application.NewMenuItem(label).SetRole(role) + if accelerator != "" { + it.SetAccelerator(accelerator) + } + return it +} + +func submenu(label string, items ...*application.MenuItem) *application.MenuItem { + return application.NewSubmenu(label, application.NewMenuFromItems(items[0], items[1:]...)) +} + +// appMenu returns the App menu, as Wails' AppMenu role has it: About, Services, Hide, Hide Others, +// Show All and Quit. macOS titles the menu with the app's name whatever its label. +func appMenu(app *application.App) *application.MenuItem { + // macOS fills the Services menu itself, in the system's language. + services := application.NewSubmenu(i18n.T("Services"), application.NewMenu()).SetRole(application.ServicesMenu) + return submenu(appName, + // i18n: A menu item that shows the app's About panel. %s is the app's name. + item(i18n.T("About %s", appName), application.About, "").OnClick(func(*application.Context) { app.Menu.ShowAbout() }), + application.NewMenuItemSeparator(), + services, + application.NewMenuItemSeparator(), + // i18n: A menu item that hides the app's windows. %s is the app's name. + item(i18n.T("Hide %s", appName), application.Hide, "CmdOrCtrl+h"), + item(i18n.T("Hide Others"), application.HideOthers, "CmdOrCtrl+OptionOrAlt+h"), + // Wails gives Show All the UnHide role, which has no action. ShowAll's is AppKit's + // unhideAllApplications:. + item(i18n.T("Show All"), application.ShowAll, ""), + application.NewMenuItemSeparator(), + // i18n: A menu item that quits the app. %s is the app's name. + item(i18n.T("Quit %s", appName), application.Quit, "CmdOrCtrl+q").OnClick(func(*application.Context) { app.Quit() }), + ) +} + +// editMenu returns the Edit menu, as Wails' EditMenu role has it on macOS. +func editMenu() *application.MenuItem { + speech := submenu(i18n.T("Speech"), + item(i18n.T("Start Speaking"), application.StartSpeaking, "CmdOrCtrl+OptionOrAlt+Shift+."), + item(i18n.T("Stop Speaking"), application.StopSpeaking, "CmdOrCtrl+OptionOrAlt+Shift+,"), + ) + return submenu(i18n.TC("menu bar", "Edit"), + item(i18n.T("Undo"), application.Undo, "CmdOrCtrl+z"), + item(i18n.T("Redo"), application.Redo, "CmdOrCtrl+Shift+z"), + application.NewMenuItemSeparator(), + // i18n: The Edit menu's item that cuts the selection. + item(i18n.T("Cut"), application.Cut, "CmdOrCtrl+x"), + // i18n: The Edit menu's item that copies the selection to the clipboard. + item(i18n.TC("menu bar", "Copy"), application.Copy, "CmdOrCtrl+c"), + item(i18n.T("Paste"), application.Paste, "CmdOrCtrl+v"), + item(i18n.T("Paste and Match Style"), application.PasteAndMatchStyle, "CmdOrCtrl+OptionOrAlt+Shift+v"), + // i18n: The Edit menu's item that deletes the selection. + item(i18n.T("Delete"), application.Delete, "backspace"), + item(i18n.T("Select All"), application.SelectAll, "CmdOrCtrl+a"), + application.NewMenuItemSeparator(), + speech, + ) +} + +func windowMenu() *application.MenuItem { + // i18n: The Window menu of the menu bar. + return submenu(i18n.T("Window"), + item(i18n.T("Minimize"), application.Minimise, "CmdOrCtrl+M"), + // i18n: The Window menu's item that resizes the window to fit its content, as macOS names it. + item(i18n.T("Zoom"), application.Zoom, ""), + // i18n: The Window menu's item that closes the window. + item(i18n.T("Close"), application.CloseWindow, "CmdOrCtrl+w"), + application.NewMenuItemSeparator(), + // Wails gives Bring All to Front the Front role, which has no action. BringAllToFront's is + // AppKit's arrangeInFront:. + item(i18n.T("Bring All to Front"), application.BringAllToFront, ""), + ) +} diff --git a/app/notify.go b/app/notify.go new file mode 100644 index 00000000..d98e2659 --- /dev/null +++ b/app/notify.go @@ -0,0 +1,175 @@ +package app + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "log/slog" + "net/url" + "strings" + "sync" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/services/notifications" + + "github.com/rclone/rclone-ui/app/interaction" +) + +// notifier shows OS toasts through Wails' notifications service, which uses +// UNUserNotificationCenter on macOS, toasts on Windows and the freedesktop D-Bus service on Linux. +// It is started by hand rather than as a bound service, because a failed start must only disable +// toasts, not stop the app. (An unbundled macOS build has no bundle identifier, so its start +// fails.) A click on a toast with a route opens that route's window. +type notifier struct { + log *slog.Logger + svc *notifications.NotificationService + // open opens the window for a clicked toast. dialog shows a toast that the OS didn't show. + open func(route string) + dialog func(title, body string) + + mu sync.Mutex + ready bool + ok bool // toasts are allowed + asked bool // the OS was already asked, and isn't asked again in this run +} + +// toast is a notification. route is the window that a click opens, such as "/history?id=…", or +// "" for none. toastOnly marks a notification that is only shown as a toast, such as the end of a +// transfer, which History, the tray and the launcher also show. Where toasts can't be shown, +// such a notification is dropped. +type toast struct { + title, body string + route string + toastOnly bool +} + +// routeKey is the key for the route in a toast's data. The OS passes the data back on a click. +const routeKey = "route" + +func newNotifier(log *slog.Logger, open func(route string)) *notifier { + n := ¬ifier{ + log: log, + svc: notifications.New(), + open: open, + dialog: func(title, body string) { interaction.Message(interaction.Info, title, body) }, + } + // Set this before the start, because Windows delivers clicks on toasts from an earlier run as + // soon as the service starts. + n.svc.OnNotificationResponse(n.responded) + return n +} + +// start starts the OS's notification service. It runs on Wails' main thread: on Windows the +// service registers the toast activator's COM class, which fails on a thread without COM +// ("CoInitialize has not been called"), and only the main thread has it. Wails starts its own +// services there for the same reason. +func (n *notifier) start() { + var err error + application.InvokeSync(func() { + err = n.svc.ServiceStartup(context.Background(), application.ServiceOptions{}) + }) + n.mu.Lock() + n.ready = err == nil + n.mu.Unlock() + if err != nil { + n.log.Warn("OS notifications are unavailable", "error", err) + } +} + +// allowed reports whether toasts may be shown. The first time the OS says no, it asks the OS for +// permission. +func (n *notifier) allowed() (bool, error) { + n.mu.Lock() + defer n.mu.Unlock() + if !n.ready { + return false, errors.New("OS notifications are unavailable") + } + if n.ok { + return true, nil + } + ok, err := n.svc.CheckNotificationAuthorization() + if err == nil && !ok && !n.asked { + n.asked = true + ok, err = n.svc.RequestNotificationAuthorization() + } + n.ok = ok + return ok, err +} + +func (n *notifier) send(title, body string) { n.show(toast{title: title, body: body}) } + +// show shows a toast. Where toasts aren't allowed or can't be shown, it shows the same message +// in a dialog (see fallBack). +func (n *notifier) show(t toast) { + if ok, err := n.allowed(); !ok { + n.log.Info("toast not allowed", "title", t.title, "error", err) + n.fallBack(t) + return + } + if err := n.svc.SendNotification(t.options()); err != nil { + n.log.Warn("could not show a toast", "title", t.title, "error", err) + n.fallBack(t) + } +} + +// fallBack shows a toast that the OS didn't show as a dialog, so the user never misses the +// message. A toast-only notification is dropped instead, because it is shown elsewhere too, and a +// dialog for every transfer would get in the way. +func (n *notifier) fallBack(t toast) { + if t.toastOnly { + n.log.Info("dropped a toast-only notification", "title", t.title) + return + } + n.dialog(t.title, t.body) +} + +// options returns the toast's options for the OS, with a new ID. The route is stored in the data. +// On Linux, a notification server without the "actions" capability reports a toast that the user +// closed the same way as a click (Wails #6334), so there closing a toast also opens its window. +// Servers with actions, which most desktops run, report the two apart. +func (t toast) options() notifications.NotificationOptions { + id := make([]byte, 8) + _, _ = rand.Read(id) + o := notifications.NotificationOptions{ID: hex.EncodeToString(id), Title: t.title, Body: t.body} + if t.route != "" { + o.Data = map[string]any{routeKey: t.route} + } + return o +} + +func (n *notifier) responded(r notifications.NotificationResult) { + if r.Error != nil { + n.log.Warn("could not read a toast's response", "error", r.Error) + return + } + route, ok := clickedRoute(r.Response) + if !ok { + return + } + n.log.Info("toast clicked", "route", route) + // Open the window outside the OS's callback, which may run on the main thread. Opening a + // window waits for the main thread. + go n.open(route) +} + +// clickedRoute returns the route that a toast's response opens. The response must be a click on +// the toast itself (toasts have no buttons), and the route must be one of the app's routes. +func clickedRoute(r notifications.NotificationResponse) (string, bool) { + if r.ActionIdentifier != notifications.DefaultActionIdentifier { + return "", false + } + route, _ := r.UserInfo[routeKey].(string) + return route, appRoute(route) +} + +// appRoute reports whether route is one of the app's pages, such as "/history?id=…". It must +// not be an outside URL, because a window would load it with access to the app's bindings. On +// Windows any program can send the app a click with its own data. +func appRoute(route string) bool { + if !strings.HasPrefix(route, "/") || strings.HasPrefix(route, "//") || strings.Contains(route, `\`) { + return false + } + u, err := url.Parse(route) + return err == nil && u.Scheme == "" && u.Host == "" +} diff --git a/app/notify_test.go b/app/notify_test.go new file mode 100644 index 00000000..118a98e9 --- /dev/null +++ b/app/notify_test.go @@ -0,0 +1,80 @@ +package app + +import ( + "encoding/json" + "log/slog" + "slices" + "testing" + + "github.com/wailsapp/wails/v3/pkg/services/notifications" +) + +func TestUnshownToastFallsBack(t *testing.T) { + var dialogs []string + // The notifier was never started, so the OS shows no toasts. + n := ¬ifier{log: slog.New(slog.DiscardHandler), dialog: func(title, _ string) { dialogs = append(dialogs, title) }} + n.send("Copied!", "Serve details copied to clipboard") + n.show(toast{title: "Mount failed", body: "photos: no such remote"}) + n.show(toast{title: "Copy finished", body: "Photos → gdrive:Photos", route: "/history?id=t1", toastOnly: true}) + if want := []string{"Copied!", "Mount failed"}; !slices.Equal(dialogs, want) { + t.Fatalf("dialogs %q, want %q", dialogs, want) + } +} + +// TestToastRoute passes the toast's data through JSON, as macOS and Windows do before they pass +// it back with a click. +func TestToastRoute(t *testing.T) { + o := toast{title: "Copy finished", route: "/history?id=t1"}.options() + if o.ID == "" || o.Title != "Copy finished" { + t.Fatalf("options %+v", o) + } + raw, err := json.Marshal(o.Data) + if err != nil { + t.Fatal(err) + } + var info map[string]any + if err := json.Unmarshal(raw, &info); err != nil { + t.Fatal(err) + } + click := notifications.NotificationResponse{ActionIdentifier: notifications.DefaultActionIdentifier, UserInfo: info} + if route, ok := clickedRoute(click); !ok || route != "/history?id=t1" { + t.Fatalf("clicked: %q, %v", route, ok) + } + + if o := (toast{title: "Mount failed"}).options(); o.Data != nil { + t.Errorf("a toast without a route carries %v", o.Data) + } + button := click + button.ActionIdentifier = "stop" + for name, r := range map[string]notifications.NotificationResponse{ + "a button": button, + "no route": {ActionIdentifier: notifications.DefaultActionIdentifier}, + "a route not a text": {ActionIdentifier: notifications.DefaultActionIdentifier, UserInfo: map[string]any{routeKey: 42.0}}, + "a URL elsewhere": {ActionIdentifier: notifications.DefaultActionIdentifier, UserInfo: map[string]any{routeKey: "https://example.com"}}, + } { + if route, ok := clickedRoute(r); ok { + t.Errorf("%s opens %q", name, route) + } + } +} + +func TestAppRoute(t *testing.T) { + for _, ok := range []string{"/", "/history", "/history?id=t1", "/settings?tab=about#x"} { + if !appRoute(ok) { + t.Errorf("appRoute(%q) refused it", ok) + } + } + for _, bad := range []string{ + "", + "transfers", + "https://example.com/transfers", + "//example.com/transfers", + `/\example.com/transfers`, + "javascript:alert(1)", + "/transfers\n?id=t1", + } { + if appRoute(bad) { + t.Errorf("appRoute(%q) accepted it", bad) + } + } +} diff --git a/app/osquit_darwin.go b/app/osquit_darwin.go new file mode 100644 index 00000000..b798f374 --- /dev/null +++ b/app/osquit_darwin.go @@ -0,0 +1,44 @@ +package app + +/* +#cgo CFLAGS: -mmacosx-version-min=12.0 -x objective-c +#cgo LDFLAGS: -mmacosx-version-min=12.0 -framework Foundation -framework CoreServices +#import +#import + +// rcuiCurrentQuit reads the class, the id and the quit reason (kAEQuitReason) of the Apple event +// being handled. A value is 0 when there is no event or no reason. +static void rcuiCurrentQuit(unsigned int *cls, unsigned int *evt, unsigned int *why) { + *cls = 0; + *evt = 0; + *why = 0; + NSAppleEventDescriptor *e = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent]; + if (e == nil) { + return; + } + *cls = [e eventClass]; + *evt = [e eventID]; + NSAppleEventDescriptor *reason = [e attributeDescriptorForKeyword:kAEQuitReason]; + if (reason == nil) { + reason = [e paramDescriptorForKeyword:kAEQuitReason]; + } + if (reason == nil) { + return; + } + OSType code = [reason typeCodeValue]; + if (code == 0) { + code = [reason enumCodeValue]; + } + *why = code; +} +*/ +import "C" + +// osEndingSession reports whether loginwindow asked the app to quit for a logout, a restart or a +// shutdown. It must run on the main thread, because it reads the Apple event that the +// applicationShouldTerminate: handler is answering. +func osEndingSession() bool { + var cls, evt, why C.uint + C.rcuiCurrentQuit(&cls, &evt, &why) + return sessionEndEvent(uint32(cls), uint32(evt), uint32(why)) +} diff --git a/app/osquit_other.go b/app/osquit_other.go new file mode 100644 index 00000000..ac241082 --- /dev/null +++ b/app/osquit_other.go @@ -0,0 +1,8 @@ +//go:build !darwin + +package app + +// osEndingSession always returns false here. Only macOS reports the end of a session through +// shouldQuit. Windows reports it in WM_ENDSESSION (see wndProc), and on Linux a logout ends the UI +// and the core together. +func osEndingSession() bool { return false } diff --git a/app/pathlink/link_darwin.go b/app/pathlink/link_darwin.go new file mode 100644 index 00000000..87ec4e0e --- /dev/null +++ b/app/pathlink/link_darwin.go @@ -0,0 +1,52 @@ +package pathlink + +import ( + "fmt" + "os/exec" + "path/filepath" + "strings" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +// macLink is the link's path. It is on the default PATH (/etc/paths) and on root's PATH. +const macLink = "/usr/local/bin/rclone" + +func newLinker() (*Linker, error) { + data, err := datadir.Default() + if err != nil { + return nil, err + } + exe, err := platform.Executable() + if err != nil { + return nil, err + } + l := &Linker{ + exe: exe, + link: macLink, + pointer: filepath.Join(data, "bin", "rclone"), + path: envPath, + asAdmin: runAsAdmin, + } + if strings.Contains(exe, "/AppTranslocation/") { + l.unsupported = i18n.M("macOS runs this Rclone UI from a temporary copy: move it to Applications and open it from there first.") + } + return l, nil +} + +func runAsAdmin(shellCmd, prompt string) error { + esc := strings.NewReplacer(`\`, `\\`, `"`, `\"`) + script := fmt.Sprintf(`do shell script "%s" with administrator privileges with prompt "%s"`, + esc.Replace(shellCmd), esc.Replace(prompt)) + out, err := exec.Command("/usr/bin/osascript", "-e", script).CombinedOutput() + if err != nil { + if strings.Contains(string(out), "-128") { + return errs.New("The administrator prompt was cancelled.") + } + return errs.Errorf("The administrator prompt failed: %s", strings.TrimSpace(string(out))) + } + return nil +} diff --git a/app/pathlink/link_linux.go b/app/pathlink/link_linux.go new file mode 100644 index 00000000..74f95fff --- /dev/null +++ b/app/pathlink/link_linux.go @@ -0,0 +1,43 @@ +package pathlink + +import ( + "os" + "path/filepath" + "strings" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/i18n" +) + +func newLinker() (*Linker, error) { + if platform.IsFlatpak() { + return &Linker{path: envPath, unsupported: i18n.M("Rclone UI runs in a Flatpak sandbox, which a terminal can't run it from. "+ + "`flatpak run --command=rcui %s ` runs its rclone.", platform.FlatpakAppID), + command: "flatpak run --command=rcui " + platform.FlatpakAppID}, nil + } + data, err := datadir.Default() + if err != nil { + return nil, err + } + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + exe, err := platform.Executable() + if err != nil { + return nil, err + } + // Inside an AppImage, the executable is in a mount that disappears when the process exits. + // The image file itself stays, and the runtime passes on the name it was called by (see + // main.go). + if img, dir := os.Getenv("APPIMAGE"), os.Getenv("APPDIR"); img != "" && dir != "" && strings.HasPrefix(exe, filepath.Clean(dir)+"/") { + exe = img + } + return &Linker{ + exe: exe, + link: filepath.Join(home, ".local", "bin", "rclone"), + pointer: filepath.Join(data, "bin", "rclone"), + path: envPath, + }, nil +} diff --git a/app/pathlink/link_other.go b/app/pathlink/link_other.go new file mode 100644 index 00000000..0f0fdd3a --- /dev/null +++ b/app/pathlink/link_other.go @@ -0,0 +1,9 @@ +//go:build !darwin && !linux && !windows + +package pathlink + +import "github.com/rclone/rclone-ui/core/i18n" + +func newLinker() (*Linker, error) { + return &Linker{path: envPath, unsupported: i18n.M("Rclone UI doesn't add rclone to PATH on this system.")}, nil +} diff --git a/app/pathlink/link_unix.go b/app/pathlink/link_unix.go new file mode 100644 index 00000000..ce346003 --- /dev/null +++ b/app/pathlink/link_unix.go @@ -0,0 +1,229 @@ +//go:build !windows + +package pathlink + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + + "golang.org/x/sys/unix" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +func (l *Linker) Status() State { + st := State{Supported: l.unsupported.IsZero(), Reason: l.unsupported.Local(), Link: l.link, Target: l.exe} + if !st.Supported { + st.Command = l.command + if st.Command == "" && l.exe != "" { + st.Command = shCommand(l.exe, l.path()) + } + return st + } + st.Enabled = l.ours() && sameFile(l.link, l.exe) + st.NeedsAdmin = l.asAdmin != nil && !writable(filepath.Dir(l.link)) + dirs := l.path() + linkAt := indexOf(dirs, filepath.Dir(l.link), false) + user, userAt := l.userRclone(dirs) + st.UserRclone = user + userFirst := userAt >= 0 && (linkAt < 0 || userAt < linkAt) + if st.Enabled { + st.Warning = warning(filepath.Dir(l.link), linkAt >= 0, user, userFirst) + } + st.Command = shCommand(l.exe, dirs) + if st.Enabled && linkAt >= 0 && !userFirst { + st.Command = "rclone" + } + return st +} + +// shCommand returns the command a POSIX shell uses to run exe. That is its name when its folder +// is on PATH (as for the deb's /usr/bin/rcui), or else its path, quoted when needed. +func shCommand(exe string, dirs []string) string { + if indexOf(dirs, filepath.Dir(exe), false) >= 0 { + return filepath.Base(exe) + } + if strings.Trim(exe, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/._-+") == "" { + return exe + } + return shQuote(exe) +} + +// Enable points the pointer to this app and creates the link, unless something else already has +// the link's name. That includes a broken link, which may be the user's own link to something they +// will put back. A broken link to the pointer belongs to this app, and works again once the +// pointer is fixed. +func (l *Linker) Enable() (State, error) { + if !l.unsupported.IsZero() { + return l.Status(), unsupported(l.unsupported) + } + if _, err := os.Lstat(l.link); err == nil && !l.ours() { + return l.Status(), foreign(l.link) + } else if err != nil && !errors.Is(err, fs.ErrNotExist) { + return l.Status(), err + } + if err := l.point(); err != nil { + return l.Status(), err + } + if !l.ours() { + if err := l.makeLink(); err != nil { + return l.Status(), err + } + } + return l.Status(), nil +} + +// foreign returns Enable's error when something else has the link's name. For a broken link, the +// error says where the link pointed. +func foreign(link string) error { + shown := errs.Errorf("An rclone that isn't Rclone UI's is already at %s. Rclone UI leaves it as it is: remove it first to use Rclone UI's.", link) + if target, err := os.Readlink(link); err == nil { + if _, err := os.Stat(link); errors.Is(err, fs.ErrNotExist) { + // i18n: %[1]s is the path of the command, and %[2]s where its broken link points. + shown = errs.Errorf("An rclone that isn't Rclone UI's is already at %[1]s (a link to %[2]s, which no longer exists). "+ + "Rclone UI leaves it as it is: remove it first to use Rclone UI's.", link, target) + } + } + return refusal{shown, ErrForeign} +} + +// Disable removes the link if it belongs to this app, and removes the pointer. Another rclone at +// the link's path is kept, even if it is a broken link. +func (l *Linker) Disable() (State, error) { + if !l.unsupported.IsZero() { + return l.Status(), nil + } + if l.ours() { + err := os.Remove(l.link) + if errors.Is(err, fs.ErrPermission) && l.asAdmin != nil { + q := shQuote(l.link) + // i18n: The text of macOS's administrator prompt, which asks for the password. + err = l.asAdmin("if [ -L "+q+" ]; then rm -f "+q+"; fi", i18n.T("Rclone UI wants to remove rclone from your PATH.")) + } + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return l.Status(), err + } + } + if info, err := os.Lstat(l.pointer); err == nil && info.Mode()&fs.ModeSymlink != 0 { + if err := os.Remove(l.pointer); err != nil { + return l.Status(), err + } + } + return l.Status(), nil +} + +// Refresh points an existing link's pointer to this app again, which is needed after the app has +// moved. +func (l *Linker) Refresh() error { + if !l.unsupported.IsZero() || !l.ours() { + return nil + } + if target, err := os.Readlink(l.pointer); err == nil && target == l.exe { + return nil + } + return l.point() +} + +// ours reports whether the link leads to this app, either through the pointer or directly. +func (l *Linker) ours() bool { + info, err := os.Lstat(l.link) + if err != nil || info.Mode()&fs.ModeSymlink == 0 { + return false + } + target, err := os.Readlink(l.link) + if err != nil { + return false + } + if !filepath.IsAbs(target) { + target = filepath.Join(filepath.Dir(l.link), target) + } + return filepath.Clean(target) == filepath.Clean(l.pointer) || sameFile(l.link, l.exe) +} + +// point makes the pointer lead to the app, replacing the old pointer with a single rename. +func (l *Linker) point() error { + if err := os.MkdirAll(filepath.Dir(l.pointer), 0o755); err != nil { + return err + } + return replaceSymlink(l.exe, l.pointer) +} + +// makeLink creates the link to the pointer. It does so directly when the folder is writable or can +// be created (as with ~/.local/bin), or else through the administrator prompt (as with macOS's +// /usr/local/bin). +func (l *Linker) makeLink() error { + dir := filepath.Dir(l.link) + if l.asAdmin == nil || writable(dir) { + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + return replaceSymlink(l.pointer, l.link) + } + return l.asAdmin(fmt.Sprintf("mkdir -p %s && ln -sfn %s %s", shQuote(dir), shQuote(l.pointer), shQuote(l.link)), + // i18n: The text of macOS's administrator prompt, which asks for the password. + i18n.T("Rclone UI wants to add rclone to your PATH.")) +} + +// userRclone returns the first rclone on PATH that isn't this app, and its position. +func (l *Linker) userRclone(dirs []string) (string, int) { + for i, dir := range dirs { + if dir == "" { + continue + } + cand := filepath.Join(dir, "rclone") + info, err := os.Stat(cand) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { + continue + } + if sameFile(cand, l.exe) || filepath.Clean(cand) == filepath.Clean(l.pointer) { + continue + } + return cand, i + } + return "", -1 +} + +// replaceSymlink makes name a link to target, replacing any existing link with a single rename. +func replaceSymlink(target, name string) error { + tmp := name + ".rcui-new" + _ = os.Remove(tmp) + if err := os.Symlink(target, tmp); err != nil { + return err + } + if err := os.Rename(tmp, name); err != nil { + _ = os.Remove(tmp) + return err + } + return nil +} + +func sameFile(a, b string) bool { + ia, err := os.Stat(a) + if err != nil { + return false + } + ib, err := os.Stat(b) + return err == nil && os.SameFile(ia, ib) +} + +// writable reports whether this user can create files in dir, or create dir. +func writable(dir string) bool { + for { + if _, err := os.Stat(dir); err == nil { + return unix.Access(dir, unix.W_OK) == nil + } + parent := filepath.Dir(dir) + if parent == dir { + return false + } + dir = parent + } +} + +// shQuote is POSIX single-quoting. +func shQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } diff --git a/app/pathlink/link_unix_test.go b/app/pathlink/link_unix_test.go new file mode 100644 index 00000000..83f24138 --- /dev/null +++ b/app/pathlink/link_unix_test.go @@ -0,0 +1,292 @@ +//go:build !windows + +package pathlink + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/rclone" +) + +// fixture is a Linker set up in temporary folders, with the app's executable, the link's folder +// (on PATH or not) and the pointer in the data folder. +type fixture struct { + l *Linker + root string + pathDir []string +} + +func newFixture(t *testing.T) *fixture { + t.Helper() + root := t.TempDir() + exe := filepath.Join(root, "app", "rcui") + writeExe(t, exe) + f := &fixture{root: root} + f.l = &Linker{ + exe: exe, + link: filepath.Join(root, "bin", "rclone"), + pointer: filepath.Join(root, "data", "bin", "rclone"), + path: func() []string { return f.pathDir }, + } + return f +} + +func writeExe(t *testing.T, path string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } +} + +func readlink(t *testing.T, name string) string { + t.Helper() + target, err := os.Readlink(name) + if err != nil { + t.Fatal(err) + } + return target +} + +func TestEnableDisable(t *testing.T) { + f := newFixture(t) + if st := f.l.Status(); !st.Supported || st.Enabled { + t.Fatalf("before: %+v", st) + } + st, err := f.l.Enable() + if err != nil { + t.Fatal(err) + } + if !st.Enabled || readlink(t, f.l.link) != f.l.pointer || readlink(t, f.l.pointer) != f.l.exe { + t.Fatalf("after Enable: %+v", st) + } + if !strings.Contains(st.Warning, "isn't on your PATH") { + t.Errorf("a link outside PATH: warning %q", st.Warning) + } + f.pathDir = []string{filepath.Dir(f.l.link)} + if st := f.l.Status(); st.Warning != "" { + t.Errorf("a link on PATH: warning %q", st.Warning) + } + // Enabling again changes nothing. + if st, err := f.l.Enable(); err != nil || !st.Enabled { + t.Fatalf("a second Enable: %+v %v", st, err) + } + + st, err = f.l.Disable() + if err != nil { + t.Fatal(err) + } + if st.Enabled { + t.Fatalf("after Disable: %+v", st) + } + for _, name := range []string{f.l.link, f.l.pointer} { + if _, err := os.Lstat(name); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s is still there: %v", name, err) + } + } + if _, err := os.Stat(f.l.exe); err != nil { + t.Errorf("the app itself: %v", err) + } +} + +func TestForeignRclone(t *testing.T) { + f := newFixture(t) + writeExe(t, f.l.link) + _, err := f.l.Enable() + if !errors.Is(err, ErrForeign) { + t.Fatalf("Enable over a user's rclone: %v", err) + } + if info, err := os.Lstat(f.l.link); err != nil || !info.Mode().IsRegular() { + t.Fatalf("the user's rclone was replaced: %v %v", info, err) + } + if _, err := f.l.Disable(); err != nil { + t.Fatal(err) + } + if info, err := os.Lstat(f.l.link); err != nil || !info.Mode().IsRegular() { + t.Fatalf("Disable removed the user's rclone: %v %v", info, err) + } +} + +func TestDanglingLink(t *testing.T) { + f := newFixture(t) + if err := os.MkdirAll(filepath.Dir(f.l.link), 0o755); err != nil { + t.Fatal(err) + } + gone := filepath.Join(f.root, "gone") + if err := os.Symlink(gone, f.l.link); err != nil { + t.Fatal(err) + } + _, err := f.l.Enable() + if !errors.Is(err, ErrForeign) || !strings.Contains(err.Error(), "(a link to "+gone+", which no longer exists)") { + t.Fatalf("Enable over a dead link elsewhere: %v", err) + } + if _, err := f.l.Disable(); err != nil { + t.Fatal(err) + } + if readlink(t, f.l.link) != gone { + t.Fatal("Disable removed the dead link") + } + + if err := os.Remove(f.l.link); err != nil { + t.Fatal(err) + } + if err := os.Symlink(f.l.pointer, f.l.link); err != nil { + t.Fatal(err) + } + if st, err := f.l.Enable(); err != nil || !st.Enabled || readlink(t, f.l.pointer) != f.l.exe { + t.Fatalf("Enable over a dead link to the pointer: %+v %v", st, err) + } +} + +func TestUserRcloneOnPath(t *testing.T) { + f := newFixture(t) + other := filepath.Join(f.root, "usr", "bin") + writeExe(t, filepath.Join(other, "rclone")) + if _, err := f.l.Enable(); err != nil { + t.Fatal(err) + } + f.pathDir = []string{other, filepath.Dir(f.l.link)} + if st := f.l.Status(); st.UserRclone != filepath.Join(other, "rclone") || !strings.Contains(st.Warning, "comes first") { + t.Errorf("a user's rclone first: %+v", st) + } + f.pathDir = []string{filepath.Dir(f.l.link), other} + if st := f.l.Status(); !strings.Contains(st.Warning, "now runs Rclone UI's rclone") { + t.Errorf("a user's rclone after: %+v", st) + } +} + +func TestRefresh(t *testing.T) { + f := newFixture(t) + if err := f.l.Refresh(); err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(f.l.pointer); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("Refresh without a link made the pointer: %v", err) + } + + moved := filepath.Join(f.root, "old place", "rcui") + writeExe(t, moved) + for name, target := range map[string]string{f.l.pointer: moved, f.l.link: f.l.pointer} { + if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, name); err != nil { + t.Fatal(err) + } + } + if st := f.l.Status(); st.Enabled { + t.Fatalf("the moved app's link counts as enabled before Refresh: %+v", st) + } + if err := f.l.Refresh(); err != nil { + t.Fatal(err) + } + if readlink(t, f.l.pointer) != f.l.exe || !f.l.Status().Enabled { + t.Fatalf("after Refresh: pointer → %s", readlink(t, f.l.pointer)) + } +} + +func TestAdminPrompt(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root writes everywhere") + } + f := newFixture(t) + dir := filepath.Dir(f.l.link) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + var prompts []string + f.l.asAdmin = func(shellCmd, prompt string) error { + prompts = append(prompts, prompt) + // Act as the administrator's shell, with the folder writable while it runs. + if err := os.Chmod(dir, 0o755); err != nil { + return err + } + defer func() { _ = os.Chmod(dir, 0o555) }() + out, err := exec.Command("/bin/sh", "-c", shellCmd).CombinedOutput() + if err != nil { + return errors.New(string(out)) + } + return nil + } + if st := f.l.Status(); !st.NeedsAdmin { + t.Fatalf("status: %+v", st) + } + if st, err := f.l.Enable(); err != nil || !st.Enabled { + t.Fatalf("Enable: %+v %v", st, err) + } + if st, err := f.l.Disable(); err != nil || st.Enabled { + t.Fatalf("Disable: %+v %v", st, err) + } + if len(prompts) != 2 { + t.Fatalf("prompts: %q", prompts) + } +} + +func TestCommand(t *testing.T) { + f := newFixture(t) + if got := f.l.Status().Command; got != f.l.exe { + t.Errorf("no link: %q", got) + } + f.pathDir = []string{filepath.Dir(f.l.exe)} + if got := f.l.Status().Command; got != "rcui" { + t.Errorf("rcui on PATH: %q", got) + } + if _, err := f.l.Enable(); err != nil { + t.Fatal(err) + } + if got := f.l.Status().Command; got != "rcui" { + t.Errorf("a link off PATH: %q", got) + } + f.pathDir = []string{filepath.Dir(f.l.link)} + if got := f.l.Status().Command; got != "rclone" { + t.Errorf("a link on PATH: %q", got) + } + other := filepath.Join(f.root, "usr", "bin") + writeExe(t, filepath.Join(other, "rclone")) + f.pathDir = []string{other, filepath.Dir(f.l.link)} + if got := f.l.Status().Command; got != f.l.exe { + t.Errorf("a user's rclone first: %q", got) + } + + if got := shCommand("/Applications/Rclone UI.app/Contents/MacOS/rcui", nil); got != `'/Applications/Rclone UI.app/Contents/MacOS/rcui'` { + t.Errorf("a path with a space: %q", got) + } +} + +// TestRefusalsReachThePageTranslated: Enable's refusals keep their kind for errors.Is, and the +// page gets their text in the app's language (the test language here). +func TestRefusalsReachThePageTranslated(t *testing.T) { + i18n.SetLanguage(i18n.Pseudo) + t.Cleanup(func() { i18n.SetLanguage(i18n.English) }) + link := filepath.Join(t.TempDir(), "rclone") + if err := os.WriteFile(link, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + err error + kind error + want string + }{ + {foreign(link), ErrForeign, "[Áñ rçlóñé thát ísñ't Rçlóñé ÚÍ's ís álréádý át " + link}, + {unsupported(i18n.M("Rclone UI doesn't add rclone to PATH on this system.")), ErrUnsupported, "[Rçlóñé ÚÍ dóésñ't ádd rçlóñé tó PÁTH óñ thís sýstém.]"}, + } { + if !errors.Is(c.err, c.kind) { + t.Errorf("%v is not %v", c.err, c.kind) + } + if got := rclone.ErrorOf(c.err).Localized().Message; !strings.HasPrefix(got, c.want) { + t.Errorf("the page gets %q, want it to start with %q", got, c.want) + } + } +} diff --git a/app/pathlink/link_windows.go b/app/pathlink/link_windows.go new file mode 100644 index 00000000..ab7a3730 --- /dev/null +++ b/app/pathlink/link_windows.go @@ -0,0 +1,194 @@ +//go:build windows + +package pathlink + +import ( + "errors" + "os" + "path/filepath" + "strings" + "syscall" + "unsafe" + + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/i18n" +) + +// On Windows, the installer and the portable zip put a console rclone.exe in the bin folder next +// to rcui.exe (see build/windows/rclone-shim), which runs ..\rcui.exe. Enabling the link adds that +// folder to the user's PATH in HKCU\Environment. A copy without it, such as an rcui.exe copied on +// its own, has no rclone.exe to add to PATH. + +func newLinker() (*Linker, error) { + exe, err := platform.Executable() + if err != nil { + return nil, err + } + l := &Linker{exe: exe, link: filepath.Join(filepath.Dir(exe), "bin"), path: newTerminalPath, userPath: userEnvPath{}} + if _, err := os.Stat(filepath.Join(l.link, "rclone.exe")); err != nil { + l.unsupported = i18n.M(`This copy of Rclone UI has no bin\rclone.exe next to it. The installer and the portable zip bring that rclone command.`) + } + return l, nil +} + +func (l *Linker) Status() State { + st := State{Supported: l.unsupported.IsZero(), Reason: l.unsupported.Local(), Link: l.link, Target: l.exe} + // A copy without bin\rclone.exe only has rcui.exe, which is a windowed program, so a terminal + // doesn't wait for it. bin\rclone.exe is a console program. + st.Command = psCommand(l.exe) + if !st.Supported { + return st + } + st.Command = psCommand(filepath.Join(l.link, "rclone.exe")) + value, err := l.userPath.get() + st.Enabled = err == nil && pathHas(value, l.link) + dirs := l.path() + linkAt := indexOf(dirs, l.link, true) + user, userAt := l.userRclone(dirs) + st.UserRclone = user + userFirst := userAt >= 0 && (linkAt < 0 || userAt < linkAt) + if st.Enabled { + st.Warning = warning(l.link, linkAt >= 0, user, userFirst) + if linkAt >= 0 && !userFirst { + st.Command = "rclone" + } + } + return st +} + +// psCommand returns the command that PowerShell (Windows' usual terminal) uses to run a program +// by its path. +func psCommand(path string) string { return `& "` + path + `"` } + +func (l *Linker) Enable() (State, error) { + if !l.unsupported.IsZero() { + return l.Status(), unsupported(l.unsupported) + } + if err := l.setUserPath(func(v string) string { return pathWith(v, l.link) }); err != nil { + return l.Status(), err + } + return l.Status(), nil +} + +func (l *Linker) Disable() (State, error) { + if err := l.setUserPath(func(v string) string { return pathWithout(v, l.link) }); err != nil { + return l.Status(), err + } + return l.Status(), nil +} + +// Refresh does nothing on Windows: the entry on PATH is the copy's own bin folder, which an +// update leaves in place. A portable copy that was moved shows the link as off, and turning it on +// again adds the new folder. +func (l *Linker) Refresh() error { return nil } + +// setUserPath rewrites the user's PATH and tells running programs that the environment changed. +// Explorer then reloads it, so new terminals get the new PATH. +func (l *Linker) setUserPath(edit func(string) string) error { + value, err := l.userPath.get() + if err != nil { + return err + } + next := edit(value) + if next == value { + return nil + } + if err := l.userPath.set(next); err != nil { + return err + } + broadcastEnvironment() + return nil +} + +// userRclone returns the first rclone.exe in dirs that isn't this app's, and its position. +func (l *Linker) userRclone(dirs []string) (string, int) { + for i, d := range dirs { + if d == "" || samePathSegment(d, l.link) { + continue + } + p := filepath.Join(d, "rclone.exe") + if info, err := os.Stat(p); err == nil && !info.IsDir() { + return p, i + } + } + return "", -1 +} + +// userEnvPath reads and writes HKCU\Environment\Path. It is kept as REG_EXPAND_SZ, because it can +// hold variables such as %USERPROFILE%. +type userEnvPath struct{} + +func (userEnvPath) get() (string, error) { + k, err := registry.OpenKey(registry.CURRENT_USER, `Environment`, registry.QUERY_VALUE) + if err != nil { + return "", err + } + defer func() { _ = k.Close() }() + v, _, err := k.GetStringValue("Path") + if errors.Is(err, registry.ErrNotExist) { + return "", nil + } + return v, err +} + +func (userEnvPath) set(value string) error { + k, _, err := registry.CreateKey(registry.CURRENT_USER, `Environment`, registry.SET_VALUE) + if err != nil { + return err + } + defer func() { _ = k.Close() }() + return k.SetExpandStringValue("Path", value) +} + +// newTerminalPath returns the PATH that a new terminal gets: the machine's PATH, then the user's, +// with variables expanded. The UI's own PATH is still the one it started with, before any change. +func newTerminalPath() []string { + var dirs []string + for _, src := range []struct { + root registry.Key + path string + }{ + {registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\Session Manager\Environment`}, + {registry.CURRENT_USER, `Environment`}, + } { + k, err := registry.OpenKey(src.root, src.path, registry.QUERY_VALUE) + if err != nil { + continue + } + v, _, err := k.GetStringValue("Path") + _ = k.Close() + if err != nil { + continue + } + if expanded, err := registry.ExpandString(v); err == nil { + v = expanded + } + dirs = append(dirs, strings.Split(v, ";")...) + } + if len(dirs) == 0 { + return envPath() + } + return dirs +} + +var sendMessageTimeout = windows.NewLazySystemDLL("user32.dll").NewProc("SendMessageTimeoutW") + +// broadcastEnvironment sends WM_SETTINGCHANGE "Environment" to every top-level window, as setx +// does. Explorer then reloads the environment, and the terminals it starts next see the new PATH. +func broadcastEnvironment() { + const ( + hwndBroadcast = 0xffff + wmSettingChange = 0x001a + smtoAbortIfHung = 0x0002 + ) + env, err := syscall.UTF16PtrFromString("Environment") + if err != nil { + return + } + var result uintptr + _, _, _ = sendMessageTimeout.Call(hwndBroadcast, wmSettingChange, 0, uintptr(unsafe.Pointer(env)), + smtoAbortIfHung, 5000, uintptr(unsafe.Pointer(&result))) +} diff --git a/app/pathlink/link_windows_test.go b/app/pathlink/link_windows_test.go new file mode 100644 index 00000000..e91d7edb --- /dev/null +++ b/app/pathlink/link_windows_test.go @@ -0,0 +1,104 @@ +//go:build windows + +package pathlink + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// memPath keeps the user's PATH in memory instead of HKCU\Environment. +type memPath struct{ value string } + +func (m *memPath) get() (string, error) { return m.value, nil } +func (m *memPath) set(v string) error { m.value = v; return nil } + +func newWindowsLinker(t *testing.T, withShim bool) (*Linker, *memPath) { + t.Helper() + root := t.TempDir() + bin := filepath.Join(root, "Rclone UI", "bin") + if err := os.MkdirAll(bin, 0o755); err != nil { + t.Fatal(err) + } + if withShim { + if err := os.WriteFile(filepath.Join(bin, "rclone.exe"), []byte("MZ"), 0o755); err != nil { + t.Fatal(err) + } + } + store := &memPath{value: `C:\Windows;C:\Tools`} + l := &Linker{ + exe: filepath.Join(root, "Rclone UI", "rcui.exe"), + link: bin, + path: func() []string { return filepath.SplitList(store.value) }, + userPath: store, + } + if !withShim { + l.unsupported = i18n.M("no rclone.exe") + } + return l, store +} + +func TestWindowsEnableDisable(t *testing.T) { + l, store := newWindowsLinker(t, true) + st, err := l.Enable() + if err != nil { + t.Fatal(err) + } + if !st.Enabled || !pathHas(store.value, l.link) || st.Warning != "" { + t.Fatalf("after Enable: %+v, PATH %q", st, store.value) + } + if st, err := l.Disable(); err != nil || st.Enabled || pathHas(store.value, l.link) { + t.Fatalf("after Disable: %+v %v, PATH %q", st, err, store.value) + } + if store.value != `C:\Windows;C:\Tools` { + t.Errorf("the rest of PATH changed: %q", store.value) + } +} + +func TestWindowsUserRclone(t *testing.T) { + l, store := newWindowsLinker(t, true) + other := t.TempDir() + if err := os.WriteFile(filepath.Join(other, "rclone.exe"), []byte("MZ"), 0o755); err != nil { + t.Fatal(err) + } + store.value = other + st, err := l.Enable() + if err != nil { + t.Fatal(err) + } + if st.UserRclone != filepath.Join(other, "rclone.exe") || st.Warning == "" { + t.Fatalf("status: %+v", st) + } +} + +func TestWindowsUnsupported(t *testing.T) { + l, store := newWindowsLinker(t, false) + if st := l.Status(); st.Supported { + t.Fatalf("status: %+v", st) + } + if _, err := l.Enable(); !errors.Is(err, ErrUnsupported) || pathHas(store.value, l.link) { + t.Fatalf("Enable: %v, PATH %q", err, store.value) + } +} + +func TestWindowsCommand(t *testing.T) { + l, _ := newWindowsLinker(t, true) + shim := `& "` + filepath.Join(l.link, "rclone.exe") + `"` + if got := l.Status().Command; got != shim { + t.Errorf("no link: %q", got) + } + if _, err := l.Enable(); err != nil { + t.Fatal(err) + } + if got := l.Status().Command; got != "rclone" { + t.Errorf("on PATH: %q", got) + } + alone, _ := newWindowsLinker(t, false) + if got := alone.Status().Command; got != `& "`+alone.exe+`"` { + t.Errorf("an rcui.exe without bin\\rclone.exe: %q", got) + } +} diff --git a/app/pathlink/linker.go b/app/pathlink/linker.go new file mode 100644 index 00000000..300cbbe5 --- /dev/null +++ b/app/pathlink/linker.go @@ -0,0 +1,78 @@ +package pathlink + +import ( + "os" + "path/filepath" + "strings" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// Linker manages the rclone link for one copy of the app. New makes the real one, and the tests +// build their own around temporary folders. +type Linker struct { + // exe is the program that `rclone` runs: rcui, or $APPIMAGE, which runs rcui. + exe string + // link is the command's path on PATH (macOS, Linux), or the folder added to PATH (Windows). + link string + // pointer is /bin/rclone, the link's target, which points to exe (macOS, Linux). + pointer string + // unsupported explains why no link can work here. It is the zero Text when a link can work. + unsupported i18n.Text + // command is State.Command for systems where no link can work and exe isn't useful to show + // (Flatpak). + command string + // path lists PATH's folders in the order a new terminal searches them. + path func() []string + // asAdmin runs a shell command through an administrator prompt (macOS). It is nil elsewhere. + asAdmin func(shellCmd, prompt string) error + // userPath is the user's stored PATH (Windows). + userPath store +} + +// store reads and writes the user's stored PATH (HKCU\Environment on Windows). +type store interface { + get() (value string, err error) + set(value string) error +} + +func New() (*Linker, error) { return newLinker() } + +// envPath returns the process's PATH. The UI role runs with the login shell's PATH (see +// platform.FixPath), so it matches the PATH that a new terminal gets. +func envPath() []string { return filepath.SplitList(os.Getenv("PATH")) } + +// indexOf returns dir's position in dirs, or -1. It compares cleaned paths, ignoring case when +// fold is set. +func indexOf(dirs []string, dir string, fold bool) int { + want := filepath.Clean(dir) + for i, d := range dirs { + if d == "" { + continue + } + d = filepath.Clean(d) + if d == want || (fold && strings.EqualFold(d, want)) { + return i + } + if r, err := filepath.EvalSymlinks(d); err == nil && r == want { + return i + } + } + return -1 +} + +// warning returns State.Warning for an enabled link. +func warning(linkDir string, onPath bool, user string, userFirst bool) string { + switch { + case !onPath: + // i18n: %s is a folder. A login shell is a terminal session that reads the user's profile. + return i18n.T("%s isn't on your PATH yet: add it, or open a new login shell.", linkDir) + case user != "" && userFirst: + // i18n: %s is the path of another rclone program. + return i18n.T("Another rclone, at %s, comes first on your PATH: `rclone` in a terminal runs that one.", user) + case user != "": + // i18n: %s is the path of another rclone program. + return i18n.T("`rclone` in a terminal now runs Rclone UI's rclone, not the one at %s.", user) + } + return "" +} diff --git a/app/pathlink/pathlink.go b/app/pathlink/pathlink.go new file mode 100644 index 00000000..50cd618a --- /dev/null +++ b/app/pathlink/pathlink.go @@ -0,0 +1,100 @@ +// Package pathlink implements "Add rclone to PATH". It adds a command named rclone that runs rcui, +// which acts as rclone when called by that name and uses the same config files as the app. It is +// opt-in, it never replaces a user's own rclone, and it updates with the app because it points to +// the app. The link lives in these places: +// +// - macOS: /usr/local/bin/rclone → /bin/rclone → the app's rcui. /usr/local/bin usually +// needs an administrator password, but the pointer in doesn't, so the app can follow a +// moved bundle without asking again. +// - Linux: ~/.local/bin/rclone → /bin/rclone → /usr/bin/rcui or $APPIMAGE. +// - Windows: the bin folder next to rcui.exe is added to the user's PATH. It holds the +// rclone.exe that the installer and the portable zip bring, a console program that runs +// rcui.exe (see build/windows/rclone-shim). +// +// The package doesn't import Wails. The UI role's PathService binds it for pages. +package pathlink + +import ( + "errors" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +type State struct { + // Supported is false where no link can work (Flatpak, or a Windows copy without + // bin\rclone.exe). Reason explains why. Reason and Warning are in the app's language. + Supported bool `json:"supported"` + Reason string `json:"reason,omitempty"` + // Enabled means that `rclone` in a new terminal runs this app's rclone, unless Warning says + // that another rclone comes first. + Enabled bool `json:"enabled"` + // Link is where the command is placed (/usr/local/bin/rclone, ~/.local/bin/rclone, or the + // folder added to PATH on Windows). Target is the program it runs. + Link string `json:"link,omitempty"` + Target string `json:"target,omitempty"` + // UserRclone is another rclone found on PATH. It is the user's own, and it is never replaced. + UserRclone string `json:"userRclone,omitempty"` + // Warning explains why an enabled link may not work as expected. + Warning string `json:"warning,omitempty"` + // NeedsAdmin means that Enable and Disable ask for an administrator password (macOS). + NeedsAdmin bool `json:"needsAdmin"` + // Command is what a terminal runs to use this app's rclone, as in ` tunnel`. It is + // "rclone" when the link works, or else the app's own program, quoted for the OS's usual + // shell. + Command string `json:"command,omitempty"` +} + +// Errors that Enable returns, which errors.Is finds. The error itself says more, in words that +// the page shows in the app's language (see refusal). +var ( + // ErrUnsupported means no link can work here. State.Reason explains why. + ErrUnsupported = errors.New("adding rclone to PATH isn't possible here") + // ErrForeign means that a file that doesn't belong to this app already has the link's name. + ErrForeign = errors.New("an rclone that isn't Rclone UI's is already there") +) + +// refusal is an error that the page shows (shown, made with core/errs, so that the page gets it +// in the app's language) and that errors.Is matches with kind (ErrUnsupported, ErrForeign). +type refusal struct{ shown, kind error } + +func (r refusal) Error() string { return r.shown.Error() } +func (r refusal) Unwrap() []error { return []error{r.shown, r.kind} } + +func unsupported(reason i18n.Text) error { + return refusal{errs.Said(errs.CodeUnsupported, reason), ErrUnsupported} +} + +func Status() (State, error) { + l, err := New() + if err != nil { + return State{}, err + } + return l.Status(), nil +} + +func Enable() (State, error) { + l, err := New() + if err != nil { + return State{}, err + } + return l.Enable() +} + +func Disable() (State, error) { + l, err := New() + if err != nil { + return State{}, err + } + return l.Disable() +} + +// Refresh keeps an enabled link pointing to this copy of the app. The UI calls it once at start, +// so the link follows a moved app. +func Refresh() error { + l, err := New() + if err != nil { + return err + } + return l.Refresh() +} diff --git a/app/pathlink/pathvalue.go b/app/pathlink/pathvalue.go new file mode 100644 index 00000000..a0ac8bd5 --- /dev/null +++ b/app/pathlink/pathvalue.go @@ -0,0 +1,51 @@ +package pathlink + +import "strings" + +// These functions work on a Windows PATH value as stored in HKCU\Environment. Folders are +// separated by ';' and compared ignoring case and a trailing backslash. They are plain string +// functions, so their tests run on every OS. + +func pathHas(value, dir string) bool { + for seg := range strings.SplitSeq(value, ";") { + if samePathSegment(seg, dir) { + return true + } + } + return false +} + +// pathWith returns the value with dir appended, unless it already lists dir. +func pathWith(value, dir string) string { + if pathHas(value, dir) { + return value + } + segs := nonEmpty(strings.Split(value, ";")) + return strings.Join(append(segs, dir), ";") +} + +// pathWithout returns the value with every occurrence of dir removed. +func pathWithout(value, dir string) string { + var out []string + for _, seg := range nonEmpty(strings.Split(value, ";")) { + if !samePathSegment(seg, dir) { + out = append(out, seg) + } + } + return strings.Join(out, ";") +} + +func samePathSegment(seg, dir string) bool { + norm := func(s string) string { return strings.ToLower(strings.TrimRight(strings.TrimSpace(s), `\`)) } + return dir != "" && norm(seg) == norm(dir) +} + +func nonEmpty(segs []string) []string { + out := segs[:0:0] + for _, s := range segs { + if strings.TrimSpace(s) != "" { + out = append(out, s) + } + } + return out +} diff --git a/app/pathlink/pathvalue_test.go b/app/pathlink/pathvalue_test.go new file mode 100644 index 00000000..c59e9932 --- /dev/null +++ b/app/pathlink/pathvalue_test.go @@ -0,0 +1,24 @@ +package pathlink + +import "testing" + +func TestPathValue(t *testing.T) { + const bin = `C:\Users\me\AppData\Local\Rclone UI\bin` + value := `%USERPROFILE%\bin;C:\Tools\;` + if pathHas(value, bin) { + t.Fatal("listed before it was added") + } + with := pathWith(value, bin) + if with != `%USERPROFILE%\bin;C:\Tools\;`+bin || !pathHas(with, `c:\users\me\appdata\local\rclone ui\bin\`) { + t.Fatalf("with: %q", with) + } + if pathWith(with, bin) != with { + t.Fatal("added twice") + } + if got := pathWithout(with+";"+bin, bin); got != `%USERPROFILE%\bin;C:\Tools\` { + t.Fatalf("without: %q", got) + } + if got := pathWith("", bin); got != bin { + t.Fatalf("to an empty PATH: %q", got) + } +} diff --git a/app/platform/hostenv.go b/app/platform/hostenv.go new file mode 100644 index 00000000..2e711040 --- /dev/null +++ b/app/platform/hostenv.go @@ -0,0 +1,147 @@ +package platform + +import ( + "context" + "os" + "os/exec" + "path" + "path/filepath" + "strings" +) + +// An AppImage's AppRun and linuxdeploy's GTK hook point the environment into the AppImage's mount +// (its AppDir). With that environment, the host's programs would load the AppImage's libraries, +// schemas and modules instead of their own, and fail. This affects xdg-open and the browser it +// starts, gsettings, the login shell and a Python password command. So these programs get the +// host's environment (see HostEnv). The UI keeps its own environment, because its GTK reads module +// paths lazily. + +// listVars are the colon-separated variables that AppRun and the GTK hook point into the AppDir. +// Most get the AppDir's folders in front of the host's value. The GTK hook replaces the values of +// GSETTINGS_SCHEMA_DIR, GI_TYPELIB_PATH and GTK_PATH with a single folder in the AppDir. +var listVars = map[string]bool{ + "PATH": true, "LD_LIBRARY_PATH": true, "XDG_DATA_DIRS": true, "PYTHONPATH": true, + "PERLLIB": true, "QT_PLUGIN_PATH": true, "GSETTINGS_SCHEMA_DIR": true, "GI_TYPELIB_PATH": true, + "GTK_PATH": true, +} + +// setVars are the variables that AppRun and the GTK hook set outright. They are kept only when +// they don't point into the AppDir. The GTK hook sets the GTK and GDK ones for GTK 4. Wails' +// AppRun sets WEBKIT_INJECTED_BUNDLE_PATH, which would make a host program that uses WebKitGTK +// load the AppImage's injected bundle. +var setVars = map[string]bool{ + "PYTHONHOME": true, "GTK_DATA_PREFIX": true, "GTK_EXE_PREFIX": true, + "GDK_PIXBUF_MODULE_FILE": true, "WEBKIT_INJECTED_BUNDLE_PATH": true, +} + +// dropVars are always dropped, whatever their value. They are the AppImage's own variables +// (APPDIR, APPIMAGE, ARGV0, OWD), and the ones that hold no path: GTK_THEME and GDK_BACKEND, which +// the GTK hook forces, and PYTHONDONTWRITEBYTECODE, which AppImageKit's AppRun sets. For those, +// the AppImage's value can't be told apart from the user's, so a host program uses its default. +var dropVars = map[string]bool{ + "APPDIR": true, "APPIMAGE": true, "ARGV0": true, "OWD": true, + "GTK_THEME": true, "GDK_BACKEND": true, "PYTHONDONTWRITEBYTECODE": true, +} + +// hostEnv returns env as a host program should get it, given the AppDir. It returns env unchanged +// when appdir is "". +func hostEnv(env []string, appdir string) []string { + if appdir == "" { + return env + } + appdir = path.Clean(appdir) + inside := func(p string) bool { + p = path.Clean(p) + return p == appdir || strings.HasPrefix(p, appdir+"/") + } + out := make([]string, 0, len(env)) + for _, kv := range env { + k, v, ok := strings.Cut(kv, "=") + switch { + case !ok: + out = append(out, kv) + case listVars[k]: + var keep []string + for p := range strings.SplitSeq(v, ":") { + if p != "" && !inside(p) { + keep = append(keep, p) + } + } + if len(keep) > 0 { + out = append(out, k+"="+strings.Join(keep, ":")) + } + case dropVars[k]: + case setVars[k] && inside(v): + default: + out = append(out, kv) + } + } + return out +} + +// appDir returns appdir when this executable runs from that AppImage's mount, and "" otherwise. +// The AppImage's runtime sets both variables. A program that the AppImage started inherits them, +// but isn't inside the mount. +func appDir(appimage, appdir, exe string) string { + if appimage == "" || appdir == "" || !strings.HasPrefix(exe, path.Clean(appdir)+"/") { + return "" + } + return appdir +} + +// AppDir returns the AppImage mount that this executable runs from, or "" when it isn't running +// from an AppImage. +func AppDir() string { + exe, err := Executable() + if err != nil { + return "" + } + return appDir(os.Getenv("APPIMAGE"), os.Getenv("APPDIR"), exe) +} + +// HostEnv returns the environment for a host program. It is this process's environment, without +// the AppImage's entries when the process runs from an AppImage. +func HostEnv() []string { return hostEnv(os.Environ(), AppDir()) } + +// HostCommand prepares a host program to run. Under an AppImage, the program is looked up only on +// the host's PATH and runs in the host's environment (see HostEnv). Otherwise it is the same as +// exec.CommandContext. +func HostCommand(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, name, args...) + dir := AppDir() + if dir == "" { + return cmd + } + cmd.Env = hostEnv(os.Environ(), dir) + if !strings.Contains(name, "/") { + if found, ok := lookPathIn(name, envValue(cmd.Env, "PATH")); ok { + cmd.Path, cmd.Err = found, nil + } else { + cmd.Path, cmd.Err = name, &exec.Error{Name: name, Err: exec.ErrNotFound} + } + } + return cmd +} + +func envValue(env []string, key string) string { + for _, kv := range env { + if v, ok := strings.CutPrefix(kv, key+"="); ok { + return v + } + } + return "" +} + +// lookPathIn finds an executable file named name in the folders of list, which is a PATH value. +func lookPathIn(name, list string) (string, bool) { + for _, dir := range filepath.SplitList(list) { + if dir == "" || !filepath.IsAbs(dir) { + continue + } + p := filepath.Join(dir, name) + if st, err := os.Stat(p); err == nil && st.Mode().IsRegular() && st.Mode().Perm()&0o111 != 0 { + return p, true + } + } + return "", false +} diff --git a/app/platform/hostenv_test.go b/app/platform/hostenv_test.go new file mode 100644 index 00000000..52b6d618 --- /dev/null +++ b/app/platform/hostenv_test.go @@ -0,0 +1,103 @@ +package platform + +import ( + "context" + "os" + "path/filepath" + "runtime" + "slices" + "testing" +) + +const testAppDir = "/tmp/.mount_RcloneX" + +func appImageEnv() []string { + app := testAppDir + return []string{ + "HOME=/home/u", + "PATH=" + app + "/usr/bin:" + app + "/usr/bin/:/usr/local/bin:/usr/bin", + "LD_LIBRARY_PATH=" + app + "/usr/lib/:" + app + "/usr/lib/x86_64-linux-gnu/:", + "XDG_DATA_DIRS=" + app + "/usr/share:/usr/share:/usr/local/share", + "PYTHONHOME=" + app + "/usr/", + "GDK_PIXBUF_MODULE_FILE=" + app + "/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders.cache", + "GTK_THEME=Adwaita:dark", + "GDK_BACKEND=x11", + "GSETTINGS_SCHEMA_DIR=" + app + "/usr/share/glib-2.0/schemas", + "GIO_MODULE_DIR=/usr/lib/gio/modules", + "APPDIR=" + app, + "APPIMAGE=/home/u/Apps/Rclone-UI-4.0.0-linux-x86_64.AppImage", + "LANG=en_US.UTF-8", + } +} + +func TestHostEnv(t *testing.T) { + env := appImageEnv() + got := hostEnv(slices.Clone(env), testAppDir) + want := []string{ + "HOME=/home/u", + "PATH=/usr/local/bin:/usr/bin", + "XDG_DATA_DIRS=/usr/share:/usr/local/share", + "GIO_MODULE_DIR=/usr/lib/gio/modules", + "LANG=en_US.UTF-8", + } + if !slices.Equal(got, want) { + t.Fatalf("got %q\nwant %q", got, want) + } + if !slices.Equal(hostEnv(slices.Clone(env), ""), env) { + t.Fatal("outside an AppImage the environment is unchanged") + } + // A folder whose name only starts like the AppDir's isn't inside it. + if got := hostEnv([]string{"PATH=" + testAppDir + "2/bin"}, testAppDir); !slices.Equal(got, []string{"PATH=" + testAppDir + "2/bin"}) { + t.Fatalf("a sibling folder: %q", got) + } +} + +func TestAppDir(t *testing.T) { + img := "/home/u/Apps/Rclone-UI-4.0.0-linux-x86_64.AppImage" + for _, c := range []struct { + name, appimage, appdir, exe, want string + }{ + {"inside", img, testAppDir, testAppDir + "/usr/bin/rcui", testAppDir}, + {"outside", img, testAppDir, "/usr/bin/xdg-open", ""}, + {"a sibling", img, testAppDir, testAppDir + "2/usr/bin/rcui", ""}, + {"unset", "", "", "/usr/bin/rcui", ""}, + {"no APPIMAGE", "", testAppDir, testAppDir + "/usr/bin/rcui", ""}, + } { + if got := appDir(c.appimage, c.appdir, c.exe); got != c.want { + t.Errorf("%s: %q, want %q", c.name, got, c.want) + } + } +} + +func TestHostCommandOffAppImage(t *testing.T) { + t.Setenv("APPIMAGE", "") + cmd := HostCommand(context.Background(), "sh", "-c", "true") + if cmd.Env != nil { + t.Fatalf("env %q", cmd.Env) + } +} + +func TestLookPathIn(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("AppImages are Linux's; Windows has no execute bits") + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "tool"), []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "plain"), nil, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil { + t.Fatal(err) + } + path := "relative:" + filepath.Join(dir, "none") + string(filepath.ListSeparator) + dir + if got, ok := lookPathIn("tool", path); !ok || got != filepath.Join(dir, "tool") { + t.Errorf("tool: %q %v", got, ok) + } + for _, name := range []string{"plain", "sub", "missing"} { + if got, ok := lookPathIn(name, path); ok { + t.Errorf("%s: %q", name, got) + } + } +} diff --git a/app/platform/path_unix.go b/app/platform/path_unix.go new file mode 100644 index 00000000..b331dd6b --- /dev/null +++ b/app/platform/path_unix.go @@ -0,0 +1,64 @@ +//go:build !windows + +package platform + +import ( + "context" + "errors" + "os" + "os/exec" + "strings" + "syscall" + "time" +) + +// pathMarker surrounds the PATH in the shell's output, so that anything a profile prints to +// stdout isn't mixed into the value. +const pathMarker = "__RCUI_PATH__" + +// FixPath gives a process launched from the GUI the PATH of the user's login shell. Finder and +// desktop launchers start apps with a minimal PATH, but rclone's password commands and the core's +// children need the user's PATH. When the app is started from a terminal, PATH is already the +// shell's, and this changes nothing that matters. FixPath runs before the app is built, because +// building it reads the environment. +func FixPath() { + shell := os.Getenv("SHELL") + if shell == "" { + shell = "/bin/sh" + } + if path, ok := readLoginPath(shell); ok { + _ = os.Setenv("PATH", path) + } +} + +// readLoginPath returns the PATH that shell prints when run as a login shell. A profile may start +// a background job without redirecting its output, such as an agent or `(sleep 60) &`. That job +// keeps the output open after the shell has exited. So the wait for the output is cut short, and +// what the shell printed is used. +func readLoginPath(shell string) (string, bool) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + // Use the host's environment, because under an AppImage the shell would load the AppImage's + // libraries. + cmd := HostCommand(ctx, shell, "-ilc", `printf '`+pathMarker+`%s`+pathMarker+`' "$PATH"`) + // Run the shell in its own session. Otherwise, when the app is started from a terminal, the + // interactive shell would take over the terminal's foreground for its job control, and keep + // it. + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + cmd.WaitDelay = 500 * time.Millisecond + out, err := cmd.Output() + if err != nil && !errors.Is(err, exec.ErrWaitDelay) { + return "", false + } + s := string(out) + start := strings.Index(s, pathMarker) + if start < 0 { + return "", false + } + s = s[start+len(pathMarker):] + end := strings.Index(s, pathMarker) + if end <= 0 { + return "", false + } + return s[:end], true +} diff --git a/app/platform/path_unix_test.go b/app/platform/path_unix_test.go new file mode 100644 index 00000000..a531abc3 --- /dev/null +++ b/app/platform/path_unix_test.go @@ -0,0 +1,59 @@ +//go:build !windows + +package platform + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +// TestReadLoginPathOwnSession uses a fake shell that prints its process group instead of PATH. +func TestReadLoginPathOwnSession(t *testing.T) { + shell := filepath.Join(t.TempDir(), "fakeshell") + script := "#!/bin/sh\nprintf '__RCUI_PATH__%s__RCUI_PATH__' \"$(ps -o pgid= -p $$)\"\n" + if err := os.WriteFile(shell, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + out, ok := readLoginPath(shell) + if !ok { + t.Skip("ps printed nothing") + } + pgid, err := strconv.Atoi(strings.TrimSpace(out)) + if err != nil { + t.Skipf("ps printed %q", out) + } + if pgid == syscall.Getpgrp() { + t.Fatalf("the shell is in the app's process group %d", pgid) + } +} + +func TestReadLoginPathBackgroundJob(t *testing.T) { + shell := filepath.Join(t.TempDir(), "fakeshell") + script := "#!/bin/sh\n(sleep 3) &\nprintf '__RCUI_PATH__/opt/fake/bin__RCUI_PATH__'\n" + if err := os.WriteFile(shell, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + start := time.Now() + path, ok := readLoginPath(shell) + if took := time.Since(start); took > 2*time.Second { + t.Errorf("took %v", took) + } + if !ok || path != "/opt/fake/bin" { + t.Fatalf("%q %v", path, ok) + } +} + +func TestReadLoginPathNoMarkers(t *testing.T) { + shell := filepath.Join(t.TempDir(), "fakeshell") + if err := os.WriteFile(shell, []byte("#!/bin/sh\necho welcome\n"), 0o700); err != nil { + t.Fatal(err) + } + if path, ok := readLoginPath(shell); ok { + t.Fatalf("%q", path) + } +} diff --git a/app/platform/path_windows.go b/app/platform/path_windows.go new file mode 100644 index 00000000..4851684a --- /dev/null +++ b/app/platform/path_windows.go @@ -0,0 +1,4 @@ +package platform + +// FixPath does nothing, because Windows already starts GUI apps with the user's full PATH. +func FixPath() {} diff --git a/app/platform/platform.go b/app/platform/platform.go new file mode 100644 index 00000000..51830aef --- /dev/null +++ b/app/platform/platform.go @@ -0,0 +1,211 @@ +// Package platform answers the UI role's questions about the machine: whether it runs in a +// Flatpak and with which permissions, whether the host is Linux Mint, and what the login shell's +// PATH is. +package platform + +import ( + "bufio" + "os" + "path/filepath" + "runtime" + "strings" +) + +// flatpakInfo is the file in which Flatpak describes the sandbox to the app inside it. +const flatpakInfo = "/.flatpak-info" + +// FlatpakAppID is the app's ID on Flathub, which the permission command uses. +const FlatpakAppID = "org.rclone.ui" + +// GnomeShellExtensions is GNOME Shell's extensions service, which the app uses to install and +// enable the launcher's GNOME extension (see app/launcher/view/linux/gnome/ensure_linux.go). +const GnomeShellExtensions = "org.gnome.Shell.Extensions" + +// autostartFilesystem is the host's autostart folder, written as a Flatpak filesystem permission. +// "Start on boot" writes its entry there (see app/autostart). +const autostartFilesystem = "xdg-config/autostart" + +// FlatpakOverride returns the command that grants the permissions the gate asks for (see +// FlatpakMissing). They are access to the host's files and autostart folder and, on GNOME, to +// GNOME Shell's extensions service, because an extension places the launcher's window there. The +// user grants them, rather than the manifest. +func FlatpakOverride() string { return flatpakOverride(IsGNOME()) } + +func flatpakOverride(gnome bool) string { + cmd := "flatpak override --user --filesystem=host --filesystem=" + autostartFilesystem + ":create " + if gnome { + cmd += "--talk-name=" + GnomeShellExtensions + " " + } + return cmd + FlatpakAppID +} + +// IsGNOME reports whether the desktop runs GNOME Shell. That is the case when XDG_CURRENT_DESKTOP +// lists GNOME, as in "GNOME" or "ubuntu:GNOME", which a Flatpak also sees. Budgie and GNOME +// Flashback list GNOME after their own name, but don't run GNOME Shell. +func IsGNOME() bool { return isGNOME(os.Getenv("XDG_CURRENT_DESKTOP")) } + +func isGNOME(current string) bool { + gnome := false + for d := range strings.SplitSeq(current, ":") { + switch { + case strings.EqualFold(d, "Budgie"), strings.EqualFold(d, "GNOME-Flashback"): + return false + case strings.EqualFold(d, "GNOME"): + gnome = true + } + } + return gnome +} + +func IsFlatpak() bool { + if runtime.GOOS != "linux" { + return false + } + if _, err := os.Stat(flatpakInfo); err == nil { + return true + } + return os.Getenv("FLATPAK_ID") != "" +} + +// Missing lists the permissions granted by FlatpakOverride that the Flatpak doesn't have. +type Missing struct { + // Disk is write access to the host's filesystem. Without it, rclone can't reach any of the + // user's files. + Disk bool + // Autostart is write access to the host's autostart folder. Without it, "Start on boot" can't + // work, because the session never reads the sandbox's own config folder. + Autostart bool + // GNOME is access to GNOME Shell's extensions service, on GNOME. Without it, the launcher's + // extension can't be installed, and there is no other way to place the launcher's window. + GNOME bool +} + +func (m Missing) Any() bool { return m.Disk || m.Autostart || m.GNOME } + +// FlatpakMissing is the startup gate. It returns the permissions granted by FlatpakOverride that +// the Flatpak doesn't have, and nothing outside a Flatpak. The app doesn't start while anything +// is missing. The app doesn't create OS schedules, so it doesn't ask for host-spawn access. +func FlatpakMissing() Missing { + if !IsFlatpak() { + return Missing{} + } + b, err := os.ReadFile(flatpakInfo) + if err != nil { + return Missing{Disk: true, Autostart: true, GNOME: IsGNOME()} + } + return missing(string(b), IsGNOME()) +} + +func missing(info string, gnome bool) Missing { + return Missing{ + Disk: !grantsFilesystem(info, "host"), + Autostart: !grantsAutostart(info), + GNOME: gnome && !grantsTalk(info, GnomeShellExtensions), + } +} + +// grantsAutostart reports whether the Flatpak may write to the host's autostart folder. That +// permission can be granted directly, or as part of access to the host's files, the home folder +// or the config folder. +func grantsAutostart(info string) bool { + for _, name := range []string{"host", "home", "xdg-config", autostartFilesystem, "~/.config", "~/.config/autostart"} { + if grantsFilesystem(info, name) { + return true + } + } + return false +} + +// grantsFilesystem checks one permission in the [Context] filesystems= list of a .flatpak-info. +// "name", "name:rw" or "name:create" grant it, while "name:ro" or a "!name" override deny it. +func grantsFilesystem(info, name string) bool { + for _, kv := range section(info, "Context") { + key, value, ok := strings.Cut(kv, "=") + if !ok || strings.TrimSpace(key) != "filesystems" { + continue + } + for item := range strings.SplitSeq(value, ";") { + item = strings.TrimSpace(item) + denied := strings.HasPrefix(item, "!") + path, mode, _ := strings.Cut(strings.TrimPrefix(item, "!"), ":") + if strings.TrimSuffix(path, "/") != name { + continue + } + return !denied && mode != "ro" + } + } + return false +} + +// grantsTalk is true when [Session Bus Policy] lets the app talk to (or own) name. +func grantsTalk(info, name string) bool { + for _, kv := range section(info, "Session Bus Policy") { + key, value, ok := strings.Cut(kv, "=") + if ok && strings.TrimSpace(key) == name { + v := strings.TrimSpace(value) + return v == "talk" || v == "own" + } + } + return false +} + +// section returns the trimmed, non-comment lines of one [name] section of an ini file. +func section(ini, name string) []string { + var lines []string + in := false + sc := bufio.NewScanner(strings.NewReader(ini)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + in = line == "["+name+"]" + continue + } + if in { + lines = append(lines, line) + } + } + return lines +} + +// IsLinuxMint reports whether the host runs Linux Mint, whose panel needs the padded tray icons. +// In a Flatpak, the host's os-release is under /run/host. +func IsLinuxMint() bool { + if runtime.GOOS != "linux" { + return false + } + paths := []string{"/etc/os-release", "/usr/lib/os-release"} + if IsFlatpak() { + paths = append([]string{"/run/host/os-release"}, paths...) + } + for _, p := range paths { + if b, err := os.ReadFile(p); err == nil { + return osReleaseIsMint(string(b)) + } + } + return false +} + +func osReleaseIsMint(osRelease string) bool { + for line := range strings.SplitSeq(osRelease, "\n") { + line = strings.TrimSpace(line) + if line == "ID=linuxmint" || line == `ID="linuxmint"` { + return true + } + } + return false +} + +// Executable returns the absolute path of this process's executable, with symlinks resolved. +func Executable() (string, error) { + exe, err := os.Executable() + if err != nil { + return "", err + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + return filepath.Abs(exe) +} diff --git a/app/platform/platform_test.go b/app/platform/platform_test.go new file mode 100644 index 00000000..b9723033 --- /dev/null +++ b/app/platform/platform_test.go @@ -0,0 +1,127 @@ +package platform + +import "testing" + +func TestGrantsHostSpawn(t *testing.T) { + cases := []struct { + info string + want bool + }{ + {"[Application]\nname=org.rclone.ui\n\n[Session Bus Policy]\norg.freedesktop.Flatpak=talk\norg.freedesktop.Notifications=talk\n", true}, + {"[Session Bus Policy]\norg.freedesktop.Flatpak=own\n", true}, + {"[Session Bus Policy]\norg.freedesktop.Notifications=talk\n", false}, + {"[System Bus Policy]\norg.freedesktop.Flatpak=talk\n", false}, + {"[Session Bus Policy]\norg.freedesktop.Flatpak=none\n", false}, + } + for _, c := range cases { + if got := grantsTalk(c.info, "org.freedesktop.Flatpak"); got != c.want { + t.Errorf("grantsTalk(%q) = %v, want %v", c.info, got, c.want) + } + } +} + +func TestGrantsHostFilesystem(t *testing.T) { + cases := []struct { + info string + want bool + }{ + {"[Context]\nfilesystems=host;\n", true}, + {"[Context]\nfilesystems=xdg-download;host:rw\n", true}, + {"[Context]\nfilesystems=host:create\n", true}, + {"[Context]\nfilesystems=host:ro;\n", false}, + {"[Context]\nfilesystems=!host;host\n", false}, + {"[Context]\nfilesystems=xdg-download\n", false}, + {"[Instance]\nfilesystems=host\n", false}, + {"# comment\n[Context]\nshared=network;\nfilesystems=home;host\n", true}, + } + for _, c := range cases { + if got := grantsFilesystem(c.info, "host"); got != c.want { + t.Errorf("grantsFilesystem(%q, host) = %v, want %v", c.info, got, c.want) + } + } +} + +func TestGrantsAutostart(t *testing.T) { + for info, want := range map[string]bool{ + "[Context]\nfilesystems=xdg-config/autostart:create;\n": true, + "[Context]\nfilesystems=xdg-config/autostart;\n": true, + "[Context]\nfilesystems=xdg-config/autostart/;\n": true, + "[Context]\nfilesystems=host;\n": true, + "[Context]\nfilesystems=home:rw;\n": true, + "[Context]\nfilesystems=xdg-config;\n": true, + "[Context]\nfilesystems=~/.config/autostart:create;\n": true, + "[Context]\nfilesystems=home:ro;xdg-config/autostart\n": true, + "[Context]\nfilesystems=xdg-config/autostart:ro;\n": false, + "[Context]\nfilesystems=!host;!home;\n": false, + "[Context]\nfilesystems=host:ro;xdg-download\n": false, + "[Context]\nfilesystems=xdg-config/git;\n": false, + "": false, + } { + if got := grantsAutostart(info); got != want { + t.Errorf("grantsAutostart(%q) = %v, want %v", info, got, want) + } + } +} + +func TestOsReleaseIsMint(t *testing.T) { + if !osReleaseIsMint("NAME=\"Linux Mint\"\nID=linuxmint\nID_LIKE=ubuntu\n") { + t.Error("plain ID not recognised") + } + if !osReleaseIsMint("ID=\"linuxmint\"\n") { + t.Error("quoted ID not recognised") + } + if osReleaseIsMint("ID=ubuntu\nID_LIKE=debian\n") { + t.Error("ubuntu taken for Mint") + } +} + +func TestFlatpakOverride(t *testing.T) { + if got := flatpakOverride(false); got != "flatpak override --user --filesystem=host --filesystem=xdg-config/autostart:create org.rclone.ui" { + t.Errorf("elsewhere: %q", got) + } + if got := flatpakOverride(true); got != "flatpak override --user --filesystem=host --filesystem=xdg-config/autostart:create --talk-name=org.gnome.Shell.Extensions org.rclone.ui" { + t.Errorf("GNOME: %q", got) + } + if !grantsTalk("[Session Bus Policy]\norg.gnome.Shell.Extensions=talk\n", GnomeShellExtensions) { + t.Error("an override's talk-name") + } + // What the override writes to .flatpak-info satisfies the gate. + info := "[Context]\nfilesystems=host;xdg-config/autostart:create;\n[Session Bus Policy]\norg.gnome.Shell.Extensions=talk\n" + if m := missing(info, true); m.Any() { + t.Errorf("after the override: %+v", m) + } +} + +func TestIsGNOME(t *testing.T) { + for in, want := range map[string]bool{ + "GNOME": true, "ubuntu:GNOME": true, "GNOME-Classic:GNOME": true, "KDE": false, "": false, + "GNOME-Flashback:GNOME": false, "Budgie:GNOME": false, "Unity": false, + } { + if got := isGNOME(in); got != want { + t.Errorf("%q: got %v", in, got) + } + } +} + +func TestMissing(t *testing.T) { + disk := "[Context]\nfilesystems=host;\n" + shell := "[Session Bus Policy]\norg.gnome.Shell.Extensions=talk\n" + for _, c := range []struct { + info string + gnome bool + want Missing + }{ + {"", false, Missing{Disk: true, Autostart: true}}, + {disk, false, Missing{}}, + {disk, true, Missing{GNOME: true}}, + {disk + shell, true, Missing{}}, + {shell, true, Missing{Disk: true, Autostart: true}}, + {"[Context]\nfilesystems=host:ro;\n", false, Missing{Disk: true, Autostart: true}}, + {"[Context]\nfilesystems=home;\n", false, Missing{Disk: true}}, + {"[Context]\nfilesystems=host:ro;xdg-config/autostart:create;\n", false, Missing{Disk: true}}, + } { + if got := missing(c.info, c.gnome); got != c.want { + t.Errorf("%q gnome=%v: missing %+v, want %+v", c.info, c.gnome, got, c.want) + } + } +} diff --git a/app/platform/process_test.go b/app/platform/process_test.go new file mode 100644 index 00000000..dd907fc4 --- /dev/null +++ b/app/platform/process_test.go @@ -0,0 +1,81 @@ +package platform + +import ( + "bufio" + "io" + "os" + "os/exec" + "testing" + "time" +) + +// helperEnv marks the copy of this test program that TestWaitForExit starts as its child. +const helperEnv = "RCUI_PLATFORM_TEST_CHILD" + +// TestMain lets the test program run as TestWaitForExit's child: it says that it runs, then +// lives until its input closes. +func TestMain(m *testing.M) { + if os.Getenv(helperEnv) != "" { + _, _ = os.Stdout.WriteString("ready\n") + _, _ = io.Copy(io.Discard, os.Stdin) + os.Exit(0) + } + os.Exit(m.Run()) +} + +// WaitForExit returns when the process exits, not before, and without waiting for its limit. +// +// The child is this test program, and it exits when the test closes its input. So the test +// decides when the child ends, and nothing depends on how long a program takes to start or to +// sleep: on a busy machine, a shell asked to sleep for 300 ms can take many seconds. +func TestWaitForExit(t *testing.T) { + cmd := exec.Command(os.Args[0]) + cmd.Env = append(os.Environ(), helperEnv+"=1") + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = stdin.Close(); _ = cmd.Process.Kill() }) + if line, err := bufio.NewReader(stdout).ReadString('\n'); err != nil || line != "ready\n" { + t.Fatalf("the child said %q, %v", line, err) + } + + // limit is far longer than anything here takes, so a return before it means the exit was + // seen, and a return after it means it wasn't. + const limit = 2 * time.Minute + returned := make(chan time.Duration, 1) + began := time.Now() + go func() { + WaitForExit(cmd.Process.Pid, limit) + returned <- time.Since(began) + }() + select { + case took := <-returned: + t.Fatalf("returned after %v while the process still runs", took) + case <-time.After(300 * time.Millisecond): + } + + if err := stdin.Close(); err != nil { + t.Fatal(err) + } + if err := cmd.Wait(); err != nil { + t.Fatalf("the child ended with %v", err) + } + if took := <-returned; took >= limit { + t.Fatalf("waited %v, its whole limit, for a process that had exited", took) + } + + // This process doesn't exit, so the wait ends at its limit. + began = time.Now() + WaitForExit(os.Getpid(), 200*time.Millisecond) + if took := time.Since(began); took < 150*time.Millisecond { + t.Fatalf("returned after %v for a running process", took) + } +} diff --git a/app/platform/process_unix.go b/app/platform/process_unix.go new file mode 100644 index 00000000..eacee264 --- /dev/null +++ b/app/platform/process_unix.go @@ -0,0 +1,23 @@ +//go:build !windows + +package platform + +import ( + "errors" + "syscall" + "time" +) + +// DetachedProcess starts a process in its own session, so that it isn't affected when this +// process ends. +func DetachedProcess() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setsid: true} } + +func WaitForExit(pid int, limit time.Duration) { + deadline := time.Now().Add(limit) + for time.Now().Before(deadline) { + if err := syscall.Kill(pid, 0); errors.Is(err, syscall.ESRCH) { + return + } + time.Sleep(50 * time.Millisecond) + } +} diff --git a/app/platform/process_windows.go b/app/platform/process_windows.go new file mode 100644 index 00000000..d9754603 --- /dev/null +++ b/app/platform/process_windows.go @@ -0,0 +1,22 @@ +package platform + +import ( + "syscall" + "time" + + "golang.org/x/sys/windows" +) + +// DetachedProcess starts a process in its own process group, without a console. +func DetachedProcess() *syscall.SysProcAttr { + return &syscall.SysProcAttr{CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.CREATE_NO_WINDOW} +} + +func WaitForExit(pid int, limit time.Duration) { + h, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid)) + if err != nil { + return // the process has already exited, or we may not wait for it + } + defer func() { _ = windows.CloseHandle(h) }() + _, _ = windows.WaitForSingleObject(h, uint32(limit/time.Millisecond)) +} diff --git a/app/platform/textscale_other.go b/app/platform/textscale_other.go new file mode 100644 index 00000000..0b034898 --- /dev/null +++ b/app/platform/textscale_other.go @@ -0,0 +1,6 @@ +//go:build !windows + +package platform + +// TextScale is 1 where the app's windows aren't enlarged by a text size setting. +func TextScale() float64 { return 1 } diff --git a/app/platform/textscale_windows.go b/app/platform/textscale_windows.go new file mode 100644 index 00000000..14f10f01 --- /dev/null +++ b/app/platform/textscale_windows.go @@ -0,0 +1,19 @@ +package platform + +import "golang.org/x/sys/windows/registry" + +// TextScale returns Windows' text size setting (Settings > Accessibility > Text size) as a factor +// from 1 to 2.25. WebView2 enlarges a whole page by it, on top of the display's scale, so a window +// has to grow by it too or its page is cut off. +func TextScale() float64 { + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Accessibility`, registry.QUERY_VALUE) + if err != nil { + return 1 + } + defer k.Close() + v, _, err := k.GetIntegerValue("TextScaleFactor") + if err != nil || v < 100 || v > 225 { + return 1 + } + return float64(v) / 100 +} diff --git a/app/quit.go b/app/quit.go new file mode 100644 index 00000000..79125822 --- /dev/null +++ b/app/quit.go @@ -0,0 +1,272 @@ +package app + +import ( + "context" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/i18n" +) + +// endingSession reports whether the quit that Wails is asking about comes from the OS ending the +// session. Tests replace it. +var endingSession = osEndingSession + +// shouldQuit lets the app veto a quit in Wails. ⌘Q, the menu's Quit, the Dock and the OS all end +// up here, and all of them go through the quit flow. Only two quits are allowed through: the +// quit flow's own exit, and the OS ending the session (a logout, a restart or a shutdown), because +// a veto there would cancel the session's end. shouldQuit runs on the main thread, where a dialog +// would deadlock. +func (u *ui) shouldQuit() bool { + if u.quitting.Load() { + return true + } + if endingSession() { + u.endSession() + return true + } + go u.quit(false) + return false +} + +// endSession lets the OS end the session. onShutdown then stops the core before the OS gives up +// waiting. +func (u *ui) endSession() { + u.sessionEnding.Store(true) + u.quitting.Store(true) + // Wails closes the windows next, and a window with unsaved changes must not hold that up. + if u.windows != nil { + u.windows.Closing() + } + u.log.Info("the OS is ending the session") +} + +const wmEndSession = 0x0016 + +// wndProc is Wails' WndProcInterceptor, which only Windows calls. It sees every message sent to +// the app's main-thread window, so it checks msg first. Wails quits on WM_ENDSESSION whatever the +// wParam is. A wParam of 0 means another app cancelled the end of the session, so the message is +// swallowed and the app keeps running. A wParam of 1 means the session ends. Wails' Quit then +// runs shouldQuit and onShutdown while handling the message, before Windows ends the process. +func (u *ui) wndProc(_ uintptr, msg uint32, wParam, _ uintptr) (uintptr, bool) { + if msg != wmEndSession { + return 0, false + } + if wParam == 0 { + return 0, true + } + u.endSession() + return 0, false +} + +// The Apple event that asks an app to quit, and the quit reasons that mean the session is ending, +// as their four-character codes (from AppleEvents.h and AERegistry.h). +const ( + aeCoreEventClass = 0x61657674 // 'aevt' + aeQuitApplication = 0x71756974 // 'quit' + aeLogOut = 0x6c6f676f // 'logo' + aeReallyLogOut = 0x726c676f // 'rlgo' + aeRestart = 0x72657374 // 'rest' + aeShowRestartDialog = 0x72727374 // 'rrst' + aeShutDown = 0x73687574 // 'shut' + aeShowShutdownDialog = 0x7273646e // 'rsdn' +) + +// sessionEndEvent reports whether an Apple event is the quit that loginwindow sends for a logout, +// a restart or a shutdown. That is a quit event whose kAEQuitReason is one of those reasons. ⌘Q +// sends no event, and the Dock's Quit sends one without a reason. +func sessionEndEvent(class, id, reason uint32) bool { + if class != aeCoreEventClass || id != aeQuitApplication { + return false + } + switch reason { + case aeLogOut, aeReallyLogOut, aeRestart, aeShowRestartDialog, aeShutDown, aeShowShutdownDialog: + return true + } + return false +} + +// quit is the only way the app exits. force skips the confirmation, as for a signal or the crash +// dialog's Exit. If a quit is already under way, quit does nothing. An update that is being +// installed finishes first (see updateFlow.holdInstalls), because exiting halfway would leave the +// app half replaced. The launcher is suspended while the question is asked, because anything +// started from it would be missing from the question's list and would not survive the stop. +func (u *ui) quit(force bool) { + if !u.quitMu.TryLock() { + return + } + defer u.quitMu.Unlock() + defer u.updates.holdInstalls()() + if u.quitting.Load() { + return + } + u.launcher.Suspend() + ctx := context.Background() + if !force && !u.confirmQuit(ctx) { + u.launcher.Resume() + return + } + u.log.Info("quitting") + // From now on no window shows again, not even one that is still loading, because stopping + // the core can take a while. + u.windows.Closing() + u.hideWindows() + u.stopCore(ctx, false) + u.exit() +} + +// confirmStop asks before stopping a busy core, for a Restart or an Update, which open the app +// again. title and action are the dialog's title and its button, in the app's language. It +// returns true when nothing is running or the user agreed. A core that doesn't answer counts as +// idle, because a dead core runs no transfers. +func (u *ui) confirmStop(ctx context.Context, title, action string) bool { + c := u.theCore() + if c == nil { + return true + } + b := c.Busy(ctx) + if len(b.Items) == 0 { + return true + } + return interaction.Ask(interaction.Warning, title, busyMessage(b), action, i18n.T("Cancel")) +} + +// confirmQuit asks before quitting when anything is running, or when watchers or schedules would +// stop running while the app is closed. It returns true when there is nothing to ask about or +// the user agreed. +func (u *ui) confirmQuit(ctx context.Context) bool { + c := u.theCore() + if c == nil { + return true + } + k := c.KeepsRunning(ctx) + text := quitMessage(c.Busy(ctx), k.Watchers, k.Schedules) + if text == "" { + return true + } + // i18n: The title of the dialog that asks before the app quits while it has work running. + title := i18n.T("Exit") + // i18n: The button that quits the app. + return interaction.Ask(interaction.Warning, title, text, i18n.T("Quit"), i18n.T("Cancel")) +} + +func busyLabels(items []core.BusyItem) []string { + labels := make([]string, 0, len(items)) + for _, it := range items { + l := it.Label + if d := it.Detail; d != "" { + l += " (" + d + ")" + } + labels = append(labels, l) + } + return labels +} + +// busyMessage returns the confirmation's text. It names what a stop would interrupt with the +// same phrase as the launcher's Stop Everything, and then lists it. +func busyMessage(busy core.BusyList) string { + const shown = 8 + labels := busyLabels(busy.Items) + var b strings.Builder + // Phrase starts with a lower-case letter. The whole sentence is capitalized, because a + // translation may not start with the phrase. + if busy.Running != (core.Running{}) { + // i18n: The start of the quit dialog, followed by a list. %s names what is running: "2 transfers, a serve and 3 mounts". + b.WriteString(capitalize(i18n.T("%s will be stopped:", busy.Running.Phrase())) + "\n") + } else { + // i18n: The start of the quit dialog, followed by a list of what is running. + b.WriteString(i18n.T("These will be stopped:") + "\n") + } + for i, l := range labels { + if i == shown { + more := len(labels) - shown + // i18n: The end of a list that is cut short. + b.WriteString("\n" + i18n.N("…and %d more", "…and %d more", more, more)) + break + } + b.WriteString("\n• " + l) + } + return b.String() +} + +func capitalize(s string) string { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError { + return s + } + return string(unicode.ToUpper(r)) + s[n:] +} + +// quitMessage returns the quit dialog's text: what a quit would stop, and the watchers and +// schedules that won't run while the app is closed. It is "" when there is neither. +func quitMessage(b core.BusyList, watchers, schedules int) string { + var parts []string + if len(b.Items) > 0 { + parts = append(parts, busyMessage(b)) + } + if kept := keptMessage(watchers, schedules); kept != "" { + parts = append(parts, kept) + } + return strings.Join(parts, "\n\n") +} + +// keptMessage says which watchers and schedules won't run while the app is closed: "your +// watcher", "your 3 schedules", "your watcher and 2 schedules", "your 2 watchers and 1 schedule". +// A single watcher or schedule is named without its number. It is "" when there are none. +func keptMessage(watchers, schedules int) string { + switch { + case watchers == 0 && schedules == 0: + return "" + case schedules == 0 && watchers == 1: + return i18n.T("While Rclone UI is closed, your watcher won't run. It starts again when you open it.") + case schedules == 0: + return i18n.N("While Rclone UI is closed, your %d watcher won't run. It starts again when you open it.", + "While Rclone UI is closed, your %d watchers won't run. They start again when you open it.", watchers, watchers) + case watchers == 0 && schedules == 1: + return i18n.T("While Rclone UI is closed, your schedule won't run. It starts again when you open it.") + case watchers == 0: + return i18n.N("While Rclone UI is closed, your %d schedule won't run. It starts again when you open it.", + "While Rclone UI is closed, your %d schedules won't run. They start again when you open it.", schedules, schedules) + } + w := i18n.MN("%d watcher", "%d watchers", watchers, watchers) + if watchers == 1 { + // i18n: The one watcher in "your watcher and 2 schedules". + w = i18n.M("watcher") + } + s := i18n.MN("%d schedule", "%d schedules", schedules, schedules) + // i18n: The quit dialog's last line, when watchers and schedules won't run: "your watcher and 2 schedules", "your 2 watchers and 1 schedule". + return i18n.T("While Rclone UI is closed, your %s and %s won't run. They start again when you open it.", w, s) +} + +// exit ends the process through Wails, bypassing the veto in shouldQuit. +func (u *ui) exit() { + u.quitting.Store(true) + u.app.Quit() +} + +// resumeOnStop reports whether the core's last stop should record what is running for the next +// start. That happens when the OS is ending the session and the user asked for things to come +// back afterwards (in Settings › General). +func (u *ui) resumeOnStop() bool { + return u.sessionEnding.Load() && u.settings().General.ResumeAfterLogout +} + +// onShutdown is the last call from Wails. It runs on the main thread, inside the +// applicationShouldTerminate: handler on macOS and inside WM_ENDSESSION on Windows. A core that +// is still running stops here, for example after an exit that skipped the quit flow or when the +// OS ends the session. It records what is running when it should, and it must finish before the +// OS stops waiting for a slow app (about 10 seconds). A child process that outlives the core +// exits when its stdin closes along with this process. +func (u *ui) onShutdown() { + u.quitting.Store(true) + // Agents are cut off first, so that none starts something while the core stops. + u.agents.Close() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + u.stopCore(ctx, u.resumeOnStop()) + u.log.Info("stopped") +} diff --git a/app/quit_message_test.go b/app/quit_message_test.go new file mode 100644 index 00000000..358d6f80 --- /dev/null +++ b/app/quit_message_test.go @@ -0,0 +1,43 @@ +package app + +import ( + "testing" + + "github.com/rclone/rclone-ui/core" +) + +func TestQuitMessage(t *testing.T) { + const tail = " won't run. They start again when you open it." + copying := core.BusyList{ + Items: []core.BusyItem{{Kind: "transfer", Label: "Copy /a → /b", Detail: "Runs again when Rclone UI starts."}}, + Running: core.Running{Transfers: 1}, + } + several := core.BusyList{ + Items: []core.BusyItem{ + {Kind: "transfer", Label: "Copy /a → /b"}, + {Kind: "mount", Label: "Mount gdrive: at /m"}, + {Kind: "tunnel", Label: "The remote tunnel"}, + }, + Running: core.Running{Transfers: 1, Mounts: 1, Tunnel: true}, + } + for _, c := range []struct { + busy core.BusyList + watchers, schedules int + want string + }{ + {core.BusyList{}, 0, 0, ""}, + {core.BusyList{}, 1, 0, "While Rclone UI is closed, your watcher won't run. It starts again when you open it."}, + {core.BusyList{}, 0, 3, "While Rclone UI is closed, your 3 schedules" + tail}, + {core.BusyList{}, 1, 2, "While Rclone UI is closed, your watcher and 2 schedules" + tail}, + {core.BusyList{}, 2, 3, "While Rclone UI is closed, your 2 watchers and 3 schedules" + tail}, + {core.BusyList{}, 2, 1, "While Rclone UI is closed, your 2 watchers and 1 schedule" + tail}, + {core.BusyList{}, 0, 1, "While Rclone UI is closed, your schedule won't run. It starts again when you open it."}, + {copying, 0, 0, "A transfer will be stopped:\n\n• Copy /a → /b (Runs again when Rclone UI starts.)"}, + {several, 1, 1, "A transfer, a mount and the remote tunnel will be stopped:\n\n• Copy /a → /b\n• Mount gdrive: at /m\n" + + "• The remote tunnel\n\nWhile Rclone UI is closed, your watcher and 1 schedule" + tail}, + } { + if got := quitMessage(c.busy, c.watchers, c.schedules); got != c.want { + t.Errorf("%+v %d %d:\n got %q\nwant %q", c.busy, c.watchers, c.schedules, got, c.want) + } + } +} diff --git a/app/quit_test.go b/app/quit_test.go new file mode 100644 index 00000000..f596934c --- /dev/null +++ b/app/quit_test.go @@ -0,0 +1,81 @@ +package app + +import ( + "log/slog" + "testing" + + settingspb "github.com/rclone/rclone-ui/core/settings" +) + +func testUI() *ui { return &ui{log: slog.New(slog.DiscardHandler)} } + +func TestShouldQuitLetsTheOSEndTheSession(t *testing.T) { + defer func(f func() bool) { endingSession = f }(endingSession) + endingSession = func() bool { return true } + u := testUI() + if !u.shouldQuit() { + t.Fatal("the OS's quit was vetoed") + } + if !u.quitting.Load() || !u.sessionEnding.Load() { + t.Fatalf("quitting %v, sessionEnding %v", u.quitting.Load(), u.sessionEnding.Load()) + } +} + +func TestResumeOnStop(t *testing.T) { + for _, c := range []struct { + ending, setting, want bool + }{ + {false, false, false}, + {true, false, false}, + {false, true, false}, + {true, true, true}, + } { + u := testUI() + u.sessionEnding.Store(c.ending) + u.applied.cur, u.applied.loaded = settingspb.Settings{General: settingspb.General{ResumeAfterLogout: c.setting}}, true + if got := u.resumeOnStop(); got != c.want { + t.Errorf("ending %v, setting %v: %v", c.ending, c.setting, got) + } + } +} + +func TestEndSessionMessages(t *testing.T) { + u := testUI() + if ret, handled := u.wndProc(0, wmEndSession, 0, 0); ret != 0 || !handled { + t.Fatalf("cancelled: %d %v", ret, handled) + } + if u.quitting.Load() || u.sessionEnding.Load() { + t.Fatal("a cancelled end of the session set the flags") + } + if _, handled := u.wndProc(0, 0x0011 /* WM_QUERYENDSESSION */, 1, 0); handled || u.quitting.Load() { + t.Fatal("another message was taken") + } + if ret, handled := u.wndProc(0, wmEndSession, 1, 0); ret != 0 || handled { + t.Fatalf("ending: %d %v", ret, handled) + } + if !u.quitting.Load() || !u.sessionEnding.Load() { + t.Fatal("an ending session didn't set the flags") + } +} + +func TestSessionEndEvent(t *testing.T) { + for _, c := range []struct { + class, id, reason uint32 + want bool + }{ + {aeCoreEventClass, aeQuitApplication, aeReallyLogOut, true}, + {aeCoreEventClass, aeQuitApplication, aeLogOut, true}, + {aeCoreEventClass, aeQuitApplication, aeRestart, true}, + {aeCoreEventClass, aeQuitApplication, aeShowRestartDialog, true}, + {aeCoreEventClass, aeQuitApplication, aeShutDown, true}, + {aeCoreEventClass, aeQuitApplication, aeShowShutdownDialog, true}, + {aeCoreEventClass, aeQuitApplication, 0, false}, + {aeCoreEventClass, aeQuitApplication, 0x71756961 /* 'quia', kAEQuitAll */, false}, + {aeCoreEventClass, 0x6f646f63 /* 'odoc' */, aeShutDown, false}, + {0, 0, 0, false}, + } { + if got := sessionEndEvent(c.class, c.id, c.reason); got != c.want { + t.Errorf("%#x %#x %#x: %v", c.class, c.id, c.reason, got) + } + } +} diff --git a/app/services.go b/app/services.go new file mode 100644 index 00000000..0c2add9d --- /dev/null +++ b/app/services.go @@ -0,0 +1,316 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + "github.com/rclone/rclone-ui/core/agents" + "os" + "runtime" + "runtime/debug" + "strings" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/autostart" + "github.com/rclone/rclone-ui/app/launcher/view/linux" + "github.com/rclone/rclone-ui/app/pathlink" + "github.com/rclone/rclone-ui/app/windows" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/rclone" +) + +// services returns the services that pages call through lib/shell. The bindings are generated +// from them. A development build adds its own services (see devServices). +func (u *ui) services() []application.Service { + return append([]application.Service{ + service(u, &WindowService{u: u}), + service(u, &LauncherService{u: u}), + // The launcher exists only once the app does, after the services are bound. + service(u, &linux.PageService{View: func() *linux.View { return u.launcher.Page() }}), + service(u, &CoreService{u: u}), + service(u, &SystemService{u: u}), + service(u, &DialogService{u: u}), + service(u, &UpdateService{u: u}), + service(u, &PathService{u: u}), + service(u, &AgentsService{u: u}), + // The core's APIs, one service per domain. + service(u, u.apis.Prefs), + service(u, u.apis.Settings), + service(u, u.apis.Favorites), + service(u, u.apis.Templates), + service(u, u.apis.Launcher), + service(u, u.apis.Logs), + service(u, u.apis.Vfs), + service(u, u.apis.Media), + service(u, u.apis.Files), + service(u, u.apis.Catalog), + service(u, u.apis.Config), + service(u, u.apis.Remotes), + service(u, u.apis.Mounts), + service(u, u.apis.Serves), + service(u, u.apis.Tunnel), + service(u, u.apis.Notifications), + service(u, u.apis.Browse), + service(u, u.apis.Transfers), + service(u, u.apis.Watchers), + service(u, u.apis.Schedules), + service(u, u.apis.Links), + service(u, u.apis.Telemetry), + service(u, u.apis.App), + }, u.devServices()...) +} + +// service binds one service, the shell's own or one of the core's APIs. Its errors reach the page +// in the core's error format, with a code, a message and the details the page acts on (see +// core/errs). Wails sets the error marshaller per service, because an app-wide one isn't used for +// a service's methods. +func service[T any](u *ui, api *T) application.Service { + return application.NewServiceWithOptions(api, application.ServiceOptions{MarshalError: u.marshalError}) +} + +// marshalError converts a call's error into the form the page receives, with rclone.ErrorOf, +// which gives every error its code. Internal errors and rclone's own failures are also logged. +// Otherwise a full disk or a busy database would only show up as a toast in a window, and nothing +// would appear in the log or in a bug report. (The log redacts credentials.) +func (u *ui) marshalError(err error) []byte { + e := rclone.ErrorOf(err) + switch e.Code { + case errs.CodeInternal: + u.log.Error("a call failed", "code", string(e.Code), "error", err) + case errs.CodeFailed: + u.log.Warn("a call failed", "code", string(e.Code), "error", err) + } + // The page shows the message, so it gets it in the app's language. The log above has it in + // English. + b, jerr := json.Marshal(e.Localized()) + if jerr != nil { + return nil // Wails then marshals the error itself + } + return b +} + +type WindowService struct{ u *ui } + +// Open opens the window for a route, such as "/remotes?action=create". The route decides the +// window's name and size. If a window with that name is already open, it is focused and switches +// to the route. +func (s *WindowService) Open(url string) error { return s.u.windows.Open(url) } + +var errNoCaller = errors.New("the call didn't come from a window") + +// SetTheme sets the calling window's appearance: "dark", "light", or "" to follow the system. +func (s *WindowService) SetTheme(ctx context.Context, theme string) error { + w, ok := windows.Caller(ctx) + if !ok { + return errNoCaller + } + s.u.windows.SetTheme(w, theme) + return nil +} + +// GuardClose sets whether closing the calling window asks its page first, which the page does +// while it holds unsaved changes. The page gets the window:close event, asks, and closes the +// window itself. +func (s *WindowService) GuardClose(ctx context.Context, on bool) { + if w, ok := windows.Caller(ctx); ok { + s.u.windows.GuardClose(w.Name(), on) + } +} + +type LauncherService struct{ u *ui } + +func (s *LauncherService) Show() { s.u.launcher.Show() } + +// SetShortcut replaces the launcher's global shortcut. It uses the syntax that Settings stores, +// such as "CmdOrCtrl+Shift+/", and "" removes the shortcut. Settings calls it before saving a +// shortcut, so a shortcut that the OS refuses is never saved. +func (s *LauncherService) SetShortcut(shortcut string) error { + return s.u.launcher.SetShortcut(strings.TrimSpace(shortcut)) +} + +type CoreService struct{ u *ui } + +func (s *CoreService) Status() CoreStatus { return s.u.coreStatus() } + +type SystemService struct{ u *ui } + +// SystemInfo holds the facts about the machine that bug reports include. +type SystemInfo struct { + // OS is Go's name for the OS ("darwin"). + OS string `json:"os"` + // OSName and OSVersion describe the OS ("macOS", "15.2"). + OSName string `json:"osName"` + OSVersion string `json:"osVersion"` + // Shell is the desktop shell and its version ("Wails v3.1.0"). + Shell string `json:"shell"` +} + +func (s *SystemService) Info() SystemInfo { + var osName, osVersion string + if env := s.u.app.Env.Info(); env.OSInfo != nil { + osName, osVersion = env.OSInfo.Name, env.OSInfo.Version + } + return SystemInfo{OS: runtime.GOOS, OSName: osName, OSVersion: osVersion, Shell: shellVersion()} +} + +func shellVersion() string { + if bi, ok := debug.ReadBuildInfo(); ok { + for _, dep := range bi.Deps { + if dep.Path == "github.com/wailsapp/wails/v3" { + return "Wails " + dep.Version + } + } + } + return "Wails" +} + +func (s *SystemService) RevealPath(path string) error { return s.u.reveal(path, true) } + +func (s *SystemService) OpenURL(url string) error { return s.u.openURL(url) } + +// Autostart reports whether the app starts at login. +func (s *SystemService) Autostart() (bool, error) { return autostart.IsEnabled(s.u.app) } + +// SetAutostart turns starting at login on or off, and tells every window (EventAutostartChanged), +// so that the switch in another window follows. +func (s *SystemService) SetAutostart(enabled bool) error { + var err error + if enabled { + err = autostart.Enable(s.u.app) + } else { + err = autostart.Disable(s.u.app) + } + if err != nil { + return err + } + s.u.app.Event.Emit(EventAutostartChanged, enabled) + return nil +} + +// Log writes a page's console line to the UI's log. level is the console method that was called. +func (s *SystemService) Log(level, window, message string) { + l := s.u.log.With("src", "page", "window", window) + switch level { + case "error": + l.Error(message) + case "warn": + l.Warn(message) + case "debug", "log", "trace": + l.Debug(message) + default: + l.Info(message) + } +} + +// Quit runs the quit flow, which first checks whether anything is busy. +func (s *SystemService) Quit() { go s.u.quit(false) } + +// Relaunch starts the app again and reopens the window at open ("" for none). Whatever is running +// stops and comes back, as it does after a quit. When something is running, the user is asked +// first, and Relaunch returns false if they keep the app running. +func (s *SystemService) Relaunch(ctx context.Context, open string) bool { + // i18n: The title and the button of the dialog that asks before a restart stops what is running. + if !s.u.confirmStop(ctx, i18n.T("Restart"), i18n.T("Restart")) { + return false + } + go s.u.relaunch(open) + return true +} + +// DialogService saves the text that a page exports. The pages show their other dialogs +// themselves (lib/shell), and the Open and Save panels for a path come from the Wails runtime. +type DialogService struct{ u *ui } + +// SaveOptions describes a save dialog. Filters use the runtime's own shape, so a page passes the +// same filters as to its Open panel. +type SaveOptions struct { + Title string `json:"title"` + // Directory is the folder the dialog opens in, and Filename is the name it suggests. + Directory string `json:"directory"` + Filename string `json:"filename"` + Filters []application.FileFilter `json:"filters"` +} + +// SaveText asks where to save, in a dialog over the calling window, and writes contents there. It +// returns the path, or "" when the user cancelled. The page never names the path itself, so a +// script in a page can't write a shell profile or a login item. +func (s *DialogService) SaveText(ctx context.Context, o SaveOptions, contents string) (string, error) { + opts := &application.SaveFileDialogOptions{ + Title: o.Title, + Directory: o.Directory, + Filename: o.Filename, + Filters: o.Filters, + CanCreateDirectories: true, + } + if w, ok := windows.Caller(ctx); ok { + opts.Window = w + } + path, err := s.u.app.Dialog.SaveFileWithOptions(opts).PromptForSingleSelection() + if err != nil || path == "" { + return "", err + } + if err := writePrivate(path, contents); err != nil { + return "", err + } + return path, nil +} + +// writePrivate writes a file that only the user can read, because an exported template or config +// can hold connection keys. A file that is replaced loses the wider mode it had. Windows has no +// such mode: the file takes its folder's permissions, which in the user's own folders let only the +// user and the administrators read it. +func writePrivate(path, contents string) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return err + } + if err := f.Chmod(0o600); err != nil && runtime.GOOS != "windows" { + _ = f.Close() + return err + } + if _, err := f.WriteString(contents); err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// AgentsService tells Settings about the MCP server that lets AI agents use the app (core/agents). +// The server is turned on and off, and given its port and a new token, through the settings. +type AgentsService struct{ u *ui } + +type AgentsInfo struct { + agents.Status + // Command is this app's executable, which a client that starts a command runs as + // ` mcp`. + Command string `json:"command"` +} + +// Status returns whether the server runs and where, and the command for clients that start one. +// EventAgentsChanged follows each change of the status. +func (s *AgentsService) Status() AgentsInfo { + return AgentsInfo{Status: s.u.agents.Status(), Command: s.u.exe} +} + +// PathService provides "Add rclone to PATH" (see app/pathlink). It adds a command named rclone +// that runs this app as rclone, with the same config files. It never replaces a user's own rclone. +type PathService struct{ u *ui } + +func (s *PathService) Status() (pathlink.State, error) { return pathlink.Status() } + +// Enable adds rclone to PATH. On macOS, it asks for an administrator password when +// /usr/local/bin requires one. +func (s *PathService) Enable() (pathlink.State, error) { return s.changed(pathlink.Enable()) } + +func (s *PathService) Disable() (pathlink.State, error) { return s.changed(pathlink.Disable()) } + +// changed tells every window the link's new state (EventPathLinkChanged), so that Settings and +// the Mobile & Remote Control window agree. +func (s *PathService) changed(st pathlink.State, err error) (pathlink.State, error) { + if err == nil { + s.u.app.Event.Emit(EventPathLinkChanged, st) + } + return st, err +} diff --git a/app/services_test.go b/app/services_test.go new file mode 100644 index 00000000..f8e83b9a --- /dev/null +++ b/app/services_test.go @@ -0,0 +1,83 @@ +package app + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestWritePrivate(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows has no mode bits") + } + dir := t.TempDir() + fresh := filepath.Join(dir, "templates.json") + replaced := filepath.Join(dir, "rclone.conf") + if err := os.WriteFile(replaced, []byte("an older and longer file"), 0o644); err != nil { + t.Fatal(err) + } + for _, path := range []string{fresh, replaced} { + if err := writePrivate(path, "{}"); err != nil { + t.Fatal(err) + } + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if st.Mode().Perm() != 0o600 { + t.Errorf("%s: mode %v", filepath.Base(path), st.Mode().Perm()) + } + if b, _ := os.ReadFile(path); string(b) != "{}" { + t.Errorf("%s: %q", filepath.Base(path), b) + } + } +} + +func TestBrowsable(t *testing.T) { + for _, ok := range []string{ + "https://rclone.org/drive/#making-your-own-client-id", + "http://127.0.0.1:53682/auth?state=x", + "HTTPS://github.com/rclone/rclone-ui", + "mailto:support@rcloneui.com", + } { + if err := browsable(ok); err != nil { + t.Errorf("browsable(%q): %v", ok, err) + } + } + for _, bad := range []string{ + "", + "/Applications/Calculator.app", + "-aCalculator", + "-https://example.com", + `C:\path\evil.exe`, + "file:///etc/passwd", + "javascript:alert(1)", + "smb://host/share", + "https:///no-host", + "https://example.com/\nx", + } { + if err := browsable(bad); err == nil { + t.Errorf("browsable(%q) accepted it", bad) + } + } +} + +func TestMaybeBundle(t *testing.T) { + dir := t.TempDir() + for _, d := range []string{"Calculator.app", "Photos", ".config"} { + if err := os.Mkdir(filepath.Join(dir, d), 0o700); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(dir, "run.command"), nil, 0o600); err != nil { + t.Fatal(err) + } + for name, want := range map[string]bool{ + "Calculator.app": true, "Calculator.app/": true, "Photos": false, ".config": false, "run.command": false, "missing.app": false, + } { + if got := maybeBundle(filepath.Join(dir, name)); got != want { + t.Errorf("%s: %v", name, got) + } + } +} diff --git a/app/settings.go b/app/settings.go new file mode 100644 index 00000000..d8bfa495 --- /dev/null +++ b/app/settings.go @@ -0,0 +1,150 @@ +package app + +import ( + "context" + "runtime" + "sync" + "time" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/launcher" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/settings" +) + +// uiSettings is the part of the core's settings that the UI role applies: the launcher's +// shortcut, the tray icon, the startup window and the update channel. It is reloaded on every +// settings.changed event. +type uiSettings struct { + // load allows only one read and apply at a time. Otherwise two settings.changed events in a + // row would race, and the older read could be applied last, bringing back the launcher's old + // shortcut. + load sync.Mutex + + mu sync.Mutex + loaded bool + cur settings.Settings + + // language is the language that the tray, the menu bar and the launcher were last drawn in. + // It is read and written under load. + language string +} + +// settings returns the settings last read from the core, or the defaults before the first read. +func (u *ui) settings() settings.Settings { + u.applied.mu.Lock() + defer u.applied.mu.Unlock() + if !u.applied.loaded { + return settings.Defaults() + } + return u.applied.cur +} + +// loadSettings reads the settings from the core and applies what changed. Reads run one at a +// time, each after the previous one was applied, so the last one to run has the newest settings. +func (u *ui) loadSettings(ctx context.Context) { + u.applied.load.Lock() + defer u.applied.load.Unlock() + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + next, err := u.apis.Settings.Get(ctx) + if err != nil { + u.log.Warn("could not read the settings", "error", err) + return + } + u.applied.mu.Lock() + prev, first := u.applied.cur, !u.applied.loaded + u.applied.cur, u.applied.loaded = next, true + u.applied.mu.Unlock() + + shortcut := next.General.LauncherShortcut + if shortcut == "" { + shortcut = launcher.DefaultShortcut + } + if first || prev.General.LauncherShortcut != next.General.LauncherShortcut { + if err := u.launcher.SetShortcut(shortcut); err != nil { + u.log.Error("could not register the launcher shortcut", "shortcut", shortcut, "error", err) + } + } + if first || prev.General.LauncherStaysOpen != next.General.LauncherStaysOpen { + u.launcher.SetStaysOpen(next.General.LauncherStaysOpen) + } + if first || prev.Appearance.TrayIcon != next.Appearance.TrayIcon { + u.tray.SetAppearance(trayAppearance(next.Appearance.TrayIcon)) + } + // The core has already switched the language (core/settings), either as it started or before + // it reported that the settings changed. The tray and the menu bar may have been drawn in the + // system's language before that, so what the Go side shows is drawn again here. + if lang := i18n.Language(); lang != u.applied.language { + u.applied.language = lang + u.languageChanged() + } + if next.General.HideStartup { + u.noStartup.Store(true) + } + // Starts, stops or restarts the agents' server when its settings changed. + u.agents.Apply(next.Agents) + // The app starts without a Dock icon (ActivationPolicyAccessory), so the first load only acts + // when the setting asks for the icon. + if first && next.General.ShowInDock || !first && prev.General.ShowInDock != next.General.ShowInDock { + showInDock(next.General.ShowInDock) + } +} + +// trayAppearance converts a tray icon setting to the name the tray package uses. An unset value +// gives the OS's default. +func trayAppearance(icon settings.TrayIcon) string { + switch icon { + case settings.TrayIconSystem: + return "system" + case settings.TrayIconColor: + return "color" + case settings.TrayIconDark: + return "dark" + case settings.TrayIconLight: + return "light" + } + if runtime.GOOS == "linux" { + return "color" + } + return "system" +} + +// skipVersion records a release that the user chose not to install, in the +// updates.skipped_version setting. +func (u *ui) skipVersion(ctx context.Context, v string) { + if _, err := u.apis.Settings.Update(ctx, settings.Patch{SkippedVersion: &v}); err != nil { + u.log.Warn("could not record the skipped version", "version", v, "error", err) + } +} + +// hideStartupFromNow turns the "Show Startup screen" setting off. +func (u *ui) hideStartupFromNow(ctx context.Context) { + hide := true + if _, err := u.apis.Settings.Update(ctx, settings.Patch{HideStartup: &hide}); err != nil { + u.log.Warn("could not turn the startup window off", "error", err) + } +} + +// checkProxy tests the proxy at startup. A proxy that can't connect is reported once, before +// every remote fails through it. Choosing Exit quits the app. +func (u *ui) checkProxy(ctx context.Context) { + proxy := u.settings().Proxy.URL + if proxy == "" { + return + } + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + _, err := u.apis.Settings.TestProxy(ctx, proxy) + if err == nil { + return + } + u.log.Warn("the proxy did not connect", "error", err) + // i18n: The title of the dialog that says the proxy failed to connect at start. + title := i18n.T("Error") + msg := i18n.T("You have a proxy set, but it failed to connect. Do you want to continue anyway?") + // i18n: The button that quits the app, in the dialog that says the proxy failed to connect. + if !interaction.Ask(interaction.Warning, title, msg, i18n.T("Continue"), i18n.T("Exit")) { + u.quit(true) + } +} diff --git a/src-tauri/icons/favicon/icon-color-padded.png b/app/tray/icons/icon-color-padded.png similarity index 100% rename from src-tauri/icons/favicon/icon-color-padded.png rename to app/tray/icons/icon-color-padded.png diff --git a/src-tauri/icons/favicon/icon-color.png b/app/tray/icons/icon-color.png similarity index 100% rename from src-tauri/icons/favicon/icon-color.png rename to app/tray/icons/icon-color.png diff --git a/src-tauri/icons/favicon/icon-light-padded.png b/app/tray/icons/icon-light-padded.png similarity index 100% rename from src-tauri/icons/favicon/icon-light-padded.png rename to app/tray/icons/icon-light-padded.png diff --git a/src-tauri/icons/favicon/icon-light.png b/app/tray/icons/icon-light.png similarity index 100% rename from src-tauri/icons/favicon/icon-light.png rename to app/tray/icons/icon-light.png diff --git a/src-tauri/icons/favicon/icon-padded.png b/app/tray/icons/icon-padded.png similarity index 100% rename from src-tauri/icons/favicon/icon-padded.png rename to app/tray/icons/icon-padded.png diff --git a/src-tauri/icons/favicon/icon.png b/app/tray/icons/icon.png similarity index 100% rename from src-tauri/icons/favicon/icon.png rename to app/tray/icons/icon.png diff --git a/app/tray/tray.go b/app/tray/tray.go new file mode 100644 index 00000000..3aa51e24 --- /dev/null +++ b/app/tray/tray.go @@ -0,0 +1,374 @@ +// Package tray is the app's tray icon and menu. The tray is created before anything else boots, +// so a failed boot still leaves a way to quit. The UI sets the running mounts and serves with +// SetRunning, and the transfers' progress with SetTransfers. Pages don't add anything to the tray. +package tray + +import ( + "bytes" + "embed" + "image" + "image/color" + "image/draw" + "image/png" + "math" + "runtime" + "strings" + "sync" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/core/i18n" +) + +//go:embed icons/*.png +var icons embed.FS + +type Item struct { + Label string + // Separator draws a line instead of an item. + Separator bool + Disabled bool + // Children make the item a submenu. + Children []Item + // OnClick runs when the item is chosen. It is called directly from the menu's click handler, + // so it must not block. + OnClick func() +} + +// Actions holds what the built-in items do. +type Actions struct { + // ShowLauncher runs on a left click, on systems where a left click opens the launcher. + ShowLauncher func() + // Open runs for the menu's Open item. It shows the launcher, with a tip about its shortcut the + // first time. ShowLauncher is used when it is nil. + Open func() + // OpenWindow opens the window for a route. The route decides the window's name and shape. + OpenWindow func(url string) + GitHub func() + Quit func() +} + +type Tray struct { + app *application.App + st *application.SystemTray + actions Actions + mint bool + + mu sync.Mutex + state state + appearance string + + // icon serialises setting the icon, so the last icon set always matches the latest state. + icon sync.Mutex + + // rebuild serialises menu rebuilds, so that cur is always the menu shown and only the menu + // it replaced is destroyed. curHistory is cur's History item, or nil when cur has none. + rebuild sync.Mutex + cur *application.Menu + curHistory *application.MenuItem +} + +type state struct { + // transfers is the History item's label while transfers run, such as + // "History (2 running · 42%)". It is "" when none runs. + transfers string + // running are the Mounts and Serves submenus that the UI adds, while any of them run. + running []Item +} + +// dot reports whether the icon shows a dot in its corner. It does while transfers run, and +// running mounts and serves don't show it. +func (s state) dot() bool { return s.transfers != "" } + +// layout returns the menu's items for a state. Open comes first. Then History (while transfers +// run) and the Mounts and Serves submenus (while any run) share a section, which is left out with +// its separator when none of them shows. Guide, GitHub and Quit come last. history is the index +// of the History item, or -1 when it isn't shown. +func layout(s state, a Actions) (items []Item, history int) { + open := Item{Label: i18n.T("Open"), OnClick: func() { + if a.Open != nil { + a.Open() + return + } + a.ShowLauncher() + }} + items = []Item{open, {Separator: true}} + section := len(items) + history = -1 + if s.transfers != "" { + history = len(items) + items = append(items, Item{Label: s.transfers, OnClick: func() { a.OpenWindow("/history") }}) + } + items = append(items, s.running...) + if len(items) > section { + items = append(items, Item{Separator: true}) + } + items = append(items, + Item{Label: i18n.T("Guide"), OnClick: func() { a.OpenWindow("/guides") }}, + Item{Label: "GitHub", OnClick: a.GitHub}, + Item{Label: i18n.T("Quit"), OnClick: a.Quit}, + ) + return items, history +} + +// DefaultAppearance returns the default tray theme. On Linux it is the coloured icon, because +// panels vary too much for a monochrome one. Elsewhere it follows the system. +func DefaultAppearance() string { + if runtime.GOOS == "linux" { + return "color" + } + return "system" +} + +// New creates the tray icon and its menu. linuxMint pads the icons for Mint's panel. +func New(app *application.App, actions Actions, linuxMint bool) *Tray { + t := &Tray{app: app, actions: actions, mint: linuxMint, appearance: DefaultAppearance()} + t.st = app.SystemTray.New() + if runtime.GOOS == "linux" { + // On Linux the label is the item's name, which panels show as the first line of the + // tooltip. Wails names an item without a label "Wails". The tooltip's text would be a + // second line that repeats the name, so there is none. + t.st.SetLabel("Rclone UI") + } else { + t.st.SetTooltip("Rclone UI") + } + t.applyIcon() + t.cur, t.curHistory = t.menu() + t.st.SetMenu(t.cur) + switch runtime.GOOS { + case "darwin": + // Both clicks open the menu, which is Wails' default on macOS when there is no click + // handler. + case "windows": + // Both buttons open the menu. Wails opens it on a right click by default, and the left + // click is set here. The launcher is opened from the menu's Open item. + t.st.OnClick(t.st.OpenMenu) + default: + t.st.OnClick(func() { actions.ShowLauncher() }) + } + return t +} + +// SetRunning replaces the items that the UI adds, which are the Mounts and Serves submenus. +func (t *Tray) SetRunning(items []Item) { + t.mu.Lock() + t.state.running = items + t.mu.Unlock() + t.setMenu() +} + +// destroyGrace is how long a replaced menu is kept before it is destroyed. It may still be open, +// or a click on it may still be on its way, and the items of a destroyed menu no longer run. +const destroyGrace = time.Minute + +// setMenu shows a menu built from the latest state. It destroys the replaced menu on the main +// thread once destroyGrace has passed, because Wails keeps every item (and its closure) until its +// menu is destroyed. +func (t *Tray) setMenu() { + t.rebuild.Lock() + defer t.rebuild.Unlock() + m, history := t.menu() + t.st.SetMenu(m) + old := t.cur + t.cur, t.curHistory = m, history + if old != nil { + time.AfterFunc(destroyGrace, func() { application.InvokeAsync(old.Destroy) }) + } +} + +// SetTransfers sets the History item's label, such as "History (2 running · 42%)", or "" when no +// transfer runs. When the first transfer starts or the last one ends, the menu is rebuilt and the +// icon is changed. Both happen in the background, because they wait for the main thread, and the +// caller may hold a lock that the main thread needs. While transfers keep running, the label is +// changed in place. It changes every second, and a menu replaced that often would close under the +// pointer, because Windows destroys the menu that was replaced. +func (t *Tray) SetTransfers(label string) { + // Hold rebuild, so that a menu being built either picks up this label or is relabelled here. + t.rebuild.Lock() + defer t.rebuild.Unlock() + t.mu.Lock() + prev := t.state.transfers + t.state.transfers = label + t.mu.Unlock() + switch { + case label == prev: + case (label == "") != (prev == ""): + // A rebuild reads the state when it runs, so the last one shows the latest label. + go t.setMenu() + go t.applyIcon() + case t.curHistory != nil: + item := t.curHistory + application.InvokeAsync(func() { item.SetLabel(escapeMnemonics(label, runtime.GOOS)) }) + } +} + +// Rebuild builds the menu again from the latest state. The app calls it when the language +// changes, because the menu's own labels are translated when it is built. +func (t *Tray) Rebuild() { t.setMenu() } + +// SetAppearance chooses the icon: "system", "color", "dark" or "light". +func (t *Tray) SetAppearance(appearance string) { + t.mu.Lock() + t.appearance = appearance + t.mu.Unlock() + t.applyIcon() +} + +func (t *Tray) applyIcon() { + t.icon.Lock() + defer t.icon.Unlock() + t.mu.Lock() + appearance, dot := t.appearance, t.state.dot() + t.mu.Unlock() + light, dark, template := IconFiles(appearance, runtime.GOOS, t.mint) + icon := func(name string) []byte { + b := mustIcon(name) + if dot { + b = mustMark(b, template) + } + return b + } + if template { + t.st.SetTemplateIcon(icon(light)) + return + } + t.st.SetIcon(icon(light)) + if dark != "" { + t.st.SetDarkModeIcon(icon(dark)) + } else { + t.st.SetDarkModeIcon(icon(light)) + } +} + +// Marked returns a tray icon (a PNG) with the dot that shows while transfers run. The dot is in the +// top right corner, separated from the glyph by a transparent ring. The dot is red, or opaque black +// for a template icon, because macOS tints a template the same way as the glyph, so only its +// shape shows. +func Marked(icon []byte, template bool) ([]byte, error) { + src, err := png.Decode(bytes.NewReader(icon)) + if err != nil { + return nil, err + } + b := src.Bounds() + img := image.NewNRGBA(b) + draw.Draw(img, b, src, b.Min, draw.Src) + size := float64(min(b.Dx(), b.Dy())) + r, ring := size*0.2, size*0.28 // the dot's radius, and the ring's outer one + cx, cy := float64(b.Max.X)-ring, float64(b.Min.Y)+ring + dot := color.NRGBA{R: 0xff, G: 0x3b, B: 0x30, A: 0xff} + if template { + dot = color.NRGBA{A: 0xff} + } + clamp := func(v float64) float64 { return math.Max(0, math.Min(1, v)) } + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + d := math.Hypot(float64(x)+0.5-cx, float64(y)+0.5-cy) + switch { + case d < r+0.5: + c := dot + c.A = uint8(255 * clamp(r+0.5-d)) + img.SetNRGBA(x, y, c) + case d < ring+0.5: + c := img.NRGBAAt(x, y) + c.A = uint8(float64(c.A) * clamp(d-(ring-0.5))) + img.SetNRGBA(x, y, c) + } + } + } + var out bytes.Buffer + if err := png.Encode(&out, img); err != nil { + return nil, err + } + return out.Bytes(), nil +} + +func mustMark(icon []byte, template bool) []byte { + b, err := Marked(icon, template) + if err != nil { + panic(err) // the icons are embedded above, so this can't fail + } + return b +} + +// IconFiles chooses the icon files for an appearance. It returns the icon for a light panel, the +// icon for a dark panel ("" when it is the same), and whether macOS draws it as a template +// (tinted to match the menu bar). +func IconFiles(appearance, goos string, mint bool) (light, dark string, template bool) { + suffix := "" + if mint { + suffix = "-padded" + } + name := func(base string) string { return "icons/" + base + suffix + ".png" } + switch appearance { + case "color": + return name("icon-color"), "", false + case "dark": + return name("icon-light"), "", goos == "darwin" + case "light": + return name("icon"), "", goos == "darwin" + } + if goos == "darwin" { + return "icons/icon.png", "", true + } + return name("icon-light"), name("icon"), false +} + +func mustIcon(name string) []byte { + b, err := icons.ReadFile(name) + if err != nil { + panic(err) // the names refer to the icons embedded above, so this can't fail + } + return b +} + +// menu builds the menu from the latest state, and returns it along with its History item (nil +// when it has none). +func (t *Tray) menu() (*application.Menu, *application.MenuItem) { + t.mu.Lock() + s := t.state + t.mu.Unlock() + items, history := layout(s, t.actions) + m := application.NewMenu() + var historyItem *application.MenuItem + for i, it := range items { + if added := addItem(m, it); i == history { + historyItem = added + } + } + return m, historyItem +} + +// addItem adds an item to a menu. It returns the added item, or nil for a separator or a submenu. +func addItem(m *application.Menu, it Item) *application.MenuItem { + label := escapeMnemonics(it.Label, runtime.GOOS) + switch { + case it.Separator: + m.AddSeparator() + case len(it.Children) > 0: + sub := m.AddSubmenu(label) + for _, child := range it.Children { + addItem(sub, child) + } + default: + click := it.OnClick + return m.Add(label).SetEnabled(!it.Disabled).OnClick(func(*application.Context) { + if click != nil { + click() + } + }) + } + return nil +} + +// escapeMnemonics keeps a label, such as a mount point or an address, as it is. Menus on Linux +// read "_" as an access key, and menus on Windows read "&", and they hide it. +func escapeMnemonics(label, goos string) string { + switch goos { + case "linux": + return strings.ReplaceAll(label, "_", "__") + case "windows": + return strings.ReplaceAll(label, "&", "&&") + } + return label +} diff --git a/app/tray/tray_test.go b/app/tray/tray_test.go new file mode 100644 index 00000000..112b1737 --- /dev/null +++ b/app/tray/tray_test.go @@ -0,0 +1,195 @@ +package tray + +import ( + "bytes" + "image/color" + "image/png" + "strings" + "testing" +) + +// The submenus that the UI adds while mounts and serves run (see SetRunning). +var ( + mounts = Item{Label: "Mounts (1)", Children: []Item{{Label: "gdrive: → /Volumes/gdrive", Children: []Item{{Label: "Open"}, {Label: "Unmount"}}}}} + serves = Item{Label: "Serves (2)", Children: []Item{{Label: "WEBDAV :8080"}, {Label: "HTTP :8081"}, {Separator: true}, {Label: "Stop All"}}} +) + +// render writes a menu's items on one line, with "-" for a separator and "▸" after a submenu. +func render(items []Item) string { + parts := make([]string, len(items)) + for i, it := range items { + switch { + case it.Separator: + parts[i] = "-" + case len(it.Children) > 0: + parts[i] = it.Label + " ▸" + default: + parts[i] = it.Label + } + } + return strings.Join(parts, " | ") +} + +func TestLayout(t *testing.T) { + const history = "History (2 running · 27%)" + for _, c := range []struct { + name string + state state + want string + at int // the History item's index + }{ + {"nothing active", state{}, + "Open | - | Guide | GitHub | Quit", -1}, + {"only transfers", state{transfers: history}, + "Open | - | History (2 running · 27%) | - | Guide | GitHub | Quit", 2}, + {"only mounts", state{running: []Item{mounts}}, + "Open | - | Mounts (1) ▸ | - | Guide | GitHub | Quit", -1}, + {"only serves", state{running: []Item{serves}}, + "Open | - | Serves (2) ▸ | - | Guide | GitHub | Quit", -1}, + {"mounts and serves", state{running: []Item{mounts, serves}}, + "Open | - | Mounts (1) ▸ | Serves (2) ▸ | - | Guide | GitHub | Quit", -1}, + {"all three", state{transfers: history, running: []Item{mounts, serves}}, + "Open | - | History (2 running · 27%) | Mounts (1) ▸ | Serves (2) ▸ | - | Guide | GitHub | Quit", 2}, + } { + items, at := layout(c.state, Actions{}) + got := render(items) + t.Logf("%-19s %s", c.name+":", got) + if got != c.want || at != c.at { + t.Errorf("%s: %s (History at %d)\nwant %s (History at %d)", c.name, got, at, c.want, c.at) + continue + } + for _, it := range items { + if it.Disabled { + t.Errorf("%s: %q is disabled", c.name, it.Label) + } + // The UI's submenus are shown as the UI gave them. + if it.Label == mounts.Label && render(it.Children) != render(mounts.Children) || + it.Label == serves.Label && render(it.Children) != render(serves.Children) { + t.Errorf("%s: %q has %s", c.name, it.Label, render(it.Children)) + } + } + } +} + +func TestLayoutActions(t *testing.T) { + var ran []string + a := Actions{ + ShowLauncher: func() { ran = append(ran, "launcher") }, + Open: func() { ran = append(ran, "open") }, + OpenWindow: func(url string) { ran = append(ran, url) }, + GitHub: func() { ran = append(ran, "github") }, + Quit: func() { ran = append(ran, "quit") }, + } + click := func(items []Item) string { + ran = nil + for _, it := range items { + if it.OnClick != nil { + it.OnClick() + } + } + return strings.Join(ran, ",") + } + items, _ := layout(state{transfers: "History (1 running)"}, a) + if got := click(items); got != "open,/history,/guides,github,quit" { + t.Errorf("the items ran %s", got) + } + a.Open = nil + items, _ = layout(state{}, a) + if got := click(items[:1]); got != "launcher" { + t.Errorf("Open without its own action ran %s", got) + } +} + +func TestDot(t *testing.T) { + for _, c := range []struct { + state state + want bool + }{ + {state{}, false}, + {state{running: []Item{mounts}}, false}, + {state{running: []Item{mounts, serves}}, false}, + {state{transfers: "History (1 running)"}, true}, + {state{transfers: "History (2 running · 27%)", running: []Item{mounts, serves}}, true}, + } { + if got := c.state.dot(); got != c.want { + t.Errorf("transfers %q, %d running items: dot %v, want %v", c.state.transfers, len(c.state.running), got, c.want) + } + } +} + +func TestEscapeMnemonics(t *testing.T) { + for _, c := range []struct{ label, goos, want string }{ + {"my_drive: → /mnt/my_drive", "linux", "my__drive: → /mnt/my__drive"}, + {"R&D: → R:", "windows", "R&&D: → R:"}, + {"R&D_x: → R:", "darwin", "R&D_x: → R:"}, + {"a&b_c", "linux", "a&b__c"}, + } { + if got := escapeMnemonics(c.label, c.goos); got != c.want { + t.Errorf("%q on %s: %q, want %q", c.label, c.goos, got, c.want) + } + } +} + +func TestIconFiles(t *testing.T) { + cases := []struct { + appearance, goos string + mint bool + light, dark string + template bool + }{ + {"system", "darwin", false, "icons/icon.png", "", true}, + {"system", "windows", false, "icons/icon-light.png", "icons/icon.png", false}, + {"system", "linux", true, "icons/icon-light-padded.png", "icons/icon-padded.png", false}, + {"color", "linux", true, "icons/icon-color-padded.png", "", false}, + {"color", "darwin", false, "icons/icon-color.png", "", false}, + {"dark", "windows", false, "icons/icon-light.png", "", false}, + {"light", "darwin", false, "icons/icon.png", "", true}, + } + for _, c := range cases { + light, dark, template := IconFiles(c.appearance, c.goos, c.mint) + if light != c.light || dark != c.dark || template != c.template { + t.Errorf("IconFiles(%q, %q, %v) = %q, %q, %v", c.appearance, c.goos, c.mint, light, dark, template) + } + for _, name := range []string{light, dark} { + if name != "" { + if _, err := icons.ReadFile(name); err != nil { + t.Errorf("icon %s not embedded: %v", name, err) + } + } + } + } +} + +func TestMarked(t *testing.T) { + for _, template := range []bool{false, true} { + src := mustIcon("icons/icon-color.png") + got, err := Marked(src, template) + if err != nil { + t.Fatal(err) + } + before, _ := png.Decode(bytes.NewReader(src)) + img, err := png.Decode(bytes.NewReader(got)) + if err != nil { + t.Fatal(err) + } + b := img.Bounds() + if b != before.Bounds() { + t.Fatalf("bounds %v, were %v", b, before.Bounds()) + } + size := float64(b.Dx()) + cx, cy := int(float64(b.Max.X)-size*0.28), int(size*0.28) + want := color.NRGBA{R: 0xff, G: 0x3b, B: 0x30, A: 0xff} + if template { + want = color.NRGBA{A: 0xff} + } + if c := color.NRGBAModel.Convert(img.At(cx, cy)).(color.NRGBA); c != want { + t.Errorf("template %v: the dot's middle is %v", template, c) + } + if _, _, _, a := img.At(cx-int(size*0.24), cy).RGBA(); a != 0 { + t.Errorf("template %v: the ring isn't clear", template) + } + if img.At(0, b.Max.Y-1) != before.At(0, b.Max.Y-1) || img.At(b.Dx()/3, b.Dy()*2/3) != before.At(b.Dx()/3, b.Dy()*2/3) { + t.Errorf("template %v: the glyph changed away from the corner", template) + } + } +} diff --git a/app/trayopen.go b/app/trayopen.go new file mode 100644 index 00000000..a45d659f --- /dev/null +++ b/app/trayopen.go @@ -0,0 +1,96 @@ +package app + +import ( + "context" + "encoding/json" + "runtime" + "slices" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/launcher" + "github.com/rclone/rclone-ui/core/i18n" +) + +// openShortcutAck is the acknowledgement that is recorded once the user has read the tip about the +// shortcut. It is stored in the pages' "acknowledgements" pref. +const openShortcutAck = "openShortcut" + +func (u *ui) trayOpen(ctx context.Context) { + if !u.acknowledged(ctx, openShortcutAck) { + shortcut := u.settings().General.LauncherShortcut + if shortcut == "" { + shortcut = launcher.DefaultShortcut + } + interaction.Show(interaction.Dialog{ + Kind: interaction.Info, + Title: i18n.T("Did you know?"), + Message: i18n.T("You can also open the Launcher using the shortcut %s.", shortcutLabel(shortcut, runtime.GOOS)), + OK: i18n.T("Good to know"), + }) + u.acknowledge(ctx, openShortcutAck) + } + u.launcher.Show() +} + +// shortcutLabel formats a shortcut the way the tip shows it, such as "Command + Shift + /". +func shortcutLabel(shortcut, goos string) string { + keys := strings.Split(shortcut, "+") + for i, k := range keys { + switch strings.ToLower(k) { + case "cmdorctrl", "commandorcontrol": + keys[i] = "Control" + if goos == "darwin" { + keys[i] = "Command" + } + case "cmd", "command", "super", "meta": + keys[i] = "Command" + case "ctrl", "control": + keys[i] = "Control" + case "alt", "option": + keys[i] = "Alt" + if goos == "darwin" { + keys[i] = "Option" + } + } + } + return strings.Join(keys, " + ") +} + +// acknowledgements returns the pages' list of hints that the user dismissed. It returns false +// when the list can't be read. +func (u *ui) acknowledgements(ctx context.Context) ([]string, bool) { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + values, err := u.apis.Prefs.Get(ctx, []string{"acknowledgements"}) + if err != nil { + u.log.Warn("could not read the acknowledgements", "error", err) + return nil, false + } + var list []string + if raw := values["acknowledgements"]; raw != "" { + _ = json.Unmarshal([]byte(raw), &list) + } + return list, true +} + +// acknowledged reports whether the hint was dismissed. If the list can't be read, the hint counts +// as dismissed, so that it doesn't come back on every Open. +func (u *ui) acknowledged(ctx context.Context, key string) bool { + list, ok := u.acknowledgements(ctx) + return !ok || slices.Contains(list, key) +} + +func (u *ui) acknowledge(ctx context.Context, key string) { + list, ok := u.acknowledgements(ctx) + if !ok || slices.Contains(list, key) { + return + } + raw, _ := json.Marshal(append(list, key)) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if err := u.apis.Prefs.Set(ctx, "acknowledgements", string(raw)); err != nil { + u.log.Warn("could not record an acknowledgement", "key", key, "error", err) + } +} diff --git a/app/trayrunning.go b/app/trayrunning.go new file mode 100644 index 00000000..44b269ef --- /dev/null +++ b/app/trayrunning.go @@ -0,0 +1,116 @@ +package app + +import ( + "context" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/launcher/engine" + "github.com/rclone/rclone-ui/app/tray" + "github.com/rclone/rclone-ui/core/children" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/rclone" + "github.com/rclone/rclone-ui/core/serves" +) + +// This file builds the tray's Mounts and Serves submenus, which list what the core is running +// (see showInTray). The UI owns these menus rather than a page, because the tray must stay up to +// date when no window is open. + +type runningAction func(ctx context.Context, c runningClients) error + +// runningItems builds the Mounts and Serves submenus, when any are running. Each item's action +// captures its row. do runs the action under a name that is used in the log. +func runningItems(ms []mounts.MountRow, ss []serves.ServeRow, do func(name string, a runningAction)) []tray.Item { + var items []tray.Item + if len(ms) > 0 { + var sub []tray.Item + for _, m := range ms { + label := m.Source + " → " + m.MountPoint + running := m.State == string(children.StatusRunning) + if !running { + // i18n: A mount or a serve in the tray menu that is still starting, as in "gdrive: → M: (starting)". + label = i18n.T("%s (starting)", label) + } + id, point := m.ID, m.MountPoint + sub = append(sub, tray.Item{Label: label, Children: []tray.Item{ + {Label: i18n.T("Open"), Disabled: !running, OnClick: func() { + do("open "+id, func(_ context.Context, c runningClients) error { return c.reveal(point) }) + }}, + {Label: i18n.T("Unmount"), OnClick: func() { + do("unmount "+id, func(ctx context.Context, c runningClients) error { return c.mounts.Stop(ctx, id) }) + }}, + }}) + } + if len(ms) > 1 { + sub = append(sub, tray.Item{Separator: true}, tray.Item{Label: i18n.T("Unmount All"), OnClick: func() { + do("unmount all", func(ctx context.Context, c runningClients) error { return c.mounts.StopAll(ctx) }) + }}) + } + // i18n: The tray menu's submenu of running mounts, with their number. + items = append(items, tray.Item{Label: i18n.T("Mounts (%d)", len(ms)), Children: sub}) + } + if len(ss) > 0 { + var sub []tray.Item + for _, v := range ss { + label := strings.ToUpper(v.Type) + " " + v.Addr + if v.State != string(children.StatusRunning) { + label = i18n.T("%s (starting)", label) + } + id, addr := v.ID, v.Addr + sub = append(sub, tray.Item{Label: label, Children: []tray.Item{ + {Label: i18n.T("Copy Address"), OnClick: func() { + do("copy "+id, func(_ context.Context, c runningClients) error { c.copy(addr); return nil }) + }}, + {Label: i18n.T("Stop"), OnClick: func() { + do("stop "+id, func(ctx context.Context, c runningClients) error { return c.serves.Stop(ctx, id) }) + }}, + }}) + } + if len(ss) > 1 { + sub = append(sub, tray.Item{Separator: true}, tray.Item{Label: i18n.T("Stop All"), OnClick: func() { + do("stop all", func(ctx context.Context, c runningClients) error { return c.serves.StopAll(ctx) }) + }}) + } + // i18n: The tray menu's submenu of running serves, with their number. + items = append(items, tray.Item{Label: i18n.T("Serves (%d)", len(ss)), Children: sub}) + } + return items +} + +type runningClients struct { + mounts engine.Stopper + serves engine.Stopper + reveal func(path string) error + copy func(text string) +} + +// runningAction runs a running item's action in the background, with a one-minute timeout, and +// shows any error. +func (u *ui) runningAction(name string, a runningAction) { + go func() { + err := func() error { + if u.theCore() == nil { + return errs.New("the core is not ready") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + return a(ctx, runningClients{ + mounts: u.apis.Mounts, + serves: u.apis.Serves, + reveal: func(path string) error { return u.reveal(path, false) }, + copy: func(text string) { + u.app.Clipboard.SetText(text) + u.notifier.send(i18n.T("Address Copied"), i18n.T("%s copied to clipboard", text)) + }, + }) + }() + if err != nil { + u.log.Error("tray action", "item", name, "error", err) + interaction.Message(interaction.Error, "Rclone UI", rclone.ErrorOf(err).Localized().Message) + } + }() +} diff --git a/app/trayrunning_test.go b/app/trayrunning_test.go new file mode 100644 index 00000000..3e91f3c9 --- /dev/null +++ b/app/trayrunning_test.go @@ -0,0 +1,69 @@ +package app + +import ( + "context" + "strings" + "testing" + + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/serves" +) + +func TestRunningItems(t *testing.T) { + none := func(string, runningAction) {} + if items := runningItems(nil, nil, none); len(items) != 0 { + t.Fatalf("nothing runs: %+v", items) + } + ms := []mounts.MountRow{ + {ID: "m1", Source: "gdrive:Photos", MountPoint: "/Volumes/Photos", State: "running"}, + {ID: "m2", Source: "box:", MountPoint: "/Volumes/box", State: "starting"}, + } + ss := []serves.ServeRow{{ID: "s1", Type: "webdav", Addr: "127.0.0.1:8080", State: "running"}} + var ran []string + items := runningItems(ms, ss, func(name string, _ runningAction) { ran = append(ran, name) }) + if len(items) != 2 || items[0].Label != "Mounts (2)" || items[1].Label != "Serves (1)" { + t.Fatalf("items %+v", items) + } + m := items[0].Children + if len(m) != 4 || m[0].Label != "gdrive:Photos → /Volumes/Photos" || m[1].Label != "box: → /Volumes/box (starting)" || + !m[2].Separator || m[3].Label != "Unmount All" { + t.Fatalf("mounts %+v", m) + } + if open := m[1].Children[0]; open.Label != "Open" || !open.Disabled { + t.Fatalf("a starting mount's Open %+v", open) + } + if m[0].Children[0].Disabled || m[0].Children[1].Label != "Unmount" { + t.Fatalf("a running mount's items %+v", m[0].Children) + } + var action runningAction + runningItems(ms, ss, func(_ string, a runningAction) { action = a })[0].Children[1].Children[0].OnClick() + var revealed string + _ = action(context.Background(), runningClients{reveal: func(p string) error { revealed = p; return nil }}) + if revealed != "/Volumes/box" { + t.Fatalf("Open revealed %q", revealed) + } + m[1].Children[0].OnClick() + m[3].OnClick() + s := items[1].Children + if len(s) != 1 || s[0].Label != "WEBDAV 127.0.0.1:8080" || s[0].Children[0].Label != "Copy Address" || s[0].Children[1].Label != "Stop" { + t.Fatalf("serves %+v", s) + } + s[0].Children[1].OnClick() + if got := strings.Join(ran, ","); got != "open m2,unmount all,stop s1" { + t.Fatalf("actions %s", got) + } +} + +func TestShortcutLabel(t *testing.T) { + for _, c := range []struct{ shortcut, goos, want string }{ + {"CmdOrCtrl+Shift+/", "darwin", "Command + Shift + /"}, + {"CmdOrCtrl+Shift+/", "windows", "Control + Shift + /"}, + {"Command+Shift+/", "darwin", "Command + Shift + /"}, + {"Ctrl+Alt+K", "linux", "Control + Alt + K"}, + {"Alt+Space", "darwin", "Option + Space"}, + } { + if got := shortcutLabel(c.shortcut, c.goos); got != c.want { + t.Errorf("%s on %s: %q, want %q", c.shortcut, c.goos, got, c.want) + } + } +} diff --git a/app/traystate.go b/app/traystate.go new file mode 100644 index 00000000..6c5c6aed --- /dev/null +++ b/app/traystate.go @@ -0,0 +1,60 @@ +package app + +import ( + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/rclone/rclone-ui/app/corestate" + "github.com/rclone/rclone-ui/app/menus" + "github.com/rclone/rclone-ui/core/bus" + "github.com/rclone/rclone-ui/core/i18n" +) + +// showInTray shows the core's state from the store in the tray: the Mounts and Serves submenus, +// and the History item and the dot on the tray icon, which both show only while the core runs +// transfers. The store calls it with the parts that changed. Each call reads the latest snapshot, +// so the tray ends up showing the latest state, and nothing once the core has stopped. +func (u *ui) showInTray(changed corestate.Part) { + s := u.store.Snapshot() + if changed&corestate.Running != 0 { + u.tray.SetRunning(runningItems(s.Mounts, s.Serves, u.runningAction)) + } + if changed&(corestate.Transfers|corestate.Progress) != 0 { + u.tray.SetTransfers(trayTransfersLabel(s.Live)) + } +} + +// languageChanged draws again, in the new language, everything that the Go side keeps on screen: +// the tray's menu, the menu bar and the launcher. The windows follow the setting themselves +// (lib/i18n.ts). Dialogs and toasts are translated as they show. +func (u *ui) languageChanged() { + s := u.store.Snapshot() + u.tray.SetTransfers(trayTransfersLabel(s.Live)) + // SetRunning builds the menu again, with its own labels in the new language. + u.tray.SetRunning(runningItems(s.Mounts, s.Serves, u.runningAction)) + // AppKit builds the menu bar on the main thread. + application.InvokeAsync(func() { menus.Set(u.app) }) + u.launcher.LanguageChanged() +} + +// trayTransfersLabel returns the label of the History item for the running transfers, keyed by +// ID, such as "History (2 running · 42%)". It returns "" when none is running, which hides the +// item and the icon's dot. A watcher's runs are left out, because they run every minute and would +// make History and the dot come and go. +func trayTransfersLabel(items map[string]bus.TransferProgress) string { + ps := make([]*bus.TransferProgress, 0, len(items)) + for _, p := range items { + if !p.Watcher { + ps = append(ps, &p) + } + } + p := corestate.SumProgress(ps) + switch { + case p.Running == 0: + return "" + case p.Pct < 0: + // i18n: The tray menu's History item while transfers run, with their number. + return i18n.T("History (%d running)", p.Running) + } + // i18n: The tray menu's History item while transfers run: their number, and how far along they are. + return i18n.T("History (%d running · %d%%)", p.Running, p.Pct) +} diff --git a/app/traystate_test.go b/app/traystate_test.go new file mode 100644 index 00000000..e42ee9fd --- /dev/null +++ b/app/traystate_test.go @@ -0,0 +1,26 @@ +package app + +import ( + "testing" + + "github.com/rclone/rclone-ui/core/bus" +) + +func TestTrayTransfersLabel(t *testing.T) { + for _, c := range []struct { + items map[string]bus.TransferProgress + want string + }{ + {nil, ""}, + {map[string]bus.TransferProgress{"t1": {Bytes: 42, TotalBytes: 100}}, "History (1 running · 42%)"}, + {map[string]bus.TransferProgress{"t1": {Bytes: 10, TotalBytes: 100}, "t2": {Bytes: 290, TotalBytes: 300}}, "History (2 running · 75%)"}, + {map[string]bus.TransferProgress{"t1": {}}, "History (1 running)"}, + // A watcher's runs are left out. + {map[string]bus.TransferProgress{"t1": {Bytes: 42, TotalBytes: 100}, "w": {Bytes: 0, TotalBytes: 100, Watcher: true}}, "History (1 running · 42%)"}, + {map[string]bus.TransferProgress{"w": {Watcher: true}}, ""}, + } { + if got := trayTransfersLabel(c.items); got != c.want { + t.Errorf("%v: %q, want %q", c.items, got, c.want) + } + } +} diff --git a/app/update/cli.go b/app/update/cli.go new file mode 100644 index 00000000..0d6da2ce --- /dev/null +++ b/app/update/cli.go @@ -0,0 +1,386 @@ +package update + +import ( + "context" + _ "embed" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/spf13/cobra" + "golang.org/x/term" + + "github.com/rclone/rclone-ui/core/version" +) + +//go:embed update.md +var updateHelp string + +// Exit codes, the same as rclone's: 1 for a failure and 2 for a usage error. +const ( + exitError = 1 + exitUsage = 2 +) + +// Install adds `update` to rclone's root command. It updates Rclone UI, which includes its rclone. +// If the build includes rclone's own `selfupdate` (a build without -tags noselfupdate), it is +// replaced by a note that points to `update`, because it would put official rclone in place of +// rcui. `version --check` reads Rclone UI's feed. +func Install(root *cobra.Command) { + c := &cli{ + out: os.Stdout, + errOut: os.Stderr, + appRunning: appRunning, + handOff: handOff, + name: invokedAs(os.Args[0]), + terminal: term.IsTerminal(int(os.Stdout.Fd())), + } + c.install(root) +} + +type cli struct { + out, errOut io.Writer + // engine holds the base options for every Engine the commands create. Tests use it to set + // the feeds and keys. + engine Options + // appRunning reports whether the app is running, and handOff passes the update to it. + appRunning func() bool + handOff func(ctx context.Context, version string, ch Channel) error + // name is the command the user typed ("rcui" or "rclone"), used in the hints. + name string + // terminal means stdout is a terminal, so progress redraws a single line. + terminal bool +} + +// install replaces any selfupdate command, and any update command that an earlier install added. +// (rclone has no update command of its own, which main_test.go checks.) +func (c *cli) install(root *cobra.Command) { + for _, cmd := range root.Commands() { + if cmd.Name() == "selfupdate" || cmd.Name() == "update" { + root.RemoveCommand(cmd) + } + } + root.AddCommand(c.updateCommand(), c.selfUpdateCommand()) + c.wrapVersionCheck(root) +} + +func invokedAs(argv0 string) string { + name := filepath.Base(argv0) + if n, ok := strings.CutSuffix(strings.ToLower(name), ".exe"); ok { + name = name[:len(n)] + } + if name == "" || name == "." { + return "rcui" + } + return name +} + +// updateFlags are the same flags as rclone's selfupdate, with the same names and meanings. +type updateFlags struct { + check bool + output string + stable bool + beta bool + version string + pkg string +} + +func (c *cli) updateCommand() *cobra.Command { + var f updateFlags + cmd := &cobra.Command{ + Use: "update", + Short: "Update Rclone UI, and the rclone it brings.", + Long: strings.TrimSpace(updateHelp), + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + if code := c.update(commandContext(cmd), f); code != 0 { + os.Exit(code) + } + }, + } + fl := cmd.Flags() + fl.BoolVar(&f.check, "check", false, "Check for the latest release, do not download") + fl.StringVar(&f.output, "output", "", "Save the downloaded release at a given path (default: install it)") + fl.BoolVar(&f.stable, "stable", false, "Install the stable release (this is the default)") + fl.BoolVar(&f.beta, "beta", false, "Install the beta release") + fl.StringVar(&f.version, "version", "", "Install the given Rclone UI version (default: latest)") + fl.StringVar(&f.pkg, "package", "", "Package format: zip|deb|rpm (default: zip, this install's own)") + return cmd +} + +const selfUpdateNote = "rclone is part of Rclone UI here, so it is updated with the whole app: run `rcui update`, or `rclone update` through the rclone link on your PATH." + +// selfUpdateCommand replaces rclone's `selfupdate` for users who type it. It explains how to +// update and does nothing else, whatever flags it is given. +func (c *cli) selfUpdateCommand() *cobra.Command { + return &cobra.Command{ + Use: "selfupdate", + Aliases: []string{"self-update"}, + Short: "rclone comes with Rclone UI: see update.", + Long: selfUpdateNote, + DisableFlagParsing: true, + Run: func(*cobra.Command, []string) { + fmt.Fprintln(c.out, selfUpdateNote) + }, + } +} + +func commandContext(cmd *cobra.Command) context.Context { + if ctx := cmd.Context(); ctx != nil { + return ctx + } + return context.Background() +} + +func (c *cli) update(ctx context.Context, f updateFlags) int { + if f.stable && f.beta { + return c.usage("--stable and --beta are mutually exclusive") + } + if err := CheckVersion(f.version); errors.Is(err, ErrBadVersion) { + return c.usage("--version: " + err.Error()) + } else if err != nil { + return c.fail(err) + } + switch f.pkg { + case "", "zip": + f.pkg = "" + case "deb", "rpm": + if runtime.GOOS != "linux" { + return c.usage(errPackageNotLinux.Error()) + } + default: + return c.usage(errPackageValue.Error()) + } + if f.check && !(f.stable || f.beta || f.output != "" || f.version != "" || f.pkg != "") { + c.printVersions(ctx) + return 0 + } + + ch := Stable + if f.beta { + ch = Beta + } + opts := c.engine + opts.Channel, opts.Version, opts.Package = ch, f.version, f.pkg + opts.Terminal, opts.NoRelaunch = true, true + e := New(opts) + + rel, err := e.Check(ctx) + if err != nil { + return c.fail(err) + } + // A portable copy doesn't update itself, and neither does the app that runs from it, so the + // command shows where to download the release instead. --output still downloads. + portable := e.InstallType() == TypePortable && f.output == "" + if f.check && portable { + c.downloadPage(c.out, rel) + return 0 + } + if f.check { + where := f.output + if where == "" { + where = e.InstallLocation() + } + fmt.Fprintf(c.out, "Without --check this would install Rclone UI %s at %s\n", rel.Describe(), where) + return 0 + } + if f.output != "" { + art, err := c.download(ctx, e, rel) + if err != nil { + return c.fail(err) + } + dst, err := art.SaveAs(f.output) + if err != nil { + art.Remove() + return c.fail(err) + } + fmt.Fprintf(c.out, "Downloaded Rclone UI %s at %s\n", rel.Describe(), dst) + return 0 + } + if rel.Same() { + fmt.Fprintf(c.out, "Rclone UI %s is up to date.\n", Describe(e.CurrentVersion(), version.Rclone())) + return 0 + } + if portable { + c.downloadPage(c.errOut, rel) + return exitError + } + + // A running app updates itself, because it stops its transfers, mounts and serves first, and + // on Windows nothing may keep rcui.exe open. It is passed the release announced here, rather + // than its own channel's latest, which may be a different one. + if c.appRunning() { + if err := c.handOff(ctx, rel.Version, ch); err == nil { + fmt.Fprintf(c.out, "Rclone UI is running; it will ask you to confirm the update to %s, then restart.\n", rel.Describe()) + return 0 + } + } + + if err := e.installable(rel.Kind); err != nil { + if errors.Is(err, ErrCantSelfUpdate) { + _, why := e.CanSelfUpdate() + fmt.Fprintln(c.errOut, why) + if e.InstallType() == TypeUnmanaged { + fmt.Fprintf(c.errOut, "`%s update --output PATH` downloads it.\n", c.name) + } + return exitError + } + return c.fail(err) + } + + note := "" + if !rel.Newer() { + note = " (an older release)" + } + fmt.Fprintf(c.out, "Updating Rclone UI %s → %s%s\n", e.CurrentVersion(), rel.Describe(), note) + art, err := c.download(ctx, e, rel) + if err != nil { + return c.fail(err) + } + if _, err := e.Install(ctx, art); err != nil { + art.Remove() + return c.fail(err) + } + if art.Kind == KindNSIS { + // Keep the file, because the installer reads it after this process exits. + fmt.Fprintf(c.out, "The Rclone UI %s installer is running; it finishes once this command exits.\n", rel.Version) + return 0 + } + art.Remove() + fmt.Fprintf(c.out, "Updated Rclone UI from %s to %s.\n", e.CurrentVersion(), rel.Describe()) + return 0 +} + +// download fetches the artifact and shows progress on stdout: one redrawn line on a terminal, or +// a summary otherwise. The engine throttles the progress calls. +func (c *cli) download(ctx context.Context, e *Engine, rel *Release) (*Artifact, error) { + var size int64 + progress := func(done, total int64) { + size = done + if !c.terminal { + return + } + if total > 0 { + fmt.Fprintf(c.out, "\rDownloading %3d%% (%s of %s)", done*100/total, megabytes(done), megabytes(total)) + } else { + fmt.Fprintf(c.out, "\rDownloading %s", megabytes(done)) + } + } + art, err := e.Download(ctx, rel, progress) + if c.terminal { + fmt.Fprintln(c.out) + } + if err != nil { + return nil, err + } + fmt.Fprintf(c.out, "Downloaded %s.\n", megabytes(size)) + return art, nil +} + +func megabytes(n int64) string { return fmt.Sprintf("%.1f MB", float64(n)/1e6) } + +func (c *cli) downloadPage(w io.Writer, rel *Release) { + fmt.Fprintln(w, PortableNote) + fmt.Fprintf(w, "Rclone UI %s is on its release page: %s\n", rel.Describe(), ReleasePage(rel.Version)) +} + +// printVersions runs `update --check` and `version --check`. It prints this version and the +// latest on each channel, in the layout of rclone's `version --check`. A portable copy is marked +// on the first line. +func (c *cli) printVersions(ctx context.Context) { + e := New(c.engine) + current := e.CurrentVersion() + mark := "" + if e.InstallType() == TypePortable { + mark = " (portable)" + } + fmt.Fprintf(c.out, "%-8sRclone UI %s%s\n", "yours:", Describe(current, version.Rclone()), mark) + for _, ch := range []Channel{Stable, Beta} { + c.printLatest(ctx, e, ch, current) + } + if compareVersions(current, "0.0.0") < 0 { + fmt.Fprintln(c.out, "Your version is a development build, so comparisons may be wrong.") + } +} + +// printLatest prints printVersions' line for one channel. Each channel gets its own checkTimeout. +// A newer release gets a line on how to upgrade: the command, or the release's page for a portable +// copy, as rclone's own `version --check` gives a URL. +func (c *cli) printLatest(ctx context.Context, e *Engine, ch Channel, current string) { + label, flag := "latest", "" + if ch == Beta { + label, flag = "beta", " --beta" + } + ctx, cancel := withCheckTimeout(ctx) + defer cancel() + f, err := e.latest(ctx, ch) + if errors.Is(err, ErrNoRelease) { + fmt.Fprintf(c.out, "%-8s%v\n", label+":", err) + return + } + if err != nil { + fmt.Fprintf(c.errOut, "Failed to get the Rclone UI %s version: %v\n", label, feedTimedOut(ctx, err)) + return + } + released := "" + if t, err := time.Parse(time.RFC3339, f.Release.Date); err == nil { + released = "(released " + t.Format("2006-01-02") + ")" + } + fmt.Fprintf(c.out, "%-8s%-40s %20s\n", label+":", "Rclone UI "+Describe(f.Release.Version, f.Rclone), released) + switch { + case compareVersions(f.Release.Version, current) <= 0: + case e.InstallType() == TypePortable: + fmt.Fprintf(c.out, " upgrade: %s\n", ReleasePage(f.Release.Version)) + default: + fmt.Fprintf(c.out, " upgrade: %s update%s\n", c.name, flag) + } +} + +// wrapVersionCheck makes `version --check` print Rclone UI's versions. `version` alone and +// `version --deps` still run rclone's code. +func (c *cli) wrapVersionCheck(root *cobra.Command) { + for _, cmd := range root.Commands() { + if cmd.Name() != "version" || cmd.Annotations["rcui-check"] != "" { + continue + } + run, runE := cmd.Run, cmd.RunE + cmd.Run = nil + cmd.RunE = func(cmd *cobra.Command, args []string) error { + check, _ := cmd.Flags().GetBool("check") + deps, _ := cmd.Flags().GetBool("deps") + if check && !deps && len(args) == 0 { + c.printVersions(commandContext(cmd)) + return nil + } + if runE != nil { + return runE(cmd, args) + } + if run != nil { + run(cmd, args) + } + return nil + } + if f := cmd.Flags().Lookup("check"); f != nil { + f.Usage = "Check for a newer Rclone UI (it brings its rclone)" + } + if cmd.Annotations == nil { + cmd.Annotations = map[string]string{} + } + cmd.Annotations["rcui-check"] = "wrapped" + } +} + +func (c *cli) usage(msg string) int { + fmt.Fprintln(c.errOut, "Error:", msg) + return exitUsage +} + +func (c *cli) fail(err error) int { + fmt.Fprintln(c.errOut, "Error:", err) + return exitError +} diff --git a/app/update/cli_test.go b/app/update/cli_test.go new file mode 100644 index 00000000..0cfc5bc7 --- /dev/null +++ b/app/update/cli_test.go @@ -0,0 +1,394 @@ +package update + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// testCLI returns the command set up against a fake feed, with no app running unless appRunning +// says so. +func testCLI(t *testing.T, f *feed, current string) (*cli, *bytes.Buffer, *bytes.Buffer) { + var out, errOut bytes.Buffer + return &cli{ + out: &out, + errOut: &errOut, + engine: f.options(t, current), + appRunning: func() bool { return false }, + handOff: func(context.Context, string, Channel) error { return errors.New("no app runs") }, + name: "rclone", + }, &out, &errOut +} + +// run parses args the way the update command would, and runs it. +func (c *cli) run(t *testing.T, args ...string) int { + t.Helper() + cmd := c.updateCommand() + var code int + cmd.Run = nil + cmd.RunE = func(*cobra.Command, []string) error { return nil } + if err := cmd.ParseFlags(args); err != nil { + t.Fatal(err) + } + fl := cmd.Flags() + var f updateFlags + f.check, _ = fl.GetBool("check") + f.output, _ = fl.GetString("output") + f.stable, _ = fl.GetBool("stable") + f.beta, _ = fl.GetBool("beta") + f.version, _ = fl.GetString("version") + f.pkg, _ = fl.GetString("package") + code = c.update(context.Background(), f) + return code +} + +func TestUpdateFlags(t *testing.T) { + f := newFeed(t) + c, _, errOut := testCLI(t, f, "4.0.1") + if code := c.run(t, "--stable", "--beta"); code != exitUsage || !strings.Contains(errOut.String(), "mutually exclusive") { + t.Errorf("--stable --beta: %d %q", code, errOut) + } + errOut.Reset() + if code := c.run(t, "--package", "msi"); code != exitUsage || !strings.Contains(errOut.String(), "zip|deb|rpm") { + t.Errorf("--package msi: %d %q", code, errOut) + } + if runtime.GOOS != "linux" { + errOut.Reset() + if code := c.run(t, "--package", "deb"); code != exitUsage || !strings.Contains(errOut.String(), "only on Linux") { + t.Errorf("--package deb: %d %q", code, errOut) + } + } + // The flags have the same names as rclone's selfupdate flags. + cmd := c.updateCommand() + for _, name := range []string{"check", "output", "stable", "beta", "version", "package"} { + if cmd.Flags().Lookup(name) == nil { + t.Errorf("no --%s", name) + } + } + if cmd.Name() != "update" || len(cmd.Aliases) != 0 { + t.Errorf("the command is %q, aliases %v", cmd.Name(), cmd.Aliases) + } + if !strings.Contains(cmd.Long, "Rclone UI") { + t.Error("the help isn't Rclone UI's") + } +} + +func TestUpdateVersionRefused(t *testing.T) { + f := newFeed(t) + c, out, errOut := testCLI(t, f, "4.0.1") + for _, tc := range []struct { + version string + code int + said string + }{ + {"3.7.5", exitError, "Rclone UI 3.7.5: no such release"}, + {"4.0", exitUsage, `"4.0" is not an Rclone UI version`}, + {"../../latest/download/x", exitUsage, "is not an Rclone UI version"}, + {"4.0.0/../../3.7.5", exitUsage, "is not an Rclone UI version"}, + } { + out.Reset() + errOut.Reset() + if code := c.run(t, "--version", tc.version, "--output", t.TempDir()); code != tc.code || !strings.Contains(errOut.String(), tc.said) { + t.Errorf("--version %s: %d %q, want %d %q", tc.version, code, errOut, tc.code, tc.said) + } + if out.Len() != 0 { + t.Errorf("--version %s said %q", tc.version, out) + } + } + if f.downloads.Load() != 0 { + t.Error("a refused version was downloaded") + } +} + +func TestUpdateBeforeTheFirstStableRelease(t *testing.T) { + _, kind := nativeType() + f := newFeed(t) + f.beta = f.release("4.0.0-beta.2", "v1.76.2", kind, artifactBytes(kind)) + c, out, errOut := testCLI(t, f, "4.0.0-beta.1") + if code := c.run(t, "--check"); code != 0 { + t.Fatalf("--check: %d %q", code, errOut) + } + for _, want := range []string{"yours: Rclone UI 4.0.0-beta.1", "latest: no stable release of Rclone UI yet", "beta: Rclone UI 4.0.0-beta.2"} { + if !strings.Contains(out.String(), want) { + t.Errorf("--check lacks %q:\n%s", want, out) + } + } + if errOut.Len() != 0 { + t.Errorf("--check failed: %q", errOut) + } + errOut.Reset() + if code := c.run(t, "--check", "--stable"); code != exitError || !strings.Contains(errOut.String(), "Error: no stable release of Rclone UI yet") { + t.Errorf("--check --stable: %d %q", code, errOut) + } +} + +func TestSelfUpdateOnlySays(t *testing.T) { + f := newFeed(t) + _, kind := nativeType() + f.stable = f.release("4.0.2", "", kind, artifactBytes(kind)) + c, out, errOut := testCLI(t, f, "4.0.1") + root := &cobra.Command{Use: "rclone"} + c.install(root) + for _, args := range [][]string{{"selfupdate"}, {"self-update", "--beta", "--version", "4.0.2"}, {"selfupdate", "--check"}} { + out.Reset() + root.SetArgs(args) + if err := root.Execute(); err != nil { + t.Fatalf("%v: %v", args, err) + } + if got := out.String(); got != selfUpdateNote+"\n" { + t.Errorf("%v said %q", args, got) + } + } + if errOut.Len() != 0 || f.downloads.Load() != 0 { + t.Errorf("selfupdate did more: %q, %d downloads", errOut, f.downloads.Load()) + } + for _, want := range []string{"rcui update", "rclone update"} { + if !strings.Contains(selfUpdateNote, want) { + t.Errorf("the note doesn't name %s", want) + } + } +} + +func TestUpdateCheck(t *testing.T) { + _, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + f.beta = f.release("4.1.0-beta.1", "v1.77.0", kind, artifactBytes(kind)) + c, out, _ := testCLI(t, f, "4.0.1") + if code := c.run(t, "--check"); code != 0 { + t.Fatalf("--check = %d", code) + } + for _, want := range []string{ + "yours: Rclone UI 4.0.1 (rclone ", + "latest: Rclone UI 4.0.2 (rclone v1.76.2)", + "(released 2026-10-01)", + "upgrade: rclone update\n", + "beta: Rclone UI 4.1.0-beta.1 (rclone v1.77.0)", + "upgrade: rclone update --beta", + } { + if !strings.Contains(out.String(), want) { + t.Errorf("--check output lacks %q:\n%s", want, out) + } + } + if f.downloads.Load() != 0 { + t.Error("--check downloaded") + } + + // With an action flag, --check reports what it would install. + out.Reset() + f.releases["4.0.0"] = f.release("4.0.0", "v1.75.1", kind, artifactBytes(kind)) + if code := c.run(t, "--check", "--version", "4.0.0"); code != 0 { + t.Fatalf("--check --version = %d", code) + } + if !strings.Contains(out.String(), "Without --check this would install Rclone UI 4.0.0 (rclone v1.75.1) at ") { + t.Errorf("--check --version said %q", out) + } +} + +func TestUpdateOutput(t *testing.T) { + _, kind := nativeType() + f := newFeed(t) + content := artifactBytes(kind) + f.stable = f.release("4.0.2", "v1.76.2", kind, content) + c, out, errOut := testCLI(t, f, "4.0.1") + dst := filepath.Join(t.TempDir(), "rcui-update") + if code := c.run(t, "--output", dst); code != 0 { + t.Fatalf("--output = %d: %s", code, errOut) + } + if b, err := os.ReadFile(dst); err != nil || !bytes.Equal(b, content) { + t.Errorf("--output wrote %d bytes, %v", len(b), err) + } + if !strings.Contains(out.String(), "Downloaded Rclone UI 4.0.2 (rclone v1.76.2) at "+dst) { + t.Errorf("--output said %q", out) + } +} + +func TestUpdateUpToDate(t *testing.T) { + _, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + c, out, _ := testCLI(t, f, "v4.0.2") + if code := c.run(t); code != 0 || !strings.Contains(out.String(), "is up to date") { + t.Errorf("up to date: %d %q", code, out) + } +} + +func TestUpdateHandsOffToTheApp(t *testing.T) { + _, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + f.beta = f.release("4.1.0-beta.1", "v1.77.0", kind, artifactBytes(kind)) + + c, out, _ := testCLI(t, f, "4.0.1") + c.appRunning = func() bool { return true } + var gotVersion string + var gotChannel Channel + c.handOff = func(_ context.Context, version string, ch Channel) error { + gotVersion, gotChannel = version, ch + return nil + } + // The app is passed the release that the command announced, and the command's channel. + for _, h := range []struct { + flags []string + version string + channel Channel + said string + }{ + {[]string{"--beta"}, "4.1.0-beta.1", "beta", "Rclone UI is running; it will ask you to confirm the update to 4.1.0-beta.1 (rclone v1.77.0), then restart.\n"}, + {nil, "4.0.2", "stable", "Rclone UI is running; it will ask you to confirm the update to 4.0.2 (rclone v1.76.2), then restart.\n"}, + } { + out.Reset() + if code := c.run(t, h.flags...); code != 0 { + t.Fatalf("hand-off %v = %d", h.flags, code) + } + if out.String() != h.said { + t.Errorf("hand-off %v said %q, want %q", h.flags, out, h.said) + } + if gotVersion != h.version || gotChannel != h.channel { + t.Errorf("hand-off %v: the app got %q on %q", h.flags, gotVersion, gotChannel) + } + } + if f.downloads.Load() != 0 { + t.Error("the command downloaded although the app updates") + } + + // A failed hand-off doesn't stop the command, which continues by itself. Here it refuses to + // replace the test binary, because no installer placed it. + c.handOff = func(context.Context, string, Channel) error { return errors.New("the app didn't answer") } + out.Reset() + var errOut bytes.Buffer + c.errOut = &errOut + if code := c.run(t); code != exitError || !strings.Contains(errOut.String(), "No installer put") { + t.Errorf("not handled: %d %q %q", code, out, errOut.String()) + } + if !strings.Contains(errOut.String(), "rclone update --output PATH") { + t.Errorf("no --output hint: %q", errOut.String()) + } +} + +func TestUpdatePortable(t *testing.T) { + _, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + c, out, errOut := testCLI(t, f, "4.0.1") + c.engine.Installed = TypePortable + handed := false + c.appRunning = func() bool { return true } + c.handOff = func(context.Context, string, Channel) error { handed = true; return nil } + page := "https://github.com/rclone/rclone-ui/releases/tag/v4.0.2" + + if code := c.run(t, "--check"); code != 0 { + t.Fatalf("--check = %d", code) + } + for _, want := range []string{"yours: Rclone UI 4.0.1 (rclone ", ") (portable)\n", "upgrade: " + page + "\n"} { + if !strings.Contains(out.String(), want) { + t.Errorf("--check output lacks %q:\n%s", want, out) + } + } + if strings.Contains(out.String(), "rclone update") { + t.Errorf("--check offers the update command:\n%s", out) + } + + out.Reset() + if code := c.run(t, "--check", "--stable"); code != 0 || !strings.Contains(out.String(), page) { + t.Errorf("--check --stable: %d %q", code, out) + } + + out.Reset() + errOut.Reset() + if code := c.run(t); code != exitError { + t.Errorf("update = %d, want %d", code, exitError) + } + for _, want := range []string{PortableNote, "Rclone UI 4.0.2 (rclone v1.76.2) is on its release page: " + page} { + if !strings.Contains(errOut.String(), want) { + t.Errorf("update lacks %q:\n%s", want, errOut) + } + } + if handed || f.downloads.Load() != 0 { + t.Errorf("handed off %v, %d downloads", handed, f.downloads.Load()) + } + + // --output still downloads the release. + dst := filepath.Join(t.TempDir(), "rcui-update") + if code := c.run(t, "--output", dst); code != 0 || f.downloads.Load() != 1 { + t.Errorf("--output = %d, %d downloads: %s", code, f.downloads.Load(), errOut) + } +} + +func TestInstallCommands(t *testing.T) { + root := &cobra.Command{Use: "rclone"} + rcloneOwn := &cobra.Command{Use: "selfupdate", Short: "Update the rclone binary.", Run: func(*cobra.Command, []string) {}} + var versionRan, versionChecked bool + versionCmd := &cobra.Command{Use: "version", RunE: func(cmd *cobra.Command, _ []string) error { + versionRan = true + versionChecked, _ = cmd.Flags().GetBool("check") + return nil + }} + versionCmd.Flags().Bool("check", false, "Check for new version") + versionCmd.Flags().Bool("deps", false, "Show the Go dependencies") + root.AddCommand(rcloneOwn, versionCmd) + + f := newFeed(t) + _, kind := nativeType() + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + c, out, _ := testCLI(t, f, "4.0.1") + c.install(root) + c.install(root) // installing twice has the same effect as once + + // There is one update command (this app's), and one selfupdate command (the note that replaces + // rclone's). + named := map[string][]*cobra.Command{} + for _, cmd := range root.Commands() { + named[cmd.Name()] = append(named[cmd.Name()], cmd) + } + if s := named["selfupdate"]; len(s) != 1 || s[0] == rcloneOwn || s[0].Long != selfUpdateNote { + t.Fatalf("selfupdate commands: %d, rclone's still there: %v", len(s), len(s) > 0 && s[0] == rcloneOwn) + } + if u := named["update"]; len(u) != 1 || u[0].Flags().Lookup("version") == nil { + t.Fatalf("update commands: %d", len(u)) + } + + root.SetArgs([]string{"version", "--check"}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + if versionRan || !strings.Contains(out.String(), "latest: Rclone UI 4.0.2 (rclone v1.76.2)") { + t.Errorf("version --check: rclone's ran %v, output %q", versionRan, out) + } + // cobra keeps flag values between runs, so reset --check. + _ = versionCmd.Flags().Set("check", "false") + root.SetArgs([]string{"version"}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + if !versionRan || versionChecked { + t.Error("version alone isn't rclone's") + } + if !strings.Contains(versionCmd.Flags().Lookup("check").Usage, "Rclone UI") { + t.Error("version --check's help isn't Rclone UI's") + } +} + +func TestInvokedAs(t *testing.T) { + for in, want := range map[string]string{ + "/usr/local/bin/rclone": "rclone", + `C:\Program Files\Rclone UI\rcui.exe`: "rcui", + "/Applications/Rclone UI.app/Contents/MacOS/rcui": "rcui", + `C:\Users\me\AppData\Local\Rclone UI\bin\RCLONE.EXE`: "RCLONE", + } { + // filepath.Base only splits on the host OS's separator. + if runtime.GOOS != "windows" && strings.Contains(in, `\`) { + continue + } + if got := invokedAs(in); got != want { + t.Errorf("invokedAs(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/app/update/download.go b/app/update/download.go new file mode 100644 index 00000000..637d0295 --- /dev/null +++ b/app/update/download.go @@ -0,0 +1,285 @@ +package update + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/rclone/rclone-ui/core/errs" +) + +// Artifact is a downloaded release artifact. +type Artifact struct { + // Path is the file. It stays in the engine's staging folder until SaveAs moves it. + Path string + Kind Kind + Release *Release +} + +// Download fetches rel's artifact into the staging folder, and checks that it arrived whole and +// is the kind the feed says. progress, when not nil, is called at the start, at most every 100 ms +// as bytes arrive, and once the last byte is in. total is -1 when the server doesn't send a +// length. A download that receives nothing for stallTimeout fails. +func (e *Engine) Download(ctx context.Context, rel *Release, progress func(done, total int64)) (*Artifact, error) { + if rel == nil || rel.URL == "" { + return nil, ErrNoArtifact + } + dir, err := e.stagingDir(rel.Version) + if err != nil { + return nil, err + } + name := artifactName(rel) + dst := filepath.Join(dir, name) + if err := e.get(ctx, rel.URL, dst, progress); err != nil { + _ = os.RemoveAll(dir) + return nil, err + } + if err := checkKind(dst, rel.Kind); err != nil { + _ = os.RemoveAll(dir) + return nil, err + } + return &Artifact{Path: dst, Kind: rel.Kind, Release: rel}, nil +} + +// stagingDir makes a new folder for one download, private to this user. It always creates a new +// folder and never reuses an existing one. In a shared temp folder (like /tmp on Linux), a folder +// that another user (or root, after `sudo rcui update`) created first would block the update, or +// let them swap the downloaded file before it is installed. +func (e *Engine) stagingDir(version string) (string, error) { + dir, err := os.MkdirTemp(e.opts.StagingDir, "rcui-update-"+safeName(version)+"-") + if err != nil { + return "", errs.Errorf("could not create the download folder: %w", err) + } + return dir, nil +} + +// stallTimeout is how long a download may receive nothing before it fails. It is a variable so +// that tests can change it. Without it, a server that stops sending would keep the update at +// "downloading" forever. +var stallTimeout = time.Minute + +// errStalled is the error for a download that received nothing for stallTimeout. +var errStalled = errs.New("the server sent nothing for a minute") + +// get streams url into dst, and fails unless every byte the server announced arrived. +func (e *Engine) get(ctx context.Context, url, dst string, progress func(done, total int64)) (err error) { + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + stall := time.AfterFunc(stallTimeout, func() { cancel(errStalled) }) + defer stall.Stop() + defer func() { + if err != nil && errors.Is(context.Cause(ctx), errStalled) { + err = errs.Errorf("download failed: %w", errStalled) + } + }() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + req.Header.Set("User-Agent", userAgent(e.opts.CurrentVersion)) + resp, err := e.opts.HTTPClient.Do(req) + if err != nil { + return errs.Errorf("download failed: %w", err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return errs.Errorf("download failed: the server answered %s", resp.Status) + } + + f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + defer func() { + if cerr := f.Close(); err == nil { + err = cerr + } + }() + var w io.Writer = f + if progress != nil { + progress(0, resp.ContentLength) + w = io.MultiWriter(w, &progressWriter{total: resp.ContentLength, fn: progress, last: time.Now()}) + } + n, err := io.Copy(w, &stallReader{r: resp.Body, timer: stall}) + if err != nil { + return errs.Errorf("download failed: %w", err) + } + if progress != nil { + // The throttled reports may have left out the last bytes. + progress(n, resp.ContentLength) + } + if resp.ContentLength >= 0 && n != resp.ContentLength { + return errs.Errorf("download failed: got %d of %d bytes", n, resp.ContentLength) + } + return f.Sync() +} + +// stallReader restarts the stall timer whenever bytes arrive. +type stallReader struct { + r io.Reader + timer *time.Timer +} + +func (s *stallReader) Read(p []byte) (int, error) { + n, err := s.r.Read(p) + if n > 0 { + s.timer.Reset(stallTimeout) + } + return n, err +} + +// progressEvery is how often a download reports its progress. io.Copy writes every 32 KB, and +// each report becomes an event sent to every window. +const progressEvery = 100 * time.Millisecond + +// progressWriter reports the bytes written to it, at most once every progressEvery. +type progressWriter struct { + done, total int64 + last time.Time + fn func(done, total int64) +} + +func (p *progressWriter) Write(b []byte) (int, error) { + p.done += int64(len(b)) + if now := time.Now(); now.Sub(p.last) >= progressEvery { + p.last = now + p.fn(p.done, p.total) + } + return len(b), nil +} + +// urlFileName returns the file name at the end of a URL ("Rclone-UI-4.0.0-macos-arm64.app.tar.gz"), or "" +// when the URL doesn't parse. +func urlFileName(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + name, _ := url.PathUnescape(path.Base(u.Path)) + return name +} + +// artifactName returns the artifact's file name from its URL, made safe to store under. +func artifactName(rel *Release) string { + name := safeName(urlFileName(rel.URL)) + if name == "" || name == "." { + name = "rclone-ui-" + safeName(rel.Version) + map[Kind]string{ + KindApp: ".app.tar.gz", KindNSIS: "-setup.exe", KindAppImage: ".AppImage", KindDeb: ".deb", KindRPM: ".rpm", + }[rel.Kind] + } + return name +} + +// safeName makes sure a file name is a single path element. +func safeName(s string) string { + return strings.Map(func(r rune) rune { + if r == '/' || r == '\\' || r == ':' || r < ' ' { + return '_' + } + return r + }, s) +} + +// checkKind checks the file's first bytes. A feed that points to the wrong file (such as a deb +// where an AppImage belongs) fails here, before anything is replaced. +func checkKind(file string, kind Kind) error { + f, err := os.Open(file) + if err != nil { + return err + } + defer func() { _ = f.Close() }() + head := make([]byte, 24) + n, _ := io.ReadFull(f, head) + head = head[:n] + ok := false + switch kind { + case KindApp: + ok = bytes.HasPrefix(head, []byte{0x1f, 0x8b}) + case KindNSIS: + ok = bytes.HasPrefix(head, []byte("MZ")) + case KindAppImage: + // An ELF file with the AppImage type-2 magic at offset 8. + ok = bytes.HasPrefix(head, []byte("\x7fELF")) && len(head) >= 11 && bytes.Equal(head[8:11], []byte("AI\x02")) + case KindDeb: + ok = bytes.HasPrefix(head, []byte("!\n")) + case KindRPM: + ok = bytes.HasPrefix(head, []byte{0xed, 0xab, 0xee, 0xdb}) + default: + return fmt.Errorf("unknown artifact kind %q", kind) + } + if !ok { + return errs.Errorf("the download isn't a %s artifact", kind) + } + return nil +} + +// SaveAs moves the artifact to dst (a file, or a folder to put it in) and returns its new path. +// `rcui update --output` uses it. +func (a *Artifact) SaveAs(dst string) (string, error) { + if info, err := os.Stat(dst); err == nil && info.IsDir() { + dst = filepath.Join(dst, filepath.Base(a.Path)) + } + mode := os.FileMode(0o644) + if a.Kind == KindAppImage { + mode = 0o755 + } + if err := os.Rename(a.Path, dst); err != nil { + if err := copyFile(a.Path, dst, mode); err != nil { + return "", err + } + _ = os.Remove(a.Path) + } + if err := os.Chmod(dst, mode); err != nil { + return "", err + } + a.Path = dst + return dst, nil +} + +// Remove deletes the artifact and its staging folder. +func (a *Artifact) Remove() { + _ = os.Remove(a.Path) + _ = os.Remove(filepath.Dir(a.Path)) // removed only if empty, since SaveAs may have moved the file +} + +// copyFile copies src to dst through a temporary file next to dst. +func copyFile(src, dst string, mode os.FileMode) (err error) { + in, err := os.Open(src) + if err != nil { + return err + } + defer func() { _ = in.Close() }() + tmp, err := os.CreateTemp(filepath.Dir(dst), "."+filepath.Base(dst)+".tmp-") + if err != nil { + return err + } + defer func() { + if err != nil { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + } + }() + if _, err = io.Copy(tmp, in); err != nil { + return err + } + if err = tmp.Chmod(mode); err != nil { + return err + } + if err = tmp.Sync(); err != nil { + return err + } + if err = tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), dst) +} diff --git a/app/update/download_test.go b/app/update/download_test.go new file mode 100644 index 00000000..0b027abc --- /dev/null +++ b/app/update/download_test.go @@ -0,0 +1,201 @@ +package update + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func TestDownload(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + content := artifactBytes(kind) + f.stable = f.release("4.0.2", "v1.76.2", kind, content) + e := engineFor(f.options(t, "4.0.1"), it, "/x") + rel, err := e.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + var calls int + var lastDone, lastTotal int64 + art, err := e.Download(context.Background(), rel, func(done, total int64) { + calls++ + lastDone, lastTotal = done, total + }) + if err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(art.Path) + if err != nil || !bytes.Equal(got, content) { + t.Fatalf("artifact = %d bytes, %v", len(got), err) + } + if art.Kind != kind || art.Release != rel { + t.Errorf("artifact = %+v", art) + } + if calls < 2 || lastDone != int64(len(content)) || lastTotal != int64(len(content)) { + t.Errorf("progress: %d calls, last %d/%d", calls, lastDone, lastTotal) + } + + // SaveAs into a folder keeps the file name, and the staging folder ends up empty. + out := t.TempDir() + dst, err := art.SaveAs(out) + if err != nil { + t.Fatal(err) + } + if filepath.Dir(dst) != out { + t.Errorf("SaveAs put it at %s", dst) + } + if b, _ := os.ReadFile(dst); !bytes.Equal(b, content) { + t.Error("SaveAs changed the file") + } +} + +// A download that isn't the kind of file the feed says fails, and leaves nothing behind. +func TestDownloadRejects(t *testing.T) { + it, kind := nativeType() + for _, c := range []struct { + name string + body []byte + }{ + {"wrong kind", []byte("PK\x03\x04 a zip")}, + {"empty", []byte{}}, + } { + t.Run(c.name, func(t *testing.T) { + f := newFeed(t) + f.stable = f.release("4.0.2", "", kind, c.body) + opts := f.options(t, "4.0.1") + e := engineFor(opts, it, "/x") + rel, err := e.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + if _, err := e.Download(context.Background(), rel, nil); err == nil { + t.Fatal("Download succeeded") + } + // Nothing is left behind. + entries, _ := os.ReadDir(opts.StagingDir) + if len(entries) != 0 { + t.Errorf("staging holds %d entries", len(entries)) + } + }) + } +} + +// A download gets its own private folder, whatever the staging folder already holds. A folder +// that another user left there (here, one this user can't write to) changes nothing. +func TestStagingDirIsFresh(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "", kind, artifactBytes(kind)) + opts := f.options(t, "4.0.1") + if err := os.Mkdir(filepath.Join(opts.StagingDir, "rcui-update"), 0o500); err != nil { + t.Fatal(err) + } + e := engineFor(opts, it, "/x") + rel, err := e.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + art, err := e.Download(context.Background(), rel, nil) + if err != nil { + t.Fatal(err) + } + dir := filepath.Dir(art.Path) + if filepath.Dir(dir) != opts.StagingDir || !strings.HasPrefix(filepath.Base(dir), "rcui-update-4.0.2-") { + t.Errorf("downloaded into %s", dir) + } + info, err := os.Stat(dir) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o700 { + t.Errorf("the folder's mode is %v, want 0700", info.Mode().Perm()) + } +} + +// Progress is reported at most every 100 ms, and once more when the last byte is in. Otherwise a +// 4 MB download arriving over 160 ms would make over a hundred calls (one per 32 KB). +func TestProgressThrottled(t *testing.T) { + it, kind := nativeType() + content := append(artifactBytes(kind), bytes.Repeat([]byte("x"), 4<<20)...) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(content))) + const parts = 16 + step := (len(content) + parts - 1) / parts + for i := 0; i < len(content); i += step { + _, _ = w.Write(content[i:min(i+step, len(content))]) + w.(http.Flusher).Flush() + time.Sleep(10 * time.Millisecond) + } + })) + defer srv.Close() + e := engineFor(Options{HTTPClient: srv.Client(), StagingDir: t.TempDir()}, it, "/x") + rel := &Release{Version: "4.0.2", Kind: kind, URL: srv.URL + "/a"} + var calls int + var lastDone, lastTotal int64 + if _, err := e.Download(context.Background(), rel, func(done, total int64) { + calls++ + lastDone, lastTotal = done, total + }); err != nil { + t.Fatal(err) + } + n := int64(len(content)) + if calls < 2 || calls > 10 || lastDone != n || lastTotal != n { + t.Errorf("progress: %d calls, the last %d/%d; want 2 to 10, the last %d/%d", calls, lastDone, lastTotal, n, n) + } +} + +// A server that stops sending partway through the body fails the download once nothing has +// arrived for stallTimeout, instead of keeping it at "downloading" forever. A slow server that +// keeps sending doesn't fail it. +func TestDownloadStalls(t *testing.T) { + saved := stallTimeout + stallTimeout = 300 * time.Millisecond + t.Cleanup(func() { stallTimeout = saved }) + + it, kind := nativeType() + content := artifactBytes(kind) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(content))) + if r.URL.Path == "/slow" { + // The whole body takes longer than stallTimeout, but never pauses that long. + for i := 0; i < len(content); i += 1000 { + _, _ = w.Write(content[i:min(i+1000, len(content))]) + w.(http.Flusher).Flush() + time.Sleep(stallTimeout / 4) + } + return + } + _, _ = w.Write(content[:100]) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer srv.Close() + staging := t.TempDir() + e := engineFor(Options{HTTPClient: srv.Client(), StagingDir: staging}, it, "/x") + + start := time.Now() + _, err := e.Download(context.Background(), &Release{Version: "4.0.2", Kind: kind, URL: srv.URL + "/stalled"}, nil) + if !errors.Is(err, errStalled) { + t.Fatalf("Download = %v, want errStalled", err) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("the stall was noticed after %v", d) + } + if entries, _ := os.ReadDir(staging); len(entries) != 0 { + t.Errorf("staging holds %d entries", len(entries)) + } + + if _, err := e.Download(context.Background(), &Release{Version: "4.0.2", Kind: kind, URL: srv.URL + "/slow"}, nil); err != nil { + t.Errorf("a slow download: %v", err) + } +} diff --git a/app/update/feed.go b/app/update/feed.go new file mode 100644 index 00000000..d947ed53 --- /dev/null +++ b/app/update/feed.go @@ -0,0 +1,363 @@ +package update + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "runtime" + "strings" + "time" + + "github.com/coreos/go-semver/semver" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +var ( + errPackageValue = errors.New("--package should be one of zip|deb|rpm") + errPackageNotLinux = errors.New(".deb and .rpm packages are supported only on Linux") +) + +// checkTimeout limits a check of the feed. It is a variable so that tests can change it. +var checkTimeout = 30 * time.Second + +var errFeedTimeout = errs.New("the update feed didn't answer within 30 seconds") + +// withCheckTimeout limits one check to checkTimeout. feedTimedOut then reports the timeout in its +// error. +func withCheckTimeout(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeoutCause(ctx, checkTimeout, errFeedTimeout) +} + +// feedTimedOut returns errFeedTimeout when ctx ran out of time for its check, or else err. +func feedTimedOut(ctx context.Context, err error) error { + if err != nil && errors.Is(context.Cause(ctx), errFeedTimeout) { + return errFeedTimeout + } + return err +} + +// FeedFormat is the format of the feed that this build reads. A feed in another format is refused, +// so a future format can change anything. +const FeedFormat = 1 + +// FeedName is the feed's file name. Each release carries its own copy. The stable channel reads +// the copy on GitHub's latest release, and the beta channel the copy on the newest beta (FeedURL). +const FeedName = "rclone-ui-update.json" + +// Feed is rclone-ui-update.json, which build/release writes. It describes one release. +type Feed struct { + // Format is FeedFormat. + Format int `json:"format"` + Release FeedRelease `json:"release"` + // Files holds the release's files that an update installs, by FileKey. + Files map[string]FeedFile `json:"files"` + // Rclone is the rclone version included in the release ("v1.76.2"). + Rclone string `json:"rclone,omitempty"` + // Policy says which running versions must or should update. It is the same in every feed + // written at the same time (build/release/policy.json). + Policy Policy `json:"policy"` +} + +type FeedRelease struct { + // Version has no leading "v". + Version string `json:"version"` + // Date is when the feed was written, in RFC 3339 format. + Date string `json:"date,omitempty"` + Notes string `json:"notes,omitempty"` +} + +type FeedFile struct { + URL string `json:"url"` +} + +// Policy says which running versions are too old. Empty fields set no limit. +type Policy struct { + // Minimum is the oldest version that may still be used. An older one must update. + Minimum string `json:"minimum,omitempty"` + // Recommended is the oldest version that isn't offered the update at start. + Recommended string `json:"recommended,omitempty"` +} + +// FileKey returns the feed key of the file of kind for goos/goarch, such as "darwin-arm64-app". +func FileKey(goos, goarch string, kind Kind) string { + return goos + "-" + goarch + "-" + string(kind) +} + +// Release is one release on a channel, with the artifact for this platform already chosen. +type Release struct { + // Version has no leading "v". + Version string + // Rclone is the rclone version included in the release ("v1.76.2"), or "" when the feed + // doesn't say. + Rclone string + Notes string + PubDate time.Time + Policy Policy + Channel Channel + // Current is the running version. + Current string + // Kind is the artifact's kind, and Key is its FileKey. + Kind Kind + Key string + URL string +} + +// Newer reports whether the release is newer than the running version. A running version that +// isn't semver (a dev build) is older than any release. +func (r *Release) Newer() bool { return compareVersions(r.Version, r.Current) > 0 } + +func (r *Release) Same() bool { return compareVersions(r.Version, r.Current) == 0 } + +// Describe returns "4.0.2 (rclone v1.76.2)", or "4.0.2" when the feed doesn't give the rclone +// version. +func (r *Release) Describe() string { return Describe(r.Version, r.Rclone) } + +func Describe(appVersion, rcloneVersion string) string { + if rcloneVersion == "" { + return appVersion + } + return appVersion + " (rclone " + rcloneVersion + ")" +} + +// CompareVersions compares two release versions and returns -1, 0 or 1. A leading "v" is +// ignored. A version that isn't semver (a dev build) is older than any release. +func CompareVersions(a, b string) int { return compareVersions(a, b) } + +// compareVersions compares in semver order. A version that doesn't parse sorts below every +// version that does. Two versions that don't parse are only checked for equality, as strings. +func compareVersions(a, b string) int { + va, errA := semver.NewVersion(strings.TrimPrefix(a, "v")) + vb, errB := semver.NewVersion(strings.TrimPrefix(b, "v")) + switch { + case errA == nil && errB == nil: + return va.Compare(*vb) + case errA == nil: + return 1 + case errB == nil: + return -1 + case a == b: + return 0 + } + return -1 +} + +// Check fetches the release that the options ask for. It reads the requested version's own feed, +// or the stable feed, or for the beta channel whichever of the beta and stable feeds has the +// newer release. It chooses this platform's artifact and fails with ErrNoArtifact when there is +// none. It gives up after 30 seconds. A version that CheckVersion refuses is refused before +// anything is fetched. +func (e *Engine) Check(ctx context.Context) (*Release, error) { + if err := CheckVersion(e.opts.Version); err != nil { + return nil, err + } + kind, err := e.artifactKind() + if err != nil { + return nil, err + } + ctx, cancel := withCheckTimeout(ctx) + defer cancel() + f, err := e.feed(ctx) + if err != nil { + return nil, feedTimedOut(ctx, err) + } + if e.opts.Version != "" && compareVersions(f.Release.Version, e.opts.Version) != 0 { + return nil, errs.Errorf("the feed of Rclone UI %s describes %s", e.opts.Version, f.Release.Version) + } + return e.release(f, kind) +} + +func (e *Engine) feed(ctx context.Context) (*Feed, error) { + if e.opts.Version != "" { + f, err := e.fetch(ctx, e.releaseFeedURL(e.opts.Version)) + if errors.Is(err, ErrNoRelease) { + return nil, fmt.Errorf("Rclone UI %s: %w", e.opts.Version, ErrNoRelease) + } + return f, err + } + return e.latest(ctx, e.opts.Channel) +} + +// noReleaseYet is ErrNoRelease for a channel that has had no release yet. beta is set when +// neither the stable nor the beta channel has one. +type noReleaseYet struct{ beta bool } + +func (e noReleaseYet) Error() string { return e.Text().String() } +func (e noReleaseYet) Unwrap() error { return ErrNoRelease } + +// Text returns the error's message, which the UI shows in the app's language. +func (e noReleaseYet) Text() i18n.Text { + if e.beta { + return i18n.M("no stable or beta release of Rclone UI yet") + } + return i18n.M("no stable release of Rclone UI yet") +} + +// latest returns the newest release on a channel. Either may not exist yet: a beta before the +// first one, and the stable feed before the first stable release. The beta channel then takes +// the other one. It also takes the stable release when GitHub won't list the betas for now +// (errListLimited). A noReleaseYet error means the channel has no release at all. +func (e *Engine) latest(ctx context.Context, ch Channel) (*Feed, error) { + stable, err := e.fetch(ctx, e.opts.FeedURL) + if ch != Beta { + if errors.Is(err, ErrNoRelease) { + return nil, noReleaseYet{} + } + return stable, err + } + if err != nil && !errors.Is(err, ErrNoRelease) { + return nil, err + } + beta, betaErr := e.newestBeta(ctx) + switch { + case errors.Is(betaErr, ErrNoRelease), errors.Is(betaErr, errListLimited) && stable != nil: + if stable == nil { + return nil, noReleaseYet{beta: true} + } + return stable, nil + case betaErr != nil: + return nil, betaErr + case stable == nil || compareVersions(beta.Release.Version, stable.Release.Version) >= 0: + return beta, nil + } + return stable, nil +} + +func (e *Engine) releaseFeedURL(version string) string { + return strings.ReplaceAll(e.opts.ReleaseFeedURL, "{version}", url.PathEscape(version)) +} + +// errListLimited means GitHub answers no more requests from this network address for now. Its +// API allows 60 an hour for each address, which other programs on the same network share. +var errListLimited = errs.New("GitHub is answering no more requests from this network for now, so the newest beta can't be looked up. Try again in an hour.") + +// maxList limits the size of GitHub's list of releases. It is a few hundred kilobytes: each +// release lists all of its files. +const maxList = 4 << 20 + +// newestBeta returns the feed of the newest beta. A beta is a pre-release on GitHub whose tag is +// a version with a pre-release part, such as v4.1.0-beta.1 (the release-beta workflow). The +// newest one is looked up in GitHub's list of the newest releases (BetaListURL), and its own +// feed is read. ErrNoRelease means the list has no beta. +func (e *Engine) newestBeta(ctx context.Context) (*Feed, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.opts.BetaListURL, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("User-Agent", userAgent(e.opts.CurrentVersion)) + resp, err := e.opts.HTTPClient.Do(req) + if err != nil { + return nil, errs.Errorf("could not reach GitHub's list of releases: %w", err) + } + defer func() { _ = resp.Body.Close() }() + switch { + case resp.StatusCode == http.StatusTooManyRequests, + resp.StatusCode == http.StatusForbidden && resp.Header.Get("X-RateLimit-Remaining") == "0": + return nil, errListLimited + case resp.StatusCode != http.StatusOK: + return nil, errs.Errorf("GitHub's list of releases answered %s (%s)", resp.Status, e.opts.BetaListURL) + } + var list []struct { + Tag string `json:"tag_name"` + Prerelease bool `json:"prerelease"` + Draft bool `json:"draft"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, maxList)).Decode(&list); err != nil { + return nil, errs.Errorf("GitHub's list of releases isn't valid (%s): %w", e.opts.BetaListURL, err) + } + newest := "" + for _, r := range list { + version, ok := strings.CutPrefix(r.Tag, "v") + if !ok || !r.Prerelease || r.Draft { + continue + } + if v, err := semver.NewVersion(version); err != nil || v.PreRelease == "" { + continue + } + if newest == "" || compareVersions(version, newest) > 0 { + newest = version + } + } + if newest == "" { + return nil, fmt.Errorf("%s: no beta: %w", e.opts.BetaListURL, ErrNoRelease) + } + f, err := e.fetch(ctx, e.releaseFeedURL(newest)) + if err != nil { + return nil, err + } + if compareVersions(f.Release.Version, newest) != 0 { + return nil, errs.Errorf("the feed of Rclone UI %s describes %s", newest, f.Release.Version) + } + return f, nil +} + +// maxFeed limits the size of a feed. A real one is a few kilobytes. +const maxFeed = 1 << 20 + +// fetch reads one feed. A 404 returns ErrNoRelease, and a feed in another format is refused. +func (e *Engine) fetch(ctx context.Context, url string) (*Feed, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", userAgent(e.opts.CurrentVersion)) + resp, err := e.opts.HTTPClient.Do(req) + if err != nil { + return nil, errs.Errorf("could not reach the update feed: %w", err) + } + defer func() { _ = resp.Body.Close() }() + switch { + case resp.StatusCode == http.StatusNotFound: + return nil, fmt.Errorf("%s: %w", url, ErrNoRelease) + case resp.StatusCode != http.StatusOK: + return nil, errs.Errorf("the update feed answered %s (%s)", resp.Status, url) + } + var f Feed + if err := json.NewDecoder(io.LimitReader(resp.Body, maxFeed)).Decode(&f); err != nil { + return nil, errs.Errorf("the update feed isn't valid (%s): %w", url, err) + } + if f.Format != FeedFormat { + return nil, errs.Errorf("%w: the update feed is in format %d, and this Rclone UI reads format %d. Download the latest release from %s", + ErrFeedFormat, f.Format, FeedFormat, ReleasesList) + } + v := strings.TrimPrefix(strings.TrimSpace(f.Release.Version), "v") + if _, err := semver.NewVersion(v); err != nil { + return nil, errs.Errorf("the update feed names no valid version (%s): %q", url, f.Release.Version) + } + f.Release.Version = v + return &f, nil +} + +// release chooses the artifact of the given kind for this platform from f. +func (e *Engine) release(f *Feed, kind Kind) (*Release, error) { + r := &Release{ + Version: f.Release.Version, + Rclone: f.Rclone, + Notes: f.Release.Notes, + Policy: f.Policy, + Channel: e.opts.Channel, + Current: e.opts.CurrentVersion, + Kind: kind, + } + if t, err := time.Parse(time.RFC3339, f.Release.Date); err == nil { + r.PubDate = t + } + key := FileKey(runtime.GOOS, runtime.GOARCH, kind) + p, ok := f.Files[key] + if !ok || p.URL == "" { + return nil, fmt.Errorf("Rclone UI %s, %s: %w", f.Release.Version, key, ErrNoArtifact) + } + r.Key, r.URL = key, p.URL + return r, nil +} + +func userAgent(current string) string { + return "rclone-ui/" + current + " (" + runtime.GOOS + "; " + runtime.GOARCH + ")" +} diff --git a/app/update/feed_test.go b/app/update/feed_test.go new file mode 100644 index 00000000..7587a03c --- /dev/null +++ b/app/update/feed_test.go @@ -0,0 +1,488 @@ +package update + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" +) + +// feed is a fake release server: /latest/download/, /releases (GitHub's list of the +// newest releases), /v/ and /files/. +type feed struct { + srv *httptest.Server + stable *Feed // nil means 404, as before the first stable release + beta *Feed // the newest beta: in the list as a pre-release, with its feed. nil means none. + // listed are more releases of the list, by tag: true for a pre-release. Their feeds are in + // releases. + listed map[string]bool + // limited makes the list answer as GitHub does once it answers no more requests. + limited bool + releases map[string]*Feed + files map[string][]byte + downloads atomic.Int32 +} + +func newFeed(t *testing.T) *feed { + t.Helper() + f := &feed{releases: map[string]*Feed{}, files: map[string][]byte{}} + f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(f.srv.Close) + return f +} + +func (f *feed) serve(w http.ResponseWriter, r *http.Request) { + var m *Feed + switch p := r.URL.Path; { + case p == "/latest/download/"+FeedName: + m = f.stable + case p == "/releases": + f.serveList(w) + return + case strings.HasPrefix(p, "/v") && strings.HasSuffix(p, "/"+FeedName): + version := strings.TrimSuffix(strings.TrimPrefix(p, "/v"), "/"+FeedName) + if m = f.releases[version]; m == nil && f.beta != nil && f.beta.Release.Version == version { + m = f.beta + } + case strings.HasPrefix(p, "/files/"): + b, ok := f.files[strings.TrimPrefix(p, "/files/")] + if !ok { + http.NotFound(w, r) + return + } + f.downloads.Add(1) + w.Header().Set("Content-Length", fmt.Sprint(len(b))) + _, _ = w.Write(b) + return + } + if m == nil { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(m) +} + +// serveList answers as GitHub's list of releases does: the releases that aren't the app's betas +// (the stable ones, and other things released from the same repository), the beta and listed. +func (f *feed) serveList(w http.ResponseWriter) { + if f.limited { + w.Header().Set("X-RateLimit-Remaining", "0") + http.Error(w, `{"message":"API rate limit exceeded"}`, http.StatusForbidden) + return + } + type listed struct { + Tag string `json:"tag_name"` + Prerelease bool `json:"prerelease"` + Draft bool `json:"draft"` + } + list := []listed{{Tag: "cloud-latest"}, {Tag: "v3.7.5"}} + if f.stable != nil { + list = append(list, listed{Tag: "v" + f.stable.Release.Version}) + } + if f.beta != nil { + list = append(list, listed{Tag: "v" + f.beta.Release.Version, Prerelease: true}) + } + for tag, pre := range f.listed { + list = append(list, listed{Tag: tag, Prerelease: pre}) + } + _ = json.NewEncoder(w).Encode(list) +} + +// release makes a feed with the given artifact for kind on every platform. The artifact is served +// at /files/-. +func (f *feed) release(version, rclone string, kind Kind, content []byte) *Feed { + name := version + "-" + string(kind) + f.files[name] = content + m := &Feed{ + Format: FeedFormat, + Release: FeedRelease{Version: version, Notes: "notes", Date: "2026-10-01T12:00:00Z"}, + Rclone: rclone, + Files: map[string]FeedFile{}, + Policy: Policy{Minimum: "4.0.0", Recommended: "4.0.1"}, + } + p := FeedFile{URL: f.srv.URL + "/files/" + name} + for _, goos := range []string{"darwin", "windows", "linux"} { + for _, arch := range []string{"amd64", "arm64"} { + m.Files[FileKey(goos, arch, kind)] = p + } + } + return m +} + +func (f *feed) options(t *testing.T, current string) Options { + return Options{ + FeedURL: f.srv.URL + "/latest/download/" + FeedName, + BetaListURL: f.srv.URL + "/releases", + ReleaseFeedURL: f.srv.URL + "/v{version}/" + FeedName, + HTTPClient: f.srv.Client(), + CurrentVersion: current, + StagingDir: t.TempDir(), + } +} + +// engineFor returns an engine that believes it is an install of type it. +func engineFor(opts Options, it InstallType, location string) *Engine { + e := New(opts) + e.installed, e.location = it, location + e.detect() + return e +} + +// nativeType returns this OS's own install type and artifact kind. +func nativeType() (InstallType, Kind) { + switch runtime.GOOS { + case "darwin": + return TypeApp, KindApp + case "windows": + return TypeNSIS, KindNSIS + } + return TypeAppImage, KindAppImage +} + +// artifactBytes returns file contents that pass checkKind for kind. +func artifactBytes(kind Kind) []byte { + head := map[Kind][]byte{ + KindApp: {0x1f, 0x8b}, + KindNSIS: []byte("MZ"), + KindAppImage: []byte("\x7fELF\x02\x01\x01\x00AI\x02"), + KindDeb: []byte("!\n"), + KindRPM: {0xed, 0xab, 0xee, 0xdb}, + }[kind] + return append(append([]byte{}, head...), bytes.Repeat([]byte("rclone ui "), 1000)...) +} + +func TestFileKey(t *testing.T) { + for _, c := range []struct { + goos, arch string + kind Kind + want string + }{ + {"darwin", "arm64", KindApp, "darwin-arm64-app"}, + {"windows", "amd64", KindNSIS, "windows-amd64-nsis"}, + {"linux", "arm64", KindAppImage, "linux-arm64-appimage"}, + {"linux", "amd64", KindDeb, "linux-amd64-deb"}, + {"linux", "arm64", KindRPM, "linux-arm64-rpm"}, + } { + if got := FileKey(c.goos, c.arch, c.kind); got != c.want { + t.Errorf("FileKey(%s, %s, %s) = %q, want %q", c.goos, c.arch, c.kind, got, c.want) + } + } +} + +func TestCompareVersions(t *testing.T) { + for _, c := range []struct { + a, b string + want int + }{ + {"4.0.2", "4.0.1", 1}, + {"v4.0.1", "4.0.1", 0}, + {"4.1.0-beta.1", "4.0.9", 1}, + {"4.1.0-beta.1", "4.1.0", -1}, + // The betas of a version are numbered, and the numbers are compared as numbers. + {"4.1.0-beta.1", "4.1.0-beta.2", -1}, + {"4.1.0-beta.2", "4.1.0-beta.10", -1}, + {"3.7.5", "4.0.0", -1}, + {"4.0.0", "dev", 1}, // a dev build is older than any release + {"dev", "dev", 0}, + } { + if got := compareVersions(c.a, c.b); got != c.want { + t.Errorf("compareVersions(%q, %q) = %d, want %d", c.a, c.b, got, c.want) + } + } +} + +func TestCheckStable(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + e := engineFor(f.options(t, "4.0.1"), it, "/somewhere") + rel, err := e.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + if rel.Version != "4.0.2" || rel.Rclone != "v1.76.2" || rel.Kind != kind || !rel.Newer() || rel.Same() { + t.Errorf("Check = %+v", rel) + } + if want := FileKey(runtime.GOOS, runtime.GOARCH, kind); rel.Key != want { + t.Errorf("key = %q, want %q", rel.Key, want) + } + if got := rel.Describe(); got != "4.0.2 (rclone v1.76.2)" { + t.Errorf("Describe = %q", got) + } + if rel.PubDate.IsZero() { + t.Error("the release date wasn't parsed") + } + if rel.Policy != (Policy{Minimum: "4.0.0", Recommended: "4.0.1"}) { + t.Errorf("policy = %+v", rel.Policy) + } +} + +func TestCheckRefusesOtherFeeds(t *testing.T) { + it, kind := nativeType() + for name, change := range map[string]func(*Feed){ + "a newer format": func(f *Feed) { f.Format = 2 }, + "no format": func(f *Feed) { f.Format = 0 }, + "no version": func(f *Feed) { f.Release.Version = "" }, + "a version of old": func(f *Feed) { f.Release.Version = "latest" }, + } { + t.Run(name, func(t *testing.T) { + f := newFeed(t) + f.stable = f.release("4.0.2", "", kind, artifactBytes(kind)) + change(f.stable) + if _, err := engineFor(f.options(t, "4.0.1"), it, "/x").Check(context.Background()); err == nil { + t.Fatal("the feed was accepted") + } else if name == "a newer format" && (!errors.Is(err, ErrFeedFormat) || !strings.Contains(err.Error(), ReleasesList)) { + t.Errorf("a newer format: %v", err) + } + }) + } +} + +func TestCheckBetaChannel(t *testing.T) { + it, kind := nativeType() + for _, c := range []struct { + name, stable, beta, want string + }{ + {"beta newer", "4.0.2", "4.1.0-beta.1", "4.1.0-beta.1"}, + {"stable newer", "4.1.0", "4.1.0-beta.2", "4.1.0"}, + {"no beta yet", "4.0.2", "", "4.0.2"}, + {"no stable release yet", "", "4.0.0-beta.1", "4.0.0-beta.1"}, + // The betas of a version stop once it is released: the release is newer than all of them. + {"the betas' version is released", "4.0.0", "4.0.0-beta.2", "4.0.0"}, + } { + t.Run(c.name, func(t *testing.T) { + f := newFeed(t) + if c.stable != "" { + f.stable = f.release(c.stable, "v1.76.2", kind, artifactBytes(kind)) + } + if c.beta != "" { + f.beta = f.release(c.beta, "v1.77.0", kind, artifactBytes(kind)) + } + opts := f.options(t, "4.0.1") + opts.Channel = Beta + rel, err := engineFor(opts, it, "/x").Check(context.Background()) + if err != nil { + t.Fatal(err) + } + if rel.Version != c.want || rel.Channel != Beta { + t.Errorf("Check = %s on %s, want %s", rel.Version, rel.Channel, c.want) + } + }) + } +} + +// A copy that runs a beta is offered the next beta, and then the version that the betas led +// to, once that is released. +func TestCheckFromABeta(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + f.beta = f.release("4.0.0-beta.2", "v1.77.0", kind, artifactBytes(kind)) + opts := f.options(t, "4.0.0-beta.1") + opts.Channel = Beta + rel, err := engineFor(opts, it, "/x").Check(context.Background()) + if err != nil || rel.Version != "4.0.0-beta.2" || !rel.Newer() { + t.Fatalf("from a beta to the next: %+v %v", rel, err) + } + f.stable = f.release("4.0.0", "v1.77.0", kind, artifactBytes(kind)) + for _, ch := range []Channel{Beta, Stable} { + opts.Channel = ch + rel, err := engineFor(opts, it, "/x").Check(context.Background()) + if err != nil || rel.Version != "4.0.0" || !rel.Newer() { + t.Errorf("%s, from a beta to its release: %+v %v", ch, rel, err) + } + } +} + +// The beta channel takes the newest beta of GitHub's list, whatever the list's order, and nothing +// else in it: a release that isn't marked as a pre-release, or one whose tag isn't a version. +func TestCheckNewestBeta(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + for _, version := range []string{"4.0.0-beta.2", "4.0.0-beta.10", "4.0.0-beta.9"} { + f.releases[version] = f.release(version, "v1.77.0", kind, artifactBytes(kind)) + } + f.listed = map[string]bool{ + "v4.0.0-beta.2": true, "v4.0.0-beta.10": true, "v4.0.0-beta.9": true, + "v9.0.0-beta.1": false, // not marked as a pre-release + "nightly": true, // not a version + "v8.0.0": true, // a pre-release without a pre-release part: not one of the betas + } + opts := f.options(t, "4.0.0-beta.2") + opts.Channel = Beta + // The numbers are compared as numbers: beta.10 is after beta.9. + rel, err := engineFor(opts, it, "/x").Check(context.Background()) + if err != nil || rel.Version != "4.0.0-beta.10" || !rel.Newer() { + t.Fatalf("Check = %+v %v, want 4.0.0-beta.10", rel, err) + } + // A beta whose release was deleted is gone from the list, and the one before it is offered. + delete(f.listed, "v4.0.0-beta.10") + if rel, err := engineFor(opts, it, "/x").Check(context.Background()); err != nil || rel.Version != "4.0.0-beta.9" { + t.Fatalf("after deleting the newest: %+v %v, want 4.0.0-beta.9", rel, err) + } + // A feed that describes another version than its release's tag is refused. + f.releases["4.0.0-beta.9"] = f.release("4.0.0-beta.2", "v1.77.0", kind, artifactBytes(kind)) + if _, err := engineFor(opts, it, "/x").Check(context.Background()); err == nil || !strings.Contains(err.Error(), "describes") { + t.Errorf("a feed for another version: %v", err) + } +} + +// When GitHub answers no more requests, the beta channel takes the stable release, and says why +// it has nothing when there is no stable release either. +func TestCheckBetaListLimited(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + f.beta = f.release("4.1.0-beta.1", "v1.77.0", kind, artifactBytes(kind)) + f.limited = true + opts := f.options(t, "4.0.0") + opts.Channel = Beta + if _, err := engineFor(opts, it, "/x").Check(context.Background()); !errors.Is(err, errListLimited) { + t.Errorf("limited, no stable release: %v, want errListLimited", err) + } + f.stable = f.release("4.0.1", "v1.76.2", kind, artifactBytes(kind)) + rel, err := engineFor(opts, it, "/x").Check(context.Background()) + if err != nil || rel.Version != "4.0.1" { + t.Errorf("limited, with a stable release: %+v %v, want 4.0.1", rel, err) + } + // The stable channel never asks for the list. + opts.Channel = Stable + if rel, err := engineFor(opts, it, "/x").Check(context.Background()); err != nil || rel.Version != "4.0.1" { + t.Errorf("the stable channel: %+v %v", rel, err) + } +} + +func TestCheckNoReleaseYet(t *testing.T) { + it, _ := nativeType() + f := newFeed(t) + for _, ch := range []Channel{Stable, Beta} { + opts := f.options(t, "4.0.0-beta.1") + opts.Channel = ch + if _, err := engineFor(opts, it, "/x").Check(context.Background()); !errors.Is(err, ErrNoRelease) { + t.Errorf("%s: %v, want ErrNoRelease", ch, err) + } + } +} + +func TestCheckVersion(t *testing.T) { + it, kind := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "v1.76.2", kind, artifactBytes(kind)) + f.releases["4.0.0"] = f.release("4.0.0", "v1.75.1", kind, artifactBytes(kind)) + opts := f.options(t, "4.0.1") + opts.Version = "v4.0.0" + rel, err := engineFor(opts, it, "/x").Check(context.Background()) + if err != nil { + t.Fatal(err) + } + // Downgrades are allowed, so a release that is neither newer nor the same is accepted. + if rel.Version != "4.0.0" || rel.Newer() || rel.Same() { + t.Errorf("Check = %+v", rel) + } + opts.Version = "9.9.9" + if _, err := engineFor(opts, it, "/x").Check(context.Background()); !errors.Is(err, ErrNoRelease) { + t.Errorf("an unknown version: %v, want ErrNoRelease", err) + } +} + +func TestCheckVersionValues(t *testing.T) { + for v, want := range map[string]error{ + "": nil, + "4.0.0": nil, + "v4.0.2": nil, + " 4.1.0-beta.1 ": nil, + "4.0.0-beta.1": nil, + "3.7.5": nil, // a version that was never released is ErrNoRelease, from the feed + "4.0": ErrBadVersion, + "latest": ErrBadVersion, + "4.0.2/../../x": ErrBadVersion, + "4.0.2?x=1": ErrBadVersion, + "4.0.2-beta/../../3.7.5": ErrBadVersion, + } { + if err := CheckVersion(v); !errors.Is(err, want) || (want == nil) != (err == nil) { + t.Errorf("CheckVersion(%q) = %v, want %v", v, err, want) + } + } +} + +func TestCheckVersionRefused(t *testing.T) { + it, kind := nativeType() + var asked atomic.Int32 + f := newFeed(t) + f.releases["4.0.3"] = f.release("4.0.1", "", kind, artifactBytes(kind)) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + f.serve(w, r) + })) + t.Cleanup(srv.Close) + opts := f.options(t, "4.0.1") + opts.ReleaseFeedURL = srv.URL + "/v{version}/" + FeedName + opts.Version = "4.0.2/../../latest" + if _, err := engineFor(opts, it, "/x").Check(context.Background()); !errors.Is(err, ErrBadVersion) { + t.Errorf("Check(%q) = %v, want ErrBadVersion", opts.Version, err) + } + if n := asked.Load(); n != 0 { + t.Errorf("the feed was asked %d times", n) + } + opts.Version = "4.0.3" + if _, err := engineFor(opts, it, "/x").Check(context.Background()); err == nil || !strings.Contains(err.Error(), "describes 4.0.1") { + t.Errorf("a feed naming 4.0.1 for 4.0.3: %v", err) + } +} + +func TestCheckNoArtifact(t *testing.T) { + it, _ := nativeType() + f := newFeed(t) + f.stable = f.release("4.0.2", "", Kind("other"), artifactBytes(KindApp)) + if _, err := engineFor(f.options(t, "4.0.1"), it, "/x").Check(context.Background()); !errors.Is(err, ErrNoArtifact) { + t.Errorf("Check = %v, want ErrNoArtifact", err) + } +} + +func TestCheckPackage(t *testing.T) { + f := newFeed(t) + f.stable = f.release("4.0.2", "", KindDeb, artifactBytes(KindDeb)) + opts := f.options(t, "4.0.1") + opts.Package = "deb" + rel, err := engineFor(opts, TypeAppImage, "/x").Check(context.Background()) + if runtime.GOOS != "linux" { + if !errors.Is(err, errPackageNotLinux) { + t.Errorf("--package deb off Linux: %v", err) + } + return + } + if err != nil || rel.Kind != KindDeb { + t.Fatalf("Check = %+v, %v", rel, err) + } + opts.Package = "msi" + if _, err := New(opts).Check(context.Background()); !errors.Is(err, errPackageValue) { + t.Errorf("--package msi: %v", err) + } +} + +func TestCheckTimeout(t *testing.T) { + saved := checkTimeout + checkTimeout = 200 * time.Millisecond + t.Cleanup(func() { checkTimeout = saved }) + silent := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + t.Cleanup(silent.Close) + + it, _ := nativeType() + e := engineFor(Options{FeedURL: silent.URL + "/latest/download/" + FeedName, HTTPClient: silent.Client()}, it, "/x") + start := time.Now() + _, err := e.Check(context.Background()) + if err == nil || err.Error() != "the update feed didn't answer within 30 seconds" { + t.Errorf("Check = %v", err) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("Check took %v", d) + } +} diff --git a/app/update/handoff.go b/app/update/handoff.go new file mode 100644 index 00000000..4c1e9e8f --- /dev/null +++ b/app/update/handoff.go @@ -0,0 +1,52 @@ +package update + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "time" + + "github.com/rclone/rclone-ui/app/deeplink" + "github.com/rclone/rclone-ui/core/datadir" +) + +// appRunning reports whether the app is running on the default data folder, which is the case +// when its core holds the folder's lock. It uses the core's path rules directly rather than the +// core package, because importing the core package would link every part of the core into the +// rclone CLI. +func appRunning() bool { + dir, err := datadir.Default() + if err != nil { + return false + } + release, err := datadir.Lock(context.Background(), dir, 0) + if err != nil { + return errors.Is(err, datadir.ErrLocked) + } + release() + return false +} + +// handOffTimeout limits the second launch, which passes the link on and exits at once. +const handOffTimeout = 30 * time.Second + +// handOff asks the running app to update. It launches the app a second time with an update link, +// which the running app receives through its single-instance lock. The app then runs its own +// update flow: it asks the user to confirm the update, because a web page can send the same link, +// and asks again if anything is busy. +func handOff(ctx context.Context, version string, ch Channel) error { + exe, err := os.Executable() + if err != nil { + return err + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + ctx, cancel := context.WithTimeout(ctx, handOffTimeout) + defer cancel() + // Pass "ui" first. When called through the rclone link, the executable's name alone would make + // it run as rclone. + return exec.CommandContext(ctx, exe, "ui", deeplink.UpdateLink(version, string(ch))).Run() +} diff --git a/app/update/install.go b/app/update/install.go new file mode 100644 index 00000000..3baa14cc --- /dev/null +++ b/app/update/install.go @@ -0,0 +1,57 @@ +package update + +import ( + "context" + "errors" + "fmt" + "runtime" +) + +// Install replaces this copy of Rclone UI with the artifact, in the same way it was installed: +// +// - macOS: the .app bundle is swapped with a single rename (renamex_np RENAME_SWAP), with an +// administrator prompt when its folder isn't writable. +// - Windows: the NSIS installer starts, detached, in passive mode. It waits for this process to +// exit, then replaces rcui.exe and restarts the app (unless Options.NoRelaunch is set). +// - Linux: $APPIMAGE is replaced with a single rename. A deb or rpm is installed through pkexec, +// or through sudo when Options.Terminal is set. +// +// relaunch starts the new version once this process has exited (on macOS, through Launch +// Services). Call it, then exit at once. On Windows the installer starts the app instead, and +// relaunch does nothing. When Install fails, the installed copy is unchanged. +func (e *Engine) Install(ctx context.Context, a *Artifact) (relaunch func() error, err error) { + if a == nil { + return nil, errors.New("nothing to install") + } + if err := e.installable(a.Kind); err != nil { + return nil, err + } + return e.install(ctx, a) +} + +func (e *Engine) installable(k Kind) error { + e.detect() + switch k { + case KindDeb, KindRPM: + // An explicit --package installs the system package whatever kind of copy this is, as + // rclone's selfupdate does. A sandboxed copy can't do that. + if runtime.GOOS != "linux" { + return errPackageNotLinux + } + if e.installed == TypeFlatpak { + _, why := e.CanSelfUpdate() + return fmt.Errorf("%w: %s", ErrCantSelfUpdate, why) + } + return nil + } + if ok, why := e.CanSelfUpdate(); !ok { + return fmt.Errorf("%w: %s", ErrCantSelfUpdate, why) + } + if e.installed.kind() != k { + return fmt.Errorf("a %s download can't update a %s install", k, e.installed) + } + return nil +} + +// noRelaunch is the relaunch function for an install that doesn't restart anything itself. +func noRelaunch() error { return nil } diff --git a/app/update/install_darwin.go b/app/update/install_darwin.go new file mode 100644 index 00000000..ea848539 --- /dev/null +++ b/app/update/install_darwin.go @@ -0,0 +1,133 @@ +package update + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "golang.org/x/sys/unix" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" +) + +func (e *Engine) install(_ context.Context, a *Artifact) (func() error, error) { + if a.Kind != KindApp { + return nil, fmt.Errorf("a %s download can't be installed on macOS", a.Kind) + } + return installBundle(a.Path, e.location, filepath.Dir(a.Path)) +} + +// installBundle replaces the .app at bundle with the one in archive. It unpacks the archive next +// to the bundle, so the swap is a single rename on one volume. When that folder isn't writable, +// it unpacks into staging (the download's private folder) and asks for an administrator password +// to move the new app into place. +func installBundle(archive, bundle, staging string) (func() error, error) { + work, err := os.MkdirTemp(filepath.Dir(bundle), ".rcui-update-") + admin := false + if err != nil { + if !errors.Is(err, fs.ErrPermission) { + return nil, err + } + admin = true + if work, err = os.MkdirTemp(staging, "app-"); err != nil { + return nil, err + } + } + defer func() { _ = os.RemoveAll(work) }() + + fresh := filepath.Join(work, filepath.Base(bundle)) + if err := untarBundle(archive, fresh); err != nil { + return nil, err + } + exe, err := bundleExecutable(fresh) + if err != nil { + return nil, err + } + if !admin { + err = swapBundle(fresh, bundle) + admin = errors.Is(err, fs.ErrPermission) + } + if admin { + err = swapBundleAsAdmin(fresh, bundle) + } + if err != nil { + return nil, err + } + // Updating the modification time makes LaunchServices read the new Info.plist. + now := time.Now() + _ = os.Chtimes(bundle, now, now) + return relaunchAfterExit(openScript, bundle, filepath.Join(bundle, "Contents", "MacOS", exe)), nil +} + +// openScript starts the bundle $1 through Launch Services, so that the new app is launched as a +// proper app, with its own TCC responsible process rather than the old app's. If that fails, it +// runs the executable $2 directly. It passes -n because Launch Services may still list the exiting +// instance, and would only activate that one. +const openScript = `/usr/bin/open -n -a "$1" || exec "$2"` + +// swapBundle exchanges fresh and bundle in one step, so there is never a moment without an app at +// bundle's path. The old app ends up at fresh's path, which the caller deletes. On a volume that +// doesn't support the swap (not APFS), it uses two renames, and undoes the first if the second +// fails. +func swapBundle(fresh, bundle string) error { + err := unix.RenamexNp(fresh, bundle, unix.RENAME_SWAP) + if err == nil { + return nil + } + if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) { + return fmt.Errorf("replace %s: %w", bundle, fs.ErrPermission) + } + if !errors.Is(err, unix.ENOTSUP) && !errors.Is(err, unix.EINVAL) { + return fmt.Errorf("replace %s: %w", bundle, err) + } + old := fresh + ".old" + if err := os.Rename(bundle, old); err != nil { + return fmt.Errorf("replace %s: %w", bundle, err) + } + if err := os.Rename(fresh, bundle); err != nil { + _ = os.Rename(old, bundle) + return fmt.Errorf("replace %s: %w", bundle, err) + } + return nil +} + +func swapBundleAsAdmin(fresh, bundle string) error { + // i18n: The text of macOS's administrator prompt, which asks for the password. + return runAsAdmin(adminSwapScript(fresh, bundle), i18n.T("Rclone UI wants to install an update.")) +} + +// adminSwapScript returns a script that moves bundle aside, moves fresh into its place, and then +// deletes the old bundle. If the second move fails (for example because fresh is on another +// volume and the target runs out of space), the old bundle is moved back, replacing whatever part +// of fresh was copied, and the script fails. +func adminSwapScript(fresh, bundle string) string { + old := bundle + ".rcui-old" + return fmt.Sprintf("rm -rf %[3]s && mv -f %[2]s %[3]s && "+ + "{ mv -f %[1]s %[2]s || { rm -rf %[2]s; mv -f %[3]s %[2]s; exit 1; }; } && rm -rf %[3]s", + shQuote(fresh), shQuote(bundle), shQuote(old)) +} + +// runAsAdmin runs a shell command through macOS's administrator prompt. +func runAsAdmin(shellCmd, prompt string) error { + esc := strings.NewReplacer(`\`, `\\`, `"`, `\"`) + script := fmt.Sprintf(`do shell script "%s" with administrator privileges with prompt "%s"`, + esc.Replace(shellCmd), esc.Replace(prompt)) + out, err := exec.Command("/usr/bin/osascript", "-e", script).CombinedOutput() + if err != nil { + if strings.Contains(string(out), "-128") { + return errs.New("the administrator prompt was cancelled") + } + return errs.Errorf("the administrator prompt failed: %s", strings.TrimSpace(string(out))) + } + return nil +} + +// shQuote quotes s for a POSIX shell with single quotes. +func shQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } diff --git a/app/update/install_darwin_test.go b/app/update/install_darwin_test.go new file mode 100644 index 00000000..9ab2ec7d --- /dev/null +++ b/app/update/install_darwin_test.go @@ -0,0 +1,151 @@ +package update + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// An update replaces the bundle whole, in place at the same path, even when the new version's +// executable has another name: nothing of the old bundle is left. +func TestInstallBundle(t *testing.T) { + apps := t.TempDir() + bundle := filepath.Join(apps, "Rclone UI.app") + old := filepath.Join(apps, "old.tar.gz") + writeTarGz(t, old, bundleEntries("rcui-previous", "4.0.1")) + if err := untarBundle(old, bundle); err != nil { + t.Fatal(err) + } + + f := newFeed(t) + archive := filepath.Join(t.TempDir(), "new.tar.gz") + writeTarGz(t, archive, bundleEntries("rcui", "4.0.2")) + content, err := os.ReadFile(archive) + if err != nil { + t.Fatal(err) + } + f.stable = f.release("4.0.2", "v1.76.2", KindApp, content) + + e := engineFor(f.options(t, "4.0.1"), TypeApp, bundle) + rel, err := e.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + art, err := e.Download(context.Background(), rel, nil) + if err != nil { + t.Fatal(err) + } + relaunch, err := e.Install(context.Background(), art) + if err != nil { + t.Fatal(err) + } + if relaunch == nil { + t.Error("no relaunch") + } + if exe, err := bundleExecutable(bundle); err != nil || exe != "rcui" { + t.Errorf("the bundle runs %q (%v), want rcui", exe, err) + } + if _, err := os.Stat(filepath.Join(bundle, "Contents", "MacOS", "rcui-previous")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("the old executable is still there: %v", err) + } + entries, _ := os.ReadDir(apps) + for _, ent := range entries { + if ent.Name() != "Rclone UI.app" && ent.Name() != "old.tar.gz" { + t.Errorf("left behind: %s", ent.Name()) + } + } +} + +func TestInstallRefuses(t *testing.T) { + for _, c := range []struct { + it InstallType + blocked string + want string + }{ + {TypeUnmanaged, "", "No installer put"}, + {TypeFlatpak, "", "Flathub"}, + {TypeApp, "macOS runs this Rclone UI from a temporary copy", "temporary copy"}, + {TypeNSIS, "", "a app download can't update a nsis install"}, + } { + e := engineFor(Options{}, c.it, "/Applications/Rclone UI.app") + e.blocked = i18n.M(c.blocked) + _, err := e.Install(context.Background(), &Artifact{Path: "/nonexistent", Kind: KindApp}) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("%s: Install = %v, want %q", c.it, err, c.want) + } + } +} + +func TestAdminSwapScript(t *testing.T) { + apps := t.TempDir() + bundle := filepath.Join(apps, "Rclone UI.app") + fresh := filepath.Join(t.TempDir(), "it's new.app") + write := func(dir, version string) { + t.Helper() + if err := os.MkdirAll(filepath.Join(dir, "Contents"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "Contents", "version"), []byte(version), 0o644); err != nil { + t.Fatal(err) + } + } + installed := func() string { + t.Helper() + b, err := os.ReadFile(filepath.Join(bundle, "Contents", "version")) + if err != nil { + t.Fatalf("no app at its path: %v", err) + } + return string(b) + } + leftovers := func() { + t.Helper() + if entries, _ := os.ReadDir(apps); len(entries) != 1 { + t.Errorf("%d entries next to the app, want only it", len(entries)) + } + } + write(bundle, "old") + + // The new bundle isn't there, so the second move fails. + if out, err := exec.Command("/bin/sh", "-c", adminSwapScript(filepath.Join(apps, "missing.app"), bundle)).CombinedOutput(); err == nil { + t.Fatalf("a failed move succeeded: %s", out) + } + if v := installed(); v != "old" { + t.Errorf("after a failed swap the app is %q, want the old one", v) + } + leftovers() + + write(fresh, "new") + if out, err := exec.Command("/bin/sh", "-c", adminSwapScript(fresh, bundle)).CombinedOutput(); err != nil { + t.Fatalf("swap: %v: %s", err, out) + } + if v := installed(); v != "new" { + t.Errorf("after the swap the app is %q, want the new one", v) + } + leftovers() +} + +// When Launch Services can't open a bundle, the script falls back to running its executable. +func TestRelaunchFallsBack(t *testing.T) { + dir := t.TempDir() + ran := filepath.Join(dir, "ran") + exe := filepath.Join(dir, "rcui") + if err := os.WriteFile(exe, []byte("#!/bin/sh\necho ran > "+shQuote(ran)+"\n"), 0o755); err != nil { + t.Fatal(err) + } + // A process that has exited and been reaped. + gone := exec.Command("true") + if err := gone.Run(); err != nil { + t.Fatal(err) + } + if err := relaunchAfter(gone.Process.Pid, openScript, "/nonexistent/Nope.app", exe); err != nil { + t.Fatal(err) + } + waitForFile(t, ran, 10*time.Second) +} diff --git a/app/update/install_linux.go b/app/update/install_linux.go new file mode 100644 index 00000000..4c218236 --- /dev/null +++ b/app/update/install_linux.go @@ -0,0 +1,91 @@ +package update + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + + "github.com/rclone/rclone-ui/core/errs" +) + +func (e *Engine) install(ctx context.Context, a *Artifact) (func() error, error) { + switch a.Kind { + case KindAppImage: + if err := replaceFile(a.Path, e.location); err != nil { + return nil, err + } + return relaunchAfterExit(execScript, e.location), nil + case KindDeb, KindRPM: + if err := e.installPackage(ctx, a); err != nil { + return nil, err + } + return relaunchAfterExit(execScript, packagedExecutable), nil + } + return nil, fmt.Errorf("a %s download can't be installed on Linux", a.Kind) +} + +// packagedExecutable is the path where the deb and rpm install rcui. +const packagedExecutable = "/usr/bin/rcui" + +// replaceFile moves src to dst with a single rename, through a temporary file next to dst, and +// keeps dst's permissions. A running AppImage keeps using its mounted image, which the rename +// doesn't affect. +func replaceFile(src, dst string) error { + mode := os.FileMode(0o755) + if info, err := os.Stat(dst); err == nil { + mode = info.Mode().Perm() | 0o111 + } + tmp := filepath.Join(filepath.Dir(dst), "."+filepath.Base(dst)+".update") + _ = os.Remove(tmp) + if err := os.Rename(src, tmp); err != nil { + if err := copyFile(src, tmp, mode); err != nil { + return errs.Errorf("could not write next to %s: %w", dst, err) + } + } + if err := os.Chmod(tmp, mode); err != nil { + _ = os.Remove(tmp) + return err + } + if err := os.Rename(tmp, dst); err != nil { + _ = os.Remove(tmp) + return errs.Errorf("could not replace %s: %w", dst, err) + } + return nil +} + +// installPackage runs dpkg or rpm as root. It runs them directly when already root, through sudo +// from a terminal, or else through pkexec (the desktop's password prompt). rpm gets --oldpackage +// and --replacepkgs, because downgrades and reinstalls are allowed. +func (e *Engine) installPackage(ctx context.Context, a *Artifact) error { + args := []string{"dpkg", "-i", a.Path} + if a.Kind == KindRPM { + args = []string{"rpm", "-U", "--oldpackage", "--replacepkgs", a.Path} + } + switch { + case os.Geteuid() == 0: + case e.opts.Terminal: + args = append([]string{"sudo"}, args...) + default: + args = append([]string{"pkexec"}, args...) + } + cmd := exec.CommandContext(ctx, args[0], args[1:]...) + var out []byte + var err error + if e.opts.Terminal { + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + err = cmd.Run() + } else { + out, err = cmd.CombinedOutput() + } + if err != nil { + var exit *exec.ExitError + if args[0] == "pkexec" && errors.As(err, &exit) && (exit.ExitCode() == 126 || exit.ExitCode() == 127) { + return errs.New("the administrator prompt was cancelled") + } + return fmt.Errorf("%s failed: %w %s", args[0], err, out) + } + return nil +} diff --git a/app/update/install_linux_test.go b/app/update/install_linux_test.go new file mode 100644 index 00000000..3d39e8c0 --- /dev/null +++ b/app/update/install_linux_test.go @@ -0,0 +1,44 @@ +package update + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" +) + +func TestInstallAppImage(t *testing.T) { + dir := t.TempDir() + img := filepath.Join(dir, "Rclone_UI.AppImage") + if err := os.WriteFile(img, []byte("old"), 0o750); err != nil { + t.Fatal(err) + } + f := newFeed(t) + content := artifactBytes(KindAppImage) + f.stable = f.release("4.0.2", "v1.76.2", KindAppImage, content) + e := engineFor(f.options(t, "4.0.1"), TypeAppImage, img) + rel, err := e.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + art, err := e.Download(context.Background(), rel, nil) + if err != nil { + t.Fatal(err) + } + relaunch, err := e.Install(context.Background(), art) + if err != nil || relaunch == nil { + t.Fatalf("Install = %v", err) + } + b, err := os.ReadFile(img) + if err != nil || !bytes.Equal(b, content) { + t.Errorf("the AppImage holds %d bytes, %v", len(b), err) + } + if info, _ := os.Stat(img); info.Mode().Perm() != 0o750|0o111 { + t.Errorf("mode = %v", info.Mode()) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 1 { + t.Errorf("left behind: %d entries", len(entries)) + } +} diff --git a/app/update/install_other.go b/app/update/install_other.go new file mode 100644 index 00000000..d7c6c4f0 --- /dev/null +++ b/app/update/install_other.go @@ -0,0 +1,20 @@ +//go:build !darwin && !linux && !windows + +package update + +import ( + "context" + "errors" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/i18n" +) + +func detectInstall() (InstallType, string, i18n.Text) { + exe, _ := platform.Executable() + return TypeUnmanaged, exe, i18n.Text{} +} + +func (e *Engine) install(context.Context, *Artifact) (func() error, error) { + return nil, errors.New("Rclone UI doesn't update itself on this system") +} diff --git a/app/update/install_windows.go b/app/update/install_windows.go new file mode 100644 index 00000000..e2c3ee6e --- /dev/null +++ b/app/update/install_windows.go @@ -0,0 +1,93 @@ +package update + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + + "golang.org/x/sys/windows" + + "github.com/rclone/rclone-ui/core/errs" +) + +func (e *Engine) install(_ context.Context, a *Artifact) (func() error, error) { + if a.Kind != KindNSIS { + return nil, fmt.Errorf("a %s download can't be installed on Windows", a.Kind) + } + if perUser(e.InstallLocation()) { + // A per-user install needs no administrator rights, so its update should show no UAC + // prompt. But the installer asks for the highest rights the user has, which for an + // administrator means a prompt. RunAsInvoker makes Windows start the installer with the + // user's own rights instead. ShellExecute passes this process's environment on, so the + // variable is set only while the installer starts. The installer clears it for the + // programs that it starts (project.nsi's .onInit). + restore, err := setEnv(compatLayer, "RunAsInvoker") + if err != nil { + return nil, err + } + defer restore() + } + if err := runInstaller(a.Path, nsisArgs(os.Getpid(), !e.opts.NoRelaunch)); err != nil { + return nil, err + } + return noRelaunch, nil +} + +// compatLayer is the environment variable that sets Windows' compatibility layers for a program. +const compatLayer = "__COMPAT_LAYER" + +func setEnv(key, value string) (restore func(), err error) { + old, had := os.LookupEnv(key) + if err := os.Setenv(key, value); err != nil { + return nil, err + } + return func() { + if had { + _ = os.Setenv(key, old) + } else { + _ = os.Unsetenv(key) + } + }, nil +} + +// nsisArgs returns the installer's switches (see build/windows/nsis/project.nsi). /P runs it in +// passive mode, with a progress window and no questions. /UPDATE updates the installed copy, with +// no new shortcuts and no uninstall. /WAITPID waits for this process to exit. /R starts the app +// when the installer is done. +func nsisArgs(pid int, relaunch bool) string { + args := []string{"/P", "/UPDATE", fmt.Sprintf("/WAITPID=%d", pid)} + if relaunch { + args = append(args, "/R") + } + return strings.Join(args, " ") +} + +// runInstaller starts the installer, detached, through the shell. The shell shows the UAC prompt +// that a per-machine install needs, where CreateProcess would fail with ERROR_ELEVATION_REQUIRED. +func runInstaller(installer, args string) error { + verb, err := windows.UTF16PtrFromString("open") + if err != nil { + return err + } + file, err := windows.UTF16PtrFromString(installer) + if err != nil { + return err + } + params, err := windows.UTF16PtrFromString(args) + if err != nil { + return err + } + dir, err := windows.UTF16PtrFromString(filepath.Dir(installer)) + if err != nil { + return err + } + if err := windows.ShellExecute(0, verb, file, params, dir, windows.SW_SHOWNORMAL); err != nil { + if err == windows.ERROR_CANCELLED { + return errs.New("the administrator prompt was cancelled") + } + return errs.Errorf("could not start the installer: %w", err) + } + return nil +} diff --git a/app/update/install_windows_test.go b/app/update/install_windows_test.go new file mode 100644 index 00000000..1ceaaa41 --- /dev/null +++ b/app/update/install_windows_test.go @@ -0,0 +1,42 @@ +package update + +import ( + "os" + "testing" +) + +// The switches that build/windows/nsis/project.nsi reads. +func TestNSISArgs(t *testing.T) { + if got := nsisArgs(42, true); got != "/P /UPDATE /WAITPID=42 /R" { + t.Errorf("nsisArgs(relaunch) = %q", got) + } + if got := nsisArgs(42, false); got != "/P /UPDATE /WAITPID=42" { + t.Errorf("nsisArgs = %q", got) + } +} + +func TestSetEnvRestores(t *testing.T) { + const key = "RCUI_TEST_SETENV" + t.Setenv(key, "") + _ = os.Unsetenv(key) + restore, err := setEnv(key, "a") + if err != nil { + t.Fatal(err) + } + if got := os.Getenv(key); got != "a" { + t.Fatalf("set: %q", got) + } + restore() + if v, ok := os.LookupEnv(key); ok { + t.Fatalf("still set after restore: %q", v) + } + + t.Setenv(key, "old") + if restore, err = setEnv(key, "b"); err != nil { + t.Fatal(err) + } + restore() + if got := os.Getenv(key); got != "old" { + t.Fatalf("restored to %q, want old", got) + } +} diff --git a/app/update/installtype.go b/app/update/installtype.go new file mode 100644 index 00000000..44772727 --- /dev/null +++ b/app/update/installtype.go @@ -0,0 +1,83 @@ +package update + +import "runtime" + +// InstallType is how a copy of Rclone UI was installed, which decides how it is replaced. +type InstallType string + +const ( + TypeApp InstallType = "app" // macOS: an .app bundle, swapped as a whole + TypeNSIS InstallType = "nsis" // Windows: the NSIS installer, which is run again + TypeAppImage InstallType = "appimage" // Linux: $APPIMAGE, which is replaced + TypeDeb InstallType = "deb" // Linux: the deb package, through dpkg + TypeRPM InstallType = "rpm" // Linux: the rpm package, through rpm + TypeFlatpak InstallType = "flatpak" // updated by the software manager + TypePortable InstallType = "portable" // Windows: the portable zip, updated by hand + TypeUnmanaged InstallType = "unmanaged" // a build that no installer placed (dev, a copied binary) +) + +// uninstallKey is the NSIS installer's uninstall entry (UNINSTKEY in +// build/windows/nsis/project.nsi), which detectInstall reads on Windows. It is under HKCU for a +// per-user install and under HKLM for a per-machine one. +const uninstallKey = `Software\Microsoft\Windows\CurrentVersion\Uninstall\org.rclone.ui` + +type Kind string + +// The artifact kinds, named after the suffixes of the feed's platform keys. +const ( + KindApp Kind = "app" // the .app.tar.gz + KindNSIS Kind = "nsis" // the -setup.exe + KindAppImage Kind = "appimage" // the .AppImage + KindDeb Kind = "deb" + KindRPM Kind = "rpm" +) + +// kind returns the artifact kind that an install of this type updates from, or "" when it doesn't +// update itself. +func (t InstallType) kind() Kind { + switch t { + case TypeApp: + return KindApp + case TypeNSIS: + return KindNSIS + case TypeAppImage: + return KindAppImage + case TypeDeb: + return KindDeb + case TypeRPM: + return KindRPM + } + return "" +} + +func defaultKind(goos string) Kind { + switch goos { + case "darwin": + return KindApp + case "windows": + return KindNSIS + case "linux": + return KindAppImage + } + return "" +} + +// artifactKind returns the kind that Download fetches. That is --package when given, or else the +// install type's own kind, or else the platform's default (for --output and --check from a copy +// that can't update itself). +func (e *Engine) artifactKind() (Kind, error) { + switch e.opts.Package { + case "deb", "rpm": + if runtime.GOOS != "linux" { + return "", errPackageNotLinux + } + return Kind(e.opts.Package), nil + case "": + default: + return "", errPackageValue + } + if k := e.InstallType().kind(); k != "" { + return k, nil + } + return defaultKind(runtime.GOOS), nil +} diff --git a/app/update/installtype_darwin.go b/app/update/installtype_darwin.go new file mode 100644 index 00000000..3386090e --- /dev/null +++ b/app/update/installtype_darwin.go @@ -0,0 +1,41 @@ +package update + +import ( + "path/filepath" + "strings" + + "golang.org/x/sys/unix" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/i18n" +) + +// detectInstall finds the .app bundle that contains the executable. A bundle that macOS +// translocated (because it was opened straight from a download) or one on a read-only volume (its +// disk image) can't be replaced. +func detectInstall() (InstallType, string, i18n.Text) { + exe, err := platform.Executable() + if err != nil { + return TypeUnmanaged, "", i18n.Text{} + } + i := strings.Index(exe, ".app/Contents/MacOS/") + if i < 0 { + return TypeUnmanaged, exe, i18n.Text{} + } + bundle := exe[:i+len(".app")] + switch { + case strings.Contains(bundle, "/AppTranslocation/"): + return TypeApp, bundle, i18n.M("macOS runs this Rclone UI from a temporary copy: move it to Applications and open it from there to update it.") + case readOnlyVolume(filepath.Dir(bundle)): + return TypeApp, bundle, i18n.M("Rclone UI runs from a read-only volume (its disk image?): copy it to Applications and open it from there to update it.") + } + return TypeApp, bundle, i18n.Text{} +} + +func readOnlyVolume(dir string) bool { + var st unix.Statfs_t + if err := unix.Statfs(dir, &st); err != nil { + return false + } + return st.Flags&unix.MNT_RDONLY != 0 +} diff --git a/app/update/installtype_linux.go b/app/update/installtype_linux.go new file mode 100644 index 00000000..ba67987e --- /dev/null +++ b/app/update/installtype_linux.go @@ -0,0 +1,52 @@ +package update + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "golang.org/x/sys/unix" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/i18n" +) + +// detectInstall tells apart the Flatpak sandbox, the AppImage and the packages. For an +// AppImage, the runtime sets $APPIMAGE and $APPDIR, and the executable runs from $APPDIR. For a +// package, dpkg or rpm owns the executable. +func detectInstall() (InstallType, string, i18n.Text) { + if platform.IsFlatpak() { + return TypeFlatpak, "", i18n.Text{} + } + exe, err := platform.Executable() + if err != nil { + return TypeUnmanaged, "", i18n.Text{} + } + if img, dir := os.Getenv("APPIMAGE"), os.Getenv("APPDIR"); img != "" && dir != "" && strings.HasPrefix(exe, filepath.Clean(dir)+"/") { + if unix.Access(filepath.Dir(img), unix.W_OK) != nil { + return TypeAppImage, img, i18n.M("The folder %s isn't writable: move the AppImage to a folder you own to update it.", filepath.Dir(img)) + } + return TypeAppImage, img, i18n.Text{} + } + if owns("dpkg-query", "-S", exe) { + return TypeDeb, exe, i18n.Text{} + } + if owns("rpm", "-qf", exe) { + return TypeRPM, exe, i18n.Text{} + } + return TypeUnmanaged, exe, i18n.Text{} +} + +// owns runs a package manager's "which package owns this file" query, and reports whether a +// package owns it. +func owns(tool string, args ...string) bool { + if _, err := exec.LookPath(tool); err != nil { + return false + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return exec.CommandContext(ctx, tool, args...).Run() == nil +} diff --git a/app/update/installtype_test.go b/app/update/installtype_test.go new file mode 100644 index 00000000..66149ae1 --- /dev/null +++ b/app/update/installtype_test.go @@ -0,0 +1,55 @@ +package update + +import ( + "context" + "errors" + "os" + "regexp" + "strings" + "testing" +) + +func TestUninstallKeyIsTheInstallers(t *testing.T) { + b, err := os.ReadFile("../../build/windows/nsis/project.nsi") + if err != nil { + t.Fatal(err) + } + defines := map[string]string{} + for _, m := range regexp.MustCompile(`(?m)^!define (\w+) "([^"]*)"`).FindAllStringSubmatch(string(b), -1) { + defines[m[1]] = m[2] + } + key := defines["UNINSTKEY"] + for name, value := range defines { + key = strings.ReplaceAll(key, "${"+name+"}", value) + } + if key != uninstallKey { + t.Fatalf("the installer writes %q, the app reads %q", key, uninstallKey) + } +} + +// A portable copy doesn't update itself, and says how to update it by hand in plain words. It +// has no artifact of its own, so a check reads the platform's installer, as for a copied binary. +func TestPortableDoesNotUpdateItself(t *testing.T) { + e := New(Options{Installed: TypePortable}) + if it := e.InstallType(); it != TypePortable { + t.Fatalf("Options.Installed gave %q", it) + } + ok, why := e.CanSelfUpdate() + if ok || why != PortableNote { + t.Errorf("CanSelfUpdate = %v, %q", ok, why) + } + for _, want := range []string{"portable copy", "portable zip", "rcui.exe, winfsp.msi and the bin folder", "data folder and rclone.conf"} { + if !strings.Contains(why, want) { + t.Errorf("the explanation lacks %q: %q", want, why) + } + } + if k := TypePortable.kind(); k != "" { + t.Errorf("a portable copy updates from %q", k) + } + if _, err := e.Install(context.Background(), &Artifact{Path: "/nonexistent", Kind: KindNSIS}); !errors.Is(err, ErrCantSelfUpdate) { + t.Errorf("Install = %v, want ErrCantSelfUpdate", err) + } + if got, want := ReleasePage("v4.0.2"), "https://github.com/rclone/rclone-ui/releases/tag/v4.0.2"; got != want { + t.Errorf("ReleasePage = %q, want %q", got, want) + } +} diff --git a/app/update/installtype_windows.go b/app/update/installtype_windows.go new file mode 100644 index 00000000..4ddeba51 --- /dev/null +++ b/app/update/installtype_windows.go @@ -0,0 +1,58 @@ +package update + +import ( + "os" + "path/filepath" + "strings" + + "golang.org/x/sys/windows/registry" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/i18n" +) + +// detectInstall finds a portable copy first (datadir.Portable). A data folder next to rcui.exe +// makes any copy portable, even one in an install folder, because the app then keeps its data +// there (datadir.Default). Otherwise detectInstall matches the executable's folder against the +// uninstall entry's InstallLocation. A folder that holds the installer's uninstall.exe counts +// too, in case a cleanup tool removed the entry. +func detectInstall() (InstallType, string, i18n.Text) { + if root, ok := datadir.Portable(); ok { + return TypePortable, root, i18n.Text{} + } + exe, err := platform.Executable() + if err != nil { + return TypeUnmanaged, "", i18n.Text{} + } + dir := filepath.Dir(exe) + for _, root := range []registry.Key{registry.CURRENT_USER, registry.LOCAL_MACHINE} { + if loc := installLocation(root); loc != "" && strings.EqualFold(filepath.Clean(loc), dir) { + return TypeNSIS, dir, i18n.Text{} + } + } + if _, err := os.Stat(filepath.Join(dir, "uninstall.exe")); err == nil { + return TypeNSIS, dir, i18n.Text{} + } + return TypeUnmanaged, exe, i18n.Text{} +} + +// perUser reports whether dir is a per-user install: the folder that the uninstall entry under +// HKCU names. A per-machine install's entry is under HKLM. +func perUser(dir string) bool { + loc := installLocation(registry.CURRENT_USER) + return dir != "" && loc != "" && strings.EqualFold(filepath.Clean(loc), filepath.Clean(dir)) +} + +func installLocation(root registry.Key) string { + k, err := registry.OpenKey(root, uninstallKey, registry.QUERY_VALUE|registry.WOW64_64KEY) + if err != nil { + return "" + } + defer func() { _ = k.Close() }() + v, _, err := k.GetStringValue("InstallLocation") + if err != nil { + return "" + } + return strings.Trim(strings.TrimSpace(v), `"`) +} diff --git a/app/update/relaunch_unix.go b/app/update/relaunch_unix.go new file mode 100644 index 00000000..1c5232f5 --- /dev/null +++ b/app/update/relaunch_unix.go @@ -0,0 +1,35 @@ +//go:build !windows + +package update + +import ( + "os" + "os/exec" + "strconv" + "syscall" +) + +// waitScript waits up to a minute for the process $1 to exit, then shifts it off, so that the +// script after it reads its own arguments from $1. The new UI mustn't start while the old one still +// holds the single-instance lock, because it would pass its arguments to the old one and exit. +const waitScript = `i=0; while kill -0 "$1" 2>/dev/null && [ "$i" -lt 600 ]; do sleep 0.1; i=$((i+1)); done; shift; ` + +const execScript = `exec "$1"` + +// relaunchAfterExit returns a relaunch function that runs script once this process has exited. +// script is a shell command that receives args as $1 and onwards. +func relaunchAfterExit(script string, args ...string) func() error { + return func() error { return relaunchAfter(os.Getpid(), script, args...) } +} + +// relaunchAfter runs script with args once process pid has exited. It runs from a detached shell +// in its own session, so that it isn't affected when this process ends. +func relaunchAfter(pid int, script string, args ...string) error { + argv := append([]string{"-c", waitScript + script, "sh", strconv.Itoa(pid)}, args...) + cmd := exec.Command("/bin/sh", argv...) + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + if err := cmd.Start(); err != nil { + return err + } + return cmd.Process.Release() +} diff --git a/app/update/relaunch_unix_test.go b/app/update/relaunch_unix_test.go new file mode 100644 index 00000000..9f970797 --- /dev/null +++ b/app/update/relaunch_unix_test.go @@ -0,0 +1,48 @@ +//go:build !windows + +package update + +import ( + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// The relaunch waits for the process to exit, then runs its script with its arguments. +func TestRelaunchAfterExit(t *testing.T) { + sleep := exec.Command("sleep", "0.5") + if err := sleep.Start(); err != nil { + t.Fatal(err) + } + start := time.Now() + // Reap the process as soon as it exits, because a zombie still answers kill -0. + go func() { _ = sleep.Wait() }() + out := filepath.Join(t.TempDir(), "out") + if err := relaunchAfter(sleep.Process.Pid, `printf %s "$2" > "$1"`, out, "a b"); err != nil { + t.Fatal(err) + } + b := waitForFile(t, out, 5*time.Second) + if d := time.Since(start); d < 400*time.Millisecond { + t.Errorf("the script ran after %v, before the process exited", d) + } + if string(b) != "a b" { + t.Errorf("the script got %q, want %q", b, "a b") + } +} + +// waitForFile returns file's contents once it has some. +func waitForFile(t *testing.T, file string, limit time.Duration) []byte { + t.Helper() + deadline := time.Now().Add(limit) + for { + if b, err := os.ReadFile(file); err == nil && len(b) > 0 { + return b + } + if time.Now().After(deadline) { + t.Fatalf("%s wasn't written within %v", file, limit) + } + time.Sleep(20 * time.Millisecond) + } +} diff --git a/app/update/untar.go b/app/update/untar.go new file mode 100644 index 00000000..50865f24 --- /dev/null +++ b/app/update/untar.go @@ -0,0 +1,192 @@ +package update + +import ( + "archive/tar" + "compress/gzip" + "encoding/xml" + "errors" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" + + "github.com/rclone/rclone-ui/core/errs" +) + +// maxBundle limits the total size that an update archive may unpack to. +const maxBundle = 2 << 30 + +// untarBundle unpacks a .app.tar.gz into dst, dropping its top folder. The archive has one top +// folder, "Rclone UI.app/", as build/package.sh writes it. Paths may not leave dst, and links may +// only point inside it. A bundle is executable code, and this runs before anything else checks +// it. Every write goes through an os.Root on dst, because checking the names alone would miss a +// chain of the archive's own links that leads out ("d/up" → "..", then "d/up/up2" → ".."). +func untarBundle(archive, dst string) error { + f, err := os.Open(archive) + if err != nil { + return err + } + defer func() { _ = f.Close() }() + gz, err := gzip.NewReader(f) + if err != nil { + return errs.Errorf("the update isn't a .tar.gz: %w", err) + } + defer func() { _ = gz.Close() }() + if err := os.MkdirAll(dst, 0o755); err != nil { + return err + } + root, err := os.OpenRoot(dst) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + tr := tar.NewReader(gz) + var total int64 + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return errs.Errorf("the update archive is damaged: %w", err) + } + rel, err := innerPath(hdr.Name) + if err != nil { + return err + } + if rel == "" { + continue // skip the top folder itself + } + target := filepath.FromSlash(rel) + mode := os.FileMode(hdr.Mode).Perm() + switch hdr.Typeflag { + case tar.TypeDir: + if err := root.MkdirAll(target, mode|0o700); err != nil { + return err + } + case tar.TypeReg: + if total += hdr.Size; total > maxBundle { + return errs.New("the update archive is too large") + } + if err := root.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + if err := writeFile(root, target, tr, mode); err != nil { + return err + } + case tar.TypeSymlink: + if !linkStaysInside(rel, hdr.Linkname) { + return fmt.Errorf("the update archive links %s outside the app", hdr.Name) + } + if err := root.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + if err := root.Symlink(hdr.Linkname, target); err != nil { + return err + } + case tar.TypeXGlobalHeader: + default: + return fmt.Errorf("the update archive holds an unexpected entry: %s", hdr.Name) + } + } + return nil +} + +// innerPath returns an entry's path below the top folder, or an error when the path would leave +// it. +func innerPath(name string) (string, error) { + clean := path.Clean(strings.TrimPrefix(name, "./")) + if path.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, "../") { + return "", fmt.Errorf("the update archive holds an unsafe path: %s", name) + } + _, rest, _ := strings.Cut(clean, "/") + return rest, nil +} + +// linkStaysInside reports whether a symlink at rel (a slash-separated path below the bundle) that +// points to target resolves inside the bundle. +func linkStaysInside(rel, target string) bool { + if target == "" || path.IsAbs(target) { + return false + } + resolved := path.Clean(path.Join(path.Dir(rel), target)) + return resolved != ".." && !strings.HasPrefix(resolved, "../") +} + +func writeFile(root *os.Root, name string, r io.Reader, mode os.FileMode) (err error) { + out, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode) + if err != nil { + return err + } + defer func() { + if cerr := out.Close(); err == nil { + err = cerr + } + }() + _, err = io.Copy(out, r) + return err +} + +// plistString reads one string value from an XML property list's top dictionary. +func plistString(file, key string) (string, error) { + f, err := os.Open(file) + if err != nil { + return "", err + } + defer func() { _ = f.Close() }() + dec := xml.NewDecoder(f) + dec.Strict = false + depth, wantValue := 0, false + for { + tok, err := dec.Token() + if errors.Is(err, io.EOF) { + return "", fmt.Errorf("%s has no %s", file, key) + } + if err != nil { + return "", fmt.Errorf("%s: %w", file, err) + } + switch t := tok.(type) { + case xml.StartElement: + depth++ + // In , the top dictionary's entries are at depth 3. + if depth != 3 { + continue + } + var text string + if err := dec.DecodeElement(&text, &t); err != nil { + return "", fmt.Errorf("%s: %w", file, err) + } + depth-- + switch { + case wantValue && t.Name.Local == "string": + return strings.TrimSpace(text), nil + case t.Name.Local == "key": + wantValue = strings.TrimSpace(text) == key + default: + wantValue = false + } + case xml.EndElement: + depth-- + } + } +} + +// bundleExecutable returns the name of the executable that an .app runs (CFBundleExecutable), and +// checks that it exists. +func bundleExecutable(bundle string) (string, error) { + name, err := plistString(filepath.Join(bundle, "Contents", "Info.plist"), "CFBundleExecutable") + if err != nil { + return "", errs.Errorf("the update isn't an app bundle: %w", err) + } + if name == "" || strings.ContainsAny(name, `/\`) { + return "", fmt.Errorf("the update's CFBundleExecutable is %q", name) + } + exe := filepath.Join(bundle, "Contents", "MacOS", name) + info, err := os.Stat(exe) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { + return "", fmt.Errorf("the update's executable %s is missing", name) + } + return name, nil +} diff --git a/app/update/untar_test.go b/app/update/untar_test.go new file mode 100644 index 00000000..a48e9bbb --- /dev/null +++ b/app/update/untar_test.go @@ -0,0 +1,171 @@ +package update + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// tarEntry is one entry of a test archive: a file (body), a folder (dir) or a link (link). +type tarEntry struct { + name, body, link string + dir bool + mode int64 +} + +func writeTarGz(t *testing.T, file string, entries []tarEntry) { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for _, e := range entries { + h := &tar.Header{Name: e.name, Mode: e.mode} + switch { + case e.dir: + h.Typeflag, h.Mode = tar.TypeDir, 0o755 + case e.link != "": + h.Typeflag, h.Linkname, h.Mode = tar.TypeSymlink, e.link, 0o777 + default: + h.Typeflag, h.Size = tar.TypeReg, int64(len(e.body)) + if h.Mode == 0 { + h.Mode = 0o644 + } + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if h.Typeflag == tar.TypeReg { + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(file, buf.Bytes(), 0o600); err != nil { + t.Fatal(err) + } +} + +func infoPlist(exe, version string) string { + return ` + + + + CFBundleDisplayName + Rclone UI + CFBundleURLTypes + CFBundleExecutablenot this one + CSResourcesFileMapped + + CFBundleExecutable + ` + exe + ` + CFBundleShortVersionString + ` + version + ` + +` +} + +// bundleEntries is an app bundle laid out the way build/updater's tar-app writes it. +func bundleEntries(exe, version string) []tarEntry { + return []tarEntry{ + {name: "Rclone UI.app/", dir: true}, + {name: "Rclone UI.app/Contents/", dir: true}, + {name: "Rclone UI.app/Contents/Info.plist", body: infoPlist(exe, version)}, + {name: "Rclone UI.app/Contents/MacOS/", dir: true}, + {name: "Rclone UI.app/Contents/MacOS/" + exe, body: "#!/bin/sh\necho " + version + "\n", mode: 0o755}, + {name: "Rclone UI.app/Contents/Resources/icon.icns", body: "icon"}, + {name: "Rclone UI.app/Contents/Resources/current", link: "icon.icns"}, + } +} + +func TestUntarBundle(t *testing.T) { + // Only macOS installs an app bundle, and Windows files have no execute bit to keep. + if runtime.GOOS == "windows" { + t.Skip("an app bundle is installed on macOS only") + } + dir := t.TempDir() + archive := filepath.Join(dir, "a.tar.gz") + writeTarGz(t, archive, bundleEntries("rcui", "4.0.2")) + dst := filepath.Join(dir, "out", "Rclone UI.app") + if err := untarBundle(archive, dst); err != nil { + t.Fatal(err) + } + exe, err := bundleExecutable(dst) + if err != nil || exe != "rcui" { + t.Fatalf("bundleExecutable = %q, %v", exe, err) + } + info, err := os.Stat(filepath.Join(dst, "Contents", "MacOS", "rcui")) + if err != nil || info.Mode().Perm()&0o100 == 0 { + t.Errorf("the executable lost its mode: %v %v", info, err) + } + if target, err := os.Readlink(filepath.Join(dst, "Contents", "Resources", "current")); err != nil || target != "icon.icns" { + t.Errorf("link = %q, %v", target, err) + } + if v, err := plistString(filepath.Join(dst, "Contents", "Info.plist"), "CFBundleShortVersionString"); err != nil || v != "4.0.2" { + t.Errorf("version = %q, %v", v, err) + } +} + +func TestUntarBundleRefusesEscapes(t *testing.T) { + for _, c := range []struct { + name string + entry tarEntry + }{ + {"dot-dot path", tarEntry{name: "Rclone UI.app/../../evil", body: "x"}}, + {"absolute path", tarEntry{name: "/etc/evil", body: "x"}}, + {"absolute link", tarEntry{name: "Rclone UI.app/Contents/l", link: "/etc/passwd"}}, + {"link out", tarEntry{name: "Rclone UI.app/Contents/l", link: "../../../../etc"}}, + } { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "a.tar.gz") + writeTarGz(t, archive, append(bundleEntries("rcui", "4.0.2"), c.entry)) + err := untarBundle(archive, filepath.Join(dir, "out", "Rclone UI.app")) + if err == nil || !strings.Contains(err.Error(), "the update archive") { + t.Errorf("untarBundle = %v", err) + } + }) + } +} + +func TestUntarBundleRefusesLinkChains(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "a.tar.gz") + writeTarGz(t, archive, append(bundleEntries("rcui", "4.0.2"), + tarEntry{name: "Rclone UI.app/d/", dir: true}, + tarEntry{name: "Rclone UI.app/d/up", link: ".."}, + tarEntry{name: "Rclone UI.app/d/up/up2", link: ".."}, + tarEntry{name: "Rclone UI.app/d/up/up2/evil", body: "x"}, + )) + out := filepath.Join(dir, "out") + if err := untarBundle(archive, filepath.Join(out, "Rclone UI.app")); err == nil { + t.Error("untarBundle unpacked through a chain of links") + } + if _, err := os.Stat(filepath.Join(out, "evil")); err == nil { + t.Error("the archive wrote outside the app") + } +} + +func TestBundleExecutableMissing(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "a.tar.gz") + entries := bundleEntries("rcui", "4.0.2") + writeTarGz(t, archive, entries[:3]) // Info.plist without the executable + dst := filepath.Join(dir, "Rclone UI.app") + if err := untarBundle(archive, dst); err != nil { + t.Fatal(err) + } + if _, err := bundleExecutable(dst); err == nil { + t.Error("a bundle without its executable passed") + } +} diff --git a/app/update/update.go b/app/update/update.go new file mode 100644 index 00000000..e6a50695 --- /dev/null +++ b/app/update/update.go @@ -0,0 +1,271 @@ +// Package update is Rclone UI's update engine. It reads the feed (rclone-ui-update.json, see Feed), +// downloads releases and installs them for each install type. +// +// The engine has two front ends: the UI role's update flow, with dialogs and progress in a window, +// and `rcui update` (see cli.go), with text and progress on stdout. It never imports Wails. +// +// # What the UI flow calls, in order +// +// 1. e := update.New(update.Options{Channel: ch, Version: v}), with the user's channel, or with +// the version and channel from an update link ("" for either means the default). `rcui +// update` passes the running app an rclone://update link through its single-instance lock. +// 2. ok, why := e.CanSelfUpdate(). It returns false under Flatpak (which updates through the +// software manager), for a copy that no installer put there, for a portable copy, and for an +// app run from its disk image or a translocated path. In that case, show why and stop. A +// portable copy still checks for updates, and sends the user to the release's page +// (ReleasePage) to download it. +// 3. rel, err := e.Check(ctx). rel.Newer() reports whether it is an update, and rel.Same() +// whether it is the running version. Downgrades are allowed, so a release that is neither is +// still installable. rel.Policy says whether the running version must or should update. +// 4. The busy check (the core's Busy), with a confirmation when anything is running. +// 5. art, err := e.Download(ctx, rel, progress). The artifact is checked when this returns, and +// everything is still running, so a failed download changes nothing. +// 6. The planned shutdown: the core's Shutdown with restart set, which records what is running +// so that it comes back. On Windows no rcui.exe may keep running, so the core stops the mount +// and serve children itself. +// 7. relaunch, err := e.Install(ctx, art). On error the old version is intact, so report the +// error and start the app again. On Windows this starts the installer, which waits for this +// process to exit. +// 8. Call relaunch(), then quit this process at once, with no confirmation and no further work. +// relaunch waits for this process to exit before it starts the new version, so the new UI +// doesn't run into this one's single-instance lock. On Windows the installer starts the new +// version instead. +package update + +import ( + "fmt" + "net/http" + "net/url" + "os" + "strings" + "sync" + "time" + + "github.com/coreos/go-semver/semver" + + "github.com/rclone/rclone-ui/app/platform" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/version" +) + +// Channel is a release channel. +type Channel string + +// The channels. Beta follows the newest beta, or the stable release when that is newer. A beta is +// a numbered build of the version it leads to, such as 4.1.0-beta.1 (the release-beta workflow), +// so it is older than that version's own release. +const ( + Stable Channel = "stable" + Beta Channel = "beta" +) + +// The feeds (FeedName). FeedURL is the stable channel's: the feed of GitHub's latest release, which +// is the one that a person set as the latest on the release page (see release.yml). +// ReleaseFeedURL is each release's own feed, used for --version and for a beta. {version} has no +// leading "v". +// +// GitHub has an address for the latest stable release only, so the beta channel finds its release +// in BetaListURL, GitHub's list of its ten newest releases: the newest pre-release there is the +// newest beta, and the channel reads that release's own feed (newestBeta). The list is GitHub's +// API, which answers 60 requests an hour for each network address. Only the beta channel asks +// it, once for each check. +const ( + FeedURL = "https://github.com/rclone/rclone-ui/releases/latest/download/" + FeedName + ReleaseFeedURL = "https://github.com/rclone/rclone-ui/releases/download/v{version}/" + FeedName + BetaListURL = "https://api.github.com/repos/rclone/rclone-ui/releases?per_page=10" +) + +// ReleasesList is the list of releases, for a copy that can't update itself, and the start of each +// release's page (ReleasePage). +const ReleasesList = "https://github.com/rclone/rclone-ui/releases" + +// PortableNote is why a portable copy doesn't update itself, and how to update it by hand. +const PortableNote = "This is a portable copy of Rclone UI, which doesn't update itself. Download the new release's portable zip, and replace rcui.exe, winfsp.msi and the bin folder with the ones in it. Your data folder and rclone.conf stay as they are." + +// ReleasePage returns the page with the downloads of version, or ReleasesList when version is "". +func ReleasePage(version string) string { + if version = strings.TrimPrefix(strings.TrimSpace(version), "v"); version == "" { + return ReleasesList + } + return ReleasesList + "/tag/v" + url.PathEscape(version) +} + +// Errors that the front ends handle separately. +var ( + // ErrNoRelease means the feed has no such release, as for a --version that was never + // released. + ErrNoRelease = errs.New("no such release") + // ErrNoArtifact means the release has no download for this platform and package. + ErrNoArtifact = errs.New("the release has no download for this platform") + // ErrCantSelfUpdate means this install type updates some other way (CanSelfUpdate says how). + ErrCantSelfUpdate = errs.New("this copy of Rclone UI can't update itself") + // ErrBadVersion means the requested version isn't a release version, such as "4.0.2" or + // "4.1.0-beta.1". + ErrBadVersion = errs.New("not an Rclone UI version, like 4.0.2") + // ErrFeedFormat means the feed is in a format that this build doesn't read (FeedFormat). + ErrFeedFormat = errs.New("unknown feed format") +) + +// CheckVersion returns an error unless v is a version that may be requested. That is "" (the +// channel's latest), or a semver version such as "4.0.2" or "v4.1.0-beta.1". +func CheckVersion(v string) error { + v = strings.TrimPrefix(strings.TrimSpace(v), "v") + if v == "" { + return nil + } + if _, err := semver.NewVersion(v); err != nil { + return fmt.Errorf("%q is %w", v, ErrBadVersion) + } + return nil +} + +// Options configure an Engine. The zero value means the stable channel's latest release, from the +// production feed, installed the same way this copy was installed. +type Options struct { + // Channel is Stable when empty. + Channel Channel + // Version chooses a release ("4.0.2" or "v4.0.2") instead of the channel's latest. Check + // refuses any version that CheckVersion refuses. + Version string + // Package is the artifact type: "" or "zip" for the install type's own, or "deb" or "rpm" + // (Linux). + Package string + + // Terminal means deb and rpm are installed through sudo rather than pkexec. + Terminal bool + // NoRelaunch means the Windows installer doesn't start the app when it is done. + NoRelaunch bool + + // The rest are for tests and staging servers. Empty means the production value. + FeedURL, BetaListURL, ReleaseFeedURL string + HTTPClient *http.Client + // CurrentVersion is the running version (version.App). + CurrentVersion string + // StagingDir is the folder in which each download gets its own folder (the temp folder). + StagingDir string + // Installed is how this copy was installed. Empty means it is detected from the running + // executable. + Installed InstallType +} + +// Engine checks, downloads and installs one update. It isn't safe for concurrent use. +type Engine struct { + opts Options + + detectOnce sync.Once + installed InstallType + location string // the bundle, $APPIMAGE, the executable, or the install folder + blocked i18n.Text // why a detected install type still can't update; zero when it can +} + +// installInfo holds what detectInstall found. +type installInfo struct { + installed InstallType + location string + blocked i18n.Text +} + +// detected runs detectInstall once per process. The running install doesn't change while the +// process runs, and on Linux detection starts dpkg-query and rpm, which every engine would +// otherwise run again. +var detected = sync.OnceValue(func() installInfo { + it, location, blocked := detectInstall() + return installInfo{installed: it, location: location, blocked: blocked} +}) + +// responseHeaderTimeout limits the wait for a server's response. There is no limit on the whole +// body, because a large download on a slow connection may take any amount of time, as long as it +// doesn't stall (see stallTimeout). +const responseHeaderTimeout = 30 * time.Second + +// defaultClient is the HTTP client that engines use. There is one per process, so its connections +// are reused. +var defaultClient = sync.OnceValue(func() *http.Client { + t := http.DefaultTransport.(*http.Transport).Clone() + t.ResponseHeaderTimeout = responseHeaderTimeout + return &http.Client{Transport: t} +}) + +// New makes an engine. Nothing is fetched until Check. +func New(opts Options) *Engine { + if opts.Channel == "" { + opts.Channel = Stable + } + if opts.Package == "zip" { + opts.Package = "" + } + opts.Version = strings.TrimPrefix(strings.TrimSpace(opts.Version), "v") + if opts.FeedURL == "" { + opts.FeedURL = FeedURL + } + if opts.BetaListURL == "" { + opts.BetaListURL = BetaListURL + } + if opts.ReleaseFeedURL == "" { + opts.ReleaseFeedURL = ReleaseFeedURL + } + if opts.HTTPClient == nil { + opts.HTTPClient = defaultClient() + } + if opts.CurrentVersion == "" { + opts.CurrentVersion = version.App + } + opts.CurrentVersion = strings.TrimPrefix(opts.CurrentVersion, "v") + if opts.StagingDir == "" { + opts.StagingDir = os.TempDir() + } + return &Engine{opts: opts, installed: opts.Installed} +} + +// CurrentVersion returns the version this engine updates from, without a leading "v". +func (e *Engine) CurrentVersion() string { return e.opts.CurrentVersion } + +// InstallType returns how this copy was installed, as detected from the running executable. +func (e *Engine) InstallType() InstallType { + e.detect() + return e.installed +} + +// InstallLocation returns what an install replaces: the .app bundle, $APPIMAGE, the executable +// that a package owns, or the install folder on Windows. It returns "" when unknown. +func (e *Engine) InstallLocation() string { + e.detect() + return e.location +} + +// CanSelfUpdate reports whether Install can replace this copy, and why not when it can't, in +// English, as the command line prints it. +func (e *Engine) CanSelfUpdate() (bool, string) { + why := e.WhyNot() + return why.IsZero(), why.String() +} + +// WhyNot says why Install can't replace this copy, as a message that the UI shows in the app's +// language. It is the zero Text when Install can. +func (e *Engine) WhyNot() i18n.Text { + e.detect() + switch e.installed { + case TypeFlatpak: + return i18n.M("Rclone UI was installed from Flathub: update it through your software manager (or `flatpak update %s`).", platform.FlatpakAppID) + case TypeUnmanaged: + if e.location == "" { + return i18n.M("No installer put this copy there, so it can't update itself. Download the latest release from %s.", ReleasesList) + } + // i18n: %[1]s is where Rclone UI runs from, and %[2]s the page of its releases. + return i18n.M("No installer put %[1]s there, so it can't update itself. Download the latest release from %[2]s.", e.location, ReleasesList) + case TypePortable: + return i18n.M(PortableNote) + } + return e.blocked +} + +func (e *Engine) detect() { + e.detectOnce.Do(func() { + if e.installed != "" { // set by Options.Installed, or by a test + return + } + d := detected() + e.installed, e.location, e.blocked = d.installed, d.location, d.blocked + }) +} diff --git a/app/update/update.md b/app/update/update.md new file mode 100644 index 00000000..c2a24b4f --- /dev/null +++ b/app/update/update.md @@ -0,0 +1,40 @@ +This command updates Rclone UI, and the rclone it brings with it: in this +build rclone is part of Rclone UI, so `rclone update` through the `rclone` +link on your PATH updates the whole app, and `selfupdate` only says so. + +If used without flags (or with the implied `--stable` flag), this command +installs the latest stable release. Use `--beta` for the latest beta, or +the stable release when that is newer. You can check in advance what would +be installed by adding the `--check` flag; `--check` alone prints your +version and the latest stable and beta releases, as `version --check` does. + +The `--version VER` flag installs that Rclone UI release instead of the +latest one, older ones included. Upon a successful update the command +prints the version you updated from, should you want to go back to it. + +When Rclone UI is running, the command hands the update to it and exits: +the app stops what it runs (transfers, mounts, serves), installs the +update and restarts, asking first when something would be interrupted. +If Rclone UI has only just started, it may miss the request: run the +command again. Otherwise the command installs the update itself, the way +this copy was installed: + +- macOS: the Rclone UI app bundle is replaced. +- Windows: the Rclone UI installer runs, and finishes after this command + exits. +- Linux: the AppImage is replaced; a deb or rpm install is updated through + `sudo`. + +`--package deb` or `--package rpm` installs that package on Linux instead. +With `--output PATH` the release is downloaded to `PATH`, and nothing is +installed. + +Rclone UI installed from Flathub is updated by the software manager, and +this command says so. + +A portable copy of Rclone UI on Windows (from the portable zip, with a +`data` folder next to `rcui.exe`) doesn't update itself either: this +command prints the release's download page, and `--check` marks your +version with "(portable)". To update the copy, download the new release's +portable zip, and replace `rcui.exe` and the `bin` folder with the ones in +it. The `data` folder and `rclone.conf` stay as they are. diff --git a/app/updateflow.go b/app/updateflow.go new file mode 100644 index 00000000..de368815 --- /dev/null +++ b/app/updateflow.go @@ -0,0 +1,492 @@ +package app + +import ( + "context" + "sync" + "sync/atomic" + "time" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/update" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/notifications" +) + +// UpdateRequest says which release to check for. Empty fields mean the latest release on the +// user's channel. `rcui update --version X` can ask for a specific version. +type UpdateRequest struct { + Version string + // Channel is "stable" or "beta". + Channel string +} + +type UpdateRelease struct { + Version string `json:"version"` + // Current is the running version. + Current string `json:"current"` + Notes string `json:"notes"` + // Date is the release date (RFC 3339). + Date string `json:"date"` + // Rclone is the version of rclone included in the release. + Rclone string `json:"rclone"` + // Required means the running version is below the policy's minimum, and the app can't be used + // without updating. + Required bool `json:"required"` + // Recommended means the running version is below the policy's recommended version, so the app + // offers the update at start. Otherwise only "Check for updates" in Settings offers it. + Recommended bool `json:"recommended"` + // Page is the release's page on GitHub, with its downloads. A portable copy, which doesn't + // update itself, sends the user there. + Page string `json:"page"` +} + +// releaseFor returns the release that the app offers, or nil. found is offered when it is newer +// than the running version, or when a specific version was asked for, which allows downgrades. +func releaseFor(found *update.Release, asked string) *UpdateRelease { + if asked == "" && !found.Newer() { + return nil + } + p := found.Policy + older := func(v string) bool { return v != "" && update.CompareVersions(found.Current, v) < 0 } + return &UpdateRelease{ + Version: found.Version, Current: found.Current, Notes: found.Notes, Rclone: found.Rclone, + Date: found.PubDate.Format(time.RFC3339), + Required: older(p.Minimum), + Recommended: older(p.Minimum) || older(p.Recommended), + Page: update.ReleasePage(found.Version), + } +} + +// updateFlow is the UI's update flow around the engine in app/update. It decides when to check +// and what to ask, runs the busy check, stops the core and exits. The engine does the rest. Only +// one update runs at a time. +type updateFlow struct { + u *ui + // enabled is true for a release build, or for a development build that uses a test feed + // (see testFeed). The real feed would offer to replace a development build with the latest + // release. + enabled bool + // engine holds the options that every engine of the flow starts from: the test feed, and in + // the tests, the install type. + engine update.Options + + running sync.Mutex // held while an update runs + startOnce sync.Once + mu sync.Mutex + last *offer // what the last check found + // reported is the release that app.update-available was last sent for. + reported string + + // installing is held from the moment the core stops until the exit, or until the relaunch + // when the install fails. A quit holds it too, so neither can interrupt the other halfway. + installing sync.Mutex + // quitWaiting is set when a quit is waiting for the install. A successful install then exits + // without relaunching. + quitWaiting atomic.Bool +} + +// offer is what a check found. It holds the release as pages see it, plus the engine and the +// release that install it. install downloads found and never reads the feed again, so the release +// that gets installed is the one that was offered. +type offer struct { + rel *UpdateRelease + eng *update.Engine + found *update.Release +} + +// release returns the offer as pages see it, or nil when there is no offer. +func (o *offer) release() *UpdateRelease { + if o == nil { + return nil + } + return o.rel +} + +func (f *updateFlow) state(s UpdateState) { + f.u.app.Event.Emit(EventUpdateState, s) +} + +func (f *updateFlow) channel(req UpdateRequest) update.Channel { + ch := update.Channel(req.Channel) + if ch == "" { + ch = update.Channel(f.u.settings().Updates.Channel) + } + if ch == "" { + ch = update.Stable + } + return ch +} + +// available reports whether this install can update itself, and why not when it can't, in the +// app's language. A portable copy can't, but it still checks for updates and sends the user to +// the release's page (Manual). +func (f *updateFlow) available() UpdateAvailability { + if !f.enabled { + return UpdateAvailability{Why: i18n.T("Updates are not available in this build.")} + } + e := update.New(f.engine) + why := e.WhyNot() + ok := why.IsZero() + return UpdateAvailability{OK: ok, Why: why.Local(), Manual: !ok && e.InstallType() == update.TypePortable} +} + +// check reads the feed. The offer is nil when the app is up to date, and in a build that doesn't +// update. Only a check with an empty req keeps its offer for Install and reports it to the +// notification targets. An offer from an update link is not kept, so that a later press of Update +// in Settings never installs it. +func (f *updateFlow) check(ctx context.Context, req UpdateRequest) (*offer, error) { + if !f.enabled { + return nil, nil + } + ch := f.channel(req) + f.u.log.Info("checking for updates", "channel", ch) + f.state(UpdateState{Phase: "checking"}) + opts := f.engine + opts.Channel, opts.Version = ch, req.Version + eng := update.New(opts) + found, err := eng.Check(ctx) + if err != nil { + f.state(UpdateState{Phase: "error", Error: i18n.Localize(err)}) + return nil, err + } + f.state(UpdateState{Phase: "idle"}) + var o *offer + if rel := releaseFor(found, req.Version); rel != nil { + o = &offer{rel: rel, eng: eng, found: found} + } + if req != (UpdateRequest{}) { + return o, nil + } + f.mu.Lock() + f.last = o + f.mu.Unlock() + if o != nil { + f.u.log.Info("an update is available", "version", o.rel.Version, "current", o.rel.Current, "required", o.rel.Required) + f.report(o.rel) + } + return o, nil +} + +// report sends app.update-available through the core's notification targets. It sends it once +// per release, because the check runs at every start and on demand. +func (f *updateFlow) report(rel *UpdateRelease) { + f.mu.Lock() + sent := f.reported == rel.Version + f.mu.Unlock() + if sent { + return + } + if f.u.theCore() == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err := f.u.apis.Notifications.ReportUpdate(ctx, notifications.UpdateAvailable{ + Version: rel.Version, Current: rel.Current, Notes: rel.Notes, + }) + if err != nil { + f.u.log.Warn("could not report the update to the notification targets", "error", err) + return + } + f.mu.Lock() + f.reported = rel.Version + f.mu.Unlock() +} + +// startUp runs the startup check in the background, once per run of the UI. It is called once the +// core's settings are read, because the channel and the skipped version come from them. It is +// also called when the core failed to start, because a required update may fix the problem. +func (f *updateFlow) startUp() { + f.startOnce.Do(func() { go f.atStart(context.Background()) }) +} + +// atStart is the check at start. It offers an update when the policy recommends or requires one. +func (f *updateFlow) atStart(ctx context.Context) { + o, err := f.check(ctx, UpdateRequest{}) + if err != nil { + f.u.log.Warn("could not check for updates", "error", err) + return + } + rel := o.release() + if rel == nil || (!rel.Required && !rel.Recommended) { + return + } + if !rel.Required && rel.Version == f.u.settings().Updates.SkippedVersion { + return + } + title, cancel := updateTitle(rel), i18n.T("Skip This Version") + if rel.Required { + // i18n: The button that quits the app instead of installing a required update. + cancel = i18n.T("Exit") + } + // i18n: %s is the new version, such as 4.0.2. + msg := i18n.T("You are running an outdated version of Rclone UI. Please update to the latest version (%s).", rel.Version) + // A portable copy offers the release's page, where the user downloads it. + avail := f.available() + // i18n: The button that installs an update. + button := i18n.T("Update") + if avail.Manual { + msg += "\n\n" + avail.Why + // i18n: The button that opens the release's page, to download the update by hand. + button = i18n.T("Download") + } + if !interaction.Ask(interaction.Info, title, msg, button, cancel) { + if rel.Required { + f.u.quit(true) + return + } + f.u.skipVersion(ctx, rel.Version) + return + } + if avail.Manual { + f.openPage(rel) + // The app can't be used below a required version, so it quits once the page is open. + if rel.Required { + f.u.quit(true) + } + return + } + f.install(ctx, o) +} + +func updateTitle(rel *UpdateRelease) string { + if rel.Required { + return i18n.T("Update Required") + } + return i18n.T("Update Available") +} + +func (f *updateFlow) openPage(rel *UpdateRelease) { + if err := f.u.openURL(rel.Page); err != nil { + f.u.log.Warn("could not open the release's page", "url", rel.Page, "error", err) + } +} + +// requested runs an update that an update link asked for. `rcui update` sends one to the running +// app, and so can any web page, so the app asks before it installs anything (linkQuestion). A +// failed check is reported, and so is a version that isn't a valid version, because the command +// told the user that the app would take over. +func (f *updateFlow) requested(ctx context.Context, req UpdateRequest) { + // CheckVersion only refuses a version that isn't one, so the message says so. + if err := update.CheckVersion(req.Version); err != nil { + f.u.log.Warn("refused a requested update", "version", req.Version, "error", err) + // i18n: %q is what an update link asked for, which isn't a version. + msg := i18n.T("Rclone UI was asked to update to %q, but that is not an Rclone UI version, like 4.0.2.", req.Version) + f.state(UpdateState{Phase: "error", Version: req.Version, Error: msg}) + interaction.Message(interaction.Warning, i18n.T("Update Refused"), msg) + return + } + o, err := f.check(ctx, req) + if err != nil { + f.fail(req.Version, stepCheck, err) + return + } + if o == nil { + return + } + // A copy that can't update itself gets install's own dialog, which installs nothing. + if f.available().OK { + title, msg := linkQuestion(o.rel) + // i18n: The button that installs an update. + if !interaction.Ask(interaction.Question, title, msg, i18n.T("Update"), i18n.T("Cancel")) { + f.u.log.Info("the user declined a requested update", "version", o.rel.Version) + f.state(UpdateState{Phase: "idle"}) + return + } + } + f.install(ctx, o) +} + +// linkQuestion returns the title and the text of the question that requested asks before it +// installs rel. +func linkQuestion(rel *UpdateRelease) (title, msg string) { + switch { + case update.CompareVersions(rel.Version, rel.Current) < 0: + // i18n: The running version, then the older one that a link asked for, such as 4.0.1. + msg = i18n.T("Rclone UI was asked to change from version %s to %s, an older version.", rel.Current, rel.Version) + case rel.Version == rel.Current: + // i18n: The running version, which a link asked to install again. + msg = i18n.T("Rclone UI was asked to install version %s again.", rel.Version) + default: + // i18n: The running version, then the newer one that a link asked for, such as 4.0.2. + msg = i18n.T("Rclone UI was asked to update from version %s to %s.", rel.Current, rel.Version) + } + // i18n: Follows the request that an update link made. + msg += "\n\n" + i18n.T("Choose Update only if you asked for this, for example with the rcui update command.") + return updateTitle(rel), msg +} + +// install runs the update steps: the download, the busy check, a planned stop of the core, the +// install and the relaunch. If a step fails, the app keeps running as it was. From the busy check +// on, the launcher is suspended, as for a quit, and it comes back if the update is cancelled or +// fails. +func (f *updateFlow) install(ctx context.Context, o *offer) { + if !f.running.TryLock() { + return + } + defer f.running.Unlock() + rel := o.rel + if avail := f.available(); !avail.OK { + title := updateTitle(rel) + if avail.Manual { + if interaction.Ask(interaction.Info, title, avail.Why, i18n.T("Download"), i18n.T("Cancel")) { + f.openPage(rel) + } + } else { + interaction.Message(interaction.Info, title, avail.Why) + } + if rel.Required { + f.u.quit(true) + } + return + } + f.state(UpdateState{Phase: "downloading", Version: rel.Version}) + art, err := o.eng.Download(ctx, o.found, func(done, total int64) { + f.state(UpdateState{Phase: "downloading", Version: rel.Version, Done: done, Total: max(total, 0)}) + }) + if err != nil { + f.fail(rel.Version, stepDownload, err) + return + } + f.u.launcher.Suspend() + // i18n: The title of the dialog that asks before an update stops what is running. + if !f.u.confirmStop(ctx, i18n.T("Update"), i18n.T("Update and Restart")) { + f.u.launcher.Resume() + art.Remove() + f.state(UpdateState{Phase: "idle"}) + return + } + // From here on, a quit (from the tray or a signal) waits, because exiting during the install + // would leave the app half replaced. A quit that has already begun goes first, and if it exits, + // the rest of this never runs. + f.installing.Lock() + defer f.installing.Unlock() + if f.u.quitting.Load() { + f.u.launcher.Resume() // the quit has its own Suspend, which keeps the launcher hidden + art.Remove() + return + } + f.state(UpdateState{Phase: "installing", Version: rel.Version}) + f.u.hideWindows() + f.u.stopCore(ctx, true) + relaunch, err := o.eng.Install(ctx, art) + if err != nil { + // The old version is intact, but its core has stopped and can only start again in a new + // process. So the app is started again, and what was running comes back. The quit inside + // relaunch waits for this install to return. + art.Remove() + f.fail(rel.Version, stepInstall, err) + go f.u.relaunch("") + return + } + // Nothing else cleans up the staging folders. The Windows installer is kept, because it reads + // its file after the app exits. + if art.Kind != update.KindNSIS { + art.Remove() + } + if f.quitWaiting.Load() { + f.u.log.Info("updated; not relaunching, since the app was asked to quit") + } else if err := relaunch(); err != nil { + f.u.log.Error("could not relaunch after the update", "error", err) + } + f.u.exit() +} + +// holdInstalls is the quit's side of installing. It waits for an install that is under way, and +// keeps a new one from starting until the returned func is called. An install that succeeds in the +// meantime exits without relaunching the app. (On Windows, the installer still starts it.) +func (f *updateFlow) holdInstalls() (release func()) { + if f == nil { + return func() {} + } + if !f.installing.TryLock() { + f.quitWaiting.Store(true) + f.installing.Lock() + f.quitWaiting.Store(false) + } + return f.installing.Unlock +} + +type updateStep int + +const ( + stepCheck updateStep = iota + stepDownload + stepInstall +) + +func (s updateStep) String() string { + return [...]string{"check", "download", "install"}[s] +} + +// failure returns the text of the dialog that says the step failed with err, in the app's +// language. The engine's own errors are translated, and other errors (the network's, the OS's) +// keep their words. +func (s updateStep) failure(err error) string { + switch s { + case stepCheck: + return i18n.T("Rclone UI could not check for the update: %s\n\nPlease try again, or tap \"Download\" to download the update manually.", err) + case stepDownload: + return i18n.T("Rclone UI could not download the update: %s\n\nPlease try again, or tap \"Download\" to download the update manually.", err) + } + return i18n.T("Rclone UI could not install the update: %s\n\nPlease try again, or tap \"Download\" to download the update manually.", err) +} + +func (f *updateFlow) fail(version string, step updateStep, err error) { + f.u.log.Error("the update failed", "version", version, "step", step.String(), "error", err) + f.state(UpdateState{Phase: "error", Version: version, Error: i18n.Localize(err)}) + // i18n: The second button is "OK", which closes the dialog. + if interaction.Ask(interaction.Error, i18n.T("Update Failed"), step.failure(err), i18n.T("Download"), i18n.T("OK")) { + if err := f.u.openURL(update.ReleasePage(version)); err != nil { + f.u.log.Warn("could not open the releases page", "error", err) + } + } +} + +type UpdateService struct{ u *ui } + +// UpdateAvailability says whether this install can update itself, and why not. +type UpdateAvailability struct { + OK bool `json:"ok"` + Why string `json:"why"` + // Manual means the install can't update itself, but still checks for updates, as a portable + // copy does. The user downloads a release that a check finds from its page + // (UpdateRelease.Page). + Manual bool `json:"manual"` +} + +func (s *UpdateService) Available() UpdateAvailability { return s.u.updates.available() } + +// Check looks for a newer release. It returns nil when the app is up to date. +func (s *UpdateService) Check(ctx context.Context) (*UpdateRelease, error) { + o, err := s.u.updates.check(ctx, UpdateRequest{}) + if err != nil { + // The engine makes its errors with core/errs, so that the page gets them in the app's + // language. errs.Failed keeps them failures, which a second try may fix, rather than + // rejected requests. + return nil, errs.Failed(err) + } + return o.release(), nil +} + +// Install runs the update steps for the release that Check found, and checks first if Check +// hasn't run. +func (s *UpdateService) Install(ctx context.Context) error { + f := s.u.updates + f.mu.Lock() + o := f.last + f.mu.Unlock() + if o == nil { + var err error + if o, err = f.check(ctx, UpdateRequest{}); err != nil { + return errs.Failed(err) + } + if o == nil { + return errs.New("Rclone UI is up to date.") + } + } + // The download and the relaunch continue after the page's call returns. + go f.install(context.Background(), o) + return nil +} diff --git a/app/updateflow_test.go b/app/updateflow_test.go new file mode 100644 index 00000000..9061d802 --- /dev/null +++ b/app/updateflow_test.go @@ -0,0 +1,138 @@ +package app + +import ( + "strings" + "testing" + "time" + + "github.com/rclone/rclone-ui/app/update" + "github.com/rclone/rclone-ui/core/i18n" +) + +func TestReleaseFor(t *testing.T) { + for _, c := range []struct { + name, current, found, asked string + pol update.Policy + offered, required, recom bool + }{ + {name: "newer", current: "4.0.1", found: "4.0.2", offered: true}, + {name: "the same", current: "4.0.2", found: "4.0.2"}, + {name: "older", current: "4.0.2", found: "4.0.1"}, + {name: "older, asked for", current: "4.0.2", found: "4.0.1", asked: "4.0.1", offered: true}, + {name: "the same, asked for", current: "4.0.2", found: "4.0.2", asked: "4.0.2", offered: true}, + {name: "a development build", current: "dev", found: "4.0.2", offered: true}, + {name: "below the minimum", current: "4.0.1", found: "4.0.3", pol: update.Policy{Minimum: "4.0.2", Recommended: "4.0.3"}, offered: true, required: true, recom: true}, + {name: "below the minimum only", current: "4.0.1", found: "4.0.3", pol: update.Policy{Minimum: "4.0.2"}, offered: true, required: true, recom: true}, + {name: "below the recommended version", current: "4.0.1", found: "4.0.3", pol: update.Policy{Minimum: "4.0.0", Recommended: "4.0.2"}, offered: true, recom: true}, + {name: "at the recommended version", current: "4.0.2", found: "4.0.3", pol: update.Policy{Minimum: "4.0.0", Recommended: "4.0.2"}, offered: true}, + } { + t.Run(c.name, func(t *testing.T) { + found := &update.Release{Version: c.found, Current: c.current, Rclone: "v1.76.2", Notes: "notes", Policy: c.pol} + rel := releaseFor(found, c.asked) + if (rel != nil) != c.offered { + t.Fatalf("offered %v, want %v", rel != nil, c.offered) + } + if rel == nil { + return + } + if rel.Required != c.required || rel.Recommended != c.recom { + t.Errorf("required %v, recommended %v; want %v, %v", rel.Required, rel.Recommended, c.required, c.recom) + } + if rel.Version != c.found || rel.Current != c.current || rel.Rclone != "v1.76.2" || rel.Notes != "notes" { + t.Errorf("release = %+v", rel) + } + if want := "https://github.com/rclone/rclone-ui/releases/tag/v" + c.found; rel.Page != want { + t.Errorf("page %q, want %q", rel.Page, want) + } + }) + } +} + +func TestUpdateAvailability(t *testing.T) { + for _, c := range []struct { + enabled bool + installed update.InstallType + ok, manual bool + why string + }{ + {true, update.TypeNSIS, true, false, ""}, + {true, update.TypePortable, false, true, update.PortableNote}, + {true, update.TypeUnmanaged, false, false, "No installer put"}, + {true, update.TypeFlatpak, false, false, "Flathub"}, + {false, update.TypePortable, false, false, "not available in this build"}, + } { + f := &updateFlow{enabled: c.enabled, engine: update.Options{Installed: c.installed}} + a := f.available() + if a.OK != c.ok || a.Manual != c.manual || !strings.Contains(a.Why, c.why) { + t.Errorf("%s (enabled %v): %+v, want ok %v, manual %v, why %q", c.installed, c.enabled, a, c.ok, c.manual, c.why) + } + } +} + +func TestQuitWaitsForInstall(t *testing.T) { + f := &updateFlow{} + f.installing.Lock() // an install, between the core's stop and the exit + held := make(chan func()) + go func() { held <- f.holdInstalls() }() + for deadline := time.Now().Add(5 * time.Second); !f.quitWaiting.Load(); time.Sleep(time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("the quit didn't say it waits") + } + } + select { + case <-held: + t.Fatal("the quit went on during the install") + case <-time.After(50 * time.Millisecond): + } + f.installing.Unlock() // the install failed, so the app keeps running and the quit goes on + release := <-held + if f.quitWaiting.Load() { + t.Error("the quit still says it waits") + } + if f.installing.TryLock() { + t.Fatal("an install could start during the quit") + } + release() + if !f.installing.TryLock() { + t.Fatal("the quit kept installs off after it") + } + + // In the UI's tests there is no update flow, so holdInstalls must work on nil. + var none *updateFlow + none.holdInstalls()() +} + +// The update flow translates the engine's errors and reasons. The engine's own text stays in +// English, because `rcui update` prints it. +func TestUpdateTextIsTranslated(t *testing.T) { + i18n.SetLanguage(i18n.Pseudo) + t.Cleanup(func() { i18n.SetLanguage(i18n.English) }) + got := stepDownload.failure(update.ErrNoArtifact) + if !strings.HasPrefix(got, "[Rçlóñé ÚÍ çóúld ñót dówñlóád thé úpdáté: [thé réléásé hás ñó dówñlóád fór thís plátfórm]") { + t.Errorf("failure: %q", got) + } + if want := "the release has no download for this platform"; update.ErrNoArtifact.Error() != want { + t.Errorf("the engine's error became %q", update.ErrNoArtifact.Error()) + } + f := &updateFlow{enabled: true, engine: update.Options{Installed: update.TypePortable}} + if a := f.available(); !strings.HasPrefix(a.Why, "[Thís ís á pórtáblé çópý") { + t.Errorf("why: %q", a.Why) + } + if _, why := update.New(update.Options{Installed: update.TypePortable}).CanSelfUpdate(); why != update.PortableNote { + t.Errorf("the command line's reason became %q", why) + } +} + +func TestLinkQuestion(t *testing.T) { + for _, c := range []struct{ current, asked, want string }{ + {"4.0.1", "4.0.2", "update from version 4.0.1 to 4.0.2."}, + {"4.1.0", "4.0.0", "change from version 4.1.0 to 4.0.0, an older version."}, + {"4.1.0-beta.2", "4.1.0-beta.1", "an older version"}, + {"4.0.2", "4.0.2", "install version 4.0.2 again."}, + } { + title, msg := linkQuestion(&UpdateRelease{Version: c.asked, Current: c.current}) + if title != "Update Available" || !strings.Contains(msg, c.want) || !strings.Contains(msg, "rcui update") { + t.Errorf("%s to %s: %q, %q; want %q", c.current, c.asked, title, msg, c.want) + } + } +} diff --git a/app/webview2.go b/app/webview2.go new file mode 100644 index 00000000..0aadbfac --- /dev/null +++ b/app/webview2.go @@ -0,0 +1,42 @@ +package app + +import ( + "errors" + "strings" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// wailsError handles an error that Wails reports. Every error is logged. A fatal error about +// WebView2 also gets a dialog on Windows (see webView2Failed), because Wails exits as soon as this +// returns, and the user would otherwise see nothing. A window that can't start WebView2 is most +// likely in a portable copy, which has no installer to install the WebView2 runtime. +func (u *ui) wailsError(err error) { + u.log.Error("wails", "error", err) + var fatal *application.FatalError + if errors.As(err, &fatal) { + if cause := fatal.Unwrap(); cause != nil && aboutWebView2(cause.Error()) { + u.webView2Failed(cause) + } + } +} + +// aboutWebView2 reports whether an error's message is about WebView2, as in Wails' "unable to +// initialise WebView2 for window". +func aboutWebView2(msg string) bool { + return strings.Contains(strings.ToLower(msg), "webview2") +} + +// webView2Installed reports whether the WebView2 runtime is installed, from the pv values that +// Microsoft's guide says to read (see webView2Versions on Windows): +// https://learn.microsoft.com/microsoft-edge/webview2/concepts/distribution#detect-if-a-webview2-runtime-is-already-installed +// The runtime is installed when one of them holds a version. An empty value or 0.0.0.0 doesn't +// count, because an uninstall can leave either behind. +func webView2Installed(pvs []string) bool { + for _, pv := range pvs { + if pv = strings.TrimSpace(pv); pv != "" && pv != "0.0.0.0" { + return true + } + } + return false +} diff --git a/app/webview2_other.go b/app/webview2_other.go new file mode 100644 index 00000000..9f7ddc7a --- /dev/null +++ b/app/webview2_other.go @@ -0,0 +1,5 @@ +//go:build !windows + +package app + +func (u *ui) webView2Failed(error) {} diff --git a/app/webview2_test.go b/app/webview2_test.go new file mode 100644 index 00000000..646ec9b4 --- /dev/null +++ b/app/webview2_test.go @@ -0,0 +1,33 @@ +package app + +import "testing" + +func TestWebView2Installed(t *testing.T) { + for _, c := range []struct { + pvs []string + want bool + }{ + {nil, false}, + {[]string{""}, false}, + {[]string{"0.0.0.0"}, false}, + {[]string{" 0.0.0.0 ", ""}, false}, + {[]string{"131.0.2903.70"}, true}, + {[]string{"0.0.0.0", "", "131.0.2903.70"}, true}, + } { + if got := webView2Installed(c.pvs); got != c.want { + t.Errorf("webView2Installed(%q) = %v, want %v", c.pvs, got, c.want) + } + } +} + +func TestAboutWebView2(t *testing.T) { + for msg, want := range map[string]bool{ + `unable to initialise WebView2 for window "Launcher"`: true, + "error getting webview2 version: not found": true, + "unable to create window": false, + } { + if got := aboutWebView2(msg); got != want { + t.Errorf("aboutWebView2(%q) = %v, want %v", msg, got, want) + } + } +} diff --git a/app/webview2_windows.go b/app/webview2_windows.go new file mode 100644 index 00000000..94a50ef6 --- /dev/null +++ b/app/webview2_windows.go @@ -0,0 +1,72 @@ +package app + +import ( + "golang.org/x/sys/windows/registry" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/core/i18n" +) + +const ( + // webView2Client is the key under which EdgeUpdate keeps the WebView2 runtime's version. + webView2Client = `SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}` + // webView2Download is Microsoft's page for the WebView2 runtime's bootstrapper. + webView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703" +) + +// webView2Versions reads the pv values that Microsoft's guide lists: a per-machine install under +// HKLM, in both the registry's 32-bit view (WOW6432Node on 64-bit Windows) and its 64-bit view, +// and a per-user install under HKCU. A missing key or value is left out. +func webView2Versions() []string { + var pvs []string + for _, k := range []struct { + root registry.Key + view uint32 + }{ + {registry.LOCAL_MACHINE, registry.WOW64_32KEY}, + {registry.LOCAL_MACHINE, registry.WOW64_64KEY}, + {registry.CURRENT_USER, 0}, + } { + key, err := registry.OpenKey(k.root, webView2Client, registry.QUERY_VALUE|k.view) + if err != nil { + continue + } + pv, _, err := key.GetStringValue("pv") + _ = key.Close() + if err == nil { + pvs = append(pvs, pv) + } + } + return pvs +} + +// webView2Failed tells the user why the app can't show its windows, before Wails exits. When the +// WebView2 runtime is missing, it offers Microsoft's download. Otherwise it shows the failure. +// Wails calls this on its main thread, which can't show a window anymore. So the dialog is a plain +// message box (interaction.ShowPlain), which needs nothing from Wails. +func (u *ui) webView2Failed(cause error) { + if !webView2Installed(webView2Versions()) { + u.log.Error("the WebView2 runtime isn't installed") + if interaction.ShowPlain(interaction.Dialog{ + Kind: interaction.Error, + Title: i18n.T("Rclone UI Needs WebView2"), + Message: i18n.T("Rclone UI draws its windows with Microsoft Edge WebView2, which isn't installed on this computer.\n\n" + + "Download and install WebView2, then open Rclone UI again."), + // i18n: A button in a plain Windows message box, which keeps its width: keep it short. + OK: i18n.T("Download"), + Cancel: i18n.T("Quit"), + }) == interaction.AnswerOK { + if err := u.openURL(webView2Download); err != nil { + u.log.Error("could not open the WebView2 download", "error", err) + } + } + return + } + interaction.ShowPlain(interaction.Dialog{ + Kind: interaction.Error, + Title: i18n.T("Rclone UI Can't Show Its Windows"), + // i18n: %[1]s is the error from WebView2, and %[2]s the path of the app's log file. + Message: i18n.T("Microsoft Edge WebView2, which Rclone UI draws its windows with, failed to start, so Rclone UI will quit.\n\n"+ + "%[1]s\n\nThe log has the details: %[2]s", cause, u.logs.Path()), + }) +} diff --git a/app/windows/cascade.go b/app/windows/cascade.go new file mode 100644 index 00000000..4200974a --- /dev/null +++ b/app/windows/cascade.go @@ -0,0 +1,33 @@ +package windows + +// Area is a screen's work area in logical pixels. +type Area struct{ X, Y, Width, Height int } + +// cascadeStep is the offset between each window and the previous one. +const cascadeStep = 20 + +// Cascade places a w×h window in the centre of area, then moves it by cascadeStep for each open +// window, so that it doesn't cover them exactly. The direction alternates between down-right and +// up-left, so a stack of windows stays near the middle. The window always stays inside the area. +func Cascade(area Area, w, h, open int) (x, y int) { + x = area.X + (area.Width-w)/2 + y = area.Y + (area.Height-h)/2 + offset := open * cascadeStep + if open%2 != 0 { + offset = -offset + } + x = clamp(x+offset, area.X, area.X+area.Width-w) + y = clamp(y+offset, area.Y, area.Y+area.Height-h) + return x, y +} + +func Center(area Area, w, h int) (x, y int) { + return Cascade(area, w, h, 0) +} + +func clamp(v, lo, hi int) int { + if hi < lo { + return lo + } + return max(lo, min(v, hi)) +} diff --git a/app/windows/cascade_test.go b/app/windows/cascade_test.go new file mode 100644 index 00000000..8b4398aa --- /dev/null +++ b/app/windows/cascade_test.go @@ -0,0 +1,35 @@ +package windows + +import "testing" + +func TestCascade(t *testing.T) { + area := Area{X: 0, Y: 25, Width: 1440, Height: 875} + cases := []struct { + open, x, y int + }{ + {0, 300, 100}, + {1, 280, 80}, + {2, 340, 140}, + {3, 240, 40}, + } + for _, c := range cases { + x, y := Cascade(area, 840, 725, c.open) + if x != c.x || y != c.y { + t.Errorf("Cascade(open=%d) = %d,%d, want %d,%d", c.open, x, y, c.x, c.y) + } + } +} + +func TestCascadeStaysOnScreen(t *testing.T) { + area := Area{X: 1920, Y: 0, Width: 1280, Height: 800} + for open := range 40 { + x, y := Cascade(area, 840, 725, open) + if x < area.X || x+840 > area.X+area.Width || y < area.Y || y+725 > area.Y+area.Height { + t.Fatalf("open=%d: %d,%d leaves the area", open, x, y) + } + } + // A window larger than the area is pinned to its top-left corner. + if x, y := Cascade(Area{Width: 600, Height: 400}, 840, 725, 3); x != 0 || y != 0 { + t.Errorf("oversized window at %d,%d", x, y) + } +} diff --git a/app/windows/route.go b/app/windows/route.go new file mode 100644 index 00000000..b0d3c6fd --- /dev/null +++ b/app/windows/route.go @@ -0,0 +1,50 @@ +package windows + +import "strings" + +// The windows whose route gives them their own shape. +const ( + // Commander opens at the size of the screen. + Commander = "Commander" + // Startup is the frameless startup screen, which the UI role opens itself. + Startup = "Startup" +) + +// Shape is the size and style of a route's window. +type Shape int + +const ( + // Standard is 840×725 (resizable from 650×500 to 1000×1000), and cascades from the windows + // that are already open. + Standard Shape = iota + // Full is the size of the screen's work area. On macOS its content extends under the title + // bar. + Full + // Small is the startup screen. It is frameless, 800×500, not resizable and always on top. + Small +) + +// ForRoute returns the name of the window that a route opens in, and its shape. The name is the +// route's first segment, capitalised, or "Main" for "/". Pages compute their own name the same way +// (see windowName in lib/shell). +func ForRoute(url string) (name string, shape Shape) { + path, _, _ := strings.Cut(url, "?") + segment := "" + for s := range strings.SplitSeq(path, "/") { + if s != "" { + segment = s + break + } + } + if segment == "" { + return "Main", Standard + } + name = strings.ToUpper(segment[:1]) + segment[1:] + switch name { + case Commander: + return name, Full + case Startup: + return name, Small + } + return name, Standard +} diff --git a/app/windows/route_test.go b/app/windows/route_test.go new file mode 100644 index 00000000..55ae1c2a --- /dev/null +++ b/app/windows/route_test.go @@ -0,0 +1,23 @@ +package windows + +import "testing" + +func TestForRoute(t *testing.T) { + for _, tc := range []struct { + url, name string + shape Shape + }{ + {"/", "Main", Standard}, + {"", "Main", Standard}, + {"/commander?path=x", "Commander", Full}, + {"/commander?left=/tmp", "Commander", Full}, + {"/startup", "Startup", Small}, + {"/settings?tab=about", "Settings", Standard}, + {"/history/", "History", Standard}, + {"/copy", "Copy", Standard}, + } { + if name, shape := ForRoute(tc.url); name != tc.name || shape != tc.shape { + t.Errorf("%s: %s %v", tc.url, name, shape) + } + } +} diff --git a/app/windows/theme.go b/app/windows/theme.go new file mode 100644 index 00000000..0377356e --- /dev/null +++ b/app/windows/theme.go @@ -0,0 +1,35 @@ +package windows + +import "github.com/wailsapp/wails/v3/pkg/application" + +// creationTheme returns the theme that Wails creates a window with on Windows. It is the app's +// theme, or the system's current theme. It is never SystemDefault (see base). +func creationTheme(theme string, systemDark bool) application.Theme { + if darkTitleBar(theme, systemDark) { + return application.Dark + } + return application.Light +} + +// darkTitleBar reports whether a window's title bar is dark. The app's theme decides, or the +// system's theme when the window follows the system (""). +func darkTitleBar(theme string, systemDark bool) bool { + switch theme { + case "dark": + return true + case "light": + return false + } + return systemDark +} + +// themeMode returns 0 to follow the system, 1 for dark and 2 for light. +func themeMode(theme string) int { + switch theme { + case "dark": + return 1 + case "light": + return 2 + } + return 0 +} diff --git a/app/windows/theme_darwin.go b/app/windows/theme_darwin.go new file mode 100644 index 00000000..7e537767 --- /dev/null +++ b/app/windows/theme_darwin.go @@ -0,0 +1,31 @@ +package windows + +/* +#cgo CFLAGS: -mmacosx-version-min=12.0 -x objective-c +#cgo LDFLAGS: -mmacosx-version-min=12.0 -framework Cocoa +#import + +static void rcuiSetAppearance(void *window, int mode) { + NSWindow *w = (NSWindow *)window; + if (mode == 0) { + w.appearance = nil; + } else { + w.appearance = [NSAppearance appearanceNamed:(mode == 1 ? NSAppearanceNameDarkAqua : NSAppearanceNameAqua)]; + } +} +*/ +import "C" + +import ( + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// setTheme sets the NSWindow's appearance. It must run on the main thread. +func setTheme(native unsafe.Pointer, theme string) { + C.rcuiSetAppearance(native, C.int(themeMode(theme))) +} + +// windowsTheme returns SystemDefault, because the creation theme is an option only on Windows. +func windowsTheme(string) application.Theme { return application.SystemDefault } diff --git a/app/windows/theme_linux.go b/app/windows/theme_linux.go new file mode 100644 index 00000000..a8f88398 --- /dev/null +++ b/app/windows/theme_linux.go @@ -0,0 +1,14 @@ +package windows + +import ( + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// setTheme does nothing on Linux. GTK's dark preference applies to the whole application, not to +// one window, so the pages' own CSS applies the theme. +func setTheme(unsafe.Pointer, string) {} + +// windowsTheme returns SystemDefault, because the creation theme is an option only on Windows. +func windowsTheme(string) application.Theme { return application.SystemDefault } diff --git a/app/windows/theme_test.go b/app/windows/theme_test.go new file mode 100644 index 00000000..9fa14494 --- /dev/null +++ b/app/windows/theme_test.go @@ -0,0 +1,41 @@ +package windows + +import ( + "testing" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +func TestDarkTitleBar(t *testing.T) { + for _, c := range []struct { + theme string + systemDark bool + want bool + }{ + {"dark", false, true}, + {"light", true, false}, + {"", true, true}, + {"", false, false}, + } { + if got := darkTitleBar(c.theme, c.systemDark); got != c.want { + t.Errorf("%q, system dark %v: %v", c.theme, c.systemDark, got) + } + } +} + +func TestCreationTheme(t *testing.T) { + for _, c := range []struct { + theme string + systemDark bool + want application.Theme + }{ + {"light", true, application.Light}, + {"dark", false, application.Dark}, + {"", true, application.Dark}, + {"", false, application.Light}, + } { + if got := creationTheme(c.theme, c.systemDark); got != c.want { + t.Errorf("%q, system dark %v: %v, want %v", c.theme, c.systemDark, got, c.want) + } + } +} diff --git a/app/windows/theme_windows.go b/app/windows/theme_windows.go new file mode 100644 index 00000000..69b0aff5 --- /dev/null +++ b/app/windows/theme_windows.go @@ -0,0 +1,40 @@ +package windows + +import ( + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/w32" + "golang.org/x/sys/windows" +) + +// windowsTheme returns the theme that a new window is created with (see base). +func windowsTheme(theme string) application.Theme { + return creationTheme(theme, w32.IsCurrentlyDarkMode()) +} + +var ( + dwmapi = windows.NewLazySystemDLL("dwmapi.dll") + dwmSetWindowAttribute = dwmapi.NewProc("DwmSetWindowAttribute") +) + +// DWMWA_USE_IMMERSIVE_DARK_MODE, and the value it had before Windows 10 20H1. +const ( + dwmaDarkMode = 20 + dwmaDarkModeLegacy = 19 +) + +// setTheme makes the window's title bar dark or light. "" follows the system's app mode. +func setTheme(native unsafe.Pointer, theme string) { + if dwmSetWindowAttribute.Find() != nil { + return + } + var dark int32 + if darkTitleBar(theme, w32.IsCurrentlyDarkMode()) { + dark = 1 + } + hwnd := uintptr(native) + if r, _, _ := dwmSetWindowAttribute.Call(hwnd, dwmaDarkMode, uintptr(unsafe.Pointer(&dark)), 4); r != 0 { + _, _, _ = dwmSetWindowAttribute.Call(hwnd, dwmaDarkModeLegacy, uintptr(unsafe.Pointer(&dark)), 4) + } +} diff --git a/app/windows/titles.go b/app/windows/titles.go new file mode 100644 index 00000000..1b49d011 --- /dev/null +++ b/app/windows/titles.go @@ -0,0 +1,67 @@ +package windows + +import "github.com/rclone/rclone-ui/core/i18n" + +// Title returns the title of the window named name ("Settings", "Wizard") in the app's language. +// The window gets it when it is made, so its title bar never shows another language while its +// page loads. The pages hold the same titles (src/routes.ts) and set them again once they have +// loaded, which also follows a change of language. A test keeps the two lists the same. +// +// A window without a title of its own (the startup screen, the launcher) keeps its name. +func Title(name string) string { + if title, ok := titleOf(name); ok { + return title + } + return name +} + +// titleOf returns the title of the window named name, and false for a name that isn't one of the +// app's titled windows. +func titleOf(name string) (string, bool) { + switch name { + case "Settings": + return i18n.T("Settings"), true + case "Remotes": + return i18n.T("Remotes"), true + case "Notifications": + return i18n.T("Notifications"), true + case "MobileRemoteControl": + return i18n.T("Mobile & Remote Control"), true + case "Sync": + return i18n.T("Sync"), true + case "Copy": + return i18n.T("Copy"), true + case "Move": + return i18n.T("Move"), true + case "Delete": + return i18n.T("Delete"), true + case "Purge": + return i18n.T("Purge"), true + case "Download": + return i18n.T("Download"), true + case "Serve": + return i18n.T("Serve"), true + case "Bisync": + return i18n.T("Bisync"), true + case "Commander": + return i18n.T("Commander"), true + case "Mount": + return i18n.T("Mount"), true + case "History": + return i18n.T("History"), true + case "Templates": + return i18n.T("Templates"), true + case "Watchers": + return i18n.T("Watchers"), true + case "Schedules": + return i18n.T("Schedules"), true + case "Automounts": + return i18n.T("Automounts"), true + case "Wizard": + // i18n: The title of the window that asks what to do and finds the operation for it. + return i18n.T("Run"), true + case "Guides": + return i18n.T("Guides"), true + } + return "", false +} diff --git a/app/windows/titles_test.go b/app/windows/titles_test.go new file mode 100644 index 00000000..586e157c --- /dev/null +++ b/app/windows/titles_test.go @@ -0,0 +1,83 @@ +package windows + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/leonelquinteros/gotext" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// A route of src/routes.ts and the title of its look: "settings: {" and, a few lines down, +// "look: { title: t`Settings`". +var routeTitle = regexp.MustCompile("(?s)\\n ([a-z]+): \\{[^}]*?title: t`([^`]+)`") + +// The titles that Go gives the windows are the pages' own (src/routes.ts), so a window's title +// doesn't change when its page has loaded. In another language, a title is translated. +func TestTitlesMatchThePages(t *testing.T) { + src, err := os.ReadFile("../../src/routes.ts") + if err != nil { + t.Fatal(err) + } + found := routeTitle.FindAllStringSubmatch(string(src), -1) + if len(found) < 20 { + t.Fatalf("only %d titles were read from src/routes.ts: has its layout changed?", len(found)) + } + for _, m := range found { + route, title := m[1], m[2] + name := strings.ToUpper(route[:1]) + route[1:] + if got, _ := ForRoute("/" + route); got != name { + t.Errorf("the window of /%s is named %q, want %q", route, got, name) + } + if got := Title(name); got != title { + t.Errorf("Title(%q) = %q, but its page's title is %q", name, got, title) + } + } + if got := Title("Startup"); got != "Startup" { + t.Errorf("a window without a title of its own: %q", got) + } + + i18n.SetLanguage(i18n.Pseudo) + t.Cleanup(func() { i18n.SetLanguage(i18n.English) }) + if got := Title("Settings"); got != "[Séttíñgs]" { + t.Errorf("in another language: %q", got) + } +} + +// A title is translated twice: for Go, which gives it to the window (core.po), and for the page, +// which sets it again once it has loaded (app.po). The two translations must be the same in every +// language, or the title would change under the user's eyes. +func TestTitlesAreTranslatedTheSameOnBothSides(t *testing.T) { + src, err := os.ReadFile("../../src/routes.ts") + if err != nil { + t.Fatal(err) + } + catalog := func(lang, file string) *gotext.Po { + b, err := os.ReadFile(filepath.Join("../../locales", lang, file)) + if err != nil { + t.Fatal(err) + } + po := gotext.NewPo() + po.Parse(b) + return po + } + for _, lang := range i18n.Languages() { + if lang == i18n.English { + continue + } + core, app := catalog(lang, "core.po"), catalog(lang, "app.po") + for _, m := range routeTitle.FindAllStringSubmatch(string(src), -1) { + title := m[2] + // Each catalog is asked for the translation alone. The methods are held in variables + // because vet takes them for fmt.Sprintf. + fromCore, fromApp := core.Get, app.Get + if c, a := fromCore(title), fromApp(title); c != a { + t.Errorf("%s: %q is %q for Go and %q for the page", lang, title, c, a) + } + } + } +} diff --git a/app/windows/windows.go b/app/windows/windows.go new file mode 100644 index 00000000..68138126 --- /dev/null +++ b/app/windows/windows.go @@ -0,0 +1,370 @@ +// Package windows opens and finds the app's windows, and sets their sizes and placement. A route +// decides its window's name and shape (see ForRoute). Opening a route whose window is already open +// focuses that window and passes it the route. Standard windows cascade around the screen's +// centre. +package windows + +import ( + "context" + "errors" + "log/slog" + "runtime" + "sync" + "sync/atomic" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/events" + + "github.com/rclone/rclone-ui/app/interaction" + "github.com/rclone/rclone-ui/app/platform" +) + +// The events that a window receives alone. +const ( + // EventCloseAsked tells a window that the user asked to close it while its page guards the + // close (see GuardClose). The page asks the user, and closes the window itself. + EventCloseAsked = "window:close" + // EventRoute tells an open window to switch to a route, which is the event's data. Opening a + // route whose window is already open sends it (see Open). + EventRoute = "window:route" +) + +// Default size of a standard window. +const ( + DefaultWidth = 840 + DefaultHeight = 725 +) + +type Manager struct { + app *application.App + log *slog.Logger + production bool + mu sync.Mutex + // Opened is called with the name of each of the app's own windows as it opens ("Commander"). + // The shell sets it once, before any window opens. + Opened func(name string) + // closing is set when the app is quitting. After that, no window shows again. + closing atomic.Bool + + themeMu sync.Mutex + themes map[string]string // each window's theme, as its page set it with SetTheme + theme string // the theme a page set last, which new windows start with + + guardMu sync.Mutex + guarded map[string]bool // the windows whose pages asked to confirm a close (GuardClose) +} + +func New(app *application.App, log *slog.Logger, production bool) *Manager { + m := &Manager{app: app, log: log, production: production, themes: map[string]string{}, guarded: map[string]bool{}} + if runtime.GOOS == "windows" { + // Windows are created with an explicit theme (see base), so that Wails doesn't reapply + // the system's theme on every change. Windows that follow the system are updated here + // instead. + app.Event.OnApplicationEvent(events.Windows.SystemThemeChanged, func(*application.ApplicationEvent) { + m.reapplyThemes() + }) + } + return m +} + +// Closing tells the Manager that the app is quitting. From then on, no window opens or shows, not +// even one whose page is still loading. +func (m *Manager) Closing() { m.closing.Store(true) } + +func (m *Manager) Get(name string) (application.Window, bool) { + return m.app.Window.GetByName(name) +} + +// Caller returns the window whose page made a bound call, from the call's context. It returns +// false when the call didn't come from a window. +func Caller(ctx context.Context) (application.Window, bool) { + w, ok := ctx.Value(application.WindowKey).(application.Window) + return w, ok && w != nil +} + +// dispatcher is a window that can receive an event of its own. +type dispatcher interface { + DispatchWailsEvent(event *application.CustomEvent) +} + +// route tells an open window to switch to url. The event goes to that window alone, because +// Wails' Emit would send it to every window. +func route(w dispatcher, url string) { + w.DispatchWailsEvent(&application.CustomEvent{Name: EventRoute, Data: url}) +} + +// reuse brings an open window to the front and passes it the route. It returns false when no such +// window is open. +func (m *Manager) reuse(name, url string) bool { + w, ok := m.app.Window.GetByName(name) + if !ok { + return false + } + if url != "" { + route(w, url) + } + if w.IsMinimised() { + w.UnMinimise() + } + w.Show() + w.Focus() + return true +} + +func (m *Manager) primary() (*application.Screen, error) { + if s := m.app.Screen.GetPrimary(); s != nil { + return s, nil + } + if all := m.app.Screen.GetAll(); len(all) > 0 { + return all[0], nil + } + return nil, errors.New("no screen found") +} + +// openCount returns the number of visible windows that a new window cascades from. The startup +// window doesn't count. +func (m *Manager) openCount() int { + n := 0 + for _, w := range m.app.Window.GetAll() { + if name := w.Name(); name != Startup && w.IsVisible() { + n++ + } + } + return n +} + +// Open opens the window for a route, such as "/remotes?action=create", in the shape that the route +// gives it (see ForRoute). If the window is already open, Open focuses it and passes it the route. +func (m *Manager) Open(url string) error { + name, shape := ForRoute(url) + m.mu.Lock() + defer m.mu.Unlock() + if m.closing.Load() { + return errors.New("the app is quitting") + } + if m.reuse(name, url) { + return nil + } + screen, err := m.primary() + if err != nil { + return err + } + opts := m.base(name, url) + opts.Screen = screen + switch shape { + case Full: + m.openFull(opts, screen) + case Small: + m.openSmall(opts, screen) + default: + m.openStandard(opts, screen) + } + // Only the app's own windows are named: a route from outside can't put its text there. + if _, own := titleOf(name); own && m.Opened != nil { + m.Opened(name) + } + return nil +} + +func (m *Manager) openStandard(opts application.WebviewWindowOptions, screen *application.Screen) { + w, h := DefaultWidth, DefaultHeight + minW, minH := 650, 500 + maxW, maxH := 1000, 1000 + if runtime.GOOS == "linux" { + minW, minH = 700, 700 + } + ts := platform.TextScale() + w, h = grow(w, ts), grow(h, ts) + minW, minH = grow(minW, ts), grow(minH, ts) + maxW, maxH = grow(maxW, ts), grow(maxH, ts) + area := Area{Width: screen.WorkArea.Width, Height: screen.WorkArea.Height} + // A small screen at a high display scale can be smaller than the default size. + w, h = min(w, area.Width), min(h, area.Height) + minW, minH = min(minW, w), min(minH, h) + var x, y int + if runtime.GOOS == "linux" { + x, y = Center(area, w, h) + } else { + x, y = Cascade(area, w, h, m.openCount()) + } + opts.Width, opts.Height = w, h + opts.MinWidth, opts.MinHeight = minW, minH + opts.MaxWidth, opts.MaxHeight = maxW, maxH + opts.InitialPosition = application.WindowXY + opts.X, opts.Y = x, y + opts.Mac.TitleBar = overlayTitleBar + m.showWhenReady(m.app.Window.NewWithOptions(opts), nil) +} + +func (m *Manager) openFull(opts application.WebviewWindowOptions, screen *application.Screen) { + opts.Width, opts.Height = screen.WorkArea.Width, screen.WorkArea.Height + opts.InitialPosition = application.WindowCentered + opts.Mac.TitleBar = overlayTitleBar + m.showWhenReady(m.app.Window.NewWithOptions(opts), nil) +} + +func (m *Manager) openSmall(opts application.WebviewWindowOptions, screen *application.Screen) { + // The page has a fixed layout and the window can't be resized. When the screen is too small + // for it, the page is zoomed out to fit. + opts.Width, opts.Height, opts.Zoom = fit(800, 500, platform.TextScale(), Area{Width: screen.WorkArea.Width, Height: screen.WorkArea.Height}) + opts.Frameless = true + opts.DisableResize = true + opts.CloseButtonState = application.ButtonDisabled + opts.MinimiseButtonState = application.ButtonHidden + opts.MaximiseButtonState = application.ButtonHidden + opts.InitialPosition = application.WindowCentered + opts.Mac.DisableShadow = true + if runtime.GOOS == "darwin" { + // Transparent WebKitGTK windows can fail to render with Wayland DMA-BUF, so the window is + // opaque on Linux. It is opaque on Windows too. + opts.BackgroundType = application.BackgroundTypeTransparent + } + win := m.app.Window.NewWithOptions(opts) + m.showWhenReady(win, func() { + // On Windows, a window put on top covers every ordinary window, the app's own dialogs and + // prompts included. One that opened before this window, such as the config password's + // prompt, keeps it an ordinary window. + if runtime.GOOS == "windows" && interaction.Open() { + return + } + win.SetAlwaysOnTop(true) + }) +} + +// base returns the options that every window shares. The window's title is the one its page has, +// in the app's language (Title), so the title bar is right before the page has loaded. +func (m *Manager) base(name, url string) application.WebviewWindowOptions { + m.themeMu.Lock() + theme := m.theme + m.themeMu.Unlock() + return application.WebviewWindowOptions{ + Name: name, + Title: Title(name), + URL: url, + Hidden: true, + Zoom: 1, + ZoomControlEnabled: false, + DevToolsEnabled: !m.production, + DefaultContextMenuDisabled: m.production, + // Never use SystemDefault. With it, Wails reapplies the system's theme to the title bar + // every time the system's theme changes, replacing the theme that the app's settings + // force. New handles the system's changes for the windows that follow it. + Windows: application.WindowsWindow{Theme: windowsTheme(theme)}, + } +} + +// overlayTitleBar puts the traffic lights over the content, without the window's title. The +// pages leave room for the traffic lights. Each window keeps its title for the Window menu and +// Mission Control. It only applies on macOS: Windows and Linux show the title in their title bar. +var overlayTitleBar = application.MacTitleBar{ + AppearsTransparent: true, + FullSizeContent: true, + HideTitle: true, +} + +// showWhenReady shows a window that was created hidden once its page has loaded the Wails +// runtime, so it never flashes white. After 2 seconds it is shown anyway. +func (m *Manager) showWhenReady(w *application.WebviewWindow, after func()) { + m.hookClose(w) + var once sync.Once + show := func() { + once.Do(func() { + if m.closing.Load() { + return + } + w.Show() + w.Focus() + if after != nil { + after() + } + }) + } + w.OnWindowEvent(events.Common.WindowRuntimeReady, func(*application.WindowEvent) { show() }) + time.AfterFunc(2*time.Second, show) +} + +// GuardClose sets whether closing the named window asks its page first. A page guards its window +// while it holds unsaved changes. A guarded window doesn't close: it gets EventCloseAsked, and its +// page asks the user, then stops the guard and closes the window itself. A quit closes every +// window without asking, because the quit flow asks about what is running. +func (m *Manager) GuardClose(name string, on bool) { + m.guardMu.Lock() + defer m.guardMu.Unlock() + if on { + m.guarded[name] = true + } else { + delete(m.guarded, name) + } +} + +func (m *Manager) isGuarded(name string) bool { + m.guardMu.Lock() + defer m.guardMu.Unlock() + return m.guarded[name] +} + +// hookClose stops the close of a guarded window and tells its page (see GuardClose). A page that +// loads again starts unguarded, so a reload can never leave a window that won't close. +func (m *Manager) hookClose(w *application.WebviewWindow) { + name := w.Name() + m.GuardClose(name, false) + w.RegisterHook(events.Common.WindowClosing, func(e *application.WindowEvent) { + if m.closing.Load() || !m.isGuarded(name) { + return + } + e.Cancel() + w.DispatchWailsEvent(&application.CustomEvent{Name: EventCloseAsked}) + }) + w.OnWindowEvent(events.Common.WindowRuntimeReady, func(*application.WindowEvent) { + m.GuardClose(name, false) + }) +} + +// SetTheme sets a window's appearance: "dark", "light", or "" to follow the system. Wails only +// sets the theme when a window is created, so this also sets it on an open window (see setTheme, +// which has one version per OS). Windows opened later start with this theme. +func (m *Manager) SetTheme(w application.Window, theme string) { + m.themeMu.Lock() + m.themes[w.Name()], m.theme = theme, theme + m.themeMu.Unlock() + native := w.NativeWindow() + if native == nil { + return + } + application.InvokeSync(func() { setTheme(native, theme) }) +} + +// reapplyThemes sets each window's theme again after the system's theme changed, so that a window +// that follows the system picks up the new theme. Only Windows needs this. +func (m *Manager) reapplyThemes() { + for _, w := range m.app.Window.GetAll() { + native := w.NativeWindow() + if native == nil { + continue + } + m.themeMu.Lock() + theme, ok := m.themes[w.Name()] + if !ok { + theme = m.theme + } + m.themeMu.Unlock() + application.InvokeAsync(func() { setTheme(native, theme) }) + } +} + +// grow scales a size by the text scale. +func grow(v int, scale float64) int { return int(float64(v)*scale + 0.5) } + +// fit returns the size of a window whose page is w by h and is enlarged by scale, and the zoom +// that makes the page fit when area is smaller than that. +func fit(w, h int, scale float64, area Area) (width, height int, zoom float64) { + width, height, zoom = grow(w, scale), grow(h, scale), 1 + if area.Width <= 0 || area.Height <= 0 { + return width, height, zoom + } + if r := min(float64(area.Width)/float64(width), float64(area.Height)/float64(height)); r < 1 { + width, height, zoom = int(float64(width)*r), int(float64(height)*r), r + } + return width, height, zoom +} diff --git a/app/windows/windows_test.go b/app/windows/windows_test.go new file mode 100644 index 00000000..b24811ec --- /dev/null +++ b/app/windows/windows_test.go @@ -0,0 +1,62 @@ +package windows + +import ( + "context" + "testing" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// fakeWindow is a window for the tests. Only the methods that a test calls are implemented. +type fakeWindow struct { + application.Window + events []*application.CustomEvent +} + +func (w *fakeWindow) DispatchWailsEvent(event *application.CustomEvent) { + w.events = append(w.events, event) +} + +func TestCaller(t *testing.T) { + if _, ok := Caller(context.Background()); ok { + t.Fatal("a call from no window has a caller") + } + var none application.Window + if _, ok := Caller(context.WithValue(context.Background(), application.WindowKey, none)); ok { + t.Fatal("a nil window counts as the caller") + } + w := &fakeWindow{} + got, ok := Caller(context.WithValue(context.Background(), application.WindowKey, application.Window(w))) + if !ok || got != w { + t.Fatalf("caller %v, %v", got, ok) + } +} + +func TestRouteGoesToTheWindow(t *testing.T) { + w := &fakeWindow{} + route(w, "/templates?action=add") + if len(w.events) != 1 || w.events[0].Name != EventRoute || w.events[0].Data != "/templates?action=add" { + t.Fatalf("events %+v", w.events) + } +} + +func TestFit(t *testing.T) { + for _, c := range []struct { + scale float64 + area Area + w, h int + zoom float64 + name string + }{ + {1, Area{Width: 1920, Height: 1040}, 800, 500, 1, "plenty of room"}, + {1.5, Area{Width: 1920, Height: 1040}, 1200, 750, 1, "larger text, still room"}, + {1.5, Area{Width: 1124, Height: 556}, 889, 556, 556.0 / 750, "larger text on a small screen"}, + {1, Area{Width: 640, Height: 400}, 640, 400, 0.8, "a screen smaller than the page"}, + {1, Area{}, 800, 500, 1, "an unknown screen"}, + } { + w, h, zoom := fit(800, 500, c.scale, c.area) + if w != c.w || h != c.h || zoom < c.zoom-0.001 || zoom > c.zoom+0.001 { + t.Errorf("%s: got %dx%d zoom %.3f, want %dx%d zoom %.3f", c.name, w, h, zoom, c.w, c.h, c.zoom) + } + } +} diff --git a/biome.json b/biome.json index 7e001662..64bdc824 100644 --- a/biome.json +++ b/biome.json @@ -1,55 +1,297 @@ { - "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", - "organizeImports": { - "enabled": true + "$schema": "https://biomejs.dev/schemas/2.6.6/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "includes": [ + "**", + "!!**/lib/shell/bindings", + "!!**/testdata", + "!!**/locales/*/rclone.json", + "!!**/.claude", + "!**/package.json", + "!!**/app/launcher/view/linux/gnome", + "!**/*.md", + "!**/*.yml", + "!**/*.yaml", + "!**/*.html" + ] + }, + "assist": { + "actions": { + "source": { + "organizeImports": "on" + } + } }, "linter": { "enabled": true, "rules": { "a11y": { - "all": true, + "preset": "all", + "noAmbiguousAnchorText": "off", + "noNoninteractiveElementInteractions": "off", + "noStaticElementInteractions": "off", "noSvgWithoutTitle": "off", - "useKeyWithClickEvents": "off" + "useAriaPropsSupportedByRole": "off", + "useKeyWithClickEvents": "off", + "useValidAutocomplete": "off" }, "complexity": { - "all": true, + "preset": "all", + "noAdjacentSpacesInRegex": "off", + "noDivRegex": "off", + "noExcessiveCognitiveComplexity": "off", + "noExcessiveLinesPerFunction": "off", + "noExcessiveNestedCallbacks": "off", + "noExcessiveSelectorClasses": "off", + "noImplicitCoercions": "off", + "noImportantStyles": "off", + "noPlaywrightUselessAwait": "off", + "noRedundantDefaultExport": "off", + "noUnnecessaryTemplateExpression": "off", + "noUselessCatchBinding": "off", + "noUselessContinue": "off", + "noUselessEscapeInRegex": "off", + "noUselessReturn": "off", + "noUselessStringRaw": "off", "noUselessTypeConstraint": "off", - "useSimplifiedLogicExpression": "off", - "noExcessiveCognitiveComplexity": "off" + "noUselessUndefined": "off", + "useArrayFind": "off", + "useArraySome": "off", + "useIndexOf": "off", + "useMathMinMax": "off", + "useMaxParams": "off", + "useRegexpTest": "off", + "useSimplifiedLogicExpression": "off" }, "correctness": { - "all": true, - "useImportExtensions": "off" + "preset": "all", + "noBeforeInteractiveScriptOutsideDocument": "off", + "noComponentHookFactories": "off", + "noDuplicateArgumentNames": "off", + "noDuplicateAttributes": "off", + "noDuplicateEnumValueNames": "off", + "noDuplicateFieldDefinitionNames": "off", + "noDuplicateInputFieldNames": "off", + "noDuplicateVariableNames": "off", + "noGlobalDirnameFilename": "off", + "noJsxNamespace": "off", + "noMissingVarFunction": "off", + "noNestedComponentDefinitions": "off", + "noNextAsyncClientComponent": "off", + "noPlaywrightMissingAwait": "off", + "noPrivateImports": "off", + "noProcessGlobal": "off", + "noQwikUseVisibleTask": "off", + "noReactNativeRawText": "off", + "noReactPropAssignments": "off", + "noRestrictedElements": "off", + "noSolidDestructuredProps": "off", + "noUnknownPseudoClass": "off", + "noUnknownPseudoElement": "off", + "noUnknownTypeSelector": "off", + "noUnresolvedImports": "off", + "noUnusedInstantiation": "off", + "noVueDataObjectDeclaration": "off", + "noVueDuplicateKeys": "off", + "noVueImportCompilerMacros": "off", + "noVueRefAsOperand": "off", + "noVueReservedKeys": "off", + "noVueReservedProps": "off", + "noVueSetupPropsReactivityLoss": "off", + "noVueVIfWithVFor": "off", + "noVueVOnNumberValues": "off", + "useGraphqlNamedOperations": "off", + "useImageSize": "off", + "useImportExtensions": "off", + "useInlineScriptId": "off", + "useJsonImportAttributes": "off", + "useLoneAnonymousOperation": "off", + "useParseIntRadix": "off", + "usePlaywrightValidDescribeCallback": "off", + "useQwikClasslist": "off", + "useQwikLoaderLocation": "off", + "useQwikMethodUsage": "off", + "useQwikValidLexicalScope": "off", + "useReactAsyncServerFunction": "off", + "useReactNativePlatformComponents": "off", + "useSingleJsDocAsterisk": "off", + "useUniqueElementIds": "off", + "useValidTypeof": "off", + "useVueVForKey": "off", + "useVueValidTemplateRoot": "off", + "useVueValidVBind": "off", + "useVueValidVCloak": "off", + "useVueValidVElse": "off", + "useVueValidVElseIf": "off", + "useVueValidVFor": "off", + "useVueValidVHtml": "off", + "useVueValidVIf": "off", + "useVueValidVOn": "off", + "useVueValidVOnce": "off", + "useVueValidVPre": "off", + "useVueValidVText": "off" }, "performance": { - "all": true + "preset": "all", + "noAwaitInLoops": "off", + "noDynamicNamespaceImportAccess": "off", + "noImgElement": "off", + "noJsxPropsBind": "off", + "noSyncScripts": "off", + "noUnwantedPolyfillio": "off", + "useDomNodeTextContent": "off", + "useGoogleFontPreconnect": "off", + "useSolidForComponent": "off", + "useVueVapor": "off" }, "security": { - "all": true + "preset": "all", + "noScriptUrl": "off", + "noSecrets": "off", + "useIframeSandbox": "off" }, "style": { - "all": true, - "useTemplate": "off", + "preset": "all", + "noCommonJs": "off", + "noContinue": "off", + "noDefaultExport": "off", + "noDescendingSpecificity": "off", + "noEnum": "off", + "noExcessiveClassesPerFile": "off", + "noExcessiveLinesPerFile": "off", + "noExportedImports": "off", + "noHeadElement": "off", + "noHexColors": "off", + "noIncrementDecrement": "off", + "noInferrableTypes": "off", + "noInlineStyles": "off", + "noJsxLiterals": "off", + "noMagicNumbers": "off", + "noMultiAssign": "off", + "noMultilineString": "off", + "noNestedTernary": "off", "noNonNullAssertion": "off", + "noPlaywrightElementHandle": "off", + "noPlaywrightEval": "off", + "noPlaywrightWaitForSelector": "off", + "noProcessEnv": "off", + "noReactNativeLiteralColors": "off", + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["**/core/api"], + "message": "Call the core through its domain module: lib/.ts, or the module next to the only feature that uses the domain. Biome's overrides list the modules that may import lib/core/api." + } + ] + } + }, + "noRestrictedTypes": "off", + "noRootType": "off", + "noSubstr": "off", + "noTernary": "off", + "noTopLevelLiterals": "off", + "noValueAtRule": "off", + "noVueOptionsApi": "off", + "useAtIndex": "off", "useBlockStatements": "off", - "noInferrableTypes": "off", - "noDefaultExport": "off", + "useCollapsedIf": "off", + "useComponentExportOnlyModules": "off", + "useConsistentArrowReturn": "off", + "useConsistentCurlyBraces": "off", + "useConsistentEnumValueType": "off", + "useConsistentGraphqlDescriptions": "off", + "useConsistentMemberAccessibility": "off", + "useConsistentMethodSignatures": "off", + "useConsistentObjectDefinitions": "off", + "useConsistentTestIt": "off", + "useConsistentTypeDefinitions": "off", + "useDeprecatedReason": "off", + "useDestructuring": "off", + "useDomQuerySelector": "off", + "useErrorCause": "off", + "useExportsLast": "off", + "useForOf": "off", + "useGlobalThis": "off", + "useGraphqlNamingConvention": "off", + "useGroupedAccessorPairs": "off", + "useImportsFirst": "off", + "useInputName": "off", + "useLoneExecutableDefinition": "off", + "useNamedCaptureGroup": "off", "useNamingConvention": "off", - "useForOf": "off" + "useNumericSeparators": "off", + "useObjectSpread": "off", + "useReactFunctionComponents": "off", + "useReadonlyClassProperties": "off", + "useReduceTypeParameter": "off", + "useSpreadOverApply": "off", + "useSymbolDescription": "off", + "useTemplate": "off", + "useTestHooksInOrder": "off", + "useTestHooksOnTop": "off", + "useThisInClassMethods": "off", + "useTrimStartEnd": "off", + "useUnicodeRegex": "off", + "useUnifiedTypeSignatures": "off", + "useVarsOnTop": "off", + "useVueConsistentDefinePropsDeclaration": "off", + "useVueConsistentVBindStyle": "off", + "useVueConsistentVOnStyle": "off", + "useVueDefineMacrosOrder": "off", + "useVueHyphenatedAttributes": "off", + "useVueMultiWordComponentNames": "off", + "useVueNextTickPromise": "off" }, "suspicious": { - "all": false + "preset": "none", + "noVar": "on", + "noWith": "on" } }, - "ignore": ["node_modules/*", "dist/*", ".work/*", "*.js"] + "includes": ["**", "!**/node_modules/**/*", "!**/dist/**/*", "!**/.work/**/*", "!**/*.js"] }, + "overrides": [ + { + "includes": [ + "lib/**", + "src/components/navigator/favorites.ts", + "src/components/navigator/fsActions.ts", + "src/components/navigator/preview/media.ts", + "src/components/navigator/streams.ts", + "src/components/navigator/useDiskUsage.ts", + "src/components/navigator/useDisks.ts", + "src/components/operation/landings.ts", + "src/components/operation/useFormRefusal.ts", + "src/pages/MobileRemoteControl/tunnel.ts", + "src/pages/Serve/serves.ts", + "src/pages/Settings/launcherHistory.ts", + "src/pages/Settings/logs.ts", + "src/pages/Watchers/watchers.ts", + "src/pages/downloadSites.ts" + ], + "linter": { + "rules": { + "style": { + "noRestrictedImports": "off" + } + } + } + } + ], "formatter": { "enabled": true, "formatWithErrors": true, "indentStyle": "space", "indentWidth": 4, "lineWidth": 100, - "ignore": ["node_modules/*", "dist/*", ".work/*"] + "includes": ["**", "!**/node_modules/**/*", "!**/dist/**/*", "!**/.work/**/*"] }, "javascript": { "formatter": { @@ -57,7 +299,11 @@ "quoteProperties": "preserve", "trailingCommas": "es5", "semicolons": "asNeeded" - }, - "globals": ["it", "describe", "expect", "test"] + } + }, + "css": { + "parser": { + "tailwindDirectives": true + } } } diff --git a/build/build.sh b/build/build.sh new file mode 100755 index 00000000..49a85d02 --- /dev/null +++ b/build/build.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# Builds rcui for GOOS/GOARCH (default: this machine) the way releases are built, with the +# frontend embedded and compressed, and with the release tags. CI and local builds both use this +# script, so the tags are defined in one place. +# +# build/build.sh # this machine → build/bin/-/rcui +# GOOS=windows GOARCH=arm64 build/build.sh +# build/build.sh --skip-frontend # reuse app/assets/dist +# build/build.sh --print-tags # print the tags for GOOS/GOARCH +# build/build.sh --vet # go vet ./... as GOOS/GOARCH builds (embeds app/assets/dist) +# POSTHOG_KEY=phc_… build/build.sh # a build that sends usage data (see below) +set -euo pipefail +cd "$(dirname "$0")/.." + +skip_frontend=false +mode=build +for arg in "$@"; do + case $arg in + --skip-frontend) skip_frontend=true ;; + --print-tags) mode=print-tags ;; + --vet) mode=vet ;; + *) echo "unknown argument: $arg" >&2; exit 2 ;; + esac +done + +goos=${GOOS:-$(go env GOOS)} +goarch=${GOARCH:-$(go env GOARCH)} + +# On every platform, embed the pages and leave out rclone's selfupdate, because ours replaces it. +tags=production,noselfupdate +ldflags="-s -w" +cgo=1 +exe=rcui +case $goos in + windows) + # Mount with WinFsp, which works without cgo. Build a GUI executable. The CLI roles attach + # to the terminal themselves. + tags+=,cmount + ldflags+=" -H windowsgui" + cgo=0 + exe=rcui.exe + ;; + darwin) + # Needed for the transparent Startup window. + tags+=,private_mac_apis + # Target macOS 12 and later. The external linker reads MACOSX_DEPLOYMENT_TARGET. The cgo + # compiles also get the minimum version as a flag, because Go's build cache hashes + # CGO_CFLAGS and CGO_LDFLAGS but not that variable. Without the flag, the cache would + # reuse objects compiled for this Mac's own version. + export MACOSX_DEPLOYMENT_TARGET=12.0 + export CGO_CFLAGS="${CGO_CFLAGS:--O2 -g} -mmacosx-version-min=12.0" + export CGO_LDFLAGS="${CGO_LDFLAGS:--O2 -g} -mmacosx-version-min=12.0" + ;; + linux) + # Linux builds need no tag. They use Wails' default stack, GTK 4 with WebKitGTK 6.0, and + # they link gtk4-layer-shell, so its development files must be installed too. + ;; +esac + +# --print-tags and --vet stop here. They don't read the version, so they need neither node nor +# the module graph. +case $mode in + print-tags) + echo "$tags" + exit 0 + ;; + vet) + echo "vetting ./... ($goos/$goarch, tags $tags)" + CGO_ENABLED=$cgo GOOS=$goos GOARCH=$goarch go vet -tags "$tags" ./... + exit 0 + ;; +esac + +version=${APP_VERSION:-$(node -p "require('./package.json').version")} +# rclone's version is the version of the rclone module. rclone's own releases set fs.Version the +# same way. +rclone_version=$(go list -m -f '{{.Version}}' github.com/rclone/rclone) +ldflags+=" -X github.com/rclone/rclone-ui/core/version.App=$version -X github.com/rclone/rclone/fs.Version=$rclone_version" +# The PostHog key can only add events, so it isn't a secret. A build without it sends nothing. +if [ -n "${POSTHOG_KEY:-}" ]; then + ldflags+=" -X github.com/rclone/rclone-ui/core/telemetry.Key=$POSTHOG_KEY" +fi + +if ! $skip_frontend; then + # The pages call the Go code through the generated bindings, so a release must not embed + # bindings that are out of date. + env -u GOOS -u GOARCH build/check.sh bindings + npm run build + env -u GOOS -u GOARCH go -C tools run ./zstdassets -src ../dist -dst ../app/assets/dist +fi + +out=build/bin/$goos-$goarch/$exe +mkdir -p "$(dirname "$out")" + +if [ "$goos" = windows ]; then + # Make a .syso with rcui.exe's icon, version and manifest (DPI awareness, common controls). + # The Go linker picks it up from the main package. It is made for this build and removed + # afterwards. @FILEVERSION@ needs four numbers, so a pre-release such as 4.0.0-beta.1 + # becomes 4.0.0.0. + res=$(mktemp -d) + trap 'rm -rf "$res" rcui_windows_'"$goarch"'.syso' EXIT + subst=(-e "s/@VERSION@/$version/g" -e "s/@FILEVERSION@/${version%%[-+]*}.0/g") + sed "${subst[@]}" build/windows/rcui.exe.manifest > "$res/rcui.exe.manifest" + sed "${subst[@]}" build/windows/info.json > "$res/info.json" + env -u GOOS -u GOARCH go tool -modfile=tools/go.mod wails3 generate syso -arch "$goarch" -icon build/windows/icon.ico \ + -manifest "$res/rcui.exe.manifest" -info "$res/info.json" -out "rcui_windows_$goarch.syso" +fi + +echo "building $out ($goos/$goarch, tags $tags)" +CGO_ENABLED=$cgo GOOS=$goos GOARCH=$goarch \ + go build -trimpath -tags "$tags" -ldflags "$ldflags" -o "$out" . + +if [ "$goos" = windows ]; then + # The console rclone.exe that the installer puts in \bin, for the PATH option. + shim="$(dirname "$out")/bin/rclone.exe" + echo "building $shim" + CGO_ENABLED=0 GOOS=$goos GOARCH=$goarch \ + go build -trimpath -ldflags "-s -w" -o "$shim" ./build/windows/rclone-shim +fi diff --git a/build/check.sh b/build/check.sh new file mode 100755 index 00000000..44cc3dd6 --- /dev/null +++ b/build/check.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# Runs the checks that CI runs. They come in three parts, and all three run when none is named. +# The script keeps going after a failure, so one run shows every problem. At the end it fails and +# lists the steps that failed. +# +# build/check.sh # frontend, api and go +# build/check.sh frontend api # only these parts +# build/check.sh --race go # go test with the race detector +# build/check.sh bindings # only the bindings check (build.sh runs it) +# +# frontend tsc, biome ci, vitest +# api actionlint, go mod tidy -diff (root and tools), the third-party notices, the +# translations (that locales/ is in step with the code, that Spanish and Chinese +# are complete, and that every translation keeps its placeholders), that no +# tracked file still names an old identifier, and the bindings check. +# In CI, npm run gen replaces the bindings check: the generated code, which +# includes the launcher's icons, must not change. Outside CI nothing in the tree +# is regenerated, because the worktree may hold other work in progress. +# bindings generates the bindings into a temporary folder and compares them with +# lib/shell/bindings, so a bound API that changed without npm run gen is caught. +# go go vet and go test, build.sh --vet for this machine and for windows/arm64 (the +# only vet of the launcher's arm64-only files), and the tools' tests +set -euo pipefail +# Use the physical path, because npm names the root package by it, and build/notices finds the +# root package to skip by comparing the two. +cd -P "$(dirname "$0")/.." + +race=false +parts=() +for arg in "$@"; do + case $arg in + --race) race=true ;; + frontend | api | go | bindings) parts+=("$arg") ;; + *) echo "usage: build/check.sh [--race] [frontend|api|go|bindings]..." >&2; exit 2 ;; + esac +done +[ ${#parts[@]} -gt 0 ] || parts=(frontend api go) + +# Files and folders that this run wrote, which are removed on exit. The expansion guards against +# an empty array, which macOS's bash 3.2 treats as unbound under set -u. +cleanup=() +trap 'rm -rf ${cleanup[@]+"${cleanup[@]}"}' EXIT + +failed=() + +run() { + echo "==> $*" + if ! "$@"; then + failed+=("$*") + fi +} + +# placeholder gives a production build an app/assets/dist when the pages aren't built. The embed +# in app/assets/embed.go matches nothing in an empty folder, and go list and go vet reject that. +placeholder() { + [ -z "$(ls -A app/assets/dist 2>/dev/null)" ] || return 0 + mkdir -p app/assets/dist + echo 'build/check.sh placeholder' > app/assets/dist/index.html + cleanup+=(app/assets/dist/index.html) +} + +generated() { + npm run gen || return 1 + local changed + changed=$(git status --porcelain -- lib/shell/bindings app/launcher/icons) + if [ -n "$changed" ]; then + echo "$changed" >&2 + echo "generated code is out of date: run npm run gen" >&2 + return 1 + fi +} + +bindings() { + local tmp + tmp=$(mktemp -d) + cleanup+=("$tmp") + go tool -modfile=tools/go.mod wails3 generate bindings -clean=true -d "$tmp" -ts || return 1 + if ! diff -r lib/shell/bindings "$tmp"; then + echo "the bindings are out of date: run npm run gen" >&2 + return 1 + fi +} + +# catalogs fails when the translations in locales/ are out of step with the code: a message that +# was added, changed or removed without `npm run i18n`. It runs npm run i18n and compares the +# result with what the tree had. Then it puts the tree's files back, so nothing is left changed. +catalogs() { + local before + before=$(mktemp -d) + cleanup+=("$before") + cp -R locales "$before/" + npm run --silent i18n >/dev/null || return 1 + if ! diff -r "$before/locales" locales; then + rm -rf locales + cp -R "$before/locales" locales + echo "the translations are out of date: run npm run i18n" >&2 + return 1 + fi +} + +# identifiers fails when a tracked file, other than a Markdown file, holds one of the old +# identifiers. The current ones are org.rclone.ui, Rclone.RcloneUI (on WinGet) and +# github.com/rclone/rclone-ui. +identifiers() { + local old=(-e 'com.rclone.ui' -e 'com.rcloneui' -e 'RcloneUI.RcloneUI' -e 'rclone-ui/rclone-ui') + if git grep -n -F "${old[@]}" -- ':!*.md' ':!build/check.sh'; then + echo "an old identifier is still used (above)" >&2 + return 1 + fi +} + +frontend() { + run npx tsc --noEmit -p . + run npx biome ci + run npx vitest run +} + +api() { + run go tool -modfile=tools/go.mod actionlint + run go mod tidy -diff + run go -C tools mod tidy -diff + placeholder + run go run ./build/notices -check + run catalogs + # The shipped languages are complete, and every translation keeps its placeholders. + run go run ./build/i18n -check + run identifiers + # In CI, generated checks the bindings in the tree itself. + if [ -n "${CI:-}" ]; then + run generated + else + run bindings + fi +} + +gocheck() { + local flags=() + run go vet ./... + if $race; then + flags+=(-race) + fi + run go test ${flags[@]+"${flags[@]}"} ./... + placeholder + run build/build.sh --vet + run env GOOS=windows GOARCH=arm64 build/build.sh --vet + run go -C tools test ./zstdassets/... +} + +for part in "${parts[@]}"; do + case $part in + frontend) frontend ;; + api) api ;; + go) gocheck ;; + bindings) run bindings ;; + esac +done + +if [ ${#failed[@]} -gt 0 ]; then + echo >&2 + echo "failed:" >&2 + printf ' %s\n' "${failed[@]}" >&2 + exit 1 +fi +echo "all checks passed (${parts[*]})" diff --git a/build/darwin/Info.plist b/build/darwin/Info.plist new file mode 100644 index 00000000..6dee01da --- /dev/null +++ b/build/darwin/Info.plist @@ -0,0 +1,57 @@ + + + + + CFBundlePackageType + APPL + CFBundleName + Rclone UI + CFBundleDisplayName + Rclone UI + CFBundleExecutable + rcui + CFBundleIdentifier + org.rclone.ui + CFBundleVersion + @VERSION@ + CFBundleShortVersionString + @VERSION@ + CFBundleInfoDictionaryVersion + 6.0 + CFBundleIconFile + icons + LSMinimumSystemVersion + 12.0 + LSApplicationCategoryType + public.app-category.utilities + + LSUIElement + + NSHighResolutionCapable + + NSHumanReadableCopyright + © Rclone + ITSAppUsesNonExemptEncryption + + + NSAppTransportSecurity + + NSAllowsLocalNetworking + + NSAllowsArbitraryLoadsInWebContent + + + CFBundleURLTypes + + + CFBundleURLName + org.rclone.ui + CFBundleURLSchemes + + rclone + + + + + diff --git a/src-tauri/icons/icon.icns b/build/darwin/icons.icns similarity index 100% rename from src-tauri/icons/icon.icns rename to build/darwin/icons.icns diff --git a/build/flatpak/org.rclone.ui.yml b/build/flatpak/org.rclone.ui.yml new file mode 100644 index 00000000..8d3f7206 --- /dev/null +++ b/build/flatpak/org.rclone.ui.yml @@ -0,0 +1,73 @@ +# The Flathub manifest of Rclone UI. It builds rcui from the release's tag offline: Go's modules +# (vendor/) and the built pages (app/assets/dist) come from the release's Rclone-UI-*-vendor.tar.gz, +# which the release workflow makes from the same commit. The release attaches this file with +# @VERSION@, @COMMIT@ and @SHA256@ filled in, for the Flathub repository. +app-id: org.rclone.ui +runtime: org.gnome.Platform +# GNOME 51 has GTK 4 and WebKitGTK 6.0, which is Wails' default stack. Its Go extension (from the +# 26.08 Freedesktop SDK) is new enough for go.mod. +runtime-version: '51' +sdk: org.gnome.Sdk +sdk-extensions: + - org.freedesktop.Sdk.Extension.golang +command: rcui +finish-args: + - --share=ipc + - --share=network + - --socket=wayland + - --socket=fallback-x11 + - --device=dri + # The tray, OS notifications, and the keychain (config passwords, the mail server's). + - --talk-name=org.kde.StatusNotifierWatcher + - --talk-name=org.freedesktop.Notifications + - --talk-name=org.freedesktop.secrets +build-options: + append-path: /usr/lib/sdk/golang/bin + env: + CGO_ENABLED: '1' + GOTOOLCHAIN: local + GOFLAGS: -mod=vendor -trimpath +modules: + # gtk4-layer-shell, which rcui links for the launcher. The launcher uses it where the + # compositor has layer-shell (KDE Plasma, COSMIC, the wlroots compositors). The GNOME runtime + # doesn't have it. + - name: gtk4-layer-shell + buildsystem: meson + config-opts: + - -Dintrospection=false + - -Dvapi=false + - -Dexamples=false + - -Ddocs=false + - -Dtests=false + post-install: + - install -Dm644 -t /app/share/licenses/gtk4-layer-shell LICENSE + sources: + - type: archive + url: https://github.com/wmww/gtk4-layer-shell/archive/refs/tags/v1.3.0.tar.gz + sha256: 1ebb01ab14e98afd1727f68f64981c37bd23305b1f131f5667c02b94cf593192 + x-checker-data: + type: json + url: https://api.github.com/repos/wmww/gtk4-layer-shell/releases/latest + version-query: .tag_name | sub("^v"; "") + url-query: '"https://github.com/wmww/gtk4-layer-shell/archive/refs/tags/v" + $version + ".tar.gz"' + - name: rclone-ui + buildsystem: simple + build-commands: + # Built like every release, with build.sh's tags and versions. The pages come from the + # vendor archive, and go list -m reads rclone's version from vendor/. + - APP_VERSION=@VERSION@ bash build/build.sh --skip-frontend + - install -Dm755 build/bin/linux-*/rcui /app/bin/rcui + - sed -e 's|^Exec=.*|Exec=rcui %u|' build/linux/org.rclone.ui.desktop > org.rclone.ui.desktop + - install -Dm644 org.rclone.ui.desktop /app/share/applications/org.rclone.ui.desktop + - install -Dm644 build/linux/org.rclone.ui.metainfo.xml /app/share/metainfo/org.rclone.ui.metainfo.xml + - for size in 32 128 256 512; do install -Dm644 build/linux/icons/${size}x${size}.png /app/share/icons/hicolor/${size}x${size}/apps/org.rclone.ui.png; done + - install -Dm644 -t /app/share/licenses/org.rclone.ui LICENSE public/THIRD_PARTY_NOTICES.txt + sources: + - type: git + url: https://github.com/rclone/rclone-ui.git + tag: v@VERSION@ + commit: '@COMMIT@' + - type: archive + url: https://github.com/rclone/rclone-ui/releases/download/v@VERSION@/Rclone-UI-@VERSION@-vendor.tar.gz + sha256: '@SHA256@' + strip-components: 0 diff --git a/build/i18n/extract.go b/build/i18n/extract.go new file mode 100644 index 00000000..38ef0cd6 --- /dev/null +++ b/build/i18n/extract.go @@ -0,0 +1,285 @@ +package main + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strconv" + "strings" +) + +// The packages whose calls carry text for the user. +const ( + i18nPath = "github.com/rclone/rclone-ui/core/i18n" + errsPath = "github.com/rclone/rclone-ui/core/errs" +) + +// call gives the positions of a function's arguments: the English format, the plural form, and +// the context (-1 when the function has none). +type call struct{ format, plural, ctx int } + +// calls lists the functions that take a message, by package path and name. +var calls = map[string]map[string]call{ + i18nPath: { + "T": {0, -1, -1}, "M": {0, -1, -1}, + "N": {0, 1, -1}, "MN": {0, 1, -1}, + "TC": {1, -1, 0}, "MC": {1, -1, 0}, + }, + errsPath: { + "New": {0, -1, -1}, "Errorf": {0, -1, -1}, "Precondition": {0, -1, -1}, "Canceled": {0, -1, -1}, + "Field": {1, -1, -1}, "NotFound": {1, -1, -1}, "Unsupported": {1, -1, -1}, "Violation": {1, -1, -1}, + }, +} + +type message struct { + ctx, id, plural string + notes []string + files map[string]bool +} + +type extraction struct { + messages map[string]*message + problems []string +} + +// roots are the folders of the Go code that shows text, relative to the repository. +var roots = []string{"app", "core", "main.go"} + +// extract collects the messages of the calls in `calls` from every Go file under dir's roots. It +// only parses the files, so it also reads the files that are built for other systems. A message +// must be a string constant, because a message that is put together at run time has no +// translation to look up. +func extract(dir string) (*extraction, error) { + x := &extraction{messages: map[string]*message{}} + var files []string + for _, root := range roots { + err := filepath.WalkDir(filepath.Join(dir, root), func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return nil + } + files = append(files, p) + return nil + }) + if err != nil { + return nil, err + } + } + sort.Strings(files) + fset := token.NewFileSet() + // A message may be a constant of its package, declared in any of its files. + parsed := map[string]*ast.File{} + consts := map[string]map[string]string{} // folder -> constant -> value + for _, p := range files { + f, err := parser.ParseFile(fset, p, nil, parser.ParseComments|parser.SkipObjectResolution) + if err != nil { + return nil, err + } + parsed[p] = f + folder := filepath.Dir(p) + if consts[folder] == nil { + consts[folder] = map[string]string{} + } + collectConsts(f, consts[folder]) + } + for _, p := range files { + rel, _ := filepath.Rel(dir, p) + rel = filepath.ToSlash(rel) + // core/errs is skipped, because its own calls only pass a caller's message on. core/i18n + // is read, because it also has messages of its own (a list's "and"), which it calls + // without the package's name. + if strings.HasPrefix(rel, "core/errs/") { + continue + } + x.file(fset, parsed[p], rel, consts[filepath.Dir(p)], strings.HasPrefix(rel, "core/i18n/")) + } + sort.Strings(x.problems) + return x, nil +} + +func collectConsts(f *ast.File, out map[string]string) { + for _, d := range f.Decls { + g, ok := d.(*ast.GenDecl) + if !ok || g.Tok != token.CONST { + continue + } + for _, spec := range g.Specs { + v := spec.(*ast.ValueSpec) + for i, name := range v.Names { + if i < len(v.Values) { + if s, ok := constant(v.Values[i], nil); ok { + out[name.Name] = s + } + } + } + } + } +} + +// constant returns the value of a string constant: a literal, a constant of the package, or +// several of them joined with +. +func constant(e ast.Expr, consts map[string]string) (string, bool) { + switch v := e.(type) { + case *ast.BasicLit: + if v.Kind != token.STRING { + return "", false + } + s, err := strconv.Unquote(v.Value) + return s, err == nil + case *ast.Ident: + s, ok := consts[v.Name] + return s, ok + case *ast.ParenExpr: + return constant(v.X, consts) + case *ast.BinaryExpr: + if v.Op != token.ADD { + return "", false + } + a, ok1 := constant(v.X, consts) + b, ok2 := constant(v.Y, consts) + return a + b, ok1 && ok2 + } + return "", false +} + +// file collects the messages of one file. +// own is true for core/i18n's own files, where the calls have no package name and a call whose +// message is a parameter only passes it on. +func (x *extraction) file(fset *token.FileSet, f *ast.File, rel string, consts map[string]string, own bool) { + // The names that this file gives the two packages. + names := map[string]string{} + for _, imp := range f.Imports { + path, _ := strconv.Unquote(imp.Path.Value) + if _, ok := calls[path]; !ok { + continue + } + // The errors of the agents' tools are read by a model, in English (core/agents). Only + // what that package says to the user, with core/i18n, is translated. + if path == errsPath && strings.HasPrefix(rel, "core/agents/") { + continue + } + name := filepath.Base(path) + if imp.Name != nil { + name = imp.Name.Name + } + names[name] = path + } + if len(names) == 0 && !own { + return + } + // A comment that starts with "i18n:" on the line above a call is a note for the translator. + // It belongs to the first message on that line, so a line with two messages needs the + // second one on a line of its own to have a note. + notes := map[int]string{} + noted := map[int]bool{} + for _, group := range f.Comments { + text := strings.TrimSpace(group.Text()) + if note, ok := strings.CutPrefix(text, "i18n:"); ok { + notes[fset.Position(group.End()).Line] = strings.Join(strings.Fields(note), " ") + } + } + ast.Inspect(f, func(n ast.Node) bool { + c, ok := n.(*ast.CallExpr) + if !ok { + return true + } + var spec call + var fn string + switch fun := c.Fun.(type) { + case *ast.SelectorExpr: + pkg, ok := fun.X.(*ast.Ident) + if !ok { + return true + } + if spec, ok = calls[names[pkg.Name]][fun.Sel.Name]; !ok { + return true + } + fn = pkg.Name + "." + fun.Sel.Name + case *ast.Ident: + if !own { + return true + } + if spec, ok = calls[i18nPath][fun.Name]; !ok { + return true + } + fn = fun.Name + default: + return true + } + pos := fset.Position(c.Pos()) + where := fmt.Sprintf("%s:%d", rel, pos.Line) + if len(c.Args) <= spec.format || spec.ctx >= len(c.Args) { + return true + } + id, ok := constant(c.Args[spec.format], consts) + if !ok { + if !own { + x.problems = append(x.problems, where+": the message of "+fn+" is not a string constant, so it can't be translated") + } + return true + } + ctx := "" + if spec.ctx >= 0 { + if ctx, ok = constant(c.Args[spec.ctx], consts); !ok { + x.problems = append(x.problems, where+": the context of "+fn+" is not a string constant") + return true + } + } + if strings.TrimSpace(strings.NewReplacer("%s", "", "%v", "", "%w", "").Replace(id)) == "" { + x.problems = append(x.problems, where+": the message of "+fn+" is only its value ("+strconv.Quote(id)+"), so it can't be translated") + return true + } + plural := "" + if spec.plural >= 0 { + if len(c.Args) <= spec.plural { + return true + } + if plural, ok = constant(c.Args[spec.plural], consts); !ok { + x.problems = append(x.problems, where+": the plural message of "+fn+" is not a string constant") + return true + } + } + key := ctx + "\x04" + id + m := x.messages[key] + if m == nil { + m = &message{ctx: ctx, id: id, plural: plural, files: map[string]bool{}} + x.messages[key] = m + } + if m.plural != plural { + x.problems = append(x.problems, where+": "+strconv.Quote(id)+" is used with two different plurals") + } + m.files[rel] = true + if note := notes[pos.Line-1]; note != "" && !noted[pos.Line] { + noted[pos.Line] = true + if !contains(m.notes, note) { + m.notes = append(m.notes, note) + } + } + return true + }) +} + +func contains(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} + +// readFile returns a file's text, or "" when it doesn't exist. +func readFile(path string) (string, error) { + b, err := os.ReadFile(path) + if os.IsNotExist(err) { + return "", nil + } + return string(b), err +} diff --git a/build/i18n/icu_test.go b/build/i18n/icu_test.go new file mode 100644 index 00000000..5173c0f5 --- /dev/null +++ b/build/i18n/icu_test.go @@ -0,0 +1,20 @@ +package main + +import "testing" + +func TestICUPlaceholders(t *testing.T) { + for msg, want := range map[string]string{ + "Delete {name}?": "{name}", + "{count, plural, one {# file} other {# files}}": "{count}", + "{0, plural, one {Yes, with # rule} other {Yes, with # rules}}": "{0}", + "Press <0>{key} to start": "<0> {key}", + "{n, selectordinal, one {#st} other {#th}} of {month}": "{month} {n}", + "Nothing to fill in": "", + "{n, plural, one {Keep} other {Keep them}} or {other}": "{n} {other}", + "{n, plural, =0 {None} other {# left}}": "{n}", + } { + if got := icuPlaceholders(msg); got != want { + t.Errorf("icuPlaceholders(%q) = %q, want %q", msg, got, want) + } + } +} diff --git a/build/i18n/main.go b/build/i18n/main.go new file mode 100644 index 00000000..fa0a137a --- /dev/null +++ b/build/i18n/main.go @@ -0,0 +1,341 @@ +// Command i18n keeps the translations in locales/ in step with the code (see locales/README.md). +// +// The windows' messages are collected by Lingui (`lingui extract`) into locales//app.po. +// This command does the same for the Go side: it reads the calls that carry text for the user +// (core/i18n's T, N, M and MN, and core/errs' constructors) and writes their messages to +// locales/en/core.po. It then brings every other language's core.po in step: a new message is +// added without a translation, and a message that the code no longer has is dropped. +// +// go run ./build/i18n # write the Go side's catalogs (npm run i18n runs it) +// go run ./build/i18n -check # fail when anything is out of step (build/check.sh) +// go run ./build/i18n -rclone # write locales/en/rclone.json from the linked rclone +// go run ./build/i18n -rclone -prune # the same, and drop the keys that this rclone lacks +// +// -check fails when: +// - a call's message isn't a string constant; +// - a core.po differs from what the code gives now; +// - a language in languages.json lacks one of its files; +// - a language that ships complete (see `complete`) lacks a translation, in app.po or core.po; +// - a translation's placeholders differ from its English message's, in a .po file or in a +// setup question of rclone.json. +// +// It also warns, without failing, when a language's rclone.json lacks translations for the keys +// of en/rclone.json, or has keys that en no longer has. It compares the files with each other, and +// doesn't read rclone's registry. +// +// -rclone writes rclone's own text (see runRclone in rclone.go). The text comes from a command of +// its own, build/i18n/rclonetext, because that command links all of rclone and this one must stay +// quick for npm run i18n and -check. +package main + +import ( + "encoding/json" + "flag" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" +) + +// complete lists the languages that ship with every message translated. Any other language may +// be partly translated, and shows English for the rest. +var complete = []string{"es", "zh-CN"} + +// plurals gives the Plural-Forms header of the languages that the app ships. A language that +// isn't here keeps the header its file has, which its translator writes. +var plurals = map[string]string{ + "en": "nplurals=2; plural=(n != 1);", + "es": "nplurals=2; plural=(n != 1);", + "zh-CN": "nplurals=1; plural=0;", +} + +func main() { + check := flag.Bool("check", false, "fail when the catalogs are out of step, and write nothing") + rcloneText := flag.Bool("rclone", false, "write locales/en/rclone.json from the rclone that is linked into the app, and nothing else") + prune := flag.Bool("prune", false, "with -rclone, drop the keys that the rclone on this system doesn't have") + dir := flag.String("dir", ".", "the repository") + flag.Parse() + if *rcloneText { + if err := runRclone(*dir, *prune); err != nil { + fmt.Fprintln(os.Stderr, "i18n:", err) + os.Exit(1) + } + return + } + problems, warnings, err := run(*dir, *check) + if err != nil { + fmt.Fprintln(os.Stderr, "i18n:", err) + os.Exit(1) + } + for _, w := range warnings { + fmt.Fprintln(os.Stderr, "warning:", w) + } + for _, p := range problems { + fmt.Fprintln(os.Stderr, p) + } + if len(problems) > 0 { + fmt.Fprintf(os.Stderr, "i18n: %d problems\n", len(problems)) + os.Exit(1) + } +} + +// run writes the Go side's catalogs, or with check only compares them, and returns what is out +// of step. With check, it also returns the warnings about rclone's text (reviewRclone). +func run(dir string, check bool) (problems, warnings []string, err error) { + langs, err := languages(dir) + if err != nil { + return nil, nil, err + } + x, err := extract(dir) + if err != nil { + return nil, nil, err + } + problems = append([]string(nil), x.problems...) + for _, lang := range langs { + path := filepath.Join(dir, "locales", lang, "core.po") + old, err := readFile(path) + if err != nil { + return nil, nil, err + } + have, err := parsePO(old) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", path, err) + } + next := merge(x, have, lang).String() + switch { + case next == old: + case check: + problems = append(problems, rel(dir, path)+" is out of date: run npm run i18n") + default: + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return nil, nil, err + } + if err := os.WriteFile(path, []byte(next), 0o644); err != nil { + return nil, nil, err + } + } + } + if !check { + return problems, nil, nil + } + for _, lang := range langs { + for _, name := range []string{"app.po", "core.po"} { + path := filepath.Join(dir, "locales", lang, name) + text, err := readFile(path) + if err != nil { + return nil, nil, err + } + if text == "" { + problems = append(problems, rel(dir, path)+" is missing") + continue + } + c, err := parsePO(text) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", path, err) + } + if lang != "en" { + problems = append(problems, review(c, rel(dir, path), name == "app.po", isComplete(lang))...) + } + } + } + rcloneProblems, warnings, err := reviewRclone(dir, langs) + return append(problems, rcloneProblems...), warnings, err +} + +func languages(dir string) ([]string, error) { + b, err := os.ReadFile(filepath.Join(dir, "locales", "languages.json")) + if err != nil { + return nil, err + } + var names map[string]string + if err := json.Unmarshal(b, &names); err != nil { + return nil, fmt.Errorf("locales/languages.json: %w", err) + } + if _, ok := names["en"]; !ok { + return nil, fmt.Errorf("locales/languages.json has no en") + } + var out []string + for lang := range names { + out = append(out, lang) + } + sort.Strings(out) + return out, nil +} + +func isComplete(lang string) bool { + for _, l := range complete { + if l == lang { + return true + } + } + return false +} + +func rel(dir, path string) string { + r, err := filepath.Rel(dir, path) + if err != nil { + return path + } + return filepath.ToSlash(r) +} + +// merge returns lang's catalog for the code's messages: each message with the translation that +// have holds for it, and with the code's notes and files. English's catalog has no translations. +func merge(x *extraction, have *catalog, lang string) *catalog { + out := &catalog{header: []string{ + "Content-Type: text/plain; charset=utf-8", + "Language: " + lang, + }} + forms := plurals[lang] + if forms == "" { + forms = have.headerValue("Plural-Forms") + } + if forms == "" { + forms = plurals["en"] + } + out.header = append(out.header, "Plural-Forms: "+forms) + n := pluralCount(forms) + for _, m := range x.messages { + e := &entry{ctx: m.ctx, id: m.id, plural: m.plural, notes: m.notes} + for f := range m.files { + e.refs = append(e.refs, f) + } + sort.Strings(e.refs) + sort.Strings(e.notes) + want := 1 + if m.plural != "" { + want = n + } + e.strs = make([]string, want) + if old := have.find(e.key()); old != nil && lang != "en" { + e.comments = old.comments + // A translation is kept only while the message has the same shape: a message + // that gained or lost its plural needs a new one. + if (old.plural != "") == (m.plural != "") { + copy(e.strs, old.strs) + } + } + out.entries = append(out.entries, e) + } + return out +} + +var nplurals = regexp.MustCompile(`nplurals\s*=\s*(\d+)`) + +func pluralCount(forms string) int { + if m := nplurals.FindStringSubmatch(forms); m != nil { + var n int + fmt.Sscan(m[1], &n) + if n > 0 { + return n + } + } + return 2 +} + +// review returns what is wrong with a language's catalog: a missing translation, when the +// language ships complete, and a translation whose placeholders differ from its message's. icu +// says that the messages are Lingui's (ICU MessageFormat), and not fmt formats. +func review(c *catalog, path string, icu, mustBeComplete bool) []string { + var problems []string + missing := 0 + for _, e := range c.entries { + if !e.translated() { + missing++ + continue + } + for i, s := range e.strs { + source := e.id + if e.plural != "" && i > 0 { + source = e.plural + } + var want, got string + if icu { + want, got = icuPlaceholders(source), icuPlaceholders(s) + } else { + want, got = verbs(source, e.plural != ""), verbs(s, e.plural != "") + } + if want != got { + problems = append(problems, fmt.Sprintf("%s: the translation of %q has other placeholders (%s) than the message (%s)", path, e.id, orNone(got), orNone(want))) + } + } + } + if missing > 0 && mustBeComplete { + problems = append(problems, fmt.Sprintf("%s: %d messages have no translation", path, missing)) + } + return problems +} + +func orNone(s string) string { + if s == "" { + return "none" + } + return s +} + +var ( + // A value is "{name}" or "{name, plural …}" (or select, number…). A plural's branch is text + // in braces, which may start with a word and a comma ("{Yes, with # rule}"): it is no value. + icuArgument = regexp.MustCompile(`\{\s*([A-Za-z0-9_]+)\s*(?:\}|,\s*(?:plural|select|selectordinal|number|date|time)\b)`) + // A branch's key comes right before its brace: "one {…}", "=0 {…}". A branch that is one + // word ("one {Keep}") is text, not a value. + icuBranchKey = regexp.MustCompile(`(?:^|[\s{}])(?:zero|one|two|few|many|other|=\d+)\s*$`) + icuTag = regexp.MustCompile(``) + verb = regexp.MustCompile(`%(\[(\d+)\])?[-+# 0]*[0-9.]*([a-zA-Z%])`) +) + +// icuPlaceholders returns the names of the values and the tags that an ICU message uses, sorted. +func icuPlaceholders(msg string) string { + set := map[string]bool{} + for _, m := range icuArgument.FindAllStringSubmatchIndex(msg, -1) { + if icuBranchKey.MatchString(msg[:m[0]]) { + continue + } + set["{"+msg[m[2]:m[3]]+"}"] = true + } + for _, m := range icuTag.FindAllStringSubmatch(msg, -1) { + set["<"+m[1]+">"] = true + } + return joined(set) +} + +// verbs returns the values that a fmt format uses, as "position:verb" pairs, sorted. A +// translation may put them in another order ("%[2]s"), so each is named by its position. A +// message about a count may leave the count out of one of its forms ("One file"), so its +// values are compared as a set that may shrink: see review. +func verbs(format string, plural bool) string { + set := map[string]bool{} + next := 1 + for _, m := range verb.FindAllStringSubmatch(format, -1) { + if m[3] == "%" { + continue + } + pos := next + if m[2] != "" { + fmt.Sscan(m[2], &pos) + } + next = pos + 1 + v := m[3] + if v == "w" || v == "v" { + v = "s" // an error or any value reads as text + } + set[fmt.Sprintf("%d:%s", pos, v)] = true + } + if plural { + // The forms of one message may use different values, so only their kinds are compared + // where both use them. That is too loose to check here, so a plural's forms pass. + return "" + } + return joined(set) +} + +func joined(set map[string]bool) string { + var out []string + for k := range set { + out = append(out, k) + } + sort.Strings(out) + return strings.Join(out, " ") +} diff --git a/build/i18n/po.go b/build/i18n/po.go new file mode 100644 index 00000000..29051ead --- /dev/null +++ b/build/i18n/po.go @@ -0,0 +1,193 @@ +package main + +import ( + "fmt" + "sort" + "strconv" + "strings" +) + +type entry struct { + comments []string // "# " lines, which a translator wrote + notes []string // "#. " lines, which the code wrote for the translator + refs []string // "#: " lines, the files that use the message + ctx string + id string + plural string + strs []string // msgstr, or msgstr[0], msgstr[1]… +} + +func (e *entry) key() string { return e.ctx + "\x04" + e.id } + +func (e *entry) translated() bool { + if len(e.strs) == 0 { + return false + } + for _, s := range e.strs { + if s == "" { + return false + } + } + return true +} + +// catalog is a PO file: its header (the entry with an empty msgid) and its messages. +type catalog struct { + header []string // the header's "Key: value" lines, in order + entries []*entry +} + +func (c *catalog) find(key string) *entry { + for _, e := range c.entries { + if e.key() == key { + return e + } + } + return nil +} + +func (c *catalog) headerValue(name string) string { + for _, h := range c.header { + if k, v, ok := strings.Cut(h, ":"); ok && k == name { + return strings.TrimSpace(v) + } + } + return "" +} + +// parsePO reads a PO file. It reads what gettext's tools and Lingui write: comments, msgctxt, +// msgid, msgid_plural, msgstr and msgstr[n], each with continuation lines. +func parsePO(text string) (*catalog, error) { + c := &catalog{} + cur := &entry{} + var target *string // the string that a continuation line adds to + started := false // cur has a msgid + flush := func() { + if !started { + return + } + if cur.id == "" && cur.ctx == "" { + if len(cur.strs) > 0 { + for _, line := range strings.Split(strings.TrimSuffix(cur.strs[0], "\n"), "\n") { + if line != "" { + c.header = append(c.header, line) + } + } + } + } else { + c.entries = append(c.entries, cur) + } + cur, target, started = &entry{}, nil, false + } + for n, line := range strings.Split(text, "\n") { + line = strings.TrimRight(line, "\r") + quoted := func(s string) (string, error) { + v, err := strconv.Unquote(strings.TrimSpace(s)) + if err != nil { + return "", fmt.Errorf("line %d: %s is not a quoted string", n+1, s) + } + return v, nil + } + var err error + switch { + case strings.TrimSpace(line) == "": + flush() + case strings.HasPrefix(line, "#~"): // an obsolete message, which is dropped + case strings.HasPrefix(line, "#."): + cur.notes = append(cur.notes, strings.TrimSpace(line[2:])) + case strings.HasPrefix(line, "#:"): + cur.refs = append(cur.refs, strings.TrimSpace(line[2:])) + case strings.HasPrefix(line, "#,"): // flags, which nothing here uses + case strings.HasPrefix(line, "#"): + cur.comments = append(cur.comments, strings.TrimSpace(line[1:])) + case strings.HasPrefix(line, "msgctxt "): + cur.ctx, err = quoted(line[len("msgctxt "):]) + target = &cur.ctx + case strings.HasPrefix(line, "msgid_plural "): + cur.plural, err = quoted(line[len("msgid_plural "):]) + target = &cur.plural + case strings.HasPrefix(line, "msgid "): + if started { + flush() + } + started = true + cur.id, err = quoted(line[len("msgid "):]) + target = &cur.id + case strings.HasPrefix(line, "msgstr["): + _, rest, ok := strings.Cut(line, "]") + if !ok { + return nil, fmt.Errorf("line %d: a msgstr[n] without its ]", n+1) + } + var v string + v, err = quoted(rest) + cur.strs = append(cur.strs, v) + target = &cur.strs[len(cur.strs)-1] + case strings.HasPrefix(line, "msgstr "): + var v string + v, err = quoted(line[len("msgstr "):]) + cur.strs = []string{v} + target = &cur.strs[0] + case strings.HasPrefix(line, `"`): + if target == nil { + return nil, fmt.Errorf("line %d: a string that continues nothing", n+1) + } + var v string + v, err = quoted(line) + *target += v + default: + return nil, fmt.Errorf("line %d: not a PO line: %s", n+1, line) + } + if err != nil { + return nil, err + } + } + flush() + return c, nil +} + +// String writes the catalog as a PO file, with its messages in the order of their keys, so that +// the file only changes when a message does. +func (c *catalog) String() string { + var b strings.Builder + b.WriteString("msgid \"\"\nmsgstr \"\"\n") + for _, h := range c.header { + b.WriteString(strconv.Quote(h+"\n") + "\n") + } + entries := append([]*entry(nil), c.entries...) + sort.SliceStable(entries, func(i, j int) bool { return entries[i].key() < entries[j].key() }) + for _, e := range entries { + b.WriteByte('\n') + for _, l := range e.comments { + b.WriteString(strings.TrimRight("# "+l, " ") + "\n") + } + for _, l := range e.notes { + b.WriteString("#. " + l + "\n") + } + for _, l := range e.refs { + b.WriteString("#: " + l + "\n") + } + if e.ctx != "" { + b.WriteString("msgctxt " + quote(e.ctx) + "\n") + } + b.WriteString("msgid " + quote(e.id) + "\n") + if e.plural == "" { + str := "" + if len(e.strs) > 0 { + str = e.strs[0] + } + b.WriteString("msgstr " + quote(str) + "\n") + continue + } + b.WriteString("msgid_plural " + quote(e.plural) + "\n") + for i, s := range e.strs { + fmt.Fprintf(&b, "msgstr[%d] %s\n", i, quote(s)) + } + } + return b.String() +} + +// quote writes a string as PO does: in double quotes, with only what must be escaped. +func quote(s string) string { + r := strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`, "\t", `\t`) + return `"` + r.Replace(s) + `"` +} diff --git a/build/i18n/rclone.go b/build/i18n/rclone.go new file mode 100644 index 00000000..24b2e39a --- /dev/null +++ b/build/i18n/rclone.go @@ -0,0 +1,349 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "maps" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" +) + +// rclone's own text (backend descriptions, option help, examples, backend command help, +// metadata help and the questions of a remote's setup) is translated in +// locales//rclone.json, a tree keyed by backend, option block and option name +// (core/catalog/texts.go describes the keys). In memory a file is flat: each key's parts are +// joined by sep. +const sep = "\x00" + +const rcloneFile = "rclone.json" + +// runRclone writes locales/en/rclone.json from the rclone that is linked into the app. The text of +// rclone's registry comes from build/i18n/rclonetext, and the questions of a remote's setup come +// from rclone's source (setup.go). +// +// It merges into the file that exists. A new key is added and a changed English text is replaced. +// A key that this rclone lacks is kept, because some options exist only on some systems (the local +// backend's, mount's). prune drops those keys, from every language. +// +// When rclone changes an English text, its translation is dropped from each language. -check then +// counts it as missing, and the app shows the new English until it is translated again. +func runRclone(dir string, prune bool) error { + cmd := exec.Command("go", "run", "./build/i18n/rclonetext") + cmd.Dir = dir + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + return fmt.Errorf("build/i18n/rclonetext: %w", err) + } + var live map[string]string + if err := json.Unmarshal(out, &live); err != nil { + return fmt.Errorf("build/i18n/rclonetext: %w", err) + } + src, err := rcloneSource(dir) + if err != nil { + return err + } + setup, err := collectSetup(src) + if err != nil { + return fmt.Errorf("rclone's source: %w", err) + } + for _, problem := range addSetup(live, setup) { + fmt.Fprintln(os.Stderr, "i18n: "+problem) + } + fmt.Fprintln(os.Stderr, "i18n: "+setup.report()) + langs, err := languages(dir) + if err != nil { + return err + } + files := map[string]map[string]string{} + for _, lang := range langs { + if files[lang], err = readTexts(filepath.Join(dir, "locales", lang, rcloneFile)); err != nil { + return err + } + } + report := mergeRclone(live, files, prune) + for _, lang := range langs { + if err := writeTexts(filepath.Join(dir, "locales", lang, rcloneFile), files[lang]); err != nil { + return err + } + } + fmt.Fprintln(os.Stderr, "i18n: "+report) + return nil +} + +// addSetup adds the setup's texts that were read from rclone's source to live, the text of +// rclone's registry. The registry already gives the common questions that rclone's config asks +// of every backend (core/catalog's setupQuestions), and the source must give the same text for +// them. It returns what can't be read, and any text that the two give differently. +func addSetup(live map[string]string, setup *setupSource) []string { + var problems []string + for _, u := range setup.unread { + problems = append(problems, "rclone's source: "+u) + } + keys := setup.keys() + for _, k := range slices.Sorted(maps.Keys(keys)) { + if old, ok := live[k]; ok && old != keys[k] { + problems = append(problems, fmt.Sprintf("rclone's source and registry give %s other texts: %q and %q, so the registry's is kept", strings.ReplaceAll(k, sep, "."), keys[k], old)) + continue + } + live[k] = keys[k] + } + return problems +} + +// mergeRclone brings files (by language, with "en") in step with live, rclone's English text, +// as runRclone describes, and says what changed. +func mergeRclone(live map[string]string, files map[string]map[string]string, prune bool) string { + en := files["en"] + if en == nil { + en = map[string]string{} + files["en"] = en + } + // A text can get a new key without changing. A key names an option's providers, so a provider + // that rclone adds to an S3 option gives the option's help a new key. A setup question's texts + // are numbered (help_2), so a text that rclone moves gets a new key too. So a new key, or a key + // whose text changed, takes the translations of a key in the same backend or block that had + // the same English text. + sameText := map[string]string{} // backend or block, and English text -> a key with that text + for _, k := range slices.Sorted(maps.Keys(en)) { + if id := scopedText(k, en[k]); sameText[id] == "" { + sameText[id] = k + } + } + // The translations to carry over are collected here, from the files as they were. They are + // applied after the next loop has dropped the translations of the changed texts. + carried := map[string]map[string]string{} // language -> key -> translation + for k, text := range live { + if old, ok := en[k]; ok && old == text { + continue + } + from := sameText[scopedText(k, text)] + if from == "" { + continue + } + for lang, f := range files { + if lang != "en" && f[from] != "" { + if carried[lang] == nil { + carried[lang] = map[string]string{} + } + carried[lang][k] = f[from] + } + } + } + added, changed, kept, dropped := 0, 0, 0, 0 + for k, text := range live { + old, ok := en[k] + switch { + case !ok: + added++ + case old != text: + changed++ + for lang, f := range files { + if lang != "en" { + delete(f, k) + } + } + } + en[k] = text + } + for lang, translations := range carried { + f := files[lang] + for k, s := range translations { + if _, has := f[k]; !has { + f[k] = s + } + } + } + for k := range en { + if _, ok := live[k]; ok { + continue + } + if !prune { + kept++ + continue + } + dropped++ + delete(en, k) + } + if prune { + for lang, f := range files { + if lang == "en" { + continue + } + for k := range f { + if _, ok := en[k]; !ok { + delete(f, k) + } + } + } + } + report := fmt.Sprintf("rclone's text: %d keys, %d new, %d changed", len(en), added, changed) + if prune { + return report + fmt.Sprintf(", %d dropped", dropped) + } + return report + fmt.Sprintf(", %d kept that this rclone lacks (-prune drops them)", kept) +} + +// scopedText identifies an English text within its backend or block (the first two parts of +// its key). +func scopedText(key, text string) string { + parts := strings.SplitN(key, sep, 3) + if len(parts) < 3 { + return key + sep + text + } + return parts[0] + sep + parts[1] + sep + text +} + +// reviewRclone returns warnings about each language's rclone.json: the keys of en that it lacks +// a translation for, and the keys that en no longer has. They don't fail the check, because an +// update of rclone shouldn't wait for its translations: the app shows English for what is +// missing. A setup question or error whose translation has other values than its English format +// is a problem, because the app fills the values in. +func reviewRclone(dir string, langs []string) (problems, warnings []string, err error) { + enPath := filepath.Join(dir, "locales", "en", rcloneFile) + en, err := readTexts(enPath) + if err != nil { + return nil, nil, err + } + if len(en) == 0 { + return nil, []string{rel(dir, enPath) + " is missing: run go run ./build/i18n -rclone"}, nil + } + for _, lang := range langs { + if lang == "en" { + continue + } + path := filepath.Join(dir, "locales", lang, rcloneFile) + f, err := readTexts(path) + if err != nil { + return nil, nil, err + } + missing, extra := 0, 0 + for _, k := range slices.Sorted(maps.Keys(en)) { + s, ok := f[k] + if !ok { + missing++ + continue + } + if !setupFormat(k) { + continue + } + if want, got := verbs(en[k], false), verbs(s, false); want != got { + problems = append(problems, fmt.Sprintf("%s: the translation of %s has other placeholders (%s) than the English (%s)", rel(dir, path), strings.ReplaceAll(k, sep, "."), orNone(got), orNone(want))) + } + } + for k := range f { + if _, ok := en[k]; !ok { + extra++ + } + } + if missing > 0 { + warnings = append(warnings, fmt.Sprintf("%s: no translation for %d of rclone's %d texts", rel(dir, path), missing, len(en))) + } + if extra > 0 { + warnings = append(warnings, fmt.Sprintf("%s: keys that en/rclone.json no longer has: %d (go run ./build/i18n -rclone -prune drops them)", rel(dir, path), extra)) + } + } + return problems, warnings, nil +} + +// helpVariant is the last part of the key of a setup question's text, or of an error's. +var helpVariant = regexp.MustCompile(`^help(_[0-9]+)?$`) + +// setupFormat reports whether the text at key is a setup question's or error's, which are fmt +// formats (see setup.go), and not a choice's help, which is plain text. +func setupFormat(key string) bool { + parts := strings.Split(key, sep) + n := len(parts) + if parts[0] != "setup" || !helpVariant.MatchString(parts[n-1]) { + return false + } + switch { + case n == 3: // setup.error.help + return parts[1] == "error" + case n == 4: // setup.question..help + return parts[1] == "question" + case n == 5: // setup.backend..error.help + return parts[1] == "backend" && parts[3] == "error" + case n == 6: // setup.backend..question..help + return parts[1] == "backend" && parts[3] == "question" + } + return false +} + +// readTexts reads a file of rclone's text into its flat form. A file that doesn't exist reads as +// empty. +func readTexts(path string) (map[string]string, error) { + b, err := os.ReadFile(path) + if os.IsNotExist(err) { + return map[string]string{}, nil + } + if err != nil { + return nil, err + } + var tree map[string]any + if err := json.Unmarshal(b, &tree); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + out := map[string]string{} + var walk func(prefix string, node map[string]any) error + walk = func(prefix string, node map[string]any) error { + for k, v := range node { + if prefix != "" { + k = prefix + sep + k + } + switch v := v.(type) { + case string: + out[k] = v + case map[string]any: + if err := walk(k, v); err != nil { + return err + } + default: + return fmt.Errorf("%s: %s is neither a text nor an object", path, strings.ReplaceAll(k, sep, ".")) + } + } + return nil + } + return out, walk("", tree) +} + +// writeTexts writes a file of rclone's text as a tree, with its keys sorted, so that the file only +// changes where a text does. An empty file is not written. +func writeTexts(path string, texts map[string]string) error { + if len(texts) == 0 { + return nil + } + tree := map[string]any{} + for _, k := range slices.Sorted(maps.Keys(texts)) { + parts := strings.Split(k, sep) + node := tree + for _, p := range parts[:len(parts)-1] { + next, ok := node[p].(map[string]any) + if !ok { + next = map[string]any{} + node[p] = next + } + node = next + } + node[parts[len(parts)-1]] = texts[k] + } + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + if err := enc.Encode(tree); err != nil { + return err + } + if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, b.Bytes()) { + return nil + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return os.WriteFile(path, b.Bytes(), 0o644) +} diff --git a/build/i18n/rclone_test.go b/build/i18n/rclone_test.go new file mode 100644 index 00000000..7f1ea1c0 --- /dev/null +++ b/build/i18n/rclone_test.go @@ -0,0 +1,145 @@ +package main + +import ( + "maps" + "os" + "path/filepath" + "strings" + "testing" +) + +func k(parts ...string) string { return strings.Join(parts, sep) } + +func fixture() map[string]map[string]string { + return map[string]map[string]string{ + "en": { + k("backend", "local", "description"): "Local Disk", + k("backend", "local", "option", "nounc", "help"): "Disable UNC (long path names) conversion on Windows.", + k("backend", "s3", "option", "acl", "provider", "AWS", "help"): "Canned ACL.", + k("options", "main", "option", "transfers", "help"): "Number of file transfers to run in parallel", + }, + "es": { + k("backend", "local", "description"): "Disco local", + k("backend", "local", "option", "nounc", "help"): "Desactiva la conversión UNC en Windows.", + k("backend", "s3", "option", "acl", "provider", "AWS", "help"): "ACL predefinida.", + k("options", "main", "option", "transfers", "help"): "Número de transferencias en paralelo", + k("options", "main", "option", "gone", "help"): "Una opción que ya no existe", + }, + } +} + +// live is what the rclone on this system gives: it lacks nounc (a Windows option), has a new +// option, a changed text, and the ACL help under a longer provider list. +func live() map[string]string { + return map[string]string{ + k("backend", "local", "description"): "Local Disk", + k("backend", "s3", "option", "acl", "provider", "AWS,Ceph", "help"): "Canned ACL.", + k("options", "main", "option", "transfers", "help"): "Number of file transfers to run in parallel.", + k("options", "main", "option", "checkers", "help"): "Number of checkers to run in parallel", + } +} + +func TestMergeRcloneKeepsWhatThisSystemLacks(t *testing.T) { + files := fixture() + mergeRclone(live(), files, false) + en, es := files["en"], files["es"] + + if en[k("options", "main", "option", "checkers", "help")] != "Number of checkers to run in parallel" { + t.Error("a new key isn't added to en") + } + if en[k("options", "main", "option", "transfers", "help")] != "Number of file transfers to run in parallel." { + t.Error("a changed English text isn't updated") + } + if _, ok := es[k("options", "main", "option", "transfers", "help")]; ok { + t.Error("the translation of a changed English text is kept") + } + if _, ok := en[k("backend", "local", "option", "nounc", "help")]; !ok { + t.Error("a key that this system's rclone lacks is dropped without -prune") + } + if es[k("backend", "local", "option", "nounc", "help")] == "" { + t.Error("the translation of a key that this system's rclone lacks is dropped without -prune") + } + if es[k("backend", "local", "description")] != "Disco local" { + t.Error("an unchanged translation is lost") + } + if got := es[k("backend", "s3", "option", "acl", "provider", "AWS,Ceph", "help")]; got != "ACL predefinida." { + t.Errorf("a new key with an existing text of the same backend got %q, want the existing translation", got) + } + if _, ok := es[k("options", "main", "option", "checkers", "help")]; ok { + t.Error("a new key got a translation") + } + if _, ok := es[k("options", "main", "option", "gone", "help")]; !ok { + t.Error("a language's key that en lacks is dropped without -prune") + } +} + +func TestMergeRclonePrune(t *testing.T) { + files := fixture() + mergeRclone(live(), files, true) + for lang, f := range files { + if _, ok := f[k("backend", "local", "option", "nounc", "help")]; ok { + t.Errorf("%s: -prune keeps a key that rclone lacks", lang) + } + if _, ok := f[k("options", "main", "option", "gone", "help")]; ok { + t.Errorf("%s: -prune keeps a key that en lacks", lang) + } + } + if len(files["en"]) != len(live()) { + t.Errorf("en has %d keys after -prune, want rclone's %d", len(files["en"]), len(live())) + } +} + +func TestRcloneFilesRoundTrip(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "locales", "es", rcloneFile) + want := fixture()["es"] + want[k("backend", "s3", "option", "region", "example", "__empty__", "help")] = "Usa & aquello" + if err := writeTexts(path, want); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), `"description": "Disco local"`) || !strings.Contains(string(b), " & aquello") { + t.Errorf("the file isn't a readable tree:\n%s", b) + } + got, err := readTexts(path) + if err != nil { + t.Fatal(err) + } + if !maps.Equal(got, want) { + t.Errorf("read back %v, want %v", got, want) + } +} + +func TestReviewRcloneWarns(t *testing.T) { + dir := t.TempDir() + files := fixture() + for lang, f := range files { + if err := writeTexts(filepath.Join(dir, "locales", lang, rcloneFile), f); err != nil { + t.Fatal(err) + } + } + delete(files["es"], k("backend", "local", "description")) + if err := writeTexts(filepath.Join(dir, "locales", "es", rcloneFile), files["es"]); err != nil { + t.Fatal(err) + } + problems, warnings, err := reviewRclone(dir, []string{"en", "es", "zh-CN"}) + if err != nil { + t.Fatal(err) + } + if len(problems) > 0 { + t.Errorf("problems in files without setup questions: %q", problems) + } + joined := strings.Join(warnings, "\n") + for _, want := range []string{ + "locales/es/rclone.json: no translation for 1 of rclone's 4 texts", + "locales/es/rclone.json: keys that en/rclone.json no longer has: 1", + "locales/zh-CN/rclone.json: no translation for 4 of rclone's 4 texts", + } { + if !strings.Contains(joined, want) { + t.Errorf("the warnings lack %q:\n%s", want, joined) + } + } +} diff --git a/build/i18n/rclonetext/main.go b/build/i18n/rclonetext/main.go new file mode 100644 index 00000000..bbe93236 --- /dev/null +++ b/build/i18n/rclonetext/main.go @@ -0,0 +1,26 @@ +// Command rclonetext prints the English text of the rclone that is linked into Rclone UI, as +// core/catalog reads it (catalog.EnglishTexts): a JSON object from each key, with its parts +// joined by "\u0000", to its text. `go run ./build/i18n -rclone` runs it and writes +// locales/en/rclone.json from its output. It is a command of its own so that build/i18n, which +// `npm run i18n` and the checks run, doesn't link all of rclone. +package main + +import ( + "encoding/json" + "fmt" + "os" + + _ "github.com/rclone/rclone/backend/all" // every backend, as main.go imports them + _ "github.com/rclone/rclone/cmd/all" // every command, with the mount and serve option blocks + + "github.com/rclone/rclone-ui/core/catalog" +) + +func main() { + enc := json.NewEncoder(os.Stdout) + enc.SetEscapeHTML(false) + if err := enc.Encode(catalog.EnglishTexts()); err != nil { + fmt.Fprintln(os.Stderr, "rclonetext:", err) + os.Exit(1) + } +} diff --git a/build/i18n/setup.go b/build/i18n/setup.go new file mode 100644 index 00000000..d99db365 --- /dev/null +++ b/build/i18n/setup.go @@ -0,0 +1,748 @@ +package main + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "go/types" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" +) + +// The questions that rclone asks while a remote is set up are in no registry. Each backend that +// asks its own builds them in its Config function, with fs's helpers (fs.ConfigConfirm, +// fs.ConfigInput…), from string literals and fmt.Sprintf formats. So -rclone reads them from +// rclone's source, in the module cache, and writes them to locales/en/rclone.json under these +// keys (core/catalog/texts.go reads them): +// +// setup.backend..question..help +// setup.backend..question..example..help +// setup.backend..error.help +// setup.question..help +// setup.error.help +// +// setup.question and setup.error hold the questions and errors of rclone's common config +// (lib/oauthutil and fs), which any backend may show. A question's help and an error are fmt +// formats: a text that rclone builds with fmt.Sprintf keeps its verbs, and a literal text has its +// "%" doubled. When one backend asks the same question with several texts, or shows several +// errors, the second text is help_2, the third help_3, in the order of the source. The help of a +// fixed choice (a ConfigChooseFixed item) is plain text. + +const rcloneModule = "github.com/rclone/rclone" + +// commonSetup are the folders of rclone's common config that ask questions, relative to the +// module. Every folder in backend/ is read too. +var commonSetup = []string{"fs", "lib/oauthutil"} + +// setupCall gives the positions of the arguments of one of fs's helpers: the question's name, its +// help and its fixed choices (-1 when the helper has none). +type setupCall struct{ name, help, items int } + +// setupCalls lists fs's helpers that ask a question or show an error. ConfigResult and ConfigGoto +// show nothing. +var setupCalls = map[string]setupCall{ + "ConfigConfirm": {2, 3, -1}, + "ConfigInput": {1, 2, -1}, + "ConfigInputOptional": {1, 2, -1}, + "ConfigPassword": {1, 2, -1}, + "ConfigChoose": {1, 2, -1}, + "ConfigChooseExclusive": {1, 2, -1}, + "ConfigChooseFixed": {1, 2, 3}, + "ConfigChooseExclusiveFixed": {1, 2, 3}, + "ConfigError": {-1, 1, -1}, +} + +// setupTexts are the texts of one backend's setup, or of the common config's. +type setupTexts struct { + // questions holds each question's helps, by its name, in the order of the source. + questions map[string][]string + // choices holds the help of each fixed choice, by question and value. + choices map[string]map[string]string + // errors are the errors that are shown before a question, in the order of the source. + errors []string + // asked counts the calls that ask a question, and shown those that show an error. + asked, shown int +} + +// setupSource is what collectSetup read: the texts of each backend ("" for the common config), +// and what it couldn't read, with where it is. +type setupSource struct { + scopes map[string]*setupTexts + unread []string +} + +// rcloneSource returns the folder of the rclone module that the app links, in the module cache. +// It never downloads anything: the module is there once build/i18n/rclonetext has been built. +func rcloneSource(dir string) (string, error) { + cmd := exec.Command("go", "list", "-m", "-f", "{{.Dir}}", rcloneModule) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GOPROXY=off", "GOFLAGS=-mod=readonly") + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("go list -m %s: %w", rcloneModule, err) + } + src := strings.TrimSpace(string(out)) + if src == "" { + return "", fmt.Errorf("rclone's source isn't in the module cache: run go mod download %s", rcloneModule) + } + return src, nil +} + +// collectSetup reads the setup's questions and errors from the rclone source in root: the common +// config's folders, and each backend's folder (not its subfolders). A backend is named as it +// registers itself (fs.RegInfo's Name). +func collectSetup(root string) (*setupSource, error) { + r := &sourceReader{root: root, fset: token.NewFileSet(), pkgs: map[string]*sourcePkg{}} + out := &setupSource{scopes: map[string]*setupTexts{}} + folders := slices.Clone(commonSetup) + entries, err := os.ReadDir(filepath.Join(root, "backend")) + if err != nil { + return nil, err + } + for _, e := range entries { + if e.IsDir() { + folders = append(folders, "backend/"+e.Name()) + } + } + for _, folder := range folders { + p, err := r.pkg(folder) + if err != nil { + return nil, err + } + if p == nil { + continue + } + scope := "" + if strings.HasPrefix(folder, "backend/") { + names := p.registered(r) + if len(names) != 1 { + if p.asks() { + out.unread = append(out.unread, fmt.Sprintf("%s: the backend's name can't be read (%d names found), so its questions are skipped", folder, len(names))) + } + continue + } + scope = names[0] + } + st := out.scopes[scope] + if st == nil { + st = &setupTexts{questions: map[string][]string{}, choices: map[string]map[string]string{}} + } + out.unread = append(out.unread, p.collect(r, st)...) + if st.asked > 0 || st.shown > 0 { + out.scopes[scope] = st + } + } + return out, nil +} + +// keys returns the source's texts by key, with the parts of each key joined by sep. +func (s *setupSource) keys() map[string]string { + out := map[string]string{} + for scope, st := range s.scopes { + prefix := []string{"setup"} + if scope != "" { + prefix = append(prefix, "backend", scope) + } + at := func(parts ...string) string { return strings.Join(append(slices.Clone(prefix), parts...), sep) } + for name, helps := range st.questions { + for i, h := range helps { + out[at("question", name, variant(i))] = h + } + } + for name, choices := range st.choices { + for value, h := range choices { + out[at("question", name, "example", valueKey(value), "help")] = h + } + } + for i, e := range st.errors { + out[at("error", variant(i))] = e + } + } + return out +} + +func (s *setupSource) report() string { + questions, texts, choices, errors, backends := 0, 0, 0, 0, 0 + for scope, st := range s.scopes { + if scope != "" { + backends++ + } + questions += st.asked + for _, helps := range st.questions { + texts += len(helps) + } + for _, c := range st.choices { + choices += len(c) + } + errors += len(st.errors) + } + return fmt.Sprintf("rclone's setup questions, from its source: %d questions with %d texts, %d fixed choices and %d errors, from %d backends and the common config, and %d that can't be read", + questions, texts, choices, errors, backends, len(s.unread)) +} + +// variant returns the last part of the key of a question's or an error's i-th text: help, help_2, +// help_3. +func variant(i int) string { + if i == 0 { + return "help" + } + return fmt.Sprintf("help_%d", i+1) +} + +// valueKey returns the part of a key that names a choice's value: an empty value is __empty__. +func valueKey(v string) string { + if v == "" { + return "__empty__" + } + return v +} + +// sourceReader reads rclone's packages, each once. +type sourceReader struct { + root string + fset *token.FileSet + pkgs map[string]*sourcePkg // by folder, relative to the module +} + +type sourcePkg struct { + folder string + files []*ast.File + paths []string // each file's path, relative to the module + consts map[string]*sourceConst // its top-level constants +} + +// sourceConst is a top-level constant, with its value once it has been read. +type sourceConst struct { + expr ast.Expr + file *ast.File + value setupValue + ok bool + reading bool + read bool +} + +// pkg reads the package in folder, or returns nil when the folder has no Go files. +func (r *sourceReader) pkg(folder string) (*sourcePkg, error) { + if p, ok := r.pkgs[folder]; ok { + return p, nil + } + entries, err := os.ReadDir(filepath.Join(r.root, filepath.FromSlash(folder))) + if err != nil { + if os.IsNotExist(err) { + r.pkgs[folder] = nil + return nil, nil + } + return nil, err + } + p := &sourcePkg{folder: folder, consts: map[string]*sourceConst{}} + for _, e := range entries { + name := e.Name() + if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(r.fset, filepath.Join(r.root, filepath.FromSlash(folder), name), nil, parser.SkipObjectResolution) + if err != nil { + return nil, err + } + p.files = append(p.files, f) + p.paths = append(p.paths, folder+"/"+name) + for _, d := range f.Decls { + g, ok := d.(*ast.GenDecl) + if !ok || g.Tok != token.CONST { + continue + } + for _, spec := range g.Specs { + v := spec.(*ast.ValueSpec) + for i, id := range v.Names { + if i < len(v.Values) { + p.consts[id.Name] = &sourceConst{expr: v.Values[i], file: f} + } + } + } + } + } + if len(p.files) == 0 { + p = nil + } + r.pkgs[folder] = p + return p, nil +} + +// imports returns the names that a file gives its imports, with their paths. +func imports(f *ast.File) map[string]string { + out := map[string]string{} + for _, imp := range f.Imports { + path, _ := strconv.Unquote(imp.Path.Value) + name := filepath.Base(path) + if imp.Name != nil { + name = imp.Name.Name + } + out[name] = path + } + return out +} + +// helper returns the name of the fs helper that c calls, when it calls one. fsName is the name +// that the file gives package fs. inFs is true in package fs itself, which calls them by their +// names. +func helper(c *ast.CallExpr, fsName string, inFs bool) (string, bool) { + var name string + switch fun := c.Fun.(type) { + case *ast.SelectorExpr: + x, ok := fun.X.(*ast.Ident) + if !ok || inFs || fsName == "" || x.Name != fsName { + return "", false + } + name = fun.Sel.Name + case *ast.Ident: + if !inFs { + return "", false + } + name = fun.Name + default: + return "", false + } + _, ok := setupCalls[name] + return name, ok +} + +// registered returns the names of the backends that the package registers (the Name of each +// fs.RegInfo literal), when they can be read. +func (p *sourcePkg) registered(r *sourceReader) []string { + var names []string + for _, f := range p.files { + fsName := fsImport(f) + ast.Inspect(f, func(n ast.Node) bool { + lit, ok := n.(*ast.CompositeLit) + if !ok { + return true + } + sel, ok := lit.Type.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "RegInfo" { + return true + } + if x, ok := sel.X.(*ast.Ident); !ok || x.Name != fsName { + return true + } + for _, e := range lit.Elts { + kv, ok := e.(*ast.KeyValueExpr) + if !ok { + continue + } + if id, ok := kv.Key.(*ast.Ident); !ok || id.Name != "Name" { + continue + } + if v, ok := r.read(p, &site{file: f}, kv.Value); ok && !v.format && !slices.Contains(names, v.text) { + names = append(names, v.text) + } + } + return true + }) + } + return names +} + +// asks reports whether the package calls one of fs's helpers. +func (p *sourcePkg) asks() bool { + found := false + for _, f := range p.files { + fsName := fsImport(f) + ast.Inspect(f, func(n ast.Node) bool { + if c, ok := n.(*ast.CallExpr); ok { + if _, ok := helper(c, fsName, p.folder == "fs"); ok { + found = true + } + } + return !found + }) + } + return found +} + +// fsImport returns the name that a file gives package fs, or "". +func fsImport(f *ast.File) string { + for name, path := range imports(f) { + if path == rcloneModule+"/fs" { + return name + } + } + return "" +} + +// collect adds the package's questions and errors to st, and returns what it couldn't read. +func (p *sourcePkg) collect(r *sourceReader, st *setupTexts) []string { + var unread []string + for i, f := range p.files { + fsName := fsImport(f) + if fsName == "" && p.folder != "fs" { + continue + } + var stack []ast.Node + ast.Inspect(f, func(n ast.Node) bool { + if n == nil { + stack = stack[:len(stack)-1] + return false + } + stack = append(stack, n) + c, ok := n.(*ast.CallExpr) + if !ok { + return true + } + name, ok := helper(c, fsName, p.folder == "fs") + if !ok { + return true + } + at := &site{file: f, stack: stack, pos: c.Pos()} + where := fmt.Sprintf("%s:%d", p.paths[i], r.fset.Position(c.Pos()).Line) + if problem := p.call(r, st, at, name, c); problem != "" { + unread = append(unread, where+": "+problem) + } + return true + }) + } + return unread +} + +// call adds what one call of an fs helper asks or shows, and returns what can't be read, or "". +func (p *sourcePkg) call(r *sourceReader, st *setupTexts, at *site, fn string, c *ast.CallExpr) string { + spec := setupCalls[fn] + if len(c.Args) <= max(spec.name, spec.help, spec.items) { + return "" + } + // A helper that is given its question's name or help by its caller only passes it on, as + // fs's own helpers do. + if spec.name >= 0 && at.param(c.Args[spec.name]) || at.param(c.Args[spec.help]) { + return "" + } + name := "" + if spec.name >= 0 { + v, ok := r.read(p, at, c.Args[spec.name]) + if !ok || v.format { + return "the name of a question (" + fn + ") can't be read: " + types.ExprString(c.Args[spec.name]) + } + name = v.text + } + what := "the error" + if name != "" { + what = "the help of " + name + } + v, ok := r.read(p, at, c.Args[spec.help]) + if !ok { + return what + " can't be read: " + types.ExprString(c.Args[spec.help]) + } + format := v.text + if !v.format { + format = strings.ReplaceAll(v.text, "%", "%%") + } + if strings.TrimSpace(format) == "" { + return "" // nothing to translate + } + if bad := unmatchable(format); bad != "" { + return what + " can't be matched: " + bad + } + if name == "" { + st.shown++ + if !slices.Contains(st.errors, format) { + st.errors = append(st.errors, format) + } + return "" + } + st.asked++ + if !slices.Contains(st.questions[name], format) { + st.questions[name] = append(st.questions[name], format) + } + if spec.items >= 0 { + return p.choices(r, st, at, name, c.Args[spec.items]) + } + return "" +} + +// choices adds the fixed choices of the question name, and returns what can't be read, or "". +func (p *sourcePkg) choices(r *sourceReader, st *setupTexts, at *site, name string, items ast.Expr) string { + lit, ok := items.(*ast.CompositeLit) + if !ok { + return "the choices of " + name + " can't be read, because they are made at run time: " + types.ExprString(items) + } + for _, e := range lit.Elts { + item, ok := e.(*ast.CompositeLit) + if !ok { + return "a choice of " + name + " can't be read: " + types.ExprString(e) + } + var value, help *setupValue + for _, f := range item.Elts { + kv, ok := f.(*ast.KeyValueExpr) + if !ok { + return "a choice of " + name + " can't be read: " + types.ExprString(item) + } + id, _ := kv.Key.(*ast.Ident) + if id == nil || id.Name != "Value" && id.Name != "Help" { + continue + } + v, ok := r.read(p, at, kv.Value) + if !ok || v.format { + return "a choice of " + name + " can't be read: " + types.ExprString(kv.Value) + } + if id.Name == "Value" { + value = &v + } else { + help = &v + } + } + if value == nil || help == nil || help.text == "" { + continue + } + if st.choices[name] == nil { + st.choices[name] = map[string]string{} + } + if old, ok := st.choices[name][value.text]; ok && old != help.text { + return fmt.Sprintf("the choice %q of %s has two helps, so the second is skipped", value.text, name) + } + st.choices[name][value.text] = help.text + } + return "" +} + +// The verbs that core/catalog matches rclone's text with: %q is a quoted string, %s and %v any +// text, and %d a number. A verb with an index, flags or a width is not matched. +var ( + anyVerb = regexp.MustCompile(`%[^%a-zA-Z]*[a-zA-Z%]`) + plainVerb = regexp.MustCompile(`^%[qsvd%]$`) +) + +// unmatchable returns the first verb of format that core/catalog can't match, or what else stops +// it from being matched, or "". +func unmatchable(format string) string { + for _, v := range anyVerb.FindAllString(format, -1) { + if !plainVerb.MatchString(v) { + return "it uses " + v + } + } + if strings.TrimSpace(anyVerb.ReplaceAllString(format, "")) == "" { + return "it is only its values: " + strconv.Quote(format) + } + return "" +} + +// setupValue is a text read from the source: plain text, or a fmt.Sprintf format. +type setupValue struct { + text string + format bool +} + +// site is where an expression is read: its file, and for a call in a function, the nodes from +// the file down to the call, and the call's position. +type site struct { + file *ast.File + stack []ast.Node + pos token.Pos +} + +// fn returns the index in the stack of the innermost function around the site, or -1. +func (s *site) fn() int { + for i := len(s.stack) - 1; i >= 0; i-- { + switch s.stack[i].(type) { + case *ast.FuncLit, *ast.FuncDecl: + return i + } + } + return -1 +} + +func funcParts(n ast.Node) (*ast.FuncType, *ast.BlockStmt) { + switch f := n.(type) { + case *ast.FuncLit: + return f.Type, f.Body + case *ast.FuncDecl: + return f.Type, f.Body + } + return nil, nil +} + +// param reports whether e is a parameter of the function around the site. +func (s *site) param(e ast.Expr) bool { + id, ok := e.(*ast.Ident) + i := s.fn() + if !ok || i < 0 { + return false + } + typ, _ := funcParts(s.stack[i]) + if typ.Params == nil { + return false + } + for _, field := range typ.Params.List { + for _, n := range field.Names { + if n.Name == id.Name { + return true + } + } + } + return false +} + +// assigned returns the last value that the function around the site assigns to the variable name +// before the site, and the site of that assignment. It reads an assignment only when the +// assignment's block also holds the site, because an assignment in another branch may or may not +// have run. +func (s *site) assigned(name string) (ast.Expr, *site, bool) { + fi := s.fn() + if fi < 0 { + return nil, nil, false + } + _, body := funcParts(s.stack[fi]) + if body == nil { + return nil, nil, false + } + var value ast.Expr + var from *site + var stack []ast.Node + ast.Inspect(body, func(n ast.Node) bool { + if n == nil { + stack = stack[:len(stack)-1] + return false + } + if n.Pos() >= s.pos { + return false + } + if _, ok := n.(*ast.FuncLit); ok { + return false // a function literal runs at another time + } + stack = append(stack, n) + var lhs, rhs []ast.Expr + switch a := n.(type) { + case *ast.AssignStmt: + if a.Tok != token.ASSIGN && a.Tok != token.DEFINE || a.End() > s.pos { + return true + } + lhs, rhs = a.Lhs, a.Rhs + case *ast.ValueSpec: + if a.End() > s.pos { + return true + } + for _, id := range a.Names { + lhs = append(lhs, id) + } + rhs = a.Values + default: + return true + } + for i, l := range lhs { + if id, ok := l.(*ast.Ident); !ok || id.Name != name { + continue + } + value, from = nil, nil + if len(rhs) == len(lhs) && s.inBlockOf(stack) { + value = rhs[i] + from = &site{file: s.file, stack: append(slices.Clone(s.stack[:fi+1]), stack...), pos: n.Pos()} + } + } + return true + }) + return value, from, value != nil +} + +// inBlockOf reports whether the site is in the innermost block of stack, the nodes down to an +// assignment. +func (s *site) inBlockOf(stack []ast.Node) bool { + for i := len(stack) - 1; i >= 0; i-- { + switch b := stack[i].(type) { + case *ast.BlockStmt, *ast.CaseClause, *ast.CommClause: + return b.Pos() <= s.pos && s.pos < b.End() + } + } + return true +} + +// read returns the text of e: a string literal, a constant, a variable that is given one, a +// concatenation of them, or fmt.Sprintf of one, which is read as its format. +func (r *sourceReader) read(p *sourcePkg, at *site, e ast.Expr) (setupValue, bool) { + return r.readDepth(p, at, e, 0) +} + +// readDepth does the work of read. depth counts the expressions that led to e, so that a chain of +// variables that never ends in a text stops. +func (r *sourceReader) readDepth(p *sourcePkg, at *site, e ast.Expr, depth int) (setupValue, bool) { + if depth > 20 { + return setupValue{}, false + } + switch v := e.(type) { + case *ast.BasicLit: + if v.Kind != token.STRING { + return setupValue{}, false + } + s, err := strconv.Unquote(v.Value) + return setupValue{text: s}, err == nil + case *ast.ParenExpr: + return r.readDepth(p, at, v.X, depth+1) + case *ast.BinaryExpr: + if v.Op != token.ADD { + return setupValue{}, false + } + a, ok1 := r.readDepth(p, at, v.X, depth+1) + b, ok2 := r.readDepth(p, at, v.Y, depth+1) + if !ok1 || !ok2 || a.format || b.format { + return setupValue{}, false + } + return setupValue{text: a.text + b.text}, true + case *ast.Ident: + if at != nil && at.stack != nil { + if value, from, ok := at.assigned(v.Name); ok { + return r.readDepth(p, from, value, depth+1) + } + if at.param(v) { + return setupValue{}, false + } + } + return r.constant(p, v.Name) + case *ast.SelectorExpr: + x, ok := v.X.(*ast.Ident) + if !ok || at == nil { + return setupValue{}, false + } + path, ok := imports(at.file)[x.Name] + folder, inModule := strings.CutPrefix(path, rcloneModule+"/") + if !ok || !inModule { + return setupValue{}, false + } + other, err := r.pkg(folder) + if err != nil || other == nil { + return setupValue{}, false + } + return r.constant(other, v.Sel.Name) + case *ast.CallExpr: + sel, ok := v.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Sprintf" || len(v.Args) == 0 || at == nil { + return setupValue{}, false + } + if x, ok := sel.X.(*ast.Ident); !ok || imports(at.file)[x.Name] != "fmt" { + return setupValue{}, false + } + f, ok := r.readDepth(p, at, v.Args[0], depth+1) + if !ok || f.format { + return setupValue{}, false + } + return setupValue{text: f.text, format: true}, true + } + return setupValue{}, false +} + +// constant returns the value of the package's top-level constant name, when it is a text. A +// constant is read once. One that is made of itself can't be read. +func (r *sourceReader) constant(p *sourcePkg, name string) (setupValue, bool) { + c := p.consts[name] + if c == nil || c.reading { + return setupValue{}, false + } + if !c.read { + c.reading = true + c.value, c.ok = r.read(p, &site{file: c.file}, c.expr) + c.reading, c.read = false, true + } + return c.value, c.ok +} diff --git a/build/i18n/setup_test.go b/build/i18n/setup_test.go new file mode 100644 index 00000000..cd753a59 --- /dev/null +++ b/build/i18n/setup_test.go @@ -0,0 +1,314 @@ +package main + +import ( + "maps" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// setupFixture is a small rclone module: fs with its own helpers and a common question, a +// constant in fs/config, the sign-in's questions in lib/oauthutil, and a few backends. +var setupFixture = map[string]string{ + "fs/backend_config.go": `package fs + +func ConfigInputOptional(state string, name string, help string) (*ConfigOut, error) { return nil, nil } + +// A helper that passes its caller's question on is not a question. +func ConfigInput(state string, name string, help string) (*ConfigOut, error) { + return ConfigInputOptional(state, name, help) +} + +func configAll() (*ConfigOut, error) { + return ConfigConfirm("*all-advanced", false, "config_fs_advanced", "Edit advanced config?") +} +`, + "fs/config/config.go": `package config + +const ( + ConfigClientID = "client_" + configID + configID = "id" +) +`, + "lib/oauthutil/oauthutil.go": `package oauthutil + +import ( + "fmt" + "strings" + + "github.com/rclone/rclone/fs" +) + +func ConfigOAuth(state string, newState func(string) string, url string, err error) (*fs.ConfigOut, error) { + switch state { + case "*oauth": + return fs.ConfigConfirm(newState("*oauth-confirm"), true, "config_refresh_token", "Token already configured - replace it?") + case "*oauth-remote": + return fs.ConfigInput(newState("*oauth-do"), "config_verification_code", fmt.Sprintf("Go to this URL:\n\n%s\n", url)) + case "*oauth-paste": + var out strings.Builder + return fs.ConfigInput(newState("*oauth-authorize"), "config_token", out.String()) + } + return fs.ConfigError(newState("*oauth-authorize"), fmt.Sprintf("Couldn't decode response: %v\n", err)) +} +`, + "backend/foo/foo.go": `package foo + +import ( + "fmt" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config" +) + +const backendName = "foo bar" + +const tokenHelp = "Personal " + "login token." + +func init() { + fs.Register(&fs.RegInfo{Name: backendName, Config: Config}) +} + +func Config(state, dev, kind string, err error, items []fs.OptionExample, other bool) (*fs.ConfigOut, error) { + switch state { + case "": + return fs.ConfigChooseExclusiveFixed("type_done", "config_type", "Type of connection", []fs.OptionExample{{ + Value: "personal", + Help: "Personal or Business", + }, { + Value: "", + Help: "None of these", + }}) + case "client": + return fs.ConfigInput("client_set", config.ConfigClientID, "Client "+"Id") + case "token": + return fs.ConfigInput("token_set", "config_login_token", tokenHelp) + case "ok": + return fs.ConfigConfirm("ok_done", true, "config_ok", fmt.Sprintf("Found %q of type %q\n", dev, kind)) + case "ok_again": + return fs.ConfigConfirm("ok_done", true, "config_ok", "Is it OK?") + case "ok_same": + return fs.ConfigConfirm("ok_done", true, "config_ok", "Is it OK?") + case "share": + return fs.ConfigConfirm("share_done", false, "config_share", "Share 100% of it?") + case "device": + var help string + if other { + help = fmt.Sprintf("The other device %s.", dev) + return fs.ConfigChoose("device_done", "config_device", help, 0, nil) + } + help = fmt.Sprintf("The device %s.", dev) + return fs.ConfigChoose("device_done", "config_device", help, 0, nil) + case "branch": + help := "Which one?" + if other { + help = "Which other one?" + } + return fs.ConfigInput("branch_done", "config_branch", help) + case "time": + return fs.ConfigInput("time_done", "config_time", fmt.Sprintf("Took %5.2f s", 1.5)) + case "phone": + return fs.ConfigChooseExclusiveFixed("phone_done", "config_phone", "Select a phone", items) + case "drives": + return fs.ConfigError("", fmt.Sprintf("Failed to list the drives: %v", err)) + case "none": + return fs.ConfigError("type", "No drives found") + } + return fs.ConfigResult("end", "not shown") +} +`, + "backend/foo/foo_test.go": `package foo + +func ask() { fs.ConfigInput("x", "config_test", "Not read: a test file.") } +`, + "backend/plain/plain.go": `package plain + +import "github.com/rclone/rclone/fs" + +func init() { fs.Register(&fs.RegInfo{Name: "plain"}) } +`, + "backend/twice/twice.go": `package twice + +import "github.com/rclone/rclone/fs" + +func init() { + fs.Register(&fs.RegInfo{Name: "one"}) + fs.Register(&fs.RegInfo{Name: "two"}) +} + +func config() (*fs.ConfigOut, error) { return fs.ConfigInput("x", "config_x", "Which?") } +`, +} + +func writeSetupFixture(t *testing.T) string { + t.Helper() + root := t.TempDir() + for name, text := range setupFixture { + path := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +func TestCollectSetup(t *testing.T) { + got, err := collectSetup(writeSetupFixture(t)) + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + // rclone's common config, with fs's own question. The helpers that pass a question on + // are not questions. + k("setup", "question", "config_fs_advanced", "help"): "Edit advanced config?", + k("setup", "question", "config_refresh_token", "help"): "Token already configured - replace it?", + k("setup", "question", "config_verification_code", "help"): "Go to this URL:\n\n%s\n", + k("setup", "error", "help"): "Couldn't decode response: %v\n", + + // A backend, by the name it registers: a fixed list of choices, a name that is another + // package's constant, a help that is a constant made of two literals, and a help that is + // a literal with a "%", which is doubled. + k("setup", "backend", "foo bar", "question", "config_type", "help"): "Type of connection", + k("setup", "backend", "foo bar", "question", "config_type", "example", "personal", "help"): "Personal or Business", + k("setup", "backend", "foo bar", "question", "config_type", "example", "__empty__", "help"): "None of these", + k("setup", "backend", "foo bar", "question", "client_id", "help"): "Client Id", + k("setup", "backend", "foo bar", "question", "config_login_token", "help"): "Personal login token.", + k("setup", "backend", "foo bar", "question", "config_share", "help"): "Share 100%% of it?", + // The same question with two texts (and one of them twice), in the order of the source: + // a format and a literal. + k("setup", "backend", "foo bar", "question", "config_ok", "help"): "Found %q of type %q\n", + k("setup", "backend", "foo bar", "question", "config_ok", "help_2"): "Is it OK?", + // A help in a variable, from the assignment before each call. + k("setup", "backend", "foo bar", "question", "config_device", "help"): "The other device %s.", + k("setup", "backend", "foo bar", "question", "config_device", "help_2"): "The device %s.", + // A question whose choices can't be read, and the errors. + k("setup", "backend", "foo bar", "question", "config_phone", "help"): "Select a phone", + k("setup", "backend", "foo bar", "error", "help"): "Failed to list the drives: %v", + k("setup", "backend", "foo bar", "error", "help_2"): "No drives found", + } + if keys := got.keys(); !maps.Equal(keys, want) { + for _, key := range slices.Sorted(maps.Keys(keys)) { + if want[key] != keys[key] { + t.Errorf("%s = %q, want %q", strings.ReplaceAll(key, sep, "."), keys[key], want[key]) + } + } + for _, key := range slices.Sorted(maps.Keys(want)) { + if _, ok := keys[key]; !ok { + t.Errorf("no %s", strings.ReplaceAll(key, sep, ".")) + } + } + } + + // Each text that can't be read is named by its file and line. + unread := strings.Join(got.unread, "\n") + for _, want := range []string{ + "lib/oauthutil/oauthutil.go:18: the help of config_token can't be read: out.String()", + // A variable that a branch may have changed. + "backend/foo/foo.go:", ": the help of config_branch can't be read: help", + ": the help of config_time can't be matched: it uses %5.2f", + ": the choices of config_phone can't be read, because they are made at run time: items", + "backend/twice: the backend's name can't be read (2 names found), so its questions are skipped", + } { + if !strings.Contains(unread, want) { + t.Errorf("the texts that can't be read lack %q:\n%s", want, unread) + } + } + if len(got.unread) != 5 { + t.Errorf("%d texts can't be read, want 5:\n%s", len(got.unread), unread) + } + if foo := got.scopes["foo bar"]; foo == nil || foo.asked != 10 || foo.shown != 2 { + t.Errorf("foo bar: %+v", foo) + } + if _, ok := got.scopes["plain"]; ok { + t.Error("a backend that asks nothing has texts") + } +} + +// The registry's text of a common question is kept when the source reads it otherwise, and the +// source adds what the registry lacks. +func TestAddSetup(t *testing.T) { + live := map[string]string{k("setup", "question", "config_is_local", "help"): "Use web browser?"} + setup := &setupSource{ + scopes: map[string]*setupTexts{ + "": {questions: map[string][]string{"config_is_local": {"Use a web browser?"}, "config_new": {"New?"}}}, + }, + unread: []string{"lib/x.go:1: the help of config_y can't be read: y"}, + } + problems := strings.Join(addSetup(live, setup), "\n") + if live[k("setup", "question", "config_is_local", "help")] != "Use web browser?" || live[k("setup", "question", "config_new", "help")] != "New?" { + t.Errorf("live is %q", live) + } + for _, want := range []string{"rclone's source: lib/x.go:1: the help of config_y can't be read: y", "setup.question.config_is_local.help other texts"} { + if !strings.Contains(problems, want) { + t.Errorf("the problems lack %q:\n%s", want, problems) + } + } +} + +// When rclone swaps a question's two texts, each translation follows its English text to its +// new key. +func TestMergeRcloneMovesATranslationWithItsText(t *testing.T) { + first := k("setup", "backend", "drive", "question", "config_change_team_drive", "help") + second := k("setup", "backend", "drive", "question", "config_change_team_drive", "help_2") + files := map[string]map[string]string{ + "en": {first: "Configure this as a Shared Drive?", second: "Change the Shared Drive %q?"}, + "es": {first: "¿Configurarlo como unidad compartida?", second: "¿Cambiar la unidad compartida %q?"}, + } + mergeRclone(map[string]string{first: "Change the Shared Drive %q?", second: "Configure this as a Shared Drive?"}, files, false) + if files["es"][first] != "¿Cambiar la unidad compartida %q?" || files["es"][second] != "¿Configurarlo como unidad compartida?" { + t.Errorf("es is %q", files["es"]) + } + // A text that no key had before has no translation. + mergeRclone(map[string]string{first: "Change the Shared Drive ID %q?", second: "Configure this as a Shared Drive?"}, files, false) + if _, ok := files["es"][first]; ok { + t.Errorf("a new text kept a translation: %q", files["es"][first]) + } +} + +// A setup question's translation must keep its English format's values, in any order. +func TestReviewRcloneSetupPlaceholders(t *testing.T) { + dir := t.TempDir() + ok := k("setup", "backend", "onedrive", "question", "config_drive_ok", "help") + choice := k("setup", "backend", "onedrive", "question", "config_type", "example", "onedrive", "help") + files := map[string]map[string]string{ + "en": {ok: "Found drive %q of type %q", choice: "OneDrive 100% Personal"}, + "es": {ok: "Unidad %[2]q de tipo %[1]q", choice: "OneDrive 100% personal"}, + "zh-CN": {ok: "找到 drive %q", choice: "OneDrive 100% Personal"}, + } + for lang, f := range files { + if err := writeTexts(filepath.Join(dir, "locales", lang, rcloneFile), f); err != nil { + t.Fatal(err) + } + } + problems, _, err := reviewRclone(dir, []string{"en", "es", "zh-CN"}) + if err != nil { + t.Fatal(err) + } + want := "locales/zh-CN/rclone.json: the translation of setup.backend.onedrive.question.config_drive_ok.help has other placeholders (1:q) than the English (1:q 2:q)" + if len(problems) != 1 || problems[0] != want { + t.Errorf("problems %q, want only %q", problems, want) + } +} + +func TestSetupFormat(t *testing.T) { + for key, want := range map[string]bool{ + k("setup", "error", "help"): true, + k("setup", "question", "config_is_local", "help"): true, + k("setup", "backend", "seafile", "error", "help_2"): true, + k("setup", "backend", "onedrive", "question", "config_type", "help_12"): true, + k("setup", "confirm", "example", "true", "help"): false, + k("setup", "backend", "onedrive", "question", "config_type", "example", "error", "help"): false, + k("setup", "backend", "x", "question", "error", "help"): true, + k("setup", "backend", "x", "question", "config_type", "description"): false, + k("backend", "local", "option", "nounc", "help"): false, + } { + if got := setupFormat(key); got != want { + t.Errorf("setupFormat(%s) = %v", strings.ReplaceAll(key, sep, "."), got) + } + } +} diff --git a/build/linux/check-appimage.sh b/build/linux/check-appimage.sh new file mode 100755 index 00000000..c3c4b364 --- /dev/null +++ b/build/linux/check-appimage.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Checks an AppImage made by build/package.sh: that GTK 4, WebKitGTK 6.0 and gtk4-layer-shell are +# inside with their license files, and that rcui starts through AppRun. It runs `rcui version` and +# looks for the noselfupdate tag, which shows that the build is ours. main.go handles `version` +# before Wails starts, so the check doesn't need a display. +# +# build/linux/check-appimage.sh build/dist/Rclone-UI-4.0.0-linux-x86_64.AppImage +set -euo pipefail + +image=$(realpath "$1") +cd "$(mktemp -d)" +"$image" --appimage-extract > /dev/null +export APPDIR=$PWD/squashfs-root +test -s "$APPDIR/usr/share/doc/rcui/THIRD_PARTY_NOTICES.txt" +# Each library that rcui links for its UI, and the Debian package whose copyright file goes with it. +for pair in libgtk-4.so.1:libgtk-4-1 libwebkitgtk-6.0.so.4:libwebkitgtk-6.0-4 \ + libgtk4-layer-shell.so.0:libgtk4-layer-shell0; do + lib=${pair%%:*} pkg=${pair#*:} + if [ ! -e "$APPDIR/usr/lib/$lib" ] || [ ! -s "$APPDIR/usr/share/doc/$pkg/copyright" ]; then + echo "the AppImage lacks usr/lib/$lib or usr/share/doc/$pkg/copyright" >&2 + exit 1 + fi +done + +# libgcrypt needs the libgpg-error that it was built with. An older host's copy lacks symbols. +if [ -e "$APPDIR/usr/lib/libgcrypt.so.20" ] && [ ! -e "$APPDIR/usr/lib/libgpg-error.so.0" ]; then + echo "the AppImage carries libgcrypt without libgpg-error" >&2 + exit 1 +fi + +timeout 30 "$APPDIR/AppRun" version | tee /dev/stderr | grep -q noselfupdate +echo "the AppImage's rcui starts, and its libraries and license files are in it" diff --git a/build/linux/icons/128x128.png b/build/linux/icons/128x128.png new file mode 100644 index 00000000..b3da6ffe Binary files /dev/null and b/build/linux/icons/128x128.png differ diff --git a/src-tauri/icons/128x128@2x.png b/build/linux/icons/256x256.png similarity index 100% rename from src-tauri/icons/128x128@2x.png rename to build/linux/icons/256x256.png diff --git a/src-tauri/icons/32x32.png b/build/linux/icons/32x32.png similarity index 100% rename from src-tauri/icons/32x32.png rename to build/linux/icons/32x32.png diff --git a/src-tauri/icons/icon.png b/build/linux/icons/512x512.png similarity index 100% rename from src-tauri/icons/icon.png rename to build/linux/icons/512x512.png diff --git a/build/linux/nfpm.yaml b/build/linux/nfpm.yaml new file mode 100644 index 00000000..a56edccf --- /dev/null +++ b/build/linux/nfpm.yaml @@ -0,0 +1,65 @@ +# deb and rpm: build/package.sh fills in ${VERSION}, ${GOARCH} and ${BIN} (the build's folder) +# and runs `wails3 tool package` on it from the repository root. +name: rcui +arch: ${GOARCH} +platform: linux +version: ${VERSION} +release: "1" +section: utils +priority: optional +maintainer: Rclone +vendor: Rclone +homepage: https://github.com/rclone/rclone-ui +license: Apache-2.0 +description: | + Cross-platform GUI for rclone & S3 +contents: + - src: ${BIN}/rcui + dst: /usr/bin/rcui + file_info: + mode: 0755 + - src: build/linux/org.rclone.ui.desktop + dst: /usr/share/applications/org.rclone.ui.desktop + - src: build/linux/icons/32x32.png + dst: /usr/share/icons/hicolor/32x32/apps/org.rclone.ui.png + - src: build/linux/icons/128x128.png + dst: /usr/share/icons/hicolor/128x128/apps/org.rclone.ui.png + - src: build/linux/icons/256x256.png + dst: /usr/share/icons/hicolor/256x256/apps/org.rclone.ui.png + - src: build/linux/icons/512x512.png + dst: /usr/share/icons/hicolor/512x512/apps/org.rclone.ui.png + # The launcher's GNOME Shell extension, which it needs because GNOME lets no app place its own + # window. It is installed for every user and removed with the package. The app enables it + # (app/launcher/view/linux/gnome/ensure_linux.go). + - src: app/launcher/view/linux/gnome/metadata.json + dst: /usr/share/gnome-shell/extensions/launcher@rclone.org/metadata.json + - src: app/launcher/view/linux/gnome/extension.js + dst: /usr/share/gnome-shell/extensions/launcher@rclone.org/extension.js + # Debian keeps a package's license in /usr/share/doc//copyright. + - src: LICENSE + dst: /usr/share/doc/rcui/copyright + type: license + - src: public/THIRD_PARTY_NOTICES.txt + dst: /usr/share/doc/rcui/THIRD_PARTY_NOTICES.txt + type: license +# GTK 4 and WebKitGTK 6.0, which is Wails' default stack, and gtk4-layer-shell, which rcui links +# for the launcher. The packages need Ubuntu 26.04, Debian 13, Fedora 41 or a later release, +# because older Ubuntu and Debian releases don't package gtk4-layer-shell. FUSE is for mounts, +# because rclone mount runs fusermount3. +depends: + - libgtk-4-1 + - libwebkitgtk-6.0-4 + - libgtk4-layer-shell0 +recommends: + - fuse3 +overrides: + rpm: + depends: + - gtk4 + - webkitgtk6.0 + - gtk4-layer-shell + recommends: + - fuse3 +scripts: + postinstall: build/linux/postinstall.sh + postremove: build/linux/postinstall.sh diff --git a/build/linux/org.rclone.ui.desktop b/build/linux/org.rclone.ui.desktop new file mode 100644 index 00000000..6bee21ba --- /dev/null +++ b/build/linux/org.rclone.ui.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Type=Application +Name=Rclone UI +Comment=Cross-platform GUI for rclone & S3 +Exec=/usr/bin/rcui %u +Icon=org.rclone.ui +Terminal=false +Categories=Utility; +StartupWMClass=org.rclone.ui +MimeType=x-scheme-handler/rclone; diff --git a/build/linux/org.rclone.ui.metainfo.xml b/build/linux/org.rclone.ui.metainfo.xml new file mode 100644 index 00000000..01b0dea9 --- /dev/null +++ b/build/linux/org.rclone.ui.metainfo.xml @@ -0,0 +1,115 @@ + + + org.rclone.ui + + Rclone UI + The GUI for rclone. + + MIT + Apache-2.0 + + + Rclone + + + + pointing + keyboard + touch + + + + 360 + + + +

+ The best way to manage your rclone remotes & tasks in a light and easy way. +

+

+ Free to use & open source. +

+

+ Stop remembering flags, copy pasting commands, and wasting time. +

+

+ Features: +

+
    +
  1. ✅ Cross platform running on Windows, Linux, macOS (x64, Arm and Apple Silicon)
  2. +
  3. ✅ rclone built in, using rclone's own config file
  4. +
  5. ✅ A file browser for every remote, side by side
  6. +
  7. ✅ Copy, Sync, Move, Delete, Bisync, Mount, Serve, and more
  8. +
  9. ✅ Transfers and their history (see every background operation)
  10. +
  11. ✅ Watchers that keep two folders in sync
  12. +
  13. ✅ Schedules that run a copy, sync or other operation at set times
  14. +
  15. ✅ Templates for the operations you run often
  16. +
  17. ✅ A launcher that opens anything from a shortcut
  18. +
  19. ✅ Notifications by email, webhook and more
  20. +
  21. ✅ Proxy support
  22. +
  23. ✅ Encrypt your rclone config, with a password or a password command
  24. +
+

+ No tracking, no ads. + Do more with Rclone! +

+
+ + + System + Network + + + + Rclone + S3 + Google Drive + OneDrive + FTP + SFTP + WebDAV + Rsync + File Manager + + + + #0a0325 + #0a0325 + + + + + https://github.com/rclone/rclone-ui/issues + https://github.com/rclone/rclone-ui + https://github.com/rclone/rclone-ui + + + + https://raw.githubusercontent.com/rclone/rclone-ui/main/build/linux/screenshots/1-commander.png + Browse your remotes side by side + + + https://raw.githubusercontent.com/rclone/rclone-ui/main/build/linux/screenshots/2-launcher.png + Open anything from a shortcut + + + https://raw.githubusercontent.com/rclone/rclone-ui/main/build/linux/screenshots/3-copy.png + Copy, Sync, Move, Mount, Serve and more + + + https://raw.githubusercontent.com/rclone/rclone-ui/main/build/linux/screenshots/4-remotes.png + Manage your remotes + + + + + + https://github.com/rclone/rclone-ui/releases/tag/v4.0.0 + +

The first release.

+
+
+
+ + org.rclone.ui.desktop +
diff --git a/build/linux/postinstall.sh b/build/linux/postinstall.sh new file mode 100755 index 00000000..48ebe942 --- /dev/null +++ b/build/linux/postinstall.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Refresh the desktop and icon caches so that the menus and the rclone:// handler pick up the +# new .desktop file and icons. +if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database -q /usr/share/applications || true +fi +if command -v gtk-update-icon-cache >/dev/null 2>&1; then + gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true +fi +exit 0 diff --git a/build/linux/screenshots/1-commander.png b/build/linux/screenshots/1-commander.png new file mode 100644 index 00000000..c52893f5 Binary files /dev/null and b/build/linux/screenshots/1-commander.png differ diff --git a/build/linux/screenshots/2-launcher.png b/build/linux/screenshots/2-launcher.png new file mode 100644 index 00000000..06b433f1 Binary files /dev/null and b/build/linux/screenshots/2-launcher.png differ diff --git a/build/linux/screenshots/3-copy.png b/build/linux/screenshots/3-copy.png new file mode 100644 index 00000000..7d23ead7 Binary files /dev/null and b/build/linux/screenshots/3-copy.png differ diff --git a/build/linux/screenshots/4-remotes.png b/build/linux/screenshots/4-remotes.png new file mode 100644 index 00000000..b0d48e14 Binary files /dev/null and b/build/linux/screenshots/4-remotes.png differ diff --git a/build/notices/gpl-3.0.txt b/build/notices/gpl-3.0.txt new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/build/notices/gpl-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/build/notices/main.go b/build/notices/main.go new file mode 100644 index 00000000..b10d7476 --- /dev/null +++ b/build/notices/main.go @@ -0,0 +1,528 @@ +// Command notices writes public/THIRD_PARTY_NOTICES.txt, which holds the licenses of the +// third-party software that a release of Rclone UI includes. That covers the Go modules linked +// into rcui on every target that build/build.sh builds (with its tags), Go's standard library, +// and the npm packages that the pages are built from. The About section shows the file, and +// build/package.sh puts it in every package. A license text that several parts share is printed +// once. +// +// go run ./build/notices # write it +// go run ./build/notices -check # fail when it is out of date (CI) +package main + +import ( + "bytes" + "crypto/sha256" + _ "embed" + "encoding/json" + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "unicode/utf8" +) + +const out = "public/THIRD_PARTY_NOTICES.txt" + +// gpl3 is the GNU GPL 3.0. The LGPL 3.0 builds on it and asks for it to be shipped alongside +// (https://www.gnu.org/licenses/gpl-3.0.txt). +// +//go:embed gpl-3.0.txt +var gpl3 string + +// targets are the GOOS/GOARCH pairs that build/build.sh builds. Each one is listed with the tags +// that build.sh uses for it (see buildTags), because a module that only one target links is +// still shipped. +var targets = []struct{ goos, goarch string }{ + {"darwin", "arm64"}, + {"darwin", "amd64"}, + {"windows", "amd64"}, + {"windows", "arm64"}, + {"linux", "amd64"}, + {"linux", "arm64"}, +} + +// licenseFile matches a file at the root of a module or package that holds its terms. +var licenseFile = regexp.MustCompile(`(?i)^(licen[cs]e|copying|notice|patents|unlicense)([._-].*)?$`) + +// A part is one module or package, with the files that hold its terms. +type part struct { + label string // "github.com/rclone/rclone v1.75.1", "react 18.3.1" + files []licensed +} + +type licensed struct{ name, text string } + +// bare is an npm package that declares its license in package.json and ships no file for it. +type bare struct{ label, license, author, repo string } + +func main() { + check := flag.Bool("check", false, "fail when "+out+" is out of date") + flag.Parse() + text, err := notices() + if err != nil { + fmt.Fprintln(os.Stderr, "notices:", err) + os.Exit(1) + } + if *check { + have, err := os.ReadFile(out) + if err != nil || !bytes.Equal(have, text) { + fmt.Fprintf(os.Stderr, "notices: %s is out of date: run go run ./build/notices\n", out) + os.Exit(1) + } + return + } + if err := os.WriteFile(out, text, 0o644); err != nil { + fmt.Fprintln(os.Stderr, "notices:", err) + os.Exit(1) + } +} + +func notices() ([]byte, error) { + own, err := os.ReadFile("LICENSE") + if err != nil { + return nil, err + } + goParts, err := goModules() + if err != nil { + return nil, err + } + npmParts, bares, err := npmPackages() + if err != nil { + return nil, err + } + + var b bytes.Buffer + b.WriteString(`Third-party software in Rclone UI +================================= + +Rclone UI is licensed under the Apache License 2.0, printed at the end of this file. It includes +the software listed here, each part under its own license. A license text that several parts +share is printed once, after the list of the parts it covers. + +The source of Rclone UI is at https://github.com/rclone/rclone-ui, and the source of each part +at its module path or npm package, in the version named. + +This file is generated by ` + "`go run ./build/notices`" + `: don't edit it by hand. + +Also in some packages +--------------------- + +- The AppImage bundles the GTK, WebKitGTK and other system libraries it runs on; their copyright + files are in its usr/share/doc folder. +- The Windows installer carries Microsoft's WebView2 Runtime bootstrapper, under Microsoft's + terms for it (https://developer.microsoft.com/microsoft-edge/webview2/). + +`) + section(&b, "Go modules linked into rcui", goParts) + section(&b, "npm packages the pages are built from", npmParts) + bareSection(&b, bares) + if lgpl3(goParts) || lgpl3(npmParts) { + b.WriteString(rule + "The GNU General Public License 3.0, which the LGPL 3.0 above builds on\n\n") + b.Write(normalize(gpl3)) + b.WriteString("\n") + } + b.WriteString(rule + "Rclone UI's own license (LICENSE)\n\n") + b.Write(normalize(string(own))) + return b.Bytes(), nil +} + +const rule = "================================================================================\n" + +// section prints parts grouped by license text. Each text is printed once, after the parts that +// it covers. +func section(b *bytes.Buffer, title string, parts []part) { + fmt.Fprintf(b, "%s\n%s\n\n", title, strings.Repeat("-", len(title))) + type group struct { + text []byte + users []string + } + groups := map[[32]byte]*group{} + var order [][32]byte + for _, p := range parts { + for _, f := range p.files { + text := normalize(f.text) + key := sha256.Sum256(text) + g, ok := groups[key] + if !ok { + g = &group{text: text} + groups[key] = g + order = append(order, key) + } + g.users = append(g.users, fmt.Sprintf("%s (%s)", p.label, f.name)) + } + } + for _, key := range order { + g := groups[key] + b.WriteString(rule) + for _, u := range g.users { + fmt.Fprintf(b, "%s\n", u) + } + b.WriteString("\n") + b.Write(g.text) + b.WriteString("\n") + } +} + +// bareSection lists the npm packages that have no license file, grouped by the license that +// their package.json declares. It adds the permission text that the common licenses ask to keep. +func bareSection(b *bytes.Buffer, bares []bare) { + if len(bares) == 0 { + return + } + title := "npm packages that ship no license file" + fmt.Fprintf(b, "%s\n%s\n\nThese declare their license in package.json only; their authors hold the copyright.\n\n", + title, strings.Repeat("-", len(title))) + byLicense := map[string][]bare{} + for _, p := range bares { + byLicense[p.license] = append(byLicense[p.license], p) + } + licenses := make([]string, 0, len(byLicense)) + for l := range byLicense { + licenses = append(licenses, l) + } + slices.Sort(licenses) + for _, l := range licenses { + b.WriteString(rule) + fmt.Fprintf(b, "Declared as %s:\n", l) + for _, p := range byLicense[l] { + line := p.label + if p.author != "" { + line += ", by " + p.author + } + if p.repo != "" { + line += ", " + p.repo + } + fmt.Fprintf(b, "%s\n", line) + } + // A compound declaration such as "(Apache-2.0 AND BSD-3-Clause)" gets the text of each. + for _, id := range licenseID.FindAllString(l, -1) { + if t, ok := permission[id]; ok { + b.WriteString("\n" + t) + } + } + b.WriteString("\n") + } +} + +// licenseID is an SPDX identifier in a license expression. +var licenseID = regexp.MustCompile(`[A-Za-z0-9][A-Za-z0-9.+-]*`) + +// permission holds the text that each license declared by a bare package asks to keep. The +// copyright line refers to the authors named above. The Apache-2.0 text is printed at the end of +// the file, as Rclone UI's own license. +var permission = map[string]string{ + "MIT": `Copyright (c) the authors named above + +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. +`, + "ISC": `Copyright (c) the authors named above + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without +fee is hereby granted, provided that the above copyright notice and this permission notice appear +in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +`, + "BSD-3-Clause": `Copyright (c) the authors named above + +Redistribution and use in source and binary forms, with or without modification, are permitted +provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions + and the following disclaimer. +2. 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. +3. Neither the name of the copyright holder 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 HOLDER 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. +`, + "Apache-2.0": "The Apache License 2.0 is printed at the end of this file.\n", +} + +// lgpl3 reports whether a part is under the LGPL 3.0, which asks for the GPL 3.0 to be included +// with it. +func lgpl3(parts []part) bool { + for _, p := range parts { + for _, f := range p.files { + if strings.Contains(f.text, "GNU LESSER GENERAL PUBLIC LICENSE") && strings.Contains(f.text, "Version 3") { + return true + } + } + } + return false +} + +// normalize returns a text as it is printed: UTF-8, LF line endings, no trailing blanks, and +// one final newline. A file that isn't UTF-8 is read as Latin-1, which is what the few old files +// with a © use. +func normalize(text string) []byte { + if !utf8.ValidString(text) { + runes := make([]rune, len(text)) + for i := range len(text) { + runes[i] = rune(text[i]) + } + text = string(runes) + } + text = strings.ReplaceAll(text, "\r\n", "\n") + lines := strings.Split(text, "\n") + for i, l := range lines { + lines[i] = strings.TrimRight(l, " \t") + } + return []byte(strings.TrimSpace(strings.Join(lines, "\n")) + "\n") +} + +// buildTags returns the tags that build/build.sh uses for goos/goarch. It asks build.sh, so that +// the tags are defined in one place. +func buildTags(goos, goarch string) (string, error) { + cmd := exec.Command("bash", "build/build.sh", "--print-tags") + cmd.Env = append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch) + cmd.Stderr = os.Stderr + tags, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("build/build.sh --print-tags for %s/%s: %w", goos, goarch, err) + } + return strings.TrimSpace(string(tags)), nil +} + +// goModules returns the modules that any target links, and Go's standard library. +func goModules() ([]part, error) { + type mod struct{ path, version, dir string } + seen := map[string]mod{} + for _, t := range targets { + tags, err := buildTags(t.goos, t.goarch) + if err != nil { + return nil, err + } + cmd := exec.Command("go", "list", "-deps", "-tags", tags, "-f", + `{{with .Module}}{{if not .Main}}{{with .Replace}}{{.Path}} {{.Version}} {{.Dir}}{{else}}{{.Path}} {{.Version}} {{.Dir}}{{end}}{{end}}{{end}}`, ".") + cmd.Env = append(os.Environ(), "GOOS="+t.goos, "GOARCH="+t.goarch, "CGO_ENABLED=1") + cmd.Stderr = os.Stderr + list, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("go list for %s/%s: %w", t.goos, t.goarch, err) + } + for line := range strings.SplitSeq(string(list), "\n") { + f := strings.Split(line, "\t") + if len(f) != 3 { + continue + } + // A module replaced by a folder of this repository (tools/nosentry) is our own code. + if f[1] == "" && (strings.HasPrefix(f[0], "./") || strings.HasPrefix(f[0], "../")) { + continue + } + seen[f[0]+" "+f[1]] = mod{f[0], f[1], f[2]} + } + } + keys := make([]string, 0, len(seen)) + for k := range seen { + keys = append(keys, k) + } + slices.Sort(keys) + + goroot, err := exec.Command("go", "env", "GOROOT").Output() + if err != nil { + return nil, err + } + goversion, err := exec.Command("go", "env", "GOVERSION").Output() + if err != nil { + return nil, err + } + std, err := filesAt(strings.TrimSpace(string(goroot))) + if err != nil || len(std) == 0 { + return nil, fmt.Errorf("Go's own license: %v", err) + } + // A patch release of the toolchain doesn't change the license. Naming it by its minor + // version keeps the file from changing with each CI runner's Go. + minor := strings.Join(strings.SplitN(strings.TrimSpace(string(goversion)), ".", 3)[:2], ".") + parts := []part{{label: "The Go standard library (" + minor + ")", files: std}} + + var missing []string + for _, k := range keys { + m := seen[k] + files, err := filesAt(m.dir) + if err != nil { + return nil, fmt.Errorf("%s: %w", k, err) + } + if len(files) == 0 { + missing = append(missing, k) + continue + } + parts = append(parts, part{label: m.path + " " + m.version, files: files}) + } + if len(missing) > 0 { + return nil, fmt.Errorf("no license file at the root of %s: add its terms by hand", strings.Join(missing, ", ")) + } + return parts, nil +} + +// npmPackages returns the packages that `npm ls --omit=dev` lists, split into those with license +// files and those without. +func npmPackages() ([]part, []bare, error) { + cmd := exec.Command("npm", "ls", "--omit=dev", "--all", "--parseable") + cmd.Stderr = os.Stderr + list, err := cmd.Output() + if err != nil { + return nil, nil, fmt.Errorf("npm ls: %w", err) + } + root, err := os.Getwd() + if err != nil { + return nil, nil, err + } + // npm prints physical paths. When run from a symlinked directory (macOS's /tmp is one), the + // root would otherwise be listed as a package of its own. + if real, err := filepath.EvalSymlinks(root); err == nil { + root = real + } + var parts []part + var bares []bare + seen := map[string]bool{} + for dir := range strings.SplitSeq(strings.TrimSpace(string(list)), "\n") { + if dir == "" || dir == root { + continue + } + p, err := readPackage(dir) + if err != nil { + return nil, nil, err + } + label := p.Name + " " + p.Version + if seen[label] { + continue // the same version at another place in node_modules + } + seen[label] = true + files, err := filesAt(dir) + if err != nil { + return nil, nil, err + } + if len(files) > 0 { + parts = append(parts, part{label: label, files: files}) + continue + } + license := p.license() + if license == "" { + return nil, nil, fmt.Errorf("%s declares no license and ships no license file: add its terms by hand", label) + } + bares = append(bares, bare{label: label, license: license, author: p.author(), repo: p.repo()}) + } + slices.SortFunc(parts, func(a, b part) int { return strings.Compare(a.label, b.label) }) + slices.SortFunc(bares, func(a, b bare) int { return strings.Compare(a.label, b.label) }) + return parts, bares, nil +} + +type packageJSON struct { + Name string `json:"name"` + Version string `json:"version"` + License json.RawMessage `json:"license"` + Licenses json.RawMessage `json:"licenses"` + Author json.RawMessage `json:"author"` + Repository json.RawMessage `json:"repository"` +} + +func readPackage(dir string) (packageJSON, error) { + var p packageJSON + raw, err := os.ReadFile(filepath.Join(dir, "package.json")) + if err != nil { + return p, err + } + if err := json.Unmarshal(raw, &p); err != nil { + return p, fmt.Errorf("%s: %w", dir, err) + } + if p.Name == "" { + return p, fmt.Errorf("%s: a package with no name", dir) + } + return p, nil +} + +// stringOr reads a package.json field that is a string or an object with key. +func stringOr(raw json.RawMessage, key string) string { + var s string + if json.Unmarshal(raw, &s) == nil { + return s + } + var o map[string]any + if json.Unmarshal(raw, &o) == nil { + if v, ok := o[key].(string); ok { + return v + } + } + return "" +} + +func (p packageJSON) license() string { + if l := stringOr(p.License, "type"); l != "" { + return l + } + var list []map[string]any + if json.Unmarshal(p.Licenses, &list) == nil { + var types []string + for _, l := range list { + if t, ok := l["type"].(string); ok { + types = append(types, t) + } + } + return strings.Join(types, " OR ") + } + return "" +} + +func (p packageJSON) author() string { return stringOr(p.Author, "name") } + +func (p packageJSON) repo() string { + r := stringOr(p.Repository, "url") + r = strings.TrimPrefix(r, "git+") + return strings.TrimSuffix(r, ".git") +} + +// filesAt returns the license files at the root of dir, with their names. +func filesAt(dir string) ([]licensed, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + var files []licensed + for _, e := range entries { + if e.IsDir() || !licenseFile.MatchString(e.Name()) { + continue + } + raw, err := os.ReadFile(filepath.Join(dir, e.Name())) + if err != nil { + return nil, err + } + if len(bytes.TrimSpace(raw)) == 0 { + continue + } + files = append(files, licensed{name: e.Name(), text: string(raw)}) + } + return files, nil +} diff --git a/build/package.sh b/build/package.sh new file mode 100755 index 00000000..700ddb3f --- /dev/null +++ b/build/package.sh @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# Packages a build made by build/build.sh (build/bin/-) for its OS. The packages +# go into build/dist, under the file names that every release uses and that its feed and the +# release page link to (build/release's updateFiles and Published), with V the version: +# +# darwin Rclone-UI-V-macos-.dmg, Rclone-UI-V-macos-.app.tar.gz (for +# updates) +# windows Rclone-UI-V-windows--setup.exe (NSIS, also used by updates and WinGet), +# Rclone-UI-V-windows--portable.zip (a portable copy, updated by hand) +# linux Rclone-UI-V-linux-.AppImage, Rclone-UI-V-linux-.deb, +# Rclone-UI-V-linux-.rpm +# +# Signing happens when its secrets are set: +# macOS APPLE_SIGNING_IDENTITY (codesign), and APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID +# (notarization). Without them the app is signed ad hoc, and only runs on this Mac. +# Windows SIGN_COMMAND, a command with %1 for the file (Azure Trusted Signing in a release) +# When APP_RELEASE_CHECK is set (a release build), missing macOS secrets fail the build instead. +# The signatures that updates check are made by build/release, which the release workflow runs. +# +# GOOS=darwin GOARCH=arm64 build/package.sh +set -euo pipefail +cd "$(dirname "$0")/.." + +goos=${GOOS:-$(go env GOOS)} +goarch=${GOARCH:-$(go env GOARCH)} +version=${APP_VERSION:-$(node -p "require('./package.json').version")} +bin=build/bin/$goos-$goarch +dist=build/dist +mkdir -p "$dist" +work=$(mktemp -d) +name="Rclone-UI-$version" +trap 'rm -rf "$work"' EXIT + +# wails3 runs on this machine, whatever GOOS/GOARCH the package is for. +wails3() { env -u GOOS -u GOARCH go tool -modfile=tools/go.mod wails3 "$@"; } + +# fetch URL SHA256 DEST downloads a pinned file, and fails unless it has that sha256. +fetch() { + curl -fsSL -o "$3" "$1" + echo "$2 $3" | sha256sum -c - +} + +sign_windows() { + [ -n "${SIGN_COMMAND:-}" ] || return 0 + local cmd=${SIGN_COMMAND//%1/\"$1\"} + echo "signing $1" + eval "$cmd" +} + +case $goos in +darwin) + arch=x64 + [ "$goarch" = arm64 ] && arch=arm64 + app="$work/Rclone UI.app" + mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" + cp "$bin/rcui" "$app/Contents/MacOS/rcui" + sed "s/@VERSION@/$version/g" build/darwin/Info.plist > "$app/Contents/Info.plist" + cp build/darwin/icons.icns "$app/Contents/Resources/icons.icns" + cp LICENSE public/THIRD_PARTY_NOTICES.txt "$app/Contents/Resources/" + printf 'APPL????' > "$app/Contents/PkgInfo" + + notarizing=false + if [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then + notarizing=true + fi + # A release that would be signed ad hoc or not notarized fails here. codesign --verify + # accepts such an app, but Gatekeeper refuses it on every other Mac. + if [ -n "${APP_RELEASE_CHECK:-}" ] && { [ -z "${APPLE_SIGNING_IDENTITY:-}" ] || ! $notarizing; }; then + echo "a release is signed and notarized: APPLE_SIGNING_IDENTITY, APPLE_ID, APPLE_PASSWORD and APPLE_TEAM_ID must all be set" >&2 + exit 1 + fi + # notarize FILE STAPLED sends FILE to Apple for notarization, then staples the ticket to + # STAPLED and checks it there. STAPLED is the app that FILE was zipped from, or the dmg itself. + notarize() { + echo "notarizing $1" + xcrun notarytool submit "$1" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait + xcrun stapler staple "$2" + xcrun stapler validate "$2" + } + if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then + # Sign with the hardened runtime. rcui needs no entitlements, because WebKit's processes + # belong to the system, and the mount and serve child processes are rcui itself. + codesign --force --options runtime --timestamp --sign "$APPLE_SIGNING_IDENTITY" "$app" + if $notarizing; then + (cd "$work" && ditto -c -k --keepParent "Rclone UI.app" app.zip) + notarize "$work/app.zip" "$app" + # Check Gatekeeper's verdict, as a downloaded copy would get it. + spctl -a -vv "$app" + fi + else + codesign --force --sign - "$app" + fi + codesign --verify --strict "$app" + + # The archive for updates has the bundle at its root (app/update's untarBundle). + tar -C "$work" -czf "$dist/$name-macos-$arch.app.tar.gz" "Rclone UI.app" + + # The dmg shows the app on the left and Applications on the right. + wails3 tool package -format dmg -name "Rclone UI" -out "$work" -window-width 660 -window-height 400 + if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then + codesign --force --timestamp --sign "$APPLE_SIGNING_IDENTITY" "$work/Rclone UI.dmg" + if $notarizing; then + notarize "$work/Rclone UI.dmg" "$work/Rclone UI.dmg" + spctl -a -vv -t open --context context:primary-signature "$work/Rclone UI.dmg" + fi + fi + mv "$work/Rclone UI.dmg" "$dist/$name-macos-$arch.dmg" + ;; + +windows) + arch=x64 + [ "$goarch" = arm64 ] && arch=arm64 + sign_windows "$bin/rcui.exe" + sign_windows "$bin/bin/rclone.exe" + # The WebView2 bootstrapper, for machines without WebView2. + wails3 generate webview2bootstrapper -dir "$work" + # WinFsp's installer, unchanged, which is what its license lets the app ship. The installer + # and the portable zip put it next to rcui.exe as winfsp.msi (core/mounts' WinFspInstaller). + # The installer installs WinFsp, and the Mount page offers it when it is missing. This is a + # 2.2 beta, because WinFsp's last stable release (2.1) lacks the security fixes of the 2.2 + # betas. + fetch https://github.com/winfsp/winfsp/releases/download/v2.2B5/winfsp-2.2.26286.msi \ + 293ffb9bcc0b625c85079fe85fa77f8fe98170aba51a02ac9c83d58f6c3b0e2f "$work/winfsp.msi" + # Windows needs four numbers in FILEVERSION, so a pre-release such as 4.0.0-beta.1 becomes + # 4.0.0.0. + # makensis gets full paths. On Windows they are written with \, because its File command + # finds nothing at a path written with / (C:/a/b.exe). Elsewhere makensis reads /. + if command -v cygpath >/dev/null; then + nsisdir() { cygpath -aw "$1"; } + sep='\' + else + nsisdir() { (cd "$1" && pwd); } + sep=/ + fi + nsisdefs=(-DVERSION="$version" -DFILEVERSION="${version%%[-+]*}.0" -DARCH="$arch" + -DBINDIR="$(nsisdir "$bin")" + -DOUTFILE="$(nsisdir "$dist")$sep$name-windows-$arch-setup.exe" + -DWEBVIEW2BOOTSTRAPPER="$(nsisdir "$work")${sep}MicrosoftEdgeWebview2Setup.exe" + -DWINFSPMSI="$(nsisdir "$work")${sep}winfsp.msi") + if [ -n "${SIGN_COMMAND:-}" ]; then + # makensis puts the file's path in place of %1 without quotes, so add them here. + nsisdefs+=(-DSIGNCOMMAND="${SIGN_COMMAND//%1/\"%1\"}") + fi + makensis -V3 "${nsisdefs[@]}" build/windows/nsis/project.nsi + + # The portable zip holds one folder, "Rclone UI". Its empty data folder makes the copy + # portable (core/datadir's Portable): the app keeps its data there, and rclone's config in + # rclone.conf next to it. It ships the same license files as the installer. + portable="$work/portable/Rclone UI" + mkdir -p "$portable/bin" "$portable/data" + cp "$bin/rcui.exe" "$portable/rcui.exe" + cp "$bin/bin/rclone.exe" "$portable/bin/rclone.exe" + cp "$work/winfsp.msi" "$portable/winfsp.msi" + cp LICENSE "$portable/LICENSE.txt" + cp public/THIRD_PARTY_NOTICES.txt build/windows/portable/README.txt "$portable/" + # The zip must keep the empty data folder, which bsdtar does. Windows has it in System32, and + # it is macOS's tar. Git Bash's own tar is GNU tar, which can't write a zip, so --format zip + # makes it fail rather than write a tar file under the zip's name. + zip_tar=tar + if command -v cygpath >/dev/null; then + zip_tar="$(cygpath -S)/tar.exe" # System32, in Git Bash's form + elif command -v bsdtar >/dev/null; then + zip_tar=bsdtar + fi + zip="$(cd "$dist" && pwd -W 2>/dev/null || pwd)/$name-windows-$arch-portable.zip" + rm -f "$zip" + (cd "$work/portable" && "$zip_tar" --format zip -cf "$zip" "Rclone UI") + ;; + +linux) + deb_arch=$goarch + rpm_arch=x86_64 + image_arch=x86_64 + if [ "$goarch" = arm64 ]; then + rpm_arch=aarch64 + image_arch=aarch64 + fi + # nfpm doesn't expand variables in file paths, so the config is filled in for this build. + sed -e "s|\${VERSION}|$version|g" -e "s|\${GOARCH}|$goarch|g" -e "s|\${BIN}|$bin|g" \ + build/linux/nfpm.yaml > "$work/nfpm.yaml" + wails3 tool package -format deb -config "$work/nfpm.yaml" -name rcui -out "$work" + mv "$work/rcui.deb" "$dist/$name-linux-$deb_arch.deb" + wails3 tool package -format rpm -config "$work/nfpm.yaml" -name rcui -out "$work" + mv "$work/rcui.rpm" "$dist/$name-linux-$rpm_arch.rpm" + + # The AppImage is only built on Linux. Wails makes the AppDir, and linuxdeploy with its GTK + # plugin collects GTK 4, WebKitGTK 6.0 and the other libraries that rcui links, which include + # gtk4-layer-shell. Wails picks the GTK version from what rcui links. Then the license files + # are added, and linuxdeploy runs on the AppDir again to pack it. The second run keeps the + # AppRun that it wrapped the first time. + if [ "$(uname -s)" = Linux ]; then + # Pin linuxdeploy, because Wails fetches it from its `continuous` release, which can change + # between builds. Wails writes the AppImage's AppRun itself: a script that starts rcui from + # usr/lib, where WebKit's sandbox finds its helper programs. The AppImage is built on its + # own arch, which is the arch that Wails uses in the tool's name. + if [ "$goarch" = arm64 ]; then + tool_arch=aarch64 + linuxdeploy_sha256=620095110d693282b8ebeb244a95b5e911cf8f65f76c88b4b47d16ae6346fcff + else + tool_arch=x86_64 + linuxdeploy_sha256=c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d + fi + mkdir -p "$work/appimage" + # Wails doesn't download linuxdeploy when this file is already there. + fetch "https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-$tool_arch.AppImage" \ + "$linuxdeploy_sha256" "$work/appimage/linuxdeploy-$tool_arch.AppImage" + + cp build/linux/icons/512x512.png "$work/org.rclone.ui.png" + sed 's|^Exec=/usr/bin/rcui|Exec=rcui|' build/linux/org.rclone.ui.desktop > "$work/org.rclone.ui.desktop" + wails3 generate appimage -binary "$bin/rcui" -icon "$work/org.rclone.ui.png" \ + -desktopfile "$work/org.rclone.ui.desktop" -builddir "$work/appimage" -outputdir "$work" + rm "$work"/*.AppImage + appdir=$(echo "$work"/appimage/*.AppDir) + linuxdeploy=$(echo "$work"/appimage/linuxdeploy-*.AppImage) + + # linuxdeploy leaves libgpg-error to the host, but it carries libgcrypt, which needs the + # libgpg-error that it was built with. With an older host's copy (Ubuntu 24.04), rcui + # fails to start on a missing symbol. + if [ -e "$appdir/usr/lib/libgcrypt.so.20" ]; then + gpg_error=$(ldd "$appdir/usr/lib/libgcrypt.so.20" | awk '$1 == "libgpg-error.so.0" { print $3 }') + install -m644 "$gpg_error" "$appdir/usr/lib/libgpg-error.so.0" + fi + + # Add the licenses: the app's license, the licenses of what it is built from, and the + # copyright files of the system libraries it carries. The copyright files come from the + # Debian packages that installed those libraries. + install -Dm644 LICENSE "$appdir/usr/share/doc/rcui/LICENSE" + install -Dm644 public/THIRD_PARTY_NOTICES.txt "$appdir/usr/share/doc/rcui/THIRD_PARTY_NOTICES.txt" + find "$appdir/usr/lib" -type f -name '*.so*' -print0 | while IFS= read -r -d '' lib; do + pkg=$(dpkg -S "*/$(basename "$lib")" 2>/dev/null | head -n1 | cut -d: -f1 | cut -d, -f1) || true + if [ -n "$pkg" ] && [ -f "/usr/share/doc/$pkg/copyright" ]; then + install -Dm644 "/usr/share/doc/$pkg/copyright" "$appdir/usr/share/doc/$pkg/copyright" + fi + done + + (cd "$work/appimage" && PATH="$PWD:$PATH" NO_STRIP=1 OUTPUT=rcui.AppImage \ + "$linuxdeploy" --appimage-extract-and-run --appdir "$appdir" --output appimage) + mv "$work/appimage/rcui.AppImage" "$dist/$name-linux-$image_arch.AppImage" + else + echo "skipping the AppImage: it's built on Linux" >&2 + fi + ;; +esac + +ls -la "$dist" diff --git a/build/release/main.go b/build/release/main.go new file mode 100644 index 00000000..1d399834 --- /dev/null +++ b/build/release/main.go @@ -0,0 +1,242 @@ +// Command release writes the feed of a release (app/update's Feed, rclone-ui-update.json), and +// checks the files that the release publishes. +// +// release manifest -version V -base-url URL [-policy FILE] [-rclone V] [-notes TEXT] [-out FILE] DIR +// Writes the feed for the files in DIR (named as package.sh names them). Every file must be +// there, because leaving one out would stop updates on that platform. The policy is FILE +// (build/release/policy.json), which is edited by hand. +// release check -version V DIR +// Checks that DIR holds exactly the files that a release of V publishes (Published). +package main + +import ( + "bytes" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/rclone/rclone-ui/app/update" +) + +// artifact is a file of a release that an update installs. +type artifact struct { + goos, goarch string + kind update.Kind +} + +// prefix starts the name of every file of a release, so that nothing that looks for another +// app's file names finds them. +func prefix(version string) string { return "Rclone-UI-" + version + "-" } + +// updateFiles returns the files of a release of version that an update installs, by the names +// that package.sh gives them. +func updateFiles(version string) map[string]artifact { + p := prefix(version) + return map[string]artifact{ + p + "macos-arm64.app.tar.gz": {"darwin", "arm64", update.KindApp}, + p + "macos-x64.app.tar.gz": {"darwin", "amd64", update.KindApp}, + p + "windows-x64-setup.exe": {"windows", "amd64", update.KindNSIS}, + p + "windows-arm64-setup.exe": {"windows", "arm64", update.KindNSIS}, + p + "linux-x86_64.AppImage": {"linux", "amd64", update.KindAppImage}, + p + "linux-aarch64.AppImage": {"linux", "arm64", update.KindAppImage}, + p + "linux-amd64.deb": {"linux", "amd64", update.KindDeb}, + p + "linux-arm64.deb": {"linux", "arm64", update.KindDeb}, + p + "linux-x86_64.rpm": {"linux", "amd64", update.KindRPM}, + p + "linux-aarch64.rpm": {"linux", "arm64", update.KindRPM}, + } +} + +// Published returns every file that a release of version publishes, sorted: the update files, the +// disk images, the Windows portable zips, the vendored sources and the Flathub manifest (the +// release workflow's vendor job), and the feed. The portable zips aren't update files, because a +// portable copy doesn't update itself. +func Published(version string) []string { + p := prefix(version) + names := []string{p + "macos-arm64.dmg", p + "macos-x64.dmg", + p + "windows-x64-portable.zip", p + "windows-arm64-portable.zip", + p + "vendor.tar.gz", "org.rclone.ui.yml", update.FeedName} + for name := range updateFiles(version) { + names = append(names, name) + } + slices.Sort(names) + return names +} + +func main() { + if len(os.Args) < 2 { + usage() + } + var err error + switch os.Args[1] { + case "manifest": + err = manifest(os.Args[2:]) + case "check": + err = check(os.Args[2:]) + default: + usage() + } + if err != nil { + fmt.Fprintln(os.Stderr, "release:", err) + os.Exit(1) + } +} + +func usage() { + fmt.Fprintln(os.Stderr, "usage: release manifest -version V -base-url URL DIR | check -version V DIR") + os.Exit(2) +} + +// versionFlag reads -version, without a leading v. +func versionFlag(v string) (string, error) { + v = strings.TrimPrefix(strings.TrimSpace(v), "v") + if v == "" { + return "", errors.New("-version is required") + } + if err := update.CheckVersion(v); err != nil { + return "", err + } + return v, nil +} + +func readPolicy(path string) (update.Policy, error) { + var p update.Policy + b, err := os.ReadFile(path) + if err != nil { + return p, err + } + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + if err := dec.Decode(&p); err != nil { + return p, fmt.Errorf("%s: %w", path, err) + } + for _, v := range []string{p.Minimum, p.Recommended} { + if v != "" { + if err := update.CheckVersion(v); err != nil { + return p, fmt.Errorf("%s: %w", path, err) + } + } + } + return p, nil +} + +func manifest(args []string) error { + fs := flag.NewFlagSet("manifest", flag.ContinueOnError) + versionArg := fs.String("version", "", "the release's version, without a v") + baseURL := fs.String("base-url", "", "where the files are downloaded from (the release's download URL)") + policyFile := fs.String("policy", filepath.Join("build", "release", "policy.json"), "the policy file") + rclone := fs.String("rclone", "", "the rclone version the release brings") + notes := fs.String("notes", "", "the release notes") + out := fs.String("out", "", "where to write the feed (default DIR/"+update.FeedName+")") + if err := fs.Parse(args); err != nil { + return err + } + version, err := versionFlag(*versionArg) + if err != nil { + return fmt.Errorf("manifest: %w", err) + } + if *baseURL == "" || fs.NArg() != 1 { + return errors.New("manifest: -base-url and DIR are required") + } + dir := fs.Arg(0) + policy, err := readPolicy(*policyFile) + if err != nil { + return err + } + f := update.Feed{ + Format: update.FeedFormat, + Release: update.FeedRelease{Version: version, Date: time.Now().UTC().Format(time.RFC3339), Notes: *notes}, + Files: map[string]update.FeedFile{}, + Rclone: *rclone, + Policy: policy, + } + files := updateFiles(version) + names := make([]string, 0, len(files)) + for name := range files { + names = append(names, name) + } + slices.Sort(names) + // Write a feed only when every file is there. A feed without one platform's file would stop + // updates on that platform, and the next release step would publish it. + var missing []string + for _, name := range names { + _, err := os.Stat(filepath.Join(dir, name)) + if errors.Is(err, os.ErrNotExist) { + missing = append(missing, name) + continue + } + if err != nil { + return err + } + } + if len(missing) > 0 { + return fmt.Errorf("missing %s: every file that an update installs is released (build/package.sh names them); one left out stops that platform's updates", + strings.Join(missing, ", ")) + } + for _, name := range names { + a := files[name] + f.Files[update.FileKey(a.goos, a.goarch, a.kind)] = update.FeedFile{URL: strings.TrimSuffix(*baseURL, "/") + "/" + name} + } + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetIndent("", " ") + if err := enc.Encode(f); err != nil { + return err + } + if *out == "" { + *out = filepath.Join(dir, update.FeedName) + } + if err := os.WriteFile(*out, b.Bytes(), 0o644); err != nil { + return err + } + fmt.Printf("wrote %s (%d files)\n", *out, len(f.Files)) + return nil +} + +// check fails unless DIR holds exactly Published(version): nothing missing, and nothing else. +func check(args []string) error { + fs := flag.NewFlagSet("check", flag.ContinueOnError) + versionArg := fs.String("version", "", "the release's version, without a v") + if err := fs.Parse(args); err != nil { + return err + } + version, err := versionFlag(*versionArg) + if err != nil { + return fmt.Errorf("check: %w", err) + } + if fs.NArg() != 1 { + return errors.New("check: DIR is required") + } + entries, err := os.ReadDir(fs.Arg(0)) + if err != nil { + return err + } + var have []string + for _, e := range entries { + have = append(have, e.Name()) + } + want := Published(version) + var missing, extra []string + for _, n := range want { + if !slices.Contains(have, n) { + missing = append(missing, n) + } + } + for _, n := range have { + if !slices.Contains(want, n) { + extra = append(extra, n) + } + } + if len(missing) > 0 || len(extra) > 0 { + return fmt.Errorf("the release's files differ from what it publishes: missing %v, not published %v", missing, extra) + } + for _, n := range have { + fmt.Println(n) + } + return nil +} diff --git a/build/release/main_test.go b/build/release/main_test.go new file mode 100644 index 00000000..439b3a56 --- /dev/null +++ b/build/release/main_test.go @@ -0,0 +1,191 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/rclone/rclone-ui/app/update" +) + +func writeFiles(t *testing.T, dir string, names []string) []string { + t.Helper() + paths := make([]string, 0, len(names)) + for i, n := range names { + p := filepath.Join(dir, n) + if err := os.WriteFile(p, []byte(strings.Repeat(n, 1000+i)), 0o644); err != nil { + t.Fatal(err) + } + paths = append(paths, p) + } + return paths +} + +func updateNames(version string) []string { + var names []string + for n := range updateFiles(version) { + names = append(names, n) + } + slices.Sort(names) + return names +} + +func policyFile(t *testing.T, text string) string { + t.Helper() + p := filepath.Join(t.TempDir(), "policy.json") + if err := os.WriteFile(p, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + return p +} + +func TestManifest(t *testing.T) { + dir := t.TempDir() + if paths := writeFiles(t, dir, updateNames("4.0.0")); len(paths) != 10 { + t.Fatalf("%d files in the table, want 10", len(paths)) + } + + policy := policyFile(t, `{"minimum": "4.0.0", "recommended": "4.0.1"}`) + if err := manifest([]string{"-version", "v4.0.0", "-base-url", "https://example.com/v4.0.0/", "-policy", policy, "-rclone", "v1.75.1", dir}); err != nil { + t.Fatal(err) + } + raw := []byte(mustRead(t, filepath.Join(dir, update.FeedName))) + var f update.Feed + if err := json.Unmarshal(raw, &f); err != nil { + t.Fatal(err) + } + if f.Format != update.FeedFormat || f.Release.Version != "4.0.0" || f.Release.Date == "" || f.Rclone != "v1.75.1" || + f.Policy != (update.Policy{Minimum: "4.0.0", Recommended: "4.0.1"}) { + t.Fatalf("feed %+v", f) + } + if len(f.Files) != 10 { + t.Fatalf("%d files in the feed, want 10: %v", len(f.Files), f.Files) + } + for name, a := range updateFiles("4.0.0") { + p, ok := f.Files[update.FileKey(a.goos, a.goarch, a.kind)] + if !ok || p.URL != "https://example.com/v4.0.0/"+name { + t.Fatalf("%s: %+v", name, p) + } + } + if tauriUpdaterReads(t, raw) { + t.Error("the Tauri updater would read the feed") + } +} + +// tauriUpdaterReads reports whether the Tauri app's updater could take b for a release. Its +// tauri-plugin-updater (2.9.0 in v1.3.0 to v3.5.4, 2.10.1 in v3.7.5) reads a release with +// RemoteRelease's Deserialize (src/updater.rs): it needs a top-level "version" (or "name"), and +// either "platforms", or "url" and "signature". +func tauriUpdaterReads(t *testing.T, b []byte) bool { + t.Helper() + var top map[string]json.RawMessage + if err := json.Unmarshal(b, &top); err != nil { + t.Fatal(err) + } + has := func(k string) bool { _, ok := top[k]; return ok } + if !has("version") && !has("name") { + return false + } + return has("platforms") || has("url") && has("signature") +} + +// TestTauriUpdaterRule checks that tauriUpdaterReads accepts a feed in the Tauri app's own format. +// Without that, its check in TestManifest could never fail. +func TestTauriUpdaterRule(t *testing.T) { + for _, c := range []struct { + feed string + reads bool + }{ + {`{"version":"3.7.5","platforms":{"darwin-aarch64":{"url":"u","signature":"s"}}}`, true}, + {`{"name":"v3.7.5","url":"u","signature":"s"}`, true}, + {`{"version":"3.7.5"}`, false}, + {`{"format":1,"release":{"version":"4.0.0"},"files":{}}`, false}, + } { + if got := tauriUpdaterReads(t, []byte(c.feed)); got != c.reads { + t.Errorf("%s: %v, want %v", c.feed, got, c.reads) + } + } +} + +func TestManifestRefusesAMissingFile(t *testing.T) { + dir := t.TempDir() + names := updateNames("4.0.0") + left := names[len(names)-1] + writeFiles(t, dir, names[:len(names)-1]) + err := manifest([]string{"-version", "4.0.0", "-base-url", "https://example.com/v4.0.0", "-policy", policyFile(t, `{}`), dir}) + if err == nil || !strings.Contains(err.Error(), "missing "+left+":") { + t.Fatalf("manifest: %v, want it to name %s", err, left) + } + if _, err := os.Stat(filepath.Join(dir, update.FeedName)); !os.IsNotExist(err) { + t.Fatalf("the feed was written: %v", err) + } +} + +func TestPolicy(t *testing.T) { + if _, err := readPolicy("policy.json"); err != nil { + t.Errorf("the repository's policy: %v", err) + } + for _, text := range []string{`{"minimumVersion": "4.0.0"}`, `{"minimum": "four"}`, `nope`} { + if _, err := readPolicy(policyFile(t, text)); err == nil { + t.Errorf("%s was accepted", text) + } + } +} + +// TestPublished checks the names of the files that a release publishes. There must be no +// latest.json and no file under the Tauri app's names (Rclone.UI_*), because other updaters and +// package managers look for those. +func TestPublished(t *testing.T) { + names := Published("4.0.0-beta.1") + if len(names) != 17 { + t.Errorf("%d files: %v", len(names), names) + } + // The portable zips are published, but no update installs them. + updates := updateFiles("4.0.0-beta.1") + for _, zip := range []string{"Rclone-UI-4.0.0-beta.1-windows-x64-portable.zip", "Rclone-UI-4.0.0-beta.1-windows-arm64-portable.zip"} { + if !slices.Contains(names, zip) { + t.Errorf("%s isn't published", zip) + } + if _, ok := updates[zip]; ok { + t.Errorf("%s is an update file", zip) + } + } + for _, n := range names { + if n == "latest.json" || strings.HasPrefix(n, "Rclone.UI_") { + t.Errorf("%s is published", n) + } + if !strings.HasPrefix(n, "Rclone-UI-4.0.0-beta.1-") && n != update.FeedName && n != "org.rclone.ui.yml" { + t.Errorf("%s doesn't name its release", n) + } + } + dir := t.TempDir() + writeFiles(t, dir, names) + if err := check([]string{"-version", "4.0.0-beta.1", dir}); err != nil { + t.Fatal(err) + } + writeFiles(t, dir, []string{"latest.json"}) + if err := check([]string{"-version", "4.0.0-beta.1", dir}); err == nil || !strings.Contains(err.Error(), "latest.json") { + t.Errorf("an extra latest.json: %v", err) + } + if err := os.Remove(filepath.Join(dir, "latest.json")); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(dir, names[0])); err != nil { + t.Fatal(err) + } + if err := check([]string{"-version", "4.0.0-beta.1", dir}); err == nil || !strings.Contains(err.Error(), names[0]) { + t.Errorf("a missing %s: %v", names[0], err) + } +} + +func mustRead(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} diff --git a/build/release/policy.json b/build/release/policy.json new file mode 100644 index 00000000..e9fe7ac2 --- /dev/null +++ b/build/release/policy.json @@ -0,0 +1,4 @@ +{ + "minimum": "", + "recommended": "4.0.0" +} diff --git a/src-tauri/icons/icon.ico b/build/windows/icon.ico similarity index 100% rename from src-tauri/icons/icon.ico rename to build/windows/icon.ico diff --git a/build/windows/info.json b/build/windows/info.json new file mode 100644 index 00000000..65bf488d --- /dev/null +++ b/build/windows/info.json @@ -0,0 +1,16 @@ +{ + "fixed": { + "file_version": "@FILEVERSION@" + }, + "info": { + "0409": { + "ProductVersion": "@VERSION@", + "FileVersion": "@VERSION@", + "CompanyName": "Rclone", + "FileDescription": "Rclone UI", + "LegalCopyright": "© Rclone", + "ProductName": "Rclone UI", + "OriginalFilename": "rcui.exe" + } + } +} diff --git a/build/windows/nsis/project.nsi b/build/windows/nsis/project.nsi new file mode 100644 index 00000000..95c387e4 --- /dev/null +++ b/build/windows/nsis/project.nsi @@ -0,0 +1,489 @@ +; The Windows installer of Rclone UI. It installs per user (in %LOCALAPPDATA%\Programs) or per +; machine (in Program Files), and an upgrade keeps the mode and folder of the existing install. +; +; Built by build/package.sh: +; makensis -DVERSION=4.0.0 -DFILEVERSION=4.0.0.0 -DARCH=x64|arm64 +; -DBINDIR= -DOUTFILE=<…> +; -DWEBVIEW2BOOTSTRAPPER= -DWINFSPMSI= +; [-DSIGNCOMMAND=] project.nsi +; +; Switches (the updater passes /P /UPDATE /WAITPID= [/R]; WinGet /S): +; /S silent /P passive: a progress window, no questions +; /UPDATE no new shortcuts /NS no shortcuts at all +; /WAITPID=n wait for process n (the app that started the update) to exit first +; /R start the app when done (passive or silent) +; /NOWINFSP don't install WinFsp (see the WinFsp section) +; +; It exits with code 10 when a running copy keeps the files and the user (or /S) gives up. WinGet +; reads that code as packageInUse, so a silent upgrade says to close the app, and not that the +; install failed. + +Unicode true +ManifestDPIAware true +SetCompressor /SOLID lzma + +; CI builds with NSIS's strlen_8192 build (build.yml). A standard build still works, but its +; uninstaller leaves $INSTDIR\bin on a PATH longer than 1024 characters (see "Add rclone to PATH"). +!if ${NSIS_MAX_STRLEN} < 8192 + !warning "NSIS_MAX_STRLEN is ${NSIS_MAX_STRLEN}: use NSIS's strlen_8192 build for releases" +!endif + +!define PRODUCTNAME "Rclone UI" +!define MANUFACTURER "Rclone" +!define BUNDLEID "org.rclone.ui" +!define HOMEPAGE "https://github.com/rclone/rclone-ui" +!define MAINBINARY "rcui.exe" +; The Start menu's folder for the app's shortcut, named after the publisher. +!define STARTMENUDIR "$SMPROGRAMS\${MANUFACTURER}" +; The app's entry in Apps & features, and the key that keeps the install folder. +!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${BUNDLEID}" +!define MANUKEY "Software\${MANUFACTURER}" +!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}" +!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" +; go-toast's notification activator class (GUID_ImplNotificationActivationCallback). +!define GOTOASTACTIVATOR "{0F82E845-CB89-4039-BDBF-67CA33254C76}" + +!ifndef VERSION + !error "-DVERSION= is required" +!endif +!ifndef FILEVERSION + !error "-DFILEVERSION= is required" +!endif +!ifndef ARCH + !error "-DARCH=x64|arm64 is required" +!endif +!ifndef BINDIR + !error "-DBINDIR= is required" +!endif +!ifndef OUTFILE + !error "-DOUTFILE= is required" +!endif +!ifndef WEBVIEW2BOOTSTRAPPER + !error "-DWEBVIEW2BOOTSTRAPPER= is required" +!endif +!ifndef WINFSPMSI + !error "-DWINFSPMSI= is required" +!endif + +; "= 0": a signing command that fails fails the build, rather than leave the installer or its +; uninstaller unsigned. +!ifdef SIGNCOMMAND + !finalize '${SIGNCOMMAND}' = 0 + !uninstfinalize '${SIGNCOMMAND}' = 0 +!endif + +Name "${PRODUCTNAME}" +OutFile "${OUTFILE}" +BrandingText "${PRODUCTNAME} ${VERSION}" +; Placeholder: MultiUser picks the folder (and RestorePreviousInstallLocation an existing one). +InstallDir "$LOCALAPPDATA\Programs\${MANUFACTURER}\${PRODUCTNAME}" + +; These two need four numbers, which a pre-release's VERSION (4.0.0-beta.1) isn't. The text keys +; below keep the full VERSION. +VIProductVersion "${FILEVERSION}" +VIFileVersion "${FILEVERSION}" +VIAddVersionKey "CompanyName" "${MANUFACTURER}" +VIAddVersionKey "FileDescription" "${PRODUCTNAME} Installer" +VIAddVersionKey "ProductName" "${PRODUCTNAME}" +VIAddVersionKey "ProductVersion" "${VERSION}" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "LegalCopyright" "© ${MANUFACTURER}" + +; Per user or per machine: the mode of an existing install by default. +!define MULTIUSER_MUI +!define MULTIUSER_EXECUTIONLEVEL Highest +!define MULTIUSER_INSTALLMODE_INSTDIR "${MANUFACTURER}\${PRODUCTNAME}" +!define MULTIUSER_INSTALLMODE_COMMANDLINE +!define MULTIUSER_USE_PROGRAMFILES64 +!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}" +!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser" +!define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation +!define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME +!include MultiUser.nsh +!include MUI2.nsh +!include FileFunc.nsh +!include LogicLib.nsh +!include WordFunc.nsh +!include x64.nsh +!include WinMessages.nsh + +; Selects the registry's 64-bit view, which the app reads (app/update). The installer is a 32-bit +; program, so without this a per-machine install's keys are read and written under WOW6432Node, +; where the app doesn't look. It must run before MultiUser reads the keys. +!macro REGVIEW_64 + ${If} ${RunningX64} + ${OrIf} ${IsNativeARM64} + SetRegView 64 + ${EndIf} +!macroend + +Var PassiveMode +Var UpdateMode +Var NoShortcutMode + +!define MUI_ICON "..\icon.ico" +!define MUI_UNICON "..\icon.ico" +!define MUI_ABORTWARNING +!define MUI_FINISHPAGE_RUN +!define MUI_FINISHPAGE_RUN_FUNCTION RunApp +; WinFsp's license asks for its notice and a link wherever it is used, and the installer adds it. +!define MUI_WELCOMEPAGE_TEXT "Setup will install ${PRODUCTNAME} on this computer.$\r$\n$\r$\n${PRODUCTNAME} mounts remotes as drives with WinFsp - Windows File System Proxy, Copyright (C) Bill Zissimopoulos (https://github.com/winfsp/winfsp). Setup also installs WinFsp when this computer doesn't have it and you are an administrator.$\r$\n$\r$\n$_CLICK" + +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_WELCOME +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MULTIUSER_PAGE_INSTALLMODE +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_FINISH + +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES + +!insertmacro MUI_LANGUAGE "English" + +Function SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd + +; RestorePreviousInstallLocation keeps an existing install's folder (the default value of the +; product key). +Function RestorePreviousInstallLocation + ReadRegStr $0 SHCTX "${MANUPRODUCTKEY}" "" + ${If} $0 != "" + StrCpy $INSTDIR $0 + ${EndIf} +FunctionEnd + +Function .onInit + ; An update of a per-user install starts this installer with __COMPAT_LAYER=RunAsInvoker + ; (app/update), so that it runs without a UAC prompt. The programs that it starts, such as the + ; app when it's done, must not inherit that. + System::Call 'kernel32::SetEnvironmentVariable(t "__COMPAT_LAYER", p 0)' + ${GetParameters} $R9 + StrCpy $PassiveMode 0 + ${GetOptions} $R9 "/P" $R0 + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + StrCpy $UpdateMode 0 + ${GetOptions} $R9 "/UPDATE" $R0 + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} + StrCpy $NoShortcutMode 0 + ${GetOptions} $R9 "/NS" $R0 + ${IfNot} ${Errors} + StrCpy $NoShortcutMode 1 + ${EndIf} + + !if "${ARCH}" == "arm64" + ${IfNot} ${IsNativeARM64} + MessageBox MB_ICONSTOP "This installer is for Windows on Arm. Download the x64 installer instead." /SD IDOK + Quit + ${EndIf} + !endif + + !insertmacro REGVIEW_64 + !insertmacro MULTIUSER_INIT + + ; Wait for the app that started the update to exit, before its files are replaced. + ${GetOptions} $R9 "/WAITPID=" $R0 + ${IfNot} ${Errors} + System::Call 'kernel32::OpenProcess(i 0x00100000, i 0, i $R0) p .r1' + ${If} $1 P<> 0 + System::Call 'kernel32::WaitForSingleObject(p r1, i 60000) i .r2' + System::Call 'kernel32::CloseHandle(p r1)' + ${EndIf} + ${EndIf} +FunctionEnd + +!define EXIT_IN_USE 10 ; WinGet's packageInUse (ExpectedReturnCodes in its manifest) + +; WaitUnlocked waits for a running copy to let go of $0 (a file of the install folder), asking +; the user to quit it when it doesn't within a few seconds. Giving up exits with EXIT_IN_USE. +; Defined twice, as the installer's and the uninstaller's (whose functions are named un.*). +!macro WAIT_UNLOCKED UN +Function ${UN}WaitUnlocked + IfFileExists "$0" 0 done + StrCpy $1 0 + retry: + ClearErrors + FileOpen $2 "$0" a + ${IfNot} ${Errors} + FileClose $2 + Goto done + ${EndIf} + IntOp $1 $1 + 1 + ${If} $1 < 20 + Sleep 500 + Goto retry + ${EndIf} + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "${PRODUCTNAME} is running. Quit it from its tray icon, then press Retry." /SD IDCANCEL IDRETRY again + SetErrorLevel ${EXIT_IN_USE} + Abort + again: + StrCpy $1 0 + Goto retry + done: +FunctionEnd +!macroend +!insertmacro WAIT_UNLOCKED "" +!insertmacro WAIT_UNLOCKED "un." + +Section WebView2 + ; WebView2 is on every supported Windows 11 and most Windows 10; the bootstrapper installs it + ; where it isn't. + ReadRegStr $0 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${If} $0 == "" + ReadRegStr $0 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ${If} $0 == "" + ReadRegStr $0 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ${If} $0 == "" + ${OrIf} $0 == "0.0.0.0" + DetailPrint "Installing WebView2..." + SetOutPath "$PLUGINSDIR" + File "/oname=MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPER}" + ExecWait '"$PLUGINSDIR\MicrosoftEdgeWebview2Setup.exe" /silent /install' $1 + ${If} $1 != 0 + MessageBox MB_ICONEXCLAMATION "WebView2 could not be installed (code $1). ${PRODUCTNAME} needs it to show its windows." /SD IDOK + ${EndIf} + ${EndIf} +SectionEnd + +Section Install + SetOutPath $INSTDIR + + StrCpy $0 "$INSTDIR\${MAINBINARY}" + Call WaitUnlocked + + File "${BINDIR}\${MAINBINARY}" + SetOutPath "$INSTDIR\bin" + File "${BINDIR}\bin\rclone.exe" + SetOutPath $INSTDIR + ; The WinFsp section installs WinFsp from this file. When it doesn't, the Mount page offers to + ; (core/mounts' WinFspInstaller). + File "/oname=winfsp.msi" "${WINFSPMSI}" + File "/oname=LICENSE.txt" "..\..\..\LICENSE" + File "..\..\..\public\THIRD_PARTY_NOTICES.txt" + + ; rclone:// links (the app also registers them for the user at start). + WriteRegStr SHCTX "Software\Classes\rclone" "" "URL:${BUNDLEID} protocol" + WriteRegStr SHCTX "Software\Classes\rclone" "URL Protocol" "" + WriteRegStr SHCTX "Software\Classes\rclone\DefaultIcon" "" '"$INSTDIR\${MAINBINARY}",0' + WriteRegStr SHCTX "Software\Classes\rclone\shell\open\command" "" '"$INSTDIR\${MAINBINARY}" "%1"' + + WriteUninstaller "$INSTDIR\uninstall.exe" + WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR + WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1 + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" '"$INSTDIR\${MAINBINARY}"' + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}" + WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}" + WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" '"$INSTDIR"' + WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" '"$INSTDIR\uninstall.exe"' + WriteRegStr SHCTX "${UNINSTKEY}" "QuietUninstallString" '"$INSTDIR\uninstall.exe" /S' + WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" 1 + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" 1 + ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2 + IntFmt $0 "0x%08X" $0 + WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0" + + ; Shortcuts, made on a first install only. The Start menu's is in the publisher's folder, which + ; is the app's own. Another program's shortcut is never replaced: a desktop shortcut with the + ; same name stays as it is. + ${If} $UpdateMode = 0 + ${AndIf} $NoShortcutMode = 0 + CreateDirectory "${STARTMENUDIR}" + CreateShortcut "${STARTMENUDIR}\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARY}" + ${IfNot} ${FileExists} "$DESKTOP\${PRODUCTNAME}.lnk" + CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARY}" + ${EndIf} + ${EndIf} + + ${If} $PassiveMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +; WinFsp mounts remotes as drives. When this computer doesn't have it, this section installs it +; from the copy in the install folder, with no questions: the welcome page says so. It is skipped +; on an update and with /NOWINFSP. WinFsp installs a driver, which needs administrator rights, so +; the section is also skipped when the installer doesn't run as an administrator. It asks for +; those rights where the user has them (MULTIUSER_EXECUTIONLEVEL Highest). When WinFsp isn't +; installed here, the Mount page offers to install it from the same copy, and Windows asks for an +; administrator then. The uninstaller leaves WinFsp, which other programs may use. +Section WinFsp + ${If} $UpdateMode = 1 + Return + ${EndIf} + ${GetParameters} $R9 + ${GetOptions} $R9 "/NOWINFSP" $R0 + ${IfNot} ${Errors} + Return + ${EndIf} + ; WinFsp's key is in the registry's 32-bit view, which the 64-bit view (REGVIEW_64) reaches + ; through WOW6432Node. + ReadRegStr $0 HKLM "SOFTWARE\WOW6432Node\WinFsp" "InstallDir" + ${If} $0 != "" + Return + ${EndIf} + System::Call 'shell32::IsUserAnAdmin() i .r0' + ${If} $0 = 0 + Return + ${EndIf} + DetailPrint "Installing WinFsp..." + ClearErrors + ExecWait '"$SYSDIR\msiexec.exe" /i "$INSTDIR\winfsp.msi" /qn /norestart' $1 + ${If} ${Errors} ; msiexec didn't start + DetailPrint "WinFsp could not be installed. The Mount page offers to install it." + ${ElseIf} $1 <> 0 + ${AndIf} $1 <> 3010 ; installed, and Windows wants a restart + DetailPrint "WinFsp could not be installed (code $1). The Mount page offers to install it." + ${EndIf} +SectionEnd + +; RunApp starts the app as the user who installed it, without administrator rights. When this +; installer runs elevated, it starts the app through Explorer, which runs as the user. That is the +; case for a per-machine install, and also for a per-user install by an administrator, because the +; installer asks for the highest rights the user has (MULTIUSER_EXECUTIONLEVEL Highest). +Function RunApp + System::Call 'shell32::IsUserAnAdmin() i .r0' + ${If} $0 <> 0 + Exec '"$WINDIR\explorer.exe" "$INSTDIR\${MAINBINARY}"' + ${Else} + Exec '"$INSTDIR\${MAINBINARY}"' + ${EndIf} +FunctionEnd + +Function .onInstSuccess + ; The finish page offers it in a normal install; /R asks for it in a passive or silent one. + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + ${GetParameters} $R9 + ${GetOptions} $R9 "/R" $R0 + ${IfNot} ${Errors} + Call RunApp + ${EndIf} + ${EndIf} +FunctionEnd + +Function un.onInit + !insertmacro REGVIEW_64 + !insertmacro MULTIUSER_UNINIT +FunctionEnd + +; un.DeleteOwnShortcut deletes the shortcut $0 when it opens this install's executable, and leaves +; another program's shortcut of the same name alone. It reads the shortcut's target through +; Windows' IShellLink: CoCreateInstance, IPersistFile::Load, then IShellLinkW::GetPath. +!define CLSID_ShellLink "{00021401-0000-0000-C000-000000000046}" +!define IID_IShellLinkW "{000214F9-0000-0000-C000-000000000046}" +!define IID_IPersistFile "{0000010B-0000-0000-C000-000000000046}" +Function un.DeleteOwnShortcut + IfFileExists "$0" 0 done + StrCpy $3 "" + System::Call 'ole32::CoInitialize(p 0)' + System::Call 'ole32::CoCreateInstance(g "${CLSID_ShellLink}", p 0, i 1, g "${IID_IShellLinkW}", *p .r1) i .r2' + ${If} $2 = 0 + System::Call '$1->0(g "${IID_IPersistFile}", *p .r4) i .r2' ; QueryInterface + ${If} $2 = 0 + System::Call '$4->5(w r0, i 0) i .r2' ; IPersistFile::Load + ${If} $2 = 0 + System::Call '$1->3(w .r3, i ${NSIS_MAX_STRLEN}, p 0, i 0) i .r2' ; IShellLinkW::GetPath + ${EndIf} + System::Call '$4->2()' ; Release + ${EndIf} + System::Call '$1->2()' ; Release + ${EndIf} + ${If} $3 == "$INSTDIR\${MAINBINARY}" + Delete "$0" + ${EndIf} + done: +FunctionEnd + +Section Uninstall + StrCpy $0 "$INSTDIR\${MAINBINARY}" + Call un.WaitUnlocked + + StrCpy $0 "${STARTMENUDIR}\${PRODUCTNAME}.lnk" + Call un.DeleteOwnShortcut + RMDir "${STARTMENUDIR}" + StrCpy $0 "$DESKTOP\${PRODUCTNAME}.lnk" + Call un.DeleteOwnShortcut + + Delete "$INSTDIR\${MAINBINARY}" + Delete "$INSTDIR\bin\rclone.exe" + RMDir "$INSTDIR\bin" + Delete "$INSTDIR\winfsp.msi" + Delete "$INSTDIR\LICENSE.txt" + Delete "$INSTDIR\THIRD_PARTY_NOTICES.txt" + Delete "$INSTDIR\uninstall.exe" + RMDir "$INSTDIR" + ; The publisher's folder that holds the install folder, when nothing else is in it. A folder + ; that the user chose has another name and stays. + ${GetParent} "$INSTDIR" $1 + ${GetFileName} "$1" $2 + ${If} $2 == "${MANUFACTURER}" + RMDir "$1" + ${EndIf} + + ; Remove the notifications' registration, which the app writes for the user at every start + ; (Wails' notification service and go-toast), but only when it opens this install. Another copy + ; of the app writes its own again when it starts. go-toast's activator class is shared by every + ; program that uses go-toast, so it is also removed only when it opens this install. + ReadRegStr $1 HKCU "Software\Classes\AppUserModelId\${PRODUCTNAME}" "CustomActivator" + ${If} $1 != "" + ReadRegStr $2 HKCU "Software\Classes\CLSID\$1\LocalServer32" "" + ${If} $2 == '"$INSTDIR\${MAINBINARY}" %1' + DeleteRegKey HKCU "Software\Classes\CLSID\$1" + DeleteRegKey HKCU "Software\Classes\AppUserModelId\${PRODUCTNAME}" + ${EndIf} + ${EndIf} + ReadRegStr $2 HKCU "Software\Classes\CLSID\${GOTOASTACTIVATOR}\LocalServer32" "" + ${If} $2 == "$INSTDIR\${MAINBINARY}" + DeleteRegKey HKCU "Software\Classes\CLSID\${GOTOASTACTIVATOR}" + ${EndIf} + + ; rclone:// when it's this install's. + ReadRegStr $1 SHCTX "Software\Classes\rclone\shell\open\command" "" + ${If} $1 == '"$INSTDIR\${MAINBINARY}" "%1"' + DeleteRegKey SHCTX "Software\Classes\rclone" + ${EndIf} + ; The per-user one the app writes at every start (deeplink.Register), which a per-machine + ; uninstall would leave pointing at nothing. + ReadRegStr $1 HKCU "Software\Classes\rclone\shell\open\command" "" + ${If} $1 == '"$INSTDIR\${MAINBINARY}" "%1"' + DeleteRegKey HKCU "Software\Classes\rclone" + ${EndIf} + + ; "Add rclone to PATH" put $INSTDIR\bin on the user's PATH. ReadRegStr reads a PATH longer than + ; NSIS_MAX_STRLEN as empty. CI makes the installer with NSIS's strlen_8192 build (build.yml), so + ; that limit is 8192 characters, not the standard build's 1024. A longer PATH is left as it is, + ; with $INSTDIR\bin in it, rather than written back cut short. + ReadRegStr $1 HKCU "Environment" "Path" + ${If} $1 != "" + StrCpy $2 $1 + ${WordReplace} "$2" ";$INSTDIR\bin" "" "+" $2 + ${WordReplace} "$2" "$INSTDIR\bin;" "" "+" $2 + ${If} $2 == "$INSTDIR\bin" + StrCpy $2 "" + ${EndIf} + ${If} $2 != $1 + WriteRegExpandStr HKCU "Environment" "Path" $2 + SendMessage ${HWND_BROADCAST} ${WM_SETTINGCHANGE} 0 "STR:Environment" /TIMEOUT=5000 + ${EndIf} + ${EndIf} + + ; Starting at login (app/autostart). + DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${BUNDLEID}" + + DeleteRegKey SHCTX "${UNINSTKEY}" + DeleteRegKey SHCTX "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty SHCTX "${MANUKEY}" +SectionEnd diff --git a/build/windows/portable/README.txt b/build/windows/portable/README.txt new file mode 100644 index 00000000..1e65611d --- /dev/null +++ b/build/windows/portable/README.txt @@ -0,0 +1,77 @@ +Rclone UI, portable +=================== + +This copy of Rclone UI keeps everything in this folder, so you can move it, +carry it on a USB drive, or keep several copies side by side: + + data The app's data: its settings, history, logs and cache. + rclone.conf rclone's config, with your remotes. Rclone UI creates it, + empty, the first time it starts. + bin rclone.exe, the rclone command. It uses the same rclone.conf. + winfsp.msi The WinFsp installer, which the Mount page uses to install + WinFsp when you ask it to. Mounts need WinFsp. + +The data folder is what makes this copy portable. Keep it, even when it's +empty. + + +Updating +-------- + +This copy checks for updates and tells you about them, but it doesn't +install them. To update it, download the new release's portable zip from +https://github.com/rclone/rclone-ui/releases, and replace rcui.exe, +winfsp.msi and the bin folder with the ones in it. The data folder and +rclone.conf stay as they are. + + +Making it a normal copy +----------------------- + +Delete the data folder (or move it away). Rclone UI then keeps its data in +%LOCALAPPDATA%\org.rclone.ui, as an installed copy does. rclone still uses +an rclone.conf that is next to rcui.exe, so move that away too if you want +rclone's usual config file. + + +What stays on this computer +--------------------------- + +- rclone:// links: Rclone UI registers itself to open them for your user + account. When a computer has several copies, the one that started last + opens them. +- Notifications: Windows keeps a registration for Rclone UI's + notifications. When a computer has several copies, clicking a + notification opens the one that started last. +- Passwords that you save, in Windows' Credential Manager: the password of + this folder's rclone.conf, saved under its path, and the mail server's + password for email notifications, which every copy of Rclone UI on this + computer shares. +- An empty %APPDATA%\rclone folder, which rclone makes the first time this + copy starts, unless it is there already. rclone makes it before it finds + this folder's rclone.conf, which doesn't exist yet at that point. +- WinFsp, when you let Rclone UI install it (see below). +- Start at login, only when you turn it on in Settings. +- The bin folder on your PATH, only when you turn on "Add rclone to PATH" in + Settings. + +Turn off the last two in Settings before you delete this folder. + + +WinFsp +------ + +Rclone UI mounts remotes as drives with WinFsp - Windows File System Proxy, +Copyright (C) Bill Zissimopoulos (https://github.com/winfsp/winfsp). When +this computer doesn't have it, the Mount page offers to install it. WinFsp +installs for the whole computer, so Windows asks for administrator rights. +It stays installed when you delete this folder: uninstall it from Windows' +Settings, under Apps, if no other program needs it. + + +WebView2 +-------- + +Rclone UI draws its windows with Microsoft Edge WebView2, which Windows 11 +and most of Windows 10 already have. If it's missing, Rclone UI says so and +links to Microsoft's download. diff --git a/build/windows/rclone-shim/main.go b/build/windows/rclone-shim/main.go new file mode 100644 index 00000000..5c680a79 --- /dev/null +++ b/build/windows/rclone-shim/main.go @@ -0,0 +1,48 @@ +// Command rclone is the rclone.exe in the bin folder next to rcui.exe, where the Windows installer +// and the portable zip put it. The "Add rclone to PATH" option adds that folder to the user's PATH +// (see app/pathlink). +// +// rcui.exe is a GUI program, so when it runs from a terminal the prompt comes back at once. This +// console program runs ..\rcui.exe with argv[0] set to "rclone" and the terminal's handles, waits +// for it, and exits with its exit code. As a result, `rclone …` in a terminal behaves like the +// real rclone. +package main + +import ( + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" +) + +func main() { + os.Exit(run()) +} + +func run() int { + self, err := os.Executable() + if err != nil { + fmt.Fprintln(os.Stderr, "rclone:", err) + return 1 + } + rcui := filepath.Join(filepath.Dir(filepath.Dir(self)), "rcui.exe") + cmd := exec.Command(rcui, os.Args[1:]...) + // rcui acts as rclone when argv[0] is "rclone" (see the dispatch in main.go). + cmd.Args[0] = "rclone" + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + // Ctrl+C reaches every process on the console. rcui handles it the way rclone does, and this + // process ignores it so that it waits for rcui instead of leaving it behind. + signal.Ignore(os.Interrupt) + err = cmd.Run() + var exit *exec.ExitError + switch { + case err == nil: + return 0 + case errors.As(err, &exit): + return exit.ExitCode() + } + fmt.Fprintf(os.Stderr, "rclone: could not run %s: %v\n", rcui, err) + return 1 +} diff --git a/build/windows/rcui.exe.manifest b/build/windows/rcui.exe.manifest new file mode 100644 index 00000000..3316d6bc --- /dev/null +++ b/build/windows/rcui.exe.manifest @@ -0,0 +1,22 @@ + + + + + + + + + + + true/pm + permonitorv2,permonitor + + + + + + + + + + \ No newline at end of file diff --git a/cli/README.md b/cli/README.md deleted file mode 100644 index 9eb22efe..00000000 --- a/cli/README.md +++ /dev/null @@ -1,42 +0,0 @@ -

- - Rclone UI - -
- - The cross-platform GUI for Rclone - -

- -Tnstalls and launches [**Rclone UI**](https://rcloneui.com). - -## Usage - -```bash -npx rclone-ui -``` - -That's it! - -If Rclone UI is already installed, it opens the app. If not, it downloads the latest release from GitHub and installs it. - -## Options - -```bash -npx rclone-ui # Open Rclone UI (installs if not found) -npx rclone-ui --install # Reinstall (or update) -npx rclone-ui --version # Show version -npx rclone-ui --help # Show help -``` - -## How it works - -- **macOS**: Mounts the `.dmg` and copies the app to `/Applications` -- **Windows**: Runs the NSIS installer in silent mode -- **Linux**: Installs the AppImage to `~/.local/bin` - -## Links - -- [Website](https://rcloneui.com) -- [GitHub](https://github.com/rclone-ui/rclone-ui) -- [Releases](https://github.com/rclone-ui/rclone-ui/releases) diff --git a/cli/bin/rclone-ui.js b/cli/bin/rclone-ui.js deleted file mode 100644 index f06d536d..00000000 --- a/cli/bin/rclone-ui.js +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env node - -import readline from 'node:readline' -import { isInstalled } from '../lib/detect.js' -import { download, install } from '../lib/install.js' -import { openApp } from '../lib/open.js' -import { getLatestVersion } from '../lib/platform.js' - -function waitForEnter(prompt) { - return new Promise((resolve) => { - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }) - - rl.question(prompt, () => { - rl.close() - resolve() - }) - }) -} - -function clearLine() { - process.stdout.write('\r\x1b[K') -} - -function formatBytes(bytes) { - if (bytes < 1024) return `${bytes} B` - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` - return `${(bytes / (1024 * 1024)).toFixed(1)} MB` -} - -async function main() { - const args = process.argv.slice(2) - - // Handle --version - if (args.includes('--version') || args.includes('-v')) { - const version = await getLatestVersion() - console.log(`rclone-ui v${version} (latest)`) - process.exit(0) - } - - // Handle --help - if (args.includes('--help') || args.includes('-h')) { - console.log(` -rclone-ui - The GUI for rclone - -Usage: - npx rclone-ui Open Rclone UI (installs if not found) - npx rclone-ui --install Reinstall (or update) - npx rclone-ui --version Show version - npx rclone-ui --help Show this help - -More info: https://rcloneui.com -`) - process.exit(0) - } - - const forceInstall = args.includes('--install') - - // Check if already installed - if (isInstalled() && !forceInstall) { - console.log('Opening Rclone UI...') - try { - await openApp() - process.exit(0) - } catch (err) { - console.error('Failed to open Rclone UI:', err.message) - process.exit(1) - } - } - - // Not installed - prompt for installation - console.log('') - await waitForEnter( - 'Rclone UI is not installed. Press Enter to install the latest release from GitHub...' - ) - console.log('') - - // Download - process.stdout.write('Downloading...') - let installerPath - try { - installerPath = await download((downloaded, total) => { - clearLine() - const percent = Math.round((downloaded / total) * 100) - const downloadedStr = formatBytes(downloaded) - const totalStr = formatBytes(total) - process.stdout.write(`Downloading... ${percent}% (${downloadedStr} / ${totalStr})`) - }) - clearLine() - console.log('Downloading... Done!') - } catch (err) { - clearLine() - console.error('Download failed:', err.message) - process.exit(1) - } - - // Install - console.log('Installing...') - try { - await install(installerPath) - console.log('Installing... Done!') - } catch (err) { - console.error('Installation failed:', err.message) - console.error('You may need to run with elevated permissions (sudo on macOS/Linux).') - process.exit(1) - } - - console.log('') - await waitForEnter('Installed! Press Enter to run Rclone UI...') - - try { - await openApp() - } catch (err) { - console.error('Failed to open Rclone UI:', err.message) - process.exit(1) - } -} - -main().catch((err) => { - console.error('Error:', err.message) - process.exit(1) -}) diff --git a/cli/lib/detect.js b/cli/lib/detect.js deleted file mode 100644 index 678f215d..00000000 --- a/cli/lib/detect.js +++ /dev/null @@ -1,37 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import os from "node:os"; -import { getPlatform } from "./platform.js"; - -export function getInstallPath() { - const { isMac, isWindows, isLinux } = getPlatform(); - - if (isMac) { - return "/Applications/Rclone UI.app"; - } - - if (isWindows) { - // NSIS installs to %LOCALAPPDATA%\Rclone UI - const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"); - return path.join(localAppData, "Rclone UI", "Rclone UI.exe"); - } - - if (isLinux) { - // AppImage installed to ~/.local/bin - return path.join(os.homedir(), ".local", "bin", "rclone-ui"); - } - - return null; -} - -export function isInstalled() { - const installPath = getInstallPath(); - if (!installPath) return false; - - try { - return fs.existsSync(installPath); - } catch { - return false; - } -} - diff --git a/cli/lib/install.js b/cli/lib/install.js deleted file mode 100644 index 2ff6e357..00000000 --- a/cli/lib/install.js +++ /dev/null @@ -1,163 +0,0 @@ -import { execSync, spawn } from 'node:child_process' -import fs from 'node:fs' -import https from 'node:https' -import os from 'node:os' -import path from 'node:path' -import { getDownloadUrl, getPlatform } from './platform.js' - -function followRedirects(url, callback) { - https.get(url, (response) => { - if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) { - followRedirects(response.headers.location, callback) - } else { - callback(response) - } - }) -} - -export function download(onProgress) { - return new Promise((resolve, reject) => { - const { url, filename } = getDownloadUrl() - const tempDir = os.tmpdir() - const filePath = path.join(tempDir, filename) - - followRedirects(url, (response) => { - if (response.statusCode !== 200) { - reject(new Error(`Failed to download: ${response.statusCode}`)) - return - } - - const totalSize = Number.parseInt(response.headers['content-length'], 10) - let downloadedSize = 0 - - const file = fs.createWriteStream(filePath) - - response.on('data', (chunk) => { - downloadedSize += chunk.length - if (onProgress && totalSize) { - onProgress(downloadedSize, totalSize) - } - }) - - response.pipe(file) - - file.on('finish', () => { - file.close() - resolve(filePath) - }) - - file.on('error', (err) => { - fs.unlink(filePath, () => {}) - reject(err) - }) - }) - }) -} - -export async function install(installerPath) { - const { isMac, isWindows, isLinux } = getPlatform() - const { type } = getDownloadUrl() - - if (isMac && type === 'dmg') { - return installMacDmg(installerPath) - } - - if (isWindows && type === 'exe') { - return installWindowsExe(installerPath) - } - - if (isLinux && type === 'appimage') { - return installLinuxAppImage(installerPath) - } - - throw new Error(`Unsupported installer type: ${type}`) -} - -async function installMacDmg(dmgPath) { - // Mount the DMG - const mountOutput = execSync(`hdiutil attach -nobrowse -readonly "${dmgPath}"`, { - encoding: 'utf-8', - }) - - // Parse mount point from output - const mountMatch = mountOutput.match(/\/Volumes\/[^\n]+/) - if (!mountMatch) { - throw new Error('Failed to mount DMG') - } - const mountPoint = mountMatch[0].trim() - - try { - // Find the .app in the mounted volume - const apps = fs.readdirSync(mountPoint).filter((f) => f.endsWith('.app')) - if (apps.length === 0) { - throw new Error('No .app found in DMG') - } - - const appName = apps[0] - const sourcePath = path.join(mountPoint, appName) - const destPath = path.join('/Applications', appName) - - // Remove existing installation if present - if (fs.existsSync(destPath)) { - fs.rmSync(destPath, { recursive: true, force: true }) - } - - // Copy to Applications - execSync(`cp -R "${sourcePath}" "/Applications/"`, { encoding: 'utf-8' }) - } finally { - // Unmount the DMG - try { - execSync(`hdiutil detach "${mountPoint}" -quiet`, { encoding: 'utf-8' }) - } catch { - // Ignore unmount errors - } - } -} - -async function installWindowsExe(exePath) { - return new Promise((resolve, reject) => { - // Run NSIS installer with /S for silent mode - const child = spawn(exePath, ['/S'], { - stdio: 'ignore', - shell: true, - }) - - child.on('error', reject) - child.on('close', (code) => { - if (code === 0) { - resolve() - } else { - reject(new Error(`Installer exited with code ${code}`)) - } - }) - }) -} - -async function installLinuxAppImage(appImagePath) { - const homeDir = os.homedir() - const binDir = path.join(homeDir, '.local', 'bin') - const destPath = path.join(binDir, 'rclone-ui') - - // Ensure ~/.local/bin exists - fs.mkdirSync(binDir, { recursive: true }) - - // Copy AppImage to destination - fs.copyFileSync(appImagePath, destPath) - - // Make executable - fs.chmodSync(destPath, 0o755) - - // Create .desktop file for application menu - const desktopDir = path.join(homeDir, '.local', 'share', 'applications') - fs.mkdirSync(desktopDir, { recursive: true }) - - const desktopEntry = `[Desktop Entry] -Name=Rclone UI -Exec=${destPath} -Type=Application -Categories=Utility; -Comment=The GUI for rclone -` - - fs.writeFileSync(path.join(desktopDir, 'rclone-ui.desktop'), desktopEntry) -} diff --git a/cli/lib/open.js b/cli/lib/open.js deleted file mode 100644 index a38d9afe..00000000 --- a/cli/lib/open.js +++ /dev/null @@ -1,40 +0,0 @@ -import { spawn } from "node:child_process"; -import { getPlatform } from "./platform.js"; -import { getInstallPath } from "./detect.js"; - -export function openApp() { - const { isMac, isWindows, isLinux } = getPlatform(); - const installPath = getInstallPath(); - - return new Promise((resolve, reject) => { - let child; - - if (isMac) { - child = spawn("open", ["-a", "Rclone UI"], { - detached: true, - stdio: "ignore", - }); - } else if (isWindows) { - child = spawn(installPath, [], { - detached: true, - stdio: "ignore", - shell: true, - }); - } else if (isLinux) { - child = spawn(installPath, [], { - detached: true, - stdio: "ignore", - }); - } else { - reject(new Error("Unsupported platform")); - return; - } - - child.unref(); - child.on("error", reject); - - // Give it a moment to spawn, then resolve - setTimeout(() => resolve(), 500); - }); -} - diff --git a/cli/lib/platform.js b/cli/lib/platform.js deleted file mode 100644 index 1fee4c59..00000000 --- a/cli/lib/platform.js +++ /dev/null @@ -1,89 +0,0 @@ -import https from 'node:https' -import os from 'node:os' - -const GITHUB_REPO = 'rclone-ui/rclone-ui' - -export function getLatestVersion() { - return new Promise((resolve, reject) => { - const options = { - hostname: 'api.github.com', - path: `/repos/${GITHUB_REPO}/releases/latest`, - headers: { 'User-Agent': 'rclone-ui-npm' }, - } - - https - .get(options, (res) => { - let data = '' - res.on('data', (chunk) => (data += chunk)) - res.on('end', () => { - try { - const release = JSON.parse(data) - const version = release.tag_name?.replace(/^v/, '') || 'unknown' - resolve(version) - } catch { - resolve('unknown') - } - }) - }) - .on('error', () => resolve('unknown')) - }) -} - -export function getPlatform() { - const platform = os.platform() - const arch = os.arch() - - return { - os: platform, - arch: arch, - isWindows: platform === 'win32', - isMac: platform === 'darwin', - isLinux: platform === 'linux', - isArm: arch === 'arm64', - isX64: arch === 'x64', - } -} - -export function getDownloadUrl(version = 'latest') { - const { os: platform, arch } = getPlatform() - const tag = version === 'latest' ? 'latest/download' : `download/v${version}` - const base = `https://github.com/${GITHUB_REPO}/releases/${tag}` - - // Map platform + arch to release filename - if (platform === 'darwin') { - // macOS - const archSuffix = arch === 'arm64' ? 'aarch64' : 'x64' - return { - url: `${base}/Rclone.UI_${archSuffix}.dmg`, - filename: `Rclone.UI_${archSuffix}.dmg`, - type: 'dmg', - } - } - - if (platform === 'win32') { - // Windows - const archSuffix = arch === 'arm64' ? 'arm64' : 'x64' - return { - url: `${base}/Rclone.UI_${archSuffix}.exe`, - filename: `Rclone.UI_${archSuffix}.exe`, - type: 'exe', - } - } - - if (platform === 'linux') { - // Linux - prefer AppImage for portability - const archSuffix = arch === 'arm64' ? 'aarch64' : 'amd64' - return { - url: `${base}/Rclone.UI_${archSuffix}.AppImage`, - filename: `Rclone.UI_${archSuffix}.AppImage`, - type: 'appimage', - } - } - - throw new Error(`Unsupported platform: ${platform} ${arch}`) -} - -export function getAppName() { - const { isMac } = getPlatform() - return isMac ? 'Rclone UI.app' : 'Rclone UI' -} diff --git a/cli/package.json b/cli/package.json deleted file mode 100644 index 63b5dbf5..00000000 --- a/cli/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "rclone-ui", - "version": "3.0.1", - "description": "Installs and launches Rclone UI", - "bin": { - "rclone-ui": "bin/rclone-ui.js" - }, - "type": "module", - "engines": { - "node": ">=18" - }, - "repository": { - "type": "git", - "url": "https://github.com/rclone-ui/rclone-ui" - }, - "homepage": "https://rcloneui.com", - "keywords": ["rclone", "gui", "drive", "s3", "cloud", "storage", "sync", "backup"], - "license": "MIT", - "author": { - "name": "Rclone UI", - "url": "https://github.com/rclone-ui/rclone-ui" - } -} diff --git a/core/agents/automation.go b/core/agents/automation.go new file mode 100644 index 00000000..2416d971 --- /dev/null +++ b/core/agents/automation.go @@ -0,0 +1,692 @@ +package agents + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "slices" + "strconv" + "strings" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/schedules" + "github.com/rclone/rclone-ui/core/watchers" +) + +// The tools for what runs by itself: schedules, which run a transfer at set times, and watchers, +// which keep two folders the same. + +func (s *Server) automationTools() { + s.listSchedulesTool() + s.saveScheduleTool() + s.deleteScheduleTool() + s.pauseScheduleTool() + s.resumeScheduleTool() + s.runScheduleNowTool() + s.listWatchersTool() + s.saveWatcherTool() + s.deleteWatcherTool() + s.pauseWatcherTool() + s.resumeWatcherTool() + s.syncWatcherNowTool() +} + +// The limits of list_schedules and list_watchers. +const ( + automationLimit = 100 + automationLimitMax = 500 +) + +// automationCap returns how many of n items a list returns for the limit an agent asked for. +func automationCap(n, limit int) int { + if limit <= 0 { + limit = automationLimit + } + return min(n, limit, automationLimitMax) +} + +// rfc3339MS returns a time in milliseconds as RFC 3339, in this computer's time zone, or "" for +// none. +func rfc3339MS(ms *int64) string { + if ms == nil { + return "" + } + return time.UnixMilli(*ms).Format(time.RFC3339) +} + +// removed is what the tools that delete a schedule or a watcher return. +type removed struct { + Deleted string `json:"deleted" jsonschema:"the name of what was deleted"` +} + +// scheduleOps are the operations that a schedule runs, for the refusals. +const scheduleOps = "copy, move, sync, bisync, delete or purge" + +// cronInWords says a cron expression in words, in this computer's time zone, for the shapes that +// the app's schedule drawer writes (src/components/schedule/when.ts): "every day at 02:00". It +// returns "" for any other expression, which an agent reads as it is. +func cronInWords(expr string) string { + switch strings.ToLower(strings.TrimSpace(expr)) { + case "@hourly": + return "every hour at :00" + case "@daily": + return "every day at 00:00" + case "@weekly": + return "every Sunday at 00:00" + case "@monthly": + return "every month on day 1 at 00:00" + } + f := strings.Fields(expr) + if len(f) != 5 || f[3] != "*" { + return "" + } + minute, ok := cronNumber(f[0], 0, 59) + if !ok { + return "" + } + if f[1] == "*" && f[2] == "*" && f[4] == "*" { + return fmt.Sprintf("every hour at :%02d", minute) + } + hour, ok := cronNumber(f[1], 0, 23) + if !ok { + return "" + } + at := fmt.Sprintf("%02d:%02d", hour, minute) + switch { + case f[2] == "*" && f[4] == "*": + return "every day at " + at + case f[2] == "*" && (f[4] == "1-5" || strings.EqualFold(f[4], "mon-fri")): + return "every weekday (Monday to Friday) at " + at + case f[2] == "*": + if day, ok := cronNumber(f[4], 0, 7); ok { + return "every " + time.Weekday(day%7).String() + " at " + at + } + for day := time.Sunday; day <= time.Saturday; day++ { + if strings.EqualFold(f[4], day.String()[:3]) { + return "every " + day.String() + " at " + at + } + } + case f[4] == "*": + if day, ok := cronNumber(f[2], 1, 31); ok { + return fmt.Sprintf("every month on day %d at %s", day, at) + } + } + return "" +} + +// cronNumber reads a cron field that is one plain number between lo and hi. +func cronNumber(field string, lo, hi int) (int, bool) { + n, err := strconv.Atoi(field) + if err != nil || n < lo || n > hi || strings.ContainsAny(field, "+-") { + return 0, false + } + return n, true +} + +// flatOptions returns the options of a form's groups as one map, by rclone's name, as an agent +// gives them. Bisync's switches and the per-remote overrides aren't options, and are left out. +func flatOptions(g *operations.Groups) map[string]any { + if g == nil { + return nil + } + out := map[string]any{} + for _, group := range g.Named() { + for key, raw := range group { + var v any + if json.Unmarshal(raw, &v) == nil && v != nil { + out[catalog.NormalizeOptionName(key)] = v + } + } + } + if len(out) == 0 { + return nil + } + return out +} + +// scheduleForm builds the form that a schedule runs from an agent's flat fields. It refuses what +// the operation's form can't hold, so that an agent can't save a form that means something else: +// a sync and a bisync take one source, and a delete and a purge take no destination. +func scheduleForm(op operations.Operation, sources []string, destination string, g operations.Groups) (operations.Form, error) { + if len(sources) == 0 { + return operations.Form{}, errs.Errorf("Give the sources that the %s reads, such as [\"gdrive:Photos\"].", op) + } + switch op { + case operations.OperationDelete, operations.OperationPurge: + if destination != "" { + return operations.Form{}, errs.Errorf("A %s takes no destination: it deletes its sources.", op) + } + if op == operations.OperationDelete { + return operations.DeleteArgs{Sources: sources, Options: g}.Form(), nil + } + return operations.PurgeArgs{Sources: sources, Options: g}.Form(), nil + } + if destination == "" { + return operations.Form{}, errs.Errorf("Give the destination that the %s writes to.", op) + } + switch op { + case operations.OperationCopy: + return operations.CopyArgs{Sources: sources, Destination: destination, Options: g}.Form(), nil + case operations.OperationMove: + return operations.MoveArgs{Sources: sources, Destination: destination, Options: g}.Form(), nil + } + if len(sources) != 1 { + return operations.Form{}, errs.Errorf("A %s takes one source.", op) + } + if op == operations.OperationSync { + return operations.SyncArgs{Source: sources[0], Destination: destination, Options: g}.Form(), nil + } + return operations.BisyncArgs{Source: sources[0], Destination: destination, Options: g}.Form(), nil +} + +// takesDestination reports whether an operation that a schedule runs writes to a destination. +func takesDestination(op operations.Operation) bool { + return op != operations.OperationDelete && op != operations.OperationPurge +} + +// scheduleItem is a schedule, as the schedule tools return it. +type scheduleItem struct { + ID string `json:"id" jsonschema:"the schedule's id, for the other schedule tools"` + Name string `json:"name"` + Operation string `json:"operation" jsonschema:"copy, move, sync, bisync, delete or purge"` + Sources []string `json:"sources"` + Destination string `json:"destination,omitempty"` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's options that each run uses, by name"` + When string `json:"when" jsonschema:"the cron expression, in this computer's time zone"` + WhenInWords string `json:"when_in_words,omitempty" jsonschema:"the same in words, for the common shapes"` + Paused bool `json:"paused"` + NextRun string `json:"next_run,omitempty" jsonschema:"when it runs next, or nothing while it is paused"` + // Running is set while a run is in progress, with its transfer once it has started. + Running bool `json:"running,omitempty"` + RunningTransferID string `json:"running_transfer_id,omitempty"` + LastRunAt string `json:"last_run_at,omitempty" jsonschema:"when the last run ended"` + LastResult string `json:"last_result,omitempty" jsonschema:"how the last run ended: completed, nothing (nothing to do), failed, stopped or interrupted"` + LastError string `json:"last_error,omitempty"` + LastTransferID string `json:"last_transfer_id,omitempty" jsonschema:"the last run's transfer, for get_transfer and History"` +} + +// scheduleItemOf converts a schedule. +func scheduleItemOf(sc schedules.Schedule) scheduleItem { + sources, destination := sc.Form.Ends() + if sources == nil { + sources = []string{} + } + return scheduleItem{ + ID: sc.ID, Name: sc.Name, Operation: string(sc.Form.Operation), Sources: sources, Destination: destination, + Options: flatOptions(sc.Form.Groups()), When: sc.When, WhenInWords: cronInWords(sc.When), Paused: sc.Paused, + NextRun: rfc3339MS(sc.NextRun), Running: sc.Running, RunningTransferID: sc.RunningID, + LastRunAt: rfc3339MS(sc.LastRunAt), LastResult: sc.LastResult, LastError: sc.LastError, + LastTransferID: sc.LastTransferID, + } +} + +type schedulesIn struct { + Limit int `json:"limit,omitempty" jsonschema:"how many schedules to return: 100 when left out, 500 at most"` +} + +type scheduleList struct { + Schedules []scheduleItem `json:"schedules"` + Total int `json:"total"` + // Truncated is set when there are more schedules than were returned. + Truncated bool `json:"truncated,omitempty" jsonschema:"there are more: call again with a higher limit"` +} + +func (s *Server) listSchedulesTool() { + add(s, &mcp.Tool{ + Name: "list_schedules", + Description: "The user's schedules, sorted by name. A schedule runs a copy, move, sync, bisync, delete or purge at set times " + + "while the app is open. Each has its id, what it runs (operation, sources, destination, options), when " + + "(the cron expression, and in words), whether it is paused, its next run, and how its last run ended.", + Annotations: reads("List schedules"), + }, func(ctx context.Context, in schedulesIn) (scheduleList, error) { + all, err := s.o.APIs.Schedules.List(ctx) + if err != nil { + return scheduleList{}, err + } + n := automationCap(len(all), in.Limit) + out := scheduleList{Schedules: make([]scheduleItem, 0, n), Total: len(all), Truncated: n < len(all)} + for _, sc := range all[:n] { + out.Schedules = append(out.Schedules, scheduleItemOf(sc)) + } + return out, nil + }) +} + +type saveScheduleIn struct { + ScheduleID string `json:"schedule_id,omitempty" jsonschema:"the schedule to change, from list_schedules. Leave it out to create one. When changing one, the fields left out keep their saved values."` + Name string `json:"name,omitempty" jsonschema:"a name that no other schedule has, such as Nightly photos backup"` + Operation string `json:"operation,omitempty" jsonschema:"what each run does: copy, move, sync, bisync, delete or purge"` + Sources []string `json:"sources,omitempty" jsonschema:"the paths that a run reads, such as [\"gdrive:Photos\"]: one for a sync or a bisync, one or more for the others"` + Destination string `json:"destination,omitempty" jsonschema:"where a copy, move, sync or bisync writes, such as /Users/me/Backup/Photos. A delete and a purge take none."` + When string `json:"when,omitempty" jsonschema:"when it runs, in this computer's time zone: a cron expression of 5 fields (minute, hour, day of month, month, day of week), or @hourly, @daily, @weekly or @monthly. Examples: \"0 2 * * *\" every day at 02:00, \"30 18 * * 1-5\" Monday to Friday at 18:30, \"0 9 * * MON\" every Monday at 09:00, \"0 3 1 * *\" the 1st of each month at 03:00, \"*/15 * * * *\" every 15 minutes."` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's options for each run, by name, such as {\"max_age\": \"7d\", \"exclude\": [\"*.tmp\"]}. When changing a schedule, these replace its saved options."` +} + +// scheduleSaved is what save_schedule returns: the schedule, and what it found while saving. +type scheduleSaved struct { + Schedule scheduleItem `json:"schedule"` + // NextRuns are the next 3 times it runs. + NextRuns []string `json:"next_runs,omitempty" jsonschema:"the next 3 times it runs, unless it is paused"` + Warning string `json:"warning,omitempty"` + // IgnoredOptions are the options that the operation doesn't use, which weren't saved. + IgnoredOptions []optionLeftOut `json:"ignored_options,omitempty"` +} + +func (s *Server) saveScheduleTool() { + add(s, &mcp.Tool{ + Name: "save_schedule", + Description: "Creates a schedule, or changes one when schedule_id is given. A schedule runs an operation at the times of `when`, " + + "while the app is open, and each run shows in History. It can run a sync, move, delete, purge or bisync, which delete or " + + "overwrite files, again and again without asking: run the same operation once with the transfer tools' dry_run first, " + + "and tell the user what it would do. The form is checked as a run would check it, which reads the sources. " + + "A new schedule runs from its next time on: use pause_schedule to keep it from running. dry_run is never saved. " + + "Options that the operation doesn't use come back in ignored_options.", + Annotations: destroys("Save a schedule"), + }, func(ctx context.Context, in saveScheduleIn) (scheduleSaved, error) { + var saved *schedules.Schedule + if in.ScheduleID != "" { + sc, err := s.o.APIs.Schedules.Get(ctx, in.ScheduleID) + if err != nil { + return scheduleSaved{}, err + } + saved = &sc + } + name, when := in.Name, in.When + op := operations.Operation(strings.ToLower(strings.TrimSpace(in.Operation))) + sources, destination := in.Sources, in.Destination + var old *operations.Groups + if saved != nil { + oldSources, oldDestination := saved.Form.Ends() + if name == "" { + name = saved.Name + } + if when == "" { + when = saved.When + } + if op == "" { + op = saved.Form.Operation + } + if len(sources) == 0 { + sources = oldSources + } + if destination == "" && takesDestination(op) { + destination = oldDestination + } + old = saved.Form.Groups() + } + switch { + case strings.TrimSpace(name) == "": + return scheduleSaved{}, errs.New("Give the schedule a name.") + case op == "": + return scheduleSaved{}, errs.Errorf("Give the operation that the schedule runs: %s.", scheduleOps) + case !slices.Contains(schedules.Operations, op): + return scheduleSaved{}, errs.Errorf("A schedule can't run %q: it runs a %s.", in.Operation, scheduleOps) + case strings.TrimSpace(when) == "": + return scheduleSaved{}, errs.New("Give when the schedule runs, as a cron expression such as \"0 2 * * *\".") + } + + // A dry run is for one run, so a schedule never keeps it. + var ignored []optionLeftOut + flat := maps.Clone(in.Options) + for key := range in.Options { + if catalog.NormalizeOptionName(key) == "dry_run" { + delete(flat, key) + ignored = append(ignored, optionLeftOut{Option: key, Reason: "A schedule doesn't keep a dry run, which is for a single run."}) + } + } + var groups operations.Groups + var left []optionLeftOut + var err error + switch { + case in.Options != nil || old == nil: + groups, left, err = optionGroupsFor(op, "", flat) + case op == saved.Form.Operation: + groups = *old + default: // the saved options, sorted again for the new operation + groups, left, err = optionGroupsFor(op, "", flatOptions(old)) + } + if err != nil { + return scheduleSaved{}, err + } + // The per-remote overrides, and bisync's switches, are set in the app's windows. A change + // of the options keeps them. + if old != nil { + if groups.Remotes == nil { + groups.Remotes = old.Remotes + } + if groups.Outer == nil && op == operations.OperationBisync && saved.Form.Operation == op { + groups.Outer = old.Outer + } + } + form, err := scheduleForm(op, sources, destination, groups) + if err != nil { + return scheduleSaved{}, err + } + sc, err := s.o.APIs.Schedules.Save(ctx, schedules.Input{ID: in.ScheduleID, Name: name, Form: form, When: when}) + if err != nil { + return scheduleSaved{}, err + } + out := scheduleSaved{Schedule: scheduleItemOf(sc), Warning: sc.Warning, IgnoredOptions: append(ignored, left...)} + if !sc.Paused { + if d, err := s.o.APIs.Schedules.Describe(ctx, sc.When); err == nil { + for _, ms := range d.Next { + out.NextRuns = append(out.NextRuns, rfc3339MS(&ms)) + } + } + } + return out, nil + }) +} + +type scheduleIDIn struct { + ScheduleID string `json:"schedule_id" jsonschema:"the schedule's id, from list_schedules"` +} + +func (s *Server) deleteScheduleTool() { + add(s, &mcp.Tool{ + Name: "delete_schedule", + Description: "Deletes a schedule, so it never runs again. A run in progress goes on. Its past runs stay in History. " + + "To stop it for a while instead, use pause_schedule.", + Annotations: destroys("Delete a schedule"), + }, func(ctx context.Context, in scheduleIDIn) (removed, error) { + sc, err := s.o.APIs.Schedules.Get(ctx, in.ScheduleID) + if err != nil { + return removed{}, err + } + if err := s.o.APIs.Schedules.Delete(ctx, in.ScheduleID); err != nil { + return removed{}, err + } + return removed{Deleted: sc.Name}, nil + }) +} + +func (s *Server) pauseScheduleTool() { + add(s, &mcp.Tool{ + Name: "pause_schedule", + Description: "Pauses a schedule: it doesn't run at its times until resume_schedule. A run in progress goes on. Returns the schedule.", + Annotations: changes("Pause a schedule"), + }, func(ctx context.Context, in scheduleIDIn) (scheduleItem, error) { + if err := s.o.APIs.Schedules.Pause(ctx, in.ScheduleID); err != nil { + return scheduleItem{}, err + } + sc, err := s.o.APIs.Schedules.Get(ctx, in.ScheduleID) + return scheduleItemOf(sc), err + }) +} + +func (s *Server) resumeScheduleTool() { + add(s, &mcp.Tool{ + Name: "resume_schedule", + Description: "Resumes a paused schedule: it runs again from its next time on, and the times it missed while paused are skipped. " + + "Its runs may delete or overwrite files, as its operation does. Returns the schedule, with its next run.", + Annotations: destroys("Resume a schedule"), + }, func(ctx context.Context, in scheduleIDIn) (scheduleItem, error) { + if err := s.o.APIs.Schedules.Resume(ctx, in.ScheduleID); err != nil { + return scheduleItem{}, err + } + sc, err := s.o.APIs.Schedules.Get(ctx, in.ScheduleID) + return scheduleItemOf(sc), err + }) +} + +// scheduleRun is what run_schedule_now returns. +type scheduleRun struct { + TransferID string `json:"transfer_id,omitempty" jsonschema:"the run's transfer: follow it with wait_for_transfer or get_transfer"` + Running bool `json:"running" jsonschema:"the run is in progress"` + // Result and Error are set when the run ended before the tool returned. + Result string `json:"result,omitempty" jsonschema:"how the run ended, when it ended at once: completed, nothing (nothing to do), failed, stopped or interrupted"` + Error string `json:"error,omitempty"` +} + +// runStartWait is how long run_schedule_now waits for the run's transfer to start. +const runStartWait = 10 * time.Second + +func (s *Server) runScheduleNowTool() { + add(s, &mcp.Tool{ + Name: "run_schedule_now", + Description: "Runs a schedule once now, paused or not, without changing its times. It can delete or overwrite files, as the " + + "schedule's operation does. It returns once the run has started, with its transfer_id: follow it with wait_for_transfer " + + "or get_transfer. History and list_transfers show it too. A schedule that is running already is refused.", + Annotations: destroys("Run a schedule now"), + }, func(ctx context.Context, in scheduleIDIn) (scheduleRun, error) { + before, err := s.o.APIs.Schedules.Get(ctx, in.ScheduleID) + if err != nil { + return scheduleRun{}, err + } + if err := s.o.APIs.Schedules.RunNow(ctx, in.ScheduleID); err != nil { + return scheduleRun{}, err + } + // The run's transfer starts in the background, and the schedule names it once it has. + ctx, cancel := context.WithTimeout(ctx, runStartWait) + defer cancel() + tick := time.NewTicker(50 * time.Millisecond) + defer tick.Stop() + for { + sc, err := s.o.APIs.Schedules.Get(ctx, in.ScheduleID) + switch { + case err != nil: + return scheduleRun{Running: true}, nil // it started, and ctx ended + case sc.RunningID != "": + return scheduleRun{TransferID: sc.RunningID, Running: true}, nil + case !sc.Running: + out := scheduleRun{} + if rfc3339MS(sc.LastRunAt) != rfc3339MS(before.LastRunAt) || sc.LastTransferID != before.LastTransferID { + out.TransferID, out.Result, out.Error = sc.LastTransferID, sc.LastResult, sc.LastError + } + return out, nil + } + select { + case <-ctx.Done(): + return scheduleRun{Running: true}, nil + case <-tick.C: + } + } + }) +} + +// watcherItem is a watcher, as the watcher tools return it. +type watcherItem struct { + ID string `json:"id" jsonschema:"the watcher's id, for the other watcher tools"` + Name string `json:"name"` + FolderA string `json:"folder_a"` + FolderB string `json:"folder_b"` + Paused bool `json:"paused"` + State string `json:"state" jsonschema:"initializing (its first merge of the two folders hasn't succeeded yet), active, paused, failing (its runs fail, and it tries again every minute) or needs_attention"` + // Attention says why the watcher stopped until the user acts. + Attention string `json:"attention,omitempty" jsonschema:"why it stopped and what the user can do, when it needs attention"` + LastError string `json:"last_error,omitempty"` + LastRunAt string `json:"last_run_at,omitempty" jsonschema:"when its last run ended"` + LastChangeAt string `json:"last_change_at,omitempty" jsonschema:"when its last run that changed a file ended"` + LastTransferID string `json:"last_transfer_id,omitempty" jsonschema:"its last run that changed something or failed, for get_transfer and History"` +} + +// watcherItemOf converts a watcher. Its state is the one that the Watchers window shows +// (src/pages/Watchers/status.ts). +func watcherItemOf(w watchers.Watcher) watcherItem { + out := watcherItem{ + ID: w.ID, Name: w.Name, FolderA: w.PathA, FolderB: w.PathB, Paused: w.Paused, LastError: w.LastError, + LastRunAt: rfc3339MS(w.LastRunAt), LastChangeAt: rfc3339MS(w.LastChangeAt), LastTransferID: w.LastTransferID, + } + lost := "one of the folders" + switch w.DeletedSide { + case watchers.SideA: + lost = w.PathA + case watchers.SideB: + lost = w.PathB + } + switch { + case w.Resyncing: + out.State = "initializing" + case w.Attention != "": + out.State = "needs_attention" + switch w.Attention { + case watchers.AttentionResync: + out.Attention = "bisync can only go on after the two folders are merged again. " + case watchers.AttentionDeletes: + out.Attention = "Many files were deleted in " + lost + " since the last sync, so the watcher stopped to make sure that was meant. " + case watchers.AttentionEmptied: + out.Attention = "Every file in " + lost + " is gone since the last sync, so the watcher stopped to make sure that was meant. " + } + out.Attention += "The user decides what to do in the app's Watchers window (open_window watchers)." + case w.Paused: + out.State = "paused" + case w.LastResult == watchers.ResultFailed: + out.State = "failing" + case !w.Baselined: + out.State = "initializing" + default: + out.State = "active" + } + return out +} + +type watchersIn struct { + Limit int `json:"limit,omitempty" jsonschema:"how many watchers to return: 100 when left out, 500 at most"` +} + +type watcherList struct { + Watchers []watcherItem `json:"watchers"` + Total int `json:"total"` + // Truncated is set when there are more watchers than were returned. + Truncated bool `json:"truncated,omitempty" jsonschema:"there are more: call again with a higher limit"` +} + +func (s *Server) listWatchersTool() { + add(s, &mcp.Tool{ + Name: "list_watchers", + Description: "The user's watchers, sorted by name. A watcher keeps two folders the same in both directions while the app is open: " + + "every minute, it copies new and changed files each way and deletes on one side what was deleted on the other. " + + "Each has its id, its two folders, whether it is paused, its state, and its last error.", + Annotations: reads("List watchers"), + }, func(ctx context.Context, in watchersIn) (watcherList, error) { + all, err := s.o.APIs.Watchers.List(ctx) + if err != nil { + return watcherList{}, err + } + n := automationCap(len(all), in.Limit) + out := watcherList{Watchers: make([]watcherItem, 0, n), Total: len(all), Truncated: n < len(all)} + for _, w := range all[:n] { + out.Watchers = append(out.Watchers, watcherItemOf(w)) + } + return out, nil + }) +} + +type saveWatcherIn struct { + WatcherID string `json:"watcher_id,omitempty" jsonschema:"the watcher to change, from list_watchers. Leave it out to create one. When changing one, the fields left out keep their saved values."` + Name string `json:"name,omitempty" jsonschema:"a name that no other watcher has, such as Notes on Drive"` + FolderA string `json:"folder_a,omitempty" jsonschema:"one of the two folders, such as /Users/me/Notes"` + FolderB string `json:"folder_b,omitempty" jsonschema:"the other folder, such as gdrive:Notes. Neither folder can be inside the other."` +} + +func (s *Server) saveWatcherTool() { + add(s, &mcp.Tool{ + Name: "save_watcher", + Description: "Creates a watcher, or changes one when watcher_id is given. A watcher keeps two folders the same in both directions " + + "while the app is open: every minute, it copies new and changed files each way, and deletes in one folder what was deleted " + + "in the other. A new watcher, or one whose folders changed, first merges the two folders at once: files missing on one side " + + "are copied over, the newer file wins where both have one, and nothing is deleted. Returns the watcher.", + Annotations: destroys("Save a watcher"), + }, func(ctx context.Context, in saveWatcherIn) (watcherItem, error) { + w := watchers.Input{ID: in.WatcherID, Name: in.Name, PathA: in.FolderA, PathB: in.FolderB} + if in.WatcherID != "" { + saved, err := s.o.APIs.Watchers.Get(ctx, in.WatcherID) + if err != nil { + return watcherItem{}, err + } + if w.Name == "" { + w.Name = saved.Name + } + if w.PathA == "" { + w.PathA = saved.PathA + } + if w.PathB == "" { + w.PathB = saved.PathB + } + } + switch { + case strings.TrimSpace(w.Name) == "": + return watcherItem{}, errs.New("Give the watcher a name.") + case strings.TrimSpace(w.PathA) == "" || strings.TrimSpace(w.PathB) == "": + return watcherItem{}, errs.New("Give both folders: folder_a and folder_b.") + } + saved, err := s.o.APIs.Watchers.Save(ctx, w) + if err != nil { + return watcherItem{}, err + } + return watcherItemOf(saved), nil + }) +} + +type watcherIDIn struct { + WatcherID string `json:"watcher_id" jsonschema:"the watcher's id, from list_watchers"` +} + +func (s *Server) deleteWatcherTool() { + add(s, &mcp.Tool{ + Name: "delete_watcher", + Description: "Deletes a watcher, and stops its run in progress. The two folders and their files stay as they are: " + + "they just stop being kept the same. To stop it for a while instead, use pause_watcher.", + Annotations: destroys("Delete a watcher"), + }, func(ctx context.Context, in watcherIDIn) (removed, error) { + w, err := s.o.APIs.Watchers.Get(ctx, in.WatcherID) + if err != nil { + return removed{}, err + } + if err := s.o.APIs.Watchers.Delete(ctx, in.WatcherID); err != nil { + return removed{}, err + } + return removed{Deleted: w.Name}, nil + }) +} + +func (s *Server) pauseWatcherTool() { + add(s, &mcp.Tool{ + Name: "pause_watcher", + Description: "Pauses a watcher: it stops keeping its two folders the same until resume_watcher. Returns the watcher.", + Annotations: changes("Pause a watcher"), + }, func(ctx context.Context, in watcherIDIn) (watcherItem, error) { + if err := s.o.APIs.Watchers.Pause(ctx, in.WatcherID); err != nil { + return watcherItem{}, err + } + w, err := s.o.APIs.Watchers.Get(ctx, in.WatcherID) + return watcherItemOf(w), err + }) +} + +func (s *Server) resumeWatcherTool() { + add(s, &mcp.Tool{ + Name: "resume_watcher", + Description: "Resumes a paused watcher: it syncs its two folders at once, and every minute after. A sync deletes in one folder " + + "what was deleted in the other while it was paused. Returns the watcher.", + Annotations: destroys("Resume a watcher"), + }, func(ctx context.Context, in watcherIDIn) (watcherItem, error) { + if err := s.o.APIs.Watchers.Resume(ctx, in.WatcherID); err != nil { + return watcherItem{}, err + } + w, err := s.o.APIs.Watchers.Get(ctx, in.WatcherID) + return watcherItemOf(w), err + }) +} + +func (s *Server) syncWatcherNowTool() { + add(s, &mcp.Tool{ + Name: "sync_watcher_now", + Description: "Syncs a watcher's two folders now, without waiting for its next minute, unless a run is in progress. " + + "A sync deletes in one folder what was deleted in the other. It returns at once: the run shows in History when it " + + "changes something or fails, and list_watchers shows how it ended.", + Annotations: destroys("Sync a watcher now"), + }, func(ctx context.Context, in watcherIDIn) (watcherItem, error) { + if err := s.o.APIs.Watchers.SyncNow(ctx, in.WatcherID); err != nil { + return watcherItem{}, err + } + w, err := s.o.APIs.Watchers.Get(ctx, in.WatcherID) + return watcherItemOf(w), err + }) +} diff --git a/core/agents/automation_test.go b/core/agents/automation_test.go new file mode 100644 index 00000000..c0daa69b --- /dev/null +++ b/core/agents/automation_test.go @@ -0,0 +1,221 @@ +package agents + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/internal/testutil" +) + +// A schedule is created from flat fields, listed, changed, paused, resumed, run at once (a copy +// between two folders, whose file arrives), and deleted. The forms that it can't run are refused. +func TestScheduleTools(t *testing.T) { + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + if err := os.WriteFile(filepath.Join(src, "a.txt"), []byte("scheduled"), 0o600); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + args map[string]any + want string + }{ + {map[string]any{"name": "x", "operation": "download", "sources": []string{src}, "destination": dst, "when": "@daily"}, "can't run"}, + {map[string]any{"name": "x", "operation": "sync", "sources": []string{src, src}, "destination": dst, "when": "@daily"}, "one source"}, + {map[string]any{"name": "x", "operation": "delete", "sources": []string{src}, "destination": dst, "when": "@daily"}, "no destination"}, + {map[string]any{"name": "x", "operation": "copy", "sources": []string{src}, "when": "@daily"}, "destination"}, + {map[string]any{"name": "x", "operation": "copy", "destination": dst, "when": "@daily"}, "sources"}, + {map[string]any{"name": "x", "operation": "copy", "sources": []string{src}, "destination": dst, "when": "daily"}, "5 fields"}, + {map[string]any{"name": "x", "operation": "copy", "sources": []string{src}, "destination": dst}, "cron"}, + {map[string]any{"operation": "copy", "sources": []string{src}, "destination": dst, "when": "@daily"}, "name"}, + {map[string]any{"schedule_id": "no-such-schedule", "when": "@daily"}, "deleted"}, + } { + if _, failed := call[scheduleSaved](t, cs, "save_schedule", c.args); !strings.Contains(failed, c.want) { + t.Errorf("%v: %q, want it to say %q", c.args, failed, c.want) + } + } + + saved := must[scheduleSaved](t, cs, "save_schedule", map[string]any{ + "name": "Nightly copy", "operation": "Copy", "sources": []string{"box:" + src}, "destination": dst, "when": "0 2 * * *", + "options": map[string]any{"dry_run": true, "max_age": "7d", "no_such_option": 1}, + }) + sc := saved.Schedule + t.Cleanup(func() { _ = apis.Schedules.Delete(t.Context(), sc.ID) }) + if sc.Name != "Nightly copy" || sc.Operation != "copy" || !slices.Equal(sc.Sources, []string{"box:" + src}) || + sc.Destination != dst || sc.When != "0 2 * * *" || sc.WhenInWords != "every day at 02:00" || sc.Paused || sc.NextRun == "" { + t.Fatalf("save_schedule: %+v", sc) + } + if len(saved.NextRuns) != 3 || saved.NextRuns[0] != sc.NextRun { + t.Errorf("next runs %v, next run %s", saved.NextRuns, sc.NextRun) + } + if len(sc.Options) != 1 || sc.Options["max_age"] != "7d" { + t.Errorf("the saved options: %v", sc.Options) + } + var ignored []string + for _, o := range saved.IgnoredOptions { + ignored = append(ignored, o.Option) + } + if !slices.Equal(ignored, []string{"dry_run", "no_such_option"}) { + t.Errorf("ignored options: %+v", saved.IgnoredOptions) + } + + // A change keeps what it leaves out. + edited := must[scheduleSaved](t, cs, "save_schedule", map[string]any{"schedule_id": sc.ID, "when": "30 18 * * 1-5"}).Schedule + if edited.ID != sc.ID || edited.Name != sc.Name || !slices.Equal(edited.Sources, sc.Sources) || edited.Destination != dst || + edited.WhenInWords != "every weekday (Monday to Friday) at 18:30" || edited.Options["max_age"] != "7d" { + t.Errorf("after changing when: %+v", edited) + } + other := must[scheduleSaved](t, cs, "save_schedule", map[string]any{ + "name": "Weekly purge", "operation": "purge", "sources": []string{"box:" + t.TempDir()}, "when": "@weekly", + }).Schedule + t.Cleanup(func() { _ = apis.Schedules.Delete(t.Context(), other.ID) }) + if other.Destination != "" || other.WhenInWords != "every Sunday at 00:00" { + t.Errorf("a purge: %+v", other) + } + list := must[scheduleList](t, cs, "list_schedules", nil) + if list.Total < 2 || list.Truncated || !slices.ContainsFunc(list.Schedules, func(s scheduleItem) bool { return s.ID == sc.ID }) { + t.Errorf("list_schedules: %+v", list) + } + if short := must[scheduleList](t, cs, "list_schedules", map[string]any{"limit": 1}); len(short.Schedules) != 1 || !short.Truncated || short.Total != list.Total { + t.Errorf("list_schedules with a limit: %+v", short) + } + + if p := must[scheduleItem](t, cs, "pause_schedule", map[string]any{"schedule_id": sc.ID}); !p.Paused || p.NextRun != "" { + t.Errorf("pause_schedule: %+v", p) + } + if r := must[scheduleItem](t, cs, "resume_schedule", map[string]any{"schedule_id": sc.ID}); r.Paused || r.NextRun == "" { + t.Errorf("resume_schedule: %+v", r) + } + + run := must[scheduleRun](t, cs, "run_schedule_now", map[string]any{"schedule_id": sc.ID}) + if run.TransferID == "" { + t.Fatalf("run_schedule_now: %+v", run) + } + // A copy puts a folder that it copies inside the destination. + testutil.Eventually(t, time.Minute, "the copied file", func() bool { + b, err := os.ReadFile(filepath.Join(dst, filepath.Base(src), "a.txt")) + return err == nil && string(b) == "scheduled" + }) + testutil.Eventually(t, time.Minute, "the run's end", func() bool { + l, failed := call[scheduleList](t, cs, "list_schedules", nil) + i := slices.IndexFunc(l.Schedules, func(s scheduleItem) bool { return s.ID == sc.ID }) + return failed == "" && i >= 0 && !l.Schedules[i].Running && l.Schedules[i].LastResult == "completed" && + l.Schedules[i].LastTransferID == run.TransferID + }) + + if got := must[removed](t, cs, "delete_schedule", map[string]any{"schedule_id": sc.ID}); got.Deleted != "Nightly copy" { + t.Errorf("delete_schedule: %+v", got) + } + if _, failed := call[removed](t, cs, "delete_schedule", map[string]any{"schedule_id": sc.ID}); !strings.Contains(failed, "deleted") { + t.Errorf("deleting it twice: %q", failed) + } + if _, failed := call[scheduleRun](t, cs, "run_schedule_now", map[string]any{"schedule_id": sc.ID}); !strings.Contains(failed, "deleted") { + t.Errorf("running a deleted schedule: %q", failed) + } +} + +// cronInWords says the drawer's shapes in words, and nothing for any other expression. +func TestCronInWords(t *testing.T) { + for expr, want := range map[string]string{ + "@hourly": "every hour at :00", + "@monthly": "every month on day 1 at 00:00", + "5 * * * *": "every hour at :05", + "0 2 * * *": "every day at 02:00", + "0 9 * * mon": "every Monday at 09:00", + "0 9 * * 7": "every Sunday at 09:00", + "0 3 15 * *": "every month on day 15 at 03:00", + "*/15 * * * *": "", + "0 2 * 1 *": "", + "0 2 1 * 1": "", + "0 2,14 * * *": "", + "not a cron": "", + "60 2 * * *": "", + "0 9 * * 1-3": "", + "0 18 * * 1-5 ": "every weekday (Monday to Friday) at 18:00", + } { + if got := cronInWords(expr); got != want { + t.Errorf("%q: %q, want %q", expr, got, want) + } + } +} + +// A watcher is created, merges its two folders at once, is listed, renamed, paused, resumed, +// synced now, and deleted. Folders that can't be kept the same are refused. +func TestWatcherTools(t *testing.T) { + cs := connect(t) + a, b := t.TempDir(), t.TempDir() + if err := os.WriteFile(filepath.Join(a, "note.txt"), []byte("watched"), 0o600); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + args map[string]any + want string + }{ + {map[string]any{"name": "x", "folder_a": a, "folder_b": a}, "same folder"}, + {map[string]any{"name": "x", "folder_a": a, "folder_b": filepath.Join(a, "inside")}, "inside"}, + {map[string]any{"name": "x", "folder_a": a}, "folder_b"}, + {map[string]any{"folder_a": a, "folder_b": b}, "name"}, + {map[string]any{"watcher_id": "no-such-watcher", "name": "x"}, "no longer exists"}, + } { + if _, failed := call[watcherItem](t, cs, "save_watcher", c.args); !strings.Contains(failed, c.want) { + t.Errorf("%v: %q, want it to say %q", c.args, failed, c.want) + } + } + + w := must[watcherItem](t, cs, "save_watcher", map[string]any{"name": "Notes", "folder_a": a, "folder_b": "box:" + b}) + t.Cleanup(func() { _ = apis.Watchers.Delete(t.Context(), w.ID) }) + if w.Name != "Notes" || w.FolderA != a || w.FolderB != "box:"+b || w.Paused || w.State != "initializing" { + t.Fatalf("save_watcher: %+v", w) + } + testutil.Eventually(t, time.Minute, "the first merge", func() bool { + got, err := os.ReadFile(filepath.Join(b, "note.txt")) + return err == nil && string(got) == "watched" + }) + testutil.Eventually(t, time.Minute, "an active watcher", func() bool { + list, failed := call[watcherList](t, cs, "list_watchers", nil) + i := slices.IndexFunc(list.Watchers, func(x watcherItem) bool { return x.ID == w.ID }) + return failed == "" && i >= 0 && list.Watchers[i].State == "active" && list.Watchers[i].LastRunAt != "" + }) + + renamed := must[watcherItem](t, cs, "save_watcher", map[string]any{"watcher_id": w.ID, "name": "Notes on box"}) + if renamed.Name != "Notes on box" || renamed.FolderA != a || renamed.FolderB != "box:"+b || renamed.State != "active" { + t.Errorf("after a rename: %+v", renamed) + } + other := must[watcherItem](t, cs, "save_watcher", map[string]any{"name": "Other", "folder_a": t.TempDir(), "folder_b": t.TempDir()}) + t.Cleanup(func() { _ = apis.Watchers.Delete(t.Context(), other.ID) }) + list := must[watcherList](t, cs, "list_watchers", nil) + if list.Total < 2 || list.Truncated { + t.Errorf("list_watchers: %+v", list) + } + if short := must[watcherList](t, cs, "list_watchers", map[string]any{"limit": 1}); len(short.Watchers) != 1 || !short.Truncated { + t.Errorf("list_watchers with a limit: %+v", short) + } + + if p := must[watcherItem](t, cs, "pause_watcher", map[string]any{"watcher_id": w.ID}); !p.Paused || p.State != "paused" { + t.Errorf("pause_watcher: %+v", p) + } + if r := must[watcherItem](t, cs, "resume_watcher", map[string]any{"watcher_id": w.ID}); r.Paused { + t.Errorf("resume_watcher: %+v", r) + } + if err := os.WriteFile(filepath.Join(b, "back.txt"), []byte("the other way"), 0o600); err != nil { + t.Fatal(err) + } + must[watcherItem](t, cs, "sync_watcher_now", map[string]any{"watcher_id": w.ID}) + testutil.Eventually(t, time.Minute, "a file from folder B", func() bool { + got, err := os.ReadFile(filepath.Join(a, "back.txt")) + return err == nil && string(got) == "the other way" + }) + + if got := must[removed](t, cs, "delete_watcher", map[string]any{"watcher_id": w.ID}); got.Deleted != "Notes on box" { + t.Errorf("delete_watcher: %+v", got) + } + if _, failed := call[watcherItem](t, cs, "sync_watcher_now", map[string]any{"watcher_id": w.ID}); !strings.Contains(failed, "no longer exists") { + t.Errorf("syncing a deleted watcher: %q", failed) + } + if _, err := os.Stat(filepath.Join(a, "note.txt")); err != nil { + t.Errorf("the folder lost its file when the watcher was deleted: %v", err) + } +} diff --git a/core/agents/bridge.go b/core/agents/bridge.go new file mode 100644 index 00000000..d627047e --- /dev/null +++ b/core/agents/bridge.go @@ -0,0 +1,164 @@ +package agents + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/datadir" +) + +// startWait is how long Bridge waits for the app to start and its server to listen. +const startWait = 30 * time.Second + +// Bridge is `rcui mcp`: it connects an agent that talks MCP over its standard input and output +// to the app's server, which talks MCP over HTTP. A client that can only start a command (Claude +// Desktop, for one) uses it. It takes no token: it reads the server's address and token from the +// app's data folder (datadir.AgentsFile), which only the user can read. +// +// When the app isn't running, Bridge starts it, hidden, and waits for its server. When the app +// runs with the server turned off, Bridge says how to turn it on, and exits. +// +// It returns the process's exit code. Its only output on stdout is the protocol's, so what it has +// to say goes to stderr, where MCP clients show or log it. +func Bridge(args []string, stdin io.ReadCloser, stdout io.WriteCloser, stderr io.Writer) int { + fs := flag.NewFlagSet("rcui mcp", flag.ContinueOnError) + fs.SetOutput(stderr) + dir := fs.String("data-dir", "", "the app's data directory (default: the app's own)") + if err := fs.Parse(args); err != nil { + return 2 + } + if *dir == "" { + d, err := datadir.Default() + if err != nil { + fmt.Fprintln(stderr, "rcui mcp: the data folder can't be found:", err) + return 1 + } + *dir = d + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + found, err := find(ctx, *dir, args) + if err != nil { + fmt.Fprintln(stderr, "rcui mcp:", err) + return 1 + } + if err := relay(ctx, found, &mcp.IOTransport{Reader: stdin, Writer: stdout}); err != nil { + fmt.Fprintln(stderr, "rcui mcp:", err) + return 1 + } + return 0 +} + +// find returns where the app's server listens. When the file that names it is missing, or names +// a server that no longer answers (the app crashed), it starts the app and waits for the server. +func find(ctx context.Context, dir string, args []string) (Found, error) { + if f, err := readFound(dir); err == nil && answers(ctx, f) { + return f, nil + } + if err := startApp(args); err != nil { + return Found{}, fmt.Errorf("Rclone UI isn't running, and couldn't be started: %w", err) + } + deadline := time.Now().Add(startWait) + for time.Now().Before(deadline) { + if f, err := readFound(dir); err == nil && answers(ctx, f) { + return f, nil + } + select { + case <-ctx.Done(): + return Found{}, ctx.Err() + case <-time.After(300 * time.Millisecond): + } + } + return Found{}, errors.New("Rclone UI isn't letting agents in. Open its Settings, and under Agents turn on \"Let AI agents use Rclone UI\"") +} + +// answers reports whether the server that f names is there: the app that wrote the file may have +// crashed since. +func answers(ctx context.Context, f Found) bool { + ctx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, f.URL, nil) + if err != nil { + return false + } + // Without the token the server answers 401, which is enough to know that it is there. + res, err := http.DefaultClient.Do(req) + if err != nil { + return false + } + _ = res.Body.Close() + return true +} + +// startApp starts the app without its startup window, on the same data folder. If the app is +// running after all, the launch ends at once and shows nothing (see the app's secondInstance). +func startApp(args []string) error { + exe, err := os.Executable() + if err != nil { + return err + } + // args are Bridge's own, which hold at most --data-dir, a flag that the app takes too. + cmd := exec.Command(exe, append([]string{"ui", "--hidden"}, args...)...) + detach(cmd) + if err := cmd.Start(); err != nil { + return err + } + // The app outlives this process, so nothing waits for it. + return cmd.Process.Release() +} + +type withToken struct{ token string } + +func (t withToken) RoundTrip(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + r.Header.Set("Authorization", "Bearer "+t.token) + return http.DefaultTransport.RoundTrip(r) +} + +// relay passes every message from the agent to the server and every message from the server to +// the agent, as they are, until either side closes. The agent's own name and its handshake reach +// the server unchanged, so the server sees the agent, not the bridge. +func relay(ctx context.Context, f Found, agent mcp.Transport) error { + server := &mcp.StreamableClientTransport{Endpoint: f.URL, HTTPClient: &http.Client{Transport: withToken{f.Token}}} + down, err := agent.Connect(ctx) + if err != nil { + return err + } + defer down.Close() + up, err := server.Connect(ctx) + if err != nil { + return err + } + defer up.Close() + ctx, cancel := context.WithCancel(ctx) + defer cancel() + pump := func(from, to mcp.Connection) error { + for { + msg, err := from.Read(ctx) + if err != nil { + return err + } + if err := to.Write(ctx, msg); err != nil { + return err + } + } + } + errs := make(chan error, 2) + go func() { errs <- pump(down, up) }() + go func() { errs <- pump(up, down) }() + err = <-errs + // The agent closing its side is how a session ends. + if errors.Is(err, io.EOF) || errors.Is(err, context.Canceled) { + return nil + } + return err +} diff --git a/core/agents/detach_unix.go b/core/agents/detach_unix.go new file mode 100644 index 00000000..91e29852 --- /dev/null +++ b/core/agents/detach_unix.go @@ -0,0 +1,14 @@ +//go:build !windows + +package agents + +import ( + "os/exec" + "syscall" +) + +// detach makes cmd outlive the process that starts it: it gets a session of its own, so the +// agent's client closing the bridge doesn't close the app. +func detach(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} +} diff --git a/core/agents/detach_windows.go b/core/agents/detach_windows.go new file mode 100644 index 00000000..d5b1e9a0 --- /dev/null +++ b/core/agents/detach_windows.go @@ -0,0 +1,14 @@ +package agents + +import ( + "os/exec" + "syscall" + + "golang.org/x/sys/windows" +) + +// detach makes cmd outlive the process that starts it: it gets a process group of its own and no +// console, so the agent's client closing the bridge doesn't close the app. +func detach(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.DETACHED_PROCESS} +} diff --git a/core/agents/files.go b/core/agents/files.go new file mode 100644 index 00000000..a083be33 --- /dev/null +++ b/core/agents/files.go @@ -0,0 +1,641 @@ +package agents + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "time" + "unicode/utf8" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/browse" + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/operations" +) + +// fileTools registers the tools that look at files and folders, and make small changes to them. +// Deleting is a transfer, in transfers.go. +func (s *Server) fileTools() { + s.listFilesTool() + s.searchFilesTool() + s.folderSizeTool() + s.compareFoldersTool() + s.publicLinkTool() + s.readFileTool() + s.makeFolderTool() + s.renameTool() + s.listOptionsTool() +} + +// filesLimit is how many entries a list returns when the agent gives no limit. filesLimitMax is +// the most that an agent can ask for. +const ( + filesLimit = 200 + filesLimitMax = 1000 +) + +func filesCap(limit int) int { + if limit <= 0 { + return filesLimit + } + return min(limit, filesLimitMax) +} + +// walkFor is how long a search or a folder's count runs before it stops and returns what it has +// found, so that a huge remote can't hold the agent for minutes. A test shortens it. +var walkFor = 30 * time.Second + +type filePathIn struct { + Path string `json:"path" jsonschema:"a remote path such as \"gdrive:Photos/2024\", or an absolute local path"` +} + +type fileEntry struct { + Name string `json:"name"` + // Path is the entry's full path, which the other tools take as it is. + Path string `json:"path"` + IsFolder bool `json:"is_folder"` + // Size is a file's size in bytes. A folder has none, and neither has a file whose remote + // doesn't know it. + Size *int64 `json:"size,omitempty"` + Modified string `json:"modified,omitempty"` +} + +func fileEntryOf(r browse.Row) fileEntry { + return fileEntry{Name: r.Name, Path: r.Path, IsFolder: r.IsDir, Size: fileSize(r.IsDir, r.Size), Modified: fileTime(r.ModTime)} +} + +// fileSize returns a file's size, or nil for a folder or a size that the remote doesn't know (-1). +func fileSize(isDir bool, size int64) *int64 { + if isDir || size < 0 { + return nil + } + return &size +} + +// fileTime returns a row's time as RFC 3339 to the second, which is all that an agent needs. +// It is "" when the remote gave no time: a file on S3, Swift and the other backends where +// reading it costs a request per file. +func fileTime(t string) string { + parsed, err := time.Parse(time.RFC3339Nano, t) + if err != nil { + return t + } + return parsed.Format(time.RFC3339) +} + +type listFilesIn struct { + Path string `json:"path" jsonschema:"the folder to list: \"gdrive:Photos\", \"gdrive:\" for a remote's root, or a local folder such as \"/Users/me/Documents\""` + Limit int `json:"limit,omitempty" jsonschema:"the most entries to return: 200 when not given, and at most 1000"` +} + +type listFilesOut struct { + Path string `json:"path"` + Entries []fileEntry `json:"entries"` + // Total is how many entries the folder has. A folder with more than browse.ListMax is + // counted up to there. + Total int `json:"total"` + Truncated bool `json:"truncated,omitempty"` + Note string `json:"note,omitempty"` +} + +func (s *Server) listFilesTool() { + add(s, &mcp.Tool{ + Name: "list_files", + Description: "Lists the files and folders directly inside one folder (not the ones below them). Each entry has its name, its full path, " + + "whether it is a folder, a file's size in bytes, and its modification time when the remote reports it cheaply (S3 and Swift don't for files). " + + "Folders come first, then by name. total counts every entry, and truncated says the limit cut the list: raise the limit, or use search_files.", + Annotations: reads("List files"), + }, func(ctx context.Context, in listFilesIn) (listFilesOut, error) { + rows, capped, err := s.o.APIs.ListRows(ctx, in.Path) + if err != nil { + return listFilesOut{}, err + } + slices.SortFunc(rows, func(a, b browse.Row) int { + if a.IsDir != b.IsDir { + if a.IsDir { + return -1 + } + return 1 + } + return browse.CompareNames(a.Name, b.Name) + }) + limit := filesCap(in.Limit) + out := listFilesOut{Path: in.Path, Entries: []fileEntry{}, Total: len(rows), Truncated: len(rows) > limit} + for _, r := range rows[:min(len(rows), limit)] { + out.Entries = append(out.Entries, fileEntryOf(r)) + } + switch { + case capped: + out.Note = fmt.Sprintf("The folder has more than %d entries, so only the first %d were read. Use search_files to find names in it.", browse.ListMax, len(rows)) + case out.Truncated: + out.Note = fmt.Sprintf("These are the first %d of %d entries. Ask with a larger limit (at most %d), or use search_files to find names.", limit, len(rows), filesLimitMax) + } + return out, nil + }) +} + +type searchFilesIn struct { + Path string `json:"path" jsonschema:"the folder to search, with everything below it: \"gdrive:Photos\", \"gdrive:\" or \"/Users/me\""` + Query string `json:"query" jsonschema:"a part of the names to find, ignoring case, such as \"invoice\" or \".pdf\""` + Limit int `json:"limit,omitempty" jsonschema:"the most matches to return: 200 when not given, and at most 1000"` +} + +type searchFilesOut struct { + Path string `json:"path"` + Query string `json:"query"` + Matches []fileEntry `json:"matches"` + // Truncated is true when there are more matches than the limit. + Truncated bool `json:"truncated,omitempty"` + // StoppedEarly is true when the search didn't read the whole folder, so there may be more + // matches. + StoppedEarly bool `json:"stopped_early,omitempty"` + Note string `json:"note,omitempty"` +} + +func (s *Server) searchFilesTool() { + add(s, &mcp.Tool{ + Name: "search_files", + Description: "Finds the files and folders below a folder, at any depth, whose name contains the query, ignoring case. " + + "Names that start with a dot, and everything inside such folders, are left out. Each match has its full path. " + + fmt.Sprintf("The search stops after %d seconds on a large remote: stopped_early then says that there may be more matches, so search a smaller folder. ", int(walkFor.Seconds())) + + "truncated says that there were more matches than the limit.", + Annotations: reads("Search files"), + }, func(ctx context.Context, in searchFilesIn) (searchFilesOut, error) { + limit := filesCap(in.Limit) + bounded, cancel := context.WithTimeout(ctx, walkFor) + defer cancel() + // One match more than the limit tells whether there are more. + rows, _, err := s.o.APIs.SearchRows(bounded, in.Path, in.Query, limit+1) + out := searchFilesOut{Path: in.Path, Query: in.Query, Matches: []fileEntry{}} + switch { + case errors.Is(err, browse.ErrWalkMax): + out.StoppedEarly = true + out.Note = fmt.Sprintf("The search read %d entries and stopped, so there may be more matches. Search a smaller folder.", browse.SearchWalkMax) + case err != nil && bounded.Err() != nil && ctx.Err() == nil: + out.StoppedEarly = true + out.Note = fmt.Sprintf("The search stopped after %s, before it read the whole folder, so there may be more matches. Search a smaller folder.", walkFor) + case err != nil: + return searchFilesOut{}, err + } + slices.SortFunc(rows, func(a, b browse.Row) int { return browse.CompareNames(a.Path, b.Path) }) + out.Truncated = len(rows) > limit + for _, r := range rows[:min(len(rows), limit)] { + out.Matches = append(out.Matches, fileEntryOf(r)) + } + if out.Truncated { + out.Note = strings.TrimSpace(fmt.Sprintf("There are more than %d matches. Ask with a larger limit (at most %d), or a more precise query. %s", limit, filesLimitMax, out.Note)) + } + return out, nil + }) +} + +type folderSizeOut struct { + Path string `json:"path"` + Files int64 `json:"files"` + Bytes int64 `json:"bytes"` + // Complete is false when the count stopped before the end, so the folder holds more. + Complete bool `json:"complete"` + Note string `json:"note,omitempty"` +} + +func (s *Server) folderSizeTool() { + add(s, &mcp.Tool{ + Name: "folder_size", + Description: "Counts the files in a folder and everything below it, and their total size in bytes. " + + fmt.Sprintf("On a large remote the count stops after %d seconds: complete is then false, and the numbers are what it counted so far.", int(walkFor.Seconds())), + Annotations: reads("Folder size"), + }, func(ctx context.Context, in filePathIn) (folderSizeOut, error) { + bounded, cancel := context.WithTimeout(ctx, walkFor) + defer cancel() + size, err := s.o.APIs.CountFolder(bounded, in.Path) + out := folderSizeOut{Path: in.Path, Files: size.Files, Bytes: size.Bytes, Complete: err == nil} + switch { + case err != nil && bounded.Err() != nil && ctx.Err() == nil: + out.Note = fmt.Sprintf("The count stopped after %s, so the folder holds more than this.", walkFor) + case err != nil: + return folderSizeOut{}, err + } + return out, nil + }) +} + +type compareFoldersIn struct { + Left string `json:"left" jsonschema:"one folder, such as \"/Users/me/Photos\""` + Right string `json:"right" jsonschema:"the other folder, such as \"gdrive:Photos\""` + Limit int `json:"limit,omitempty" jsonschema:"the most names in each list: 200 when not given, and at most 1000"` +} + +// comparedEntry is a name that only one side of a comparison has. +type comparedEntry struct { + Name string `json:"name"` + IsFolder bool `json:"is_folder"` + Size *int64 `json:"size,omitempty"` +} + +// comparedPair is a name that both sides of a comparison have, with what each side holds. +type comparedPair struct { + Name string `json:"name"` + LeftIsFolder bool `json:"left_is_folder,omitempty"` + RightIsFolder bool `json:"right_is_folder,omitempty"` + LeftSize *int64 `json:"left_size,omitempty"` + RightSize *int64 `json:"right_size,omitempty"` + LeftModified string `json:"left_modified,omitempty"` + RightModified string `json:"right_modified,omitempty"` +} + +type comparedCounts struct { + OnlyLeft int `json:"only_left"` + OnlyRight int `json:"only_right"` + Different int `json:"different"` + Same int `json:"same"` + FoldersInBoth int `json:"folders_in_both"` +} + +type compareFoldersOut struct { + Left string `json:"left"` + Right string `json:"right"` + Counts comparedCounts `json:"counts"` + OnlyLeft []comparedEntry `json:"only_left"` + OnlyRight []comparedEntry `json:"only_right"` + Different []comparedPair `json:"different"` + // Truncated is true when a list holds fewer names than its count. + Truncated bool `json:"truncated,omitempty"` + // StoppedEarly is true when a folder held more names than the comparison reads. + StoppedEarly bool `json:"stopped_early,omitempty"` + Note string `json:"note,omitempty"` +} + +func (s *Server) compareFoldersTool() { + add(s, &mcp.Tool{ + Name: "compare_folders", + Description: "Compares the names directly inside two folders, one level deep: what is only on the left, only on the right, and different. " + + "A file is the same when both sides have the same hash, and different when the sizes or the hashes differ, when the two remotes share no hash type to check, " + + "or when one side is a folder. Folders on both sides are only counted, not compared inside: compare them in turn. " + + "Names that start with a dot are left out. The counts cover every name; the lists stop at the limit (truncated).", + Annotations: reads("Compare folders"), + }, func(ctx context.Context, in compareFoldersIn) (compareFoldersOut, error) { + res, err := s.o.APIs.Browse.Compare(ctx, in.Left, in.Right, false) + if err != nil { + return compareFoldersOut{}, err + } + limit := filesCap(in.Limit) + out := compareFoldersOut{ + Left: in.Left, Right: in.Right, StoppedEarly: res.Capped, + OnlyLeft: []comparedEntry{}, OnlyRight: []comparedEntry{}, Different: []comparedPair{}, + } + for _, p := range res.Pairs { + switch { + case p.Class == browse.OnlyLeft: + out.Counts.OnlyLeft++ + if len(out.OnlyLeft) < limit { + out.OnlyLeft = append(out.OnlyLeft, comparedEntry{Name: p.Name, IsFolder: p.Left.IsDir, Size: fileSize(p.Left.IsDir, p.Left.Size)}) + } + case p.Class == browse.OnlyRight: + out.Counts.OnlyRight++ + if len(out.OnlyRight) < limit { + out.OnlyRight = append(out.OnlyRight, comparedEntry{Name: p.Name, IsFolder: p.Right.IsDir, Size: fileSize(p.Right.IsDir, p.Right.Size)}) + } + case p.Class == browse.SameByHash: + out.Counts.Same++ + case p.Left.IsDir && p.Right.IsDir: + out.Counts.FoldersInBoth++ + default: + out.Counts.Different++ + if len(out.Different) < limit { + out.Different = append(out.Different, comparedPair{ + Name: p.Name, LeftIsFolder: p.Left.IsDir, RightIsFolder: p.Right.IsDir, + LeftSize: fileSize(p.Left.IsDir, p.Left.Size), RightSize: fileSize(p.Right.IsDir, p.Right.Size), + LeftModified: fileTime(p.Left.ModTime), RightModified: fileTime(p.Right.ModTime), + }) + } + } + } + c := out.Counts + out.Truncated = c.OnlyLeft > len(out.OnlyLeft) || c.OnlyRight > len(out.OnlyRight) || c.Different > len(out.Different) + switch { + case out.StoppedEarly: + out.Note = fmt.Sprintf("A folder holds more than %d names, so only that many were compared on each side, and some names may be in the wrong list.", browse.CompareMax) + case out.Truncated: + out.Note = fmt.Sprintf("A list stops at %d names. Ask with a larger limit (at most %d).", limit, filesLimitMax) + } + return out, nil + }) +} + +type publicLinkOut struct { + Path string `json:"path"` + Link string `json:"link"` +} + +// publicLinkTool registers get_public_link. Making a link can share the file on the remote, so +// the tool isn't read-only. +func (s *Server) publicLinkTool() { + add(s, &mcp.Tool{ + Name: "get_public_link", + Description: "Makes a public link to a file or folder, on remotes that can make one (such as Google Drive, Dropbox, OneDrive, Box and pCloud), and returns it. " + + "Anyone who has the link can open the file, so share it only as the user asked. Fails on remotes that can't, such as a local disk.", + Annotations: changes("Get a public link"), + }, func(ctx context.Context, in filePathIn) (publicLinkOut, error) { + link, err := s.o.APIs.Browse.PublicLink(ctx, in.Path) + if err != nil { + return publicLinkOut{}, err + } + return publicLinkOut{Path: in.Path, Link: link}, nil + }) +} + +// readMax is the most bytes of a file that read_file returns, and what it returns unless the +// agent asks for fewer. +const readMax = 256 << 10 + +type readFileIn struct { + Path string `json:"path" jsonschema:"the file to read, such as \"gdrive:Notes/todo.md\" or \"/Users/me/notes.txt\""` + MaxBytes int `json:"max_bytes,omitempty" jsonschema:"the most bytes to return: 262144 (256 KiB) when not given, which is also the most"` +} + +type readFileOut struct { + Path string `json:"path"` + Text string `json:"text"` + // Size is the whole file's size in bytes, when the remote knows it. + Size *int64 `json:"size,omitempty"` + Modified string `json:"modified,omitempty"` + // Truncated is true when Text is only the start of the file. + Truncated bool `json:"truncated,omitempty"` +} + +func (s *Server) readFileTool() { + add(s, &mcp.Tool{ + Name: "read_file", + Description: "Returns the text of a small text file, such as a note, a config file or a log. " + + "It reads at most max_bytes (256 KiB when not given, which is also the most): a larger file comes back as its start, with truncated set. " + + "A file that isn't text (not valid UTF-8, or it holds NUL bytes) is refused.", + Annotations: reads("Read a file"), + }, func(ctx context.Context, in readFileIn) (readFileOut, error) { + limit := readMax + if in.MaxBytes > 0 { + limit = min(in.MaxBytes, readMax) + } + start, err := s.o.APIs.ReadFile(ctx, in.Path, int64(limit)) + if err != nil { + return readFileOut{}, err + } + data := start.Data + if !start.Whole { + data = withoutCutRune(data) + } + if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) { + return readFileOut{}, errs.New("This file isn't text (it isn't valid UTF-8, or it holds NUL bytes), and read_file reads only text. Copy it to a local folder to open it with a program that reads its type.") + } + out := readFileOut{Path: in.Path, Text: string(data), Size: fileSize(false, start.Size), Truncated: !start.Whole} + if !start.ModTime.IsZero() { + out.Modified = start.ModTime.Format(time.RFC3339) + } + return out, nil + }) +} + +// withoutCutRune drops the bytes at the end of data that start a character which the read cut +// off, so that the start of a longer file is still valid UTF-8. +func withoutCutRune(data []byte) []byte { + for i := len(data) - 1; i >= 0 && i >= len(data)-utf8.UTFMax; i-- { + if utf8.RuneStart(data[i]) { + if !utf8.FullRune(data[i:]) { + return data[:i] + } + break + } + } + return data +} + +type madeFolder struct { + Path string `json:"path"` +} + +func (s *Server) makeFolderTool() { + add(s, &mcp.Tool{ + Name: "make_folder", + Description: "Creates a folder at the path. It fails when something with that name is already there. " + + "On a remote that can't hold an empty folder (S3 and the other bucket stores), it puts an empty .empty file inside, so that the folder exists.", + Annotations: changes("Make a folder"), + }, func(ctx context.Context, in filePathIn) (madeFolder, error) { + if err := s.o.APIs.Files.Mkdir(ctx, in.Path); err != nil { + return madeFolder{}, err + } + return madeFolder{Path: in.Path}, nil + }) +} + +type renameIn struct { + Path string `json:"path" jsonschema:"the file or folder to rename, such as \"gdrive:Photos/old.jpg\""` + NewName string `json:"new_name" jsonschema:"the new name alone, without a folder, such as \"new.jpg\": the entry stays in its folder"` +} + +type renamed struct { + // Path is the entry's new path. + Path string `json:"path"` + // TransferID is the transfer that renames a folder, in the background. + TransferID string `json:"transfer_id,omitempty"` + Note string `json:"note,omitempty"` +} + +// renameTool registers rename. It finds out whether the path is a folder, which the Commander +// knows from its listing, so that the agent needn't say. +func (s *Server) renameTool() { + add(s, &mcp.Tool{ + Name: "rename", + Description: "Renames a file or folder, which stays in its folder. It refuses a name that is taken, so it never overwrites. " + + "A file is renamed at once. A folder is renamed by a transfer in the background, because some remotes move each file: " + + "it returns the transfer's id, so follow it with wait_for_transfer. Whatever pointed to the old name, such as a link or another program's setting, stops working.", + Annotations: destroys("Rename a file or folder"), + }, func(ctx context.Context, in renameIn) (renamed, error) { + folder, err := s.o.APIs.Files.IsFolder(ctx, in.Path) + if err != nil { + return renamed{}, err + } + res, err := s.o.APIs.Files.Rename(ctx, in.Path, folder, in.NewName) + if err != nil { + return renamed{}, err + } + out := renamed{Path: res.Path, TransferID: res.TransferID} + if res.TransferID != "" { + out.Note = "The folder is being renamed in the background. Follow the transfer with wait_for_transfer." + } + return out, nil + }) +} + +// optionOperations are the operations whose options list_options lists. +var optionOperations = []operations.Operation{ + operations.OperationCopy, operations.OperationMove, operations.OperationSync, operations.OperationBisync, + operations.OperationDelete, operations.OperationPurge, operations.OperationDownload, + operations.OperationMount, operations.OperationServe, +} + +type listOptionsIn struct { + Operation string `json:"operation" jsonschema:"copy, move, sync, bisync, delete, purge, download, mount or serve"` + ServeType string `json:"serve_type,omitempty" jsonschema:"for serve only: the serve's type, such as http or webdav. Without it, every type's options are listed"` + Search string `json:"search,omitempty" jsonschema:"only the options whose name or help contains this, ignoring case, such as \"age\" or \"bandwidth\""` +} + +type optionInfo struct { + Name string `json:"name"` + Type string `json:"type"` + // Default is the value that a run takes when the option isn't given: the app's own default + // where it has one, and rclone's otherwise. + Default string `json:"default,omitempty"` + // Choices are the values that a choice or flags option takes. + Choices []string `json:"choices,omitempty"` + // Help is the first sentence of rclone's help. + Help string `json:"help"` +} + +// optionSection is one group of an operation's options, as its window shows them. +type optionSection struct { + Name string `json:"name"` + Options []optionInfo `json:"options"` +} + +type optionsListed struct { + Operation string `json:"operation"` + Groups []optionSection `json:"groups"` +} + +// listOptionsTool registers list_options. Its groups are those of the operation's form +// (operations.FormSections), the same groups that optionGroupsFor sorts an agent's flat options +// into. The options and their help are rclone's English, whatever the app's language. +func (s *Server) listOptionsTool() { + add(s, &mcp.Tool{ + Name: "list_options", + Description: "Lists the rclone options that an operation takes, grouped as its window shows them: each option's name, its type, its default and a line of help. " + + "Pass options to the other tools by these names, flat, whatever their group. " + + "Types: bool, int, float, size (\"64M\"), duration (\"30s\", \"1h\"), time, text, list (a JSON array of strings), choice (one of choices), flags (choices joined by commas), tristate (true, false or unset). " + + "The config group also takes rclone's other per-run options that no window lists, such as max_depth. Use search to narrow the list.", + Annotations: reads("List rclone options"), + }, func(ctx context.Context, in listOptionsIn) (optionsListed, error) { + op := operations.Operation(in.Operation) + if !slices.Contains(optionOperations, op) { + return optionsListed{}, errs.New("operation must be one of copy, move, sync, bisync, delete, purge, download, mount or serve.") + } + cat, err := s.o.APIs.Catalog.English(ctx) + if err != nil { + return optionsListed{}, err + } + serve := "" + if op == operations.OperationServe && in.ServeType != "" { + serve = in.ServeType + if !slices.ContainsFunc(cat.Groups, func(g catalog.Section) bool { return g.Name == "serve."+serve }) { + var types []string + for _, g := range cat.Groups { + if t, ok := strings.CutPrefix(g.Name, "serve."); ok { + types = append(types, t) + } + } + return optionsListed{}, errs.Errorf("serve_type must be one of %s.", strings.Join(types, ", ")) + } + } + // FormSections returns nothing for a download, because no template can be for one. Like a + // purge, a download reads only its config group. + sections := []operations.FormSection{{Group: operations.GroupConfig, Catalog: []string{operations.GroupConfig}}} + if op != operations.OperationDownload { + sections = operations.FormSections(op, serve) + } + return optionsListed{Operation: in.Operation, Groups: optionSections(cat, op, sections, in.Search)}, nil + }) +} + +// optionSections describes the options of each group of op's form, from the catalog. An option +// that two of a group's catalog groups list (copy and sync list many of the same) is described +// once. Hidden options are left out, and so are those that search doesn't match. A group left +// without options is left out too. +func optionSections(cat catalog.Catalog, op operations.Operation, sections []operations.FormSection, search string) []optionSection { + blocks := map[string]map[string]*catalog.Option{} + for i := range cat.Blocks { + b := &cat.Blocks[i] + blocks[b.Name] = map[string]*catalog.Option{} + for j := range b.Options { + blocks[b.Name][b.Options[j].Name] = &b.Options[j] + } + } + refs := map[string][]catalog.OptionRef{} + for _, g := range cat.Groups { + refs[g.Name] = g.Options + } + term := strings.ToLower(strings.TrimSpace(search)) + named := catalog.NormalizeOptionName(term) + defaults := cat.Defaults[string(op)] + if op == operations.OperationServe { + defaults = cat.Defaults["serve"] + } + out := []optionSection{} + for _, sec := range sections { + seen := map[string]bool{} + group := optionSection{Name: sec.Group, Options: []optionInfo{}} + for _, from := range sec.Catalog { + for _, ref := range refs[from] { + o := blocks[ref.Block][ref.Name] + if o == nil || o.Hidden || seen[o.Name] { + continue + } + if term != "" && !strings.Contains(o.Name, named) && !strings.Contains(strings.ToLower(o.Help), term) { + continue + } + seen[o.Name] = true + group.Options = append(group.Options, optionInfoOf(o, defaults[sec.Group][o.Name])) + } + } + if len(group.Options) == 0 { + continue + } + slices.SortFunc(group.Options, func(a, b optionInfo) int { return strings.Compare(a.Name, b.Name) }) + out = append(out, group) + } + return out +} + +// optionInfoOf describes an option. appDefault is the app's default for it, as JSON, or nil when +// the app keeps rclone's. +func optionInfoOf(o *catalog.Option, appDefault json.RawMessage) optionInfo { + info := optionInfo{Name: o.Name, Type: string(o.Kind), Default: o.DefaultText, Help: firstSentence(o.Help)} + if appDefault != nil { + var text string + if json.Unmarshal(appDefault, &text) == nil { + info.Default = text + } else { + info.Default = string(appDefault) + } + } + // Only a closed set's choices are listed. The other options' choices are suggestions, such + // as common sizes, which the type already explains. + if o.Kind == catalog.KindChoice || o.Kind == catalog.KindFlags { + for _, c := range o.Choices { + info.Choices = append(info.Choices, c.Value) + } + } + return info +} + +// firstSentence returns the first sentence of rclone's help, or its first line when that ends +// first. Some help runs to several paragraphs, which would make list_options long. +func firstSentence(help string) string { + line, _, _ := strings.Cut(strings.TrimSpace(help), "\n") + line = strings.TrimSpace(line) + for from := 0; ; { + i := strings.Index(line[from:], ". ") + if i < 0 { + return line + } + end := from + i + 1 + // An abbreviation's dot doesn't end the sentence. + if word := strings.ToLower(line[max(0, end-4):end]); !strings.HasSuffix(word, "e.g.") && !strings.HasSuffix(word, "i.e.") && !strings.HasSuffix(word, "etc.") { + return line[:end] + } + from = end + } +} diff --git a/core/agents/files_test.go b/core/agents/files_test.go new file mode 100644 index 00000000..832ea2cb --- /dev/null +++ b/core/agents/files_test.go @@ -0,0 +1,379 @@ +package agents + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/transfers" +) + +// fileTree writes files under a new temporary folder and returns its real path. files maps a +// slash-separated path to its content, and a path that ends in / is an empty folder. +func fileTree(t *testing.T, files map[string]string) string { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + for name, body := range files { + p := filepath.Join(root, filepath.FromSlash(name)) + if strings.HasSuffix(name, "/") { + if err := os.MkdirAll(p, 0o755); err != nil { + t.Fatal(err) + } + continue + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +// onBox returns a local path as a path on the tests' remote, box. +func onBox(p string) string { return "box:" + filepath.ToSlash(p) } + +// entryNames returns the names of entries, in their order. +func entryNames(entries []fileEntry) []string { + out := make([]string, len(entries)) + for i, e := range entries { + out[i] = e.Name + } + return out +} + +// shortWalks makes searches and counts stop at once, until the test ends. +func shortWalks(t *testing.T) { + was := walkFor + walkFor = time.Nanosecond + t.Cleanup(func() { walkFor = was }) +} + +// A folder's entries come folders first, then by name, each with its full path, and the list +// stops at the limit. +func TestListFiles(t *testing.T) { + cs := connect(t) + root := fileTree(t, map[string]string{"b.txt": "bb", "A.txt": "a", "c/": "", "B/": "", ".hidden": "h"}) + out := must[listFilesOut](t, cs, "list_files", map[string]any{"path": onBox(root)}) + if want := []string{"B", "c", ".hidden", "A.txt", "b.txt"}; !slices.Equal(entryNames(out.Entries), want) || out.Total != 5 || out.Truncated { + t.Fatalf("entries %q (total %d), want %q", entryNames(out.Entries), out.Total, want) + } + folder, file := out.Entries[0], out.Entries[3] + if !folder.IsFolder || folder.Size != nil || folder.Path != onBox(root)+"/B" { + t.Errorf("a folder: %+v", folder) + } + if _, err := time.Parse(time.RFC3339, file.Modified); file.IsFolder || file.Size == nil || *file.Size != 1 || err != nil { + t.Errorf("a file: %+v", file) + } + + // The listing is read again each time, so a file that the agent wrote by other means shows + // at once. + if err := os.WriteFile(filepath.Join(root, "d.txt"), nil, 0o644); err != nil { + t.Fatal(err) + } + out = must[listFilesOut](t, cs, "list_files", map[string]any{"path": onBox(root), "limit": 2}) + if len(out.Entries) != 2 || out.Total != 6 || !out.Truncated || out.Note == "" { + t.Errorf("at most two, after a new file: %+v", out) + } + // A local path's entries have local paths. + out = must[listFilesOut](t, cs, "list_files", map[string]any{"path": root}) + if out.Total != 6 || out.Entries[0].Path != filepath.Join(root, "B") { + t.Errorf("a local folder: %+v", out) + } + + for _, p := range []string{filepath.Join(root, "missing"), filepath.Join(root, "A.txt"), "relative/folder", ""} { + if _, failed := call[listFilesOut](t, cs, "list_files", map[string]any{"path": p}); failed == "" { + t.Errorf("%q was listed", p) + } + } +} + +// A search finds names at any depth, ignoring case and what starts with a dot, and stops at the +// limit or when its time is up. +func TestSearchFiles(t *testing.T) { + cs := connect(t) + root := fileTree(t, map[string]string{ + "docs/Report.txt": "1", "docs/old/report-2023.md": "2", "notes.txt": "3", ".git/report": "4", "reports/": "", + }) + out := must[searchFilesOut](t, cs, "search_files", map[string]any{"path": onBox(root), "query": "REPORT"}) + var paths []string + for _, m := range out.Matches { + paths = append(paths, m.Path) + } + want := []string{onBox(root) + "/docs/old/report-2023.md", onBox(root) + "/docs/Report.txt", onBox(root) + "/reports"} + if !slices.Equal(paths, want) || out.Truncated || out.StoppedEarly { + t.Fatalf("matches %q, want %q: %+v", paths, want, out) + } + if !out.Matches[2].IsFolder || out.Matches[1].Size == nil { + t.Errorf("matches %+v", out.Matches) + } + + out = must[searchFilesOut](t, cs, "search_files", map[string]any{"path": root, "query": "report", "limit": 1}) + if len(out.Matches) != 1 || !out.Truncated || out.Note == "" { + t.Errorf("at most one: %+v", out) + } + if _, failed := call[searchFilesOut](t, cs, "search_files", map[string]any{"path": root, "query": ""}); failed == "" { + t.Error("an empty query was searched") + } + + shortWalks(t) + out = must[searchFilesOut](t, cs, "search_files", map[string]any{"path": root, "query": "report"}) + if !out.StoppedEarly || !strings.Contains(out.Note, "stopped") { + t.Errorf("a search out of time: %+v", out) + } +} + +// A folder's size counts everything below it, and says when the count stopped early. +func TestFolderSize(t *testing.T) { + cs := connect(t) + root := fileTree(t, map[string]string{"a/one": "1", "a/sub/two": "22", "b/": ""}) + out := must[folderSizeOut](t, cs, "folder_size", map[string]any{"path": onBox(filepath.Join(root, "a"))}) + if out.Files != 2 || out.Bytes != 3 || !out.Complete || out.Note != "" { + t.Errorf("a folder: %+v", out) + } + if _, failed := call[folderSizeOut](t, cs, "folder_size", map[string]any{"path": filepath.Join(root, "missing")}); failed == "" { + t.Error("a missing folder was counted") + } + shortWalks(t) + if out := must[folderSizeOut](t, cs, "folder_size", map[string]any{"path": root}); out.Complete || out.Note == "" { + t.Errorf("a count out of time: %+v", out) + } +} + +// Two folders compare one level deep, with counts for every class and lists that stop at the +// limit. +func TestCompareFolders(t *testing.T) { + cs := connect(t) + left := fileTree(t, map[string]string{"same.txt": "x", "diff.txt": "aaa", "mine.txt": "l", "both/": "", "lonely/": "", "kind": "a file"}) + right := fileTree(t, map[string]string{"same.txt": "x", "diff.txt": "bbbb", "theirs.txt": "r", "both/": "", "kind/": ""}) + out := must[compareFoldersOut](t, cs, "compare_folders", map[string]any{"left": left, "right": onBox(right)}) + if want := (comparedCounts{OnlyLeft: 2, OnlyRight: 1, Different: 2, Same: 1, FoldersInBoth: 1}); out.Counts != want { + t.Fatalf("counts %+v, want %+v", out.Counts, want) + } + if len(out.OnlyLeft) != 2 || !out.OnlyLeft[0].IsFolder || out.OnlyLeft[0].Name != "lonely" || out.OnlyRight[0].Name != "theirs.txt" { + t.Errorf("only on one side: %+v %+v", out.OnlyLeft, out.OnlyRight) + } + var diff comparedPair + for _, p := range out.Different { + if p.Name == "diff.txt" { + diff = p + } + } + if diff.LeftSize == nil || *diff.LeftSize != 3 || diff.RightSize == nil || *diff.RightSize != 4 || diff.LeftModified == "" { + t.Errorf("a file that differs: %+v", diff) + } + if out.Truncated || out.StoppedEarly { + t.Errorf("nothing was cut: %+v", out) + } + + out = must[compareFoldersOut](t, cs, "compare_folders", map[string]any{"left": left, "right": right, "limit": 1}) + if len(out.OnlyLeft) != 1 || out.Counts.OnlyLeft != 2 || !out.Truncated || out.Note == "" { + t.Errorf("at most one name a list: %+v", out) + } + if _, failed := call[compareFoldersOut](t, cs, "compare_folders", map[string]any{"left": left, "right": filepath.Join(right, "missing")}); failed == "" { + t.Error("a missing folder was compared") + } +} + +// A local disk can't make public links, and a root is no entry to link to. +func TestPublicLinkRefusals(t *testing.T) { + cs := connect(t) + root := fileTree(t, map[string]string{"a.txt": "a"}) + for _, p := range []string{filepath.Join(root, "a.txt"), "box:"} { + if _, failed := call[publicLinkOut](t, cs, "get_public_link", map[string]any{"path": p}); failed == "" { + t.Errorf("%s got a link", p) + } + } +} + +// A text file reads whole or as its start, cut between characters, and a file that isn't text +// is refused. +func TestReadFile(t *testing.T) { + cs := connect(t) + root := fileTree(t, map[string]string{ + "notes.txt": "hello\nworld", "accent.txt": "hé!", "binary.bin": "\xff\xfe\x01", "nul.txt": "a\x00b", + "big.txt": strings.Repeat("a", readMax+10), "folder/": "", + }) + out := must[readFileOut](t, cs, "read_file", map[string]any{"path": onBox(filepath.Join(root, "notes.txt"))}) + if out.Text != "hello\nworld" || out.Truncated || out.Size == nil || *out.Size != 11 || out.Modified == "" { + t.Errorf("a whole file: %+v", out) + } + out = must[readFileOut](t, cs, "read_file", map[string]any{"path": filepath.Join(root, "notes.txt"), "max_bytes": 5}) + if out.Text != "hello" || !out.Truncated { + t.Errorf("a file's start: %+v", out) + } + // é is two bytes, and the read stops after its first. + out = must[readFileOut](t, cs, "read_file", map[string]any{"path": filepath.Join(root, "accent.txt"), "max_bytes": 2}) + if out.Text != "h" || !out.Truncated { + t.Errorf("a character cut in two: %+v", out) + } + out = must[readFileOut](t, cs, "read_file", map[string]any{"path": filepath.Join(root, "big.txt"), "max_bytes": 1 << 30}) + if len(out.Text) != readMax || !out.Truncated || *out.Size != readMax+10 { + t.Errorf("a large file: %d bytes, %+v %v", len(out.Text), out.Truncated, out.Size) + } + for _, name := range []string{"binary.bin", "nul.txt"} { + if _, failed := call[readFileOut](t, cs, "read_file", map[string]any{"path": filepath.Join(root, name)}); !strings.Contains(failed, "isn't text") { + t.Errorf("%s: %q", name, failed) + } + } + for _, name := range []string{"folder", "missing.txt"} { + if _, failed := call[readFileOut](t, cs, "read_file", map[string]any{"path": filepath.Join(root, name)}); failed == "" { + t.Errorf("%s was read", name) + } + } +} + +// A folder is made, a file is renamed at once, and a folder by the agent's transfer. Neither +// overwrites what is there. +func TestMakeFolderAndRename(t *testing.T) { + cs := connect(t) + root := fileTree(t, map[string]string{"a.txt": "a", "taken.txt": "t", "full/in.txt": "x"}) + made := must[madeFolder](t, cs, "make_folder", map[string]any{"path": onBox(filepath.Join(root, "new"))}) + if info, err := os.Stat(filepath.Join(root, "new")); err != nil || !info.IsDir() || made.Path != onBox(filepath.Join(root, "new")) { + t.Fatalf("make_folder: %+v %v", made, err) + } + if _, failed := call[madeFolder](t, cs, "make_folder", map[string]any{"path": filepath.Join(root, "new")}); !strings.Contains(failed, "already exists") { + t.Errorf("a folder made twice: %q", failed) + } + + out := must[renamed](t, cs, "rename", map[string]any{"path": filepath.Join(root, "a.txt"), "new_name": "b.txt"}) + if out.Path != filepath.Join(root, "b.txt") || out.TransferID != "" || !fileExists(filepath.Join(root, "b.txt")) || fileExists(filepath.Join(root, "a.txt")) { + t.Errorf("a file renamed: %+v", out) + } + for _, tc := range []struct{ path, name, says string }{ + {filepath.Join(root, "b.txt"), "taken.txt", "already exists"}, + {filepath.Join(root, "b.txt"), "x/y.txt", "cannot contain"}, + {filepath.Join(root, "missing.txt"), "c.txt", "doesn't exist"}, + } { + if _, failed := call[renamed](t, cs, "rename", map[string]any{"path": tc.path, "new_name": tc.name}); !strings.Contains(failed, tc.says) { + t.Errorf("%s to %s: %q, want %q", tc.path, tc.name, failed, tc.says) + } + } + + out = must[renamed](t, cs, "rename", map[string]any{"path": onBox(filepath.Join(root, "full")), "new_name": "moved"}) + if out.TransferID == "" || out.Path != onBox(filepath.Join(root, "moved")) { + t.Fatalf("a folder renamed: %+v", out) + } + d := awaitRename(t, out.TransferID) + if d.State != transfers.StateCompleted || d.Origin.Kind != transfers.OriginAgent || !fileExists(filepath.Join(root, "moved", "in.txt")) || fileExists(filepath.Join(root, "full")) { + t.Errorf("the folder's rename: %s %+v", d.State, d.Origin) + } +} + +// fileExists reports whether path is on disk. +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// awaitRename waits for the transfer that renames a folder to end, and returns it. +func awaitRename(t *testing.T, id string) transfers.Detail { + t.Helper() + ctx := context.Background() + for range 300 { + d, err := apis.Transfers.Get(ctx, id) + if err != nil { + t.Fatal(err) + } + if d.EndedAt != nil { + return d + } + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("%s is still running after 30 seconds", id) + return transfers.Detail{} +} + +// An operation's options come in its window's groups, with the app's defaults, and a search +// narrows them. +func TestListOptions(t *testing.T) { + cs := connect(t) + optionIn := func(out optionsListed, group, name string) *optionInfo { + for _, g := range out.Groups { + if g.Name != group { + continue + } + for i := range g.Options { + if g.Options[i].Name == name { + return &g.Options[i] + } + } + } + return nil + } + groups := func(out optionsListed) []string { + var names []string + for _, g := range out.Groups { + names = append(names, g.Name) + } + return names + } + + out := must[optionsListed](t, cs, "list_options", map[string]any{"operation": "copy"}) + if want := []string{"copy", "filter", "config", "metadata"}; !slices.Equal(groups(out), want) { + t.Errorf("copy's groups %q, want %q", groups(out), want) + } + if o := optionIn(out, "config", "transfers"); o == nil || o.Default != "8" || o.Type != "int" || o.Help == "" || strings.Contains(o.Help, "\n") { + t.Errorf("transfers, whose default is the app's: %+v", o) + } + if o := optionIn(out, "filter", "max_age"); o == nil || o.Type != "duration" { + t.Errorf("max_age: %+v", o) + } + if optionIn(out, "copy", "backup_dir") == nil { + t.Error("a copy's own group has no backup_dir") + } + + out = must[optionsListed](t, cs, "list_options", map[string]any{"operation": "copy", "search": "max-age"}) + if o := optionIn(out, "filter", "max_age"); o == nil { + t.Errorf("a search for max-age: %+v", out) + } + for _, g := range out.Groups { + for _, o := range g.Options { + if !strings.Contains(o.Name, "max_age") && !strings.Contains(strings.ToLower(o.Help), "max-age") { + t.Errorf("%s matches the search for max-age? %+v", g.Name, o) + } + } + } + + out = must[optionsListed](t, cs, "list_options", map[string]any{"operation": "mount"}) + if o := optionIn(out, "vfs", "vfs_cache_mode"); o == nil || o.Default != "off" || !slices.Contains(o.Choices, "full") { + t.Errorf("vfs_cache_mode: %+v", o) + } + out = must[optionsListed](t, cs, "list_options", map[string]any{"operation": "serve", "serve_type": "http"}) + if optionIn(out, "serve", "addr") == nil || optionIn(out, "serve", "auth_key") != nil { + t.Errorf("an http serve's group: %+v", out.Groups[0]) + } + if out := must[optionsListed](t, cs, "list_options", map[string]any{"operation": "download"}); !slices.Equal(groups(out), []string{"config"}) { + t.Errorf("a download's groups: %q", groups(out)) + } + for _, args := range []map[string]any{{"operation": "rename"}, {"operation": "serve", "serve_type": "gopher"}} { + if _, failed := call[optionsListed](t, cs, "list_options", args); failed == "" { + t.Errorf("%v was listed", args) + } + } +} + +// The help of an option is cut to its first sentence, but not at an abbreviation. +func TestFirstSentence(t *testing.T) { + for help, want := range map[string]string{ + "Number of file transfers to run in parallel": "Number of file transfers to run in parallel", + "Skip files. Then more.": "Skip files.", + "Use a size, e.g. 10M. Then more.": "Use a size, e.g. 10M.", + "First line\n\nA second paragraph.": "First line", + " Trimmed.\n": "Trimmed.", + "Ends with a dot.": "Ends with a dot.", + "Several i.e. abbreviations etc. are kept. And this is the second.": "Several i.e. abbreviations etc. are kept.", + } { + if got := firstSentence(help); got != want { + t.Errorf("%q: %q, want %q", help, got, want) + } + } +} diff --git a/core/agents/info.go b/core/agents/info.go new file mode 100644 index 00000000..7ea63b75 --- /dev/null +++ b/core/agents/info.go @@ -0,0 +1,90 @@ +package agents + +import ( + "context" + "runtime" + "slices" + + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +type about struct { + AppVersion string `json:"app_version"` + RcloneVersion string `json:"rclone_version"` + OS string `json:"os" jsonschema:"darwin, windows or linux: the form of local paths follows from it"` + // CanMount is false when this computer lacks what a mount needs (WinFsp, macFUSE or FUSE). + CanMount bool `json:"can_mount"` + // MountHelp says what is missing when the computer can't mount. + MountHelp string `json:"mount_help,omitempty"` +} + +type remote struct { + Name string `json:"name" jsonschema:"the remote's name: its root is the path name followed by a colon"` + Type string `json:"type" jsonschema:"rclone's backend, such as drive, s3 or sftp"` + State string `json:"state,omitempty" jsonschema:"ok (reachable), checking (being checked now), unknown (it didn't answer in time) or faulty (it failed: see error); empty when it hasn't been checked yet"` + Error string `json:"error,omitempty" jsonschema:"why the remote can't be used, when it can't"` + NeedsSignIn bool `json:"needs_sign_in,omitempty" jsonschema:"true when the user must sign in to the remote again, in the app's Remotes window; an agent can't do it for them"` + // UsedBytes, FreeBytes and TotalBytes are the remote's storage, where it reports them. + UsedBytes *int64 `json:"used_bytes,omitempty"` + FreeBytes *int64 `json:"free_bytes,omitempty"` + TotalBytes *int64 `json:"total_bytes,omitempty"` +} + +type remoteList struct { + Remotes []remote `json:"remotes"` +} + +type nothing struct{} + +func (s *Server) infoTools() { + add(s, &mcp.Tool{ + Name: "about", + Description: "Rclone UI's and rclone's versions, this computer's OS, and whether it can mount remotes as drives.", + Annotations: reads("About Rclone UI"), + }, func(ctx context.Context, _ nothing) (about, error) { + info, err := s.o.APIs.App.Info(ctx) + if err != nil { + return about{}, err + } + out := about{AppVersion: info.AppVersion, RcloneVersion: info.RcloneVersion, OS: runtime.GOOS} + if sup, err := s.o.APIs.Mounts.Support(ctx); err == nil { + out.CanMount, out.MountHelp = sup.Supported, sup.Reason + } + return out, nil + }) + + add(s, &mcp.Tool{ + Name: "list_remotes", + Description: "The user's remotes (their connected storage): each one's name, its type, whether it is reachable, and its storage use. " + + "A remote's files are at \"name:path\". Remotes are added, changed and signed in to by the user, in the app's Remotes window.", + Annotations: reads("List remotes"), + }, func(ctx context.Context, _ nothing) (remoteList, error) { + list, err := s.o.APIs.Remotes.List(ctx) + if err != nil { + return remoteList{}, err + } + // The health is what the app last found. A remote that was never checked has none. + health, _ := s.o.APIs.Remotes.Health(ctx) + out := remoteList{Remotes: make([]remote, 0, len(list))} + for _, r := range list { + item := remote{Name: r.Name, Type: r.Type} + if h, ok := health[r.Name]; ok { + item.State, item.Error, item.NeedsSignIn = h.State, h.Error, h.CanReconnect + if q := h.About; q != nil { + item.UsedBytes, item.FreeBytes, item.TotalBytes = q.Used, q.Free, q.Total + } + } + out.Remotes = append(out.Remotes, item) + } + slices.SortFunc(out.Remotes, func(a, b remote) int { + if a.Name < b.Name { + return -1 + } + if a.Name > b.Name { + return 1 + } + return 0 + }) + return out, nil + }) +} diff --git a/core/agents/main_test.go b/core/agents/main_test.go new file mode 100644 index 00000000..0323b43a --- /dev/null +++ b/core/agents/main_test.go @@ -0,0 +1,152 @@ +// Tests for the agents' server. They run in this process on a real core, whose one remote, "box", +// is the local disk, and reach the tools the way an agent does: through an MCP client. When this +// binary is started as an rclone child (marked by childenv), it runs rclone's command line, as +// main.go does, so a test can mount or serve. +package agents + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + _ "github.com/rclone/rclone/backend/local" + rclonecmd "github.com/rclone/rclone/cmd" + _ "github.com/rclone/rclone/cmd/serve/http" + rcloneconfig "github.com/rclone/rclone/fs/config" + "github.com/spf13/cobra" + "github.com/zalando/go-keyring" + + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/children/childenv" + "github.com/rclone/rclone-ui/core/internal/testutil" +) + +func TestMain(m *testing.M) { + if _, ok := os.LookupEnv(childenv.Env); ok { + childenv.Adopt(nil) + rclonecmd.Root.PersistentPreRun = func(*cobra.Command, []string) { childenv.Ready() } + rclonecmd.Root.SetArgs(os.Args[1:]) + rclonecmd.Main() + os.Exit(0) + } + // A serve with a password keeps it in the keychain. The tests' home folder has no keychain, + // and macOS would ask the person at the screen about it, so the tests get one in memory. + keyring.MockInit() + testutil.Main(m, func(dir string) error { + home = dir + conf := rcloneconfig.GetConfigPath() + if err := os.MkdirAll(filepath.Dir(conf), 0o700); err != nil { + return err + } + return os.WriteFile(conf, []byte("[box]\ntype = local\n"), 0o600) + }) +} + +// The package's tests share one core, because rclone is set up once per process. +var ( + home string // the tests' home folder + once sync.Once + apis *core.APIs + dataDir string + opened []string // the routes that tools asked to open + startup error +) + +// server returns a server on the shared core. Its OpenWindow records the route in opened. +func server(t *testing.T) *Server { + t.Helper() + once.Do(func() { + dataDir = filepath.Join(home, "data") + runDir, err := os.MkdirTemp("", "rc") // a socket's path must stay short + if err != nil { + startup = err + return + } + apis = core.NewAPIs(core.APIOptions{DataDir: dataDir}) + _, startup = core.Start(core.Options{DataDir: dataDir, RunDir: runDir, APIs: apis}) + }) + if startup != nil { + t.Fatal(startup) + } + return New(Options{ + APIs: apis, Log: slog.New(slog.NewTextHandler(io.Discard, nil)), DataDir: dataDir, Version: "test", + OpenWindow: func(route string) error { opened = append(opened, route); return nil }, + }) +} + +// connect returns an agent's session with a server on the shared core, over a connection in +// memory. The agent calls itself "Test Agent". +func connect(t *testing.T) *mcp.ClientSession { + t.Helper() + return connectTo(t, server(t)) +} + +func connectTo(t *testing.T, s *Server) *mcp.ClientSession { + t.Helper() + ctx := context.Background() + serverSide, clientSide := mcp.NewInMemoryTransports() + ss, err := s.mcp.Connect(ctx, serverSide, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ss.Close() }) + return session(t, clientSide) +} + +func session(t *testing.T, transport mcp.Transport) *mcp.ClientSession { + t.Helper() + client := mcp.NewClient(&mcp.Implementation{Name: "test-agent", Title: "Test Agent", Version: "1"}, nil) + cs, err := client.Connect(context.Background(), transport, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cs.Close() }) + return cs +} + +// call calls a tool and returns its output, decoded into Out, or the tool's error as text. It +// fails the test when the call itself fails, which is a protocol error rather than a tool's. +func call[Out any](t *testing.T, cs *mcp.ClientSession, tool string, args any) (Out, string) { + t.Helper() + var out Out + if args == nil { + args = map[string]any{} + } + res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: tool, Arguments: args}) + if err != nil { + t.Fatalf("%s: %v", tool, err) + } + if res.IsError { + text := "" + for _, c := range res.Content { + if tc, ok := c.(*mcp.TextContent); ok { + text += tc.Text + } + } + return out, text + } + b, err := json.Marshal(res.StructuredContent) + if err != nil { + t.Fatalf("%s: %v", tool, err) + } + if err := json.Unmarshal(b, &out); err != nil { + t.Fatalf("%s: its output %s doesn't decode: %v", tool, b, err) + } + return out, "" +} + +// must is call for a tool that is expected to succeed. +func must[Out any](t *testing.T, cs *mcp.ClientSession, tool string, args any) Out { + t.Helper() + out, failed := call[Out](t, cs, tool, args) + if failed != "" { + t.Fatalf("%s failed: %s", tool, failed) + } + return out +} diff --git a/core/agents/running.go b/core/agents/running.go new file mode 100644 index 00000000..0294d0d2 --- /dev/null +++ b/core/agents/running.go @@ -0,0 +1,462 @@ +package agents + +import ( + "context" + "encoding/json" + "net" + "net/url" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/location" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/serves" +) + +// A mount and a serve run as processes of their own, so they are few, and their lists have no +// limit. + +func (s *Server) runningTools() { + s.listMountsTool() + s.mountTool() + s.unmountTool() + s.listServesTool() + s.serveTool() + s.stopServeTool() + s.openWindowTool() +} + +// optionLeftOut is an option that a tool didn't use, with the reason, so that the agent learns +// which options an operation takes. +type optionLeftOut struct { + Option string `json:"option"` + Reason string `json:"reason"` +} + +// optionGroupsFor sorts an agent's flat options into the groups of op's form, as the options of a +// template are sorted (operations.TemplateGroups). serve is a serve's protocol, or "" for any +// other operation. It returns the options that the form leaves out, with the reason. The values +// are checked when the operation starts. +func optionGroupsFor(op operations.Operation, serve string, flat map[string]any) (operations.Groups, []optionLeftOut, error) { + if len(flat) == 0 { + return operations.Groups{}, nil, nil + } + raw := make(catalog.Group, len(flat)) + for key, v := range flat { + b, err := json.Marshal(v) + if err != nil { + return operations.Groups{}, nil, err + } + raw[key] = b + } + groups, skipped, err := operations.TemplateGroups(op, serve, raw) + if err != nil { + return operations.Groups{}, nil, err + } + var left []optionLeftOut + for _, sk := range skipped { + left = append(left, optionLeftOut{Option: sk.Flag, Reason: sk.Reason}) + } + return groups, left, nil +} + +type mountItem struct { + ID string `json:"id" jsonschema:"the mount's id, for unmount"` + Source string `json:"source"` + MountPoint string `json:"mount_point" jsonschema:"the folder, or on Windows the drive, where the source's files appear"` + State string `json:"state" jsonschema:"starting, running (ready to use) or restarting (it went down and is starting again)"` + // UploadsWaiting counts the files written through the mount that aren't on the remote yet. + UploadsWaiting int `json:"uploads_waiting"` + Error string `json:"error,omitempty" jsonschema:"why it last went down, while it restarts"` + NeedsRestart bool `json:"needs_restart,omitempty" jsonschema:"a remote it mounts changed since it started: unmount it and mount it again for the change to apply"` + // IgnoredOptions are the options that mount didn't use. Only mount returns them. + IgnoredOptions []optionLeftOut `json:"ignored_options,omitempty"` +} + +func mountItemOf(r mounts.MountRow) mountItem { + return mountItem{ + ID: r.ID, Source: r.Source, MountPoint: r.MountPoint, State: r.State, + UploadsWaiting: r.UploadsPending, Error: r.Error, NeedsRestart: r.Restart, + } +} + +type mountList struct { + Mounts []mountItem `json:"mounts"` +} + +func (s *Server) listMountsTool() { + add(s, &mcp.Tool{ + Name: "list_mounts", + Description: "The remotes that are mounted now as folders or drives on this computer: each mount's id, source, mount point, " + + "state, the uploads still waiting to reach the remote, and its error while it restarts.", + Annotations: reads("List mounts"), + }, func(ctx context.Context, _ nothing) (mountList, error) { + rows, err := s.o.APIs.Mounts.List(ctx, true) + if err != nil { + return mountList{}, err + } + out := mountList{Mounts: make([]mountItem, 0, len(rows))} + for _, r := range rows { + out.Mounts = append(out.Mounts, mountItemOf(r)) + } + return out, nil + }) +} + +type mountIn struct { + Source string `json:"source" jsonschema:"what to mount: a folder of a remote, such as gdrive:Photos, or gdrive: for its root"` + MountPoint string `json:"mount_point,omitempty" jsonschema:"where its files appear: an empty folder, or one that doesn't exist yet, such as /Users/me/Rclone/gdrive; on Windows a free drive letter such as M: or * for the next free one. Leave it out for ~/Rclone/, or the next free drive on Windows."` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's mount, vfs, filter and config options by name, such as {\"vfs_cache_mode\": \"full\", \"read_only\": true}"` +} + +// suggestedMountPoint returns where the Mount window mounts source when the user doesn't choose +// (src/pages/Mount/mountPoint.ts): a folder named after its remote in ~/Rclone, which the core +// creates, or on Windows the next free drive letter. A folder on this computer has no suggestion. +func suggestedMountPoint(source string) (string, error) { + if runtime.GOOS == "windows" { + return "*", nil + } + if err := location.Refusal(source); err != nil { + return "", err + } + at, err := location.Split(source) + if err != nil { + return "", err + } + name := strings.TrimPrefix(at.Name, ":") // an on-the-fly remote such as :s3 is named after its type + if at.Local || name == "local" || name == "" { + return "", errs.New("Give a mount_point to mount a folder of this computer: an empty folder, or one that doesn't exist yet.") + } + home, err := os.UserHomeDir() + if err != nil { + return "", errs.New("This computer's home folder can't be found, so give a mount_point.") + } + return filepath.Join(home, "Rclone", name), nil +} + +func (s *Server) mountTool() { + add(s, &mcp.Tool{ + Name: "mount", + Description: "Mounts a remote's folder as a folder (or on Windows a drive) of this computer, so that every app can open its files. " + + "It returns once the mount is ready, with its id and mount point. The mount keeps running until unmount, or until the app quits. " + + "Without a mount_point, it mounts at ~/Rclone/ (the next free drive on Windows), as the app's Mount window does. " + + "Options it doesn't use come back in ignored_options. The about tool says whether this computer can mount.", + Annotations: changes("Mount a remote"), + }, func(ctx context.Context, in mountIn) (mountItem, error) { + sup, err := s.o.APIs.Mounts.Support(ctx) + if err != nil { + return mountItem{}, err + } + if !sup.Supported { + fix := "The user has to set this up before anything can be mounted." + if sup.CanInstall { + fix = "The user can install WinFsp from the app's Mount window." + } else if sup.Docs != "" { + fix = "See " + sup.Docs + "." + } + return mountItem{}, errs.Errorf("This computer can't mount: %s %s", sup.Reason, fix) + } + point := in.MountPoint + if point == "" { + if point, err = suggestedMountPoint(in.Source); err != nil { + return mountItem{}, err + } + } + groups, left, err := optionGroupsFor(operations.OperationMount, "", in.Options) + if err != nil { + return mountItem{}, err + } + row, err := s.o.APIs.Mounts.StartReady(ctx, operations.MountArgs{Source: in.Source, Destination: point, Options: groups}) + if err != nil { + return mountItem{}, err + } + out := mountItemOf(row) + out.IgnoredOptions = left + return out, nil + }) +} + +type mountIDIn struct { + MountID string `json:"mount_id" jsonschema:"the mount's id, from list_mounts or mount"` +} + +type unmounted struct { + Unmounted string `json:"unmounted" jsonschema:"the mount point that was unmounted"` +} + +func (s *Server) unmountTool() { + add(s, &mcp.Tool{ + Name: "unmount", + Description: "Unmounts a mount. Apps that have its files open lose them. Uploads that haven't reached the remote yet are kept, " + + "and are sent the next time the same folder is mounted at the same place. It returns once the mount is gone.", + Annotations: destroys("Unmount"), + }, func(ctx context.Context, in mountIDIn) (unmounted, error) { + rows, err := s.o.APIs.Mounts.List(ctx, false) + if err != nil { + return unmounted{}, err + } + point := "" + for _, r := range rows { + if r.ID == in.MountID { + point = r.MountPoint + } + } + if err := s.o.APIs.Mounts.Stop(ctx, in.MountID); err != nil { + return unmounted{}, err + } + return unmounted{Unmounted: point}, nil + }) +} + +type serveItem struct { + ID string `json:"id" jsonschema:"the serve's id, for stop_serve"` + Source string `json:"source"` + Protocol string `json:"protocol"` + Address string `json:"address" jsonschema:"host:port where clients connect"` + State string `json:"state" jsonschema:"starting, running (it accepts connections) or restarting (it went down and is starting again)"` + Error string `json:"error,omitempty" jsonschema:"why it last went down, while it restarts"` + // NeedsRestart is true when a remote it serves changed after it started. + NeedsRestart bool `json:"needs_restart,omitempty" jsonschema:"a remote it serves changed since it started: stop it and serve it again for the change to apply"` + // Warning and IgnoredOptions are only in what serve returns. + Warning string `json:"warning,omitempty"` + IgnoredOptions []optionLeftOut `json:"ignored_options,omitempty"` +} + +// serveItemOf converts a serve's row. Its form isn't returned, because it holds the serve's +// password. +func serveItemOf(r serves.ServeRow) serveItem { + return serveItem{ + ID: r.ID, Source: r.Source, Protocol: r.Type, Address: r.Addr, State: r.State, + Error: r.Error, NeedsRestart: r.Restart, + } +} + +type serveList struct { + Serves []serveItem `json:"serves"` +} + +func (s *Server) listServesTool() { + add(s, &mcp.Tool{ + Name: "list_serves", + Description: "The folders that this computer shares now on the network (serves): each one's id, source, protocol, " + + "the address where clients connect, its state, and its error while it restarts.", + Annotations: reads("List serves"), + }, func(ctx context.Context, _ nothing) (serveList, error) { + rows, err := s.o.APIs.Serves.List(ctx) + if err != nil { + return serveList{}, err + } + out := serveList{Serves: make([]serveItem, 0, len(rows))} + for _, r := range rows { + out.Serves = append(out.Serves, serveItemOf(r)) + } + return out, nil + }) +} + +// serveLogins says, for each protocol, which options make a client sign in. dlna and nfs have +// none. An sftp serve refuses to start without one, unless no_auth is set. +var serveLogins = map[string]string{ + "http": "user and pass (or htpasswd, a file of users)", + "webdav": "user and pass (or htpasswd, a file of users)", + "restic": "user and pass (or htpasswd, a file of users)", + "ftp": "user and pass", + "sftp": "user and pass (or authorized_keys, a file of SSH keys)", + "s3": `auth_key, as "ACCESS_KEY_ID,SECRET_ACCESS_KEY"`, +} + +// loginOptions are the options that make a client of a serve sign in, by rclone's name. +var loginOptions = []string{"user", "pass", "htpasswd", "auth_key", "authorized_keys", "auth_proxy"} + +// openWarning returns the warning for a serve that anyone who reaches it can use, or "" for one +// that asks clients to sign in. +func openWarning(protocol, addr string, serve catalog.Group) string { + given := func(name string) bool { + for key, raw := range serve { + if catalog.NormalizeOptionName(key) == name { + var v any + return json.Unmarshal(raw, &v) == nil && v != nil && v != "" && v != false + } + } + return false + } + reach := "anyone who can reach " + addr + if host, _, err := net.SplitHostPort(addr); err == nil { + if ip := net.ParseIP(host); host == "localhost" || (ip != nil && ip.IsLoopback()) { + reach = "any program on this computer" + } + } + can := "read and change the files (unless read_only is set)" + if protocol == "http" || protocol == "dlna" { // they only read + can = "read the files" + } + logins, ok := serveLogins[protocol] + switch { + case !ok: + return protocol + " has no sign-in, so " + reach + " can " + can + "." + case protocol == "sftp": + if given("no_auth") { + return "no_auth is set, so " + reach + " can " + can + "." + } + return "" + case slices.ContainsFunc(loginOptions, given): + return "" + } + return "No user and password are set, so " + reach + " can " + can + ". " + + "To require a sign-in, stop this serve and serve again with " + logins + " in options." +} + +type serveIn struct { + Source string `json:"source" jsonschema:"the folder to share: a remote path such as gdrive:Shared, or a folder of this computer such as /Users/me/Public"` + Protocol string `json:"protocol" jsonschema:"http (browse and download in a web browser), webdav (open as a network drive), ftp, sftp, s3, dlna (media players and TVs), nfs or restic (a backup repository)"` + Address string `json:"address,omitempty" jsonschema:"host:port to listen on: 127.0.0.1:8080 for this computer only, :8080 for the whole network, and port 0 for any free port. Leave it out for rclone's default for the protocol."` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's options for the serve and its vfs, filter and config by name, such as {\"user\": \"me\", \"pass\": \"secret\", \"read_only\": true}"` +} + +func (s *Server) serveTool() { + add(s, &mcp.Tool{ + Name: "serve", + Description: "Shares a folder on the network over http, webdav, ftp, sftp, s3, dlna, nfs or restic, until stop_serve or until the app quits. " + + "It returns once the serve accepts connections, with the address to connect to. " + + "Without a sign-in, anyone who can reach the address can read the files: set the options user and pass " + + "(http, webdav, restic, ftp, sftp), or auth_key as \"ACCESS_KEY_ID,SECRET_ACCESS_KEY\" (s3). dlna and nfs have no sign-in. " + + "warning says when the serve is open to anyone. A protocol that this computer lacks is refused with the list of those it has. " + + "Options it doesn't use come back in ignored_options.", + Annotations: changes("Serve a folder"), + }, func(ctx context.Context, in serveIn) (serveItem, error) { + protocol := strings.ToLower(strings.TrimSpace(in.Protocol)) + if types := s.o.APIs.Serves.Types(); !slices.Contains(types, protocol) { + return serveItem{}, errs.Errorf("This computer can't serve over %q. Use one of: %s.", in.Protocol, strings.Join(types, ", ")) + } + groups, left, err := optionGroupsFor(operations.OperationServe, protocol, in.Options) + if err != nil { + return serveItem{}, err + } + row, err := s.o.APIs.Serves.StartReady(ctx, operations.ServeArgs{Type: protocol, Source: in.Source, Addr: in.Address, Options: groups}) + if err != nil { + return serveItem{}, err + } + out := serveItemOf(row) + out.Warning = openWarning(protocol, row.Addr, groups.Serve) + out.IgnoredOptions = left + return out, nil + }) +} + +type serveIDIn struct { + ServeID string `json:"serve_id" jsonschema:"the serve's id, from list_serves or serve"` +} + +type stopped struct { + Stopped string `json:"stopped" jsonschema:"the address that no longer answers"` +} + +func (s *Server) stopServeTool() { + add(s, &mcp.Tool{ + Name: "stop_serve", + Description: "Stops a serve. Its clients are disconnected, and its address no longer answers. It returns once the serve is gone.", + Annotations: destroys("Stop a serve"), + }, func(ctx context.Context, in serveIDIn) (stopped, error) { + rows, err := s.o.APIs.Serves.List(ctx) + if err != nil { + return stopped{}, err + } + addr := "" + for _, r := range rows { + if r.ID == in.ServeID { + addr = r.Addr + } + } + if err := s.o.APIs.Serves.Stop(ctx, in.ServeID); err != nil { + return stopped{}, err + } + return stopped{Stopped: addr}, nil + }) +} + +// appWindows are the app's windows that open_window shows, by the names of their routes +// (src/routes.ts). The startup screen, the launcher's window and the dev pages are left out. +var appWindows = []string{ + "remotes", "commander", "history", "schedules", "watchers", "templates", "automounts", + "copy", "move", "sync", "bisync", "delete", "purge", "download", "mount", "serve", + "settings", "notifications", "mobileRemoteControl", "guides", "wizard", +} + +// The windows that take a path to start with, as the launcher opens them +// (app/launcher/engine/providers): a source as initialSource, and a destination (a mount's mount +// point) as initialDestination. The Commander takes a folder to show as path. +var ( + windowsWithSource = []string{"copy", "move", "sync", "bisync", "delete", "purge", "mount", "serve", "commander"} + windowsWithDestination = []string{"copy", "move", "sync", "bisync", "download", "mount"} +) + +type openWindowIn struct { + Window string `json:"window" jsonschema:"the window to show: remotes, commander (a file manager), history (the transfers), schedules, watchers, templates, automounts, copy, move, sync, bisync, delete, purge, download, mount, serve, settings, notifications, mobileRemoteControl (to use the app from a phone), guides or wizard"` + TransferID string `json:"transfer_id,omitempty" jsonschema:"for history: the transfer to show, by its id"` + Source string `json:"source,omitempty" jsonschema:"for copy, move, sync, bisync, delete, purge, mount and serve: the path to fill in as the source, such as gdrive:Photos; for commander: the folder to show"` + Destination string `json:"destination,omitempty" jsonschema:"for copy, move, sync, bisync and download: the destination to fill in; for mount: the mount point"` +} + +type windowOpened struct { + Opened string `json:"opened" jsonschema:"the window that the user now sees"` +} + +func (s *Server) openWindowTool() { + add(s, &mcp.Tool{ + Name: "open_window", + Description: "Shows the user one of the app's windows, to point them at something: History on a transfer, " + + "or an operation's window with its paths filled in for them to check and start. The window opens in front, " + + "and nothing starts by itself. Use it when the user asks to see something, or when a step is theirs to take.", + Annotations: changes("Open a window"), + }, func(_ context.Context, in openWindowIn) (windowOpened, error) { + // The name is matched without case, and spelled as the route spells it from here on. + asked := strings.TrimSpace(in.Window) + i := slices.IndexFunc(appWindows, func(w string) bool { return strings.EqualFold(w, asked) }) + if i < 0 { + return windowOpened{}, errs.Errorf("The app has no %q window. Use one of: %s.", in.Window, strings.Join(appWindows, ", ")) + } + window := appWindows[i] + query := url.Values{} + if in.TransferID != "" { + if window != "history" { + return windowOpened{}, errs.New("Only the history window takes a transfer_id.") + } + query.Set("id", in.TransferID) + } + if in.Source != "" { + if !slices.Contains(windowsWithSource, window) { + return windowOpened{}, errs.Errorf("The %s window takes no source.", window) + } + if window == "commander" { + query.Set("path", in.Source) + } else { + query.Set("initialSource", in.Source) + } + } + if in.Destination != "" { + if !slices.Contains(windowsWithDestination, window) { + return windowOpened{}, errs.Errorf("The %s window takes no destination.", window) + } + query.Set("initialDestination", in.Destination) + } + if s.o.OpenWindow == nil { + return windowOpened{}, errs.New("This app can't show windows.") + } + route := "/" + window + if len(query) > 0 { + route += "?" + query.Encode() + } + if err := s.o.OpenWindow(route); err != nil { + return windowOpened{}, err + } + return windowOpened{Opened: window}, nil + }) +} diff --git a/core/agents/running_test.go b/core/agents/running_test.go new file mode 100644 index 00000000..d1a1abee --- /dev/null +++ b/core/agents/running_test.go @@ -0,0 +1,276 @@ +package agents + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + + // The mount commands that a mount child of this test binary runs: nfsmount on macOS, and FUSE + // on Linux. Each builds everywhere, as a stub where it doesn't run. + _ "github.com/rclone/rclone/cmd/mount" + _ "github.com/rclone/rclone/cmd/nfsmount" +) + +// A remote's folder is mounted, read through the mount point, listed, and unmounted. The +// refusals come first, since they need no mount. +func TestMountTools(t *testing.T) { + cs := connect(t) + if _, failed := call[unmounted](t, cs, "unmount", map[string]any{"mount_id": "no-such-mount"}); !strings.Contains(failed, "not running") { + t.Errorf("unmounting what isn't mounted: %q", failed) + } + sup, err := apis.Mounts.Support(context.Background()) + if err != nil { + t.Fatal(err) + } + if !sup.Supported { + if _, failed := call[mountItem](t, cs, "mount", map[string]any{"source": "box:" + t.TempDir()}); !strings.Contains(failed, "can't mount") { + t.Errorf("a mount where the computer can't mount: %q", failed) + } + t.Skipf("this computer can't mount: %s", sup.Reason) + } + if runtime.GOOS == "windows" { + t.Skip("a mount on Windows needs cmount, which this test binary doesn't have (-tags cmount)") + } + if _, failed := call[mountItem](t, cs, "mount", map[string]any{"source": t.TempDir()}); !strings.Contains(failed, "mount_point") { + t.Errorf("a local folder without a mount point: %q", failed) + } + + src := t.TempDir() + if err := os.WriteFile(filepath.Join(src, "a.txt"), []byte("through the mount"), 0o600); err != nil { + t.Fatal(err) + } + // base is not under t.TempDir, whose cleanup would walk into a mount that is still there. + // + // The mount point is spelled "Mounts", while the folder on disk is "mounts". The same happens + // when the suggested ~/Rclone/box meets a folder called ~/rclone: on a Mac both name one + // folder, and the mount table names it as the disk does. The mount must still count as ready. + base, err := os.MkdirTemp("", "rcui-mnt-") + if err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(base, "mounts"), 0o700); err != nil { + t.Fatal(err) + } + point := filepath.Join(base, "Mounts", "box") + var id string + t.Cleanup(func() { + if id != "" { + _ = apis.Mounts.Stop(context.Background(), id) + } + _ = os.RemoveAll(base) + }) + m := must[mountItem](t, cs, "mount", map[string]any{ + "source": "box:" + src, "mount_point": point, + "options": map[string]any{"vfs_cache_mode": "writes", "no_such_option": true}, + }) + id = m.ID + if m.MountPoint != point || m.State != "running" { + t.Fatalf("mount: %+v, want it running at %s", m, point) + } + if len(m.IgnoredOptions) != 1 || m.IgnoredOptions[0].Option != "no_such_option" || m.IgnoredOptions[0].Reason == "" { + t.Errorf("ignored options: %+v", m.IgnoredOptions) + } + if b, err := os.ReadFile(filepath.Join(point, "a.txt")); err != nil || string(b) != "through the mount" { + t.Errorf("a file through the mount point: %q, %v", b, err) + } + list := must[mountList](t, cs, "list_mounts", nil) + if len(list.Mounts) != 1 || list.Mounts[0].ID != m.ID || list.Mounts[0].Source != "box:"+src || list.Mounts[0].State != "running" { + t.Errorf("list_mounts: %+v", list) + } + + if got := must[unmounted](t, cs, "unmount", map[string]any{"mount_id": m.ID}); got.Unmounted != point { + t.Errorf("unmount: %+v", got) + } + id = "" + if list := must[mountList](t, cs, "list_mounts", nil); len(list.Mounts) != 0 { + t.Errorf("list_mounts after unmount: %+v", list) + } + if _, err := os.Stat(filepath.Join(point, "a.txt")); err == nil { + t.Error("the file is still in the mount point after unmount") + } +} + +func TestSuggestedMountPoint(t *testing.T) { + if runtime.GOOS == "windows" { + if got, err := suggestedMountPoint(`C:\Users\me`); got != "*" || err != nil { + t.Errorf("on Windows: %q, %v", got, err) + } + return + } + for source, want := range map[string]string{ + "box:/a/b": filepath.Join(home, "Rclone", "box"), + "gdrive,team=x:Docs": filepath.Join(home, "Rclone", "gdrive"), + ":s3:bucket": filepath.Join(home, "Rclone", "s3"), + } { + if got, err := suggestedMountPoint(source); got != want || err != nil { + t.Errorf("%s: %q, %v, want %s", source, got, err, want) + } + } + for _, source := range []string{"/Users/me/Photos", ":local:/tmp"} { + if _, err := suggestedMountPoint(source); err == nil || !strings.Contains(err.Error(), "mount_point") { + t.Errorf("%s: %v", source, err) + } + } + if _, err := suggestedMountPoint("relative/path"); err == nil { + t.Error("a path that isn't full has a suggestion") + } +} + +// A folder is served over http on a free port of this computer, a file is fetched from it, and +// the serve is stopped. A serve without a sign-in warns, and one with a user and password asks +// for them. +func TestServeTools(t *testing.T) { + cs := connect(t) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("served"), 0o600); err != nil { + t.Fatal(err) + } + if _, failed := call[serveItem](t, cs, "serve", map[string]any{"source": dir, "protocol": "gopher"}); !strings.Contains(failed, "http") { + t.Errorf("an unknown protocol: %q", failed) + } + if _, failed := call[stopped](t, cs, "stop_serve", map[string]any{"serve_id": "no-such-serve"}); !strings.Contains(failed, "not running") { + t.Errorf("stopping what isn't served: %q", failed) + } + + addr := fmt.Sprintf("127.0.0.1:%d", freePort(t)) + v := must[serveItem](t, cs, "serve", map[string]any{ + "source": dir, "protocol": "HTTP", "address": addr, "options": map[string]any{"no_such_option": 1}, + }) + t.Cleanup(func() { _ = apis.Serves.Stop(context.Background(), v.ID) }) + if v.Address != addr || v.State != "running" || v.Protocol != "http" || v.Source != dir { + t.Fatalf("serve: %+v", v) + } + if !strings.Contains(v.Warning, "any program on this computer") { + t.Errorf("a serve without a sign-in: its warning is %q", v.Warning) + } + if len(v.IgnoredOptions) != 1 || v.IgnoredOptions[0].Option != "no_such_option" { + t.Errorf("ignored options: %+v", v.IgnoredOptions) + } + if code, body := fetch(t, "http://"+addr+"/a.txt"); code != http.StatusOK || body != "served" { + t.Errorf("a.txt over http: %d %q", code, body) + } + + // With a user and a password, a client must sign in, and there is no warning. + locked := fmt.Sprintf("127.0.0.1:%d", freePort(t)) + w := must[serveItem](t, cs, "serve", map[string]any{ + "source": dir, "protocol": "http", "address": locked, "options": map[string]any{"user": "me", "pass": "s3cret"}, + }) + t.Cleanup(func() { _ = apis.Serves.Stop(context.Background(), w.ID) }) + if w.Warning != "" { + t.Errorf("a serve with a sign-in warns: %q", w.Warning) + } + if code, _ := fetch(t, "http://"+locked+"/a.txt"); code != http.StatusUnauthorized { + t.Errorf("without signing in: %d", code) + } + if code, body := fetch(t, "http://me:s3cret@"+locked+"/a.txt"); code != http.StatusOK || body != "served" { + t.Errorf("signed in: %d %q", code, body) + } + + list := must[serveList](t, cs, "list_serves", nil) + ids := []string{} + for _, item := range list.Serves { + ids = append(ids, item.ID) + } + if len(ids) != 2 || !slices.Contains(ids, v.ID) || !slices.Contains(ids, w.ID) { + t.Errorf("list_serves: %+v", list) + } + for _, id := range []string{v.ID, w.ID} { + must[stopped](t, cs, "stop_serve", map[string]any{"serve_id": id}) + } + if list := must[serveList](t, cs, "list_serves", nil); len(list.Serves) != 0 { + t.Errorf("list_serves after stop_serve: %+v", list) + } + if _, err := http.Get("http://" + addr + "/a.txt"); err == nil { + t.Error("the address still answers after stop_serve") + } +} + +func fetch(t *testing.T, url string) (int, string) { + t.Helper() + res, err := http.Get(url) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + return res.StatusCode, string(b) +} + +func TestOpenWarning(t *testing.T) { + for _, c := range []struct { + protocol, addr, options, want string + }{ + {"webdav", ":8080", `{}`, "anyone who can reach :8080 can read and change"}, + {"webdav", "[::1]:8080", `{"read_only": true}`, "any program on this computer"}, + {"webdav", "localhost:8080", `{"user": "me", "pass": "x"}`, ""}, + {"s3", "0.0.0.0:8080", `{"auth_key": ["a,b"]}`, ""}, + {"s3", "0.0.0.0:8080", `{}`, "auth_key"}, + {"dlna", ":7879", `{}`, "dlna has no sign-in, so anyone who can reach :7879 can read the files."}, + {"sftp", ":2022", `{}`, ""}, + {"sftp", ":2022", `{"no_auth": true}`, "no_auth is set"}, + } { + var options map[string]any + if err := json.Unmarshal([]byte(c.options), &options); err != nil { + t.Fatal(err) + } + groups, _, err := optionGroupsFor("serve", c.protocol, options) + if err != nil { + t.Fatal(err) + } + got := openWarning(c.protocol, c.addr, groups.Serve) + if c.want == "" && got != "" || !strings.Contains(got, c.want) { + t.Errorf("%s at %s with %s: %q, want %q", c.protocol, c.addr, c.options, got, c.want) + } + } +} + +// open_window opens the window of a route, with what it starts with in its query, as the +// launcher opens it. It refuses a window that doesn't exist, and an argument that the window +// doesn't take. +func TestOpenWindow(t *testing.T) { + cs := connect(t) + for _, c := range []struct { + args map[string]any + want string + }{ + {map[string]any{"window": "history"}, "/history"}, + {map[string]any{"window": "History", "transfer_id": "t-1"}, "/history?id=t-1"}, + {map[string]any{"window": "copy", "source": "box:/a b", "destination": "/c"}, "/copy?initialDestination=%2Fc&initialSource=box%3A%2Fa+b"}, + {map[string]any{"window": "mount", "source": "box:", "destination": "/mnt/box"}, "/mount?initialDestination=%2Fmnt%2Fbox&initialSource=box%3A"}, + {map[string]any{"window": "commander", "source": "box:/x"}, "/commander?path=box%3A%2Fx"}, + {map[string]any{"window": " Settings "}, "/settings"}, + {map[string]any{"window": "mobileRemoteControl"}, "/mobileRemoteControl"}, + {map[string]any{"window": "mobileremotecontrol"}, "/mobileRemoteControl"}, + } { + opened = nil + got := must[windowOpened](t, cs, "open_window", c.args) + if len(opened) != 1 || opened[0] != c.want || got.Opened == "" { + t.Errorf("%v: opened %v (%+v), want %s", c.args, opened, got, c.want) + } + } + opened = nil + for _, c := range []struct { + args map[string]any + want string + }{ + {map[string]any{"window": "launcher"}, "remotes, commander, history"}, + {map[string]any{"window": "copy", "transfer_id": "t-1"}, "transfer_id"}, + {map[string]any{"window": "settings", "source": "box:"}, "no source"}, + {map[string]any{"window": "delete", "destination": "/x"}, "no destination"}, + } { + if _, failed := call[windowOpened](t, cs, "open_window", c.args); !strings.Contains(failed, c.want) { + t.Errorf("%v: %q, want it to say %q", c.args, failed, c.want) + } + } + if len(opened) != 0 { + t.Errorf("a refused call opened %v", opened) + } +} diff --git a/core/agents/server.go b/core/agents/server.go new file mode 100644 index 00000000..10feff5e --- /dev/null +++ b/core/agents/server.go @@ -0,0 +1,252 @@ +// Package agents lets AI agents use the app, over the Model Context Protocol (MCP). An agent that +// is connected can do what the windows do: browse the remotes, start and follow transfers, mount, +// serve, and manage schedules and watchers. The tools call the core's APIs, the same ones that +// the pages call, so the same rules apply and everything shows in History. +// +// The server is off until the user turns it on in Settings (settings.Agents). It listens on this +// computer only, and a client must send the token. There are two ways in: +// +// - HTTP, at http://127.0.0.1:/mcp, for clients that take a URL and a header; +// - `rcui mcp` (Bridge), which a client starts as a command and which passes its messages on to +// the HTTP server. It finds the server through a file in the data folder (datadir.AgentsFile). +// +// The app doesn't ask the user before a tool runs. The agent's own client does that, and each +// tool says whether it only reads or may destroy something (its annotations). Tool descriptions +// and the errors that a tool returns are in English, because a model reads them. +package agents + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core" + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/settings" +) + +const Path = "/mcp" + +type Options struct { + APIs *core.APIs + Log *slog.Logger + // DataDir is the app's data folder, where the server leaves the file that `rcui mcp` reads. + DataDir string + // Version is the app's version, which the server reports to its clients. + Version string + // OpenWindow opens the app's window for a route, such as "/history". + OpenWindow func(route string) error + // Changed is called with the new status each time the server starts, stops or fails to start. + Changed func(Status) +} + +type Status struct { + Running bool `json:"running"` + // URL is where the server answers while it runs. + URL string `json:"url"` + // Error says why the server couldn't start, in the app's language. + Error string `json:"error"` +} + +// Found is what `rcui mcp` reads from the data folder to reach the server: its address and its +// token. +type Found struct { + URL string `json:"url"` + Token string `json:"token"` +} + +// Server is the agents' server. Apply starts and stops it as the settings ask. +type Server struct { + o Options + mcp *mcp.Server + + mu sync.Mutex + cfg settings.Agents // what the running server was started with + http *http.Server + status Status + failed i18n.Text // why the last start failed, kept so that Status follows the language +} + +// New returns the server, stopped. Its tools are registered once, here. +func New(o Options) *Server { + s := &Server{o: o} + s.mcp = mcp.NewServer( + &mcp.Implementation{Name: "rclone-ui", Title: "Rclone UI", Version: o.Version}, + &mcp.ServerOptions{Instructions: instructions}, + ) + s.tools() + return s +} + +func (s *Server) Status() Status { + s.mu.Lock() + defer s.mu.Unlock() + st := s.status + st.Error = s.failed.Local() + return st +} + +// Apply makes the server match the settings: started when they turn it on, stopped when they turn +// it off, and started again when its port or its token changed. +func (s *Server) Apply(cfg settings.Agents) { + s.mu.Lock() + if cfg == s.cfg && (s.status.Running || !cfg.Enabled) { + s.mu.Unlock() + return + } + s.stop() + s.cfg = cfg + if cfg.Enabled { + s.failed = s.start(cfg) + if !s.failed.IsZero() { + s.o.Log.Error("the agents' server could not start", "port", cfg.Port, "error", s.failed.String()) + } + } + st := s.status + st.Error = s.failed.Local() + s.mu.Unlock() + if s.o.Changed != nil { + s.o.Changed(st) + } +} + +func (s *Server) Close() { + s.mu.Lock() + defer s.mu.Unlock() + s.stop() + s.cfg = settings.Agents{} +} + +// start listens on the port and serves. It returns why it couldn't, or the zero Text. s.mu is held. +func (s *Server) start(cfg settings.Agents) i18n.Text { + if cfg.Token == "" { + // The settings make a token when the server is turned on, so this is a damaged document. + return i18n.M("The agents' token is missing. Make a new one in Settings.") + } + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.Port)) + ln, err := net.Listen("tcp", addr) + if err != nil { + // i18n: %d is a port number. Another program on this computer already listens on it. + return i18n.M("Port %d is in use by another program. Choose another port.", cfg.Port) + } + handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return s.mcp }, nil) + mux := http.NewServeMux() + mux.Handle(Path, guard(cfg.Token, handler)) + s.http = &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} + go func(srv *http.Server) { + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { + s.o.Log.Error("the agents' server stopped", "error", err) + } + }(s.http) + url := "http://" + addr + Path + if err := writeFound(s.o.DataDir, Found{URL: url, Token: cfg.Token}); err != nil { + // Clients that take the URL still work. Only `rcui mcp` can't find the server. + s.o.Log.Error("could not write where the agents' server listens", "error", err) + } + s.status = Status{Running: true, URL: url} + s.o.Log.Info("the agents' server listens", "url", url) + return i18n.Text{} +} + +// stop closes the server and its connections, and removes the file that names it. s.mu is held. +func (s *Server) stop() { + if s.http == nil { + s.status, s.failed = Status{}, i18n.Text{} + return + } + // A session keeps a stream open for as long as its client stays, so the server is closed + // rather than shut down gracefully. + _ = s.http.Close() + s.http = nil + _ = os.Remove(filepath.Join(s.o.DataDir, datadir.AgentsFile)) + s.status, s.failed = Status{}, i18n.Text{} + s.o.Log.Info("the agents' server stopped") +} + +// guard lets a request through only when it is a local program's and carries the token. +// +// A web page can make this computer's browser send requests to 127.0.0.1. Such a request carries +// an Origin header, which no MCP client sends, so it is refused whatever else it holds. The SDK's +// handler also refuses a request whose Host isn't this computer (DNS rebinding). +func guard(token string, next http.Handler) http.Handler { + want := []byte("Bearer " + token) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Origin") != "" { + http.Error(w, "requests from web pages are refused", http.StatusForbidden) + return + } + got := []byte(strings.TrimSpace(r.Header.Get("Authorization"))) + if subtle.ConstantTimeCompare(got, want) != 1 { + w.Header().Set("WWW-Authenticate", `Bearer realm="Rclone UI"`) + http.Error(w, "the token is missing or wrong: copy it from Rclone UI's Settings", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} + +// writeFound writes where the server listens, in a file that only the user can read. It is +// written whole and then renamed, so `rcui mcp` never reads half of it. +func writeFound(dir string, f Found) error { + b, err := json.Marshal(f) + if err != nil { + return err + } + path := filepath.Join(dir, datadir.AgentsFile) + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// readFound reads what writeFound wrote. It fails when the server isn't running. +func readFound(dir string) (Found, error) { + b, err := os.ReadFile(filepath.Join(dir, datadir.AgentsFile)) + if err != nil { + return Found{}, err + } + var f Found + if err := json.Unmarshal(b, &f); err != nil || f.URL == "" || f.Token == "" { + return Found{}, fmt.Errorf("%s can't be read", datadir.AgentsFile) + } + return f, nil +} + +// clientName returns the name that a tool call's client gave itself, such as "Claude Code", or "" +// when it gave none. For "", History shows its own word for an agent. +func clientName(req *mcp.CallToolRequest) string { + if req != nil && req.Session != nil { + if p := req.Session.InitializeParams(); p != nil && p.ClientInfo != nil { + if p.ClientInfo.Title != "" { + return p.ClientInfo.Title + } + if p.ClientInfo.Name != "" { + return p.ClientInfo.Name + } + } + } + return "" +} + +type ctxKey struct{} + +// clientOf returns the name of the client whose tool call ctx belongs to. +func clientOf(ctx context.Context) string { + name, _ := ctx.Value(ctxKey{}).(string) + return name +} diff --git a/core/agents/server_test.go b/core/agents/server_test.go new file mode 100644 index 00000000..c9e29ccc --- /dev/null +++ b/core/agents/server_test.go @@ -0,0 +1,182 @@ +package agents + +import ( + "context" + "io" + "net" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/settings" +) + +func freePort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + return ln.Addr().(*net.TCPAddr).Port +} + +func TestAboutAndRemotes(t *testing.T) { + cs := connect(t) + a := must[about](t, cs, "about", nil) + if a.AppVersion == "" || a.RcloneVersion == "" || a.OS != runtime.GOOS { + t.Errorf("about: %+v", a) + } + list := must[remoteList](t, cs, "list_remotes", nil) + if len(list.Remotes) != 1 || list.Remotes[0].Name != "box" || list.Remotes[0].Type != "local" { + t.Errorf("list_remotes: %+v", list) + } +} + +// Every tool says what it is and whether it only reads, so that an agent's client can ask its +// user before the ones that change something. +func TestToolsAreDescribed(t *testing.T) { + cs := connect(t) + res, err := cs.ListTools(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + if len(res.Tools) == 0 { + t.Fatal("no tools") + } + for _, tool := range res.Tools { + if len(tool.Description) < 20 { + t.Errorf("%s: its description is too short to tell an agent what it does", tool.Name) + } + a := tool.Annotations + if a == nil || a.Title == "" { + t.Errorf("%s: no title", tool.Name) + continue + } + if !a.ReadOnlyHint && a.DestructiveHint == nil { + t.Errorf("%s: a tool that changes something says whether it can destroy", tool.Name) + } + } +} + +// The server runs only while the settings turn it on. It answers a client that has the token, +// and refuses one without it and any request from a web page. +func TestServerLifecycleAndGuard(t *testing.T) { + s := server(t) + var seen []Status + s.o.Changed = func(st Status) { seen = append(seen, st) } + cfg := settings.Agents{Enabled: true, Port: freePort(t), Token: "s3cret-token"} + s.Apply(cfg) + t.Cleanup(s.Close) + st := s.Status() + if !st.Running || st.Error != "" || !strings.HasSuffix(st.URL, Path) || len(seen) != 1 { + t.Fatalf("status after a start: %+v, %d changes", st, len(seen)) + } + found, err := readFound(dataDir) + if err != nil || found.URL != st.URL || found.Token != cfg.Token { + t.Fatalf("the file for the bridge: %+v %v", found, err) + } + if runtime.GOOS != "windows" { + if info, err := os.Stat(filepath.Join(dataDir, datadir.AgentsFile)); err != nil || info.Mode().Perm() != 0o600 { + t.Errorf("the file's mode: %v %v", info.Mode(), err) + } + } + + post := func(header, value string) int { + req, _ := http.NewRequest(http.MethodPost, st.URL, strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"ping"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + if header != "" { + req.Header.Set(header, value) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _, _ = io.Copy(io.Discard, res.Body) + _ = res.Body.Close() + return res.StatusCode + } + if got := post("", ""); got != http.StatusUnauthorized { + t.Errorf("without a token: %d", got) + } + if got := post("Authorization", "Bearer wrong"); got != http.StatusUnauthorized { + t.Errorf("with a wrong token: %d", got) + } + + // With the token, an agent connects over HTTP and uses a tool. + client := &http.Client{Transport: withToken{cfg.Token}} + cs := session(t, &mcp.StreamableClientTransport{Endpoint: st.URL, HTTPClient: client}) + if list := must[remoteList](t, cs, "list_remotes", nil); len(list.Remotes) != 1 { + t.Errorf("over HTTP: %+v", list) + } + // A web page's request carries an Origin, and is refused even with the token. + req, _ := http.NewRequest(http.MethodPost, st.URL, strings.NewReader(`{}`)) + req.Header.Set("Origin", "https://example.com") + res, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + _ = res.Body.Close() + if res.StatusCode != http.StatusForbidden { + t.Errorf("from a web page: %d", res.StatusCode) + } + + // A second server can't take the port, and says so. + other := server(t) + other.Apply(cfg) + if st := other.Status(); st.Running || !strings.Contains(st.Error, "in use") { + t.Errorf("a taken port: %+v", st) + } + + // A new token starts the server again, and the old token stops working. + cfg.Token = "another-token" + s.Apply(cfg) + if got := post("Authorization", "Bearer s3cret-token"); got != http.StatusUnauthorized { + t.Errorf("the old token after a new one: %d", got) + } + + cfg.Enabled = false + s.Apply(cfg) + if st := s.Status(); st.Running { + t.Errorf("status after a stop: %+v", st) + } + if _, err := readFound(dataDir); err == nil { + t.Error("the file for the bridge is still there after a stop") + } +} + +// `rcui mcp` passes an agent's messages to the server and back: the agent uses a tool through +// it, and the server sees the agent's own name. +func TestBridgeRelays(t *testing.T) { + s := server(t) + cfg := settings.Agents{Enabled: true, Port: freePort(t), Token: "bridge-token"} + s.Apply(cfg) + t.Cleanup(s.Close) + found, err := find(context.Background(), dataDir, nil) + if err != nil { + t.Fatal(err) + } + // The agent's side of the bridge's stdin and stdout. + toBridge, agentOut := io.Pipe() + agentIn, fromBridge := io.Pipe() + done := make(chan error, 1) + go func() { + done <- relay(context.Background(), found, &mcp.IOTransport{Reader: toBridge, Writer: fromBridge}) + }() + cs := session(t, &mcp.IOTransport{Reader: agentIn, Writer: agentOut}) + if list := must[remoteList](t, cs, "list_remotes", nil); len(list.Remotes) != 1 || list.Remotes[0].Name != "box" { + t.Errorf("through the bridge: %+v", list) + } + _ = cs.Close() + _ = agentOut.Close() + if err := <-done; err != nil { + t.Errorf("the bridge ended with %v", err) + } +} diff --git a/core/agents/tools.go b/core/agents/tools.go new file mode 100644 index 00000000..8c606fa7 --- /dev/null +++ b/core/agents/tools.go @@ -0,0 +1,82 @@ +package agents + +import ( + "context" + "errors" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/rclone" + "github.com/rclone/rclone-ui/core/transfers" +) + +const instructions = `Rclone UI manages files on cloud storage with rclone. Each storage the user has connected is a "remote". + +Paths: a remote path is "name:path/inside" ("gdrive:Photos/2024", or "gdrive:" for its root). A local path is absolute ("/Users/me/Documents", "C:\Users\me\Documents"). Call list_remotes first to learn the remotes' names. + +Transfers (copy, move, sync, bisync, delete, purge, download) run in the background. Starting one returns its id at once: follow it with wait_for_transfer or get_transfer, and tell the user how it ended. The user sees every transfer in the app's History window. + +Before anything that can delete or overwrite files (sync, move, delete, purge, bisync), run the same tool with dry_run set, read what it would do with get_transfer, and tell the user. Then run it for real only if that is what they asked for. + +sync makes the destination identical to the source, deleting what is only in the destination. copy never deletes. Use copy unless the user asked for a mirror. + +Options are rclone's own, by their rclone names with underscores ("max_age", "transfers"). Call list_options to see which an operation takes.` + +func (s *Server) tools() { + s.infoTools() + s.fileTools() + s.transferTools() + s.runningTools() + s.automationTools() +} + +func reads(title string) *mcp.ToolAnnotations { + return &mcp.ToolAnnotations{Title: title, ReadOnlyHint: true, OpenWorldHint: ptr(true)} +} + +// changes are the annotations of a tool that changes something without destroying anything: it +// adds files, starts something, or saves a schedule. +func changes(title string) *mcp.ToolAnnotations { + return &mcp.ToolAnnotations{Title: title, DestructiveHint: ptr(false), OpenWorldHint: ptr(true)} +} + +// destroys are the annotations of a tool that can delete or overwrite files, or stop something +// that is running. +func destroys(title string) *mcp.ToolAnnotations { + return &mcp.ToolAnnotations{Title: title, DestructiveHint: ptr(true), OpenWorldHint: ptr(true)} +} + +func ptr[T any](v T) *T { return &v } + +// add registers a tool. Around the handler, it records which client called, so that History shows +// a transfer that the call starts as the agent's (transfers.WithOrigin). It also logs the call, +// and returns an error as the core's own message, in English, because the agent reads it. +// +// The tool is registered without an output schema. Every client loads every tool's definition +// into its model's context before the first call, and output schemas would be more than half of +// that text. An output is JSON with plain names, which a model reads without a schema. +func add[In, Out any](s *Server, tool *mcp.Tool, handle func(ctx context.Context, in In) (Out, error)) { + mcp.AddTool(s.mcp, tool, func(ctx context.Context, req *mcp.CallToolRequest, in In) (*mcp.CallToolResult, any, error) { + client := clientName(req) + ctx = context.WithValue(ctx, ctxKey{}, client) + ctx = transfers.WithOrigin(ctx, transfers.Origin{Kind: transfers.OriginAgent, Name: client}) + began := time.Now() + out, err := handle(ctx, in) + if err != nil { + message := rclone.ErrorOf(err).Message + s.o.Log.Warn("an agent's tool call failed", "tool", tool.Name, "client", orUnnamed(client), "error", message) + return nil, nil, errors.New(message) + } + s.o.Log.Info("an agent called a tool", "tool", tool.Name, "client", orUnnamed(client), "took", time.Since(began).Round(time.Millisecond).String()) + return nil, out, nil + }) +} + +// orUnnamed returns a client's name for the log, where an empty name would read as a mistake. +func orUnnamed(client string) string { + if client == "" { + return "unnamed" + } + return client +} diff --git a/core/agents/transfers.go b/core/agents/transfers.go new file mode 100644 index 00000000..028c46b1 --- /dev/null +++ b/core/agents/transfers.go @@ -0,0 +1,897 @@ +package agents + +import ( + "cmp" + "context" + "encoding/json" + "fmt" + "net/url" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/rclone/rclone/fs/fspath" + + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/rclone" + "github.com/rclone/rclone-ui/core/templates" + "github.com/rclone/rclone-ui/core/transfers" +) + +const ( + transferListDefault = 20 + transferListMax = 100 + // transferChangedShown, transferFailedShown and transferCheckedShown are how many files of + // each outcome get_transfer lists. + transferChangedShown = 100 + transferFailedShown = 50 + transferCheckedShown = 20 + // transferChangedRead is how many changed files get_transfer reads, to put the deletions + // first. The record keeps the newest 1,000 of them, and a page holds at most 200. + transferChangedRead = 1000 + transferFilesPage = 200 + // transferWaitDefault and transferWaitMax are wait_for_transfer's default and longest + // timeouts, in seconds. + transferWaitDefault = 30 + transferWaitMax = 120 + // transferWaitPoll is how often wait_for_transfer reads the transfer again. + transferWaitPoll = 250 * time.Millisecond +) + +type transferStarted struct { + TransferID string `json:"transfer_id" jsonschema:"the transfer's id, for wait_for_transfer, get_transfer and stop_transfer"` + Number int64 `json:"number" jsonschema:"the transfer's number, which the app's History window shows as #12"` + // IgnoredOptions are the options that the operation doesn't take. It runs without them. + IgnoredOptions []ignoredTransferOption `json:"ignored_options" jsonschema:"the options that this operation doesn't take, each with the reason. The transfer runs without them"` +} + +type ignoredTransferOption struct { + Option string `json:"option"` + Reason string `json:"reason"` +} + +// transferCopyIn is what copy and move take. +type transferCopyIn struct { + Sources []string `json:"sources" jsonschema:"the files and folders, such as [\"gdrive:Photos/2024\", \"/Users/me/notes.txt\"]"` + Destination string `json:"destination" jsonschema:"the folder that they go into, such as \"s3:backup\""` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's options by name, such as {\"max_age\": \"7d\", \"exclude\": [\"*.tmp\"]}"` + DryRun bool `json:"dry_run,omitempty" jsonschema:"only find out what would be done, and change nothing"` +} + +type transferSyncIn struct { + Source string `json:"source" jsonschema:"the folder to copy from, such as \"/Users/me/Documents\". It is not changed"` + Destination string `json:"destination" jsonschema:"the folder to make identical to the source, such as \"gdrive:Documents\""` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's options by name, such as {\"exclude\": [\"*.tmp\"]}"` + DryRun bool `json:"dry_run,omitempty" jsonschema:"only find out what would be copied and deleted, and change nothing"` +} + +type transferBisyncIn struct { + Path1 string `json:"path1" jsonschema:"one of the two folders, such as \"/Users/me/Notes\""` + Path2 string `json:"path2" jsonschema:"the other folder, such as \"gdrive:Notes\""` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's options by name, such as {\"exclude\": [\"*.tmp\"]}"` + DryRun bool `json:"dry_run,omitempty" jsonschema:"only find out what would be copied and deleted, and change nothing"` + Resync bool `json:"resync,omitempty" jsonschema:"set the baseline: needed for the first run of two folders, and after bisync asks for it"` +} + +type transferDeleteIn struct { + Paths []string `json:"paths" jsonschema:"the folders whose files are deleted, or files, such as [\"gdrive:Old/2019\"]"` + Options map[string]any `json:"options,omitempty" jsonschema:"rclone's filter options, which narrow what is deleted, such as {\"min_age\": \"1y\"} for the files older than a year"` + DryRun bool `json:"dry_run,omitempty" jsonschema:"only find out which files would be deleted, and delete nothing"` +} + +type transferPurgeIn struct { + Paths []string `json:"paths" jsonschema:"the folders to delete with everything in them, such as [\"gdrive:Old/2019\"]"` + DryRun bool `json:"dry_run,omitempty" jsonschema:"only check the folders, and delete nothing"` +} + +type transferDownloadIn struct { + URL string `json:"url" jsonschema:"the web link, such as \"https://example.com/report.pdf\""` + Destination string `json:"destination" jsonschema:"the folder to save the file in, such as \"/Users/me/Downloads\""` + Filename string `json:"filename,omitempty" jsonschema:"the name to save it as, such as \"report.pdf\". By default, the media's own name or the link's last part"` +} + +type transferRow struct { + TransferID string `json:"transfer_id"` + Number int64 `json:"number" jsonschema:"the number that History shows, as #12"` + Operation string `json:"operation" jsonschema:"copy, move, sync, bisync, delete, purge, download or cleanup"` + Sources []string `json:"sources"` + Destination string `json:"destination,omitempty"` + // State is queued, running, completed, failed, stopped or interrupted. + State string `json:"state" jsonschema:"queued, running, completed, failed, stopped (by someone), or interrupted (the app quit while it ran)"` + DryRun bool `json:"dry_run" jsonschema:"true when it only found out what it would do, and changed nothing"` + StartedBy transferOrigin `json:"started_by"` + StartedAt string `json:"started_at"` + EndedAt string `json:"ended_at,omitempty"` + // Progress is set while the transfer runs. + Progress *transferProgress `json:"progress,omitempty"` +} + +type transferOrigin struct { + Kind string `json:"kind" jsonschema:"page or commander (the user, in the app's windows), template, watcher, schedule, or agent (an AI agent)"` + Name string `json:"name,omitempty" jsonschema:"the template's, the watcher's or the schedule's name, or the agent's"` +} + +type transferProgress struct { + Percent int `json:"percent"` + Bytes int64 `json:"bytes"` + TotalBytes int64 `json:"total_bytes" jsonschema:"the bytes to transfer that rclone has found so far"` + BytesPerSecond int64 `json:"bytes_per_second"` + ETASeconds *int64 `json:"eta_seconds,omitempty" jsonschema:"the time left, when rclone can tell"` + Files int64 `json:"files"` + TotalFiles int64 `json:"total_files"` + Errors int64 `json:"errors,omitempty"` +} + +type transferDetail struct { + transferRow + // StillRunning is set by wait_for_transfer when its timeout passed first. + StillRunning bool `json:"still_running,omitempty" jsonschema:"true when the wait ended before the transfer did: wait again"` + Error string `json:"error,omitempty" jsonschema:"why the transfer failed"` + // Errors are the errors that belong to a step or to the whole transfer, besides Error. + Errors []transferError `json:"errors,omitempty" jsonschema:"other errors that are not about a single file"` + // Totals are set once the transfer has ended. + Totals *transferTotals `json:"totals,omitempty"` + // RetryableParts is how many parts retry_transfer would run again. + RetryableParts int `json:"retryable_parts,omitempty" jsonschema:"how many failed parts retry_transfer can run again"` + // RetryOf is the number of the transfer that this one retries. + RetryOf int64 `json:"retry_of,omitempty" jsonschema:"the number of the transfer that this one retries"` + Changed transferFiles `json:"changed" jsonschema:"the files copied, moved, renamed or deleted (in a dry run: that would be), deletions first"` + Failed transferFiles `json:"failed" jsonschema:"the files that failed, each with its error"` + Checked transferFiles `json:"checked" jsonschema:"files that were compared and left as they were"` +} + +// transferError is an error about a step of a transfer, or about all of it. +type transferError struct { + About string `json:"about,omitempty" jsonschema:"the step or path that it is about"` + Error string `json:"error"` +} + +type transferTotals struct { + Bytes int64 `json:"bytes" jsonschema:"bytes copied (in a dry run: that would be)"` + FilesTransferred int64 `json:"files_transferred"` + FilesChecked int64 `json:"files_checked"` + Deleted int64 `json:"deleted" jsonschema:"files and folders deleted (in a dry run: that would be)"` + Renamed int64 `json:"renamed,omitempty"` + Errors int64 `json:"errors"` + DurationSeconds float64 `json:"duration_seconds"` +} + +// transferFiles are a transfer's files with one outcome. +type transferFiles struct { + Count int `json:"count" jsonschema:"how many files the record holds with this outcome. It keeps up to 1,000; totals has the full numbers"` + // ByAction counts the changed files by action. It covers only the files that were read. + ByAction map[string]int `json:"by_action,omitempty" jsonschema:"how many of the files were copied, deleted, moved or renamed"` + Files []transferFile `json:"files"` + Truncated bool `json:"truncated,omitempty" jsonschema:"true when files lists only some of them"` +} + +type transferFile struct { + Path string `json:"path" jsonschema:"the file's full path, or its path inside the transfer's folder when the app doesn't know which folder (a deletion's)"` + // Action is what was done to the file, in plain words (transferFileAction). + Action string `json:"action" jsonschema:"copy, delete, move, rename (such as a bisync conflict's), or check. For a failed file, what failed"` + Size int64 `json:"size"` + Error string `json:"error,omitempty"` +} + +type transferListIn struct { + State string `json:"state,omitempty" jsonschema:"keep only the transfers that are running (or queued), finished, failed or stopped"` + Search string `json:"search,omitempty" jsonschema:"keep only the transfers that it is found in: their number (#12), operation, paths, error, or who started them"` + Limit int `json:"limit,omitempty" jsonschema:"the most transfers to return: 20 by default, at most 100"` +} + +type transferList struct { + Transfers []transferRow `json:"transfers"` + Truncated bool `json:"truncated,omitempty"` + // More says how to see the transfers left out, when Truncated is set. + More string `json:"more,omitempty"` +} + +type transferIn struct { + TransferID string `json:"transfer_id" jsonschema:"the transfer's id, or its number as History shows it, such as \"#12\""` +} + +type transferWaitIn struct { + TransferID string `json:"transfer_id" jsonschema:"the transfer's id, or its number as History shows it, such as \"#12\""` + TimeoutSeconds int `json:"timeout_seconds,omitempty" jsonschema:"how long to wait at most: 30 seconds by default, at most 120"` +} + +type transferTemplate struct { + TemplateID string `json:"template_id"` + Name string `json:"name"` + Operations []string `json:"operations" jsonschema:"what the template is for: copy, move, sync, bisync, delete, purge, mount or serve"` + Sources []string `json:"sources,omitempty"` + Destination string `json:"destination,omitempty"` + // CanRunAs are the operations that run_template runs it as. + CanRunAs []string `json:"can_run_as" jsonschema:"the operations that run_template can run it as. It needs saved paths"` +} + +type transferTemplates struct { + Templates []transferTemplate `json:"templates"` +} + +type transferTemplateIn struct { + TemplateID string `json:"template_id" jsonschema:"the template's id, from list_templates"` + Operation string `json:"operation" jsonschema:"what to run it as: one of the template's can_run_as, such as \"sync\""` + DryRun bool `json:"dry_run,omitempty" jsonschema:"only find out what would be done, and change nothing"` +} + +// transferDryRunFirst ends the description of a tool that can delete or overwrite files. +const transferDryRunFirst = " Run it with dry_run first, read what it would do with get_transfer, and tell the user before you run it for real." + +// transferStartsAtOnce ends the description of a tool that starts a transfer. +const transferStartsAtOnce = " It runs in the background: this returns the transfer's id at once. Follow it with wait_for_transfer." + +func (s *Server) transferTools() { + add(s, &mcp.Tool{ + Name: "copy", + Description: "Copies files and folders into a destination folder. Each source lands in the destination under its own name: " + + "copying \"/Users/me/Photos\" to \"gdrive:Backup\" makes \"gdrive:Backup/Photos\". A remote's root (\"gdrive:\") puts its contents straight into the destination. " + + "A file that the destination already has is overwritten when the two differ. Copy never deletes anything." + transferStartsAtOnce, + Annotations: changes("Copy files"), + }, func(ctx context.Context, in transferCopyIn) (transferStarted, error) { + groups, ignored, err := transferGroups(operations.OperationCopy, in.Options) + if err != nil { + return transferStarted{}, err + } + f := operations.CopyArgs{Sources: in.Sources, Destination: in.Destination, Options: groups}.Form() + return s.startTransfer(ctx, f, in.DryRun, ignored) + }) + + add(s, &mcp.Tool{ + Name: "move", + Description: "Moves files and folders into a destination folder: each source lands in the destination under its own name, as with copy, " + + "and its files are then DELETED from the source (its folders can stay behind, empty). " + + "A file that the destination already has is overwritten when the two differ." + transferDryRunFirst + transferStartsAtOnce, + Annotations: destroys("Move files"), + }, func(ctx context.Context, in transferCopyIn) (transferStarted, error) { + groups, ignored, err := transferGroups(operations.OperationMove, in.Options) + if err != nil { + return transferStarted{}, err + } + f := operations.MoveArgs{Sources: in.Sources, Destination: in.Destination, Options: groups}.Form() + return s.startTransfer(ctx, f, in.DryRun, ignored) + }) + + add(s, &mcp.Tool{ + Name: "sync", + Description: "Makes a destination folder identical to a source folder. It copies the source's new and changed files, overwriting the destination's copies, " + + "and DELETES every file in the destination that the source doesn't have. The source's contents go straight into the destination, not into a subfolder, " + + "and the source is not changed. Use copy unless the user asked for a mirror." + transferDryRunFirst + transferStartsAtOnce, + Annotations: destroys("Sync folders"), + }, func(ctx context.Context, in transferSyncIn) (transferStarted, error) { + groups, ignored, err := transferGroups(operations.OperationSync, in.Options) + if err != nil { + return transferStarted{}, err + } + f := operations.SyncArgs{Source: in.Source, Destination: in.Destination, Options: groups}.Form() + return s.startTransfer(ctx, f, in.DryRun, ignored) + }) + + add(s, &mcp.Tool{ + Name: "bisync", + Description: "Syncs two folders both ways. New and changed files on either side are copied to the other, overwriting the older copy, " + + "and a file deleted on one side is DELETED on the other. A file changed on both sides is kept twice, renamed. " + + "The first run of two folders needs resync: it copies files both ways so that the two match (where both have a file and they differ, path1's copy wins) and deletes nothing. " + + "bisync stops by itself before deleting more than half of a side's files: the user can override that in the app's Bisync window." + transferDryRunFirst + transferStartsAtOnce, + Annotations: destroys("Bisync folders"), + }, func(ctx context.Context, in transferBisyncIn) (transferStarted, error) { + groups, ignored, err := transferGroups(operations.OperationBisync, in.Options) + if err != nil { + return transferStarted{}, err + } + if in.Resync { + groups.Outer = &operations.BisyncSwitches{Resync: true} + } + f := operations.BisyncArgs{Source: in.Path1, Destination: in.Path2, Options: groups}.Form() + return s.startTransfer(ctx, f, in.DryRun, ignored) + }) + + add(s, &mcp.Tool{ + Name: "delete", + Description: "DELETES the files inside the given paths and keeps the folders, even when they end up empty. " + + "A folder has every file in it deleted, in its subfolders too, and a file is deleted. Filter options narrow what is deleted: " + + "{\"min_age\": \"1y\"} deletes only the files older than a year, and include and exclude take patterns. It refuses a remote's root. " + + "To delete folders too, use purge." + transferDryRunFirst + transferStartsAtOnce, + Annotations: destroys("Delete files"), + }, func(ctx context.Context, in transferDeleteIn) (transferStarted, error) { + groups, ignored, err := transferGroups(operations.OperationDelete, in.Options) + if err != nil { + return transferStarted{}, err + } + f := operations.DeleteArgs{Sources: in.Paths, Options: groups}.Form() + return s.startTransfer(ctx, f, in.DryRun, ignored) + }) + + add(s, &mcp.Tool{ + Name: "purge", + Description: "DELETES the given folders and everything in them, subfolders included. It takes only folders, never a remote's root, and no filter applies. " + + "Run it with dry_run first: that checks the folders, but on most remotes it doesn't list the files inside, " + + "so also list what is in them, and tell the user what will be lost before you run it for real." + transferStartsAtOnce, + Annotations: destroys("Purge folders"), + }, func(ctx context.Context, in transferPurgeIn) (transferStarted, error) { + f := operations.PurgeArgs{Sources: in.Paths}.Form() + return s.startTransfer(ctx, f, in.DryRun, []ignoredTransferOption{}) + }) + + add(s, &mcp.Tool{ + Name: "download", + Description: "Saves the file behind a web link (http or https) in a folder. For a page of a video or image site that the app knows, it saves the media on the page; " + + "for any other link, the file at the link. A file of the same name in the folder is overwritten." + transferStartsAtOnce, + Annotations: changes("Download a link"), + }, func(ctx context.Context, in transferDownloadIn) (transferStarted, error) { + return s.startDownload(ctx, in) + }) + + add(s, &mcp.Tool{ + Name: "list_transfers", + Description: "Lists the transfers in the app's History: the running and queued ones first, then the ended ones, newest first. " + + "Each has its id, its number (#12 in History), operation, paths, state, whether it was a dry run, who started it, its times, " + + "and a running one's progress. state and search narrow the list. Returns 20 transfers by default, at most 100.", + Annotations: reads("List transfers"), + }, func(ctx context.Context, in transferListIn) (transferList, error) { + return s.listTransfers(ctx, in) + }) + + add(s, &mcp.Tool{ + Name: "get_transfer", + Description: "Reads one transfer in full: its state, progress or totals, its errors, and its files by outcome: changed (copied, moved, renamed or deleted), failed and checked. " + + "For a dry run, nothing was changed: the changed files are what the real run WOULD copy or delete. Report them to the user, deletions first. " + + "Each list is capped, and its count and totals say how many there are in all.", + Annotations: reads("Read a transfer"), + }, func(ctx context.Context, in transferIn) (transferDetail, error) { + id, err := s.transferID(ctx, in.TransferID) + if err != nil { + return transferDetail{}, err + } + d, err := s.o.APIs.Transfers.Get(ctx, id) + if err != nil { + return transferDetail{}, err + } + return s.transferDetailOf(ctx, d) + }) + + add(s, &mcp.Tool{ + Name: "wait_for_transfer", + Description: "Waits until a transfer ends, or until timeout_seconds pass (30 by default, at most 120), and then returns what get_transfer returns. " + + "still_running is true when the time ran out first: call it again to keep waiting.", + Annotations: reads("Wait for a transfer"), + }, func(ctx context.Context, in transferWaitIn) (transferDetail, error) { + id, err := s.transferID(ctx, in.TransferID) + if err != nil { + return transferDetail{}, err + } + timeout := in.TimeoutSeconds + if timeout <= 0 { + timeout = transferWaitDefault + } + return s.waitTransfer(ctx, id, time.Duration(min(timeout, transferWaitMax))*time.Second) + }) + + add(s, &mcp.Tool{ + Name: "stop_transfer", + Description: "Stops a running or queued transfer. What it has already copied or deleted stays that way. " + + "It is recorded as stopped, and returned as list_transfers shows it.", + Annotations: destroys("Stop a transfer"), + }, func(ctx context.Context, in transferIn) (transferRow, error) { + id, err := s.transferID(ctx, in.TransferID) + if err != nil { + return transferRow{}, err + } + if err := s.o.APIs.Transfers.Stop(ctx, id); err != nil { + return transferRow{}, err + } + d, err := s.o.APIs.Transfers.Get(ctx, id) + if err != nil { + return transferRow{}, err + } + return transferRowOf(d.Transfer), nil + }) + + add(s, &mcp.Tool{ + Name: "retry_transfer", + Description: "Runs the parts of an ended transfer that failed again, with the same settings and the same dry run setting, as a new transfer. " + + "It does what the original did, so the retry of a move, a sync, a bisync, a delete or a purge can delete files. " + + "get_transfer's retryable_parts says how many parts there are to retry." + transferStartsAtOnce, + Annotations: destroys("Retry a transfer"), + }, func(ctx context.Context, in transferIn) (transferStarted, error) { + id, err := s.transferID(ctx, in.TransferID) + if err != nil { + return transferStarted{}, err + } + st, err := s.o.APIs.Transfers.Retry(ctx, id, nil) + if err != nil { + return transferStarted{}, transferStartError(err) + } + return transferStarted{TransferID: st.ID, Number: st.Seq, IgnoredOptions: []ignoredTransferOption{}}, nil + }) + + add(s, &mcp.Tool{ + Name: "list_templates", + Description: "Lists the user's saved templates: named sets of rclone options that the user made in the app, often with the paths to run them on. " + + "Each has its id, its name, the operations it is for, its paths, and the operations that run_template can run it as.", + Annotations: reads("List templates"), + }, func(ctx context.Context, _ nothing) (transferTemplates, error) { + list, err := s.o.APIs.Templates.List(ctx) + if err != nil { + return transferTemplates{}, err + } + out := transferTemplates{Templates: make([]transferTemplate, 0, len(list.Templates))} + for _, t := range list.Templates { + out.Templates = append(out.Templates, transferTemplateOf(t)) + } + return out, nil + }) + + add(s, &mcp.Tool{ + Name: "run_template", + Description: "Runs a saved template as one of its operations (copy, move, sync, bisync, delete or purge), on its own paths and with its own options. " + + "A template that moves, syncs, bisyncs, deletes or purges can delete or overwrite files." + transferDryRunFirst + transferStartsAtOnce, + Annotations: destroys("Run a template"), + }, func(ctx context.Context, in transferTemplateIn) (transferStarted, error) { + return s.runSavedTemplate(ctx, in) + }) +} + +// transferGroups sorts an agent's flat options into the groups of op's form, as a template's +// options are sorted (operations.TemplateGroups), and returns the options that op doesn't take, +// with the reasons in English. +func transferGroups(op operations.Operation, options map[string]any) (operations.Groups, []ignoredTransferOption, error) { + flat := catalog.Group{} + for key, v := range options { + // The value was read from JSON, so it is written back as it was. + raw, err := json.Marshal(v) + if err != nil { + return operations.Groups{}, nil, fmt.Errorf("the option %s: %w", key, err) + } + flat[key] = raw + } + groups, skipped, err := operations.TemplateGroups(op, "", flat) + if err != nil { + return operations.Groups{}, nil, err + } + return groups, transferIgnored(skipped), nil +} + +func transferIgnored(skipped []catalog.SkippedFlag) []ignoredTransferOption { + out := make([]ignoredTransferOption, 0, len(skipped)) + for _, sk := range skipped { + out = append(out, ignoredTransferOption{Option: sk.Flag, Reason: sk.Reason}) + } + return out +} + +// startTransfer starts the transfer of a form as an operation's window does, with the form as +// its preset, so that History can open the window with it again. The context makes the +// transfer the agent's. +func (s *Server) startTransfer(ctx context.Context, f operations.Form, dryRun bool, ignored []ignoredTransferOption) (transferStarted, error) { + return s.startTransferWith(ctx, f, f, dryRun, ignored) +} + +// startTransferWith is startTransfer with a preset that differs from the form, as a download's +// does. +func (s *Server) startTransferWith(ctx context.Context, f, preset operations.Form, dryRun bool, ignored []ignoredTransferOption) (transferStarted, error) { + st, err := s.o.APIs.Transfers.Start(ctx, f, transfers.StartOptions{DryRun: dryRun, Origin: transfers.OriginPage, Preset: &preset}) + if err != nil { + return transferStarted{}, transferStartError(err) + } + return transferStarted{TransferID: st.ID, Number: st.Seq, IgnoredOptions: ignored}, nil +} + +// transferStartError returns the error of a start as the agent reads it. A transfer that failed +// at once was recorded first, so the error names it, for get_transfer. rclone refuses the first +// bisync of two folders until a resync sets their baseline: the Bisync window offers that resync, +// and the agent is told how to run it. +func transferStartError(err error) error { + e := errs.Of(err) + switch { + case e == nil || e.Transfer == nil: + return err + case e.What == operations.WhatBisyncBaseline: + return errs.New("These two folders have never been bisynced together, so bisync has no baseline to compare them with. " + + "Run bisync again with resync set to true (with dry_run first): it copies files both ways so that the two folders match " + + "(where both have a file and they differ, path1's copy wins), and deletes nothing.") + } + // i18n: rclone's error, then the number and the id of the transfer that failed. Only AI agents read this. + return errs.Errorf("%s (The transfer failed as #%d, transfer_id %s: get_transfer shows what failed.)", rclone.ErrorOf(err).Message, e.Transfer.Seq, e.Transfer.ID) +} + +// startDownload starts a download as the Download window does. A page of a site that the link +// service knows is looked up, and the media found there is downloaded under its own name. Any +// other link is downloaded as it is, under the last part of its path. The preset keeps the link +// as the agent gave it, so that History's Duplicate looks it up again. +func (s *Server) startDownload(ctx context.Context, in transferDownloadIn) (transferStarted, error) { + typed := operations.DownloadArgs{URL: strings.TrimSpace(in.URL), Filename: strings.TrimSpace(in.Filename), Destination: in.Destination} + run := typed + // The window downloads the link itself when the lookup fails, and so does this. + if link, err := s.o.APIs.Links.Resolve(ctx, typed.URL); err == nil && link.Found { + run.URL = link.URL + if run.Filename == "" { + run.Filename = link.Filename + } + } + if run.Filename == "" { + run.Filename = linkFilename(typed.URL) + } + if run.Filename == "" { + return transferStarted{}, errs.New("The link doesn't end in a file name. Give the file a name with filename.") + } + return s.startTransferWith(ctx, run.Form(), typed.Form(), false, []ignoredTransferOption{}) +} + +// linkFilename returns the last part of a link's path, decoded, as the Download window names a +// link's file. It returns "" when the path ends in a slash or the link can't be read. +func linkFilename(link string) string { + u, err := url.Parse(link) + if err != nil { + return "" + } + escaped := u.EscapedPath() + last := escaped[strings.LastIndex(escaped, "/")+1:] + if last == "" { + return "" + } + // A part that decodes to a path, such as "a%2Fb", is kept as it is written. + if name, err := url.PathUnescape(last); err == nil && !strings.ContainsAny(name, `/\`) && name != "." && name != ".." { + return name + } + return last +} + +// listTransfers lists the open transfers, then the ended ones, newest first. +func (s *Server) listTransfers(ctx context.Context, in transferListIn) (transferList, error) { + limit := in.Limit + if limit <= 0 { + limit = transferListDefault + } + limit = min(limit, transferListMax) + open, ended := true, true + var state transfers.State + switch strings.ToLower(strings.TrimSpace(in.State)) { + case "": + case "running", "queued": + ended = false + case "finished", "completed": + open, state = false, transfers.StateCompleted + case "failed": + open, state = false, transfers.StateFailed + case "stopped", "interrupted": + open, state = false, transfers.StateStopped + default: + return transferList{}, errs.New("state is running, finished, failed or stopped, or leave it out for every transfer.") + } + + out := transferList{Transfers: []transferRow{}} + if open { + active, err := s.o.APIs.Transfers.ListActive(ctx) + if err != nil { + return transferList{}, err + } + for _, t := range active { + if !transfers.Matches(t, in.Search) { + continue + } + if len(out.Transfers) == limit { + out.Truncated = true + break + } + out.Transfers = append(out.Transfers, transferRowOf(t)) + } + } + if ended && !out.Truncated { + // At least one is asked for, to learn whether the list goes on. + left := limit - len(out.Transfers) + page, err := s.o.APIs.Transfers.ListEnded(ctx, transfers.EndedQuery{Limit: max(left, 1), State: state, Search: in.Search}) + if err != nil { + return transferList{}, err + } + items := page.Items[:min(left, len(page.Items))] + for _, t := range items { + out.Transfers = append(out.Transfers, transferRowOf(t)) + } + out.Truncated = page.More || len(items) < len(page.Items) + } + if out.Truncated { + out.More = "There are more transfers. Raise limit (at most 100), or narrow the list with state or search." + } + return out, nil +} + +// transferID returns the id of the transfer that an agent names: by its id, or by its number as +// History shows it ("#12", or "12"). +func (s *Server) transferID(ctx context.Context, named string) (string, error) { + named = strings.TrimSpace(named) + if named == "" { + return "", errs.New("Name the transfer by its transfer_id, or by its number, such as #12.") + } + if seq, err := strconv.ParseInt(strings.TrimPrefix(named, "#"), 10, 64); err == nil { + return s.o.APIs.Transfers.IDOf(ctx, seq) + } + return named, nil +} + +// waitTransfer reads the transfer every transferWaitPoll until it has ended, the timeout has +// passed, or the call is cancelled. When the timeout passes first, it reads the transfer once +// more and returns it with StillRunning set. +func (s *Server) waitTransfer(ctx context.Context, id string, timeout time.Duration) (transferDetail, error) { + deadline := time.NewTimer(timeout) + defer deadline.Stop() + tick := time.NewTicker(transferWaitPoll) + defer tick.Stop() + late := false + for { + d, err := s.o.APIs.Transfers.Get(ctx, id) + if err != nil { + return transferDetail{}, err + } + if d.EndedAt != nil || late { + out, err := s.transferDetailOf(ctx, d) + out.StillRunning = d.EndedAt == nil + return out, err + } + select { + case <-ctx.Done(): + return transferDetail{}, ctx.Err() + case <-deadline.C: + late = true + case <-tick.C: + } + } +} + +// transferTime writes a time in milliseconds since the epoch as RFC 3339, in this computer's +// time zone, or "" for no time. +func transferTime(ms int64) string { + if ms == 0 { + return "" + } + return time.UnixMilli(ms).Format(time.RFC3339) +} + +func transferRowOf(t transfers.Transfer) transferRow { + row := transferRow{ + TransferID: t.ID, Number: t.Seq, Operation: string(t.Operation), Sources: t.Sources, + Destination: t.Destination, State: string(t.State), DryRun: t.IsDryRun, + StartedBy: transferOrigin{Kind: string(t.Origin.Kind), Name: t.Origin.Name}, + StartedAt: transferTime(t.CreatedAt), + } + if row.Sources == nil { + row.Sources = []string{} + } + if t.StartedAt != nil { + row.StartedAt = transferTime(*t.StartedAt) + } + if t.EndedAt != nil { + row.EndedAt = transferTime(*t.EndedAt) + } + if p := t.Live; p != nil && t.EndedAt == nil { + row.Progress = &transferProgress{ + Percent: p.Pct, Bytes: p.Bytes, TotalBytes: p.TotalBytes, BytesPerSecond: int64(p.Speed), + ETASeconds: p.Eta, Files: p.Files, TotalFiles: p.TotalFiles, Errors: p.Errors, + } + } + return row +} + +// transferDetailOf returns a transfer in full, as get_transfer shows it: the row, its errors in +// English, its totals, and its files by outcome. +func (s *Server) transferDetailOf(ctx context.Context, d transfers.Detail) (transferDetail, error) { + out := transferDetail{ + transferRow: transferRowOf(d.Transfer), + Error: d.ErrorText().String(), + RetryableParts: d.Retryable, + } + for _, g := range d.General { + text := g.ErrorText().String() + // The transfer's own error is often its one general error too. + if g.Subject == "" && text == out.Error { + continue + } + out.Errors = append(out.Errors, transferError{About: g.Subject, Error: text}) + } + if d.RetryOf != nil { + out.RetryOf = d.RetryOf.Seq + } + if st := d.Stats; st != nil { + out.Totals = &transferTotals{ + Bytes: st.Bytes, FilesTransferred: st.Transfers, FilesChecked: st.Checks, Deleted: st.Deletes, + Renamed: st.Renames, Errors: st.Errors, DurationSeconds: float64(st.DurationMs) / 1000, + } + } + var err error + if out.Changed, err = s.transferChanged(ctx, d.ID); err != nil { + return transferDetail{}, err + } + if out.Failed, err = s.transferFilesOf(ctx, d.ID, transfers.OutcomeFailed, transferFailedShown); err != nil { + return transferDetail{}, err + } + if out.Checked, err = s.transferFilesOf(ctx, d.ID, transfers.OutcomeChecked, transferCheckedShown); err != nil { + return transferDetail{}, err + } + return out, nil +} + +// transferFilesOf returns the newest files of a transfer with one outcome, at most limit of +// them. +func (s *Server) transferFilesOf(ctx context.Context, id string, outcome transfers.Outcome, limit int) (transferFiles, error) { + page, err := s.o.APIs.Transfers.Files(ctx, id, outcome, "", limit) + if err != nil { + return transferFiles{}, err + } + out := transferFiles{Count: page.Total, Files: make([]transferFile, 0, len(page.Items)), Truncated: page.More} + for _, f := range page.Items { + out.Files = append(out.Files, transferFileOf(f)) + } + return out, nil +} + +// transferChanged returns the files that a transfer changed, or that its dry run would change. +// It reads as many as the record keeps, so that it can count them by action and list the +// deletions, which matter most to the user, before the copies. +func (s *Server) transferChanged(ctx context.Context, id string) (transferFiles, error) { + var all []transferFile + out := transferFiles{ByAction: map[string]int{}} + for before := ""; len(all) < transferChangedRead; { + page, err := s.o.APIs.Transfers.Files(ctx, id, transfers.OutcomeTransferred, before, transferFilesPage) + if err != nil { + return transferFiles{}, err + } + out.Count = page.Total + for _, f := range page.Items { + all = append(all, transferFileOf(f)) + } + if !page.More || len(page.Items) == 0 { + break + } + before = page.Items[len(page.Items)-1].Cursor + } + for _, f := range all { + out.ByAction[f.Action]++ + } + slices.SortStableFunc(all, func(a, b transferFile) int { + return cmp.Or(cmp.Compare(transferActionRank(a.Action), transferActionRank(b.Action)), strings.Compare(a.Path, b.Path)) + }) + out.Files = all[:min(len(all), transferChangedShown)] + out.Truncated = len(out.Files) < out.Count + if out.Files == nil { + out.Files = []transferFile{} + } + if len(out.ByAction) == 0 { + out.ByAction = nil + } + return out, nil +} + +// transferActionRank orders changed files for the agent: deletions first, then moves and +// renames, then anything else, and the copies last. +func transferActionRank(action string) int { + switch action { + case "delete": + return 0 + case "move": + return 1 + case "rename": + return 2 + case "copy": + return 4 + } + return 3 +} + +// transferFileOf returns a file of a transfer as an agent reads it. Its path is in the folder +// that rclone names as its source. A deletion names none, so its path is the one inside the +// folder that the transfer deleted it from. +func transferFileOf(f transfers.File) transferFile { + path := f.Name + if f.SrcFs != "" { + path = transferFilePath(f.SrcFs, f.Name) + } + return transferFile{Path: path, Action: transferFileAction(f.What), Size: f.Size, Error: f.Error} +} + +// transferFilePath returns the path of the file called name in the folder that rclone names +// srcFs. The app opens a local folder as a remote of the local backend, so rclone names it +// ":local:/tmp/x". On Windows rclone uses the long form ("//?/C:/x", or "//?/UNC/server/share/x" +// for a share). Both are turned back into the plain local path, as the agent wrote it. Any other +// file is named by rclone's own join. +func transferFilePath(srcFs, name string) string { + root, ok := strings.CutPrefix(srcFs, ":local:") + if ok && runtime.GOOS == "windows" { + if share, isShare := strings.CutPrefix(root, "//?/UNC/"); isShare { + root = "//" + share + } else { + root = strings.TrimPrefix(root, "//?/") + } + } + if !ok || !filepath.IsAbs(filepath.FromSlash(root)) { + return fspath.JoinRootPath(srcFs, name) + } + return filepath.Join(filepath.FromSlash(root), filepath.FromSlash(name)) +} + +// transferFileAction returns what rclone did to a file (its "what") in plain words. +func transferFileAction(what string) string { + switch what { + case "transferring": + return "copy" + case "deleting": + return "delete" + case "moving": + return "move" + case "renaming": + return "rename" + case "checking", "hashing", "listing": + return "check" + case "merging": + return "merge" + } + return what +} + +// transferTemplateOf returns a template as list_templates shows it. Its options are left out, +// because they are rclone's own flags, which could hold a backend's secret. +func transferTemplateOf(t templates.Template) transferTemplate { + out := transferTemplate{TemplateID: t.ID, Name: t.Name, Operations: []string{}, CanRunAs: []string{}} + for _, tag := range t.Tags { + out.Operations = append(out.Operations, string(tag)) + if t.Paths != nil && runsAsTransfer(tag) { + out.CanRunAs = append(out.CanRunAs, string(tag)) + } + } + if t.Paths != nil { + out.Sources, out.Destination = t.Paths.Sources, t.Paths.Destination + } + return out +} + +// runsAsTransfer reports whether a template for op runs as a transfer. A mount's or a serve's +// template is only applied in its window. +func runsAsTransfer(op operations.Operation) bool { + switch op { + case operations.OperationCopy, operations.OperationMove, operations.OperationSync, + operations.OperationBisync, operations.OperationDelete, operations.OperationPurge: + return true + } + return false +} + +// runSavedTemplate runs a saved template as one of its operations. History shows the run as the +// template's, as when the user runs it. The core can't start a template as a dry run, so a dry +// run starts the template's form like any other tool's transfer, and History shows it as the +// agent's. +func (s *Server) runSavedTemplate(ctx context.Context, in transferTemplateIn) (transferStarted, error) { + list, err := s.o.APIs.Templates.List(ctx) + if err != nil { + return transferStarted{}, err + } + i := slices.IndexFunc(list.Templates, func(t templates.Template) bool { return t.ID == in.TemplateID }) + if i < 0 { + return transferStarted{}, errs.New("No saved template has this id. list_templates lists them.") + } + t, op := list.Templates[i], operations.Operation(strings.ToLower(strings.TrimSpace(in.Operation))) + if t.Paths == nil || !runsAsTransfer(op) || !slices.Contains(t.Tags, op) { + return transferStarted{}, errs.New("This template can't run as that operation. Its can_run_as, in list_templates, lists the ones it can.") + } + _, skipped, err := operations.TemplateGroups(op, "", t.Options) + if err != nil { + return transferStarted{}, err + } + ignored := transferIgnored(skipped) + if in.DryRun { + f, err := operations.TemplateArgs(op, t.Paths.Sources, t.Paths.Destination, t.Options) + if err != nil { + return transferStarted{}, err + } + return s.startTransfer(ctx, f, true, ignored) + } + st, err := s.o.APIs.Transfers.StartTemplate(ctx, t.ID, op) + if err != nil { + return transferStarted{}, transferStartError(err) + } + return transferStarted{TransferID: st.ID, Number: st.Seq, IgnoredOptions: ignored}, nil +} diff --git a/core/agents/transfers_test.go b/core/agents/transfers_test.go new file mode 100644 index 00000000..d402587f --- /dev/null +++ b/core/agents/transfers_test.go @@ -0,0 +1,559 @@ +package agents + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/templates" +) + +// writeTransferFiles writes files under dir, by their slash-separated paths, with their +// contents. +func writeTransferFiles(t *testing.T, dir string, files map[string]string) { + t.Helper() + for name, body := range files { + path := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } +} + +func transferExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// awaitTransfer waits for a transfer to end, as an agent does, and returns it. +func awaitTransfer(t *testing.T, cs *mcp.ClientSession, id string) transferDetail { + t.Helper() + d := must[transferDetail](t, cs, "wait_for_transfer", map[string]any{"transfer_id": id, "timeout_seconds": 60}) + if d.StillRunning || d.EndedAt == "" { + t.Fatalf("%s is still running after a minute: %+v", id, d.transferRow) + } + return d +} + +func pathsOfTransferFiles(files []transferFile) []string { + out := make([]string, len(files)) + for i, f := range files { + out[i] = f.Path + } + return out +} + +// A copy runs in the background as the agent's, and the agent follows it to its end and finds it +// in the list, by its id or its number. +func TestCopy(t *testing.T) { + cs := connect(t) + src, dst := filepath.Join(t.TempDir(), "Photos"), t.TempDir() + writeTransferFiles(t, src, map[string]string{"a.jpg": "aaa", "trip/b.jpg": "bbbb"}) + + started := must[transferStarted](t, cs, "copy", map[string]any{"sources": []string{"box:" + src}, "destination": dst}) + if started.TransferID == "" || started.Number <= 0 || started.IgnoredOptions == nil { + t.Fatalf("copy: %+v", started) + } + d := awaitTransfer(t, cs, started.TransferID) + if d.State != "completed" || d.Operation != "copy" || d.DryRun || d.Error != "" { + t.Fatalf("the copy ended as %+v", d) + } + if d.StartedBy != (transferOrigin{Kind: "agent", Name: "Test Agent"}) { + t.Errorf("started by %+v", d.StartedBy) + } + for _, name := range []string{"a.jpg", "trip/b.jpg"} { + if !transferExists(filepath.Join(dst, "Photos", filepath.FromSlash(name))) { + t.Errorf("%s was not copied into the destination under its folder's name", name) + } + } + if d.Totals == nil || d.Totals.FilesTransferred != 2 || d.Totals.Bytes != 7 { + t.Errorf("totals %+v", d.Totals) + } + if d.Changed.Count != 2 || d.Changed.ByAction["copy"] != 2 || len(d.Changed.Files) != 2 || d.Changed.Truncated { + t.Errorf("changed %+v", d.Changed) + } + for _, f := range d.Changed.Files { + if f.Action != "copy" || !strings.HasPrefix(f.Path, "box:") || !strings.HasSuffix(f.Path, ".jpg") || f.Size == 0 { + t.Errorf("a copied file: %+v", f) + } + } + + // The number that History shows names the same transfer. + byNumber := must[transferDetail](t, cs, "get_transfer", map[string]any{"transfer_id": fmt.Sprintf("#%d", started.Number)}) + if byNumber.TransferID != started.TransferID { + t.Errorf("#%d is %s, want %s", started.Number, byNumber.TransferID, started.TransferID) + } + if _, failed := call[transferDetail](t, cs, "get_transfer", map[string]any{"transfer_id": "#999999999"}); !strings.Contains(failed, "No such transfer") { + t.Errorf("an unknown number: %q", failed) + } + if _, failed := call[transferDetail](t, cs, "get_transfer", map[string]any{"transfer_id": "nope"}); failed == "" { + t.Error("an unknown id was found") + } + + list := must[transferList](t, cs, "list_transfers", map[string]any{"search": src}) + if len(list.Transfers) != 1 || list.Transfers[0].TransferID != started.TransferID || list.Truncated { + t.Errorf("list_transfers: %+v", list) + } +} + +// An option that the operation doesn't take is left out and named, and an option's value that +// rclone can't read is refused. +func TestCopyOptions(t *testing.T) { + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + writeTransferFiles(t, src, map[string]string{"keep.txt": "k", "skip.log": "s"}) + + started := must[transferStarted](t, cs, "copy", map[string]any{ + "sources": []string{src}, "destination": dst, + "options": map[string]any{"exclude": []string{"*.log"}, "no_such_option": true, "vfs_cache_mode": "full"}, + }) + var ignored []string + for _, o := range started.IgnoredOptions { + if o.Reason == "" { + t.Errorf("%s is ignored without a reason", o.Option) + } + ignored = append(ignored, o.Option) + } + slices.Sort(ignored) + if !slices.Equal(ignored, []string{"no_such_option", "vfs_cache_mode"}) { + t.Errorf("ignored %+v", started.IgnoredOptions) + } + if d := awaitTransfer(t, cs, started.TransferID); d.State != "completed" { + t.Fatalf("the copy ended as %+v", d) + } + folder := filepath.Join(dst, filepath.Base(src)) + if !transferExists(filepath.Join(folder, "keep.txt")) || transferExists(filepath.Join(folder, "skip.log")) { + t.Error("the exclude option was not applied") + } + // A local file is named by its path, as the agent wrote the source. + if d := must[transferDetail](t, cs, "get_transfer", map[string]any{"transfer_id": started.TransferID}); len(d.Changed.Files) != 1 || + d.Changed.Files[0].Path != filepath.Join(src, "keep.txt") { + t.Errorf("the copied files: %+v", d.Changed.Files) + } + + if _, failed := call[transferStarted](t, cs, "copy", map[string]any{ + "sources": []string{src}, "destination": dst, "options": map[string]any{"max_age": "banana"}, + }); failed == "" { + t.Error("a max_age of banana was taken") + } + if _, failed := call[transferStarted](t, cs, "copy", map[string]any{ + "sources": []string{filepath.Join(src, "missing")}, "destination": dst, + }); failed == "" { + t.Error("a missing source was copied") + } + if _, failed := call[transferStarted](t, cs, "copy", map[string]any{"sources": []string{src}}); failed == "" { + t.Error("a copy without a destination started") + } +} + +// A sync's dry run lists the copies and the deletions it would make, deletions first, and +// changes nothing. The real run then makes the destination match. +func TestSyncDryRunThenReal(t *testing.T) { + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + writeTransferFiles(t, src, map[string]string{"new.txt": "new"}) + writeTransferFiles(t, dst, map[string]string{"old.txt": "old"}) + + dry := must[transferStarted](t, cs, "sync", map[string]any{"source": src, "destination": "box:" + dst, "dry_run": true}) + d := awaitTransfer(t, cs, dry.TransferID) + if d.State != "completed" || !d.DryRun { + t.Fatalf("the dry run ended as %+v", d) + } + if !transferExists(filepath.Join(dst, "old.txt")) || transferExists(filepath.Join(dst, "new.txt")) { + t.Fatal("the dry run changed the destination") + } + files := d.Changed.Files + if len(files) != 2 || files[0].Action != "delete" || !strings.HasSuffix(files[0].Path, "old.txt") || + files[1].Action != "copy" || !strings.HasSuffix(files[1].Path, "new.txt") { + t.Errorf("the dry run would change %+v", files) + } + if d.Changed.ByAction["delete"] != 1 || d.Changed.ByAction["copy"] != 1 { + t.Errorf("by action %v", d.Changed.ByAction) + } + if d.Totals == nil || d.Totals.Deleted != 1 || d.Totals.FilesTransferred != 1 { + t.Errorf("the dry run's totals %+v", d.Totals) + } + + real := must[transferStarted](t, cs, "sync", map[string]any{"source": src, "destination": "box:" + dst}) + if d := awaitTransfer(t, cs, real.TransferID); d.State != "completed" || d.DryRun { + t.Fatalf("the sync ended as %+v", d) + } + if transferExists(filepath.Join(dst, "old.txt")) || !transferExists(filepath.Join(dst, "new.txt")) { + t.Error("the sync didn't make the destination match the source") + } +} + +func TestMove(t *testing.T) { + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + writeTransferFiles(t, src, map[string]string{"box/f.txt": "f", "g.txt": "g"}) + + started := must[transferStarted](t, cs, "move", map[string]any{ + "sources": []string{filepath.Join(src, "box"), filepath.Join(src, "g.txt")}, "destination": dst, + }) + if d := awaitTransfer(t, cs, started.TransferID); d.State != "completed" || d.Operation != "move" { + t.Fatalf("the move ended as %+v", d) + } + if !transferExists(filepath.Join(dst, "box", "f.txt")) || !transferExists(filepath.Join(dst, "g.txt")) { + t.Error("the files are not in the destination") + } + if transferExists(filepath.Join(src, "box", "f.txt")) || transferExists(filepath.Join(src, "g.txt")) { + t.Error("the files are still in the source") + } +} + +// The first bisync of two folders is refused with what to do instead, a resync sets the +// baseline, and later runs carry changes both ways. +func TestBisync(t *testing.T) { + cs := connect(t) + one, two := t.TempDir(), t.TempDir() + writeTransferFiles(t, one, map[string]string{"one.txt": "1"}) + writeTransferFiles(t, two, map[string]string{"two.txt": "2"}) + args := map[string]any{"path1": one, "path2": "box:" + two} + + if _, failed := call[transferStarted](t, cs, "bisync", args); !strings.Contains(failed, "resync") { + t.Fatalf("a first bisync: %q", failed) + } + dry := must[transferStarted](t, cs, "bisync", map[string]any{"path1": one, "path2": "box:" + two, "resync": true, "dry_run": true}) + if d := awaitTransfer(t, cs, dry.TransferID); d.State != "completed" || !d.DryRun { + t.Fatalf("the resync's dry run ended as %+v", d) + } + if transferExists(filepath.Join(one, "two.txt")) || transferExists(filepath.Join(two, "one.txt")) { + t.Fatal("the dry run copied files") + } + resync := must[transferStarted](t, cs, "bisync", map[string]any{"path1": one, "path2": "box:" + two, "resync": true}) + if d := awaitTransfer(t, cs, resync.TransferID); d.State != "completed" { + t.Fatalf("the resync ended as %+v", d) + } + if !transferExists(filepath.Join(one, "two.txt")) || !transferExists(filepath.Join(two, "one.txt")) { + t.Fatal("the resync didn't copy both ways") + } + + writeTransferFiles(t, two, map[string]string{"later.txt": "later"}) + if err := os.Remove(filepath.Join(one, "one.txt")); err != nil { + t.Fatal(err) + } + run := must[transferStarted](t, cs, "bisync", args) + if d := awaitTransfer(t, cs, run.TransferID); d.State != "completed" { + t.Fatalf("the bisync ended as %+v", d) + } + if !transferExists(filepath.Join(one, "later.txt")) || transferExists(filepath.Join(two, "one.txt")) { + t.Error("the bisync didn't carry the new file and the deletion across") + } +} + +// A delete deletes the files that its filters keep and leaves the folders. A purge deletes whole +// folders. Neither takes a remote's root, and a purge takes no file. +func TestDeleteAndPurge(t *testing.T) { + cs := connect(t) + dir := t.TempDir() + writeTransferFiles(t, dir, map[string]string{"a.txt": "a", "b.log": "b", "sub/c.log": "c"}) + args := map[string]any{"paths": []string{"box:" + dir}, "options": map[string]any{"include": []string{"*.log"}}} + + dry := must[transferStarted](t, cs, "delete", map[string]any{ + "paths": []string{"box:" + dir}, "options": map[string]any{"include": []string{"*.log"}}, "dry_run": true, + }) + d := awaitTransfer(t, cs, dry.TransferID) + got := pathsOfTransferFiles(d.Changed.Files) + slices.Sort(got) + if d.State != "completed" || !d.DryRun || !slices.Equal(got, []string{"b.log", "sub/c.log"}) || d.Changed.ByAction["delete"] != 2 { + t.Fatalf("the dry run would delete %v: %+v", got, d) + } + if !transferExists(filepath.Join(dir, "b.log")) { + t.Fatal("the dry run deleted a file") + } + real := must[transferStarted](t, cs, "delete", args) + if d := awaitTransfer(t, cs, real.TransferID); d.State != "completed" { + t.Fatalf("the delete ended as %+v", d) + } + if !transferExists(filepath.Join(dir, "a.txt")) || transferExists(filepath.Join(dir, "b.log")) || + transferExists(filepath.Join(dir, "sub", "c.log")) || !transferExists(filepath.Join(dir, "sub")) { + t.Error("the delete didn't delete just the .log files, keeping the folders") + } + + writeTransferFiles(t, dir, map[string]string{"gone/x.txt": "x", "gone/deep/y.txt": "y"}) + purged := must[transferStarted](t, cs, "purge", map[string]any{"paths": []string{filepath.Join(dir, "gone")}}) + if d := awaitTransfer(t, cs, purged.TransferID); d.State != "completed" || d.Operation != "purge" { + t.Fatalf("the purge ended as %+v", d) + } + if transferExists(filepath.Join(dir, "gone")) || !transferExists(filepath.Join(dir, "a.txt")) { + t.Error("the purge didn't delete just its folder") + } + + // Refused before anything runs. The dry runs keep them harmless all the same. + for _, c := range []struct{ tool, path string }{ + {"delete", "box:"}, {"purge", "box:"}, {"purge", filepath.Join(dir, "a.txt")}, {"purge", filepath.Join(dir, "missing")}, + } { + if _, failed := call[transferStarted](t, cs, c.tool, map[string]any{"paths": []string{c.path}, "dry_run": true}); failed == "" { + t.Errorf("%s of %s was taken", c.tool, c.path) + } + } + if !transferExists(filepath.Join(dir, "a.txt")) { + t.Error("a refused purge deleted a file") + } +} + +// A download saves a link's file under the link's name or the one given, and asks for a name +// when the link has none. +func TestDownload(t *testing.T) { + cs := connect(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("report body")) + })) + t.Cleanup(srv.Close) + dir := t.TempDir() + + started := must[transferStarted](t, cs, "download", map[string]any{"url": srv.URL + "/files/q3%20report.txt", "destination": dir}) + if d := awaitTransfer(t, cs, started.TransferID); d.State != "completed" || d.Operation != "download" { + t.Fatalf("the download ended as %+v", d) + } + if b, err := os.ReadFile(filepath.Join(dir, "q3 report.txt")); err != nil || string(b) != "report body" { + t.Errorf("the downloaded file: %q, %v", b, err) + } + + named := must[transferStarted](t, cs, "download", map[string]any{"url": srv.URL + "/", "destination": dir, "filename": "index.html"}) + if d := awaitTransfer(t, cs, named.TransferID); d.State != "completed" || !transferExists(filepath.Join(dir, "index.html")) { + t.Fatalf("a named download ended as %+v", d) + } + if _, failed := call[transferStarted](t, cs, "download", map[string]any{"url": srv.URL + "/", "destination": dir}); !strings.Contains(failed, "filename") { + t.Errorf("a link without a file name: %q", failed) + } +} + +// A running transfer shows its progress in the list. A wait that times out says so, a stop +// ends the transfer as stopped, and a transfer that isn't running can't be stopped. +func TestWaitAndStop(t *testing.T) { + cs := connect(t) + // The link sends a little of a large file, and then nothing until it is stopped. + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "100000000") + _, _ = w.Write(make([]byte, 1024)) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(func() { close(release); srv.Close() }) + dir := t.TempDir() + + started := must[transferStarted](t, cs, "download", map[string]any{"url": srv.URL + "/big.bin", "destination": dir}) + waited := must[transferDetail](t, cs, "wait_for_transfer", map[string]any{"transfer_id": started.TransferID, "timeout_seconds": 1}) + if !waited.StillRunning || waited.State != "running" || waited.EndedAt != "" { + t.Fatalf("a wait that timed out: %+v", waited.transferRow) + } + running := must[transferList](t, cs, "list_transfers", map[string]any{"state": "running", "search": dir}) + if len(running.Transfers) != 1 || running.Transfers[0].TransferID != started.TransferID { + t.Fatalf("the running transfers: %+v", running) + } + + stopped := must[transferRow](t, cs, "stop_transfer", map[string]any{"transfer_id": started.TransferID}) + if stopped.State != "stopped" { + t.Errorf("after a stop: %+v", stopped) + } + if d := awaitTransfer(t, cs, started.TransferID); d.State != "stopped" { + t.Errorf("a stopped transfer ended as %+v", d) + } + if _, failed := call[transferRow](t, cs, "stop_transfer", map[string]any{"transfer_id": started.TransferID}); !strings.Contains(failed, "not running") { + t.Errorf("a second stop: %q", failed) + } +} + +// A failed transfer's failures can be retried, and the retry is a new transfer that keeps the +// original's origin. A transfer with nothing that failed has nothing to retry. +func TestRetry(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("a file can't be made unreadable here") + } + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + writeTransferFiles(t, src, map[string]string{"ok.txt": "ok", "locked.txt": "locked"}) + locked := filepath.Join(src, "locked.txt") + if err := os.Chmod(locked, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(locked, 0o644) }) + + // The copy fails within the moment that a start waits for, so the start fails, and names the + // transfer that it recorded. + _, failed := call[transferStarted](t, cs, "copy", map[string]any{"sources": []string{src}, "destination": dst}) + list := must[transferList](t, cs, "list_transfers", map[string]any{"search": src, "state": "failed"}) + if len(list.Transfers) != 1 || !strings.Contains(failed, list.Transfers[0].TransferID) { + t.Fatalf("the copy's start: %q, and the failed transfers %+v", failed, list) + } + started := list.Transfers[0] + d := awaitTransfer(t, cs, started.TransferID) + if d.State != "failed" || d.Failed.Count != 1 || len(d.Failed.Files) != 1 || + !strings.HasSuffix(d.Failed.Files[0].Path, "locked.txt") || d.Failed.Files[0].Error == "" || d.RetryableParts == 0 { + t.Fatalf("the copy ended as %+v", d) + } + if err := os.Chmod(locked, 0o644); err != nil { + t.Fatal(err) + } + retry := must[transferStarted](t, cs, "retry_transfer", map[string]any{"transfer_id": fmt.Sprintf("#%d", started.Number)}) + r := awaitTransfer(t, cs, retry.TransferID) + if r.State != "completed" || r.RetryOf != started.Number || r.StartedBy.Kind != "agent" { + t.Fatalf("the retry ended as %+v", r) + } + if !transferExists(filepath.Join(dst, filepath.Base(src), "locked.txt")) { + t.Error("the retry didn't copy the file") + } + if _, failed := call[transferStarted](t, cs, "retry_transfer", map[string]any{"transfer_id": retry.TransferID}); failed == "" { + t.Error("a transfer with nothing that failed was retried") + } +} + +// The list puts the newest first, and is capped. Its state must be one that it knows. +func TestListTransfers(t *testing.T) { + cs := connect(t) + src := t.TempDir() + writeTransferFiles(t, src, map[string]string{"f.txt": "f"}) + var numbers []int64 + for range 3 { + started := must[transferStarted](t, cs, "copy", map[string]any{"sources": []string{filepath.Join(src, "f.txt")}, "destination": t.TempDir()}) + awaitTransfer(t, cs, started.TransferID) + numbers = append(numbers, started.Number) + } + + all := must[transferList](t, cs, "list_transfers", map[string]any{"search": src, "limit": 10}) + if len(all.Transfers) != 3 || all.Truncated { + t.Fatalf("all: %+v", all) + } + for i, row := range all.Transfers { + if row.Number != numbers[2-i] || row.State != "completed" || row.StartedAt == "" || row.EndedAt == "" || row.Progress != nil { + t.Errorf("row %d: %+v", i, row) + } + } + capped := must[transferList](t, cs, "list_transfers", map[string]any{"search": src, "limit": 2}) + if len(capped.Transfers) != 2 || !capped.Truncated || capped.More == "" || capped.Transfers[0].Number != numbers[2] { + t.Errorf("capped: %+v", capped) + } + if finished := must[transferList](t, cs, "list_transfers", map[string]any{"search": src, "state": "finished"}); len(finished.Transfers) != 3 { + t.Errorf("finished: %+v", finished) + } + if failed := must[transferList](t, cs, "list_transfers", map[string]any{"search": src, "state": "failed"}); len(failed.Transfers) != 0 { + t.Errorf("failed: %+v", failed) + } + if _, failed := call[transferList](t, cs, "list_transfers", map[string]any{"state": "sleeping"}); failed == "" { + t.Error("an unknown state was taken") + } +} + +// get_transfer caps the changed files and puts the deletions first, and the count still says +// how many there are. +func TestChangedFilesAreCapped(t *testing.T) { + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + files := map[string]string{} + for i := range transferChangedShown + 20 { + files[fmt.Sprintf("f%03d.txt", i)] = "x" + } + writeTransferFiles(t, src, files) + writeTransferFiles(t, dst, map[string]string{"zzz-extra.txt": "old"}) + + dry := must[transferStarted](t, cs, "sync", map[string]any{"source": src, "destination": dst, "dry_run": true}) + d := awaitTransfer(t, cs, dry.TransferID) + c := d.Changed + if c.Count != transferChangedShown+21 || len(c.Files) != transferChangedShown || !c.Truncated || + c.ByAction["copy"] != transferChangedShown+20 || c.ByAction["delete"] != 1 { + t.Fatalf("changed: count %d, %d files, truncated %v, %v", c.Count, len(c.Files), c.Truncated, c.ByAction) + } + if c.Files[0].Action != "delete" || c.Files[0].Path != "zzz-extra.txt" { + t.Errorf("the deletion is not first: %+v", c.Files[0]) + } +} + +// The user's templates are listed with the operations that they run as, and run, for real or +// as a dry run. A template runs only as an operation that it has paths for. +func TestTemplates(t *testing.T) { + cs := connect(t) + src, dst := t.TempDir(), t.TempDir() + writeTransferFiles(t, src, map[string]string{"a.txt": "a", "b.log": "b"}) + ctx := context.Background() + saved, err := apis.Templates.Save(ctx, templates.Template{ + Name: "Backup " + filepath.Base(src), + Tags: []operations.Operation{operations.OperationCopy, operations.OperationMount}, + Options: catalog.Group{ + "exclude": json.RawMessage(`["*.log"]`), + "vfs_cache_mode": json.RawMessage(`"full"`), + }, + Paths: &templates.Paths{Sources: []string{src}, Destination: dst}, + }) + if err != nil { + t.Fatal(err) + } + bare, err := apis.Templates.Save(ctx, templates.Template{Name: "Options only", Tags: []operations.Operation{operations.OperationSync}}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = apis.Templates.DeleteMany(ctx, []string{saved.ID, bare.ID}) }) + + list := must[transferTemplates](t, cs, "list_templates", nil) + byID := map[string]transferTemplate{} + for _, tpl := range list.Templates { + byID[tpl.TemplateID] = tpl + } + if got := byID[saved.ID]; got.Name != saved.Name || !slices.Equal(got.Operations, []string{"copy", "mount"}) || + !slices.Equal(got.CanRunAs, []string{"copy"}) || !slices.Equal(got.Sources, []string{src}) || got.Destination != dst { + t.Errorf("the template: %+v", got) + } + if got := byID[bare.ID]; len(got.CanRunAs) != 0 || got.Sources != nil { + t.Errorf("a template without paths: %+v", got) + } + + dry := must[transferStarted](t, cs, "run_template", map[string]any{"template_id": saved.ID, "operation": "copy", "dry_run": true}) + if len(dry.IgnoredOptions) != 1 || dry.IgnoredOptions[0].Option != "vfs_cache_mode" { + t.Errorf("ignored %+v", dry.IgnoredOptions) + } + if d := awaitTransfer(t, cs, dry.TransferID); d.State != "completed" || !d.DryRun || d.Changed.Count != 1 { + t.Fatalf("the dry run ended as %+v", d) + } + if transferExists(filepath.Join(dst, filepath.Base(src))) { + t.Fatal("the dry run copied files") + } + run := must[transferStarted](t, cs, "run_template", map[string]any{"template_id": saved.ID, "operation": "copy"}) + d := awaitTransfer(t, cs, run.TransferID) + if d.State != "completed" || d.StartedBy != (transferOrigin{Kind: "template", Name: saved.Name}) { + t.Fatalf("the run ended as %+v", d) + } + if !transferExists(filepath.Join(dst, filepath.Base(src), "a.txt")) || transferExists(filepath.Join(dst, filepath.Base(src), "b.log")) { + t.Error("the template's paths or options were not applied") + } + + for _, c := range []struct{ id, op string }{{saved.ID, "mount"}, {saved.ID, "sync"}, {bare.ID, "sync"}, {"nope", "copy"}} { + if _, failed := call[transferStarted](t, cs, "run_template", map[string]any{"template_id": c.id, "operation": c.op, "dry_run": true}); failed == "" { + t.Errorf("%s ran as %s", c.id, c.op) + } + } +} + +func TestLinkFilename(t *testing.T) { + for link, want := range map[string]string{ + "https://example.com/a/report.pdf": "report.pdf", + "https://example.com/q3%20plan.txt": "q3 plan.txt", + "https://example.com/a%2Fb": "a%2Fb", + "https://example.com/": "", + "https://example.com": "", + "https://example.com/file.zip?x=1#y": "file.zip", + } { + if got := linkFilename(link); got != want { + t.Errorf("%s: %q, want %q", link, got, want) + } + } +} diff --git a/core/alive_unix_test.go b/core/alive_unix_test.go new file mode 100644 index 00000000..2d1ffa01 --- /dev/null +++ b/core/alive_unix_test.go @@ -0,0 +1,15 @@ +//go:build !windows + +package core + +import ( + "errors" + "syscall" +) + +// alive reports whether process pid is still running. A zombie that hasn't been waited for +// doesn't count. +func alive(pid int) bool { + err := syscall.Kill(pid, 0) + return err == nil || !errors.Is(err, syscall.ESRCH) +} diff --git a/core/alive_windows_test.go b/core/alive_windows_test.go new file mode 100644 index 00000000..e149463f --- /dev/null +++ b/core/alive_windows_test.go @@ -0,0 +1,13 @@ +package core + +import "golang.org/x/sys/windows" + +func alive(pid int) bool { + h, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid)) + if err != nil { + return false + } + defer func() { _ = windows.CloseHandle(h) }() + ev, _ := windows.WaitForSingleObject(h, 0) + return ev == uint32(windows.WAIT_TIMEOUT) +} diff --git a/core/apis.go b/core/apis.go new file mode 100644 index 00000000..076aade3 --- /dev/null +++ b/core/apis.go @@ -0,0 +1,242 @@ +package core + +import ( + "context" + + "github.com/rclone/rclone-ui/core/app" + "github.com/rclone/rclone-ui/core/browse" + "github.com/rclone/rclone-ui/core/catalog" + "github.com/rclone/rclone-ui/core/config" + "github.com/rclone/rclone-ui/core/datadir" + "github.com/rclone/rclone-ui/core/favorites" + "github.com/rclone/rclone-ui/core/files" + "github.com/rclone/rclone-ui/core/internal/late" + "github.com/rclone/rclone-ui/core/launcher" + "github.com/rclone/rclone-ui/core/linkresolve" + "github.com/rclone/rclone-ui/core/logs" + "github.com/rclone/rclone-ui/core/media" + "github.com/rclone/rclone-ui/core/mounts" + "github.com/rclone/rclone-ui/core/notifications" + "github.com/rclone/rclone-ui/core/operations" + "github.com/rclone/rclone-ui/core/prefs" + "github.com/rclone/rclone-ui/core/remotes" + "github.com/rclone/rclone-ui/core/schedules" + "github.com/rclone/rclone-ui/core/serves" + "github.com/rclone/rclone-ui/core/settings" + "github.com/rclone/rclone-ui/core/telemetry" + "github.com/rclone/rclone-ui/core/templates" + "github.com/rclone/rclone-ui/core/transfers" + "github.com/rclone/rclone-ui/core/tunnel" + "github.com/rclone/rclone-ui/core/vfs" + "github.com/rclone/rclone-ui/core/watchers" +) + +// Emit sends an event to the window that made the call ctx belongs to. When ctx doesn't belong +// to a call, it sends the event to every window. +type Emit func(ctx context.Context, name string, data any) + +// APIs are the APIs that the pages call, one per domain. The shell binds them before the core +// starts. A call that arrives early waits for its service, and fails with Unavailable when the +// core failed to start. The calls that need nothing from the boot answer at once: the log, the +// app's info, and the catalog's backends and options (all but its Values). The links wait for the +// boot like the rest, because their first request fixes the proxy for the whole process, and +// rclone's init sets it. +type APIs struct { + Prefs *prefs.API + Settings *settings.API + Favorites *favorites.API + Templates *templates.API + Launcher *launcher.API + Logs *logs.API + Vfs *vfs.API + Media *media.API + Files *files.API + Catalog *catalog.API + Config *config.API + Remotes *remotes.API + Mounts *mounts.API + Serves *serves.API + Tunnel *tunnel.API + Notifications *notifications.API + Browse *browse.API + Transfers *transfers.API + Watchers *watchers.API + Schedules *schedules.API + Links *linkresolve.API + Telemetry *telemetry.API + App *app.API + + telemetry *late.Value[*telemetry.Service] + lister *late.Value[*browse.Lister] + transfers *late.Value[*transfers.Service] + core *late.Value[*Core] + sets []func(*Core) + fails []func(error) +} + +// bind returns a value that an API waits for. Once the core has started, get reads the value +// from it. +func bind[T any](a *APIs, get func(*Core) T) *late.Value[T] { + v := late.New[T]() + a.sets = append(a.sets, func(c *Core) { v.Set(get(c)) }) + a.fails = append(a.fails, v.Fail) + return v +} + +type APIOptions struct { + Emit Emit + // Log is the app's log, which the core is given too (Options.Log). The Logs API reads it at + // once. nil means the log that the core opens, once the core has started. + Log *logs.Log + // DataDir is the app's data folder, as the core is given it (Options.DataDir). "" means the + // OS's default. + DataDir string +} + +func NewAPIs(o APIOptions) *APIs { + a := &APIs{} + dir := o.DataDir + if dir == "" { + // When the default can't be found, the core can't start either, and says why. + dir, _ = datadir.Default() + } + log := late.Of(o.Log) + if o.Log == nil { + log = bind(a, func(c *Core) *logs.Log { return c.logs }) + } + a.Prefs = prefs.NewAPI(bind(a, func(c *Core) *prefs.Service { return c.prefs })) + a.Settings = settings.NewAPI(bind(a, func(c *Core) *settings.Service { return c.settings })) + a.Favorites = favorites.NewAPI(bind(a, func(c *Core) *favorites.Service { return c.favorites })) + a.Templates = templates.NewAPI(bind(a, func(c *Core) *templates.Service { return c.templates })) + a.Launcher = launcher.NewAPI(bind(a, func(c *Core) *launcher.Service { return c.launcher })) + a.Logs = logs.NewAPI(log) + a.Vfs = vfs.NewAPI(bind(a, func(c *Core) *vfs.Service { return c.vfs })) + a.Media = media.NewAPI(bind(a, func(c *Core) *media.Signer { return c.media })) + a.Files = files.NewAPI(bind(a, func(c *Core) *files.Service { return c.files })) + a.Catalog = catalog.NewAPI(catalog.New(executable()), bind(a, func(*Core) struct{} { return struct{}{} })) + a.Config = config.NewAPI(bind(a, func(c *Core) *config.Service { return c.configs })) + a.Remotes = remotes.NewAPI(bind(a, func(c *Core) *remotes.Service { return c.remotes })) + a.Mounts = mounts.NewAPI(bind(a, func(c *Core) *mounts.Service { return c.mounts })) + a.Serves = serves.NewAPI(bind(a, func(c *Core) *serves.Service { return c.serves })) + a.Tunnel = tunnel.NewAPI(bind(a, func(c *Core) *tunnel.Service { return c.tunnel })) + a.Notifications = notifications.NewAPI(bind(a, func(c *Core) *notifications.Service { return c.notifications })) + a.lister = bind(a, func(c *Core) *browse.Lister { return c.lister }) + a.Browse = browse.NewAPI(a.lister, o.Emit) + a.transfers = bind(a, func(c *Core) *transfers.Service { return c.transfers }) + a.Transfers = transfers.NewAPI(a.transfers, bind(a, func(c *Core) transfers.Templates { return c.templates })) + a.Watchers = watchers.NewAPI(bind(a, func(c *Core) *watchers.Service { return c.watchers })) + a.Schedules = schedules.NewAPI(bind(a, func(c *Core) *schedules.Service { return c.schedules })) + a.Links = linkresolve.NewAPI(bind(a, func(c *Core) *linkresolve.Resolver { return c.links })) + a.telemetry = bind(a, func(c *Core) *telemetry.Service { return c.telemetry }) + a.Telemetry = telemetry.NewAPI(a.telemetry) + a.App = app.NewAPI(dir) + a.core = bind(a, func(c *Core) *Core { return c }) + return a +} + +// ListFolder lists a folder for the shell's launcher. It calls page with the rows as they +// arrive. +func (a *APIs) ListFolder(ctx context.Context, path string, page func([]browse.Row)) error { + l, err := a.lister.Get(ctx) + if err != nil { + return err + } + // The launcher shows no dates, so it never waits for slow ones. + _, _, err = browse.ListFolder(ctx, l, path, false, false, page) + return err +} + +// ListRows lists a folder for the agents' server, and returns all the rows together. It asks +// rclone rather than the cache, because the agent may have just changed the folder by other +// means. It returns at most browse.ListMax rows, and whether the listing stopped there. Like +// ListFolder, it never waits for slow dates. +func (a *APIs) ListRows(ctx context.Context, path string) ([]browse.Row, bool, error) { + l, err := a.lister.Get(ctx) + if err != nil { + return nil, false, err + } + var rows []browse.Row + _, capped, err := browse.ListFolder(ctx, l, path, true, false, func(page []browse.Row) { rows = append(rows, page...) }) + if err != nil { + return nil, false, err + } + return rows, capped, nil +} + +// SearchRows finds the entries under a folder whose names contain q, for the agents' server +// (browse.SearchFolder), and returns all the rows together, without the slow dates. It returns at +// most limit rows, and whether the search stopped there. When the walk stops early, it returns the +// rows found so far along with the error: ctx's error, or browse.ErrWalkMax at +// browse.SearchWalkMax entries. +func (a *APIs) SearchRows(ctx context.Context, path, q string, limit int) ([]browse.Row, bool, error) { + if _, err := a.core.Get(ctx); err != nil { + return nil, false, err + } + var rows []browse.Row + capped, err := browse.SearchFolder(ctx, path, q, limit, false, func(page []browse.Row) { rows = append(rows, page...) }) + return rows, capped, err +} + +// CountFolder counts the files and their bytes below a folder, for the agents' server +// (browse.CountFolder). When ctx ends partway, it returns the counts so far with ctx's error. +func (a *APIs) CountFolder(ctx context.Context, path string) (browse.Size, error) { + return late.Call(ctx, a.core, func(*Core) (browse.Size, error) { return browse.CountFolder(ctx, path) }) +} + +// ReadFile returns the first limit bytes of a file, for the agents' server (media.Read). +func (a *APIs) ReadFile(ctx context.Context, path string, limit int64) (media.Start, error) { + return late.Call(ctx, a.core, func(*Core) (media.Start, error) { return media.Read(ctx, path, limit) }) +} + +// StartCleanup starts the launcher's cleanup of a remote's trash and old file versions as a +// transfer, which History follows. transfers.API.Start doesn't start a cleanup, because no page +// does. +func (a *APIs) StartCleanup(ctx context.Context, remote string) (transfers.Started, error) { + return late.Call(ctx, a.transfers, func(s *transfers.Service) (transfers.Started, error) { + return s.Start(ctx, transfers.Spec{ + Form: operations.CleanupArgs{Remote: remote}.Form(), Origin: transfers.Origin{Kind: transfers.OriginPage}, + }) + }) +} + +// StopAll is the launcher's Stop Everything (see Core.StopAll). No page calls it. +func (a *APIs) StopAll(ctx context.Context) (StopSummary, error) { + return late.Call(ctx, a.core, func(c *Core) (StopSummary, error) { return c.StopAll(ctx) }) +} + +// set gives each API its service, once every service has started. +func (a *APIs) set(c *Core) { + if a == nil { + return + } + for _, set := range a.sets { + set(c) + } +} + +// fail makes every waiting API call, and every later one, fail with Unavailable. +func (a *APIs) fail(err error) { + if a == nil { + return + } + for _, fail := range a.fails { + fail(err) + } +} + +// Screen records that a window opened, by its fixed name, in the usage data that the user shares +// (core/telemetry). The shell calls it. It never waits, and does nothing before the core is up. +func (a *APIs) Screen(window string) { + if s, ok := a.telemetry.Ready(); ok { + s.Screen(window) + } +} + +// Panic reports a panic that was recovered and logged, as a crash report, when the user shares +// them. source is the part of the app that logged it. The shell calls it for every such line of +// the log (telemetry.TapPanics). It never waits, and does nothing before the core is up. +func (a *APIs) Panic(source, value, stack string) { + if s, ok := a.telemetry.Ready(); ok { + s.Panic(source, value, []byte(stack)) + } +} diff --git a/core/apis_test.go b/core/apis_test.go new file mode 100644 index 00000000..e8c0c11d --- /dev/null +++ b/core/apis_test.go @@ -0,0 +1,77 @@ +package core + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/internal/testutil" + "github.com/rclone/rclone-ui/core/logs" +) + +// The APIs that need nothing from the boot answer before any core starts: the log, the app's +// info, and the catalog's backends and options. The others wait for the core, as the catalog's +// Values does, because it reads what rclone's init sets. Once the core fails, the waiting ones +// fail with Unavailable, and the early ones keep answering. +func TestEarlyAPIsAnswerBeforeTheBoot(t *testing.T) { + dir := t.TempDir() + l, err := logs.Open(logs.Options{Path: filepath.Join(dir, "rcui.log")}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close() }) + l.Append(logs.Record{Message: "a line before the core"}) + + apis := NewAPIs(APIOptions{Log: l, DataDir: dir}) + // Nothing sets the APIs, so a call that waited would fail with this deadline. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + if info, err := apis.App.Info(ctx); err != nil || info.DataDir != dir || info.PID != os.Getpid() || info.StartedAt == 0 { + t.Errorf("Info: %+v %v", info, err) + } + // The log writes its lines on its own goroutine, so they reach the tail a moment later. + testutil.Eventually(t, 2*time.Second, "the log's lines", func() bool { + lines, err := apis.Logs.Tail(ctx, 10) + return err == nil && len(lines) > 0 + }) + if cat, err := apis.Catalog.Get(ctx); err != nil || len(cat.Backends) == 0 { + t.Errorf("Get: %d backends, %v", len(cat.Backends), err) + } + if b, err := apis.Catalog.Backend(ctx, "local", ""); err != nil || b.Backend.Name != "local" { + t.Errorf("Backend: %+v %v", b.Backend.Name, err) + } + if p, err := apis.Catalog.ParseCommand(ctx, "rclone copy a: b: --transfers 8"); err != nil || len(p.Args) == 0 { + t.Errorf("ParseCommand: %+v %v", p, err) + } + + short, stop := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer stop() + if _, err := apis.Catalog.Values(short); !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("Values before the boot: %v, want it to wait", err) + } + if _, err := apis.Links.Resolve(short, "https://example.com/a"); !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("Resolve before the boot: %v, want it to wait", err) + } + + apis.fail(errors.New("the data folder is locked")) + if _, err := apis.Catalog.Values(ctx); !unavailable(err) { + t.Errorf("Values after a failed boot: %v", err) + } + if _, err := apis.Settings.Get(ctx); !unavailable(err) { + t.Errorf("Settings after a failed boot: %v", err) + } + if info, err := apis.App.Info(ctx); err != nil || info.DataDir != dir { + t.Errorf("Info after a failed boot: %+v %v", info, err) + } +} + +// unavailable reports whether err is the Unavailable error of an API whose core didn't start. +func unavailable(err error) bool { + e := errs.Of(err) + return e != nil && e.Code == errs.CodeUnavailable +} diff --git a/core/app/api.go b/core/app/api.go new file mode 100644 index 00000000..c4ec2bfd --- /dev/null +++ b/core/app/api.go @@ -0,0 +1,43 @@ +// Package app describes the running app: its versions and the machine it runs on. +package app + +import ( + "context" + "os" + "runtime" + "time" + + "github.com/rclone/rclone-ui/core/version" +) + +type Info struct { + AppVersion string `json:"appVersion"` + RcloneVersion string `json:"rcloneVersion"` + Arch string `json:"arch"` + GoVersion string `json:"goVersion"` + // StartedAt is when the app started, in milliseconds since the epoch. + StartedAt int64 `json:"startedAt"` + DataDir string `json:"dataDir"` + PID int `json:"pid"` +} + +// started is when the process started, near enough: package variables are set before main runs. +var started = time.Now() + +// API returns information about the running app. Nothing in it waits for the core, so it answers +// at once, even when the core can't start. +type API struct{ info Info } + +func NewAPI(dataDir string) *API { + return &API{info: Info{ + AppVersion: version.App, + RcloneVersion: version.Rclone(), + Arch: runtime.GOARCH, + GoVersion: runtime.Version(), + StartedAt: started.UnixMilli(), + DataDir: dataDir, + PID: os.Getpid(), + }} +} + +func (a *API) Info(context.Context) (Info, error) { return a.info, nil } diff --git a/core/browse/api.go b/core/browse/api.go new file mode 100644 index 00000000..131c8ba7 --- /dev/null +++ b/core/browse/api.go @@ -0,0 +1,571 @@ +package browse + +import ( + "context" + "errors" + "slices" + "strings" + "sync" + "time" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/fspath" + "github.com/rclone/rclone/fs/operations" + + "github.com/rclone/rclone-ui/core/children" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/internal/ids" + "github.com/rclone/rclone-ui/core/internal/late" + "github.com/rclone/rclone-ui/core/location" + "github.com/rclone/rclone-ui/core/rclone" +) + +// The events that a listing, a search, a folder count and a Disk Usage scan send to the window +// that asked for them. +const ( + EventRows = "browse:rows" + EventSize = "browse:size" + EventUsage = "browse:usage" +) + +// perFrame is the most rows that one event carries. A cached listing of 50 000 rows is sent in +// pieces, and the page shows each piece as it arrives. +const perFrame = 2000 + +// Row is one entry of a listing or a search. +type Row struct { + // Path is the entry's full path, with the root written the same way as in the requested folder. + Path string `json:"path"` + Name string `json:"name"` + Size int64 `json:"size"` + ModTime string `json:"modTime"` + IsDir bool `json:"isDir"` + ID string `json:"id"` + Tier string `json:"tier"` + IsBucket bool `json:"isBucket"` + // Below is the path of a search match, relative to the folder that was searched. + Below string `json:"below,omitempty"` +} + +// Rows is one piece of the rows of a listing or a search, tagged with its request. The last +// piece has Done set and no rows. +type Rows struct { + Request string `json:"request"` + Entries []Row `json:"entries"` + Done bool `json:"done,omitempty"` + // FetchedAt is when rclone listed the folder, in ms since the epoch. Only the last piece of a + // listing sets it. + FetchedAt int64 `json:"fetchedAt,omitempty"` + // Capped reports that the rows stopped at ListMax or SearchMax. + Capped bool `json:"capped,omitempty"` +} + +// FolderSize is the count for one folder, tagged with its request. The last one has Done set +// and no path. +type FolderSize struct { + Request string `json:"request"` + Path string `json:"path,omitempty"` + Files int64 `json:"files"` + Bytes int64 `json:"bytes"` + // Partial marks counts that are incomplete because the work stopped partway through the folder. + Partial bool `json:"partial,omitempty"` + Done bool `json:"done,omitempty"` +} + +// CompareResult is the comparison of two folders side by side. +type CompareResult struct { + Pairs []Pair `json:"pairs"` + Capped bool `json:"capped"` +} + +// API lists, searches and counts folders for the pages, and answers their other questions about +// entries. +type API struct { + l *late.Value[*Lister] + emit func(ctx context.Context, name string, data any) + mounts func() ([]string, error) + usage usageScans +} + +// NewAPI returns the API over the listings cache, which l provides once the core has started. +// emit sends an event to the window that made the call in ctx. +func NewAPI(l *late.Value[*Lister], emit func(ctx context.Context, name string, data any)) *API { + return &API{l: l, emit: emit, mounts: children.MountPoints} +} + +// inJob runs one read as an rclone job in its own stats group (ui//), and deletes the +// group afterwards. Running it as a job has three effects. A fatal rclone error while opening a +// remote (such as a bad override) becomes the read's error instead of ending the core. The +// global.* keys of a connection string apply only to that remote. And the Fs stays in rclone's +// cache while the read uses it. +func inJob(ctx context.Context, kind string, fn func(ctx context.Context) error) error { + group := rclone.UIGroup(kind, ids.New()) + defer rclone.DeleteGroup(context.WithoutCancel(ctx), group) + _, err := rclone.Run(ctx, rclone.CallOpts{Group: group}, fn) + return err +} + +// folderOf splits a requested folder into the root that rclone opens and the folder below it, +// using location.Split. It refuses an empty path with the message missing, and paths that rclone +// would refuse or misread with the message from location.Problem. Both the listing's cache entry +// and the paths of its rows come from this split. +func folderOf(p, field string, missing i18n.Text) (location.Fs, error) { + if p == "" { + return location.Fs{}, errs.Invalid(missing, errs.Violation(field, "missing")) + } + if err := location.FieldRefusal(field, p); err != nil { + // The page receives it as Invalid, with the field and the same sentence as its message. + return location.Fs{}, err + } + // FieldRefusal has already refused every path that Split can't read. + at, _ := location.Split(p) + return at, nil +} + +// rowOf turns an entry below at's root into the Row a page reads. The row carries the full path, +// with the root written as in the requested folder, so that pages never build paths themselves. +func rowOf(at location.Fs, e Entry) Row { + return Row{ + Path: at.Entry(e.Path), Name: e.Name, Size: e.Size, ModTime: e.ModTime, + IsDir: e.IsDir, ID: e.ID, Tier: e.Tier, IsBucket: e.IsBucket, + } +} + +// pieces converts rows with row and passes them to send in pieces of at most perFrame. +func pieces(rows []Entry, row func(Entry) Row, send func([]Row)) { + for len(rows) > 0 { + n := min(len(rows), perFrame) + out := make([]Row, n) + for i, e := range rows[:n] { + out[i] = row(e) + } + send(out) + rows = rows[n:] + } +} + +// ListFolder lists a folder from the cache while the cached copy is fresh, and from rclone +// otherwise. It calls page with the rows as each batch arrives. It returns when rclone listed +// the folder (in ms since the epoch) and whether the rows stopped at ListMax. +func ListFolder(ctx context.Context, l *Lister, path string, fresh, fileDates bool, page func([]Row)) (fetchedAt int64, capped bool, err error) { + at, err := folderOf(path, "path", i18n.M("Specify the folder to list.")) + if err != nil { + return 0, false, err + } + row := func(e Entry) Row { return rowOf(at, e) } + n := 0 + err = inJob(ctx, "list", func(ctx context.Context) (err error) { + fetchedAt, err = l.List(ctx, at.Root(), at.Rel, fresh, fileDates, ListMax, func(rows []Entry) { + n += len(rows) + pieces(rows, row, page) + }) + return err + }) + if err != nil { + return 0, false, err + } + return fetchedAt, n >= ListMax, nil +} + +// List lists a folder, sending its rows as EventRows for request. fileDates reads the files' dates +// on S3, Swift and the other backends where each costs a request (Commander's File dates). +func (a *API) List(ctx context.Context, request, path string, fresh, fileDates bool) error { + return a.l.Do(ctx, func(l *Lister) error { + fetchedAt, capped, err := ListFolder(ctx, l, path, fresh, fileDates, func(rows []Row) { + a.emit(ctx, EventRows, Rows{Request: request, Entries: rows}) + }) + if err != nil { + return err + } + a.emit(ctx, EventRows, Rows{Request: request, Entries: []Row{}, Done: true, FetchedAt: fetchedAt, Capped: capped}) + return nil + }) +} + +// errCapped stops a search at its most matches. +var errCapped = errors.New("enough results") + +// SearchFolder finds the entries under the folder at path whose names contain q (Search, which +// reads at most SearchWalkMax entries), and calls page with their rows as they are found. It +// stops after max matches, and reports whether it did. When the walk ended at SearchWalkMax, it +// returns ErrWalkMax, after the rows it found. fileDates is as for List. +func SearchFolder(ctx context.Context, path, q string, max int, fileDates bool, page func([]Row)) (capped bool, err error) { + if q == "" { + return false, errs.Invalid(i18n.M("Nothing to search for."), errs.Violation("q", "missing")) + } + at, err := folderOf(path, "path", i18n.M("Specify the folder to search.")) + if err != nil { + return false, err + } + // A match is shown by its path below the folder searched. + row := func(e Entry) Row { + r := rowOf(at, e) + r.Below = strings.TrimPrefix(e.Path, at.Dir()) + return r + } + ctx, stop := context.WithCancelCause(ctx) + defer stop(nil) + n := 0 + err = inJob(ctx, "search", func(ctx context.Context) error { + return Search(ctx, at.Root(), at.Rel, q, SearchWalkMax, fileDates, func(found []Entry) { + if n >= max { + return + } + found = found[:min(len(found), max-n)] + n += len(found) + pieces(found, row, page) + if n >= max { + stop(errCapped) + } + }) + }) + if errors.Is(context.Cause(ctx), errCapped) { + return true, nil + } + return false, err +} + +// Search finds the entries under a folder whose names contain q, sending them as EventRows +// for request. It stops at SearchMax matches. fileDates is as for List. +func (a *API) Search(ctx context.Context, request, path, q string, fileDates bool) error { + capped, err := SearchFolder(ctx, path, q, SearchMax, fileDates, func(rows []Row) { + a.emit(ctx, EventRows, Rows{Request: request, Entries: rows}) + }) + // The page isn't told that a walk ended at SearchWalkMax. + if err != nil && !errors.Is(err, ErrWalkMax) { + return err + } + a.emit(ctx, EventRows, Rows{Request: request, Entries: []Row{}, Done: true, Capped: capped}) + return nil +} + +// CountFolder counts the files and their bytes below the folder at path, as Sizes counts each of +// its folders, but it returns the reason when the folder can't be counted. When ctx ends partway, +// it returns the counts so far, marked Partial, with ctx's error. +func CountFolder(ctx context.Context, path string) (Size, error) { + if _, err := folderOf(path, "path", i18n.M("Specify the folder to count.")); err != nil { + return Size{}, err + } + s := Size{Path: path} + err := inJob(ctx, "sizes", func(ctx context.Context) (err error) { + s, err = count(ctx, path) + return err + }) + if err != nil && ctx.Err() != nil { + s.Partial = true + } + return s, err +} + +// Sizes counts each folder's size and files, sending each as EventSize for request as it is +// counted. +func (a *API) Sizes(ctx context.Context, request string, paths []string) error { + err := inJob(ctx, "sizes", func(ctx context.Context) error { + return Sizes(ctx, paths, func(s Size) { + a.emit(ctx, EventSize, FolderSize{Request: request, Path: s.Path, Files: s.Files, Bytes: s.Bytes, Partial: s.Partial}) + }) + }) + if err != nil { + return err + } + a.emit(ctx, EventSize, FolderSize{Request: request, Done: true}) + return nil +} + +// Compare puts two folders side by side, one level down. fileDates is as for List. +func (a *API) Compare(ctx context.Context, left, right string, fileDates bool) (CompareResult, error) { + if left == "" || right == "" { + return CompareResult{}, errs.Invalid(i18n.M("Two folders are needed."), errs.Violation("right", "missing")) + } + // Check both paths the same way a listing does, since rclone would refuse or misread them. + for _, side := range [][2]string{{"left", left}, {"right", right}} { + if _, err := folderOf(side[1], side[0], i18n.M("Two folders are needed.")); err != nil { + return CompareResult{}, err + } + } + var c Comparison + err := inJob(ctx, "compare", func(ctx context.Context) (err error) { + c, err = Compare(ctx, left, right, fileDates) + return err + }) + if err != nil { + return CompareResult{}, err + } + return CompareResult{Pairs: c.Pairs[:min(len(c.Pairs), CompareMax)], Capped: c.Capped || len(c.Pairs) > CompareMax}, nil +} + +// Disks returns the disks and folders on this machine that the pickers offer, using rclone's +// core/disks. +func (a *API) Disks(ctx context.Context) ([]string, error) { return rclone.Disks(ctx) } + +// PublicLink creates a public link to an entry, on backends that support them. +func (a *API) PublicLink(ctx context.Context, path string) (string, error) { + parent, leaf, err := fspath.Split(path) + if err != nil || leaf == "" { + return "", errs.Invalid(i18n.M("Pick an entry inside the folder."), errs.Violation("path", "a root")) + } + var link string + err = inJob(ctx, "link", func(ctx context.Context) error { + f, err := cache.Get(ctx, parent) + if err != nil { + return err + } + link, err = operations.PublicLink(ctx, f, leaf, fs.DurationOff, false) + return err + }) + if err != nil { + return "", err + } + return link, nil +} + +// UsageState is where a Disk Usage scan is. +type UsageState string + +// The states of a scan. +const ( + UsageScanning UsageState = "scanning" + UsageDone UsageState = "done" + // UsageStopped is a scan that the user stopped. Its tree holds what it found until then. + UsageStopped UsageState = "stopped" + // UsageCapped is a scan that reached UsageFolderMax folders and stopped there. + UsageCapped UsageState = "capped" + // UsageFailed is a scan that stopped on an error after it found something. + UsageFailed UsageState = "failed" +) + +// UsageProgress is where a scan is, tagged with its request. A scan sends it a few times a +// second while it runs, and once when it ends. +type UsageProgress struct { + Request string `json:"request"` + // Root is the scanned root, written as a listing's rows write paths (`gdrive:`, `/`, `C:\`). + Root string `json:"root"` + // Local is true for a disk on this machine. + Local bool `json:"local"` + Count UsageCount `json:"count"` + State UsageState `json:"state"` + // Error is why a failed scan stopped. + Error string `json:"error,omitempty"` + // EndedAt is when the scan ended, in ms since the epoch. + EndedAt int64 `json:"endedAt,omitempty"` +} + +const ( + // usageBeat is how often a running scan sends its progress. + usageBeat = 250 * time.Millisecond + // usageIdle is how long an ended scan is kept while no page reads it. + usageIdle = 30 * time.Minute + // usageScansMax is the most scans kept at once. A page that reloads can't end the scan it + // started, so the oldest one is let go when another starts. + usageScansMax = 2 + // usageRowsMax is the most rows that one read of a folder returns. + usageRowsMax = 5000 +) + +// errUsageStopped is the cause of a scan that the user stopped. +var errUsageStopped = errors.New("the scan was stopped") + +// usageScan is a scan that a page holds. +type usageScan struct { + root UsageRoot + tree *UsageTree + stop context.CancelCauseFunc // ends the walk and keeps the tree + end context.CancelFunc // lets go of the scan + read chan struct{} // a page read the scan + + mu sync.Mutex + // resend sends the scan's progress again, with its totals as they are now. It is set once + // the scan has ended. Until then, the scan sends its progress on its own beat. + resend func() +} + +// usageScans are the scans that pages hold, by request. +type usageScans struct { + mu sync.Mutex + m map[string]*usageScan + order []string // oldest first +} + +func (u *usageScans) add(request string, s *usageScan) { + u.mu.Lock() + defer u.mu.Unlock() + if u.m == nil { + u.m = map[string]*usageScan{} + } + u.m[request] = s + u.order = append(u.order, request) + for len(u.order) > usageScansMax { + if old := u.m[u.order[0]]; old != nil { + old.end() + } + u.order = u.order[1:] + } +} + +func (u *usageScans) remove(request string, s *usageScan) { + u.mu.Lock() + defer u.mu.Unlock() + if u.m[request] == s { + delete(u.m, request) + u.order = slices.DeleteFunc(u.order, func(r string) bool { return r == request }) + } +} + +// get returns the scan of request, and counts the call as a read. +func (u *usageScans) get(request string) (*usageScan, error) { + u.mu.Lock() + s := u.m[request] + u.mu.Unlock() + if s == nil { + return nil, errs.NotFound("scan", "This scan is no longer available. Scan again to see the disk usage.") + } + select { + case s.read <- struct{}{}: + default: + } + return s, nil +} + +// Usage scans the whole remote, or the whole local disk, that the folder at path is on, for +// Disk Usage. While it scans, it sends EventUsage for request a few times a second, and once more +// when it ends. Then it keeps the result for the page and returns when the page cancels the +// call, when another scan replaces it, or when no page read it for usageIdle. UsageLevel reads +// the result one folder at a time, during the scan and after it. +// +// When nothing could be read at all, the call returns the error instead (a remote that doesn't +// open, or whose root can't be listed). +func (a *API) Usage(ctx context.Context, request, path string) error { + root, err := usageRootOf(path, a.mounts) + if err != nil { + return err + } + ctx, end := context.WithCancel(ctx) + defer end() + walkCtx, stop := context.WithCancelCause(ctx) + defer stop(nil) + s := &usageScan{root: root, tree: NewUsageTree(), stop: stop, end: end, read: make(chan struct{}, 1)} + a.usage.add(request, s) + defer a.usage.remove(request, s) + + send := func(state UsageState, err error, endedAt int64) { + a.emit(ctx, EventUsage, UsageProgress{ + Request: request, Root: root.Entry(""), Local: root.Local, Count: s.tree.Count(), + State: state, Error: i18n.Localize(err), EndedAt: endedAt, + }) + } + send(UsageScanning, nil, 0) + scanned := make(chan error, 1) + go func() { + scanned <- inJob(walkCtx, "usage", func(ctx context.Context) error { + f, err := getFs(ctx, root.Root()) + if err != nil { + return err + } + return scanUsage(ctx, f, root.Skip, s.tree) + }) + }() + beat := time.NewTicker(usageBeat) + var scanErr error +running: + for { + select { + case scanErr = <-scanned: + break running + case <-beat.C: + send(UsageScanning, nil, 0) + } + } + beat.Stop() + if ctx.Err() != nil { + return nil // the page let go of the scan, or another one replaced it + } + count := s.tree.Count() + state := UsageDone + switch { + case errors.Is(context.Cause(walkCtx), errUsageStopped): + state, scanErr = UsageStopped, nil + case scanErr != nil && count.Files == 0 && count.Folders == 0: + return scanErr + case scanErr != nil: + state = UsageFailed + case count.Capped: + state = UsageCapped + } + endedAt := time.Now().UnixMilli() + send(state, scanErr, endedAt) + s.mu.Lock() + s.resend = func() { send(state, scanErr, endedAt) } + s.mu.Unlock() + + idle := time.NewTimer(usageIdle) + defer idle.Stop() + for { + select { + case <-ctx.Done(): + return nil + case <-s.read: + idle.Reset(usageIdle) + case <-idle.C: + return nil + } + } +} + +// UsageRoot returns the root that a scan of the folder at path reads (`gdrive:`, `/`, `C:\`), +// as UsageProgress writes it. A page compares it with the root of the scan it holds, to show that +// scan again rather than start one. +func (a *API) UsageRoot(ctx context.Context, path string) (string, error) { + root, err := usageRootOf(path, a.mounts) + if err != nil { + return "", err + } + return root.Entry(""), nil +} + +// UsageLevel returns one folder of a scan, during the scan or after it: the folder's totals and +// its first limit rows in the order by. rel is the folder below the scan's root, "" for the root. +func (a *API) UsageLevel(ctx context.Context, request, rel string, by UsageSort, limit int) (UsageLevel, error) { + s, err := a.usage.get(request) + if err != nil { + return UsageLevel{}, err + } + if limit <= 0 || limit > usageRowsMax { + limit = usageRowsMax + } + level, ok := s.tree.Level(s.root.Fs, rel, by, limit) + if !ok { + return UsageLevel{}, errs.NotFound("folder", "The scan has no folder %s.", rel) + } + return level, nil +} + +// UsageStop stops a scan's walk. The scan keeps what it found, and ends as stopped. +func (a *API) UsageStop(ctx context.Context, request string) error { + s, err := a.usage.get(request) + if err != nil { + return err + } + s.stop(errUsageStopped) + return nil +} + +// UsageForget takes an entry that was deleted out of a scan and out of every total above it. rel +// is the entry's path below the scan's root, and isDir says whether it is a folder. +func (a *API) UsageForget(ctx context.Context, request, rel string, isDir bool) error { + s, err := a.usage.get(request) + if err != nil { + return err + } + if !s.tree.Forget(rel, isDir) { + return nil + } + s.mu.Lock() + resend := s.resend + s.mu.Unlock() + if resend != nil { + resend() // the totals at the top changed + } + return nil +} diff --git a/core/browse/api_fatal_test.go b/core/browse/api_fatal_test.go new file mode 100644 index 00000000..136f0d47 --- /dev/null +++ b/core/browse/api_fatal_test.go @@ -0,0 +1,24 @@ +package browse + +import ( + "context" + "strings" + "testing" + + _ "github.com/rclone/rclone/backend/http" + + "github.com/rclone/rclone-ui/core/internal/late" +) + +// TestAFatalRemoteIsTheReadsError checks that a fatal rclone error only fails the read. The +// remote's override gives a client cert without its key, so rclone's HTTP client calls +// fs.Fatalf. The read fails, and the core keeps running. +func TestAFatalRemoteIsTheReadsError(t *testing.T) { + _, err := testAPI().PublicLink(context.Background(), ":http,url='http://127.0.0.1:9/',override.client_cert='/nonexistent.pem':file.txt") + if err == nil || !strings.Contains(err.Error(), "client-key") { + t.Fatalf("got %v", err) + } +} + +// testAPI returns an API that discards its events. +func testAPI() *API { return NewAPI(late.Of(NewLister()), func(context.Context, string, any) {}) } diff --git a/core/browse/api_test.go b/core/browse/api_test.go new file mode 100644 index 00000000..4adc71db --- /dev/null +++ b/core/browse/api_test.go @@ -0,0 +1,251 @@ +package browse_test + +import ( + "context" + "io" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/operations" + + "github.com/rclone/rclone-ui/core/browse" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/internal/late" + "github.com/rclone/rclone-ui/core/rclone" +) + +// The pages send one path, written as the user sees it, and use each row's path unchanged. These +// tests cover the ways a panel writes a path, and the paths it gets back. + +// recorder keeps the events that an API sent, in order. +type recorder struct { + mu sync.Mutex + events []any +} + +func (r *recorder) emit(_ context.Context, _ string, data any) { + r.mu.Lock() + defer r.mu.Unlock() + r.events = append(r.events, data) +} + +// rows returns the rows that the API sent, by path, after checking that the last piece is done. +func (r *recorder) rows(t *testing.T) []browse.Row { + t.Helper() + r.mu.Lock() + defer r.mu.Unlock() + var out []browse.Row + for i, e := range r.events { + p := e.(browse.Rows) + if p.Done != (i == len(r.events)-1) { + t.Fatalf("piece %d of %d: done %v", i, len(r.events), p.Done) + } + out = append(out, p.Entries...) + } + r.events = nil + slices.SortFunc(out, func(a, b browse.Row) int { return strings.Compare(a.Path, b.Path) }) + return out +} + +func api(t *testing.T) (*browse.API, *recorder) { + t.Helper() + r := &recorder{} + return browse.NewAPI(late.Of(browse.NewLister()), r.emit), r +} + +func pathsOf(rows []browse.Row) []string { + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = r.Path + } + return out +} + +// memTree writes files into a memory bucket. files maps a slash-separated path to its content. +func memTree(t *testing.T, bucket string, files map[string]string) { + t.Helper() + ctx := context.Background() + f, err := cache.Get(ctx, "mem:"+bucket) + if err != nil { + t.Fatal(err) + } + for name, text := range files { + if _, err := operations.Rcat(ctx, f, name, io.NopCloser(strings.NewReader(text)), time.Now(), nil); err != nil { + t.Fatal(err) + } + } +} + +func TestRowsCarryTheirWholePath(t *testing.T) { + ctx := context.Background() + a, rec := api(t) + tree := map[string]string{"a/one.txt": "1", "a/sub/two.txt": "22", "a/.dot": "3"} + memTree(t, "rowpaths", tree) + local := browse.MakeTree(t, tree) + // The machine's own form of a path: its own separator throughout, and the drive first on + // Windows. + under := func(names ...string) string { return filepath.Join(append([]string{local}, names...)...) } + spelled := func(p string) string { return ":local:" + filepath.ToSlash(p) } + + cases := []struct { + name, folder string + want []string + }{ + {"a remote", "mem:rowpaths/a", []string{"mem:rowpaths/a/.dot", "mem:rowpaths/a/one.txt", "mem:rowpaths/a/sub"}}, + {"a remote, with a trailing slash", "mem:rowpaths/a/", []string{"mem:rowpaths/a/.dot", "mem:rowpaths/a/one.txt", "mem:rowpaths/a/sub"}}, + // The slash stays with the root. On sftp it is absolute, which is a different place from + // `remote:`. + {"a remote under its absolute root", "mem:/rowpaths/a", []string{"mem:/rowpaths/a/.dot", "mem:/rowpaths/a/one.txt", "mem:/rowpaths/a/sub"}}, + {"a local folder", under("a"), []string{under("a", ".dot"), under("a", "one.txt"), under("a", "sub")}}, + {"a local folder, with a trailing separator", under("a") + string(filepath.Separator), []string{under("a", ".dot"), under("a", "one.txt"), under("a", "sub")}}, + // The local backend written as a remote stays in that form, with rclone's `/` (and the + // drive first on Windows). + {":local: spelled", ":local:" + under("a"), []string{spelled(under("a", ".dot")), spelled(under("a", "one.txt")), spelled(under("a", "sub"))}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if err := a.List(ctx, "r", tc.folder, false, false); err != nil { + t.Fatal(err) + } + got := rec.rows(t) + if !slices.Equal(pathsOf(got), tc.want) { + t.Fatalf("paths %q, want %q", pathsOf(got), tc.want) + } + if r := got[1]; r.Name != "one.txt" || r.Size != 1 || r.IsDir || r.ModTime == "" || r.Below != "" { + t.Errorf("row %+v", r) + } + if !got[2].IsDir { + t.Errorf("%s is not a folder", got[2].Path) + } + }) + } +} + +func TestSearchRowsSayWhereBelowTheFolder(t *testing.T) { + ctx := context.Background() + a, rec := api(t) + memTree(t, "searchpaths", map[string]string{"a/b/match.txt": "1", "a/match-too": "2", "other/match": "3"}) + for _, tc := range []struct{ folder, wantPath, wantBelow string }{ + {"mem:searchpaths/a", "mem:searchpaths/a/b/match.txt", "b/match.txt"}, + {"mem:/searchpaths/a/", "mem:/searchpaths/a/b/match.txt", "b/match.txt"}, + {"mem:searchpaths", "mem:searchpaths/a/b/match.txt", "a/b/match.txt"}, + } { + if err := a.Search(ctx, "r", tc.folder, "match.", false); err != nil { + t.Fatal(err) + } + got := rec.rows(t) + if len(got) != 1 || got[0].Path != tc.wantPath || got[0].Below != tc.wantBelow || got[0].Name != "match.txt" { + t.Errorf("%s: %+v", tc.folder, got) + } + } +} + +func TestSizesAnswerByThePathAsked(t *testing.T) { + ctx := context.Background() + a, rec := api(t) + local := browse.MakeTree(t, map[string]string{"a/one": "1", "a/sub/two": "22", "b/": ""}) + // The paths are written as a listing's rows write them: in the machine's form, or with + // `:local:` as typed. rclone would misread a relative path as relative to the process's + // working directory (this package's folder, where rel is), so it is left out along with the + // folders that can't be counted. + rel, err := os.MkdirTemp(".", "rel") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(rel) }) + asked := []string{filepath.Join(local, "a"), filepath.Join(local, "b"), filepath.Join(local, "missing"), "-bad:x", + ":local:" + filepath.Join(local, "a"), rel, ":local:" + rel} + if err := a.Sizes(ctx, "r", asked); err != nil { + t.Fatal(err) + } + got := map[string][2]int64{} + for i, e := range rec.events { + s := e.(browse.FolderSize) + if s.Done != (i == len(rec.events)-1) { + t.Fatalf("size %d of %d: done %v", i, len(rec.events), s.Done) + } + if !s.Done { + got[s.Path] = [2]int64{s.Files, s.Bytes} + } + } + want := map[string][2]int64{filepath.Join(local, "a"): {2, 3}, filepath.Join(local, "b"): {0, 0}, + ":local:" + filepath.Join(local, "a"): {2, 3}} + if len(got) != len(want) { + t.Fatalf("sizes %v, want %v (a folder that can't be counted is left out)", got, want) + } + for p, w := range want { + if got[p] != w { + t.Errorf("%s: %v, want %v", p, got[p], w) + } + } +} + +func TestAFolderRcloneWouldMisreadIsRefused(t *testing.T) { + a, _ := api(t) + for _, p := range []string{"", "-bad:x"} { + err := a.List(context.Background(), "r", p, false, false) + e := rclone.ErrorOf(err) + if e.Code != errs.CodeInvalid || len(e.Fields) != 1 || e.Fields[0].Field != "path" { + t.Errorf("%q: %+v", p, e) + } + } + // A comparison's two folders are refused in the same way as a listing's. A relative folder + // would be read from the process's working directory. + local := browse.MakeTree(t, map[string]string{"a/one": "1"}) + for _, pair := range [][2]string{{"a", local}, {local, ":local:a"}, {local, "-bad:x"}} { + _, err := a.Compare(context.Background(), pair[0], pair[1], false) + if rclone.ErrorOf(err).Code != errs.CodeInvalid { + t.Errorf("%q: %v", pair, err) + } + } + if _, err := a.Compare(context.Background(), local, local, false); err != nil { + t.Errorf("two full paths: %v", err) + } +} + +func TestSearchFolderStopsAtItsMax(t *testing.T) { + ctx := context.Background() + local := browse.MakeTree(t, map[string]string{"a/match-1": "1", "a/b/match-2": "2", "match-3": "3", "other": "4"}) + var rows []browse.Row + collect := func(page []browse.Row) { rows = append(rows, page...) } + capped, err := browse.SearchFolder(ctx, local, "MATCH", 10, false, collect) + if err != nil || capped || len(rows) != 3 { + t.Fatalf("all matches: %q %v %v", pathsOf(rows), capped, err) + } + if !slices.Contains(pathsOf(rows), filepath.Join(local, "a", "b", "match-2")) { + t.Errorf("a match's row has its whole path: %q", pathsOf(rows)) + } + rows = nil + capped, err = browse.SearchFolder(ctx, local, "match", 2, false, collect) + if err != nil || !capped || len(rows) != 2 { + t.Errorf("at most two: %q %v %v", pathsOf(rows), capped, err) + } + if _, err := browse.SearchFolder(ctx, "rel", "match", 2, false, collect); rclone.ErrorOf(err).Code != errs.CodeInvalid { + t.Errorf("a relative folder: %v", err) + } +} + +// CountFolder counts one folder and says why it can't, where Sizes leaves the folder out. +func TestCountFolder(t *testing.T) { + ctx := context.Background() + local := browse.MakeTree(t, map[string]string{"a/one": "1", "a/sub/two": "22", "file": "x"}) + s, err := browse.CountFolder(ctx, filepath.Join(local, "a")) + if err != nil || s.Files != 2 || s.Bytes != 3 || s.Partial { + t.Fatalf("count: %+v %v", s, err) + } + if _, err := browse.CountFolder(ctx, filepath.Join(local, "missing")); err == nil { + t.Error("a missing folder was counted") + } + if _, err := browse.CountFolder(ctx, filepath.Join(local, "file")); err == nil { + t.Error("a file was counted as a folder") + } + if _, err := browse.CountFolder(ctx, ""); rclone.ErrorOf(err).Code != errs.CodeInvalid { + t.Errorf("no folder: %v", err) + } +} diff --git a/core/browse/compare.go b/core/browse/compare.go new file mode 100644 index 00000000..a472743d --- /dev/null +++ b/core/browse/compare.go @@ -0,0 +1,213 @@ +package browse + +import ( + "context" + "errors" + "fmt" + "path" + "slices" + "strings" + "sync" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/accounting" + "github.com/rclone/rclone/fs/hash" + "github.com/rclone/rclone/fs/operations" + + "github.com/rclone/rclone-ui/core/rclone" +) + +// Class is the group that a name falls into in a comparison. The classes match the groups in +// CompareDrawer.tsx, in the same order. +type Class string + +const ( + OnlyLeft Class = "onlyLeft" + OnlyRight Class = "onlyRight" + // SameByName is a name on both sides without a matching common hash, either because no + // common hash is known or because the digests differ. + SameByName Class = "sameByName" + // SameByHash is a name on both sides with equal digests for a common hash type. + SameByHash Class = "sameByHash" +) + +// Side describes a name on one side of a comparison. +type Side struct { + IsDir bool `json:"isDir"` + Size int64 `json:"size"` // -1 when the backend does not know + ModTime string `json:"modTime,omitempty"` +} + +// Pair is one name in a comparison. In the only-left and only-right classes, one side is nil. +type Pair struct { + Class Class `json:"class"` + Name string `json:"name"` + Left *Side `json:"left,omitempty"` + Right *Side `json:"right,omitempty"` +} + +// Comparison is two folders side by side. Each name appears once. Pairs are grouped by class in +// the order of the Class constants, and within a class, folders come first, then names in order. +type Comparison struct { + Pairs []Pair + // Capped reports that a side held more than CompareMax names and its listing stopped there. + // Some names are then missing, and a name that the other side has may be in the wrong class. + Capped bool +} + +// Compare lists the folders left and right (rclone paths) one level down and sorts their names +// into the four classes, leaving out names that start with a dot. Each side stops at CompareMax +// names, and Comparison.Capped reports when that happened. +func Compare(ctx context.Context, left, right string, fileDates bool) (Comparison, error) { + var ( + fss [2]fs.Fs + sides [2]side + errs [2]error + wg sync.WaitGroup + ) + locs := [2]string{left, right} + // Both remotes are opened on the caller's goroutine, which runs an rclone job, because a fatal + // rclone error while opening a remote can only be recovered there. They are then listed in + // parallel. + for i := range locs { + f, err := getFs(ctx, locs[i]) + if err != nil { + return Comparison{}, fmt.Errorf("%s: %w", locs[i], err) + } + fss[i] = f + } + // Each side is listed as its own job in the comparison's stats group, because rclone can only + // recover from a fatal error on a goroutine that its job runner started. + group, _ := accounting.StatsGroupFromContext(ctx) + for i := range locs { + wg.Go(func() { + _, errs[i] = rclone.Run(ctx, rclone.CallOpts{Group: group}, func(ctx context.Context) (err error) { + sides[i], err = listSide(ctx, fss[i], fileDates) + return err + }) + }) + } + wg.Wait() + for i, err := range errs { + if err != nil { + return Comparison{}, fmt.Errorf("%s: %w", locs[i], err) + } + } + l, r := sides[0], sides[1] + + rightByName := make(map[string]*item, len(r.items)) + for i := range r.items { + rightByName[r.items[i].name] = &r.items[i] + } + var byClass [4][]Pair + for i := range l.items { + li := &l.items[i] + ri := rightByName[li.name] + switch { + case ri == nil: + byClass[0] = append(byClass[0], Pair{Class: OnlyLeft, Name: li.name, Left: &li.side}) + case sameByHash(ctx, li.obj, ri.obj): + byClass[3] = append(byClass[3], Pair{Class: SameByHash, Name: li.name, Left: &li.side, Right: &ri.side}) + default: + byClass[2] = append(byClass[2], Pair{Class: SameByName, Name: li.name, Left: &li.side, Right: &ri.side}) + } + if ri != nil { + ri.paired = true + } + } + for i := range r.items { + if ri := &r.items[i]; !ri.paired { + byClass[1] = append(byClass[1], Pair{Class: OnlyRight, Name: ri.name, Right: &ri.side}) + } + } + return Comparison{Pairs: slices.Concat(byClass[:]...), Capped: l.capped || r.capped}, nil +} + +type side struct { + items []item // folders first, then by name + capped bool // the listing stopped at CompareMax +} + +type item struct { + name string + side Side + obj fs.Object // nil for a folder + paired bool +} + +func listSide(ctx context.Context, f fs.Fs, fileDates bool) (side, error) { + format := timeFormat(f.Precision()) + slow := !fileDates && slowModTime(ctx, f) + var s side + seen := map[string]struct{}{} + var mu sync.Mutex + err := listDir(ctx, f, "", func(entries fs.DirEntries) error { + mu.Lock() + defer mu.Unlock() + for _, e := range entries { + if len(s.items) >= CompareMax { + s.capped = true + return errStop + } + name := path.Base(e.Remote()) + if e.Remote() == "" || strings.HasPrefix(name, ".") { + continue + } + if _, dup := seen[name]; dup { + continue + } + seen[name] = struct{}{} + it := item{name: name, side: Side{Size: e.Size()}} + if t := modTimeOf(ctx, e, slow); !t.IsZero() { + it.side.ModTime = t.Format(format) + } + switch x := e.(type) { + case fs.Directory: + it.side.IsDir = true + case fs.Object: + it.obj = x + } + s.items = append(s.items, it) + } + return nil + }) + if err != nil && !errors.Is(err, errStop) { + return side{}, err + } + slices.SortFunc(s.items, func(a, b item) int { + if a.side.IsDir != b.side.IsDir { + if a.side.IsDir { + return -1 + } + return 1 + } + return CompareNames(a.name, b.name) + }) + return s, nil +} + +// CompareNames orders names roughly as the page's localeCompare does: ignoring case first, then +// by exact bytes. The Commander's lists, Disk Usage and the agents' file tools all use it. +func CompareNames(a, b string) int { + if c := strings.Compare(strings.ToLower(a), strings.ToLower(b)); c != 0 { + return c + } + return strings.Compare(a, b) +} + +// sameByHash reports whether two files have equal digests for a common hash type. It compares +// them the way rclone's check does, with operations.CheckHashes, using one hash type that both +// backends support. Different sizes settle the answer early, because on a local disk computing +// a digest means reading the whole file. +func sameByHash(ctx context.Context, a, b fs.Object) bool { + if a == nil || b == nil { + return false + } + if a.Size() >= 0 && b.Size() >= 0 && a.Size() != b.Size() { + return false + } + // When the two sides share no hash type, CheckHashes returns hash.None and reports the files + // as equal. They are not equal by hash, so they don't count here. + equal, ht, err := operations.CheckHashes(ctx, a, b) + return err == nil && equal && ht != hash.None +} diff --git a/core/browse/compare_test.go b/core/browse/compare_test.go new file mode 100644 index 00000000..083ecfdf --- /dev/null +++ b/core/browse/compare_test.go @@ -0,0 +1,155 @@ +package browse + +import ( + "context" + "io" + "slices" + "strings" + "testing" + "time" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/operations" +) + +func classes(c Comparison) map[Class][]string { + out := map[Class][]string{} + for _, p := range c.Pairs { + out[p.Class] = append(out[p.Class], p.Name) + } + return out +} + +func TestCompare(t *testing.T) { + left := MakeTree(t, map[string]string{ + "same.txt": "hello", + "Diff.txt": "aaaa", + "sizediff.txt": "abc", + "onlyL.txt": "l", + "both/x": "", + "dirL/": "", + "file-vs-dir": "f", + ".hidden": "h", + "a-only.txt": "a", + }) + right := MakeTree(t, map[string]string{ + "same.txt": "hello", + "Diff.txt": "bbbb", // same size, other content + "sizediff.txt": "abcdef", + "onlyR.txt": "r", + "both/": "", + "dirR/": "", + "file-vs-dir/y": "", + ".hidden2": "h", + }) + c, err := Compare(context.Background(), left, right, false) + if err != nil { + t.Fatal(err) + } + want := map[Class][]string{ + OnlyLeft: {"dirL", "a-only.txt", "onlyL.txt"}, + OnlyRight: {"dirR", "onlyR.txt"}, + SameByName: {"both", "Diff.txt", "file-vs-dir", "sizediff.txt"}, + SameByHash: {"same.txt"}, + } + got := classes(c) + for _, cl := range []Class{OnlyLeft, OnlyRight, SameByName, SameByHash} { + if !slices.Equal(got[cl], want[cl]) { + t.Errorf("%s: %q, want %q", cl, got[cl], want[cl]) + } + } + // The classes come in order, and each pair has the sides that hold its name. + var order []Class + for _, p := range c.Pairs { + if len(order) == 0 || order[len(order)-1] != p.Class { + order = append(order, p.Class) + } + if (p.Left == nil) != (p.Class == OnlyRight) || (p.Right == nil) != (p.Class == OnlyLeft) { + t.Errorf("%+v: sides", p) + } + } + if !slices.Equal(order, []Class{OnlyLeft, OnlyRight, SameByName, SameByHash}) { + t.Errorf("class order %q", order) + } + if p := c.Pairs[len(c.Pairs)-1]; p.Left.Size != 5 || p.Left.ModTime == "" || p.Left.IsDir { + t.Errorf("side %+v", *p.Left) + } +} + +func TestCompareAcrossBackendsUsesACommonHash(t *testing.T) { + ctx := context.Background() + f, err := cache.Get(ctx, ":memory:compare") + if err != nil { + t.Fatal(err) + } + for name, text := range map[string]string{"same": "content", "differs": "other!"} { + if _, err := operations.Rcat(ctx, f, "d/"+name, io.NopCloser(strings.NewReader(text)), time.Now(), nil); err != nil { + t.Fatal(err) + } + } + local := MakeTree(t, map[string]string{"same": "content", "differs": "OTHER!"}) + c, err := Compare(ctx, local, ":memory:compare/d", false) + if err != nil { + t.Fatal(err) + } + got := classes(c) + if !slices.Equal(got[SameByHash], []string{"same"}) || !slices.Equal(got[SameByName], []string{"differs"}) { + t.Errorf("%v", got) + } +} + +func TestCompareFailsOnAMissingSide(t *testing.T) { + if _, err := Compare(context.Background(), MakeTree(t, map[string]string{"a": ""}), "/does/not/exist/rcc", false); err == nil || + !strings.HasPrefix(err.Error(), "/does/not/exist/rcc: ") { + t.Fatalf("err %v", err) + } +} + +// A side with more names than CompareMax stops at the cap, and the comparison reports it. That +// holds whether the other side is also too large or is empty. A comparison of one name against +// one is complete. +func TestCompareSaysWhenASideWasCut(t *testing.T) { + ctx := context.Background() + many := memoryFiles(t, "d", CompareMax+50) + "/d" + empty := MakeTree(t, map[string]string{"empty/": ""}) + "/empty" + one := MakeTree(t, map[string]string{"a": "a"}) + for _, tc := range []struct { + name string + left, right string + capped bool + }{ + {"both sides cut", many, many, true}, + {"one side cut", many, empty, true}, + {"the other side cut", empty, many, true}, + {"one against one", one, one, false}, + } { + t.Run(tc.name, func(t *testing.T) { + c, err := Compare(ctx, tc.left, tc.right, false) + if err != nil || c.Capped != tc.capped { + t.Fatalf("capped %v, %v", c.Capped, err) + } + }) + } + // The API reports it too, even though it sends only CompareMax pairs. + res, err := testAPI().Compare(ctx, many, empty, false) + if err != nil { + t.Fatal(err) + } + if !res.Capped || len(res.Pairs) != CompareMax { + t.Fatalf("capped %v, %d pairs", res.Capped, len(res.Pairs)) + } +} + +// A backend whose listing calls fs.Fatalf fails the comparison, which runs each side as its own +// job. The core keeps running. +func TestAFatalListingInCompareIsTheReadsError(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a": "a"}), Hook: func(context.Context, string) error { + fs.Fatalf(nil, "the backend gave up") + return nil + }} + _, err := testAPI().Compare(context.Background(), AddFixture(fx), MakeTree(t, map[string]string{"a": "a"}), false) + if err == nil || !strings.Contains(err.Error(), "the backend gave up") { + t.Fatalf("got %v", err) + } +} diff --git a/core/browse/handler_windows_test.go b/core/browse/handler_windows_test.go new file mode 100644 index 00000000..07224d6d --- /dev/null +++ b/core/browse/handler_windows_test.go @@ -0,0 +1,50 @@ +package browse + +import ( + "slices" + "testing" + + "github.com/rclone/rclone-ui/core/i18n" +) + +// On Windows, the local backend written as a remote takes a drive, and fspath.SplitFs reads a +// share as a local root. The listing's root and folder are in rclone's form, and its rows write +// the root the same way the request did. +func TestFoldersOnWindows(t *testing.T) { + for _, tc := range []struct{ folder, root, rel, row string }{ + {`:local:C:\x`, ":local:C:/", "x", ":local:C:/x/y"}, + {`:local:C:/x/`, ":local:C:/", "x", ":local:C:/x/y"}, + {`C:\x\`, ":local:C:/", "x", `C:\x\y`}, + {`\\srv\share\x`, ":local://srv/share/", "x", `\\srv\share\x\y`}, + {`:local:\\srv\share\x`, ":local://srv/share/", "x", ":local://srv/share/x/y"}, + } { + at, err := folderOf(tc.folder, "path", i18n.M("Specify the folder to list.")) + if err != nil || at.Root() != tc.root || at.Rel != tc.rel { + t.Errorf("%s: %q %q (%v), want %q %q", tc.folder, at.Root(), at.Rel, err, tc.root, tc.rel) + continue + } + if got := rowOf(at, Entry{Path: "x/y"}).Path; got != tc.row { + t.Errorf("%s: row %q, want %q", tc.folder, got, tc.row) + } + } +} + +// A change to a Windows path invalidates the listings of its folder, however each one is written. +func TestInvalidationOnWindows(t *testing.T) { + l, _ := testLister() + keys := [][2]string{{":local:C:/", "x"}, {":local:C:/", "y"}, {":local://srv/share/", "x"}} + before := map[[2]string]uint64{} + for _, k := range keys { + before[k] = epochOf(l, k[0], k[1]) + } + l.InvalidatePaths(`C:\x\new`, `\\srv\share\x\new`) + var got [][2]string + for _, k := range keys { + if epochOf(l, k[0], k[1]) != before[k] { + got = append(got, k) + } + } + if want := [][2]string{keys[0], keys[2]}; !slices.Equal(got, want) { + t.Errorf("invalidated %q, want %q", got, want) + } +} diff --git a/core/browse/listing.go b/core/browse/listing.go new file mode 100644 index 00000000..274a33cc --- /dev/null +++ b/core/browse/listing.go @@ -0,0 +1,430 @@ +// Package browse reads folders through rclone for the pages. It provides listings behind an +// in-memory cache, recursive search, folder sizes, and the comparison of two folders. Each of +// these works on the context it is given. The API runs each call as an rclone job (rclone.Run, +// like everything else that opens a remote) in its own ui// stats group. rclone's +// errors are returned with their original text, so any advice in them to reconnect reaches the +// page. +package browse + +import ( + "context" + "errors" + "path" + "slices" + "strings" + "sync" + "time" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/accounting" + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/list" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/operations" +) + +const ( + // ListingFresh is how long a cached listing is served without asking rclone again. + ListingFresh = 5 * time.Minute + // ListingKeep is how long a listing stays in memory after it was last requested. + ListingKeep = 30 * time.Minute + + // sweepEvery is how often listings older than ListingKeep are dropped, while any are held. + sweepEvery = time.Minute +) + +// The limits for the pages. Past them the work stops early, and the page tells the user. +const ( + ListMax = 50000 + SearchMax = 5000 + // SearchWalkMax is the most entries a search reads, whether they match or not. On a bucket, + // rclone keeps every folder that its walk passed through until the walk ends. The page is + // not told. + SearchWalkMax = 1000000 + CompareMax = 20000 +) + +// Entry is one row of a listing or a search. Path is relative to the listed root, like rclone's +// remote paths, and includes the folder. The cache holds one listing for every way of writing +// the folder, and the API writes each row's full path the way its request did (location.Fs.Entry). +// There is no MimeType, because on some backends it costs one request per object. There are no +// Hashes either, because only the comparison needs them. +type Entry struct { + Path string + Name string + Size int64 + ModTime string + IsDir bool + ID string + Tier string + IsBucket bool +} + +// Lister is the listings cache. It holds one shared listing per (fs, dir). A listing is served +// without asking rclone while it is fresh (ListingFresh), and kept for ListingKeep after it was +// last requested. Listings are never saved to disk, and a failed listing is not kept. Only a +// refresh, an invalidation or age makes the Lister ask rclone again. +type Lister struct { + now func() time.Time + fresh, keep time.Duration + + mu sync.Mutex + states map[listingKey]*state + gen uint64 + sweep *time.Timer +} + +type listingKey struct{ fs, dir string } + +// state is the cache entry for one (fs, dir). It holds the listing and a generation number, +// which changes when the cached listing may no longer be served. +type state struct { + at place + atOK bool + gen uint64 + asked time.Time + last *listing +} + +type listing struct { + rows []Entry // sorted by Path + fileDates bool // the files' dates were read on a backend where they are slow (see slowModTime) + fetchedAt time.Time + gen uint64 // the state's generation when rclone was asked + capped bool // the listing stopped at the caller's max +} + +func NewLister() *Lister { + return &Lister{now: time.Now, fresh: ListingFresh, keep: ListingKeep, states: map[listingKey]*state{}} +} + +// List emits the rows of dir under fs (in the form Clean returns) and returns when rclone was +// asked for them, in ms. The rows come from the cache while it is fresh, unless fresh is set for +// a refresh. Otherwise they come from rclone, and each batch is emitted as it arrives. Each batch +// has duplicates removed by Path and is sorted within itself, while the cached copy is sorted as +// a whole. List returns at most max rows, and a paged backend's listing stops there. fileDates +// reads the files' dates even where each costs a request (see slowModTime), and a cached listing +// is served only if it was made the same way. +// emit must not modify or keep the slice it is given. +func (l *Lister) List(ctx context.Context, fsName, dir string, fresh, fileDates bool, max int, emit func([]Entry)) (int64, error) { + fsName, dir = Clean(fsName, dir) + k := listingKey{fsName, dir} + l.mu.Lock() + st := l.stateLocked(k) + if c := st.last; !fresh && c != nil && c.gen == st.gen && c.fileDates == fileDates && l.freshLocked(c) && (!c.capped || len(c.rows) >= max) { + l.mu.Unlock() + rows := c.rows[:min(len(c.rows), max)] + if len(rows) > 0 { + emit(rows) + } + return c.fetchedAt.UnixMilli(), nil + } + gen := st.gen + l.mu.Unlock() + + asked := l.now() + rows, capped, err := fetch(ctx, fsName, dir, max, fileDates, emit) + if err != nil { + return 0, err + } + l.mu.Lock() + defer l.mu.Unlock() + // A change made while rclone was listing may be missing from the result. In that case the + // result isn't kept, so the next request fetches again. + if st := l.states[k]; st != nil && st.gen == gen { + st.last = &listing{rows: rows, fileDates: fileDates, fetchedAt: asked, gen: gen, capped: capped} + } + return asked.UnixMilli(), nil +} + +// InvalidateRemotes forgets every listing on these remotes. It is called after a config change, +// with the changed remotes and the remotes that wrap them, as named by the remotes service. +func (l *Lister) InvalidateRemotes(names []string) { + l.invalidate(func(p place) bool { return slices.Contains(names, p.remote) }) +} + +// InvalidatePaths records a change to each path, such as a folder created, or an entry renamed +// or deleted through the file actions. It forgets the listing of the folder that holds the path. +// For a folder it also forgets the folder's own listing and every listing below it. For a file, +// that second part matches nothing. +func (l *Lister) InvalidatePaths(paths ...string) { + var entries []place + for _, p := range paths { + if at, ok := placeOf(p); ok { + entries = append(entries, at) + } + } + l.invalidate(func(q place) bool { + for _, p := range entries { + if q == p.parent() || p.covers(q) { + return true + } + } + return false + }) +} + +// InvalidateFolders forgets the listing of each folder, every listing below it, and every listing +// above it, where a folder created by the change shows up. An example is the destination of a +// copy. +func (l *Lister) InvalidateFolders(paths ...string) { + var folders []place + for _, p := range paths { + if at, ok := placeOf(p); ok { + folders = append(folders, at) + } + } + l.invalidate(func(q place) bool { + return slices.ContainsFunc(folders, func(p place) bool { return p.covers(q) || q.covers(p) }) + }) +} + +// TransferEnded forgets the listings that a transfer changed. Its destination changed, and so +// did every folder above it, where a folder that the transfer created shows up. A download's +// destination is the file it wrote, so the folder that holds the file is covered too. A move, a +// delete and a purge also changed the folders that held the sources. A bisync writes to its +// source as well as its destination. +func (l *Lister) TransferEnded(operation operations.Operation, sources []string, destination string) { + if destination != "" { + l.InvalidateFolders(destination) + } + switch operation { + case operations.OperationMove, operations.OperationDelete, operations.OperationPurge: + l.InvalidatePaths(sources...) + case operations.OperationBisync: + l.InvalidateFolders(sources...) + } +} + +func (l *Lister) invalidate(match func(place) bool) { + l.mu.Lock() + defer l.mu.Unlock() + for _, st := range l.states { + if st.atOK && match(st.at) { + st.gen = l.nextGenLocked() + st.last = nil + } + } +} + +// stateLocked returns the state for k, creating it if needed, and marks it as requested now. +func (l *Lister) stateLocked(k listingKey) *state { + now := l.now() + l.sweepLocked(now) + st := l.states[k] + if st == nil { + st = &state{gen: l.nextGenLocked()} + st.at, st.atOK = placeOf(Join(k.fs, k.dir)) + l.states[k] = st + if l.sweep == nil { + l.sweep = time.AfterFunc(sweepEvery, l.tick) + } + } + st.asked = now + return st +} + +func (l *Lister) freshLocked(c *listing) bool { return l.now().Sub(c.fetchedAt) < l.fresh } + +func (l *Lister) nextGenLocked() uint64 { + l.gen++ + return l.gen +} + +func (l *Lister) sweepLocked(now time.Time) { + for k, st := range l.states { + if now.Sub(st.asked) >= l.keep { + delete(l.states, k) + } + } +} + +func (l *Lister) tick() { + l.mu.Lock() + defer l.mu.Unlock() + l.sweepLocked(l.now()) + if len(l.states) > 0 { + l.sweep.Reset(sweepEvery) + } else { + l.sweep = nil + } +} + +// errStop ends a listing when it reaches its cap. +var errStop = errors.New("browse: cap reached") + +// fetch asks rclone to list dir under fs, returning at most max rows. fileDates reads the files' +// dates even where each costs a request (see slowModTime). +func fetch(ctx context.Context, fsName, dir string, max int, fileDates bool, emit func([]Entry)) (rows []Entry, capped bool, err error) { + f, err := getFs(ctx, fsName) + if err != nil { + return nil, false, err + } + mk := newEntryMaker(ctx, f, dir, fileDates) + seen := map[string]struct{}{} + var mu sync.Mutex + add := func(entries fs.DirEntries) error { + mu.Lock() + defer mu.Unlock() + var batch []Entry + for _, e := range entries { + if len(rows)+len(batch) >= max { + break + } + // A few backends report the same object twice. + if _, dup := seen[e.Remote()]; dup { + continue + } + seen[e.Remote()] = struct{}{} + batch = append(batch, mk.entry(ctx, e)) + } + sortByPath(batch) + rows = append(rows, batch...) + if len(batch) > 0 { + emit(batch) + } + if len(rows) >= max { + capped = true + return errStop + } + return nil + } + err = listDir(ctx, f, dir, add) + if err != nil && dir != "" && !errors.Is(err, errStop) && ctx.Err() == nil { + // Some backends want a folder with a trailing slash, and others refuse it. When the retry + // fails too, the first error is returned because it explains the real problem. Most + // backends simply have no folder with a trailing slash. + first := err + if err = listDir(ctx, f, dir+"/", add); err != nil && !errors.Is(err, errStop) { + err = first + } + } + if errors.Is(err, errStop) { + err = nil + } + if err != nil { + return nil, false, err + } + sortByPath(rows) + return rows, capped, nil +} + +// listDir lists dir of f one level down, passing each batch to add until add returns an error. +// It uses the Fs's ListP when there is one, which paged backends have, so a cap stops the listing +// after the page where it is reached. Otherwise it uses List. +func listDir(ctx context.Context, f fs.Fs, dir string, add fs.ListRCallback) error { + stats := accounting.Stats(ctx) + cb := func(entries fs.DirEntries) error { + stats.Listed(int64(len(entries))) + return add(list.RemoveEscaping(entries)) + } + if listP := f.Features().ListP; listP != nil { + return listP(ctx, dir, cb) + } + entries, err := f.List(ctx, dir) + if err != nil { + return err + } + return cb(entries) +} + +// getFs returns the Fs of a folder from rclone's fs cache, which a config change clears. +func getFs(ctx context.Context, fsName string) (fs.Fs, error) { + f, err := cache.Get(ctx, fsName) + if errors.Is(err, fs.ErrorIsFile) { + return nil, errs.Errorf("%s is a file, not a folder", fsName) + } + return f, err +} + +// entryMaker builds Entries the same way as rclone's fs/operations/lsjson.go, with noMimeType set, +// and with noModTime set for the files of a backend whose mod times are slow, unless the user +// asked for them (see slowModTime). +type entryMaker struct { + format string + isBucket bool + tier bool + slowModTime bool +} + +func newEntryMaker(ctx context.Context, f fs.Fs, dir string, fileDates bool) entryMaker { + ft := f.Features() + return entryMaker{ + format: timeFormat(f.Precision()), + isBucket: ft.BucketBased && dir == "" && f.Root() == "", + tier: ft.GetTier, + slowModTime: !fileDates && slowModTime(ctx, f), + } +} + +// slowModTime reports whether reading a file's mod time costs a request of its own. s3, swift +// and a few other backends keep it in metadata that a listing doesn't return, so each file would +// need a HEAD request, one after another: minutes for a large folder. Their files are then shown +// without a time, as rclone's --no-modtime does, unless the user turns on File dates in +// Commander. With --use-server-modtime, the time in the listing is used, which costs nothing. +func slowModTime(ctx context.Context, f fs.Fs) bool { + return f.Features().SlowModTime && !fs.GetConfig(ctx).UseServerModTime +} + +// modTimeOf returns e's mod time, or the zero time for a file whose time is slow to read. A +// folder's time comes with the listing. +func modTimeOf(ctx context.Context, e fs.DirEntry, slow bool) time.Time { + if _, file := e.(fs.Object); file && slow { + return time.Time{} + } + return e.ModTime(ctx) +} + +func (m entryMaker) entry(ctx context.Context, e fs.DirEntry) Entry { + it := Entry{Path: e.Remote(), Name: path.Base(e.Remote()), Size: e.Size()} + if e.Remote() == "" { + it.Name = "" + } + if t := modTimeOf(ctx, e, m.slowModTime); !t.IsZero() { + it.ModTime = t.Format(m.format) + } + if do, ok := e.(fs.IDer); ok { + it.ID = do.ID() + } + switch x := e.(type) { + case fs.Directory: + // Only the top level of a bucket-based remote's root holds buckets. + it.IsDir, it.IsBucket = true, m.isBucket && !strings.Contains(e.Remote(), "/") + case fs.Object: + if do, ok := x.(fs.GetTierer); ok && m.tier { + it.Tier = do.GetTier() + } + } + return it +} + +// timeFormat returns the ModTime format for a backend's precision, as formatForPrecision in +// lsjson.go does. +func timeFormat(precision time.Duration) string { + switch { + case precision <= time.Nanosecond: + return "2006-01-02T15:04:05.000000000Z07:00" + case precision <= 10*time.Nanosecond: + return "2006-01-02T15:04:05.00000000Z07:00" + case precision <= 100*time.Nanosecond: + return "2006-01-02T15:04:05.0000000Z07:00" + case precision <= time.Microsecond: + return "2006-01-02T15:04:05.000000Z07:00" + case precision <= 10*time.Microsecond: + return "2006-01-02T15:04:05.00000Z07:00" + case precision <= 100*time.Microsecond: + return "2006-01-02T15:04:05.0000Z07:00" + case precision <= time.Millisecond: + return "2006-01-02T15:04:05.000Z07:00" + case precision <= 10*time.Millisecond: + return "2006-01-02T15:04:05.00Z07:00" + case precision <= 100*time.Millisecond: + return "2006-01-02T15:04:05.0Z07:00" + } + return time.RFC3339 +} + +func sortByPath(rows []Entry) { + slices.SortStableFunc(rows, func(a, b Entry) int { return strings.Compare(a.Path, b.Path) }) +} diff --git a/core/browse/listing_test.go b/core/browse/listing_test.go new file mode 100644 index 00000000..f8b67346 --- /dev/null +++ b/core/browse/listing_test.go @@ -0,0 +1,409 @@ +package browse + +import ( + "context" + "errors" + "fmt" + "io" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/operations" +) + +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *clock) add(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +func testLister() (*Lister, *clock) { + c := &clock{t: time.UnixMilli(1_700_000_000_000)} + l := NewLister() + l.now = c.now + return l, c +} + +// epochOf returns the generation of the (fs, dir) listing in l. An invalidation changes it. +func epochOf(l *Lister, fsName, dir string) uint64 { + fsName, dir = Clean(fsName, dir) + l.mu.Lock() + defer l.mu.Unlock() + return l.stateLocked(listingKey{fsName, dir}).gen +} + +// listOf lists through l and returns the emitted rows and fetchedAt. +func listOf(t *testing.T, l *Lister, fsName, dir string, fresh bool, max int) ([]Entry, int64, error) { + t.Helper() + var rows []Entry + at, err := l.List(context.Background(), fsName, dir, fresh, false, max, func(e []Entry) { rows = append(rows, e...) }) + return rows, at, err +} + +func paths(rows []Entry) []string { + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = r.Path + } + return out +} + +func TestListingCache(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/2.txt": "22", "a/1.txt": "1", "a/sub/x": "x", "b/": ""})} + root := AddFixture(fx) + l, c := testLister() + + rows, at, err := listOf(t, l, root, "a", false, ListMax) + if err != nil { + t.Fatal(err) + } + if got := paths(rows); !slices.Equal(got, []string{"a/1.txt", "a/2.txt", "a/sub"}) { + t.Fatalf("rows %v", got) + } + if !rows[2].IsDir || rows[1].Size != 2 || rows[1].Name != "2.txt" || rows[1].ModTime == "" { + t.Errorf("row shape: %+v", rows) + } + if at != c.now().UnixMilli() || fx.Lists() != 1 { + t.Fatalf("fetchedAt %d, %d listings", at, fx.Lists()) + } + epoch := epochOf(l, root, "a") + + step := func(name string, d time.Duration, fresh bool, wantLists int, wantAt int64) { + t.Helper() + c.add(d) + rows, got, err := listOf(t, l, root, "a", fresh, ListMax) + if err != nil || len(rows) != 3 { + t.Fatalf("%s: %v %v", name, paths(rows), err) + } + if fx.Lists() != wantLists || got != wantAt { + t.Fatalf("%s: %d listings, fetchedAt %d; want %d, %d", name, fx.Lists(), got, wantLists, wantAt) + } + } + step("fresh: served from the cache", 4*time.Minute, false, 1, at) + if epochOf(l, root, "a") != epoch { + t.Error("the epoch changed while the listing is fresh") + } + step("a refresh asks rclone", 0, true, 2, c.now().UnixMilli()) + at = c.now().UnixMilli() + if epochOf(l, root, "a") != epoch { + t.Error("a refresh changed the epoch") + } + step("still fresh after the refresh", 4*time.Minute, false, 2, at) + c.add(time.Minute + time.Millisecond) + step("stale: asks rclone", 0, false, 3, c.now().UnixMilli()) +} + +func TestListingKeep(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/1": "1"})} + root := AddFixture(fx) + l, c := testLister() + l.fresh = 24 * time.Hour // test only the keep rule + + for range 3 { // requested every 20 min, so it is kept + if _, _, err := listOf(t, l, root, "a", false, ListMax); err != nil { + t.Fatal(err) + } + c.add(20 * time.Minute) + } + c.add(9 * time.Minute) // 29 minutes since the last request + if _, _, err := listOf(t, l, root, "a", false, ListMax); err != nil || fx.Lists() != 1 { + t.Fatalf("kept while asked for: %d listings, %v", fx.Lists(), err) + } + c.add(ListingKeep) + if _, _, err := listOf(t, l, root, "a", false, ListMax); err != nil || fx.Lists() != 2 { + t.Fatalf("dropped after %v unasked: %d listings, %v", ListingKeep, fx.Lists(), err) + } + c.add(ListingKeep) + l.tick() + l.mu.Lock() + n := len(l.states) + l.mu.Unlock() + if n != 0 { + t.Errorf("%d listings held after the sweep", n) + } +} + +func TestAFailedListingIsNotCached(t *testing.T) { + var fail bool + var mu sync.Mutex + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/1": "1"}), Hook: func(_ context.Context, dir string) error { + mu.Lock() + defer mu.Unlock() + if fail { + return errRefused + } + return nil + }} + root := AddFixture(fx) + l, _ := testLister() + mu.Lock() + fail = true + mu.Unlock() + if _, _, err := listOf(t, l, root, "", false, ListMax); !errors.Is(err, errRefused) { + t.Fatalf("err %v", err) + } + mu.Lock() + fail = false + mu.Unlock() + rows, _, err := listOf(t, l, root, "", false, ListMax) + if err != nil || len(rows) != 1 || fx.Lists() != 2 { + t.Fatalf("after a failure: %v %v, %d listings", paths(rows), err, fx.Lists()) + } +} + +func TestAChangeDuringAListingIsNotCached(t *testing.T) { + started := make(chan struct{}, 1) + release := make(chan struct{}) + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/1": "1"}), Hook: func(ctx context.Context, _ string) error { + select { + case started <- struct{}{}: + <-release + default: + } + return nil + }} + root := AddFixture(fx) + l, _ := testLister() + done := make(chan error) + go func() { + _, _, err := listOf(t, l, root, "a", false, ListMax) + done <- err + }() + <-started + l.InvalidatePaths(root + "a/new") + close(release) + if err := <-done; err != nil { + t.Fatal(err) + } + if _, _, err := listOf(t, l, root, "a", false, ListMax); err != nil || fx.Lists() != 2 { + t.Fatalf("%d listings, %v: the answer begun before the change was served", fx.Lists(), err) + } +} + +func TestTrailingSlashRetry(t *testing.T) { + var dirs []string + var mu sync.Mutex + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/1": "1"}), Hook: func(_ context.Context, dir string) error { + mu.Lock() + defer mu.Unlock() + dirs = append(dirs, dir) + if !strings.HasSuffix(dir, "/") { + return errRefused // this backend wants folders with a slash + } + return nil + }} + root := AddFixture(fx) + l, _ := testLister() + rows, _, err := listOf(t, l, root, "a", false, ListMax) + if err != nil || !slices.Equal(paths(rows), []string{"a/1"}) { + t.Fatalf("%v %v", paths(rows), err) + } + // The root is not retried, because "" has no form with a trailing slash. + if _, _, err := listOf(t, l, root, "", false, ListMax); !errors.Is(err, errRefused) { + t.Fatalf("root: %v", err) + } + mu.Lock() + defer mu.Unlock() + if !slices.Equal(dirs, []string{"a", "a/", ""}) { + t.Errorf("asked %q", dirs) + } +} + +// TestTrailingSlashRetryKeepsTheFirstError checks that when the retry also fails, the first +// listing's error is returned rather than the retry's. S3, for example, has no folder whose name +// ends in a slash. +func TestTrailingSlashRetryKeepsTheFirstError(t *testing.T) { + errNotFound := errors.New("directory not found") + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/1": "1"}), Hook: func(_ context.Context, dir string) error { + if strings.HasSuffix(dir, "/") { + return errNotFound + } + return errRefused + }} + l, _ := testLister() + if _, _, err := listOf(t, l, AddFixture(fx), "a", false, ListMax); !errors.Is(err, errRefused) || fx.Lists() != 2 { + t.Fatalf("%d listings: %v, want the first one's error", fx.Lists(), err) + } +} + +func TestRowsAreSortedAndDeduped(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{"c": "", "a": "", "b/": ""}), Dupes: true} + root := AddFixture(fx) + l, _ := testLister() + rows, _, err := listOf(t, l, root, "", false, ListMax) + if err != nil || !slices.Equal(paths(rows), []string{"a", "b", "c"}) { + t.Fatalf("%v %v", paths(rows), err) + } +} + +func TestCleanAndTheAbsoluteRoot(t *testing.T) { + for _, tc := range []struct{ fs, dir, wantFs, wantDir string }{ + {"r:", "a/b/", "r:", "a/b"}, + {"r:", "/a", "r:/", "a"}, + {"r:", "/", "r:/", ""}, + {"r:/", "a", "r:/", "a"}, + {":local:/", "/tmp/x", ":local:/", "tmp/x"}, + {"r:sub", "/x", "r:sub", "x"}, + } { + gotFs, gotDir := Clean(tc.fs, tc.dir) + if gotFs != tc.wantFs || gotDir != tc.wantDir { + t.Errorf("Clean(%q, %q) = %q, %q", tc.fs, tc.dir, gotFs, gotDir) + } + } + // The two roots are two separate listings. + l, _ := testLister() + if epochOf(l, "r:", "") == epochOf(l, "r:/", "") || epochOf(l, "r:", "/a") != epochOf(l, "r:/", "a/") { + t.Error("keys: r: and r:/ must differ, r: + /a and r:/ + a/ must not") + } +} + +// memoryFiles creates n files in folder dir of a new memory bucket and returns the bucket's fs. +func memoryFiles(t *testing.T, dir string, n int) string { + t.Helper() + bucket := fmt.Sprintf(":memory:bkt-%s", strings.ToLower(strings.ReplaceAll(t.Name(), "/", "-"))) + ctx := context.Background() + f, err := cache.Get(ctx, bucket) + if err != nil { + t.Fatal(err) + } + for i := range n { + name := fmt.Sprintf("%s/file-%03d", dir, i) + if _, err := operations.Rcat(ctx, f, name, io.NopCloser(strings.NewReader("x")), time.Now(), nil); err != nil { + t.Fatal(err) + } + } + return bucket +} + +func TestAPagedListingStopsAtTheCap(t *testing.T) { + bucket := memoryFiles(t, "d", 250) + for _, tc := range []struct { + name string + listP bool + max int + wantRows int + wantTranches int + }{ + {"paged, under the cap", true, ListMax, 250, 3}, + {"paged, stopped in the page the cap is reached in", true, 150, 150, 2}, + {"paged, stopped at a page's end", true, 100, 100, 1}, + {"not paged: cut after the one answer", false, 150, 150, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := &Fixture{Inner: bucket, ListP: tc.listP} + root := AddFixture(fx) + l, _ := testLister() + rows, _, err := listOf(t, l, root, "d", false, tc.max) + if err != nil { + t.Fatal(err) + } + if len(rows) != tc.wantRows || fx.Tranches() != tc.wantTranches || fx.Lists() != 1 { + t.Fatalf("%d rows, %d pages, %d listings", len(rows), fx.Tranches(), fx.Lists()) + } + // The cached copy serves the same cap, sorted as a whole. A bigger cap asks rclone again. + again, _, _ := listOf(t, l, root, "d", false, tc.max) + if len(again) != tc.wantRows || fx.Lists() != 1 { + t.Fatalf("again: %d rows, %d listings", len(again), fx.Lists()) + } + if !slices.IsSortedFunc(again, func(a, b Entry) int { return strings.Compare(a.Path, b.Path) }) { + t.Error("the cached rows are not sorted") + } + if tc.wantRows < 250 { + if more, _, _ := listOf(t, l, root, "d", false, ListMax); len(more) != 250 || fx.Lists() != 2 { + t.Fatalf("a bigger cap: %d rows, %d listings", len(more), fx.Lists()) + } + } + }) + } +} + +func TestInvalidation(t *testing.T) { + keys := [][2]string{ + {"mem:", ""}, {"mem:", "a"}, {"mem:", "a/b"}, {"mem:", "a/b/c"}, {"mem:", "ab"}, + {"mem:/", "a"}, {"mem,x=y:", "a"}, {"other:", "a"}, {"other:", "a/z"}, {"other:", "z"}, + {":local:/", "tmp/x"}, {":local:/", "tmp/xy"}, + } + for _, tc := range []struct { + name string + do func(l *Lister) + want []string // "fs|dir" of the listings invalidated + }{ + {"an entry changed: its folder, itself and below", func(l *Lister) { l.InvalidatePaths("mem:a/b") }, + []string{"mem:|a", "mem:|a/b", "mem:|a/b/c", "mem,x=y:|a"}}, + {"an entry at the root", func(l *Lister) { l.InvalidatePaths("mem:a") }, + []string{"mem:|", "mem:|a", "mem:|a/b", "mem:|a/b/c", "mem,x=y:|a"}}, + {"a folder, below and above it", func(l *Lister) { l.InvalidateFolders("mem:a/") }, + []string{"mem:|", "mem:|a", "mem:|a/b", "mem:|a/b/c", "mem,x=y:|a"}}, + {"a new folder deep down: every folder above it", func(l *Lister) { l.InvalidateFolders("mem:a/b/new/deep") }, + []string{"mem:|", "mem:|a", "mem:|a/b", "mem,x=y:|a"}}, + {"the absolute root is another place", func(l *Lister) { l.InvalidatePaths("mem:/a/f.txt") }, + []string{"mem:/|a"}}, + {"remotes", func(l *Lister) { l.InvalidateRemotes([]string{"mem"}) }, + []string{"mem:|", "mem:|a", "mem:|a/b", "mem:|a/b/c", "mem:|ab", "mem:/|a", "mem,x=y:|a"}}, + {"a copy ended: its destination", func(l *Lister) { l.TransferEnded("copy", []string{"mem:ab/f.txt"}, "other:a/") }, + []string{"other:|a", "other:|a/z"}}, + {"a move ended: its sources too", func(l *Lister) { l.TransferEnded("move", []string{"mem:ab/f.txt"}, "other:z") }, + []string{"mem:|ab", "other:|z"}}, + {"a download ended: the entry it wrote and its folder", func(l *Lister) { l.TransferEnded("download", []string{"https://x/y"}, "other:a/z") }, + []string{"other:|a", "other:|a/z"}}, + {"a purge ended", func(l *Lister) { l.TransferEnded("purge", []string{"mem:a/b"}, "") }, + []string{"mem:|a", "mem:|a/b", "mem:|a/b/c", "mem,x=y:|a"}}, + {"a bisync ended: both its paths", func(l *Lister) { l.TransferEnded("bisync", []string{"mem:a/b"}, "other:a") }, + []string{"mem:|", "mem:|a", "mem:|a/b", "mem:|a/b/c", "mem,x=y:|a", "other:|a", "other:|a/z"}}, + {"a local path", func(l *Lister) { l.InvalidatePaths("/tmp/x/new") }, + []string{":local:/|tmp/x"}}, + } { + t.Run(tc.name, func(t *testing.T) { + l, _ := testLister() + before := map[string]uint64{} + for _, k := range keys { + before[k[0]+"|"+k[1]] = epochOf(l, k[0], k[1]) + } + tc.do(l) + var got []string + for _, k := range keys { + if epochOf(l, k[0], k[1]) != before[k[0]+"|"+k[1]] { + got = append(got, k[0]+"|"+k[1]) + } + } + slices.Sort(got) + want := slices.Sorted(slices.Values(tc.want)) + if !slices.Equal(got, want) { + t.Errorf("invalidated %q, want %q", got, want) + } + }) + } +} + +func TestInvalidationDropsTheCachedRows(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a/1": "1"})} + root := AddFixture(fx) + l, _ := testLister() + for i, invalidate := range []func(){ + func() { l.InvalidatePaths(root + "a/1") }, + func() { l.InvalidateFolders(root) }, + } { + if _, _, err := listOf(t, l, root, "a", false, ListMax); err != nil { + t.Fatal(err) + } + invalidate() + if _, _, err := listOf(t, l, root, "a", false, ListMax); err != nil || fx.Lists() != i+2 { + t.Fatalf("case %d: %d listings, %v", i, fx.Lists(), err) + } + } +} diff --git a/core/browse/main_test.go b/core/browse/main_test.go new file mode 100644 index 00000000..8c9be3e1 --- /dev/null +++ b/core/browse/main_test.go @@ -0,0 +1,260 @@ +package browse + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + _ "github.com/rclone/rclone/backend/local" + _ "github.com/rclone/rclone/backend/memory" + "github.com/rclone/rclone/backend/overview" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/accounting" + "github.com/rclone/rclone/fs/config/configmap" + "github.com/rclone/rclone/fs/fspath" + + "github.com/rclone/rclone-ui/core/internal/testutil" + "github.com/rclone/rclone-ui/core/rclone" +) + +// Every test shares one Init, as the app does. The remotes are in memory. +func TestMain(m *testing.M) { + testutil.Main(m, func(dir string) error { + conf := filepath.Join(dir, "rclone.conf") + if err := os.WriteFile(conf, []byte("[mem]\ntype = memory\n"), 0o600); err != nil { + return err + } + _, err := rclone.Init(context.Background(), rclone.InitOptions{ConfigPath: conf, CacheDir: filepath.Join(dir, "cache")}) + return err + }) +} + +// MakeTree writes files under a new temporary folder and returns its real path. files maps a +// slash-separated path to its content, and a path ending in / is an empty folder. +func MakeTree(t testing.TB, files map[string]string) string { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + for rel, text := range files { + p := filepath.Join(root, filepath.FromSlash(rel)) + if rel[len(rel)-1] == '/' { + if err := os.MkdirAll(p, 0o755); err != nil { + t.Fatal(err) + } + continue + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +// Fixture sets how the test backend behaves. The `:browsetest,id=:` root returned by +// AddFixture lists the Fs at Inner/ through the test backend. Hook runs before every List +// or ListP of dir, for example to add a delay or a failure. With ListP set, the backend is paged. +// With ListR set, it lists a whole tree at once, and stops at the first folder that fails. With +// Dupes set, every List reports each entry twice. +type Fixture struct { + Inner string + ListP bool + ListR bool + Dupes bool + Hook func(ctx context.Context, dir string) error + + lists, tranches, running, most atomic.Int32 + mu sync.Mutex + groups []string +} + +// Lists returns how many List or ListP calls were made. Most returns the largest number that +// ran at the same time. Tranches returns how many pages a ListP delivered. +func (fx *Fixture) Lists() int { return int(fx.lists.Load()) } +func (fx *Fixture) Most() int { return int(fx.most.Load()) } +func (fx *Fixture) Running() int { return int(fx.running.Load()) } +func (fx *Fixture) Tranches() int { return int(fx.tranches.Load()) } + +// Groups returns the stats groups that the listings ran in. +func (fx *Fixture) Groups() []string { + fx.mu.Lock() + defer fx.mu.Unlock() + return append([]string(nil), fx.groups...) +} + +var ( + fixturesMu sync.Mutex + fixtures = map[string]*Fixture{} + fixtureSeq int +) + +// AddFixture returns the root of fx as an fs string. +func AddFixture(fx *Fixture) string { + fixturesMu.Lock() + defer fixturesMu.Unlock() + fixtureSeq++ + id := fmt.Sprintf("f%d", fixtureSeq) + fixtures[id] = fx + return ":browsetest,id=" + id + ":" +} + +// Sleep waits for d or until ctx ends, like a request to a throttled backend. +func Sleep(ctx context.Context, d time.Duration) error { + select { + case <-time.After(d): + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func init() { + fs.Register(&fs.RegInfo{ + Name: "browsetest", + Description: "browse's test backend", + NewFs: newTestFs, + Options: []fs.Option{{Name: "id", Help: "The fixture.", Required: true}}, + Overview: new(overview.BackendConfig), + }) +} + +// testFs wraps the inner Fs under its own name and root. rclone's fs cache stores an Fs under +// fs.ConfigString(f), so with the inner Fs's name and root the cache would return the inner Fs +// in place of this one. +type testFs struct { + fs.Fs + name, root string + fx *Fixture + features *fs.Features +} + +// testFsP is a paged backend, because it has ListP. +type testFsP struct{ *testFs } + +// testFsR lists a whole tree at once, because it has ListR. +type testFsR struct{ *testFs } + +func newTestFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) { + id, _ := m.Get("id") + fixturesMu.Lock() + fx := fixtures[id] + fixturesMu.Unlock() + if fx == nil { + return nil, fmt.Errorf("no fixture %q", id) + } + inner, err := fs.NewFs(ctx, fspath.JoinRootPath(fx.Inner, root)) + if inner == nil { + return nil, err + } + t := &testFs{Fs: inner, name: name, root: root, fx: fx} + var f fs.Fs = t + switch { + case fx.ListP: + f = &testFsP{t} + case fx.ListR: + f = &testFsR{t} + } + t.features = (&fs.Features{}).Fill(ctx, f) + return f, err // fs.ErrorIsFile passes through +} + +func (f *testFs) Features() *fs.Features { return f.features } +func (f *testFs) Name() string { return f.name } +func (f *testFs) Root() string { return f.root } +func (f *testFs) String() string { return f.name + ":" + f.root } + +func (f *testFs) List(ctx context.Context, dir string) (fs.DirEntries, error) { + if err := f.fx.enter(ctx, dir); err != nil { + return nil, err + } + defer f.fx.running.Add(-1) + entries, err := f.Fs.List(ctx, dir) + if f.fx.Dupes { + entries = append(entries, entries...) + } + return entries, err +} + +// ListP splits the inner listing into pages. It uses the inner backend's own pages when that +// backend is paged (the memory backend uses 100 entries each), and pages of 100 otherwise. +func (f *testFsP) ListP(ctx context.Context, dir string, callback fs.ListRCallback) error { + if err := f.fx.enter(ctx, dir); err != nil { + return err + } + defer f.fx.running.Add(-1) + page := func(entries fs.DirEntries) error { + f.fx.tranches.Add(1) + return callback(entries) + } + if listP := f.Fs.Features().ListP; listP != nil { + return listP(ctx, dir, page) + } + entries, err := f.Fs.List(ctx, dir) + if err != nil { + return err + } + for len(entries) > 0 { + n := min(100, len(entries)) + if err := page(entries[:n]); err != nil { + return err + } + entries = entries[n:] + } + return nil +} + +// ListR lists each folder below dir through List, so the hook runs for each, and sends each +// listing on. It stops at the first error, as a bucket's listing does. +func (f *testFsR) ListR(ctx context.Context, dir string, callback fs.ListRCallback) error { + entries, err := f.List(ctx, dir) + if err != nil { + return err + } + if err := callback(entries); err != nil { + return err + } + for _, e := range entries { + if d, ok := e.(fs.Directory); ok { + if err := f.ListR(ctx, d.Remote(), callback); err != nil { + return err + } + } + } + return nil +} + +// enter counts a listing and runs the hook. On success, the caller must decrement running. +func (fx *Fixture) enter(ctx context.Context, dir string) error { + fx.lists.Add(1) + if g, ok := accounting.StatsGroupFromContext(ctx); ok { + fx.mu.Lock() + fx.groups = append(fx.groups, g) + fx.mu.Unlock() + } + n := fx.running.Add(1) + for { + most := fx.most.Load() + if n <= most || fx.most.CompareAndSwap(most, n) { + break + } + } + if fx.Hook != nil { + if err := fx.Hook(ctx, dir); err != nil { + fx.running.Add(-1) + return err + } + } + return nil +} + +var errRefused = errors.New("the backend refused this folder") diff --git a/core/browse/paths.go b/core/browse/paths.go new file mode 100644 index 00000000..f96d5f9e --- /dev/null +++ b/core/browse/paths.go @@ -0,0 +1,62 @@ +package browse + +import ( + "strings" + + "github.com/rclone/rclone/fs/fspath" +) + +// Clean puts a listing's location in the form that keys its cache entry. fs is the root that is +// listed (`remote:`, `remote:/`, `:local:/`), and dir is the folder below it, without slashes at +// either end. A leading slash on dir moves to the root, so `remote:` + `/a` becomes `remote:/` + +// `a`. On sftp that is the machine's root rather than the login folder. listingKey.ts keeps the +// two apart in the same way. +func Clean(fsName, dir string) (string, string) { + if strings.HasPrefix(dir, "/") && strings.HasSuffix(fsName, ":") { + fsName += "/" + } + return fsName, strings.Trim(dir, "/") +} + +func Join(fsName, dir string) string { return fspath.JoinRootPath(fsName, dir) } + +// place is a parsed path, used to match listings when they are invalidated. remote is the +// config name without connection-string parameters (listingKey.ts also keys by the panel's +// remote), or ":local" for this machine. abs says whether the path is absolute. path has no +// slashes at either end and uses `/` between names, because fspath turns `\` into `/` on Windows. +type place struct { + remote string + abs bool + path string +} + +func placeOf(p string) (place, bool) { + parsed, err := fspath.Parse(p) + if err != nil { + return place{}, false + } + name, pth := parsed.Name, parsed.Path + if name == "" { + name = ":local" + } + return place{remote: name, abs: strings.HasPrefix(pth, "/"), path: strings.Trim(pth, "/")}, true +} + +// parent returns the folder that holds p. A root has nothing above it, so it is its own parent. +func (p place) parent() place { + i := strings.LastIndexByte(p.path, '/') + if i < 0 { + p.path = "" + } else { + p.path = p.path[:i] + } + return p +} + +// covers reports whether q is p or a folder below it (`r:ab` is not below `r:a`). +func (p place) covers(q place) bool { + if p.remote != q.remote || p.abs != q.abs { + return false + } + return p.path == "" || q.path == p.path || strings.HasPrefix(q.path, p.path+"/") +} diff --git a/core/browse/search.go b/core/browse/search.go new file mode 100644 index 00000000..98d0b5d4 --- /dev/null +++ b/core/browse/search.go @@ -0,0 +1,88 @@ +package browse + +import ( + "context" + "errors" + "path" + "strings" + "sync" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/walk" + "golang.org/x/text/unicode/norm" +) + +// Search walks dir under fs (in the form Clean returns) and everything below it. It emits the +// entries whose name contains term, ignoring case, as they are found. It uses the backend's ListR +// when there is one, and otherwise walks --checkers folders at a time. Entries whose name starts +// with a dot, and anything inside such a folder below dir, are left out because the page hides +// them. This isn't done with an rclone filter, because an include rule without a slash lets every +// folder through and turns off the backend's ListR (fs/filter/filter.go:347-358,685-695). A +// folder that can't be read does not stop the walk. Its error is returned at the end. The walk +// ends after max entries, whether they match or not, and then Search returns ErrWalkMax. +func Search(ctx context.Context, fsName, dir, term string, max int, fileDates bool, emit func([]Entry)) error { + fsName, dir = Clean(fsName, dir) + f, err := getFs(ctx, fsName) + if err != nil { + return err + } + mk := newEntryMaker(ctx, f, dir, fileDates) + want := folded(term) + prefix := "" + if dir != "" { + prefix = dir + "/" + } + var mu sync.Mutex + seen := map[string]struct{}{} + walked := 0 + err = walk.ListR(ctx, f, dir, true, -1, walk.ListAll, func(entries fs.DirEntries) error { + mu.Lock() + defer mu.Unlock() + full := len(entries) >= max-walked + entries = entries[:min(len(entries), max-walked)] + walked += len(entries) + var found []Entry + for _, e := range entries { + rel, ok := strings.CutPrefix(e.Remote(), prefix) + if !ok || rel == "" || hidden(rel) || !strings.Contains(folded(path.Base(rel)), want) { + continue + } + if _, dup := seen[e.Remote()]; dup { + continue + } + seen[e.Remote()] = struct{}{} + found = append(found, mk.entry(ctx, e)) + } + if len(found) > 0 { + sortByPath(found) + emit(found) + } + if full { + return errStop + } + return ctx.Err() + }) + if errors.Is(err, errStop) { + return ErrWalkMax + } + return err +} + +// ErrWalkMax ends a search that read its most entries (Search's max) before it reached the end +// of the folder. The matches it found up to there were emitted, but there may be more. +var ErrWalkMax = errors.New("the search read its most entries and stopped") + +// folded returns a name in the form that a search compares: composed (NFC) and lower case. +// Composing means that "café" typed with é as one character still finds a name that a Mac +// stored with the accent as a separate character. +func folded(s string) string { return strings.ToLower(norm.NFC.String(s)) } + +// hidden reports whether a segment of the slash-separated rel starts with a dot. +func hidden(rel string) bool { + for seg := range strings.SplitSeq(rel, "/") { + if strings.HasPrefix(seg, ".") { + return true + } + } + return false +} diff --git a/core/browse/search_test.go b/core/browse/search_test.go new file mode 100644 index 00000000..0ed511ff --- /dev/null +++ b/core/browse/search_test.go @@ -0,0 +1,153 @@ +package browse + +import ( + "context" + "errors" + "fmt" + "io" + "slices" + "strings" + "testing" + "time" + + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/operations" +) + +var searchTree = map[string]string{ + "docs/Report.txt": "1", + "docs/report-old.md": "2", + "docs/.hidden/report.txt": "3", + "docs/.report-draft": "4", + ".git/report": "5", + "notes/REPORTS/x.txt": "6", + "a/b/c/deep-report.log": "7", + "other.txt": "8", + "reportless/": "", +} + +func search(t *testing.T, fsName, dir, term string) (found []string, emits int, err error) { + t.Helper() + err = Search(context.Background(), fsName, dir, term, SearchWalkMax, false, func(e []Entry) { + emits++ + found = append(found, paths(e)...) + }) + slices.Sort(found) + return found, emits, err +} + +func TestSearchMatching(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, searchTree)} + root := AddFixture(fx) + for _, tc := range []struct { + name, dir, term string + want []string + }{ + {"name contains the term, case ignored; nothing under or named with a dot", "", "report", + []string{"a/b/c/deep-report.log", "docs/Report.txt", "docs/report-old.md", "notes/REPORTS", "reportless"}}, + {"the term's case does not matter either", "docs", "REPORT", []string{"docs/Report.txt", "docs/report-old.md"}}, + {"the leaf only, not the folders above it", "notes", "notes", nil}, + {"within a dot folder the page opened, what is below it", ".git", "rep", []string{".git/report"}}, + {"a dir with slashes", "/docs/", "old", []string{"docs/report-old.md"}}, + } { + t.Run(tc.name, func(t *testing.T) { + got, _, err := search(t, root, tc.dir, tc.term) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(got, tc.want) { + t.Errorf("found %q, want %q", got, tc.want) + } + }) + } +} + +func TestSearchEmitsAsItWalks(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, searchTree)} + found, emits, err := search(t, AddFixture(fx), "", "report") + if err != nil || len(found) != 5 || emits < 3 { + t.Fatalf("%d matches in %d emits, %v: want them folder by folder", len(found), emits, err) + } +} + +func TestSearchThroughTheBackendsListR(t *testing.T) { + ctx := context.Background() + f, err := cache.Get(ctx, ":memory:search-listr") + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"x/Match-1", "x/y/match-2", "x/.no/match", "x/other"} { + if _, err := operations.Rcat(ctx, f, name, io.NopCloser(strings.NewReader("m")), time.Now(), nil); err != nil { + t.Fatal(err) + } + } + if f.Features().ListR == nil { + t.Fatal("memory has no ListR any more: this test needs a backend with one") + } + got, _, err := search(t, ":memory:search-listr", "x", "MATCH") + if err != nil || !slices.Equal(got, []string{"x/Match-1", "x/y/match-2"}) { + t.Fatalf("%q %v", got, err) + } +} + +// TestSearchStopsAfterItsWalkMax checks that the walk ends after max entries, matching or not, +// without an error, and keeps the matches it found until then. +func TestSearchStopsAfterItsWalkMax(t *testing.T) { + ctx := context.Background() + f, err := cache.Get(ctx, ":memory:search-walkmax") + if err != nil { + t.Fatal(err) + } + for i := range 10 { + name := fmt.Sprintf("x/match-%d", i) + if _, err := operations.Rcat(ctx, f, name, io.NopCloser(strings.NewReader("m")), time.Now(), nil); err != nil { + t.Fatal(err) + } + } + var found []string + err = Search(ctx, ":memory:search-walkmax", "x", "match", 3, false, func(e []Entry) { found = append(found, paths(e)...) }) + if !errors.Is(err, ErrWalkMax) || len(found) != 3 { + t.Fatalf("%q %v: want 3 matches and ErrWalkMax", found, err) + } +} + +// TestSearchIgnoresTheUnicodeForm checks that a term typed in composed form (NFC) finds a name +// stored in decomposed form (NFD, as macOS names files), and the other way round. +func TestSearchIgnoresTheUnicodeForm(t *testing.T) { + ctx := context.Background() + f, err := cache.Get(ctx, ":memory:search-nfc") + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"café.txt", "Naïve.txt"} { + if _, err := operations.Rcat(ctx, f, name, io.NopCloser(strings.NewReader("m")), time.Now(), nil); err != nil { + t.Fatal(err) + } + } + for term, want := range map[string]string{"café": "café.txt", "CAFÉ": "café.txt", "naïve": "Naïve.txt"} { + if got, _, err := search(t, ":memory:search-nfc", "", term); err != nil || !slices.Equal(got, []string{want}) { + t.Errorf("%q: %q %v", term, got, err) + } + } +} + +func TestSearchStopsWithItsContext(t *testing.T) { + entered := make(chan struct{}, 1) + fx := &Fixture{Inner: MakeTree(t, searchTree), Hook: func(ctx context.Context, dir string) error { + if dir == "a/b" { + entered <- struct{}{} + return Sleep(ctx, time.Minute) + } + return nil + }} + ctx, cancel := context.WithCancel(context.Background()) + go func() { + <-entered + cancel() + }() + start := time.Now() + err := Search(ctx, AddFixture(fx), "", "report", SearchWalkMax, false, func([]Entry) {}) + if !errors.Is(err, context.Canceled) || time.Since(start) > 5*time.Second { + t.Fatalf("err %v after %v", err, time.Since(start)) + } +} diff --git a/core/browse/sizes.go b/core/browse/sizes.go new file mode 100644 index 00000000..5d2658a1 --- /dev/null +++ b/core/browse/sizes.go @@ -0,0 +1,126 @@ +package browse + +import ( + "context" + "sync" + "sync/atomic" + + "github.com/rclone/rclone/fs/accounting" + "github.com/rclone/rclone/fs/operations" + + "github.com/rclone/rclone-ui/core/location" + "github.com/rclone/rclone-ui/core/rclone" +) + +// sizesAtOnce is how many folders one Sizes call counts at the same time. +const sizesAtOnce = 2 + +// Size is the content of one folder, counting everything below it. +type Size struct { + Path string + Files int64 + Bytes int64 + // Partial marks counts that are incomplete because the work stopped partway through the folder. + Partial bool +} + +// Sizes counts each folder in paths with operations.Count, two at a time, and emits each result +// when it is done. The paths are rclone paths, as in a listing's rows. A folder that can't be +// counted is left out. When ctx ends, Count stops promptly. The folders being counted then +// report what they had so far, marked Partial, and Sizes returns ctx's error. +func Sizes(ctx context.Context, paths []string, emit func(Size)) error { + // Each folder's remote is opened here first, on the caller's goroutine, which runs an rclone + // job. A fatal rclone error while opening the remote can only be recovered there. The + // folder's own Fs, which a worker opens later, has the same config. A folder whose remote + // doesn't open has nothing to count, so it is left out like any folder that can't be counted. + var todo []string + opened := map[string]bool{} + for _, p := range paths { + // Paths that rclone would refuse or misread are left out too, just as a listing refuses + // them. For example, a relative local path would be counted from the root. + if !location.Problem(p).IsZero() { + continue + } + at, err := location.Split(p) + if err != nil { + continue + } + root := at.Root() + if _, seen := opened[root]; !seen { + _, err := getFs(ctx, root) + if err != nil && ctx.Err() != nil { + return context.Cause(ctx) + } + opened[root] = err == nil + } + if opened[root] { + todo = append(todo, p) + } + } + if len(todo) == 0 { + return nil + } + var ( + mu sync.Mutex // emit is called one at a time + finished atomic.Int64 + wg sync.WaitGroup + ) + // Each folder is counted as its own job in the call's stats group, because rclone can only + // recover from a fatal error on a goroutine that its job runner started. The job's own error, + // which is a fatal one, becomes the folder's error. + group, _ := accounting.StatsGroupFromContext(ctx) + work := make(chan string) + for range min(sizesAtOnce, len(todo)) { + wg.Go(func() { + for p := range work { + var ( + s Size + err error + ) + _, jobErr := rclone.Run(ctx, rclone.CallOpts{Group: group}, func(ctx context.Context) error { + s, err = count(ctx, p) + return nil // count's error is kept with its partial counts + }) + if jobErr != nil { + s, err = Size{Path: p}, jobErr + } + switch { + case err == nil: + finished.Add(1) + case ctx.Err() == nil: + finished.Add(1) + continue + default: + s.Partial = true + } + mu.Lock() + emit(s) + mu.Unlock() + } + }) + } +feed: + for _, p := range todo { + select { + case work <- p: + case <-ctx.Done(): + break feed + } + } + close(work) + wg.Wait() + if finished.Load() < int64(len(todo)) { + return context.Cause(ctx) + } + return nil +} + +// count returns the content of the folder at p, as far as Count got. +func count(ctx context.Context, p string) (Size, error) { + f, err := getFs(ctx, p) + if err != nil { + return Size{Path: p}, err + } + files, bytes, _, err := operations.Count(ctx, f) + return Size{Path: p, Files: files, Bytes: bytes}, err +} diff --git a/core/browse/sizes_test.go b/core/browse/sizes_test.go new file mode 100644 index 00000000..441e33e1 --- /dev/null +++ b/core/browse/sizes_test.go @@ -0,0 +1,89 @@ +package browse + +import ( + "context" + "errors" + "slices" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestSizes(t *testing.T) { + root := MakeTree(t, map[string]string{ + "a/one": "0123456789", + "a/sub/two": "01234567890123456789", + "b/three": "abcde", + "c/": "", + }) + var running, most atomic.Int32 + fx := &Fixture{Inner: root, Hook: func(ctx context.Context, dir string) error { + if dir == "" { // the top of each counted folder: track how many are counted at once + n := running.Add(1) + defer running.Add(-1) + for m := most.Load(); n > m && !most.CompareAndSwap(m, n); m = most.Load() { + } + return Sleep(ctx, 50*time.Millisecond) + } + return nil + }} + var got []Size + fsName := AddFixture(fx) + err := Sizes(context.Background(), []string{fsName + "a", fsName + "b", fsName + "c", fsName + "missing", "-bad:x"}, func(s Size) { got = append(got, s) }) + if err != nil { + t.Fatal(err) + } + slices.SortFunc(got, func(x, y Size) int { return strings.Compare(x.Path, y.Path) }) + want := []Size{{Path: fsName + "a", Files: 2, Bytes: 30}, {Path: fsName + "b", Files: 1, Bytes: 5}, {Path: fsName + "c"}} + if !slices.Equal(got, want) { + t.Errorf("sizes %+v, want %+v (a folder that cannot be counted, or named, is left out)", got, want) + } + if most.Load() != 2 { + t.Errorf("%d folders counted at once, want 2", most.Load()) + } +} + +func TestSizesStopWithPartialCounts(t *testing.T) { + entered := make(chan struct{}, 2) + fx := &Fixture{Inner: MakeTree(t, map[string]string{ + "big/f1": "1", "big/f2": "22", "big/slow/f3": "333", + "next/f": "x", + }), Hook: func(ctx context.Context, dir string) error { + if dir == "slow" { + entered <- struct{}{} + return Sleep(ctx, time.Minute) + } + return nil + }} + ctx, cancel := context.WithCancel(context.Background()) + go func() { + <-entered + cancel() + }() + var got []Size + start := time.Now() + fsName := AddFixture(fx) + err := Sizes(ctx, []string{fsName + "big"}, func(s Size) { got = append(got, s) }) + if !errors.Is(err, context.Canceled) || time.Since(start) > 5*time.Second { + t.Fatalf("err %v after %v", err, time.Since(start)) + } + if len(got) != 1 || got[0] != (Size{Path: fsName + "big", Files: 2, Bytes: 3, Partial: true}) { + t.Fatalf("got %+v: want what was counted before the stop, marked partial", got) + } + + // Folders not yet started are not reported. + got = nil + ctx, cancel = context.WithCancel(context.Background()) + cancel() + fsName = AddFixture(fx) + err = Sizes(ctx, []string{fsName + "big", fsName + "next", fsName + "big/slow"}, func(s Size) { got = append(got, s) }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err %v", err) + } + for _, s := range got { + if !s.Partial { + t.Errorf("%+v reported whole after the stop", s) + } + } +} diff --git a/core/browse/slowmodtime_test.go b/core/browse/slowmodtime_test.go new file mode 100644 index 00000000..7790cf88 --- /dev/null +++ b/core/browse/slowmodtime_test.go @@ -0,0 +1,183 @@ +package browse + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/rclone/gofakes3" + "github.com/rclone/gofakes3/s3mem" + _ "github.com/rclone/rclone/backend/s3" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/object" +) + +// countingS3 is an S3 server in the test process that counts the requests it gets by method. +type countingS3 struct { + mu sync.Mutex + counts map[string]int + url string +} + +func newCountingS3(t *testing.T, buckets ...string) *countingS3 { + t.Helper() + mem := s3mem.New() + for _, b := range buckets { + if err := mem.CreateBucket(context.Background(), b); err != nil { + t.Fatal(err) + } + } + c := &countingS3{counts: map[string]int{}} + fake := gofakes3.New(mem).Server() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.mu.Lock() + c.counts[r.Method]++ + c.mu.Unlock() + fake.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + c.url = srv.URL + return c +} + +// remote returns an on-the-fly remote for a bucket, as a connection string. +func (c *countingS3) remote(bucket string) string { + return fmt.Sprintf(":s3,provider=Other,endpoint=%q,access_key_id=k,secret_access_key=s,force_path_style=true:%s", c.url, bucket) +} + +func (c *countingS3) reset() { + c.mu.Lock() + c.counts = map[string]int{} + c.mu.Unlock() +} + +func (c *countingS3) heads() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.counts[http.MethodHead] +} + +// put uploads files through rclone's s3 backend, which keeps each one's mod time in its metadata. +func (c *countingS3) put(t *testing.T, bucket string, names ...string) { + t.Helper() + ctx := context.Background() + f, err := fs.NewFs(ctx, c.remote(bucket)) + if err != nil { + t.Fatal(err) + } + at := time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + for _, n := range names { + body := []byte("content of " + n) + info := object.NewStaticObjectInfo(n, at, int64(len(body)), true, nil, f) + if _, err := f.Put(ctx, bytes.NewReader(body), info); err != nil { + t.Fatal(err) + } + } +} + +// TestNoRequestPerFileForModTimes: s3 keeps a file's mod time in metadata that a listing doesn't +// return, so reading it costs a HEAD request per file (rclone's SlowModTime). A listing, a search +// and a comparison leave those times out instead, which keeps a large folder fast, unless File +// dates is on. Folders keep theirs, and so do the files of other backends. +func TestNoRequestPerFileForModTimes(t *testing.T) { + s3 := newCountingS3(t, "left", "right") + var names []string + for i := range 30 { + names = append(names, fmt.Sprintf("dir/file%02d.txt", i)) + } + s3.put(t, "left", names...) + // No name in common: a name on both sides is compared by hash, which may need a request. + s3.put(t, "right", "dir/other.txt") + ctx := context.Background() + + s3.reset() + rows, _, err := fetch(ctx, s3.remote("left"), "dir", 1000, false, func([]Entry) {}) + if err != nil { + t.Fatal(err) + } + if len(rows) != 30 || s3.heads() != 0 { + t.Errorf("listing: %d rows, %d HEAD requests", len(rows), s3.heads()) + } + for _, r := range rows { + if r.ModTime != "" { + t.Errorf("listing: %s has the time %s", r.Path, r.ModTime) + } + } + + s3.reset() + var found []Entry + if err := Search(ctx, s3.remote("left"), "", "file1", 1000, false, func(es []Entry) { found = append(found, es...) }); err != nil { + t.Fatal(err) + } + if len(found) != 10 || s3.heads() != 0 { + t.Errorf("search: %d found, %d HEAD requests", len(found), s3.heads()) + } + + // Opening a path below a bucket checks once whether it is a file. That is one request per + // side, whatever the number of files, so the remotes are opened before counting. + for _, side := range []string{"left", "right"} { + if _, err := getFs(ctx, s3.remote(side)+"/dir"); err != nil { + t.Fatal(err) + } + } + s3.reset() + cmp, err := Compare(ctx, s3.remote("left")+"/dir", s3.remote("right")+"/dir", false) + if err != nil { + t.Fatal(err) + } + if len(cmp.Pairs) != 31 || s3.heads() != 0 { + t.Errorf("compare: %d pairs, %d HEAD requests", len(cmp.Pairs), s3.heads()) + } + + // With File dates on, the times are read, one request per file. A cached listing made + // without them isn't served. + l := NewLister() + if _, err := l.List(ctx, s3.remote("left"), "dir", false, false, 1000, func([]Entry) {}); err != nil { + t.Fatal(err) + } + s3.reset() + rows = nil + if _, err := l.List(ctx, s3.remote("left"), "dir", false, true, 1000, func(es []Entry) { rows = append(rows, es...) }); err != nil { + t.Fatal(err) + } + if len(rows) != 30 || s3.heads() != 30 || rows[0].ModTime == "" { + t.Errorf("with dates: %d rows, %d HEAD requests, first time %q", len(rows), s3.heads(), rows[0].ModTime) + } + // Asked again the same way, it comes from the cache. + s3.reset() + if _, err := l.List(ctx, s3.remote("left"), "dir", false, true, 1000, func([]Entry) {}); err != nil || s3.counts[http.MethodGet] != 0 || s3.heads() != 0 { + t.Errorf("cached listing with dates: %v, %v", s3.counts, err) + } + + // A local file's time is in its listing, so it stays. + local := MakeTree(t, map[string]string{"a.txt": "a"}) + rows, _, err = fetch(ctx, local, "", 10, false, func([]Entry) {}) + if err != nil || len(rows) != 1 || rows[0].ModTime == "" { + t.Errorf("local listing: %+v, %v", rows, err) + } +} + +// TestServerModTimesAreShown: with --use-server-modtime, a file's time is the one in the listing, +// which costs nothing, so it is shown. +func TestServerModTimesAreShown(t *testing.T) { + s3 := newCountingS3(t, "bucket") + s3.put(t, "bucket", "a.txt", "b.txt") + ctx, ci := fs.AddConfig(context.Background()) + ci.UseServerModTime = true + + s3.reset() + // Another bucket name than the other test's, so rclone's cache doesn't hand back an Fs made + // without the setting. + rows, _, err := fetch(ctx, s3.remote("bucket"), "", 10, false, func([]Entry) {}) + if err != nil { + t.Fatal(err) + } + if len(rows) != 2 || s3.heads() != 0 || rows[0].ModTime == "" { + t.Errorf("rows %+v, %d HEAD requests", rows, s3.heads()) + } +} diff --git a/core/browse/usage.go b/core/browse/usage.go new file mode 100644 index 00000000..945fbd56 --- /dev/null +++ b/core/browse/usage.go @@ -0,0 +1,831 @@ +package browse + +import ( + "cmp" + "container/heap" + "context" + "errors" + "path" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/accounting" + "github.com/rclone/rclone/fs/walk" + + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/location" + "github.com/rclone/rclone-ui/core/rclone" +) + +// Disk Usage scans a whole remote, or a whole local disk, into a tree of folders with their +// totals. The Commander's Disk Usage drawer reads it one folder at a time while the scan runs. +// The totals are always exact. The files are kept by name only as far as memory allows: each +// folder keeps its largest files, and the others count as its "smaller files". + +const ( + // usageKeep is the most files that one folder keeps by name. + usageKeep = 1000 + // usageFileBudget is the most files that a whole scan keeps by name. Past it, the smallest + // files of every folder count as its smaller files. + usageFileBudget = 1_000_000 + // usageFloor is the first size below which files stop being kept by name, when a scan passes + // its budget. It doubles each time the scan passes the budget again. + usageFloor = 4096 + // UsageFolderMax is the most folders that a scan reads. Past it the scan stops and says so. + UsageFolderMax = 1_000_000 +) + +// UsageSort is the order of a folder's rows. +type UsageSort string + +const ( + BySize UsageSort = "size" // largest first + ByName UsageSort = "name" // A to Z + ByFiles UsageSort = "files" // most files first +) + +// usageTotals are the files below a folder, and their bytes. A file whose size the backend +// doesn't know counts as a file with no bytes, and also as unknown. +type usageTotals struct{ bytes, files, unknown int64 } + +func (t *usageTotals) add(o usageTotals) { + t.bytes += o.bytes + t.files += o.files + t.unknown += o.unknown +} + +func (t *usageTotals) sub(o usageTotals) { + t.bytes -= o.bytes + t.files -= o.files + t.unknown -= o.unknown +} + +func fileTotals(size int64) usageTotals { + if size < 0 { + return usageTotals{files: 1, unknown: 1} + } + return usageTotals{bytes: size, files: 1} +} + +// usageFile is a file kept by name. size is -1 when the backend doesn't know it. +type usageFile struct { + name string + size int64 +} + +// fileHeap is a folder's kept files, with the smallest on top, so the one to let go of when a +// larger file arrives is at hand. A file of unknown size counts as the smallest. +type fileHeap []usageFile + +func (h fileHeap) Len() int { return len(h) } +func (h fileHeap) Less(i, j int) bool { return h[i].size < h[j].size } +func (h fileHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *fileHeap) Push(x any) { *h = append(*h, x.(usageFile)) } +func (h *fileHeap) Pop() any { + old := *h + f := old[len(old)-1] + *h = old[:len(old)-1] + return f +} + +// usageNode is one folder of a scan. +type usageNode struct { + name string + parent *usageNode + dirs map[string]*usageNode // made when the first folder inside arrives + files fileHeap // the files directly inside that are kept by name + rest usageTotals // the files directly inside that aren't + total usageTotals // every file below, those directly inside included + // folders is how many folders are below. + folders int64 + // unread marks a folder that couldn't be listed, so its content isn't counted. + unread bool + // unreadBelow is how many folders below couldn't be listed. + unreadBelow int64 +} + +// rel returns the folder's path below the scan's root, "" for the root. +func (n *usageNode) rel() string { + var names []string + for ; n.parent != nil; n = n.parent { + names = append(names, n.name) + } + slices.Reverse(names) + return strings.Join(names, "/") +} + +// UsageTree is the result of a scan, as far as it got. It is safe to read while the scan adds to +// it. +type UsageTree struct { + mu sync.Mutex + root *usageNode + // kept is how many files the whole tree keeps by name, and floor the size below which a file + // isn't kept. + kept int + floor int64 + // The limits, which tests lower. + keep, budget int + maxFolders int64 + // capped is set when the scan reached maxFolders. + capped bool + // at is the folder that was read last. + at string + // lastDir and lastNode remember the folder that the last entry went into, because the + // entries of one listing usually share it. + lastDir string + lastNode *usageNode +} + +func NewUsageTree() *UsageTree { + root := &usageNode{} + return &UsageTree{root: root, keep: usageKeep, budget: usageFileBudget, maxFolders: UsageFolderMax, lastNode: root} +} + +// node returns the folder at rel, making it and any missing folder above it. Buckets often list +// files without the folders they are in, so a file's folder may not have arrived yet. +func (t *UsageTree) node(rel string) *usageNode { + if rel == t.lastDir && t.lastNode != nil { + return t.lastNode + } + n := t.root + if rel != "" { + for name := range strings.SplitSeq(rel, "/") { + n = t.child(n, name) + } + } + t.lastDir, t.lastNode = rel, n + return n +} + +// child returns the folder name inside n, making it when it is new. +func (t *UsageTree) child(n *usageNode, name string) *usageNode { + if c := n.dirs[name]; c != nil { + return c + } + if n.dirs == nil { + n.dirs = map[string]*usageNode{} + } + c := &usageNode{name: name, parent: n} + n.dirs[name] = c + for p := n; p != nil; p = p.parent { + p.folders++ + } + if t.root.folders >= t.maxFolders { + t.capped = true + } + return c +} + +// add puts a batch of entries into the tree. Each entry's path is below the scan's root. +func (t *UsageTree) add(entries fs.DirEntries) { + t.mu.Lock() + defer t.mu.Unlock() + for _, e := range entries { + rel := e.Remote() + if rel == "" { + continue + } + dir, name := path.Split(rel) + dir = strings.TrimSuffix(dir, "/") + switch e.(type) { + case fs.Directory: + t.child(t.node(dir), name) + case fs.Object: + t.addFile(t.node(dir), name, e.Size()) + } + } +} + +// addFile counts a file in n and every folder above, and keeps it by name when it is among the +// largest of n. +func (t *UsageTree) addFile(n *usageNode, name string, size int64) { + tt := fileTotals(size) + for p := n; p != nil; p = p.parent { + p.total.add(tt) + } + switch { + case max(size, 0) < t.floor: // unknown sizes are kept until the floor rises + n.rest.add(tt) + return + case len(n.files) < t.keep: + heap.Push(&n.files, usageFile{name, size}) + t.kept++ + case size > n.files[0].size: + out := heap.Pop(&n.files).(usageFile) + n.rest.add(fileTotals(out.size)) + heap.Push(&n.files, usageFile{name, size}) + default: + n.rest.add(tt) + return + } + if t.kept > t.budget { + t.raiseFloor() + } +} + +// raiseFloor lets go of the smallest files of every folder until the tree keeps no more than its +// budget. They then count as their folders' smaller files. +func (t *UsageTree) raiseFloor() { + for t.kept > t.budget { + t.floor = max(usageFloor, t.floor*2) + t.kept = 0 + stack := []*usageNode{t.root} + for len(stack) > 0 { + n := stack[len(stack)-1] + stack = stack[:len(stack)-1] + kept := n.files[:0] + for _, f := range n.files { + if max(f.size, 0) >= t.floor { + kept = append(kept, f) + } else { + n.rest.add(fileTotals(f.size)) + } + } + n.files = kept + heap.Init(&n.files) + t.kept += len(n.files) + for _, c := range n.dirs { + stack = append(stack, c) + } + } + } +} + +// unread marks the folder at rel as one that couldn't be listed. +func (t *UsageTree) unread(rel string) { + t.mu.Lock() + defer t.mu.Unlock() + n := t.node(rel) + if n.unread { + return + } + n.unread = true + for p := n.parent; p != nil; p = p.parent { + p.unreadBelow++ + } +} + +// reset empties the tree, for a scan that starts again. +func (t *UsageTree) reset() { + t.mu.Lock() + defer t.mu.Unlock() + t.root = &usageNode{} + t.kept, t.floor, t.capped, t.at = 0, 0, false, "" + t.lastDir, t.lastNode = "", t.root +} + +// reading notes the folder that the scan reads now. +func (t *UsageTree) reading(rel string) { + t.mu.Lock() + t.at = rel + t.mu.Unlock() +} + +// full reports whether the scan reached its most folders. +func (t *UsageTree) full() bool { + t.mu.Lock() + defer t.mu.Unlock() + return t.capped +} + +// UsageCount is what a scan found so far. +type UsageCount struct { + Bytes int64 `json:"bytes"` + Files int64 `json:"files"` + Folders int64 `json:"folders"` + // Unknown is how many files have no known size. + Unknown int64 `json:"unknown"` + // Unread is how many folders couldn't be listed. + Unread int64 `json:"unread"` + // At is the folder that was read last, below the root. + At string `json:"at,omitempty"` + Capped bool `json:"capped,omitempty"` +} + +func (t *UsageTree) Count() UsageCount { + t.mu.Lock() + defer t.mu.Unlock() + r := t.root + unread := r.unreadBelow + if r.unread { + unread++ + } + return UsageCount{ + Bytes: r.total.bytes, Files: r.total.files, Folders: r.folders, Unknown: r.total.unknown, + Unread: unread, At: t.at, Capped: t.capped, + } +} + +// UsageRow is one entry of a folder in a scan: a folder with everything below it, or a file. +type UsageRow struct { + Name string `json:"name"` + // Rel is the entry's path below the scan's root, and Path its full path, as a listing's rows + // write it. + Rel string `json:"rel"` + Path string `json:"path"` + IsDir bool `json:"isDir"` + // Bytes, Files and Folders count everything below a folder. A file counts itself as one file. + Bytes int64 `json:"bytes"` + Files int64 `json:"files"` + Folders int64 `json:"folders"` + // Unknown is how many of the files have no known size. For a file, it is 1 when its own size + // is unknown. + Unknown int64 `json:"unknown"` + // Unread marks a folder that couldn't be listed, and UnreadBelow counts the folders below it + // that couldn't be. + Unread bool `json:"unread,omitempty"` + UnreadBelow int64 `json:"unreadBelow,omitempty"` +} + +// UsageRest is the files directly in a folder that the scan doesn't keep by name. +type UsageRest struct { + Files int64 `json:"files"` + Bytes int64 `json:"bytes"` + Unknown int64 `json:"unknown"` +} + +// UsageLevel is one folder of a scan with its rows. +type UsageLevel struct { + // Rel is the folder's path below the scan's root, "" for the root. + Rel string `json:"rel"` + // Total is the folder itself, as its row in its parent shows it. + Total UsageRow `json:"total"` + // Rows are its folders and kept files in the asked order, at most the asked number. + Rows []UsageRow `json:"rows"` + // More is how many rows follow the last one returned. + More int `json:"more"` + Rest UsageRest `json:"rest"` +} + +// Level returns the folder at rel with its first limit rows in the order by. root writes the rows' +// full paths. It returns false when the tree has no such folder. +// +// The drawer reads a folder twice a second while the scan adds to it, under the tree's lock. So +// only the rows it returns are built: the folder's entries are ordered by their numbers, and a +// heap keeps the first limit of them. +func (t *UsageTree) Level(root location.Fs, rel string, by UsageSort, limit int) (UsageLevel, bool) { + t.mu.Lock() + defer t.mu.Unlock() + n := t.find(rel) + if n == nil { + return UsageLevel{}, false + } + total := len(n.dirs) + len(n.files) + keep := total + if limit > 0 && limit < total { + keep = limit + } + order := usageOrder(by) + first := &entryHeap{order: order, items: make([]usageEntry, 0, keep)} + add := func(e usageEntry) { + switch { + case keep == total: // every entry is returned, so no heap is needed + first.items = append(first.items, e) + case len(first.items) < keep: + heap.Push(first, e) + case order(e, first.items[0]) < 0: + first.items[0] = e + heap.Fix(first, 0) + } + } + for _, c := range n.dirs { + add(usageEntry{name: c.name, bytes: c.total.bytes, files: c.total.files, dir: c}) + } + for _, f := range n.files { + add(usageEntry{name: f.name, bytes: max(f.size, 0), files: 1, size: f.size}) + } + entries := first.items + slices.SortFunc(entries, order) + + prefix := "" + if rel != "" { + prefix = rel + "/" + } + rows := make([]UsageRow, len(entries)) + for i, e := range entries { + if e.dir != nil { + rows[i] = dirRow(root, e.dir) + continue + } + rows[i] = UsageRow{Name: e.name, Rel: prefix + e.name, Bytes: e.bytes, Files: 1} + if e.size < 0 { + rows[i].Unknown = 1 + } + rows[i].Path = root.Entry(rows[i].Rel) + } + return UsageLevel{ + Rel: rel, Total: dirRow(root, n), Rows: rows, More: total - len(rows), + Rest: UsageRest{Files: n.rest.files, Bytes: n.rest.bytes, Unknown: n.rest.unknown}, + }, true +} + +// usageEntry is an entry of a folder as Level orders it, before its row is built. dir is nil for a +// file, whose size is -1 when the backend doesn't know it. +type usageEntry struct { + name string + bytes, files int64 + dir *usageNode + size int64 +} + +// entryHeap holds the first entries in an order, with the last of them on top, so that an entry +// that comes before it takes its place. +type entryHeap struct { + order func(a, b usageEntry) int + items []usageEntry +} + +func (h *entryHeap) Len() int { return len(h.items) } +func (h *entryHeap) Less(i, j int) bool { return h.order(h.items[j], h.items[i]) < 0 } +func (h *entryHeap) Swap(i, j int) { h.items[i], h.items[j] = h.items[j], h.items[i] } +func (h *entryHeap) Push(x any) { h.items = append(h.items, x.(usageEntry)) } +func (h *entryHeap) Pop() any { + e := h.items[len(h.items)-1] + h.items = h.items[:len(h.items)-1] + return e +} + +func dirRow(root location.Fs, n *usageNode) UsageRow { + rel := n.rel() + return UsageRow{ + Name: n.name, Rel: rel, Path: root.Entry(rel), IsDir: true, + Bytes: n.total.bytes, Files: n.total.files, Folders: n.folders, Unknown: n.total.unknown, + Unread: n.unread, UnreadBelow: n.unreadBelow, + } +} + +// usageOrder compares two entries in the order by. Ties go by name, so the order never flickers +// between two reads. +func usageOrder(by UsageSort) func(a, b usageEntry) int { + name := func(a, b usageEntry) int { return CompareNames(a.name, b.name) } + switch by { + case ByName: + return name + case ByFiles: + return func(a, b usageEntry) int { + return cmp.Or(cmp.Compare(b.files, a.files), cmp.Compare(b.bytes, a.bytes), name(a, b)) + } + default: + return func(a, b usageEntry) int { + return cmp.Or(cmp.Compare(b.bytes, a.bytes), cmp.Compare(b.files, a.files), name(a, b)) + } + } +} + +// find returns the folder at rel, or nil when the tree has none. +func (t *UsageTree) find(rel string) *usageNode { + n := t.root + if rel == "" { + return n + } + for name := range strings.SplitSeq(rel, "/") { + if n = n.dirs[name]; n == nil { + return nil + } + } + return n +} + +// Forget takes the entry at rel out of the tree and out of every total above it, after it was +// deleted. isDir says whether it is a folder, because a bucket can hold a file and a folder of +// the same name. It returns false when the tree doesn't hold the entry by name. +func (t *UsageTree) Forget(rel string, isDir bool) bool { + t.mu.Lock() + defer t.mu.Unlock() + dir, name := path.Split(rel) + parent := t.find(strings.TrimSuffix(dir, "/")) + if parent == nil || name == "" { + return false + } + t.lastDir, t.lastNode = "", t.root // the folder remembered may be the one going away + if isDir { + c := parent.dirs[name] + if c == nil { + return false + } + delete(parent.dirs, name) + unread := c.unreadBelow + if c.unread { + unread++ + } + for p := parent; p != nil; p = p.parent { + p.total.sub(c.total) + p.folders -= c.folders + 1 + p.unreadBelow -= unread + } + stack := []*usageNode{c} + for len(stack) > 0 { + n := stack[len(stack)-1] + stack = stack[:len(stack)-1] + t.kept -= len(n.files) + for _, d := range n.dirs { + stack = append(stack, d) + } + } + return true + } + i := slices.IndexFunc(parent.files, func(f usageFile) bool { return f.name == name }) + if i < 0 { + return false + } + f := heap.Remove(&parent.files, i).(usageFile) + t.kept-- + for p := parent; p != nil; p = p.parent { + p.total.sub(fileTotals(f.size)) + } + return true +} + +// scanUsage reads everything below f's root into t. skip names folders below the root that the +// scan leaves out (the mount points of other disks), with / between names. +// +// A backend that lists a whole tree at once (ListR, which buckets have) is read that way, as one +// stream. Any other is walked folder by folder, as many at a time as rclone's --checkers, from +// the top down and taking turns between the folders at the top (walkQueue), so they all grow at +// the same time. A folder that can't be listed is marked and the walk goes on. When the root +// itself can't be listed, scanUsage returns its error. +// +// The stream stops at the first folder it can't list, such as a bucket that refuses its listing. +// The scan then starts again as a walk, which marks that folder and reads the rest. +// +// When ctx ends, the walk stops and the tree keeps what it found. +func scanUsage(ctx context.Context, f fs.Fs, skip map[string]bool, t *UsageTree) error { + if f.Features().ListR != nil && len(skip) == 0 { + err := listRUsage(ctx, f, t) + if err == nil || ctx.Err() != nil { + return err + } + fs.Debugf(f, "Disk Usage: listing the whole tree failed, walking it folder by folder: %v", err) + t.reset() + } + return walkUsage(ctx, f, skip, t) +} + +func listRUsage(ctx context.Context, f fs.Fs, t *UsageTree) error { + err := walk.ListR(ctx, f, "", true, -1, walk.ListAll, func(entries fs.DirEntries) error { + if len(entries) > 0 { + dir, _ := path.Split(entries[len(entries)-1].Remote()) + t.reading(strings.TrimSuffix(dir, "/")) + } + t.add(entries) + if t.full() { + return errStop + } + return ctx.Err() + }) + if errors.Is(err, errStop) { + return nil + } + return err +} + +func walkUsage(ctx context.Context, f fs.Fs, skip map[string]bool, t *UsageTree) error { + var ( + mu sync.Mutex + wake = sync.NewCond(&mu) + queue = newWalkQueue() + busy int + rootErr error + wg sync.WaitGroup + ) + stop := context.AfterFunc(ctx, func() { + mu.Lock() + wake.Broadcast() + mu.Unlock() + }) + defer stop() + + // next waits for a folder to read. It returns false when there is none left, or the scan + // stopped. + next := func() (string, bool) { + mu.Lock() + defer mu.Unlock() + for queue.len() == 0 && busy > 0 && ctx.Err() == nil { + wake.Wait() + } + if queue.len() == 0 || ctx.Err() != nil || t.full() { + wake.Broadcast() + return "", false + } + busy++ + return queue.pop(), true + } + done := func(found []string) { + mu.Lock() + defer mu.Unlock() + busy-- + for _, dir := range found { + queue.push(dir) + } + wake.Broadcast() + } + + // read lists one folder. A panic while it lists (a fatal rclone error) still ends the folder, + // marked as unread, so that the other workers don't wait for it. The job runner then + // recovers the panic, and that worker stops. + rootDied := false + read := func(ctx context.Context, dir string) { + var found []string + listed := false + defer func() { + if !listed { + t.unread(dir) + if dir == "" { + mu.Lock() + rootDied = true + mu.Unlock() + } + } + done(found) + }() + t.reading(dir) + found, err := listUsage(ctx, f, dir, skip, t) + if err != nil && ctx.Err() == nil { + if dir == "" { + mu.Lock() + rootErr = err + mu.Unlock() + } + t.unread(dir) + } + listed = true + } + + // Each worker runs as its own job in the scan's stats group, because rclone can only recover + // from a fatal error on a goroutine that its job runner started. + var died error // the last worker's panic + group, _ := accounting.StatsGroupFromContext(ctx) + for range max(1, fs.GetConfig(ctx).Checkers) { + wg.Go(func() { + _, err := rclone.Run(ctx, rclone.CallOpts{Group: group}, func(ctx context.Context) error { + for { + dir, ok := next() + if !ok { + return nil + } + read(ctx, dir) + } + }) + if err != nil { + mu.Lock() + died = err + mu.Unlock() + } + }) + } + wg.Wait() + // The scan didn't finish when the root's listing died, or when folders still wait, which + // happens only when every worker died. + if rootErr == nil && died != nil && (rootDied || queue.len() > 0 && ctx.Err() == nil && !t.full()) { + return died + } + return rootErr +} + +// walkQueue holds the folders that a walk reads next. Each folder at the top of the tree has a +// queue of the folders below it, read in the order they were found, and the walk takes one from +// each in turn. So a scan finds the first files of every top folder early, and their sizes grow +// side by side, instead of one top folder being read to the end before the next. +type walkQueue struct { + byTop map[string][]string + tops []string // the top folders that have folders waiting, in the order they came + turn int // the next top folder to take from + n int +} + +func newWalkQueue() *walkQueue { + q := &walkQueue{byTop: map[string][]string{}} + q.push("") + return q +} + +func (q *walkQueue) len() int { return q.n } + +func (q *walkQueue) push(dir string) { + top, _, _ := strings.Cut(dir, "/") + if len(q.byTop[top]) == 0 { + q.tops = append(q.tops, top) + } + q.byTop[top] = append(q.byTop[top], dir) + q.n++ +} + +// pop returns the next folder. The queue must not be empty. +func (q *walkQueue) pop() string { + q.turn %= len(q.tops) + top := q.tops[q.turn] + waiting := q.byTop[top] + dir := waiting[0] + if len(waiting) == 1 { + delete(q.byTop, top) + q.tops = slices.Delete(q.tops, q.turn, q.turn+1) + } else { + q.byTop[top] = waiting[1:] + q.turn++ + } + q.n-- + return dir +} + +// listUsage lists one folder into t and returns the folders inside it that the walk reads next. +func listUsage(ctx context.Context, f fs.Fs, dir string, skip map[string]bool, t *UsageTree) ([]string, error) { + var found []string + seen := map[string]struct{}{} // a few backends report the same entry twice + err := listDir(ctx, f, dir, func(entries fs.DirEntries) error { + batch := entries[:0:0] + for _, e := range entries { + rel := e.Remote() + if _, dup := seen[rel]; dup || rel == "" || skip[rel] { + continue + } + seen[rel] = struct{}{} + if _, ok := e.(fs.Directory); ok { + found = append(found, rel) + } + batch = append(batch, e) + } + t.add(batch) + return ctx.Err() + }) + return found, err +} + +// UsageRoot is what a scan reads: the root of a remote, or a whole local disk. +type UsageRoot struct { + location.Fs + // Skip names the folders below the root that the scan leaves out, with / between names. + Skip map[string]bool +} + +// usageRootOf returns the root of the remote or local disk that the folder at p is on. On a +// remote, that is the remote's root as p writes it, with its parameters and its leading slash +// (`sftp:/` is the machine's root, `sftp:` the login folder). On this machine, it is the disk +// that p is on, and the scan leaves out the mount points below it: other disks, network shares +// and mounted remotes. mounts lists the mount points. +func usageRootOf(p string, mounts func() ([]string, error)) (UsageRoot, error) { + at, err := folderOf(p, "path", i18n.M("Select a folder on the remote or disk to scan.")) + if err != nil { + return UsageRoot{}, err + } + if !at.Local { + at.Rel, at.Folder = "", true + return UsageRoot{Fs: at}, nil + } + full := at.Entry(at.Rel) + var points []string + if mounts != nil { + points, _ = mounts() // without the table, the scan can still read the disk + } + root, skip := diskRoot(runtime.GOOS, full, points) + // The disk's root is the anchor, so that rclone opens it and the rows' paths start with it. + anchor := filepath.ToSlash(root) + if !strings.HasSuffix(anchor, "/") { + anchor += "/" + } + rootAt := location.Fs{Name: ":local", Config: ":local", Anchor: anchor, Folder: true, Local: true} + return UsageRoot{Fs: rootAt, Skip: skip}, nil +} + +// darwinData is where macOS mounts the volume that holds the user's data. Its folders also +// appear at the top of / through firmlinks, so a scan of / leaves it out and still counts them. +const darwinData = "/System/Volumes/Data" + +// diskRoot returns the root of the disk that the local folder full is on, and the mount points +// below that root, as paths below it. points are the mount table's entries. +// +// On Windows, the disk is the path's drive or share. Elsewhere, it is the deepest mount point +// that holds the folder. On macOS, the data volume counts as part of /. +func diskRoot(goos, full string, points []string) (string, map[string]bool) { + if goos == "windows" { + return filepath.VolumeName(full) + `\`, nil + } + real := full + if r, err := filepath.EvalSymlinks(full); err == nil { + real = r + } + root := "/" + for _, p := range points { + if within(real, p) && len(p) > len(root) { + root = p + } + } + if goos == "darwin" && root == darwinData { + root = "/" + } + skip := map[string]bool{} + for _, p := range points { + if p != root && within(p, root) { + skip[strings.TrimPrefix(strings.TrimPrefix(p, root), "/")] = true + } + } + return root, skip +} + +// within reports whether the slash-separated path p is dir or below it. +func within(p, dir string) bool { + return dir == "/" || p == dir || strings.HasPrefix(p, dir+"/") +} diff --git a/core/browse/usage_api_test.go b/core/browse/usage_api_test.go new file mode 100644 index 00000000..7e0399d7 --- /dev/null +++ b/core/browse/usage_api_test.go @@ -0,0 +1,217 @@ +package browse_test + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/browse" + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/internal/late" + "github.com/rclone/rclone-ui/core/internal/testutil" +) + +// progress keeps the progress that scans sent, by request. +type progress struct { + mu sync.Mutex + sent map[string][]browse.UsageProgress +} + +func (p *progress) emit(_ context.Context, name string, data any) { + if name != browse.EventUsage { + return + } + p.mu.Lock() + defer p.mu.Unlock() + u := data.(browse.UsageProgress) + p.sent[u.Request] = append(p.sent[u.Request], u) +} + +func (p *progress) last(request string) (browse.UsageProgress, bool) { + p.mu.Lock() + defer p.mu.Unlock() + s := p.sent[request] + if len(s) == 0 { + return browse.UsageProgress{}, false + } + return s[len(s)-1], true +} + +// ended waits for request's scan to end and returns its last progress. +func (p *progress) ended(t *testing.T, request string) browse.UsageProgress { + t.Helper() + var last browse.UsageProgress + testutil.Eventually(t, 10*time.Second, "the scan to end", func() bool { + var ok bool + last, ok = p.last(request) + return ok && last.State != browse.UsageScanning + }) + return last +} + +func usageAPI() (*browse.API, *progress) { + p := &progress{sent: map[string][]browse.UsageProgress{}} + return browse.NewAPI(late.Of(browse.NewLister()), p.emit), p +} + +// scan starts a scan of path and returns a function that cancels its call, as the page does, +// and waits for the call to return its error. Calling it again returns the same error. +func scan(a *browse.API, request, path string) (release func() error) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- a.Usage(ctx, request, path) }() + var ( + once sync.Once + err error + ) + return func() error { + once.Do(func() { + cancel() + select { + case err = <-done: + case <-time.After(10 * time.Second): + err = errors.New("the call didn't return") + } + }) + return err + } +} + +func TestUsageScansARemote(t *testing.T) { + ctx := context.Background() + fx := &browse.Fixture{Inner: browse.MakeTree(t, map[string]string{ + "photos/2024/a.jpg": "0123456789", + "photos/b.jpg": "01234", + "notes.txt": "abc", + })} + root := browse.AddFixture(fx) + a, p := usageAPI() + release := scan(a, "r1", root+"photos/2024") // a folder deep down: the whole remote is scanned + defer func() { _ = release() }() + if got, err := a.UsageRoot(ctx, root+"photos/2024"); err != nil || got != root { + t.Fatalf("the root of a folder deep down: %q %v", got, err) + } + end := p.ended(t, "r1") + if end.State != browse.UsageDone || end.Root != root || end.Local || end.EndedAt == 0 { + t.Fatalf("end %+v", end) + } + if c := end.Count; c.Bytes != 18 || c.Files != 3 || c.Folders != 2 { + t.Fatalf("count %+v", c) + } + level, err := a.UsageLevel(ctx, "r1", "", browse.BySize, 0) + if err != nil { + t.Fatal(err) + } + var got []string + for _, r := range level.Rows { + got = append(got, r.Path) + } + if !slices.Equal(got, []string{root + "photos", root + "notes.txt"}) { + t.Fatalf("rows %q", got) + } + if err := a.UsageForget(ctx, "r1", "photos/2024", true); err != nil { + t.Fatal(err) + } + if after, _ := p.last("r1"); after.Count.Bytes != 8 || after.State != browse.UsageDone || after.EndedAt != end.EndedAt { + t.Fatalf("the progress sent again after a delete: %+v", after) + } + level, _ = a.UsageLevel(ctx, "r1", "photos", browse.BySize, 0) + if level.Total.Bytes != 5 || len(level.Rows) != 1 { + t.Fatalf("photos after forgetting 2024: %+v", level) + } + if _, err := a.UsageLevel(ctx, "r1", "photos/2024", browse.BySize, 0); code(err) != errs.CodeNotFound { + t.Fatalf("a forgotten folder: %v", err) + } + + // Once the page lets go of the call, the scan is gone. + if err := release(); err != nil { + t.Fatal(err) + } + if _, err := a.UsageLevel(ctx, "r1", "", browse.BySize, 0); code(err) != errs.CodeNotFound { + t.Fatalf("a released scan: %v", err) + } +} + +// TestUsageReadsWhileItScans checks that a page can read a scan before it ends, and that Stop +// ends the walk and keeps what it found. +func TestUsageReadsWhileItScans(t *testing.T) { + ctx := context.Background() + entered := make(chan struct{}) + var once sync.Once + fx := &browse.Fixture{Inner: browse.MakeTree(t, map[string]string{"fast/a": "12345", "slow/b": "1"}), Hook: func(ctx context.Context, dir string) error { + if dir == "slow" { + once.Do(func() { close(entered) }) + return browse.Sleep(ctx, time.Minute) + } + return nil + }} + a, p := usageAPI() + release := scan(a, "r2", browse.AddFixture(fx)) + defer func() { _ = release() }() + <-entered + testutil.Eventually(t, 5*time.Second, "the fast folder to be read during the scan", func() bool { + level, err := a.UsageLevel(ctx, "r2", "fast", browse.BySize, 0) + return err == nil && level.Total.Bytes == 5 + }) + if last, _ := p.last("r2"); last.State != browse.UsageScanning { + t.Fatalf("state %s during the scan", last.State) + } + if err := a.UsageStop(ctx, "r2"); err != nil { + t.Fatal(err) + } + end := p.ended(t, "r2") + if end.State != browse.UsageStopped || end.Count.Bytes != 5 || end.Count.Unread != 0 { + t.Fatalf("end %+v", end) + } + if _, err := a.UsageLevel(ctx, "r2", "", browse.BySize, 0); err != nil { + t.Fatalf("a stopped scan is kept: %v", err) + } +} + +func TestUsageReturnsTheErrorWhenNothingCouldBeRead(t *testing.T) { + a, _ := usageAPI() + err := a.Usage(context.Background(), "r3", ":browsetest,id=nothing:") + if err == nil { + t.Fatal("a remote that doesn't open was scanned") + } + if err := a.Usage(context.Background(), "r4", ""); code(err) != errs.CodeInvalid { + t.Fatalf("no path: %v", err) + } +} + +// TestUsageKeepsTheNewestScans checks that a third scan lets go of the oldest one, because a page +// that reloads can't cancel the call it made. +func TestUsageKeepsTheNewestScans(t *testing.T) { + ctx := context.Background() + root := browse.AddFixture(&browse.Fixture{Inner: browse.MakeTree(t, map[string]string{"a": "1"})}) + a, p := usageAPI() + var releases []func() error + for _, r := range []string{"old", "mid", "new"} { + releases = append(releases, scan(a, r, root)) + p.ended(t, r) + } + defer func() { + for _, release := range releases { + _ = release() + } + }() + if _, err := a.UsageLevel(ctx, "old", "", browse.BySize, 0); code(err) != errs.CodeNotFound { + t.Fatalf("the oldest scan: %v", err) + } + for _, r := range []string{"mid", "new"} { + if _, err := a.UsageLevel(ctx, r, "", browse.BySize, 0); err != nil { + t.Fatalf("scan %s: %v", r, err) + } + } +} + +// code returns the code that a page receives with err. +func code(err error) errs.Code { + if e := errs.Of(err); e != nil { + return e.Code + } + return "" +} diff --git a/core/browse/usage_test.go b/core/browse/usage_test.go new file mode 100644 index 00000000..28d54d7b --- /dev/null +++ b/core/browse/usage_test.go @@ -0,0 +1,559 @@ +package browse + +import ( + "context" + "fmt" + "io" + "maps" + "path" + "reflect" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/cache" + "github.com/rclone/rclone/fs/operations" + "github.com/rclone/rclone/fstest/mockdir" + + "github.com/rclone/rclone-ui/core/location" +) + +// file is a listed file: only its path and size are read. +type file struct { + fs.Object + remote string + size int64 +} + +func (f file) Remote() string { return f.remote } +func (f file) Size() int64 { return f.size } + +// entries makes a listing: a name ending in / is a folder, and any other gets its size from +// sizes, or 1. +func entries(sizes map[string]int64, names ...string) fs.DirEntries { + var out fs.DirEntries + for _, n := range names { + if rel, ok := strings.CutSuffix(n, "/"); ok { + out = append(out, mockdir.New(rel)) + continue + } + size, ok := sizes[n] + if !ok { + size = 1 + } + out = append(out, file{remote: n, size: size}) + } + return out +} + +var memRoot = location.Fs{Name: "mem", Config: "mem", Folder: true} + +// names returns the rows' names in order, with their bytes. +func names(level UsageLevel) []string { + var out []string + for _, r := range level.Rows { + out = append(out, r.Name) + } + return out +} + +func level(t *testing.T, tree *UsageTree, rel string, by UsageSort) UsageLevel { + t.Helper() + l, ok := tree.Level(memRoot, rel, by, 0) + if !ok { + t.Fatalf("no folder %q", rel) + } + return l +} + +// TestUsageTreeAddsUp checks the totals of a tree built from entries in any order, where some +// files arrive before their folders and some folders never arrive at all, as on a bucket. +func TestUsageTreeAddsUp(t *testing.T) { + tree := NewUsageTree() + tree.add(entries(map[string]int64{"a/b/c.txt": 10, "a/d.txt": 5, "a/b/doc": -1}, "a/b/c.txt", "e", "f/", "a/d.txt")) + tree.add(entries(map[string]int64{"a/b/doc": -1}, "a/", "a/b/", "a/b/doc", ".hidden/x")) + + got := tree.Count() + want := UsageCount{Bytes: 17, Files: 5, Folders: 4, Unknown: 1} + if got != want { + t.Fatalf("count %+v, want %+v", got, want) + } + root := level(t, tree, "", BySize) + if !slices.Equal(names(root), []string{"a", ".hidden", "e", "f"}) { + t.Fatalf("root rows %q", names(root)) + } + a := root.Rows[0] + if a.Bytes != 15 || a.Files != 3 || a.Folders != 1 || a.Unknown != 1 || !a.IsDir || a.Rel != "a" || a.Path != "mem:a" { + t.Fatalf("row a %+v", a) + } + inA := level(t, tree, "a", BySize) + if !slices.Equal(names(inA), []string{"b", "d.txt"}) || inA.Total.Bytes != 15 { + t.Fatalf("a's rows %q, total %+v", names(inA), inA.Total) + } + if d := inA.Rows[1]; d.IsDir || d.Bytes != 5 || d.Files != 1 || d.Path != "mem:a/d.txt" { + t.Fatalf("row d.txt %+v", d) + } + doc := level(t, tree, "a/b", BySize).Rows[1] + if doc.Name != "doc" || doc.Unknown != 1 || doc.Bytes != 0 { + t.Fatalf("a file of unknown size: %+v", doc) + } + if _, ok := tree.Level(memRoot, "a/missing", BySize, 0); ok { + t.Fatal("a folder the tree hasn't got was found") + } +} + +func TestUsageTreeSorts(t *testing.T) { + tree := NewUsageTree() + tree.add(entries(map[string]int64{"big": 100, "many/1": 1, "many/2": 1, "many/3": 1, "Mid": 50, "same-a": 7, "same-b": 7}, + "big", "many/1", "many/2", "many/3", "Mid", "same-b", "same-a")) + for by, want := range map[UsageSort][]string{ + BySize: {"big", "Mid", "same-a", "same-b", "many"}, + ByName: {"big", "many", "Mid", "same-a", "same-b"}, + ByFiles: {"many", "big", "Mid", "same-a", "same-b"}, + } { + if got := names(level(t, tree, "", by)); !slices.Equal(got, want) { + t.Errorf("by %s: %q, want %q", by, got, want) + } + } + l, _ := tree.Level(memRoot, "", BySize, 2) + if !slices.Equal(names(l), []string{"big", "Mid"}) || l.More != 3 { + t.Fatalf("the first 2 rows: %q, more %d", names(l), l.More) + } +} + +// TestUsageTreeFirstRows checks that the first rows of a folder with many entries are the same as +// the start of all its rows, in each order. +func TestUsageTreeFirstRows(t *testing.T) { + tree := NewUsageTree() + sizes := map[string]int64{} + var all []string + for i := range 300 { + dir := fmt.Sprintf("d%03d/", i) + for j := range i % 4 { + name := fmt.Sprintf("%sf%d", dir, j) + sizes[name] = int64((i * 7919) % 50) + all = append(all, name) + } + all = append(all, dir) + file := fmt.Sprintf("F%03d", i) + sizes[file] = int64((i * 104729) % 60) + all = append(all, file) + } + tree.add(entries(sizes, all...)) + for _, by := range []UsageSort{BySize, ByName, ByFiles} { + every := level(t, tree, "", by) + first, _ := tree.Level(memRoot, "", by, 50) + if len(every.Rows) != 600 || every.More != 0 { + t.Fatalf("by %s: %d rows, more %d", by, len(every.Rows), every.More) + } + if !slices.Equal(names(first), names(every)[:50]) || first.More != 550 { + t.Errorf("by %s: the first 50 rows\n got %q\nwant %q, more %d", by, names(first), names(every)[:50], first.More) + } + if !reflect.DeepEqual(first.Rows, every.Rows[:50]) { + t.Errorf("by %s: the first rows differ from the start of all rows", by) + } + } +} + +// TestUsageTreeKeepsTheLargestFiles checks that a folder keeps its largest files by name, and +// counts the others as its smaller files, with the totals exact. +func TestUsageTreeKeepsTheLargestFiles(t *testing.T) { + tree := NewUsageTree() + tree.keep = 3 + sizes := map[string]int64{} + var all []string + for i := range 10 { + n := "d/" + string(rune('a'+i)) + sizes[n] = int64(i + 1) + all = append(all, n) + } + rand := []int{4, 9, 0, 7, 2, 5, 8, 1, 6, 3} // a fixed order that isn't sorted + for _, i := range rand { + tree.add(entries(sizes, all[i])) + } + d := level(t, tree, "d", BySize) + if !slices.Equal(names(d), []string{"j", "i", "h"}) { + t.Fatalf("kept %q, want the 3 largest", names(d)) + } + if d.Rest != (UsageRest{Files: 7, Bytes: 28}) || d.Total.Bytes != 55 || d.Total.Files != 10 { + t.Fatalf("rest %+v, total %+v", d.Rest, d.Total) + } +} + +// TestUsageTreeStaysInItsBudget checks that a scan past its budget lets go of the smallest files +// of every folder, and keeps counting them. +func TestUsageTreeStaysInItsBudget(t *testing.T) { + tree := NewUsageTree() + tree.budget = 4 + sizes := map[string]int64{"a/1": 10000, "b/2": 5000, "a/3": 100, "c/4": 200, "b/5": 8000, "c/6": 9000, "a/7": 300} + for _, n := range []string{"a/1", "b/2", "a/3", "c/4", "b/5", "c/6", "a/7"} { + tree.add(entries(sizes, n)) + } + if tree.kept != 4 || tree.floor != usageFloor { + t.Fatalf("kept %d with floor %d, want 4 with %d", tree.kept, tree.floor, usageFloor) + } + a := level(t, tree, "a", BySize) + if !slices.Equal(names(a), []string{"1"}) || a.Rest != (UsageRest{Files: 2, Bytes: 400}) { + t.Fatalf("a keeps %q, rest %+v", names(a), a.Rest) + } + if c := tree.Count(); c.Bytes != 32600 || c.Files != 7 { + t.Fatalf("count %+v", c) + } +} + +func TestUsageTreeForgets(t *testing.T) { + tree := NewUsageTree() + tree.add(entries(map[string]int64{"a/b/c": 10, "a/b/d/e": 20, "a/f": 5, "g": 1}, "a/b/c", "a/b/d/e", "a/f", "g")) + tree.unread("a/b/d/x") + if tree.Forget("a/b", false) || !tree.Forget("a/b", true) { + t.Fatal("a/b wasn't forgotten") + } + if c := tree.Count(); c.Bytes != 6 || c.Files != 2 || c.Folders != 1 || c.Unread != 0 { + t.Fatalf("count after forgetting a/b: %+v", c) + } + if tree.kept != 2 { + t.Fatalf("kept %d, want 2", tree.kept) + } + if tree.Forget("a/f", true) || !tree.Forget("a/f", false) || tree.Forget("a/f", false) || tree.Forget("nothing/here", false) { + t.Fatal("forgetting a file once, then again, then one the tree hasn't got") + } + if c := tree.Count(); c.Bytes != 1 || c.Files != 1 { + t.Fatalf("count after forgetting a/f: %+v", c) + } + // New entries still go to the right place after the folder remembered last went away. + tree.add(entries(nil, "a/b/new")) + if c := tree.Count(); c.Files != 2 || c.Folders != 2 { + t.Fatalf("count after a new entry: %+v", c) + } +} + +// A bucket can hold a file and a folder of the same name. Forgetting one leaves the other. +func TestUsageTreeForgetsAFileOrAFolderOfTheSameName(t *testing.T) { + tree := NewUsageTree() + tree.add(entries(map[string]int64{"logs": 10, "logs/a": 20, "logs/b": 30}, "logs", "logs/a", "logs/b")) + if !tree.Forget("logs", false) { + t.Fatal("the file logs wasn't forgotten") + } + if c := tree.Count(); c.Bytes != 50 || c.Files != 2 || c.Folders != 1 { + t.Fatalf("count after forgetting the file: %+v", c) + } + if !tree.Forget("logs", true) { + t.Fatal("the folder logs wasn't forgotten") + } + if c := tree.Count(); c.Bytes != 0 || c.Files != 0 || c.Folders != 0 { + t.Fatalf("count after forgetting the folder: %+v", c) + } +} + +func TestUsageTreeMarksWhatItCouldNotRead(t *testing.T) { + tree := NewUsageTree() + tree.add(entries(nil, "a/b/", "a/c/")) + tree.unread("a/b") + tree.unread("a/b") + if c := tree.Count(); c.Unread != 1 { + t.Fatalf("unread %d, want 1", c.Unread) + } + if a := level(t, tree, "", BySize).Rows[0]; a.Unread || a.UnreadBelow != 1 { + t.Fatalf("row a %+v", a) + } + if b := level(t, tree, "a", ByName).Rows[0]; b.Name != "b" || !b.Unread { + t.Fatalf("row b %+v", b) + } +} + +func TestUsageTreeStopsAtItsMostFolders(t *testing.T) { + tree := NewUsageTree() + tree.maxFolders = 2 + tree.add(entries(nil, "a/")) + if tree.full() { + t.Fatal("full after 1 folder") + } + tree.add(entries(nil, "b/x")) + if !tree.full() || !tree.Count().Capped { + t.Fatal("not full after 2 folders") + } +} + +// TestScanUsageWalksFolderByFolder scans a local tree through a backend without ListR. A folder +// that can't be listed is marked, a skipped folder isn't listed at all, and dot-files count. +func TestScanUsageWalksFolderByFolder(t *testing.T) { + var mu sync.Mutex + var listed []string + fx := &Fixture{Inner: MakeTree(t, map[string]string{ + "a/one": "0123456789", + "a/sub/two": "01234567890123456789", + ".dot/three": "abc", + "bad/four": "abcd", + "skip/five": "abcde", + "six": "abcdef", + }), Hook: func(ctx context.Context, dir string) error { + mu.Lock() + listed = append(listed, dir) + mu.Unlock() + if dir == "bad" { + return errRefused + } + return nil + }} + f, err := cache.Get(context.Background(), AddFixture(fx)) + if err != nil { + t.Fatal(err) + } + tree := NewUsageTree() + if err := scanUsage(context.Background(), f, map[string]bool{"skip": true}, tree); err != nil { + t.Fatal(err) + } + if c := tree.Count(); c.Bytes != 39 || c.Files != 4 || c.Folders != 4 || c.Unread != 1 { + t.Fatalf("count %+v", c) + } + if slices.Contains(listed, "skip") { + t.Fatal("the skipped folder was listed") + } + if got := names(level(t, tree, "", BySize)); !slices.Equal(got, []string{"a", "six", ".dot", "bad"}) { + t.Fatalf("root rows %q", got) + } +} + +func TestScanUsageFailsWhenTheRootCannotBeListed(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{"a": "x"}), Hook: func(ctx context.Context, dir string) error { + return errRefused + }} + f, err := cache.Get(context.Background(), AddFixture(fx)) + if err != nil { + t.Fatal(err) + } + if err := scanUsage(context.Background(), f, nil, NewUsageTree()); err == nil || !strings.Contains(err.Error(), errRefused.Error()) { + t.Fatalf("err %v, want the root's error", err) + } +} + +func TestScanUsageThroughTheBackendsListR(t *testing.T) { + ctx := context.Background() + f, err := cache.Get(ctx, ":memory:usage-listr") + if err != nil { + t.Fatal(err) + } + if f.Features().ListR == nil { + t.Fatal("memory has no ListR any more: this test needs a backend with one") + } + for name, text := range map[string]string{"bucket/x/1": "aa", "bucket/x/y/2": "bbb", "other/3": "c"} { + if _, err := operations.Rcat(ctx, f, name, io.NopCloser(strings.NewReader(text)), time.Now(), nil); err != nil { + t.Fatal(err) + } + } + tree := NewUsageTree() + if err := scanUsage(ctx, f, nil, tree); err != nil { + t.Fatal(err) + } + if c := tree.Count(); c.Bytes != 6 || c.Files != 3 || c.Folders != 4 { + t.Fatalf("count %+v", c) + } +} + +// TestScanUsageAfterAFailedTreeListing scans through a backend that lists the whole tree at once, +// where one folder can't be listed. The scan walks the tree again, marks that folder, and counts +// the rest once. +func TestScanUsageAfterAFailedTreeListing(t *testing.T) { + fx := &Fixture{ListR: true, Inner: MakeTree(t, map[string]string{ + "a/one": "0123456789", "bad/two": "01", "c/three": "012", "four": "0123", + }), Hook: func(ctx context.Context, dir string) error { + if dir == "bad" { + return errRefused + } + return nil + }} + f, err := cache.Get(context.Background(), AddFixture(fx)) + if err != nil { + t.Fatal(err) + } + if f.Features().ListR == nil { + t.Fatal("the fixture has no ListR") + } + tree := NewUsageTree() + if err := scanUsage(context.Background(), f, nil, tree); err != nil { + t.Fatal(err) + } + if c := tree.Count(); c.Bytes != 17 || c.Files != 3 || c.Folders != 3 || c.Unread != 1 { + t.Fatalf("count %+v", c) + } +} + +// TestScanUsageWhenAWorkerDies checks that a scan ends when a listing panics, as a fatal rclone +// error does. That folder is marked unread, and the others are counted. +func TestScanUsageWhenAWorkerDies(t *testing.T) { + fx := &Fixture{Inner: MakeTree(t, map[string]string{ + "a/one": "0123456789", "bad/two": "01", "c/three": "012", "c/d/five": "01234", "four": "0123", + }), Hook: func(ctx context.Context, dir string) error { + if dir == "bad" { + panic("a fatal error") + } + return nil + }} + f, err := cache.Get(context.Background(), AddFixture(fx)) + if err != nil { + t.Fatal(err) + } + tree := NewUsageTree() + ended := make(chan error, 1) + go func() { ended <- scanUsage(context.Background(), f, nil, tree) }() + select { + case err := <-ended: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("the scan hangs") + } + if c := tree.Count(); c.Bytes != 22 || c.Files != 4 || c.Unread != 1 { + t.Fatalf("count %+v", c) + } + + // With one worker, nobody reads the folders left: the scan ends with the panic's error. + ctx, ci := fs.AddConfig(context.Background()) + ci.Checkers = 1 + fx.Hook = func(ctx context.Context, dir string) error { + if dir == "" { + panic("a fatal error") + } + return nil + } + f, err = cache.Get(ctx, AddFixture(fx)) + if err != nil { + t.Fatal(err) + } + if err := scanUsage(ctx, f, nil, NewUsageTree()); err == nil || !strings.Contains(err.Error(), "a fatal error") { + t.Fatalf("err %v, want the panic's", err) + } +} + +// TestScanUsageStops checks that a scan stops promptly when its context ends, and keeps what +// it found. +func TestScanUsageStops(t *testing.T) { + entered := make(chan struct{}) + var once sync.Once + fx := &Fixture{Inner: MakeTree(t, map[string]string{"fast": "12345", "slow/x": "1"}), Hook: func(ctx context.Context, dir string) error { + if dir == "slow" { + once.Do(func() { close(entered) }) + return Sleep(ctx, time.Minute) + } + return nil + }} + f, err := cache.Get(context.Background(), AddFixture(fx)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + go func() { + <-entered + cancel() + }() + tree := NewUsageTree() + start := time.Now() + _ = scanUsage(ctx, f, nil, tree) + if time.Since(start) > 5*time.Second { + t.Fatalf("stopped after %v", time.Since(start)) + } + if c := tree.Count(); c.Bytes != 5 || c.Files != 1 || c.Unread != 0 { + t.Fatalf("count %+v: want what was found before the stop, with nothing marked unread", c) + } +} + +func TestDiskRoot(t *testing.T) { + mac := []string{"/", darwinData, "/System/Volumes/VM", "/dev", "/Volumes/Backup", "/Users/me/mnt/gdrive"} + linux := []string{"/", "/home", "/proc", "/home/me/fuse"} + for _, c := range []struct { + goos, full, root string + skip []string + }{ + {"darwin", "/Users/me/Documents", "/", []string{"System/Volumes/Data", "System/Volumes/VM", "dev", "Volumes/Backup", "Users/me/mnt/gdrive"}}, + {"darwin", darwinData + "/Users/me", "/", []string{"System/Volumes/Data", "System/Volumes/VM", "dev", "Volumes/Backup", "Users/me/mnt/gdrive"}}, + {"darwin", "/Volumes/Backup/photos", "/Volumes/Backup", nil}, + {"darwin", "/Volumes/BackupOld", "/", []string{"System/Volumes/Data", "System/Volumes/VM", "dev", "Volumes/Backup", "Users/me/mnt/gdrive"}}, + {"linux", "/home/me", "/home", []string{"me/fuse"}}, + {"linux", "/etc", "/", []string{"home", "proc", "home/me/fuse"}}, + {"linux", "/opt", "/", []string{"home", "proc", "home/me/fuse"}}, + } { + points := linux + if c.goos == "darwin" { + points = mac + } + root, skip := diskRoot(c.goos, c.full, points) + if root != c.root || !slices.Equal(slices.Sorted(maps.Keys(skip)), slices.Sorted(slices.Values(c.skip))) { + t.Errorf("%s %s: root %s, skip %v, want %s, %v", c.goos, c.full, root, slices.Sorted(maps.Keys(skip)), c.root, c.skip) + } + } + if root, _ := diskRoot("linux", "/anything", nil); root != "/" { + t.Errorf("without a mount table: %s", root) + } +} + +func TestUsageRootOf(t *testing.T) { + for _, c := range []struct{ path, root string }{ + {"mem:a/b", "mem:"}, + {"mem,x=1:a", "mem,x=1:"}, + {"sftp:/var/log", "sftp:/"}, + {"sftp:docs", "sftp:"}, + } { + at, err := usageRootOf(c.path, nil) + if err != nil { + t.Fatal(err) + } + if got := at.Entry(""); got != c.root || at.Local || len(at.Skip) != 0 { + t.Errorf("%s: root %s (local %v), want %s", c.path, got, at.Local, c.root) + } + } + if runtime.GOOS == "windows" { + return + } + dir := MakeTree(t, map[string]string{"x/": ""}) + parent := path.Dir(dir) + at, err := usageRootOf(path.Join(dir, "x"), func() ([]string, error) { return []string{"/", parent, dir + "/x/mnt"}, nil }) + if err != nil { + t.Fatal(err) + } + if !at.Local || at.Entry("") != parent+"/" || !at.Skip[path.Base(dir)+"/x/mnt"] { + t.Fatalf("root %s, local %v, skip %v", at.Entry(""), at.Local, at.Skip) + } + if at.Entry("a/b") != parent+"/a/b" { + t.Fatalf("an entry's path: %s", at.Entry("a/b")) + } + if _, err := usageRootOf("relative/path", nil); err == nil { + t.Fatal("a relative path was accepted") + } +} + +// TestWalkQueueTakesTurns checks that the walk takes one folder from each top folder in turn, and +// reads the folders below each one in the order they were found. +func TestWalkQueueTakesTurns(t *testing.T) { + q := newWalkQueue() + if q.pop() != "" || q.len() != 0 { + t.Fatal("the walk starts at the root") + } + for _, dir := range []string{"a", "b", "c"} { + q.push(dir) + } + var got []string + pop := func() { + dir := q.pop() + got = append(got, dir) + // Each top folder holds two folders, and a/1 one more. + switch dir { + case "a", "b", "c": + q.push(dir + "/1") + q.push(dir + "/2") + case "a/1": + q.push("a/1/x") + } + } + for q.len() > 0 { + pop() + } + want := []string{"a", "b", "c", "a/1", "b/1", "c/1", "a/2", "b/2", "c/2", "a/1/x"} + if !slices.Equal(got, want) { + t.Fatalf("order %q, want %q", got, want) + } +} diff --git a/core/bus/bus.go b/core/bus/bus.go new file mode 100644 index 00000000..622681cc --- /dev/null +++ b/core/bus/bus.go @@ -0,0 +1,80 @@ +// Package bus is the core's in-process event bus. Services publish what changed, and the shell +// passes each event on to the windows so the pages know what to refetch. Events are not stored. +// A subscriber that falls behind is told to read again what it shows (Resync). +package bus + +import "sync" + +type Event struct { + Name string + Data any +} + +// buffer is how many events a subscriber can fall behind before it is dropped. +const buffer = 256 + +// Bus sends each event to all of its subscribers. Publish never blocks. A subscriber that cannot +// keep up is closed instead, and Core.Subscribe then subscribes again and sends Resync. +type Bus struct { + mu sync.Mutex + subs map[*Sub]struct{} + // heard is closed by the first call to Subscribe. + heard chan struct{} + heardOnce sync.Once +} + +func New() *Bus { + return &Bus{subs: map[*Sub]struct{}{}, heard: make(chan struct{})} +} + +// Heard returns a channel that is closed once anything has subscribed. An event published before +// then reaches nobody. So anything the core finds while it starts, before the UI subscribes, must +// wait for this channel if the user needs to see it. +func (b *Bus) Heard() <-chan struct{} { return b.heard } + +// Sub is one subscriber. C is closed when the subscriber is closed, either by Close or because it +// fell behind. +type Sub struct { + C <-chan Event + c chan Event + bus *Bus +} + +// Subscribe adds a subscriber. The app has one user, so every subscriber gets every event. +func (b *Bus) Subscribe() *Sub { + c := make(chan Event, buffer) + s := &Sub{C: c, c: c, bus: b} + b.mu.Lock() + b.subs[s] = struct{}{} + b.mu.Unlock() + b.heardOnce.Do(func() { close(b.heard) }) + return s +} + +// Close removes the subscriber and closes C. Closing twice is harmless. +func (s *Sub) Close() { + s.bus.mu.Lock() + defer s.bus.mu.Unlock() + s.bus.drop(s) +} + +// drop removes s and closes its channel. The caller must hold b.mu. +func (b *Bus) drop(s *Sub) { + if _, ok := b.subs[s]; ok { + delete(b.subs, s) + close(s.c) + } +} + +func (b *Bus) Publish(name string, data any) { + ev := Event{Name: name, Data: data} + b.mu.Lock() + defer b.mu.Unlock() + for s := range b.subs { + select { + case s.c <- ev: + default: + b.drop(s) + } + } +} diff --git a/core/bus/bus_test.go b/core/bus/bus_test.go new file mode 100644 index 00000000..213862f2 --- /dev/null +++ b/core/bus/bus_test.go @@ -0,0 +1,182 @@ +package bus + +import ( + "encoding/json" + "slices" + "sync" + "sync/atomic" + "testing" + "time" +) + +// drain reads the events buffered for s without waiting, and reports whether C is closed. +func drain(s *Sub) (events []Event, closed bool) { + for { + select { + case ev, ok := <-s.C: + if !ok { + return events, true + } + events = append(events, ev) + default: + return events, false + } + } +} + +func names(events []Event) []string { + out := []string{} + for _, ev := range events { + out = append(out, ev.Name) + } + return out +} + +func TestFanOut(t *testing.T) { + b := New() + one, two := b.Subscribe(), b.Subscribe() + + b.Publish(TransfersChanged, TransfersChangedData{ID: "t1"}) + b.Publish(NotifyOS, NotifyOSData{EventID: "job.completed", Title: "Copy finished"}) + + for _, s := range []*Sub{one, two} { + events, closed := drain(s) + if got := names(events); closed || !slices.Equal(got, []string{TransfersChanged, NotifyOS}) { + t.Errorf("got %v (closed %v)", got, closed) + } + } + events, _ := drain(b.Subscribe()) + if len(events) != 0 { + t.Errorf("a new subscriber got %v: there is no replay", names(events)) + } + b.Publish(TransfersChanged, TransfersChangedData{ID: "t2"}) + if got, _ := drain(one); len(got) != 1 || got[0].Data.(TransfersChangedData).ID != "t2" { + t.Errorf("event = %+v", got) + } +} + +// Heard is closed by the first subscription, and stays closed. +func TestHeard(t *testing.T) { + b := New() + select { + case <-b.Heard(): + t.Fatal("heard before anything subscribed") + default: + } + b.Subscribe().Close() + b.Subscribe().Close() // a second subscription doesn't close it again + select { + case <-b.Heard(): + default: + t.Fatal("not heard after a subscription") + } +} + +func TestClose(t *testing.T) { + b := New() + s, other := b.Subscribe(), b.Subscribe() + s.Close() + s.Close() // closing again is harmless + if _, closed := drain(s); !closed { + t.Error("Close did not close C") + } + b.Publish(TemplatesChanged, nil) + if events, closed := drain(other); closed || len(events) != 1 { + t.Errorf("another subscriber: %v, closed %v", names(events), closed) + } + other.Close() + b.Publish(TemplatesChanged, nil) // nobody left +} + +func TestASlowSubscriberIsClosedNotWaitedFor(t *testing.T) { + b := New() + slow := b.Subscribe() + fast := b.Subscribe() + var got atomic.Int64 + done := make(chan struct{}) + go func() { + defer close(done) + for range fast.C { + got.Add(1) + } + }() + + // The fast reader gets time to catch up before the last ten events. Otherwise, under load, + // it could fall a whole buffer behind and be closed too, which would be correct behavior but + // would fail the test. + published := make(chan struct{}) + go func() { + for range buffer { + b.Publish(TransfersChanged, nil) + } + for deadline := time.Now().Add(5 * time.Second); got.Load() < buffer && time.Now().Before(deadline); { + time.Sleep(time.Millisecond) + } + for i := buffer; i < buffer+10; i++ { + b.Publish(TransfersChanged, nil) + } + close(published) + }() + select { + case <-published: + case <-time.After(5 * time.Second): + t.Fatal("Publish blocked on a subscriber that does not read") + } + + events, closed := drain(slow) + if !closed || len(events) != buffer { + t.Errorf("slow subscriber: %d events, closed %v; want %d and closed", len(events), closed, buffer) + } + fast.Close() + <-done + if n := got.Load(); n != buffer+10 { + t.Errorf("fast subscriber got %d events, want %d", n, buffer+10) + } +} + +func TestConcurrentUse(t *testing.T) { + b := New() + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + for range 200 { + b.Publish(RemotesChanged, nil) + } + }) + wg.Go(func() { + for range 50 { + s := b.Subscribe() + drain(s) + s.Close() + } + }) + } + wg.Wait() +} + +func TestPayloadShapes(t *testing.T) { + for _, c := range []struct { + data any + want string + }{ + {TransfersChangedData{ID: "1", State: "running", Operation: "delete", Sources: []string{"a:"}}, + `{"id":"1","state":"running","operation":"delete","sources":["a:"]}`}, + {TransfersProgressData{Items: map[string]TransferProgress{"1": {Seq: 3, State: "running"}}}, + `{"items":{"1":{"seq":3,"state":"running","bytes":0,"totalBytes":0,"speed":0,"eta":null,"pct":0,"files":0,"totalFiles":0,"errors":0,"checks":0,"listed":0,"transferring":null,"checking":null,"transferred":null}}}`}, + {RemotesChangedData{Names: []string{"a", "b"}}, `{"names":["a","b"]}`}, + {RemotesChangedData{}, `{}`}, + {RemotesHealthData{ID: "s3", State: "faulty", Error: "x"}, `{"id":"s3","state":"faulty","error":"x"}`}, + {RemotesHealthData{ID: "s3", State: "ok"}, `{"id":"s3","state":"ok"}`}, + {MountsChangedData{ID: "m", State: "starting", MountPoint: "/mnt"}, `{"id":"m","state":"starting","mountPoint":"/mnt"}`}, + {ServesChangedData{ID: "s", State: "failed", Error: "bind"}, `{"id":"s","state":"failed","error":"bind"}`}, + {PrefsChangedData{Names: []string{"theme"}}, `{"names":["theme"]}`}, + {NotifyOSData{EventID: "job.failed", Title: "t", Body: "b"}, `{"eventId":"job.failed","title":"t","body":"b"}`}, + {NotifyOSData{EventID: "job.failed", Title: "t", Body: "b", Route: "/transfers?id=1", ToastOnly: true}, + `{"eventId":"job.failed","title":"t","body":"b","route":"/transfers?id=1","toastOnly":true}`}, + } { + got, err := json.Marshal(c.data) + if err != nil || string(got) != c.want { + t.Errorf("%T = %s, %v; want %s", c.data, got, err, c.want) + } + } +} diff --git a/core/bus/bustest/bustest.go b/core/bus/bustest/bustest.go new file mode 100644 index 00000000..fb0d014d --- /dev/null +++ b/core/bus/bustest/bustest.go @@ -0,0 +1,106 @@ +// Package bustest records a bus's events for tests. +package bustest + +import ( + "slices" + "sync" + "testing" + "time" + + "github.com/rclone/rclone-ui/core/bus" +) + +// waitLimit is how long Wait waits before it fails the test. It only bounds a test that is +// broken, so it is long. +const waitLimit = 30 * time.Second + +// Recorder holds the events of one bus. It has no goroutine: it reads the subscription when it is +// asked. Publish queues an event for every subscriber before it returns, so a read never misses +// an event that was published before it. +type Recorder struct { + t testing.TB + sub *bus.Sub + mu sync.Mutex + events []bus.Event + closed bool +} + +// Record subscribes to b until the test ends. +func Record(t testing.TB, b *bus.Bus) *Recorder { + r := &Recorder{t: t, sub: b.Subscribe()} + t.Cleanup(func() { + r.mu.Lock() + r.closed = true + r.mu.Unlock() + r.sub.Close() + }) + return r +} + +// take moves the queued events into r.events. The caller holds r.mu. +func (r *Recorder) take() { + for { + select { + case ev, ok := <-r.sub.C: + if !ok { + // The bus drops a subscriber whose queue is full. + if !r.closed { + r.closed = true + r.t.Error("bustest: the bus dropped the recorder, because too many events were published between two reads") + } + return + } + r.events = append(r.events, ev) + default: + return + } + } +} + +// Events returns every event published so far, in order. +func (r *Recorder) Events() []bus.Event { + r.mu.Lock() + defer r.mu.Unlock() + r.take() + return slices.Clone(r.events) +} + +// Named returns the events published so far that have the given name. +func (r *Recorder) Named(name string) []bus.Event { + var out []bus.Event + for _, ev := range r.Events() { + if ev.Name == name { + out = append(out, ev) + } + } + return out +} + +// Wait returns the first event, past or future, for which match returns true. It is for an event +// that another goroutine publishes. It fails the test if none arrives. +func (r *Recorder) Wait(what string, match func(bus.Event) bool) bus.Event { + r.t.Helper() + r.mu.Lock() + defer r.mu.Unlock() + r.take() + for _, ev := range r.events { + if match(ev) { + return ev + } + } + limit := time.After(waitLimit) + for { + select { + case ev, ok := <-r.sub.C: + if !ok { + r.t.Fatalf("bustest: the subscription closed while waiting for %s", what) + } + r.events = append(r.events, ev) + if match(ev) { + return ev + } + case <-limit: + r.t.Fatalf("bustest: %s was never published", what) + } + } +} diff --git a/core/bus/events.go b/core/bus/events.go new file mode 100644 index 00000000..97c3e144 --- /dev/null +++ b/core/bus/events.go @@ -0,0 +1,173 @@ +package bus + +// The event names. Each event carries its payload struct, or no data (nil) when it only tells the +// pages what to refetch. The pages get the payload unchanged, as a Wails event with the same +// name. The shell registers each name with its type in app/events.go, so add new events there. +const ( + // Resync tells a subscriber that it fell behind and missed events, so it should read again + // what it shows. Core.Subscribe sends it. It is never published. + Resync = "core.resync" + + TransfersChanged = "transfers.changed" + TransfersProgress = "transfers.progress" + RemotesChanged = "remotes.changed" + RemotesHealth = "remotes.health" + RemotesSession = "remotes.session" + MountsChanged = "mounts.changed" + ServesChanged = "serves.changed" + TemplatesChanged = "templates.changed" + FavoritesChanged = "favorites.changed" + NotificationsChanged = "notifications.changed" + SettingsChanged = "settings.changed" + PrefsChanged = "prefs.changed" + // ConfigChanged means that the config file's state (such as needing a password, or being + // unreadable) or its settings changed. + ConfigChanged = "config.changed" + TunnelChanged = "tunnel.changed" + // WatchersChanged means that a watcher was added, changed or removed, or that one of its + // runs started or ended. + WatchersChanged = "watchers.changed" + // AutomountsChanged means that an automount was added, changed or removed. + AutomountsChanged = "automounts.changed" + // SchedulesChanged means that a schedule was added, changed or removed, or that one of its + // runs started or ended. + SchedulesChanged = "schedules.changed" + // FilesChanged names entries that were changed in place (FilesChangedData). The panels that + // show their folders list them again. + FilesChanged = "files.changed" + // NotifyOS asks the UI to show an OS notification (NotifyOSData). The core's notification + // service decides what to notify (notifications.Service.Desktop), and the UI handles the OS + // side. + NotifyOS = "notify.os" +) + +type PrefsChangedData struct { + Names []string `json:"names"` +} + +// FilesChangedData lists the entries that a file action changed, as full rclone paths. Dirs lists +// the ones that are folders, whose contents changed too. +type FilesChangedData struct { + Names []string `json:"names"` + Dirs []string `json:"dirs,omitempty"` +} + +// TransfersChangedData reports that a transfer was created, ended or stopped. +type TransfersChangedData struct { + ID string `json:"id"` + State string `json:"state"` + Operation string `json:"operation"` + Sources []string `json:"sources"` + Destination string `json:"destination,omitempty"` +} + +// TransfersProgressData holds the progress of every running transfer, by transfer id. It is sent +// every second while any transfer runs. +type TransfersProgressData struct { + Items map[string]TransferProgress `json:"items"` +} + +type TransferProgress struct { + Seq int64 `json:"seq"` + State string `json:"state"` + Bytes int64 `json:"bytes"` + TotalBytes int64 `json:"totalBytes"` + Speed float64 `json:"speed"` + Eta *int64 `json:"eta"` // seconds; null when unknown + Pct int `json:"pct"` + Files int64 `json:"files"` + TotalFiles int64 `json:"totalFiles"` + Errors int64 `json:"errors"` + Checks int64 `json:"checks"` + Listed int64 `json:"listed"` + Transferring []TransferringFile `json:"transferring"` + Checking []CheckingFile `json:"checking"` + Transferred []TransferredFile `json:"transferred"` // the last 50 + // Watcher is set for a watcher's run, which the tray's count leaves out. + Watcher bool `json:"watcher,omitempty"` +} + +type TransferringFile struct { + Name string `json:"name"` + Size int64 `json:"size"` + Bytes int64 `json:"bytes"` + Pct int `json:"pct"` + Speed float64 `json:"speed"` +} + +type CheckingFile struct { + Name string `json:"name"` +} + +// TransferredFile is a file that was transferred, or that failed. +type TransferredFile struct { + Name string `json:"name"` + Size int64 `json:"size"` + Bytes int64 `json:"bytes"` + Error string `json:"error,omitempty"` +} + +// RemotesChangedData lists the remotes that changed, when the publisher knows them. A remote +// counts as changed when it was added, removed or edited, or when it wraps a remote that changed. +// An empty list means "refetch every remote". +type RemotesChangedData struct { + Names []string `json:"names,omitempty"` +} + +// RemotesHealthData reports that a health check of the remote ID finished. State is ok, faulty +// (with rclone's error message), or unknown (when the check got no answer). The quota and the +// advice to reconnect are in the remotes' Health, which the pages refetch after this event. +type RemotesHealthData struct { + ID string `json:"id"` + State string `json:"state"` + Error string `json:"error,omitempty"` +} + +type RemotesSessionData struct { + ID string `json:"id"` + State string `json:"state"` +} + +// MountsChangedData reports that a mount started, became ready, failed, stopped, crashed or +// restarted. An event without an ID only means that the list of stopped mounts changed (one was +// mounted again, or discarded), or that WinFsp was installed (mounts.InstallWinFsp), which +// changes mounts.Support. CannotMount comes with a failed mount when this computer can't mount. +// Error is why the mount went down, in the app's language. +type MountsChangedData struct { + ID string `json:"id"` + State string `json:"state"` + MountPoint string `json:"mountPoint,omitempty"` + Error string `json:"error,omitempty"` + CannotMount bool `json:"cannotMount,omitempty"` +} + +// ServesChangedData reports that a serve started, became ready, failed, stopped, crashed or +// restarted. Error is why the serve went down, in the app's language. +type ServesChangedData struct { + ID string `json:"id"` + State string `json:"state"` + Addr string `json:"addr,omitempty"` + Error string `json:"error,omitempty"` +} + +// TunnelChangedData reports that the remote tunnel turned on or off, or is starting (or starting +// again). Error explains why a start failed or why the tunnel went down, in the app's language. +// The credentials are only ever in the tunnel's Status. +type TunnelChangedData struct { + State string `json:"state"` + Error string `json:"error,omitempty"` +} + +// NotifyOSData is the OS notification that NotifyOS asks for. EventID is the id from the +// notification catalog ("job.completed", "mount.failed", …), so the UI can group it or act on it. +// Route is the window that a click on it opens ("/history?id=…"). An empty Route opens nothing. +// ToastOnly means the notification is shown as a toast or not at all. Where the OS can't show +// a toast, the UI drops it rather than show a dialog. This is used for a transfer's end, which +// the Transfers page and the tray also show. +type NotifyOSData struct { + EventID string `json:"eventId"` + Title string `json:"title"` + Body string `json:"body"` + Route string `json:"route,omitempty"` + ToastOnly bool `json:"toastOnly,omitempty"` +} diff --git a/core/busy_test.go b/core/busy_test.go new file mode 100644 index 00000000..9036406a --- /dev/null +++ b/core/busy_test.go @@ -0,0 +1,58 @@ +package core + +import ( + "testing" + + "github.com/rclone/rclone-ui/core/transfers" +) + +// A running transfer from the pages starts again after an update. A schedule's run runs again at +// the next start, whatever stops it. A retry of a scheduled run is the user's, and keeps neither. +func TestBusyDetail(t *testing.T) { + page := transfers.Origin{Kind: transfers.OriginPage} + schedule := transfers.Origin{Kind: transfers.OriginSchedule, ID: "s1", Name: "Nightly"} + for _, c := range []struct { + tr transfers.Transfer + want string + }{ + {transfers.Transfer{State: transfers.StateRunning, Operation: "copy", Origin: page}, "Starts again after an update."}, + {transfers.Transfer{State: transfers.StateRunning, Operation: "copy", Origin: schedule}, + "Runs again when Rclone UI starts."}, + {transfers.Transfer{State: transfers.StateRunning, Operation: "bisync", Origin: schedule}, + "Runs again when Rclone UI starts."}, + {transfers.Transfer{State: transfers.StateRunning, Operation: "copy", Origin: schedule, RetryOf: "t1"}, ""}, + {transfers.Transfer{State: transfers.StateRunning, Operation: "bisync", Origin: page}, ""}, + {transfers.Transfer{State: transfers.StateRunning, Operation: "bisync", + Origin: transfers.Origin{Kind: transfers.OriginWatcher, ID: "w1"}}, ""}, + } { + if got := busyDetail(c.tr); got != c.want { + t.Errorf("%+v: %q, want %q", c.tr, got, c.want) + } + } +} + +// Phrase names what runs in one line, the same for a question and its answer. Done says what a +// stop stopped, or that nothing was running. +func TestRunningPhrase(t *testing.T) { + for _, c := range []struct { + r Running + want string + }{ + {Running{}, ""}, + {Running{Mounts: 1}, "a mount"}, + {Running{Tunnel: true}, "the remote tunnel"}, + {Running{Transfers: 2, Serves: 1}, "2 transfers and a serve"}, + {Running{Transfers: 2, Serves: 1, Mounts: 3}, "2 transfers, a serve and 3 mounts"}, + {Running{Transfers: 1, Mounts: 2, Tunnel: true}, "a transfer, 2 mounts and the remote tunnel"}, + } { + if got := c.r.Phrase().String(); got != c.want { + t.Errorf("%+v: %q, want %q", c.r, got, c.want) + } + } + if got := (StopSummary{Running{Transfers: 2, Serves: 1, Mounts: 3}}).Done().String(); got != "Stopped 2 transfers, a serve and 3 mounts." { + t.Errorf("done: %q", got) + } + if got := (StopSummary{}).Done().String(); got != "Nothing was running." { + t.Errorf("done with nothing: %q", got) + } +} diff --git a/core/catalog/api.go b/core/catalog/api.go new file mode 100644 index 00000000..fb8cb35a --- /dev/null +++ b/core/catalog/api.go @@ -0,0 +1,68 @@ +package catalog + +import ( + "context" + + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/internal/late" +) + +// API serves rclone's option catalog to the forms. rclone registers its backends and option +// blocks as the process starts, so every method but Values answers at once, before the core has +// started. Values reads the values that rclone's init sets, so it waits for the core. +type API struct { + s *Service + // ready is set once the core has started, and fails when it can't. + ready *late.Value[struct{}] +} + +func NewAPI(s *Service, ready *late.Value[struct{}]) *API { return &API{s: s, ready: ready} } + +// Get returns the catalog with rclone's text in the app's language. The backends come without +// their options. +func (a *API) Get(context.Context) (Catalog, error) { + return *a.s.SummaryIn(i18n.Language()), nil +} + +// English returns the catalog as Get does, but always with rclone's English text. The agents' +// server uses it, because a model reads the text there, not the user. +func (a *API) English(context.Context) (Catalog, error) { return *a.s.Summary(), nil } + +// Values returns the values of the global options. +func (a *API) Values(ctx context.Context) (Values, error) { + return late.CallValue(ctx, a.ready, func(struct{}) (*Values, error) { return a.s.Values(ctx), nil }) +} + +// Backend returns one backend's options for a provider, with rclone's text in the app's +// language. +func (a *API) Backend(_ context.Context, typ, provider string) (BackendOptions, error) { + return value(a.s.BackendIn(typ, provider, i18n.Language())) +} + +// ParseCommand reads a pasted command line into option groups. The reasons for the flags that it +// skips are in the app's language. +func (a *API) ParseCommand(_ context.Context, command string) (ParsedCommand, error) { + out, err := value(a.s.ParseCommand(command)) + if err == nil { + out.Skipped = LocalSkipped(out.Skipped) + } + return out, err +} + +// value returns what p points to, or T's zero value when p is nil, as late.CallValue does. +func value[T any](p *T, err error) (T, error) { + if p == nil { + var zero T + return zero, err + } + return *p, err +} + +// SortOptions sorts a template's flat options into the catalog's groups, for the template +// drawer's sections. serve is a serve's type, or "" for every type. The options that no group +// takes come back as skipped, with the reason in the app's language. +func (*API) SortOptions(_ context.Context, options Group, serve string) (Sorted, error) { + out := SortOptions(options, serve) + out.Skipped = LocalSkipped(out.Skipped) + return out, nil +} diff --git a/core/catalog/catalog.go b/core/catalog/catalog.go new file mode 100644 index 00000000..60d0081f --- /dev/null +++ b/core/catalog/catalog.go @@ -0,0 +1,485 @@ +// Package catalog provides rclone's reference data for the pages: the backends and their +// options, the global option blocks, and the option groups that the pages offer. Each option +// carries its kind, so that no page has to work out from a Go type name what a value is. +package catalog + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "maps" + "reflect" + "slices" + "sort" + "strings" + "sync" + "time" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config/configstruct" + "github.com/rclone/rclone/lib/encoder" + "github.com/rclone/rclone/vfs/vfscommon" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/rclone" + "github.com/rclone/rclone-ui/core/version" +) + +// Service builds the catalog once, because rclone's registry doesn't change while the process +// runs. +type Service struct { + once sync.Once + cat *Catalog + summary *Catalog + // exe is the running executable, which a pasted Copy command puts in front of the app's own + // metadata mapper. ParseCommand removes it. + exe string +} + +func New(exe string) *Service { return &Service{exe: exe} } + +func (s *Service) load() { + s.once.Do(func() { + s.cat = build() + s.summary = summarize(s.cat) + }) +} + +// Catalog returns the whole catalog, with every backend and its options. Callers must not +// change it. +func (s *Service) Catalog() *Catalog { + s.load() + return s.cat +} + +// Summary returns the catalog that API.Get sends, with the backends but without their options. +// The options make up four fifths of the catalog's size, and the pages request them through +// Backend, one backend and provider at a time. Callers must not change it. +func (s *Service) Summary() *Catalog { + s.load() + return s.summary +} + +// summarize returns a copy of cat without the backends' options. +func summarize(cat *Catalog) *Catalog { + out := *cat + out.Backends = make([]Backend, len(cat.Backends)) + for i, b := range cat.Backends { + b.Options = nil + out.Backends[i] = b + } + return &out +} + +// Values returns the global options that differ from rclone's defaults, without secrets. They +// are grouped by block and keyed by rclone's option name. Each value is written as rclone writes +// it, in the same form as default_text ("5m0s", not 300000000000). List options also come as +// their separate elements. +func (s *Service) Values(ctx context.Context) *Values { + out := &Values{Blocks: map[string]*BlockValues{}} + for block, text := range rclone.OptionValues(ctx) { + out.Blocks[block] = &BlockValues{Text: text, Lists: lists(block, text)} + } + return out +} + +// lists returns the elements of the list options among a block's values, where text maps option +// names to their text. The elements are read from rclone's value itself (a []string, +// fs.CommaSepList or fs.SpaceSepList), because a list's text is a CSV record or an argv, and only +// rclone's parser splits it exactly. +func lists(block string, text map[string]string) map[string]*List { + oi, ok := fs.OptionsRegistry[block] + if !ok || oi.Opt == nil { + return nil + } + items, err := configstruct.Items(oi.Opt) + if err != nil { + return nil + } + var out map[string]*List + for _, it := range items { + if _, ok := text[it.Name]; !ok { + continue + } + v := reflect.ValueOf(it.Value) + if !v.IsValid() || !rclone.IsListType(v.Type()) { + continue + } + if out == nil { + out = map[string]*List{} + } + out[it.Name] = &List{Values: slices.Clone(v.Convert(reflect.TypeFor[[]string]()).Interface().([]string))} + } + return out +} + +func build() *Catalog { + out := &Catalog{} + for _, ri := range fs.Registry { + out.Backends = append(out.Backends, backendOf(ri, ri.Options, nil)) + } + sort.Slice(out.Backends, func(i, j int) bool { return out.Backends[i].Name < out.Backends[j].Name }) + + blocks := blockOptions() + for _, name := range slices.Sorted(maps.Keys(blocks)) { + out.Blocks = append(out.Blocks, Block{Name: name, Options: blocks[name]}) + } + out.Groups = sections() + out.Defaults = Defaults() + + // The version identifies the content. It is rclone's version plus a hash, which covers a + // build that changed an option without a new version number, such as a development build. + raw, _ := json.Marshal(out) // plain fields and sorted maps, so it can't fail and is stable + sum := sha256.Sum256(raw) + out.Version = version.Rclone() + "-" + hex.EncodeToString(sum[:6]) + return out +} + +// backendOf describes one of rclone's backends with the given options, which are either all of +// its own or those that apply to one provider. Its text is in t's language, or in English when t +// is nil. +func backendOf(ri *fs.RegInfo, options []fs.Option, t *texts) Backend { + prefix := backendPrefix(ri.Name) + b := Backend{ + Name: ri.Name, + Description: t.text(key(prefix, "description"), ri.Description), + Prefix: ri.Prefix, + Aliases: slices.Clone(ri.Aliases), + // fs.Register itself hides an alias, such as tardigrade for storj. + Hidden: ri.Hide, + MetadataInfo: t.metadataInfo(ri.Name, ri.MetadataInfo), + } + for i := range options { + local := t.option(prefix, options[i]) + o := convert(&local) + o.PerOperation = true + o.Path = backendPath(ri.Name, o.Name) + b.Options = append(b.Options, *o) + } + return b +} + +// Backend returns the backend typ (a remote's type, looked up with fs.Find) with the options that +// rclone's config asks for when the remote has the given provider (configAll in +// fs/backend_config.go). An option or an example is kept when its provider filter matches the +// provider (fs.MatchProvider). An empty provider means the provider option's default. When that +// is empty too, no provider is chosen yet: the result has only the options that apply to every +// provider, with all their examples. The text is rclone's English (BackendIn gives it in another +// language). +func (s *Service) Backend(typ, provider string) (*BackendOptions, error) { + return s.backend(typ, provider, nil) +} + +// backend is Backend, with its text in t's language, or in English when t is nil. +func (s *Service) backend(typ, provider string, t *texts) (*BackendOptions, error) { + ri, err := fs.Find(typ) + if err != nil { + return nil, errs.NotFound("backend", "Rclone has no such backend: %s", typ) + } + providerOption := ri.Options.Get(fs.ConfigProvider) + if provider == "" && providerOption != nil { + provider = defaultText(providerOption) + } + var options []fs.Option + for _, o := range ri.Options { + if provider == "" && providerOption != nil && o.Provider != "" { + continue // asked only once a provider is chosen + } + if !fs.MatchProvider(o.Provider, provider) { + continue + } + if provider != "" && len(o.Examples) > 0 { + examples := fs.OptionExamples{} + for _, ex := range o.Examples { + if fs.MatchProvider(ex.Provider, provider) { + examples = append(examples, ex) + } + } + o.Examples = examples + } + options = append(options, o) + } + return &BackendOptions{Backend: backendOf(ri, options, t), Provider: provider}, nil +} + +// FromOption describes one of rclone's options the way the catalog does, with its kind, its +// default as text, and its choices. It is also used for a config session's question (the Option +// in fs.ConfigOut). +func FromOption(o *fs.Option) *Option { return convert(o) } + +func convert(o *fs.Option) *Option { + out := &Option{ + Name: o.Name, + Help: o.Help, + Groups: o.Groups, + Type: o.Type(), + DefaultText: defaultText(o), + Required: o.Required, + Advanced: o.Advanced, + Password: o.IsPassword, + Sensitive: o.Sensitive, + Hidden: o.Hide != 0, + Exclusive: o.Exclusive, + } + if b, err := json.Marshal(o.Default); err == nil { + out.Default = b + } + out.Kind, out.Choices, out.Separator = kindOf(o.GetValue()) + + // rclone's examples add help to the values of a closed set, and act as suggestions for any + // other option. + if len(o.Examples) > 0 { + if out.Kind == KindChoice || out.Kind == KindFlags { + for i := range out.Choices { + c := &out.Choices[i] + for _, ex := range o.Examples { + if strings.EqualFold(ex.Value, c.Value) && c.Help == "" { + c.Help = ex.Help + } + } + } + } else { + var ex []Choice + for _, e := range o.Examples { + ex = append(ex, Choice{Value: e.Value, Help: e.Help}) + } + out.Choices = append(ex, out.Choices...) + } + } + if out.Kind != KindChoice && out.Kind != KindFlags { + for _, v := range namePresets[o.Name] { + out.Choices = append(out.Choices, Choice{Value: v}) + } + out.Choices = unique(out.Choices) + } + if out.Kind == KindText && len(out.Choices) == 0 { + out.Exclusive = false + } + return out +} + +// defaultText returns the default in the form that rclone reads from a flag or a config file and +// writes back, using fs.Option.String, so a size keeps its unit and a list keeps its quoting. Any +// value set by a flag is ignored. +func defaultText(o *fs.Option) string { + c := o.Copy() + c.Value = nil + return c.String() +} + +type enumChoices interface{ Choices() []string } + +type bitsChoices interface { + Choices() []fs.BitsChoicesInfo +} + +var ( + sizePresets = []string{"0", "8M", "16M", "32M", "64M", "128M", "256M", "512M", "1G"} + durationPresets = []string{"0s", "5s", "30s", "1m", "5m", "30m", "1h", "6h", "24h"} + tristateChoices = []string{"unset", "true", "false"} +) + +// namePresets lists common values for options whose type doesn't suggest any, keyed by name. +var namePresets = map[string][]string{ + "order_by": { + "name,ascending", "name,descending", + "size,ascending", "size,descending", + "modtime,ascending", "modtime,descending", + }, +} + +// kindOf returns the kind of v's type, its choices, and a list's separator. The choices are +// either the only values allowed (a closed set) or common ones. +func kindOf(v any) (Kind, []Choice, string) { + switch x := v.(type) { + case bool: + return KindBool, nil, "" + case fs.Tristate: + return KindTristate, choices(tristateChoices), "" + case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + return KindInt, nil, "" + case float32, float64: + return KindFloat, nil, "" + case fs.SizeSuffix: + return KindSize, choices(sizePresets), "" + case fs.Duration, time.Duration: + return KindDuration, choices(durationPresets), "" + case fs.Time: + return KindTime, nil, "" + case vfscommon.FileMode: + return KindFileMode, nil, "" + case fs.BwTimetable: + return KindBwTimetable, nil, "" + case fs.CommaSepList: + return KindList, nil, "," + case fs.SpaceSepList: + return KindList, nil, " " + case []string: + return KindList, nil, "," + case encoder.MultiEncoder: + return KindFlags, choices(strings.Split(encoder.ValidStrings(), ", ")), "" + case enumChoices: + return KindChoice, choices(x.Choices()), "" + case bitsChoices: + var names []string + for _, c := range x.Choices() { + if c.Name != "" { + names = append(names, c.Name) + } + } + return KindFlags, choices(names), "" + } + return KindText, nil, "" +} + +func choices(values []string) []Choice { + out := make([]Choice, 0, len(values)) + for _, v := range values { + out = append(out, Choice{Value: v}) + } + return out +} + +// unique keeps the first choice for each value. A value that several providers offer, such as +// s3's region us-east-1, becomes one choice with the help text of the first. +func unique(in []Choice) []Choice { + seen := map[string]bool{} + out := in[:0] + for _, c := range in { + if seen[c.Value] { + continue + } + seen[c.Value] = true + out = append(out, c) + } + return out +} + +// backendPaths lists the backend options that name a local file or folder. rclone doesn't mark +// them, so they are listed here by name. +var backendPaths = map[string]Path{ + "service_account_file": PathFile, // drive, google cloud storage + "box_config_file": PathFile, // box + "client_certificate_path": PathFile, // azureblob, azurefiles + "service_principal_file": PathFile, // azureblob, azurefiles + "config_file": PathFile, // oracleobjectstorage + "sse_customer_key_file": PathFile, // oracleobjectstorage + "shared_credentials_file": PathFile, // s3 + "key_file": PathFile, // sftp + "known_hosts_file": PathFile, // sftp + "pubkey_file": PathFile, // sftp + "kerberos_ccache": PathFile, // smb + "unix_socket": PathFile, // webdav + "chunk_path": PathDir, // cache + "db_path": PathDir, // cache + "tmp_upload_path": PathDir, // cache +} + +// wrappedRemotes lists the backend options whose value rclone opens as one path: the remote that +// the backend wraps. rclone Cloud lists the same options among those that open an Fs +// (internal/rclone/names/paths.go). cache's tmp_upload_path opens an Fs too, but it is a local +// folder (backendPaths), so it keeps the folder picker. TestWrappedRemotes checks the list +// against rclone. +var wrappedRemotes = map[string]string{ + "alias": "remote", + "archive": "remote", + "cache": "remote", + "chunker": "remote", + "compress": "remote", + "crypt": "remote", + "hasher": "remote", +} + +func backendPath(backend, option string) Path { + if wrappedRemotes[backend] == option { + return PathRemote + } + return backendPaths[option] +} + +// blockOptions returns the options of each of rclone's option blocks, keyed by the block's name, +// in English. rclone registers its blocks at init and never changes them, so they are read once. +// Callers must not change them. +var blockOptions = sync.OnceValue(func() map[string][]Option { return convertBlocks(nil) }) + +// convertBlocks describes the options of each of rclone's option blocks, keyed by the block's +// name, with their text in t's language, or in English when t is nil. +func convertBlocks(t *texts) map[string][]Option { + blocks := map[string][]Option{} + for name, info := range fs.OptionsRegistry { + prefix := blockPrefix(name) + var opts []Option + for i := range info.Options { + local := t.option(prefix, info.Options[i]) + o := convert(&local) + o.PerOperation = name != "main" || rclone.PerOperation(o.Name) + opts = append(opts, *o) + } + blocks[name] = opts + } + return blocks +} + +// sections returns the sections of options that the pages offer (groups), built once. Callers +// must not change them. +var sections = sync.OnceValue(func() []Section { return groups(blockOptions()) }) + +// groups returns the sections of options that the pages offer. Each section picks options from +// rclone's option blocks by their group tags, sorted by name. +func groups(blocks map[string][]Option) []Section { + in := func(o *Option, g string) bool { return strings.Contains(o.Groups, g) } + pick := func(name string, from []string, keep func(*Option) bool) Section { + type ref struct { + block string + o *Option + } + var refs []ref + for _, b := range from { + for i := range blocks[b] { + if o := &blocks[b][i]; keep(o) { + refs = append(refs, ref{b, o}) + } + } + } + slices.SortStableFunc(refs, func(a, b ref) int { return byName(a.o.Name, b.o.Name) }) + g := Section{Name: name} + for _, r := range refs { + g.Options = append(g.Options, OptionRef{Block: r.block, Name: r.o.Name}) + } + return g + } + notMetadata := func(o *Option) bool { return !in(o, "Metadata") } + out := []Section{ + pick("filter", []string{"filter"}, notMetadata), + pick("config", []string{"main"}, func(o *Option) bool { + return o.PerOperation && + (in(o, "Performance") || in(o, "Listing") || in(o, "Networking") || in(o, "Check") || + o.Name == "use_server_modtime") + }), + pick("mount", []string{"mount"}, notMetadata), + pick("vfs", []string{"vfs"}, notMetadata), + pick("copy", []string{"main"}, func(o *Option) bool { return in(o, "Copy") && !in(o, "Metadata") }), + pick("sync", []string{"main"}, func(o *Option) bool { + return (in(o, "Copy") || in(o, "Sync")) && !in(o, "Metadata") + }), + // Everything tagged Metadata (metadata, metadata_mapper and the metadata filter rules) has + // its own section, and the other groups leave it out. + pick("metadata", []string{"main", "filter"}, func(o *Option) bool { return in(o, "Metadata") }), + } + for _, t := range rclone.ServeTypes() { + // Only include the serve types built for this platform (nfs is Unix only). A serve's + // block is registered only when the serve is built in. + if _, ok := blocks[t]; ok { + out = append(out, pick("serve."+t, []string{t}, func(*Option) bool { return true })) + } + } + return out +} + +// byName orders option names ([a-z0-9_]) as localeCompare does, with the underscore before +// digits and digits before letters. +func byName(a, b string) int { + key := func(s string) string { return strings.ReplaceAll(s, "_", "\x01") } + return strings.Compare(key(a), key(b)) +} diff --git a/core/catalog/catalog_test.go b/core/catalog/catalog_test.go new file mode 100644 index 00000000..28c02f02 --- /dev/null +++ b/core/catalog/catalog_test.go @@ -0,0 +1,548 @@ +package catalog + +import ( + "context" + "encoding/json" + "fmt" + "slices" + "strings" + "testing" + "time" + + _ "github.com/rclone/rclone/backend/all" + _ "github.com/rclone/rclone/cmd/all" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config/configmap" + "github.com/rclone/rclone/fs/config/configstruct" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/rclone" +) + +func backend(t *testing.T, c *Catalog, name string) *Backend { + t.Helper() + for i := range c.Backends { + if c.Backends[i].Name == name { + return &c.Backends[i] + } + } + t.Fatalf("no backend %s", name) + return nil +} + +func option(t *testing.T, opts []Option, name string) *Option { + t.Helper() + for i := range opts { + if opts[i].Name == name { + return &opts[i] + } + } + t.Fatalf("no option %s", name) + return nil +} + +func block(t *testing.T, c *Catalog, name string) []Option { + t.Helper() + for _, b := range c.Blocks { + if b.Name == name { + return b.Options + } + } + t.Fatalf("no block %s", name) + return nil +} + +func group(t *testing.T, c *Catalog, name string) []OptionRef { + t.Helper() + for _, g := range c.Groups { + if g.Name == name { + return g.Options + } + } + t.Fatalf("no group %s", name) + return nil +} + +func values(cs []Choice) []string { + var out []string + for _, c := range cs { + out = append(out, c.Value) + } + return out +} + +func names(refs []OptionRef) []string { + var out []string + for _, r := range refs { + out = append(out, r.Name) + } + return out +} + +func TestKinds(t *testing.T) { + c := New("").Catalog() + drive := backend(t, c, "drive").Options + for _, tc := range []struct { + opts []Option + name string + kind Kind + defaultTxt string + }{ + {drive, "pacer_min_sleep", KindDuration, "100ms"}, + {drive, "chunk_size", KindSize, "8Mi"}, + {drive, "encoding", KindFlags, "InvalidUtf8"}, + {drive, "metadata_labels", KindFlags, "off"}, + {drive, "pacer_burst", KindInt, "100"}, + {drive, "use_trash", KindBool, "true"}, + {backend(t, c, "swift").Options, "use_segments_container", KindTristate, "unset"}, + {backend(t, c, "dropbox").Options, "export_formats", KindList, "html,md"}, + {backend(t, c, "onedrive").Options, "access_scopes", KindList, ""}, + {backend(t, c, "s3").Options, "version_at", KindTime, "off"}, + {backend(t, c, "local").Options, "time_type", KindChoice, "mtime"}, + {backend(t, c, "zoho").Options, "tpslimit", KindFloat, ""}, + {block(t, c, "vfs"), "vfs_cache_mode", KindChoice, "off"}, + {block(t, c, "vfs"), "umask", KindFileMode, ""}, + {block(t, c, "main"), "bwlimit", KindBwTimetable, ""}, + {block(t, c, "main"), "metadata_mapper", KindList, ""}, + {block(t, c, "filter"), "include", KindList, ""}, + {block(t, c, "main"), "cutoff_mode", KindChoice, "HARD"}, + } { + o := option(t, tc.opts, tc.name) + if o.Kind != tc.kind { + t.Errorf("%s: kind %v, want %v (type %s)", tc.name, o.Kind, tc.kind, o.Type) + } + if tc.defaultTxt != "" && o.DefaultText != tc.defaultTxt { + t.Errorf("%s: default %q, want %q", tc.name, o.DefaultText, tc.defaultTxt) + } + } + + // Every backend option has a kind, so a form shows more than bools and strings. + for _, b := range c.Backends { + for _, o := range b.Options { + if o.Kind == "" { + t.Errorf("%s.%s: no kind", b.Name, o.Name) + } + if o.Kind == KindText && o.Type != "string" { + t.Errorf("%s.%s: type %s shown as text", b.Name, o.Name, o.Type) + } + } + } + + if got := values(option(t, block(t, c, "vfs"), "vfs_cache_mode").Choices); !slices.Equal(got, []string{"off", "minimal", "writes", "full"}) { + t.Errorf("cache modes %v", got) + } + enc := option(t, drive, "encoding") + if !slices.Contains(values(enc.Choices), "Slash") || !slices.Contains(values(enc.Choices), "InvalidUtf8") { + t.Errorf("encodings %v", values(enc.Choices)) + } + if got := values(option(t, backend(t, c, "swift").Options, "use_segments_container").Choices); !slices.Equal(got, []string{"unset", "true", "false"}) { + t.Errorf("tristate %v", got) + } + // Examples first, then the presets. + provider := option(t, backend(t, c, "s3").Options, "provider") + if len(provider.Choices) < 10 || provider.Choices[0].Help == "" { + t.Errorf("s3 provider examples %v", values(provider.Choices)) + } + chunk := option(t, drive, "chunk_size") + if !slices.Contains(values(chunk.Choices), "64M") { + t.Errorf("size presets %v", values(chunk.Choices)) + } + if o := option(t, backend(t, c, "sftp").Options, "key_file"); o.Path != PathFile { + t.Errorf("key_file path %v", o.Path) + } + if o := option(t, backend(t, c, "sftp").Options, "pass"); !o.Password { + t.Error("sftp pass is not a password") + } + // An alias that rclone registers for a renamed backend (tardigrade for storj) isn't offered + // by any form. + if !backend(t, c, "tardigrade").Hidden || backend(t, c, "storj").Hidden { + t.Error("tardigrade offered, or storj not") + } +} + +func TestDefaultText(t *testing.T) { + // The default uses rclone's own text, so a bare size keeps its unit and reads back as the + // same size. + o := &fs.Option{Name: "x", Default: fs.SizeSuffix(100)} + if got := defaultText(o); got != "100B" { + t.Errorf("size %q", got) + } + // A value set by a flag is not the default. + o.Value = fs.SizeSuffix(200) + if got := defaultText(o); got != "100B" { + t.Errorf("with a value %q", got) + } + if got := defaultText(&fs.Option{Name: "l", Default: []string{"a b", "c"}}); got != "a b,c" { + t.Errorf("list %q", got) + } +} + +// The catalog's backends have the choices of every provider, with each value once. us-east-1 +// belongs to AWS and to other providers, and it keeps the first one's help. +func TestChoicesOnce(t *testing.T) { + region := option(t, backend(t, New("").Catalog(), "s3").Options, "region") + seen := map[string]bool{} + for _, ch := range region.Choices { + if seen[ch.Value] { + t.Fatalf("region %s twice", ch.Value) + } + seen[ch.Value] = true + } + if !seen["us-east-1"] || !seen["de"] { + t.Errorf("regions %v", values(region.Choices)) + } +} + +func TestFromOption(t *testing.T) { + // A config session's yes/no question. + out, _ := fs.ConfigConfirm("state", true, "config_change_team_drive", "Configure this as a Shared Drive?") + q := FromOption(out.Option) + if q.Name != "config_change_team_drive" || q.Kind != KindBool || q.DefaultText != "true" { + t.Errorf("confirm %+v", q) + } + if got := values(q.Choices); !slices.Equal(got, []string{"true", "false"}) { + t.Errorf("confirm choices %v", got) + } +} + +func TestGroups(t *testing.T) { + c := New("").Catalog() + main := block(t, c, "main") + if o := option(t, main, "bwlimit"); o.PerOperation { + t.Error("bwlimit per operation") + } + if o := option(t, main, "checkers"); !o.PerOperation { + t.Error("checkers not per operation") + } + config := names(group(t, c, "config")) + for _, name := range []string{"checkers", "transfers", "use_server_modtime", "fast_list"} { + if !slices.Contains(config, name) { + t.Errorf("config group lacks %s", name) + } + } + for _, name := range rclone.NotPerOperation { + if slices.Contains(config, name) { + t.Errorf("config group offers %s, which a job does not apply", name) + } + } + copyNames, syncNames := names(group(t, c, "copy")), names(group(t, c, "sync")) + for _, name := range copyNames { + if !slices.Contains(syncNames, name) { + t.Errorf("sync group lacks copy's %s", name) + } + } + metadata := group(t, c, "metadata") + for _, want := range []struct{ Block, Name string }{{"main", "metadata"}, {"main", "metadata_mapper"}, {"filter", "metadata_include"}} { + if !slices.ContainsFunc(metadata, func(r OptionRef) bool { return r.Block == want.Block && r.Name == want.Name }) { + t.Errorf("metadata group lacks %s.%s", want.Block, want.Name) + } + } + if slices.Contains(names(group(t, c, "filter")), "metadata_include") { + t.Error("filter group has a metadata rule") + } + for _, g := range c.Groups { + if !slices.IsSortedFunc(names(g.Options), byName) { + t.Errorf("group %s not sorted", g.Name) + } + } + // There is a group for each serve type built into rclone here (nfs only on Unix), and no + // others. + var serves []string + for _, g := range c.Groups { + if typ, ok := strings.CutPrefix(g.Name, "serve."); ok { + serves = append(serves, typ) + } + } + if !slices.Equal(serves, rclone.ServeTypes()) || len(serves) < 7 { + t.Errorf("serve groups %v, rclone's serves %v", serves, rclone.ServeTypes()) + } + for _, typ := range serves { + opts := block(t, c, typ) + if len(group(t, c, "serve."+typ)) == 0 { + t.Errorf("serve %s: no options", typ) + } + for _, o := range opts { + if o.Name == "addr" && strings.ContainsAny(o.DefaultText, "[]") { + t.Errorf("serve %s addr default %q", typ, o.DefaultText) + } + } + } + if c.Version == "" || New("").Catalog().Version != c.Version { + t.Errorf("version %q not stable", c.Version) + } +} + +func TestByName(t *testing.T) { + in := []string{"a1", "ab", "a_b", "a"} + slices.SortFunc(in, byName) + if got := strings.Join(in, ","); got != "a,a_b,a1,ab" { + t.Errorf("order %s, want localeCompare's a,a_b,a1,ab", got) + } +} + +func TestValues(t *testing.T) { + if v := New("").Values(context.Background()); v.Blocks == nil { + t.Error("no blocks map") + } + // rclone's current values come as text, by option name. The nanoseconds and bytes in the rc + // JSON are not what a form shows. + ci := fs.GetConfig(context.Background()) + before := ci.ConnectTimeout + ci.ConnectTimeout = fs.Duration(90 * time.Second) + defer func() { ci.ConnectTimeout = before }() + main := New("").Values(context.Background()).Blocks["main"].Text + if main["contimeout"] != "1m30s" { + t.Errorf("main texts %v", main) + } + if _, ok := main["transfers"]; ok { + t.Errorf("a default's text %v", main) + } + + if lists := New("").Values(context.Background()).Blocks["main"].Lists; lists != nil { + t.Errorf("lists with no list set %v", lists) + } + + // A list comes as its elements, as rclone holds them, as well as its text. This covers an + // argv (a SpaceSepList) with a quoted word, and a comma list with a comma inside one element. + beforeMapper := ci.MetadataMapper + ci.MetadataMapper = fs.SpaceSepList{"/usr/bin/mapper", "a b", "-v"} + defer func() { ci.MetadataMapper = beforeMapper }() + main2 := New("").Values(context.Background()).Blocks["main"] + if got := main2.Text["metadata_mapper"]; got != `/usr/bin/mapper "a b" -v` { + t.Errorf("mapper text %q", got) + } + if got := main2.Lists["metadata_mapper"].Values; !slices.Equal(got, []string{"/usr/bin/mapper", "a b", "-v"}) { + t.Errorf("mapper elements %q", got) + } + + // A serve's values are keyed by option name too (the Go field is Addrs), and a repeated + // flag comes as its elements. + oi := fs.OptionsRegistry["webdav"] + addr := oi.Options.Get("addr") + if addr == nil || addr.FieldName == addr.Name { + t.Fatalf("webdav's addr %+v", addr) + } + if err := configstruct.Set(configmap.Simple{"addr": `127.0.0.1:9999,"[::1]:8,0"`}, oi.Opt); err != nil { + t.Fatal(err) + } + defer func() { _ = configstruct.Set(configmap.Simple{"addr": defaultText(addr)}, oi.Opt) }() + webdav := New("").Values(context.Background()).Blocks["webdav"] + if got := webdav.Text; got["addr"] != `127.0.0.1:9999,"[::1]:8,0"` { + t.Errorf("webdav texts %v", got) + } + if got := webdav.Lists["addr"].Values; !slices.Equal(got, []string{"127.0.0.1:9999", "[::1]:8,0"}) { + t.Errorf("webdav addr elements %q", got) + } +} + +// rcloneAsks runs rclone's own config for a new remote of type ri with the given provider. It +// calls fs.BackendConfig from ConfigAll, includes every advanced question, and answers each one +// with its current value. It returns the options asked, in order, and the values suggested for +// each. The backend's own Config step, which comes afterwards, is left out. +func rcloneAsks(t *testing.T, ri *fs.RegInfo, provider string) ([]string, map[string][]string) { + t.Helper() + r := *ri + r.Config = nil + m := configmap.Simple{} + if provider != "" { + m[fs.ConfigProvider] = provider + } + var asked []string + examples := map[string][]string{} + in := fs.ConfigIn{State: fs.ConfigAll} + advanced := false + for range 10000 { + out, err := fs.BackendConfig(context.Background(), "test", m, &r, configmap.Simple{}, in) + if err != nil { + t.Fatalf("%s: %v", ri.Name, err) + } + if out == nil || out.State == "" { + return asked, examples + } + if out.Option.Name == "config_fs_advanced" { // asked after each round: answer yes once + in = fs.ConfigIn{State: out.State, Result: fmt.Sprint(!advanced)} + advanced = true + continue + } + asked = append(asked, out.Option.Name) + for _, ex := range out.Option.Examples { + if !slices.Contains(examples[out.Option.Name], ex.Value) { + examples[out.Option.Name] = append(examples[out.Option.Name], ex.Value) + } + } + current, _ := m.Get(out.Option.Name) + in = fs.ConfigIn{State: out.State, Result: current} + } + t.Fatalf("%s: rclone's config did not end", ri.Name) + return nil, nil +} + +// A backend's view for a provider matches what rclone's config asks for it. It has the same +// options, apart from those that rclone hides from its config, which the catalog also marks. +// Each option's choices start with the values rclone suggests. This is checked for every +// provider of every backend that has providers. +func TestBackendIsWhatRcloneAsks(t *testing.T) { + s := New("") + compared := 0 + defer func() { + if compared < 40 { // s3 alone has more providers + t.Errorf("only %d providers compared", compared) + } + }() + for _, ri := range fs.Registry { + po := ri.Options.Get(fs.ConfigProvider) + if po == nil { + continue + } + providers := []string{""} + for _, ex := range po.Examples { + providers = append(providers, ex.Value) + } + for _, provider := range providers { + view, err := s.Backend(ri.Name, provider) + if err != nil { + t.Fatal(err) + } + if provider == "" && view.Provider != defaultText(po) { + t.Errorf("%s: no provider is %q, want the default %q", ri.Name, view.Provider, defaultText(po)) + } + if view.Provider == "" { + continue // no provider yet: see TestBackendWaitsForAProvider + } + compared++ + asked, examples := rcloneAsks(t, ri, view.Provider) + var shown []string + for _, o := range view.Backend.Options { + if ri.Options.Get(o.Name).Hide&fs.OptionHideConfigurator == 0 { + shown = append(shown, o.Name) + } + if want := examples[o.Name]; o.Kind != KindChoice && o.Kind != KindFlags && + (len(o.Choices) < len(want) || !slices.Equal(values(o.Choices)[:len(want)], want)) { + t.Errorf("%s for %s: %s offers %v, rclone %v", ri.Name, view.Provider, o.Name, values(o.Choices), want) + } + } + slices.Sort(shown) + slices.Sort(asked) + if !slices.Equal(shown, asked) { + t.Errorf("%s for %s: options\n %v\nrclone asks\n %v", ri.Name, view.Provider, shown, asked) + } + } + } +} + +// With no provider chosen and no default, a backend's view has the options that apply to every +// provider, with their suggestions unfiltered, as rclone shows them without a provider. +func TestBackendWaitsForAProvider(t *testing.T) { + s := New("") + view, err := s.Backend("s3", "") + if err != nil || view.Provider != "" { + t.Fatalf("%+v %v", view, err) + } + ri, _ := fs.Find("s3") + var want []string + for _, o := range ri.Options { + if o.Provider == "" { + want = append(want, o.Name) + } + } + var got []string + for _, o := range view.Backend.Options { + got = append(got, o.Name) + } + if !slices.Equal(got, want) || !slices.Contains(got, "provider") || slices.Contains(got, "region") { + t.Errorf("options %v, want %v", got, want) + } + // A provider's view offers only that provider's regions. + aws, _ := s.Backend("s3", "AWS") + region := values(option(t, aws.Backend.Options, "region").Choices) + if !slices.Contains(region, "eu-west-1") || slices.Contains(region, "de") { + t.Errorf("AWS regions %v", region) + } + // A backend without providers has all its options, and every registered name, aliases + // included, finds its own backend. + drive, _ := s.Backend("drive", "") + if len(drive.Backend.Options) != len(backend(t, s.Catalog(), "drive").Options) { + t.Errorf("drive has %d options", len(drive.Backend.Options)) + } + for _, ri := range fs.Registry { + if b, err := s.Backend(ri.Name, ""); err != nil || b.Backend.Name != ri.Name { + t.Errorf("%s: %v %v", ri.Name, b.Backend.Name, err) + } + } + if _, err := s.Backend("gopher", ""); errs.Of(err) == nil || errs.Of(err).Code != errs.CodeNotFound { + t.Errorf("an unknown backend: %v", err) + } +} + +func TestSummaryLeavesOptionsOut(t *testing.T) { + s := New("") + sum, cat := s.Summary(), s.Catalog() + for _, b := range sum.Backends { + if len(b.Options) > 0 { + t.Errorf("Summary's %s has %d options", b.Name, len(b.Options)) + } + } + // The metadata mapper reads a local path's fields from the metadata info, so the summary + // keeps it. + if backend(t, sum, "local").MetadataInfo == nil { + t.Error("Summary's local lost its metadata info") + } + if len(backend(t, cat, "s3").Options) == 0 { + t.Error("Catalog's s3 lost its options") + } + size := func(c *Catalog) int { + b, _ := json.Marshal(c) + return len(b) + } + if got, all := size(sum), size(cat); got*3 >= all { + t.Errorf("Summary is %d bytes of Catalog's %d, want under a third", got, all) + } +} + +// The remote option of each wrapping backend is marked for the remote picker, and only that +// option. A backend that rclone adds later with a "remote" option fails here until it is listed. +func TestWrappedRemotes(t *testing.T) { + for typ, opt := range wrappedRemotes { + ri, err := fs.Find(typ) + if err != nil { + t.Errorf("rclone has no backend %s", typ) + continue + } + if ri.Options.Get(opt) == nil { + t.Errorf("%s has no option %s", typ, opt) + } + } + for _, ri := range fs.Registry { + if ri.Options.Get("remote") != nil && wrappedRemotes[ri.Name] != "remote" { + t.Errorf("%s has a remote option that is not marked", ri.Name) + } + } + s := New("") + for _, typ := range []string{"alias", "crypt"} { + b, err := s.Backend(typ, "") + if err != nil { + t.Fatal(err) + } + for _, o := range b.Backend.Options { + if want := o.Name == "remote"; (o.Path == PathRemote) != want { + t.Errorf("%s.%s path = %q", typ, o.Name, o.Path) + } + } + } + cache, err := s.Backend("cache", "") + if err != nil { + t.Fatal(err) + } + if p := option(t, cache.Backend.Options, "tmp_upload_path").Path; p != PathDir { + t.Errorf("cache tmp_upload_path path = %q, want a folder", p) + } + s3, err := s.Backend("s3", "AWS") + if err != nil { + t.Fatal(err) + } + for _, o := range s3.Backend.Options { + if o.Path == PathRemote { + t.Errorf("s3.%s is marked as a wrapped remote", o.Name) + } + } +} diff --git a/core/catalog/cliflags_test.go b/core/catalog/cliflags_test.go new file mode 100644 index 00000000..911d2a2f --- /dev/null +++ b/core/catalog/cliflags_test.go @@ -0,0 +1,140 @@ +package catalog + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "os" + "os/exec" + "slices" + "strings" + "testing" + + rclonecmd "github.com/rclone/rclone/cmd" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config/configflags" + "github.com/rclone/rclone/fs/filter/filterflags" + "github.com/rclone/rclone/fs/log/logflags" + "github.com/rclone/rclone/fs/rc/rcflags" + "github.com/spf13/pflag" +) + +// cliFlag is one flag on rclone's command line, as the child process reports it. +type cliFlag struct { + Name, Short, Type string + Option bool // the flag's value is an option in rclone's registry +} + +const cliFlagsLine = "RCUI-CLI-FLAGS " + +// rcloneCLIFlags returns the global flags on rclone's command line in this binary (the flags +// that `rcui sync …` parses). They are read in a child process of the test, where rclone adds +// them to pflag.CommandLine as cmd.Main does (setupRootCommand's four AddFlags, then +// AddBackendFlags). That sets NoPrefix on the registry's options and would read RCLONE_* into +// rclone's globals. The child's environment has no RCLONE_* variables, and its changed state is +// thrown away when it exits. +func rcloneCLIFlags(t *testing.T) []cliFlag { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestCLIOnlyFlags$") + home := t.TempDir() + cmd.Env = []string{"RCUI_TEST_CLI_FLAGS=1", "HOME=" + home, "XDG_CONFIG_HOME=" + home, "TMPDIR=" + os.TempDir()} + out, err := cmd.Output() + if err != nil { + t.Fatalf("child: %v\n%s", err, out) + } + sc := bufio.NewScanner(bytes.NewReader(out)) + sc.Buffer(nil, 16<<20) + for sc.Scan() { + if rest, ok := strings.CutPrefix(sc.Text(), cliFlagsLine); ok { + var flags []cliFlag + if err := json.Unmarshal([]byte(rest), &flags); err != nil { + t.Fatal(err) + } + return flags + } + } + t.Fatalf("child printed no flags:\n%s", out) + return nil +} + +// printCLIFlags runs in the child. It prints rclone's global flags as its command line defines +// them. +func printCLIFlags(t *testing.T) { + ci := fs.GetConfig(context.Background()) + configflags.AddFlags(ci, pflag.CommandLine) + filterflags.AddFlags(pflag.CommandLine) + rcflags.AddFlags(pflag.CommandLine) + logflags.AddFlags(pflag.CommandLine) + rclonecmd.AddBackendFlags() + var flags []cliFlag + pflag.CommandLine.VisitAll(func(f *pflag.Flag) { + _, option := f.Value.(*fs.Option) + flags = append(flags, cliFlag{Name: f.Name, Short: f.Shorthand, Type: f.Value.Type(), Option: option}) + }) + raw, err := json.Marshal(flags) + if err != nil { + t.Fatal(err) + } + os.Stdout.WriteString("\n" + cliFlagsLine + string(raw) + "\n") +} + +// TestCLIOnlyFlags checks that cliOnly holds exactly the flags on rclone's command line that +// aren't options in its registry, each with its shorthand and kind. Cobra's help, which every +// command has, is left out of the comparison. It also checks that every flag ParseCommand defines +// for rclone's global blocks and backends matches the flag rclone defines. +func TestCLIOnlyFlags(t *testing.T) { + if os.Getenv("RCUI_TEST_CLI_FLAGS") == "1" { + printCLIFlags(t) + return + } + cli := rcloneCLIFlags(t) + kinds := map[cliKind]string{cliBool: "bool", cliCount: "count", cliString: "string", cliList: "stringArray"} + var own, theirs []string + for _, c := range cliOnly { + if c.name != "help" { + own = append(own, c.name+"/"+c.short+"/"+kinds[c.kind]) + } + } + byName := map[string]cliFlag{} + for _, f := range cli { + byName[f.Name] = f + if !f.Option { + kind := f.Type + if kind != "bool" && kind != "count" && kind != "stringArray" { + kind = "string" // a single value, however rclone parses it + } + theirs = append(theirs, f.Name+"/"+f.Short+"/"+kind) + } + } + slices.Sort(own) + slices.Sort(theirs) + if !slices.Equal(own, theirs) { + t.Errorf("cliOnly (name/short/kind)\n %v\nrclone's command line\n %v", own, theirs) + } + + set, flags := flagSet("") + for name, fo := range flags { + global := fo.backend + switch fo.block { + case "main", "filter", "rc", "log": + global = true + } + if !global { + continue // a command's own flags (mount, vfs, a serve): see TestFlagNames in core/operations + } + f, ok := byName[name] + if !ok || !f.Option { + t.Errorf("--%s (%s.%s) is no flag of rclone's command line", name, fo.block, fo.opt.Name) + continue + } + if short := set.Lookup(name).Shorthand; short != "" && short != f.Short { + t.Errorf("--%s is -%s here, -%s in rclone", name, short, f.Short) + } + } + for _, f := range cli { + if f.Option && set.Lookup(f.Name) == nil { + t.Errorf("rclone's --%s is not known here", f.Name) + } + } +} diff --git a/core/catalog/command.go b/core/catalog/command.go new file mode 100644 index 00000000..d5111a15 --- /dev/null +++ b/core/catalog/command.go @@ -0,0 +1,445 @@ +package catalog + +import ( + "errors" + "fmt" + "path/filepath" + "slices" + "strings" + + "github.com/rclone/rclone/fs" + "github.com/spf13/pflag" + + "github.com/rclone/rclone-ui/core/errs" + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/metadatamap" + "github.com/rclone/rclone-ui/core/rclone" +) + +// The reasons why a flag from a pasted command, or an option of a template, was not put into any +// group. A page shows them next to the flag, in the app's language (LocalSkipped). +var ( + reasonUnknown = i18n.M("Rclone has no such flag.") + // i18n: The flag is one of a storage backend's options, such as --drive-chunk-size. + reasonBackend = i18n.M("A backend's option: set it on the remote.") + // i18n: The flag is one of the app's settings, such as --bwlimit, which applies to every run. + reasonSettings = i18n.M("Applies to the whole app, not to a single operation.") + reasonNoGroup = i18n.M("No page sets this option.") + reasonCLI = i18n.M("Only rclone's command line reads it.") +) + +// ErrCommand is the start of the error for a command line that can't be read, such as one with an +// unclosed quote or a flag without its value. ParseCommand refuses such a line on the command +// field, with a message that starts with ErrCommand's. +var ErrCommand = errors.New("The command line cannot be read") + +var errUnclosed = fmt.Errorf("%w: a quote is not closed.", ErrCommand) + +// flagOf records what one flag in the temporary flag set stands for: an option of a block, or +// an option of a backend, whose flags carry the backend's prefix. +type flagOf struct { + block string + backend bool + opt *fs.Option +} + +// ParseCommand reads a pasted command line with rclone's own flag definitions. Each flag's value +// is a copy of its option (fs.Option is a pflag.Value), in a flag set made for this call, so +// neither rclone's global flags nor its config are affected. The options that the command sets +// are sorted into the catalog's groups (SortOptions). Flags that no group takes are skipped, with +// the reason. A line that can't be read is refused on the command field. +// +// When metadata_mapper runs the app's own mapper, the executable path that the Copy command put +// in front of it is removed. The value is then what the mapping panel writes +// (`["metadata-map", …]`), so it works whichever binary the app runs as later. +func (s *Service) ParseCommand(line string) (*ParsedCommand, error) { + words, err := splitCommand(line) + if err != nil { + // splitCommand fails only on a quote that isn't closed (errUnclosed). + return nil, errs.Field("command", "The command line cannot be read: a quote is not closed.") + } + if len(words) > 0 && isRclone(words[0]) { + words = words[1:] + } + serve := serveType(words) + set, flags := flagSet(serve) + out := &ParsedCommand{} + for _, name := range unknownFlags(set, words) { + out.Skipped = append(out.Skipped, Skip(name, reasonUnknown)) + } + var order []string // the flags that were set, in the order they first appear + written := map[string]string{} // the last text given for each flag + err = set.ParseAll(words, func(f *pflag.Flag, value string) error { + if err := f.Value.Set(value); err != nil { + // rclone's own reason, such as an invalid size, keeps rclone's words. + out.Skipped = append(out.Skipped, SkippedFlag{Flag: "--" + f.Name, Reason: err.Error()}) + return nil + } + if !slices.Contains(order, f.Name) { + order = append(order, f.Name) + } + written[f.Name] = value + return nil + }) + if err != nil { + // i18n: The value is pflag's English reason, such as "flag needs an argument: --transfers". + return nil, errs.Field("command", "The command line cannot be read: %s.", err) + } + out.Args = set.Args() + + // The options of the blocks that the pages set are sorted into groups by SortOptions. A + // serve's own block counts only in that serve's command, because rclone's other commands + // have no such flags. + flat := Group{} + flagOf := map[string]string{} // the flag of each option in flat + reasons := map[string]i18n.Text{} + for _, name := range order { + fo, known := flags[name] + switch { + case known && !fo.opt.IsSet(): + continue // every value given for it was refused + case !known: // one of cliOnly + reasons[name] = reasonCLI + case fo.backend: + reasons[name] = reasonBackend + case !pageBlock(fo.block, serve): + reasons[name] = reasonNoGroup + default: + value := pageValue(fo.opt, written[name]) + if argv, ok := value.([]string); ok && fo.opt.Name == "metadata_mapper" { + if own, ok := metadatamap.Own(argv, s.exe); ok { + value = own + } + } + flat[fo.opt.Name] = marshal(value) + flagOf[fo.opt.Name] = name + } + } + sorted := SortOptions(flat, serve) + for _, skip := range sorted.Skipped { + reasons[flagOf[skip.Flag]] = skip.text + } + for _, name := range order { + if reason, ok := reasons[name]; ok { + out.Skipped = append(out.Skipped, Skip("--"+name, reason)) + } + } + out.Groups = sorted.Groups + return out, nil +} + +// pageBlock reports whether the pages take a block's options from a command. They take the +// global blocks and the mount block, and a serve's own block only from that serve's command. +func pageBlock(block, serve string) bool { + switch block { + case "main", "filter", "vfs", "mount": + return true + } + return block == serve && serve != "" +} + +// flagSet defines every rclone option as a flag. Each flag is a copy of the option, named as +// rclone names its flag (fs.Option.FlagName). The blocks that the pages set come first (main, +// filter, vfs, mount, and the serve's own block when the command is a serve). They are added +// without a prefix, as rclone adds them (flags.AddFlagsFromOptions sets NoPrefix). Then come the +// other blocks, and the backends' options with their prefix, so that their flags are recognized +// and their values aren't mistaken for paths. When a name or a shorthand is already defined, the +// first definition wins, because rclone's own command line has one flag per name. +func flagSet(serve string) (*pflag.FlagSet, map[string]flagOf) { + set := pflag.NewFlagSet("rclone", pflag.ContinueOnError) + set.SetOutput(discard{}) + set.ParseErrorsAllowlist.UnknownFlags = true + flags := map[string]flagOf{} + add := func(prefix, block string, backend bool, o *fs.Option) { + c := o.Copy() + c.Value = nil + c.MarkUnset() + if prefix == "" { + c.NoPrefix = true + } + name := c.FlagName(prefix) + if set.Lookup(name) != nil { + return + } + short := c.ShortOpt + if short != "" && set.ShorthandLookup(short) != nil { + short = "" + } + f := set.VarPF(c, name, short, "") + if _, isBool := c.Default.(bool); isBool { + f.NoOptDefVal = "true" + } + flags[name] = flagOf{block: block, backend: backend, opt: c} + } + blocks := []string{"main", "filter", "vfs", "mount"} + if serve != "" { + blocks = append(blocks, serve) + } + var rest []string + for name := range fs.OptionsRegistry { + if !slices.Contains(blocks, name) { + rest = append(rest, name) + } + } + slices.Sort(rest) + for _, block := range append(blocks, rest...) { + oi, ok := fs.OptionsRegistry[block] + if !ok { + continue + } + for i := range oi.Options { + add("", block, false, &oi.Options[i]) + } + } + for _, ri := range fs.Registry { + for i := range ri.Options { + add(ri.Prefix, ri.Name, true, &ri.Options[i]) + } + } + for _, c := range cliOnly { + if set.Lookup(c.name) != nil { + continue + } + short := c.short + if short != "" && set.ShorthandLookup(short) != nil { + short = "" + } + switch c.kind { + case cliBool: + set.BoolP(c.name, short, false, "") + case cliCount: + set.CountP(c.name, short, "") + case cliString: + set.StringP(c.name, short, "", "") + case cliList: + set.StringArrayP(c.name, short, nil, "") + } + } + return set, flags +} + +type cliKind int + +const ( + cliBool cliKind = iota + cliCount + cliString + cliList +) + +// cliOnly lists the flags on rclone's command line that aren't options: the flags that +// configflags.AddFlags defines itself (fs/config/configflags/configflags.go:44-60), the ones of +// the command package (cmd/cmd.go:47-49), and cobra's help. rclone keeps them in package +// variables that only its CLI reads, so no page sets them. They are defined here so that their +// values aren't mistaken for paths and -h doesn't end the parse. The list is kept by hand, +// because calling rclone's AddFlags on our own flag set would change rclone's globals: it reads +// RCLONE_* into the global options, can end the process with fs.Fatalf, and sets NoPrefix on the +// registry's options. TestCLIOnlyFlags checks the list against rclone's command line. +var cliOnly = []struct { + name, short string + kind cliKind +}{ + {"verbose", "v", cliCount}, + {"quiet", "q", cliBool}, + {"config", "", cliString}, + {"cache-dir", "", cliString}, + {"temp-dir", "", cliString}, + {"dump-headers", "", cliBool}, + {"dump-bodies", "", cliBool}, + {"delete-before", "", cliBool}, + {"delete-during", "", cliBool}, + {"delete-after", "", cliBool}, + {"bind", "", cliString}, + {"disable", "", cliString}, + {"header-upload", "", cliList}, + {"header-download", "", cliList}, + {"header", "", cliList}, + {"metadata-set", "", cliList}, + {"dscp", "", cliString}, + {"cpuprofile", "", cliString}, + {"memprofile", "", cliString}, + {"stats", "", cliString}, // a duration + {"help", "h", cliBool}, +} + +// discard swallows pflag's usage output. +type discard struct{} + +func (discard) Write(p []byte) (int, error) { return len(p), nil } + +// pageValue returns an option's value in the form that the pages' option editors write in a +// group's JSON. A switch, a tristate or a number is a JSON value. The elements of a repeated +// flag or an argv become a list. Anything else is the last text given for the flag. rclone has +// already parsed that text, so it will parse the same way again, whereas rclone's own rendering +// would round a size of 1234567 bytes to 1.177Mi. +func pageValue(o *fs.Option, text string) any { + switch v := o.GetValue().(type) { + case bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64: + return v + case fs.Tristate: + if !v.Valid { + return nil + } + return v.Value + case []string: + return append([]string{}, v...) + case fs.SpaceSepList: + return append([]string{}, v...) + } + return text +} + +// serveType returns the serve type that a command starts (`serve webdav …`) when its block is +// registered in this build, and "" otherwise. +func serveType(words []string) string { + var args []string + for _, w := range words { + if w == "--" { + break + } + if !strings.HasPrefix(w, "-") { + args = append(args, w) + } + } + if len(args) < 2 || args[0] != "serve" || !slices.Contains(rclone.ServeTypes(), args[1]) { + return "" + } + if _, ok := fs.OptionsRegistry[args[1]]; !ok { + return "" + } + return args[1] +} + +// isRclone reports whether a command's first word runs rclone, meaning rclone or this app, at +// any path. +func isRclone(word string) bool { + base := strings.ToLower(filepath.Base(strings.ReplaceAll(word, `\`, "/"))) + base = strings.TrimSuffix(base, ".exe") + return base == "rclone" || base == "rcui" +} + +// unknownFlags returns the flags in words that set doesn't define, as they were written. pflag +// has no supported way to list them. When unknown flags are allowed +// (ParseErrorsAllowlist.UnknownFlags), pflag skips each one, along with the next word if that +// isn't a flag (stripUnknownFlagValue), and calls no callback. When they are refused, the parse +// stops at the first one with a NotExistError that doesn't say which. So this function walks the +// words using pflag's own grammar (parseArgs, parseLongArg and parseSingleShortArg in pflag +// v1.0.10). +func unknownFlags(set *pflag.FlagSet, words []string) []string { + var out []string + for i := 0; i < len(words); i++ { + w := words[i] + switch { + case w == "--": + return out + case strings.HasPrefix(w, "--"): + name, _, hasValue := strings.Cut(w[2:], "=") + f := set.Lookup(name) + switch { + case f == nil: + out = append(out, "--"+name) + case !hasValue && f.NoOptDefVal == "": + i++ // the next word is its value + } + case strings.HasPrefix(w, "-") && len(w) > 1: + shorts := w[1:] + for j := 0; j < len(shorts); j++ { + if shorts[j] == '=' { + break + } + f := set.ShorthandLookup(shorts[j : j+1]) + if f == nil { + out = append(out, "-"+shorts[j:j+1]) + continue + } + if f.NoOptDefVal == "" { + if j == len(shorts)-1 { + i++ // the next word is its value + } + break // the rest of the word is its value + } + } + } + } + return out +} + +// splitCommand splits a pasted line into words as a POSIX shell does. Blanks separate words. +// Single quotes keep everything inside them as is. Double quotes keep everything except a +// backslash before " \ $ or `, which is dropped. Outside quotes, a backslash escapes the +// character after it. The exception is a backslash before a letter, a digit, a dot or an +// underscore, which is kept, so that a Windows path (C:\Users\me) works without quotes. A +// backslash at the end of a line joins it to the next line. +func splitCommand(line string) ([]string, error) { + var ( + words []string + cur strings.Builder + in bool // a word has started (a pair of quotes starts an empty one) + ) + flush := func() { + if in { + words = append(words, cur.String()) + cur.Reset() + in = false + } + } + r := []rune(line) + for i := 0; i < len(r); i++ { + c := r[i] + switch { + case c == ' ' || c == '\t' || c == '\n' || c == '\r': + flush() + case c == '\'': + in = true + j := i + 1 + for j < len(r) && r[j] != '\'' { + j++ + } + if j == len(r) { + return nil, errUnclosed + } + cur.WriteString(string(r[i+1 : j])) + i = j + case c == '"': + in = true + j := i + 1 + for ; j < len(r) && r[j] != '"'; j++ { + if r[j] == '\\' && j+1 < len(r) && strings.ContainsRune("\"\\$`", r[j+1]) { + j++ + } else if r[j] == '\\' && j+1 < len(r) && r[j+1] == '\n' { + j++ + continue + } + cur.WriteRune(r[j]) + } + if j == len(r) { + return nil, errUnclosed + } + i = j + case c == '\\' && i+1 < len(r): + next := r[i+1] + switch { + case next == '\n': + i++ // a continued line + case next == '\r' && i+2 < len(r) && r[i+2] == '\n': + i += 2 + case isWordRune(next): + in = true + cur.WriteRune(c) // a path's separator + default: + in = true + cur.WriteRune(next) + i++ + } + default: + in = true + cur.WriteRune(c) + } + } + flush() + return words, nil +} + +func isWordRune(c rune) bool { + return c == '.' || c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' +} diff --git a/core/catalog/command_test.go b/core/catalog/command_test.go new file mode 100644 index 00000000..75e8dae0 --- /dev/null +++ b/core/catalog/command_test.go @@ -0,0 +1,173 @@ +package catalog + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "slices" + "strings" + "testing" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/filter" + + "github.com/rclone/rclone-ui/core/errs" +) + +func TestSplitCommand(t *testing.T) { + for _, c := range []struct { + in string + want []string + }{ + {`rclone sync a: b:`, []string{"rclone", "sync", "a:", "b:"}}, + {` --exclude "*.tmp" --include '*.jpg' `, []string{"--exclude", "*.tmp", "--include", "*.jpg"}}, + {`--exclude="a b" x\ y`, []string{"--exclude=a b", "x y"}}, + {`--header "X-A: \"q\""`, []string{"--header", `X-A: "q"`}}, + {`'it''s'`, []string{"its"}}, + {`""`, []string{""}}, + {"sync a: \\\n b: --dry-run", []string{"sync", "a:", "b:", "--dry-run"}}, + {`copy C:\Users\me\Photos D:\Backup`, []string{"copy", `C:\Users\me\Photos`, `D:\Backup`}}, + {`copy "C:\Program Files\x" y:`, []string{"copy", `C:\Program Files\x`, "y:"}}, + } { + got, err := splitCommand(c.in) + if err != nil || !slices.Equal(got, c.want) { + t.Errorf("splitCommand(%q) = %q, %v; want %q", c.in, got, err, c.want) + } + } + for _, bad := range []string{`--exclude "*.tmp`, `'open`} { + if _, err := splitCommand(bad); !errors.Is(err, ErrCommand) { + t.Errorf("splitCommand(%q): %v", bad, err) + } + } +} + +func groupOf(t *testing.T, out *ParsedCommand, name string) map[string]any { + t.Helper() + group, ok := out.Groups[name] + if !ok { + return nil + } + var g map[string]any + if err := json.Unmarshal(marshal(group), &g); err != nil { + t.Fatalf("group %s: %v", name, err) + } + return g +} + +func skipped(out *ParsedCommand) map[string]string { + m := map[string]string{} + for _, s := range out.Skipped { + m[s.Flag] = s.Reason + } + return m +} + +func TestParseCommand(t *testing.T) { + ciBefore := *fs.GetConfig(context.Background()) + fiBefore := filter.GetConfig(context.Background()).Opt + s := New("") + out, err := s.ParseCommand(`/usr/local/bin/rclone -vv sync --delete-after gdrive:Photos "/Volumes/Backup/My Photos" ` + + `--transfers 8 -P --exclude "*.tmp" --exclude=.DS_Store --fast-list --dry-run --bwlimit 1M ` + + `--max-delete 10 --metadata --max-age 2d --size-only=false --drive-chunk-size 64M --no-such-flag --help`) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(out.Args, []string{"sync", "gdrive:Photos", "/Volumes/Backup/My Photos"}) { + t.Errorf("args %q", out.Args) + } + if got := groupOf(t, out, "config"); !reflect.DeepEqual(got, map[string]any{"transfers": 8.0, "fast_list": true, "dry_run": true}) { + t.Errorf("config %v", got) + } + if got := groupOf(t, out, "filter"); !reflect.DeepEqual(got, map[string]any{"exclude": []any{"*.tmp", ".DS_Store"}, "max_age": "2d"}) { + t.Errorf("filter %v", got) + } + if got := groupOf(t, out, "sync"); !reflect.DeepEqual(got, map[string]any{"max_delete": 10.0}) { + t.Errorf("sync %v", got) + } + if got := groupOf(t, out, "copy"); !reflect.DeepEqual(got, map[string]any{"size_only": false}) { + t.Errorf("copy %v", got) + } + if got := groupOf(t, out, "metadata"); !reflect.DeepEqual(got, map[string]any{"metadata": true}) { + t.Errorf("metadata %v", got) + } + why := skipped(out) + for flag, reason := range map[string]string{ + "--bwlimit": reasonSettings.String(), + "--drive-chunk-size": reasonBackend.String(), + "--no-such-flag": reasonUnknown.String(), + "--verbose": reasonCLI.String(), + "--delete-after": reasonCLI.String(), + "--help": reasonCLI.String(), + "--progress": reasonCLI.String(), + } { + if why[flag] != reason { + t.Errorf("%s skipped as %q, want %q (all %v)", flag, why[flag], reason, why) + } + } + // None of the flags changed rclone's own settings. + if ci := fs.GetConfig(context.Background()); ci.Transfers != ciBefore.Transfers || ci.DryRun != ciBefore.DryRun || ci.Progress != ciBefore.Progress { + t.Errorf("rclone's config changed: transfers %d dry-run %v", ci.Transfers, ci.DryRun) + } + if fi := filter.GetConfig(context.Background()).Opt; !reflect.DeepEqual(fi.ExcludeRule, fiBefore.ExcludeRule) { + t.Errorf("rclone's filters changed: %v", fi.ExcludeRule) + } + for _, o := range fs.ConfigOptionsInfo { + if o.IsSet() { + t.Errorf("rclone's %s marked set", o.Name) + } + } +} + +// A pasted Copy command puts this executable in front of the app's own metadata mapper, and the +// import removes it again. Another program's mapper is kept whole. +func TestParseCommandMapper(t *testing.T) { + const exe = "/opt/Rclone UI/rcui" + s := New(exe) + out, err := s.ParseCommand(`rclone copy a: b: --metadata --metadata-mapper '"/opt/Rclone UI/rcui" metadata-map --map "a b=c"'`) + if err != nil { + t.Fatal(err) + } + if got := groupOf(t, out, "metadata")["metadata_mapper"]; !reflect.DeepEqual(got, []any{"metadata-map", "--map", "a b=c"}) { + t.Errorf("own mapper %v", got) + } + out, err = s.ParseCommand(`rclone copy a: b: --metadata-mapper "/opt/bin/mapper -v"`) + if err != nil { + t.Fatal(err) + } + if got := groupOf(t, out, "metadata")["metadata_mapper"]; !reflect.DeepEqual(got, []any{"/opt/bin/mapper", "-v"}) { + t.Errorf("another program %v", got) + } +} + +func TestParseCommandServeAndValues(t *testing.T) { + s := New("") + out, err := s.ParseCommand(`rclone serve webdav remote: --addr :8080 --vfs-cache-mode full --read-only --dir-cache-time 5m --transfers nope`) + if err != nil { + t.Fatal(err) + } + if got := groupOf(t, out, "serve.webdav"); got["addr"] == nil || got["addr"].([]any)[0] != ":8080" { + t.Errorf("serve.webdav %v", got) + } + vfs := groupOf(t, out, "vfs") + // Values keep the text as written, which rclone has parsed, rather than rclone's rendering of + // it (5m0s). + if vfs["vfs_cache_mode"] != "full" || vfs["read_only"] != true || vfs["dir_cache_time"] != "5m" { + t.Errorf("vfs %v", vfs) + } + if why := skipped(out)["--transfers"]; why == "" { + t.Errorf("a bad value taken: %v", out.Skipped) + } + // A serve's options are only taken from that serve's command. --addr in any other command + // isn't an option that a page sets. + out, err = s.ParseCommand(`sync a: b: --addr :8080`) + if err != nil { + t.Fatal(err) + } + if len(out.Groups) != 0 || skipped(out)["--addr"] != reasonNoGroup.String() { + t.Errorf("groups %v skipped %v", out.Groups, out.Skipped) + } + if _, err := s.ParseCommand(`sync a: b: --transfers`); errs.FieldOf(err) != "command" || !strings.HasPrefix(err.Error(), ErrCommand.Error()) { + t.Errorf("a flag without its value: %v", err) + } +} diff --git a/core/catalog/defaults.go b/core/catalog/defaults.go new file mode 100644 index 00000000..be4ab860 --- /dev/null +++ b/core/catalog/defaults.go @@ -0,0 +1,54 @@ +package catalog + +import "encoding/json" + +// The app's own defaults for rclone's options. rclone's own defaults are tuned for a command that +// runs once in a terminal, so the app raises the number of parallel transfers and checkers, and +// the number of streams that a large file is sent in. Everything else is rclone's own default. +// +// The operations package applies them under every transfer, mount and serve (withDefaults), +// whatever starts it. The pages show them in their option groups, and send only what differs: +// a changed value, or null for a default that the user removed, which means rclone's own default. +// So a saved template, schedule or automount holds only the user's own choices. + +// configDefaults are the defaults in the config group of every operation that has options. +func configDefaults() Group { + return Group{ + "transfers": json.RawMessage(`8`), + "checkers": json.RawMessage(`16`), + } +} + +// multiThreadDefaults are the defaults for an operation that copies files. A large file is sent +// in this many streams at once. +func multiThreadDefaults() Group { + return Group{ + "multi_thread_streams": json.RawMessage(`8`), + } +} + +// Defaults returns the app's default options, keyed by operation ("copy", "mount"…) and then by +// the form's group ("config", "copy"…). An operation without defaults is left out. Copy, Move, +// Sync and Bisync keep their multi-thread default in their own group, where the pages show it. +// A save has only a config group, so its multi-thread default goes there. A mount and a serve +// have none in their vfs group. Each call returns new maps, so a caller may change them. +func Defaults() map[string]map[string]Group { + withMultiThread := func(own string) map[string]Group { + return map[string]Group{own: multiThreadDefaults(), "config": configDefaults()} + } + save := configDefaults() + for name, value := range multiThreadDefaults() { + save[name] = value + } + return map[string]map[string]Group{ + "copy": withMultiThread("copy"), + "move": withMultiThread("move"), + "sync": withMultiThread("sync"), + "bisync": withMultiThread("bisync"), + "save": {"config": save}, + "delete": {"config": configDefaults()}, + "purge": {"config": configDefaults()}, + "mount": {"config": configDefaults()}, + "serve": {"config": configDefaults()}, + } +} diff --git a/core/catalog/group.go b/core/catalog/group.go new file mode 100644 index 00000000..a052a6be --- /dev/null +++ b/core/catalog/group.go @@ -0,0 +1,78 @@ +package catalog + +import ( + "bytes" + "encoding/json" + "slices" + "strings" + + "github.com/rclone/rclone-ui/core/location" +) + +// Group holds the options of one group of a form, such as its config or filter options, keyed by +// rclone's option name as the page wrote it. Each value stays the JSON that the page sent, so a +// number such as 1.50 keeps every digit until rclone's own parser reads it. +type Group map[string]json.RawMessage + +// remotePathOptions are the options whose value rclone opens as a path, so they can name a +// remote. compare_dest and copy_dest can hold a list. backup_dir1 and backup_dir2 are bisync's. +var remotePathOptions = []string{"backup_dir", "compare_dest", "copy_dest", "backup_dir1", "backup_dir2"} + +// RenameRemote rewrites the values of the options that hold a path on the remote from, after the +// remote is renamed to to. A value can be one path or a list of paths. Keys are matched with +// dashes or underscores, and with or without leading dashes. It changes g in place, and reports +// whether anything changed. +func (g Group) RenameRemote(from, to string) bool { + changed := false + for key, value := range g { + name := strings.ReplaceAll(strings.TrimLeft(key, "-"), "-", "_") + if !slices.Contains(remotePathOptions, name) { + continue + } + if renamed, ok := renameInValue(value, from, to); ok { + g[key] = renamed + changed = true + } + } + return changed +} + +// renameInValue rewrites a value that is a path or a list of paths. It returns the new JSON and +// whether anything changed. In a list, other values are kept as they are. +func renameInValue(value json.RawMessage, from, to string) (json.RawMessage, bool) { + var one string + if json.Unmarshal(value, &one) == nil { + p, ok := location.RenameRemote(one, from, to) + if !ok { + return nil, false + } + return marshal(p), true + } + var list []json.RawMessage + if json.Unmarshal(value, &list) != nil { + return nil, false + } + changed := false + for i, elem := range list { + if json.Unmarshal(elem, &one) != nil { + continue + } + if p, ok := location.RenameRemote(one, from, to); ok { + list[i] = marshal(p) + changed = true + } + } + if !changed { + return nil, false + } + return marshal(list), true +} + +// marshal writes v as JSON without escaping <, > and &, which can appear in paths. +func marshal(v any) json.RawMessage { + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + _ = enc.Encode(v) // strings and lists of raw JSON always encode + return bytes.TrimRight(b.Bytes(), "\n") +} diff --git a/core/catalog/group_test.go b/core/catalog/group_test.go new file mode 100644 index 00000000..2eedb586 --- /dev/null +++ b/core/catalog/group_test.go @@ -0,0 +1,38 @@ +package catalog + +import ( + "encoding/json" + "testing" +) + +// A rename rewrites the options that hold a path on the remote, one path or a list, and leaves +// other remotes, local paths and other options alone. +func TestGroupRenameRemote(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {`{"transfers":4,"backup_dir":"old:Trash"}`, `{"backup_dir":"new:Trash","transfers":4}`}, + {`{"compare_dest":["old:a","other:b","old:"]}`, `{"compare_dest":["new:a","other:b","new:"]}`}, + {`{"compare_dest":["old:a",1,"other:b"]}`, `{"compare_dest":["new:a",1,"other:b"]}`}, + {`{"copy-dest":"old,link=x:a & b"}`, `{"copy-dest":"new,link=x:a & b"}`}, + {`{"--backup-dir":"old:x"}`, `{"--backup-dir":"new:x"}`}, + {`{"backup_dir1":"old:1","backup_dir2":"old:2"}`, `{"backup_dir1":"new:1","backup_dir2":"new:2"}`}, + {`{"backup_dir":"older:x"}`, ``}, + {`{"backup_dir":"/old:x"}`, ``}, + {`{"description":"old:x"}`, ``}, + {`{"backup_dir":":local:old:x"}`, ``}, + {`{}`, ``}, + } { + var g Group + if err := json.Unmarshal([]byte(c.in), &g); err != nil { + t.Fatal(err) + } + changed := g.RenameRemote("old", "new") + got := marshal(g) + want := c.want + if want == "" { + want = c.in + } + if changed != (c.want != "") || string(got) != want { + t.Errorf("%s: got %s (changed %v), want %s", c.in, got, changed, want) + } + } +} diff --git a/core/catalog/sort.go b/core/catalog/sort.go new file mode 100644 index 00000000..18d23388 --- /dev/null +++ b/core/catalog/sort.go @@ -0,0 +1,141 @@ +package catalog + +import ( + "maps" + "slices" + "strings" + "sync" + + "github.com/rclone/rclone/fs" + + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/core/rclone" +) + +type Sorted struct { + // Groups holds the options of each catalog group (filter, config, copy, serve.http…), keyed + // by rclone's option name. A group without options is missing. + Groups map[string]Group `json:"groups"` + // Skipped lists the options that no group takes, each with the reason. Flag is the key as it + // was given. + Skipped []SkippedFlag `json:"skipped"` +} + +// NormalizeOptionName converts a key written by a page to rclone's option name, so `--dry-run`, +// `dry-run` and `dry_run` all name the same option. +func NormalizeOptionName(name string) string { + return strings.ReplaceAll(strings.TrimPrefix(name, "--"), "-", "_") +} + +// SortOptions sorts options into the catalog's groups. It is the one rule for this: a pasted +// command (ParseCommand), a template applied to a page, and the template drawer all use it. +// +// Each key is read as rclone's option name, in any spelling, and the option is put under that +// name. Its block is the first one that has the name, in the order that rclone's command line +// defines their flags: main, filter, vfs, mount, and then the serve's own block. The option goes +// into the first catalog group that lists it, so an option that config and copy both list goes +// into config. serve names the serve type. When it is "", a serve option goes into the group of +// every serve type that has it, because an option such as addr belongs to each one. +// +// Some options go into no group, and are skipped with the reason. A main option that a run can +// set, but no group lists (dry_run, max_depth), goes into config. The exceptions are the logging +// options, which only rclone's command line reads. A main option that rclone sets once for the +// whole app (rclone.NotPerOperation) is skipped as one of the app's settings. A name that none of +// these blocks has is skipped too, whether another block has it or rclone has no such option. +func SortOptions(options Group, serve string) Sorted { + out := Sorted{Groups: map[string]Group{}} + for _, key := range slices.Sorted(maps.Keys(options)) { + name := NormalizeOptionName(key) + into, reason := groupsOf(name, serve) + if !reason.IsZero() { + out.Skipped = append(out.Skipped, Skip(key, reason)) + continue + } + for _, group := range into { + if out.Groups[group] == nil { + out.Groups[group] = Group{} + } + out.Groups[group][name] = options[key] + } + } + return out +} + +// groupsOf returns the catalog groups that take the option called name, or the reason why none +// does. serve is as in SortOptions. +func groupsOf(name, serve string) ([]string, i18n.Text) { + index := sectionIndex() + for _, block := range []string{"main", "filter", "vfs", "mount"} { + o, ok := optionOf(block, name) + if !ok { + continue + } + if group, ok := index[optionKey{block, name}]; ok { + return []string{group}, i18n.Text{} + } + if block != "main" { + return nil, reasonNoGroup + } + switch { + case !rclone.PerOperation(name): + return nil, reasonSettings + case strings.Contains(o.Groups, "Logging"): + return nil, reasonCLI + } + return []string{"config"}, i18n.Text{} + } + var into []string + for _, t := range serveBlocks(serve) { + if group, ok := index[optionKey{t, name}]; ok { + into = append(into, group) + } + } + if len(into) > 0 { + return into, i18n.Text{} + } + for block := range fs.OptionsRegistry { + if _, ok := optionOf(block, name); ok { + return nil, reasonNoGroup + } + } + return nil, reasonUnknown +} + +func optionOf(block, name string) (*fs.Option, bool) { + info, ok := fs.OptionsRegistry[block] + if !ok { + return nil, false + } + o := info.Options.Get(name) + return o, o != nil +} + +// serveBlocks returns the blocks of the serve type serve, or of every serve type when serve is +// "". Only the types that this build has are returned. +func serveBlocks(serve string) []string { + types := rclone.ServeTypes() + if serve == "" { + return types + } + if slices.Contains(types, serve) { + return []string{serve} + } + return nil +} + +type optionKey struct{ block, name string } + +// sectionIndex maps each block option to the first catalog group that lists it, in the order of +// the groups. For example, an option that both copy and sync list belongs to copy. +var sectionIndex = sync.OnceValue(func() map[optionKey]string { + out := map[optionKey]string{} + for _, g := range sections() { + for _, ref := range g.Options { + k := optionKey{ref.Block, ref.Name} + if _, ok := out[k]; !ok { + out[k] = g.Name + } + } + } + return out +}) diff --git a/core/catalog/sort_test.go b/core/catalog/sort_test.go new file mode 100644 index 00000000..3886364c --- /dev/null +++ b/core/catalog/sort_test.go @@ -0,0 +1,131 @@ +package catalog + +import ( + "context" + "encoding/json" + "reflect" + "strings" + "testing" + + "github.com/rclone/rclone-ui/core/i18n" +) + +func TestSortOptions(t *testing.T) { + options := Group{ + "transfers": json.RawMessage(`4`), + "--dry-run": json.RawMessage(`true`), + "max-depth": json.RawMessage(`2`), + "ignore_existing": json.RawMessage(`true`), + "max_delete": json.RawMessage(`10`), + "exclude": json.RawMessage(`["*.tmp"]`), + "metadata": json.RawMessage(`true`), + "vfs_cache_mode": json.RawMessage(`"full"`), + "allow_other": json.RawMessage(`true`), + "addr": json.RawMessage(`":8080"`), + "bwlimit": json.RawMessage(`"1M"`), + "stats_one_line": json.RawMessage(`true`), + "log_file": json.RawMessage(`"/tmp/x.log"`), + "no_such_option": json.RawMessage(`1`), + } + got := SortOptions(options, "") + names := func(group string) []string { + var out []string + for name := range got.Groups[group] { + out = append(out, name) + } + return out + } + for group, want := range map[string][]string{ + // A main option that a run can set, but no group lists, goes to config, under rclone's + // name. + "config": {"dry_run", "max_depth", "transfers"}, + "copy": {"ignore_existing"}, + "sync": {"max_delete"}, + "filter": {"exclude"}, + "metadata": {"metadata"}, + "vfs": {"vfs_cache_mode"}, + "mount": {"allow_other"}, + } { + if g := names(group); !sameSet(g, want) { + t.Errorf("%s: %v, want %v", group, g, want) + } + } + // Without a serve type, a serve option goes into the group of each serve that has it. + for _, serve := range []string{"serve.http", "serve.webdav", "serve.ftp"} { + if _, ok := got.Groups[serve]["addr"]; !ok { + t.Errorf("addr is not in %s: %v", serve, got.Groups) + } + } + if got.Groups["config"]["dry_run"] == nil || string(got.Groups["config"]["dry_run"]) != "true" { + t.Errorf("the value of dry_run: %s", got.Groups["config"]["dry_run"]) + } + why := map[string]string{} + for _, s := range got.Skipped { + why[s.Flag] = s.Reason + } + if want := map[string]string{ + "bwlimit": reasonSettings.String(), + "stats_one_line": reasonCLI.String(), + "log_file": reasonNoGroup.String(), + "no_such_option": reasonUnknown.String(), + }; !reflect.DeepEqual(why, want) { + t.Errorf("skipped %v, want %v", why, want) + } + + // With a serve type, a serve option goes into that serve's group alone, and an option that + // only another serve has is skipped. + got = SortOptions(Group{"addr": json.RawMessage(`":8080"`), "announce_interval": json.RawMessage(`"5m"`)}, "webdav") + if len(got.Groups) != 1 || got.Groups["serve.webdav"]["addr"] == nil { + t.Errorf("groups of a webdav serve: %v", got.Groups) + } + if len(got.Skipped) != 1 || got.Skipped[0].Reason != reasonNoGroup.String() { + t.Errorf("skipped of a webdav serve: %v", got.Skipped) + } +} + +func sameSet(a, b []string) bool { + if len(a) != len(b) { + return false + } + in := map[string]bool{} + for _, s := range a { + in[s] = true + } + for _, s := range b { + if !in[s] { + return false + } + } + return true +} + +// The reasons reach the page in the app's language. The pseudo-language shows that they are +// translated, whether or not a language has their translation yet. rclone's own reason keeps its +// words. +func TestLocalSkipped(t *testing.T) { + t.Cleanup(func() { i18n.SetLanguage(i18n.English) }) + a := NewAPI(New(""), nil) + i18n.SetLanguage(i18n.Pseudo) + sorted, _ := a.SortOptions(context.Background(), Group{"no_such_option": json.RawMessage(`1`)}, "") + if len(sorted.Skipped) != 1 || !strings.HasPrefix(sorted.Skipped[0].Reason, "[") { + t.Errorf("SortOptions' reason isn't translated: %v", sorted.Skipped) + } + parsed, err := a.ParseCommand(context.Background(), `sync a: b: --no-such-flag --max-size nope`) + if err != nil { + t.Fatal(err) + } + why := map[string]string{} + for _, s := range parsed.Skipped { + why[s.Flag] = s.Reason + } + if !strings.HasPrefix(why["--no-such-flag"], "[") || why["--max-size"] == "" || strings.HasPrefix(why["--max-size"], "[") { + t.Errorf("ParseCommand's reasons: %v", why) + } + i18n.SetLanguage(i18n.English) + if got := LocalSkipped([]SkippedFlag{Skip("--x", reasonCLI)}); got[0].Reason != reasonCLI.String() { + t.Errorf("English reason %q", got[0].Reason) + } + if got := LocalSkipped(nil); got == nil { + t.Error("a nil list stays nil") + } +} diff --git a/core/catalog/texts.go b/core/catalog/texts.go new file mode 100644 index 00000000..2a31dbc9 --- /dev/null +++ b/core/catalog/texts.go @@ -0,0 +1,544 @@ +package catalog + +import ( + "cmp" + "context" + "encoding/json" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "sync" + + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config/configmap" + "github.com/rclone/rclone/lib/oauthutil" + + "github.com/rclone/rclone-ui/core/i18n" + "github.com/rclone/rclone-ui/locales" +) + +// rclone's own text (backend descriptions, the help of options and their examples, backend +// command help, metadata help, and the questions of a remote's setup) is translated in +// locales//rclone.json. Each file is a tree keyed by backend, option block and option +// name, in the shape of rclone-ui/rclone-i18n's language packs: +// +// backend..description +// backend..option.