mirror of
https://github.com/rust-kotlin/ashell.git
synced 2026-10-03 16:00:18 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ae44c9e44 | ||
|
|
73938aef8a | ||
|
|
59df2b5a9a | ||
|
|
b225b0e56f | ||
|
|
2cdd6d3ded | ||
|
|
42c408f63f | ||
|
|
f4005bf2bb | ||
|
|
d5fab2e9ca | ||
|
|
1b7f625aea | ||
|
|
b6b4d3c35e | ||
|
|
ae763eae1c | ||
|
|
a89d15d255 | ||
|
|
b5a068541d | ||
|
|
7be0c420e1 | ||
|
|
62028c7921 | ||
|
|
56a6ef98b7 | ||
|
|
caa8a58561 | ||
|
|
6150bd410b | ||
|
|
f55c3a8470 | ||
|
|
7ae44ab9a7 | ||
|
|
9c43b2dde7 | ||
|
|
e6134bc0d1 | ||
|
|
96cd85a8d3 | ||
|
|
f45c2ed60f | ||
|
|
8a8f280401 | ||
|
|
dc006f7144 | ||
|
|
daaebe4c2b | ||
|
|
2a37f45ba2 | ||
|
|
ee8c18844c | ||
|
|
c5b09628b3 | ||
|
|
b45364331d | ||
|
|
2d92f0ceee | ||
|
|
162a245a8f | ||
|
|
68bf152792 | ||
|
|
13b9433c90 | ||
|
|
445e474fe8 | ||
|
|
4c7c06f391 | ||
|
|
e4fbd65a31 | ||
|
|
bd376935f4 | ||
|
|
16761c1bf5 | ||
|
|
c3201e7c30 | ||
|
|
2d5062ed75 | ||
|
|
d7d6faeeb1 | ||
|
|
19a4274473 | ||
|
|
4bb3bee6c8 | ||
|
|
8ab4b43825 | ||
|
|
bbf843dde6 | ||
|
|
bc6af2e213 | ||
|
|
d224506fd5 | ||
|
|
d175135529 | ||
|
|
c769b982b4 | ||
|
|
ee68835972 | ||
|
|
8a535fad5a | ||
|
|
90c07e16e1 | ||
|
|
33a3d624b7 |
@@ -0,0 +1,58 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: ${{ matrix.name }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
name: windows-x86_64
|
||||
- os: ubuntu-22.04 # build on the oldest supported runner for broader glibc compatibility
|
||||
target: x86_64-unknown-linux-gnu
|
||||
name: linux-x86_64
|
||||
- os: macos-14 # Apple Silicon
|
||||
target: aarch64-apple-darwin
|
||||
name: macos-aarch64
|
||||
- os: macos-14 # Intel (cross-compiled from Apple Silicon to avoid queue delays)
|
||||
target: x86_64-apple-darwin
|
||||
name: macos-x86_64
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# GPUI needs these system libs on Linux to compile.
|
||||
- name: Install Linux GUI dependencies
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
build-essential pkg-config cmake \
|
||||
libfontconfig1-dev libfreetype6-dev \
|
||||
libxcb1-dev libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev \
|
||||
libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev \
|
||||
libgl1-mesa-dev libegl1-mesa-dev libgtk-3-dev \
|
||||
libudev-dev
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Cache cargo build
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
|
||||
- name: Build (release)
|
||||
# We build in release mode so that the release workflow can reuse the exact artifacts
|
||||
run: cargo build --release --target ${{ matrix.target }}
|
||||
@@ -12,7 +12,7 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write # needed to create / update the GitHub Release
|
||||
contents: write # needed to create / update the GitHub Release
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -26,15 +26,15 @@ jobs:
|
||||
target: x86_64-pc-windows-msvc
|
||||
name: windows-x86_64
|
||||
bin: ashell.exe
|
||||
- os: ubuntu-22.04 # build on the oldest supported runner for broader glibc compatibility
|
||||
- os: ubuntu-22.04 # build on the oldest supported runner for broader glibc compatibility
|
||||
target: x86_64-unknown-linux-gnu
|
||||
name: linux-x86_64
|
||||
bin: ashell
|
||||
- os: macos-14 # Apple Silicon
|
||||
- os: macos-14 # Apple Silicon
|
||||
target: aarch64-apple-darwin
|
||||
name: macos-aarch64
|
||||
bin: ashell
|
||||
- os: macos-14 # Intel (cross-compiled from Apple Silicon to avoid queue delays)
|
||||
- os: macos-14 # Intel (cross-compiled from Apple Silicon to avoid queue delays)
|
||||
target: x86_64-apple-darwin
|
||||
name: macos-x86_64
|
||||
bin: ashell
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
# Note: We build the bundle manually here rather than running
|
||||
# scripts/package-macos-app.sh, because that script runs `cargo build`
|
||||
# without respecting the `--target` flag from the matrix.
|
||||
|
||||
|
||||
APP="ashell.app"
|
||||
CONTENTS="$APP/Contents"
|
||||
mkdir -p "$CONTENTS/MacOS" "$CONTENTS/Resources"
|
||||
@@ -168,3 +168,84 @@ jobs:
|
||||
files: dist/**/*
|
||||
generate_release_notes: true
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
cask:
|
||||
name: Update Homebrew Cask
|
||||
needs: publish
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Homebrew Tap
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: rust-kotlin/homebrew-taps
|
||||
token: ${{ secrets.TAP_GITHUB_TOKEN }}
|
||||
path: tap
|
||||
|
||||
- name: Download all macOS artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: macos-*
|
||||
path: dist
|
||||
|
||||
- name: Update Cask
|
||||
run: |
|
||||
VERSION=${GITHUB_REF#refs/tags/v}
|
||||
SHA_ARM=$(sha256sum dist/macos-aarch64/*.zip | cut -d' ' -f1)
|
||||
SHA_INTEL=$(sha256sum dist/macos-x86_64/*.zip | cut -d' ' -f1)
|
||||
|
||||
mkdir -p tap/Casks
|
||||
CASK_FILE="tap/Casks/ashell.rb"
|
||||
|
||||
cat > "$CASK_FILE" <<EOF
|
||||
cask "ashell" do
|
||||
version "${VERSION}"
|
||||
|
||||
on_arm do
|
||||
sha256 "${SHA_ARM}"
|
||||
url "https://github.com/rust-kotlin/ashell/releases/download/v#{version}/ashell-v#{version}-macos-aarch64.zip"
|
||||
end
|
||||
on_intel do
|
||||
sha256 "${SHA_INTEL}"
|
||||
url "https://github.com/rust-kotlin/ashell/releases/download/v#{version}/ashell-v#{version}-macos-x86_64.zip"
|
||||
end
|
||||
|
||||
name "ashell"
|
||||
desc "ashell is a modern, fast, GPUI Component-based desktop terminal client written in Rust."
|
||||
homepage "https://github.com/rust-kotlin/ashell"
|
||||
|
||||
app "ashell.app"
|
||||
|
||||
postflight do
|
||||
puts "Removing quarantine flag from ashell.app..."
|
||||
system_command "/usr/bin/xattr",
|
||||
args: ["-rd", "com.apple.quarantine", "#{appdir}/ashell.app"],
|
||||
sudo: true
|
||||
end
|
||||
|
||||
caveats <<~EOS
|
||||
ashell uses ad-hoc signing. The installation includes a postflight script
|
||||
that removes the 'com.apple.quarantine' attribute from the application
|
||||
to allow it to run. This will require your administrator password.
|
||||
|
||||
ashell 采用本地签名。安装程序包含一个后置脚本,用于移除应用程序的
|
||||
'com.apple.quarantine' 属性以允许其运行。这需要您的管理员密码。
|
||||
EOS
|
||||
end
|
||||
EOF
|
||||
# Remove the 10 leading spaces added for YAML formatting
|
||||
sed -i 's/^ //' "$CASK_FILE"
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
VERSION=${GITHUB_REF#refs/tags/v}
|
||||
cd tap
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
if [[ -n $(git status -s) ]]; then
|
||||
git add Casks/ashell.rb
|
||||
git commit -m "chore: bump ashell to v${VERSION}"
|
||||
git push
|
||||
else
|
||||
echo "No changes to commit"
|
||||
fi
|
||||
|
||||
Generated
+232
-27
@@ -265,6 +265,18 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayref"
|
||||
version = "0.3.9"
|
||||
@@ -303,11 +315,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ashell"
|
||||
version = "0.1.0"
|
||||
version = "0.4.7"
|
||||
dependencies = [
|
||||
"alacritty_terminal",
|
||||
"anyhow",
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"base64",
|
||||
"chacha20poly1305",
|
||||
"chrono",
|
||||
"directories",
|
||||
"flate2",
|
||||
@@ -316,11 +331,15 @@ dependencies = [
|
||||
"gpui-component",
|
||||
"gpui-component-assets",
|
||||
"gpui_platform",
|
||||
"hex",
|
||||
"hmac",
|
||||
"image",
|
||||
"menu",
|
||||
"notify 6.1.1",
|
||||
"open",
|
||||
"portable-pty",
|
||||
"rand 0.8.6",
|
||||
"reqwest",
|
||||
"rfd",
|
||||
"russh",
|
||||
"russh-keys",
|
||||
@@ -328,13 +347,16 @@ dependencies = [
|
||||
"rust-i18n 3.1.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"ssh-key",
|
||||
"sys-locale",
|
||||
"sysinfo 0.33.1",
|
||||
"tar",
|
||||
"thiserror 1.0.69",
|
||||
"time",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"walkdir",
|
||||
@@ -840,6 +862,15 @@ dependencies = [
|
||||
"no_std_io2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block"
|
||||
version = "0.1.6"
|
||||
@@ -1089,6 +1120,19 @@ dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20poly1305"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"chacha20",
|
||||
"cipher",
|
||||
"poly1305",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
@@ -1199,9 +1243,8 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "collections"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"gpui_util",
|
||||
"indexmap",
|
||||
"rustc-hash 2.1.2",
|
||||
]
|
||||
@@ -1650,6 +1693,15 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
dependencies = [
|
||||
"powerfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.4.2"
|
||||
@@ -1687,7 +1739,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "derive_refineable"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -2671,7 +2723,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui"
|
||||
version = "0.2.2"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"anyhow",
|
||||
@@ -2701,7 +2753,6 @@ dependencies = [
|
||||
"gpui_macros",
|
||||
"gpui_shared_string",
|
||||
"gpui_util",
|
||||
"heapless",
|
||||
"http_client",
|
||||
"image",
|
||||
"inventory",
|
||||
@@ -2821,7 +2872,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_linux"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"accesskit_unix",
|
||||
@@ -2872,7 +2923,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_macos"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"accesskit_macos",
|
||||
@@ -2917,7 +2968,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -2928,7 +2979,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"console_error_panic_hook",
|
||||
"gpui",
|
||||
@@ -2941,7 +2992,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_shared_string"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
@@ -2951,7 +3002,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_util"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"log",
|
||||
@@ -2960,7 +3011,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_web"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"console_error_panic_hook",
|
||||
@@ -2984,7 +3035,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_wgpu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytemuck",
|
||||
@@ -3013,7 +3064,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "gpui_windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"accesskit_windows",
|
||||
@@ -3262,7 +3313,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "http_client"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-compression",
|
||||
@@ -3325,6 +3376,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3333,13 +3385,16 @@ version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"hyper",
|
||||
"ipnet",
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"tokio",
|
||||
@@ -4135,7 +4190,7 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
|
||||
[[package]]
|
||||
name = "media"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bindgen",
|
||||
@@ -4183,7 +4238,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"gpui",
|
||||
]
|
||||
@@ -4540,6 +4595,12 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
@@ -4602,6 +4663,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_threads"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc"
|
||||
version = "0.2.7"
|
||||
@@ -4988,6 +5058,17 @@ dependencies = [
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
@@ -5053,7 +5134,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
[[package]]
|
||||
name = "perf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"collections",
|
||||
"serde",
|
||||
@@ -5371,6 +5452,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
@@ -5829,7 +5916,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "refineable"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"derive_refineable",
|
||||
]
|
||||
@@ -5869,6 +5956,44 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
"url",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resvg"
|
||||
version = "0.45.1"
|
||||
@@ -6445,7 +6570,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "scheduler"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"backtrace",
|
||||
@@ -7184,7 +7309,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
[[package]]
|
||||
name = "sum_tree"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"heapless",
|
||||
"log",
|
||||
@@ -7298,6 +7423,12 @@ dependencies = [
|
||||
"zeno",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "symlink"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.117"
|
||||
@@ -7533,6 +7664,39 @@ dependencies = [
|
||||
"zune-jpeg 0.5.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"itoa",
|
||||
"libc",
|
||||
"num-conv",
|
||||
"num_threads",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-keccak"
|
||||
version = "2.0.2"
|
||||
@@ -7783,6 +7947,24 @@ dependencies = [
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
dependencies = [
|
||||
"bitflags 2.12.1",
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"pin-project-lite",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
@@ -7807,6 +7989,19 @@ dependencies = [
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-appender"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"symlink",
|
||||
"thiserror 2.0.18",
|
||||
"time",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
@@ -7852,6 +8047,7 @@ dependencies = [
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
"time",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
@@ -8097,7 +8293,7 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
[[package]]
|
||||
name = "util"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-fs",
|
||||
@@ -8136,7 +8332,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "util_macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"perf",
|
||||
"quote",
|
||||
@@ -8530,6 +8726,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
@@ -10013,7 +10218,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "zlog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
@@ -10042,7 +10247,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ztracing"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
@@ -10053,7 +10258,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ztracing_macro"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/zed-industries/zed#dde98fa822c59028475850f242a4827ba770e24a"
|
||||
source = "git+https://github.com/zed-industries/zed#969a67fcfbf799e68ab00854028228274be847e8"
|
||||
|
||||
[[package]]
|
||||
name = "zune-core"
|
||||
|
||||
+12
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ashell"
|
||||
version = "0.1.0"
|
||||
version = "0.4.7"
|
||||
edition = "2024"
|
||||
authors = ["ashell contributors"]
|
||||
description = "A GPUI Component based SSH and local terminal client"
|
||||
@@ -34,7 +34,7 @@ tar = "0.4"
|
||||
thiserror = "1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "io-util", "net", "time", "fs"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "local-time", "time"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
walkdir = "2"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
@@ -42,6 +42,16 @@ image = { version = "0.25.9", default-features = false, features = ["png"] }
|
||||
futures = "0.3.32"
|
||||
notify = "6.1.1"
|
||||
open = "5.1"
|
||||
time = { version = "0.3.45", features = ["formatting", "local-offset"] }
|
||||
tracing-appender = "0.2.5"
|
||||
argon2 = "0.5"
|
||||
base64 = "0.22"
|
||||
chacha20poly1305 = "0.10"
|
||||
hmac = "0.12"
|
||||
hex = "0.4"
|
||||
rand = "0.8"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
|
||||
sha2 = "0.10"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
|
||||
+31
-10
@@ -8,15 +8,15 @@
|
||||
|
||||
This project focuses on providing a high-performance and visually appealing shell workspace by combining local and remote environments with a rich set of built-in features.
|
||||
|
||||
## 🚀 v0.3 Massive Update!
|
||||
## 🚀 v0.4 Major Upgrades
|
||||
|
||||
The brand-new v0.3 introduces comprehensive upgrades to both architecture and user experience:
|
||||
- ✨ **Global Real-Time Font Settings** (Thanks to [@ancion](https://github.com/ancion) for [PR #6](https://github.com/rust-kotlin/ashell/pull/6)): Customize your global UI fonts and terminal rendering fonts independently. Adjust text size in real-time with automatic persistence.
|
||||
- ✨ **Concurrent SFTP Transfers**: A dedicated Transfers dialog now supports highly optimized, concurrent file uploads and downloads with precise progress display.
|
||||
- ✨ **Persistent Workspace State**: Your sidebar width adjustments, terminal themes, font settings, and file visibility preferences are completely restored upon your next launch!
|
||||
- ✨ **Intelligent SSH Disconnect/Reconnect**: Greatly enhanced SSH connection resilience. Provides a beautiful and localized overlay for one-click re-connection on unexpected disconnections.
|
||||
- ✨ **Hot-Swappable i18n System**: Deeply optimized internationalization. Switch instantly between English and Simplified Chinese without restarting the application.
|
||||
- ✨ **Smart Right-Click Actions**: Added intelligent right-click copy and paste for the terminal, featuring a dedicated settings toggle and OS-native keyboard shortcut hints.
|
||||
v0.4 builds on the v0.3 foundation and focuses on more capable workspace operations and a smoother daily workflow:
|
||||
- ✨ **Keybinding Management**: View and edit common shortcuts from the settings UI with conflict hints.
|
||||
- ✨ **Settings Page Polish**: A more compact and clearer settings experience with improved layout and interaction flow.
|
||||
- ✨ **Multi-Pane Tabs with a tmux-like Workflow**: A single tab can now host multiple panes, with split, focus, and switching actions for a tmux-inspired experience.
|
||||
- ✨ **Transfer History Improvements**: The transfer history panel now presents richer task details, making upload and download activity easier to review.
|
||||
- ✨ **SSH Passphrase Support**: Private keys can now store a passphrase, and SSH connections will use it automatically.
|
||||
- ✨ **Terminal Rendering Enhancements**: Terminal rendering now handles Block Elements and similar custom glyphs more completely.
|
||||
|
||||
## Download
|
||||
|
||||
@@ -24,8 +24,28 @@ You can download the latest pre-compiled releases for macOS, Windows, and Linux
|
||||
|
||||
## Mac Installation Guide
|
||||
|
||||
After downloading, please unzip the file and move `ashell.app` to your **Applications** folder.
|
||||
Since the app uses ad-hoc signing, macOS may warn that the app is "damaged" upon first launch. If this happens, open Terminal and run the following command:
|
||||
### Method 1: Homebrew (Recommended)
|
||||
|
||||
If you use [Homebrew](https://brew.sh/), you can install it quickly with:
|
||||
|
||||
```bash
|
||||
brew install rust-kotlin/taps/ashell --cask
|
||||
```
|
||||
|
||||
To update the app:
|
||||
|
||||
```bash
|
||||
brew update
|
||||
brew upgrade ashell --cask
|
||||
```
|
||||
|
||||
> **Note**: Since the app uses ad-hoc signing, the Homebrew installation or update includes a postflight script to automatically handle the quarantine flag. This will require you to enter your administrator password for authorization.
|
||||
|
||||
### Method 2: Manual Download
|
||||
|
||||
1. Download and unzip from the [Releases page](https://github.com/rust-kotlin/ashell/releases/latest).
|
||||
2. Move `ashell.app` to your **Applications** folder.
|
||||
3. Since the app uses ad-hoc signing, macOS may warn that the app is "damaged" upon first launch. If this happens, open Terminal and run:
|
||||
|
||||
```bash
|
||||
sudo xattr -cr /Applications/ashell.app
|
||||
@@ -43,6 +63,7 @@ The current version provides a fully-featured GPUI-native workspace:
|
||||
- **System Telemetry:** Real-time visualization of CPU, memory, swap, network, and disk metrics in the left cockpit sidebar.
|
||||
- **Theming System:** Switch between multiple GPUI Component themes directly from the top toolbar.
|
||||
- **Embedded Fonts:** Uses embedded Maple Mono NF CN fonts out-of-the-box for excellent CJK character and Nerd Font icon support.
|
||||
- **v0.3 Core Enhancements:** Global font and font-size controls, concurrent SFTP transfers, persistent layout state, disconnect awareness, hot-swappable i18n, and smart terminal right-click copy/paste.
|
||||
|
||||
## Run
|
||||
|
||||
|
||||
@@ -8,15 +8,15 @@
|
||||
|
||||
该项目旨在通过结合本地和远程环境,并内置丰富的核心功能,提供一个高性能且美观的 Shell 工作区。
|
||||
|
||||
## 🚀 v0.3 版本重磅更新!
|
||||
## 🚀 v0.4 版本重要升级
|
||||
|
||||
全新发布的 v0.3 迎来了架构和体验的全面升级:
|
||||
- ✨ **全局实时字体设置与字号调节**(感谢 [@ancion](https://github.com/ancion) 提供的 [PR #6](https://github.com/rust-kotlin/ashell/pull/6)):支持自定义全局 UI 字体和终端渲染字体,支持实时字号调节并自动记忆。
|
||||
- ✨ **SFTP 多任务并发传输队列**:引入全新的独立传输对话框,支持多文件并发上传下载,提供精准的进度展示。
|
||||
- ✨ **持久化工作区记忆**:您对侧边栏的尺寸拖拽、终端主题、字体、隐藏文件开关等一切设置都会在下次启动时原样恢复!
|
||||
- ✨ **智能断线重连与状态感知**:全面增强的 SSH 网络异常处理机制,断线后直接提供美观的覆盖层用于一键重连或关闭。
|
||||
- ✨ **多语言热切换增强**:深度优化的 i18n 系统,包含中文与英文在内的所有界面文案现在均支持热切换。
|
||||
- ✨ **智能右键快捷操作**:新增终端右键智能复制与粘贴功能,提供专属设置项自由控制开关,并支持根据不同操作系统自适应显示原生快捷键提示。
|
||||
v0.4 在 v0.3 打下的基础上,重点带来了更完整的工作区操作能力和更顺手的日常体验:
|
||||
- ✨ **键位管理功能**:支持在设置中可视化查看和修改常用快捷键,并提供冲突提示。
|
||||
- ✨ **设置页优化**:设置页的布局和交互更加紧凑顺手,整体信息层级更清晰。
|
||||
- ✨ **Tab 内多 Pane 与类 tmux 体验**:一个 tab 内现在可以管理多个 pane,支持分屏、聚焦和切换,提供更接近 tmux 的工作流。
|
||||
- ✨ **传输历史增强**:传输历史面板展示更完整的任务信息,便于回溯上传和下载过程。
|
||||
- ✨ **SSH passphrase 支持**:现在可以为私钥填写 passphrase,并在连接时自动使用保存的口令。
|
||||
- ✨ **终端显示优化**:终端渲染进一步增强,支持 Block Elements 等自定义图形字符的更完整显示。
|
||||
|
||||
## 下载
|
||||
|
||||
@@ -24,8 +24,28 @@
|
||||
|
||||
## Mac 安装指南
|
||||
|
||||
下载并解压后,请先将 `ashell.app` 拖入或移动到 **应用程序 (Applications)** 目录。
|
||||
由于应用采用本地签名,初次启动时如果系统提示“App 已损坏,无法打开”,请打开终端(Terminal)并执行以下命令:
|
||||
### 方法 1: Homebrew 安装 (推荐)
|
||||
|
||||
如果您使用 [Homebrew](https://brew.sh/),可以通过以下命令快速安装:
|
||||
|
||||
```bash
|
||||
brew install rust-kotlin/taps/ashell --cask
|
||||
```
|
||||
|
||||
更新应用:
|
||||
|
||||
```bash
|
||||
brew update
|
||||
brew upgrade ashell --cask
|
||||
```
|
||||
|
||||
> **注意**: 由于应用采用本地签名,Homebrew 在安装或更新过程中会执行一个后置脚本来自动处理隔离属性(quarantine flag),这需要您输入管理员密码以授权。
|
||||
|
||||
### 方法 2: 手动下载
|
||||
|
||||
1. 从 [Releases 页面](https://github.com/rust-kotlin/ashell/releases/latest) 下载并解压。
|
||||
2. 将 `ashell.app` 拖入或移动到 **应用程序 (Applications)** 目录。
|
||||
3. 由于应用采用本地签名,初次启动时如果系统提示“App 已损坏,无法打开”,请打开终端(Terminal)并执行以下命令:
|
||||
|
||||
```bash
|
||||
sudo xattr -cr /Applications/ashell.app
|
||||
@@ -43,6 +63,7 @@ sudo xattr -cr /Applications/ashell.app
|
||||
- **系统遥测**:在左侧边栏实时可视化显示 CPU、内存、Swap、网络和磁盘的使用指标。
|
||||
- **主题系统**:支持直接从顶部工具栏切换多种 GPUI Component 颜色主题。
|
||||
- **内置字体**:开箱即用,内置 Maple Mono NF CN 字体,提供卓越的中日韩(CJK)字符与 Nerd Font 图标支持。
|
||||
- **v0.3 核心增强**:全局字体与字号可调,支持 SFTP 并发传输、布局记忆、断线感知、多语言热切换,以及终端右键复制粘贴等增强能力。
|
||||
|
||||
## 运行
|
||||
|
||||
|
||||
+68
-3
@@ -67,7 +67,6 @@ terminal_font_size: "Terminal Font Size"
|
||||
system_default: "System Default"
|
||||
ui_font_family: "UI Font"
|
||||
terminal_font_family: "Terminal Font"
|
||||
theme_management_hint: "Theme mode and light/dark theme families are managed from the top-bar theme button."
|
||||
monitoring_position: "Monitoring Position"
|
||||
position_bottom: "Bottom"
|
||||
position_sidebar: "Sidebar"
|
||||
@@ -95,7 +94,7 @@ n_folders: "%{folders} folders"
|
||||
n_files_and_folders: "%{files} files and %{folders} folders"
|
||||
reset: "Reset"
|
||||
reset_layout: "Reset Default Layout"
|
||||
reset_layout_success: "Layout reset. Window size takes effect on restart."
|
||||
reset_layout_hint: "Reset panel layout proportion. Window size will take effect on next startup."
|
||||
|
||||
transfers: "Transfers"
|
||||
no_transfers_yet: "No transfers yet"
|
||||
@@ -104,14 +103,80 @@ paused: "Paused"
|
||||
completed: "Completed"
|
||||
failed: "Failed"
|
||||
cancelled: "Cancelled"
|
||||
interrupted: "Interrupted"
|
||||
session: "Session"
|
||||
zombie: "Zombie"
|
||||
zombie_reason: "This transfer was interrupted because the application exited. The transfer task no longer exists."
|
||||
|
||||
software_builtin: "Built-in"
|
||||
retry: "Retry"
|
||||
right_click_copy_paste: "Right-click Copy/Paste"
|
||||
copy_paste_hint: "Tip: Regardless of this switch, you can always use %{key} + C/V to copy/paste."
|
||||
copy_paste_hint: "Regardless of this switch, you can always use %{key} + C/V to copy/paste."
|
||||
edit_file: "Edit File"
|
||||
edit_file_tooltip: "Download to temporary directory, open in default editor, and auto upload on save."
|
||||
auto_saved_and_uploaded: "Auto-saved & uploaded: %{base}"
|
||||
scroll: "Scroll ↓"
|
||||
clone: "Clone"
|
||||
settings_general: "General"
|
||||
settings_key_bindings: "Key Bindings"
|
||||
settings_help: "Help"
|
||||
settings_about: "About"
|
||||
settings_group_appearance: "Appearance"
|
||||
settings_group_font: "Font"
|
||||
settings_group_other: "Other"
|
||||
settings_group_keybind_general: "General"
|
||||
settings_group_keybind_zoom: "Zoom"
|
||||
settings_group_keybind_focus: "Focus"
|
||||
settings_group_keybind_panel: "Panel"
|
||||
theme: "Theme"
|
||||
theme_mode: "Theme Mode"
|
||||
clear_transfers: "Clear History"
|
||||
transfers_limit: " (Max 100 records)"
|
||||
|
||||
press_new_key: "Press new key..."
|
||||
settings_open_settings: "Open Settings"
|
||||
settings_open_session: "Open Session"
|
||||
settings_open_transfers: "Open Transfer History"
|
||||
files_downloading: "%{count} files downloading"
|
||||
files_uploading: "%{count} files uploading"
|
||||
panel_minimize: "Minimize Panel"
|
||||
panel_expand: "Expand Panel"
|
||||
settings_new_ssh: "New SSH"
|
||||
settings_toggle_sidebar: "Toggle Sidebar"
|
||||
settings_toggle_sftp_zoom: "Toggle SFTP Zoom"
|
||||
settings_focus_pane_left: "Focus Pane Left"
|
||||
settings_focus_pane_right: "Focus Pane Right"
|
||||
settings_focus_pane_up: "Focus Pane Up"
|
||||
settings_focus_pane_down: "Focus Pane Down"
|
||||
settings_split_pane_left: "Split Pane Left"
|
||||
settings_split_pane_right: "Split Pane Right"
|
||||
settings_split_pane_up: "Split Pane Up"
|
||||
settings_split_pane_down: "Split Pane Down"
|
||||
settings_close_pane: "Close Pane"
|
||||
keybind_conflict: '"%{key}" is already used by "%{action}", please choose another key'
|
||||
title_bar_style: "Title Bar Style"
|
||||
title_bar_native: "Native"
|
||||
title_bar_integrated: "Integrated"
|
||||
restart_hint: " (Restart required)"
|
||||
settings_sync: "Configuration Sync"
|
||||
sync_endpoint: "WebDAV Endpoint"
|
||||
sync_username: "WebDAV Username"
|
||||
sync_webdav_password: "WebDAV Password"
|
||||
sync_encryption_password: "Encryption Password (8+ characters)"
|
||||
sync_security_hint: "Only connection parameters are stored locally. WebDAV passwords, S3 secrets, and encryption passwords remain in memory for this process. Uploaded data is end-to-end encrypted. Downloading replaces locally saved SSH sessions."
|
||||
sync_s3_endpoint: "S3 Endpoint (optional for AWS S3)"
|
||||
sync_s3_region: "S3 Region"
|
||||
sync_s3_bucket: "S3 Bucket"
|
||||
sync_s3_object_key: "Object Key"
|
||||
sync_s3_access_key: "Access Key ID"
|
||||
sync_s3_secret_key: "Secret Access Key"
|
||||
sync_s3_session_token: "Session Token (optional)"
|
||||
sync_download: "Download Remote"
|
||||
sync_upload: "Upload Remote"
|
||||
sync_not_run: "Not synchronized yet"
|
||||
sync_uploading: "Encrypting and uploading configuration..."
|
||||
sync_downloading: "Downloading and decrypting configuration..."
|
||||
sync_upload_complete: "Configuration uploaded"
|
||||
sync_download_complete: "Configuration downloaded"
|
||||
sync_failed: "Synchronization failed"
|
||||
keyboard_interactive: "Keyboard Interactive"
|
||||
|
||||
+69
-4
@@ -23,7 +23,6 @@ system_path_warning: "警告:您即将删除系统关键路径!这可能会
|
||||
delete_success: "成功删除 %{count} 个项"
|
||||
delete_failed: "删除失败: %{err}"
|
||||
deleting_paths: "正在删除 %{count} 个项..."
|
||||
cancel: "取消"
|
||||
confirm: "确认"
|
||||
local_terminal: "本地终端"
|
||||
open_local_shell_tab: "打开一个新的本地终端页面"
|
||||
@@ -69,7 +68,6 @@ terminal_font_size: "终端字体大小"
|
||||
system_default: "系统默认"
|
||||
ui_font_family: "界面字体"
|
||||
terminal_font_family: "终端字体"
|
||||
theme_management_hint: "深色/浅色模式以及主题配色由顶部栏的样式按钮统一管理。"
|
||||
monitoring_position: "系统监控显示位置"
|
||||
position_bottom: "底部"
|
||||
position_sidebar: "侧边栏"
|
||||
@@ -97,7 +95,7 @@ n_folders: "%{folders} 个文件夹"
|
||||
n_files_and_folders: "%{files} 个文件及 %{folders} 个文件夹"
|
||||
reset: "重置"
|
||||
reset_layout: "恢复默认布局"
|
||||
reset_layout_success: "布局占比已恢复默认。窗口大小将在下次启动时生效。"
|
||||
reset_layout_hint: "重置面板布局占比,窗口大小将在下次启动时生效"
|
||||
|
||||
transfers: "传输记录"
|
||||
no_transfers_yet: "暂无传输记录"
|
||||
@@ -106,14 +104,81 @@ paused: "已暂停"
|
||||
completed: "已完成"
|
||||
failed: "失败"
|
||||
cancelled: "已取消"
|
||||
interrupted: "已中断"
|
||||
session: "会话"
|
||||
zombie: "僵尸任务"
|
||||
zombie_reason: "此传输任务因程序退出而中断,传输进程已不存在。"
|
||||
|
||||
software_builtin: "软件内置"
|
||||
retry: "重试"
|
||||
right_click_copy_paste: "右键复制/粘贴"
|
||||
copy_paste_hint: "提示:不管是否开启此开关,都可以使用 %{key} + C/V 快捷键进行复制和粘贴。"
|
||||
copy_paste_hint: "不管是否开启此开关,都可以使用 %{key} + C/V 快捷键进行复制和粘贴。"
|
||||
edit_file: "编辑文件"
|
||||
edit_file_tooltip: "下载到临时目录,使用默认编辑器打开,并在保存后自动上传。"
|
||||
auto_saved_and_uploaded: "已自动保存并上传: %{base}"
|
||||
scroll: "滑动查看 ↓"
|
||||
clone: "克隆"
|
||||
about_feedback_hint: "如果遇到问题或者有什么建议,请前往我们的 GitHub 项目中反馈。"
|
||||
settings_general: "常规"
|
||||
settings_key_bindings: "快捷键"
|
||||
settings_help: "帮助"
|
||||
settings_about: "关于"
|
||||
settings_group_appearance: "外观"
|
||||
settings_group_font: "字体"
|
||||
settings_group_other: "其它"
|
||||
settings_group_keybind_general: "常规"
|
||||
settings_group_keybind_zoom: "缩放"
|
||||
settings_group_keybind_focus: "焦点"
|
||||
settings_group_keybind_panel: "面板"
|
||||
theme: "主题"
|
||||
theme_mode: "主题模式"
|
||||
clear_transfers: "清空记录"
|
||||
transfers_limit: " (最多保留 100 条)"
|
||||
|
||||
press_new_key: "请按下新的快捷键..."
|
||||
settings_open_settings: "打开设置"
|
||||
settings_open_session: "打开会话"
|
||||
settings_open_transfers: "打开传输历史"
|
||||
files_downloading: "%{count} 个文件正在下载"
|
||||
files_uploading: "%{count} 个文件正在上传"
|
||||
panel_minimize: "折叠面板"
|
||||
panel_expand: "展开面板"
|
||||
settings_new_ssh: "新建 SSH"
|
||||
settings_toggle_sidebar: "缩放侧边栏"
|
||||
settings_toggle_sftp_zoom: "缩放 SFTP 面板"
|
||||
settings_focus_pane_left: "向左切换焦点"
|
||||
settings_focus_pane_right: "向右切换焦点"
|
||||
settings_focus_pane_up: "向上切换焦点"
|
||||
settings_focus_pane_down: "向下切换焦点"
|
||||
settings_split_pane_left: "向左拆分面板"
|
||||
settings_split_pane_right: "向右拆分面板"
|
||||
settings_split_pane_up: "向上拆分面板"
|
||||
settings_split_pane_down: "向下拆分面板"
|
||||
settings_close_pane: "关闭当前面板"
|
||||
keybind_conflict: '"%{key}" 已被「%{action}」使用,请选择其他快捷键'
|
||||
title_bar_style: "标题栏样式"
|
||||
title_bar_native: "原生"
|
||||
title_bar_integrated: "融合"
|
||||
restart_hint: " (修改后重启生效)"
|
||||
settings_sync: "配置同步"
|
||||
sync_endpoint: "WebDAV 地址"
|
||||
sync_username: "WebDAV 用户名"
|
||||
sync_webdav_password: "WebDAV 密码"
|
||||
sync_encryption_password: "配置加密口令(至少 8 位)"
|
||||
sync_security_hint: "仅连接参数会保存到本机。WebDAV 密码、S3 密钥和加密口令只保留在当前进程内;上传内容使用端到端加密。下载会替换本机保存的 SSH 会话。"
|
||||
sync_s3_endpoint: "S3 Endpoint(AWS S3 可留空)"
|
||||
sync_s3_region: "S3 Region"
|
||||
sync_s3_bucket: "S3 Bucket"
|
||||
sync_s3_object_key: "对象路径"
|
||||
sync_s3_access_key: "Access Key ID"
|
||||
sync_s3_secret_key: "Secret Access Key"
|
||||
sync_s3_session_token: "Session Token(可选)"
|
||||
sync_download: "从远程下载"
|
||||
sync_upload: "上传到远程"
|
||||
sync_not_run: "尚未同步"
|
||||
sync_uploading: "正在加密并上传配置..."
|
||||
sync_downloading: "正在下载并解密配置..."
|
||||
sync_upload_complete: "配置上传完成"
|
||||
sync_download_complete: "配置下载完成"
|
||||
sync_failed: "同步失败"
|
||||
keyboard_interactive: "键盘交互"
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
use gpui::{Context, Entity, SharedString};
|
||||
use gpui_component::input::InputState;
|
||||
use rust_i18n::t;
|
||||
|
||||
use crate::{
|
||||
Ashell,
|
||||
sync::{self, SyncBackendCredentials, SyncCredentials, SyncPayload, SyncResult},
|
||||
terminal::BackendEvent,
|
||||
};
|
||||
|
||||
impl Ashell {
|
||||
fn sync_input_value(input: &Entity<InputState>, cx: &Context<Self>) -> String {
|
||||
input.read(cx).value().trim().to_string()
|
||||
}
|
||||
|
||||
fn sync_credentials(&self, cx: &Context<Self>) -> SyncCredentials {
|
||||
let backend = if self.config.sync_backend() == "s3" {
|
||||
SyncBackendCredentials::S3 {
|
||||
endpoint: Self::sync_input_value(&self.sync_s3_endpoint_input, cx),
|
||||
region: Self::sync_input_value(&self.sync_s3_region_input, cx),
|
||||
bucket: Self::sync_input_value(&self.sync_s3_bucket_input, cx),
|
||||
object_key: Self::sync_input_value(&self.sync_s3_object_key_input, cx),
|
||||
access_key: Self::sync_input_value(&self.sync_s3_access_key_input, cx),
|
||||
secret_key: self.sync_s3_secret_key_input.read(cx).value().to_string(),
|
||||
session_token: self
|
||||
.sync_s3_session_token_input
|
||||
.read(cx)
|
||||
.value()
|
||||
.to_string(),
|
||||
}
|
||||
} else {
|
||||
SyncBackendCredentials::WebDav {
|
||||
endpoint: Self::sync_input_value(&self.sync_endpoint_input, cx),
|
||||
username: Self::sync_input_value(&self.sync_username_input, cx),
|
||||
password: self.sync_webdav_password_input.read(cx).value().to_string(),
|
||||
}
|
||||
};
|
||||
SyncCredentials {
|
||||
backend,
|
||||
encryption_password: self
|
||||
.sync_encryption_password_input
|
||||
.read(cx)
|
||||
.value()
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_sync(
|
||||
&mut self,
|
||||
status: SharedString,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<SyncCredentials> {
|
||||
if self.sync_in_progress {
|
||||
return None;
|
||||
}
|
||||
let credentials = self.sync_credentials(cx);
|
||||
match &credentials.backend {
|
||||
SyncBackendCredentials::WebDav {
|
||||
endpoint, username, ..
|
||||
} => {
|
||||
self.config
|
||||
.set_sync_connection(endpoint.clone(), username.clone());
|
||||
}
|
||||
SyncBackendCredentials::S3 {
|
||||
endpoint,
|
||||
region,
|
||||
bucket,
|
||||
object_key,
|
||||
..
|
||||
} => {
|
||||
self.config.set_sync_s3_connection(
|
||||
endpoint.clone(),
|
||||
region.clone(),
|
||||
bucket.clone(),
|
||||
object_key.clone(),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Err(err) = self.config.save() {
|
||||
self.sync_status = format!("{}: {err:#}", t!("sync_failed")).into();
|
||||
cx.notify();
|
||||
return None;
|
||||
}
|
||||
self.sync_in_progress = true;
|
||||
self.sync_status = status;
|
||||
cx.notify();
|
||||
Some(credentials)
|
||||
}
|
||||
|
||||
pub(crate) fn set_sync_backend(&mut self, backend: &str, cx: &mut Context<Self>) {
|
||||
self.config.set_sync_backend(backend);
|
||||
let _ = self.config.save();
|
||||
self.sync_status = t!("sync_not_run").into();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(crate) fn upload_sync_config(&mut self, cx: &mut Context<Self>) {
|
||||
let Some(credentials) = self.begin_sync(t!("sync_uploading").into(), cx) else {
|
||||
return;
|
||||
};
|
||||
let payload = SyncPayload::new(
|
||||
self.config.sync_device_id().to_string(),
|
||||
self.config.sessions().to_vec(),
|
||||
);
|
||||
let expected_etag = self.config.sync_etag().map(str::to_string);
|
||||
let events = self.events_tx.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = match sync::upload(credentials, payload, expected_etag).await {
|
||||
Ok(etag) => SyncResult::Uploaded { etag },
|
||||
Err(err) => SyncResult::Failed(format!("{err:#}")),
|
||||
};
|
||||
let _ = events.send(BackendEvent::SyncFinished(result));
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn download_sync_config(&mut self, cx: &mut Context<Self>) {
|
||||
let Some(credentials) = self.begin_sync(t!("sync_downloading").into(), cx) else {
|
||||
return;
|
||||
};
|
||||
let events = self.events_tx.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = match sync::download(credentials).await {
|
||||
Ok((payload, etag)) => SyncResult::Downloaded { payload, etag },
|
||||
Err(err) => SyncResult::Failed(format!("{err:#}")),
|
||||
};
|
||||
let _ = events.send(BackendEvent::SyncFinished(result));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub(crate) const DEFAULT_COLS: u16 = 100;
|
||||
pub(crate) const DEFAULT_ROWS: u16 = 30;
|
||||
pub(crate) const SIDEBAR_WIDTH: f32 = 306.0;
|
||||
pub(crate) const COLLAPSED_SIDEBAR_WIDTH: f32 = 52.0;
|
||||
pub(crate) const TAB_BAR_HEIGHT: f32 = 52.0;
|
||||
pub(crate) const TERMINAL_PADDING_X: f32 = 32.0;
|
||||
pub(crate) const TERMINAL_PADDING_Y: f32 = 32.0;
|
||||
|
||||
+1254
-689
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,391 @@
|
||||
use gpui::{
|
||||
Action as _, App, Entity, IntoElement, KeyBinding, KeyDownEvent, Keystroke, Unbind, prelude::*,
|
||||
};
|
||||
use gpui_component::{
|
||||
Sizable,
|
||||
button::{Button, ButtonVariants},
|
||||
kbd::Kbd,
|
||||
setting::{SettingField, SettingGroup, SettingItem},
|
||||
};
|
||||
use rust_i18n::t;
|
||||
|
||||
use crate::{Ashell, session::config::ConfigStore};
|
||||
|
||||
gpui::actions!(
|
||||
ashell_workspace,
|
||||
[
|
||||
OpenSettings,
|
||||
OpenSession,
|
||||
OpenTransfers,
|
||||
NewSsh,
|
||||
ToggleSidebar,
|
||||
ToggleSftpZoom,
|
||||
FocusPaneLeft,
|
||||
FocusPaneRight,
|
||||
FocusPaneUp,
|
||||
FocusPaneDown,
|
||||
SplitPaneLeft,
|
||||
SplitPaneRight,
|
||||
SplitPaneUp,
|
||||
SplitPaneDown,
|
||||
ClosePane
|
||||
]
|
||||
);
|
||||
|
||||
pub struct KeybindingsPage;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct WorkspaceAction {
|
||||
id: &'static str,
|
||||
label_key: &'static str,
|
||||
default_suffix: &'static str,
|
||||
}
|
||||
|
||||
pub(crate) const WORKSPACE_ACTIONS: &[WorkspaceAction] = &[
|
||||
WorkspaceAction {
|
||||
id: "OpenSettings",
|
||||
label_key: "settings_open_settings",
|
||||
default_suffix: ",",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "OpenSession",
|
||||
label_key: "settings_open_session",
|
||||
default_suffix: "o",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "OpenTransfers",
|
||||
label_key: "settings_open_transfers",
|
||||
default_suffix: "t",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "NewSsh",
|
||||
label_key: "settings_new_ssh",
|
||||
default_suffix: "n",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "ToggleSidebar",
|
||||
label_key: "settings_toggle_sidebar",
|
||||
default_suffix: "s",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "ToggleSftpZoom",
|
||||
label_key: "settings_toggle_sftp_zoom",
|
||||
default_suffix: "m",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "FocusPaneLeft",
|
||||
label_key: "settings_focus_pane_left",
|
||||
default_suffix: "h",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "FocusPaneRight",
|
||||
label_key: "settings_focus_pane_right",
|
||||
default_suffix: "l",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "FocusPaneUp",
|
||||
label_key: "settings_focus_pane_up",
|
||||
default_suffix: "k",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "FocusPaneDown",
|
||||
label_key: "settings_focus_pane_down",
|
||||
default_suffix: "j",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "SplitPaneLeft",
|
||||
label_key: "settings_split_pane_left",
|
||||
default_suffix: "shift-h",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "SplitPaneRight",
|
||||
label_key: "settings_split_pane_right",
|
||||
default_suffix: "shift-l",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "SplitPaneUp",
|
||||
label_key: "settings_split_pane_up",
|
||||
default_suffix: "shift-k",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "SplitPaneDown",
|
||||
label_key: "settings_split_pane_down",
|
||||
default_suffix: "shift-j",
|
||||
},
|
||||
WorkspaceAction {
|
||||
id: "ClosePane",
|
||||
label_key: "settings_close_pane",
|
||||
default_suffix: "w",
|
||||
},
|
||||
];
|
||||
|
||||
pub(crate) fn default_modifier() -> &'static str {
|
||||
if cfg!(target_os = "macos") {
|
||||
"cmd"
|
||||
} else {
|
||||
"ctrl"
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn default_keystroke(action_id: &str) -> Option<String> {
|
||||
WORKSPACE_ACTIONS
|
||||
.iter()
|
||||
.find(|action| action.id == action_id)
|
||||
.map(|action| format!("{}-{}", default_modifier(), action.default_suffix))
|
||||
}
|
||||
|
||||
pub(crate) fn configured_keystroke(config: &ConfigStore, action_id: &str) -> Option<String> {
|
||||
config
|
||||
.key_bindings()
|
||||
.get(action_id)
|
||||
.cloned()
|
||||
.or_else(|| default_keystroke(action_id))
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_recorded_keystroke(event: &KeyDownEvent) -> Option<String> {
|
||||
let key = event.keystroke.key.trim();
|
||||
if key.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut parts = Vec::new();
|
||||
if event.keystroke.modifiers.control {
|
||||
parts.push("ctrl".to_string());
|
||||
}
|
||||
if event.keystroke.modifiers.alt {
|
||||
parts.push("alt".to_string());
|
||||
}
|
||||
if event.keystroke.modifiers.shift {
|
||||
parts.push("shift".to_string());
|
||||
}
|
||||
if event.keystroke.modifiers.platform {
|
||||
parts.push("cmd".to_string());
|
||||
}
|
||||
if event.keystroke.modifiers.function {
|
||||
parts.push("fn".to_string());
|
||||
}
|
||||
|
||||
parts.push(key.to_ascii_lowercase());
|
||||
let keystroke = parts.join("-");
|
||||
Keystroke::parse(&keystroke).ok().map(|_| keystroke)
|
||||
}
|
||||
|
||||
pub(crate) fn format_keystroke(keystroke: &str) -> String {
|
||||
Keystroke::parse(keystroke)
|
||||
.map(|stroke| Kbd::format(&stroke))
|
||||
.unwrap_or_else(|_| keystroke.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn bind_workspace_keys_from_config(cx: &mut App, config: &ConfigStore) {
|
||||
bind_workspace_actions(cx, config);
|
||||
}
|
||||
|
||||
/// Unbind all workspace keybindings (used when entering keybinding settings to prevent interference).
|
||||
pub(crate) fn unbind_all_workspace_keys(cx: &mut App, config: &ConfigStore) {
|
||||
let mut bindings = Vec::new();
|
||||
|
||||
macro_rules! unbind_action {
|
||||
($id:literal, $action:expr) => {
|
||||
let default = default_keystroke($id).expect("workspace action has default key");
|
||||
let configured = configured_keystroke(config, $id).unwrap_or_else(|| default.clone());
|
||||
let action_name = $action.name();
|
||||
|
||||
// Unbind both the default and configured keystroke
|
||||
bindings.push(KeyBinding::new(&default, Unbind(action_name.into()), None));
|
||||
if configured != default {
|
||||
bindings.push(KeyBinding::new(
|
||||
&configured,
|
||||
Unbind(action_name.into()),
|
||||
None,
|
||||
));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
unbind_action!("OpenSettings", crate::OpenSettings);
|
||||
unbind_action!("OpenSession", crate::OpenSession);
|
||||
unbind_action!("OpenTransfers", crate::OpenTransfers);
|
||||
unbind_action!("NewSsh", crate::NewSsh);
|
||||
unbind_action!("ToggleSidebar", crate::ToggleSidebar);
|
||||
unbind_action!("ToggleSftpZoom", crate::ToggleSftpZoom);
|
||||
unbind_action!("FocusPaneLeft", crate::FocusPaneLeft);
|
||||
unbind_action!("FocusPaneRight", crate::FocusPaneRight);
|
||||
unbind_action!("FocusPaneUp", crate::FocusPaneUp);
|
||||
unbind_action!("FocusPaneDown", crate::FocusPaneDown);
|
||||
unbind_action!("SplitPaneLeft", crate::SplitPaneLeft);
|
||||
unbind_action!("SplitPaneRight", crate::SplitPaneRight);
|
||||
unbind_action!("SplitPaneUp", crate::SplitPaneUp);
|
||||
unbind_action!("SplitPaneDown", crate::SplitPaneDown);
|
||||
unbind_action!("ClosePane", crate::ClosePane);
|
||||
|
||||
cx.bind_keys(bindings);
|
||||
}
|
||||
|
||||
/// Check if a keystroke conflicts with any other action's binding.
|
||||
/// Returns Some((conflicting_action_id, label)) if there is a conflict.
|
||||
pub(crate) fn find_conflict(
|
||||
config: &ConfigStore,
|
||||
current_action_id: &str,
|
||||
new_keystroke: &str,
|
||||
) -> Option<(String, String)> {
|
||||
for action in WORKSPACE_ACTIONS {
|
||||
if action.id == current_action_id {
|
||||
continue;
|
||||
}
|
||||
let existing = configured_keystroke(config, action.id).unwrap_or_default();
|
||||
if !existing.is_empty() && existing == new_keystroke {
|
||||
return Some((action.id.to_string(), t!(action.label_key).to_string()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn bind_workspace_actions(cx: &mut App, config: &ConfigStore) {
|
||||
let mut bindings = Vec::new();
|
||||
|
||||
macro_rules! bind_action {
|
||||
($id:literal, $action:expr) => {
|
||||
let default = default_keystroke($id).expect("workspace action has default key");
|
||||
let configured = configured_keystroke(config, $id).unwrap_or_else(|| default.clone());
|
||||
let action_name = $action.name();
|
||||
|
||||
if configured != default {
|
||||
bindings.push(KeyBinding::new(&default, Unbind(action_name.into()), None));
|
||||
}
|
||||
|
||||
bindings.push(KeyBinding::new(&configured, $action, None));
|
||||
};
|
||||
}
|
||||
|
||||
bind_action!("OpenSettings", crate::OpenSettings);
|
||||
bind_action!("OpenSession", crate::OpenSession);
|
||||
bind_action!("OpenTransfers", crate::OpenTransfers);
|
||||
bind_action!("NewSsh", crate::NewSsh);
|
||||
bind_action!("ToggleSidebar", crate::ToggleSidebar);
|
||||
bind_action!("ToggleSftpZoom", crate::ToggleSftpZoom);
|
||||
bind_action!("FocusPaneLeft", crate::FocusPaneLeft);
|
||||
bind_action!("FocusPaneRight", crate::FocusPaneRight);
|
||||
bind_action!("FocusPaneUp", crate::FocusPaneUp);
|
||||
bind_action!("FocusPaneDown", crate::FocusPaneDown);
|
||||
bind_action!("SplitPaneLeft", crate::SplitPaneLeft);
|
||||
bind_action!("SplitPaneRight", crate::SplitPaneRight);
|
||||
bind_action!("SplitPaneUp", crate::SplitPaneUp);
|
||||
bind_action!("SplitPaneDown", crate::SplitPaneDown);
|
||||
bind_action!("ClosePane", crate::ClosePane);
|
||||
|
||||
cx.bind_keys(bindings);
|
||||
}
|
||||
|
||||
impl KeybindingsPage {
|
||||
pub fn render_groups(view: &Entity<Ashell>, cx: &mut App) -> Vec<SettingGroup> {
|
||||
let groups = [
|
||||
(
|
||||
"settings_group_keybind_general",
|
||||
vec!["OpenSettings", "OpenSession", "OpenTransfers", "NewSsh"],
|
||||
),
|
||||
(
|
||||
"settings_group_keybind_zoom",
|
||||
vec!["ToggleSidebar", "ToggleSftpZoom"],
|
||||
),
|
||||
(
|
||||
"settings_group_keybind_focus",
|
||||
vec![
|
||||
"FocusPaneLeft",
|
||||
"FocusPaneRight",
|
||||
"FocusPaneUp",
|
||||
"FocusPaneDown",
|
||||
],
|
||||
),
|
||||
(
|
||||
"settings_group_keybind_panel",
|
||||
vec![
|
||||
"SplitPaneLeft",
|
||||
"SplitPaneRight",
|
||||
"SplitPaneUp",
|
||||
"SplitPaneDown",
|
||||
"ClosePane",
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
let mut result = Vec::new();
|
||||
|
||||
for (group_label, action_ids) in groups {
|
||||
let mut group = SettingGroup::new().title(t!(group_label).to_string());
|
||||
|
||||
for action_id in action_ids {
|
||||
let action = WORKSPACE_ACTIONS
|
||||
.iter()
|
||||
.find(|a| a.id == action_id)
|
||||
.expect("action exists");
|
||||
|
||||
let recording = view.read(cx).recording_action.as_deref() == Some(action.id);
|
||||
let has_error = view
|
||||
.read(cx)
|
||||
.keybind_error
|
||||
.as_ref()
|
||||
.is_some_and(|(id, _)| id == action.id);
|
||||
let error_msg = if has_error {
|
||||
view.read(cx)
|
||||
.keybind_error
|
||||
.as_ref()
|
||||
.map(|(_, msg)| msg.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let keystroke = {
|
||||
let config = &view.read(cx).config;
|
||||
configured_keystroke(config, action.id).unwrap_or_default()
|
||||
};
|
||||
|
||||
let btn_label = if recording {
|
||||
t!("press_new_key").to_string()
|
||||
} else if keystroke.is_empty() {
|
||||
t!("none").to_string()
|
||||
} else {
|
||||
format_keystroke(&keystroke)
|
||||
};
|
||||
|
||||
let mut item = SettingItem::new(
|
||||
t!(action.label_key).to_string(),
|
||||
SettingField::render({
|
||||
let view = view.clone();
|
||||
let action_id = action.id.to_string();
|
||||
move |_, _window, _cx| {
|
||||
Button::new(gpui::SharedString::from(format!("keybind-{action_id}")))
|
||||
.label(btn_label.clone())
|
||||
.small()
|
||||
.when(recording, |this| this.primary())
|
||||
.when(has_error, |this| this.danger())
|
||||
.on_click({
|
||||
let view = view.clone();
|
||||
let action_id = action_id.clone();
|
||||
move |_event, window, cx| {
|
||||
view.update(cx, |this, cx| {
|
||||
// Clear any previous error when starting new recording
|
||||
this.keybind_error = None;
|
||||
this.recording_action = Some(action_id.clone());
|
||||
this.focus_handle.focus(window, cx);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if let Some(msg) = error_msg {
|
||||
item = item.description(msg);
|
||||
}
|
||||
|
||||
group = group.item(item);
|
||||
}
|
||||
|
||||
result.push(group);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
+279
-72
@@ -1,5 +1,7 @@
|
||||
pub mod config_sync;
|
||||
pub mod constants;
|
||||
pub mod dialogs;
|
||||
pub mod keybinding_recorder;
|
||||
pub mod startup;
|
||||
pub mod theme;
|
||||
pub mod ui;
|
||||
@@ -14,9 +16,8 @@ use std::{
|
||||
};
|
||||
|
||||
use gpui::{
|
||||
AppContext as _, Bounds, Context, Entity, FocusHandle, Pixels, Point,
|
||||
SharedString, Size, UniformListScrollHandle, Window, point,
|
||||
px, size,
|
||||
AppContext as _, Bounds, Context, Entity, FocusHandle, Pixels, Point, SharedString, Size,
|
||||
UniformListScrollHandle, Window, point, px, size,
|
||||
};
|
||||
use gpui_component::{
|
||||
Theme, ThemeMode, ThemeRegistry,
|
||||
@@ -31,7 +32,6 @@ use crate::{
|
||||
session::config::{AuthMethod, ConfigStore},
|
||||
system::{SystemSampler, SystemSnapshot},
|
||||
terminal::{self, BackendEvent, TabKind, TerminalTab},
|
||||
backend::ssh,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -82,7 +82,10 @@ impl PaneLayout {
|
||||
pub fn replace_at(&mut self, path: &[usize], replacement: PaneLayout) {
|
||||
match (self, path) {
|
||||
(this @ PaneLayout::Single(_), []) => *this = replacement,
|
||||
(PaneLayout::Horizontal(children, _) | PaneLayout::Vertical(children, _), [first, rest @ ..]) => {
|
||||
(
|
||||
PaneLayout::Horizontal(children, _) | PaneLayout::Vertical(children, _),
|
||||
[first, rest @ ..],
|
||||
) => {
|
||||
if let Some(child) = children.get_mut(*first) {
|
||||
child.replace_at(rest, replacement);
|
||||
}
|
||||
@@ -187,7 +190,14 @@ impl ScrollbarHandle for TerminalScrollbarHandle {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum DialogKind {
|
||||
Settings,
|
||||
SessionSelector,
|
||||
Transfers,
|
||||
NewSsh,
|
||||
PromptRequest,
|
||||
}
|
||||
|
||||
pub(crate) struct Ashell {
|
||||
pub(crate) focus_handle: FocusHandle,
|
||||
@@ -199,6 +209,20 @@ pub(crate) struct Ashell {
|
||||
pub(crate) password_input: Entity<InputState>,
|
||||
pub(crate) key_path_input: Entity<InputState>,
|
||||
pub(crate) key_inline_input: Entity<InputState>,
|
||||
pub(crate) passphrase_input: Entity<InputState>,
|
||||
pub(crate) sync_endpoint_input: Entity<InputState>,
|
||||
pub(crate) sync_username_input: Entity<InputState>,
|
||||
pub(crate) sync_webdav_password_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_endpoint_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_region_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_bucket_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_object_key_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_access_key_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_secret_key_input: Entity<InputState>,
|
||||
pub(crate) sync_s3_session_token_input: Entity<InputState>,
|
||||
pub(crate) sync_encryption_password_input: Entity<InputState>,
|
||||
pub(crate) sync_in_progress: bool,
|
||||
pub(crate) sync_status: SharedString,
|
||||
pub(crate) sftp_path_input: Entity<InputState>,
|
||||
pub(crate) ssh_auth_method: AuthMethod,
|
||||
pub(crate) editing_session_id: Option<String>,
|
||||
@@ -217,6 +241,7 @@ pub(crate) struct Ashell {
|
||||
pub(crate) selector_selection: usize,
|
||||
pub(crate) workspace_panels: Entity<ResizableState>,
|
||||
pub(crate) body_panels: Entity<ResizableState>,
|
||||
pub(crate) is_layout_reset: bool,
|
||||
pub(crate) terminal_scrollbars: HashMap<String, TerminalScrollbarHandle>,
|
||||
pub(crate) remote_files_scroll_handle: UniformListScrollHandle,
|
||||
pub(crate) disk_scroll_handle: gpui::ScrollHandle,
|
||||
@@ -236,16 +261,26 @@ pub(crate) struct Ashell {
|
||||
pub(crate) system_status: Option<SharedString>,
|
||||
pub(crate) pane_root: PaneLayout,
|
||||
pub(crate) focused_pane_path: Vec<usize>,
|
||||
pub(crate) terminal_panel_bounds: Option<Bounds<Pixels>>,
|
||||
pub(crate) terminal_bounds: HashMap<String, Bounds<Pixels>>,
|
||||
pub(crate) terminal_selecting: bool,
|
||||
pub(crate) dragging_splitter: Option<(Vec<usize>, usize)>, // (parent_path, child_index)
|
||||
pub(crate) drag_split_origin: Option<gpui::Point<Pixels>>,
|
||||
pub(crate) terminal_marked_text: Option<String>,
|
||||
pub(crate) sftp_panel_minimized: bool,
|
||||
pub(crate) sidebar_collapsed: bool,
|
||||
pub(crate) collapsed_saved_scroll_handle: gpui::ScrollHandle,
|
||||
pub(crate) prev_monitoring_size: Option<Pixels>,
|
||||
pub(crate) status: SharedString,
|
||||
pub(crate) config: ConfigStore,
|
||||
pub(crate) active_title_bar_style: crate::session::config::TitleBarStyle,
|
||||
pub(crate) system_sampler: SystemSampler,
|
||||
pub(crate) recording_action: Option<String>,
|
||||
pub(crate) active_dialog: Option<DialogKind>,
|
||||
/// Error message when a recorded keybinding conflicts with another
|
||||
pub(crate) keybind_error: Option<(String, String)>, // (action_id, error_message)
|
||||
/// Whether workspace keybindings are currently suspended (during settings)
|
||||
pub(crate) keybinds_suspended: bool,
|
||||
pub(crate) system: SystemSnapshot,
|
||||
pub(crate) cpu_history: Vec<f32>,
|
||||
pub(crate) net_rx_history: Vec<f32>,
|
||||
@@ -255,7 +290,7 @@ pub(crate) struct Ashell {
|
||||
|
||||
pub(crate) system_tab_id: Option<String>,
|
||||
pub(crate) sftp_handles: std::collections::HashMap<String, crate::sftp::SftpHandle>,
|
||||
|
||||
|
||||
pub(crate) remote_sample_in_flight: bool,
|
||||
pub(crate) runtime: Runtime,
|
||||
pub(crate) events_rx: mpsc::Receiver<BackendEvent>,
|
||||
@@ -286,6 +321,26 @@ pub(crate) struct SftpContextMenuState {
|
||||
}
|
||||
|
||||
impl Ashell {
|
||||
fn transfer_source_title(&self, tab_id: &str) -> String {
|
||||
self.tabs
|
||||
.iter()
|
||||
.find(|tab| tab.id == tab_id)
|
||||
.map(|tab| tab.title.clone())
|
||||
.or_else(|| {
|
||||
self.tab_groups
|
||||
.iter()
|
||||
.find(|group| group.id == tab_id)
|
||||
.map(|group| group.title.clone())
|
||||
})
|
||||
.or_else(|| {
|
||||
self.tab_groups
|
||||
.iter()
|
||||
.find(|group| group.pane_root.contains(tab_id))
|
||||
.map(|group| group.title.clone())
|
||||
})
|
||||
.unwrap_or_else(|| "Unknown".to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let host_input = cx.new(|cx| InputState::new(window, cx).placeholder(t!("host")));
|
||||
let session_name_input =
|
||||
@@ -305,8 +360,71 @@ impl Ashell {
|
||||
.rows(5)
|
||||
.placeholder("-----BEGIN OPENSSH PRIVATE KEY-----")
|
||||
});
|
||||
let passphrase_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder("SSH private key passphrase (optional)")
|
||||
.masked(true)
|
||||
});
|
||||
let sftp_path_input = cx.new(|cx| InputState::new(window, cx).default_value("/"));
|
||||
let sftp_new_folder_input = cx.new(|cx| InputState::new(window, cx).placeholder(t!("new_folder").to_string()));
|
||||
let sftp_new_folder_input =
|
||||
cx.new(|cx| InputState::new(window, cx).placeholder(t!("new_folder").to_string()));
|
||||
let config = ConfigStore::load().unwrap_or_else(|err| {
|
||||
tracing::warn!("failed to load config: {err:#}");
|
||||
ConfigStore::in_memory()
|
||||
});
|
||||
let sync_endpoint_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder("https://dav.example.com/ashell/")
|
||||
.default_value(config.sync_endpoint())
|
||||
});
|
||||
let sync_username_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("sync_username").to_string())
|
||||
.default_value(config.sync_username())
|
||||
});
|
||||
let sync_webdav_password_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("sync_webdav_password").to_string())
|
||||
.masked(true)
|
||||
});
|
||||
let sync_s3_endpoint_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder("https://s3.example.com")
|
||||
.default_value(config.sync_s3_endpoint())
|
||||
});
|
||||
let sync_s3_region_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder("us-east-1")
|
||||
.default_value(config.sync_s3_region())
|
||||
});
|
||||
let sync_s3_bucket_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("sync_s3_bucket").to_string())
|
||||
.default_value(config.sync_s3_bucket())
|
||||
});
|
||||
let sync_s3_object_key_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder("ashell-sync.json")
|
||||
.default_value(config.sync_s3_object_key())
|
||||
});
|
||||
let sync_s3_access_key_input = cx.new(|cx| {
|
||||
InputState::new(window, cx).placeholder(t!("sync_s3_access_key").to_string())
|
||||
});
|
||||
let sync_s3_secret_key_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("sync_s3_secret_key").to_string())
|
||||
.masked(true)
|
||||
});
|
||||
let sync_s3_session_token_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("sync_s3_session_token").to_string())
|
||||
.masked(true)
|
||||
});
|
||||
let sync_encryption_password_input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("sync_encryption_password").to_string())
|
||||
.masked(true)
|
||||
});
|
||||
|
||||
let _subscriptions = vec![
|
||||
cx.subscribe_in(&host_input, window, Self::on_input_event),
|
||||
@@ -316,8 +434,24 @@ impl Ashell {
|
||||
cx.subscribe_in(&password_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&key_path_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&key_inline_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&passphrase_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sftp_path_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sftp_new_folder_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_endpoint_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_username_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_webdav_password_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_endpoint_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_region_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_bucket_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_object_key_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_access_key_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_secret_key_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(&sync_s3_session_token_input, window, Self::on_input_event),
|
||||
cx.subscribe_in(
|
||||
&sync_encryption_password_input,
|
||||
window,
|
||||
Self::on_input_event,
|
||||
),
|
||||
];
|
||||
|
||||
let (events_tx, events_rx) = mpsc::channel();
|
||||
@@ -327,16 +461,7 @@ impl Ashell {
|
||||
let system = system_sampler.sample();
|
||||
let default_light_theme_name = ThemeRegistry::global(cx).default_light_theme().name.clone();
|
||||
let default_dark_theme_name = ThemeRegistry::global(cx).default_dark_theme().name.clone();
|
||||
let config = ConfigStore::load().unwrap_or_else(|err| {
|
||||
tracing::warn!("failed to load config: {err:#}");
|
||||
ConfigStore::in_memory()
|
||||
});
|
||||
let follow_system_theme =
|
||||
if config.light_theme_name().is_empty() && config.dark_theme_name().is_empty() {
|
||||
true
|
||||
} else {
|
||||
config.follow_system_theme()
|
||||
};
|
||||
let follow_system_theme = config.follow_system_theme();
|
||||
|
||||
let theme_mode = match config.theme_mode() {
|
||||
"light" => ThemeMode::Light,
|
||||
@@ -378,6 +503,20 @@ impl Ashell {
|
||||
password_input,
|
||||
key_path_input,
|
||||
key_inline_input,
|
||||
passphrase_input,
|
||||
sync_endpoint_input,
|
||||
sync_username_input,
|
||||
sync_webdav_password_input,
|
||||
sync_s3_endpoint_input,
|
||||
sync_s3_region_input,
|
||||
sync_s3_bucket_input,
|
||||
sync_s3_object_key_input,
|
||||
sync_s3_access_key_input,
|
||||
sync_s3_secret_key_input,
|
||||
sync_s3_session_token_input,
|
||||
sync_encryption_password_input,
|
||||
sync_in_progress: false,
|
||||
sync_status: t!("sync_not_run").into(),
|
||||
sftp_path_input,
|
||||
ssh_auth_method: AuthMethod::Password,
|
||||
editing_session_id: None,
|
||||
@@ -395,9 +534,11 @@ impl Ashell {
|
||||
active_group: None,
|
||||
pane_root: PaneLayout::Single(String::new()),
|
||||
focused_pane_path: Vec::new(),
|
||||
terminal_panel_bounds: None,
|
||||
selector_selection: 0,
|
||||
workspace_panels,
|
||||
body_panels,
|
||||
is_layout_reset: false,
|
||||
terminal_scrollbars: HashMap::new(),
|
||||
remote_files_scroll_handle: UniformListScrollHandle::new(),
|
||||
disk_scroll_handle: gpui::ScrollHandle::new(),
|
||||
@@ -412,7 +553,20 @@ impl Ashell {
|
||||
sftp_new_folder_input,
|
||||
sftp_delete_scroll_handle: gpui::ScrollHandle::new(),
|
||||
show_hidden_files: config.show_hidden_files(),
|
||||
transfers: config.transfers(),
|
||||
transfers: {
|
||||
let mut transfers = config.transfers();
|
||||
for t in transfers.iter_mut() {
|
||||
if matches!(
|
||||
t.state,
|
||||
crate::terminal::TransferState::Running
|
||||
| crate::terminal::TransferState::Paused
|
||||
) {
|
||||
t.state =
|
||||
crate::terminal::TransferState::Zombie(t!("zombie_reason").to_string());
|
||||
}
|
||||
}
|
||||
transfers
|
||||
},
|
||||
show_transfers_dialog: false,
|
||||
system_status: None,
|
||||
terminal_bounds: HashMap::new(),
|
||||
@@ -420,11 +574,18 @@ impl Ashell {
|
||||
terminal_marked_text: None,
|
||||
dragging_splitter: None,
|
||||
drag_split_origin: None,
|
||||
sftp_panel_minimized: false,
|
||||
sftp_panel_minimized: config.sftp_panel_minimized(),
|
||||
sidebar_collapsed: config.sidebar_collapsed(),
|
||||
collapsed_saved_scroll_handle: gpui::ScrollHandle::new(),
|
||||
prev_monitoring_size: None,
|
||||
status: "ready".into(),
|
||||
active_title_bar_style: config.title_bar_style(),
|
||||
config,
|
||||
system_sampler,
|
||||
recording_action: None,
|
||||
active_dialog: None,
|
||||
keybind_error: None,
|
||||
keybinds_suspended: false,
|
||||
system,
|
||||
cpu_history: Vec::with_capacity(20),
|
||||
net_rx_history: Vec::with_capacity(20),
|
||||
@@ -434,7 +595,7 @@ impl Ashell {
|
||||
|
||||
system_tab_id: None,
|
||||
sftp_handles: std::collections::HashMap::new(),
|
||||
|
||||
|
||||
remote_sample_in_flight: false,
|
||||
runtime: Runtime::new().expect("create tokio runtime"),
|
||||
events_rx,
|
||||
@@ -444,7 +605,7 @@ impl Ashell {
|
||||
|
||||
this.apply_theme_preferences(window, cx);
|
||||
// this.open_local(cx);
|
||||
this.start_event_pump(cx);
|
||||
this.start_event_pump(window, cx);
|
||||
this
|
||||
}
|
||||
|
||||
@@ -476,7 +637,9 @@ impl Ashell {
|
||||
let base_path = self.sftp_path_input.read(cx).text().to_string();
|
||||
let path = crate::sftp::join_remote(&base_path, &name);
|
||||
if let Some(handle) = self.active_sftp_handle() {
|
||||
let _ = handle.commands.send(crate::sftp::SftpCommand::CreateDir(path));
|
||||
let _ = handle
|
||||
.commands
|
||||
.send(crate::sftp::SftpCommand::CreateDir(path));
|
||||
}
|
||||
}
|
||||
self.sftp_creating_folder = false;
|
||||
@@ -492,17 +655,19 @@ impl Ashell {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(crate) fn start_event_pump(&self, cx: &mut Context<Self>) {
|
||||
cx.spawn(async move |this, cx| {
|
||||
pub(crate) fn start_event_pump(&self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
cx.spawn_in(window, async move |this, mut cx| {
|
||||
let mut idle_frames = 0u32;
|
||||
loop {
|
||||
cx.background_executor()
|
||||
.timer(Duration::from_millis(16))
|
||||
.await;
|
||||
if this
|
||||
.update(cx, |this, cx| {
|
||||
let changed = this.drain_backend_events();
|
||||
let system_sampled = this.sample_system_if_due();
|
||||
let mut changed = false;
|
||||
let mut system_sampled = false;
|
||||
let update_res = gpui::AsyncWindowContext::update(&mut cx, |window, cx| {
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
changed = this.drain_backend_events(window, cx);
|
||||
system_sampled = this.sample_system_if_due();
|
||||
this.sync_theme_if_due(cx);
|
||||
if changed || system_sampled {
|
||||
cx.notify();
|
||||
@@ -514,9 +679,9 @@ impl Ashell {
|
||||
idle_frames = 0;
|
||||
}
|
||||
}
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
});
|
||||
});
|
||||
if update_res.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -524,7 +689,7 @@ impl Ashell {
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub(crate) fn drain_backend_events(&mut self) -> bool {
|
||||
pub(crate) fn drain_backend_events(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
|
||||
let mut changed = false;
|
||||
let mut transfers_changed = false;
|
||||
while let Ok(event) = self.events_rx.try_recv() {
|
||||
@@ -543,7 +708,8 @@ impl Ashell {
|
||||
if progress.tab_id == tab_id {
|
||||
progress.lines.push(text.clone().into());
|
||||
let _idx = progress.lines.len().saturating_sub(1);
|
||||
self.connection_scroll_handle.set_offset(point(px(0.), px(-99999.0)));
|
||||
self.connection_scroll_handle
|
||||
.set_offset(point(px(0.), px(-99999.0)));
|
||||
}
|
||||
}
|
||||
self.status = text.into();
|
||||
@@ -562,6 +728,21 @@ impl Ashell {
|
||||
self.connection_progress = None;
|
||||
}
|
||||
}
|
||||
BackendEvent::PromptRequest {
|
||||
tab_id,
|
||||
prompt_type,
|
||||
instruction,
|
||||
prompts,
|
||||
} => {
|
||||
self.show_interactive_prompt_dialog(
|
||||
tab_id,
|
||||
prompt_type,
|
||||
instruction,
|
||||
prompts,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
BackendEvent::SftpEntries {
|
||||
tab_id,
|
||||
path,
|
||||
@@ -634,8 +815,8 @@ impl Ashell {
|
||||
if self.system_tab_id.as_deref() == Some(tab_id.as_str()) {
|
||||
self.system_status = Some(reason.clone().into());
|
||||
}
|
||||
let is_graceful_exit = reason == "local shell closed"
|
||||
|| reason == "ssh session closed";
|
||||
let is_graceful_exit =
|
||||
reason == "local shell closed" || reason == "ssh session closed";
|
||||
// Auto-close the pane on graceful exit (e.g. user typed exit)
|
||||
if is_graceful_exit {
|
||||
self.handle_tab_close(tab_id.clone());
|
||||
@@ -648,7 +829,8 @@ impl Ashell {
|
||||
if progress.tab_id == tab_id {
|
||||
progress.lines.push(reason.clone().into());
|
||||
let _idx = progress.lines.len().saturating_sub(1);
|
||||
self.connection_scroll_handle.set_offset(point(px(0.), px(-99999.0)));
|
||||
self.connection_scroll_handle
|
||||
.set_offset(point(px(0.), px(-99999.0)));
|
||||
let _ = session_label;
|
||||
let _ = tab_title;
|
||||
progress.title = t!("connection_failed").into();
|
||||
@@ -659,14 +841,16 @@ impl Ashell {
|
||||
progress.tab_id = tab_id.clone();
|
||||
let msg = format!("{}: {}", tab_title.unwrap_or_default(), reason);
|
||||
progress.lines.push(msg.into());
|
||||
self.connection_scroll_handle.set_offset(point(px(0.), px(-99999.0)));
|
||||
self.connection_scroll_handle
|
||||
.set_offset(point(px(0.), px(-99999.0)));
|
||||
progress.title = t!("connection_failed").into();
|
||||
progress.failed = true;
|
||||
} else {
|
||||
// Already showing a failure dialog, just append the new failure
|
||||
let msg = format!("{}: {}", tab_title.unwrap_or_default(), reason);
|
||||
progress.lines.push(msg.into());
|
||||
self.connection_scroll_handle.set_offset(point(px(0.), px(-99999.0)));
|
||||
self.connection_scroll_handle
|
||||
.set_offset(point(px(0.), px(-99999.0)));
|
||||
}
|
||||
} else if let Some(_) = session_label {
|
||||
needs_new_progress = true;
|
||||
@@ -699,12 +883,7 @@ impl Ashell {
|
||||
}
|
||||
}
|
||||
BackendEvent::TransferStarted { tab_id, info } => {
|
||||
let tab_title = self
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|t| t.id == tab_id)
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_else(|| "Unknown".to_string());
|
||||
let tab_title = self.transfer_source_title(&tab_id);
|
||||
self.transfers.insert(
|
||||
0,
|
||||
crate::terminal::Transfer {
|
||||
@@ -716,6 +895,9 @@ impl Ashell {
|
||||
state: crate::terminal::TransferState::Running,
|
||||
},
|
||||
);
|
||||
if self.transfers.len() > 100 {
|
||||
self.transfers.truncate(100);
|
||||
}
|
||||
transfers_changed = true;
|
||||
}
|
||||
BackendEvent::SftpHome { tab_id, home } => {
|
||||
@@ -730,6 +912,32 @@ impl Ashell {
|
||||
tab.title = title.clone();
|
||||
}
|
||||
}
|
||||
BackendEvent::SyncFinished(result) => {
|
||||
self.sync_in_progress = false;
|
||||
match result {
|
||||
crate::sync::SyncResult::Uploaded { etag } => {
|
||||
if etag.is_some() {
|
||||
self.config.set_sync_etag(etag);
|
||||
}
|
||||
self.sync_status = t!("sync_upload_complete").into();
|
||||
let _ = self.config.save();
|
||||
}
|
||||
crate::sync::SyncResult::Downloaded { payload, etag } => {
|
||||
self.config.replace_sessions(payload.sessions);
|
||||
self.config.set_sync_etag(etag);
|
||||
match self.config.save() {
|
||||
Ok(()) => self.sync_status = t!("sync_download_complete").into(),
|
||||
Err(err) => {
|
||||
self.sync_status =
|
||||
format!("{}: {err:#}", t!("sync_failed")).into()
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::sync::SyncResult::Failed(error) => {
|
||||
self.sync_status = format!("{}: {error}", t!("sync_failed")).into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if transfers_changed {
|
||||
@@ -743,7 +951,12 @@ impl Ashell {
|
||||
self.last_system_sample = Instant::now();
|
||||
// Use system_tab_id (not active_tab) to decide remote vs local sampling
|
||||
if let Some(ref tab_id) = self.system_tab_id.clone() {
|
||||
if self.tabs.iter().any(|t| t.id == *tab_id && t.kind == TabKind::Ssh && t.connected) && self.system_status.is_none() {
|
||||
if self
|
||||
.tabs
|
||||
.iter()
|
||||
.any(|t| t.id == *tab_id && t.kind == TabKind::Ssh && t.connected)
|
||||
&& self.system_status.is_none()
|
||||
{
|
||||
self.request_active_system_snapshot();
|
||||
return false;
|
||||
}
|
||||
@@ -777,31 +990,23 @@ impl Ashell {
|
||||
}
|
||||
|
||||
pub(crate) fn request_active_system_snapshot(&mut self) {
|
||||
let Some(ref tab_id) = self.system_tab_id.clone() else { return };
|
||||
let Some(session) = (|| {
|
||||
let Some(ref tab_id) = self.system_tab_id.clone() else {
|
||||
return;
|
||||
};
|
||||
let Some(backend) = (|| {
|
||||
let tab = self.tabs.iter().find(|t| t.id == *tab_id)?;
|
||||
if !tab.connected { return None; }
|
||||
tab.session.clone()
|
||||
})() else { return };
|
||||
if !tab.connected {
|
||||
return None;
|
||||
}
|
||||
Some(tab.backend.clone())
|
||||
})() else {
|
||||
return;
|
||||
};
|
||||
if self.remote_sample_in_flight {
|
||||
return;
|
||||
}
|
||||
self.remote_sample_in_flight = true;
|
||||
let events = self.events_tx.clone();
|
||||
let tab_id = tab_id.clone();
|
||||
self.runtime.spawn(async move {
|
||||
match ssh::sample_remote_system(session).await {
|
||||
Ok(snapshot) => {
|
||||
let _ = events.send(BackendEvent::RemoteSystem { tab_id, snapshot });
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = events.send(BackendEvent::RemoteSystemUnavailable {
|
||||
tab_id,
|
||||
reason: format!("remote metrics unavailable: {err:#}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
backend.send(crate::terminal::BackendCommand::SampleMetrics);
|
||||
}
|
||||
|
||||
pub(crate) fn terminal_ime_bounds_for_range(
|
||||
@@ -816,14 +1021,16 @@ impl Ashell {
|
||||
let x = element_bounds.origin.x
|
||||
+ px(cell_width) * cursor.col as f32
|
||||
+ px(cell_width) * range_utf16.start as f32;
|
||||
let y = element_bounds.origin.y
|
||||
+ px(line_height) * cursor.row as f32;
|
||||
let y = element_bounds.origin.y + px(line_height) * cursor.row as f32;
|
||||
Some(Bounds::new(
|
||||
point(x, y),
|
||||
size(
|
||||
px(cell_width),
|
||||
px(line_height),
|
||||
),
|
||||
size(px(cell_width), px(line_height)),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn remove_transfer(&mut self, transfer_id: &str, cx: &mut Context<Self>) {
|
||||
self.transfers.retain(|t| t.info.id != transfer_id);
|
||||
self.config.set_transfers(self.transfers.clone());
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
+209
-38
@@ -1,13 +1,134 @@
|
||||
use gpui::{App, AppContext as _, Bounds, WindowOptions, point, px, size};
|
||||
use gpui_component::Root;
|
||||
|
||||
use crate::session::config::ConfigStore;
|
||||
use crate::Ashell;
|
||||
use crate::session::config::ConfigStore;
|
||||
|
||||
pub(crate) fn bind_workspace_keys(cx: &mut gpui::App) {
|
||||
let config = ConfigStore::load().unwrap_or_else(|_| ConfigStore::in_memory());
|
||||
crate::app::keybinding_recorder::bind_workspace_keys_from_config(cx, &config);
|
||||
}
|
||||
|
||||
struct LocalMinutelyRoller {
|
||||
dir: std::path::PathBuf,
|
||||
prefix: String,
|
||||
current_minute: u32,
|
||||
file: Option<std::fs::File>,
|
||||
}
|
||||
|
||||
impl LocalMinutelyRoller {
|
||||
fn new(dir: std::path::PathBuf, prefix: String) -> Self {
|
||||
Self {
|
||||
dir,
|
||||
prefix,
|
||||
current_minute: 60,
|
||||
file: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rollover(&mut self, now: chrono::DateTime<chrono::Local>) -> std::io::Result<()> {
|
||||
use chrono::Timelike;
|
||||
let minute = now.minute();
|
||||
if self.current_minute != minute || self.file.is_none() {
|
||||
let filename = format!("{}-{}.log", self.prefix, now.format("%Y-%m-%d-%H-%M"));
|
||||
let path = self.dir.join(filename);
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)?;
|
||||
self.file = Some(file);
|
||||
self.current_minute = minute;
|
||||
|
||||
// Cleanup old files keeping last 6
|
||||
if let Ok(entries) = std::fs::read_dir(&self.dir) {
|
||||
let mut files: Vec<_> = entries
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.file_name().to_string_lossy().starts_with(&self.prefix))
|
||||
.collect();
|
||||
files.sort_by_key(|e| {
|
||||
e.metadata()
|
||||
.and_then(|m| m.modified())
|
||||
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
|
||||
});
|
||||
if files.len() > 6 {
|
||||
for file in files.iter().take(files.len() - 6) {
|
||||
let _ = std::fs::remove_file(file.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for LocalMinutelyRoller {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let now = chrono::Local::now();
|
||||
let _ = self.rollover(now);
|
||||
if let Some(f) = &mut self.file {
|
||||
f.write(buf)
|
||||
} else {
|
||||
Ok(buf.len())
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
if let Some(f) = &mut self.file {
|
||||
f.flush()
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn init_logging() {
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
let log_dir = directories::BaseDirs::new()
|
||||
.map(|dirs| dirs.home_dir().join(".config").join("ashell").join("log"))
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||
|
||||
std::fs::create_dir_all(&log_dir).ok();
|
||||
|
||||
let roller = LocalMinutelyRoller::new(log_dir.clone(), "ashell".to_string());
|
||||
|
||||
let (non_blocking, _guard) = tracing_appender::non_blocking(roller);
|
||||
// Leak the guard so it lives for the entire duration of the app since GPUI's run might not return
|
||||
std::mem::forget(_guard);
|
||||
|
||||
let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
|
||||
|
||||
let stdout_layer = if cfg!(debug_assertions) {
|
||||
Some(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_timer(tracing_subscriber::fmt::time::LocalTime::rfc_3339())
|
||||
.with_target(true),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let file_layer = tracing_subscriber::fmt::layer()
|
||||
.with_timer(tracing_subscriber::fmt::time::LocalTime::rfc_3339())
|
||||
.with_writer(non_blocking)
|
||||
.with_ansi(false)
|
||||
.with_target(true);
|
||||
|
||||
tracing_subscriber::registry()
|
||||
.with(env_filter)
|
||||
.with(stdout_layer)
|
||||
.with(file_layer)
|
||||
.init();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn sync_macos_launch_environment() {
|
||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".to_string());
|
||||
let Ok(output) = std::process::Command::new(&shell).args(["-l", "-c", "env -0"]).output() else {
|
||||
let Ok(output) = std::process::Command::new(&shell)
|
||||
.args(["-l", "-c", "env -0"])
|
||||
.output()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !output.status.success() {
|
||||
@@ -55,14 +176,23 @@ pub(crate) fn sync_macos_launch_environment() {
|
||||
pub(crate) fn sync_macos_launch_environment() {}
|
||||
|
||||
pub(crate) fn open_main_window(cx: &mut App) {
|
||||
let config = ConfigStore::load().unwrap_or_else(|_| ConfigStore::in_memory());
|
||||
|
||||
let mut window_options = WindowOptions::default();
|
||||
|
||||
if config.title_bar_style() == crate::session::config::TitleBarStyle::Integrated {
|
||||
window_options.titlebar = Some(gpui::TitlebarOptions {
|
||||
title: None,
|
||||
appears_transparent: true,
|
||||
traffic_light_position: Some(gpui::point(px(9.0), px(9.0))),
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if let Ok(img) = image::load_from_memory(include_bytes!("../../assets/icons/ashell.png")) {
|
||||
window_options.icon = Some(std::sync::Arc::new(img.into_rgba8()));
|
||||
}
|
||||
|
||||
let config = ConfigStore::load().unwrap_or_else(|_| ConfigStore::in_memory());
|
||||
if let Some(bounds) = config.window_bounds() {
|
||||
window_options.window_bounds = Some(match bounds {
|
||||
crate::session::config::SavedWindowBounds::Fullscreen {
|
||||
@@ -117,45 +247,87 @@ pub(crate) fn open_main_window(cx: &mut App) {
|
||||
gpui_component::Theme::sync_system_appearance(Some(window), cx);
|
||||
let view = cx.new(|cx| Ashell::new(window, cx));
|
||||
|
||||
tracing::info!("[ui] main application window opened");
|
||||
let focus_handle = view.read(cx).focus_handle.clone();
|
||||
window.focus(&focus_handle, cx);
|
||||
|
||||
|
||||
|
||||
let workspace_panels_clone = view.read(cx).workspace_panels.clone();
|
||||
let body_panels_clone = view.read(cx).body_panels.clone();
|
||||
let view_clone = view.clone();
|
||||
window.on_window_should_close(cx, move |window: &mut gpui::Window, cx: &mut gpui::App| {
|
||||
let mut config = ConfigStore::load().unwrap_or_else(|_| ConfigStore::in_memory());
|
||||
if view_clone.read(cx).is_layout_reset {
|
||||
tracing::info!("[ui] layout was reset, skipping save layout state.");
|
||||
return true;
|
||||
}
|
||||
let current_bounds = window.window_bounds();
|
||||
let saved_bounds = match current_bounds {
|
||||
gpui::WindowBounds::Fullscreen(b) => crate::session::config::SavedWindowBounds::Fullscreen {
|
||||
x: b.origin.x.into(),
|
||||
y: b.origin.y.into(),
|
||||
width: b.size.width.into(),
|
||||
height: b.size.height.into(),
|
||||
},
|
||||
gpui::WindowBounds::Maximized(b) => crate::session::config::SavedWindowBounds::Maximized {
|
||||
x: b.origin.x.into(),
|
||||
y: b.origin.y.into(),
|
||||
width: b.size.width.into(),
|
||||
height: b.size.height.into(),
|
||||
},
|
||||
gpui::WindowBounds::Windowed(b) => crate::session::config::SavedWindowBounds::Windowed {
|
||||
x: b.origin.x.into(),
|
||||
y: b.origin.y.into(),
|
||||
width: b.size.width.into(),
|
||||
height: b.size.height.into(),
|
||||
},
|
||||
let bounds = match current_bounds {
|
||||
gpui::WindowBounds::Fullscreen(b) => b,
|
||||
gpui::WindowBounds::Maximized(b) => b,
|
||||
gpui::WindowBounds::Windowed(b) => b,
|
||||
};
|
||||
let workspace_sizes: Vec<f32> = workspace_panels_clone
|
||||
.read(cx)
|
||||
.sizes()
|
||||
.iter()
|
||||
.map(|s| s.into())
|
||||
.collect();
|
||||
let body_sizes: Vec<f32> = body_panels_clone
|
||||
.read(cx)
|
||||
.sizes()
|
||||
.iter()
|
||||
.map(|s| s.into())
|
||||
.collect();
|
||||
config.set_layout_state(Some(saved_bounds), Some(workspace_sizes), Some(body_sizes));
|
||||
let _ = config.save();
|
||||
let size = bounds.size;
|
||||
if size.width.as_f32() > 400.0 && size.height.as_f32() > 300.0 {
|
||||
tracing::info!("[ui] main application window closed, saving layout state...");
|
||||
let mut config = ConfigStore::load().unwrap_or_else(|_| ConfigStore::in_memory());
|
||||
let saved_bounds = match current_bounds {
|
||||
gpui::WindowBounds::Fullscreen(b) => {
|
||||
crate::session::config::SavedWindowBounds::Fullscreen {
|
||||
x: b.origin.x.into(),
|
||||
y: b.origin.y.into(),
|
||||
width: b.size.width.into(),
|
||||
height: b.size.height.into(),
|
||||
}
|
||||
}
|
||||
gpui::WindowBounds::Maximized(b) => {
|
||||
crate::session::config::SavedWindowBounds::Maximized {
|
||||
x: b.origin.x.into(),
|
||||
y: b.origin.y.into(),
|
||||
width: b.size.width.into(),
|
||||
height: b.size.height.into(),
|
||||
}
|
||||
}
|
||||
gpui::WindowBounds::Windowed(b) => {
|
||||
crate::session::config::SavedWindowBounds::Windowed {
|
||||
x: b.origin.x.into(),
|
||||
y: b.origin.y.into(),
|
||||
width: b.size.width.into(),
|
||||
height: b.size.height.into(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let workspace_sizes: Vec<f32> = workspace_panels_clone
|
||||
.read(cx)
|
||||
.sizes()
|
||||
.iter()
|
||||
.map(|s| s.into())
|
||||
.collect();
|
||||
let mut body_sizes: Vec<f32> = body_panels_clone
|
||||
.read(cx)
|
||||
.sizes()
|
||||
.iter()
|
||||
.map(|s| s.into())
|
||||
.collect();
|
||||
|
||||
if view_clone.read(cx).sftp_panel_minimized {
|
||||
if let Some(prev) = view_clone.read(cx).prev_monitoring_size {
|
||||
if body_sizes.len() > 1 {
|
||||
body_sizes[1] = prev.into();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
config.set_layout_state(Some(saved_bounds), Some(workspace_sizes), Some(body_sizes));
|
||||
config.set_sidebar_collapsed(view_clone.read(cx).sidebar_collapsed);
|
||||
config.set_sftp_panel_minimized(view_clone.read(cx).sftp_panel_minimized);
|
||||
let _ = config.save();
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"[ui] window size is too small ({:?}), skipping save layout state to prevent corrupting saved bounds.",
|
||||
size
|
||||
);
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
@@ -163,4 +335,3 @@ pub(crate) fn open_main_window(cx: &mut App) {
|
||||
})
|
||||
.expect("failed to open window");
|
||||
}
|
||||
|
||||
|
||||
+26
-102
@@ -1,11 +1,6 @@
|
||||
use anyhow::{Context as _, Result};
|
||||
use gpui::{Anchor, App, Context, IntoElement, SharedString, Window, px};
|
||||
use gpui_component::{
|
||||
ActiveTheme as _, IconName, Sizable as _, Theme, ThemeMode, ThemeRegistry,
|
||||
button::{Button, ButtonVariants as _},
|
||||
menu::{DropdownMenu as _, PopupMenuItem},
|
||||
};
|
||||
use rust_i18n::t;
|
||||
use gpui::{App, Context, SharedString, Window, px};
|
||||
use gpui_component::{ActiveTheme as _, Theme, ThemeMode, ThemeRegistry};
|
||||
|
||||
use crate::Ashell;
|
||||
|
||||
@@ -17,9 +12,12 @@ pub(crate) const EMBEDDED_THEME_JSONS: &[&str] = &[
|
||||
];
|
||||
|
||||
pub(crate) fn load_fonts(cx: &mut App) -> Result<()> {
|
||||
let regular =
|
||||
std::borrow::Cow::Borrowed(include_bytes!("../../assets/fonts/MapleMono-NF-CN-Regular.ttf").as_slice());
|
||||
let bold = std::borrow::Cow::Borrowed(include_bytes!("../../assets/fonts/MapleMono-NF-CN-Bold.ttf").as_slice());
|
||||
let regular = std::borrow::Cow::Borrowed(
|
||||
include_bytes!("../../assets/fonts/MapleMono-NF-CN-Regular.ttf").as_slice(),
|
||||
);
|
||||
let bold = std::borrow::Cow::Borrowed(
|
||||
include_bytes!("../../assets/fonts/MapleMono-NF-CN-Bold.ttf").as_slice(),
|
||||
);
|
||||
cx.text_system()
|
||||
.add_fonts(vec![regular, bold])
|
||||
.context("load Maple Mono NF CN fonts")?;
|
||||
@@ -42,7 +40,12 @@ pub(crate) fn set_theme_font_names(theme: &mut Theme, ui_font_family: &str) {
|
||||
}
|
||||
|
||||
impl Ashell {
|
||||
pub(crate) fn switch_theme_mode(&mut self, mode: ThemeMode, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(crate) fn switch_theme_mode(
|
||||
&mut self,
|
||||
mode: ThemeMode,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.follow_system_theme = false;
|
||||
self.theme_mode = mode;
|
||||
self.apply_theme_preferences(window, cx);
|
||||
@@ -51,7 +54,12 @@ impl Ashell {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(crate) fn apply_theme(&mut self, name: SharedString, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(crate) fn apply_theme(
|
||||
&mut self,
|
||||
name: SharedString,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let Some(theme_config) = ThemeRegistry::global(cx).themes().get(&name).cloned() else {
|
||||
self.status = format!("theme not found: {name}").into();
|
||||
cx.notify();
|
||||
@@ -87,7 +95,12 @@ impl Ashell {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(crate) fn set_display_language(&mut self, locale: &str, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(crate) fn set_display_language(
|
||||
&mut self,
|
||||
locale: &str,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.config.set_locale(locale);
|
||||
let mut active_locale = locale.to_string();
|
||||
if active_locale == "system" {
|
||||
@@ -146,93 +159,4 @@ impl Ashell {
|
||||
tracing::warn!("failed to save theme preferences: {err:#}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn theme_dropdown(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let view = cx.entity();
|
||||
let themes = ThemeRegistry::global(cx)
|
||||
.sorted_themes()
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let light_themes = themes
|
||||
.iter()
|
||||
.filter(|theme| !theme.mode.is_dark())
|
||||
.map(|theme| theme.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let dark_themes = themes
|
||||
.iter()
|
||||
.filter(|theme| theme.mode.is_dark())
|
||||
.map(|theme| theme.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let follow_system = self.follow_system_theme;
|
||||
let is_dark_mode = cx.theme().mode.is_dark();
|
||||
let light_theme_name = self.light_theme_name.clone();
|
||||
let dark_theme_name = self.dark_theme_name.clone();
|
||||
let icon = if follow_system {
|
||||
IconName::Sun
|
||||
} else if is_dark_mode {
|
||||
IconName::Moon
|
||||
} else {
|
||||
IconName::Sun
|
||||
};
|
||||
|
||||
Button::new("theme-dropdown")
|
||||
.ghost()
|
||||
.small()
|
||||
.icon(icon)
|
||||
.dropdown_menu_with_anchor(Anchor::BottomRight, move |mut menu, window, _| {
|
||||
menu = menu
|
||||
.min_w(220.)
|
||||
.item(
|
||||
PopupMenuItem::new(t!("follow_system"))
|
||||
.checked(follow_system)
|
||||
.on_click(window.listener_for(&view, |this, _, window, cx| {
|
||||
this.set_follow_system_theme(true, window, cx)
|
||||
})),
|
||||
)
|
||||
.item(
|
||||
PopupMenuItem::new(t!("use_light_mode"))
|
||||
.checked(!follow_system && !is_dark_mode)
|
||||
.on_click(window.listener_for(&view, |this, _, window, cx| {
|
||||
this.switch_theme_mode(ThemeMode::Light, window, cx)
|
||||
})),
|
||||
)
|
||||
.item(
|
||||
PopupMenuItem::new(t!("use_dark_mode"))
|
||||
.checked(!follow_system && is_dark_mode)
|
||||
.on_click(window.listener_for(&view, |this, _, window, cx| {
|
||||
this.switch_theme_mode(ThemeMode::Dark, window, cx)
|
||||
})),
|
||||
)
|
||||
.separator()
|
||||
.label(t!("light_theme").to_string());
|
||||
|
||||
for theme_name in light_themes.clone() {
|
||||
let checked = theme_name == light_theme_name;
|
||||
menu = menu.item(
|
||||
PopupMenuItem::new(theme_name.clone())
|
||||
.checked(checked)
|
||||
.on_click(window.listener_for(&view, move |this, _, window, cx| {
|
||||
this.apply_theme(theme_name.clone(), window, cx)
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
menu = menu.separator();
|
||||
menu = menu.label(t!("dark_theme").to_string());
|
||||
|
||||
for theme_name in dark_themes.clone() {
|
||||
let checked = theme_name == dark_theme_name;
|
||||
menu = menu.item(
|
||||
PopupMenuItem::new(theme_name.clone())
|
||||
.checked(checked)
|
||||
.on_click(window.listener_for(&view, move |this, _, window, cx| {
|
||||
this.apply_theme(theme_name.clone(), window, cx)
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
menu
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+1324
-573
File diff suppressed because it is too large
Load Diff
+31
-17
@@ -94,27 +94,41 @@ pub fn spawn_local_terminal(
|
||||
let write_tab = tab_id.clone();
|
||||
let write_events = events.clone();
|
||||
thread::spawn(move || {
|
||||
while let Ok(command) = cmd_rx.recv() {
|
||||
match command {
|
||||
BackendCommand::Input(bytes) => {
|
||||
if let Err(err) = writer.write_all(&bytes) {
|
||||
loop {
|
||||
match cmd_rx.recv_timeout(std::time::Duration::from_millis(100)) {
|
||||
Ok(command) => match command {
|
||||
BackendCommand::Input(bytes) => {
|
||||
if let Err(err) = writer.write_all(&bytes) {
|
||||
let _ = write_events.send(BackendEvent::Closed {
|
||||
tab_id: write_tab.clone(),
|
||||
reason: format!("local write error: {err}"),
|
||||
});
|
||||
break;
|
||||
}
|
||||
let _ = writer.flush();
|
||||
}
|
||||
BackendCommand::Resize { cols, rows } => {
|
||||
let _ = master.resize(PtySize {
|
||||
rows,
|
||||
cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
});
|
||||
}
|
||||
BackendCommand::Close => break,
|
||||
BackendCommand::SampleMetrics => {}
|
||||
BackendCommand::PromptResponse(_) => {}
|
||||
},
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
let _ = write_events.send(BackendEvent::Closed {
|
||||
tab_id: write_tab.clone(),
|
||||
reason: format!("local write error: {err}"),
|
||||
tab_id: write_tab,
|
||||
reason: format!("local shell exited: {status}"),
|
||||
});
|
||||
break;
|
||||
return;
|
||||
}
|
||||
let _ = writer.flush();
|
||||
}
|
||||
BackendCommand::Resize { cols, rows } => {
|
||||
let _ = master.resize(PtySize {
|
||||
rows,
|
||||
cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
});
|
||||
}
|
||||
BackendCommand::Close => break,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
|
||||
+290
-30
@@ -16,8 +16,23 @@ use tokio::sync::mpsc;
|
||||
use crate::{
|
||||
session::config::{AuthMethod, Session},
|
||||
system::{SystemSnapshot, remote_snapshot_from_kv},
|
||||
terminal::{BackendCommand, BackendEvent, BackendTx},
|
||||
terminal::{BackendCommand, BackendEvent, BackendTx, PromptType, PromptInfo},
|
||||
};
|
||||
use std::sync::OnceLock;
|
||||
use std::collections::HashMap;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CachedCreds {
|
||||
pub password: Option<String>,
|
||||
pub passphrase: Option<String>,
|
||||
pub kb_responses: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
pub static CREDENTIALS_CACHE: OnceLock<std::sync::Mutex<HashMap<String, CachedCreds>>> = OnceLock::new();
|
||||
|
||||
pub static PROMPT_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
|
||||
pub fn spawn_ssh_terminal(
|
||||
runtime: &tokio::runtime::Handle,
|
||||
@@ -49,10 +64,12 @@ pub fn spawn_ssh_terminal(
|
||||
BackendTx::Ssh(cmd_tx)
|
||||
}
|
||||
|
||||
pub async fn sample_remote_system(session: Session) -> Result<SystemSnapshot> {
|
||||
let (events_tx, _events_rx) = std::sync::mpsc::channel();
|
||||
let handle = connect_and_authenticate("remote-metrics", &session, &events_tx).await?;
|
||||
async fn sample_remote_system_with_handle(
|
||||
handle: Arc<tokio::sync::Mutex<russh::client::Handle<ClientHandler>>>,
|
||||
) -> Result<SystemSnapshot> {
|
||||
let mut channel = handle
|
||||
.lock()
|
||||
.await
|
||||
.channel_open_session()
|
||||
.await
|
||||
.context("open metrics session")?;
|
||||
@@ -72,9 +89,6 @@ pub async fn sample_remote_system(session: Session) -> Result<SystemSnapshot> {
|
||||
}
|
||||
}
|
||||
|
||||
let _ = handle
|
||||
.disconnect(Disconnect::ByApplication, "metrics done", "")
|
||||
.await;
|
||||
let output = String::from_utf8_lossy(&stdout);
|
||||
remote_snapshot_from_kv(&output)
|
||||
}
|
||||
@@ -95,9 +109,13 @@ async fn run_ssh(
|
||||
),
|
||||
});
|
||||
|
||||
let handle = connect_and_authenticate(&tab_id, &session, &events).await?;
|
||||
let handle = Arc::new(tokio::sync::Mutex::new(
|
||||
connect_and_authenticate(&tab_id, &session, &events, &mut commands).await?,
|
||||
));
|
||||
|
||||
let mut channel = handle
|
||||
.lock()
|
||||
.await
|
||||
.channel_open_session()
|
||||
.await
|
||||
.context("open session")?;
|
||||
@@ -124,6 +142,7 @@ async fn run_ssh(
|
||||
match command {
|
||||
Some(BackendCommand::Input(bytes)) => {
|
||||
if let Err(err) = channel.data(bytes.as_slice()).await {
|
||||
tracing::error!("[ssh] write error on tab {}: {}", tab_id, err);
|
||||
exit_reason = format!("ssh write error: {err}");
|
||||
break;
|
||||
}
|
||||
@@ -131,7 +150,32 @@ async fn run_ssh(
|
||||
Some(BackendCommand::Resize { cols, rows }) => {
|
||||
let _ = channel.window_change(cols.into(), rows.into(), 0, 0).await;
|
||||
}
|
||||
Some(BackendCommand::SampleMetrics) => {
|
||||
let handle_clone = handle.clone();
|
||||
let tab_id_clone = tab_id.clone();
|
||||
let events_clone = events.clone();
|
||||
tokio::spawn(async move {
|
||||
match sample_remote_system_with_handle(handle_clone).await {
|
||||
Ok(snapshot) => {
|
||||
let _ = events_clone.send(BackendEvent::RemoteSystem {
|
||||
tab_id: tab_id_clone,
|
||||
snapshot,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = events_clone.send(BackendEvent::RemoteSystemUnavailable {
|
||||
tab_id: tab_id_clone,
|
||||
reason: format!("remote metrics unavailable: {err:#}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(BackendCommand::PromptResponse(_)) => {
|
||||
tracing::warn!("[ssh] received unexpected prompt response after authentication");
|
||||
}
|
||||
Some(BackendCommand::Close) | None => {
|
||||
tracing::info!("[ssh] local client closed the session for tab {}", tab_id);
|
||||
let _ = channel.eof().await;
|
||||
exit_reason = "ssh session closed".to_string();
|
||||
break;
|
||||
@@ -151,16 +195,20 @@ async fn run_ssh(
|
||||
}
|
||||
Some(ChannelMsg::Close) => {
|
||||
if is_graceful_close {
|
||||
tracing::info!("[ssh] session gracefully closed by server for tab {}", tab_id);
|
||||
exit_reason = "ssh session closed".to_string();
|
||||
} else {
|
||||
tracing::warn!("[ssh] connection abruptly closed by server for tab {}", tab_id);
|
||||
exit_reason = "ssh connection lost (abrupt close)".to_string();
|
||||
}
|
||||
break;
|
||||
}
|
||||
None => {
|
||||
if is_graceful_close {
|
||||
tracing::info!("[ssh] network stream ended gracefully for tab {}", tab_id);
|
||||
exit_reason = "ssh session closed".to_string();
|
||||
} else {
|
||||
tracing::warn!("[ssh] network drop detected for tab {}", tab_id);
|
||||
exit_reason = "ssh connection lost (network drop)".to_string();
|
||||
}
|
||||
break;
|
||||
@@ -172,6 +220,8 @@ async fn run_ssh(
|
||||
}
|
||||
|
||||
let _ = handle
|
||||
.lock()
|
||||
.await
|
||||
.disconnect(Disconnect::ByApplication, "bye", "")
|
||||
.await;
|
||||
let _ = events.send(BackendEvent::Closed {
|
||||
@@ -181,10 +231,27 @@ async fn run_ssh(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_session_private_key_with_cache(session: &Session) -> Result<PrivateKey> {
|
||||
let cached_passphrase = {
|
||||
let cache_lock = CREDENTIALS_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
|
||||
let cache = cache_lock.lock().unwrap();
|
||||
cache.get(&session.id).and_then(|c| c.passphrase.clone())
|
||||
};
|
||||
if let Some(p) = cached_passphrase {
|
||||
let mut temp_session = session.clone();
|
||||
temp_session.passphrase = p;
|
||||
if let Ok(key) = load_session_private_key(&temp_session) {
|
||||
return Ok(key);
|
||||
}
|
||||
}
|
||||
load_session_private_key(session)
|
||||
}
|
||||
|
||||
async fn connect_and_authenticate(
|
||||
tab_id: &str,
|
||||
session: &Session,
|
||||
events: &std::sync::mpsc::Sender<BackendEvent>,
|
||||
commands: &mut mpsc::UnboundedReceiver<BackendCommand>,
|
||||
) -> Result<russh::client::Handle<ClientHandler>> {
|
||||
let config = Arc::new(client::Config {
|
||||
inactivity_timeout: Some(std::time::Duration::from_secs(600)),
|
||||
@@ -193,6 +260,11 @@ async fn connect_and_authenticate(
|
||||
..Default::default()
|
||||
});
|
||||
let addr = format!("{}:{}", session.host, session.port);
|
||||
tracing::info!(
|
||||
"[ssh] initiating tcp connection to {} (user: {})",
|
||||
addr,
|
||||
session.user
|
||||
);
|
||||
let _ = events.send(BackendEvent::Status {
|
||||
tab_id: tab_id.to_string(),
|
||||
text: format!("opening tcp connection to {addr}"),
|
||||
@@ -201,8 +273,15 @@ async fn connect_and_authenticate(
|
||||
.await
|
||||
.with_context(|| format!("connect {addr} failed"))?;
|
||||
|
||||
tracing::debug!("[ssh] tcp connected to {}", addr);
|
||||
|
||||
let authed = match session.auth {
|
||||
AuthMethod::Password => {
|
||||
tracing::info!(
|
||||
"[ssh] sending password authentication for {}@{}",
|
||||
session.user,
|
||||
addr
|
||||
);
|
||||
let _ = events.send(BackendEvent::Status {
|
||||
tab_id: tab_id.to_string(),
|
||||
text: format!(
|
||||
@@ -217,30 +296,181 @@ async fn connect_and_authenticate(
|
||||
}
|
||||
AuthMethod::Key => {
|
||||
let source = key_source_label(session);
|
||||
tracing::info!(
|
||||
"[ssh] sending key authentication for {}@{} (key source: {})",
|
||||
session.user,
|
||||
addr,
|
||||
source
|
||||
);
|
||||
let _ = events.send(BackendEvent::Status {
|
||||
tab_id: tab_id.to_string(),
|
||||
text: format!("connected to {addr}, loading private key from {source}"),
|
||||
});
|
||||
let keypair = load_session_private_key(session)?;
|
||||
let mut keypair = load_session_private_key_with_cache(session).await;
|
||||
if let Err(e) = &keypair {
|
||||
let err_str = e.to_string();
|
||||
if err_str.contains("encrypted") || err_str.contains("passphrase") || err_str.contains("decrypt") {
|
||||
let prompt_lock = PROMPT_LOCK.get_or_init(|| Mutex::new(()));
|
||||
let _guard = prompt_lock.lock().await;
|
||||
let _ = events.send(BackendEvent::PromptRequest {
|
||||
tab_id: tab_id.to_string(),
|
||||
prompt_type: PromptType::Passphrase,
|
||||
instruction: format!("Enter passphrase for private key (source: {})", source),
|
||||
prompts: vec![PromptInfo {
|
||||
prompt: "Passphrase".to_string(),
|
||||
echo: false,
|
||||
}],
|
||||
});
|
||||
let mut passphrase_res = None;
|
||||
while let Some(cmd) = commands.recv().await {
|
||||
match cmd {
|
||||
BackendCommand::PromptResponse(responses) => {
|
||||
if let Some(p) = responses.first().cloned() {
|
||||
passphrase_res = Some(p);
|
||||
}
|
||||
break;
|
||||
}
|
||||
BackendCommand::Close => {
|
||||
return Err(anyhow!("Authentication cancelled by user"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(p) = passphrase_res {
|
||||
{
|
||||
let cache_lock = CREDENTIALS_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
|
||||
let mut cache = cache_lock.lock().unwrap();
|
||||
cache.entry(session.id.clone()).or_insert_with(|| CachedCreds {
|
||||
password: None,
|
||||
passphrase: None,
|
||||
kb_responses: None,
|
||||
}).passphrase = Some(p.clone());
|
||||
}
|
||||
let mut temp_session = session.clone();
|
||||
temp_session.passphrase = p;
|
||||
keypair = load_session_private_key(&temp_session);
|
||||
} else {
|
||||
return Err(anyhow!("Passphrase prompt cancelled"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let keypair = keypair.context("failed to load private key")?;
|
||||
let algorithm = format!("{:?}", keypair.algorithm());
|
||||
let _ = events.send(BackendEvent::Status {
|
||||
tab_id: tab_id.to_string(),
|
||||
text: format!("private key loaded from {source}, algorithm {algorithm}, sending public key authentication for {}", session.user),
|
||||
});
|
||||
let key = private_key_with_alg(keypair).context("invalid private key")?;
|
||||
handle
|
||||
.authenticate_publickey(&session.user, key)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"public key authentication failed for {}@{}:{} using {} ({})",
|
||||
session.user, session.host, session.port, source, algorithm
|
||||
)
|
||||
})?
|
||||
let keys = private_keys_with_algs(keypair).context("invalid private key")?;
|
||||
let mut success = false;
|
||||
for key in keys {
|
||||
match handle.authenticate_publickey(&session.user, key).await {
|
||||
Ok(true) => {
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
Ok(false) => {
|
||||
tracing::debug!("[ssh] public key auth failed with algorithm, trying next");
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!("[ssh] public key auth error: {:?}, trying next", e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !success {
|
||||
return Err(anyhow::anyhow!(
|
||||
"public key authentication failed for {}@{}:{} using {} ({})",
|
||||
session.user,
|
||||
session.host,
|
||||
session.port,
|
||||
source,
|
||||
algorithm
|
||||
));
|
||||
}
|
||||
success
|
||||
}
|
||||
AuthMethod::KeyboardInteractive => {
|
||||
let cached = {
|
||||
let cache_lock = CREDENTIALS_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
|
||||
let cache = cache_lock.lock().unwrap();
|
||||
cache.get(&session.id).cloned()
|
||||
};
|
||||
let mut response = if cached.as_ref().and_then(|c| c.kb_responses.as_ref()).is_some() {
|
||||
handle.authenticate_keyboard_interactive_start(&session.user, None).await?
|
||||
} else {
|
||||
let prompt_lock = PROMPT_LOCK.get_or_init(|| Mutex::new(()));
|
||||
let _guard = prompt_lock.lock().await;
|
||||
handle.authenticate_keyboard_interactive_start(&session.user, None).await?
|
||||
};
|
||||
loop {
|
||||
match response {
|
||||
russh::client::KeyboardInteractiveAuthResponse::Success => {
|
||||
break true;
|
||||
}
|
||||
russh::client::KeyboardInteractiveAuthResponse::Failure => {
|
||||
break false;
|
||||
}
|
||||
russh::client::KeyboardInteractiveAuthResponse::InfoRequest { name, instructions, prompts } => {
|
||||
let mut responses = Vec::new();
|
||||
let mut cache_hit = false;
|
||||
if let Some(c) = cached.as_ref().and_then(|c| c.kb_responses.as_ref()) {
|
||||
if c.len() == prompts.len() {
|
||||
responses = c.clone();
|
||||
cache_hit = true;
|
||||
}
|
||||
}
|
||||
if !cache_hit {
|
||||
let prompt_lock = PROMPT_LOCK.get_or_init(|| Mutex::new(()));
|
||||
let _guard = prompt_lock.lock().await;
|
||||
let mut prompt_infos = Vec::new();
|
||||
for p in &prompts {
|
||||
prompt_infos.push(PromptInfo {
|
||||
prompt: p.prompt.clone(),
|
||||
echo: p.echo,
|
||||
});
|
||||
}
|
||||
let _ = events.send(BackendEvent::PromptRequest {
|
||||
tab_id: tab_id.to_string(),
|
||||
prompt_type: PromptType::KeyboardInteractive,
|
||||
instruction: format!("{}\n{}", name, instructions),
|
||||
prompts: prompt_infos,
|
||||
});
|
||||
let mut prompt_res = None;
|
||||
while let Some(cmd) = commands.recv().await {
|
||||
match cmd {
|
||||
BackendCommand::PromptResponse(res) => {
|
||||
prompt_res = Some(res);
|
||||
break;
|
||||
}
|
||||
BackendCommand::Close => {
|
||||
return Err(anyhow!("Authentication cancelled"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(res) = prompt_res {
|
||||
responses = res;
|
||||
let cache_lock = CREDENTIALS_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
|
||||
let mut cache = cache_lock.lock().unwrap();
|
||||
cache.entry(session.id.clone()).or_insert_with(|| CachedCreds {
|
||||
password: None,
|
||||
passphrase: None,
|
||||
kb_responses: None,
|
||||
}).kb_responses = Some(responses.clone());
|
||||
} else {
|
||||
return Err(anyhow!("Keyboard-interactive cancelled"));
|
||||
}
|
||||
}
|
||||
response = handle.authenticate_keyboard_interactive_respond(responses).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if !authed {
|
||||
tracing::warn!("[ssh] authentication failed for {}@{}", session.user, addr);
|
||||
let _ = handle
|
||||
.disconnect(Disconnect::ByApplication, "auth failed", "")
|
||||
.await;
|
||||
@@ -258,10 +488,20 @@ async fn connect_and_authenticate(
|
||||
session.port,
|
||||
key_source_label(session)
|
||||
),
|
||||
AuthMethod::KeyboardInteractive => format!(
|
||||
"authentication failed: server rejected keyboard-interactive authentication for {}@{}:{}",
|
||||
session.user, session.host, session.port
|
||||
),
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"[ssh] authentication successful for {}@{}",
|
||||
session.user,
|
||||
addr
|
||||
);
|
||||
|
||||
let _ = events.send(BackendEvent::Status {
|
||||
tab_id: tab_id.to_string(),
|
||||
text: format!(
|
||||
@@ -276,6 +516,8 @@ async fn connect_and_authenticate(
|
||||
fn load_session_private_key(session: &Session) -> Result<PrivateKey> {
|
||||
let inline_key = normalize_inline_private_key(&session.private_key_inline);
|
||||
let key_path = expand_key_path(session.private_key_path.trim());
|
||||
let passphrase = session.passphrase.trim();
|
||||
let passphrase = (!passphrase.is_empty()).then_some(passphrase);
|
||||
let has_inline = !inline_key.is_empty();
|
||||
let has_path = key_path.is_some();
|
||||
|
||||
@@ -286,14 +528,14 @@ fn load_session_private_key(session: &Session) -> Result<PrivateKey> {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
if has_inline {
|
||||
match decode_secret_key(&inline_key, None) {
|
||||
match decode_secret_key(&inline_key, passphrase) {
|
||||
Ok(key) => return Ok(key),
|
||||
Err(err) => errors.push(format!("decode private key content: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = key_path {
|
||||
match load_secret_key(path.as_path(), None) {
|
||||
match load_secret_key(path.as_path(), passphrase) {
|
||||
Ok(key) => return Ok(key),
|
||||
Err(err) => errors.push(format!("load key {}: {err}", path.display())),
|
||||
}
|
||||
@@ -302,16 +544,33 @@ fn load_session_private_key(session: &Session) -> Result<PrivateKey> {
|
||||
Err(anyhow!(errors.join("; ")))
|
||||
}
|
||||
|
||||
fn private_key_with_alg(keypair: PrivateKey) -> Result<PrivateKeyWithHashAlg> {
|
||||
let hash_alg = if keypair.algorithm().is_rsa() {
|
||||
Some(HashAlg::Sha512)
|
||||
fn private_keys_with_algs(keypair: PrivateKey) -> Result<Vec<PrivateKeyWithHashAlg>> {
|
||||
let mut algs = Vec::new();
|
||||
let key_arc = Arc::new(keypair);
|
||||
|
||||
if key_arc.algorithm().is_rsa() {
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), Some(HashAlg::Sha512)) {
|
||||
algs.push(k);
|
||||
}
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), Some(HashAlg::Sha256)) {
|
||||
algs.push(k);
|
||||
}
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), None) {
|
||||
algs.push(k);
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(
|
||||
PrivateKeyWithHashAlg::new(Arc::new(keypair.clone()), hash_alg)
|
||||
.or_else(|_| PrivateKeyWithHashAlg::new(Arc::new(keypair), Some(HashAlg::Sha256)))?,
|
||||
)
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), None) {
|
||||
algs.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
if algs.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Failed to construct PrivateKeyWithHashAlg for any supported hash algorithm"
|
||||
));
|
||||
}
|
||||
|
||||
Ok(algs)
|
||||
}
|
||||
|
||||
fn normalize_inline_private_key(value: &str) -> String {
|
||||
@@ -438,6 +697,7 @@ echo "NET_RX=0"
|
||||
echo "NET_TX=0"
|
||||
'"#;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ClientHandler;
|
||||
|
||||
#[async_trait]
|
||||
|
||||
+22
-10
@@ -1,12 +1,13 @@
|
||||
#![windows_subsystem = "windows"]
|
||||
|
||||
use gpui::{ KeyBinding };
|
||||
use gpui::KeyBinding;
|
||||
use gpui_component_assets::Assets;
|
||||
|
||||
mod app;
|
||||
mod backend;
|
||||
mod session;
|
||||
mod sftp;
|
||||
mod sync;
|
||||
mod system;
|
||||
mod terminal;
|
||||
|
||||
@@ -14,26 +15,28 @@ rust_i18n::i18n!("locales", fallback = "en");
|
||||
|
||||
gpui::actions!(ashell_terminal, [TerminalTabKey, TerminalBacktabKey]);
|
||||
|
||||
pub(crate) use app::keybinding_recorder::{
|
||||
ClosePane, FocusPaneDown, FocusPaneLeft, FocusPaneRight, FocusPaneUp, NewSsh, OpenSession,
|
||||
OpenSettings, OpenTransfers, SplitPaneDown, SplitPaneLeft, SplitPaneRight, SplitPaneUp,
|
||||
ToggleSftpZoom, ToggleSidebar,
|
||||
};
|
||||
|
||||
pub(crate) use app::{
|
||||
Ashell, ConnectionProgress, PaneLayout, SelectorEntry, SftpContextMenuState, TabGroup,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
app::startup::sync_macos_launch_environment();
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
app::startup::init_logging();
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let app = gpui_platform::application()
|
||||
.with_assets(Assets)
|
||||
.with_quit_mode(gpui::QuitMode::Explicit);
|
||||
.with_quit_mode(gpui::QuitMode::LastWindowClosed);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let app = gpui_platform::application().with_assets(Assets);
|
||||
|
||||
app.on_reopen(|cx| {
|
||||
if cx.windows().is_empty() {
|
||||
app::startup::open_main_window(cx);
|
||||
@@ -42,9 +45,18 @@ fn main() {
|
||||
app.run(move |cx| {
|
||||
gpui_component::init(cx);
|
||||
cx.bind_keys([
|
||||
KeyBinding::new("tab", TerminalTabKey, Some(app::constants::TERMINAL_KEY_CONTEXT)),
|
||||
KeyBinding::new("shift-tab", TerminalBacktabKey, Some(app::constants::TERMINAL_KEY_CONTEXT)),
|
||||
KeyBinding::new(
|
||||
"tab",
|
||||
TerminalTabKey,
|
||||
Some(app::constants::TERMINAL_KEY_CONTEXT),
|
||||
),
|
||||
KeyBinding::new(
|
||||
"shift-tab",
|
||||
TerminalBacktabKey,
|
||||
Some(app::constants::TERMINAL_KEY_CONTEXT),
|
||||
),
|
||||
]);
|
||||
app::startup::bind_workspace_keys(cx);
|
||||
app::theme::load_embedded_themes(cx);
|
||||
if let Err(err) = app::theme::load_fonts(cx) {
|
||||
tracing::warn!("failed to load embedded fonts: {err:#}");
|
||||
|
||||
+220
-8
@@ -6,10 +6,11 @@ use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum AuthMethod {
|
||||
Password,
|
||||
Key,
|
||||
KeyboardInteractive,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -27,6 +28,8 @@ pub struct Session {
|
||||
#[serde(default)]
|
||||
pub private_key_inline: String,
|
||||
#[serde(default)]
|
||||
pub passphrase: String,
|
||||
#[serde(default)]
|
||||
pub last_used: Option<String>,
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ impl Session {
|
||||
password,
|
||||
private_key_path: String::new(),
|
||||
private_key_inline: String::new(),
|
||||
passphrase: String::new(),
|
||||
last_used: None,
|
||||
}
|
||||
}
|
||||
@@ -53,6 +57,7 @@ impl Session {
|
||||
user: String,
|
||||
private_key_path: String,
|
||||
private_key_inline: String,
|
||||
passphrase: String,
|
||||
) -> Self {
|
||||
let name = format!("{user}@{host}");
|
||||
Self {
|
||||
@@ -65,6 +70,28 @@ impl Session {
|
||||
password: String::new(),
|
||||
private_key_path,
|
||||
private_key_inline,
|
||||
passphrase,
|
||||
last_used: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn keyboard_interactive(
|
||||
host: String,
|
||||
port: u16,
|
||||
user: String,
|
||||
) -> Self {
|
||||
let name = format!("{user}@{host}");
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
name,
|
||||
host,
|
||||
port,
|
||||
user,
|
||||
auth: AuthMethod::KeyboardInteractive,
|
||||
password: String::new(),
|
||||
private_key_path: String::new(),
|
||||
private_key_inline: String::new(),
|
||||
passphrase: String::new(),
|
||||
last_used: None,
|
||||
}
|
||||
}
|
||||
@@ -93,9 +120,17 @@ pub enum SavedWindowBounds {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum TitleBarStyle {
|
||||
Native,
|
||||
#[default]
|
||||
Integrated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ConfigFile {
|
||||
#[serde(default)]
|
||||
#[serde(default = "default_follow_system_theme")]
|
||||
pub follow_system_theme: bool,
|
||||
#[serde(default)]
|
||||
pub theme_mode: String,
|
||||
@@ -116,6 +151,8 @@ pub struct ConfigFile {
|
||||
#[serde(default = "default_terminal_font_family")]
|
||||
pub terminal_font_family: String,
|
||||
#[serde(default)]
|
||||
pub title_bar_style: TitleBarStyle,
|
||||
#[serde(default)]
|
||||
pub sessions: Vec<Session>,
|
||||
#[serde(default)]
|
||||
pub window_bounds: Option<SavedWindowBounds>,
|
||||
@@ -129,22 +166,60 @@ pub struct ConfigFile {
|
||||
pub show_hidden_files: bool,
|
||||
#[serde(default = "default_monitoring_position")]
|
||||
pub monitoring_position: String,
|
||||
#[serde(default)]
|
||||
pub sidebar_collapsed: bool,
|
||||
#[serde(default)]
|
||||
pub sftp_panel_minimized: bool,
|
||||
#[serde(default)]
|
||||
pub key_bindings: std::collections::HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub sync_endpoint: String,
|
||||
#[serde(default)]
|
||||
pub sync_username: String,
|
||||
#[serde(default)]
|
||||
pub sync_etag: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sync_device_id: String,
|
||||
#[serde(default)]
|
||||
pub sync_backend: String,
|
||||
#[serde(default)]
|
||||
pub sync_etag_backend: String,
|
||||
#[serde(default)]
|
||||
pub sync_s3_endpoint: String,
|
||||
#[serde(default = "default_s3_region")]
|
||||
pub sync_s3_region: String,
|
||||
#[serde(default)]
|
||||
pub sync_s3_bucket: String,
|
||||
#[serde(default = "default_s3_object_key")]
|
||||
pub sync_s3_object_key: String,
|
||||
}
|
||||
|
||||
fn default_monitoring_position() -> String {
|
||||
"Sidebar".to_string()
|
||||
}
|
||||
|
||||
fn default_s3_region() -> String {
|
||||
"us-east-1".to_string()
|
||||
}
|
||||
|
||||
fn default_s3_object_key() -> String {
|
||||
"ashell-sync.json".to_string()
|
||||
}
|
||||
|
||||
fn default_follow_system_theme() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_locale() -> String {
|
||||
"system".to_string()
|
||||
}
|
||||
|
||||
fn default_terminal_font_size() -> f32 {
|
||||
13.0
|
||||
18.0
|
||||
}
|
||||
|
||||
fn default_ui_font_size() -> f32 {
|
||||
12.0
|
||||
14.0
|
||||
}
|
||||
|
||||
pub fn default_ui_font_family() -> String {
|
||||
@@ -183,21 +258,47 @@ impl ConfigStore {
|
||||
let _ = fs::create_dir_all(&tmp_dir);
|
||||
}
|
||||
|
||||
let cache = if path.exists() {
|
||||
let mut cache = if path.exists() {
|
||||
let raw = fs::read_to_string(&path)
|
||||
.with_context(|| format!("failed to read {}", path.display()))?;
|
||||
serde_json::from_str::<ConfigFile>(&raw).unwrap_or_default()
|
||||
match serde_json::from_str::<ConfigFile>(&raw) {
|
||||
Ok(cache) => cache,
|
||||
Err(err) => {
|
||||
let backup_path = path.with_extension("json.bak");
|
||||
if let Err(backup_err) = fs::write(&backup_path, raw.as_bytes()) {
|
||||
tracing::warn!(
|
||||
"failed to parse config {}; backup to {} also failed: {backup_err:#}; parse error: {err:#}",
|
||||
path.display(),
|
||||
backup_path.display(),
|
||||
);
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"failed to parse config {}; backed up the original to {} and loaded defaults: {err:#}",
|
||||
path.display(),
|
||||
backup_path.display(),
|
||||
);
|
||||
}
|
||||
ConfigFile::default()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ConfigFile::default()
|
||||
};
|
||||
|
||||
if cache.sync_device_id.is_empty() {
|
||||
cache.sync_device_id = Uuid::new_v4().to_string();
|
||||
}
|
||||
Ok(Self { path, cache })
|
||||
}
|
||||
|
||||
pub fn in_memory() -> Self {
|
||||
let cache = ConfigFile {
|
||||
sync_device_id: Uuid::new_v4().to_string(),
|
||||
..ConfigFile::default()
|
||||
};
|
||||
Self {
|
||||
path: PathBuf::new(),
|
||||
cache: ConfigFile::default(),
|
||||
cache,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +315,79 @@ impl ConfigStore {
|
||||
&self.cache.sessions
|
||||
}
|
||||
|
||||
pub fn replace_sessions(&mut self, sessions: Vec<Session>) {
|
||||
self.cache.sessions = sessions;
|
||||
}
|
||||
|
||||
pub fn sync_endpoint(&self) -> &str {
|
||||
&self.cache.sync_endpoint
|
||||
}
|
||||
|
||||
pub fn sync_username(&self) -> &str {
|
||||
&self.cache.sync_username
|
||||
}
|
||||
|
||||
pub fn sync_etag(&self) -> Option<&str> {
|
||||
(self.cache.sync_etag_backend == self.sync_backend())
|
||||
.then_some(self.cache.sync_etag.as_deref())
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub fn sync_device_id(&self) -> &str {
|
||||
&self.cache.sync_device_id
|
||||
}
|
||||
|
||||
pub fn sync_backend(&self) -> &str {
|
||||
if self.cache.sync_backend == "s3" {
|
||||
"s3"
|
||||
} else {
|
||||
"webdav"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_sync_backend(&mut self, backend: &str) {
|
||||
self.cache.sync_backend = if backend == "s3" { "s3" } else { "webdav" }.to_string();
|
||||
}
|
||||
|
||||
pub fn sync_s3_endpoint(&self) -> &str {
|
||||
&self.cache.sync_s3_endpoint
|
||||
}
|
||||
|
||||
pub fn sync_s3_region(&self) -> &str {
|
||||
if self.cache.sync_s3_region.is_empty() { "us-east-1" } else { &self.cache.sync_s3_region }
|
||||
}
|
||||
|
||||
pub fn sync_s3_bucket(&self) -> &str {
|
||||
&self.cache.sync_s3_bucket
|
||||
}
|
||||
|
||||
pub fn sync_s3_object_key(&self) -> &str {
|
||||
if self.cache.sync_s3_object_key.is_empty() { "ashell-sync.json" } else { &self.cache.sync_s3_object_key }
|
||||
}
|
||||
|
||||
pub fn set_sync_connection(&mut self, endpoint: String, username: String) {
|
||||
self.cache.sync_endpoint = endpoint;
|
||||
self.cache.sync_username = username;
|
||||
}
|
||||
|
||||
pub fn set_sync_s3_connection(
|
||||
&mut self,
|
||||
endpoint: String,
|
||||
region: String,
|
||||
bucket: String,
|
||||
object_key: String,
|
||||
) {
|
||||
self.cache.sync_s3_endpoint = endpoint;
|
||||
self.cache.sync_s3_region = region;
|
||||
self.cache.sync_s3_bucket = bucket;
|
||||
self.cache.sync_s3_object_key = object_key;
|
||||
}
|
||||
|
||||
pub fn set_sync_etag(&mut self, etag: Option<String>) {
|
||||
self.cache.sync_etag = etag;
|
||||
self.cache.sync_etag_backend = self.sync_backend().to_string();
|
||||
}
|
||||
|
||||
pub fn tmp_dir(&self) -> Option<PathBuf> {
|
||||
self.path.parent().map(|p| p.join("tmp"))
|
||||
}
|
||||
@@ -246,8 +420,22 @@ impl ConfigStore {
|
||||
self.cache.locale = locale.to_string();
|
||||
}
|
||||
|
||||
pub fn key_bindings(&self) -> &std::collections::HashMap<String, String> {
|
||||
&self.cache.key_bindings
|
||||
}
|
||||
|
||||
pub fn set_key_binding(&mut self, action_name: &str, keystroke: &str) {
|
||||
self.cache
|
||||
.key_bindings
|
||||
.insert(action_name.to_string(), keystroke.to_string());
|
||||
}
|
||||
|
||||
pub fn monitoring_position(&self) -> &str {
|
||||
&self.cache.monitoring_position
|
||||
if self.cache.monitoring_position.is_empty() {
|
||||
"Sidebar"
|
||||
} else {
|
||||
&self.cache.monitoring_position
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_monitoring_position(&mut self, pos: &str) {
|
||||
@@ -358,6 +546,14 @@ impl ConfigStore {
|
||||
self.cache.terminal_font_family = family.to_string();
|
||||
}
|
||||
|
||||
pub fn title_bar_style(&self) -> TitleBarStyle {
|
||||
self.cache.title_bar_style
|
||||
}
|
||||
|
||||
pub fn set_title_bar_style(&mut self, style: TitleBarStyle) {
|
||||
self.cache.title_bar_style = style;
|
||||
}
|
||||
|
||||
pub fn show_hidden_files(&self) -> bool {
|
||||
self.cache.show_hidden_files
|
||||
}
|
||||
@@ -366,6 +562,22 @@ impl ConfigStore {
|
||||
self.cache.show_hidden_files = val;
|
||||
}
|
||||
|
||||
pub fn sidebar_collapsed(&self) -> bool {
|
||||
self.cache.sidebar_collapsed
|
||||
}
|
||||
|
||||
pub fn set_sidebar_collapsed(&mut self, val: bool) {
|
||||
self.cache.sidebar_collapsed = val;
|
||||
}
|
||||
|
||||
pub fn sftp_panel_minimized(&self) -> bool {
|
||||
self.cache.sftp_panel_minimized
|
||||
}
|
||||
|
||||
pub fn set_sftp_panel_minimized(&mut self, val: bool) {
|
||||
self.cache.sftp_panel_minimized = val;
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> Option<&Session> {
|
||||
self.cache.sessions.iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
+186
-74
@@ -1,13 +1,10 @@
|
||||
pub mod config;
|
||||
|
||||
use gpui::{
|
||||
App, AppContext as _, Context, Entity, KeyDownEvent, MouseButton,
|
||||
MouseDownEvent, MouseMoveEvent, SharedString, Window, px,
|
||||
};
|
||||
use gpui_component::{
|
||||
Theme, WindowExt as _,
|
||||
input::InputState,
|
||||
App, AppContext as _, Context, Entity, KeyDownEvent, MouseButton, MouseDownEvent,
|
||||
MouseMoveEvent, SharedString, Window, px,
|
||||
};
|
||||
use gpui_component::{Theme, WindowExt as _, input::InputState};
|
||||
use rust_i18n::t;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -15,9 +12,12 @@ use self::config::{AuthMethod, Session};
|
||||
|
||||
use crate::{
|
||||
Ashell, ConnectionProgress, PaneLayout, SelectorEntry, TabGroup,
|
||||
app::constants::{
|
||||
DEFAULT_COLS, DEFAULT_ROWS, SIDEBAR_WIDTH, TAB_BAR_HEIGHT, TERMINAL_PADDING_X,
|
||||
TERMINAL_PADDING_Y,
|
||||
},
|
||||
backend::{local, ssh},
|
||||
terminal::{BackendCommand, RenderSnapshot, TabKind, TerminalTab},
|
||||
app::constants::{DEFAULT_COLS, DEFAULT_ROWS, SIDEBAR_WIDTH, TAB_BAR_HEIGHT, TERMINAL_PADDING_X, TERMINAL_PADDING_Y},
|
||||
};
|
||||
|
||||
impl Ashell {
|
||||
@@ -57,6 +57,7 @@ impl Ashell {
|
||||
}
|
||||
|
||||
pub(crate) fn connect_ssh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
tracing::info!("[ui] user initiating new ssh connection from form");
|
||||
let session_name = self.session_name_input.read(cx).value().trim().to_string();
|
||||
let host = self.host_input.read(cx).value().trim().to_string();
|
||||
let port = self
|
||||
@@ -70,6 +71,7 @@ impl Ashell {
|
||||
let password = self.password_input.read(cx).value().to_string();
|
||||
let key_path = self.key_path_input.read(cx).value().trim().to_string();
|
||||
let key_inline = self.key_inline_input.read(cx).value().to_string();
|
||||
let passphrase = self.passphrase_input.read(cx).value().to_string();
|
||||
|
||||
if host.is_empty() || user.is_empty() {
|
||||
self.status = t!("host_and_user_required").into();
|
||||
@@ -96,8 +98,9 @@ impl Ashell {
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
Session::key(host, port, user, key_path, key_inline)
|
||||
Session::key(host, port, user, key_path, key_inline, passphrase)
|
||||
}
|
||||
AuthMethod::KeyboardInteractive => Session::keyboard_interactive(host, port, user),
|
||||
};
|
||||
session.name = name;
|
||||
if let Some(id) = existing_id {
|
||||
@@ -111,7 +114,9 @@ impl Ashell {
|
||||
|
||||
self.open_ssh_session(session, cx);
|
||||
self.editing_session_id = None;
|
||||
self.active_dialog = None;
|
||||
window.close_dialog(cx);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(crate) fn set_input_value(
|
||||
@@ -133,6 +138,7 @@ impl Ashell {
|
||||
Self::set_input_value(&self.password_input, "", window, cx);
|
||||
Self::set_input_value(&self.key_path_input, "", window, cx);
|
||||
Self::set_input_value(&self.key_inline_input, "", window, cx);
|
||||
Self::set_input_value(&self.passphrase_input, "", window, cx);
|
||||
}
|
||||
|
||||
pub(crate) fn load_session_into_form(
|
||||
@@ -160,6 +166,12 @@ impl Ashell {
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
Self::set_input_value(
|
||||
&self.passphrase_input,
|
||||
session.passphrase.clone(),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn pick_ssh_key_path(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
@@ -222,7 +234,12 @@ impl Ashell {
|
||||
};
|
||||
self.load_session_into_form(&session, window, cx);
|
||||
self.editing_session_id = None;
|
||||
Self::set_input_value(&self.session_name_input, format!("{}-copy", session.name), window, cx);
|
||||
Self::set_input_value(
|
||||
&self.session_name_input,
|
||||
format!("{}-copy", session.name),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
self.show_ssh_dialog(window, cx);
|
||||
}
|
||||
|
||||
@@ -284,10 +301,10 @@ impl Ashell {
|
||||
self.config.set_layout_state(None, None, None);
|
||||
let _ = self.config.save();
|
||||
|
||||
self.is_layout_reset = true;
|
||||
self.workspace_panels = cx.new(|_| gpui_component::resizable::ResizableState::default());
|
||||
self.body_panels = cx.new(|_| gpui_component::resizable::ResizableState::default());
|
||||
|
||||
self.status = t!("reset_layout_success").into();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
@@ -297,6 +314,10 @@ impl Ashell {
|
||||
}
|
||||
|
||||
pub(crate) fn connect_saved_session(&mut self, session_id: String, cx: &mut Context<Self>) {
|
||||
tracing::info!(
|
||||
"[ui] user clicked to connect saved session '{}'",
|
||||
session_id
|
||||
);
|
||||
let Some(session) = self.config.get(&session_id).cloned() else {
|
||||
self.status = "saved session not found".into();
|
||||
cx.notify();
|
||||
@@ -340,12 +361,17 @@ impl Ashell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn activate_selector_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(crate) fn activate_selector_selection(
|
||||
&mut self,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let entries = self.selector_entries();
|
||||
let Some(entry) = entries.get(self.selector_selection).cloned() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.active_dialog = None;
|
||||
match entry {
|
||||
SelectorEntry::Local => {
|
||||
self.open_local(cx);
|
||||
@@ -360,6 +386,7 @@ impl Ashell {
|
||||
window.close_dialog(cx);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(crate) fn on_selector_key_down(
|
||||
@@ -390,6 +417,12 @@ impl Ashell {
|
||||
}
|
||||
|
||||
pub(crate) fn open_ssh_session(&mut self, session: Session, cx: &mut Context<Self>) {
|
||||
tracing::info!(
|
||||
"[session] opening ssh tab for session '{}' ({}@{})",
|
||||
session.name,
|
||||
session.user,
|
||||
session.host
|
||||
);
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let backend = ssh::spawn_ssh_terminal(
|
||||
self.runtime.handle(),
|
||||
@@ -426,7 +459,12 @@ impl Ashell {
|
||||
self.active_group = Some(group_id.clone());
|
||||
self.tabs_scroll_handle.scroll_to_item(self.tabs.len() - 1);
|
||||
if let Some(session_id) = self.active_session_id() {
|
||||
if let Some(index) = self.config.sessions().iter().position(|s| s.id == session_id) {
|
||||
if let Some(index) = self
|
||||
.config
|
||||
.sessions()
|
||||
.iter()
|
||||
.position(|s| s.id == session_id)
|
||||
{
|
||||
self.saved_scroll_handle.scroll_to_item(index);
|
||||
}
|
||||
}
|
||||
@@ -493,15 +531,15 @@ impl Ashell {
|
||||
);
|
||||
|
||||
// Replace tab state in-place to reuse the UI component
|
||||
self.tabs[ix] = TerminalTab::new_ssh(
|
||||
tab_id.clone(),
|
||||
&session,
|
||||
backend,
|
||||
self.events_tx.clone(),
|
||||
);
|
||||
self.tabs[ix] =
|
||||
TerminalTab::new_ssh(tab_id.clone(), &session, backend, self.events_tx.clone());
|
||||
|
||||
// Find group to restart SFTP
|
||||
if let Some(group) = self.tab_groups.iter().find(|g| g.pane_root.contains(&tab_id)) {
|
||||
if let Some(group) = self
|
||||
.tab_groups
|
||||
.iter()
|
||||
.find(|g| g.pane_root.contains(&tab_id))
|
||||
{
|
||||
groups_to_restart_sftp.insert(group.id.clone());
|
||||
}
|
||||
}
|
||||
@@ -510,8 +548,12 @@ impl Ashell {
|
||||
for group_id in groups_to_restart_sftp {
|
||||
if let Some(group) = self.tab_groups.iter_mut().find(|g| g.id == group_id) {
|
||||
// Use the session of any tab in that group
|
||||
let group_session = self.tabs.iter().find(|t| group.pane_root.contains(&t.id) && t.session.is_some()).and_then(|t| t.session.clone());
|
||||
|
||||
let group_session = self
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|t| group.pane_root.contains(&t.id) && t.session.is_some())
|
||||
.and_then(|t| t.session.clone());
|
||||
|
||||
if let Some(session) = group_session {
|
||||
if let Some(old_handle) = self.sftp_handles.remove(&group.id) {
|
||||
old_handle.close();
|
||||
@@ -523,7 +565,7 @@ impl Ashell {
|
||||
self.events_tx.clone(),
|
||||
);
|
||||
self.sftp_handles.insert(group.id.clone(), sftp_handle);
|
||||
|
||||
|
||||
if let Some(sftp) = group.sftp.as_mut() {
|
||||
sftp.status = rust_i18n::t!("sftp_connecting").to_string();
|
||||
}
|
||||
@@ -546,7 +588,9 @@ impl Ashell {
|
||||
return;
|
||||
}
|
||||
self.connection_progress = None;
|
||||
let tabs_to_close: Vec<_> = self.tabs.iter()
|
||||
let tabs_to_close: Vec<_> = self
|
||||
.tabs
|
||||
.iter()
|
||||
.filter(|tab| !tab.connected && tab.session.is_some())
|
||||
.map(|tab| tab.id.clone())
|
||||
.collect();
|
||||
@@ -566,7 +610,10 @@ impl Ashell {
|
||||
}
|
||||
self.active_tab = Some(id.clone());
|
||||
// Find which group this tab belongs to and restore its pane_root
|
||||
let tab_group = self.tab_groups.iter_mut().find(|g| g.pane_root.contains(&id));
|
||||
let tab_group = self
|
||||
.tab_groups
|
||||
.iter_mut()
|
||||
.find(|g| g.pane_root.contains(&id));
|
||||
if let Some(group) = tab_group {
|
||||
self.pane_root = group.pane_root.clone();
|
||||
self.active_group = Some(group.id.clone());
|
||||
@@ -581,7 +628,12 @@ impl Ashell {
|
||||
}
|
||||
if self.tabs.iter().any(|t| t.id == id) {
|
||||
if let Some(session_id) = self.active_session_id() {
|
||||
if let Some(index) = self.config.sessions().iter().position(|s| s.id == session_id) {
|
||||
if let Some(index) = self
|
||||
.config
|
||||
.sessions()
|
||||
.iter()
|
||||
.position(|s| s.id == session_id)
|
||||
{
|
||||
self.saved_scroll_handle.scroll_to_item(index);
|
||||
}
|
||||
}
|
||||
@@ -597,10 +649,16 @@ impl Ashell {
|
||||
}
|
||||
|
||||
pub(crate) fn handle_tab_close(&mut self, id: String) {
|
||||
let group_ix = self.tab_groups.iter().position(|g| g.pane_root.contains(&id));
|
||||
let group_ix = self
|
||||
.tab_groups
|
||||
.iter()
|
||||
.position(|g| g.pane_root.contains(&id));
|
||||
let Some(ref group) = group_ix.map(|i| self.tab_groups[i].clone()) else {
|
||||
// Fallback: find and close individual tab
|
||||
eprintln!("[handle_tab_close] no group found for tab '{}', closing individually", id);
|
||||
tracing::info!(
|
||||
"[handle_tab_close] no group found for tab '{}', closing individually",
|
||||
id
|
||||
);
|
||||
if let Some(ix) = self.tabs.iter().position(|tab| tab.id == id) {
|
||||
self.tabs[ix].backend.send(BackendCommand::Close);
|
||||
self.tabs.remove(ix);
|
||||
@@ -611,9 +669,11 @@ impl Ashell {
|
||||
let pane_ids = group.pane_root.tab_ids();
|
||||
let pane_ids_str: Vec<&str> = pane_ids.iter().map(|s| *s).collect();
|
||||
let is_group_close = pane_ids.len() <= 1;
|
||||
eprintln!(
|
||||
tracing::info!(
|
||||
"[handle_tab_close] id='{}' group_panes={:?} is_group_close={}",
|
||||
id, pane_ids_str, is_group_close
|
||||
id,
|
||||
pane_ids_str,
|
||||
is_group_close
|
||||
);
|
||||
|
||||
let was_active = self.active_tab.as_deref() == Some(id.as_str());
|
||||
@@ -632,16 +692,31 @@ impl Ashell {
|
||||
let all_groups = &self.tab_groups;
|
||||
if let Some(pos) = all_groups.iter().position(|g| g.id == group.id) {
|
||||
if pos > 0 {
|
||||
next_active_id = all_groups[pos - 1].pane_root.tab_ids().first().copied().map(String::from);
|
||||
next_active_id = all_groups[pos - 1]
|
||||
.pane_root
|
||||
.tab_ids()
|
||||
.first()
|
||||
.copied()
|
||||
.map(String::from);
|
||||
} else if pos + 1 < all_groups.len() {
|
||||
next_active_id = all_groups[pos + 1].pane_root.tab_ids().first().copied().map(String::from);
|
||||
next_active_id = all_groups[pos + 1]
|
||||
.pane_root
|
||||
.tab_ids()
|
||||
.first()
|
||||
.copied()
|
||||
.map(String::from);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_group_close {
|
||||
// Close all tabs in the group
|
||||
let tab_ids: Vec<String> = group.pane_root.tab_ids().iter().map(|s| s.to_string()).collect();
|
||||
let tab_ids: Vec<String> = group
|
||||
.pane_root
|
||||
.tab_ids()
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
for tab_id in &tab_ids {
|
||||
if let Some(ix) = self.tabs.iter().position(|tab| tab.id == *tab_id) {
|
||||
self.tabs[ix].backend.send(BackendCommand::Close);
|
||||
@@ -659,7 +734,11 @@ impl Ashell {
|
||||
self.tabs[ix].backend.send(BackendCommand::Close);
|
||||
self.tabs.retain(|t| t.id != id);
|
||||
}
|
||||
if let Some(g) = self.tab_groups.iter_mut().find(|g| g.pane_root.contains(&id)) {
|
||||
if let Some(g) = self
|
||||
.tab_groups
|
||||
.iter_mut()
|
||||
.find(|g| g.pane_root.contains(&id))
|
||||
{
|
||||
g.pane_root.remove_tab(&id);
|
||||
}
|
||||
self.pane_root.remove_tab(&id);
|
||||
@@ -684,9 +763,6 @@ impl Ashell {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
if was_active
|
||||
|| self
|
||||
.active_tab
|
||||
@@ -695,12 +771,20 @@ impl Ashell {
|
||||
{
|
||||
// Activate next available pane
|
||||
let new_id = next_active_id.or_else(|| {
|
||||
self.pane_root.tab_ids().first().copied().map(String::from)
|
||||
self.pane_root
|
||||
.tab_ids()
|
||||
.first()
|
||||
.copied()
|
||||
.map(String::from)
|
||||
.or_else(|| self.tabs.first().map(|t| t.id.clone()))
|
||||
});
|
||||
if let Some(new_id) = new_id {
|
||||
self.active_tab = Some(new_id.clone());
|
||||
if let Some(g) = self.tab_groups.iter().find(|g| g.pane_root.contains(&new_id)) {
|
||||
if let Some(g) = self
|
||||
.tab_groups
|
||||
.iter()
|
||||
.find(|g| g.pane_root.contains(&new_id))
|
||||
{
|
||||
self.active_group = Some(g.id.clone());
|
||||
self.pane_root = g.pane_root.clone();
|
||||
}
|
||||
@@ -796,28 +880,33 @@ impl Ashell {
|
||||
.first()
|
||||
.map(|size| size.as_f32())
|
||||
.unwrap_or(SIDEBAR_WIDTH);
|
||||
let terminal_height = self
|
||||
.body_panels
|
||||
.read(cx)
|
||||
.sizes()
|
||||
.first()
|
||||
.map(|size| size.as_f32())
|
||||
.unwrap_or(viewport.height.as_f32() - TAB_BAR_HEIGHT - 248.0);
|
||||
let width = (viewport.width.as_f32() - sidebar_width - TERMINAL_PADDING_X - 8.0)
|
||||
.max(self.terminal_cell_width());
|
||||
let height = (terminal_height - TERMINAL_PADDING_Y).max(self.terminal_line_height());
|
||||
|
||||
// Use the whole terminal panel bounds for PTY sizing.
|
||||
// Individual pane bounds are smaller when split, so using them here
|
||||
// would shrink the root PTY dimensions a second time.
|
||||
let (width, height) = if let Some(bounds) = self.terminal_panel_bounds {
|
||||
(bounds.size.width.as_f32(), bounds.size.height.as_f32())
|
||||
} else {
|
||||
let terminal_height = self
|
||||
.body_panels
|
||||
.read(cx)
|
||||
.sizes()
|
||||
.first()
|
||||
.map(|size| size.as_f32())
|
||||
.unwrap_or(viewport.height.as_f32() - TAB_BAR_HEIGHT - 248.0);
|
||||
(
|
||||
(viewport.width.as_f32() - sidebar_width - TERMINAL_PADDING_X - 8.0)
|
||||
.max(self.terminal_cell_width()),
|
||||
(terminal_height - TERMINAL_PADDING_Y).max(self.terminal_line_height()),
|
||||
)
|
||||
};
|
||||
let total_cols = (width / self.terminal_cell_width()).floor().max(1.0) as u16;
|
||||
let total_rows = (height / self.terminal_line_height()).floor().max(1.0) as u16;
|
||||
|
||||
Self::resize_pane_tree(&mut self.tabs, &self.pane_root, total_cols, total_rows);
|
||||
}
|
||||
|
||||
fn resize_pane_tree(
|
||||
tabs: &mut [TerminalTab],
|
||||
layout: &PaneLayout,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
) {
|
||||
fn resize_pane_tree(tabs: &mut [TerminalTab], layout: &PaneLayout, cols: u16, rows: u16) {
|
||||
match layout {
|
||||
PaneLayout::Single(id) => {
|
||||
if let Some(tab) = tabs.iter_mut().find(|t| t.id == *id) {
|
||||
@@ -842,7 +931,7 @@ impl Ashell {
|
||||
}
|
||||
|
||||
pub(crate) fn split_current_pane(&mut self, direction: &str, cx: &mut Context<Self>) {
|
||||
eprintln!(
|
||||
tracing::info!(
|
||||
"[split] direction={} pane_root={:?} focused_path={:?} active_tab={:?} tabs={}",
|
||||
direction,
|
||||
self.pane_root,
|
||||
@@ -902,12 +991,7 @@ impl Ashell {
|
||||
self.events_tx.clone(),
|
||||
);
|
||||
self.sftp_handles.insert(new_id.clone(), sftp_handle);
|
||||
TerminalTab::new_ssh(
|
||||
new_id.clone(),
|
||||
&session,
|
||||
backend,
|
||||
self.events_tx.clone(),
|
||||
)
|
||||
TerminalTab::new_ssh(new_id.clone(), &session, backend, self.events_tx.clone())
|
||||
}
|
||||
};
|
||||
tab.resize(DEFAULT_COLS, DEFAULT_ROWS);
|
||||
@@ -936,7 +1020,8 @@ impl Ashell {
|
||||
_ => return,
|
||||
};
|
||||
|
||||
self.pane_root.replace_at(&self.focused_pane_path, split_layout);
|
||||
self.pane_root
|
||||
.replace_at(&self.focused_pane_path, split_layout);
|
||||
self.sync_pane_root_to_group();
|
||||
// Update focused_pane_path: the new pane is at the indicated child index
|
||||
let parent_path = self.focused_pane_path.clone();
|
||||
@@ -949,7 +1034,7 @@ impl Ashell {
|
||||
self.focused_pane_path = new_full_path;
|
||||
self.active_tab = Some(new_id);
|
||||
self.status = "pane split".into();
|
||||
eprintln!(
|
||||
tracing::info!(
|
||||
"[split] DONE: pane_root={:?} focused_path={:?} active_tab={:?} tabs={}",
|
||||
self.pane_root,
|
||||
self.focused_pane_path,
|
||||
@@ -998,7 +1083,11 @@ impl Ashell {
|
||||
}
|
||||
}
|
||||
|
||||
fn find_adjacent_pane(layout: &PaneLayout, path: &[usize], direction: &str) -> Option<Vec<usize>> {
|
||||
fn find_adjacent_pane(
|
||||
layout: &PaneLayout,
|
||||
path: &[usize],
|
||||
direction: &str,
|
||||
) -> Option<Vec<usize>> {
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -1020,7 +1109,11 @@ impl Ashell {
|
||||
if path.len() == 1 {
|
||||
// Direct child level
|
||||
if moves_in_this_split {
|
||||
let delta: i32 = if direction == "up" || direction == "left" { -1 } else { 1 };
|
||||
let delta: i32 = if direction == "up" || direction == "left" {
|
||||
-1
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let new_idx = idx as i32 + delta;
|
||||
if new_idx >= 0 && (new_idx as usize) < children.len() {
|
||||
let mut path = vec![new_idx as usize];
|
||||
@@ -1034,17 +1127,26 @@ impl Ashell {
|
||||
}
|
||||
} else {
|
||||
// Recurse into child first
|
||||
if let Some(mut child_path) = Self::find_adjacent_pane(&children[idx], &path[1..], direction) {
|
||||
if let Some(mut child_path) =
|
||||
Self::find_adjacent_pane(&children[idx], &path[1..], direction)
|
||||
{
|
||||
child_path.insert(0, idx);
|
||||
Some(child_path)
|
||||
} else if moves_in_this_split {
|
||||
// Try sibling at this level
|
||||
let delta: i32 = if direction == "up" || direction == "left" { -1 } else { 1 };
|
||||
let delta: i32 = if direction == "up" || direction == "left" {
|
||||
-1
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let new_idx = idx as i32 + delta;
|
||||
if new_idx >= 0 && (new_idx as usize) < children.len() {
|
||||
let inner_idx = *path.get(1).unwrap_or(&0);
|
||||
let mut path = vec![new_idx as usize];
|
||||
path.extend(Self::leaf_at_index(&children[new_idx as usize], inner_idx));
|
||||
path.extend(Self::leaf_at_index(
|
||||
&children[new_idx as usize],
|
||||
inner_idx,
|
||||
));
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
@@ -1065,7 +1167,11 @@ impl Ashell {
|
||||
) {
|
||||
// Save current group state
|
||||
if let Some(current_group_id) = self.active_group.clone() {
|
||||
if let Some(group) = self.tab_groups.iter_mut().find(|g| g.id == current_group_id) {
|
||||
if let Some(group) = self
|
||||
.tab_groups
|
||||
.iter_mut()
|
||||
.find(|g| g.id == current_group_id)
|
||||
{
|
||||
group.pane_root = self.pane_root.clone();
|
||||
}
|
||||
}
|
||||
@@ -1108,7 +1214,8 @@ impl Ashell {
|
||||
}
|
||||
|
||||
// Check if current system_tab_id is valid in this group
|
||||
let is_current_valid = self.system_tab_id
|
||||
let is_current_valid = self
|
||||
.system_tab_id
|
||||
.as_ref()
|
||||
.map_or(false, |id| group_ssh_tabs.contains(id));
|
||||
|
||||
@@ -1184,15 +1291,20 @@ impl Ashell {
|
||||
match (layout, path) {
|
||||
(PaneLayout::Horizontal(_, _), []) => true,
|
||||
(PaneLayout::Vertical(_, _), []) => false,
|
||||
(PaneLayout::Horizontal(children, _) | PaneLayout::Vertical(children, _), [first, rest @ ..]) => {
|
||||
children.get(*first).map_or(false, |c| Self::is_layout_horizontal_at(c, rest))
|
||||
}
|
||||
(
|
||||
PaneLayout::Horizontal(children, _) | PaneLayout::Vertical(children, _),
|
||||
[first, rest @ ..],
|
||||
) => children
|
||||
.get(*first)
|
||||
.map_or(false, |c| Self::is_layout_horizontal_at(c, rest)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn adjust_split_ratio(layout: &mut PaneLayout, path: &[usize], _child_idx: usize, delta: f32) {
|
||||
if let PaneLayout::Horizontal(children, ratio) | PaneLayout::Vertical(children, ratio) = layout {
|
||||
if let PaneLayout::Horizontal(children, ratio) | PaneLayout::Vertical(children, ratio) =
|
||||
layout
|
||||
{
|
||||
if path.is_empty() {
|
||||
*ratio = (*ratio + delta).clamp(0.1, 0.9);
|
||||
} else {
|
||||
|
||||
+209
-40
@@ -258,7 +258,7 @@ async fn run_sftp(
|
||||
.canonicalize(".")
|
||||
.await
|
||||
.unwrap_or_else(|_| "/".to_string());
|
||||
|
||||
|
||||
let _ = events.send(BackendEvent::SftpHome {
|
||||
tab_id: tab_id.clone(),
|
||||
home: home.clone(),
|
||||
@@ -379,16 +379,28 @@ async fn run_sftp(
|
||||
}
|
||||
Err(err) => {
|
||||
let err_msg = format!("{err:#}");
|
||||
let is_cancelled = err_msg.contains("transfer cancelled");
|
||||
let state = if is_cancelled {
|
||||
crate::terminal::TransferState::Interrupted(
|
||||
"User cancelled".to_string(),
|
||||
)
|
||||
} else {
|
||||
crate::terminal::TransferState::Failed(err_msg.clone())
|
||||
};
|
||||
let _ = events_clone.send(BackendEvent::SftpStatus {
|
||||
tab_id: tab_id_clone.clone(),
|
||||
text: t!("download_failed", err = err_msg.clone()).to_string(),
|
||||
text: if is_cancelled {
|
||||
"Transmission cancelled".to_string()
|
||||
} else {
|
||||
t!("download_failed", err = err_msg.clone()).to_string()
|
||||
},
|
||||
});
|
||||
let _ = events_clone.send(BackendEvent::TransferProgress {
|
||||
tab_id: tab_id_clone,
|
||||
id: id.clone(),
|
||||
transferred: 0,
|
||||
total: None,
|
||||
state: crate::terminal::TransferState::Failed(err_msg),
|
||||
state,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -480,16 +492,28 @@ async fn run_sftp(
|
||||
}
|
||||
Err(err) => {
|
||||
let err_msg = format!("{err:#}");
|
||||
let is_cancelled = err_msg.contains("transfer cancelled");
|
||||
let state = if is_cancelled {
|
||||
crate::terminal::TransferState::Interrupted(
|
||||
"User cancelled".to_string(),
|
||||
)
|
||||
} else {
|
||||
crate::terminal::TransferState::Failed(err_msg.clone())
|
||||
};
|
||||
let _ = events_clone.send(BackendEvent::SftpStatus {
|
||||
tab_id: tab_id_clone.clone(),
|
||||
text: t!("upload_failed", err = err_msg.clone()).to_string(),
|
||||
text: if is_cancelled {
|
||||
"Transmission cancelled".to_string()
|
||||
} else {
|
||||
t!("upload_failed", err = err_msg.clone()).to_string()
|
||||
},
|
||||
});
|
||||
let _ = events_clone.send(BackendEvent::TransferProgress {
|
||||
tab_id: tab_id_clone,
|
||||
id: id.clone(),
|
||||
transferred: 0,
|
||||
total: None,
|
||||
state: crate::terminal::TransferState::Failed(err_msg),
|
||||
state,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -575,10 +599,13 @@ async fn run_sftp(
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
while let Ok(_) = rx.try_recv() {} // drain pending
|
||||
|
||||
if commands_tx_clone.send(SftpCommand::UploadEditedFile {
|
||||
local_path: local_path.to_string_lossy().to_string(),
|
||||
remote_path: remote_path.clone(),
|
||||
}).is_err() {
|
||||
if commands_tx_clone
|
||||
.send(SftpCommand::UploadEditedFile {
|
||||
local_path: local_path.to_string_lossy().to_string(),
|
||||
remote_path: remote_path.clone(),
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -622,7 +649,11 @@ async fn run_sftp(
|
||||
let now = chrono::Local::now().format("%H:%M:%S");
|
||||
let _ = events_clone.send(BackendEvent::SftpStatus {
|
||||
tab_id: tab_id_clone.clone(),
|
||||
text: format!("{} ({})", t!("auto_saved_and_uploaded", base = base_name(&remote_path)), now),
|
||||
text: format!(
|
||||
"{} ({})",
|
||||
t!("auto_saved_and_uploaded", base = base_name(&remote_path)),
|
||||
now
|
||||
),
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -643,13 +674,16 @@ async fn run_sftp(
|
||||
path.clone()
|
||||
};
|
||||
|
||||
tracing::info!("[sftp] creating directory: '{}'", actual_path);
|
||||
|
||||
match sftp.create_dir(&actual_path).await {
|
||||
Ok(_) => {
|
||||
let _ = events.send(BackendEvent::SftpStatus {
|
||||
tab_id: tab_id.clone(),
|
||||
text: t!("create_folder_success", name = base_name(&actual_path)).to_string(),
|
||||
text: t!("create_folder_success", name = base_name(&actual_path))
|
||||
.to_string(),
|
||||
});
|
||||
|
||||
|
||||
// Re-fetch the parent directory to show the newly created folder
|
||||
if let Some(parent) = parent_dir(&actual_path) {
|
||||
let _ = commands_tx.send(SftpCommand::ListDir(parent));
|
||||
@@ -666,6 +700,7 @@ async fn run_sftp(
|
||||
}
|
||||
}
|
||||
SftpCommand::DeletePaths(paths) => {
|
||||
tracing::info!("[sftp] batch deleting {} paths", paths.len());
|
||||
let _ = events.send(BackendEvent::SftpStatus {
|
||||
tab_id: tab_id.clone(),
|
||||
text: t!("deleting_paths", count = paths.len()).to_string(),
|
||||
@@ -738,21 +773,27 @@ fn recursive_delete<'a>(
|
||||
continue;
|
||||
}
|
||||
let child_path = crate::sftp::join_remote(&path, &name);
|
||||
|
||||
|
||||
let meta = entry.metadata();
|
||||
let permissions = meta.permissions.unwrap_or(0);
|
||||
let is_dir = (permissions & 0o170_000) == 0o040_000;
|
||||
|
||||
|
||||
if is_dir {
|
||||
recursive_delete(sftp, child_path).await?;
|
||||
} else {
|
||||
sftp.remove_file(&child_path).await.with_context(|| format!("Failed to delete file {child_path}"))?;
|
||||
sftp.remove_file(&child_path)
|
||||
.await
|
||||
.with_context(|| format!("Failed to delete file {child_path}"))?;
|
||||
}
|
||||
}
|
||||
sftp.remove_dir(&path).await.with_context(|| format!("Failed to delete dir {path}"))?;
|
||||
sftp.remove_dir(&path)
|
||||
.await
|
||||
.with_context(|| format!("Failed to delete dir {path}"))?;
|
||||
}
|
||||
Err(_) => {
|
||||
sftp.remove_file(&path).await.with_context(|| format!("Failed to delete {path}"))?;
|
||||
sftp.remove_file(&path)
|
||||
.await
|
||||
.with_context(|| format!("Failed to delete {path}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -797,11 +838,63 @@ async fn connect_and_authenticate(
|
||||
.context("password authentication failed")?,
|
||||
AuthMethod::Key => {
|
||||
let keypair = load_session_private_key(session)?;
|
||||
let key = private_key_with_alg(keypair).context("invalid private key")?;
|
||||
handle
|
||||
.authenticate_publickey(&session.user, key)
|
||||
.await
|
||||
.context("public key authentication failed")?
|
||||
let keys = private_keys_with_algs(keypair).context("invalid private key")?;
|
||||
let mut success = false;
|
||||
for key in keys {
|
||||
match handle.authenticate_publickey(&session.user, key).await {
|
||||
Ok(true) => {
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
Ok(false) => {
|
||||
tracing::debug!(
|
||||
"[sftp] public key auth failed with algorithm, trying next"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!("[sftp] public key auth error: {:?}, trying next", e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !success {
|
||||
return Err(anyhow!(
|
||||
"public key authentication failed for {}@{}:{}",
|
||||
session.user,
|
||||
session.host,
|
||||
session.port
|
||||
));
|
||||
}
|
||||
success
|
||||
}
|
||||
AuthMethod::KeyboardInteractive => {
|
||||
let cached_kb_responses = {
|
||||
let cache_lock = crate::backend::ssh::CREDENTIALS_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
|
||||
let cache = cache_lock.lock().unwrap();
|
||||
cache.get(&session.id).and_then(|c| c.kb_responses.clone())
|
||||
};
|
||||
let responses = cached_kb_responses.unwrap_or_else(|| vec![session.password.clone()]);
|
||||
let mut response = handle.authenticate_keyboard_interactive_start(&session.user, None).await?;
|
||||
loop {
|
||||
match response {
|
||||
russh::client::KeyboardInteractiveAuthResponse::Success => {
|
||||
break true;
|
||||
}
|
||||
russh::client::KeyboardInteractiveAuthResponse::Failure => {
|
||||
break false;
|
||||
}
|
||||
russh::client::KeyboardInteractiveAuthResponse::InfoRequest { prompts, .. } => {
|
||||
let mut resp = responses.clone();
|
||||
if resp.len() < prompts.len() {
|
||||
resp.resize(prompts.len(), String::new());
|
||||
} else if resp.len() > prompts.len() {
|
||||
resp.truncate(prompts.len());
|
||||
}
|
||||
response = handle.authenticate_keyboard_interactive_respond(resp).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -814,6 +907,7 @@ async fn connect_and_authenticate(
|
||||
match session.auth {
|
||||
AuthMethod::Password => "password",
|
||||
AuthMethod::Key => "public key",
|
||||
AuthMethod::KeyboardInteractive => "keyboard interactive",
|
||||
},
|
||||
session.user,
|
||||
session.host,
|
||||
@@ -827,6 +921,17 @@ async fn connect_and_authenticate(
|
||||
fn load_session_private_key(session: &Session) -> Result<PrivateKey> {
|
||||
let inline_key = normalize_inline_private_key(&session.private_key_inline);
|
||||
let key_path = expand_key_path(session.private_key_path.trim());
|
||||
let cached_passphrase = {
|
||||
let cache_lock = crate::backend::ssh::CREDENTIALS_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
|
||||
let cache = cache_lock.lock().unwrap();
|
||||
cache.get(&session.id).and_then(|c| c.passphrase.clone())
|
||||
};
|
||||
let passphrase = if let Some(ref p) = cached_passphrase {
|
||||
Some(p.as_str())
|
||||
} else {
|
||||
let p = session.passphrase.trim();
|
||||
(!p.is_empty()).then_some(p)
|
||||
};
|
||||
let has_inline = !inline_key.is_empty();
|
||||
let has_path = key_path.is_some();
|
||||
|
||||
@@ -837,14 +942,14 @@ fn load_session_private_key(session: &Session) -> Result<PrivateKey> {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
if has_inline {
|
||||
match decode_secret_key(&inline_key, None) {
|
||||
match decode_secret_key(&inline_key, passphrase) {
|
||||
Ok(key) => return Ok(key),
|
||||
Err(err) => errors.push(format!("decode private key content: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = key_path {
|
||||
match load_secret_key(path.as_path(), None) {
|
||||
match load_secret_key(path.as_path(), passphrase) {
|
||||
Ok(key) => return Ok(key),
|
||||
Err(err) => errors.push(format!("load key {}: {err}", path.display())),
|
||||
}
|
||||
@@ -853,16 +958,33 @@ fn load_session_private_key(session: &Session) -> Result<PrivateKey> {
|
||||
Err(anyhow!(errors.join("; ")))
|
||||
}
|
||||
|
||||
fn private_key_with_alg(keypair: PrivateKey) -> Result<PrivateKeyWithHashAlg> {
|
||||
let hash_alg = if keypair.algorithm().is_rsa() {
|
||||
Some(HashAlg::Sha512)
|
||||
fn private_keys_with_algs(keypair: PrivateKey) -> Result<Vec<PrivateKeyWithHashAlg>> {
|
||||
let mut algs = Vec::new();
|
||||
let key_arc = Arc::new(keypair);
|
||||
|
||||
if key_arc.algorithm().is_rsa() {
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), Some(HashAlg::Sha512)) {
|
||||
algs.push(k);
|
||||
}
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), Some(HashAlg::Sha256)) {
|
||||
algs.push(k);
|
||||
}
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), None) {
|
||||
algs.push(k);
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(
|
||||
PrivateKeyWithHashAlg::new(Arc::new(keypair.clone()), hash_alg)
|
||||
.or_else(|_| PrivateKeyWithHashAlg::new(Arc::new(keypair), Some(HashAlg::Sha256)))?,
|
||||
)
|
||||
if let Ok(k) = PrivateKeyWithHashAlg::new(key_arc.clone(), None) {
|
||||
algs.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
if algs.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Failed to construct PrivateKeyWithHashAlg for any supported hash algorithm"
|
||||
));
|
||||
}
|
||||
|
||||
Ok(algs)
|
||||
}
|
||||
|
||||
fn normalize_inline_private_key(value: &str) -> String {
|
||||
@@ -1065,6 +1187,12 @@ async fn download_path_impl(
|
||||
.await
|
||||
.with_context(|| format!("create {}", local_dir.display()))?;
|
||||
|
||||
// Check for cancellation after initial setup
|
||||
let state = flag.0.load(Ordering::SeqCst);
|
||||
if state == 2 {
|
||||
return Err(anyhow::anyhow!("transfer cancelled"));
|
||||
}
|
||||
|
||||
let metadata = sftp
|
||||
.metadata(remote)
|
||||
.await
|
||||
@@ -1158,7 +1286,15 @@ async fn download_remote_directory_archive(
|
||||
base_name(remote_dir),
|
||||
Uuid::new_v4()
|
||||
);
|
||||
|
||||
// Check for cancellation before creating remote archive
|
||||
let state = flag.0.load(Ordering::SeqCst);
|
||||
if state == 2 {
|
||||
return Err(anyhow::anyhow!("transfer cancelled"));
|
||||
}
|
||||
|
||||
create_remote_archive(handle, remote_dir, &remote_archive).await?;
|
||||
|
||||
let local_extract_root = local_archive
|
||||
.parent()
|
||||
.unwrap_or_else(|| Path::new("."))
|
||||
@@ -1264,6 +1400,12 @@ async fn upload_paths_impl(
|
||||
tab_id: &str,
|
||||
id: &str,
|
||||
) -> Result<String> {
|
||||
// Check for cancellation before starting
|
||||
let state = flag.0.load(Ordering::SeqCst);
|
||||
if state == 2 {
|
||||
return Err(anyhow::anyhow!("transfer cancelled"));
|
||||
}
|
||||
|
||||
create_remote_dir_all(sftp, remote_dir).await?;
|
||||
let mut file_count = 0usize;
|
||||
let mut folder_count = 0usize;
|
||||
@@ -1316,9 +1458,19 @@ async fn upload_paths_impl(
|
||||
}
|
||||
}
|
||||
|
||||
// Check for cancellation before creating directories
|
||||
let state = flag.0.load(Ordering::SeqCst);
|
||||
if state == 2 {
|
||||
return Err(anyhow::anyhow!("transfer cancelled"));
|
||||
}
|
||||
|
||||
// Create directories sequentially first
|
||||
for dir in dirs_to_create {
|
||||
// Check for cancellation between each directory creation
|
||||
let state = flag.0.load(Ordering::SeqCst);
|
||||
if state == 2 {
|
||||
return Err(anyhow::anyhow!("transfer cancelled"));
|
||||
}
|
||||
create_remote_dir_all(sftp, &dir).await?;
|
||||
}
|
||||
|
||||
@@ -1486,14 +1638,31 @@ async fn exec_remote_command(
|
||||
let mut stderr = Vec::new();
|
||||
let mut stdout = Vec::new();
|
||||
let mut exit_status = None;
|
||||
while let Some(msg) = channel.wait().await {
|
||||
match msg {
|
||||
russh::ChannelMsg::Data { data } => stdout.extend_from_slice(&data),
|
||||
russh::ChannelMsg::ExtendedData { data, .. } => stderr.extend_from_slice(&data),
|
||||
russh::ChannelMsg::ExitStatus { exit_status: code } => exit_status = Some(code),
|
||||
russh::ChannelMsg::Close => break,
|
||||
_ => {}
|
||||
|
||||
// Add timeout to prevent indefinite blocking (300 seconds = 5 minutes)
|
||||
let timeout = tokio::time::Duration::from_secs(300);
|
||||
let result = tokio::time::timeout(timeout, async {
|
||||
loop {
|
||||
// Yield to allow cancellation
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
if let Some(msg) = channel.wait().await {
|
||||
match msg {
|
||||
russh::ChannelMsg::Data { data } => stdout.extend_from_slice(&data),
|
||||
russh::ChannelMsg::ExtendedData { data, .. } => stderr.extend_from_slice(&data),
|
||||
russh::ChannelMsg::ExitStatus { exit_status: code } => exit_status = Some(code),
|
||||
russh::ChannelMsg::Close => break,
|
||||
_ => {}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
if result.is_err() {
|
||||
return Err(anyhow!("remote command timeout: {command}"));
|
||||
}
|
||||
|
||||
match exit_status.unwrap_or(0) {
|
||||
|
||||
+80
-12
@@ -8,8 +8,14 @@ use crate::{
|
||||
|
||||
pub(crate) fn is_editable_text_file(filename: &str) -> bool {
|
||||
let lower = filename.to_lowercase();
|
||||
let ext = std::path::Path::new(&lower).extension().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let known_exts = ["txt", "conf", "json", "yaml", "yml", "xml", "ini", "sh", "py", "rs", "js", "ts", "html", "css", "md", "toml", "csv", "log", "cfg"];
|
||||
let ext = std::path::Path::new(&lower)
|
||||
.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("");
|
||||
let known_exts = [
|
||||
"txt", "conf", "json", "yaml", "yml", "xml", "ini", "sh", "py", "rs", "js", "ts", "html",
|
||||
"css", "md", "toml", "csv", "log", "cfg",
|
||||
];
|
||||
if known_exts.contains(&ext) {
|
||||
return true;
|
||||
}
|
||||
@@ -22,24 +28,29 @@ pub(crate) fn is_editable_text_file(filename: &str) -> bool {
|
||||
|
||||
impl Ashell {
|
||||
pub(crate) fn active_sftp(&self) -> Option<&terminal::SftpUiState> {
|
||||
self.active_group.as_ref()
|
||||
self.active_group
|
||||
.as_ref()
|
||||
.and_then(|id| self.tab_groups.iter().find(|g| &g.id == id))
|
||||
.and_then(|g| g.sftp.as_ref())
|
||||
}
|
||||
|
||||
pub(crate) fn active_sftp_mut(&mut self) -> Option<&mut terminal::SftpUiState> {
|
||||
let active_id = self.active_group.clone()?;
|
||||
self.tab_groups.iter_mut().find(|g| g.id == active_id)
|
||||
self.tab_groups
|
||||
.iter_mut()
|
||||
.find(|g| g.id == active_id)
|
||||
.and_then(|g| g.sftp.as_mut())
|
||||
}
|
||||
|
||||
pub(crate) fn active_sftp_handle(&self) -> Option<&SftpHandle> {
|
||||
self.active_group.as_ref()
|
||||
self.active_group
|
||||
.as_ref()
|
||||
.and_then(|id| self.sftp_handles.get(id))
|
||||
}
|
||||
|
||||
pub(crate) fn navigate_sftp(&mut self, path: String, cx: &mut Context<Self>) {
|
||||
if let Some(handle) = self.active_sftp_handle() {
|
||||
tracing::info!("[sftp] navigating to directory: '{}'", path);
|
||||
handle.list_dir(path.clone());
|
||||
if let Some(sftp) = self.active_sftp_mut() {
|
||||
sftp.current_path = path;
|
||||
@@ -121,7 +132,11 @@ impl Ashell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn trigger_sftp_context_download(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(crate) fn trigger_sftp_context_download(
|
||||
&mut self,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let Some(menu) = self.sftp_context_menu.take() else {
|
||||
return;
|
||||
};
|
||||
@@ -134,6 +149,7 @@ impl Ashell {
|
||||
return;
|
||||
};
|
||||
if let Some(handle) = self.active_sftp_handle() {
|
||||
tracing::info!("[sftp] triggering edit for file: '{}'", menu.remote_path);
|
||||
handle.edit_file(menu.remote_path);
|
||||
}
|
||||
cx.notify();
|
||||
@@ -158,7 +174,17 @@ impl Ashell {
|
||||
match path_prompt.await {
|
||||
Ok(Ok(Some(mut paths))) => {
|
||||
if let Some(folder) = paths.pop() {
|
||||
handle.download(remote_path, folder.to_string_lossy().to_string());
|
||||
let local_path = folder.to_string_lossy().to_string();
|
||||
tracing::info!(
|
||||
"[sftp] initiating download of '{}' to '{}'",
|
||||
remote_path,
|
||||
local_path
|
||||
);
|
||||
handle.download(remote_path, local_path);
|
||||
this.update(cx, |this, cx| {
|
||||
this.show_transfers_dialog = true;
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
@@ -192,7 +218,17 @@ impl Ashell {
|
||||
match path_prompt.await {
|
||||
Ok(Ok(Some(mut paths))) => {
|
||||
if let Some(file) = paths.pop() {
|
||||
handle.upload_paths(vec![file.to_string_lossy().to_string()], remote_dir);
|
||||
let local_path = file.to_string_lossy().to_string();
|
||||
tracing::info!(
|
||||
"[sftp] initiating upload of file '{}' to '{}'",
|
||||
local_path,
|
||||
remote_dir
|
||||
);
|
||||
handle.upload_paths(vec![local_path], remote_dir);
|
||||
this.update(cx, |this, cx| {
|
||||
this.show_transfers_dialog = true;
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
@@ -226,7 +262,17 @@ impl Ashell {
|
||||
match path_prompt.await {
|
||||
Ok(Ok(Some(mut paths))) => {
|
||||
if let Some(folder) = paths.pop() {
|
||||
handle.upload_paths(vec![folder.to_string_lossy().to_string()], remote_dir);
|
||||
let local_path = folder.to_string_lossy().to_string();
|
||||
tracing::info!(
|
||||
"[sftp] initiating upload of folder '{}' to '{}'",
|
||||
local_path,
|
||||
remote_dir
|
||||
);
|
||||
handle.upload_paths(vec![local_path], remote_dir);
|
||||
this.update(cx, |this, cx| {
|
||||
this.show_transfers_dialog = true;
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
@@ -242,7 +288,12 @@ impl Ashell {
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_sftp_entry(&mut self, path: String, checked: bool, cx: &mut Context<Self>) {
|
||||
pub(crate) fn toggle_sftp_entry(
|
||||
&mut self,
|
||||
path: String,
|
||||
checked: bool,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if let Some(sftp) = self.active_sftp_mut() {
|
||||
if checked {
|
||||
sftp.selected_entries.insert(path);
|
||||
@@ -267,7 +318,11 @@ impl Ashell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn download_selected_sftp_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
pub(crate) fn download_selected_sftp_entries(
|
||||
&mut self,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let Some(sftp) = self.active_sftp() else {
|
||||
return;
|
||||
};
|
||||
@@ -291,6 +346,11 @@ impl Ashell {
|
||||
if let Ok(Ok(Some(mut paths))) = path_prompt.await {
|
||||
if let Some(folder) = paths.pop() {
|
||||
let local_dir = folder.to_string_lossy().to_string();
|
||||
tracing::info!(
|
||||
"[sftp] initiating batch download of {} entries to '{}'",
|
||||
selected.len(),
|
||||
local_dir
|
||||
);
|
||||
for remote in selected {
|
||||
let _ = handle.commands.send(crate::sftp::SftpCommand::Download {
|
||||
remote,
|
||||
@@ -302,6 +362,7 @@ impl Ashell {
|
||||
if let Some(sftp_mut) = this.active_sftp_mut() {
|
||||
sftp_mut.selected_entries.clear();
|
||||
}
|
||||
this.show_transfers_dialog = true;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
@@ -311,16 +372,23 @@ impl Ashell {
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub(crate) fn upload_sftp_files_batch(&mut self, paths: Vec<String>, _cx: &mut Context<Self>) {
|
||||
pub(crate) fn upload_sftp_files_batch(&mut self, paths: Vec<String>, cx: &mut Context<Self>) {
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Some(sftp) = self.active_sftp() {
|
||||
if let Some(handle) = self.active_sftp_handle() {
|
||||
tracing::info!(
|
||||
"[sftp] initiating batch upload of {} files to '{}'",
|
||||
paths.len(),
|
||||
sftp.current_path
|
||||
);
|
||||
let _ = handle.commands.send(crate::sftp::SftpCommand::UploadPaths {
|
||||
locals: paths,
|
||||
remote_dir: sftp.current_path.clone(),
|
||||
});
|
||||
self.show_transfers_dialog = true;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+577
@@ -0,0 +1,577 @@
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use argon2::Argon2;
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use chacha20poly1305::{
|
||||
XChaCha20Poly1305, XNonce,
|
||||
aead::{Aead, KeyInit},
|
||||
};
|
||||
use hmac::{Hmac, Mac};
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
use reqwest::{Client, StatusCode, header};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::session::config::Session;
|
||||
|
||||
const SYNC_FILE_NAME: &str = "ashell-sync.json";
|
||||
const FORMAT_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SyncPayload {
|
||||
pub schema_version: u32,
|
||||
pub revision: String,
|
||||
pub updated_at: String,
|
||||
pub device_id: String,
|
||||
pub sessions: Vec<Session>,
|
||||
}
|
||||
|
||||
impl SyncPayload {
|
||||
pub fn new(device_id: String, sessions: Vec<Session>) -> Self {
|
||||
Self {
|
||||
schema_version: FORMAT_VERSION,
|
||||
revision: Uuid::new_v4().to_string(),
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
device_id,
|
||||
sessions,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct EncryptedEnvelope {
|
||||
format_version: u32,
|
||||
kdf: String,
|
||||
cipher: String,
|
||||
salt: String,
|
||||
nonce: String,
|
||||
payload: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SyncCredentials {
|
||||
pub backend: SyncBackendCredentials,
|
||||
pub encryption_password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum SyncBackendCredentials {
|
||||
WebDav {
|
||||
endpoint: String,
|
||||
username: String,
|
||||
password: String,
|
||||
},
|
||||
S3 {
|
||||
endpoint: String,
|
||||
region: String,
|
||||
bucket: String,
|
||||
object_key: String,
|
||||
access_key: String,
|
||||
secret_key: String,
|
||||
session_token: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SyncResult {
|
||||
Uploaded {
|
||||
etag: Option<String>,
|
||||
},
|
||||
Downloaded {
|
||||
payload: SyncPayload,
|
||||
etag: Option<String>,
|
||||
},
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
pub async fn upload(
|
||||
credentials: SyncCredentials,
|
||||
payload: SyncPayload,
|
||||
expected_etag: Option<String>,
|
||||
) -> Result<Option<String>> {
|
||||
validate_credentials(&credentials)?;
|
||||
let body = encrypt_payload(&payload, &credentials.encryption_password)?;
|
||||
match credentials.backend {
|
||||
SyncBackendCredentials::WebDav {
|
||||
endpoint,
|
||||
username,
|
||||
password,
|
||||
} => upload_webdav(&endpoint, &username, &password, body, expected_etag).await,
|
||||
SyncBackendCredentials::S3 {
|
||||
endpoint,
|
||||
region,
|
||||
bucket,
|
||||
object_key,
|
||||
access_key,
|
||||
secret_key,
|
||||
session_token,
|
||||
} => {
|
||||
let config = S3Config {
|
||||
endpoint,
|
||||
region,
|
||||
bucket,
|
||||
object_key,
|
||||
access_key,
|
||||
secret_key,
|
||||
session_token,
|
||||
};
|
||||
upload_s3(&config, body, expected_etag).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn upload_webdav(
|
||||
endpoint: &str,
|
||||
username: &str,
|
||||
password: &str,
|
||||
body: Vec<u8>,
|
||||
expected_etag: Option<String>,
|
||||
) -> Result<Option<String>> {
|
||||
let client = Client::new();
|
||||
let mut request = client
|
||||
.put(sync_url(endpoint))
|
||||
.basic_auth(username, Some(password))
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(body);
|
||||
request = if let Some(etag) = expected_etag {
|
||||
request.header(header::IF_MATCH, etag)
|
||||
} else {
|
||||
// An uninitialized client may only create a new remote file. This keeps
|
||||
// it from silently replacing configuration uploaded by another device.
|
||||
request.header(header::IF_NONE_MATCH, "*")
|
||||
};
|
||||
let response = request.send().await.context("send WebDAV upload")?;
|
||||
if response.status() == StatusCode::PRECONDITION_FAILED
|
||||
|| response.status() == StatusCode::CONFLICT
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"remote configuration changed; download it before uploading"
|
||||
));
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow!("WebDAV upload failed: HTTP {}", response.status()));
|
||||
}
|
||||
Ok(response
|
||||
.headers()
|
||||
.get(header::ETAG)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_string))
|
||||
}
|
||||
|
||||
pub async fn download(credentials: SyncCredentials) -> Result<(SyncPayload, Option<String>)> {
|
||||
validate_credentials(&credentials)?;
|
||||
let encryption_password = credentials.encryption_password;
|
||||
let (body, etag) = match credentials.backend {
|
||||
SyncBackendCredentials::WebDav {
|
||||
endpoint,
|
||||
username,
|
||||
password,
|
||||
} => download_webdav(&endpoint, &username, &password).await?,
|
||||
SyncBackendCredentials::S3 {
|
||||
endpoint,
|
||||
region,
|
||||
bucket,
|
||||
object_key,
|
||||
access_key,
|
||||
secret_key,
|
||||
session_token,
|
||||
} => {
|
||||
let config = S3Config {
|
||||
endpoint,
|
||||
region,
|
||||
bucket,
|
||||
object_key,
|
||||
access_key,
|
||||
secret_key,
|
||||
session_token,
|
||||
};
|
||||
download_s3(&config).await?
|
||||
}
|
||||
};
|
||||
let payload = decrypt_payload(&body, &encryption_password)?;
|
||||
Ok((payload, etag))
|
||||
}
|
||||
|
||||
async fn download_webdav(
|
||||
endpoint: &str,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<(Vec<u8>, Option<String>)> {
|
||||
let response = Client::new()
|
||||
.get(sync_url(endpoint))
|
||||
.basic_auth(username, Some(password))
|
||||
.send()
|
||||
.await
|
||||
.context("send WebDAV download")?;
|
||||
if response.status() == StatusCode::NOT_FOUND {
|
||||
return Err(anyhow!("no remote configuration exists yet"));
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow!(
|
||||
"WebDAV download failed: HTTP {}",
|
||||
response.status()
|
||||
));
|
||||
}
|
||||
let etag = response
|
||||
.headers()
|
||||
.get(header::ETAG)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_string);
|
||||
let body = response
|
||||
.bytes()
|
||||
.await
|
||||
.context("read WebDAV response")?
|
||||
.to_vec();
|
||||
Ok((body, etag))
|
||||
}
|
||||
|
||||
fn validate_credentials(credentials: &SyncCredentials) -> Result<()> {
|
||||
if credentials.encryption_password.len() < 8 {
|
||||
return Err(anyhow!(
|
||||
"encryption password must contain at least 8 characters"
|
||||
));
|
||||
}
|
||||
match &credentials.backend {
|
||||
SyncBackendCredentials::WebDav { endpoint, .. } if endpoint.trim().is_empty() => {
|
||||
Err(anyhow!("WebDAV endpoint is required"))
|
||||
}
|
||||
SyncBackendCredentials::S3 {
|
||||
region,
|
||||
bucket,
|
||||
access_key,
|
||||
secret_key,
|
||||
..
|
||||
} if region.trim().is_empty()
|
||||
|| bucket.trim().is_empty()
|
||||
|| access_key.trim().is_empty()
|
||||
|| secret_key.is_empty() =>
|
||||
{
|
||||
Err(anyhow!(
|
||||
"S3 region, bucket, access key and secret key are required"
|
||||
))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
struct S3Config {
|
||||
endpoint: String,
|
||||
region: String,
|
||||
bucket: String,
|
||||
object_key: String,
|
||||
access_key: String,
|
||||
secret_key: String,
|
||||
session_token: String,
|
||||
}
|
||||
|
||||
async fn upload_s3(
|
||||
config: &S3Config,
|
||||
body: Vec<u8>,
|
||||
expected_etag: Option<String>,
|
||||
) -> Result<Option<String>> {
|
||||
let url = s3_url(config)?;
|
||||
let mut headers = signed_s3_headers("PUT", &url, &body, config)?;
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
if let Some(etag) = expected_etag {
|
||||
headers.insert(header::IF_MATCH, header_value(&etag, "S3 ETag")?);
|
||||
} else {
|
||||
headers.insert(header::IF_NONE_MATCH, header::HeaderValue::from_static("*"));
|
||||
}
|
||||
let response = Client::new()
|
||||
.put(url)
|
||||
.headers(headers)
|
||||
.body(body)
|
||||
.send()
|
||||
.await
|
||||
.context("send S3 upload")?;
|
||||
if response.status() == StatusCode::PRECONDITION_FAILED
|
||||
|| response.status() == StatusCode::CONFLICT
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"remote configuration changed; download it before uploading"
|
||||
));
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let detail = response.text().await.unwrap_or_default();
|
||||
return Err(anyhow!("S3 upload failed: HTTP {status}: {detail}"));
|
||||
}
|
||||
Ok(response
|
||||
.headers()
|
||||
.get(header::ETAG)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_string))
|
||||
}
|
||||
|
||||
async fn download_s3(config: &S3Config) -> Result<(Vec<u8>, Option<String>)> {
|
||||
let url = s3_url(config)?;
|
||||
let headers = signed_s3_headers("GET", &url, &[], config)?;
|
||||
let response = Client::new()
|
||||
.get(url)
|
||||
.headers(headers)
|
||||
.send()
|
||||
.await
|
||||
.context("send S3 download")?;
|
||||
if response.status() == StatusCode::NOT_FOUND {
|
||||
return Err(anyhow!("no remote configuration exists yet"));
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let detail = response.text().await.unwrap_or_default();
|
||||
return Err(anyhow!("S3 download failed: HTTP {status}: {detail}"));
|
||||
}
|
||||
let etag = response
|
||||
.headers()
|
||||
.get(header::ETAG)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_string);
|
||||
let body = response.bytes().await.context("read S3 response")?.to_vec();
|
||||
Ok((body, etag))
|
||||
}
|
||||
|
||||
fn s3_url(config: &S3Config) -> Result<reqwest::Url> {
|
||||
let endpoint = if config.endpoint.trim().is_empty() {
|
||||
format!("https://s3.{}.amazonaws.com", config.region.trim())
|
||||
} else {
|
||||
config.endpoint.trim().trim_end_matches('/').to_string()
|
||||
};
|
||||
let key = if config.object_key.trim().is_empty() {
|
||||
SYNC_FILE_NAME
|
||||
} else {
|
||||
config.object_key.trim().trim_start_matches('/')
|
||||
};
|
||||
let url = format!(
|
||||
"{}/{}/{}",
|
||||
endpoint,
|
||||
aws_uri_encode(config.bucket.trim(), true),
|
||||
aws_uri_encode(key, false)
|
||||
);
|
||||
reqwest::Url::parse(&url).context("parse S3 object URL")
|
||||
}
|
||||
|
||||
fn signed_s3_headers(
|
||||
method: &str,
|
||||
url: &reqwest::Url,
|
||||
body: &[u8],
|
||||
config: &S3Config,
|
||||
) -> Result<header::HeaderMap> {
|
||||
let now = chrono::Utc::now();
|
||||
let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
|
||||
let date = now.format("%Y%m%d").to_string();
|
||||
let host = url
|
||||
.host_str()
|
||||
.ok_or_else(|| anyhow!("S3 endpoint has no host"))?;
|
||||
let host = match url.port() {
|
||||
Some(port) => format!("{host}:{port}"),
|
||||
None => host.to_string(),
|
||||
};
|
||||
let payload_hash = hex_sha256(body);
|
||||
let mut canonical_headers =
|
||||
format!("host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n");
|
||||
let mut signed_headers = "host;x-amz-content-sha256;x-amz-date".to_string();
|
||||
if !config.session_token.is_empty() {
|
||||
canonical_headers.push_str(&format!(
|
||||
"x-amz-security-token:{}\n",
|
||||
config.session_token.trim()
|
||||
));
|
||||
signed_headers.push_str(";x-amz-security-token");
|
||||
}
|
||||
let canonical_request = format!(
|
||||
"{method}\n{}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}",
|
||||
url.path()
|
||||
);
|
||||
let scope = format!("{date}/{}/s3/aws4_request", config.region.trim());
|
||||
let string_to_sign = format!(
|
||||
"AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}",
|
||||
hex_sha256(canonical_request.as_bytes())
|
||||
);
|
||||
let date_key = hmac_sha256(
|
||||
format!("AWS4{}", config.secret_key).as_bytes(),
|
||||
date.as_bytes(),
|
||||
)?;
|
||||
let region_key = hmac_sha256(&date_key, config.region.trim().as_bytes())?;
|
||||
let service_key = hmac_sha256(®ion_key, b"s3")?;
|
||||
let signing_key = hmac_sha256(&service_key, b"aws4_request")?;
|
||||
let signature = hex::encode(hmac_sha256(&signing_key, string_to_sign.as_bytes())?);
|
||||
let authorization = format!(
|
||||
"AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}",
|
||||
config.access_key.trim()
|
||||
);
|
||||
let mut headers = header::HeaderMap::new();
|
||||
headers.insert("x-amz-date", header_value(&amz_date, "S3 date")?);
|
||||
headers.insert(
|
||||
"x-amz-content-sha256",
|
||||
header_value(&payload_hash, "S3 payload hash")?,
|
||||
);
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
header_value(&authorization, "S3 authorization")?,
|
||||
);
|
||||
if !config.session_token.is_empty() {
|
||||
headers.insert(
|
||||
"x-amz-security-token",
|
||||
header_value(config.session_token.trim(), "S3 session token")?,
|
||||
);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn header_value(value: &str, name: &str) -> Result<header::HeaderValue> {
|
||||
header::HeaderValue::from_str(value).with_context(|| format!("invalid {name}"))
|
||||
}
|
||||
|
||||
fn hmac_sha256(key: &[u8], value: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut mac =
|
||||
<Hmac<Sha256> as Mac>::new_from_slice(key).map_err(|_| anyhow!("initialize S3 signer"))?;
|
||||
mac.update(value);
|
||||
Ok(mac.finalize().into_bytes().to_vec())
|
||||
}
|
||||
|
||||
fn hex_sha256(value: &[u8]) -> String {
|
||||
hex::encode(Sha256::digest(value))
|
||||
}
|
||||
|
||||
fn aws_uri_encode(value: &str, encode_slash: bool) -> String {
|
||||
let mut encoded = String::new();
|
||||
for byte in value.bytes() {
|
||||
if byte.is_ascii_alphanumeric()
|
||||
|| matches!(byte, b'-' | b'_' | b'.' | b'~')
|
||||
|| (!encode_slash && byte == b'/')
|
||||
{
|
||||
encoded.push(byte as char);
|
||||
} else {
|
||||
encoded.push_str(&format!("%{byte:02X}"));
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn sync_url(endpoint: &str) -> String {
|
||||
let endpoint = endpoint.trim();
|
||||
if endpoint.ends_with('/') {
|
||||
format!("{endpoint}{SYNC_FILE_NAME}")
|
||||
} else if endpoint.ends_with(".json") {
|
||||
endpoint.to_string()
|
||||
} else {
|
||||
format!("{endpoint}/{SYNC_FILE_NAME}")
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt_payload(payload: &SyncPayload, password: &str) -> Result<Vec<u8>> {
|
||||
let mut salt = [0u8; 16];
|
||||
let mut nonce = [0u8; 24];
|
||||
OsRng.fill_bytes(&mut salt);
|
||||
OsRng.fill_bytes(&mut nonce);
|
||||
let key = derive_key(password, &salt)?;
|
||||
let plaintext = serde_json::to_vec(payload).context("serialize sync payload")?;
|
||||
let ciphertext = XChaCha20Poly1305::new((&key).into())
|
||||
.encrypt(XNonce::from_slice(&nonce), plaintext.as_ref())
|
||||
.map_err(|_| anyhow!("encrypt sync payload"))?;
|
||||
serde_json::to_vec_pretty(&EncryptedEnvelope {
|
||||
format_version: FORMAT_VERSION,
|
||||
kdf: "argon2id".to_string(),
|
||||
cipher: "xchacha20poly1305".to_string(),
|
||||
salt: STANDARD.encode(salt),
|
||||
nonce: STANDARD.encode(nonce),
|
||||
payload: STANDARD.encode(ciphertext),
|
||||
})
|
||||
.context("serialize encrypted sync envelope")
|
||||
}
|
||||
|
||||
fn decrypt_payload(raw: &[u8], password: &str) -> Result<SyncPayload> {
|
||||
let envelope: EncryptedEnvelope =
|
||||
serde_json::from_slice(raw).context("parse encrypted sync envelope")?;
|
||||
if envelope.format_version != FORMAT_VERSION
|
||||
|| envelope.kdf != "argon2id"
|
||||
|| envelope.cipher != "xchacha20poly1305"
|
||||
{
|
||||
return Err(anyhow!("unsupported remote sync format"));
|
||||
}
|
||||
let salt = STANDARD.decode(envelope.salt).context("decode sync salt")?;
|
||||
let nonce = STANDARD
|
||||
.decode(envelope.nonce)
|
||||
.context("decode sync nonce")?;
|
||||
if nonce.len() != 24 {
|
||||
return Err(anyhow!("invalid sync nonce"));
|
||||
}
|
||||
let ciphertext = STANDARD
|
||||
.decode(envelope.payload)
|
||||
.context("decode encrypted sync payload")?;
|
||||
let key = derive_key(password, &salt)?;
|
||||
let plaintext = XChaCha20Poly1305::new((&key).into())
|
||||
.decrypt(XNonce::from_slice(&nonce), ciphertext.as_ref())
|
||||
.map_err(|_| anyhow!("cannot decrypt remote configuration; check the password"))?;
|
||||
let payload: SyncPayload =
|
||||
serde_json::from_slice(&plaintext).context("parse decrypted sync payload")?;
|
||||
if payload.schema_version != FORMAT_VERSION {
|
||||
return Err(anyhow!("unsupported synchronized configuration version"));
|
||||
}
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
fn derive_key(password: &str, salt: &[u8]) -> Result<[u8; 32]> {
|
||||
let mut key = [0u8; 32];
|
||||
Argon2::default()
|
||||
.hash_password_into(password.as_bytes(), salt, &mut key)
|
||||
.map_err(|err| anyhow!("derive encryption key: {err}"))?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn encrypted_payload_round_trip() {
|
||||
let payload = SyncPayload::new("test-device".into(), Vec::new());
|
||||
let encrypted = encrypt_payload(&payload, "correct horse battery staple").unwrap();
|
||||
assert!(!String::from_utf8_lossy(&encrypted).contains("test-device"));
|
||||
let decrypted = decrypt_payload(&encrypted, "correct horse battery staple").unwrap();
|
||||
assert_eq!(decrypted.revision, payload.revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_password_is_rejected() {
|
||||
let payload = SyncPayload::new("test-device".into(), Vec::new());
|
||||
let encrypted = encrypt_payload(&payload, "correct horse battery staple").unwrap();
|
||||
assert!(decrypt_payload(&encrypted, "incorrect password").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_can_be_a_collection_or_file() {
|
||||
assert_eq!(
|
||||
sync_url("https://example.test/dav/"),
|
||||
"https://example.test/dav/ashell-sync.json"
|
||||
);
|
||||
assert_eq!(
|
||||
sync_url("https://example.test/config.json"),
|
||||
"https://example.test/config.json"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s3_url_uses_path_style_and_encodes_object_key() {
|
||||
let config = S3Config {
|
||||
endpoint: "https://s3.example.test".into(),
|
||||
region: "us-east-1".into(),
|
||||
bucket: "my-bucket".into(),
|
||||
object_key: "configs/my file.json".into(),
|
||||
access_key: "access".into(),
|
||||
secret_key: "secret".into(),
|
||||
session_token: String::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
s3_url(&config).unwrap().as_str(),
|
||||
"https://s3.example.test/my-bucket/configs/my%20file.json"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aws_uri_encoding_preserves_only_object_key_slashes() {
|
||||
assert_eq!(aws_uri_encode("a b/c", false), "a%20b/c");
|
||||
assert_eq!(aws_uri_encode("a/b", true), "a%2Fb");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
use gpui::{Bounds, Hsla, Path, Pixels, Window, fill, point, px, size};
|
||||
|
||||
pub fn is_custom_block_supported(c: char) -> bool {
|
||||
match c as u32 {
|
||||
0x2580..=0x258F | 0x2590 | 0x2594..=0x259F => true, // Block Elements
|
||||
0x2500 | 0x2502 | 0x250C | 0x2510 | 0x2514 | 0x2518 | 0x251C | 0x2524 | 0x252C | 0x2534
|
||||
| 0x253C => true, // Light lines
|
||||
0x2501 | 0x2503 | 0x250F | 0x2513 | 0x2517 | 0x251B | 0x2523 | 0x252B | 0x2533 | 0x253B
|
||||
| 0x254B => true, // Heavy lines
|
||||
0xE0B0..=0xE0B6 => true, // Powerline
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn paint_custom_block(
|
||||
window: &mut Window,
|
||||
c: char,
|
||||
raw_x: f32,
|
||||
raw_y: f32,
|
||||
raw_w: f32,
|
||||
raw_h: f32,
|
||||
color: Hsla,
|
||||
) -> bool {
|
||||
let scale = window.scale_factor();
|
||||
|
||||
let x = px((raw_x * scale).round() / scale);
|
||||
let y = px((raw_y * scale).round() / scale);
|
||||
let w = px(((raw_x + raw_w) * scale).round() / scale) - x;
|
||||
let h = px(((raw_y + raw_h) * scale).round() / scale) - y;
|
||||
|
||||
let mut painted = false;
|
||||
|
||||
// Helper to paint a quad snapping its true physical boundaries to integer physical pixels
|
||||
let mut paint_quad = |qx: Pixels, qy: Pixels, qw: Pixels, qh: Pixels| {
|
||||
let l = px((qx.as_f32() * scale).round() / scale);
|
||||
let t = px((qy.as_f32() * scale).round() / scale);
|
||||
let r = px(((qx + qw).as_f32() * scale).round() / scale);
|
||||
let b = px(((qy + qh).as_f32() * scale).round() / scale);
|
||||
window.paint_quad(fill(Bounds::new(point(l, t), size(r - l, b - t)), color));
|
||||
painted = true;
|
||||
};
|
||||
|
||||
let px_1 = px(1.0);
|
||||
let px_2 = px(2.0);
|
||||
|
||||
// Box drawing thickness
|
||||
let light = (w * 0.1).max(px_1);
|
||||
let heavy = (w * 0.2).max(px_2);
|
||||
let cx = x + w / 2.0;
|
||||
let cy = y + h / 2.0;
|
||||
|
||||
match c as u32 {
|
||||
// --- Block Elements (U+2580..=U+259F) ---
|
||||
0x2580 => paint_quad(x, y, w, h / 2.0),
|
||||
0x2581 => paint_quad(x, y + h * 7.0 / 8.0, w, h / 8.0),
|
||||
0x2582 => paint_quad(x, y + h * 3.0 / 4.0, w, h / 4.0),
|
||||
0x2583 => paint_quad(x, y + h * 5.0 / 8.0, w, h * 3.0 / 8.0),
|
||||
0x2584 => paint_quad(x, y + h / 2.0, w, h / 2.0),
|
||||
0x2585 => paint_quad(x, y + h * 3.0 / 8.0, w, h * 5.0 / 8.0),
|
||||
0x2586 => paint_quad(x, y + h / 4.0, w, h * 3.0 / 4.0),
|
||||
0x2587 => paint_quad(x, y + h / 8.0, w, h * 7.0 / 8.0),
|
||||
0x2588 => paint_quad(x, y, w, h),
|
||||
0x2589 => paint_quad(x, y, w * 7.0 / 8.0, h),
|
||||
0x258A => paint_quad(x, y, w * 3.0 / 4.0, h),
|
||||
0x258B => paint_quad(x, y, w * 5.0 / 8.0, h),
|
||||
0x258C => paint_quad(x, y, w / 2.0, h),
|
||||
0x258D => paint_quad(x, y, w * 3.0 / 8.0, h),
|
||||
0x258E => paint_quad(x, y, w / 4.0, h),
|
||||
0x258F => paint_quad(x, y, w / 8.0, h),
|
||||
0x2590 => paint_quad(x + w / 2.0, y, w / 2.0, h),
|
||||
0x2594 => paint_quad(x, y, w, h / 8.0),
|
||||
0x2595 => paint_quad(x + w * 7.0 / 8.0, y, w / 8.0, h),
|
||||
0x2596 => paint_quad(x, y + h / 2.0, w / 2.0, h / 2.0),
|
||||
0x2597 => paint_quad(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0),
|
||||
0x2598 => paint_quad(x, y, w / 2.0, h / 2.0),
|
||||
0x2599 => {
|
||||
paint_quad(x, y, w / 2.0, h);
|
||||
paint_quad(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0);
|
||||
}
|
||||
0x259A => {
|
||||
paint_quad(x, y, w / 2.0, h / 2.0);
|
||||
paint_quad(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0);
|
||||
}
|
||||
0x259B => {
|
||||
paint_quad(x, y, w, h / 2.0);
|
||||
paint_quad(x, y + h / 2.0, w / 2.0, h / 2.0);
|
||||
}
|
||||
0x259C => {
|
||||
paint_quad(x, y, w, h / 2.0);
|
||||
paint_quad(x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0);
|
||||
}
|
||||
0x259D => paint_quad(x + w / 2.0, y, w / 2.0, h / 2.0),
|
||||
0x259E => {
|
||||
paint_quad(x + w / 2.0, y, w / 2.0, h / 2.0);
|
||||
paint_quad(x, y + h / 2.0, w / 2.0, h / 2.0);
|
||||
}
|
||||
0x259F => {
|
||||
paint_quad(x + w / 2.0, y, w / 2.0, h);
|
||||
paint_quad(x, y + h / 2.0, w / 2.0, h / 2.0);
|
||||
}
|
||||
|
||||
// --- Basic Box Drawing (U+2500..=U+257F) ---
|
||||
// Light lines
|
||||
0x2500 => paint_quad(x, cy - light / 2.0, w, light), // Horizontal
|
||||
0x2502 => paint_quad(cx - light / 2.0, y, light, h), // Vertical
|
||||
0x250C => {
|
||||
// Down + Right
|
||||
paint_quad(
|
||||
cx - light / 2.0,
|
||||
cy - light / 2.0,
|
||||
light,
|
||||
h / 2.0 + light / 2.0,
|
||||
);
|
||||
paint_quad(
|
||||
cx - light / 2.0,
|
||||
cy - light / 2.0,
|
||||
w / 2.0 + light / 2.0,
|
||||
light,
|
||||
);
|
||||
}
|
||||
0x2510 => {
|
||||
// Down + Left
|
||||
paint_quad(
|
||||
cx - light / 2.0,
|
||||
cy - light / 2.0,
|
||||
light,
|
||||
h / 2.0 + light / 2.0,
|
||||
);
|
||||
paint_quad(x, cy - light / 2.0, w / 2.0 + light / 2.0, light);
|
||||
}
|
||||
0x2514 => {
|
||||
// Up + Right
|
||||
paint_quad(cx - light / 2.0, y, light, h / 2.0 + light / 2.0);
|
||||
paint_quad(
|
||||
cx - light / 2.0,
|
||||
cy - light / 2.0,
|
||||
w / 2.0 + light / 2.0,
|
||||
light,
|
||||
);
|
||||
}
|
||||
0x2518 => {
|
||||
// Up + Left
|
||||
paint_quad(cx - light / 2.0, y, light, h / 2.0 + light / 2.0);
|
||||
paint_quad(x, cy - light / 2.0, w / 2.0 + light / 2.0, light);
|
||||
}
|
||||
0x251C => {
|
||||
// Vertical + Right
|
||||
paint_quad(cx - light / 2.0, y, light, h);
|
||||
paint_quad(
|
||||
cx - light / 2.0,
|
||||
cy - light / 2.0,
|
||||
w / 2.0 + light / 2.0,
|
||||
light,
|
||||
);
|
||||
}
|
||||
0x2524 => {
|
||||
// Vertical + Left
|
||||
paint_quad(cx - light / 2.0, y, light, h);
|
||||
paint_quad(x, cy - light / 2.0, w / 2.0 + light / 2.0, light);
|
||||
}
|
||||
0x252C => {
|
||||
// Horizontal + Down
|
||||
paint_quad(x, cy - light / 2.0, w, light);
|
||||
paint_quad(
|
||||
cx - light / 2.0,
|
||||
cy - light / 2.0,
|
||||
light,
|
||||
h / 2.0 + light / 2.0,
|
||||
);
|
||||
}
|
||||
0x2534 => {
|
||||
// Horizontal + Up
|
||||
paint_quad(x, cy - light / 2.0, w, light);
|
||||
paint_quad(cx - light / 2.0, y, light, h / 2.0 + light / 2.0);
|
||||
}
|
||||
0x253C => {
|
||||
// Vertical + Horizontal (Cross)
|
||||
paint_quad(x, cy - light / 2.0, w, light);
|
||||
paint_quad(cx - light / 2.0, y, light, h);
|
||||
}
|
||||
|
||||
// Heavy lines
|
||||
0x2501 => paint_quad(x, cy - heavy / 2.0, w, heavy), // Heavy Horizontal
|
||||
0x2503 => paint_quad(cx - heavy / 2.0, y, heavy, h), // Heavy Vertical
|
||||
0x250F => {
|
||||
// Heavy Down + Right
|
||||
paint_quad(
|
||||
cx - heavy / 2.0,
|
||||
cy - heavy / 2.0,
|
||||
heavy,
|
||||
h / 2.0 + heavy / 2.0,
|
||||
);
|
||||
paint_quad(
|
||||
cx - heavy / 2.0,
|
||||
cy - heavy / 2.0,
|
||||
w / 2.0 + heavy / 2.0,
|
||||
heavy,
|
||||
);
|
||||
}
|
||||
0x2513 => {
|
||||
// Heavy Down + Left
|
||||
paint_quad(
|
||||
cx - heavy / 2.0,
|
||||
cy - heavy / 2.0,
|
||||
heavy,
|
||||
h / 2.0 + heavy / 2.0,
|
||||
);
|
||||
paint_quad(x, cy - heavy / 2.0, w / 2.0 + heavy / 2.0, heavy);
|
||||
}
|
||||
0x2517 => {
|
||||
// Heavy Up + Right
|
||||
paint_quad(cx - heavy / 2.0, y, heavy, h / 2.0 + heavy / 2.0);
|
||||
paint_quad(
|
||||
cx - heavy / 2.0,
|
||||
cy - heavy / 2.0,
|
||||
w / 2.0 + heavy / 2.0,
|
||||
heavy,
|
||||
);
|
||||
}
|
||||
0x251B => {
|
||||
// Heavy Up + Left
|
||||
paint_quad(cx - heavy / 2.0, y, heavy, h / 2.0 + heavy / 2.0);
|
||||
paint_quad(x, cy - heavy / 2.0, w / 2.0 + heavy / 2.0, heavy);
|
||||
}
|
||||
0x2523 => {
|
||||
// Heavy Vertical + Right
|
||||
paint_quad(cx - heavy / 2.0, y, heavy, h);
|
||||
paint_quad(
|
||||
cx - heavy / 2.0,
|
||||
cy - heavy / 2.0,
|
||||
w / 2.0 + heavy / 2.0,
|
||||
heavy,
|
||||
);
|
||||
}
|
||||
0x252B => {
|
||||
// Heavy Vertical + Left
|
||||
paint_quad(cx - heavy / 2.0, y, heavy, h);
|
||||
paint_quad(x, cy - heavy / 2.0, w / 2.0 + heavy / 2.0, heavy);
|
||||
}
|
||||
0x2533 => {
|
||||
// Heavy Horizontal + Down
|
||||
paint_quad(x, cy - heavy / 2.0, w, heavy);
|
||||
paint_quad(
|
||||
cx - heavy / 2.0,
|
||||
cy - heavy / 2.0,
|
||||
heavy,
|
||||
h / 2.0 + heavy / 2.0,
|
||||
);
|
||||
}
|
||||
0x253B => {
|
||||
// Heavy Horizontal + Up
|
||||
paint_quad(x, cy - heavy / 2.0, w, heavy);
|
||||
paint_quad(cx - heavy / 2.0, y, heavy, h / 2.0 + heavy / 2.0);
|
||||
}
|
||||
0x254B => {
|
||||
// Heavy Vertical + Horizontal (Cross)
|
||||
paint_quad(x, cy - heavy / 2.0, w, heavy);
|
||||
paint_quad(cx - heavy / 2.0, y, heavy, h);
|
||||
}
|
||||
|
||||
// --- Powerline ---
|
||||
0xE0B0 => {
|
||||
// Rightward Solid Arrow
|
||||
let mut path = Path::new(point(x, y));
|
||||
path.line_to(point(x + w, y + h / 2.0));
|
||||
path.line_to(point(x, y + h));
|
||||
path.line_to(point(x, y));
|
||||
window.paint_path(path, color);
|
||||
painted = true;
|
||||
}
|
||||
0xE0B2 => {
|
||||
// Leftward Solid Arrow
|
||||
let mut path = Path::new(point(x + w, y));
|
||||
path.line_to(point(x, y + h / 2.0));
|
||||
path.line_to(point(x + w, y + h));
|
||||
path.line_to(point(x + w, y));
|
||||
window.paint_path(path, color);
|
||||
painted = true;
|
||||
}
|
||||
0xE0B1 => {
|
||||
// Rightward Line Arrow
|
||||
let t = px(1.0);
|
||||
let mut p = Path::new(point(x, y));
|
||||
p.line_to(point(x + w, y + h / 2.0));
|
||||
p.line_to(point(x + w - t, y + h / 2.0));
|
||||
p.line_to(point(x, y + t));
|
||||
p.line_to(point(x, y));
|
||||
window.paint_path(p, color);
|
||||
let mut p2 = Path::new(point(x, y + h));
|
||||
p2.line_to(point(x + w, y + h / 2.0));
|
||||
p2.line_to(point(x + w - t, y + h / 2.0));
|
||||
p2.line_to(point(x, y + h - t));
|
||||
p2.line_to(point(x, y + h));
|
||||
window.paint_path(p2, color);
|
||||
painted = true;
|
||||
}
|
||||
0xE0B3 => {
|
||||
// Leftward Line Arrow
|
||||
let t = px(1.0);
|
||||
let mut p = Path::new(point(x + w, y));
|
||||
p.line_to(point(x, y + h / 2.0));
|
||||
p.line_to(point(x + t, y + h / 2.0));
|
||||
p.line_to(point(x + w, y + t));
|
||||
p.line_to(point(x + w, y));
|
||||
window.paint_path(p, color);
|
||||
let mut p2 = Path::new(point(x + w, y + h));
|
||||
p2.line_to(point(x, y + h / 2.0));
|
||||
p2.line_to(point(x + t, y + h / 2.0));
|
||||
p2.line_to(point(x + w, y + h - t));
|
||||
p2.line_to(point(x + w, y + h));
|
||||
window.paint_path(p2, color);
|
||||
painted = true;
|
||||
}
|
||||
|
||||
// Half arches (Powerline rounded)
|
||||
0xE0B4 => {
|
||||
// Rightward Solid Semicircle
|
||||
let mut path = Path::new(point(x, y));
|
||||
path.curve_to(point(x, y + h), point(x + w * 2.0, y + h / 2.0));
|
||||
path.line_to(point(x, y));
|
||||
window.paint_path(path, color);
|
||||
painted = true;
|
||||
}
|
||||
0xE0B6 => {
|
||||
// Leftward Solid Semicircle
|
||||
let mut path = Path::new(point(x + w, y));
|
||||
path.curve_to(point(x + w, y + h), point(x - w, y + h / 2.0));
|
||||
path.line_to(point(x + w, y));
|
||||
window.paint_path(path, color);
|
||||
painted = true;
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
|
||||
painted
|
||||
}
|
||||
+68
-7
@@ -11,6 +11,7 @@ use gpui::{
|
||||
use gpui_component::ActiveTheme as _;
|
||||
|
||||
use crate::Ashell;
|
||||
use crate::terminal::custom_blocks::{is_custom_block_supported, paint_custom_block};
|
||||
use crate::terminal::{RenderSnapshot, ViewportSelection};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -138,9 +139,19 @@ pub struct PrepaintState {
|
||||
metrics: TerminalMetrics,
|
||||
rects: Vec<LayoutRect>,
|
||||
runs: Vec<BatchedTextRun>,
|
||||
custom_blocks: Vec<LayoutCustomBlock>,
|
||||
cursor: Option<CursorLayout>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LayoutCustomBlock {
|
||||
c: char,
|
||||
row: i32,
|
||||
col: i32,
|
||||
cells: usize,
|
||||
color: Hsla,
|
||||
}
|
||||
|
||||
struct TerminalInputHandler {
|
||||
view: Entity<Ashell>,
|
||||
element_bounds: Bounds<Pixels>,
|
||||
@@ -219,9 +230,12 @@ impl InputHandler for TerminalInputHandler {
|
||||
_window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
self.view
|
||||
.read(cx)
|
||||
.terminal_ime_bounds_for_range(range_utf16, self.element_bounds, self.cell_width, self.line_height)
|
||||
self.view.read(cx).terminal_ime_bounds_for_range(
|
||||
range_utf16,
|
||||
self.element_bounds,
|
||||
self.cell_width,
|
||||
self.line_height,
|
||||
)
|
||||
}
|
||||
|
||||
fn character_index_for_point(
|
||||
@@ -331,9 +345,13 @@ impl TerminalElement {
|
||||
}
|
||||
}
|
||||
|
||||
fn layout_grid(&self, cx: &App) -> (Vec<LayoutRect>, Vec<BatchedTextRun>) {
|
||||
fn layout_grid(
|
||||
&self,
|
||||
cx: &App,
|
||||
) -> (Vec<LayoutRect>, Vec<BatchedTextRun>, Vec<LayoutCustomBlock>) {
|
||||
let mut rects = Vec::new();
|
||||
let mut runs = Vec::new();
|
||||
let mut custom_blocks = Vec::new();
|
||||
let mut current_run: Option<BatchedTextRun> = None;
|
||||
|
||||
for render_cell in &self.snapshot.cells {
|
||||
@@ -352,7 +370,11 @@ impl TerminalElement {
|
||||
rects.push(LayoutRect {
|
||||
row: render_cell.row,
|
||||
col: render_cell.col,
|
||||
cells: 1,
|
||||
cells: if cell.flags.contains(Flags::WIDE_CHAR) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
},
|
||||
color: if selected {
|
||||
cx.theme().selection
|
||||
} else if cell.flags.contains(Flags::INVERSE) {
|
||||
@@ -371,6 +393,28 @@ impl TerminalElement {
|
||||
}
|
||||
|
||||
let style = self.cell_run_style(cell, cx);
|
||||
|
||||
// Box Drawing & Block Elements interception
|
||||
let is_custom_block = is_custom_block_supported(cell.c);
|
||||
|
||||
if is_custom_block {
|
||||
if let Some(run) = current_run.take() {
|
||||
runs.push(run);
|
||||
}
|
||||
custom_blocks.push(LayoutCustomBlock {
|
||||
c: cell.c,
|
||||
row: render_cell.row,
|
||||
col: render_cell.col,
|
||||
cells: if cell.flags.contains(Flags::WIDE_CHAR) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
},
|
||||
color: style.color,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(run) = current_run.as_mut() {
|
||||
if run.can_append(&style, render_cell.row, render_cell.col) {
|
||||
run.append(cell.c, cell.zerowidth());
|
||||
@@ -402,7 +446,7 @@ impl TerminalElement {
|
||||
runs.push(run);
|
||||
}
|
||||
|
||||
(merge_rects(rects), runs)
|
||||
(merge_rects(rects), runs, custom_blocks)
|
||||
}
|
||||
|
||||
fn cursor_layout(&self, cx: &App) -> Option<CursorLayout> {
|
||||
@@ -458,7 +502,7 @@ impl Element for TerminalElement {
|
||||
cx: &mut App,
|
||||
) -> Self::PrepaintState {
|
||||
let _ = self.base_text_style(cx);
|
||||
let (rects, runs) = self.layout_grid(cx);
|
||||
let (rects, runs, custom_blocks) = self.layout_grid(cx);
|
||||
PrepaintState {
|
||||
bounds,
|
||||
metrics: TerminalMetrics {
|
||||
@@ -467,6 +511,7 @@ impl Element for TerminalElement {
|
||||
},
|
||||
rects,
|
||||
runs,
|
||||
custom_blocks,
|
||||
cursor: self.cursor_layout(cx),
|
||||
}
|
||||
}
|
||||
@@ -489,6 +534,22 @@ impl Element for TerminalElement {
|
||||
run.paint(prepaint.bounds.origin, prepaint.metrics, window, cx);
|
||||
}
|
||||
|
||||
for block in &prepaint.custom_blocks {
|
||||
let x = prepaint.bounds.origin.x.as_f32()
|
||||
+ block.col as f32 * prepaint.metrics.cell_width.as_f32();
|
||||
let y = prepaint.bounds.origin.y.as_f32()
|
||||
+ block.row as f32 * prepaint.metrics.line_height.as_f32();
|
||||
paint_custom_block(
|
||||
window,
|
||||
block.c,
|
||||
x,
|
||||
y,
|
||||
prepaint.metrics.cell_width.as_f32() * block.cells as f32,
|
||||
prepaint.metrics.line_height.as_f32(),
|
||||
block.color,
|
||||
);
|
||||
}
|
||||
|
||||
window.handle_input(
|
||||
&self.focus_handle,
|
||||
TerminalInputHandler {
|
||||
|
||||
+83
-12
@@ -8,9 +8,8 @@ use gpui::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Ashell,
|
||||
Ashell, TerminalBacktabKey, TerminalTabKey,
|
||||
terminal::{BackendCommand, encode_key},
|
||||
TerminalBacktabKey, TerminalTabKey,
|
||||
};
|
||||
|
||||
impl Ashell {
|
||||
@@ -287,7 +286,11 @@ impl Ashell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_terminal_selection(&mut self, event: &MouseDownEvent, cx: &mut Context<Self>) {
|
||||
pub(crate) fn begin_terminal_selection(
|
||||
&mut self,
|
||||
event: &MouseDownEvent,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let click_count = event.click_count.max(1);
|
||||
let selection_type = match click_count {
|
||||
1 => SelectionType::Simple,
|
||||
@@ -394,19 +397,87 @@ impl Ashell {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let delta_lines = match event.delta {
|
||||
ScrollDelta::Lines(point) => point.y.round() as i32,
|
||||
ScrollDelta::Pixels(point) => {
|
||||
(point.y.as_f32() / self.terminal_line_height()).round() as i32
|
||||
}
|
||||
};
|
||||
if delta_lines == 0 {
|
||||
return;
|
||||
}
|
||||
let Some(active_id) = self.active_tab.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Get coordinates before mutably borrowing tabs
|
||||
let grid_point = self.terminal_grid_point_and_side(event.position);
|
||||
|
||||
let line_height = self.terminal_line_height();
|
||||
|
||||
if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == active_id) {
|
||||
let delta_lines = match event.delta {
|
||||
ScrollDelta::Lines(point) => point.y.round() as i32,
|
||||
ScrollDelta::Pixels(point) => {
|
||||
tab.scroll_pixel_y += point.y.as_f32();
|
||||
let lines = (tab.scroll_pixel_y / line_height).trunc() as i32;
|
||||
tab.scroll_pixel_y -= (lines as f32) * line_height;
|
||||
lines
|
||||
}
|
||||
};
|
||||
|
||||
if delta_lines == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let mode = tab.term.mode();
|
||||
|
||||
let is_mouse_tracking = mode.intersects(
|
||||
alacritty_terminal::term::TermMode::MOUSE_REPORT_CLICK
|
||||
| alacritty_terminal::term::TermMode::MOUSE_MOTION
|
||||
| alacritty_terminal::term::TermMode::MOUSE_DRAG,
|
||||
);
|
||||
|
||||
let is_alternate_scroll = mode.contains(
|
||||
alacritty_terminal::term::TermMode::ALT_SCREEN
|
||||
| alacritty_terminal::term::TermMode::ALTERNATE_SCROLL,
|
||||
);
|
||||
|
||||
if is_mouse_tracking {
|
||||
if let Some((row, col, _)) = grid_point {
|
||||
let sgr = mode.contains(alacritty_terminal::term::TermMode::SGR_MOUSE);
|
||||
let button = if delta_lines > 0 { 64 } else { 65 };
|
||||
let times = delta_lines.abs();
|
||||
let mut bytes = Vec::new();
|
||||
for _ in 0..times {
|
||||
if sgr {
|
||||
bytes.extend_from_slice(
|
||||
format!("\x1b[<{};{};{}M", button, col + 1, row + 1).as_bytes(),
|
||||
);
|
||||
} else {
|
||||
if col < 223 && row < 223 {
|
||||
bytes.extend_from_slice(b"\x1b[M");
|
||||
bytes.push(button as u8 + 32);
|
||||
bytes.push(col as u8 + 33);
|
||||
bytes.push(row as u8 + 33);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !bytes.is_empty() {
|
||||
tab.backend
|
||||
.send(crate::terminal::BackendCommand::Input(bytes));
|
||||
}
|
||||
}
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
} else if is_alternate_scroll {
|
||||
let times = delta_lines.abs();
|
||||
let code = if delta_lines > 0 { b'A' } else { b'B' };
|
||||
let mut bytes = Vec::with_capacity((times * 3) as usize);
|
||||
for _ in 0..times {
|
||||
bytes.extend_from_slice(&[b'\x1b', b'O', code]);
|
||||
}
|
||||
if !bytes.is_empty() {
|
||||
tab.backend
|
||||
.send(crate::terminal::BackendCommand::Input(bytes));
|
||||
}
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
|
||||
tab.scroll_history(delta_lines);
|
||||
window.prevent_default();
|
||||
cx.stop_propagation();
|
||||
|
||||
+75
-5
@@ -1,3 +1,4 @@
|
||||
pub mod custom_blocks;
|
||||
pub mod element;
|
||||
pub mod input;
|
||||
|
||||
@@ -23,15 +24,35 @@ pub enum TabKind {
|
||||
Ssh,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PromptType {
|
||||
KeyboardInteractive,
|
||||
Passphrase,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PromptInfo {
|
||||
pub prompt: String,
|
||||
pub echo: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum BackendCommand {
|
||||
Input(Vec<u8>),
|
||||
Resize { cols: u16, rows: u16 },
|
||||
SampleMetrics,
|
||||
Close,
|
||||
PromptResponse(Vec<String>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BackendEvent {
|
||||
PromptRequest {
|
||||
tab_id: String,
|
||||
prompt_type: PromptType,
|
||||
instruction: String,
|
||||
prompts: Vec<PromptInfo>,
|
||||
},
|
||||
Output {
|
||||
tab_id: String,
|
||||
bytes: Vec<u8>,
|
||||
@@ -88,6 +109,7 @@ pub enum BackendEvent {
|
||||
tab_id: String,
|
||||
title: String,
|
||||
},
|
||||
SyncFinished(crate::sync::SyncResult),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -121,6 +143,7 @@ pub struct TerminalTab {
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
pub backend: BackendTx,
|
||||
pub scroll_pixel_y: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -227,6 +250,7 @@ impl TerminalTab {
|
||||
cols: 100,
|
||||
rows: 30,
|
||||
backend,
|
||||
scroll_pixel_y: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,10 +259,19 @@ impl TerminalTab {
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, cols: u16, rows: u16) {
|
||||
self.cols = cols.max(1);
|
||||
self.rows = rows.max(1);
|
||||
self.term.resize(TerminalSize::new(self.cols, self.rows));
|
||||
self.backend.send(BackendCommand::Resize { cols, rows });
|
||||
let new_cols = cols.max(1);
|
||||
let new_rows = rows.max(1);
|
||||
if self.cols != new_cols || self.rows != new_rows {
|
||||
self.cols = new_cols;
|
||||
self.rows = new_rows;
|
||||
tracing::info!(
|
||||
"[ui] terminal resized to {}x{} (cols x rows)",
|
||||
self.cols,
|
||||
self.rows
|
||||
);
|
||||
self.term.resize(TerminalSize::new(self.cols, self.rows));
|
||||
self.backend.send(BackendCommand::Resize { cols, rows });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cursor_state(&self) -> Option<CursorState> {
|
||||
@@ -665,15 +698,52 @@ pub enum TransferType {
|
||||
Download,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
pub enum TransferState {
|
||||
Running,
|
||||
Paused,
|
||||
Completed,
|
||||
Failed(String),
|
||||
Interrupted(String), // 中断传输:包含原因(例如 "User cancelled", "Network timeout")
|
||||
Zombie(String), // 程序重启后残留的 Running/Paused 任务
|
||||
// 兼容 v0.3.11 -> v0.4.x:旧配置里曾保存过 `Cancelled`,
|
||||
// 新版本改成了带原因的状态,因此要手动接住旧枚举值。
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
enum TransferStateCompat {
|
||||
Running,
|
||||
Paused,
|
||||
Completed,
|
||||
Failed(String),
|
||||
Interrupted(String),
|
||||
Zombie(String),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl From<TransferStateCompat> for TransferState {
|
||||
fn from(value: TransferStateCompat) -> Self {
|
||||
match value {
|
||||
TransferStateCompat::Running => Self::Running,
|
||||
TransferStateCompat::Paused => Self::Paused,
|
||||
TransferStateCompat::Completed => Self::Completed,
|
||||
TransferStateCompat::Failed(reason) => Self::Failed(reason),
|
||||
TransferStateCompat::Interrupted(reason) => Self::Interrupted(reason),
|
||||
TransferStateCompat::Zombie(reason) => Self::Zombie(reason),
|
||||
TransferStateCompat::Cancelled => Self::Interrupted("Cancelled".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for TransferState {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
TransferStateCompat::deserialize(deserializer).map(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TransferInfo {
|
||||
pub id: String,
|
||||
|
||||
Reference in New Issue
Block a user