diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fde7a92..b065b11 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,10 +19,10 @@ jobs: name: fmt + clippy runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Rust toolchain (from rust-toolchain.toml) run: rustup toolchain install || rustup show - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: ./.github/actions/linux-deps - run: cargo fmt --all -- --check - run: cargo clippy --workspace --all-targets --locked -- -D warnings @@ -36,10 +36,10 @@ jobs: os: [ubuntu-latest, macos-15-intel, windows-latest] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Rust toolchain (from rust-toolchain.toml) run: rustup toolchain install || rustup show - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - if: runner.os == 'Linux' uses: ./.github/actions/linux-deps - run: cargo test --workspace --locked diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 40db11d..4fe43f4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,90 +6,258 @@ on: workflow_dispatch: inputs: tag: - description: Tag to build and publish, e.g. v0.0.1 (created at this branch's head if missing) + description: Tag to build, e.g. v0.0.1. An existing tag must be the commit this run builds (run the workflow on the tag); a missing one is created at this branch's head when publishing required: true + publish: + description: Publish a GitHub release; when off, the builds are only kept as workflow artifacts + type: boolean + default: true +# Only the publish job writes to the repository. permissions: - contents: write + contents: read env: CARGO_TERM_COLOR: always CARGO_INCREMENTAL: 0 TAG: ${{ github.event.inputs.tag || github.ref_name }} + # Installers are built by cargo-packager from [package.metadata.packager] in + # crates/redshell-app/Cargo.toml. Update the checksums in "Install cargo-packager" and the + # file names in "Seed the AppImage tools" with it. + CARGO_PACKAGER_VERSION: 0.11.8 jobs: + version: + # Every other job waits for this one, which checks that the tag fits what is built: + # * It is v and a version: only a v0.0.x tag is published as a prerelease, so a tag + # without the v would make a full release. + # * It matches the crate version: the update check compares releases with it, so a + # build tagged with a different version would offer an update to itself. + # * An existing tag is the commit being built. A manual run builds its branch's head, + # which may have moved past the tag, so it must be run on the tag (or on a branch + # whose head is the tag's commit). A missing tag is created at that commit. + name: tag matches the build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - run: | + set -euo pipefail + if [[ ! "$TAG" =~ ^v[0-9] ]]; then + echo "::error::Tag $TAG must be v and the version, e.g. v0.0.1" + exit 1 + fi + # Assigned on its own line so that a failed lookup stops the job instead of + # reading as a missing tag. + remote=$(git ls-remote --tags origin "refs/tags/$TAG") + if [ -n "$remote" ]; then + git fetch --no-tags --depth=1 origin "refs/tags/$TAG" + tagged=$(git rev-parse "FETCH_HEAD^{commit}") + if [ "$tagged" != "$GITHUB_SHA" ]; then + echo "::error::Tag $TAG is commit $tagged but this run builds $GITHUB_SHA; run the workflow on the tag" + exit 1 + fi + fi + rustup toolchain install || rustup show + version=$(cargo metadata --no-deps --format-version 1 \ + | jq -r '.packages[] | select(.name == "redshell-app") | .version') + if [ "${TAG#v}" != "$version" ]; then + echo "::error::Tag $TAG does not match the crate version $version in Cargo.toml" + exit 1 + fi + build: + needs: version name: build (${{ matrix.name }}) + permissions: + contents: read strategy: fail-fast: false matrix: include: - - { name: linux-x86_64, os: ubuntu-22.04, targets: x86_64-unknown-linux-gnu } + - name: linux-x86_64 + os: ubuntu-22.04 + targets: x86_64-unknown-linux-gnu + package-target: x86_64-unknown-linux-gnu + formats: deb,appimage # One Intel runner builds both architectures and merges them with lipo. # Hosted macOS arm64 runners are often unavailable; the SDK cross-compiles # to arm64 from Intel just as well. - - { name: macos-universal, os: macos-15-intel, targets: aarch64-apple-darwin x86_64-apple-darwin } - - { name: windows-x86_64, os: windows-latest, targets: x86_64-pc-windows-msvc } + - name: macos-universal + os: macos-15-intel + targets: aarch64-apple-darwin x86_64-apple-darwin + package-target: universal-apple-darwin + formats: app,dmg + - name: windows-x86_64 + os: windows-latest + targets: x86_64-pc-windows-msvc + package-target: x86_64-pc-windows-msvc + formats: nsis runs-on: ${{ matrix.os }} env: TARGETS: ${{ matrix.targets }} + # cargo-packager reads the binary from target//release. + PACKAGE_TARGET: ${{ matrix.package-target }} + # Release files are named redshell--.. + BASE_NAME: redshell-${{ github.event.inputs.tag || github.ref_name }}-${{ matrix.name }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Rust toolchain (from rust-toolchain.toml) shell: bash run: | rustup toolchain install || rustup show rustup target add $TARGETS - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: ${{ matrix.name }} - if: runner.os == 'Linux' uses: ./.github/actions/linux-deps + - name: Install cargo-packager + shell: bash + # cargo-quickinstall's prebuilt binary, pinned by checksum; compiled from crates.io + # when the download is unavailable. + run: | + set -euo pipefail + case "$RUNNER_OS" in + Linux) target=x86_64-unknown-linux-gnu sum=59be4a604184c61f31600f1d00e211947f8570f8927c16c7eddfd5fccd7f060e ;; + macOS) target=x86_64-apple-darwin sum=03d614d12680975fa1cf5c29c75c3b21ee8d0c6f1b76783d54ce383e56f5d62c ;; + Windows) target=x86_64-pc-windows-msvc sum=24e25795c002e357ffadf9c5e990ba289215537286bcbea652a5967400782a3b ;; + esac + name="cargo-packager-$CARGO_PACKAGER_VERSION" + # A relative path: tar reads "D:\..." as a remote host. + archive=cargo-packager.tar.gz + if curl -fsSL -o "$archive" \ + "https://github.com/cargo-bins/cargo-quickinstall/releases/download/$name/$name-$target.tar.gz"; then + actual=$( (sha256sum "$archive" 2>/dev/null || shasum -a 256 "$archive") | cut -d' ' -f1) + if [ "$actual" != "$sum" ]; then + echo "::error::cargo-packager archive checksum mismatch: $actual" + exit 1 + fi + tar -xzf "$archive" -C "$HOME/.cargo/bin" + rm "$archive" + else + cargo install --locked "cargo-packager@$CARGO_PACKAGER_VERSION" + fi + cargo packager --version - name: Build shell: bash run: | + set -euo pipefail for target in $TARGETS; do cargo build --release --locked --target "$target" -p redshell-app done - - name: Package - shell: bash - run: | - set -euo pipefail - dir="redshell-${TAG}-${{ matrix.name }}" - mkdir -p "$dir" set -- $TARGETS if [ $# -gt 1 ]; then - lipo -create $(printf 'target/%s/release/redshell ' "$@") -output "$dir/redshell" - lipo -info "$dir/redshell" - else - bin="target/$1/release/redshell" - [ -f "$bin.exe" ] && bin="$bin.exe" - cp "$bin" "$dir/" + mkdir -p "target/$PACKAGE_TARGET/release" + lipo -create $(printf 'target/%s/release/redshell ' "$@") -output "target/$PACKAGE_TARGET/release/redshell" + lipo -info "target/$PACKAGE_TARGET/release/redshell" fi + - name: Archive + shell: bash + run: | + set -euo pipefail + dir="$BASE_NAME" + mkdir -p "$dir" dist + bin="target/$PACKAGE_TARGET/release/redshell" + [ -f "$bin.exe" ] && bin="$bin.exe" + cp "$bin" "$dir/" cp README.md LICENSE CHANGELOG.md "$dir/" cp -r shell-integration "$dir/" + # Linux: a desktop entry and hicolor icons, laid out to copy into ~/.local/share. + # (Windows embeds the icon in the exe; macOS ships a bare binary.) + if [ "${{ runner.os }}" = "Linux" ]; then + app_id=dev.redshell.RedShell + install -Dm644 "assets/linux/$app_id.desktop" "$dir/share/applications/$app_id.desktop" + for size in 16 24 32 48 64 128 256 512; do + install -Dm644 "assets/icon/png/redshell-$size.png" \ + "$dir/share/icons/hicolor/${size}x${size}/apps/$app_id.png" + done + fi if [ "${{ runner.os }}" = "Windows" ]; then - 7z a -tzip "$dir.zip" "$dir" >/dev/null - sha256sum "$dir.zip" > "$dir.zip.sha256" + 7z a -tzip "dist/$dir.zip" "$dir" >/dev/null else - tar -czf "$dir.tar.gz" "$dir" - shasum -a 256 "$dir.tar.gz" > "$dir.tar.gz.sha256" + tar -czf "dist/$dir.tar.gz" "$dir" fi - - uses: actions/upload-artifact@v4 + - if: runner.os == 'Linux' + name: Seed the AppImage tools + shell: bash + # cargo-packager downloads AppRun, linuxdeploy and linuxdeploy's AppImage plugin into + # its cache unless they are there, without checking them, and the plugin's + # appimagetool then downloads the AppImage runtime the same way. So all four are + # cached here, checked against these sums, under the names cargo-packager 0.11.8 + # looks for (src/package/appimage/mod.rs), and the plugin is pointed at the runtime. + # linuxdeploy, the plugin and the runtime come from versioned releases instead of + # the moving tags the tools use; AppRun is the packager's own file, which only + # exists under tauri's apprun-old tag. Re-check the names when upgrading the packager. + # The cached AppRun is also made executable for group and others: 0.11.8 would + # cache it without, which appimagetool rejects (crabnebula-dev/cargo-packager#492). + run: | + set -euo pipefail + dir="${XDG_CACHE_HOME:-$HOME/.cache}/.cargo-packager/AppImage" + mkdir -p "$dir" + fetch() { # + curl -fsSL --retry 3 -o "$dir/$1" "$3" + echo "$2 $dir/$1" | sha256sum -c - + chmod 755 "$dir/$1" + } + fetch AppRun-x86_64 f30140a43a0a59e46db21bdefdf749b9e9f2c6946e92afabbacf98b8ae73fb4f \ + https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-x86_64 + fetch linuxdeploy-x86_64.AppImage c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d \ + https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-x86_64.AppImage + fetch linuxdeploy-plugin-appimage.AppImage 992d502a248e14ab185448ddf6f6e7d25558cb84d4623c354c3af350c25fccb3 \ + https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/1-alpha-20250213-1/linuxdeploy-plugin-appimage-x86_64.AppImage + fetch runtime-x86_64 2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d \ + https://github.com/AppImage/type2-runtime/releases/download/20251108/runtime-x86_64 + echo "LDAI_RUNTIME_FILE=$dir/runtime-x86_64" >> "$GITHUB_ENV" + - name: Installers + shell: bash + env: + # Hosted Linux runners have no FUSE; run linuxdeploy's AppImages extracted. + APPIMAGE_EXTRACT_AND_RUN: 1 + run: | + set -euo pipefail + mkdir -p packager-out + cargo packager --release --target "$PACKAGE_TARGET" --formats "${{ matrix.formats }}" \ + --out-dir packager-out + if [ "${{ runner.os }}" = "macOS" ]; then + app=packager-out/RedShell.app + plutil -lint "$app/Contents/Info.plist" + codesign --verify --deep --strict --verbose=2 "$app" + codesign -dv "$app" + lipo -info "$app/Contents/MacOS/redshell" + fi + for file in packager-out/*.deb packager-out/*.AppImage packager-out/*.dmg packager-out/*-setup.exe; do + [ -e "$file" ] || continue + case "$file" in + *-setup.exe) name="$BASE_NAME-setup.exe" ;; + *) name="$BASE_NAME.${file##*.}" ;; + esac + mv "$file" "dist/$name" + done + ls -la dist + - name: Checksums + shell: bash + working-directory: dist + run: | + set -euo pipefail + for file in *; do + if command -v sha256sum >/dev/null; then sha256sum "$file"; else shasum -a 256 "$file"; fi > "$file.sha256" + done + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: ${{ matrix.name }} - path: | - redshell-*.tar.gz* - redshell-*.zip* + path: dist/* publish: - needs: build + needs: [version, build] + permissions: + contents: write # Publish whatever built, so one stuck runner doesn't block a release; re-run # the workflow for the tag to add a missing platform (assets are replaced). - if: ${{ always() && !cancelled() }} + # A manual run with `publish` off stops after the builds. + if: ${{ always() && !cancelled() && needs.version.result == 'success' && (github.event_name == 'push' || inputs.publish) }} runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: dist merge-multiple: true @@ -97,7 +265,7 @@ jobs: run: | ls -la dist ls dist/redshell-* >/dev/null - - uses: softprops/action-gh-release@v2 + - uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: tag_name: ${{ env.TAG }} target_commitish: ${{ github.sha }} diff --git a/CHANGELOG.md b/CHANGELOG.md index b18dc1b..6c7d77d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,161 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and versions follow [Semantic Versioning](https://semver.org/). +## [0.0.2] - 2026-12-01 + +This release gives RedShell its own title bar, makes it feel at home on Windows, and fixes the +rough edges of the first preview: selections in full-screen agents, tmux sessions after a +restart, and a settings panel that rewrote your `config.toml`. + +**Upgrading from 0.0.1.** The configuration file that 0.0.1 created sets `confirm_close_tab`, +`confirm_close_window` and `confirm_quit` to `"always"` and `retain_days` to `0`, and those +lines keep the old behaviour. To get the new defaults, which ask only when work would be lost +and keep recordings for 30 days, delete those four lines from the `[safety]` and `[history]` +sections, or set them yourself: `confirm_close_tab = "running"`, +`confirm_close_window = "multiple_tabs"`, `confirm_quit = "multiple_tabs"` and +`retain_days = 30`. Panes now close when their program ends successfully +(`terminal.close_on_exit = "graceful"`); set it to `"never"` to keep them open. If you saved settings from the 0.0.1 settings panel, your file also contains every +other option; apart from these four, those values match the new defaults and can stay. + +### Added +- Installers for Windows (setup), Linux (.deb, AppImage) and macOS (.dmg). +- An app icon, which the Windows executable carries together with its version information, and + a desktop entry with icons for Linux. +- RedShell looks for a newer release on GitHub shortly after it starts and then once a day, and + offers it in a notification that you can follow or skip for that version. *Check for Updates* + in the command palette checks right away. Nothing is downloaded or installed for you, and + `updates.check = false` (or the switch on the Safety page) turns the check off. +- Tabs have a right-click menu to rename, duplicate or split them, and to close one tab, the + other tabs or the tabs to the right; closing several tabs asks once. +- The window opens again where you closed it, with its size and maximised or full-screen state, + and a new window opens slightly offset from the one it came from. +- *Paste Image* hands a screenshot to an AI agent running on an SSH host, also inside tmux or + screen there: when the clipboard holds an image, `Ctrl+V` (`Alt+V` on Windows) uploads it to + the host and types its path into the prompt. On Windows this includes bitmap-only screenshots + such as the one PrintScreen copies. +- Shell integration loads by itself in bash, zsh, fish and PowerShell without any change to + your profile, so the working directory and prompt jumping work in a fresh install. +- Settings lets you pick the shell from those found on your computer, follow the system's light + or dark mode with a theme for each, and set the font weight, the letter spacing and how much + inactive panes dim. +- Text fields behave like native ones: you can select with the mouse, a double-click or + Shift with the arrows, delete whole words, and cut, copy and paste the selection, also with + `Ctrl+Insert` and `Shift+Insert` and, on Windows and Linux, the terminal's `Ctrl+Shift+C` and + `Ctrl+Shift+V`. +- New keys: `Ctrl+Shift+F` finds in the terminal and `F3` / `Shift+F3` step through the matches, + `Ctrl+Alt+1`…`9` switch tabs on Windows and Linux, `Shift` with the wheel scrolls RedShell's + own scrollback even while a program uses the mouse, and `Ctrl` with the wheel, `Ctrl++` or the + numpad keys zoom. +- `terminal.close_on_exit` decides whether a pane closes when its program ends. + +### Changed +- On Windows the system title bar is gone: the tabs, a sidebar toggle and the window controls, + with snap layouts, share one strip at the top. On macOS the same strip sits beside the traffic + lights, and on Linux below the window manager's title bar. Tabs share its width like browser + tabs, shrinking as you open more, and show short paths with `~` for your home folder. +- The sidebar shows your open sessions and SSH hosts by default. Shells, agents, tmux and screen + sessions and recent history can be turned on in Settings → Appearance, you can resize the + sidebar by dragging its edge or hide it with the toggle in the title bar, and the permanent + recording badge is gone. +- RedShell asks before closing only when work would be lost: closing a tab asks while a program + runs in it, and closing a window or quitting asks when more than one tab is open or a program + runs. A pane whose program exits successfully closes, one that fails stays open with its + error, and closing the last tab closes the window. +- Recordings are kept for 30 days by default instead of forever; pinned sessions are still kept + until you delete them. +- The settings panel edits `config.toml` in place and changes only the keys you changed, so your + comments, order and formatting stay. A file with an error is never overwritten: until it is + fixed, changes apply without being saved and a notification offers to open the file. +- Zoom applies to the current window and is no longer saved, and `Ctrl+0` returns to your + configured font size. +- On Windows, `Ctrl+C` copies the selection or interrupts the program when nothing is selected, + and `Ctrl+V` pastes, as in Windows Terminal. `Ctrl+Insert` and `Shift+Insert` copy and paste + on Windows and Linux. +- `Ctrl+K` reaches the shell immediately, because the theme picker no longer has a key chord; + it stays in the command palette and Settings. Searching all sessions moved to + `Ctrl+Shift+Alt+F`. +- The mouse wheel scrolls three lines per notch on Windows and Linux instead of nine. +- The status bar is quieter: the theme name and shortcut hints are gone, and the grid size only + appears while a pane is being resized. +- *Edit config.toml* opens the file in the system editor unless `$VISUAL` or `$EDITOR` names a + terminal editor. +- On Windows, RedShell no longer polls tmux through WSL in the background, which kept the WSL + virtual machine running; WSL sessions are listed when you open the session manager or show + them in the sidebar. +- The session manager lists an SSH host's sessions and windows over a single connection instead + of one per session, which on Windows took a full SSH handshake each. It shows the sessions it + found last time right away while it checks again, and keeps them on screen with the error when + the host can't be reached. Its name field has the keyboard when it opens. +- The sidebar's tmux section also lists the sessions on SSH hosts you have a tab open on, and on + hosts set up with `attach_session`, each under its host's name. Hosts with an open tab are + checked about once a minute without ever prompting for a password; one that can't be reached + says why in one line and is tried again after five minutes. +- The sidebar's edge can be grabbed on the border line itself and just beside it. +- The settings panel and dialogs fit into small windows and scroll, the Keybindings page reads + as plain command names and keys, and messages throughout the app are written in plain words. + +### Fixed +- Selecting text in full-screen programs such as Claude Code and Codex works: the selection no + longer disappears when they repaint, and mouse drags and motion are reported to programs that + ask for them. +- Closing a tab or quitting no longer types Enter and Ctrl+D into the program, which could log + out the shell inside tmux and end the session. +- tmux sessions attached natively come back after a restart. A tab attached to a session that + has since ended shows tmux's error instead of creating a new session, re-attaching `work` no + longer picks `work2`, and a failed attach says why. +- Tabs come back after a restart with their split panes, the name you gave them and the same + tab and pane active, instead of every pane opening as a tab of its own. A tab's name belongs + to the tab, so it stays when you split it or click another of its panes. +- The background image shows behind the text again, transparent and blurred windows no longer + stack their backgrounds, the sidebar and title bar follow the window's transparency, and + changing `window_background` applies without a restart. +- `letter_spacing` had no effect. +- On Windows, the working directory is tracked (OSC 7, Git Bash paths and OSC 9;9 from + PowerShell, oh-my-posh and Starship), so new tabs and splits open in the right folder, and + RedShell can tell an idle shell from a running program when deciding whether to ask before + closing. +- With a Russian layout, `Ctrl` with keys such as `Х` and `Ъ` sends the same control codes as + their Latin counterparts. +- App shortcuts no longer fire behind an open dialog, so keys reach the dialog's input; quitting + and full screen still work there. +- Pasting with the right or middle mouse button asks before pasting several lines, like the + paste key does. +- Shell integration reports the exit status in zsh, handles folders containing `%`, keeps your + own bash `DEBUG` trap, and no longer wraps the PowerShell prompt twice. +- Long titles and paths end with an ellipsis instead of spilling out, and tooltips with long + paths no longer overlap their second line. +- Typing into the find bar reaches it again. +- Attaching to, killing or renaming tmux sessions over SSH works when the remote login shell is + zsh, and restored WSL tmux tabs reopen in the distribution they ran in. +- A program ended by a signal reports 128 plus the signal's number, as a shell does: 130 after + Ctrl+C, so a pane set to close on a clean exit closes after it, and 139 after a crash. +- Saving a setting keeps config.toml's file permissions, keeps comments with their SSH host when + a host is removed, and keeps sidebar sections added by a newer version. +- zsh shell integration loads when the data folder contains spaces, as it does on macOS, and on + Windows the working directory reported by Cygwin, or by Git Bash on a computer with a DNS host + name, is followed too. +- Closing a WSL tab on Windows, whether opened with `wsl.exe` or the `bash.exe` that starts WSL, + asks first, because the programs running inside it can't be seen from Windows. +- The config editor tab asks before closing and is not reopened after a restart, splitting or + duplicating it opens a shell instead of a second editor, and an `$EDITOR` with quotes or + spaces in its path works. +- A confirmed multi-line paste goes to the pane it came from, even after switching tabs. +- The plugins dialog takes the keyboard and closes with Esc. +- Paste Image no longer holds back Ctrl+V while an upload runs, and an upload gives up once it + stops making progress, so a large screenshot gets through a slow link. +- Duplicating a tmux tab opened as tabs opens a new window in that session. +- Clicking the tab bar while a dialog is open only switches tabs, so a half-finished dialog is + never lost. +- Several keys bound to the same command in `[keybindings]` all work. +- Closing the last window notifies plugins and saves history the same way quitting does. +- A host where tmux has never run lists no sessions instead of an "error connecting" message, and + listing or killing sessions over SSH gives up after 30 seconds when the host stops answering. + +### Security +- On Windows, a working directory reported by a program is only used when it is a local drive + path or a share of a local WSL distribution. Other network paths are ignored, because merely + checking one makes Windows authenticate to that host. + ## [0.0.1] - 2026-11-30 First public preview. @@ -27,4 +182,5 @@ First public preview. themes; settings UI for fonts, opacity, background image, cursor, safety, history and keybindings; hot-reloaded `config.toml`. +[0.0.2]: https://github.com/redstone-md/RedShell/compare/v0.0.1...v0.0.2 [0.0.1]: https://github.com/redstone-md/RedShell/releases/tag/v0.0.1 diff --git a/Cargo.lock b/Cargo.lock index 95c7a4a..ccc924a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4604,7 +4604,7 @@ dependencies = [ [[package]] name = "redshell-agents" -version = "0.0.1" +version = "0.0.2" dependencies = [ "redshell-core", "which 8.0.6", @@ -4612,14 +4612,16 @@ dependencies = [ [[package]] name = "redshell-app" -version = "0.0.1" +version = "0.0.2" dependencies = [ "anyhow", "chrono", "dirs 6.0.0", + "embed-resource", "env_logger", "futures", "gpui", + "image", "log", "parking_lot", "redshell-agents", @@ -4630,26 +4632,36 @@ dependencies = [ "redshell-terminal", "redshell-theme", "redshell-ui", + "semver", + "serde", + "serde_json", + "tempfile", + "tokio", "uuid", "which 8.0.6", + "windows 0.61.3", + "zed-reqwest", ] [[package]] name = "redshell-core" -version = "0.0.1" +version = "0.0.2" dependencies = [ "anyhow", "dirs 6.0.0", + "semver", "serde", + "serde_json", "tempfile", "toml 0.9.12+spec-1.1.0", + "toml_edit 0.25.21+spec-1.1.0", "uuid", "which 8.0.6", ] [[package]] name = "redshell-history" -version = "0.0.1" +version = "0.0.2" dependencies = [ "anyhow", "chrono", @@ -4667,7 +4679,7 @@ dependencies = [ [[package]] name = "redshell-plugin" -version = "0.0.1" +version = "0.0.2" dependencies = [ "anyhow", "crossbeam-channel", @@ -4683,21 +4695,23 @@ dependencies = [ [[package]] name = "redshell-remote" -version = "0.0.1" +version = "0.0.2" dependencies = [ "anyhow", + "chrono", "crossbeam-channel", "dirs 6.0.0", "log", "parking_lot", "redshell-core", "tempfile", + "uuid", "which 8.0.6", ] [[package]] name = "redshell-terminal" -version = "0.0.1" +version = "0.0.2" dependencies = [ "alacritty_terminal", "anyhow", @@ -4707,11 +4721,12 @@ dependencies = [ "portable-pty", "redshell-core", "redshell-theme", + "windows-sys 0.61.2", ] [[package]] name = "redshell-theme" -version = "0.0.1" +version = "0.0.2" dependencies = [ "anyhow", "gpui", @@ -4721,11 +4736,12 @@ dependencies = [ [[package]] name = "redshell-ui" -version = "0.0.1" +version = "0.0.2" dependencies = [ "gpui", "redshell-core", "redshell-theme", + "unicode-segmentation", ] [[package]] @@ -6095,6 +6111,7 @@ dependencies = [ "indexmap", "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", + "toml_writer", "winnow 1.0.5", ] diff --git a/Cargo.toml b/Cargo.toml index ed9fc19..467aec2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ members = [ default-members = ["crates/redshell-app"] [workspace.package] -version = "0.0.1" +version = "0.0.2" edition = "2024" license = "MIT" repository = "https://github.com/redstone-md/RedShell" @@ -36,7 +36,9 @@ portable-pty = "0.9" rusqlite = { version = "0.37", features = ["bundled"] } serde = { version = "1", features = ["derive"] } serde_json = "1" +semver = "1" toml = "0.9" +toml_edit = "0.25" anyhow = "1" thiserror = "2" parking_lot = "0.12" diff --git a/README.md b/README.md index 0b1f390..e0a6a55 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,182 @@ +
+ +RedShell icon + # RedShell -A fast, modular terminal workspace written in Rust on [GPUI](https://www.gpui.rs/), the -GPU-accelerated UI framework behind Zed. - -RedShell is a terminal emulator plus a session manager. It records every session so you can -search and restore it later, opens SSH hosts and AI coding agents as tabs, manages tmux and -screen sessions natively, and makes it hard to close something by accident. - -![RedShell main window: sidebar with sessions, shells, agents, SSH hosts and tmux, and a tab running git log and tests](docs/screenshots/main.png) - -> **RU, коротко.** RedShell — лёгкий кроссплатформенный терминал на Rust + GPUI. Он побайтово -> записывает каждую сессию в SQLite с полнотекстовым поиском и восстанавливает вкладки со -> скроллбэком после перезапуска. Внутри — SSH-клиент (через системный OpenSSH и -> `~/.ssh/config`), запуск AI-агентов (Claude Code, Codex, Gemini CLI, Aider и др.) и -> нативное управление tmux/screen: локально, по SSH и через WSL на Windows. Есть плагины -> (Rust, `plugin.toml` или хук-процесс на любом языке), темы shadcn/tweakcn (CSS вставляется -> как есть) и защита от случайного закрытия: Enter и Esc в диалоге *отменяют*, подтверждение — -> только кликом или Ctrl+Enter. - ---- - -## Highlights - -| | | -|---|---| -| **Fast, light** | GPU rendering through GPUI and alacritty's VT parser. PTY output coalesces into one repaint per frame. The release build uses LTO and is stripped. | -| **History** | Every byte of output is stored with a timestamp in SQLite. Output, commands and titles are indexed with FTS5. You can view any past session read-only, restore it as a live tab with its scrollback, or export it as an [asciicast](https://docs.asciinema.org/manual/asciicast/v2/) file. | -| **Restore** | Open tabs survive restarts, crashes and `kill -9`: they come back in the same directory with their scrollback replayed. With `multiplexer.auto_attach_local`, tabs run inside tmux and re-attach live. | -| **Hard to close** | Closing a tab, closing a window and quitting each ask first (configurable). **Enter and Esc cancel.** You confirm only by clicking or pressing Ctrl/⌘+Enter, and you can also require typing a word. Closing the last tab opens a fresh one, and a finished process keeps its tab open. | -| **SSH** | Hosts come from `~/.ssh/config` and `[[ssh.hosts]]`. RedShell drives the system OpenSSH, so agent forwarding, FIDO keys, ProxyJump and ControlMaster all work. A host can auto-attach to a remote tmux or screen session. | -| **tmux / screen** | A native manager lists, attaches, creates and kills sessions and shows tmux windows. It works locally, on any SSH host, and on Windows through a native tmux build or WSL. | -| **Native tmux** | *Attach tmux Session Natively…* (or *Attach natively* in the manager) drives tmux through control mode (`tmux -C`), like iTerm2: every tmux window becomes a RedShell tab and every pane a native pane with its own scrollback, search and history recording. Splits follow tmux's layout, and splitting a native pane splits it in tmux. Closing a tab asks whether to detach (the default, the window keeps running) or kill the tmux window; quitting RedShell or losing the connection only detaches. Needs tmux 3.2 or newer; over SSH it needs key or agent authentication. | -| **AI agents** | Claude Code, Codex CLI, Gemini CLI, Copilot CLI, opencode, Aider, Cursor Agent, Qwen Code, Goose and Crush are detected on `PATH` and start in the current tab's folder. Add your own with `[[agents.custom]]`. | -| **Plugins** | Rust `Plugin` trait, declarative `plugin.toml` (commands, profiles, themes, snippets), and hook processes in any language that speak JSON lines. | -| **Themes** | The UI uses shadcn/ui tokens, so any [tweakcn](https://tweakcn.com) CSS export works as-is: drop the file into `themes/` or use *Import tweakcn Theme from Clipboard*. The theme picker previews live. Built in: RedShell (light and dark), Neutral, Nebula, Catppuccin Mocha, Tokyo Night, Nord, Gruvbox, Rosé Pine, Solarized Light. | -| **Customisable** | Fonts, line height, padding, cursor, opacity, transparent or blurred window, background image, tab bar position, sidebar, status bar and every keybinding. `config.toml` hot-reloads. | -| **Cross-platform** | Linux (X11 and Wayland), macOS, Windows (ConPTY). | - -## Screenshots - -| | | -|---|---| -| ![Split panes](docs/screenshots/splits.png) | ![Command palette](docs/screenshots/palette.png) | -| **Split panes** | **Command palette** | -| ![Theme grid in Settings](docs/screenshots/themes.png) | ![Full-text search across all recorded sessions](docs/screenshots/search.png) | -| **Themes** | **Search across sessions** | -| ![tmux session manager](docs/screenshots/mux.png) | ![In-pane find with highlighted matches](docs/screenshots/find.png) | -| **tmux / screen manager** | **Find in terminal** | -| ![RedShell Light theme with split panes](docs/screenshots/light.png) | | -| **Light theme** | | - -Screenshots are taken headlessly with [`scripts/screenshot.sh`](scripts/screenshot.sh). +A fast terminal for Windows, Linux and macOS that remembers every session, brings your tabs back +after a restart and keeps your SSH hosts, tmux sessions and AI coding agents a keystroke away. + +[![Release](https://img.shields.io/github/v/release/redstone-md/RedShell?include_prereleases&sort=semver)](https://github.com/redstone-md/RedShell/releases) +[![CI](https://github.com/redstone-md/RedShell/actions/workflows/ci.yml/badge.svg)](https://github.com/redstone-md/RedShell/actions/workflows/ci.yml) +[![License: MIT](https://img.shields.io/github/license/redstone-md/RedShell)](LICENSE) + +
+ +![RedShell with three tabs in the title bar, a sidebar listing the open sessions, SSH hosts and tmux sessions, and a git log and a test run in ~/src/aurora](docs/screenshots/main.png) + +> **RU, коротко.** RedShell — быстрый кроссплатформенный терминал на Rust + GPUI. Он побайтово +> записывает каждую сессию в SQLite с полнотекстовым поиском и после перезапуска возвращает +> вкладки со скроллбэком, в том числе подключённые к tmux. Внутри — SSH (через системный OpenSSH +> и `~/.ssh/config`), запуск AI-агентов (Claude Code, Codex, Gemini CLI, Aider и др.) и нативное +> управление tmux/screen: локально, по SSH и через WSL на Windows. В Claude Code и Codex работает +> выделение мышью, а скриншот из буфера обмена можно вставить агенту на SSH-сервере. Вкладки +> живут в заголовке окна, боковая панель настраивается, `config.toml` правится на месте с +> сохранением комментариев. Терминал спрашивает перед закрытием, только когда можно потерять +> работу (Enter и Esc в диалоге *отменяют*), сам подхватывает интеграцию с bash, zsh, fish и +> PowerShell и раз в день проверяет, не вышла ли новая версия. Есть плагины (Rust, `plugin.toml` +> или хук-процесс на любом языке) и темы shadcn/tweakcn (CSS вставляется как есть). + +## Why RedShell + +Most terminals forget everything the moment you close a tab. RedShell records every session to a +local database, so you can find what a command printed last week, replay it, or reopen it as a +live tab with its scrollback, and the tabs you had open come back after a restart or a crash. It +also gathers what you would otherwise juggle in separate windows: the SSH hosts from your +`~/.ssh/config`, tmux and screen sessions on any machine, and AI coding agents such as Claude Code +and Codex, which open as ordinary tabs in the folder you are working in. It is written in Rust on +[GPUI](https://www.gpui.rs/), the GPU-accelerated UI framework behind Zed, on top of alacritty's +VT parser, so it starts quickly and stays light. + +## Features + +### Every session, searchable + +Every byte a program prints is stored with a timestamp in SQLite, and the output, commands and tab +titles are indexed for full-text search. *Search All Sessions* finds a line across everything you +have run, and from a result you can view the recording read-only, restore it as a live tab with +its scrollback, open it in a new window or export it as an +[asciicast](https://docs.asciinema.org/manual/asciicast/v2/) file. Recordings are kept for 30 +days by default, and pinned sessions stay until you delete them. + +![Search across all recorded sessions for "deploy", with live and ended sessions and the commands and output that matched](docs/screenshots/search.png) + +### Tabs and panes that come back + +Tabs sit in the title bar and share its width like browser tabs, shrinking as you open more and +showing short paths with `~` for your home folder. Split a tab into panes, drag the line between +them to resize, and double-click it to make them equal again. Right-click a tab to rename, +duplicate or split it, or to close it, the other tabs or the tabs to its right. + +Open tabs survive restarts, crashes and `kill -9`: they come back with their split panes and +names, in the same folder with their scrollback replayed, and tabs attached to a tmux or screen +session re-attach to it live. The +window itself reopens with the size and position you left it at. + +![A tab split into three panes: a git log on the left, a test run on the right and a deploy below it](docs/screenshots/splits.png) + +

+The right-click menu of a tab with Rename, Duplicate, Split Right, Split Down, Close, Close Other Tabs and Close Tabs to the Right +The command palette filtered to the two split commands and their keys +

+ +Every command, with its key, is in the command palette, and the sidebar lists your open sessions +and SSH hosts. In Settings you can add shells, agents, tmux and screen sessions and recent history +to the sidebar, and you can drag its edge to make it wider or hide it with the button in the title +bar. + +### SSH, tmux and screen + +Hosts come from `~/.ssh/config` and `[[ssh.hosts]]`. RedShell drives the system OpenSSH, so agent +forwarding, FIDO keys, ProxyJump and ControlMaster all work, and a host can drop you straight into +a remote tmux or screen session. The session manager lists, attaches, creates and kills sessions +on this computer, on any SSH host and, on Windows, through a native tmux build or WSL. It lists a +host in one connection and shows what it found last time while it asks again, and the sidebar's +tmux section also lists the sessions on the SSH hosts you have tabs open on, checking each about +once a minute. + +*Open tmux Session as Tabs…*, or *Open as tabs* in the manager, drives tmux through control +mode (`tmux -C`) the way iTerm2 does: every tmux window becomes a RedShell tab and every pane a +native pane with its own scrollback, search and history. Splits follow tmux's layout, splitting a +native pane splits it in tmux, and closing a tab asks whether to detach (the default) or kill the +tmux window. After a restart RedShell attaches to the same sessions again, and if one has ended +in the meantime it tells you instead of creating a new one. Native attach needs tmux 3.2 or newer, +and over SSH it needs key or agent authentication. + +![The tmux session manager with the local computer and three SSH hosts as targets, and three sessions with their windows](docs/screenshots/mux.png) + +### Made for AI coding agents + +Claude Code, Codex CLI, Gemini CLI, GitHub Copilot CLI, opencode, Aider, Cursor Agent, Qwen Code, +Goose and Crush are found on `PATH` and start in the current tab's folder, and `[[agents.custom]]` +adds your own. Selecting text works in them as you would expect: the selection stays put while the +agent repaints its screen, and mouse drags reach agents that track the mouse themselves. When an +agent runs on an SSH host, *Paste Image* uploads a screenshot from your clipboard and types its +path into the prompt, [as described below](#pasting-images-into-remote-agents). + +### Asks before you lose work + +Closing a tab asks while a program is running in it, and closing a window or quitting asks when +more than one tab is open or a program is running. In these dialogs **Enter and Esc cancel**: you +confirm by clicking or with Ctrl+Enter (⌘+Enter on macOS), and you can also require typing a word. +A pane closes by itself when its program exits successfully and stays open to show the error when +it fails, and closing the last tab closes the window, as in other terminals. All of this can be +changed in `[safety]` and `terminal.close_on_exit`. + +### Find in the terminal + +Find highlights every match in the pane's scrollback and steps through them, with switches for +case and regular expressions. + +![Find in the terminal with "auth" highlighted seven times in a git log and a test run](docs/screenshots/find.png) + +### Themes and settings + +The interface uses shadcn/ui tokens, so any [tweakcn](https://tweakcn.com) CSS export works as it +is: drop the file into `themes/` or use *Import tweakcn Theme from Clipboard*, and the theme picker +previews it live. RedShell ships with RedShell (light and dark), Neutral (light and dark), Nebula, +Catppuccin Mocha, Tokyo Night, Nord, Gruvbox, Rosé Pine and Solarized Light, and it can follow +your system's light or dark mode with a theme for each. + +The Settings panel covers fonts, weight and letter spacing, line height, padding, the cursor, a +transparent or blurred window, a background image, the tab bar and sidebar, the shell, safety, +history and keybindings. It writes only the options you change into `config.toml`, keeping your +comments and the order of your keys, and edits you make to the file by hand apply as soon as you +save it. Zoom applies to the current window and leaves your configured font size alone. + +![The theme grid in Settings, with the option to match the system appearance](docs/screenshots/themes.png) + +![The RedShell Light theme with a tab split into two panes](docs/screenshots/light.png) ## Install -Download an archive for your platform from -[Releases](https://github.com/redstone-md/RedShell/releases), unpack it and run `redshell` -(`redshell.exe` on Windows). Each archive has a `.sha256` checksum next to it. +Every [release](https://github.com/redstone-md/RedShell/releases) has an installer and a +portable archive for each platform, each with a `.sha256` checksum next to it. To update, install +the newer release the same way; your settings and history are kept. + +**Windows.** Run `redshell--windows-x86_64-setup.exe`. It installs for your user only, +without an administrator prompt, adds RedShell to the Start menu and the desktop (untick the +desktop shortcut on the last page if you don't want it), and registers an uninstaller under +Apps & Features. Uninstalling leaves your settings and history in `%APPDATA%\redshell`. +Builds are not code-signed yet, so SmartScreen warns on the first run: choose *More info*, then +*Run anyway*. The portable `windows-x86_64.zip` holds `redshell.exe`, which runs from any folder. + +**Linux.** On Debian, Ubuntu and their derivatives, install the `.deb`, which pulls in the +libraries RedShell needs (Vulkan loader and driver, xkbcommon, Wayland, X11): + +```sh +sudo apt install ./redshell--linux-x86_64.deb +``` + +On other distributions, use the AppImage: make it executable with +`chmod +x redshell--linux-x86_64.AppImage` and run it. The `.tar.gz` holds the bare +binary plus a desktop entry and icons; to get the launcher entry, copy the binary onto your +`PATH` and the bundled `share` folder into `~/.local`: + +```sh +install -Dm755 redshell ~/.local/bin/redshell +cp -r share ~/.local/ +``` + +**macOS.** Open `redshell--macos-universal.dmg` and drag RedShell into Applications. +The app runs natively on Apple silicon and Intel Macs with macOS 10.15.7 or newer. It is not +notarized yet, so the first time, right-click RedShell in Applications, choose *Open*, then +*Open* again in the dialog; after that it starts normally. On recent macOS versions where that +dialog only offers *Done*, allow it under *System Settings → Privacy & Security → Open Anyway*. -Linux builds need the runtime libraries GPUI uses (Vulkan loader, xkbcommon, Wayland/X11, -fontconfig), which desktop distributions already ship. Pre-1.0 builds are not code-signed, so -macOS Gatekeeper and Windows SmartScreen will ask before the first start. +RedShell checks GitHub for a newer release once a day and tells you when there is one; you +download and install it yourself. Turn this off with `updates.check = false` (see +[docs/CONFIG.md](docs/CONFIG.md#updates)). ## Build @@ -73,70 +189,129 @@ cargo run --release # binary: target/release/redshell cargo test --workspace # unit and integration tests (PTY, SQLite, tmux, plugins) ``` -macOS needs Xcode command-line tools. Windows needs the MSVC toolchain. +macOS needs Xcode command-line tools. Windows needs the MSVC toolchain. The Rust version is pinned +in [`rust-toolchain.toml`](rust-toolchain.toml). `REDSHELL_HOME=/some/dir` keeps config and data in one folder, which is useful for portable installs and testing. -## Default keys - -Linux and Windows use Ctrl+Shift so that plain Ctrl stays with the shell. On macOS, read -`ctrl-shift` as `⌘`. - -| Action | Key | -|---|---| -| Command palette | `Ctrl+Shift+P` | -| Open profile (shell, agent, SSH, plugin) | `Ctrl+Shift+O` | -| Launch AI agent / connect SSH | `Ctrl+Shift+I` / `Ctrl+Shift+S` | -| Search all sessions | `Ctrl+Shift+F` | -| Session history | `Ctrl+Shift+H` | -| In history / search: pin, open in new window, delete | `Alt+P` / `Alt+Enter` / `Shift+Delete` | -| tmux / screen manager | `Ctrl+Shift+M` | -| Attach tmux natively | palette: *Attach tmux Session Natively…* (`mux.attach_native`) | -| New / close tab | `Ctrl+Shift+T` / `Ctrl+Shift+W` | -| Split right / down | `Ctrl+Shift+D` / `Ctrl+Shift+Alt+D` | -| Next / previous pane | `Ctrl+Shift+]` / `Ctrl+Shift+[` | -| Go to tab N | `Alt+1…9` | -| Copy / paste | `Ctrl+Shift+C` / `Ctrl+Shift+V` | -| Find in terminal | `Ctrl+Shift+G` (macOS `⌘F`); `Enter` / `Shift+Enter` older / newer match, `Alt+C` case, `Alt+R` regex, `Esc` close | -| Open link (URL or OSC 8 hyperlink) | `Ctrl`+click, underlined while `Ctrl` is held (macOS `⌘`) | -| Previous / next prompt | `Ctrl+Shift+Z` / `Ctrl+Shift+X` (macOS `⌘↑` / `⌘↓`) | -| Zoom | `Ctrl+=` / `Ctrl+-` / `Ctrl+0` | -| Settings | `Ctrl+,` | -| Theme picker | `Ctrl+K Ctrl+T` | -| Quit | `Ctrl+Shift+Q` | - -You can rebind any key in `[keybindings]`. The palette lists every command id. - -With the mouse, drag the line between split panes to resize them; double-click it to make the -panes equal again. Drag tabs to reorder them, hover a tab for its full title and folder, and -middle-click a tab to close it (with the usual confirmation). - -## Shell integration (optional) - -Source the script for your shell from [`shell-integration/`](shell-integration). It reports the -working directory (OSC 7) and exact command boundaries (OSC 133). Prompt marks also enable -*Jump to Previous/Next Prompt*. Without it, RedShell falls back to reading the prompt line when -you press Enter. +## Keyboard shortcuts + +On Windows and Linux RedShell's own keys use Ctrl+Shift or Ctrl+Alt, so that plain Ctrl and Alt +keys such as Ctrl+K, Ctrl+R and Alt+1 stay with the shell. Windows follows Windows Terminal for the +clipboard: Ctrl+C copies when text is selected and interrupts the program otherwise, and Ctrl+V +pastes. + +| Action | Windows | Linux | macOS | +|---|---|---|---| +| Command palette | `Ctrl+Shift+P` | `Ctrl+Shift+P` | `⌘⇧P` | +| Open a profile (shell, agent, SSH host, plugin) | `Ctrl+Shift+O` | `Ctrl+Shift+O` | `⌘O` | +| Launch an AI agent | `Ctrl+Shift+I` | `Ctrl+Shift+I` | `⌘⇧I` | +| Connect to an SSH host | `Ctrl+Shift+S` | `Ctrl+Shift+S` | `⌘⇧S` | +| tmux / screen sessions | `Ctrl+Shift+M` | `Ctrl+Shift+M` | `⌘⇧M` | +| New tab / close tab | `Ctrl+Shift+T` / `Ctrl+Shift+W` | `Ctrl+Shift+T` / `Ctrl+Shift+W` | `⌘T` / `⌘W` | +| Rename tab | `Ctrl+Shift+R` | `Ctrl+Shift+R` | `⌘⇧R` | +| Next / previous tab | `Ctrl+Tab` / `Ctrl+Shift+Tab` | `Ctrl+Tab` / `Ctrl+Shift+Tab` | `⌘⇧]` / `⌘⇧[` | +| Go to tab 1…8 / last tab | `Ctrl+Alt+1…8` / `Ctrl+Alt+9` | `Ctrl+Alt+1…8` / `Ctrl+Alt+9` | `⌘1…8` / `⌘9` | +| Move tab left / right | `Ctrl+Shift+PgUp` / `PgDn` | `Ctrl+Shift+PgUp` / `PgDn` | none | +| Split right / down | `Ctrl+Shift+D` / `Ctrl+Shift+Alt+D` | `Ctrl+Shift+D` / `Ctrl+Shift+Alt+D` | `⌘D` / `⌘⇧D` | +| Next / previous pane | `Ctrl+Shift+]` / `Ctrl+Shift+[` | `Ctrl+Shift+]` / `Ctrl+Shift+[` | `⌘]` / `⌘[` | +| Close pane | `Ctrl+Shift+Alt+W` | `Ctrl+Shift+Alt+W` | `⌘⌥W` | +| Copy | `Ctrl+C` with a selection, `Ctrl+Shift+C`, `Ctrl+Insert` | `Ctrl+Shift+C`, `Ctrl+Insert` | `⌘C` | +| Paste | `Ctrl+V`, `Ctrl+Shift+V`, `Shift+Insert` | `Ctrl+Shift+V`, `Shift+Insert` | `⌘V` | +| Paste an image into an agent on an SSH host | `Alt+V` | `Ctrl+V` | `Ctrl+V` | +| Select all | `Ctrl+Shift+A` | `Ctrl+Shift+A` | `⌘A` | +| Find in the terminal | `Ctrl+Shift+F` | `Ctrl+Shift+F` | `⌘F` | +| Older / newer match | `F3` / `Shift+F3` | `F3` / `Shift+F3` | `⌘G` / `⌘⇧G` | +| Search all sessions | `Ctrl+Shift+Alt+F` | `Ctrl+Shift+Alt+F` | `⌘⇧F` | +| Session history | `Ctrl+Shift+H` | `Ctrl+Shift+H` | `⌘⇧H` | +| Insert a snippet | `Ctrl+Shift+E` | `Ctrl+Shift+E` | `⌘⇧E` | +| Previous / next prompt | `Ctrl+Shift+Z` / `Ctrl+Shift+X` | `Ctrl+Shift+Z` / `Ctrl+Shift+X` | `⌘↑` / `⌘↓` | +| Clear scrollback | `Ctrl+Shift+K` | `Ctrl+Shift+K` | `⌘K` | +| Scroll a page up / down | `Shift+PgUp` / `Shift+PgDn` | `Shift+PgUp` / `Shift+PgDn` | `⇧PgUp` / `⇧PgDn` | +| Scroll to the top / bottom | `Ctrl+Shift+Home` / `End` | `Ctrl+Shift+Home` / `End` | `⌘Home` / `⌘End` | +| Zoom in / out / reset | `Ctrl+=` or `Ctrl++` / `Ctrl+-` / `Ctrl+0` | `Ctrl+=` or `Ctrl++` / `Ctrl+-` / `Ctrl+0` | `⌘=` / `⌘-` / `⌘0` | +| Toggle the sidebar | `Ctrl+Shift+B` | `Ctrl+Shift+B` | `⌘B` | +| Full screen | `F11` | `F11` | `⌃⌘F` | +| Settings | `Ctrl+,` | `Ctrl+,` | `⌘,` | +| New window | `Ctrl+Shift+N` | `Ctrl+Shift+N` | `⌘N` | +| Quit | `Ctrl+Shift+Q` | `Ctrl+Shift+Q` | `⌘Q` | + +Zooming also works with `Ctrl` (`⌘` on macOS) and the numpad `+` and `-` keys. In the find bar, `Enter` +and `Shift+Enter` step to the older and newer match, `Alt+C` toggles case, `Alt+R` regular +expressions and `Esc` closes it. In session history and search, `Alt+P` pins a session, +`Alt+Enter` opens it in a new window, `Shift+Delete` deletes it and `Ctrl+Enter` (`⌘Enter`) +restores it as a live tab. Commands without a default key, such as *Select Theme…* and *Open +tmux Session as Tabs…*, are in the palette, and you can rebind any command in `[keybindings]`; +the palette shows every command id. + +With the mouse, drag tabs to reorder them, hover a tab for its full title and folder, double-click +it to rename it and middle-click it to close it (with the usual confirmation). In the terminal, +drag to select text (double-click selects a word, triple-click a line), right-click to copy the +selection or paste when there is none, and middle-click to paste. Programs that use the mouse +themselves, such as Claude Code, vim or htop, receive clicks, drags and the wheel instead; hold +`Shift` (on macOS also `Option`) to select text in them as usual, and `Shift` with the wheel to +scroll RedShell's own scrollback. `Ctrl` with the wheel changes the font size. + +## Pasting images into remote agents + +AI agents such as Claude Code, Codex and Gemini CLI read a pasted screenshot straight from the +clipboard, which an agent running on an SSH host cannot see. In those panes RedShell's +*Paste Image* key (`Ctrl+V`, or `Alt+V` on Windows, the keys Claude Code uses) acts while the +clipboard holds an image and no text: it uploads the image to `~/.cache/redshell/paste` on the +host and types the file's path into the prompt, which the agents attach like a pasted image. +This works for SSH tabs and for tmux or screen sessions on an SSH host, attached normally or +natively. On Windows it also picks up bitmap-only screenshots, such as the one PrintScreen +copies. Everywhere else, WSL included (Claude Code reads the Windows clipboard from there), and +whenever the clipboard holds text, the key goes to the program as usual. + +The upload is a separate `ssh` connection with the tab's host and options in batch mode, so it +needs key or agent authentication (a password prompt cannot be answered) and reuses a +`ControlMaster` connection when your `~/.ssh/config` sets one up. Uploaded files are readable +only by you and are deleted after a week, at the next upload. Turn this off with +`terminal.paste_image_upload = false`. + +## Shell integration + +New tabs running bash, zsh, fish or PowerShell load RedShell's integration script from +[`shell-integration/`](shell-integration) automatically, after your own startup files, so there is +no profile to edit. It reports the working directory (OSC 7, or OSC 9;9 from PowerShell) and exact +command boundaries (OSC 133). Prompt marks also enable *Jump to Previous/Next Prompt*. Prompts +that already report the directory with OSC 9;9, such as oh-my-posh and Starship on Windows, are +understood as well. Without integration, RedShell falls back to reading the prompt line when you +press Enter. + +Turn it off with `terminal.shell_integration = false`; the +[configuration reference](docs/CONFIG.md#shell-integration) explains how each shell is started. +When a shell starts with arguments of your own (say `bash --norc`), source the script yourself: ```sh # ~/.bashrc [ -n "$REDSHELL_SESSION" ] && source ~/RedShell/shell-integration/redshell.bash ``` -## Documentation +## Configuration + +RedShell reads `config.toml` from `~/.config/redshell` on Linux, +`~/Library/Application Support/redshell` on macOS and `%APPDATA%\redshell` on Windows, and writes +a commented template there on first start. Every key is optional. The [configuration reference](docs/CONFIG.md) +describes each section, from fonts and the sidebar to safety, history, SSH hosts, agents, update +checks and keybindings, along with how to write your own themes. -* [Configuration reference](docs/CONFIG.md) -* [Writing plugins](docs/PLUGINS.md), with a full example in [`examples/plugins/hello`](examples/plugins/hello) -* [Architecture](docs/ARCHITECTURE.md) +## Plugins -## Workspace layout +Plugins add commands, launch profiles, themes and snippets. They can be written against the Rust +`Plugin` trait, declared in a `plugin.toml` file, or run as a hook process in any language that +speaks JSON lines. [Writing plugins](docs/PLUGINS.md) walks through all three, with a full example +in [`examples/plugins/hello`](examples/plugins/hello). + +## Project layout ``` crates/ redshell-core settings, Launchable/LaunchProfile, commands, events, fuzzy matcher redshell-theme shadcn token model, tweakcn CSS importer (oklch/hsl/hex), registry - redshell-terminal PTY + VT engine, input/mouse encoding, render snapshots, OSC 7/133 + redshell-terminal PTY + VT engine, input/mouse encoding, render snapshots, OSC 7/9;9/133 redshell-history SQLite + FTS5 recorder, search, restore, asciicast export redshell-remote SSH profiles, ~/.ssh/config, tmux/screen over local/SSH/WSL redshell-agents AI agent detection and launch profiles @@ -145,6 +320,9 @@ crates/ redshell-app the application (workspace, terminal view, palette, settings) ``` +[Architecture](docs/ARCHITECTURE.md) explains how the crates fit together. Screenshots are taken +headlessly with [`scripts/screenshot.sh`](scripts/screenshot.sh). + ## License MIT diff --git a/assets/icon/png/redshell-1024.png b/assets/icon/png/redshell-1024.png new file mode 100644 index 0000000..bb5d102 Binary files /dev/null and b/assets/icon/png/redshell-1024.png differ diff --git a/assets/icon/png/redshell-128.png b/assets/icon/png/redshell-128.png new file mode 100644 index 0000000..ec05367 Binary files /dev/null and b/assets/icon/png/redshell-128.png differ diff --git a/assets/icon/png/redshell-16.png b/assets/icon/png/redshell-16.png new file mode 100644 index 0000000..18cfd3f Binary files /dev/null and b/assets/icon/png/redshell-16.png differ diff --git a/assets/icon/png/redshell-24.png b/assets/icon/png/redshell-24.png new file mode 100644 index 0000000..8ebbfe6 Binary files /dev/null and b/assets/icon/png/redshell-24.png differ diff --git a/assets/icon/png/redshell-256.png b/assets/icon/png/redshell-256.png new file mode 100644 index 0000000..be671e3 Binary files /dev/null and b/assets/icon/png/redshell-256.png differ diff --git a/assets/icon/png/redshell-32.png b/assets/icon/png/redshell-32.png new file mode 100644 index 0000000..d2813a4 Binary files /dev/null and b/assets/icon/png/redshell-32.png differ diff --git a/assets/icon/png/redshell-48.png b/assets/icon/png/redshell-48.png new file mode 100644 index 0000000..2b1bddb Binary files /dev/null and b/assets/icon/png/redshell-48.png differ diff --git a/assets/icon/png/redshell-512.png b/assets/icon/png/redshell-512.png new file mode 100644 index 0000000..5c1c0d1 Binary files /dev/null and b/assets/icon/png/redshell-512.png differ diff --git a/assets/icon/png/redshell-64.png b/assets/icon/png/redshell-64.png new file mode 100644 index 0000000..8b68f77 Binary files /dev/null and b/assets/icon/png/redshell-64.png differ diff --git a/assets/icon/redshell-small.svg b/assets/icon/redshell-small.svg new file mode 100644 index 0000000..affb978 --- /dev/null +++ b/assets/icon/redshell-small.svg @@ -0,0 +1,8 @@ + + + + + + + diff --git a/assets/icon/redshell.icns b/assets/icon/redshell.icns new file mode 100644 index 0000000..be24610 Binary files /dev/null and b/assets/icon/redshell.icns differ diff --git a/assets/icon/redshell.ico b/assets/icon/redshell.ico new file mode 100644 index 0000000..79d3592 Binary files /dev/null and b/assets/icon/redshell.ico differ diff --git a/assets/icon/redshell.svg b/assets/icon/redshell.svg new file mode 100644 index 0000000..b3460de --- /dev/null +++ b/assets/icon/redshell.svg @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/linux/dev.redshell.RedShell.desktop b/assets/linux/dev.redshell.RedShell.desktop new file mode 100644 index 0000000..ba6cc33 --- /dev/null +++ b/assets/linux/dev.redshell.RedShell.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Type=Application +Name=RedShell +GenericName=Terminal +Comment=Fast GPU terminal and session manager +Exec=redshell +Icon=dev.redshell.RedShell +Terminal=false +Categories=System;TerminalEmulator; +Keywords=shell;prompt;command;commandline;ssh;tmux; +StartupWMClass=dev.redshell.RedShell diff --git a/crates/redshell-app/Cargo.toml b/crates/redshell-app/Cargo.toml index 69fbd47..f8e3012 100644 --- a/crates/redshell-app/Cargo.toml +++ b/crates/redshell-app/Cargo.toml @@ -25,8 +25,109 @@ anyhow.workspace = true log.workspace = true env_logger.workspace = true parking_lot.workspace = true +serde.workspace = true +serde_json.workspace = true chrono.workspace = true uuid.workspace = true futures = "0.3" +# Already built for gpui (same version and features); converts BMP/TIFF clipboard images to PNG. +image = "0.25" which.workspace = true dirs.workspace = true +semver.workspace = true +# The HTTP client gpui already builds (through gpui_http_client), with features it already +# enables, so the update check compiles nothing new. Keep the version in step with gpui's. +reqwest = { package = "zed-reqwest", version = "0.12.15-zed", default-features = false, features = ["rustls-tls-native-roots"] } +tokio = { version = "1", default-features = false, features = ["rt"] } + +[target.'cfg(windows)'.dependencies] +# gpui's copy, with features gpui already enables (nothing is rebuilt): reads +# bitmap-only clipboards (PrintScreen) for Paste Image. +windows = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_System_DataExchange", + "Win32_System_Memory", + "Win32_System_Ole", +] } + +[build-dependencies] +embed-resource = "3" + +[dev-dependencies] +tempfile.workspace = true + +# Installers built by cargo-packager (pinned in .github/workflows/release.yml): NSIS setup +# on Windows, .deb and AppImage on Linux, a .dmg holding RedShell.app on macOS. The version +# comes from the crate, and paths are relative to this directory. +[package.metadata.packager] +product-name = "RedShell" +identifier = "dev.redshell.RedShell" +# Part of the Windows registry keys an upgrade finds the old install by: never change it. +publisher = "RedShell" +authors = ["RedShell developers"] +homepage = "https://github.com/redstone-md/RedShell" +description = "Fast GPU terminal and session manager" +long-description = """ +RedShell is a GPU-rendered terminal with tabs, split panes, SSH and tmux sessions, +searchable output history and plugins.""" +category = "DeveloperTool" +# The .icns becomes the app bundle icon; the PNG is the AppImage icon. +icons = ["../../assets/icon/redshell.icns", "../../assets/icon/png/redshell-512.png"] + +# Per-user install (no admin prompt) into %LOCALAPPDATA%\RedShell. Settings and history live +# in %APPDATA%\redshell, which the uninstaller leaves alone. +[package.metadata.packager.nsis] +installer-mode = "currentUser" +installer-icon = "../../assets/icon/redshell.ico" + +[package.metadata.packager.macos] +# GPUI's own deployment target. +minimum-system-version = "10.15.7" +# Ad-hoc signature: no Developer ID yet, but Apple silicon refuses to run unsigned bundles. +signing-identity = "-" + +# Linux packages install the same desktop entry and icons as the tarball, named after the +# window's app id, so the packager's own entry (named after the binary) is turned off. +[package.metadata.packager.linux] +generate-desktop-entry = false + +[package.metadata.packager.deb] +package-name = "redshell" +section = "x11" +# The binary links libxcb, xkbcommon and libgcc; GPUI loads the Vulkan loader and +# libwayland-client at runtime, and finds fonts through the fontconfig configuration. +depends = [ + "libc6 (>= 2.35)", + "libgcc-s1", + "libxcb1", + "libxkbcommon0", + "libxkbcommon-x11-0", + "libwayland-client0", + "libvulkan1", + "mesa-vulkan-drivers | vulkan-icd", + "fontconfig-config", +] + +[package.metadata.packager.deb.files] +"../../assets/linux/dev.redshell.RedShell.desktop" = "/usr/share/applications/dev.redshell.RedShell.desktop" +"../../assets/icon/png/redshell-16.png" = "/usr/share/icons/hicolor/16x16/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-24.png" = "/usr/share/icons/hicolor/24x24/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-32.png" = "/usr/share/icons/hicolor/32x32/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-48.png" = "/usr/share/icons/hicolor/48x48/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-64.png" = "/usr/share/icons/hicolor/64x64/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-128.png" = "/usr/share/icons/hicolor/128x128/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-256.png" = "/usr/share/icons/hicolor/256x256/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-512.png" = "/usr/share/icons/hicolor/512x512/apps/dev.redshell.RedShell.png" + +# The AppImage build expects the entry under the binary's name; the name inside the image is +# not visible to the desktop, which reads the entry's own Icon and StartupWMClass keys. +[package.metadata.packager.appimage.files] +"../../assets/linux/dev.redshell.RedShell.desktop" = "/usr/share/applications/redshell.desktop" +"../../assets/icon/png/redshell-16.png" = "/usr/share/icons/hicolor/16x16/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-24.png" = "/usr/share/icons/hicolor/24x24/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-32.png" = "/usr/share/icons/hicolor/32x32/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-48.png" = "/usr/share/icons/hicolor/48x48/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-64.png" = "/usr/share/icons/hicolor/64x64/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-128.png" = "/usr/share/icons/hicolor/128x128/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-256.png" = "/usr/share/icons/hicolor/256x256/apps/dev.redshell.RedShell.png" +"../../assets/icon/png/redshell-512.png" = "/usr/share/icons/hicolor/512x512/apps/dev.redshell.RedShell.png" diff --git a/crates/redshell-app/build.rs b/crates/redshell-app/build.rs new file mode 100644 index 0000000..d304c4f --- /dev/null +++ b/crates/redshell-app/build.rs @@ -0,0 +1,64 @@ +//! Embeds the app icon and version information into the Windows executable. +//! +//! GPUI loads the window class icon from resource id 1 of the running module, so the icon +//! group must use that id for the title bar, taskbar and Alt+Tab to show it. + +use std::env; +use std::fs; +use std::path::{Path, PathBuf}; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + embed_windows_resources(); + } +} + +fn embed_windows_resources() { + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo")); + let icon = manifest_dir.join("../../assets/icon/redshell.ico"); + println!("cargo:rerun-if-changed={}", icon.display()); + + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); + let rc = out_dir.join("redshell.rc"); + fs::write(&rc, resource_script(&icon)).expect("write redshell.rc"); + embed_resource::compile(&rc, embed_resource::NONE) + .manifest_required() + .unwrap_or_else(|err| panic!("embedding Windows resources failed: {err}")); +} + +/// Builds the `.rc` script: icon group 1 plus a VERSIONINFO block with the crate version. +fn resource_script(icon: &Path) -> String { + let version = env!("CARGO_PKG_VERSION"); + let file_version = + [env!("CARGO_PKG_VERSION_MAJOR"), env!("CARGO_PKG_VERSION_MINOR"), env!("CARGO_PKG_VERSION_PATCH"), "0"] + .join(","); + let icon = icon.display().to_string().replace('\\', "\\\\"); + format!( + r#"1 ICON "{icon}" + +1 VERSIONINFO +FILEVERSION {file_version} +PRODUCTVERSION {file_version} +FILEOS 0x40004 +FILETYPE 0x1 +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "RedShell" + VALUE "FileVersion", "{version}" + VALUE "OriginalFilename", "redshell.exe" + VALUE "ProductName", "RedShell" + VALUE "ProductVersion", "{version}" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +"# + ) +} diff --git a/crates/redshell-app/src/clipboard_dib.rs b/crates/redshell-app/src/clipboard_dib.rs new file mode 100644 index 0000000..4465867 --- /dev/null +++ b/crates/redshell-app/src/clipboard_dib.rs @@ -0,0 +1,176 @@ +//! Bitmaps on the Windows clipboard. +//! +//! PrintScreen and many screenshot tools put only a device-independent +//! bitmap (`CF_DIBV5` / `CF_DIB`) on the clipboard, which GPUI does not +//! read. A DIB is a BMP file without its 14-byte file header, so adding that +//! header lets the `image` crate decode it. + +/// Size of the BMP file header (`BITMAPFILEHEADER`). +const FILE_HEADER: usize = 14; +/// `BITMAPINFOHEADER`; larger headers (V4, V5) carry their colour masks inside. +const INFO_HEADER: usize = 40; +/// `BITMAPCOREHEADER` (OS/2): 16-bit sizes and 3-byte palette entries. +const CORE_HEADER: usize = 12; +const BI_BITFIELDS: u32 = 3; +const BI_ALPHABITFIELDS: u32 = 6; + +fn u16_at(bytes: &[u8], at: usize) -> Option { + Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?)) +} + +fn u32_at(bytes: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) +} + +/// A packed DIB (header, colour masks, palette, pixels) as a BMP file, or +/// `None` when the header is malformed. +pub fn dib_to_bmp(dib: &[u8]) -> Option> { + let header = u32_at(dib, 0)? as usize; + let (bit_count, compression, colors_used, palette_entry) = if header == CORE_HEADER { + (u16_at(dib, 10)?, 0, 0, 3) + } else if header >= INFO_HEADER { + (u16_at(dib, 14)?, u32_at(dib, 16)?, u32_at(dib, 32)? as usize, 4) + } else { + return None; + }; + // A plain info header is followed by the masks when bit fields are used. + let masks = match compression { + BI_BITFIELDS if header == INFO_HEADER => 12, + BI_ALPHABITFIELDS if header == INFO_HEADER => 16, + _ => 0, + }; + let colors = match colors_used { + 0 if bit_count <= 8 => 1 << bit_count, + n => n, + }; + let pixels = header + masks + colors.checked_mul(palette_entry)?; + if pixels > dib.len() { + return None; + } + let mut bmp = Vec::with_capacity(FILE_HEADER + dib.len()); + bmp.extend_from_slice(b"BM"); + bmp.extend_from_slice(&u32::try_from(FILE_HEADER + dib.len()).ok()?.to_le_bytes()); + bmp.extend_from_slice(&[0; 4]); + bmp.extend_from_slice(&u32::try_from(FILE_HEADER + pixels).ok()?.to_le_bytes()); + bmp.extend_from_slice(dib); + Some(bmp) +} + +/// The clipboard's bitmap (`CF_DIBV5`, else `CF_DIB`) as a BMP file. +#[cfg(windows)] +pub fn read() -> Option> { + use windows::Win32::Foundation::HGLOBAL; + use windows::Win32::System::DataExchange::{ + CloseClipboard, GetClipboardData, IsClipboardFormatAvailable, OpenClipboard, + }; + use windows::Win32::System::Memory::{GlobalLock, GlobalSize, GlobalUnlock}; + use windows::Win32::System::Ole::{CF_DIB, CF_DIBV5}; + + // SAFETY: the clipboard is open while its data handle is used, and the + // locked memory is copied before it is unlocked. + unsafe { + OpenClipboard(None).ok()?; + let dib = [CF_DIBV5, CF_DIB].into_iter().find_map(|format| { + let format = u32::from(format.0); + IsClipboardFormatAvailable(format).ok()?; + let memory = HGLOBAL(GetClipboardData(format).ok()?.0); + let data = GlobalLock(memory); + if data.is_null() { + return None; + } + let dib = std::slice::from_raw_parts(data.cast::(), GlobalSize(memory)).to_vec(); + let _ = GlobalUnlock(memory); + Some(dib) + }); + let _ = CloseClipboard(); + dib_to_bmp(&dib?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A DIB with `header` bytes of header whose leading fields are set. + fn dib(header: u32, width: i32, height: i32, bits: u16, compression: u32, colors_used: u32) -> Vec { + let mut d = Vec::new(); + d.extend_from_slice(&header.to_le_bytes()); + d.extend_from_slice(&width.to_le_bytes()); + d.extend_from_slice(&height.to_le_bytes()); + d.extend_from_slice(&1u16.to_le_bytes()); + d.extend_from_slice(&bits.to_le_bytes()); + d.extend_from_slice(&compression.to_le_bytes()); + d.extend_from_slice(&[0; 12]); // image size, resolution + d.extend_from_slice(&colors_used.to_le_bytes()); + d.extend_from_slice(&[0; 4]); // important colours + d.resize(header as usize, 0); + d + } + + fn masks(d: &mut [u8], at: usize, masks: &[u32]) { + for (i, mask) in masks.iter().enumerate() { + d[at + i * 4..at + i * 4 + 4].copy_from_slice(&mask.to_le_bytes()); + } + } + + fn decode(dib: &[u8]) -> image::RgbaImage { + image::load_from_memory_with_format(&dib_to_bmp(dib).unwrap(), image::ImageFormat::Bmp).unwrap().to_rgba8() + } + + const RED: [u8; 4] = [255, 0, 0, 255]; + const BLUE: [u8; 4] = [0, 0, 255, 255]; + + /// 2×2 BGRA pixels: red row first in memory, then blue. + fn bgra_rows(d: &mut Vec) { + d.extend_from_slice(&[0, 0, 255, 255, 0, 0, 255, 255, 255, 0, 0, 255, 255, 0, 0, 255]); + } + + #[test] + fn v5_bitfields_screenshots_both_row_orders() { + for (height, top) in [(-2, RED), (2, BLUE)] { + let mut d = dib(124, 2, height, 32, BI_BITFIELDS, 0); + masks(&mut d, 40, &[0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0xff00_0000]); + bgra_rows(&mut d); + let image = decode(&d); + assert_eq!(image.get_pixel(0, 0).0, top, "height {height}"); + assert_eq!(image.dimensions(), (2, 2)); + } + } + + #[test] + fn info_header_bitfields_skip_the_masks() { + let mut d = dib(40, 2, -2, 32, BI_BITFIELDS, 0); + d.extend_from_slice(&[0; 12]); + masks(&mut d, 40, &[0x00ff_0000, 0x0000_ff00, 0x0000_00ff]); + bgra_rows(&mut d); + assert_eq!(&dib_to_bmp(&d).unwrap()[10..14], &(14u32 + 52).to_le_bytes()); + assert_eq!(decode(&d).get_pixel(1, 1).0, BLUE); + } + + #[test] + fn rgb24_rows_are_padded() { + let mut d = dib(40, 1, 2, 24, 0, 0); + // Bottom-up: the last row in the image comes first. 3 bytes + 1 pad each. + d.extend_from_slice(&[255, 0, 0, 0, 0, 0, 255, 0]); + let image = decode(&d); + assert_eq!(image.get_pixel(0, 0).0, RED); + assert_eq!(image.get_pixel(0, 1).0, BLUE); + } + + #[test] + fn palette_images_skip_the_palette() { + let mut d = dib(40, 2, -1, 8, 0, 2); + d.extend_from_slice(&[255, 0, 0, 0, 0, 0, 255, 0]); // blue, red (BGRx) + d.extend_from_slice(&[1, 0, 0, 0]); + assert_eq!(&dib_to_bmp(&d).unwrap()[10..14], &(14u32 + 40 + 8).to_le_bytes()); + let image = decode(&d); + assert_eq!((image.get_pixel(0, 0).0, image.get_pixel(1, 0).0), (RED, BLUE)); + } + + #[test] + fn rejects_truncated_headers() { + assert_eq!(dib_to_bmp(&[]), None); + assert_eq!(dib_to_bmp(&dib(40, 1, 1, 8, 0, 0)), None, "the 256-colour palette is missing"); + assert_eq!(dib_to_bmp(&20u32.to_le_bytes()), None); + } +} diff --git a/crates/redshell-app/src/closing.rs b/crates/redshell-app/src/closing.rs new file mode 100644 index 0000000..611ef88 --- /dev/null +++ b/crates/redshell-app/src/closing.rs @@ -0,0 +1,147 @@ +//! What closing tabs, panes or windows would end, whether that is worth a +//! question, and how the question says it. Every close confirmation words +//! the same facts the same way. + +use gpui::{App, Entity}; +use redshell_core::LaunchKind; +use redshell_core::settings::ConfirmPolicy; + +use crate::terminal_view::TerminalView; + +/// What closing some panes would end: the input of the confirmation policies. +#[derive(Debug, Default, Clone, Copy, PartialEq)] +pub struct Work { + /// Tabs with at least one live pane. + pub tabs: usize, + /// Live panes whose session ends with them. + pub sessions: usize, + /// Live multiplexer panes: closing only detaches from their session. + pub detached: usize, + /// Panes in which a program other than an idle shell runs. + pub programs: usize, +} + +/// What stays after closing, for the end of a confirmation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kept { + /// History is off: nothing to point to. + Nothing, + /// The output can be found and restored from the history. + History, + /// The tabs reopen on the next start. + Tabs, +} + +impl Work { + /// What closing one tab (or pane) made of `views` would end. + pub fn of(views: &[Entity], cx: &App) -> Self { + let live: Vec<_> = views.iter().map(|v| v.read(cx)).filter(|v| v.is_alive()).collect(); + let detached = live.iter().filter(|v| v.kind() == LaunchKind::Multiplexer).count(); + Self { + tabs: usize::from(!live.is_empty()), + sessions: live.len() - detached, + detached, + programs: live.iter().filter(|v| v.has_running_job()).count(), + } + } + + /// Whether closing asks first under `policy`. Nothing that has already + /// exited is worth a question, whatever the policy. + pub fn asks(self, policy: ConfirmPolicy) -> bool { + self.sessions + self.detached > 0 && policy.asks(self.programs > 0, self.tabs) + } + + /// The body of a confirmation: what stops, what keeps running, and + /// what is `kept` afterwards. + pub fn summary(self, kept: Kept) -> String { + let mut parts = Vec::new(); + match self.programs { + 0 => {} + 1 => parts.push("A program is running and will be stopped.".to_owned()), + n => parts.push(format!("{n} programs are running and will be stopped.")), + } + match self.sessions { + // A running program already says its session ends. + 1 if self.programs > 0 => {} + 0 => {} + 1 => parts.push("The session will end.".to_owned()), + n => parts.push(format!("{n} sessions will end.")), + } + match self.detached { + 0 => {} + 1 => parts.push("A tmux or screen session only detaches and keeps running.".to_owned()), + n => parts.push(format!("{n} tmux or screen sessions only detach and keep running.")), + } + parts.extend(kept.sentence().map(str::to_owned)); + parts.join(" ") + } +} + +impl Kept { + /// What is kept, as the last sentence of a confirmation. + pub fn sentence(self) -> Option<&'static str> { + match self { + Self::Nothing => None, + Self::History => Some("The output stays in your history."), + Self::Tabs => Some("Your tabs come back next time, with their output."), + } + } +} + +impl std::ops::Add for Work { + type Output = Self; + + fn add(self, other: Self) -> Self { + Self { + tabs: self.tabs + other.tabs, + sessions: self.sessions + other.sessions, + detached: self.detached + other.detached, + programs: self.programs + other.programs, + } + } +} + +impl std::iter::Sum for Work { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), std::ops::Add::add) + } +} + +/// How the kill confirmations describe what killing a multiplexer session +/// or window does. +pub const KILL_STOPS_PROGRAMS: &str = "Every program in it will be stopped. This cannot be undone."; + +#[cfg(test)] +mod tests { + use super::*; + + const IDLE: Work = Work { tabs: 1, sessions: 1, detached: 0, programs: 0 }; + const BUSY: Work = Work { tabs: 1, sessions: 2, detached: 0, programs: 1 }; + const TMUX: Work = Work { tabs: 1, sessions: 0, detached: 1, programs: 0 }; + + #[test] + fn closing_only_exited_tabs_never_asks() { + let exited = Work::default(); + assert!(!exited.asks(ConfirmPolicy::Always)); + assert!(IDLE.asks(ConfirmPolicy::Always)); + assert!(TMUX.asks(ConfirmPolicy::Always)); + assert!(!IDLE.asks(ConfirmPolicy::MultipleTabs)); + assert!([IDLE, IDLE, exited].into_iter().sum::().asks(ConfirmPolicy::MultipleTabs)); + assert_eq!([IDLE, BUSY].into_iter().sum::(), Work { tabs: 2, sessions: 3, detached: 0, programs: 1 }); + } + + #[test] + fn summaries_say_what_ends_and_what_stays() { + assert_eq!(IDLE.summary(Kept::Nothing), "The session will end."); + assert_eq!( + Work { programs: 1, ..IDLE }.summary(Kept::History), + "A program is running and will be stopped. The output stays in your history." + ); + assert_eq!( + (BUSY + TMUX).summary(Kept::Tabs), + "A program is running and will be stopped. 2 sessions will end. A tmux or screen session only \ + detaches and keeps running. Your tabs come back next time, with their output." + ); + assert_eq!((TMUX + TMUX).summary(Kept::Nothing), "2 tmux or screen sessions only detach and keep running."); + } +} diff --git a/crates/redshell-app/src/commands.rs b/crates/redshell-app/src/commands.rs index 8be3449..c583aab 100644 --- a/crates/redshell-app/src/commands.rs +++ b/crates/redshell-app/src/commands.rs @@ -4,27 +4,63 @@ //! palette and `[keybindings]` overrides in `config.toml`. Adding a command //! is one line here plus one arm in `Workspace::run_command`. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use gpui::{App, KeyBinding}; +/// The platform whose key conventions the defaults follow. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Platform { + MacOs, + Linux, + Windows, +} + +impl Platform { + pub const CURRENT: Self = if cfg!(target_os = "macos") { + Self::MacOs + } else if cfg!(windows) { + Self::Windows + } else { + Self::Linux + }; +} + /// Static command metadata. #[derive(Debug, Clone, Copy)] pub struct CommandDef { pub id: &'static str, pub category: &'static str, pub title: &'static str, - /// Default keystrokes on macOS and on Linux/Windows. - pub mac: Option<&'static str>, - pub other: Option<&'static str>, + /// Default keystrokes on macOS and on Linux/Windows, the one shown in + /// the UI first. [`WINDOWS_KEYS`] replaces `other` where Windows differs. + mac: &'static [&'static str], + other: &'static [&'static str], } impl CommandDef { - pub fn default_key(&self) -> Option<&'static str> { - if cfg!(target_os = "macos") { self.mac } else { self.other } + /// Default keystrokes on `platform`, the one shown in the UI first. + pub fn default_keys(&self, platform: Platform) -> &'static [&'static str] { + match platform { + Platform::MacOs => self.mac, + Platform::Linux => self.other, + Platform::Windows => { + WINDOWS_KEYS.iter().find(|(id, _)| *id == self.id).map_or(self.other, |(_, keys)| *keys) + } + } } } +/// Windows defaults that differ from Linux, following Windows Terminal: +/// plain Ctrl+C copies a selection (and interrupts without one) and plain +/// Ctrl+V pastes. Linux leaves both to the shell. Paste Image takes the key +/// the AI agents paste images with on each platform. +const WINDOWS_KEYS: &[(&str, &[&str])] = &[ + ("terminal.copy_or_interrupt", &["ctrl-c"]), + ("terminal.paste", &["ctrl-v", "ctrl-shift-v", "shift-insert"]), + ("terminal.paste_image", &["alt-v"]), +]; + /// Runs any command by id; used for plugin commands bound in `[keybindings]`. #[derive(Clone, PartialEq, Debug, Default, gpui::Action)] #[action(namespace = redshell, no_json)] @@ -64,87 +100,130 @@ macro_rules! commands { } commands! { - NewTab => "tab.new", "Tab", "New Tab", Some("cmd-t"), Some("ctrl-shift-t"); - CloseTab => "tab.close", "Tab", "Close Tab", Some("cmd-w"), Some("ctrl-shift-w"); - DuplicateTab => "tab.duplicate", "Tab", "Duplicate Tab", None, None; - RenameTab => "tab.rename", "Tab", "Rename Tab…", Some("cmd-shift-r"), Some("ctrl-shift-r"); - NextTab => "tab.next", "Tab", "Next Tab", Some("cmd-shift-]"), Some("ctrl-tab"); - PrevTab => "tab.prev", "Tab", "Previous Tab", Some("cmd-shift-["), Some("ctrl-shift-tab"); - MoveTabLeft => "tab.move_left", "Tab", "Move Tab Left", None, Some("ctrl-shift-pageup"); - MoveTabRight => "tab.move_right", "Tab", "Move Tab Right", None, Some("ctrl-shift-pagedown"); - ActivateTab1 => "tab.activate_1", "Tab", "Go to Tab 1", Some("cmd-1"), Some("alt-1"); - ActivateTab2 => "tab.activate_2", "Tab", "Go to Tab 2", Some("cmd-2"), Some("alt-2"); - ActivateTab3 => "tab.activate_3", "Tab", "Go to Tab 3", Some("cmd-3"), Some("alt-3"); - ActivateTab4 => "tab.activate_4", "Tab", "Go to Tab 4", Some("cmd-4"), Some("alt-4"); - ActivateTab5 => "tab.activate_5", "Tab", "Go to Tab 5", Some("cmd-5"), Some("alt-5"); - ActivateTab6 => "tab.activate_6", "Tab", "Go to Tab 6", Some("cmd-6"), Some("alt-6"); - ActivateTab7 => "tab.activate_7", "Tab", "Go to Tab 7", Some("cmd-7"), Some("alt-7"); - ActivateTab8 => "tab.activate_8", "Tab", "Go to Tab 8", Some("cmd-8"), Some("alt-8"); - ActivateTab9 => "tab.activate_9", "Tab", "Go to Last Tab", Some("cmd-9"), Some("alt-9"); - SplitRight => "pane.split_right", "Pane", "Split Right", Some("cmd-d"), Some("ctrl-shift-d"); - SplitDown => "pane.split_down", "Pane", "Split Down", Some("cmd-shift-d"), Some("ctrl-shift-alt-d"); - FocusNextPane => "pane.focus_next", "Pane", "Focus Next Pane", Some("cmd-]"), Some("ctrl-shift-]"); - FocusPrevPane => "pane.focus_prev", "Pane", "Focus Previous Pane", Some("cmd-["), Some("ctrl-shift-["); - ClosePane => "pane.close", "Pane", "Close Pane", Some("cmd-alt-w"), Some("ctrl-shift-alt-w"); - CommandPalette => "palette.commands", "View", "Command Palette", Some("cmd-shift-p"), Some("ctrl-shift-p"); - LaunchPalette => "palette.launch", "Launch", "Open Profile…", Some("cmd-o"), Some("ctrl-shift-o"); - LaunchAgent => "agent.launch", "Launch", "Launch AI Agent…", Some("cmd-shift-i"), Some("ctrl-shift-i"); - ConnectSsh => "ssh.connect", "Launch", "Connect to SSH Host…", Some("cmd-shift-s"), Some("ctrl-shift-s"); - SelectTheme => "theme.select", "Appearance", "Select Theme…", Some("cmd-k cmd-t"), Some("ctrl-k ctrl-t"); - ImportTheme => "theme.import_clipboard", "Appearance", "Import tweakcn Theme from Clipboard", None, None; - InsertSnippet => "snippet.insert", "Terminal", "Insert Snippet…", Some("cmd-shift-e"), Some("ctrl-shift-e"); - SearchSessions => "session.search", "History", "Search All Sessions…", Some("cmd-shift-f"), Some("ctrl-shift-f"); - BrowseHistory => "session.history", "History", "Browse Session History…", Some("cmd-shift-h"), Some("ctrl-shift-h"); - ExportSession => "session.export", "History", "Export Session (asciicast)", None, None; - RestartSession => "session.restart", "Terminal", "Restart Session", None, None; - ClearScrollback => "terminal.clear", "Terminal", "Clear Scrollback", Some("cmd-k"), Some("ctrl-shift-k"); - Copy => "terminal.copy", "Terminal", "Copy", Some("cmd-c"), Some("ctrl-shift-c"); - Paste => "terminal.paste", "Terminal", "Paste", Some("cmd-v"), Some("ctrl-shift-v"); - SelectAll => "terminal.select_all", "Terminal", "Select All", Some("cmd-a"), Some("ctrl-shift-a"); - ScrollPageUp => "terminal.page_up", "Terminal", "Scroll Page Up", Some("shift-pageup"), Some("shift-pageup"); - ScrollPageDown => "terminal.page_down", "Terminal", "Scroll Page Down", Some("shift-pagedown"), Some("shift-pagedown"); - ScrollToTop => "terminal.scroll_top", "Terminal", "Scroll to Top", Some("cmd-home"), Some("ctrl-shift-home"); - ScrollToBottom => "terminal.scroll_bottom", "Terminal", "Scroll to Bottom", Some("cmd-end"), Some("ctrl-shift-end"); - Find => "terminal.find", "Terminal", "Find in Terminal…", Some("cmd-f"), Some("ctrl-shift-g"); - FindNext => "terminal.find_next", "Terminal", "Find Next (Older)", Some("cmd-g"), None; - FindPrev => "terminal.find_prev", "Terminal", "Find Previous (Newer)", Some("cmd-shift-g"), None; - PrevPrompt => "terminal.prev_prompt", "Terminal", "Jump to Previous Prompt", Some("cmd-up"), Some("ctrl-shift-z"); - NextPrompt => "terminal.next_prompt", "Terminal", "Jump to Next Prompt", Some("cmd-down"), Some("ctrl-shift-x"); - ZoomIn => "view.zoom_in", "View", "Increase Font Size", Some("cmd-="), Some("ctrl-="); - ZoomOut => "view.zoom_out", "View", "Decrease Font Size", Some("cmd--"), Some("ctrl--"); - ZoomReset => "view.zoom_reset", "View", "Reset Font Size", Some("cmd-0"), Some("ctrl-0"); - ToggleSidebar => "view.toggle_sidebar", "View", "Toggle Sidebar", Some("cmd-b"), Some("ctrl-shift-b"); - ToggleFullscreen => "view.toggle_fullscreen", "View", "Toggle Fullscreen", Some("cmd-ctrl-f"), Some("f11"); - OpenSettings => "settings.open", "Settings", "Open Settings", Some("cmd-,"), Some("ctrl-,"); - EditConfig => "settings.edit_file", "Settings", "Edit config.toml", None, None; - ReloadConfig => "settings.reload", "Settings", "Reload Configuration", None, None; - OpenConfigDir => "settings.reveal", "Settings", "Reveal Config Folder", None, None; - ManageMux => "mux.manage", "Multiplexer", "Manage tmux / screen Sessions…", Some("cmd-shift-m"), Some("ctrl-shift-m"); - AttachNative => "mux.attach_native", "Multiplexer", "Attach tmux Session Natively…", None, None; - ShowPlugins => "plugins.list", "Plugins", "Show Loaded Plugins", None, None; - NewWindow => "app.new_window", "App", "New Window", Some("cmd-n"), Some("ctrl-shift-n"); - Quit => "app.quit", "App", "Quit RedShell", Some("cmd-q"), Some("ctrl-shift-q"); + NewTab => "tab.new", "Tab", "New Tab", &["cmd-t"], &["ctrl-shift-t"]; + CloseTab => "tab.close", "Tab", "Close Tab", &["cmd-w"], &["ctrl-shift-w"]; + DuplicateTab => "tab.duplicate", "Tab", "Duplicate Tab", &[], &[]; + RenameTab => "tab.rename", "Tab", "Rename Tab…", &["cmd-shift-r"], &["ctrl-shift-r"]; + NextTab => "tab.next", "Tab", "Next Tab", &["cmd-shift-]"], &["ctrl-tab"]; + PrevTab => "tab.prev", "Tab", "Previous Tab", &["cmd-shift-["], &["ctrl-shift-tab"]; + MoveTabLeft => "tab.move_left", "Tab", "Move Tab Left", &[], &["ctrl-shift-pageup"]; + MoveTabRight => "tab.move_right", "Tab", "Move Tab Right", &[], &["ctrl-shift-pagedown"]; + ActivateTab1 => "tab.activate_1", "Tab", "Go to Tab 1", &["cmd-1"], &["ctrl-alt-1"]; + ActivateTab2 => "tab.activate_2", "Tab", "Go to Tab 2", &["cmd-2"], &["ctrl-alt-2"]; + ActivateTab3 => "tab.activate_3", "Tab", "Go to Tab 3", &["cmd-3"], &["ctrl-alt-3"]; + ActivateTab4 => "tab.activate_4", "Tab", "Go to Tab 4", &["cmd-4"], &["ctrl-alt-4"]; + ActivateTab5 => "tab.activate_5", "Tab", "Go to Tab 5", &["cmd-5"], &["ctrl-alt-5"]; + ActivateTab6 => "tab.activate_6", "Tab", "Go to Tab 6", &["cmd-6"], &["ctrl-alt-6"]; + ActivateTab7 => "tab.activate_7", "Tab", "Go to Tab 7", &["cmd-7"], &["ctrl-alt-7"]; + ActivateTab8 => "tab.activate_8", "Tab", "Go to Tab 8", &["cmd-8"], &["ctrl-alt-8"]; + ActivateTab9 => "tab.activate_9", "Tab", "Go to Last Tab", &["cmd-9"], &["ctrl-alt-9"]; + SplitRight => "pane.split_right", "Pane", "Split Right", &["cmd-d"], &["ctrl-shift-d"]; + SplitDown => "pane.split_down", "Pane", "Split Down", &["cmd-shift-d"], &["ctrl-shift-alt-d"]; + FocusNextPane => "pane.focus_next", "Pane", "Focus Next Pane", &["cmd-]"], &["ctrl-shift-]"]; + FocusPrevPane => "pane.focus_prev", "Pane", "Focus Previous Pane", &["cmd-["], &["ctrl-shift-["]; + ClosePane => "pane.close", "Pane", "Close Pane", &["cmd-alt-w"], &["ctrl-shift-alt-w"]; + CommandPalette => "palette.commands", "View", "Command Palette", &["cmd-shift-p"], &["ctrl-shift-p"]; + LaunchPalette => "palette.launch", "Launch", "Open Profile…", &["cmd-o"], &["ctrl-shift-o"]; + LaunchAgent => "agent.launch", "Launch", "Launch AI Agent…", &["cmd-shift-i"], &["ctrl-shift-i"]; + ConnectSsh => "ssh.connect", "Launch", "Connect to SSH Host…", &["cmd-shift-s"], &["ctrl-shift-s"]; + SelectTheme => "theme.select", "Appearance", "Select Theme…", &[], &[]; + ImportTheme => "theme.import_clipboard", "Appearance", "Import tweakcn Theme from Clipboard", &[], &[]; + InsertSnippet => "snippet.insert", "Terminal", "Insert Snippet…", &["cmd-shift-e"], &["ctrl-shift-e"]; + SearchSessions => "session.search", "History", "Search All Sessions…", &["cmd-shift-f"], &["ctrl-shift-alt-f"]; + BrowseHistory => "session.history", "History", "Browse Session History…", &["cmd-shift-h"], &["ctrl-shift-h"]; + ExportSession => "session.export", "History", "Export Session (asciicast)", &[], &[]; + RestartSession => "session.restart", "Terminal", "Restart Session", &[], &[]; + ClearScrollback => "terminal.clear", "Terminal", "Clear Scrollback", &["cmd-k"], &["ctrl-shift-k"]; + Copy => "terminal.copy", "Terminal", "Copy", &["cmd-c"], &["ctrl-shift-c", "ctrl-insert"]; + CopyOrInterrupt => "terminal.copy_or_interrupt", "Terminal", "Copy or Interrupt", &[], &[]; + Paste => "terminal.paste", "Terminal", "Paste", &["cmd-v"], &["ctrl-shift-v", "shift-insert"]; + // Declines (the key reaches the program) unless the pane is remote, the + // clipboard holds just an image and no upload of the pane is running. + PasteImage => "terminal.paste_image", "Terminal", "Paste Image", &["ctrl-v"], &["ctrl-v"]; + SelectAll => "terminal.select_all", "Terminal", "Select All", &["cmd-a"], &["ctrl-shift-a"]; + ScrollPageUp => "terminal.page_up", "Terminal", "Scroll Page Up", &["shift-pageup"], &["shift-pageup"]; + ScrollPageDown => "terminal.page_down", "Terminal", "Scroll Page Down", &["shift-pagedown"], &["shift-pagedown"]; + ScrollToTop => "terminal.scroll_top", "Terminal", "Scroll to Top", &["cmd-home"], &["ctrl-shift-home"]; + ScrollToBottom => "terminal.scroll_bottom", "Terminal", "Scroll to Bottom", &["cmd-end"], &["ctrl-shift-end"]; + Find => "terminal.find", "Terminal", "Find in Terminal…", &["cmd-f"], &["ctrl-shift-f"]; + FindNext => "terminal.find_next", "Terminal", "Find Next (Older)", &["cmd-g"], &["f3"]; + FindPrev => "terminal.find_prev", "Terminal", "Find Previous (Newer)", &["cmd-shift-g"], &["shift-f3"]; + PrevPrompt => "terminal.prev_prompt", "Terminal", "Jump to Previous Prompt", &["cmd-up"], &["ctrl-shift-z"]; + NextPrompt => "terminal.next_prompt", "Terminal", "Jump to Next Prompt", &["cmd-down"], &["ctrl-shift-x"]; + // Ctrl+Shift+= arrives as `+`; the numpad + and - keys arrive as `+` / `-` + // on Windows and macOS and as `add` / `subtract` on Linux. + ZoomIn => "view.zoom_in", "View", "Increase Font Size", &["cmd-=", "cmd-+"], &["ctrl-=", "ctrl-+", "ctrl-add"]; + ZoomOut => "view.zoom_out", "View", "Decrease Font Size", &["cmd--"], &["ctrl--", "ctrl-subtract"]; + ZoomReset => "view.zoom_reset", "View", "Reset Font Size", &["cmd-0"], &["ctrl-0"]; + ToggleSidebar => "view.toggle_sidebar", "View", "Toggle Sidebar", &["cmd-b"], &["ctrl-shift-b"]; + ToggleFullscreen => "view.toggle_fullscreen", "View", "Toggle Fullscreen", &["cmd-ctrl-f"], &["f11"]; + OpenSettings => "settings.open", "Settings", "Open Settings", &["cmd-,"], &["ctrl-,"]; + EditConfig => "settings.edit_file", "Settings", "Edit config.toml", &[], &[]; + ReloadConfig => "settings.reload", "Settings", "Reload Configuration", &[], &[]; + OpenConfigDir => "settings.reveal", "Settings", "Reveal Config Folder", &[], &[]; + ManageMux => "mux.manage", "Multiplexer", "Manage tmux / screen Sessions…", &["cmd-shift-m"], &["ctrl-shift-m"]; + AttachNative => "mux.attach_native", "Multiplexer", "Open tmux Session as Tabs…", &[], &[]; + ShowPlugins => "plugins.list", "Plugins", "Show Loaded Plugins", &[], &[]; + NewWindow => "app.new_window", "App", "New Window", &["cmd-n"], &["ctrl-shift-n"]; + CheckForUpdates => "app.check_updates", "App", "Check for Updates", &[], &[]; + Quit => "app.quit", "App", "Quit RedShell", &["cmd-q"], &["ctrl-shift-q"]; } /// Default bindings merged with the user's `[keybindings]` table. -/// A user entry with an empty command removes the default for that key. +/// A user entry with an empty command removes the default for that key; +/// binding a command replaces all of its default keys, and every key the +/// user binds to it applies. pub fn keymap(overrides: &BTreeMap) -> BTreeMap { - let mut map: BTreeMap = - COMMANDS.iter().filter_map(|c| c.default_key().map(|k| (k.to_owned(), c.id.to_owned()))).collect(); + keymap_for(Platform::CURRENT, overrides) +} + +fn keymap_for(platform: Platform, overrides: &BTreeMap) -> BTreeMap { + let mut map: BTreeMap = COMMANDS + .iter() + .flat_map(|c| c.default_keys(platform).iter().map(|k| ((*k).to_owned(), c.id.to_owned()))) + .collect(); + let rebound: HashSet<&str> = overrides.values().map(String::as_str).filter(|id| !id.is_empty()).collect(); + map.retain(|_, id| !rebound.contains(id.as_str())); for (key, id) in overrides { if id.is_empty() { map.remove(key); } else { - map.retain(|_, v| v != id); map.insert(key.clone(), id.clone()); } } map } -/// The binding shown in the UI for a command. +/// The binding shown in the UI for a command: its first default key while +/// that is still bound, otherwise any key bound to it. pub fn key_for(id: &str, keymap: &BTreeMap) -> Option { - keymap.iter().find(|(_, v)| v.as_str() == id).map(|(k, _)| k.clone()) + key_for_on(Platform::CURRENT, id, keymap) +} + +fn key_for_on(platform: Platform, id: &str, keymap: &BTreeMap) -> Option { + let bound = |key: &str| keymap.get(key).is_some_and(|v| v == id); + COMMANDS + .iter() + .find(|c| c.id == id) + .and_then(|c| c.default_keys(platform).iter().find(|k| bound(k))) + .map(|k| (*k).to_owned()) + .or_else(|| keymap.iter().find(|(_, v)| v.as_str() == id).map(|(k, _)| k.clone())) +} + +/// Key context in which a command's bindings fire. Apart from quitting and +/// fullscreen, none fire while a modal overlay is open (the workspace context +/// then also carries `Overlay`), and the clipboard keys leave text fields +/// such as the find bar to themselves. +fn binding_context(id: &str) -> &'static str { + match id { + "app.quit" | "view.toggle_fullscreen" => "Workspace", + "terminal.copy" + | "terminal.copy_or_interrupt" + | "terminal.paste" + | "terminal.paste_image" + | "terminal.select_all" => "Workspace && !Overlay && !TextInput", + _ => "Workspace && !Overlay", + } } /// (Re)installs keybindings. @@ -159,7 +238,7 @@ pub fn install_keybindings(cx: &mut App, overrides: &BTreeMap) { match KeyBinding::load( &key, action, - Some(gpui::KeyBindingContextPredicate::parse("Workspace").unwrap().into()), + gpui::KeyBindingContextPredicate::parse(binding_context(&id)).ok().map(Into::into), false, None, &gpui::DummyKeyboardMapper, @@ -168,5 +247,104 @@ pub fn install_keybindings(cx: &mut App, overrides: &BTreeMap) { Err(err) => log::warn!("keybinding `{key}`: {err:?}"), } } + bindings.extend(redshell_ui::TextInput::key_bindings()); cx.bind_keys(bindings); } + +#[cfg(test)] +mod tests { + use super::*; + + const PLATFORMS: [Platform; 3] = [Platform::MacOs, Platform::Linux, Platform::Windows]; + + #[test] + fn default_keys_are_single_keystrokes_that_never_collide() { + for platform in PLATFORMS { + let mut seen = BTreeMap::new(); + for c in COMMANDS { + for key in c.default_keys(platform) { + // A chord would hold its first key back from the shell + // until the chord times out. + assert!(gpui::Keystroke::parse(key).is_ok(), "{platform:?}: `{key}` is not one keystroke"); + if let Some(other) = seen.insert(*key, c.id) { + panic!("{platform:?}: `{key}` is bound to both {other} and {}", c.id); + } + } + } + } + } + + #[test] + fn bindings_stay_out_of_overlays_and_text_fields() { + let fires = |id: &str, stack: &[&str]| { + let stack: Vec = stack.iter().map(|c| gpui::KeyContext::parse(c).unwrap()).collect(); + gpui::KeyBindingContextPredicate::parse(binding_context(id)).unwrap().depth_of(&stack).is_some() + }; + let terminal = ["Workspace", "Terminal"]; + let find_bar = ["Workspace", "Terminal", "TextInput"]; + assert!(fires("tab.new", &terminal)); + assert!(fires("tab.new", &find_bar)); + assert!(!fires("tab.new", &["Workspace Overlay", "TextInput"])); + assert!(!fires("tab.new", &["Workspace Overlay", "Terminal"])); + assert!(fires("app.quit", &["Workspace Overlay", "TextInput"])); + assert!(fires("terminal.paste", &terminal)); + assert!(!fires("terminal.paste", &find_bar)); + } + + #[test] + fn windows_keys_name_real_commands() { + for (id, _) in WINDOWS_KEYS { + assert!(COMMANDS.iter().any(|c| c.id == *id), "unknown command {id}"); + } + } + + #[test] + fn alt_digits_stay_with_the_shell() { + for platform in [Platform::Linux, Platform::Windows] { + let map = keymap_for(platform, &BTreeMap::new()); + assert!((1..=9).all(|n| !map.contains_key(&format!("alt-{n}")))); + assert_eq!(map.get("ctrl-alt-1").map(String::as_str), Some("tab.activate_1")); + } + } + + #[test] + fn plain_ctrl_c_and_v_copy_and_paste_only_on_windows() { + let windows = keymap_for(Platform::Windows, &BTreeMap::new()); + let linux = keymap_for(Platform::Linux, &BTreeMap::new()); + assert_eq!(windows.get("ctrl-c").map(String::as_str), Some("terminal.copy_or_interrupt")); + assert_eq!(windows.get("ctrl-v").map(String::as_str), Some("terminal.paste")); + assert!(!linux.contains_key("ctrl-c")); + // Paste Image hands Ctrl+V on to the shell unless it uploads an image. + assert_eq!(linux.get("ctrl-v").map(String::as_str), Some("terminal.paste_image")); + assert_eq!(windows.get("alt-v").map(String::as_str), Some("terminal.paste_image")); + for map in [&windows, &linux] { + assert_eq!(map.get("ctrl-insert").map(String::as_str), Some("terminal.copy")); + assert_eq!(map.get("shift-insert").map(String::as_str), Some("terminal.paste")); + } + assert_eq!(key_for_on(Platform::Windows, "terminal.paste", &windows).as_deref(), Some("ctrl-v")); + assert_eq!(key_for_on(Platform::Linux, "terminal.copy", &linux).as_deref(), Some("ctrl-shift-c")); + } + + #[test] + fn overrides_replace_and_remove_defaults() { + let overrides = + BTreeMap::from([("ctrl-t".to_owned(), "tab.new".to_owned()), ("ctrl-shift-w".to_owned(), String::new())]); + let map = keymap_for(Platform::Linux, &overrides); + assert_eq!(map.get("ctrl-t").map(String::as_str), Some("tab.new")); + assert!(!map.contains_key("ctrl-shift-t")); + assert!(!map.contains_key("ctrl-shift-w")); + assert_eq!(key_for_on(Platform::Linux, "tab.new", &map).as_deref(), Some("ctrl-t")); + } + + #[test] + fn several_user_keys_for_one_command_all_apply() { + let overrides = BTreeMap::from([ + ("alt-t".to_owned(), "tab.new".to_owned()), + ("ctrl-t".to_owned(), "tab.new".to_owned()), + ("f2".to_owned(), "tab.new".to_owned()), + ]); + let map = keymap_for(Platform::Linux, &overrides); + let keys: Vec<&str> = map.iter().filter(|(_, id)| *id == "tab.new").map(|(k, _)| k.as_str()).collect(); + assert_eq!(keys, ["alt-t", "ctrl-t", "f2"]); + } +} diff --git a/crates/redshell-app/src/confirm.rs b/crates/redshell-app/src/confirm.rs index d9579ba..4720300 100644 --- a/crates/redshell-app/src/confirm.rs +++ b/crates/redshell-app/src/confirm.rs @@ -15,10 +15,16 @@ use redshell_ui::{ #[derive(Debug, Clone, PartialEq)] pub enum ConfirmAction { CloseTab(usize), + /// Close several tabs at once (by tab id). + CloseTabs(Vec), ClosePane(gpui::EntityId), CloseWindow, Quit, - Paste(String), + /// Paste `text` into the pane `view`, if it is still open. + Paste { + view: gpui::EntityId, + text: String, + }, KillMux { target: String, session: String, @@ -101,7 +107,7 @@ impl ConfirmDialog { (None, None) } }; - let destructive = !matches!(action, ConfirmAction::Paste(_) | ConfirmAction::DetachNative(_)); + let destructive = !matches!(action, ConfirmAction::Paste { .. } | ConfirmAction::DetachNative(_)); Self { title: title.into(), body: body.into(), diff --git a/crates/redshell-app/src/editor.rs b/crates/redshell-app/src/editor.rs new file mode 100644 index 0000000..0487290 --- /dev/null +++ b/crates/redshell-app/src/editor.rs @@ -0,0 +1,140 @@ +//! Editing config.toml in a tab, and telling such a program apart from a +//! shell. +//! +//! The editor runs as a local program (`LaunchKind::Shell`, like a shell) +//! but is not one: it is not idle while it waits for keys, a split or a +//! duplicate of it opens a shell instead of a second editor on the same +//! file, and it is not reopened on the next start. + +use std::path::Path; + +use redshell_core::{CommandSpec, LaunchKind, LaunchProfile}; + +/// Programs that hand the file to the system instead of editing it in the +/// terminal; with one of these the file opens through the OS. +const SYSTEM_OPENERS: [&str; 4] = ["notepad", "textedit", "xdg-open", "open"]; + +/// Whether `profile` runs an interactive shell, which is idle until a +/// program runs in it. Local shells are the only profiles with a `shell:` +/// id; other local programs (the config editor) count as running while +/// they live. +pub fn is_shell(profile: &LaunchProfile) -> bool { + profile.kind == LaunchKind::Shell && profile.id.starts_with("shell:") +} + +/// A tab running the terminal editor named by `editor` (the value of +/// `$VISUAL` / `$EDITOR`) on `path`. `None` when it is empty or names the +/// system's own editor or opener: the file then opens through the OS. +/// +/// The value is split like a shell command line (`code --wait`, +/// `"C:\Program Files\Vim\vim.exe" -n`); an absolute path that `exists` as +/// a whole is taken as the program even with spaces in it, the way Windows +/// users set it. +pub fn editor_profile(editor: Option<&str>, path: &Path, exists: impl Fn(&Path) -> bool) -> Option { + let editor = editor?.trim(); + let whole = Path::new(editor); + let mut parts = if whole.is_absolute() && exists(whole) { + vec![editor.to_owned()] + } else { + split_command(editor, cfg!(windows)) + } + .into_iter(); + let program = parts.next()?; + let name = program.rsplit(['/', '\\']).next().unwrap_or_default().to_lowercase(); + if SYSTEM_OPENERS.contains(&name.strip_suffix(".exe").unwrap_or(&name)) { + return None; + } + Some(LaunchProfile { + id: "editor:config".into(), + name: "config.toml".into(), + kind: LaunchKind::Shell, + description: "Editing configuration".into(), + available: true, + command: CommandSpec::new(program).args(parts).arg(path.display().to_string()), + }) +} + +/// Splits a command line into words: whitespace separates them, and +/// single or double quotes keep spaces in one. Outside single quotes a +/// backslash escapes the next character, except on `windows`, where it +/// separates path components. +fn split_command(line: &str, windows: bool) -> Vec { + let mut words = Vec::new(); + let mut word: Option = None; + let mut quote: Option = None; + let mut chars = line.chars(); + while let Some(c) = chars.next() { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (None, '\'' | '"') => { + quote = Some(c); + word.get_or_insert_default(); + } + (None, c) if c.is_whitespace() => words.extend(word.take()), + (q, '\\') if !windows && q != Some('\'') => { + word.get_or_insert_default().extend(chars.next()); + } + (_, c) => word.get_or_insert_default().push(c), + } + } + words.extend(word); + words +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nothing_exists(_: &Path) -> bool { + false + } + + #[test] + fn config_opens_in_a_tab_only_with_a_terminal_editor() { + let path = Path::new("/cfg/config.toml"); + let profile = editor_profile(Some("nvim -u NONE"), path, nothing_exists).unwrap(); + assert_eq!(profile.command.program, "nvim"); + assert_eq!(profile.command.args, ["-u", "NONE", "/cfg/config.toml"]); + assert!(editor_profile(None, path, nothing_exists).is_none()); + assert!(editor_profile(Some(" "), path, nothing_exists).is_none()); + let full_path = if cfg!(windows) { r"C:\Windows\notepad.exe" } else { "/usr/bin/xdg-open" }; + for system in ["notepad", full_path, "xdg-open", "open -e", "TextEdit"] { + assert!(editor_profile(Some(system), path, nothing_exists).is_none(), "{system}"); + } + } + + #[test] + fn an_existing_path_with_spaces_is_one_program() { + let editor = if cfg!(windows) { r"C:\Program Files\Neovim\bin\nvim.exe" } else { "/opt/My Editor/bin/ed" }; + let profile = editor_profile(Some(editor), Path::new("/cfg/config.toml"), |p| p == Path::new(editor)); + assert_eq!(profile.unwrap().command.program, editor); + } + + #[test] + fn command_lines_split_like_a_shell() { + assert_eq!(split_command(" code --wait ", false), ["code", "--wait"]); + assert_eq!(split_command(r#""/opt/My Editor/ed" -n"#, false), ["/opt/My Editor/ed", "-n"]); + assert_eq!(split_command(r"vim -c 'set ft=toml'", false), ["vim", "-c", "set ft=toml"]); + assert_eq!(split_command(r"/opt/My\ Editor/ed", false), ["/opt/My Editor/ed"]); + assert_eq!(split_command(r#"ed """#, false), ["ed", ""]); + } + + #[test] + fn windows_backslashes_stay_in_paths() { + assert_eq!( + split_command(r#""C:\Program Files\Vim\vim.exe" -n"#, true), + [r"C:\Program Files\Vim\vim.exe", "-n"] + ); + assert_eq!(split_command(r"C:\tools\nvim.exe", true), [r"C:\tools\nvim.exe"]); + } + + #[test] + fn only_local_shells_are_shells() { + let shell = redshell_core::shell::local_shell_profile(&Default::default()); + assert!(is_shell(&shell)); + let editor = editor_profile(Some("nvim"), Path::new("/c.toml"), nothing_exists).unwrap(); + assert!(!is_shell(&editor)); + let agent = LaunchProfile { kind: LaunchKind::Agent, ..shell }; + assert!(!is_shell(&agent)); + } +} diff --git a/crates/redshell-app/src/find_bar.rs b/crates/redshell-app/src/find_bar.rs index 5df8ed8..d91535e 100644 --- a/crates/redshell-app/src/find_bar.rs +++ b/crates/redshell-app/src/find_bar.rs @@ -119,7 +119,7 @@ impl Render for FindBar { let (label, error) = match self.status { FindStatus::Found(s) if s.total > 0 => (format!("{} of {}", s.current, s.total), false), FindStatus::Found(_) if has_text => ("No results".to_owned(), true), - FindStatus::Invalid => ("Invalid regex".to_owned(), true), + FindStatus::Invalid => ("Not a valid pattern".to_owned(), true), _ => (String::new(), false), }; let toggle = |id: &'static str, icon: IconName, tip: &'static str, on: bool, regex: bool| { @@ -143,8 +143,10 @@ impl Render for FindBar { div() .id("find-bar") .capture_key_down(cx.listener(Self::on_key)) - // Keys and clicks stay in the bar instead of reaching the terminal. - .on_key_down(|_, _, cx| cx.stop_propagation()) + // Clicks stay in the bar instead of reaching the terminal. Keys must + // keep propagating: a handled key never reaches the platform input + // handler that types it into the field, and the terminal already + // ignores keys while the bar has focus. .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation()) .on_mouse_down(MouseButton::Middle, |_, _, cx| cx.stop_propagation()) diff --git a/crates/redshell-app/src/image_paste.rs b/crates/redshell-app/src/image_paste.rs new file mode 100644 index 0000000..b70130c --- /dev/null +++ b/crates/redshell-app/src/image_paste.rs @@ -0,0 +1,161 @@ +//! Paste Image: hands a clipboard image to a program running on another +//! machine. +//! +//! AI agents (Claude Code, Codex, Gemini CLI) read images from the system +//! clipboard on their image-paste key, which an agent on an SSH host cannot +//! reach. For such panes the image is uploaded there and its path typed into +//! the prompt, which the agents take as an attachment. Local and WSL panes, +//! and clipboards holding text, get the key itself. + +use std::io::Cursor; +use std::time::Duration; + +use futures::future::{Either, select}; +use gpui::{AppContext as _, ClipboardEntry, Context, Image, ImageFormat, Task}; +use redshell_core::LaunchProfile; +use redshell_remote::{ImageType, MuxTarget, PastedImage, shell_join, upload_image}; +use redshell_ui::ToastKind; + +use super::{TerminalView, TerminalViewEvent}; +use crate::state::AppState; + +#[cfg(any(windows, test))] +#[path = "clipboard_dib.rs"] +mod clipboard_dib; + +/// Uploads taking longer than this get a progress toast. +const SLOW_UPLOAD: Duration = Duration::from_secs(1); + +/// The target to upload to: panes on an SSH host, while the setting is on. +/// Local programs read the clipboard themselves, and so do agents in WSL +/// (Claude Code reaches the Windows clipboard from there). +fn upload_target(enabled: bool, target: Option) -> Option { + target.filter(|t| enabled && matches!(t, MuxTarget::Remote(_))) +} + +/// The clipboard's image, when it holds one in a format the agents can be +/// given and no text (text goes to the program as the key itself). +fn clipboard_image(entries: &[ClipboardEntry]) -> Option { + let mut image = None; + for entry in entries { + match entry { + ClipboardEntry::Image(i) if i.format != ImageFormat::Svg => image = Some(i), + ClipboardEntry::Image(_) => {} + ClipboardEntry::String(_) => return None, + } + } + image.cloned() +} + +/// The image as a file the agents accept: BMP and TIFF become PNG. +fn encode(image: Image) -> anyhow::Result { + let kind = match image.format { + ImageFormat::Png => ImageType::Png, + ImageFormat::Jpeg => ImageType::Jpeg, + ImageFormat::Gif => ImageType::Gif, + ImageFormat::Webp => ImageType::Webp, + ImageFormat::Bmp => return to_png(&image.bytes, image::ImageFormat::Bmp), + ImageFormat::Tiff => return to_png(&image.bytes, image::ImageFormat::Tiff), + ImageFormat::Svg => anyhow::bail!("SVG images can't be attached"), + }; + Ok(PastedImage { kind, bytes: image.bytes }) +} + +fn to_png(bytes: &[u8], format: image::ImageFormat) -> anyhow::Result { + let mut png = Cursor::new(Vec::new()); + image::load_from_memory_with_format(bytes, format)?.write_to(&mut png, image::ImageFormat::Png)?; + Ok(PastedImage { kind: ImageType::Png, bytes: png.into_inner() }) +} + +/// Starts uploading the clipboard image for the pane running `profile`, or +/// returns `None` to let the key through to the program. +pub(super) fn start(profile: &LaunchProfile, cx: &mut Context) -> Option> { + let state = cx.global::(); + let located = MuxTarget::of_profile(profile, &state.settings.multiplexer, &state.ssh); + let target = upload_target(state.settings.terminal.paste_image_upload, located)?; + let image = match cx.read_from_clipboard() { + Some(item) => clipboard_image(item.entries())?, + // GPUI skips bitmap-only clipboards, which PrintScreen leaves. + #[cfg(windows)] + None => Image::from_bytes(ImageFormat::Bmp, clipboard_dib::read()?), + #[cfg(not(windows))] + None => return None, + }; + let host = target.label(); + Some(cx.spawn(async move |view, cx| { + let upload = cx.background_spawn(async move { upload_image(&target, &encode(image)?) }); + let slow = cx.background_executor().timer(SLOW_UPLOAD); + let result = match select(upload, slow).await { + Either::Left((result, _)) => result, + Either::Right(((), upload)) => { + let title = format!("Uploading the image to {host}…"); + let _ = view.update(cx, |_, cx| cx.emit(TerminalViewEvent::Toast(ToastKind::Info, title, None))); + upload.await + } + }; + let _ = view.update(cx, |view, cx| { + // This task is finishing: detaching (rather than dropping) it does not cancel it. + if let Some(this_task) = view.image_upload.take() { + this_task.detach(); + } + match result { + Ok(path) => view.paste(&format!("{} ", shell_join(&[path]))), + Err(err) => { + let title = format!("Couldn't upload the image to {host}"); + cx.emit(TerminalViewEvent::Toast(ToastKind::Error, title, Some(format!("{err:#}")))); + } + } + }); + })) +} + +#[cfg(test)] +mod tests { + use redshell_core::settings::SshHost; + use redshell_remote::SshProfile; + + use super::*; + + fn image(format: ImageFormat) -> ClipboardEntry { + ClipboardEntry::Image(Image::from_bytes(format, vec![1, 2, 3])) + } + + fn text() -> ClipboardEntry { + ClipboardEntry::from("hello".to_owned()) + } + + #[test] + fn uploads_only_for_ssh_panes_while_enabled() { + let ssh = SshProfile { host: SshHost::default(), program: "ssh".into(), keep_alive_secs: 0, from_config: true }; + let remote = || Some(MuxTarget::Remote(Box::new(ssh.clone()))); + let wsl = || Some(MuxTarget::Wsl { distribution: None }); + assert!(upload_target(true, remote()).is_some()); + assert!(upload_target(true, wsl()).is_none()); + assert!(upload_target(false, remote()).is_none()); + assert!(upload_target(true, Some(MuxTarget::Local)).is_none()); + assert!(upload_target(true, None).is_none()); + } + + #[test] + fn takes_an_image_only_without_text() { + let pick = |entries: Vec| clipboard_image(&entries).map(|i| i.format); + assert_eq!(pick(vec![image(ImageFormat::Png)]), Some(ImageFormat::Png)); + assert_eq!(pick(vec![image(ImageFormat::Tiff)]), Some(ImageFormat::Tiff)); + assert_eq!(pick(vec![text()]), None); + assert_eq!(pick(vec![image(ImageFormat::Png), text()]), None); + assert_eq!(pick(vec![image(ImageFormat::Svg)]), None); + assert_eq!(pick(vec![]), None); + } + + #[test] + fn converts_bitmaps_to_png() { + let mut bmp = Cursor::new(Vec::new()); + image::RgbImage::new(2, 2).write_to(&mut bmp, image::ImageFormat::Bmp).unwrap(); + let pasted = encode(Image::from_bytes(ImageFormat::Bmp, bmp.into_inner())).unwrap(); + assert_eq!(pasted.kind, ImageType::Png); + assert_eq!(image::guess_format(&pasted.bytes).unwrap(), image::ImageFormat::Png); + + let jpeg = encode(Image::from_bytes(ImageFormat::Jpeg, vec![0xff, 0xd8])).unwrap(); + assert_eq!((jpeg.kind, jpeg.bytes), (ImageType::Jpeg, vec![0xff, 0xd8])); + } +} diff --git a/crates/redshell-app/src/main.rs b/crates/redshell-app/src/main.rs index 1c2235c..e335e8b 100644 --- a/crates/redshell-app/src/main.rs +++ b/crates/redshell-app/src/main.rs @@ -3,42 +3,46 @@ // Release builds on Windows are GUI apps: don't open a console window next to them. #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] +mod closing; mod commands; mod confirm; +mod editor; mod find_bar; +mod mux_listings; mod mux_view; mod panes; mod picker; +mod plugins_view; +mod restore; mod search; mod settings_view; mod state; mod terminal_view; +mod update; +mod window_state; mod workspace; -use gpui::{ - App, AppContext as _, Application, Bounds, TitlebarOptions, WindowBackgroundAppearance, WindowBounds, - WindowOptions, px, size, -}; +use gpui::{App, AppContext as _, Application, Window, WindowOptions}; use redshell_core::AppEvent; -use redshell_core::settings::WindowBackground; +use redshell_ui::TitleBar; -use crate::state::{AppState, after_settings_change}; +use crate::state::{AppState, after_settings_change, window_background_appearance}; use crate::workspace::Workspace; -/// Opens a workspace window. Only the first window restores saved tabs. -pub fn open_window(restore: bool, cx: &mut App) { - let appearance = &cx.global::().settings.appearance; - let background = match appearance.window_background { - WindowBackground::Opaque => WindowBackgroundAppearance::Opaque, - WindowBackground::Transparent => WindowBackgroundAppearance::Transparent, - WindowBackground::Blurred => WindowBackgroundAppearance::Blurred, +/// Opens a workspace window. The first one (`beside` is `None`) restores +/// the saved tabs and window bounds; later ones cascade from `beside`. +pub fn open_window(beside: Option<&Window>, cx: &mut App) { + let background = window_background_appearance(cx.global::().settings.appearance.window_background); + let bounds = match beside { + Some(window) => window_state::beside(window, cx), + None => window_state::initial(cx), }; - let bounds = Bounds::centered(None, size(px(1280.), px(800.)), cx); + let restore = beside.is_none(); let options = WindowOptions { - window_bounds: Some(WindowBounds::Windowed(bounds)), - titlebar: Some(TitlebarOptions { title: Some("RedShell".into()), ..Default::default() }), + window_bounds: Some(bounds), + titlebar: Some(TitleBar::titlebar_options("RedShell")), window_background: background, - window_min_size: Some(size(px(480.), px(320.))), + window_min_size: Some(window_state::MIN_SIZE), app_id: Some("dev.redshell.RedShell".into()), ..Default::default() }; @@ -64,8 +68,18 @@ fn main() { } }) .detach(); + // However the app ends (Quit, the last window's close button), plugins + // hear of it and the history is written out. + cx.on_app_quit(|cx| { + cx.global_mut::().emit(AppEvent::Quitting); + if let Some(history) = &cx.global::().history { + history.flush(); + } + async {} + }) + .detach(); - open_window(true, cx); + open_window(None, cx); cx.activate(true); }); } diff --git a/crates/redshell-app/src/mux_listings.rs b/crates/redshell-app/src/mux_listings.rs new file mode 100644 index 0000000..89f7a8e --- /dev/null +++ b/crates/redshell-app/src/mux_listings.rs @@ -0,0 +1,255 @@ +//! The last known tmux / screen sessions of each multiplexer target +//! (`local`, `ssh:`), shared by the session manager and the sidebar of +//! every window. Both show what is known right away while a listing runs in +//! the background, and a failed listing keeps the sessions listed before it. + +use std::collections::{BTreeMap, HashMap}; +use std::time::{Duration, Instant}; + +use gpui::App; +use redshell_core::LaunchProfile; +use redshell_core::settings::MultiplexerSettings; +use redshell_remote::{MuxListing, MuxTarget, NotInstalled, SshProvider}; + +use crate::state::AppState; + +/// How long a target whose listing failed waits before the background +/// timer tries it again (an unreachable host, a key it does not accept). +const FAILURE_BACKOFF: Duration = Duration::from_secs(5 * 60); + +/// Why a target's latest listing failed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ListingError { + /// The multiplexer is not installed there. + NotInstalled(String), + Failed(String), +} + +impl ListingError { + pub fn message(&self) -> &str { + match self { + Self::NotInstalled(m) | Self::Failed(m) => m, + } + } +} + +/// What is known about one target's sessions. +#[derive(Debug, Default)] +pub struct TargetListing { + /// Sessions of the latest listing that succeeded; `None` until one has. + pub sessions: Option>, + /// Why the latest listing failed, if it did. + pub error: Option, + /// A listing is running. + pub refreshing: bool, + /// When the latest listing ended. + finished: Option, + /// Asked for while a listing ran (say, after a kill), so that one may be + /// out of date: list again when it ends. + again: bool, +} + +impl TargetListing { + /// Whether a target polled every `interval` is due for a background + /// listing at `now`. After a failure it waits at least [`FAILURE_BACKOFF`]. + fn due(&self, interval: Duration, now: Instant) -> bool { + let wait = if self.error.is_some() { interval.max(FAILURE_BACKOFF) } else { interval }; + !self.refreshing && self.finished.is_none_or(|at| now.saturating_duration_since(at) >= wait) + } +} + +#[derive(Default)] +pub struct MuxListings { + targets: HashMap, +} + +impl MuxListings { + pub fn get(&self, key: &str) -> Option<&TargetListing> { + self.targets.get(key) + } + + /// Marks a listing of `key` as running; `false` if one already is, which + /// then lists again once it ends. + fn start(&mut self, key: &str) -> bool { + let target = self.targets.entry(key.to_owned()).or_default(); + target.again = target.refreshing; + !std::mem::replace(&mut target.refreshing, true) + } + + /// Records the result of a listing; `true` when it should run again. + fn finish(&mut self, key: &str, result: anyhow::Result>, now: Instant) -> bool { + let target = self.targets.entry(key.to_owned()).or_default(); + target.refreshing = false; + target.finished = Some(now); + match result { + Ok(sessions) => { + target.sessions = Some(sessions); + target.error = None; + } + Err(err) => { + target.error = Some(match err.downcast_ref::() { + Some(missing) => ListingError::NotInstalled(missing.to_string()), + None => ListingError::Failed(format!("{err:#}")), + }); + } + } + std::mem::take(&mut target.again) + } +} + +/// Lists the sessions on `key` in the background (after the listing already +/// running, if there is one) and redraws every window when they arrive. +pub fn refresh(key: &str, cx: &mut App) { + let state = cx.global_mut::(); + let Some(client) = state.mux_client(key) else { return }; + if !state.mux_listings.start(key) { + return; + } + let key = key.to_owned(); + let task = cx.background_executor().spawn(async move { client.snapshot() }); + cx.spawn(async move |cx| { + let result = task.await; + cx.update(|cx| { + if cx.global_mut::().mux_listings.finish(&key, result, Instant::now()) { + refresh(&key, cx); + } + cx.refresh_windows(); + }) + .ok(); + }) + .detach(); +} + +/// [`refresh`] for the background timer: lists `key` only when a target +/// polled every `interval` is due. +pub fn refresh_if_due(key: &str, interval: Duration, cx: &mut App) { + let listings = &cx.global::().mux_listings; + if listings.get(key).is_none_or(|target| target.due(interval, Instant::now())) { + refresh(key, cx); + } +} + +/// An SSH host whose sessions the sidebar shows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SidebarHost { + pub name: String, + /// A tab is open on the host, so the timer keeps its listing fresh. + /// Other hosts are listed only when the user shows the section. + pub in_use: bool, +} + +impl SidebarHost { + /// Its target key, as [`AppState::mux_client`] takes it. + pub fn key(&self) -> String { + format!("ssh:{}", self.name) + } +} + +/// The SSH hosts the sidebar lists sessions for, by name: every host a tab +/// runs on (`open` holds the profiles of all open panes: SSH tabs and tmux +/// or screen sessions there, attached either way), and every host set up +/// to `attach_session`. +pub fn sidebar_hosts<'a>( + open: impl IntoIterator, + settings: &MultiplexerSettings, + ssh: &SshProvider, +) -> Vec { + let configured = ssh.hosts().iter().filter(|p| p.host.attach_session.is_some()); + let mut hosts: BTreeMap = configured.map(|p| (p.host.name.clone(), false)).collect(); + for profile in open { + if let Some(MuxTarget::Remote(p)) = MuxTarget::of_profile(profile, settings, ssh) { + hosts.insert(p.host.name, true); + } + } + hosts.into_iter().map(|(name, in_use)| SidebarHost { name, in_use }).collect() +} + +#[cfg(test)] +mod tests { + use redshell_core::settings::{MultiplexerKind, SshHost, SshSettings}; + use redshell_core::{CommandSpec, LaunchKind}; + use redshell_remote::{MuxClient, MuxSession}; + + use super::*; + + #[test] + fn sidebar_hosts_are_those_in_use_and_those_that_attach_a_session() { + let host = |name: &str, attach: Option<&str>| SshHost { + name: name.into(), + host: format!("{name}.example.com"), + attach_session: attach.map(Into::into), + ..Default::default() + }; + let hosts = vec![host("idle", None), host("dev", Some("main")), host("prod", None), host("db", None)]; + let ssh = SshProvider::new(&SshSettings { hosts, import_ssh_config: false, ..Default::default() }); + let settings = MultiplexerSettings::default(); + let profile = |id: &str, kind| LaunchProfile { + id: id.into(), + kind, + command: CommandSpec::new("ssh"), + ..Default::default() + }; + let prod = + MuxClient::new(MuxTarget::Remote(Box::new(ssh.find("prod").unwrap().clone())), MultiplexerKind::Tmux); + let open = [ + profile("ssh:db", LaunchKind::Ssh), + prod.attach_profile("work"), + profile("tmux-native:ssh:db:main", LaunchKind::Multiplexer), + profile("ssh:gone", LaunchKind::Ssh), + profile("shell:bash", LaunchKind::Shell), + ]; + + let listed = sidebar_hosts(&open, &settings, &ssh); + let listed: Vec<_> = listed.iter().map(|h| (h.name.as_str(), h.in_use)).collect(); + assert_eq!(listed, [("db", true), ("dev", false), ("prod", true)]); + } + + const MINUTE: Duration = Duration::from_secs(60); + + fn session(name: &str) -> MuxListing { + let session = MuxSession { name: name.into(), windows: 1, attached: false, created: None }; + MuxListing { session, windows: Vec::new() } + } + + #[test] + fn a_failure_keeps_the_sessions_listed_before_it() { + let mut listings = MuxListings::default(); + let now = Instant::now(); + assert!(listings.start("ssh:box")); + assert!(!listings.start("ssh:box"), "one listing at a time"); + assert!(listings.finish("ssh:box", Ok(vec![session("main")]), now), "asked for meanwhile"); + assert!(listings.start("ssh:box")); + assert!(!listings.finish("ssh:box", Err(anyhow::anyhow!("Connection timed out")), now)); + + let target = listings.get("ssh:box").unwrap(); + assert_eq!(target.sessions.as_deref(), Some(&[session("main")][..])); + assert_eq!(target.error, Some(ListingError::Failed("Connection timed out".into()))); + assert!(!target.refreshing); + } + + #[test] + fn a_missing_multiplexer_is_told_apart() { + let mut listings = MuxListings::default(); + let missing = NotInstalled("bash: line 1: tmux: command not found".into()); + listings.finish("ssh:box", Err(missing.into()), Instant::now()); + assert!(matches!(listings.get("ssh:box").unwrap().error, Some(ListingError::NotInstalled(_)))); + } + + #[test] + fn listings_are_due_after_their_interval_and_failures_back_off() { + let start = Instant::now(); + let mut target = TargetListing::default(); + assert!(target.due(MINUTE, start), "never listed"); + + target.refreshing = true; + assert!(!target.due(MINUTE, start), "already listing"); + + target = TargetListing { finished: Some(start), ..Default::default() }; + assert!(!target.due(MINUTE, start + MINUTE / 2)); + assert!(target.due(MINUTE, start + MINUTE)); + + target.error = Some(ListingError::Failed("Permission denied".into())); + assert!(!target.due(MINUTE, start + 4 * MINUTE)); + assert!(target.due(MINUTE, start + 5 * MINUTE)); + } +} diff --git a/crates/redshell-app/src/mux_view.rs b/crates/redshell-app/src/mux_view.rs index 1dfea61..c1a30ef 100644 --- a/crates/redshell-app/src/mux_view.rs +++ b/crates/redshell-app/src/mux_view.rs @@ -1,17 +1,21 @@ //! Native tmux / screen session manager. +//! +//! It shows the last known sessions of the selected target right away (see +//! [`crate::mux_listings`]) and replaces them when a fresh listing lands. use gpui::prelude::*; use gpui::{ - App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, KeyDownEvent, SharedString, Subscription, - Task, Window, div, px, + AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, KeyDownEvent, SharedString, + Subscription, Window, div, px, }; use redshell_core::LaunchProfile; -use redshell_remote::{MuxSession, MuxWindow}; +use redshell_remote::{MuxListing, MuxWindow}; use redshell_ui::{ - ActiveTheme, Button, ButtonSize, ButtonVariant, Icon, IconName, IconSize, InputEvent, ListItem, Modal, TextInput, - ThemeExt, alpha, section_label, + ActiveTheme, Button, ButtonSize, ButtonVariant, Icon, IconName, IconSize, InputEvent, ListItem, Modal, StyledExt, + TextInput, ThemeExt, alpha, section_label, }; +use crate::mux_listings; use crate::state::AppState; #[derive(Debug, Clone, PartialEq)] @@ -29,84 +33,47 @@ pub enum MuxEvent { Close, } -enum Listing { - Loading, - Ready(Vec<(MuxSession, Vec)>), - Failed(String), -} - pub struct MuxManager { focus: FocusHandle, targets: Vec<(String, String)>, target: String, - listing: Listing, program: &'static str, new_name: Entity, - _load: Option>, _sub: Subscription, } impl EventEmitter for MuxManager {} +/// The new session name takes the keyboard, so typing a name and Enter +/// creates a session; Esc there closes the manager. impl Focusable for MuxManager { - fn focus_handle(&self, _cx: &App) -> FocusHandle { - self.focus.clone() + fn focus_handle(&self, cx: &App) -> FocusHandle { + self.new_name.focus_handle(cx) } } impl MuxManager { pub fn new(window: &mut Window, cx: &mut Context) -> Self { let focus = cx.focus_handle(); - focus.focus(window); let targets = cx.global::().mux_targets(); let new_name = cx.new(|cx| TextInput::new(cx).placeholder("new session name")); + new_name.read(cx).focus(window); let sub = cx.subscribe_in(&new_name, window, |this: &mut Self, _, ev: &InputEvent, _w, cx| match ev { InputEvent::Submit => this.create(cx), InputEvent::Cancel => cx.emit(MuxEvent::Close), _ => {} }); - let mut this = Self { - focus, - target: "local".into(), - targets, - listing: Listing::Loading, - program: "tmux", - new_name, - _load: None, - _sub: sub, - }; + let mut this = Self { focus, target: "local".into(), targets, program: "tmux", new_name, _sub: sub }; this.reload(cx); this } + /// Lists the selected target's sessions again; what is known meanwhile stays on screen. pub fn reload(&mut self, cx: &mut Context) { let Some(client) = cx.global::().mux_client(&self.target) else { return }; self.program = client.mux.program(); - self.listing = Listing::Loading; + mux_listings::refresh(&self.target, cx); cx.notify(); - let task = cx.background_executor().spawn(async move { - let sessions = client.sessions()?; - Ok::<_, anyhow::Error>( - sessions - .into_iter() - .map(|s| { - let windows = client.windows(&s.name).unwrap_or_default(); - (s, windows) - }) - .collect::>(), - ) - }); - self._load = Some(cx.spawn(async move |this, cx| { - let result = task.await; - this.update(cx, |this, cx| { - this.listing = match result { - Ok(list) => Listing::Ready(list), - Err(err) => Listing::Failed(format!("{err:#}")), - }; - cx.notify(); - }) - .ok(); - })); } fn attach(&self, session: &str, cx: &mut Context) { @@ -127,12 +94,159 @@ impl MuxManager { cx.stop_propagation(); } } + + /// The selected target's sessions: the last known ones under the error + /// of a refresh that failed, or what is happening when none are known. + fn render_body(&self, cx: &mut Context) -> AnyElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + let listing = cx.global::().mux_listings.get(&self.target); + let sessions = listing.and_then(|l| l.sessions.clone()); + let error = listing.and_then(|l| l.error.as_ref()).map(|e| { + div() + .p(px(16.)) + .m(px(12.)) + .rounded(t.radius_md()) + .bg(alpha(ui.destructive, 0.1)) + .text_color(ui.destructive) + .text_size(t.text_sm()) + .child(SharedString::from(e.message().to_owned())) + }); + let muted = + |text: SharedString| div().p(px(20.)).text_color(ui.muted_foreground).text_size(t.text_sm()).child(text); + let content: Vec = match sessions { + None if error.is_some() => Vec::new(), + None => vec![muted("Loading sessions…".into()).into_any_element()], + Some(list) if list.is_empty() => { + let empty = format!("No {} sessions here yet. Create one below.", self.program); + vec![muted(empty.into()).into_any_element()] + } + Some(list) => { + list.iter().enumerate().map(|(i, l)| self.session_card(i, l, cx).into_any_element()).collect() + } + }; + div().flex().flex_col().gap(px(6.)).p(px(10.)).children(error).children(content).into_any_element() + } + + /// One session with its actions and, for tmux, its windows. + fn session_card(&self, i: usize, listing: &MuxListing, cx: &mut Context) -> impl IntoElement + use<> { + let t = cx.theme().clone(); + let ui = *t.ui(); + let MuxListing { session: s, windows } = listing; + let name = s.name.clone(); + let native_name = s.name.clone(); + let native_target = self.target.clone(); + let kill_name = s.name.clone(); + let target = self.target.clone(); + let program = self.program; + let meta = format!( + "{} window{}{}", + s.windows, + if s.windows == 1 { "" } else { "s" }, + if s.attached { " · attached elsewhere" } else { "" } + ); + div() + .flex() + .flex_col() + .gap(px(10.)) + .p(px(12.)) + .rounded(t.radius_lg()) + .border_1() + .border_color(ui.border) + .bg(ui.card) + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child( + div() + .flex() + .flex_none() + .items_center() + .justify_center() + .size(px(32.)) + .rounded(t.radius_md()) + .bg(alpha(ui.muted, 0.8)) + .child(Icon::new(IconName::LayoutGrid).size(IconSize::Medium).color(ui.foreground)), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .truncate_line() + .child(SharedString::from(s.name.clone())), + ) + .child( + div() + .text_size(t.text_xs()) + .text_color(ui.muted_foreground) + .child(SharedString::from(meta)), + ), + ) + .child( + Button::new(("attach", i)) + .label("Attach") + .size(ButtonSize::Sm) + .variant(ButtonVariant::Secondary) + .tooltip(format!("Open the session in a new tab, inside {program}")) + .on_click(cx.listener(move |this, _, _, cx| this.attach(&name, cx))), + ) + .when(program == "tmux", |d| { + d.child( + Button::new(("attach-native", i)) + .label("Open as tabs") + .size(ButtonSize::Sm) + .variant(ButtonVariant::Outline) + .tooltip("Each tmux window opens as a RedShell tab, with its panes") + .on_click(cx.listener(move |_, _, _, cx| { + cx.emit(MuxEvent::AttachNative { + target: native_target.clone(), + session: native_name.clone(), + }) + })), + ) + }) + .child( + Button::new(("kill", i)) + .icon(IconName::Trash) + .size(ButtonSize::Icon) + .variant(ButtonVariant::GhostDestructive) + .tooltip("Kill session…") + .on_click(cx.listener(move |_, _, _, cx| { + cx.emit(MuxEvent::RequestKill { target: target.clone(), session: kill_name.clone() }) + })), + ), + ) + .when(!windows.is_empty(), |d| { + d.child( + div() + .flex() + .flex_wrap() + .gap(px(6.)) + .pl(px(42.)) + .children(windows.iter().map(|w| window_chip(w, &t))), + ) + }) + } } impl Render for MuxManager { fn render(&mut self, _w: &mut Window, cx: &mut Context) -> impl IntoElement { let t = cx.theme().clone(); let ui = *t.ui(); + // Known sessions (or an error) being checked again. + let revalidating = cx + .global::() + .mux_listings + .get(&self.target) + .is_some_and(|l| l.refreshing && (l.sessions.is_some() || l.error.is_some())); + let body = self.render_body(cx); let targets = self.targets.clone().into_iter().map(|(key, label)| { let active = key == self.target; let icon = if key == "local" { IconName::Monitor } else { IconName::Server }; @@ -146,144 +260,6 @@ impl Render for MuxManager { })) }); - let body: gpui::AnyElement = match &self.listing { - Listing::Loading => { - div().p(px(20.)).text_color(ui.muted_foreground).child("Loading sessions…").into_any_element() - } - Listing::Failed(err) => div() - .p(px(16.)) - .m(px(12.)) - .rounded(t.radius_md()) - .bg(alpha(ui.destructive, 0.1)) - .text_color(ui.destructive) - .text_size(t.text_sm()) - .child(SharedString::from(err.clone())) - .into_any_element(), - Listing::Ready(list) if list.is_empty() => div() - .p(px(20.)) - .text_color(ui.muted_foreground) - .text_size(t.text_sm()) - .child(SharedString::from(format!( - "No {} sessions on this target yet. Create one below.", - self.program - ))) - .into_any_element(), - Listing::Ready(list) => div() - .flex() - .flex_col() - .gap(px(6.)) - .p(px(10.)) - .children(list.iter().enumerate().map(|(i, (s, windows))| { - let name = s.name.clone(); - let native_name = s.name.clone(); - let native_target = self.target.clone(); - let kill_name = s.name.clone(); - let target = self.target.clone(); - let program = self.program; - let meta = format!( - "{} window{}{}", - s.windows, - if s.windows == 1 { "" } else { "s" }, - if s.attached { " · attached elsewhere" } else { "" } - ); - div() - .flex() - .flex_col() - .gap(px(10.)) - .p(px(12.)) - .rounded(t.radius_lg()) - .border_1() - .border_color(ui.border) - .bg(ui.card) - .child( - div() - .flex() - .items_center() - .gap(px(10.)) - .child( - div() - .flex() - .flex_none() - .items_center() - .justify_center() - .size(px(32.)) - .rounded(t.radius_md()) - .bg(alpha(ui.muted, 0.8)) - .child( - Icon::new(IconName::LayoutGrid).size(IconSize::Medium).color(ui.foreground), - ), - ) - .child( - div() - .flex() - .flex_col() - .flex_1() - .min_w_0() - .child( - div() - .font_weight(FontWeight::SEMIBOLD) - .whitespace_nowrap() - .text_ellipsis() - .child(SharedString::from(s.name.clone())), - ) - .child( - div() - .text_size(t.text_xs()) - .text_color(ui.muted_foreground) - .child(SharedString::from(meta)), - ), - ) - .child( - Button::new(("attach", i)) - .label("Attach") - .size(ButtonSize::Sm) - .variant(ButtonVariant::Secondary) - .tooltip(format!("Open {program} attach in a new tab")) - .on_click(cx.listener(move |this, _, _, cx| this.attach(&name, cx))), - ) - .when(program == "tmux", |d| { - d.child( - Button::new(("attach-native", i)) - .label("Attach natively") - .size(ButtonSize::Sm) - .variant(ButtonVariant::Outline) - .tooltip("tmux windows become RedShell tabs and panes") - .on_click(cx.listener(move |_, _, _, cx| { - cx.emit(MuxEvent::AttachNative { - target: native_target.clone(), - session: native_name.clone(), - }) - })), - ) - }) - .child( - Button::new(("kill", i)) - .icon(IconName::Trash) - .size(ButtonSize::Icon) - .variant(ButtonVariant::GhostDestructive) - .tooltip("Kill session…") - .on_click(cx.listener(move |_, _, _, cx| { - cx.emit(MuxEvent::RequestKill { - target: target.clone(), - session: kill_name.clone(), - }) - })), - ), - ) - .when(!windows.is_empty(), |d| { - d.child( - div() - .flex() - .flex_wrap() - .gap(px(6.)) - .pl(px(42.)) - .children(windows.iter().map(|w| window_chip(w, &t))), - ) - }) - })) - .into_any_element(), - }; - let this = cx.entity().downgrade(); Modal::new("mux") .width(px(820.)) @@ -325,10 +301,16 @@ impl Render for MuxManager { .border_color(ui.border) .child( div() - .flex_1() .font_weight(FontWeight::SEMIBOLD) .child(SharedString::from(format!("{} sessions", self.program))), ) + .child( + div() + .flex_1() + .text_size(t.text_xs()) + .text_color(ui.muted_foreground) + .when(revalidating, |d| d.child("Refreshing…")), + ) .child( Button::new("refresh") .label("Refresh") diff --git a/crates/redshell-app/src/overlays.rs b/crates/redshell-app/src/overlays.rs new file mode 100644 index 0000000..a371036 --- /dev/null +++ b/crates/redshell-app/src/overlays.rs @@ -0,0 +1,179 @@ +//! The overlays commands open (pickers, rename, settings, the multiplexer +//! manager), each with the handler of its events. +//! +//! This is a child module of `workspace` so it can manage the overlay +//! directly. + +use super::*; + +impl Workspace { + /// The command palette: built-in commands, then plugin commands. + pub(super) fn open_command_palette(&mut self, window: &mut Window, cx: &mut Context) { + let items = self.command_items(cx); + self.open_picker(PickerKind::Commands, "Commands", "Type a command…", items, None, window, cx); + } + + /// A picker of launch profiles: all of them, or those of one `kind`. + pub(super) fn open_profile_picker( + &mut self, + kind: Option, + title: &str, + placeholder: &str, + window: &mut Window, + cx: &mut Context, + ) { + let state = cx.global::(); + let profiles = match kind { + Some(kind) => state.profiles_of(kind).cloned().collect(), + None => state.all_profiles().to_vec(), + }; + let items = Self::profile_items(profiles); + self.open_picker(PickerKind::Launch, title, placeholder, items, None, window, cx); + } + + /// The theme picker; highlighting a theme previews it. + pub(super) fn open_theme_picker(&mut self, window: &mut Window, cx: &mut Context) { + let items = cx + .global::() + .themes + .iter() + .map(|th| PickerItem { + id: th.id.clone(), + icon: Some(if th.is_dark() { IconName::Moon } else { IconName::Sun }), + title: th.name.clone(), + subtitle: format!("{} · {}", if th.is_dark() { "dark" } else { "light" }, th.source), + ..Default::default() + }) + .collect(); + let current = cx.theme().theme.id.clone(); + self.open_picker( + PickerKind::Themes, + "Themes (live preview)", + "Search themes…", + items, + Some(current), + window, + cx, + ); + } + + /// The snippets plugins contributed, to type into the active pane. + pub(super) fn open_snippet_picker(&mut self, window: &mut Window, cx: &mut Context) { + let items = cx + .global::() + .plugins + .contributions() + .snippets + .iter() + .map(|s| PickerItem { + id: s.name.clone(), + icon: Some(IconName::Scissors), + title: s.name.clone(), + subtitle: s.text.clone(), + ..Default::default() + }) + .collect(); + self.open_picker(PickerKind::Snippets, "Snippets", "Insert into the terminal…", items, None, window, cx); + } + + /// The session history browser, or a hint when recording is off. + pub(super) fn open_history_browser(&mut self, window: &mut Window, cx: &mut Context) { + if cx.global::().history.is_none() { + return self.history_disabled_toast(cx); + } + let items = self.history_items(cx); + self.open_picker(PickerKind::History, "Session history", "Filter sessions…", items, None, window, cx); + } + + /// Asks for a new title of the active tab (empty: automatic again). + pub(super) fn open_rename(&mut self, window: &mut Window, cx: &mut Context) { + let Some(tab) = self.tabs.get(self.active) else { return }; + let tab_id = tab.id; + let current = tab.title(cx); + let input = cx.new(|cx| { + let mut i = TextInput::new(cx).placeholder("Tab title (empty = automatic)"); + i.set_value(current, cx); + i.select_all(cx); + i + }); + input.read(cx).focus(window); + let sub = cx.subscribe_in(&input, window, |this, input, ev: &InputEvent, window, cx| match ev { + InputEvent::Submit => { + let title = input.read(cx).value().trim().to_owned(); + if let Some(Overlay::Rename(_, tab_id)) = this.overlay { + this.rename_tab(tab_id, &title, window, cx); + } + this.close_overlay(window, cx); + } + InputEvent::Cancel => this.close_overlay(window, cx), + _ => {} + }); + self.set_overlay(Overlay::Rename(input, tab_id), Some(sub), cx); + } + + /// Gives tab `tab_id` the name `title`, or its automatic title back when + /// empty. The name is saved with the open tabs, and also becomes the + /// title of the active pane's recording in the history. + fn rename_tab(&mut self, tab_id: usize, title: &str, window: &mut Window, cx: &mut Context) { + let Some(tab) = self.tabs.iter_mut().find(|t| t.id == tab_id) else { return }; + tab.name = (!title.is_empty()).then(|| title.to_owned()); + let session = tab.active.read(cx).session; + if let Some(h) = &cx.global::().history + && !title.is_empty() + { + let _ = h.rename(session, title); + } + self.persist(window, cx); + } + + pub(super) fn open_settings(&mut self, window: &mut Window, cx: &mut Context) { + let view = cx.new(|cx| SettingsView::new(window, cx)); + let sub = cx.subscribe_in(&view, window, |this, _, ev: &SettingsEvent, window, cx| match ev { + SettingsEvent::Close => this.close_overlay(window, cx), + SettingsEvent::EditFile => { + this.close_overlay(window, cx); + this.run_command("settings.edit_file", window, cx); + } + SettingsEvent::ImportTheme => this.import_theme_from_clipboard(cx), + SettingsEvent::RevealConfig => this.run_command("settings.reveal", window, cx), + }); + self.set_overlay(Overlay::Settings(view), Some(sub), cx); + } + + pub(super) fn open_plugin_list(&mut self, window: &mut Window, cx: &mut Context) { + let view = cx.new(|cx| PluginList::new(window, cx)); + let sub = + cx.subscribe_in(&view, window, |this, _, _: &DismissEvent, window, cx| this.close_overlay(window, cx)); + self.set_overlay(Overlay::Plugins(view), Some(sub), cx); + } + + /// The tmux / screen session manager. It lists the local sessions as it + /// opens, for the sidebar too. + pub(super) fn open_mux_manager(&mut self, window: &mut Window, cx: &mut Context) { + let view = cx.new(|cx| MuxManager::new(window, cx)); + let sub = cx.subscribe_in(&view, window, |this, _, ev: &MuxEvent, window, cx| match ev { + MuxEvent::Attach(profile) => { + this.close_overlay(window, cx); + this.open_profile(profile.clone(), window, cx); + } + MuxEvent::RequestKill { target, session } => { + this.close_overlay(window, cx); + this.confirm( + format!("Kill session “{session}”?"), + KILL_STOPS_PROGRAMS, + "Kill session", + ConfirmAction::KillMux { target: target.clone(), session: session.clone() }, + None, + window, + cx, + ); + } + MuxEvent::AttachNative { target, session } => { + this.close_overlay(window, cx); + this.attach_native(target, session, window, cx); + } + MuxEvent::Close => this.close_overlay(window, cx), + }); + self.set_overlay(Overlay::Mux(view), Some(sub), cx); + } +} diff --git a/crates/redshell-app/src/panes.rs b/crates/redshell-app/src/panes.rs index 1d65ff2..9a4fe81 100644 --- a/crates/redshell-app/src/panes.rs +++ b/crates/redshell-app/src/panes.rs @@ -3,9 +3,15 @@ //! The tree is generic over its leaf so the layout logic (splitting, //! closing, resizing) is plain data and unit-tested without a window. //! Every split keeps one size ratio per child; ratios sum to 1. +//! +//! A tree of session ids is what is saved at exit to bring a tab's layout +//! back (see `restore`), so the tree serialises with serde. + +use serde::{Deserialize, Serialize}; /// Direction children of a split are laid out in. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum Axis { /// Side by side (a vertical divider between children). Horizontal, @@ -16,12 +22,79 @@ pub enum Axis { /// Smallest share a pane can be dragged down to. pub const MIN_RATIO: f32 = 0.05; -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum PaneNode { Leaf(L), Split { axis: Axis, children: Vec>, ratios: Vec }, } +impl PaneNode { + /// The same layout with every leaf turned into `f(leaf)`, in reading order. + pub fn map(self, mut f: impl FnMut(L) -> M) -> PaneNode { + self.map_with(&mut f) + } + + fn map_with(self, f: &mut dyn FnMut(L) -> M) -> PaneNode { + match self { + PaneNode::Leaf(l) => PaneNode::Leaf(f(l)), + PaneNode::Split { axis, children, ratios } => { + PaneNode::Split { axis, children: children.into_iter().map(|c| c.map_with(f)).collect(), ratios } + } + } + } + + /// The layout with every leaf turned into `f(leaf)`, without the leaves + /// it gives `None` for. The rest of a split share a dropped pane's space + /// in proportion, and a split left with one pane becomes that pane. + /// `None` when no leaf is left. + pub fn filter_map(self, mut f: impl FnMut(L) -> Option) -> Option> { + self.filter_map_with(&mut f) + } + + fn filter_map_with(self, f: &mut dyn FnMut(L) -> Option) -> Option> { + let (axis, children, ratios) = match self { + PaneNode::Leaf(l) => return f(l).map(PaneNode::Leaf), + PaneNode::Split { axis, children, ratios } => (axis, children, ratios), + }; + let (mut kept, mut shares) = (Vec::new(), Vec::new()); + for (child, share) in children.into_iter().zip(ratios) { + match child.filter_map_with(f) { + None => {} + // A collapsed child with this split's axis merges into it. + Some(PaneNode::Split { axis: inner, children, ratios }) if inner == axis => { + kept.extend(children); + shares.extend(ratios.into_iter().map(|r| r * share)); + } + Some(child) => { + kept.push(child); + shares.push(share); + } + } + } + if kept.len() < 2 { + return kept.pop(); + } + let total: f32 = shares.iter().sum(); + Some(PaneNode::Split { axis, children: kept, ratios: shares.into_iter().map(|r| r / total).collect() }) + } + + /// Whether every split has two or more children, each with a finite, + /// positive share: what the layout code relies on. A tree read back from + /// disk is checked before it is used. + pub fn is_sound(&self) -> bool { + match self { + PaneNode::Leaf(_) => true, + PaneNode::Split { children, ratios, .. } => { + children.len() >= 2 + && ratios.len() == children.len() + && ratios.iter().all(|r| r.is_finite() && *r > 0.0) + && children.iter().all(Self::is_sound) + } + } + } +} + impl PaneNode { /// Every leaf, in reading order. pub fn leaves(&self) -> Vec { @@ -312,6 +385,83 @@ mod tests { assert!(close(&ratios(&n), &[0.3, 0.7])); } + /// H[1, V[2, 3]] with the vertical split dragged to 0.8 / 0.2. + fn three_panes() -> Node { + let mut n = Node::Leaf(1); + n.split(&1, 2, Axis::Horizontal); + n.split(&2, 3, Axis::Vertical); + n.move_divider(&[1], 0, 0.8); + n + } + + #[test] + fn layout_round_trips_through_json() { + let n = three_panes(); + let json = serde_json::to_string(&n).unwrap(); + let back: Node = serde_json::from_str(&json).unwrap(); + assert_eq!(back, n); + assert!(back.is_sound()); + } + + #[test] + fn map_keeps_the_layout() { + let n = three_panes().map(|l| l * 10); + assert_eq!(n.leaves(), vec![10, 20, 30]); + assert_eq!(n.map(|l| l / 10), three_panes()); + } + + /// Keeps the leaves `keep` accepts. + fn keep(n: Node, keep: impl Fn(u32) -> bool) -> Option { + n.filter_map(|l| keep(l).then_some(l)) + } + + #[test] + fn filter_map_drops_leaves_and_collapses() { + // 2 goes and V[3] collapses into H[1, 3]; 3 keeps the whole half. + let n = keep(three_panes(), |l| l != 2).unwrap(); + assert_eq!(n.leaves(), vec![1, 3]); + assert!(matches!(&n, PaneNode::Split { axis: Axis::Horizontal, .. })); + assert!(close(&ratios(&n), &[0.5, 0.5])); + assert!(n.is_sound()); + + // 1 goes and the vertical split is all that is left, sizes intact. + let n = keep(three_panes(), |l| l != 1).unwrap(); + assert!(matches!(&n, PaneNode::Split { axis: Axis::Vertical, .. })); + assert!(close(&ratios(&n), &[0.8, 0.2])); + + assert_eq!(keep(three_panes(), |l| l == 3), Some(Node::Leaf(3))); + assert_eq!(keep(three_panes(), |_| true), Some(three_panes())); + assert_eq!(keep(three_panes(), |_| false), None); + assert_eq!(three_panes().filter_map(|l| (l != 2).then(|| l * 10)).unwrap().leaves(), vec![10, 30]); + } + + #[test] + fn filter_map_shares_space_in_proportion_and_merges_same_axis_splits() { + // H[1, V[2, H[3, 4]]]: without 2, H[3, 4] joins the outer split. + let mut n = Node::Leaf(1); + n.split(&1, 2, Axis::Horizontal); + n.split(&2, 3, Axis::Vertical); + n.split(&3, 4, Axis::Horizontal); + let n = keep(n, |l| l != 2).unwrap(); + assert_eq!(n.leaves(), vec![1, 3, 4]); + assert!(close(&ratios(&n), &[0.5, 0.25, 0.25])); + + let mut n = Node::Leaf(1); + n.split(&1, 2, Axis::Horizontal); + n.split(&2, 3, Axis::Horizontal); + let n = keep(n, |l| l != 3).unwrap(); + assert!(close(&ratios(&n), &[2.0 / 3.0, 1.0 / 3.0])); + } + + #[test] + fn unsound_layouts_are_recognised() { + let split = |children: Vec, ratios: Vec| Node::Split { axis: Axis::Vertical, children, ratios }; + assert!(!split(vec![Node::Leaf(1), Node::Leaf(2)], vec![1.0]).is_sound()); + assert!(!split(vec![Node::Leaf(1)], vec![1.0]).is_sound()); + assert!(!split(vec![Node::Leaf(1), Node::Leaf(2)], vec![0.5, f32::NAN]).is_sound()); + assert!(!split(vec![Node::Leaf(1), split(vec![], vec![])], vec![0.5, 0.5]).is_sound()); + } + #[test] fn divider_positions_are_cumulative() { assert!(close(÷r_positions(&[0.5, 0.25, 0.25]), &[0.5, 0.75])); diff --git a/crates/redshell-app/src/plugins_view.rs b/crates/redshell-app/src/plugins_view.rs new file mode 100644 index 0000000..693b87b --- /dev/null +++ b/crates/redshell-app/src/plugins_view.rs @@ -0,0 +1,96 @@ +//! The list of loaded plugins. It holds the keyboard while open, and Esc +//! or a click beside it closes it ([`DismissEvent`]). + +use gpui::prelude::*; +use gpui::{ + App, Context, DismissEvent, EventEmitter, FocusHandle, Focusable, KeyDownEvent, SharedString, Window, div, px, +}; +use redshell_ui::{IconName, ListItem, Modal, ThemeExt, modal_header}; + +use crate::state::AppState; + +pub struct PluginList { + focus: FocusHandle, +} + +impl EventEmitter for PluginList {} + +impl Focusable for PluginList { + fn focus_handle(&self, _cx: &App) -> FocusHandle { + self.focus.clone() + } +} + +impl PluginList { + pub fn new(window: &mut Window, cx: &mut Context) -> Self { + let focus = cx.focus_handle(); + focus.focus(window); + Self { focus } + } + + fn on_key(&mut self, ev: &KeyDownEvent, _w: &mut Window, cx: &mut Context) { + if ev.keystroke.key == "escape" { + cx.emit(DismissEvent); + cx.stop_propagation(); + } + } +} + +impl Render for PluginList { + fn render(&mut self, _w: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + let state = cx.global::(); + let plugins: Vec<_> = state.plugins.plugins().cloned().collect(); + let dir = state.paths.plugins_dir().display().to_string(); + let this = cx.entity().downgrade(); + Modal::new("plugins") + .width(px(560.)) + .on_backdrop_click(move |_, cx| { + this.update(cx, |_, cx| cx.emit(DismissEvent)).ok(); + }) + .child( + div() + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::on_key)) + .flex() + .flex_col() + .min_h_0() + .child(modal_header( + "Plugins", + Some(format!("To install a plugin, put its folder in {dir}").into()), + cx, + )) + .child( + div() + .id("plugin-list") + .min_h_0() + .overflow_y_scroll() + .p(px(12.)) + .flex() + .flex_col() + .gap(px(4.)) + .children(plugins.into_iter().map(|p| { + ListItem::new( + SharedString::from(format!("plugin-{}", p.id)), + format!("{} {}", p.name, p.version), + ) + .icon(IconName::Puzzle) + .subtitle(if p.description.is_empty() { + p.id.clone() + } else { + p.description.clone() + }) + })), + ) + .child( + div() + .px(px(24.)) + .pb(px(16.)) + .text_size(t.text_xs()) + .text_color(ui.muted_foreground) + .child("Plugins can add commands, themes, snippets and things to open in a new tab."), + ), + ) + } +} diff --git a/crates/redshell-app/src/restore.rs b/crates/redshell-app/src/restore.rs new file mode 100644 index 0000000..b69b5b5 --- /dev/null +++ b/crates/redshell-app/src/restore.rs @@ -0,0 +1,328 @@ +//! How each tab saved at exit comes back on the next start. +//! +//! A tab comes back with its name and its split layout, minus the panes +//! that cannot come back (their neighbours take their space). Sessions no +//! saved layout holds, which is every tab of a RedShell that saved no +//! layouts, come back as a tab each. +//! +//! Panes attached to a tmux or screen session re-attach to that session +//! instead of starting over. A session the user picked is never created +//! again: if it is gone, the pane shows the multiplexer's error. Sessions +//! RedShell named itself (`multiplexer.auto_attach_local`) are plain shells +//! to the user, so after a reboot they simply start fresh, in the last +//! directory RedShell knew for the pane (tmux does not report the directory +//! of the shell inside it, so usually the one the pane was opened in). + +use std::collections::{HashMap, HashSet}; + +use redshell_core::{LaunchKind, SessionId}; +use redshell_history::{SavedTab, SessionRecord}; +use redshell_remote::{MuxRef, NativeRef}; +use serde::{Deserialize, Serialize}; + +use crate::editor::is_shell; +use crate::panes::PaneNode; + +/// What is saved of a tab's panes: their sessions in the split layout, and +/// the one that was active. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TabLayout { + pub root: PaneNode, + pub active: SessionId, +} + +impl TabLayout { + /// A tab of one pane. + pub fn single(session: SessionId) -> Self { + Self { root: PaneNode::Leaf(session), active: session } + } +} + +/// How one saved pane is reopened. +#[derive(Debug, Clone, PartialEq)] +pub enum PaneStep { + /// Runs the saved command again. + Relaunch { + record: Box, + /// Start in the pane's last known directory. + last_cwd: bool, + /// Replay the recorded scrollback first (multiplexers redraw instead). + replay: bool, + }, + /// Re-attaches a session the user chose, without creating it. + Reattach { record: Box, mux: MuxRef }, +} + +/// How one saved tab, or one natively attached tmux session, is reopened. +#[derive(Debug, PartialEq)] +pub enum RestoreStep { + /// Opens a tab of `panes`, focusing `active_pane` when it came back. + /// `active` marks the tab that was active. + Tab { panes: PaneNode, active_pane: SessionId, name: Option, active: bool }, + /// Re-attaches a tmux session natively, which brings back every window + /// of it in tmux's layout. `sessions` are the saved records of its panes. + Native { native: NativeRef, sessions: Vec }, +} + +/// What becomes of one saved session. +enum Reopen { + Pane(PaneStep), + Native(NativeRef), +} + +/// How `record` comes back, if it does. +fn reopen(record: SessionRecord) -> Option { + if let Some(native) = NativeRef::parse(&record.profile.id) { + return Some(Reopen::Native(native)); + } + // Panes without a command, and local programs opened on a file (the + // config editor), are not started again. + if record.profile.command.program.is_empty() + || record.profile.kind == LaunchKind::Shell && !is_shell(&record.profile) + { + return None; + } + let kind = record.profile.kind; + let mux = MuxRef::parse(&record.profile.id).filter(|_| kind == LaunchKind::Multiplexer); + Some(Reopen::Pane(match mux { + Some(mux) if !mux.is_generated() => PaneStep::Reattach { record: Box::new(record), mux }, + generated => PaneStep::Relaunch { + last_cwd: is_shell(&record.profile) || generated.is_some(), + replay: kind != LaunchKind::Multiplexer, + record: Box::new(record), + }, + })) +} + +/// Turns the sessions open at exit (in tab order) and the saved tabs into +/// restore steps. A native tmux session is attached once, where its first +/// pane was. A saved layout that does not hold together is ignored, so its +/// sessions come back as a tab each. +pub fn plan(records: Vec, saved: Vec>) -> Vec { + let mut tabs: Vec<_> = saved.into_iter().filter(|t| t.layout.root.is_sound()).collect(); + let laid_out: HashSet = tabs.iter().flat_map(|t| t.layout.root.leaves()).collect(); + let single = |id| SavedTab { layout: TabLayout::single(id), name: None, active: false }; + tabs.extend(records.iter().map(|r| r.id).filter(|id| !laid_out.contains(id)).map(single)); + let mut open: HashMap = records.into_iter().map(|r| (r.id, r)).collect(); + + let mut steps = Vec::new(); + for tab in tabs { + let panes = tab.layout.root.filter_map(|id| match reopen(open.remove(&id)?)? { + Reopen::Pane(step) => Some(step), + Reopen::Native(native) => { + add_native(&mut steps, native, id); + None + } + }); + if let Some(panes) = panes { + steps.push(RestoreStep::Tab { panes, active_pane: tab.layout.active, name: tab.name, active: tab.active }); + } + } + steps +} + +/// Adds `session` to the step attaching `native`, or adds that step. +fn add_native(steps: &mut Vec, native: NativeRef, session: SessionId) { + let pending = steps.iter_mut().find_map(|step| match step { + RestoreStep::Native { native: n, sessions } if *n == native => Some(sessions), + _ => None, + }); + match pending { + Some(sessions) => sessions.push(session), + None => steps.push(RestoreStep::Native { native, sessions: vec![session] }), + } +} + +#[cfg(test)] +mod tests { + use redshell_core::{CommandSpec, LaunchProfile, new_session_id}; + + use super::*; + use crate::panes::Axis; + + fn record(id: &str, kind: LaunchKind, program: &str) -> SessionRecord { + SessionRecord { + id: new_session_id(), + profile: LaunchProfile { + id: id.into(), + name: id.into(), + kind, + description: String::new(), + available: true, + command: if program.is_empty() { CommandSpec::default() } else { CommandSpec::new(program) }, + }, + title: id.into(), + cwd: None, + started_at: 0, + ended_at: None, + exit_code: None, + bytes: 0, + cols: 80, + rows: 24, + open_tab: true, + pinned: false, + } + } + + fn shell() -> SessionRecord { + record("shell:bash", LaunchKind::Shell, "bash") + } + + fn pane(step: &PaneStep) -> String { + match step { + PaneStep::Relaunch { record, last_cwd, replay } => { + let what = match (last_cwd, replay) { + (true, true) => "relaunch+cwd+replay", + (true, false) => "relaunch+cwd", + (false, true) => "relaunch+replay", + (false, false) => "relaunch", + }; + format!("{what} {}", record.profile.id) + } + PaneStep::Reattach { record, .. } => format!("reattach {}", record.profile.id), + } + } + + /// One line per step, panes of a tab separated by `|`, for compact assertions. + fn summary(steps: &[RestoreStep]) -> Vec { + steps + .iter() + .map(|s| match s { + RestoreStep::Tab { panes, .. } => panes.leaves().iter().map(pane).collect::>().join(" | "), + RestoreStep::Native { native, sessions } => format!("native {native} x{}", sessions.len()), + }) + .collect() + } + + /// The saved tab H[a, V[b, c]] with `b` active. + fn split_tab(a: &SessionRecord, b: &SessionRecord, c: &SessionRecord) -> SavedTab { + let mut root = PaneNode::Leaf(a.id); + root.split(&a.id, b.id, Axis::Horizontal); + root.split(&b.id, c.id, Axis::Vertical); + SavedTab { layout: TabLayout { root, active: b.id }, name: Some("build".into()), active: true } + } + + #[test] + fn every_kind_of_tab() { + let records = vec![ + shell(), + record("mux:local:tmux:work", LaunchKind::Multiplexer, "tmux"), + record("mux:local:tmux:redshell-1a2b3c", LaunchKind::Multiplexer, "tmux"), + record("ssh:box", LaunchKind::Ssh, "ssh"), + record("agent:claude", LaunchKind::Agent, "claude"), + ]; + assert_eq!( + summary(&plan(records, Vec::new())), + [ + "relaunch+cwd+replay shell:bash", + "reattach mux:local:tmux:work", + "relaunch+cwd mux:local:tmux:redshell-1a2b3c", + "relaunch+replay ssh:box", + "relaunch+replay agent:claude", + ] + ); + } + + #[test] + fn native_sessions_attach_once_in_place() { + let records = vec![ + record("tmux-native:local:work", LaunchKind::Multiplexer, ""), + shell(), + record("tmux-native:local:work", LaunchKind::Multiplexer, ""), + record("tmux-native:ssh:box:work", LaunchKind::Multiplexer, ""), + ]; + let steps = plan(records.clone(), Vec::new()); + assert_eq!( + summary(&steps), + [ + "native tmux-native:local:work x2", + "relaunch+cwd+replay shell:bash", + "native tmux-native:ssh:box:work x1" + ] + ); + let RestoreStep::Native { sessions, .. } = &steps[0] else { unreachable!() }; + assert_eq!(*sessions, [records[0].id, records[2].id]); + } + + #[test] + fn tabs_without_a_command_are_skipped() { + assert!(plan(vec![record("plugin:viewer", LaunchKind::Plugin, "")], Vec::new()).is_empty()); + } + + #[test] + fn the_config_editor_is_not_reopened() { + assert!(plan(vec![record("editor:config", LaunchKind::Shell, "nvim")], Vec::new()).is_empty()); + } + + #[test] + fn mux_ids_only_count_for_multiplexer_tabs() { + let steps = plan(vec![record("mux:local:tmux:work", LaunchKind::Plugin, "x")], Vec::new()); + assert_eq!(summary(&steps), ["relaunch+replay mux:local:tmux:work"]); + } + + #[test] + fn saved_tabs_come_back_with_layout_name_and_focus() { + let (a, b, c, d) = (shell(), shell(), shell(), shell()); + let other = SavedTab { layout: TabLayout::single(d.id), name: None, active: false }; + let saved = vec![split_tab(&a, &b, &c), other]; + let steps = plan(vec![a.clone(), b.clone(), c.clone(), d.clone()], saved.clone()); + assert_eq!(steps.len(), 2); + let RestoreStep::Tab { panes, active_pane, name, active } = &steps[0] else { unreachable!() }; + let ids = panes.clone().map(|step| match step { + PaneStep::Relaunch { record, .. } | PaneStep::Reattach { record, .. } => record.id, + }); + assert_eq!(ids, saved[0].layout.root); + assert_eq!((*active_pane, name.as_deref(), *active), (b.id, Some("build"), true)); + assert!(matches!(&steps[1], RestoreStep::Tab { name: None, active: false, .. })); + } + + #[test] + fn panes_that_cannot_come_back_leave_the_layout() { + // b is the config editor and c is no longer in the history. + let (a, b, c) = (shell(), record("editor:config", LaunchKind::Shell, "nvim"), shell()); + let steps = plan(vec![a.clone(), b.clone()], vec![split_tab(&a, &b, &c)]); + let [RestoreStep::Tab { panes, .. }] = steps.as_slice() else { panic!("{steps:?}") }; + assert!(matches!(panes, PaneNode::Leaf(PaneStep::Relaunch { record, .. }) if record.id == a.id)); + } + + #[test] + fn sessions_no_layout_holds_follow_as_a_tab_each() { + let (a, b, c, d) = (shell(), shell(), shell(), record("ssh:box", LaunchKind::Ssh, "ssh")); + let steps = plan(vec![d, a.clone(), b.clone(), c.clone()], vec![split_tab(&a, &b, &c)]); + assert_eq!( + summary(&steps), + [ + "relaunch+cwd+replay shell:bash | relaunch+cwd+replay shell:bash | relaunch+cwd+replay shell:bash", + "relaunch+replay ssh:box", + ] + ); + } + + #[test] + fn a_layout_that_does_not_hold_together_is_ignored() { + let (a, b) = (shell(), shell()); + let root = PaneNode::Split { + axis: Axis::Horizontal, + children: vec![PaneNode::Leaf(a.id), PaneNode::Leaf(b.id)], + ratios: vec![1.0], + }; + let saved = vec![SavedTab { layout: TabLayout { root, active: a.id }, name: Some("x".into()), active: true }]; + let steps = plan(vec![a, b], saved); + assert_eq!(summary(&steps), ["relaunch+cwd+replay shell:bash", "relaunch+cwd+replay shell:bash"]); + } + + #[test] + fn native_tabs_are_left_to_tmux() { + let (a, b) = (record("tmux-native:local:work", LaunchKind::Multiplexer, ""), shell()); + let (c, d) = (record("tmux-native:local:work", LaunchKind::Multiplexer, ""), shell()); + let mut root = PaneNode::Leaf(a.id); + root.split(&a.id, c.id, Axis::Vertical); + let native = SavedTab { layout: TabLayout { root, active: a.id }, name: None, active: false }; + let saved = vec![SavedTab { layout: TabLayout::single(b.id), name: None, active: true }, native]; + let steps = plan(vec![a, b, c, d], saved); + assert_eq!( + summary(&steps), + ["relaunch+cwd+replay shell:bash", "native tmux-native:local:work x2", "relaunch+cwd+replay shell:bash"] + ); + } +} diff --git a/crates/redshell-app/src/settings_view.rs b/crates/redshell-app/src/settings_view.rs index c81ae78..aaf79be 100644 --- a/crates/redshell-app/src/settings_view.rs +++ b/crates/redshell-app/src/settings_view.rs @@ -6,19 +6,17 @@ use gpui::{ AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, KeyDownEvent, PathPromptOptions, SharedString, Subscription, Window, div, px, }; -use redshell_core::settings::{ - ConfirmPolicy, CursorStyle, ImageFit, MultiplexerKind, Settings, TabBarPosition, WindowBackground, -}; use redshell_theme::Theme; -use redshell_ui::{ - Badge, BadgeVariant, Button, ButtonSize, ButtonVariant, IconName, Kbd, Modal, Segmented, Stepper, Switch, ThemeExt, - alpha, section_label, setting_row, -}; +use redshell_ui::{Button, ButtonSize, ButtonVariant, IconName, Modal, StyledExt, ThemeExt, alpha}; -use crate::commands::{COMMANDS, key_for, keymap}; use crate::picker::{Picker, PickerEvent, PickerItem, PickerKind}; use crate::state::{AppState, update_settings}; +mod options; +mod pages; +use options::{Tab, follows_system, font_choices, pick_theme}; +use pages::reset_section; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SettingsEvent { Close, @@ -27,27 +25,6 @@ pub enum SettingsEvent { RevealConfig, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Tab { - Appearance, - Terminal, - Safety, - Sessions, - Keys, -} - -impl Tab { - fn label(self) -> &'static str { - match self { - Tab::Appearance => "Appearance", - Tab::Terminal => "Terminal", - Tab::Safety => "Safety", - Tab::Sessions => "Sessions", - Tab::Keys => "Keybindings", - } - } -} - /// Which font setting the font picker edits. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum FontTarget { @@ -63,93 +40,6 @@ pub struct SettingsView { reset_armed: Option, } -/// Whether a font family name looks monospaced (used to list likely -/// terminal fonts first; any font can still be picked). -pub fn looks_monospace(name: &str) -> bool { - const HINTS: &[&str] = &[ - "mono", - "code", - "consol", - "courier", - "menlo", - "monaco", - "fixed", - "terminal", - "term", - "hack", - "iosevka", - "inconsolata", - "typewriter", - "nerd font", - "jetbrains", - "cascadia", - "fira", - "hasklig", - "victor", - "plex mono", - ]; - let lower = name.to_lowercase(); - HINTS.iter().any(|h| lower.contains(h)) -} - -/// De-duplicated, sorted font names; with `mono_first`, likely monospaced -/// fonts come first. Returns (name, looks monospaced). -pub fn font_choices(mut names: Vec, mono_first: bool) -> Vec<(String, bool)> { - names.retain(|n| !n.trim().is_empty() && !n.starts_with('.')); - names.sort_by_key(|n| n.to_lowercase()); - names.dedup(); - let mut out: Vec<(String, bool)> = names.into_iter().map(|n| (n.clone(), looks_monospace(&n))).collect(); - if mono_first { - out.sort_by_key(|(_, mono)| !*mono); - } - out -} - -/// Restores the defaults of the settings a tab shows (and only those: e.g. -/// the theme and the shell are kept). -pub fn reset_section(settings: &mut Settings, section: &str) { - let d = Settings::default(); - let (a, da) = (&mut settings.appearance, &d.appearance); - match section { - "Appearance" => { - a.font_family = da.font_family.clone(); - a.font_size = da.font_size; - a.line_height = da.line_height; - a.ui_font_family = da.ui_font_family.clone(); - a.ui_font_size = da.ui_font_size; - a.background_opacity = da.background_opacity; - a.window_background = da.window_background; - a.background_image = da.background_image.clone(); - a.background_image_opacity = da.background_image_opacity; - a.background_image_fit = da.background_image_fit; - a.padding = da.padding; - a.tab_bar = da.tab_bar; - a.show_sidebar = da.show_sidebar; - a.show_status_bar = da.show_status_bar; - } - "Terminal" => { - a.cursor_style = da.cursor_style; - a.cursor_blink = da.cursor_blink; - a.bold_is_bright = da.bold_is_bright; - settings.terminal.copy_on_select = d.terminal.copy_on_select; - settings.terminal.visual_bell = d.terminal.visual_bell; - settings.terminal.scrollback_lines = d.terminal.scrollback_lines; - } - "Safety" => settings.safety = d.safety, - "Sessions" => { - let h = &mut settings.history; - h.enabled = d.history.enabled; - h.restore_tabs = d.history.restore_tabs; - h.restore_scrollback = d.history.restore_scrollback; - h.retain_days = d.history.retain_days; - settings.multiplexer.preferred = d.multiplexer.preferred; - settings.multiplexer.auto_attach_local = d.multiplexer.auto_attach_local; - } - "Keybindings" => settings.keybindings.clear(), - _ => {} - } -} - impl EventEmitter for SettingsView {} impl Focusable for SettingsView { @@ -161,36 +51,6 @@ impl Focusable for SettingsView { } } -fn opts(items: [(&'static str, &'static str); N]) -> Vec<(SharedString, SharedString)> { - items.into_iter().map(|(v, l)| (v.into(), l.into())).collect() -} - -fn policy_str(p: ConfirmPolicy) -> &'static str { - match p { - ConfirmPolicy::Always => "always", - ConfirmPolicy::Running => "running", - ConfirmPolicy::Never => "never", - } -} - -fn parse_policy(s: &str) -> ConfirmPolicy { - match s { - "running" => ConfirmPolicy::Running, - "never" => ConfirmPolicy::Never, - _ => ConfirmPolicy::Always, - } -} - -/// A switch bound to one boolean setting. -fn toggle(id: &'static str, value: bool, set: fn(&mut Settings, bool)) -> Switch { - Switch::new(id, value).on_toggle(move |on, _w, cx| update_settings(cx, |s| set(s, on))) -} - -/// A stepper bound to one numeric setting. -fn stepper(id: &'static str, label: String, unit: &'static str, apply: fn(&mut Settings, i32)) -> Stepper { - Stepper::new(id, label).unit(unit).on_step(move |d, _w, cx| update_settings(cx, |s| apply(s, d))) -} - impl SettingsView { pub fn new(window: &mut Window, cx: &mut Context) -> Self { let focus = cx.focus_handle(); @@ -210,7 +70,7 @@ impl SettingsView { .into_iter() .map(|(name, mono)| PickerItem { icon: Some(if mono { IconName::Terminal } else { IconName::Type }), - subtitle: if mono { "monospace".into() } else { String::new() }, + subtitle: if mono { "Monospaced".into() } else { String::new() }, keywords: if mono { "mono".into() } else { String::new() }, title: name.clone(), id: name, @@ -218,7 +78,7 @@ impl SettingsView { }) .collect(); let title = match target { - FontTarget::Terminal => "Terminal font (monospaced fonts first)", + FontTarget::Terminal => "Terminal font", FontTarget::Ui => "Interface font", }; let picker = cx.new(|cx| { @@ -285,13 +145,13 @@ impl SettingsView { .variant(if armed { ButtonVariant::Destructive } else { ButtonVariant::Ghost }) .tooltip(match tab { Tab::Appearance => "Fonts, window and layout; the theme is kept", - Tab::Keys => "Removes every [keybindings] override", + Tab::Keys => "Restores every default shortcut", _ => "Only the settings on this page", }) .on_click(cx.listener(move |this, _, _, cx| { if this.reset_armed == Some(tab) { this.reset_armed = None; - update_settings(cx, |s| reset_section(s, tab.label())); + update_settings(cx, |s| reset_section(s, tab)); } else { this.reset_armed = Some(tab); } @@ -301,16 +161,6 @@ impl SettingsView { .into_any_element() } - fn font_button(id: &'static str, name: &str, target: FontTarget, cx: &mut Context) -> Button { - Button::new(id) - .label(name.to_owned()) - .icon(IconName::Type) - .variant(ButtonVariant::Outline) - .size(ButtonSize::Sm) - .tooltip("Choose from installed fonts") - .on_click(cx.listener(move |this, _, window, cx| this.open_font_picker(target, window, cx))) - } - fn on_key(&mut self, ev: &KeyDownEvent, _w: &mut Window, cx: &mut Context) { if ev.keystroke.key == "escape" { cx.emit(SettingsEvent::Close); @@ -322,7 +172,7 @@ impl SettingsView { let t = cx.theme().clone(); let ui = *t.ui(); let p = theme.ui; - let id = theme.id.clone(); + let picked = theme.clone(); let swatch = |c: redshell_theme::Rgba| { div().size(px(14.)).rounded_full().border_1().border_color(alpha(p.foreground, 0.15)).bg(c) }; @@ -338,10 +188,7 @@ impl SettingsView { .overflow_hidden() .cursor_pointer() .hover(|s| s.shadow_md()) - .on_click(move |_, _w, cx| { - let id = id.clone(); - update_settings(cx, |s| s.appearance.theme = id); - }) + .on_click(move |_, _w, cx| update_settings(cx, |s| pick_theme(&mut s.appearance, &picked))) .child( div() .flex() @@ -392,474 +239,30 @@ impl SettingsView { div() .flex_1() .min_w_0() - .overflow_hidden() .font_weight(FontWeight::MEDIUM) - .whitespace_nowrap() - .text_ellipsis() + .truncate_line() .child(theme.name.clone()), ), ) } - fn appearance(&self, cx: &mut Context) -> Vec { - let s = &cx.global::().settings; - let a = s.appearance.clone(); - let themes: Vec = cx.global::().themes.iter().cloned().collect(); - let active = cx.theme().theme.id.clone(); - let mut out = vec![ - section_label("Theme", cx).into_any_element(), - div() - .flex() - .flex_wrap() - .gap(px(10.)) - .children(themes.iter().map(|th| Self::theme_card(th, th.id == active, cx))) - .into_any_element(), - div() - .flex() - .gap(px(8.)) - .pt(px(10.)) - .child( - Button::new("import-theme") - .label("Import tweakcn theme from clipboard") - .icon(IconName::ClipboardPaste) - .variant(ButtonVariant::Outline) - .size(ButtonSize::Sm) - .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::ImportTheme))), - ) - .child( - Button::new("reveal-themes") - .label("Open config folder") - .variant(ButtonVariant::Ghost) - .size(ButtonSize::Sm) - .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::RevealConfig))), - ) - .into_any_element(), - section_label("Typography", cx).into_any_element(), - ]; - out.push(setting_row( - "Terminal font", - Some("Monospaced fonts are listed first"), - Self::font_button("font-family", &a.font_family, FontTarget::Terminal, cx), - cx, - )); - out.push(setting_row( - "Font size", - None, - stepper("font-size", format!("{:.0}", a.font_size), "px", |s, d| s.appearance.font_size += d as f32), - cx, - )); - out.push(setting_row( - "Line height", - Some("Multiple of the font size"), - stepper("line-height", format!("{:.2}", a.line_height), "×", |s, d| { - s.appearance.line_height += d as f32 * 0.05 - }), - cx, - )); - out.push(setting_row( - "Interface font", - None, - Self::font_button("ui-font-family", &a.ui_font_family, FontTarget::Ui, cx), - cx, - )); - out.push(setting_row( - "Interface font size", - None, - stepper("ui-size", format!("{:.0}", a.ui_font_size), "px", |s, d| s.appearance.ui_font_size += d as f32), - cx, - )); - out.push(section_label("Window", cx).into_any_element()); - out.push(setting_row( - "Background opacity", - Some("Terminal background; combine with a transparent or blurred window"), - stepper("opacity", format!("{:.0}", a.background_opacity * 100.0), "%", |s, d| { - s.appearance.background_opacity += d as f32 * 0.05 - }), - cx, - )); - out.push(setting_row( - "Window background", - None, - Segmented::new( - "window-bg", - opts([("opaque", "Opaque"), ("transparent", "Transparent"), ("blurred", "Blurred")]), - match a.window_background { - WindowBackground::Opaque => "opaque", - WindowBackground::Transparent => "transparent", - WindowBackground::Blurred => "blurred", - }, - ) - .on_select(|v, _w, cx| { - update_settings(cx, |s| { - s.appearance.window_background = match v.as_ref() { - "transparent" => WindowBackground::Transparent, - "blurred" => WindowBackground::Blurred, - _ => WindowBackground::Opaque, - } - }) - }), - cx, - )); - let has_image = a.background_image.is_some(); - out.push(setting_row( - "Background image", - Some( - &a.background_image - .as_ref() - .map(|p| p.display().to_string()) - .unwrap_or_else(|| "Painted behind the terminal grid".into()), - ), - div() - .flex() - .gap(px(6.)) - .child( - Button::new("bg-choose") - .label(if has_image { "Change…" } else { "Choose…" }) - .icon(IconName::FolderOpen) - .variant(ButtonVariant::Outline) - .size(ButtonSize::Sm) - .on_click(cx.listener(|this, _, _, cx| this.choose_background_image(cx))), - ) - .when(has_image, |d| { - d.child( - Button::new("bg-remove") - .label("Remove") - .variant(ButtonVariant::Ghost) - .size(ButtonSize::Sm) - .on_click(|_, _, cx| update_settings(cx, |s| s.appearance.background_image = None)), - ) - }), - cx, - )); - if has_image { - out.push(setting_row( - "Image opacity", - None, - stepper("img-opacity", format!("{:.0}", a.background_image_opacity * 100.0), "%", |s, d| { - s.appearance.background_image_opacity += d as f32 * 0.05 - }), - cx, - )); - out.push(setting_row( - "Image fit", - None, - Segmented::new( - "img-fit", - opts([("cover", "Cover"), ("contain", "Contain"), ("fill", "Fill"), ("none", "Original")]), - match a.background_image_fit { - ImageFit::Cover => "cover", - ImageFit::Contain => "contain", - ImageFit::Fill => "fill", - ImageFit::None => "none", - }, - ) - .on_select(|v, _w, cx| { - update_settings(cx, |s| { - s.appearance.background_image_fit = match v.as_ref() { - "contain" => ImageFit::Contain, - "fill" => ImageFit::Fill, - "none" => ImageFit::None, - _ => ImageFit::Cover, - } - }) - }), - cx, - )); - } - out.push(setting_row( - "Padding", - None, - stepper("padding", format!("{:.0}", a.padding), "px", |s, d| s.appearance.padding += d as f32 * 2.0), - cx, - )); - out.push(setting_row( - "Tab bar", - None, - Segmented::new( - "tab-bar", - opts([("top", "Top"), ("bottom", "Bottom"), ("hidden", "Hidden")]), - match a.tab_bar { - TabBarPosition::Top => "top", - TabBarPosition::Bottom => "bottom", - TabBarPosition::Hidden => "hidden", - }, - ) - .on_select(|v, _w, cx| { - update_settings(cx, |s| { - s.appearance.tab_bar = match v.as_ref() { - "bottom" => TabBarPosition::Bottom, - "hidden" => TabBarPosition::Hidden, - _ => TabBarPosition::Top, - } - }) - }), - cx, - )); - out.push(setting_row( - "Sidebar", - None, - toggle("sidebar", a.show_sidebar, |s, v| s.appearance.show_sidebar = v), - cx, - )); - out.push(setting_row( - "Status bar", - None, - toggle("statusbar", a.show_status_bar, |s, v| s.appearance.show_status_bar = v), - cx, - )); - out - } - - fn terminal(&self, cx: &mut Context) -> Vec { - let s = cx.global::().settings.clone(); - let a = &s.appearance; - vec![ - section_label("Cursor", cx).into_any_element(), - setting_row( - "Cursor style", - None, - Segmented::new( - "cursor", - opts([("block", "Block"), ("bar", "Bar"), ("underline", "Underline"), ("hollow", "Hollow")]), - match a.cursor_style { - CursorStyle::Block => "block", - CursorStyle::Bar => "bar", - CursorStyle::Underline => "underline", - CursorStyle::Hollow => "hollow", - }, - ) - .on_select(|v, _w, cx| { - update_settings(cx, |s| { - s.appearance.cursor_style = match v.as_ref() { - "bar" => CursorStyle::Bar, - "underline" => CursorStyle::Underline, - "hollow" => CursorStyle::Hollow, - _ => CursorStyle::Block, - } - }) - }), - cx, - ), - setting_row( - "Blinking cursor", - None, - toggle("blink", a.cursor_blink, |s, v| s.appearance.cursor_blink = v), - cx, - ), - section_label("Behaviour", cx).into_any_element(), - setting_row( - "Copy on select", - Some("Selected text goes to the clipboard immediately"), - toggle("copy-select", s.terminal.copy_on_select, |s, v| s.terminal.copy_on_select = v), - cx, - ), - setting_row( - "Visual bell", - None, - toggle("bell", s.terminal.visual_bell, |s, v| s.terminal.visual_bell = v), - cx, - ), - setting_row( - "Bold text uses bright colours", - None, - toggle("bold-bright", a.bold_is_bright, |s, v| s.appearance.bold_is_bright = v), - cx, - ), - setting_row( - "Scrollback", - Some("Lines kept in memory per pane (history on disk is unlimited)"), - stepper("scrollback", format!("{}k", s.terminal.scrollback_lines / 1000), "lines", |s, d| { - s.terminal.scrollback_lines = - (s.terminal.scrollback_lines as i64 + d as i64 * 5000).max(1000) as usize - }), - cx, - ), - setting_row( - "Shell", - Some(&s.terminal.shell.clone().unwrap_or_else(redshell_core::shell::default_shell)), - div() - .text_size(cx.theme().text_xs()) - .text_color(cx.theme().ui().muted_foreground) - .child("terminal.shell"), - cx, - ), - ] - } - - fn safety(&self, cx: &mut Context) -> Vec { - let s = cx.global::().settings.safety.clone(); - let policy = |id: &'static str, v: ConfirmPolicy, set: fn(&mut Settings, ConfirmPolicy)| { - Segmented::new( - id, - opts([("always", "Always"), ("running", "If running"), ("never", "Never")]), - policy_str(v), - ) - .on_select(move |v, _w, cx| update_settings(cx, |s| set(s, parse_policy(&v)))) + /// The theme cards; the chosen ones (two while following the system) + /// are outlined. + fn theme_cards(cx: &mut Context) -> AnyElement { + let a = &cx.global::().settings.appearance; + let chosen: Vec = if follows_system(a) { + [&a.theme_light, &a.theme_dark].into_iter().flatten().cloned().collect() + } else { + vec![cx.theme().theme.id.clone()] }; - vec![ - section_label("Confirm before closing", cx).into_any_element(), - setting_row( - "Closing a tab", - Some("Enter/Esc cancel; confirming needs a click or Ctrl+Enter"), - policy("p-tab", s.confirm_close_tab, |s, p| s.safety.confirm_close_tab = p), - cx, - ), - setting_row( - "Closing a window", - None, - policy("p-win", s.confirm_close_window, |s, p| s.safety.confirm_close_window = p), - cx, - ), - setting_row( - "Quitting RedShell", - None, - policy("p-quit", s.confirm_quit, |s, p| s.safety.confirm_quit = p), - cx, - ), - setting_row( - "Require typing “close” to quit", - Some("An extra speed bump for windows full of long-running sessions"), - Switch::new("typed", s.typed_confirmation.is_some()).on_toggle(|on, _w, cx| { - update_settings(cx, |s| s.safety.typed_confirmation = on.then(|| "close".into())) - }), - cx, - ), - setting_row( - "Confirm multi-line paste", - Some("Only when the shell has no bracketed-paste protection"), - toggle("ml-paste", s.confirm_multiline_paste, |s, v| s.safety.confirm_multiline_paste = v), - cx, - ), - ] - } - - fn sessions(&self, cx: &mut Context) -> Vec { - let s = cx.global::().settings.clone(); - vec![ - section_label("History", cx).into_any_element(), - setting_row( - "Record sessions", - Some("Every byte, searchable. Applies to new tabs after restart."), - toggle("hist", s.history.enabled, |s, v| s.history.enabled = v), - cx, - ), - setting_row( - "Restore tabs on start", - None, - toggle("restore", s.history.restore_tabs, |s, v| s.history.restore_tabs = v), - cx, - ), - setting_row( - "Replay scrollback into restored tabs", - None, - toggle("replay", s.history.restore_scrollback, |s, v| s.history.restore_scrollback = v), - cx, - ), - setting_row( - "Keep history for", - Some("0 = forever. Pinned and open sessions are never pruned."), - stepper( - "retain", - if s.history.retain_days == 0 { "∞".into() } else { format!("{}", s.history.retain_days) }, - "days", - |s, d| s.history.retain_days = (s.history.retain_days as i64 + d as i64 * 7).max(0) as u32, - ), - cx, - ), - section_label("Multiplexer", cx).into_any_element(), - setting_row( - "Preferred multiplexer", - Some("Used locally, over SSH and through WSL on Windows"), - Segmented::new( - "mux", - opts([("tmux", "tmux"), ("screen", "screen")]), - match s.multiplexer.preferred { - MultiplexerKind::Tmux => "tmux", - MultiplexerKind::Screen => "screen", - }, - ) - .on_select(|v, _w, cx| { - update_settings(cx, |s| { - s.multiplexer.preferred = - if v.as_ref() == "screen" { MultiplexerKind::Screen } else { MultiplexerKind::Tmux } - }) - }), - cx, - ), - setting_row( - "Run new local tabs inside the multiplexer", - Some("Tabs then survive crashes and restarts and re-attach automatically"), - toggle("auto-mux", s.multiplexer.auto_attach_local, |s, v| s.multiplexer.auto_attach_local = v), - cx, - ), - ] - } -} - -impl SettingsView { - fn keybindings(&self, cx: &mut Context) -> Vec { - let overrides = cx.global::().settings.keybindings.clone(); - let keys = keymap(&overrides); - let t = cx.theme().clone(); - let ui = *t.ui(); - let mut out = vec![ - div() - .flex() - .items_center() - .gap(px(12.)) - .pt(px(14.)) - .child( - div() - .flex_1() - .min_w_0() - .text_size(t.text_xs()) - .text_color(ui.muted_foreground) - .child("Rebind keys under [keybindings] in config.toml, e.g. \"ctrl-shift-x\" = \"tab.new\". An empty command removes a default binding."), - ) - .child( - Button::new("keys-edit") - .label("Edit in config.toml") - .icon(IconName::Pencil) - .variant(ButtonVariant::Outline) - .size(ButtonSize::Sm) - .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::EditFile))), - ) - .into_any_element(), - ]; - // Group by category, in order of first appearance. - let mut categories: Vec<&str> = Vec::new(); - for c in COMMANDS { - if !categories.contains(&c.category) { - categories.push(c.category); - } - } - for category in categories { - out.push(section_label(category, cx).into_any_element()); - for c in COMMANDS.iter().filter(|c| c.category == category) { - let key = key_for(c.id, &keys); - let custom = key.as_ref().is_some_and(|k| overrides.contains_key(k)); - out.push( - div() - .flex() - .items_center() - .gap(px(10.)) - .px(px(10.)) - .py(px(5.)) - .border_b_1() - .border_color(alpha(ui.border, 0.6)) - .text_size(t.text_sm()) - .child(div().flex_1().min_w_0().whitespace_nowrap().text_ellipsis().child(c.title)) - .child(div().flex_none().text_size(t.text_xs()).text_color(ui.muted_foreground).child(c.id)) - .when(custom, |d| d.child(Badge::new("custom").variant(BadgeVariant::Primary))) - .child(match key { - Some(k) => Kbd::new(k).into_any_element(), - None => div().text_color(ui.muted_foreground).child("—").into_any_element(), - }) - .into_any_element(), - ); - } - } - out + let themes: Vec = cx.global::().themes.iter().cloned().collect(); + div() + .flex() + .flex_wrap() + .gap(px(10.)) + .pt(px(12.)) + .children(themes.iter().map(|th| Self::theme_card(th, chosen.contains(&th.id), cx))) + .into_any_element() } } @@ -867,21 +270,9 @@ impl Render for SettingsView { fn render(&mut self, _w: &mut Window, cx: &mut Context) -> impl IntoElement { let t = cx.theme().clone(); let ui = *t.ui(); - let body = match self.tab { - Tab::Appearance => self.appearance(cx), - Tab::Terminal => self.terminal(cx), - Tab::Safety => self.safety(cx), - Tab::Sessions => self.sessions(cx), - Tab::Keys => self.keybindings(cx), - }; + let rows = self.tab.rows(&cx.global::().settings); + let body: Vec = rows.into_iter().filter_map(|row| row.render(cx)).collect(); let reset = self.reset_button(cx); - let nav = [ - (Tab::Appearance, "Appearance", IconName::Palette), - (Tab::Terminal, "Terminal", IconName::Terminal), - (Tab::Safety, "Safety", IconName::Shield), - (Tab::Sessions, "Sessions", IconName::History), - (Tab::Keys, "Keybindings", IconName::Keyboard), - ]; let problems = cx.global::().problems.clone(); let this = cx.entity().downgrade(); let close = this.clone(); @@ -896,6 +287,7 @@ impl Render for SettingsView { .on_key_down(cx.listener(Self::on_key)) .flex() .h(px(600.)) + .min_h_0() .child( div() .flex() @@ -915,11 +307,11 @@ impl Render for SettingsView { .font_weight(FontWeight::SEMIBOLD) .child("Settings"), ) - .children(nav.into_iter().map(|(tab, label, icon)| { + .children(Tab::ALL.into_iter().map(|tab| { let active = tab == self.tab; - Button::new(label) - .label(label) - .icon(icon) + Button::new(tab.label()) + .label(tab.label()) + .icon(tab.icon()) .variant(ButtonVariant::Ghost) .selected(active) .full_width() @@ -933,7 +325,7 @@ impl Render for SettingsView { .child(div().flex_1()) .child( Button::new("edit-file") - .label("Edit config.toml") + .label("Edit config file") .icon(IconName::Pencil) .variant(ButtonVariant::Outline) .size(ButtonSize::Sm) @@ -967,50 +359,3 @@ impl Render for SettingsView { div().absolute().inset_0().child(modal).children(self.font_picker.as_ref().map(|(_, p, _)| p.clone())) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn monospace_names_are_detected() { - for name in ["JetBrains Mono", "Fira Code", "DejaVu Sans Mono", "Cascadia Code", "Iosevka Term", "Menlo"] { - assert!(looks_monospace(name), "{name}"); - } - for name in ["DejaVu Sans", "Inter", "Noto Serif", "Helvetica Neue"] { - assert!(!looks_monospace(name), "{name}"); - } - } - - #[test] - fn font_choices_sort_dedup_and_put_mono_first() { - let names = ["Inter", "Fira Code", "inter", "Arial", "Fira Code", ".Hidden", "DejaVu Sans Mono", ""] - .map(String::from) - .to_vec(); - let mono: Vec<_> = font_choices(names.clone(), true).into_iter().map(|(n, _)| n).collect(); - assert_eq!(mono, ["DejaVu Sans Mono", "Fira Code", "Arial", "Inter", "inter"]); - let plain: Vec<_> = font_choices(names, false).into_iter().map(|(n, _)| n).collect(); - assert_eq!(plain, ["Arial", "DejaVu Sans Mono", "Fira Code", "Inter", "inter"]); - } - - #[test] - fn reset_section_only_touches_that_section() { - let mut s = Settings::default(); - s.appearance.theme = "nord".into(); - s.appearance.font_size = 20.0; - s.appearance.cursor_blink = false; - s.safety.confirm_quit = ConfirmPolicy::Never; - s.keybindings.insert("ctrl-x".into(), "tab.new".into()); - reset_section(&mut s, "Appearance"); - assert_eq!(s.appearance.font_size, Settings::default().appearance.font_size); - assert_eq!(s.appearance.theme, "nord", "the theme is kept"); - assert!(!s.appearance.cursor_blink, "cursor belongs to the Terminal page"); - assert_eq!(s.safety.confirm_quit, ConfirmPolicy::Never); - reset_section(&mut s, "Terminal"); - assert!(s.appearance.cursor_blink); - reset_section(&mut s, "Safety"); - assert_eq!(s.safety.confirm_quit, ConfirmPolicy::Always); - reset_section(&mut s, "Keybindings"); - assert!(s.keybindings.is_empty()); - } -} diff --git a/crates/redshell-app/src/settings_view/options.rs b/crates/redshell-app/src/settings_view/options.rs new file mode 100644 index 0000000..9fd7c2a --- /dev/null +++ b/crates/redshell-app/src/settings_view/options.rs @@ -0,0 +1,300 @@ +//! The pure parts of the Settings panel: the choices it offers and the +//! edits it makes, kept apart from rendering so they can be tested. + +use redshell_core::settings::{ + AppearanceSettings, CloseOnExit, ConfirmPolicy, CursorStyle, ImageFit, MultiplexerKind, TabBarPosition, + WindowBackground, +}; +use redshell_core::{LaunchKind, LaunchProfile}; +use redshell_theme::Theme; +use redshell_ui::{IconName, SelectOption}; + +/// A setting with a few fixed values, offered side by side. +pub trait Choice: Copy + PartialEq + 'static { + /// Every value, in the order they are offered. + const ALL: &'static [Self]; + + /// What the panel calls the value. + fn label(self) -> &'static str; + + /// Position of the value in [`Self::ALL`]: the control's key for it. + fn index(self) -> usize { + Self::ALL.iter().position(|c| *c == self).unwrap_or_default() + } +} + +/// Implements [`Choice`] for a settings enum: `Type { Variant => "Label", … }`. +macro_rules! choices { + ($($ty:ident { $($variant:ident => $label:literal),+ $(,)? })*) => {$( + impl Choice for $ty { + const ALL: &'static [Self] = &[$($ty::$variant),+]; + + fn label(self) -> &'static str { + match self { + $($ty::$variant => $label),+ + } + } + } + )*}; +} + +choices! { + WindowBackground { Opaque => "Opaque", Transparent => "Transparent", Blurred => "Blurred" } + ImageFit { Cover => "Cover", Contain => "Contain", Fill => "Fill", None => "Original" } + TabBarPosition { Top => "Top", Bottom => "Bottom", Hidden => "Hidden" } + CursorStyle { Block => "Block", Bar => "Bar", Underline => "Underline", Hollow => "Hollow" } + CloseOnExit { Graceful => "On success", Always => "Always", Never => "Never" } + ConfirmPolicy { Always => "Always", MultipleTabs => "Several tabs", Running => "If running", Never => "Never" } + MultiplexerKind { Tmux => "tmux", Screen => "screen" } +} + +/// The pages of the Settings panel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tab { + Appearance, + Terminal, + Safety, + Sessions, + Keys, +} + +impl Tab { + pub const ALL: [Self; 5] = [Self::Appearance, Self::Terminal, Self::Safety, Self::Sessions, Self::Keys]; + + pub fn label(self) -> &'static str { + match self { + Self::Appearance => "Appearance", + Self::Terminal => "Terminal", + Self::Safety => "Safety", + Self::Sessions => "Sessions", + Self::Keys => "Keybindings", + } + } + + pub fn icon(self) -> IconName { + match self { + Self::Appearance => IconName::Palette, + Self::Terminal => IconName::Terminal, + Self::Safety => IconName::Shield, + Self::Sessions => IconName::History, + Self::Keys => IconName::Keyboard, + } + } +} + +/// Whether a font family name looks monospaced (used to list likely +/// terminal fonts first; any font can still be picked). +pub fn looks_monospace(name: &str) -> bool { + const HINTS: &[&str] = &[ + "mono", + "code", + "consol", + "courier", + "menlo", + "monaco", + "fixed", + "terminal", + "term", + "hack", + "iosevka", + "inconsolata", + "typewriter", + "nerd font", + "jetbrains", + "cascadia", + "fira", + "hasklig", + "victor", + "plex mono", + ]; + let lower = name.to_lowercase(); + HINTS.iter().any(|h| lower.contains(h)) +} + +/// De-duplicated, sorted font names; with `mono_first`, likely monospaced +/// fonts come first. Returns (name, looks monospaced). +pub fn font_choices(mut names: Vec, mono_first: bool) -> Vec<(String, bool)> { + names.retain(|n| !n.trim().is_empty() && !n.starts_with('.')); + names.sort_by_key(|n| n.to_lowercase()); + names.dedup(); + let mut out: Vec<(String, bool)> = names.into_iter().map(|n| (n.clone(), looks_monospace(&n))).collect(); + if mono_first { + out.sort_by_key(|(_, mono)| !*mono); + } + out +} + +/// Choices for the Shell setting: the system default, then every local +/// shell profile (the configured shell leads that list even when it is not +/// on `PATH`). Values are programs; the system default is `""`. +pub fn shell_options<'a>(profiles: impl IntoIterator) -> Vec { + let system = redshell_core::shell::default_shell(); + let system_name = std::path::Path::new(&system).file_stem().map_or(system.clone(), |s| s.to_string_lossy().into()); + let mut out = vec![SelectOption::new("", format!("System default ({system_name})"))]; + for p in profiles.into_iter().filter(|p| p.kind == LaunchKind::Shell) { + let program = p.command.program.clone(); + if !out.iter().any(|o| o.value.as_ref() == program) { + out.push(SelectOption::new(program.clone(), p.name.clone()).detail(program)); + } + } + out +} + +/// Font weights offered in Settings, by name. +pub const FONT_WEIGHTS: [(u16, &str); 9] = [ + (100, "Thin"), + (200, "Extra light"), + (300, "Light"), + (400, "Regular"), + (500, "Medium"), + (600, "Semibold"), + (700, "Bold"), + (800, "Extra bold"), + (900, "Black"), +]; + +/// Whether the theme follows the system's light or dark appearance. +pub fn follows_system(a: &AppearanceSettings) -> bool { + a.theme_light.is_some() || a.theme_dark.is_some() +} + +/// Starts or stops following the system appearance. Starting keeps +/// `current` for its own appearance and pairs it with the RedShell theme +/// of the other; stopping keeps `current` as the only theme. +pub fn set_follow_system(a: &mut AppearanceSettings, on: bool, current: &Theme) { + if on { + let (light, dark) = if current.is_dark() { + ("redshell-light", current.id.as_str()) + } else { + (current.id.as_str(), "redshell-dark") + }; + a.theme_light = Some(light.into()); + a.theme_dark = Some(dark.into()); + } else { + a.theme = current.id.clone(); + a.theme_light = None; + a.theme_dark = None; + } +} + +/// Picks a theme. While following the system, a dark theme becomes the dark +/// choice and a light theme the light one. +pub fn pick_theme(a: &mut AppearanceSettings, theme: &Theme) { + let id = Some(theme.id.clone()); + match (follows_system(a), theme.is_dark()) { + (true, true) => a.theme_dark = id, + (true, false) => a.theme_light = id, + (false, _) => a.theme = theme.id.clone(), + } +} + +/// The history lengths the Settings stepper offers, shortest first; 0 +/// (forever) comes last. +const RETENTION_DAYS: [u32; 7] = [7, 14, 30, 90, 180, 365, 0]; + +/// Moves `days` to the next longer (`delta > 0`) or shorter choice of +/// [`RETENTION_DAYS`]. A value typed into the file steps to its neighbours. +pub fn step_retention(days: u32, delta: i32) -> u32 { + let length = |d: u32| if d == 0 { u32::MAX } else { d }; + let next = if delta > 0 { + RETENTION_DAYS.into_iter().find(|&d| length(d) > length(days)) + } else { + RETENTION_DAYS.into_iter().rev().find(|&d| length(d) < length(days)) + }; + next.unwrap_or(days) +} + +#[cfg(test)] +mod tests { + use super::*; + use redshell_core::settings::ConfirmPolicy; + + #[test] + fn monospace_names_are_detected() { + for name in ["JetBrains Mono", "Fira Code", "DejaVu Sans Mono", "Cascadia Code", "Iosevka Term", "Menlo"] { + assert!(looks_monospace(name), "{name}"); + } + for name in ["DejaVu Sans", "Inter", "Noto Serif", "Helvetica Neue"] { + assert!(!looks_monospace(name), "{name}"); + } + } + + #[test] + fn font_choices_sort_dedup_and_put_mono_first() { + let names = ["Inter", "Fira Code", "inter", "Arial", "Fira Code", ".Hidden", "DejaVu Sans Mono", ""] + .map(String::from) + .to_vec(); + let mono: Vec<_> = font_choices(names.clone(), true).into_iter().map(|(n, _)| n).collect(); + assert_eq!(mono, ["DejaVu Sans Mono", "Fira Code", "Arial", "Inter", "inter"]); + let plain: Vec<_> = font_choices(names, false).into_iter().map(|(n, _)| n).collect(); + assert_eq!(plain, ["Arial", "DejaVu Sans Mono", "Fira Code", "Inter", "inter"]); + } + + #[test] + fn shell_options_list_the_default_then_each_shell_once() { + use redshell_core::settings::TerminalSettings; + use redshell_core::shell::local_shell_profile; + let shell = |program: &str| { + local_shell_profile(&TerminalSettings { shell: Some(program.into()), ..Default::default() }) + }; + let mut agent = shell("/usr/bin/claude"); + agent.kind = LaunchKind::Agent; + let profiles = [shell("/opt/custom/zsh"), shell("/bin/bash"), shell("/opt/custom/zsh"), agent]; + let options = shell_options(&profiles); + let values: Vec<&str> = options.iter().map(|o| o.value.as_ref()).collect(); + assert_eq!(values, ["", "/opt/custom/zsh", "/bin/bash"]); + assert!(options[0].label.starts_with("System default (")); + assert_eq!(options[1].label.as_ref(), "zsh"); + } + + #[test] + fn following_the_system_pairs_themes_by_appearance() { + let themes = redshell_theme::ThemeRegistry::with_builtins(); + let (nord, light) = (themes.resolve("nord").clone(), themes.resolve("redshell-light").clone()); + let mut a = AppearanceSettings { theme: "nord".into(), ..Default::default() }; + set_follow_system(&mut a, true, &nord); + assert!(follows_system(&a)); + assert_eq!((a.theme_light.as_deref(), a.theme_dark.as_deref()), (Some("redshell-light"), Some("nord"))); + + let solarized = themes.resolve("solarized-light").clone(); + pick_theme(&mut a, &solarized); + assert_eq!(a.theme_light.as_deref(), Some("solarized-light")); + assert_eq!(a.theme_dark.as_deref(), Some("nord"), "a light pick keeps the dark theme"); + + set_follow_system(&mut a, false, &light); + assert!(!follows_system(&a)); + assert_eq!(a.theme, "redshell-light", "the theme on screen stays"); + pick_theme(&mut a, &nord); + assert_eq!(a.theme, "nord"); + } + + #[test] + fn retention_steps_through_the_choices() { + assert_eq!(step_retention(30, 1), 90); + assert_eq!(step_retention(30, -1), 14); + assert_eq!(step_retention(365, 1), 0, "after a year comes forever"); + assert_eq!(step_retention(0, 1), 0); + assert_eq!(step_retention(0, -1), 365); + assert_eq!(step_retention(7, -1), 7); + assert_eq!(step_retention(45, 1), 90, "a typed value steps to a neighbour"); + assert_eq!(step_retention(45, -1), 30); + } + + #[test] + fn every_choice_is_offered_once_under_its_own_label() { + fn check() { + let labels: std::collections::HashSet<_> = T::ALL.iter().map(|c| c.label()).collect(); + assert_eq!(labels.len(), T::ALL.len(), "{:?}", T::ALL); + for (i, c) in T::ALL.iter().enumerate() { + assert_eq!(c.index(), i); + } + } + check::(); + check::(); + check::(); + check::(); + check::(); + check::(); + check::(); + } +} diff --git a/crates/redshell-app/src/settings_view/pages.rs b/crates/redshell-app/src/settings_view/pages.rs new file mode 100644 index 0000000..b0e1220 --- /dev/null +++ b/crates/redshell-app/src/settings_view/pages.rs @@ -0,0 +1,714 @@ +//! The rows of each Settings page. A row knows how to draw itself and +//! which settings it edits, so a page's reset restores exactly the +//! settings its rows show, including rows hidden until another setting +//! makes them relevant. + +use gpui::prelude::*; +use gpui::{AnyElement, Context, SharedString, div, px}; +use redshell_core::settings::{Settings, SidebarSection, WindowBackground}; +use redshell_ui::{ + Badge, BadgeVariant, Button, ButtonSize, ButtonVariant, IconName, Kbd, Segmented, Select, SelectOption, Stepper, + StyledExt, Switch, ThemeExt, alpha, section_label, setting_row, +}; + +use super::options::{Choice, FONT_WEIGHTS, Tab, follows_system, set_follow_system, shell_options, step_retention}; +use super::{FontTarget, SettingsEvent, SettingsView}; +use crate::commands::{COMMANDS, key_for, keymap}; +use crate::state::{AppState, update_settings}; + +/// One setting: how to read it and how to write it. +pub struct Field { + get: fn(&Settings) -> T, + set: fn(&mut Settings, T), +} + +impl Clone for Field { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Field {} + +/// The [`Field`] at a path below [`Settings`], e.g. `field!(terminal.visual_bell)`. +macro_rules! field { + ($($path:ident).+) => { + Field { get: |s: &Settings| Clone::clone(&s.$($path).+), set: |s: &mut Settings, v| s.$($path).+ = v } + }; +} + +type Render = Box) -> AnyElement>; +/// Restores settings (the first argument) from the defaults (the second). +type Reset = Box; + +/// One row of a page. +pub struct Row { + /// `None` for a row that is hidden now (it still resets). + render: Option, + resets: Vec, +} + +impl Row { + /// A row drawn by `render` that resets nothing. + fn custom(render: impl FnOnce(&mut Context) -> AnyElement + 'static) -> Self { + Self { render: Some(Box::new(render)), resets: Vec::new() } + } + + /// Resets `field` without showing anything. + fn reset_only(field: Field) -> Self { + Self { render: None, resets: Vec::new() }.resets(field) + } + + fn section(label: &'static str) -> Self { + Self::custom(move |cx| section_label(label, cx).into_any_element()) + } + + /// A labelled row with the control `control` builds. + fn setting( + label: &'static str, + description: Option<&str>, + control: impl FnOnce(&mut Context) -> E + 'static, + ) -> Self { + let description = description.map(str::to_owned); + Self::custom(move |cx| { + let control = control(cx); + setting_row(label, description.as_deref(), control, cx) + }) + } + + /// A switch for `field`. + fn toggle( + label: &'static str, + description: Option<&str>, + id: &'static str, + field: Field, + s: &Settings, + ) -> Self { + let on = (field.get)(s); + Self::setting(label, description, move |_| { + Switch::new(id, on).on_toggle(move |on, _w, cx| update_settings(cx, |s| (field.set)(s, on))) + }) + .resets(field) + } + + /// Segmented buttons offering every value of `field`. + fn choice( + label: &'static str, + description: Option<&str>, + id: &'static str, + field: Field, + s: &Settings, + ) -> Self { + let value = (field.get)(s); + Self::setting(label, description, move |_| { + let options = T::ALL.iter().enumerate().map(|(i, c)| (i.to_string().into(), c.label().into())).collect(); + Segmented::new(id, options, value.index().to_string()).on_select(move |key, _w, cx| { + if let Some(&value) = key.parse().ok().and_then(|i: usize| T::ALL.get(i)) { + update_settings(cx, |s| (field.set)(s, value)); + } + }) + }) + .resets(field) + } + + /// A stepper showing `value` and applying `step` (-1 or +1) per click. + fn stepper( + label: &'static str, + description: Option<&str>, + id: &'static str, + value: String, + unit: &'static str, + step: fn(&mut Settings, i32), + ) -> Self { + Self::setting(label, description, move |_| { + Stepper::new(id, value).unit(unit).on_step(move |d, _w, cx| update_settings(cx, |s| step(s, d))) + }) + } + + /// A stepper moving `field` by `by` per click, shown through `show`. + #[allow(clippy::too_many_arguments)] + fn number( + label: &'static str, + description: Option<&str>, + id: &'static str, + field: Field, + s: &Settings, + by: f32, + show: fn(f32) -> String, + unit: &'static str, + ) -> Self { + let value = show((field.get)(s)); + Self::setting(label, description, move |_| { + Stepper::new(id, value) + .unit(unit) + .on_step(move |d, _w, cx| update_settings(cx, |s| (field.set)(s, (field.get)(s) + d as f32 * by))) + }) + .resets(field) + } + + /// Also restores `field` when the page is reset. + fn resets(mut self, field: Field) -> Self { + self.resets.push(Box::new(move |s, defaults| (field.set)(s, (field.get)(defaults)))); + self + } + + /// Shows the row only when `visible`; a hidden row still resets. + fn shown(mut self, visible: bool) -> Self { + if !visible { + self.render = None; + } + self + } + + /// Draws the row, unless it is hidden. + pub fn render(self, cx: &mut Context) -> Option { + self.render.map(|render| render(cx)) + } +} + +/// Whole numbers, as most steppers show their value. +fn whole(v: f32) -> String { + format!("{v:.0}") +} + +/// A fraction as a whole percentage. +fn percent(v: f32) -> String { + format!("{:.0}", v * 100.0) +} + +impl Tab { + /// The rows of this page for the settings `s`. + pub fn rows(self, s: &Settings) -> Vec { + match self { + Tab::Appearance => appearance(s), + Tab::Terminal => terminal(s), + Tab::Safety => safety(s), + Tab::Sessions => sessions(s), + Tab::Keys => keybindings(s), + } + } +} + +/// Restores the defaults of the settings a page shows, and only those (the +/// theme and the shell are kept: they have rows but no reset). +pub fn reset_section(settings: &mut Settings, tab: Tab) { + let defaults = Settings::default(); + for row in tab.rows(settings) { + for reset in &row.resets { + reset(settings, &defaults); + } + } +} + +fn appearance(s: &Settings) -> Vec { + [theme(s), typography(s), window(s), layout(s), sidebar(s)].into_iter().flatten().collect() +} + +/// The Theme section of the Appearance page; its rows are kept by a reset. +fn theme(s: &Settings) -> Vec { + let following = follows_system(&s.appearance); + vec![ + Row::section("Theme"), + Row::setting( + "Match system appearance", + Some(if following { + "Pick one light and one dark theme" + } else { + "Switch between a light and a dark theme with the system" + }), + move |_| { + Switch::new("follow-system", following).on_toggle(move |on, _w, cx| { + let current = cx.theme().theme.clone(); + update_settings(cx, |s| set_follow_system(&mut s.appearance, on, ¤t)) + }) + }, + ), + Row::custom(SettingsView::theme_cards), + Row::custom(|cx| { + div() + .flex() + .gap(px(8.)) + .pt(px(10.)) + .child( + Button::new("import-theme") + .label("Import theme from clipboard") + .icon(IconName::ClipboardPaste) + .variant(ButtonVariant::Outline) + .size(ButtonSize::Sm) + .tooltip("Copy a theme's CSS from tweakcn.com first") + .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::ImportTheme))), + ) + .child( + Button::new("reveal-themes") + .label("Open config folder") + .variant(ButtonVariant::Ghost) + .size(ButtonSize::Sm) + .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::RevealConfig))), + ) + .into_any_element() + }), + ] +} + +fn typography(s: &Settings) -> Vec { + let weight = s.appearance.font_weight.to_string(); + vec![ + Row::section("Typography"), + font_row("Terminal font", Some("Monospaced fonts are listed first"), FontTarget::Terminal, s) + .resets(field!(appearance.font_family)), + Row::number("Font size", None, "font-size", field!(appearance.font_size), s, 1.0, whole, "px"), + Row::setting("Font weight", None, move |_| { + Select::new( + "font-weight", + FONT_WEIGHTS.iter().map(|(w, name)| SelectOption::new(w.to_string(), *name)).collect(), + weight, + ) + .on_select(|weight, _w, cx| { + if let Ok(weight) = weight.parse() { + update_settings(cx, |s| s.appearance.font_weight = weight) + } + }) + }) + .resets(field!(appearance.font_weight)), + Row::number( + "Line height", + Some("Multiple of the font size"), + "line-height", + field!(appearance.line_height), + s, + 0.05, + |v| format!("{v:.2}"), + "×", + ), + Row::number( + "Letter spacing", + Some("Extra space between characters"), + "letter-spacing", + field!(appearance.letter_spacing), + s, + 0.5, + |v| format!("{v:.1}"), + "px", + ), + font_row("Interface font", None, FontTarget::Ui, s).resets(field!(appearance.ui_font_family)), + Row::number("Interface font size", None, "ui-size", field!(appearance.ui_font_size), s, 1.0, whole, "px"), + ] +} + +fn window(s: &Settings) -> Vec { + let a = &s.appearance; + let has_image = a.background_image.is_some(); + let image = a.background_image.as_ref().map(|p| p.display().to_string()); + vec![ + Row::section("Window"), + Row::choice("Window background", None, "window-bg", field!(appearance.window_background), s), + Row::number( + "Background opacity", + Some("Lower values let more of the desktop show through"), + "opacity", + field!(appearance.background_opacity), + s, + 0.05, + percent, + "%", + ) + .shown(a.window_background != WindowBackground::Opaque), + Row::setting( + "Background image", + Some(image.as_deref().unwrap_or("Shown behind the terminal text in every pane")), + move |cx| { + div() + .flex() + .gap(px(6.)) + .child( + Button::new("bg-choose") + .label(if has_image { "Change…" } else { "Choose…" }) + .icon(IconName::FolderOpen) + .variant(ButtonVariant::Outline) + .size(ButtonSize::Sm) + .on_click(cx.listener(|this, _, _, cx| this.choose_background_image(cx))), + ) + .when(has_image, |d| { + d.child( + Button::new("bg-remove") + .label("Remove") + .variant(ButtonVariant::Ghost) + .size(ButtonSize::Sm) + .on_click(|_, _, cx| update_settings(cx, |s| s.appearance.background_image = None)), + ) + }) + }, + ) + .resets(field!(appearance.background_image)), + Row::number( + "Image opacity", + None, + "img-opacity", + field!(appearance.background_image_opacity), + s, + 0.05, + percent, + "%", + ) + .shown(has_image), + Row::choice("Image fit", None, "img-fit", field!(appearance.background_image_fit), s).shown(has_image), + ] +} + +fn layout(s: &Settings) -> Vec { + vec![ + Row::section("Layout"), + Row::number("Padding", None, "padding", field!(appearance.padding), s, 2.0, whole, "px"), + Row::choice("Tab bar", None, "tab-bar", field!(appearance.tab_bar), s), + Row::toggle("Status bar", None, "statusbar", field!(appearance.show_status_bar), s), + Row::number( + "Dim inactive panes", + Some("How much split panes without focus fade"), + "pane-dim", + field!(appearance.inactive_pane_dim), + s, + 0.05, + percent, + "%", + ), + ] +} + +/// The Sidebar section of the Appearance page. +fn sidebar(s: &Settings) -> Vec { + let a = &s.appearance; + let mut rows = vec![ + Row::section("Sidebar"), + Row::toggle("Show sidebar", None, "sidebar", field!(appearance.show_sidebar), s), + // Set by dragging the sidebar's edge. + Row::reset_only(field!(appearance.sidebar_width)), + Row::reset_only(field!(appearance.sidebar_sections)), + ]; + for (i, section) in SidebarSection::ALL.into_iter().enumerate() { + let description = match section { + SidebarSection::Multiplexer => Some("tmux or screen sessions on this computer"), + SidebarSection::Recent => Some("Closed sessions from history"), + _ => None, + }; + let on = a.sidebar_sections.contains(§ion); + rows.push(Row::setting(section.label(), description, move |_| { + Switch::new(("sidebar-section", i), on) + .on_toggle(move |on, _w, cx| update_settings(cx, |s| s.appearance.set_sidebar_section(section, on))) + })); + } + rows +} + +/// A button showing the font of `target` that opens the font picker. +fn font_row(label: &'static str, description: Option<&str>, target: FontTarget, s: &Settings) -> Row { + let (id, name) = match target { + FontTarget::Terminal => ("font-family", s.appearance.font_family.clone()), + FontTarget::Ui => ("ui-font-family", s.appearance.ui_font_family.clone()), + }; + Row::setting(label, description, move |cx| { + Button::new(id) + .label(name) + .icon(IconName::Type) + .variant(ButtonVariant::Outline) + .size(ButtonSize::Sm) + .tooltip("Choose from installed fonts") + .on_click(cx.listener(move |this, _, window, cx| this.open_font_picker(target, window, cx))) + }) +} + +fn terminal(s: &Settings) -> Vec { + let shell = s.terminal.shell.clone().unwrap_or_default(); + vec![ + Row::section("Cursor"), + Row::choice("Cursor style", None, "cursor", field!(appearance.cursor_style), s), + Row::toggle("Blinking cursor", None, "blink", field!(appearance.cursor_blink), s), + Row::section("Behaviour"), + Row::toggle( + "Copy on select", + Some("Selected text goes to the clipboard immediately"), + "copy-select", + field!(terminal.copy_on_select), + s, + ), + Row::toggle("Visual bell", None, "bell", field!(terminal.visual_bell), s), + Row::toggle( + "Shell integration", + Some("Tracks the folder and prompts of bash, zsh, fish and PowerShell in new tabs"), + "shell-integration", + field!(terminal.shell_integration), + s, + ), + Row::choice( + "Close when the program exits", + Some("On success keeps a pane open when its program fails"), + "close-on-exit", + field!(terminal.close_on_exit), + s, + ), + Row::toggle( + "Upload pasted images", + Some("Paste Image sends a clipboard image to the agent on an SSH host"), + "paste-image-upload", + field!(terminal.paste_image_upload), + s, + ), + Row::toggle("Bold text uses bright colours", None, "bold-bright", field!(appearance.bold_is_bright), s), + Row::stepper( + "Scrollback", + Some("Lines you can scroll back in each pane"), + "scrollback", + format!("{}k", s.terminal.scrollback_lines / 1000), + "lines", + |s, d| { + s.terminal.scrollback_lines = (s.terminal.scrollback_lines as i64 + d as i64 * 5000).max(1000) as usize + }, + ) + .resets(field!(terminal.scrollback_lines)), + // The shell is kept by a reset. + Row::setting("Shell", Some("Used for new tabs"), move |cx| { + Select::new("shell", shell_options(cx.global::().all_profiles()), shell).on_select( + |program, _w, cx| { + update_settings(cx, |s| { + let shell = (!program.is_empty()).then(|| program.to_string()); + // Arguments belong to the shell they were written for. + if s.terminal.shell != shell { + s.terminal.shell = shell; + s.terminal.shell_args.clear(); + } + }) + }, + ) + }), + ] +} + +fn safety(s: &Settings) -> Vec { + let typed = s.safety.typed_confirmation.is_some(); + vec![ + // Every closing offers every policy: "Several tabs" also asks when + // closing more than one tab at once (Close Other Tabs). + Row::section("Confirm before closing"), + Row::choice( + "Closing a tab", + Some("Several tabs: also when closing more than one at once"), + "p-tab", + field!(safety.confirm_close_tab), + s, + ), + Row::choice( + "Closing a window", + Some("Several tabs: also when more than one tab is open"), + "p-win", + field!(safety.confirm_close_window), + s, + ), + Row::choice( + "Quitting RedShell", + Some(if cfg!(target_os = "macos") { + "Confirm with a click or Cmd+Enter; Enter and Esc cancel" + } else { + "Confirm with a click or Ctrl+Enter; Enter and Esc cancel" + }), + "p-quit", + field!(safety.confirm_quit), + s, + ), + Row::setting( + "Require typing “close” to quit", + Some("An extra check before closing everything at once"), + move |_| { + Switch::new("typed", typed).on_toggle(|on, _w, cx| { + update_settings(cx, |s| s.safety.typed_confirmation = on.then(|| "close".into())) + }) + }, + ) + .resets(field!(safety.typed_confirmation)), + Row::toggle( + "Confirm multi-line paste", + Some("Asks before pasting several lines that would run right away"), + "ml-paste", + field!(safety.confirm_multiline_paste), + s, + ), + Row::section("Updates"), + Row::toggle( + "Check for updates", + Some("Asks GitHub once a day. Nothing is downloaded or installed."), + "updates", + field!(updates.check), + s, + ), + ] +} + +fn sessions(s: &Settings) -> Vec { + let retain = s.history.retain_days; + vec![ + Row::section("History"), + Row::toggle( + "Record sessions", + Some("Keeps terminal output so you can search it later. Takes effect after a restart."), + "hist", + field!(history.enabled), + s, + ), + Row::toggle("Restore tabs on start", None, "restore", field!(history.restore_tabs), s), + Row::toggle("Show earlier output in restored tabs", None, "replay", field!(history.restore_scrollback), s), + Row::stepper( + "Keep history for", + Some( + "Recordings older than this are deleted when RedShell starts. Pinned sessions and open tabs are \ + always kept, and ∞ keeps everything.", + ), + "retain", + if retain == 0 { "∞".into() } else { retain.to_string() }, + "days", + |s, d| s.history.retain_days = step_retention(s.history.retain_days, d), + ) + .resets(field!(history.retain_days)), + Row::section("Multiplexer"), + Row::choice( + "Preferred multiplexer", + Some("Used locally, over SSH and through WSL on Windows"), + "mux", + field!(multiplexer.preferred), + s, + ), + Row::toggle( + "Keep new tabs running in tmux or screen", + Some("Tabs survive crashes and restarts and reconnect on their own"), + "auto-mux", + field!(multiplexer.auto_attach_local), + s, + ), + ] +} + +fn keybindings(s: &Settings) -> Vec { + let keys = keymap(&s.keybindings); + let mut rows = vec![ + Row::reset_only(field!(keybindings)), + Row::custom(|cx| { + let t = cx.theme().clone(); + div() + .flex() + .items_center() + .gap(px(12.)) + .pt(px(14.)) + .child( + div() + .flex_1() + .min_w_0() + .text_size(t.text_xs()) + .text_color(t.ui().muted_foreground) + .child("You can change these shortcuts in the config file."), + ) + .child( + Button::new("keys-edit") + .label("Edit config file") + .icon(IconName::Pencil) + .variant(ButtonVariant::Outline) + .size(ButtonSize::Sm) + .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::EditFile))), + ) + .into_any_element() + }), + ]; + // Grouped by category, in order of first appearance. + let mut categories: Vec<&str> = Vec::new(); + for c in COMMANDS { + if !categories.contains(&c.category) { + categories.push(c.category); + } + } + for category in categories { + rows.push(Row::section(category)); + for c in COMMANDS.iter().filter(|c| c.category == category) { + let key = key_for(c.id, &keys); + let custom = key.as_ref().is_some_and(|k| s.keybindings.contains_key(k)); + rows.push(Row::custom(move |cx| keybinding_row(c.title, key, custom, cx))); + } + } + rows +} + +/// A command and the key that runs it; `custom` when the user chose the key. +fn keybinding_row( + title: &'static str, + key: Option, + custom: bool, + cx: &mut Context, +) -> AnyElement { + let t = cx.theme().clone(); + let ui = *t.ui(); + div() + .flex() + .items_center() + .gap(px(10.)) + .px(px(10.)) + .py(px(5.)) + .border_b_1() + .border_color(alpha(ui.border, 0.6)) + .text_size(t.text_sm()) + .child(div().flex_1().min_w_0().truncate_line().child(title)) + .when(custom, |d| d.child(Badge::new("Changed").variant(BadgeVariant::Primary))) + .child(match key { + Some(k) => Kbd::new(k).into_any_element(), + None => div().text_color(ui.muted_foreground).child(SharedString::from("—")).into_any_element(), + }) + .into_any_element() +} + +#[cfg(test)] +mod tests { + use super::*; + use redshell_core::settings::{CloseOnExit, ConfirmPolicy, WindowBackground}; + + #[test] + fn reset_section_only_touches_that_section() { + let mut s = Settings::default(); + s.appearance.theme = "nord".into(); + s.appearance.font_size = 20.0; + s.appearance.cursor_blink = false; + s.safety.confirm_quit = ConfirmPolicy::Never; + s.keybindings.insert("ctrl-x".into(), "tab.new".into()); + reset_section(&mut s, Tab::Appearance); + assert_eq!(s.appearance.font_size, Settings::default().appearance.font_size); + assert_eq!(s.appearance.theme, "nord", "the theme is kept"); + assert!(!s.appearance.cursor_blink, "cursor belongs to the Terminal page"); + assert_eq!(s.safety.confirm_quit, ConfirmPolicy::Never); + reset_section(&mut s, Tab::Terminal); + assert!(s.appearance.cursor_blink); + reset_section(&mut s, Tab::Safety); + assert_eq!(s.safety.confirm_quit, ConfirmPolicy::MultipleTabs); + reset_section(&mut s, Tab::Keys); + assert!(s.keybindings.is_empty()); + } + + #[test] + fn every_row_of_the_terminal_page_resets_but_the_shell() { + let mut s = Settings::default(); + let t = &mut s.terminal; + (t.copy_on_select, t.visual_bell, t.shell_integration) = (!t.copy_on_select, !t.visual_bell, false); + (t.paste_image_upload, t.close_on_exit, t.scrollback_lines) = (!t.paste_image_upload, CloseOnExit::Never, 1000); + t.shell = Some("/bin/zsh".into()); + reset_section(&mut s, Tab::Terminal); + let defaults = Settings::default().terminal; + assert_eq!(s.terminal.shell.as_deref(), Some("/bin/zsh"), "the shell is kept"); + assert_eq!( + s.terminal.clone(), + redshell_core::settings::TerminalSettings { shell: s.terminal.shell.clone(), ..defaults } + ); + } + + #[test] + fn hidden_rows_reset_too() { + let mut s = Settings::default(); + s.appearance.background_opacity = 0.5; + s.appearance.background_image_opacity = 0.2; + s.appearance.sidebar_width = 400.0; + assert_eq!(s.appearance.window_background, WindowBackground::Opaque, "the opacity row is hidden"); + reset_section(&mut s, Tab::Appearance); + assert_eq!(s.appearance, redshell_core::settings::AppearanceSettings::default()); + } +} diff --git a/crates/redshell-app/src/sidebar.rs b/crates/redshell-app/src/sidebar.rs new file mode 100644 index 0000000..e07f10a --- /dev/null +++ b/crates/redshell-app/src/sidebar.rs @@ -0,0 +1,468 @@ +//! The sidebar next to the panes: the sections listed in +//! `appearance.sidebar_sections`, in that order, and a handle on its right +//! edge that resizes it. + +use std::collections::HashSet; + +use gpui::prelude::*; +use gpui::{ + AnyElement, App, ClickEvent, Context, DragMoveEvent, FontWeight, MouseButton, MouseUpEvent, SharedString, Window, + div, px, +}; +use redshell_core::display_path::PathDisplay; +use redshell_core::settings::{AppearanceSettings, SidebarSection}; +use redshell_core::{LaunchKind, LaunchProfile, SessionId}; +use redshell_history::SessionRecord; +use redshell_remote::{MuxSession, MuxTarget}; +use redshell_ui::{Button, ButtonSize, ButtonVariant, IconName, ListItem, StyledExt, ThemeExt, alpha}; + +use super::{DragGhost, PATH_LABEL_MAX_CHARS, Tab, Workspace}; +use crate::commands::CommandTarget; +use crate::mux_listings::{self, ListingError, SidebarHost, sidebar_hosts}; +use crate::state::{AppState, Surfaces, update_settings}; + +/// Drag payload of the sidebar's resize handle. +#[derive(Clone)] +struct SidebarResize; + +impl Workspace { + pub(super) fn render_sidebar(&self, cx: &mut Context) -> impl IntoElement + use<> { + let t = cx.theme().clone(); + let ui = *t.ui(); + let appearance = &cx.global::().settings.appearance; + let width = px(self.sidebar_drag.unwrap_or(appearance.sidebar_width)); + let surface = Surfaces::new(appearance).chrome(ui.sidebar); + let sections = appearance.sidebar_sections.clone(); + let body: Vec = sections.into_iter().map(|s| self.render_sidebar_section(s, cx)).collect(); + + div() + .relative() + .flex() + .flex_col() + .flex_none() + .w(width) + .h_full() + .bg(surface) + .text_color(ui.sidebar_foreground) + .border_r_1() + .border_color(ui.sidebar_border) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .h(px(40.)) + .px(px(14.)) + .border_b_1() + .border_color(ui.sidebar_border) + .child(div().size(px(10.)).rounded_full().bg(ui.primary).shadow_sm()) + .child(div().flex_1().font_weight(FontWeight::BOLD).text_size(t.ui_size + px(1.)).child("RedShell")) + .child(command_button("side-search", IconName::Search, "Search sessions", "session.search", cx)) + .child(command_button("side-settings", IconName::Settings, "Settings", "settings.open", cx)), + ) + .child(div().id("sidebar-scroll").flex_1().overflow_y_scroll().px(px(6.)).pb(px(12.)).children(body)) + // Drag moves of the handle (see [`Self::render_sidebar_handle`]) + // reach this listener wherever the pointer is; the release is + // caught over the sidebar or anywhere else. + .on_drag_move(cx.listener(|this, ev: &DragMoveEvent, _, cx| { + let width = AppearanceSettings::clamp_sidebar_width( + f32::from(ev.event.position.x - ev.bounds.origin.x).round(), + ); + if this.sidebar_drag != Some(width) { + this.sidebar_drag = Some(width); + cx.notify(); + } + })) + .capture_any_mouse_up(cx.listener(Self::finish_sidebar_resize)) + .on_mouse_up_out(MouseButton::Left, cx.listener(Self::finish_sidebar_resize)) + } + + /// The handle that resizes the sidebar: a strip straddling its right + /// border, 3 px on either side. It is placed in the sidebar's parent + /// after the panes so it lies above their edge (the terminal's padding) + /// but below dialogs. Double-click restores the default width. + pub(super) fn render_sidebar_handle(&self, cx: &mut Context) -> impl IntoElement + use<> { + const REACH: f32 = 3.; + let ui = *cx.theme().ui(); + let appearance = &cx.global::().settings.appearance; + let width = self.sidebar_drag.unwrap_or(appearance.sidebar_width); + div() + .id("sidebar-resize") + .absolute() + .top_0() + .bottom_0() + .left(px(width - REACH)) + .w(px(2. * REACH)) + .occlude() + .cursor_col_resize() + .hover(|s| s.bg(alpha(ui.ring, 0.35))) + .on_drag(SidebarResize, |_, _, _, cx| cx.new(|_| DragGhost)) + .on_click(cx.listener(|_, ev: &ClickEvent, _, cx| { + if ev.click_count() >= 2 { + let default = AppearanceSettings::default().sidebar_width; + update_settings(cx, |s| s.appearance.sidebar_width = default); + } + })) + } + + /// Saves the width a drag of the sidebar edge left behind: once, on + /// release, rather than on every move. + fn finish_sidebar_resize(&mut self, _: &MouseUpEvent, _: &mut Window, cx: &mut Context) { + if let Some(width) = self.sidebar_drag.take() { + update_settings(cx, |s| s.appearance.sidebar_width = width); + } + } + + /// One section: its header, then its rows, or a short hint when it has none. + fn render_sidebar_section(&self, section: SidebarSection, cx: &mut Context) -> AnyElement { + let title: SharedString = match section { + SidebarSection::Multiplexer => cx.global::().local_mux().mux.program().into(), + _ => section.label().into(), + }; + let action = section_action(section, cx); + let rows = match section { + SidebarSection::Sessions => self.session_rows(cx), + SidebarSection::Shells => { + let shells: Vec<_> = cx + .global::() + .all_profiles() + .iter() + .filter(|p| matches!(p.kind, LaunchKind::Shell | LaunchKind::Plugin)) + .cloned() + .collect(); + profile_rows(shells, cx) + } + SidebarSection::Agents => { + let agents: Vec<_> = + cx.global::().profiles_of(LaunchKind::Agent).filter(|p| p.available).cloned().collect(); + profile_rows(agents, cx) + } + SidebarSection::Hosts => { + let hosts: Vec<_> = cx.global::().profiles_of(LaunchKind::Ssh).cloned().collect(); + profile_rows(hosts, cx) + } + SidebarSection::Multiplexer => self.mux_rows(cx), + SidebarSection::Recent => self.recent_rows(cx), + }; + let hint = if rows.is_empty() { empty_hint(section, cx) } else { None }; + div().child(section_header(title, action, cx)).children(rows).children(hint).into_any_element() + } + + fn session_rows(&self, cx: &mut Context) -> Vec { + let primary = cx.theme().ui().primary; + self.tabs + .iter() + .enumerate() + .map(|(i, tab)| { + let tab_id = tab.id; + let v = tab.active.read(cx); + let paths = PathDisplay::user(); + let title = Self::tab_label(tab, cx); + // The folder, unless the title already is it. + let sub = v + .cwd + .as_deref() + .map(|cwd| paths.compact(cwd, PATH_LABEL_MAX_CHARS)) + .filter(|cwd| *cwd != title) + .unwrap_or_else(|| v.profile.description.clone()); + ListItem::new(("side-tab", tab.id), title) + .icon(v.kind().into()) + .subtitle(sub) + .dense(true) + .selected(i == self.active) + .when(i != self.active && tab.views().iter().any(|v| v.read(cx).has_activity), |l| { + l.end(div().size(px(6.)).rounded_full().bg(primary)) + }) + .on_click(cx.listener(move |this, _, w, cx| this.activate_tab_id(tab_id, w, cx))) + .into_any_element() + }) + .collect() + } + + /// Lists the sessions the multiplexer section shows, while it is + /// visible: this computer's and those of the [`sidebar_hosts`]. The + /// timer lists a target only when it is due (see + /// [`MuxTarget::poll_interval`]); `on_request` (the user just showed the + /// section) also lists those never polled, such as WSL. + pub(super) fn refresh_mux_sessions(&self, on_request: bool, cx: &mut Context) { + for (key, target, in_use) in self.mux_section_targets(cx) { + match target.poll_interval(in_use) { + _ if on_request => mux_listings::refresh(&key, cx), + Some(interval) => mux_listings::refresh_if_due(&key, interval, cx), + None => {} + } + } + } + + /// Lists this computer's sessions now if the section shows them (WSL, + /// which the timer never lists, once as a window opens). + pub(super) fn list_local_mux_sessions(&self, cx: &mut Context) { + if self.mux_section_targets(cx).iter().any(|(key, ..)| key == "local") { + mux_listings::refresh("local", cx); + } + } + + /// The targets the multiplexer section lists, as keys with their + /// target and whether they are in use: none while it is hidden, this + /// computer when its multiplexer is there, and the [`sidebar_hosts`]. + fn mux_section_targets(&self, cx: &App) -> Vec<(String, MuxTarget, bool)> { + let state = cx.global::(); + if !state.settings.appearance.visible_sidebar_sections().contains(&SidebarSection::Multiplexer) { + return Vec::new(); + } + let local = state.local_mux(); + let local = local.locally_available().then(|| ("local".to_owned(), local.target, true)); + let hosts = self.sidebar_hosts(cx).into_iter().filter_map(|host| { + let key = host.key(); + Some((key.clone(), state.mux_client(&key)?.target, host.in_use)) + }); + local.into_iter().chain(hosts).collect() + } + + /// The SSH hosts whose sessions the sidebar shows, see [`sidebar_hosts`]. + fn sidebar_hosts(&self, cx: &App) -> Vec { + let state = cx.global::(); + let views: Vec<_> = self.tabs.iter().flat_map(Tab::views).collect(); + let profiles = views.iter().map(|v| &v.read(cx).profile); + sidebar_hosts(profiles, &state.settings.multiplexer, &state.ssh) + } + + /// This computer's sessions, then those of each SSH host under its + /// name. A host whose listing failed shows why; one without sessions, + /// or without the multiplexer, is left out. + fn mux_rows(&self, cx: &mut Context) -> Vec { + let state = cx.global::(); + let known = |key: &str| { + let listing = state.mux_listings.get(key); + let sessions = listing.and_then(|l| l.sessions.as_ref()).into_iter().flatten(); + let error = listing.and_then(|l| l.error.as_ref()).filter(|e| !matches!(e, ListingError::NotInstalled(_))); + (sessions.map(|l| l.session.clone()).collect::>(), error.map(|e| e.message().to_owned())) + }; + let local = known("local").0; + let local_label = match state.local_mux().target { + MuxTarget::Local => "This computer".to_owned(), + other => other.label(), + }; + let hosts: Vec<_> = self + .sidebar_hosts(cx) + .into_iter() + .map(|host| { + let key = host.key(); + let known = known(&key); + (key, host.name, known) + }) + .filter(|(_, _, (sessions, error))| !sessions.is_empty() || error.is_some()) + .collect(); + + let mut rows = Vec::new(); + if !hosts.is_empty() && !local.is_empty() { + rows.push(group_label(local_label, cx)); + } + rows.extend(local.iter().map(|s| mux_row("local", s, cx))); + if local.is_empty() && hosts.iter().all(|(_, _, (sessions, _))| sessions.is_empty()) { + rows.extend(empty_hint(SidebarSection::Multiplexer, cx)); + } + for (key, name, (sessions, error)) in hosts { + rows.push(group_label(name, cx)); + rows.extend(sessions.iter().map(|s| mux_row(&key, s, cx))); + rows.extend(error.map(|e| muted_line(e, cx))); + } + rows + } + + fn recent_rows(&self, cx: &mut Context) -> Vec { + let open_now = self.open_sessions(cx); + recent_entries(self.recent.clone(), &open_now) + .into_iter() + .map(|r| { + let id = r.id; + ListItem::new(SharedString::from(format!("recent-{}", r.id)), r.title.clone()) + .icon(IconName::History) + .subtitle(format!("{} · {}", r.profile.name, r.started().format("%b %d %H:%M"))) + .dense(true) + .on_click(cx.listener(move |this, _, w, cx| this.open_recording(id, false, w, cx))) + .into_any_element() + }) + .collect() + } +} + +/// Rows that open a launch profile when clicked. +fn profile_rows(profiles: impl IntoIterator, cx: &mut Context) -> Vec { + profiles + .into_iter() + .map(|p| { + ListItem::new(SharedString::from(format!("side-{}", p.id)), p.name.clone()) + .icon(p.kind.into()) + .subtitle(p.description.clone()) + .dense(true) + .dimmed(!p.available) + .on_click(cx.listener(move |this, _, w, cx| this.open_profile(p.clone(), w, cx))) + .into_any_element() + }) + .collect() +} + +/// A multiplexer session on target `key`; clicking attaches it in a new +/// tab, as the session manager's Attach does. +fn mux_row(key: &str, s: &MuxSession, cx: &mut Context) -> AnyElement { + let (key, name) = (key.to_owned(), s.name.clone()); + ListItem::new(SharedString::from(format!("mux-{key}-{name}")), s.name.clone()) + .icon(IconName::LayoutGrid) + .subtitle(format!( + "{} window{}{}", + s.windows, + if s.windows == 1 { "" } else { "s" }, + if s.attached { " · attached" } else { "" } + )) + .dense(true) + .on_click(cx.listener(move |this, _, w, cx| { + if let Some(client) = cx.global::().mux_client(&key) { + this.open_profile(client.attach_profile(&name), w, cx); + } + })) + .into_any_element() +} + +/// The name of a machine above its sessions. +fn group_label(text: String, cx: &App) -> AnyElement { + let t = cx.theme(); + div() + .px(px(10.)) + .pt(px(6.)) + .pb(px(2.)) + .text_size(t.text_xs()) + .font_weight(FontWeight::MEDIUM) + .text_color(t.ui().muted_foreground) + .truncate_line() + .child(SharedString::from(text)) + .into_any_element() +} + +/// One muted line, cut off at the sidebar's edge (a host that could not be listed). +fn muted_line(text: String, cx: &App) -> AnyElement { + let t = cx.theme(); + div() + .px(px(10.)) + .py(px(2.)) + .text_size(t.text_xs()) + .text_color(alpha(t.ui().muted_foreground, 0.8)) + .truncate_line() + .child(SharedString::from(text)) + .into_any_element() +} + +/// The button at the right of a section header, if the section has one. +fn section_action(section: SidebarSection, cx: &mut Context) -> Option