Compare commits

...
7 Commits
Author SHA1 Message Date
Bill 8442103343 chore: release v1.0.15 2026-09-21 00:00:36 +08:00
Bill 481f54ed59 feat: custom terminal background image + theme editor hardening
- settings: backgroundImage/backgroundImageOpacity (10..100, default 60)
- main: otimg:// protocol serves only the configured background file
  (path-allowlisted, 403 otherwise); dev http origin cannot load file:
- TerminalView: allowTransparency + transparent theme background while an
  image is set; .term-bg-image layer behind the xterm surface
- terminal.css: .has-bg-image keeps .xterm-viewport transparent — the old
  chrome-bg pin covered the image layer (root cause of image not showing)
- ThemeSettingsTab: image picker + opacity slider
- ThemeEditor: duplicate-name hint now covers builtin names too; seed
  colors normalized to #rrggbb
- settingsStore: sanitize theme colors, reject non-hex values
2026-09-20 23:24:43 +08:00
Bill c94e0fbac7 fix: settings nav active label readable (white, like inactive tabs)
antd's runtime-injected .ant-tabs-tab-active .ant-tabs-tab-btn rule
(colorPrimary blue) out-ranks a same-specificity stylesheet rule, so the
active label stayed blue on the accent-tinted row; add the .ant-tabs-tab
class to out-specify it.
2026-09-20 22:35:07 +08:00
Bill f128c3e8be chore: event-loop stall detectors for hang diagnosis
WER records AppHangTransient with no stack, so measure lag in both
processes and log it on recovery: [main] event loop stalled / [renderer]
main thread stalled. Tells a main-process block from a renderer freeze
the next time the app 'freezes then recovers'.
2026-09-20 22:25:23 +08:00
Bill 258e5fac0c fix(release): replace version-independent channel files on 409
latest.yml and release-notes.md change every release, but the atomic
publish no longer wipes the channel up front, so their PUTs now hit the
previous release's stored file. Swap them in place (delete + put, one
small file); version-named payloads keep the same-size keep rule.
2026-09-20 21:21:46 +08:00
Bill eccc1f52e7 chore: bump version to 1.0.14 2026-09-20 21:04:35 +08:00
Bill 806fd93638 fix: sync language at render time without notifying subscribers
setLanguage() during App's render fired onLanguageChange, which made the
same component's useSyncExternalStore schedule an update mid-render
(React: cannot update a component while rendering a different component).
syncLanguage() updates the module silently; re-renders flow through the
settings store, which is the only path a renderer language change takes.
2026-09-20 20:45:44 +08:00
23 changed files with 432 additions and 38 deletions

No files matched your search

+42
View File
@@ -1,5 +1,47 @@
# OpenTerminal Changelog
## v1.0.15 - 2026-09-20
- **Custom terminal background image**: Settings → Theme → Background image lets you use any local image as the terminal background, with 10%–100% image opacity control; removing the image restores the solid background
- **Duplicate-name warning in the theme editor**: creating or renaming a theme that collides with a builtin or another custom theme now shows a hint (saving is still allowed)
- Theme editor seed colors are normalized; invalid color values can no longer enter custom themes
- Corrupted custom theme colors are auto-repaired to defaults with a warning logged
- The selected item in the settings dialog's left navigation is now white, matching the contrast of unselected items (fixes unreadable blue text on dark backgrounds)
- New background-image and opacity controls ship with localized strings in all four languages (zh-CN / zh-TW / en / ja)
- Added freeze-duration probes for the renderer and main process to help diagnose future "not responding" reports
## v1.0.14 - 2026-09-20
- Fixed silent corruption of uploaded files **larger than ~250KB** (size looked correct but the content had scrambled bytes)
- Fixed a remote file-handle leak on every download and a leftover SFTP channel after every transfer; a malformed server response no longer crashes the whole app
- Uploading over an existing file now asks for confirmation; partially failed multi-file deletes are now reported
- Permission editor fixes: files with unknown mode no longer get a stray `chmod 000`; an empty GID is no longer replaced by the new UID; setuid / setgid / sticky bits are shown and preserved
- chmod / chown now time out instead of spinning forever
- Fixed Chinese output over SSH turning into mojibake (multi-byte chars split across network chunks)
- Fixed command history being lost or corrupted after accepting a Tab completion
- Fixed editing keys (Ctrl+U / Ctrl+W, …) being written into command history (the "two commands merged" entries)
- `cd ~/dir` and `cd $HOME/...` are now remembered; new terminals restore them
- URL click ranges inside lines containing CJK characters no longer shift; degenerate sizes are no longer sent when the window is tiny
- SSH sessions report the real exit code; ZMODEM timeouts no longer dump garbage into the terminal or the log
- A failed session restore no longer disables snapshot saving for the whole run
- Monitor CPU / network history charts now redraw live; polling stops while the SSH workspace is hidden
- Broadcast: closing one pane of a split no longer drops the other from broadcast targets; unchecking one target no longer clears the rest
- Connection failures show the real reason; double-clicks no longer open duplicate sessions
- Fixed "Close others / Close right" skipping tabs
- Language switches apply from the first frame; active-tab text adapts after a theme switch (no more unreadable labels on light themes)
- The private-key path field no longer claims to be a server-side path
- File drops can no longer navigate the window; external links are limited to http(s) / ftp; IPC is sender-checked
- Stored passwords are only used for password-auth bookmarks (key-auth bookmarks no longer fall back to sending a password)
- Connections / known hosts are written atomically — a crash can no longer wipe them
- A crashed renderer has all of its sessions and logs reclaimed automatically
- A corrupted custom theme no longer prevents the app from starting
- Update-channel publishing is atomic — a failed publish can no longer break auto-update
## v1.0.13 - 2026-09-20
- Simplified Chinese, Traditional Chinese, English and Japanese, switchable in Settings → System → Language; applies instantly and persists
+42
View File
@@ -1,5 +1,47 @@
# OpenTerminal 更新履歴
## v1.0.15 - 2026-09-20
- **ターミナルの背景画像をカスタマイズ**:設定 → テーマ → 背景画像で、任意のローカル画像をターミナルの背景に指定でき、画像の不透明度(10%~100%)も調整可能。画像を削除すると単色背景に戻ります
- **テーマエディターの名前重複警告**:新規作成・編集時に内蔵テーマや他のテーマと名前が重複すると黄色のヒントを表示(保存は可能)
- テーマエディターのシードカラーを自動正規化し、無効なカラー値がカスタムテーマに入らないように
- 破損したカスタムテーマのカラーはデフォルト色に自動修復され、警告ログを記録
- 設定ダイアログ左側ナビの選択中項目の文字を白色に変更し、未選択項目と同じコントラストに(濃い背景で青い文字が見えにくい問題を修正)
- 背景画像・不透明度などの新規コントロールと4言語(簡体字/繁体字/英語/日本語)の文言を同時リリース
- レンダラーとメインプロセスにフリーズ時間の検出ログを追加し、「応答なし」問題の今後の診断に役立てます
## v1.0.14 - 2026-09-20
- **約 250KB を超える**アップロードファイルが静かに破損する問題を修正(サイズは正しいのに内容のバイトが乱れる)
- ダウンロードのたびにリモートのファイルハンドルが漏出し、転送のたびに SFTP チャネルが残る問題を修正。サーバーのプロトコル異常でアプリ全体が落ちることもなくなりました
- 同名ファイルへのアップロードは上書き確認を表示。複数ファイル削除の部分失敗も正しく報告されます
- 権限エディタの修正:不明なモードのファイルに誤って `chmod 000` を送らない。空の GID が新しい UID で置き換えられない。setuid / setgid / sticky ビットを表示・保持
- chmod / chown にタイムアウトを追加し、遠端の無応答で永久にスピンしなくなりました
- SSH 出力の日本語・中文が文字化けする問題を修正(ネットワークパケットをまたいで分割されたマルチバイト文字)
- Tab 補完を確定した後にコマンド履歴が失われる・壊れる問題を修正
- Ctrl+U / Ctrl+W などの編集キーがコマンド履歴に書き込まれる問題を修正(「2 つのコマンドが連結される」症状)
- `cd ~/ディレクトリ` や `cd $HOME/...` が正しく記憶され、新しいターミナルで復元されます
- CJK 文字を含む行内のリンクのクリック範囲がずれない。極端に小さいサイズをターミナルに送らない
- SSH セッションは実際の終了コードを表示。ZMODEM のタイムアウト・エラーでターミナルやログに文字化けを流し込まない
- セッション復元に失敗しても、その実行中のスナップショット保存が止まらなくなりました
- モニターの CPU / ネットワーク履歴グラフがリアルタイムに再描画されます。SSH ワークスペース非表示中はポーリングを停止
- ブロードキャスト:SSH 分割の片方を閉じてももう片方がブロードキャスト対象に残ります。チェックを外しても他の選択をクリアしない
- 接続失敗時に実際の理由を表示。ダブルクリックで重複接続しない
- 「他を閉じる / 右側を閉じる」がタブを飛ばして閉じる問題を修正
- 言語切り替えが最初のフレームから有効。テーマ切り替え後にアクティブタブの文字色が自動で調整され、明るいテーマでも読める
- 秘密鍵パス欄の説明を「この PC 上のパス」に修正(以前はサーバー上のパスと表示され、その通り入力すると接続に失敗していました)
- ウィンドウへのファイル ドロップによるナビゲーションを禁止。外部リンクは http(s) / ftp のみ。IPC に送信元チェックを追加
- 保存パスワードはパスワード認証のブックマークにのみ使用(鍵認証のブックマークがパスワードをフォールバック送信しない)
- 接続ブックマークやホスト指紋をアトミックに書き込み、クラッシュでデータが消えない
- レンダラープロセスの異常終了時に、そのセッションとログを自動回収
- 破損したカスタムテーマでアプリが起動しなくなる問題を修正
- 更新チャネルの公開をアトミックに。公開中の失敗で自動更新が使えなくなることはなくなりました
## v1.0.13 - 2026-09-20
- 簡体字中国語 / 繁体字中国語 / English / 日本語 に対応。設定 → システム → 表示言語 から切り替え、即時反映され保存されます
+42
View File
@@ -1,5 +1,47 @@
# OpenTerminal 更新日志
## v1.0.15 - 2026-09-20
- **自定义终端背景图片**:设置 → 主题 → 背景图片,可为终端指定任意本地图片作为背景,并支持 10%–100% 的图片不透明度调节;移除图片后恢复纯色背景
- **主题编辑器重名提醒**:新建/编辑主题与内置或其他主题重名时给出黄色提示(仍可保存)
- 主题编辑器种子颜色自动规范化,非法颜色值不再能进入自定义主题
- 自定义主题颜色数据损坏时自动修复为默认色,并记录告警日志
- 设置弹窗左侧导航选中项文字改为白色,与未选中项对比度一致(修复蓝色文字在深色背景上看不清的问题)
- 设置弹窗背景图片、透明度等新增控件与四语言(简/繁/英/日)文案同步上线
- 渲染进程与主进程新增冻结时长探测日志,便于后续诊断"卡死无响应"类问题
## v1.0.14 - 2026-09-20
- 修复上传 **大于约 250KB** 的文件会被静默损坏的问题(文件大小正确但内容出现字节错乱)
- 修复每次下载泄漏一个远端文件句柄、每次传输遗留一个 SFTP 通道的问题;服务器协议异常不再导致整个应用退出
- 上传遇到同名文件时先询问是否覆盖;删除多个文件时部分失败会如实报告
- 权限编辑修复:未知权限的文件不再误发 `chmod 000`;GID 留空不再被误改成 UID 的值;正确显示并保留 setuid / setgid / sticky 特殊位
- chmod / chown 增加超时,远端无响应不再永久转圈
- 修复 SSH 输出中文乱码(跨网络包被截断的多字节字符)
- 修复按 Tab 接受补全后命令历史丢失或记录错乱的问题
- 修复 Ctrl+U / Ctrl+W 等编辑键被写进命令历史(表现为历史里出现"两条命令拼接")
- `cd ~/目录`、`cd $HOME/...` 现在能正确记忆目录,新终端按此恢复
- 中文行内的网址链接点击范围不再错位;窗口尺寸过小时不再向终端发送异常尺寸
- SSH 会话退出时显示真实退出码;ZMODEM 超时/出错不再向终端和日志倾倒乱码
- 启动恢复失败不再导致本次运行期间会话快照永久停止保存
- 监控面板 CPU / 网络历史曲线现在会实时重绘;切到本地终端工作区时停止向服务器轮询
- 广播输入:SSH 分屏关闭一侧不再让另一侧丢失广播目标;取消勾选一个目标不再清空其余选择
- 连接失败时显示真实原因(密码错误 / 拒绝连接等),双击不再重复创建连接
- 修复"关闭其他 / 关闭右侧"会漏关标签的问题
- 界面语言切换首帧即生效;切换主题后活动标签文字颜色自动适配,不再出现浅色主题下看不清
- 私钥路径字段提示纠正为"本机路径"(此前提示为服务器路径,照做会连接失败)
- 禁止把文件拖入窗口导航;外部链接仅允许 http(s) / ftp;IPC 增加来源校验
- 仅密码认证的连接才使用存储的密码(密钥认证的连接不再回退发送密码)
- 连接书签、主机指纹等配置改为原子写入,崩溃不再导致数据丢失
- 渲染进程异常退出时自动回收其全部终端会话与日志
- 自定义主题数据损坏不再导致应用无法启动
- 内置更新通道发布改为原子操作,发布中途失败不再导致自动更新不可用
## v1.0.13 - 2026-09-20
- 支持简体中文 / 繁體中文 / English / 日本語,入口在「设置 → 系统 → 界面语言」,切换即时生效并持久化
+42
View File
@@ -1,5 +1,47 @@
# OpenTerminal 更新日誌
## v1.0.15 - 2026-09-20
- **自訂終端機背景圖片**:設定 → 主題 → 背景圖片,可為終端機指定任意本機圖片作為背景,並支援 10%–100% 的圖片不透明度調整;移除圖片後恢復純色背景
- **主題編輯器重名提醒**:新增/編輯主題與內建或其他主題重名時顯示黃色提示(仍可儲存)
- 主題編輯器種子顏色自動規範化,非法顏色值不再能進入自訂主題
- 自訂主題顏色資料損壞時自動修復為預設色,並記錄警告日誌
- 設定彈窗左側導覽選取項文字改為白色,與未選取項對比一致(修復藍色文字在深色背景上看不清的問題)
- 背景圖片、透明度等新控件與四種語言(簡/繁/英/日)文案同步上線
- 渲染程序與主程序新增凍結時長探測日誌,便於後續診斷「卡死無反應」類問題
## v1.0.14 - 2026-09-20
- 修復上傳 **大於約 250KB** 的檔案會被靜默損壞的問題(檔案大小正確但內容出現位元組錯亂)
- 修復每次下載洩漏一個遠端檔案句柄、每次傳輸遺留一個 SFTP 通道的問題;伺服器協定異常不再導致整個應用結束
- 上傳遇到同名檔案時先詢問是否覆蓋;刪除多個檔案時部分失敗會如實報告
- 權限編輯修復:未知權限的檔案不再誤發 `chmod 000`;GID 留空不再被誤改成 UID 的值;正確顯示並保留 setuid / setgid / sticky 特殊位
- chmod / chown 增加逾時,遠端無回應不再永久轉圈
- 修復 SSH 輸出中文亂碼(跨網路封包被截斷的多位元組字元)
- 修復按 Tab 接受補全後命令歷史丟失或記錯亂的問題
- 修復 Ctrl+U / Ctrl+W 等編輯鍵被寫進命令歷史(表現為歷史裡出現「兩條命令拼接」)
- `cd ~/目錄`、`cd $HOME/...` 現在能正確記憶目錄,新終端按此恢復
- 中文行內的網址連結點擊範圍不再錯位;視窗尺寸過小時不再向終端發送異常尺寸
- SSH 連線結束時顯示真實離開代碼;ZMODEM 逾時/出錯不再向終端和日誌傾倒亂碼
- 啟動恢復失敗不再導致本次執行期間工作階段快照永久停止儲存
- 監控面板 CPU / 網路歷史曲線現在會即時重繪;切到本地終端工作區時停止向伺服器輪詢
- 廣播輸入:SSH 分屏關閉一側不再讓另一側丟失廣播目標;取消勾選一個目標不再清空其餘選擇
- 連線失敗時顯示真實原因(密碼錯誤/拒絕連線等),雙擊不再重複建立連線
- 修復「關閉其他 / 關閉右側」會漏關標籤的問題
- 介面語言切換首影格即生效;切換主題後活動標籤文字顏色自動適配,不再出現淺色主題下看不清
- 私鑰路徑欄位提示更正為「本機路徑」(此前提示為伺服器路徑,照做會連線失敗)
- 禁止把檔案拖入視窗導覽;外部連結僅允許 http(s) / ftp;IPC 增加來源校驗
- 僅密碼認證的連線才使用儲存的密碼(金鑰認證的連線不再回退發送密碼)
- 連線書籤、主機指紋等設定改為原子寫入,當機不再導致資料丟失
- 渲染程序異常結束時自動回收其全部終端連線與日誌
- 自訂主題資料損壞不再導致應用無法啟動
- 內建更新通道發布改為原子操作,發布中途失敗不再導致自動更新不可用
## v1.0.13 - 2026-09-20
- 支援簡體中文 / 繁體中文 / English / 日本語,入口在「設定 → 系統 → 介面語言」,切換即時生效並持久化
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "open-terminal",
"version": "1.0.13",
"version": "1.0.14",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "open-terminal",
"version": "1.0.13",
"version": "1.0.14",
"license": "MIT",
"dependencies": {
"@lydell/node-pty": "^1.2.0-beta.15",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "open-terminal",
"productName": "OpenTerminal",
"version": "1.0.13",
"version": "1.0.15",
"description": "Open-source terminal with SSH, split panes, themes and fonts",
"main": "out/main/index.js",
"author": "Bill",
+26 -12
View File
@@ -200,21 +200,35 @@ async function giteaChannel() {
for (const [f, name] of ordered) {
const stat = fs.statSync(f)
const url = `${base}/${encodeURIComponent(name)}`
const resp = await fetch(url, {
method: 'PUT',
headers: { Authorization: `token ${env.GIT_TOKEN}`, 'Content-Type': 'application/octet-stream', 'Content-Length': String(stat.size) },
body: fs.createReadStream(f),
duplex: 'half'
})
const put = async () =>
fetch(url, {
method: 'PUT',
headers: { Authorization: `token ${env.GIT_TOKEN}`, 'Content-Type': 'application/octet-stream', 'Content-Length': String(stat.size) },
body: fs.createReadStream(f),
duplex: 'half'
})
let resp = await put()
console.log(` put ${name}: HTTP ${resp.status}`)
if (!resp.ok && (resp.status === 409 || resp.status === 422)) {
if (/\d+\.\d+\.\d+/.test(name)) {
// Version-named payloads are immutable per release: accept a stored
// copy only when it has exactly the same size.
if ((await channelFileSize(url)) === stat.size) {
console.log(` ${name} is already published with the same size, kept`)
continue
}
} else {
// latest.yml / release-notes.md change every release and the atomic
// flow no longer wipes the channel up front, so replace them in place.
// The swap window is one small file (sub-second), not the whole channel.
const del = await fetch(url, { method: 'DELETE', headers: { Authorization: `token ${env.GIT_TOKEN}` } })
console.log(` delete old ${name}: HTTP ${del.status}`)
resp = await put()
console.log(` put ${name}: HTTP ${resp.status}`)
}
}
if (!resp.ok) {
const detail = (await resp.text()).slice(0, 200)
// Re-publishing the same version can hit an already-stored file; accept it
// only when the stored copy has exactly the same size.
if ((resp.status === 409 || resp.status === 422) && (await channelFileSize(url)) === stat.size) {
console.log(` ${name} is already published with the same size, kept`)
continue
}
throw new Error(`channel put failed (${resp.status}) for ${name}: ${detail}`)
}
}
+35 -1
View File
@@ -1,6 +1,7 @@
import { app, BrowserWindow, globalShortcut, nativeImage, shell } from 'electron'
import { app, BrowserWindow, globalShortcut, net, nativeImage, protocol, shell } from 'electron'
import { existsSync } from 'fs'
import { join } from 'path'
import { pathToFileURL } from 'url'
import { isTrustedRendererUrl, registerIpc } from './ipc'
import { killAllPtys, killPtysByOwner } from './pty'
import { applyStartupSystemSettings, loadSettings } from './settingsStore'
@@ -45,6 +46,14 @@ if (!app.isPackaged) {
app.setPath('userData', join(app.getPath('appData'), 'OpenTerminal-dev'))
}
// Custom background image (设置 → 主题): the renderer page cannot load file:
// subresources directly (Chromium blocks them from non-file origins), so it
// references them through this scheme instead. The handler serves exactly one
// file — the configured background image — nothing else.
protocol.registerSchemesAsPrivileged([
{ scheme: 'otimg', privileges: { secure: true, supportFetchAPI: false, corsEnabled: false } }
])
// Single instance: a second launch just surfaces the existing window (pulls
// it out of the tray if hidden there) instead of starting another process.
// The refused instance skips the whole startup path: `app.quit()` only asks
@@ -57,6 +66,19 @@ if (!gotSingleInstanceLock) {
app.on('second-instance', () => showOrCreate())
app.whenReady().then(() => {
// Serve the configured background image (path lives in settings; anything
// else — including a path that is no longer configured — is refused, so the
// protocol cannot be used to read arbitrary files).
protocol.handle('otimg', (request) => {
const url = new URL(request.url)
const requested = decodeURIComponent(url.pathname.replace(/^\//, ''))
const allowed = loadSettings().terminal.backgroundImage
if (allowed === '' || requested !== allowed || !existsSync(requested)) {
return new Response('', { status: 403 })
}
return net.fetch(pathToFileURL(requested).toString())
})
registerIpc()
registerUpdateIpc()
// Before the window exists: a renderer-triggered check must not run against
@@ -167,6 +189,18 @@ process.on('uncaughtException', (err) => {
console.error('[main] uncaughtException:', err)
})
// Diagnostics for "app froze then recovered" reports: WER logs an
// AppHangTransient but keeps no stack. A stall of THIS (UI) thread is what
// Windows flags as a hang, so measure event-loop lag and say so loudly when
// it happens — that distinguishes a main-process block from a renderer one.
let lastTick = Date.now()
setInterval(() => {
const now = Date.now()
const lag = now - lastTick - 1000
if (lag > 2000) console.error(`[main] event loop stalled ~${lag}ms`)
lastTick = now
}, 1000).unref()
app.on('before-quit', () => {
// Let window 'close' events pass through so teardown completes.
markQuitting()
+7 -3
View File
@@ -138,11 +138,15 @@ function sanitizeThemes(value: unknown, warnings: Warnings): TerminalTheme[] {
: null
const colors: ThemeColors = { ...DEFAULT_DARK.colors }
const target = colors as unknown as Record<string, string>
const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i
for (const key of THEME_COLOR_KEYS) {
const color = candidate?.[key]
if (typeof color === 'string' && color !== '') target[key] = color
else if (color !== undefined) {
warnings.push(`customThemes[${index}].colors.${key} repaired → built-in default`)
// Only well-formed hex colours survive: xterm would render anything else
// as black, and the theme editor's native colour input needs #rrggbb.
if (typeof color === 'string' && HEX_COLOR.test(color.trim())) {
target[key] = color.trim()
} else if (color !== undefined) {
warnings.push(`customThemes[${index}].colors.${key}: not a hex color — repaired`)
}
}
themes.push({
+1 -1
View File
@@ -5,7 +5,7 @@
<title>OpenTerminal</title>
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' file: data: otimg:"
/>
</head>
<body>
+7 -6
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useSyncExternalStore } from 'react'
import { useEffect, useState } from 'react'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import zhTW from 'antd/locale/zh_TW'
@@ -9,7 +9,7 @@ import { SettingsDialog } from '@renderer/settings/SettingsDialog'
import { TransferPanel } from '@renderer/sftp/TransferPanel'
import { useSettingsStore } from '@renderer/settings/store'
import { getThemeById } from '@shared/theme'
import { DEFAULT_LANGUAGE, getLanguage, onLanguageChange, setLanguage, type Language } from '@shared/i18n'
import { DEFAULT_LANGUAGE, syncLanguage, type Language } from '@shared/i18n'
import { applyChromeTheme, applyTabAccent } from '@renderer/theme/chrome'
import appIconUrl from '../../../build/icon.png'
@@ -50,10 +50,11 @@ export default function App(): React.JSX.Element {
}, [hydrate])
// Interface language: t() reads the module-level language at render time, so
// sync it before the tree renders — an effect would paint one frame late. The
// subscription re-renders every t() caller when the language changes elsewhere.
if (getLanguage() !== storedLanguage) setLanguage(storedLanguage)
const language = useSyncExternalStore(onLanguageChange, getLanguage)
// sync it before the tree renders — an effect would paint one frame late.
// Silent on purpose: notifying subscribers during a render is what React
// warns about; every language change re-renders App via the settings store.
syncLanguage(storedLanguage)
const language = storedLanguage
useEffect(() => {
document.documentElement.lang = language
}, [language])
+13
View File
@@ -11,6 +11,19 @@ import { useSettingsStore } from './settings/store'
import { mix } from './theme/chrome'
import './global.css'
// Diagnostics: report renderer main-thread freezes after recovery. console.error
// is surfaced into the dev terminal by the main process's console-message hook,
// so a "卡死又恢复" report tells us which process stalled and for how long.
{
let lastTick = performance.now()
setInterval(() => {
const now = performance.now()
const lag = now - lastTick - 2000
if (lag > 3000) console.error(`[renderer] main thread stalled ~${Math.round(lag)}ms`)
lastTick = now
}, 2000)
}
// Dev convenience: allow opening the renderer in a plain browser (vite page)
// so layout/UX work doesn't require the electron shell. No-op under electron.
if (typeof window !== 'undefined' && !window.api) {
+38 -1
View File
@@ -1,5 +1,5 @@
import { useMemo } from 'react'
import { Button, ColorPicker, Popconfirm } from 'antd'
import { Button, ColorPicker, Popconfirm, Slider } from 'antd'
import { t } from '@shared/i18n'
import type { TerminalSettings } from '@shared/settings'
import { DEFAULT_SETTINGS } from '@shared/settings'
@@ -46,8 +46,45 @@ export function ThemeSettingsTab({
await setCustomThemes(next)
}
const pickImage = async (): Promise<void> => {
const files = await window.api.pickFiles()
const image = files.find((f) => /\.(png|jpe?g|bmp|gif|webp|avif)$/i.test(f))
if (image) await updateTerminal({ backgroundImage: image })
}
return (
<div className="theme-pane">
<div className="theme-accent-row">
<div>
<div className="settings-block-label">{t('settings.theme.backgroundImage')}</div>
<div className="settings-block-hint">{t('settings.theme.backgroundImageDesc')}</div>
</div>
<div className="theme-accent-controls">
<Button size="small" onClick={() => void pickImage()}>
{t('settings.theme.chooseImage')}
</Button>
{settings.terminal.backgroundImage !== '' && (
<Button size="small" onClick={() => void updateTerminal({ backgroundImage: '' })}>
{t('settings.theme.clearImage')}
</Button>
)}
</div>
</div>
{settings.terminal.backgroundImage !== '' && (
<div className="theme-accent-row">
<div>
<div className="settings-block-label">{t('settings.theme.imageOpacity')}</div>
</div>
<Slider
style={{ width: 200 }}
min={10}
max={100}
step={5}
value={settings.terminal.backgroundImageOpacity}
onChange={(v) => void updateTerminal({ backgroundImageOpacity: v })}
/>
</div>
)}
<div className="theme-accent-row">
<div>
<div className="settings-block-label">{t('settings.theme.accent')}</div>
+15
View File
@@ -44,6 +44,13 @@
background: color-mix(in srgb, var(--tab-accent, #3fb950) 16%, transparent);
}
/* antd paints the active tab label in the primary blue, which is hard to read
on the accent-tinted row; keep it identical to the inactive labels. The
extra .ant-tabs-tab class out-specifies antd's runtime-injected rule. */
.settings-body .ant-tabs-left > .ant-tabs-nav .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: #ffffff;
}
.settings-body .ant-tabs-left > .ant-tabs-nav .ant-tabs-ink-bar {
background: var(--tab-accent, #3fb950);
}
@@ -575,3 +582,11 @@
.shortcut-input.is-recording .ant-input {
border-color: var(--tab-accent, #3fb950);
}
/* theme editor: duplicate-name notice under the name field */
.theme-editor-hint {
margin: -4px 0 10px;
padding-left: 2px;
font-size: 12px;
color: #d29922;
}
+33 -5
View File
@@ -67,8 +67,20 @@ const SEARCH_DECORATIONS: NonNullable<NonNullable<Parameters<SearchAddon['findNe
// xterm's default overviewRulerBorder (#7f7f7f) renders as a light vertical line
// on the dark surface once scrollback exists. Force it transparent; search-match
// marks in the ruler keep their own colors.
function withChromeColors(colors: ITheme): ITheme {
return { ...colors, overviewRulerBorder: '#00000000' }
function withChromeColors(colors: ITheme, transparentBackground: boolean): ITheme {
return {
...colors,
overviewRulerBorder: '#00000000',
// While a custom background image is set the xterm surface goes fully
// transparent so the image layer behind the host is what shows through.
...(transparentBackground ? { background: '#00000000' } : {})
}
}
/** URL for a background image, served by the main process's otimg:// handler
* (the page itself cannot reference file: paths from non-file origins). */
function toFileUrl(path: string): string {
return `otimg://bg/${encodeURIComponent(path)}`
}
export interface TerminalHandle {
@@ -673,8 +685,9 @@ export const TerminalView: ForwardRefExoticComponent<TerminalViewProps & { ref?:
cursorBlink: tSettings.cursorBlink,
cursorStyle: tSettings.cursorStyle,
cursorInactiveStyle: tSettings.cursorInactiveStyle,
theme: withChromeColors(getThemeById(tSettings.themeId, settings.customThemes).colors as ITheme),
theme: withChromeColors(getThemeById(tSettings.themeId, settings.customThemes).colors as ITheme, Boolean(tSettings.backgroundImage)),
allowProposedApi: true,
allowTransparency: true,
overviewRuler: { width: 9, showTopBorder: false, showBottomBorder: false },
drawBoldTextInBrightColors: true,
minContrastRatio: 1,
@@ -1009,7 +1022,7 @@ export const TerminalView: ForwardRefExoticComponent<TerminalViewProps & { ref?:
// Live-appliable in xterm 6: without this the setting only took effect for
// terminals opened after the change, which reads as "the setting is broken".
term.options.scrollback = tSettings.scrollback
term.options.theme = withChromeColors(getThemeById(tSettings.themeId, settings.customThemes).colors as ITheme)
term.options.theme = withChromeColors(getThemeById(tSettings.themeId, settings.customThemes).colors as ITheme, Boolean(tSettings.backgroundImage))
scheduleFit()
}, [tSettings, settings.customThemes, scheduleFit])
@@ -1048,7 +1061,13 @@ export const TerminalView: ForwardRefExoticComponent<TerminalViewProps & { ref?:
[sessionId]
)
const terminalClassName = useMemo(() => ['terminal-view', className].filter(Boolean).join(' '), [className])
const terminalClassName = useMemo(
() =>
['terminal-view', settings.terminal.backgroundImage !== '' && 'has-bg-image', className]
.filter(Boolean)
.join(' '),
[className, settings.terminal.backgroundImage]
)
/**
* [M5] Compute and store the floating popup position so it hugs the text
@@ -1277,6 +1296,15 @@ export const TerminalView: ForwardRefExoticComponent<TerminalViewProps & { ref?:
</div>
)}
<div className="terminal-view-dock" ref={hostRef}>
{settings.terminal.backgroundImage !== '' && (
<div
className="term-bg-image"
style={{
backgroundImage: `url("${toFileUrl(settings.terminal.backgroundImage)}")`,
opacity: Math.min(100, Math.max(10, settings.terminal.backgroundImageOpacity)) / 100
}}
/>
)}
{dead && (
<div className="term-dead-mask">
<div>{t('terminal.dead.message', { code: exitCode })}</div>
+26 -2
View File
@@ -15,11 +15,17 @@
/* xterm.css defaults .xterm-viewport to #000; when the pane height isn't a
multiple of the cell height the leftover bottom strip shows that black.
Pin it to the (theme-derived) chrome background so the gap is invisible. */
.terminal-view .xterm .xterm-viewport {
Pin it to the (theme-derived) chrome background so the gap is invisible.
With a custom background image the viewport must stay transparent — this
opaque layer would cover the .term-bg-image behind the xterm surface. */
.terminal-view:not(.has-bg-image) .xterm .xterm-viewport {
background-color: var(--chrome-bg);
}
.terminal-view.has-bg-image .xterm .xterm-viewport {
background-color: transparent;
}
/* Slim slate scrollbar for the xterm viewport — the native Windows one renders
light track + arrow buttons that look broken on the dark surface. The thumb
sits inset inside a wider grab lane (transparent border + padding-box clip)
@@ -353,6 +359,24 @@
padding: 0;
}
/* ---- custom background image (设置 → 主题) ----
Sits behind the xterm screen; while an image is set the theme background is
transparent (allowTransparency), so this layer is what shows through. */
.term-bg-image {
position: absolute;
inset: 0;
z-index: 0;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
pointer-events: none;
}
.terminal-view-dock > .xterm {
position: relative;
z-index: 1;
}
/* ---- dead process overlay ---- */
.term-dead-mask {
position: absolute;
+20 -3
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'
import { Input, Modal } from 'antd'
import { t } from '@shared/i18n'
import type { ThemeColors, TerminalTheme } from '@shared/theme'
import { DEFAULT_DARK, getThemeById } from '@shared/theme'
import { BUILTIN_THEMES, DEFAULT_DARK, getThemeById } from '@shared/theme'
import { useSettingsStore } from '../../settings/store'
export interface ThemeEditorProps {
@@ -49,6 +49,17 @@ const ANSI_KEYS: FieldSpec[] = [
{ key: 'brightWhite', label: 'Bright White' }
]
/** The native colour input only accepts #rrggbb: clamp every seeded value so a
* hand-edited or migrated theme can't render the picker as solid black. */
function normalizeThemeColors(colors: ThemeColors, fallback: ThemeColors): ThemeColors {
const out = { ...fallback }
for (const key of Object.keys(fallback) as (keyof ThemeColors)[]) {
const value = colors[key] ?? ''
out[key] = /^#[0-9a-f]{6}$/i.test(value) ? value : (fallback[key] ?? '')
}
return out
}
export function ThemeEditor({ open, onClose, themeId }: ThemeEditorProps): React.JSX.Element {
const settings = useSettingsStore((s) => s.settings)
const updateTerminal = useSettingsStore((s) => s.updateTerminal)
@@ -64,6 +75,11 @@ export function ThemeEditor({ open, onClose, themeId }: ThemeEditorProps): React
const [name, setName] = useState('')
const [colors, setColors] = useState<ThemeColors>(DEFAULT_DARK.colors)
const [saving, setSaving] = useState(false)
/** another theme (builtin or custom) already uses this name (allowed, but the user should know) */
const duplicateName =
name.trim() !== '' &&
(BUILTIN_THEMES.some((th) => th.name === name.trim()) ||
settings.customThemes.some((th) => th.id !== themeId && th.name === name.trim()))
// (re)initialize the form each time the modal opens
useEffect(() => {
@@ -75,12 +91,12 @@ export function ThemeEditor({ open, onClose, themeId }: ThemeEditorProps): React
return
}
setName(editingTheme.name)
setColors({ ...editingTheme.colors })
setColors(normalizeThemeColors(editingTheme.colors, DEFAULT_DARK.colors))
} else {
/** create mode: seed a fresh copy based on the currently active theme */
const active = getThemeById(settings.terminal.themeId, settings.customThemes)
setName(active.name + t('settings.themeEditor.copySuffix'))
setColors({ ...active.colors })
setColors(normalizeThemeColors(active.colors, DEFAULT_DARK.colors))
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open])
@@ -141,6 +157,7 @@ export function ThemeEditor({ open, onClose, themeId }: ThemeEditorProps): React
maxLength={60}
/>
</div>
{duplicateName && <div className="theme-editor-hint">{t('settings.themeEditor.duplicateName')}</div>}
<div className="theme-editor-colors">
{headerKeys().map((spec) => (
+6
View File
@@ -139,12 +139,18 @@ const settings: Record<string, string> = {
'settings.highlight.builtin.url': 'Web links',
'settings.theme.accent': 'Tab accent color',
'settings.theme.accentDesc': 'Accent color for the active tab border, the sidebar indicator, and SSH badges',
'settings.theme.backgroundImage': 'Background image',
'settings.theme.backgroundImageDesc': 'Show an image behind the terminal; remove it to go back to a solid background',
'settings.theme.chooseImage': 'Choose image',
'settings.theme.clearImage': 'Remove',
'settings.theme.imageOpacity': 'Image opacity',
'settings.theme.customBadge': 'Custom',
'settings.theme.deleteTitle': 'Delete custom theme',
'settings.theme.create': 'New theme',
'settings.theme.editTitle': 'Edit theme',
'settings.themeEditor.name': 'Name',
'settings.themeEditor.namePlaceholder': 'Theme name',
'settings.themeEditor.duplicateName': 'Same name as another theme (saving is still allowed)',
'settings.themeEditor.copySuffix': ' (copy)',
'settings.about.currentVersion': 'Current version',
'settings.about.statusIdle': 'Click to check for updates',
+6
View File
@@ -136,12 +136,18 @@ const settings: Record<string, string> = {
'settings.highlight.builtin.url': 'ウェブリンク',
'settings.theme.accent': 'タブのアクセントカラー',
'settings.theme.accentDesc': 'アクティブなタブの枠線、サイドバーのインジケーター、SSH バッジのアクセントカラー',
'settings.theme.backgroundImage': '背景画像',
'settings.theme.backgroundImageDesc': 'ターミナルの背後に画像を表示します。削除すると無地の背景に戻ります',
'settings.theme.chooseImage': '画像を選択',
'settings.theme.clearImage': '削除',
'settings.theme.imageOpacity': '画像の不透明度',
'settings.theme.customBadge': 'カスタム',
'settings.theme.deleteTitle': 'カスタムテーマを削除',
'settings.theme.create': '新しいテーマ',
'settings.theme.editTitle': 'テーマを編集',
'settings.themeEditor.name': '名前',
'settings.themeEditor.namePlaceholder': 'テーマ名',
'settings.themeEditor.duplicateName': '他のテーマと同名です(保存は可能)',
'settings.themeEditor.copySuffix': '(コピー)',
'settings.about.currentVersion': '現在のバージョン',
'settings.about.statusIdle': 'クリックして更新を確認',
+6
View File
@@ -133,12 +133,18 @@ const settings: Record<string, string> = {
'settings.highlight.builtin.url': '网址链接',
'settings.theme.accent': '标签强调色',
'settings.theme.accentDesc': '活动标签边框、侧栏指示条与 SSH 徽章的强调颜色',
'settings.theme.backgroundImage': '背景图片',
'settings.theme.backgroundImageDesc': '为终端设置一张背景图片;移除后恢复纯色背景',
'settings.theme.chooseImage': '选择图片',
'settings.theme.clearImage': '移除图片',
'settings.theme.imageOpacity': '图片不透明度',
'settings.theme.customBadge': '自定义',
'settings.theme.deleteTitle': '删除自定义主题',
'settings.theme.create': '新建主题',
'settings.theme.editTitle': '编辑主题',
'settings.themeEditor.name': '名称',
'settings.themeEditor.namePlaceholder': '主题名称',
'settings.themeEditor.duplicateName': '与其他主题重名,仍可保存',
'settings.themeEditor.copySuffix': '(副本)',
'settings.about.currentVersion': '当前版本',
'settings.about.statusIdle': '点击检查更新',
+6
View File
@@ -133,12 +133,18 @@ const settings: Record<string, string> = {
'settings.highlight.builtin.url': '網址連結',
'settings.theme.accent': '標籤強調色',
'settings.theme.accentDesc': '作用中標籤的邊框、側邊欄指示條與 SSH 徽章的強調顏色',
'settings.theme.backgroundImage': '背景圖片',
'settings.theme.backgroundImageDesc': '為終端設定一張背景圖片;移除後恢復純色背景',
'settings.theme.chooseImage': '選擇圖片',
'settings.theme.clearImage': '移除圖片',
'settings.theme.imageOpacity': '圖片不透明度',
'settings.theme.customBadge': '自訂',
'settings.theme.deleteTitle': '刪除自訂主題',
'settings.theme.create': '新增主題',
'settings.theme.editTitle': '編輯主題',
'settings.themeEditor.name': '名稱',
'settings.themeEditor.namePlaceholder': '主題名稱',
'settings.themeEditor.duplicateName': '與其他主題同名,仍可儲存',
'settings.themeEditor.copySuffix': '(副本)',
'settings.about.currentVersion': '目前版本',
'settings.about.statusIdle': '點擊檢查更新',
+9
View File
@@ -70,6 +70,15 @@ export function setLanguage(lang: Language): void {
for (const listener of listeners) listener(lang)
}
/** Render-time sync for the React tree: update the module language WITHOUT
* notifying subscribers — firing listeners during another component's render
* makes React warn ("cannot update a component while rendering a different
* component"). Renderer components re-render via the settings store instead;
* the notifying setLanguage stays for the main process (tray rebuild). */
export function syncLanguage(lang: Language): void {
current = lang
}
export function getLanguage(): Language {
return current
}
+7 -1
View File
@@ -49,6 +49,10 @@ export interface TerminalSettings {
showOpenCwdButton: boolean
/** accent color for the active tab outline, rail indicator and SSH badges */
tabAccentColor: string
/** absolute path to an image rendered behind the terminal; '' = none */
backgroundImage: string
/** background image layer opacity, 10..100 (%) */
backgroundImageOpacity: number
}
export interface SystemSettings {
@@ -132,7 +136,9 @@ export const DEFAULT_SETTINGS: AppSettings = {
showRecButton: false,
showOpenLogsButton: false,
showOpenCwdButton: true,
tabAccentColor: '#3fb950'
tabAccentColor: '#3fb950',
backgroundImage: '',
backgroundImageOpacity: 60
},
customThemes: [],
highlightRules: DEFAULT_HIGHLIGHT_RULES,