Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions src-tauri/src/desktop_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,36 +225,34 @@ pub(crate) fn integrate(app: &tauri::AppHandle) {
/// Removes the entry and the icon (the in-app uninstall), as lines for the
/// uninstall log: nothing when there was nothing to remove (a development
/// build), one line per file that could not be removed.
pub(crate) fn remove(app: &tauri::AppHandle) -> Vec<String> {
pub(crate) fn remove(app: &tauri::AppHandle) -> Vec<crate::wire::UninstallStep> {
Files::for_app(app).map(|f| f.remove()).unwrap_or_default()
}

impl Files {
fn remove(&self) -> Vec<String> {
fn remove(&self) -> Vec<crate::wire::UninstallStep> {
use crate::wire::UninstallStep;
let mut log = Vec::new();
let mut removed = false;
for path in [&self.desktop, &self.icon] {
match std::fs::remove_file(path) {
Ok(()) => removed = true,
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => log.push(tr!(
Err(e) => log.push(UninstallStep::failed(tr!(
format!("未能删除 {}({e})", path.display()),
format!("{} could not be deleted ({e})", path.display())
)),
))),
}
}
if removed {
if let Some(dir) = self.desktop.parent() {
run("update-desktop-database", &[dir.as_os_str()]);
}
if log.is_empty() {
log.push(
tr!(
"已移除应用菜单中的条目",
"The application menu entry was removed"
)
.into(),
);
log.push(UninstallStep::done(tr!(
"已移除应用菜单中的条目",
"The application menu entry was removed"
)));
}
}
log
Expand Down Expand Up @@ -326,7 +324,9 @@ mod tests {
assert!(f.remove().is_empty());
write_if_changed(&f.desktop, b"[Desktop Entry]\n").unwrap();
write_if_changed(&f.icon, ICON).unwrap();
assert_eq!(f.remove().len(), 1);
let out = f.remove();
assert_eq!(out.len(), 1);
assert!(out[0].ok, "{}", out[0].text);
assert!(!f.desktop.exists() && !f.icon.exists());
std::fs::remove_dir_all(&dir).unwrap();
}
Expand Down
48 changes: 28 additions & 20 deletions src-tauri/src/uninstall.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! 还原全部接管,以及卸载。

use crate::{autostart, data_dir, error::Out};
use crate::{autostart, data_dir, error::Out, wire::UninstallStep};

/// 把所有接管过的客户端一次性还原(第二层的第二个入口)。
///
Expand Down Expand Up @@ -51,45 +51,53 @@ pub struct RestoreOutcome {
///
/// **我们不删自己。**macOS 上应用删除没有钩子,也不该由应用自己动手 ——
/// 最后一句话是「可以把应用拖进废纸篓了」,那一下由用户来。
///
/// 每一步交回做成了没有(`UninstallStep`),一步没做成不影响后面的步骤。
#[tauri::command]
pub async fn uninstall(app: tauri::AppHandle, drop_data: bool) -> Out<Vec<String>> {
pub async fn uninstall(app: tauri::AppHandle, drop_data: bool) -> Out<Vec<UninstallStep>> {
let mut log = Vec::new();
for r in restore_all().await? {
log.push(tr!(
format!("{}:{}", r.client, r.detail),
format!("{}: {}", r.client, r.detail)
));
log.push(UninstallStep {
ok: r.ok,
text: tr!(
format!("{}:{}", r.client, r.detail),
format!("{}: {}", r.client, r.detail)
),
});
}
// 注销 LaunchAgent。**失败只记一句**:它不该挡住卸载,而留下一个
// 开机自启项的后果,用户在系统设置里看得见、也删得掉
let launcher = autostart::launcher(&app);
match launcher.disable() {
Ok(_) => log.push(tr!("已取消开机启动", "Launch at login turned off").into()),
Ok(_) => log.push(UninstallStep::done(tr!(
"已取消开机启动",
"Launch at login turned off"
))),
// 退路按平台说:自启项在哪儿、用户去哪儿关,三处各不相同
#[cfg(target_os = "macos")]
Err(e) => log.push(tr!(
Err(e) => log.push(UninstallStep::failed(tr!(
format!(
"未能取消开机启动({e})。请在「系统设置 › 通用 › 登录项」中关闭 ThinkWatch Lite。"
),
format!(
"Launch at login could not be turned off ({e}). Turn off ThinkWatch Lite in System Settings › General › Login Items."
)
)),
))),
#[cfg(windows)]
Err(e) => log.push(tr!(
Err(e) => log.push(UninstallStep::failed(tr!(
format!("未能取消开机启动({e})。请在「设置 › 应用 › 启动」中关闭 ThinkWatch Lite。"),
format!(
"Launch at login could not be turned off ({e}). Turn off ThinkWatch Lite in Settings › Apps › Startup."
)
)),
))),
// 各家桌面的「开机启动的应用」设置不在同一个地方,文件在哪儿却是确定的
#[cfg(target_os = "linux")]
Err(e) => {
let file = launcher.file().display();
log.push(tr!(
log.push(UninstallStep::failed(tr!(
format!("未能取消开机启动({e})。请删除 {file}。"),
format!("Launch at login could not be turned off ({e}). Delete {file}.")
))
)))
}
}
// AppImage 每次启动写的菜单条目和图标(见 `desktop_entry`)。删不掉的
Expand All @@ -99,24 +107,24 @@ pub async fn uninstall(app: tauri::AppHandle, drop_data: bool) -> Out<Vec<String
if drop_data {
let dir = data_dir();
match std::fs::remove_dir_all(&dir) {
Ok(_) => log.push(tr!(
Ok(_) => log.push(UninstallStep::done(tr!(
format!("数据目录已删除:{}", dir.display()),
format!("Data directory deleted: {}", dir.display())
)),
))),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => log.push(tr!(
Err(e) => log.push(UninstallStep::failed(tr!(
format!("未能删除数据目录:{}({e})", dir.display()),
format!(
"The data directory could not be deleted: {} ({e})",
dir.display()
)
)),
))),
}
} else {
log.push(tr!(
log.push(UninstallStep::done(tr!(
format!("数据目录已保留:{}", data_dir().display()),
format!("Data directory kept: {}", data_dir().display())
));
)));
}
// 「废纸篓」只是 macOS 的说法;Windows 上走系统的卸载,Linux 上就是删掉
// 那个 AppImage 文件
Expand All @@ -140,7 +148,7 @@ pub async fn uninstall(app: tauri::AppHandle, drop_data: bool) -> Out<Vec<String
),
None => tr!("现可删除应用。", "The app can now be deleted.").into(),
};
log.push(last);
log.push(UninstallStep::done(last));
Ok(log)
}

Expand Down
29 changes: 29 additions & 0 deletions src-tauri/src/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,35 @@ pub struct KeyUsage {
pub buckets: Vec<tw_api::CostBucketGroup>,
}

// ---------------------------------------------------------- 卸载

/// 完全卸载的一步(`uninstall` 交回的是一串):做成了没有,和给用户看的那句话。
///
/// **成败要单独给,不能让界面从句子里猜。**对话框的标题要说「卸载完成」还是
/// 「有几项没做成」,没做成的那几行要标出来;句子是按语言拼的,拿来判断成败
/// 换一种语言就失效。说明性的几句(数据目录已保留、现在可以删应用了)算成。
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub struct UninstallStep {
pub ok: bool,
pub text: String,
}

impl UninstallStep {
pub fn done(text: impl Into<String>) -> Self {
Self {
ok: true,
text: text.into(),
}
}

pub fn failed(text: impl Into<String>) -> Self {
Self {
ok: false,
text: text.into(),
}
}
}

// ---------------------------------------------------------- 静态扫描

/// 一处扫描发现有多要紧。
Expand Down
1 change: 1 addition & 0 deletions src-tauri/tests/ts_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ fn lite_typescript() -> String {
c.root::<wire::McpTargetView>();
c.root::<wire::McpOpRequest>();
c.root::<wire::LocalEvent>();
c.root::<wire::UninstallStep>();

// **契约里已经有的名字从那边引用**(`Msg`,以及 core 还在发的同名同形的类型),
// 不另写一份:两份同名的声明在 `types.ts` 里一起转出去是歧义
Expand Down
9 changes: 9 additions & 0 deletions src/generated/lite-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,15 @@ export type SkillView = { name: string, client: string, path: string, allowed_to
*/
export type TakesEffect = "immediately" | "on_restart";

/**
* 完全卸载的一步(`uninstall` 交回的是一串):做成了没有,和给用户看的那句话。
*
* **成败要单独给,不能让界面从句子里猜。**对话框的标题要说「卸载完成」还是
* 「有几项没做成」,没做成的那几行要标出来;句子是按语言拼的,拿来判断成败
* 换一种语言就失效。说明性的几句(数据目录已保留、现在可以删应用了)算成。
*/
export type UninstallStep = { ok: boolean, text: string, };

/**
* 一个客户端的接管方式验证到什么程度。
*/
Expand Down
4 changes: 4 additions & 0 deletions src/settings/SettingsPage.i18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ export const settingsText = messages(
dropDataWhat: "包括请求历史、费用记录与配置备份,删除后无法恢复。",
confirmUninstall: "卸载",
uninstalled: "卸载完成",
uninstalledWithFailures: (n: number) => `卸载已结束,${n} 项未成功`,
stepFailed: "未成功",
uninstallFailed: "未能完成卸载",
uninstalledRow: "已完成卸载。",
},
Expand Down Expand Up @@ -155,6 +157,8 @@ export const settingsText = messages(
dropDataWhat: "The request history, cost records and config backups. This cannot be undone.",
confirmUninstall: "Uninstall",
uninstalled: "Uninstall complete",
uninstalledWithFailures: (n: number) => (n === 1 ? "Uninstall finished; 1 step failed" : `Uninstall finished; ${n} steps failed`),
stepFailed: "Failed",
uninstallFailed: "The uninstall did not finish",
uninstalledRow: "The uninstall is complete.",
},
Expand Down
31 changes: 23 additions & 8 deletions src/settings/UninstallSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ import { Button } from "@/ui/button";
import { Checkbox } from "@/ui/checkbox";
import { Skeleton } from "@/ui/skeleton";
import { Spinner } from "@/ui/spinner";
import { StatusDot } from "@/ui/status-dot";
import type { UninstallStep } from "@/types";
import { useResource } from "@/lib/resource";
import { cn } from "@/lib/utils";
import { useText } from "@/i18n";
import { commonText } from "@/i18n/common.i18n";
import { errorText } from "@/i18n/core.i18n";
Expand All @@ -30,7 +33,7 @@ import { settingsText } from "./SettingsPage.i18n";
* 最近一次卸载每一步的结果。**放在模块里**:切到别的页再回来,这一节还记得已经
* 卸载过(这之后用户多半就去把应用移到废纸篓了)。
*/
let lastLog: string[] | null = null;
let lastLog: UninstallStep[] | null = null;

/**
* 完全卸载。
Expand All @@ -57,7 +60,7 @@ export function UninstallSection({ remote }: { remote: RemoteCore | null }) {
label={t.uninstallTitle}
description={
<>
{log ? (log.at(-1) ?? t.uninstalledRow) : t.uninstallIntro(em)}
{log ? (log.at(-1)?.text ?? t.uninstalledRow) : t.uninstallIntro(em)}
{remote && !log && <span className="mt-1 block">{rt.uninstallServer(remote.name)}</span>}
</>
}
Expand All @@ -81,9 +84,13 @@ export function UninstallSection({ remote }: { remote: RemoteCore | null }) {
);
}

type Stage = { kind: "ask" } | { kind: "running" } | { kind: "done"; log: string[] } | { kind: "failed"; error: unknown };
type Stage =
| { kind: "ask" }
| { kind: "running" }
| { kind: "done"; log: UninstallStep[] }
| { kind: "failed"; error: unknown };

function UninstallDialog({ onClose, onDone }: { onClose: () => void; onDone: (log: string[]) => void }) {
function UninstallDialog({ onClose, onDone }: { onClose: () => void; onDone: (log: UninstallStep[]) => void }) {
const t = useText(settingsText);
const common = useText(commonText);
const [drop, setDrop] = useState(false);
Expand All @@ -97,6 +104,8 @@ function UninstallDialog({ onClose, onDone }: { onClose: () => void; onDone: (lo
const adopted = clients.data?.clients.filter((c) => c.adopted_at_ms !== null).map((c) => c.name);
const running = stage.kind === "running";
const done = stage.kind === "done";
/** 没做成的几步。**标题按它说**:有一步没做成还写「卸载完成」,用户就不会往下看是哪一步 */
const failed = stage.kind === "done" ? stage.log.filter((s) => !s.ok).length : 0;

async function run() {
setStage({ kind: "running" });
Expand All @@ -114,16 +123,22 @@ function UninstallDialog({ onClose, onDone }: { onClose: () => void; onDone: (lo
<AlertDialog open onOpenChange={(o) => !o && !running && onClose()}>
<AlertDialogContent className="data-[size=default]:sm:max-w-[440px]">
<AlertDialogHeader>
<AlertDialogTitle className="tw-title">{done ? t.uninstalled : t.uninstallTitle}</AlertDialogTitle>
<AlertDialogTitle className="tw-title">
{!done ? t.uninstallTitle : failed > 0 ? t.uninstalledWithFailures(failed) : t.uninstalled}
</AlertDialogTitle>
{!done && <AlertDialogDescription>{t.willDo}</AlertDialogDescription>}
</AlertDialogHeader>

{stage.kind === "done" ? (
<ul className="flex flex-col gap-1.5 rounded-lg border border-border bg-surface/45 px-3.5 py-3 tw-body">
{stage.log.map((line, i) => (
{stage.log.map((step, i) => (
<li key={i} className="flex gap-2.5 motion-fade">
<span aria-hidden className="mt-[0.6em] size-1 shrink-0 rounded-full bg-muted-foreground" />
<span className="min-w-0 break-words select-text">{line}</span>
{step.ok ? (
<span aria-hidden className="mt-[0.6em] size-1 shrink-0 rounded-full bg-muted-foreground" />
) : (
<StatusDot tone="error" className="mt-[0.45em] shrink-0" label={t.stepFailed} />
)}
<span className={cn("min-w-0 break-words select-text", !step.ok && "text-destructive")}>{step.text}</span>
</li>
))}
</ul>
Expand Down
5 changes: 3 additions & 2 deletions src/settings/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { invoke } from "@tauri-apps/api/core";
import type { Lang } from "@/i18n";
import type { Found, UpdateView } from "@/updateFlow";
import type { UninstallStep } from "@/types";

export type Theme = "light" | "dark";
/** 设置里的三档:`system` 是跟随系统 */
Expand Down Expand Up @@ -63,8 +64,8 @@ export const settingsApi = {
info: () => invoke<AppInfo>("app_info"),
/** 诊断包写在数据目录里,交回路径 */
saveDiagnostics: () => invoke<string>("save_diagnostics"),
/** 还原接管、取消开机启动、按需删数据目录。交回的是每一步的结果,一步一句 */
uninstall: (dropData: boolean) => invoke<string[]>("uninstall", { dropData }),
/** 还原接管、取消开机启动、按需删数据目录。交回的是每一步的结果:做成了没有,和一句话 */
uninstall: (dropData: boolean) => invoke<UninstallStep[]>("uninstall", { dropData }),
};

/**
Expand Down
Loading