Unlucky Launcher v0.0.1-alpha
CI / fmt (rustfmt --check) (push) Canceled after 0s
CI / clippy (ubuntu-latest) (push) Canceled after 0s
CI / clippy (windows-latest) (push) Canceled after 0s
CI / test (ubuntu-latest) (push) Canceled after 0s
CI / test (windows-latest) (push) Canceled after 0s
CI / build release (ubuntu-latest) (push) Canceled after 0s
CI / build release (windows-latest) (push) Canceled after 0s
Guards / core 零 UI 守门 (push) Canceled after 0s
Guards / 文件行数 ≤400 守门 (push) Canceled after 0s
Guards / 依赖许可与来源(cargo-deny) (push) Canceled after 0s
CI / fmt (rustfmt --check) (push) Canceled after 0s
CI / clippy (ubuntu-latest) (push) Canceled after 0s
CI / clippy (windows-latest) (push) Canceled after 0s
CI / test (ubuntu-latest) (push) Canceled after 0s
CI / test (windows-latest) (push) Canceled after 0s
CI / build release (ubuntu-latest) (push) Canceled after 0s
CI / build release (windows-latest) (push) Canceled after 0s
Guards / core 零 UI 守门 (push) Canceled after 0s
Guards / 文件行数 ≤400 守门 (push) Canceled after 0s
Guards / 依赖许可与来源(cargo-deny) (push) Canceled after 0s
Rust 原生单文件 Minecraft 启动器:CLI 完整可用(install/launch/accounts/java/diagnose/agent), MCP server 接入外部 Agent 工具,GUI 开发中。
This commit is contained in:
commit
bc41dfcf7d
517 files changed
+92844
No files matched your search
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "unlucky-app"
|
||||
description = "Unlucky-Launcher 桌面壳:Slint + Metro 视觉(唯一允许依赖 UI 框架的 crate)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "unlucky-launcher"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
slint.workspace = true
|
||||
|
||||
# 边界(01c §5 / D3):app 只经 DTO 消费 core/agent,**不 import 内部类型**。
|
||||
# P0 的 host 是 src/mock.rs 的假后端;这两个依赖在这里登记,是为了后续把真实 host
|
||||
# (core 的快照/事件流翻译成 src/dto 的类型)落位时不必再动 workspace 契约。
|
||||
unlucky-core = { path = "../core", version = "0.1" }
|
||||
unlucky-agent = { path = "../agent", version = "0.1" }
|
||||
|
||||
[build-dependencies]
|
||||
slint-build.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Slint 编译入口:把 ui/main.slint 编译成 Rust 代码,供 src/main.rs 的 `slint::include_modules!()` 引入。
|
||||
//! 保持极简——UI 结构演进(多文件拆分、主题文件)在 M17 阶段 B 里扩展本脚本。
|
||||
|
||||
/// 编译 `ui/main.slint`;失败时让构建直接报错(UI 语法错误不该被静默忽略)。
|
||||
fn main() {
|
||||
slint_build::compile("ui/main.slint").expect("Slint UI 编译失败(ui/main.slint)");
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! 「外观(高级)」四件的回调接线(从 `callbacks.rs` 拆出,守住单文件 ≤400 行)。
|
||||
//!
|
||||
//! 与 `wire_settings` 的分工:这个文件只负责 09 §101-104 的四个高级特性
|
||||
//! (背景图 / 面板半透明度 / 玻璃拟态 / 强调色)+ 主题三态。
|
||||
//! 每个回调都是同一套动作:改 `state.prefs` → 下发到 Slint(`apply_*`)→ 落盘(`persist_settings`)→
|
||||
//! `sync()`。出厂全部关闭,所以「不碰设置页」时这里一次都不会触发。
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use crate::conv;
|
||||
use crate::ui_bind::Inner;
|
||||
|
||||
/// 接主题三态与外观四件的回调。
|
||||
pub(crate) fn wire(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_theme_changed(move |mode| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.theme = conv::theme_mode_from(mode);
|
||||
this.apply_theme();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
// ── 09 §101-104「外观(高级)」四件(出厂全关,改动即刻落盘)────────
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_bg_image_enabled_changed(move |enabled| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.appearance.bg_image_enabled = enabled;
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_bg_image_changed(move |path| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.appearance.bg_image = path.to_string();
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_bg_fill_changed(move |fill| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.appearance.bg_fill = conv::bg_fill_from(fill);
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_bg_dim_changed(move |value| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.appearance.bg_dim = value;
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_panel_alpha_changed(move |value| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.appearance.panel_alpha = value;
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_glass_changed(move |enabled| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.appearance.glass = enabled;
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_accent_color_changed(move |text| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let accepted = this.state.borrow_mut().prefs.appearance.set_accent(&text);
|
||||
// 非法输入:只亮设置页的 warn 行,不改现状、不落盘
|
||||
this.ui.set_accent_invalid(!accepted);
|
||||
if accepted {
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
}
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_accent_swatch_picked(move |index| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let Ok(index) = usize::try_from(index) else {
|
||||
return;
|
||||
};
|
||||
let accepted = this
|
||||
.state
|
||||
.borrow_mut()
|
||||
.prefs
|
||||
.appearance
|
||||
.set_accent_preset(index);
|
||||
if !accepted {
|
||||
return;
|
||||
}
|
||||
let hex = this.state.borrow().prefs.appearance.accent_color.clone();
|
||||
this.ui.set_accent_color(conv::accent_color(&hex));
|
||||
this.ui.set_accent_invalid(false);
|
||||
this.apply_appearance();
|
||||
this.persist_settings();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! 背景图与玻璃拟态模糊层的准备(09 §101/§103 的「预生成」手法,纯 Rust、无新依赖)。
|
||||
//!
|
||||
//! 为什么要自己算:Slint 没有 `backdrop-filter`,也无法在渲染管线里做高斯模糊。可用的只有
|
||||
//! `Image::load_from_path` + 像素缓冲(`to_rgba8` / `from_rgba8`)。于是:
|
||||
//!
|
||||
//! - **模糊层** = 把原图按面积平均降到极小的尺寸(默认宽 48px),渲染时被平滑放大 → 天然模糊
|
||||
//! (面积平均本身就是低通滤波,比在满分辨率上跑 box blur 快几个数量级,且一次只在设置变更时算);
|
||||
//! - **tile 模式** = Slint 的 `image-fit` 没有 `repeat`,所以在 Rust 侧按窗口尺寸平铺成一张画布,
|
||||
//! 交给 `image-fit: cover`(画布与窗口同尺寸,等价于 1:1 铺设)。
|
||||
//!
|
||||
//! 解码格式:Slint 默认只编译 PNG 解码器(`image-default-formats` 特性未开),因此这里只保证 PNG;
|
||||
//! 其它格式 `load_from_path` 直接失败,UI 侧给出提示而不是静默无效果。
|
||||
|
||||
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
|
||||
|
||||
use crate::prefs::BgFill;
|
||||
|
||||
/// 模糊层目标宽度(像素)。越小越糊;96 在 1180px 宽窗口上 ≈ 24px 半径高斯的效果。
|
||||
const BLUR_WIDTH: u32 = 96;
|
||||
/// 小图上再跑几轮 box blur(3×3):把降采样的块状边缘抹平。
|
||||
const BLUR_PASSES: usize = 3;
|
||||
/// tile 画布上限(防超大窗口吃爆内存:4096×2560×4 ≈ 40MB)。
|
||||
const TILE_MAX_WIDTH: u32 = 4096;
|
||||
const TILE_MAX_HEIGHT: u32 = 2560;
|
||||
|
||||
/// 一次准备出来的两张图:原图(按填充模式处理)+ 模糊层。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct BackgroundLayers {
|
||||
/// 铺在窗口底的图(tile 模式下已平铺成整窗画布)
|
||||
pub image: Image,
|
||||
/// 玻璃拟态用的模糊层
|
||||
pub blur: Image,
|
||||
}
|
||||
|
||||
/// 载入并加工背景图。
|
||||
///
|
||||
/// `viewport` 是窗口的**物理像素**尺寸(tile 模式平铺用;拿不到时传 `(0, 0)` 退回只载入)。
|
||||
/// 返回 `None` 表示路径无效 / 解码失败 / 读了像素但为空——调用方据此提示用户。
|
||||
#[must_use]
|
||||
pub fn prepare(path: &str, fill: BgFill, viewport: (u32, u32)) -> Option<BackgroundLayers> {
|
||||
let path = path.trim();
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let loaded = Image::load_from_path(std::path::Path::new(path)).ok()?;
|
||||
let source = loaded.to_rgba8()?;
|
||||
if source.width() == 0 || source.height() == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let image = match fill {
|
||||
BgFill::Tile => {
|
||||
let (width, height) = tile_canvas_size(source.width(), source.height(), viewport);
|
||||
Image::from_rgba8(tile(&source, width, height))
|
||||
}
|
||||
// cover / contain 交给 Slint 的 image-fit,这里保留原图
|
||||
BgFill::Cover | BgFill::Contain => loaded,
|
||||
};
|
||||
|
||||
let blurred = box_blur(&downscale(&source, BLUR_WIDTH), BLUR_PASSES);
|
||||
// 放大回窗口物理尺寸再做 1:1 贴图:软件渲染器对图片缩放不做平滑插值(最近邻),
|
||||
// 直接把 96px 的小图丢给它会出现明显方块;这里自己双线性放大,观感才是「磨砂」。
|
||||
let blur = match viewport {
|
||||
(0, 0) => Image::from_rgba8(blurred),
|
||||
(width, height) => Image::from_rgba8(upscale(&blurred, width, height)),
|
||||
};
|
||||
|
||||
Some(BackgroundLayers { image, blur })
|
||||
}
|
||||
|
||||
/// 3×3 均值模糊,`passes` 轮(小图上跑,代价可忽略)。
|
||||
fn box_blur(
|
||||
source: &SharedPixelBuffer<Rgba8Pixel>,
|
||||
passes: usize,
|
||||
) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let width = source.width() as usize;
|
||||
let height = source.height() as usize;
|
||||
if width < 3 || height < 3 || passes == 0 {
|
||||
return source.clone();
|
||||
}
|
||||
let mut current: Vec<Rgba8Pixel> = source.as_slice().to_vec();
|
||||
let mut next = current.clone();
|
||||
for _ in 0..passes {
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let mut sum = [0u32; 4];
|
||||
let mut count = 0u32;
|
||||
for dy in -1i32..=1 {
|
||||
for dx in -1i32..=1 {
|
||||
let sy = (y as i32 + dy).clamp(0, height as i32 - 1) as usize;
|
||||
let sx = (x as i32 + dx).clamp(0, width as i32 - 1) as usize;
|
||||
let pixel = current[sy * width + sx];
|
||||
sum[0] += u32::from(pixel.r);
|
||||
sum[1] += u32::from(pixel.g);
|
||||
sum[2] += u32::from(pixel.b);
|
||||
sum[3] += u32::from(pixel.a);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
next[y * width + x] = Rgba8Pixel {
|
||||
r: (sum[0] / count) as u8,
|
||||
g: (sum[1] / count) as u8,
|
||||
b: (sum[2] / count) as u8,
|
||||
a: (sum[3] / count) as u8,
|
||||
};
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut current, &mut next);
|
||||
}
|
||||
let mut out = SharedPixelBuffer::<Rgba8Pixel>::new(source.width(), source.height());
|
||||
out.make_mut_slice().copy_from_slice(¤t);
|
||||
out
|
||||
}
|
||||
|
||||
/// 双线性放大到目标尺寸。
|
||||
fn upscale(
|
||||
source: &SharedPixelBuffer<Rgba8Pixel>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let src_w = source.width();
|
||||
let src_h = source.height();
|
||||
if src_w == 0 || src_h == 0 || width == 0 || height == 0 {
|
||||
return SharedPixelBuffer::new(width.max(1), height.max(1));
|
||||
}
|
||||
let pixels = source.as_slice();
|
||||
let mut out = SharedPixelBuffer::<Rgba8Pixel>::new(width, height);
|
||||
let dst = out.make_mut_slice();
|
||||
let sample = |fx: f32, fy: f32| -> Rgba8Pixel {
|
||||
let x = (fx * (src_w - 1) as f32).clamp(0.0, (src_w - 1) as f32);
|
||||
let y = (fy * (src_h - 1) as f32).clamp(0.0, (src_h - 1) as f32);
|
||||
let x0 = x.floor() as usize;
|
||||
let y0 = y.floor() as usize;
|
||||
let x1 = (x0 + 1).min(src_w as usize - 1);
|
||||
let y1 = (y0 + 1).min(src_h as usize - 1);
|
||||
let tx = x - x0 as f32;
|
||||
let ty = y - y0 as f32;
|
||||
let at = |px: usize, py: usize| pixels[py * src_w as usize + px];
|
||||
let blend = |a: u8, b: u8, c: u8, d: u8| -> u8 {
|
||||
let top = f32::from(a) * (1.0 - tx) + f32::from(b) * tx;
|
||||
let bottom = f32::from(c) * (1.0 - tx) + f32::from(d) * tx;
|
||||
(top * (1.0 - ty) + bottom * ty).round().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
let (p00, p10, p01, p11) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1));
|
||||
Rgba8Pixel {
|
||||
r: blend(p00.r, p10.r, p01.r, p11.r),
|
||||
g: blend(p00.g, p10.g, p01.g, p11.g),
|
||||
b: blend(p00.b, p10.b, p01.b, p11.b),
|
||||
a: blend(p00.a, p10.a, p01.a, p11.a),
|
||||
}
|
||||
};
|
||||
for y in 0..height as usize {
|
||||
let fy = y as f32 / height as f32;
|
||||
for x in 0..width as usize {
|
||||
dst[y * width as usize + x] = sample(x as f32 / width as f32, fy);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 平铺画布尺寸:覆盖整个视口、且是原图尺寸的整数倍(超上限就截断)。
|
||||
fn tile_canvas_size(source_width: u32, source_height: u32, viewport: (u32, u32)) -> (u32, u32) {
|
||||
if viewport.0 == 0 || viewport.1 == 0 {
|
||||
return (source_width, source_height);
|
||||
}
|
||||
let repeat_x = viewport.0.div_ceil(source_width).max(1);
|
||||
let repeat_y = viewport.1.div_ceil(source_height).max(1);
|
||||
let width = (repeat_x * source_width).min(TILE_MAX_WIDTH);
|
||||
let height = (repeat_y * source_height).min(TILE_MAX_HEIGHT);
|
||||
(width.max(source_width), height.max(source_height))
|
||||
}
|
||||
|
||||
/// 按整数格平铺(源图超出画布的部分裁掉)。
|
||||
fn tile(
|
||||
source: &SharedPixelBuffer<Rgba8Pixel>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let mut canvas = SharedPixelBuffer::<Rgba8Pixel>::new(width, height);
|
||||
let src_w = source.width() as usize;
|
||||
let src_h = source.height() as usize;
|
||||
let src = source.as_slice();
|
||||
let dst = canvas.make_mut_slice();
|
||||
for y in 0..height as usize {
|
||||
let src_row = (y % src_h) * src_w;
|
||||
let dst_row = y * width as usize;
|
||||
for x in 0..width as usize {
|
||||
dst[dst_row + x] = src[src_row + (x % src_w)];
|
||||
}
|
||||
}
|
||||
canvas
|
||||
}
|
||||
|
||||
/// 面积平均降采样(保留宽高比,最窄 1px)。
|
||||
fn downscale(
|
||||
source: &SharedPixelBuffer<Rgba8Pixel>,
|
||||
target_width: u32,
|
||||
) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let src_w = source.width();
|
||||
let src_h = source.height();
|
||||
let target_width = target_width.clamp(1, src_w);
|
||||
let target_height = ((src_h as u64 * target_width as u64) / src_w as u64).max(1) as u32;
|
||||
|
||||
let mut out = SharedPixelBuffer::<Rgba8Pixel>::new(target_width, target_height);
|
||||
let src = source.as_slice();
|
||||
let dst = out.make_mut_slice();
|
||||
|
||||
for ty in 0..target_height as usize {
|
||||
// 每个目标像素覆盖的源矩形(按比例分块,块内取平均)
|
||||
let y0 = ty * src_h as usize / target_height as usize;
|
||||
let y1 = ((ty + 1) * src_h as usize / target_height as usize).max(y0 + 1);
|
||||
for tx in 0..target_width as usize {
|
||||
let x0 = tx * src_w as usize / target_width as usize;
|
||||
let x1 = ((tx + 1) * src_w as usize / target_width as usize).max(x0 + 1);
|
||||
let mut sum = [0u32; 4];
|
||||
let mut count = 0u32;
|
||||
for y in y0..y1.min(src_h as usize) {
|
||||
for x in x0..x1.min(src_w as usize) {
|
||||
let pixel = src[y * src_w as usize + x];
|
||||
sum[0] += u32::from(pixel.r);
|
||||
sum[1] += u32::from(pixel.g);
|
||||
sum[2] += u32::from(pixel.b);
|
||||
sum[3] += u32::from(pixel.a);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
let count = count.max(1);
|
||||
dst[ty * target_width as usize + tx] = Rgba8Pixel {
|
||||
r: (sum[0] / count) as u8,
|
||||
g: (sum[1] / count) as u8,
|
||||
b: (sum[2] / count) as u8,
|
||||
a: (sum[3] / count) as u8,
|
||||
};
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn solid(width: u32, height: u32, pixel: Rgba8Pixel) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let mut buffer = SharedPixelBuffer::<Rgba8Pixel>::new(width, height);
|
||||
buffer.make_mut_slice().fill(pixel);
|
||||
buffer
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downscale_keeps_aspect_and_averages_area() {
|
||||
let mut source = SharedPixelBuffer::<Rgba8Pixel>::new(96, 48);
|
||||
// 左半黑、右半白:降采样后左右两侧应各自保持纯色
|
||||
for y in 0..48 {
|
||||
for x in 0..96 {
|
||||
let value = if x < 48 { 0 } else { 255 };
|
||||
source.make_mut_slice()[y * 96 + x] = Rgba8Pixel {
|
||||
r: value,
|
||||
g: value,
|
||||
b: value,
|
||||
a: 255,
|
||||
};
|
||||
}
|
||||
}
|
||||
let small = downscale(&source, 24);
|
||||
assert_eq!(small.width(), 24);
|
||||
assert_eq!(small.height(), 12, "宽高比保持 2:1");
|
||||
let pixels = small.as_slice();
|
||||
assert_eq!(pixels[0].r, 0, "左侧仍是黑");
|
||||
assert_eq!(pixels[23].r, 255, "右侧仍是白");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downscale_never_produces_zero_height() {
|
||||
let source = solid(
|
||||
400,
|
||||
3,
|
||||
Rgba8Pixel {
|
||||
r: 1,
|
||||
g: 2,
|
||||
b: 3,
|
||||
a: 255,
|
||||
},
|
||||
);
|
||||
let small = downscale(&source, 2);
|
||||
assert_eq!(small.width(), 2);
|
||||
assert!(small.height() >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_canvas_covers_viewport_in_whole_repeats() {
|
||||
assert_eq!(tile_canvas_size(120, 100, (1180, 760)), (1200, 800));
|
||||
// 视口未知(取不到窗口尺寸)时退回单块
|
||||
assert_eq!(tile_canvas_size(120, 100, (0, 0)), (120, 100));
|
||||
// 超大视口被上限截断
|
||||
let (width, height) = tile_canvas_size(64, 64, (9000, 9000));
|
||||
assert!(width <= TILE_MAX_WIDTH && height <= TILE_MAX_HEIGHT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_repeats_source_pixels() {
|
||||
let source = solid(
|
||||
2,
|
||||
2,
|
||||
Rgba8Pixel {
|
||||
r: 9,
|
||||
g: 9,
|
||||
b: 9,
|
||||
a: 255,
|
||||
},
|
||||
);
|
||||
let canvas = tile(&source, 5, 3);
|
||||
assert_eq!(canvas.width(), 5);
|
||||
assert_eq!(canvas.height(), 3);
|
||||
assert!(canvas.as_slice().iter().all(|pixel| pixel.r == 9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_rejects_bad_input() {
|
||||
assert!(prepare("", BgFill::Cover, (100, 100)).is_none());
|
||||
assert!(prepare("D:/definitely/not/here.png", BgFill::Cover, (100, 100)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_blur_smooths_a_hard_edge() {
|
||||
// 左黑右白:模糊后交界处应出现中间灰(硬边被抹平)
|
||||
let mut source = SharedPixelBuffer::<Rgba8Pixel>::new(9, 3);
|
||||
for y in 0..3 {
|
||||
for x in 0..9 {
|
||||
let value = if x < 4 { 0 } else { 255 };
|
||||
source.make_mut_slice()[y * 9 + x] = Rgba8Pixel {
|
||||
r: value,
|
||||
g: value,
|
||||
b: value,
|
||||
a: 255,
|
||||
};
|
||||
}
|
||||
}
|
||||
let blurred = box_blur(&source, 2);
|
||||
let middle = blurred.as_slice()[9 + 4]; // 第 1 行(共 9 列)的第 4 个像素
|
||||
assert!(
|
||||
middle.r > 20 && middle.r < 235,
|
||||
"交界处应被抹成中间灰,实际 {}",
|
||||
middle.r
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upscale_matches_requested_size_and_interpolates() {
|
||||
let mut source = SharedPixelBuffer::<Rgba8Pixel>::new(2, 1);
|
||||
let pixels = source.make_mut_slice();
|
||||
pixels[0] = Rgba8Pixel {
|
||||
r: 0,
|
||||
g: 0,
|
||||
b: 0,
|
||||
a: 255,
|
||||
};
|
||||
pixels[1] = Rgba8Pixel {
|
||||
r: 255,
|
||||
g: 255,
|
||||
b: 255,
|
||||
a: 255,
|
||||
};
|
||||
let big = upscale(&source, 8, 2);
|
||||
assert_eq!(big.width(), 8);
|
||||
assert_eq!(big.height(), 2);
|
||||
let row = big.as_slice();
|
||||
// 双线性:中间像素应是灰阶过渡而不是 0/255 二值
|
||||
assert!(row[3].r > 60 && row[3].r < 200, "实际 {}", row[3].r);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
//! 回调接线:把 `ui/main.slint` 暴露的每个回调翻译成「状态变更 + AppCommand + 同步」。
|
||||
//!
|
||||
//! 逐条列出而不做通用转发,是为了让「用户能做的每一件事」在这里一目了然;
|
||||
//! 新增交互时只改这一处 + `.slint` 的 callback 声明。
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use crate::conv;
|
||||
use crate::dto::AppCommand;
|
||||
use crate::router::Route;
|
||||
use crate::toast::ToastKind;
|
||||
use crate::ui_bind::Inner;
|
||||
|
||||
/// 接全部回调;闭包持弱引用,避免 `MainWindow` 与闭包互相持有导致窗口永不释放。
|
||||
pub(crate) fn wire(weak: Weak<Inner>) {
|
||||
let Some(inner) = weak.upgrade() else { return };
|
||||
// 只在注册期间持有强引用;闭包内一律持弱引用(否则窗口与闭包互相持有、永不释放)。
|
||||
let ui = &inner.ui;
|
||||
|
||||
wire_window(ui, &weak);
|
||||
wire_navigation(ui, &weak);
|
||||
wire_instances(ui, &weak);
|
||||
wire_download(ui, &weak);
|
||||
wire_logs(ui, &weak);
|
||||
wire_settings(ui, &weak);
|
||||
wire_overlays(ui, &weak);
|
||||
}
|
||||
|
||||
fn wire_window(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_toggle_maximize(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let window = this.ui.window();
|
||||
window.set_maximized(!window.is_maximized());
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_minimize(move || {
|
||||
if let Some(this) = weak.upgrade() {
|
||||
this.ui.window().set_minimized(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_request_close(move || {
|
||||
if let Some(this) = weak.upgrade() {
|
||||
let _ = this.ui.hide();
|
||||
}
|
||||
let _ = slint::quit_event_loop();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_navigation(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_navigate(move |route| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
if let Some(route) = conv::route_from(route) {
|
||||
this.state.borrow_mut().navigate(route);
|
||||
this.sync();
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_toggle_nav(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().toggle_nav();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_toggle_ai(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().toggle_ai();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_expand_ai(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().navigate(Route::Agent);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_dock_ai(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().back();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_toggle_yolo(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let enabled = {
|
||||
let mut state = this.state.borrow_mut();
|
||||
state.ai.yolo = !state.ai.yolo;
|
||||
state.ai.yolo
|
||||
};
|
||||
this.dispatch(AppCommand::SetYolo(enabled));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_ai_send(move |text| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let text = text.to_string();
|
||||
if text.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
// 不做本地回显:user 消息由 host 的 MessageAppended 事件带回(契约 §3)
|
||||
this.state.borrow_mut().ai.draft.clear();
|
||||
this.ui.set_ai_draft("".into());
|
||||
this.ask_agent(&text);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_ai_stop(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().ai.finish_stream();
|
||||
this.dispatch(AppCommand::StopAgent);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_instances(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_instance_launch(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.dispatch(AppCommand::LaunchInstance(id.to_string()));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_instance_configure(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
// 齿轮键进实例详情(G4 占位页),实例级设置后续挂在该页 tab 上
|
||||
this.state
|
||||
.borrow_mut()
|
||||
.navigate(Route::Detail(id.to_string()));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_instance_stop(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.dispatch(AppCommand::StopInstance(id.to_string()));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_instance_open(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state
|
||||
.borrow_mut()
|
||||
.navigate(Route::Detail(id.to_string()));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_new_instance(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state
|
||||
.borrow_mut()
|
||||
.toasts
|
||||
.push(ToastKind::Info, "新建实例向导(G5)在 P1 落地");
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_instance_view_changed(move |view| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.instance_view = conv::instance_view_from(view);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_tile_size_changed(move |size| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().prefs.tile_size = conv::tile_size_from(size);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_instance_query_changed(move |query| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().instance_query = query.to_string();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_download(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_download_category_changed(move |category| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let category = conv::version_category(category);
|
||||
this.state.borrow_mut().prefs.download_category = category;
|
||||
this.dispatch(AppCommand::ListVersions(category));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_download_install(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.dispatch(AppCommand::InstallVersion(id.to_string()));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_installed_only_changed(move |only| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().installed_only = only;
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_download_query_changed(move |query| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().download_query = query.to_string();
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_ancient_help(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().toasts.push(
|
||||
ToastKind::Info,
|
||||
"远古版(classic/alpha/beta)需旧版 Java 与旧启动参数;完整说明页 P1 接入",
|
||||
);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_logs(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_log_select(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().selected_session = Some(id.to_string());
|
||||
this.dispatch(AppCommand::OpenLogSession(id.to_string()));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_log_ask_ai(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
let question = format!("帮我看下会话 {id} 为什么崩溃");
|
||||
this.state.borrow_mut().navigate(Route::Agent);
|
||||
this.ask_agent(&question);
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_log_apply_fix(move || {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state
|
||||
.borrow_mut()
|
||||
.toasts
|
||||
.push(ToastKind::Warn, "一键修复在 P1 接 diagnose 的 fix_action");
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_settings(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
// 主题三态 + 外观四件在 appearance_bind.rs(拆文件守 400 行)
|
||||
crate::appearance_bind::wire(ui, weak);
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_yolo_changed(move |enabled| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().ai.yolo = enabled;
|
||||
this.dispatch(AppCommand::SetYolo(enabled));
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_mcp_changed(move |_enabled| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state
|
||||
.borrow_mut()
|
||||
.toasts
|
||||
.push(ToastKind::Info, "MCP server 开关在 P1 接 agent");
|
||||
this.sync();
|
||||
});
|
||||
}
|
||||
// P0 只保留入口:设置分组与 AI 端点暂不落状态(P1 接 setting schema)。
|
||||
ui.on_settings_section_changed(|_section| {});
|
||||
ui.on_ai_endpoint_changed(|_index| {});
|
||||
}
|
||||
|
||||
fn wire_overlays(ui: &crate::MainWindow, weak: &Weak<Inner>) {
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_dialog_primary(move || close_current_dialog(&weak));
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_dialog_secondary(move || close_current_dialog(&weak));
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_dialog_dismissed(move || close_current_dialog(&weak));
|
||||
}
|
||||
{
|
||||
let weak = weak.clone();
|
||||
ui.on_toast_dismissed(move |id| {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
if let Ok(id) = id.parse::<u64>() {
|
||||
this.state.borrow_mut().toasts.dismiss(id);
|
||||
this.sync();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn close_current_dialog(weak: &Weak<Inner>) {
|
||||
let Some(this) = weak.upgrade() else { return };
|
||||
this.state.borrow_mut().dialogs.close_current();
|
||||
this.sync();
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! AI 页与覆盖层:会话消息、对话框(一次一条)、Toast。
|
||||
|
||||
use crate::dialogs as dlg;
|
||||
use crate::dto::ChatRole as DtoChatRole;
|
||||
use crate::state::AppState;
|
||||
use crate::toast as toast_mod;
|
||||
use crate::{ChatRole, DialogKind, UiChatMessage, UiDialog, UiToast};
|
||||
|
||||
/// AI 会话消息。
|
||||
pub fn chat(state: &AppState) -> Vec<UiChatMessage> {
|
||||
state
|
||||
.ai
|
||||
.messages
|
||||
.iter()
|
||||
.map(|message| UiChatMessage {
|
||||
role: match message.role {
|
||||
DtoChatRole::User => ChatRole::User,
|
||||
DtoChatRole::Assistant => ChatRole::Assistant,
|
||||
DtoChatRole::Tool => ChatRole::Tool,
|
||||
DtoChatRole::System => ChatRole::System,
|
||||
},
|
||||
text: message.text.clone().into(),
|
||||
tool_name: message
|
||||
.tool
|
||||
.as_ref()
|
||||
.map(|tool| tool.name.clone())
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
tool_ok: message.tool.as_ref().is_none_or(|tool| tool.ok),
|
||||
streaming: message.streaming,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 当前对话框(一次一条)+ 是否显示 + 队列剩余条数。
|
||||
pub fn dialog(state: &AppState) -> (UiDialog, bool, i32) {
|
||||
let queued = i32::try_from(state.dialogs.pending_len()).unwrap_or(0);
|
||||
match state.dialogs.current() {
|
||||
None => (UiDialog::default(), false, queued),
|
||||
Some(request) => {
|
||||
let (kind, primary, secondary) = match &request.kind {
|
||||
dlg::DialogKind::Confirm { primary, secondary } => {
|
||||
(DialogKind::Confirm, primary.clone(), secondary.clone())
|
||||
}
|
||||
dlg::DialogKind::Input { primary, .. } => {
|
||||
(DialogKind::Input, primary.clone(), String::new())
|
||||
}
|
||||
dlg::DialogKind::Progress { .. } => {
|
||||
(DialogKind::Progress, "取消".to_string(), String::new())
|
||||
}
|
||||
dlg::DialogKind::Error { primary, .. } => {
|
||||
(DialogKind::Error, primary.clone(), "忽略".to_string())
|
||||
}
|
||||
};
|
||||
let progress = match &request.kind {
|
||||
dlg::DialogKind::Progress { progress, .. } => *progress,
|
||||
_ => 0.0,
|
||||
};
|
||||
let input_label = match &request.kind {
|
||||
dlg::DialogKind::Input { label, .. } => label.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let input_value = match &request.kind {
|
||||
dlg::DialogKind::Input { value, .. } => value.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
(
|
||||
UiDialog {
|
||||
id: request.id.to_string().into(),
|
||||
kind,
|
||||
title: request.title.clone().into(),
|
||||
body: request.body.clone().into(),
|
||||
primary: primary.into(),
|
||||
secondary: secondary.into(),
|
||||
progress,
|
||||
input_label: input_label.into(),
|
||||
input_value: input_value.into(),
|
||||
},
|
||||
true,
|
||||
queued,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Toast 列表。
|
||||
pub fn toasts(state: &AppState) -> Vec<UiToast> {
|
||||
state
|
||||
.toasts
|
||||
.items()
|
||||
.iter()
|
||||
.map(|toast| UiToast {
|
||||
id: toast.id.to_string().into(),
|
||||
kind: match toast.kind {
|
||||
toast_mod::ToastKind::Info => crate::ToastKind::Info,
|
||||
toast_mod::ToastKind::Success => crate::ToastKind::Success,
|
||||
toast_mod::ToastKind::Warn => crate::ToastKind::Warn,
|
||||
toast_mod::ToastKind::Error => crate::ToastKind::Error,
|
||||
},
|
||||
text: toast.text.clone().into(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! 实例相关:磁贴外观(相位/进度/徽标/占位色)、运行中列表。
|
||||
|
||||
use slint::Color;
|
||||
|
||||
use crate::dto::{self, InstanceRuntime};
|
||||
use crate::state::{AppState, TileCell};
|
||||
use crate::{LoaderKind, RuntimePhase, UiTile};
|
||||
|
||||
/// 头像/图标占位的底色池(Metro 强调色系,按 id 哈希稳定取色)。
|
||||
const HUES: [u32; 8] = [
|
||||
0x0078D4, 0x8764B0, 0xD13438, 0xCA5010, 0x498205, 0x038387, 0x5C2D91, 0x0050EF,
|
||||
];
|
||||
|
||||
/// 加载器枚举。
|
||||
pub fn loader(kind: dto::LoaderKind) -> LoaderKind {
|
||||
match kind {
|
||||
dto::LoaderKind::Vanilla => LoaderKind::Vanilla,
|
||||
dto::LoaderKind::Fabric => LoaderKind::Fabric,
|
||||
dto::LoaderKind::Quilt => LoaderKind::Quilt,
|
||||
dto::LoaderKind::Forge => LoaderKind::Forge,
|
||||
dto::LoaderKind::NeoForge => LoaderKind::Neoforge,
|
||||
dto::LoaderKind::OptiFine => LoaderKind::Optifine,
|
||||
dto::LoaderKind::LiteLoader => LoaderKind::Liteloader,
|
||||
}
|
||||
}
|
||||
|
||||
/// 运行时状态 → (磁贴外观相位, 进度 0~1, 阶段文案)。
|
||||
pub fn phase(runtime: &InstanceRuntime) -> (RuntimePhase, f32, String) {
|
||||
match runtime {
|
||||
InstanceRuntime::Idle => (RuntimePhase::Idle, 0.0, String::new()),
|
||||
InstanceRuntime::Busy { stage, progress } => {
|
||||
let phase = match stage {
|
||||
dto::LaunchStage::Download => RuntimePhase::Downloading,
|
||||
dto::LaunchStage::Verify => RuntimePhase::Verifying,
|
||||
dto::LaunchStage::Launch => RuntimePhase::Launching,
|
||||
};
|
||||
(phase, progress.ratio(), stage.label().to_string())
|
||||
}
|
||||
InstanceRuntime::Running { .. } => (RuntimePhase::Running, 1.0, "运行中".to_string()),
|
||||
InstanceRuntime::Failed { reason } => (RuntimePhase::Failed, 0.0, reason.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 名字首字(无图标时的占位字母)。
|
||||
pub fn initial_of(name: &str) -> String {
|
||||
name.chars()
|
||||
.next()
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| "?".to_string())
|
||||
}
|
||||
|
||||
/// id → 稳定底色(同一实例每次启动同色)。
|
||||
pub fn hue_of(id: &str) -> Color {
|
||||
let hash = id.bytes().fold(0u32, |acc, byte| {
|
||||
acc.wrapping_mul(31).wrapping_add(u32::from(byte))
|
||||
});
|
||||
Color::from_argb_encoded(0xFF00_0000 | HUES[(hash as usize) % HUES.len()])
|
||||
}
|
||||
|
||||
/// ISO-8601 UTC → 逗号少的本地展示串(`2026-10-29 19:22`);None/空 → 从未启动。
|
||||
pub fn last_played(raw: &Option<String>) -> String {
|
||||
match raw {
|
||||
None => "从未启动".to_string(),
|
||||
Some(value) if value.is_empty() => "从未启动".to_string(),
|
||||
Some(value) => {
|
||||
let trimmed = value.trim_end_matches('Z');
|
||||
let mut out = String::with_capacity(trimmed.len());
|
||||
let mut seen_time = false;
|
||||
for ch in trimmed.chars() {
|
||||
match ch {
|
||||
'T' => {
|
||||
seen_time = true;
|
||||
out.push(' ');
|
||||
}
|
||||
':' if seen_time && out.ends_with(|c: char| c.is_ascii_digit()) => {
|
||||
// 只保留到分钟:秒(第三段冒号之后)直接截断
|
||||
if out.matches(':').count() >= 1 {
|
||||
break;
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
_ => out.push(ch),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个磁贴。
|
||||
pub fn tile(cell: &TileCell<'_>) -> UiTile {
|
||||
let instance = cell.instance;
|
||||
let (phase, progress, label) = phase(&instance.runtime);
|
||||
UiTile {
|
||||
id: instance.id.clone().into(),
|
||||
name: instance.name.clone().into(),
|
||||
mc_version: instance.mc_version.clone().into(),
|
||||
loader: loader(instance.loader.kind),
|
||||
loader_version: instance.loader.version.clone().into(),
|
||||
loader_label: instance.loader.badge().into(),
|
||||
last_played: last_played(&instance.last_played).into(),
|
||||
phase,
|
||||
phase_label: label.into(),
|
||||
progress,
|
||||
icon: slint::Image::default(),
|
||||
hue: hue_of(&instance.id),
|
||||
initial: initial_of(&instance.name).into(),
|
||||
row: i32::try_from(cell.row).unwrap_or(0),
|
||||
col: i32::try_from(cell.col).unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// 磁贴网格(已按当前尺寸算好 row/col)。
|
||||
pub fn tiles(state: &AppState) -> Vec<UiTile> {
|
||||
state.tiles().iter().map(tile).collect()
|
||||
}
|
||||
|
||||
/// 运行中实例(顶部迷你状态条)。
|
||||
pub fn running_tiles(state: &AppState) -> Vec<UiTile> {
|
||||
state
|
||||
.running()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, instance)| {
|
||||
let cell = TileCell {
|
||||
instance,
|
||||
row: 0,
|
||||
col: index,
|
||||
};
|
||||
tile(&cell)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{hue_of, initial_of, last_played};
|
||||
|
||||
#[test]
|
||||
fn initial_is_first_grapheme_or_question_mark() {
|
||||
assert_eq!(initial_of("生存整合包"), "生");
|
||||
assert_eq!(initial_of("Vanilla"), "V");
|
||||
assert_eq!(initial_of(""), "?");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_is_stable_per_id() {
|
||||
assert_eq!(hue_of("survival"), hue_of("survival"));
|
||||
// 不同 id 大体不同色(哈希池 8 色,这里只验证确定性 + 不 panic)
|
||||
let _ = hue_of("another-instance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_played_formats_iso_to_minutes() {
|
||||
assert_eq!(
|
||||
last_played(&Some("2026-10-29T19:22:45Z".to_string())),
|
||||
"2026-10-29 19:22"
|
||||
);
|
||||
assert_eq!(last_played(&None), "从未启动");
|
||||
assert_eq!(last_played(&Some(String::new())), "从未启动");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! 日志页:会话列表、日志行、D8 诊断卡片。
|
||||
|
||||
use crate::dto::{LogLevel as DtoLogLevel, LogOutcome as DtoLogOutcome};
|
||||
use crate::state::AppState;
|
||||
use crate::{LogLevel, LogOutcome, UiDiagnosis, UiLogLine, UiLogSession};
|
||||
|
||||
/// 日志会话列表。
|
||||
pub fn log_sessions(state: &AppState) -> Vec<UiLogSession> {
|
||||
state
|
||||
.log_sessions
|
||||
.iter()
|
||||
.map(|session| UiLogSession {
|
||||
id: session.id.clone().into(),
|
||||
when: session.when.clone().into(),
|
||||
instance: session.instance.clone().into(),
|
||||
outcome: match session.outcome {
|
||||
DtoLogOutcome::Ok => LogOutcome::Ok,
|
||||
DtoLogOutcome::Crashed => LogOutcome::Crashed,
|
||||
DtoLogOutcome::SilentFail => LogOutcome::SilentFail,
|
||||
},
|
||||
duration: duration(session.duration_secs).into(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 秒 → `1h03m` / `62s`。
|
||||
pub fn duration(secs: u64) -> String {
|
||||
if secs >= 3_600 {
|
||||
format!("{}h{:02}m", secs / 3_600, (secs % 3_600) / 60)
|
||||
} else if secs >= 60 {
|
||||
format!("{}m{:02}s", secs / 60, secs % 60)
|
||||
} else {
|
||||
format!("{secs}s")
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前会话日志行。
|
||||
pub fn log_lines(state: &AppState) -> Vec<UiLogLine> {
|
||||
state
|
||||
.log_lines
|
||||
.iter()
|
||||
.map(|line| UiLogLine {
|
||||
text: line.text.clone().into(),
|
||||
level: match line.level {
|
||||
DtoLogLevel::Debug => LogLevel::Debug,
|
||||
DtoLogLevel::Info => LogLevel::Info,
|
||||
DtoLogLevel::Warn => LogLevel::Warn,
|
||||
DtoLogLevel::Error => LogLevel::Error,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 诊断卡片内容(无结论时返回默认值 + has=false)。
|
||||
pub fn diagnosis(state: &AppState) -> (UiDiagnosis, bool) {
|
||||
match &state.diagnosis {
|
||||
None => (UiDiagnosis::default(), false),
|
||||
Some(report) => {
|
||||
let diagnosis = &report.diagnosis;
|
||||
(
|
||||
UiDiagnosis {
|
||||
rule: diagnosis.rule.clone().into(),
|
||||
title: diagnosis.title.clone().into(),
|
||||
confidence: i32::from(diagnosis.confidence),
|
||||
hint: diagnosis.hint.clone().into(),
|
||||
has_fix: diagnosis.fix.is_some(),
|
||||
},
|
||||
true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::duration;
|
||||
|
||||
#[test]
|
||||
fn duration_is_human_readable() {
|
||||
assert_eq!(duration(8), "8s");
|
||||
assert_eq!(duration(62), "1m02s");
|
||||
assert_eq!(duration(3_780), "1h03m");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! 状态层 → Slint 视图模型的单向转换(DTO 值 → `models.slint` 结构体)。
|
||||
//!
|
||||
//! 只做「领域值 → 展示值」的搬运与格式化,不含业务判断;
|
||||
//! 这样 `ui_bind.rs` 里的同步逻辑就是纯粹的「状态灌进属性」。
|
||||
//! 按领域拆子模块:instances / versions / logs / agent / ui,全量 `pub use`,
|
||||
//! 调用方统一写 `crate::conv::tiles(...)` 这类路径。
|
||||
|
||||
mod agent;
|
||||
mod instances;
|
||||
mod logs;
|
||||
mod ui;
|
||||
mod versions;
|
||||
|
||||
pub use agent::{chat, dialog, toasts};
|
||||
pub use instances::{running_tiles, tiles};
|
||||
pub use logs::{diagnosis, log_lines, log_sessions};
|
||||
pub use ui::{
|
||||
accent_color, bg_fill, bg_fill_from, category_from, instance_view, instance_view_from, route,
|
||||
route_from, theme_mode, theme_mode_from, tile_size, tile_size_from, version_category,
|
||||
};
|
||||
pub use versions::versions;
|
||||
@@ -0,0 +1,136 @@
|
||||
//! UI 偏好/路由枚举的双向映射(Slint 枚举 ↔ 状态层枚举)。
|
||||
|
||||
use crate::dto::{self, VersionCategory};
|
||||
use crate::prefs;
|
||||
use crate::router;
|
||||
use crate::{BgFillKind, DownloadCategory, InstanceView, RouteKind, ThemeMode, TileSize};
|
||||
|
||||
/// 路由 → 导航高亮/页面选择。
|
||||
pub fn route(route: &router::Route) -> RouteKind {
|
||||
match route {
|
||||
router::Route::Instances => RouteKind::Instances,
|
||||
router::Route::Download => RouteKind::Download,
|
||||
router::Route::Logs => RouteKind::Logs,
|
||||
router::Route::Settings => RouteKind::Settings,
|
||||
router::Route::Detail(_) => RouteKind::Detail,
|
||||
router::Route::Agent => RouteKind::Agent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slint 侧导航点击 → 路由(详情页保持当前实例,不在导航里触发)。
|
||||
pub fn route_from(kind: RouteKind) -> Option<router::Route> {
|
||||
match kind {
|
||||
RouteKind::Instances => Some(router::Route::Instances),
|
||||
RouteKind::Download => Some(router::Route::Download),
|
||||
RouteKind::Logs => Some(router::Route::Logs),
|
||||
RouteKind::Settings => Some(router::Route::Settings),
|
||||
RouteKind::Agent => Some(router::Route::Agent),
|
||||
RouteKind::Detail => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 磁贴尺寸。
|
||||
pub fn tile_size(size: prefs::TileSize) -> TileSize {
|
||||
match size {
|
||||
prefs::TileSize::Small => TileSize::Small,
|
||||
prefs::TileSize::Medium => TileSize::Medium,
|
||||
prefs::TileSize::Large => TileSize::Large,
|
||||
}
|
||||
}
|
||||
|
||||
/// 视图模式。
|
||||
pub fn instance_view(view: prefs::InstanceView) -> InstanceView {
|
||||
match view {
|
||||
prefs::InstanceView::Tiles => InstanceView::Tiles,
|
||||
prefs::InstanceView::List => InstanceView::List,
|
||||
}
|
||||
}
|
||||
|
||||
/// 主题三态。
|
||||
pub fn theme_mode(mode: prefs::ThemeMode) -> ThemeMode {
|
||||
match mode {
|
||||
prefs::ThemeMode::Auto => ThemeMode::Auto,
|
||||
prefs::ThemeMode::Light => ThemeMode::Light,
|
||||
prefs::ThemeMode::Dark => ThemeMode::Dark,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slint 主题三态 → 偏好枚举。
|
||||
pub fn theme_mode_from(mode: ThemeMode) -> prefs::ThemeMode {
|
||||
match mode {
|
||||
ThemeMode::Auto => prefs::ThemeMode::Auto,
|
||||
ThemeMode::Light => prefs::ThemeMode::Light,
|
||||
ThemeMode::Dark => prefs::ThemeMode::Dark,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slint 磁贴尺寸 → 偏好枚举。
|
||||
pub fn tile_size_from(size: TileSize) -> prefs::TileSize {
|
||||
match size {
|
||||
TileSize::Small => prefs::TileSize::Small,
|
||||
TileSize::Medium => prefs::TileSize::Medium,
|
||||
TileSize::Large => prefs::TileSize::Large,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slint 视图模式 → 偏好枚举。
|
||||
pub fn instance_view_from(view: InstanceView) -> prefs::InstanceView {
|
||||
match view {
|
||||
InstanceView::Tiles => prefs::InstanceView::Tiles,
|
||||
InstanceView::List => prefs::InstanceView::List,
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载分类 → core 侧分类枚举。
|
||||
pub fn version_category(category: DownloadCategory) -> VersionCategory {
|
||||
match category {
|
||||
DownloadCategory::Release => VersionCategory::Release,
|
||||
DownloadCategory::Snapshot => VersionCategory::Snapshot,
|
||||
DownloadCategory::AncientClassic => VersionCategory::Ancient(dto::AncientKind::Classic),
|
||||
DownloadCategory::AncientAlpha => VersionCategory::Ancient(dto::AncientKind::OldAlpha),
|
||||
DownloadCategory::AncientBeta => VersionCategory::Ancient(dto::AncientKind::OldBeta),
|
||||
DownloadCategory::AncientUnlisted => VersionCategory::Ancient(dto::AncientKind::Unlisted),
|
||||
DownloadCategory::Modpack => VersionCategory::Modpack,
|
||||
DownloadCategory::Mod => VersionCategory::Mod,
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载分类(偏好 → Slint)——供启动时回填。
|
||||
pub fn category_from(category: VersionCategory) -> DownloadCategory {
|
||||
match category {
|
||||
VersionCategory::Release => DownloadCategory::Release,
|
||||
VersionCategory::Snapshot => DownloadCategory::Snapshot,
|
||||
VersionCategory::Ancient(dto::AncientKind::Classic) => DownloadCategory::AncientClassic,
|
||||
VersionCategory::Ancient(dto::AncientKind::OldAlpha) => DownloadCategory::AncientAlpha,
|
||||
VersionCategory::Ancient(dto::AncientKind::OldBeta) => DownloadCategory::AncientBeta,
|
||||
VersionCategory::Ancient(dto::AncientKind::Unlisted) => DownloadCategory::AncientUnlisted,
|
||||
VersionCategory::Modpack => DownloadCategory::Modpack,
|
||||
VersionCategory::Mod => DownloadCategory::Mod,
|
||||
}
|
||||
}
|
||||
|
||||
/// 背景图填充模式(core 侧枚举 → Slint)。
|
||||
pub fn bg_fill(fill: unlucky_core::setting::appearance::BgFill) -> BgFillKind {
|
||||
match fill {
|
||||
unlucky_core::setting::appearance::BgFill::Cover => BgFillKind::Cover,
|
||||
unlucky_core::setting::appearance::BgFill::Contain => BgFillKind::Contain,
|
||||
unlucky_core::setting::appearance::BgFill::Tile => BgFillKind::Tile,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slint 填充模式 → core 侧枚举。
|
||||
pub fn bg_fill_from(fill: BgFillKind) -> unlucky_core::setting::appearance::BgFill {
|
||||
match fill {
|
||||
BgFillKind::Cover => unlucky_core::setting::appearance::BgFill::Cover,
|
||||
BgFillKind::Contain => unlucky_core::setting::appearance::BgFill::Contain,
|
||||
BgFillKind::Tile => unlucky_core::setting::appearance::BgFill::Tile,
|
||||
}
|
||||
}
|
||||
|
||||
/// 强调色十六进制串 → Slint 颜色;空串/非法值给透明(= 用出厂 accent)。
|
||||
pub fn accent_color(hex: &str) -> slint::Color {
|
||||
match unlucky_core::setting::appearance::hex_to_rgb(hex) {
|
||||
Some((r, g, b)) => slint::Color::from_rgb_u8(r, g, b),
|
||||
None => slint::Color::from_argb_u8(0, 0, 0, 0),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! 版本列表与下载分类映射(下载页)。
|
||||
|
||||
use crate::dto::{AncientKind, VersionKind as DtoVersionKind};
|
||||
use crate::state::AppState;
|
||||
use crate::{UiVersion, VersionKind};
|
||||
|
||||
/// 下载页版本行(已按「仅已装」+ 版本号筛选词过滤)。
|
||||
pub fn versions(state: &AppState) -> Vec<UiVersion> {
|
||||
let query = state.download_query.trim().to_lowercase();
|
||||
state
|
||||
.versions
|
||||
.iter()
|
||||
.filter(|version| !state.installed_only || version.installed)
|
||||
.filter(|version| query.is_empty() || version.id.to_lowercase().contains(&query))
|
||||
.map(|version| UiVersion {
|
||||
id: version.id.clone().into(),
|
||||
kind: version_kind(version.kind),
|
||||
released: version.released.clone().into(),
|
||||
installed: version.installed,
|
||||
ancient: version.kind.is_ancient(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn version_kind(kind: DtoVersionKind) -> VersionKind {
|
||||
match kind {
|
||||
DtoVersionKind::Release => VersionKind::Release,
|
||||
DtoVersionKind::Snapshot => VersionKind::Snapshot,
|
||||
DtoVersionKind::Ancient(AncientKind::Classic) => VersionKind::AncientClassic,
|
||||
DtoVersionKind::Ancient(AncientKind::OldAlpha) => VersionKind::AncientAlpha,
|
||||
DtoVersionKind::Ancient(AncientKind::OldBeta) => VersionKind::AncientBeta,
|
||||
DtoVersionKind::Ancient(AncientKind::Unlisted) => VersionKind::AncientUnlisted,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::versions;
|
||||
use crate::dto::{VersionKind, VersionSummary};
|
||||
use crate::state::AppState;
|
||||
|
||||
fn state_with_versions() -> AppState {
|
||||
let mut state = AppState::new();
|
||||
let row = |id: &str, installed: bool| VersionSummary {
|
||||
id: id.to_string(),
|
||||
kind: VersionKind::Release,
|
||||
released: "2026-01-01".to_string(),
|
||||
installed,
|
||||
};
|
||||
state.versions = vec![
|
||||
row("1.21.9", false),
|
||||
row("1.20.4", true),
|
||||
row("1.20.1", true),
|
||||
];
|
||||
state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_only_filter_hides_uninstalled_versions() {
|
||||
let mut state = state_with_versions();
|
||||
assert_eq!(versions(&state).len(), 3);
|
||||
|
||||
state.installed_only = true;
|
||||
let filtered = versions(&state);
|
||||
assert_eq!(filtered.len(), 2);
|
||||
assert!(filtered.iter().all(|version| version.installed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_filters_by_version_id_substring() {
|
||||
let mut state = state_with_versions();
|
||||
state.download_query = "1.20".to_string();
|
||||
let filtered = versions(&state);
|
||||
assert_eq!(filtered.len(), 2);
|
||||
|
||||
state.download_query = "1.21".to_string();
|
||||
state.installed_only = true;
|
||||
// 「仅已装」优先:1.21.9 未安装 → 空列表
|
||||
assert!(versions(&state).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! 对话框队列(HMCL 队列语义 + Metro 化,09 §3)。
|
||||
//!
|
||||
//! 语义:**一次只显示一条**。新请求按来源插队(用户操作 > 后台任务 > 提示),同来源 FIFO;
|
||||
//! 当前条被确认/取消后由 [`DialogQueue::advance`] 推进到下一条,UI 只渲染 `current`。
|
||||
//! 非阻塞提示走 [`crate::toast`],不占模态队列。
|
||||
|
||||
/// 对话框标识。
|
||||
pub type DialogId = u64;
|
||||
|
||||
/// 对话框来源:决定插队优先级。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum DialogSource {
|
||||
/// 提示类(教程、首次使用说明)
|
||||
Hint = 0,
|
||||
/// 后台任务(下载完成、需要选择镜像源)
|
||||
BackgroundTask = 1,
|
||||
/// 用户操作触发(AI 敏感写操作的二次确认)
|
||||
UserAction = 2,
|
||||
}
|
||||
|
||||
impl DialogSource {
|
||||
/// 数值越大越优先。
|
||||
pub fn priority(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// 对话框类型(09 §3:确认 / 进度 / 输入 / 错误)。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum DialogKind {
|
||||
/// 确认:主按钮 + 次按钮
|
||||
Confirm {
|
||||
/// 主按钮文字(如「允许」)
|
||||
primary: String,
|
||||
/// 次按钮文字(如「拒绝」)
|
||||
secondary: String,
|
||||
},
|
||||
/// 输入:单行文本
|
||||
Input {
|
||||
/// 输入框标签
|
||||
label: String,
|
||||
/// 初始值
|
||||
value: String,
|
||||
/// 主按钮文字
|
||||
primary: String,
|
||||
},
|
||||
/// 进度:不可点主按钮(任务结束后由 [`crate::dto::AppEvent::DialogClosed`] 收起)
|
||||
Progress {
|
||||
/// 阶段文案
|
||||
label: String,
|
||||
/// 0.0~1.0
|
||||
progress: f32,
|
||||
},
|
||||
/// 错误:含诊断入口提示
|
||||
Error {
|
||||
/// 主按钮文字
|
||||
primary: String,
|
||||
/// 诊断/修复提示
|
||||
hint: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
/// 主按钮文字。
|
||||
pub fn primary_label(&self) -> &str {
|
||||
match self {
|
||||
Self::Confirm { primary, .. }
|
||||
| Self::Input { primary, .. }
|
||||
| Self::Error { primary, .. } => primary,
|
||||
Self::Progress { .. } => "取消",
|
||||
}
|
||||
}
|
||||
|
||||
/// 次按钮文字(None 表示不显示次按钮)。
|
||||
pub fn secondary_label(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Confirm { secondary, .. } => Some(secondary),
|
||||
Self::Error { .. } => Some("忽略"),
|
||||
Self::Input { .. } | Self::Progress { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 是否可交互(进度条不可点主按钮)。
|
||||
pub fn is_blocking_progress(&self) -> bool {
|
||||
matches!(self, Self::Progress { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// 一条对话框请求。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DialogRequest {
|
||||
/// 队列内唯一 id(由 [`DialogQueue::push_request`] 重新编号)
|
||||
pub id: DialogId,
|
||||
/// 来源(决定插队优先级)
|
||||
pub source: DialogSource,
|
||||
/// 标题
|
||||
pub title: String,
|
||||
/// 正文
|
||||
pub body: String,
|
||||
/// 类型与按钮
|
||||
pub kind: DialogKind,
|
||||
}
|
||||
|
||||
/// 模态队列:一次一条 + 来源插队。
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DialogQueue {
|
||||
current: Option<DialogRequest>,
|
||||
pending: Vec<DialogRequest>,
|
||||
next_id: DialogId,
|
||||
}
|
||||
|
||||
impl DialogQueue {
|
||||
/// 新建空队列。
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// 当前应显示的对话框。
|
||||
pub fn current(&self) -> Option<&DialogRequest> {
|
||||
self.current.as_ref()
|
||||
}
|
||||
|
||||
/// 排队中(不含当前)条数。
|
||||
pub fn pending_len(&self) -> usize {
|
||||
self.pending.len()
|
||||
}
|
||||
|
||||
/// 是否完全没有对话框(当前 + 排队)。
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.current.is_none() && self.pending.is_empty()
|
||||
}
|
||||
|
||||
/// 入队一条请求(UI 内部调用方用,id 由队列自增分配)。没有当前条时立即成为当前条。
|
||||
///
|
||||
/// 返回值用于后续 [`Self::close`] / 进度更新。
|
||||
pub fn push(
|
||||
&mut self,
|
||||
source: DialogSource,
|
||||
title: impl Into<String>,
|
||||
body: impl Into<String>,
|
||||
kind: DialogKind,
|
||||
) -> DialogId {
|
||||
self.next_id += 1;
|
||||
self.push_request(DialogRequest {
|
||||
id: self.next_id,
|
||||
source,
|
||||
title: title.into(),
|
||||
body: body.into(),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
/// 入队一条已经组装好的请求(事件通道用)。
|
||||
///
|
||||
/// **id 归生产者**:这里原样保留 `request.id`(不重编号),因为关闭事件
|
||||
/// [`crate::dto::AppEvent::DialogClosed`] 携带的是生产者 id;重编号会让
|
||||
/// 「任务完成 → 自动收起进度框」在多来源弹框时静默失配。生产者负责自身 id 唯一。
|
||||
pub fn push_request(&mut self, request: DialogRequest) -> DialogId {
|
||||
let id = request.id;
|
||||
let source = request.source;
|
||||
if self.current.is_none() {
|
||||
self.current = Some(request);
|
||||
} else {
|
||||
let at = self
|
||||
.pending
|
||||
.iter()
|
||||
.position(|queued| queued.source < source)
|
||||
.unwrap_or(self.pending.len());
|
||||
self.pending.insert(at, request);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// 关闭指定对话框:若是当前条则推进到下一条,否则从队列移除。
|
||||
///
|
||||
/// 返回 `true` 表示确实移除了。
|
||||
pub fn close(&mut self, id: DialogId) -> bool {
|
||||
if self
|
||||
.current
|
||||
.as_ref()
|
||||
.is_some_and(|current| current.id == id)
|
||||
{
|
||||
self.advance();
|
||||
return true;
|
||||
}
|
||||
if let Some(at) = self.pending.iter().position(|queued| queued.id == id) {
|
||||
self.pending.remove(at);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 推进到下一条排队请求(当前条已被处理)。
|
||||
pub fn advance(&mut self) {
|
||||
self.current = if self.pending.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.pending.remove(0))
|
||||
};
|
||||
}
|
||||
|
||||
/// 关闭当前条并推进到下一条(确认 / 取消 / 点遮罩都走这里)。
|
||||
///
|
||||
/// 返回 `false` 表示本来就没有当前条(幂等,双击不会误推进队列)。
|
||||
pub fn close_current(&mut self) -> bool {
|
||||
if self.current.is_none() {
|
||||
return false;
|
||||
}
|
||||
self.advance();
|
||||
true
|
||||
}
|
||||
|
||||
/// 更新进度对话框的进度(任务回调直接喂进来)。
|
||||
pub fn update_progress(&mut self, id: DialogId, progress: f32) {
|
||||
let Some(current) = &mut self.current else {
|
||||
return;
|
||||
};
|
||||
if current.id != id {
|
||||
return;
|
||||
}
|
||||
if let DialogKind::Progress {
|
||||
progress: value, ..
|
||||
} = &mut current.kind
|
||||
{
|
||||
*value = progress.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{DialogKind, DialogQueue, DialogSource};
|
||||
|
||||
fn confirm() -> DialogKind {
|
||||
DialogKind::Confirm {
|
||||
primary: "确定".into(),
|
||||
secondary: "取消".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shows_one_dialog_at_a_time() {
|
||||
let mut queue = DialogQueue::new();
|
||||
let first = queue.push(DialogSource::BackgroundTask, "A", "", confirm());
|
||||
let second = queue.push(DialogSource::BackgroundTask, "B", "", confirm());
|
||||
|
||||
assert_eq!(queue.current().map(|d| d.id), Some(first));
|
||||
assert_eq!(queue.pending_len(), 1);
|
||||
|
||||
queue.advance();
|
||||
assert_eq!(queue.current().map(|d| d.id), Some(second));
|
||||
assert_eq!(queue.pending_len(), 0);
|
||||
|
||||
queue.advance();
|
||||
assert!(queue.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_action_jumps_the_queue() {
|
||||
let mut queue = DialogQueue::new();
|
||||
queue.push(DialogSource::Hint, "提示", "", confirm());
|
||||
queue.push(DialogSource::Hint, "提示2", "", confirm());
|
||||
queue.push(DialogSource::BackgroundTask, "后台", "", confirm());
|
||||
let urgent = queue.push(DialogSource::UserAction, "确认删除", "", confirm());
|
||||
|
||||
// 当前仍是队首(一次一条),但排队里用户操作插到最前 → 关掉当前条后立刻轮到它
|
||||
queue.advance();
|
||||
assert_eq!(queue.current().map(|d| d.id), Some(urgent));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_non_current_dialog_removes_it_from_pending() {
|
||||
let mut queue = DialogQueue::new();
|
||||
let first = queue.push(DialogSource::Hint, "A", "", confirm());
|
||||
let second = queue.push(DialogSource::Hint, "B", "", confirm());
|
||||
|
||||
assert!(queue.close(second));
|
||||
assert_eq!(queue.pending_len(), 0);
|
||||
assert_eq!(queue.current().map(|d| d.id), Some(first));
|
||||
assert!(!queue.close(999));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_dialog_can_be_updated() {
|
||||
let mut queue = DialogQueue::new();
|
||||
let id = queue.push(
|
||||
DialogSource::BackgroundTask,
|
||||
"下载中",
|
||||
"",
|
||||
DialogKind::Progress {
|
||||
label: "资源".into(),
|
||||
progress: 0.0,
|
||||
},
|
||||
);
|
||||
queue.update_progress(id, 1.7);
|
||||
match queue.current().map(|d| &d.kind) {
|
||||
Some(DialogKind::Progress { progress, .. }) => {
|
||||
assert!((*progress - 1.0).abs() < f32::EPSILON);
|
||||
}
|
||||
other => panic!("unexpected dialog kind: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! AI 会话 DTO:消息、工具调用可视化与 agent 事件。
|
||||
|
||||
/// 会话消息角色。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ChatRole {
|
||||
/// 用户
|
||||
User,
|
||||
/// 助手(可流式)
|
||||
Assistant,
|
||||
/// 工具调用(会话里可见,D4 要求)
|
||||
Tool,
|
||||
/// 系统提示(弱化展示)
|
||||
System,
|
||||
}
|
||||
|
||||
/// 工具调用可视化条目。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ToolCallView {
|
||||
/// 工具名(与 ToolSpec 注册表同名)
|
||||
pub name: String,
|
||||
/// 是否成功
|
||||
pub ok: bool,
|
||||
/// 一行结果摘要
|
||||
pub summary: String,
|
||||
}
|
||||
|
||||
/// 一条会话消息。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ChatMessage {
|
||||
/// 角色
|
||||
pub role: ChatRole,
|
||||
/// 正文(流式时持续追加)
|
||||
pub text: String,
|
||||
/// role == Tool 时带上工具调用详情
|
||||
pub tool: Option<ToolCallView>,
|
||||
/// 流式未收敛
|
||||
pub streaming: bool,
|
||||
}
|
||||
|
||||
impl ChatMessage {
|
||||
/// 用户消息。
|
||||
pub fn user(text: impl Into<String>) -> Self {
|
||||
Self {
|
||||
role: ChatRole::User,
|
||||
text: text.into(),
|
||||
tool: None,
|
||||
streaming: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 助手流式消息起点(空文本 + streaming)。
|
||||
pub fn assistant_stream() -> Self {
|
||||
Self {
|
||||
role: ChatRole::Assistant,
|
||||
text: String::new(),
|
||||
tool: None,
|
||||
streaming: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// agent 侧事件。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AgentEvent {
|
||||
/// 追加一条完整消息
|
||||
MessageAppended(ChatMessage),
|
||||
/// 给指定序号的流式消息追加增量
|
||||
MessageDelta {
|
||||
/// 目标消息在会话里的序号
|
||||
index: usize,
|
||||
/// 增量文本
|
||||
delta: String,
|
||||
},
|
||||
/// 流式收敛
|
||||
MessageFinished {
|
||||
/// 目标消息序号
|
||||
index: usize,
|
||||
},
|
||||
/// 开始一次工具调用(会话里插入工具条目)
|
||||
ToolCallStarted {
|
||||
/// 工具名
|
||||
name: String,
|
||||
/// 调用参数摘要
|
||||
summary: String,
|
||||
},
|
||||
/// 工具调用结束
|
||||
ToolCallFinished {
|
||||
/// 工具名
|
||||
name: String,
|
||||
/// 是否成功
|
||||
ok: bool,
|
||||
/// 结果摘要
|
||||
summary: String,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! 事件与指令:core/agent → app 的事件队列,app → core/agent 的用户意图。
|
||||
|
||||
use crate::dialogs::{DialogId, DialogRequest};
|
||||
use crate::dto::{AgentEvent, DiagnosisReport, InstanceId, InstanceRuntime, InstanceSummary};
|
||||
use crate::dto::{LogLine, LogSession, SessionId, VersionCategory, VersionSummary};
|
||||
use crate::toast::Toast;
|
||||
|
||||
/// core 侧事件(不可变快照发布 + 事件流,01c §5 的三条通道之二)。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum CoreEvent {
|
||||
/// 实例列表整体刷新
|
||||
InstancesChanged(Vec<InstanceSummary>),
|
||||
/// 单个实例运行时状态变化(启动进度/运行中/失败)
|
||||
InstanceRuntimeChanged {
|
||||
/// 实例 id
|
||||
id: InstanceId,
|
||||
/// 新状态
|
||||
runtime: InstanceRuntime,
|
||||
},
|
||||
/// 下载页版本列表刷新
|
||||
VersionListChanged(Vec<VersionSummary>),
|
||||
/// 日志会话列表刷新
|
||||
LogSessionsChanged(Vec<LogSession>),
|
||||
/// 当前会话日志行刷新(P0 整批替换;P1 改增量追加)
|
||||
LogLinesChanged(Vec<LogLine>),
|
||||
/// 诊断结论产出
|
||||
DiagnosisReady(DiagnosisReport),
|
||||
}
|
||||
|
||||
/// 统一事件队列的元素:core / agent / UI 自产(对话框、Toast)都走这一条路,
|
||||
/// 这样 [`crate::state::AppState::apply`] 是唯一的状态变更入口。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum AppEvent {
|
||||
/// 来自 core
|
||||
Core(CoreEvent),
|
||||
/// 来自 agent
|
||||
Agent(AgentEvent),
|
||||
/// core/agent 请求弹对话框(会进队列,一次一条)
|
||||
DialogRequested(DialogRequest),
|
||||
/// 关闭指定对话框(任务完成收起进度条)
|
||||
DialogClosed(DialogId),
|
||||
/// 右下角 Toast
|
||||
Toast(Toast),
|
||||
}
|
||||
|
||||
/// app → core/agent 的用户意图。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AppCommand {
|
||||
/// 重新扫描实例目录
|
||||
RefreshInstances,
|
||||
/// 启动实例
|
||||
LaunchInstance(InstanceId),
|
||||
/// 停止实例(含取消启动中的管线)
|
||||
StopInstance(InstanceId),
|
||||
/// 拉取某分类的版本列表
|
||||
ListVersions(VersionCategory),
|
||||
/// 安装指定版本
|
||||
InstallVersion(String),
|
||||
/// 刷新日志会话列表
|
||||
RefreshLogSessions,
|
||||
/// 打开某个会话(拉取日志行 + 触发诊断)
|
||||
OpenLogSession(SessionId),
|
||||
/// 向 AI 提问(会话状态在 app 侧,agent 只回事件)
|
||||
AskAgent(String),
|
||||
/// 中断当前 AI 流
|
||||
StopAgent,
|
||||
/// YOLO 开关(跳过确认,审计照记)
|
||||
SetYolo(bool),
|
||||
}
|
||||
|
||||
/// 后端通道:core/agent host 实现它;P0 用 [`crate::mock::MockBackend`] 验证通道语义。
|
||||
///
|
||||
/// 轮询模型(而非回调)是为了让 Slint 的定时器成为唯一调度者,
|
||||
/// 避免跨线程回调里碰 Slint 模型。
|
||||
pub trait Backend {
|
||||
/// 取走自上次调用以来积压的事件(FIFO,不可丢序号)。
|
||||
fn drain_events(&mut self) -> Vec<AppEvent>;
|
||||
|
||||
/// 下发一条用户意图。
|
||||
fn dispatch(&mut self, command: AppCommand);
|
||||
|
||||
/// 时间推进(mock 用脚本推进进度;真实后端可以是空实现)。
|
||||
fn tick(&mut self, elapsed: std::time::Duration) {
|
||||
let _ = elapsed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! 实例相关 DTO:磁贴与列表视图的唯一数据源。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// 实例标识:core::game 生成的稳定 id,app 视为不透明字符串。
|
||||
pub type InstanceId = String;
|
||||
|
||||
/// 加载器种类(磁贴徽标 + 详情页版本链)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LoaderKind {
|
||||
/// 原版(无加载器)
|
||||
Vanilla,
|
||||
/// Fabric
|
||||
Fabric,
|
||||
/// Quilt
|
||||
Quilt,
|
||||
/// Forge
|
||||
Forge,
|
||||
/// NeoForge
|
||||
NeoForge,
|
||||
/// OptiFine
|
||||
OptiFine,
|
||||
/// LiteLoader
|
||||
LiteLoader,
|
||||
}
|
||||
|
||||
impl LoaderKind {
|
||||
/// 徽标显示文字。
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Vanilla => "原版",
|
||||
Self::Fabric => "Fabric",
|
||||
Self::Quilt => "Quilt",
|
||||
Self::Forge => "Forge",
|
||||
Self::NeoForge => "NeoForge",
|
||||
Self::OptiFine => "OptiFine",
|
||||
Self::LiteLoader => "LiteLoader",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 加载器 + 版本(例如 Fabric 0.16.5)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LoaderInfo {
|
||||
/// 加载器种类
|
||||
pub kind: LoaderKind,
|
||||
/// 加载器版本号;原版为空串
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl LoaderInfo {
|
||||
/// 徽标文字:原版只写「原版」,装加载器时写「Fabric 0.16.5」。
|
||||
pub fn badge(&self) -> String {
|
||||
if self.kind == LoaderKind::Vanilla || self.version.is_empty() {
|
||||
self.kind.label().to_string()
|
||||
} else {
|
||||
format!("{} {}", self.kind.label(), self.version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 字节进度;`total == 0` 表示总量未知(UI 转不确定态)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct Progress {
|
||||
/// 已完成量
|
||||
pub done: u64,
|
||||
/// 总量;0 = 未知
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// 0.0~1.0;未知总量返回 0.0。
|
||||
pub fn ratio(self) -> f32 {
|
||||
if self.total == 0 {
|
||||
0.0
|
||||
} else {
|
||||
(self.done as f32 / self.total as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// 总量是否已知。
|
||||
pub fn is_known(self) -> bool {
|
||||
self.total > 0
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动管线阶段(磁贴进度环的文案来源;D8 的 10 阶段在 P1 细化)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LaunchStage {
|
||||
/// 下载资源
|
||||
Download,
|
||||
/// 校验文件
|
||||
Verify,
|
||||
/// 组装命令行并拉起进程
|
||||
Launch,
|
||||
}
|
||||
|
||||
impl LaunchStage {
|
||||
/// 磁贴上的阶段文案。
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Download => "下载资源",
|
||||
Self::Verify => "校验文件",
|
||||
Self::Launch => "启动中",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 实例运行时状态(磁贴的四种外观)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub enum InstanceRuntime {
|
||||
/// 空闲
|
||||
#[default]
|
||||
Idle,
|
||||
/// 启动管线进行中
|
||||
Busy {
|
||||
/// 当前阶段
|
||||
stage: LaunchStage,
|
||||
/// 该阶段进度
|
||||
progress: Progress,
|
||||
},
|
||||
/// 游戏进程存活
|
||||
Running {
|
||||
/// 进程号(停止/诊断用)
|
||||
pid: u32,
|
||||
},
|
||||
/// 上次启动失败(磁贴显示「重试」)
|
||||
Failed {
|
||||
/// 失败原因(用户可见文案)
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// 实例摘要:磁贴/列表视图唯一数据源。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct InstanceSummary {
|
||||
/// 稳定 id
|
||||
pub id: InstanceId,
|
||||
/// 显示名
|
||||
pub name: String,
|
||||
/// 游戏版本(如 1.20.4)
|
||||
pub mc_version: String,
|
||||
/// 加载器信息
|
||||
pub loader: LoaderInfo,
|
||||
/// ISO-8601 UTC 最后游玩时间;None = 从未启动
|
||||
pub last_played: Option<String>,
|
||||
/// 运行时状态
|
||||
pub runtime: InstanceRuntime,
|
||||
/// 实例图标路径(P0 直接给路径;P1 换成 core 提供的图像句柄)
|
||||
pub icon: Option<PathBuf>,
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! 日志页 DTO:会话列表、日志行与 D8 诊断结论。
|
||||
|
||||
/// 一次启动会话(日志页左栏单位)标识。
|
||||
pub type SessionId = String;
|
||||
|
||||
/// 一次运行的结局(G3 左栏图标:✓ 正常 / ✗ 崩溃 / ⚠ 静默失败)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LogOutcome {
|
||||
/// 正常退出
|
||||
Ok,
|
||||
/// 崩溃(非零退出码或 hs_err_pid)
|
||||
Crashed,
|
||||
/// exit0 但游戏没起来(D8 新增检测)
|
||||
SilentFail,
|
||||
}
|
||||
|
||||
/// 会话摘要。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LogSession {
|
||||
/// 会话 id
|
||||
pub id: SessionId,
|
||||
/// 实例名(会话属于哪个实例)
|
||||
pub instance: String,
|
||||
/// 展示用时间(`10-29 19:22`)
|
||||
pub when: String,
|
||||
/// 结局
|
||||
pub outcome: LogOutcome,
|
||||
/// 时长(秒)
|
||||
pub duration_secs: u64,
|
||||
}
|
||||
|
||||
/// 日志行等级(错误行高亮)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LogLevel {
|
||||
/// debug
|
||||
Debug,
|
||||
/// info
|
||||
Info,
|
||||
/// warn
|
||||
Warn,
|
||||
/// error
|
||||
Error,
|
||||
}
|
||||
|
||||
/// 一行日志。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LogLine {
|
||||
/// 原始文本(含时间戳前缀)
|
||||
pub text: String,
|
||||
/// 等级
|
||||
pub level: LogLevel,
|
||||
}
|
||||
|
||||
/// D8 规则引擎结论(日志页崩溃诊断卡片)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Diagnosis {
|
||||
/// 命中规则 id(`gpu.driver_old`)
|
||||
pub rule: String,
|
||||
/// 结论标题
|
||||
pub title: String,
|
||||
/// 0~100 置信度
|
||||
pub confidence: u8,
|
||||
/// 建议文案
|
||||
pub hint: String,
|
||||
/// 可一键执行的修复动作(无则只给建议)
|
||||
pub fix: Option<String>,
|
||||
}
|
||||
|
||||
/// 诊断结论 + 归属会话(UI 用它决定卡片显隐)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DiagnosisReport {
|
||||
/// 归属会话
|
||||
pub session: SessionId,
|
||||
/// 诊断内容
|
||||
pub diagnosis: Diagnosis,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! app ↔ core/agent 的 IPC 边界(01c §5 纪律)。
|
||||
//!
|
||||
//! 这里只允许出现「扁平 DTO / 事件 / 指令」:`crates/app` 任何模块都不得 `use unlucky_core::*`
|
||||
//! 或 `use unlucky_agent::*` 的内部类型。core/agent 侧的 host 层负责把自身类型翻译成本模块的类型,
|
||||
//! 反向的 [`AppCommand`] 也一样。P0 阶段由 [`crate::mock`] 的假后端实现 [`Backend`] 驱动骨架。
|
||||
//!
|
||||
//! 结构:**按领域拆子模块**(instances / versions / logs / agent / events),
|
||||
//! 全量 `pub use` 出去,调用方依旧写 `crate::dto::InstanceSummary` 这类路径。
|
||||
//! 契约说明(字段口径、事件顺序、错误语义)见 `DevDocs/SubAgentsTalk/app-DTO通道约定.md`。
|
||||
|
||||
mod agent;
|
||||
mod events;
|
||||
mod instances;
|
||||
mod logs;
|
||||
mod versions;
|
||||
|
||||
pub use agent::{AgentEvent, ChatMessage, ChatRole, ToolCallView};
|
||||
pub use events::{AppCommand, AppEvent, Backend, CoreEvent};
|
||||
pub use instances::{
|
||||
InstanceId, InstanceRuntime, InstanceSummary, LaunchStage, LoaderInfo, LoaderKind, Progress,
|
||||
};
|
||||
pub use logs::{Diagnosis, DiagnosisReport, LogLevel, LogLine, LogOutcome, LogSession, SessionId};
|
||||
pub use versions::{AncientKind, VersionCategory, VersionKind, VersionSummary};
|
||||
@@ -0,0 +1,60 @@
|
||||
//! 下载页 DTO:版本列表与分类(含远古版子类,D16/Q24-4)。
|
||||
|
||||
/// 版本类型(远古版按 unlisted-versions 的分类拆开)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VersionKind {
|
||||
/// 正式版
|
||||
Release,
|
||||
/// 预览版(snapshot)
|
||||
Snapshot,
|
||||
/// 远古版(带子类)
|
||||
Ancient(AncientKind),
|
||||
}
|
||||
|
||||
/// 远古版子类。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AncientKind {
|
||||
/// classic(rd-*)
|
||||
Classic,
|
||||
/// old_alpha(a1.*)
|
||||
OldAlpha,
|
||||
/// old_beta(b1.*)
|
||||
OldBeta,
|
||||
/// 未列入官方清单的远古版汇总
|
||||
Unlisted,
|
||||
}
|
||||
|
||||
impl VersionKind {
|
||||
/// 是否属于「远古版」——列表行要加警示徽标。
|
||||
pub fn is_ancient(self) -> bool {
|
||||
matches!(self, Self::Ancient(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载页版本行。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct VersionSummary {
|
||||
/// 版本 id(如 `1.20.4` / `rd-132211`)
|
||||
pub id: String,
|
||||
/// 版本类型
|
||||
pub kind: VersionKind,
|
||||
/// 发布日期(ISO-8601 日期部分)
|
||||
pub released: String,
|
||||
/// 本地是否已安装(行尾显示「已装」)
|
||||
pub installed: bool,
|
||||
}
|
||||
|
||||
/// 下载页左侧分类(页内常驻侧栏的选中项)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VersionCategory {
|
||||
/// 正式版
|
||||
Release,
|
||||
/// 预览版
|
||||
Snapshot,
|
||||
/// 远古版某子类
|
||||
Ancient(AncientKind),
|
||||
/// 整合包(P1)
|
||||
Modpack,
|
||||
/// Mod(P1)
|
||||
Mod,
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Unlucky-Launcher 桌面壳(`unlucky_app`):Slint UI + Metro 视觉。
|
||||
//!
|
||||
//! 边界(决策 D3 / D16):本 crate 是**唯一**允许依赖 UI 框架的 crate;
|
||||
//! 它只经「快照 + 事件流 + 注入的显示服务」消费 core/agent,不直接触碰其内部类型
|
||||
//! (P0 的 host 是 `mock` 假后端,`crate::dto` 是唯一跨界类型集合)。
|
||||
//!
|
||||
//! 渲染策略(`DevDocs/PlanDoc/01c-native-gui-options.md` §6):
|
||||
//! GL 优先(femtovg),启动参数 `--software-renderer` 或 Win7 老机探测失败时切 CPU 软渲染。
|
||||
//!
|
||||
//! 主题与外观(D17 / 09 §101-113):
|
||||
//! - 主题三态 `appearance.theme_mode ∈ {auto, light, dark}`(出厂 auto);
|
||||
//! - 「外观(高级)」四件(背景图 / 面板半透明度 / 玻璃拟态 / 强调色)出厂全关;
|
||||
//! - 全部走 `core::setting` 的 schema(`crate::settings_bridge`),AI 可写并且**热切**
|
||||
//! (tick 里 1s 一次 mtime 比对);系统主题由 `core::platform::theme_probe` 对齐 + 兜底轮询。
|
||||
//!
|
||||
//! 架构分层(本文件只有一个职责:把窗口拉起来):
|
||||
//! - `state.rs` / `prefs.rs` / `router.rs` / `dialogs.rs` / `toast.rs`:纯 Rust 状态(可单测,无 Slint)
|
||||
//! - `dto/`:跨边界 DTO 与事件/指令
|
||||
//! - `conv.rs`:状态 → Slint 视图模型
|
||||
//! - `ui_bind.rs` + `callbacks.rs`:窗口/状态/后端缝合 + 回调接线
|
||||
//! - `settings_bridge.rs`:`config/launcher.json` 的读写与热切(core::setting 的 schema API)
|
||||
//! - `bg_image.rs` + `png.rs`:背景图/模糊层加工与截图编码(09 §101/§103 的预生成手法)
|
||||
//! - `mock.rs` + `mock_data.rs`:P0 假后端(脚本化事件)
|
||||
//!
|
||||
//! 关于 unsafe:本 crate 不写 unsafe,workspace lint 已设 `unsafe_code = "deny"`。
|
||||
//! 这里不能升级成 `#![forbid(unsafe_code)]`——Slint 生成的代码自带 `#[allow(unsafe_code)]`,
|
||||
//! 而 forbid 无法被内层 allow 覆盖(会直接编译失败)。同理 Slint 生成类型不带文档注释,
|
||||
//! 只能在 crate 级放开 `missing_docs`(库 crate 仍由 workspace lint 保持 warn)。
|
||||
// 关于 dead_code:P0 骨架里有一批「已定义、等接线」的公共 API——事件通道 / 偏好键登记 /
|
||||
// 诊断文案 / mock 数据构造器等,它们被单测覆盖但业务侧要 P1 才用到。逐条 `#[allow]`
|
||||
// 会把噪音藏进实现细节,这里统一放开并在 P1 接线时逐个转正(届时删掉本行即可暴露真死码)。
|
||||
#![allow(missing_docs, dead_code)]
|
||||
|
||||
mod appearance_bind;
|
||||
mod bg_image;
|
||||
mod callbacks;
|
||||
mod conv;
|
||||
mod dialogs;
|
||||
mod dto;
|
||||
mod mock;
|
||||
mod mock_data;
|
||||
mod png;
|
||||
mod prefs;
|
||||
mod router;
|
||||
mod settings_bridge;
|
||||
mod state;
|
||||
mod theme_runtime;
|
||||
mod toast;
|
||||
mod ui_bind;
|
||||
|
||||
slint::include_modules!();
|
||||
|
||||
fn main() -> Result<(), slint::PlatformError> {
|
||||
apply_renderer_flag();
|
||||
|
||||
let app = ui_bind::AppUi::new(MainWindow::new()?);
|
||||
|
||||
// 截图验收通道(M41 视觉验收;无交互桌面/无 GPU 环境下的唯一可靠取图方式:
|
||||
// 不截屏幕,而是让 Slint 把当前场景渲染进内存像素缓冲再自己编码 PNG)。
|
||||
if let Some(path) = screenshot_path() {
|
||||
if std::env::args().any(|arg| arg == "--screenshot-settings") {
|
||||
app.open_settings_appearance();
|
||||
}
|
||||
app.render_screenshot(&path)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
app.start_timer();
|
||||
app.run()
|
||||
}
|
||||
|
||||
/// Win7 老机 / 无可用 OpenGL 驱动时的软渲染兜底开关(01c §6 的 Slint 核心卖点)。
|
||||
fn apply_renderer_flag() {
|
||||
let software = std::env::args()
|
||||
.skip(1)
|
||||
.any(|arg| arg == "--software-renderer");
|
||||
if software {
|
||||
std::env::set_var("SLINT_BACKEND", "winit-software");
|
||||
}
|
||||
}
|
||||
|
||||
/// `--screenshot <path>` / `--screenshot=<path>`:渲染一帧并写 PNG 后退出。
|
||||
fn screenshot_path() -> Option<String> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(value) = arg.strip_prefix("--screenshot=") {
|
||||
return Some(value.to_owned());
|
||||
}
|
||||
if arg == "--screenshot" {
|
||||
return args.next();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! P0 假后端:用脚本化事件驱动骨架,验证 app ↔ core/agent 通道语义。
|
||||
//!
|
||||
//! 覆盖四条通道:实例运行状态(磁贴进度环)、AI 流式会话(含工具调用)、
|
||||
//! 对话框队列(进度对话框)、Toast。阶段 B 里由真正的 core/agent host 替换
|
||||
//! [`MockBackend`],[`crate::dto::Backend`] 之上的 state/reducer 不动。
|
||||
//! 假数据本体在 [`crate::mock_data`]。
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::dialogs::{DialogKind, DialogRequest, DialogSource};
|
||||
use crate::dto::{
|
||||
AgentEvent, AppCommand, AppEvent, Backend, ChatMessage, ChatRole, CoreEvent, InstanceId,
|
||||
InstanceRuntime, LaunchStage, Progress,
|
||||
};
|
||||
use crate::mock_data::{mock_instances, mock_log_lines, mock_log_sessions, mock_versions};
|
||||
use crate::toast::{Toast, ToastKind};
|
||||
|
||||
/// 启动脚本:按时间推进 download → verify → launch → running。
|
||||
#[derive(Debug)]
|
||||
struct LaunchScript {
|
||||
id: InstanceId,
|
||||
elapsed_ms: u64,
|
||||
}
|
||||
|
||||
/// AI 流式脚本:每条提问回一段可切分的话 + 一次工具调用。
|
||||
#[derive(Debug)]
|
||||
struct ChatScript {
|
||||
elapsed_ms: u64,
|
||||
chunks: VecDeque<String>,
|
||||
/// 流式助手消息在 app 会话里的序号
|
||||
message_index: usize,
|
||||
}
|
||||
|
||||
/// 假后端。
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MockBackend {
|
||||
events: VecDeque<AppEvent>,
|
||||
launch: Option<LaunchScript>,
|
||||
chat: Option<ChatScript>,
|
||||
/// 已投递给 app 的会话消息条数(用来给 MessageDelta 算序号)
|
||||
emitted_messages: usize,
|
||||
next_dialog: u64,
|
||||
}
|
||||
|
||||
impl MockBackend {
|
||||
/// 预置一批假数据事件(实例/版本/日志会话)。
|
||||
pub fn new() -> Self {
|
||||
let mut backend = Self::default();
|
||||
backend.seed();
|
||||
backend
|
||||
}
|
||||
|
||||
fn seed(&mut self) {
|
||||
self.events.push_back(AppEvent::Core(
|
||||
CoreEvent::InstancesChanged(mock_instances()),
|
||||
));
|
||||
self.events
|
||||
.push_back(AppEvent::Core(CoreEvent::VersionListChanged(
|
||||
mock_versions(),
|
||||
)));
|
||||
self.events
|
||||
.push_back(AppEvent::Core(CoreEvent::LogSessionsChanged(
|
||||
mock_log_sessions(),
|
||||
)));
|
||||
self.events
|
||||
.push_back(AppEvent::Core(CoreEvent::LogLinesChanged(mock_log_lines())));
|
||||
}
|
||||
|
||||
fn emit(&mut self, event: AppEvent) {
|
||||
self.events.push_back(event);
|
||||
}
|
||||
|
||||
fn next_dialog_id(&mut self) -> u64 {
|
||||
self.next_dialog += 1;
|
||||
self.next_dialog
|
||||
}
|
||||
|
||||
fn script_launch(&mut self, id: InstanceId) {
|
||||
self.emit(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
id: id.clone(),
|
||||
runtime: InstanceRuntime::Busy {
|
||||
stage: LaunchStage::Download,
|
||||
progress: Progress {
|
||||
done: 0,
|
||||
total: 1_500,
|
||||
},
|
||||
},
|
||||
}));
|
||||
self.launch = Some(LaunchScript { id, elapsed_ms: 0 });
|
||||
}
|
||||
|
||||
fn step_launch(&mut self, elapsed: Duration) {
|
||||
let Some((id, elapsed_ms)) = self.launch.as_mut().map(|script| {
|
||||
script.elapsed_ms += u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
|
||||
(script.id.clone(), script.elapsed_ms)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// 0~1.5s 下载、1.5~2.5s 校验、2.5~3s 启动、3s 后转为运行中
|
||||
let runtime = if elapsed_ms < 1_500 {
|
||||
InstanceRuntime::Busy {
|
||||
stage: LaunchStage::Download,
|
||||
progress: Progress {
|
||||
done: elapsed_ms,
|
||||
total: 1_500,
|
||||
},
|
||||
}
|
||||
} else if elapsed_ms < 2_500 {
|
||||
InstanceRuntime::Busy {
|
||||
stage: LaunchStage::Verify,
|
||||
progress: Progress {
|
||||
done: elapsed_ms - 1_500,
|
||||
total: 1_000,
|
||||
},
|
||||
}
|
||||
} else if elapsed_ms < 3_000 {
|
||||
InstanceRuntime::Busy {
|
||||
stage: LaunchStage::Launch,
|
||||
progress: Progress {
|
||||
done: elapsed_ms - 2_500,
|
||||
total: 500,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
self.launch = None;
|
||||
self.emit(AppEvent::Toast(Toast {
|
||||
id: 0,
|
||||
kind: ToastKind::Success,
|
||||
text: "游戏已启动".to_string(),
|
||||
remaining_ms: 0,
|
||||
}));
|
||||
InstanceRuntime::Running { pid: 12_345 }
|
||||
};
|
||||
|
||||
self.emit(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
id,
|
||||
runtime,
|
||||
}));
|
||||
}
|
||||
|
||||
fn script_chat(&mut self, text: String) {
|
||||
let user_index = self.emitted_messages;
|
||||
self.emit(AppEvent::Agent(AgentEvent::MessageAppended(
|
||||
ChatMessage::user(text),
|
||||
)));
|
||||
self.emit(AppEvent::Agent(AgentEvent::MessageAppended(
|
||||
ChatMessage::assistant_stream(),
|
||||
)));
|
||||
self.emitted_messages += 2;
|
||||
self.chat = Some(ChatScript {
|
||||
elapsed_ms: 0,
|
||||
chunks: VecDeque::from(vec![
|
||||
"先确认版本:".to_string(),
|
||||
"官方 1.20.4 是正式版,".to_string(),
|
||||
"装完再用 Fabric 加加载器。".to_string(),
|
||||
]),
|
||||
message_index: user_index + 1,
|
||||
});
|
||||
}
|
||||
|
||||
fn step_chat(&mut self, elapsed: Duration) {
|
||||
let Some(chat) = self.chat.as_mut() else {
|
||||
return;
|
||||
};
|
||||
chat.elapsed_ms += u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
|
||||
if chat.elapsed_ms < 300 {
|
||||
return;
|
||||
}
|
||||
chat.elapsed_ms = 0;
|
||||
let index = chat.message_index;
|
||||
let chunk = chat.chunks.pop_front();
|
||||
|
||||
if let Some(delta) = chunk {
|
||||
self.emit(AppEvent::Agent(AgentEvent::MessageDelta { index, delta }));
|
||||
return;
|
||||
}
|
||||
|
||||
// 流结束后补一次工具调用(工具执行在会话里可见)+ 收尾消息
|
||||
self.emit(AppEvent::Agent(AgentEvent::ToolCallStarted {
|
||||
name: "read_game_log".to_string(),
|
||||
summary: "读取最近一次崩溃日志".to_string(),
|
||||
}));
|
||||
self.emit(AppEvent::Agent(AgentEvent::ToolCallFinished {
|
||||
name: "read_game_log".to_string(),
|
||||
ok: true,
|
||||
summary: "读到 128 行,无 ERROR".to_string(),
|
||||
}));
|
||||
self.emit(AppEvent::Agent(AgentEvent::MessageFinished { index }));
|
||||
self.emit(AppEvent::Agent(AgentEvent::MessageAppended(ChatMessage {
|
||||
role: ChatRole::Assistant,
|
||||
text: "日志没有 ERROR,问题更可能在 Java 版本。".to_string(),
|
||||
tool: None,
|
||||
streaming: false,
|
||||
})));
|
||||
self.emitted_messages += 2;
|
||||
self.chat = None;
|
||||
}
|
||||
|
||||
fn script_install(&mut self, version: String) {
|
||||
let id = self.next_dialog_id();
|
||||
self.emit(AppEvent::DialogRequested(DialogRequest {
|
||||
id,
|
||||
source: DialogSource::BackgroundTask,
|
||||
title: format!("正在安装 {version}"),
|
||||
body: String::new(),
|
||||
kind: DialogKind::Progress {
|
||||
label: "下载资源".to_string(),
|
||||
progress: 0.0,
|
||||
},
|
||||
}));
|
||||
self.emit(AppEvent::DialogClosed(id));
|
||||
self.emit(AppEvent::Toast(Toast {
|
||||
id: 0,
|
||||
kind: ToastKind::Success,
|
||||
text: format!("{version} 安装完成"),
|
||||
remaining_ms: 0,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for MockBackend {
|
||||
fn drain_events(&mut self) -> Vec<AppEvent> {
|
||||
self.events.drain(..).collect()
|
||||
}
|
||||
|
||||
fn dispatch(&mut self, command: AppCommand) {
|
||||
match command {
|
||||
AppCommand::LaunchInstance(id) => self.script_launch(id),
|
||||
AppCommand::StopInstance(id) => {
|
||||
self.launch = None;
|
||||
self.emit(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
id,
|
||||
runtime: InstanceRuntime::Idle,
|
||||
}));
|
||||
}
|
||||
AppCommand::AskAgent(text) => self.script_chat(text),
|
||||
AppCommand::InstallVersion(version) => self.script_install(version),
|
||||
AppCommand::SetYolo(enabled) => self.emit(AppEvent::Toast(Toast {
|
||||
id: 0,
|
||||
kind: ToastKind::Info,
|
||||
text: if enabled {
|
||||
"YOLO 已开启(审计照记)"
|
||||
} else {
|
||||
"YOLO 已关闭"
|
||||
}
|
||||
.to_string(),
|
||||
remaining_ms: 0,
|
||||
})),
|
||||
AppCommand::ListVersions(category) => {
|
||||
self.emit(AppEvent::Core(CoreEvent::VersionListChanged(
|
||||
crate::mock_data::mock_versions_for(category),
|
||||
)));
|
||||
}
|
||||
AppCommand::OpenLogSession(id) => {
|
||||
// P0:换会话 = 换一批假日志行 + 一条诊断结论(日志页诊断卡片可见)
|
||||
self.emit(AppEvent::Core(CoreEvent::LogLinesChanged(mock_log_lines())));
|
||||
self.emit(AppEvent::Core(CoreEvent::DiagnosisReady(
|
||||
crate::mock_data::mock_diagnosis(id),
|
||||
)));
|
||||
}
|
||||
AppCommand::RefreshInstances
|
||||
| AppCommand::RefreshLogSessions
|
||||
| AppCommand::StopAgent => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self, elapsed: Duration) {
|
||||
self.step_launch(elapsed);
|
||||
self.step_chat(elapsed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::MockBackend;
|
||||
use crate::dto::{AgentEvent, AppCommand, AppEvent, Backend, CoreEvent, InstanceRuntime};
|
||||
|
||||
#[test]
|
||||
fn seeds_instances_and_versions() {
|
||||
let mut backend = MockBackend::new();
|
||||
let events = backend.drain_events();
|
||||
assert_eq!(events.len(), 4);
|
||||
assert!(events
|
||||
.iter()
|
||||
.all(|event| matches!(event, AppEvent::Core(_))));
|
||||
assert!(backend.drain_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launching_emits_progress_then_running() {
|
||||
let mut backend = MockBackend::new();
|
||||
backend.drain_events();
|
||||
backend.dispatch(AppCommand::LaunchInstance("survival".to_string()));
|
||||
|
||||
let first = backend.drain_events();
|
||||
assert!(matches!(
|
||||
first[0],
|
||||
AppEvent::Core(CoreEvent::InstanceRuntimeChanged { .. })
|
||||
));
|
||||
|
||||
backend.tick(std::time::Duration::from_millis(1_600));
|
||||
let verify = backend.drain_events();
|
||||
match &verify[0] {
|
||||
AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
runtime: InstanceRuntime::Busy { stage, .. },
|
||||
..
|
||||
}) => assert_eq!(*stage, crate::dto::LaunchStage::Verify),
|
||||
other => panic!("unexpected event: {other:?}"),
|
||||
}
|
||||
|
||||
backend.tick(std::time::Duration::from_millis(2_000));
|
||||
let done = backend.drain_events();
|
||||
assert!(done.iter().any(|event| matches!(
|
||||
event,
|
||||
AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
runtime: InstanceRuntime::Running { .. },
|
||||
..
|
||||
})
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_cancels_the_launch_script() {
|
||||
let mut backend = MockBackend::new();
|
||||
backend.drain_events();
|
||||
backend.dispatch(AppCommand::LaunchInstance("a".to_string()));
|
||||
backend.drain_events();
|
||||
|
||||
backend.dispatch(AppCommand::StopInstance("a".to_string()));
|
||||
let events = backend.drain_events();
|
||||
assert!(matches!(
|
||||
events[0],
|
||||
AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
runtime: InstanceRuntime::Idle,
|
||||
..
|
||||
})
|
||||
));
|
||||
|
||||
// 脚本已取消:再推进时间也不会再产出事件
|
||||
backend.tick(std::time::Duration::from_millis(5_000));
|
||||
assert!(backend.drain_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asking_the_agent_streams_and_finishes() {
|
||||
let mut backend = MockBackend::new();
|
||||
backend.drain_events();
|
||||
backend.dispatch(AppCommand::AskAgent("装哪个版本".to_string()));
|
||||
|
||||
let start = backend.drain_events();
|
||||
assert_eq!(start.len(), 2);
|
||||
|
||||
let mut deltas = 0;
|
||||
for _ in 0..6 {
|
||||
backend.tick(std::time::Duration::from_millis(400));
|
||||
let events = backend.drain_events();
|
||||
deltas += events
|
||||
.iter()
|
||||
.filter(|event| matches!(event, AppEvent::Agent(AgentEvent::MessageDelta { .. })))
|
||||
.count();
|
||||
}
|
||||
assert_eq!(deltas, 3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
//! P0 假数据:实例 / 版本 / 日志 / 诊断 / 工具调用样例。
|
||||
//!
|
||||
//! 只被 [`crate::mock`] 与阶段 B 的 main.rs 使用;真实后端接入后整文件可删。
|
||||
|
||||
use crate::dto::{
|
||||
AncientKind, ChatMessage, ChatRole, Diagnosis, DiagnosisReport, InstanceRuntime,
|
||||
InstanceSummary, LoaderInfo, LoaderKind, LogLevel, LogLine, LogOutcome, LogSession, SessionId,
|
||||
ToolCallView, VersionCategory, VersionKind, VersionSummary,
|
||||
};
|
||||
|
||||
/// P0 演示实例:覆盖空闲 / 失败两种磁贴状态(运行中由启动脚本产生)。
|
||||
pub fn mock_instances() -> Vec<InstanceSummary> {
|
||||
vec![
|
||||
InstanceSummary {
|
||||
id: "survival".to_string(),
|
||||
name: "生存整合包".to_string(),
|
||||
mc_version: "1.20.4".to_string(),
|
||||
loader: LoaderInfo {
|
||||
kind: LoaderKind::Fabric,
|
||||
version: "0.16.5".to_string(),
|
||||
},
|
||||
last_played: Some("2026-10-29T19:22:00Z".to_string()),
|
||||
runtime: InstanceRuntime::Idle,
|
||||
icon: None,
|
||||
},
|
||||
InstanceSummary {
|
||||
id: "vanilla-latest".to_string(),
|
||||
name: "原版最新".to_string(),
|
||||
mc_version: "1.21.9".to_string(),
|
||||
loader: LoaderInfo {
|
||||
kind: LoaderKind::Vanilla,
|
||||
version: String::new(),
|
||||
},
|
||||
last_played: Some("2026-10-28T21:03:00Z".to_string()),
|
||||
runtime: InstanceRuntime::Idle,
|
||||
icon: None,
|
||||
},
|
||||
InstanceSummary {
|
||||
id: "ancient-1.7.10".to_string(),
|
||||
name: "远古 1.7.10".to_string(),
|
||||
mc_version: "1.7.10".to_string(),
|
||||
loader: LoaderInfo {
|
||||
kind: LoaderKind::Forge,
|
||||
version: "10.13.4.1614".to_string(),
|
||||
},
|
||||
last_played: None,
|
||||
runtime: InstanceRuntime::Idle,
|
||||
icon: None,
|
||||
},
|
||||
InstanceSummary {
|
||||
id: "modded-dev".to_string(),
|
||||
name: "开发测试".to_string(),
|
||||
mc_version: "1.21.1".to_string(),
|
||||
loader: LoaderInfo {
|
||||
kind: LoaderKind::NeoForge,
|
||||
version: "21.1.72".to_string(),
|
||||
},
|
||||
last_played: Some("2026-10-27T12:40:00Z".to_string()),
|
||||
runtime: InstanceRuntime::Failed {
|
||||
reason: "exit0 静默失败".to_string(),
|
||||
},
|
||||
icon: None,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// P0 演示版本列表(含远古版三子类,验证分类侧栏与警示徽标)。
|
||||
pub fn mock_versions() -> Vec<VersionSummary> {
|
||||
fn row(id: &str, kind: VersionKind, released: &str, installed: bool) -> VersionSummary {
|
||||
VersionSummary {
|
||||
id: id.to_string(),
|
||||
kind,
|
||||
released: released.to_string(),
|
||||
installed,
|
||||
}
|
||||
}
|
||||
vec![
|
||||
row("1.21.9", VersionKind::Release, "2026-09-20", false),
|
||||
row("1.21.8", VersionKind::Release, "2026-07-11", true),
|
||||
row("1.20.4", VersionKind::Release, "2023-12-07", true),
|
||||
row("1.21.9-pre3", VersionKind::Snapshot, "2026-09-01", false),
|
||||
row(
|
||||
"rd-132211",
|
||||
VersionKind::Ancient(AncientKind::Classic),
|
||||
"2009-05-13",
|
||||
false,
|
||||
),
|
||||
row(
|
||||
"a1.2.6",
|
||||
VersionKind::Ancient(AncientKind::OldAlpha),
|
||||
"2010-08-11",
|
||||
false,
|
||||
),
|
||||
row(
|
||||
"b1.7.3",
|
||||
VersionKind::Ancient(AncientKind::OldBeta),
|
||||
"2011-07-08",
|
||||
false,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// 日志会话样例(✓ / ✗ / ⚠ 三种结局各一条)。
|
||||
pub fn mock_log_sessions() -> Vec<LogSession> {
|
||||
vec![
|
||||
LogSession {
|
||||
id: "s-1029-1922".to_string(),
|
||||
instance: "生存整合包".to_string(),
|
||||
when: "10-29 19:22".to_string(),
|
||||
outcome: LogOutcome::Ok,
|
||||
duration_secs: 3_780,
|
||||
},
|
||||
LogSession {
|
||||
id: "s-1029-1840".to_string(),
|
||||
instance: "开发测试".to_string(),
|
||||
when: "10-29 18:40".to_string(),
|
||||
outcome: LogOutcome::Crashed,
|
||||
duration_secs: 62,
|
||||
},
|
||||
LogSession {
|
||||
id: "s-1029-1755".to_string(),
|
||||
instance: "原版最新".to_string(),
|
||||
when: "10-29 17:55".to_string(),
|
||||
outcome: LogOutcome::SilentFail,
|
||||
duration_secs: 8,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// 日志行样例(含一条 ERROR 供高亮验证)。
|
||||
pub fn mock_log_lines() -> Vec<LogLine> {
|
||||
fn line(text: &str, level: LogLevel) -> LogLine {
|
||||
LogLine {
|
||||
text: text.to_string(),
|
||||
level,
|
||||
}
|
||||
}
|
||||
vec![
|
||||
line(
|
||||
"[19:22:01] [main/INFO] Launching Minecraft 1.20.4",
|
||||
LogLevel::Info,
|
||||
),
|
||||
line("[19:22:02] [main/INFO] Loading 42 mods", LogLevel::Info),
|
||||
line(
|
||||
"[19:22:03] [Render thread/WARN] GL vendor: unknown",
|
||||
LogLevel::Warn,
|
||||
),
|
||||
line(
|
||||
"[19:22:05] [Render thread/ERROR] OpenGL 2.1 not supported",
|
||||
LogLevel::Error,
|
||||
),
|
||||
line("[19:22:05] [main/INFO] Stopping!", LogLevel::Info),
|
||||
]
|
||||
}
|
||||
|
||||
/// 崩溃诊断样例(验证日志页诊断卡片 + 「让 AI 详解」入口)。
|
||||
pub fn mock_diagnosis(session: SessionId) -> DiagnosisReport {
|
||||
DiagnosisReport {
|
||||
session,
|
||||
diagnosis: Diagnosis {
|
||||
rule: "gpu.driver_old".to_string(),
|
||||
title: "显卡驱动过旧(OpenGL 版本不足)".to_string(),
|
||||
confidence: 92,
|
||||
hint: "升级显卡驱动,或在启动参数里改用软件渲染".to_string(),
|
||||
fix: Some("switch_software_renderer".to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 工具调用条目样例(AI 面板静态填充用)。
|
||||
pub fn mock_tool_message() -> ChatMessage {
|
||||
ChatMessage {
|
||||
role: ChatRole::Tool,
|
||||
text: "读到 128 行,无 ERROR".to_string(),
|
||||
tool: Some(ToolCallView {
|
||||
name: "read_game_log".to_string(),
|
||||
ok: true,
|
||||
summary: "读到 128 行,无 ERROR".to_string(),
|
||||
}),
|
||||
streaming: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 分类 → 该分类下的假版本(下载页切换分类时用)。
|
||||
pub fn mock_versions_for(category: VersionCategory) -> Vec<VersionSummary> {
|
||||
mock_versions()
|
||||
.into_iter()
|
||||
.filter(|version| match category {
|
||||
VersionCategory::Release => version.kind == VersionKind::Release,
|
||||
VersionCategory::Snapshot => version.kind == VersionKind::Snapshot,
|
||||
VersionCategory::Ancient(kind) => version.kind == VersionKind::Ancient(kind),
|
||||
VersionCategory::Modpack | VersionCategory::Mod => false,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::dto::{AncientKind, VersionCategory, VersionKind};
|
||||
use crate::mock_data::{mock_instances, mock_versions_for};
|
||||
|
||||
#[test]
|
||||
fn mock_instances_cover_the_tile_states() {
|
||||
let instances = mock_instances();
|
||||
assert_eq!(instances.len(), 4);
|
||||
assert!(instances.iter().any(|instance| matches!(
|
||||
instance.runtime,
|
||||
crate::dto::InstanceRuntime::Failed { .. }
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_are_filtered_by_category() {
|
||||
let release = mock_versions_for(VersionCategory::Release);
|
||||
assert!(release
|
||||
.iter()
|
||||
.all(|version| version.kind == VersionKind::Release));
|
||||
assert_eq!(release.len(), 3);
|
||||
|
||||
let classic = mock_versions_for(VersionCategory::Ancient(AncientKind::Classic));
|
||||
assert_eq!(classic.len(), 1);
|
||||
assert_eq!(classic[0].id, "rd-132211");
|
||||
|
||||
assert!(mock_versions_for(VersionCategory::Mod).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! 极简 PNG 编码器(只做「无压缩 stored deflate」),给截图验收用。
|
||||
//!
|
||||
//! 为什么不引 `image` / `png` crate:截屏只是开发期验收工具(`--screenshot`),
|
||||
//! 为它加一个依赖违反「新依赖过 deny.toml 白名单」的成本收益。PNG 规范里 zlib 流允许
|
||||
//! **stored(未压缩)块**,于是我们只需要 CRC32 + Adler32 两个校验和就能产出合法 PNG——
|
||||
//! 文件大一些,但任何看图工具都认。
|
||||
//!
|
||||
//! 输出:8bit RGBA(color type 6),逐行 filter=0(None)。
|
||||
|
||||
use slint::{Rgba8Pixel, SharedPixelBuffer};
|
||||
|
||||
/// 把 RGBA8 像素缓冲写成 PNG 字节流。
|
||||
#[must_use]
|
||||
pub fn encode_rgba8(buffer: &SharedPixelBuffer<Rgba8Pixel>) -> Vec<u8> {
|
||||
let width = buffer.width();
|
||||
let height = buffer.height();
|
||||
let pixels = buffer.as_slice();
|
||||
|
||||
// 原始扫描线:每行前面加一个 filter 字节 0
|
||||
let stride = width as usize * 4;
|
||||
let mut raw = Vec::with_capacity((stride + 1) * height as usize);
|
||||
for y in 0..height as usize {
|
||||
raw.push(0u8);
|
||||
for x in 0..width as usize {
|
||||
let pixel = pixels[y * width as usize + x];
|
||||
raw.extend_from_slice(&[pixel.r, pixel.g, pixel.b, pixel.a]);
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
let mut ihdr = Vec::with_capacity(13);
|
||||
ihdr.extend_from_slice(&width.to_be_bytes());
|
||||
ihdr.extend_from_slice(&height.to_be_bytes());
|
||||
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 位深 8、RGBA、deflate、无交错
|
||||
push_chunk(&mut out, b"IHDR", &ihdr);
|
||||
push_chunk(&mut out, b"IDAT", &zlib_stored(&raw));
|
||||
push_chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
fn push_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(data);
|
||||
let mut crc_input = Vec::with_capacity(4 + data.len());
|
||||
crc_input.extend_from_slice(kind);
|
||||
crc_input.extend_from_slice(data);
|
||||
out.extend_from_slice(&crc32(&crc_input).to_be_bytes());
|
||||
}
|
||||
|
||||
/// zlib 容器 + 全 stored deflate 块(每块上限 65535 字节)。
|
||||
fn zlib_stored(raw: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(raw.len() + raw.len() / 65_535 * 5 + 16);
|
||||
out.extend_from_slice(&[0x78, 0x01]); // CMF/FLG:deflate、32K 窗口、无字典、最快
|
||||
let mut offset = 0usize;
|
||||
while offset < raw.len() {
|
||||
let len = (raw.len() - offset).min(65_535);
|
||||
let last = offset + len >= raw.len();
|
||||
out.push(u8::from(last)); // BFINAL + BTYPE=00
|
||||
let len_u16 = len as u16;
|
||||
out.extend_from_slice(&len_u16.to_le_bytes());
|
||||
out.extend_from_slice(&(!len_u16).to_le_bytes());
|
||||
out.extend_from_slice(&raw[offset..offset + len]);
|
||||
offset += len;
|
||||
}
|
||||
if raw.is_empty() {
|
||||
out.push(1);
|
||||
out.extend_from_slice(&[0, 0, 0xff, 0xff]);
|
||||
}
|
||||
out.extend_from_slice(&adler32(raw).to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = 0xffff_ffffu32;
|
||||
for byte in data {
|
||||
crc ^= u32::from(*byte);
|
||||
for _ in 0..8 {
|
||||
let mask = (crc & 1).wrapping_neg();
|
||||
crc = (crc >> 1) ^ (0xedb8_8320 & mask);
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
fn adler32(data: &[u8]) -> u32 {
|
||||
let mut a: u32 = 1;
|
||||
let mut b: u32 = 0;
|
||||
for byte in data {
|
||||
a = (a + u32::from(*byte)) % 65_521;
|
||||
b = (b + a) % 65_521;
|
||||
}
|
||||
(b << 16) | a
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pixel(r: u8, g: u8, b: u8) -> Rgba8Pixel {
|
||||
Rgba8Pixel { r, g, b, a: 255 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_and_chunks_are_well_formed() {
|
||||
let mut buffer = SharedPixelBuffer::<Rgba8Pixel>::new(3, 2);
|
||||
buffer.make_mut_slice().fill(pixel(1, 2, 3));
|
||||
let bytes = encode_rgba8(&buffer);
|
||||
assert_eq!(
|
||||
&bytes[..8],
|
||||
&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
);
|
||||
// IHDR:宽 3 高 2、8bit、RGBA(6)
|
||||
assert_eq!(&bytes[8..12], &13u32.to_be_bytes());
|
||||
assert_eq!(&bytes[12..16], b"IHDR");
|
||||
assert_eq!(&bytes[16..20], &3u32.to_be_bytes());
|
||||
assert_eq!(&bytes[20..24], &2u32.to_be_bytes());
|
||||
assert_eq!(bytes[24], 8);
|
||||
assert_eq!(bytes[25], 6);
|
||||
// 结尾是 IEND 块
|
||||
assert_eq!(&bytes[bytes.len() - 8..bytes.len() - 4], b"IEND");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksums_match_known_vectors() {
|
||||
// CRC32("IEND") 是公认值 0xAE426082(写进 IEND 块尾)
|
||||
assert_eq!(crc32(b"IEND"), 0xae42_6082);
|
||||
// Adler32("Wikipedia") = 0x11E60398
|
||||
assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_buffer_still_produces_valid_stream() {
|
||||
let buffer = SharedPixelBuffer::<Rgba8Pixel>::new(0, 0);
|
||||
let bytes = encode_rgba8(&buffer);
|
||||
assert!(bytes.windows(4).any(|window| window == b"IDAT"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! UI 偏好项与持久化键登记(导航折叠、AI 栏折叠、磁贴尺寸、视图、主题三态与外观四件、下载分类)。
|
||||
//!
|
||||
//! 偏好不自己写盘:core::setting 的 schema 按 [`keys::ALL`] 登记这些键,
|
||||
//! app 启动时读一次、变更时写回(跨模块约定见 `DevDocs/SubAgentsTalk/app-DTO通道约定.md`)。
|
||||
//! 落盘实现是 [`crate::settings_bridge`](同一份 `config/launcher.json`,与 `ull config set` 同源),
|
||||
//! 主题三态 + `appearance.*` 高级键已接(M41);其余 UI 偏好键仍只在内存里(后续 mission 接)。
|
||||
|
||||
/// 背景图填充模式(09 §101)。直接复用 core 的枚举:取值与落盘词表只有一处真相。
|
||||
pub use unlucky_core::setting::appearance::BgFill;
|
||||
|
||||
use crate::dto::VersionCategory;
|
||||
|
||||
/// 预设强调色板(09 §104)。**必须**与 `ui/pages/settings-appearance.slint` 的 `swatch-colors`
|
||||
/// 同序同值:Slint 侧只回传索引,十六进制串由这张表给出(一处真相)。
|
||||
pub const ACCENT_PRESETS: [&str; 8] = [
|
||||
"#0078D4", "#0F6CBD", "#107C10", "#9D5D00", "#C42B1C", "#8764B8", "#C239B3", "#00B7C3",
|
||||
];
|
||||
|
||||
/// 磁贴尺寸(Q24-3:小 6 列 / 中 4 列 / 大 3 列)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum TileSize {
|
||||
/// 小:6 列,只留图标/名字/启动键
|
||||
Small,
|
||||
/// 中:4 列(D16 默认)
|
||||
#[default]
|
||||
Medium,
|
||||
/// 大:3 列,显示完整徽标与最后游玩时间
|
||||
Large,
|
||||
}
|
||||
|
||||
impl TileSize {
|
||||
/// 该尺寸对应的网格列数。
|
||||
pub fn columns(self) -> usize {
|
||||
match self {
|
||||
Self::Small => 6,
|
||||
Self::Medium => 4,
|
||||
Self::Large => 3,
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置页/实例页分段控件的文案。
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Small => "小",
|
||||
Self::Medium => "中",
|
||||
Self::Large => "大",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 实例页视图模式。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum InstanceView {
|
||||
/// 磁贴网格(默认)
|
||||
#[default]
|
||||
Tiles,
|
||||
/// 紧凑列表
|
||||
List,
|
||||
}
|
||||
|
||||
/// 主题三态(D17,P0 交付):`appearance.theme_mode ∈ {light, dark, auto}`,出厂 auto。
|
||||
///
|
||||
/// auto 由 `theme/tokens.slint` 读 Slint 原生 `Palette.color-scheme` 跟随系统(后端随 OS 热更);
|
||||
/// light/dark 由 `Theme.theme-mode` 钉死**自绘体系**;std-widgets 内部件(ListView 滚动条 /
|
||||
/// ProgressIndicator / AboutSlint)目前仍跟随系统色,`Palette.color-scheme` 的钉死留 P1。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum ThemeMode {
|
||||
/// 跟随系统(默认)
|
||||
#[default]
|
||||
Auto,
|
||||
/// 强制浅色
|
||||
Light,
|
||||
/// 强制深色
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl ThemeMode {
|
||||
/// 落盘取值(`appearance.theme_mode`):`auto` / `light` / `dark`。
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Auto => "auto",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
|
||||
/// 从落盘取值解析;未知值按 `auto` 兜底(配置被手改坏也不崩)。
|
||||
pub fn from_key_value(value: &str) -> Self {
|
||||
match value {
|
||||
"light" => Self::Light,
|
||||
"dark" => Self::Dark,
|
||||
_ => Self::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 09 §101-104「外观(高级)」四件的取值快照(出厂全部关闭)。
|
||||
///
|
||||
/// 与 `unlucky_core::setting::appearance::Appearance` 一一对应,但字段类型是 UI 侧好用的
|
||||
/// `f32`/`String`;落盘由 [`crate::settings_bridge`] 转成 schema 键。
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct AppearancePrefs {
|
||||
/// 背景图总开关
|
||||
pub bg_image_enabled: bool,
|
||||
/// 背景图路径(PNG;空 = 未设置)
|
||||
pub bg_image: String,
|
||||
/// 填充模式
|
||||
pub bg_fill: BgFill,
|
||||
/// 暗化层强度 0.0~0.9
|
||||
pub bg_dim: f32,
|
||||
/// 面板半透明度 0.4~1.0
|
||||
pub panel_alpha: f32,
|
||||
/// 玻璃拟态卡片
|
||||
pub glass: bool,
|
||||
/// 自定义强调色 `#RRGGBB`;空 = 出厂 [#0078D4]
|
||||
pub accent_color: String,
|
||||
}
|
||||
|
||||
impl AppearancePrefs {
|
||||
/// 出厂态:Metro 纯色,四个高级特性全关。
|
||||
pub fn factory() -> Self {
|
||||
Self {
|
||||
bg_image_enabled: false,
|
||||
bg_image: String::new(),
|
||||
bg_fill: BgFill::Cover,
|
||||
bg_dim: 0.35,
|
||||
panel_alpha: 1.0,
|
||||
glass: false,
|
||||
accent_color: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 背景图是否真的生效(开关打开且路径非空)。
|
||||
pub fn bg_active(&self) -> bool {
|
||||
self.bg_image_enabled && !self.bg_image.trim().is_empty()
|
||||
}
|
||||
|
||||
/// 规范化写入强调色:`#RRGGBB` 才接受(空串 = 恢复出厂)。
|
||||
///
|
||||
/// 返回 `false` 表示输入不合法(调用方据此亮设置页的 warn 行,不改现状)。
|
||||
pub fn set_accent(&mut self, text: &str) -> bool {
|
||||
let trimmed = text.trim();
|
||||
if trimmed.is_empty() {
|
||||
self.accent_color.clear();
|
||||
return true;
|
||||
}
|
||||
match unlucky_core::setting::appearance::normalize_hex(trimmed) {
|
||||
Some(hex) => {
|
||||
self.accent_color = hex;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 用预设色板第 `index` 个颜色(越界忽略)。
|
||||
pub fn set_accent_preset(&mut self, index: usize) -> bool {
|
||||
match ACCENT_PRESETS.get(index) {
|
||||
Some(hex) => self.set_accent(hex),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 需要跨会话记忆的 UI 偏好。
|
||||
///
|
||||
/// 注意:`Eq` 不成立([`AppearancePrefs`] 带 `f32` 滑条值),用到的地方按 `PartialEq` 比。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UiPrefs {
|
||||
/// 左侧导航栏折叠成图标条
|
||||
pub nav_collapsed: bool,
|
||||
/// 右侧 AI 栏折叠成 icon 轨
|
||||
pub ai_collapsed: bool,
|
||||
/// 磁贴尺寸
|
||||
pub tile_size: TileSize,
|
||||
/// 实例页视图
|
||||
pub instance_view: InstanceView,
|
||||
/// 主题模式
|
||||
pub theme: ThemeMode,
|
||||
/// 外观(高级)四件(09 §101-104)
|
||||
pub appearance: AppearancePrefs,
|
||||
/// 下载页选中的分类
|
||||
pub download_category: VersionCategory,
|
||||
}
|
||||
|
||||
impl Default for UiPrefs {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
nav_collapsed: false,
|
||||
ai_collapsed: false,
|
||||
// D16 默认中磁贴(4 列)
|
||||
tile_size: TileSize::Medium,
|
||||
instance_view: InstanceView::Tiles,
|
||||
theme: ThemeMode::Auto,
|
||||
appearance: AppearancePrefs::factory(),
|
||||
download_category: VersionCategory::Release,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 持久化键名登记(core::setting schema 按此注册;改名等于迁移,慎动)。
|
||||
pub mod keys {
|
||||
/// 导航栏折叠
|
||||
pub const NAV_COLLAPSED: &str = "ui.nav.collapsed";
|
||||
/// AI 栏折叠
|
||||
pub const AI_COLLAPSED: &str = "ui.ai.collapsed";
|
||||
/// 磁贴尺寸
|
||||
pub const TILE_SIZE: &str = "ui.instances.tile_size";
|
||||
/// 实例页视图(磁贴/列表)
|
||||
pub const INSTANCE_VIEW: &str = "ui.instances.view";
|
||||
/// 主题三态(D17;与设置页「外观」分组同名,取值见 [`super::ThemeMode::as_str`])
|
||||
pub const THEME_MODE: &str = "appearance.theme_mode";
|
||||
/// 背景图开关(09 §101)
|
||||
pub const BG_IMAGE_ENABLED: &str = "appearance.bg_image_enabled";
|
||||
/// 背景图路径
|
||||
pub const BG_IMAGE: &str = "appearance.bg_image";
|
||||
/// 背景图填充模式
|
||||
pub const BG_FILL: &str = "appearance.bg_fill";
|
||||
/// 暗化层强度
|
||||
pub const BG_DIM: &str = "appearance.bg_dim";
|
||||
/// 面板半透明度(09 §102)
|
||||
pub const PANEL_ALPHA: &str = "appearance.panel_alpha";
|
||||
/// 玻璃拟态卡片(09 §103)
|
||||
pub const GLASS: &str = "appearance.glass";
|
||||
/// 自定义强调色(09 §104)
|
||||
pub const ACCENT_COLOR: &str = "appearance.accent_color";
|
||||
/// 下载页分类
|
||||
pub const DOWNLOAD_CATEGORY: &str = "ui.download.category";
|
||||
|
||||
/// 本模块登记的全部键(自检/迁移用)。
|
||||
pub const ALL: [&str; 13] = [
|
||||
NAV_COLLAPSED,
|
||||
AI_COLLAPSED,
|
||||
TILE_SIZE,
|
||||
INSTANCE_VIEW,
|
||||
THEME_MODE,
|
||||
BG_IMAGE_ENABLED,
|
||||
BG_IMAGE,
|
||||
BG_FILL,
|
||||
BG_DIM,
|
||||
PANEL_ALPHA,
|
||||
GLASS,
|
||||
ACCENT_COLOR,
|
||||
DOWNLOAD_CATEGORY,
|
||||
];
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{keys, InstanceView, ThemeMode, TileSize, UiPrefs};
|
||||
|
||||
#[test]
|
||||
fn defaults_match_d16() {
|
||||
let prefs = UiPrefs::default();
|
||||
assert_eq!(prefs.tile_size, TileSize::Medium);
|
||||
assert_eq!(prefs.tile_size.columns(), 4);
|
||||
assert_eq!(prefs.instance_view, InstanceView::Tiles);
|
||||
assert_eq!(prefs.theme, ThemeMode::Auto);
|
||||
assert_eq!(prefs.theme.as_str(), "auto");
|
||||
assert!(!prefs.nav_collapsed);
|
||||
assert!(!prefs.ai_collapsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_size_columns_follow_q24() {
|
||||
assert_eq!(TileSize::Small.columns(), 6);
|
||||
assert_eq!(TileSize::Medium.columns(), 4);
|
||||
assert_eq!(TileSize::Large.columns(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_mode_round_trips_through_key_values() {
|
||||
for mode in [ThemeMode::Auto, ThemeMode::Light, ThemeMode::Dark] {
|
||||
assert_eq!(ThemeMode::from_key_value(mode.as_str()), mode);
|
||||
}
|
||||
// 坏值兜底
|
||||
assert_eq!(ThemeMode::from_key_value("solarized"), ThemeMode::Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pref_keys_are_unique() {
|
||||
let mut keys = keys::ALL.to_vec();
|
||||
let total = keys.len();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
assert_eq!(keys.len(), total);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! 页面路由与 AI 助手栏形态(09 §1 / D16)。
|
||||
//!
|
||||
//! 栈语义抄 HMCL 的导航栈:**顶层页面互相替换**(实例/下载/日志/设置),
|
||||
//! 子页面(实例详情、AI 独立页)压栈,`back()` 逐层回退。
|
||||
//! 本模块刻意不依赖 Slint 类型,便于单元测试;UI 侧枚举映射在 main.rs 的转换层做。
|
||||
|
||||
use crate::dto::InstanceId;
|
||||
|
||||
/// 一级导航项(左侧导航栏高亮单位)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NavSection {
|
||||
/// 实例
|
||||
Instances,
|
||||
/// 下载
|
||||
Download,
|
||||
/// 日志
|
||||
Logs,
|
||||
/// 设置
|
||||
Settings,
|
||||
}
|
||||
|
||||
/// 页面路由。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Route {
|
||||
/// G1 实例页(主页)
|
||||
Instances,
|
||||
/// G2 下载页
|
||||
Download,
|
||||
/// G3 日志页
|
||||
Logs,
|
||||
/// G6 设置页
|
||||
Settings,
|
||||
/// 实例详情(G4):从磁贴点进来,返回时回到实例页
|
||||
Detail(InstanceId),
|
||||
/// AI 助手独立页(D16 双形态之一)
|
||||
Agent,
|
||||
}
|
||||
|
||||
impl Route {
|
||||
/// 是否是一级导航页(互相替换,不进栈)。
|
||||
pub fn is_top_level(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Instances | Self::Download | Self::Logs | Self::Settings
|
||||
)
|
||||
}
|
||||
|
||||
/// 该路由高亮哪个导航项(None = 没有导航项高亮,如 AI 独立页)。
|
||||
pub fn nav(&self) -> Option<NavSection> {
|
||||
match self {
|
||||
Self::Instances | Self::Detail(_) => Some(NavSection::Instances),
|
||||
Self::Download => Some(NavSection::Download),
|
||||
Self::Logs => Some(NavSection::Logs),
|
||||
Self::Settings => Some(NavSection::Settings),
|
||||
Self::Agent => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// AI 栏形态:右侧栏 / 独立全宽页(两形态共享同一份会话状态)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AiPanelMode {
|
||||
/// 右侧常驻栏
|
||||
Docked,
|
||||
/// 拆出的独立全宽页
|
||||
Page,
|
||||
}
|
||||
|
||||
/// 导航栈。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Router {
|
||||
stack: Vec<Route>,
|
||||
}
|
||||
|
||||
impl Default for Router {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Router {
|
||||
/// 启动时停在实例页。
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
stack: vec![Route::Instances],
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前页面。
|
||||
pub fn route(&self) -> &Route {
|
||||
// 栈不变量:构造后永远非空(navigate/back 都不允许清空)
|
||||
self.stack.last().expect("router stack is never empty")
|
||||
}
|
||||
|
||||
/// 栈深度(1 表示没有可回退的子页面)。
|
||||
pub fn depth(&self) -> usize {
|
||||
self.stack.len()
|
||||
}
|
||||
|
||||
/// 是否能回退。
|
||||
pub fn can_go_back(&self) -> bool {
|
||||
self.stack.len() > 1
|
||||
}
|
||||
|
||||
/// 跳转到某路由:一级页替换整栈,子页面压栈(重复目标不重复压栈)。
|
||||
pub fn navigate(&mut self, route: Route) {
|
||||
if route.is_top_level() {
|
||||
self.stack.clear();
|
||||
self.stack.push(route);
|
||||
return;
|
||||
}
|
||||
if self.stack.last() == Some(&route) {
|
||||
return;
|
||||
}
|
||||
self.stack.push(route);
|
||||
}
|
||||
|
||||
/// 回退一层;已在根页面时返回 `false`。
|
||||
pub fn back(&mut self) -> bool {
|
||||
if self.stack.len() <= 1 {
|
||||
return false;
|
||||
}
|
||||
self.stack.pop();
|
||||
true
|
||||
}
|
||||
|
||||
/// 当前 AI 栏形态(栈顶是 Agent 页即为独立页形态)。
|
||||
pub fn ai_mode(&self) -> AiPanelMode {
|
||||
if self.route() == &Route::Agent {
|
||||
AiPanelMode::Page
|
||||
} else {
|
||||
AiPanelMode::Docked
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{AiPanelMode, NavSection, Route, Router};
|
||||
|
||||
#[test]
|
||||
fn top_level_navigation_replaces_the_stack() {
|
||||
let mut router = Router::new();
|
||||
router.navigate(Route::Detail("a".into()));
|
||||
assert_eq!(router.depth(), 2);
|
||||
|
||||
router.navigate(Route::Download);
|
||||
assert_eq!(router.depth(), 1);
|
||||
assert_eq!(router.route(), &Route::Download);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_pushes_and_back_pops_to_instances() {
|
||||
let mut router = Router::new();
|
||||
router.navigate(Route::Detail("survival".into()));
|
||||
assert!(router.can_go_back());
|
||||
assert_eq!(router.route().nav(), Some(NavSection::Instances));
|
||||
|
||||
assert!(router.back());
|
||||
assert_eq!(router.route(), &Route::Instances);
|
||||
assert!(!router.back());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_page_switches_ai_panel_mode() {
|
||||
let mut router = Router::new();
|
||||
assert_eq!(router.ai_mode(), AiPanelMode::Docked);
|
||||
|
||||
router.navigate(Route::Agent);
|
||||
assert_eq!(router.ai_mode(), AiPanelMode::Page);
|
||||
|
||||
router.back();
|
||||
assert_eq!(router.ai_mode(), AiPanelMode::Docked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigating_to_the_same_sub_route_does_not_grow_the_stack() {
|
||||
let mut router = Router::new();
|
||||
router.navigate(Route::Agent);
|
||||
router.navigate(Route::Agent);
|
||||
assert_eq!(router.depth(), 2);
|
||||
assert_eq!(router.route().nav(), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! 设置持久化桥:把 UI 偏好落到 `core::setting` 的 schema 文件里,并支持**外部热改热切**。
|
||||
//!
|
||||
//! 三条纪律(`DevDocs/SubAgentsTalk/app-DTO通道约定.md` §6 / AGENTS §6):
|
||||
//!
|
||||
//! 1. **不另立配置文件**:读写的就是 `ull config set/get` 与 AI `set_config` 用的那一份
|
||||
//! `<data root>/config/launcher.json`(`core::platform::data_dir` 解析数据根、`layout` 给路径);
|
||||
//! 2. **不自己拼 JSON**:一律过 `core::setting::store::SettingStore`(schema 校验 + 原子写);
|
||||
//! 3. **不 import 领域类型**:跨边界只看「键名 + 取值」,领域模型留在 core。
|
||||
//!
|
||||
//! 热切:文件 `mtime` 变了就整份重读(AI / CLI 改完下一拍即生效),见 [`SettingsBridge::reload_if_changed`]。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use unlucky_core::platform::data_dir::{DataDirRequest, DataMode, Resolver};
|
||||
use unlucky_core::platform::layout::LauncherLayout;
|
||||
use unlucky_core::platform::paths::Platform;
|
||||
use unlucky_core::setting::appearance::Appearance;
|
||||
use unlucky_core::setting::keys::launcher_schema;
|
||||
use unlucky_core::setting::store::SettingStore;
|
||||
|
||||
use crate::prefs::{AppearancePrefs, ThemeMode};
|
||||
|
||||
/// 数据根配置键(决定 `launcher.json` 落在哪个数据目录;与 CLI 的 `DATA_ROOT_KEYS` 同源同义)。
|
||||
const DATA_ROOT_KEYS: [&str; 4] = [
|
||||
"core.data_mode",
|
||||
"core.data_custom_root",
|
||||
"core.launcher_home",
|
||||
"core.game_home",
|
||||
];
|
||||
|
||||
/// 设置文件桥(一个进程一份)。
|
||||
#[derive(Debug)]
|
||||
pub struct SettingsBridge {
|
||||
/// `config/launcher.json`;`None` = 数据根解析不出来(内存态运行,不落盘)
|
||||
path: Option<PathBuf>,
|
||||
store: Option<SettingStore>,
|
||||
/// 上次读/写之后的文件 `mtime`(热切探测用)
|
||||
last_mtime: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl SettingsBridge {
|
||||
/// 按三模式数据根打开真实配置文件(启动时调用一次)。
|
||||
#[must_use]
|
||||
pub fn open() -> Self {
|
||||
match resolve_config_path() {
|
||||
Some(path) => Self::with_path(path),
|
||||
None => Self::memory_only(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 指定路径打开(测试与特殊数据根用)。
|
||||
#[must_use]
|
||||
pub fn with_path(path: impl Into<PathBuf>) -> Self {
|
||||
let path = path.into();
|
||||
let store = SettingStore::load(&path, launcher_schema());
|
||||
let last_mtime = mtime(&path);
|
||||
Self {
|
||||
path: Some(path),
|
||||
store: Some(store),
|
||||
last_mtime,
|
||||
}
|
||||
}
|
||||
|
||||
/// 不落盘(数据根解析失败 / 单测)。
|
||||
#[must_use]
|
||||
pub fn memory_only() -> Self {
|
||||
Self {
|
||||
path: None,
|
||||
store: None,
|
||||
last_mtime: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 配置文件路径(诊断/日志用)。
|
||||
#[must_use]
|
||||
pub fn path(&self) -> Option<&Path> {
|
||||
self.path.as_deref()
|
||||
}
|
||||
|
||||
/// 当前生效的外观配置与主题模式。
|
||||
#[must_use]
|
||||
pub fn load(&self) -> (AppearancePrefs, ThemeMode) {
|
||||
let Some(store) = &self.store else {
|
||||
return (AppearancePrefs::factory(), ThemeMode::Auto);
|
||||
};
|
||||
let appearance = Appearance::from_store(store);
|
||||
let theme = ThemeMode::from_key_value(&appearance.theme_mode);
|
||||
(
|
||||
AppearancePrefs {
|
||||
bg_image_enabled: appearance.bg_image_enabled,
|
||||
bg_image: appearance.bg_image,
|
||||
bg_fill: appearance.bg_fill,
|
||||
bg_dim: appearance.bg_dim as f32,
|
||||
panel_alpha: appearance.panel_alpha as f32,
|
||||
glass: appearance.glass,
|
||||
accent_color: appearance.accent_color,
|
||||
},
|
||||
theme,
|
||||
)
|
||||
}
|
||||
|
||||
/// 落盘(只写出现过的键;失败静默——配置写不进去不该把 UI 卡住,诊断走日志)。
|
||||
pub fn persist(&mut self, appearance: &AppearancePrefs, theme: ThemeMode) {
|
||||
let Some(store) = self.store.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let mut snapshot = Appearance::from_store(store);
|
||||
snapshot.theme_mode = theme.as_str().to_owned();
|
||||
snapshot.bg_image_enabled = appearance.bg_image_enabled;
|
||||
snapshot.bg_image = appearance.bg_image.clone();
|
||||
snapshot.bg_fill = appearance.bg_fill;
|
||||
snapshot.bg_dim = f64::from(appearance.bg_dim);
|
||||
snapshot.panel_alpha = f64::from(appearance.panel_alpha);
|
||||
snapshot.glass = appearance.glass;
|
||||
snapshot.accent_color = appearance.accent_color.clone();
|
||||
if snapshot.write(store).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = store.save();
|
||||
if let Some(path) = self.path() {
|
||||
self.last_mtime = mtime(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// 文件被外部(AI / `ull config set`)改过就重读;返回新的生效值。
|
||||
///
|
||||
/// `mtime` 采样不到(某些文件系统精度/权限)时返回 `None`,退化为「只在启动时读一次」。
|
||||
pub fn reload_if_changed(&mut self) -> Option<(AppearancePrefs, ThemeMode)> {
|
||||
let path = self.path.clone()?;
|
||||
let current = mtime(&path);
|
||||
if current.is_none() || current == self.last_mtime {
|
||||
return None;
|
||||
}
|
||||
self.last_mtime = current;
|
||||
let store = self.store.as_mut()?;
|
||||
store.reload();
|
||||
Some(self.load())
|
||||
}
|
||||
}
|
||||
|
||||
/// 数据根解析 → `config/launcher.json`。
|
||||
///
|
||||
/// 与 CLI 同一套语义:先读便携目录那份 `launcher.json` 的 `core.*`(数据根决定键),
|
||||
/// 再交 `Resolver` 解析(含 `redirect.json` 跟随)。任何一步失败都退回内存态。
|
||||
fn resolve_config_path() -> Option<PathBuf> {
|
||||
let exe_dir = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|path| path.parent().map(Path::to_path_buf));
|
||||
let exe_dir = exe_dir?;
|
||||
let request = request_from_portable(&exe_dir);
|
||||
let resolver = Resolver::new(Platform::current(), Some(exe_dir.clone()));
|
||||
match resolver.resolve_default(&request) {
|
||||
Ok(resolved) => Some(resolved.layout().launcher_config()),
|
||||
// 连 exe 目录都解析不了(极端情况):仍旧用便携落点,至少设置能存下来
|
||||
Err(_) => Some(LauncherLayout::new(exe_dir.join(".ULL")).launcher_config()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 便携目录那份 `launcher.json` → 三模式请求(只读 `core.*` 四个键)。
|
||||
fn request_from_portable(exe_dir: &Path) -> DataDirRequest {
|
||||
let mut request = DataDirRequest::default();
|
||||
let path = portable_config_path(exe_dir);
|
||||
if !path.is_file() {
|
||||
return request;
|
||||
}
|
||||
let store = SettingStore::load(&path, launcher_schema());
|
||||
let text = |key: &str| store.doc().effective_str(key).map(str::to_string);
|
||||
if let Some(mode) = text(DATA_ROOT_KEYS[0]).as_deref().and_then(DataMode::parse) {
|
||||
request.mode = mode;
|
||||
}
|
||||
if let Some(root) = text(DATA_ROOT_KEYS[1]) {
|
||||
request.custom_root = Some(PathBuf::from(root));
|
||||
}
|
||||
if let Some(home) = text(DATA_ROOT_KEYS[2]) {
|
||||
request.launcher_home = Some(PathBuf::from(home));
|
||||
}
|
||||
if let Some(home) = text(DATA_ROOT_KEYS[3]) {
|
||||
request.game_home = Some(PathBuf::from(home));
|
||||
}
|
||||
request
|
||||
}
|
||||
|
||||
/// `<exe 目录>/.ULL/config/launcher.json`。
|
||||
fn portable_config_path(exe_dir: &Path) -> PathBuf {
|
||||
LauncherLayout::new(exe_dir.join(".ULL")).launcher_config()
|
||||
}
|
||||
|
||||
fn mtime(path: &Path) -> Option<SystemTime> {
|
||||
std::fs::metadata(path).ok()?.modified().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use unlucky_core::setting::appearance::BgFill;
|
||||
|
||||
fn temp_config(label: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"ull-bridge-{label}-{}-{}",
|
||||
std::process::id(),
|
||||
line!()
|
||||
));
|
||||
std::fs::create_dir_all(dir.join("config")).expect("临时目录");
|
||||
let path = dir.join("config/launcher.json");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factory_defaults_when_file_missing() {
|
||||
let path = temp_config("factory");
|
||||
let bridge = SettingsBridge::with_path(&path);
|
||||
let (appearance, theme) = bridge.load();
|
||||
assert_eq!(appearance, AppearancePrefs::factory());
|
||||
assert_eq!(theme, ThemeMode::Auto);
|
||||
assert!(!path.exists(), "只读不写:缺文件不该被创建");
|
||||
std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_then_reload_round_trips() {
|
||||
let path = temp_config("roundtrip");
|
||||
let mut bridge = SettingsBridge::with_path(&path);
|
||||
let mut appearance = AppearancePrefs::factory();
|
||||
appearance.bg_image_enabled = true;
|
||||
appearance.bg_image = "D:/wall/p.png".to_owned();
|
||||
appearance.bg_fill = BgFill::Contain;
|
||||
appearance.bg_dim = 0.5;
|
||||
appearance.panel_alpha = 0.8;
|
||||
appearance.glass = true;
|
||||
assert!(appearance.set_accent("#0f6cbd"));
|
||||
bridge.persist(&appearance, ThemeMode::Dark);
|
||||
|
||||
let reloaded = SettingsBridge::with_path(&path);
|
||||
let (value, theme) = reloaded.load();
|
||||
assert_eq!(value, appearance);
|
||||
assert_eq!(theme, ThemeMode::Dark);
|
||||
std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_edit_is_picked_up_by_reload() {
|
||||
let path = temp_config("hotreload");
|
||||
let mut bridge = SettingsBridge::with_path(&path);
|
||||
// 先落一份(建立 mtime 基线)
|
||||
bridge.persist(&AppearancePrefs::factory(), ThemeMode::Light);
|
||||
assert!(bridge.reload_if_changed().is_none(), "自己写完不该报告变更");
|
||||
|
||||
// 模拟外部写入(AI / `ull config set`):改主题 + 打开背景图
|
||||
let mut external = SettingsBridge::with_path(&path);
|
||||
let mut appearance = AppearancePrefs::factory();
|
||||
appearance.bg_image_enabled = true;
|
||||
appearance.bg_image = "D:/wall/x.png".to_owned();
|
||||
external.persist(&appearance, ThemeMode::Dark);
|
||||
|
||||
// mtime 精度:有的文件系统 1s 粒度,这里显式等到时间戳变化
|
||||
for _ in 0..50 {
|
||||
if let Some((value, theme)) = bridge.reload_if_changed() {
|
||||
assert_eq!(theme, ThemeMode::Dark);
|
||||
assert!(value.bg_image_enabled);
|
||||
assert_eq!(value.bg_image, "D:/wall/x.png");
|
||||
std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).ok();
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
panic!("外部修改没有被 mtime 热切捕获");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accent_preset_and_validation() {
|
||||
let mut appearance = AppearancePrefs::factory();
|
||||
assert_eq!(appearance.accent_color, "");
|
||||
assert!(appearance.set_accent_preset(1));
|
||||
assert_eq!(appearance.accent_color, "#0F6CBD");
|
||||
assert!(!appearance.set_accent("not-a-color"), "非法输入不改现状");
|
||||
assert_eq!(appearance.accent_color, "#0F6CBD");
|
||||
assert!(appearance.set_accent(""), "空串恢复出厂");
|
||||
assert_eq!(appearance.accent_color, "");
|
||||
assert!(!appearance.set_accent_preset(99));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bg_active_needs_both_switch_and_path() {
|
||||
let mut appearance = AppearancePrefs::factory();
|
||||
appearance.bg_image = "D:/wall/p.png".to_owned();
|
||||
assert!(!appearance.bg_active(), "开关没开不算生效");
|
||||
appearance.bg_image_enabled = true;
|
||||
assert!(appearance.bg_active());
|
||||
appearance.bg_image.clear();
|
||||
assert!(!appearance.bg_active(), "路径空也不算生效");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! UI 状态与 reducer:Slint 只负责渲染,所有状态变更都汇聚到 [`AppState::apply`]。
|
||||
//!
|
||||
//! 数据流向:mock/host 后端 → [`crate::dto::AppEvent`] 队列 → `apply` → 状态字段 → Slint 属性。
|
||||
//! 偏好项在 [`crate::prefs`] 里登记了持久化键名,core::setting 的 schema 落地后按这些键读写。
|
||||
|
||||
use crate::dialogs::DialogQueue;
|
||||
use crate::dto::{
|
||||
AgentEvent, AppEvent, ChatMessage, ChatRole, CoreEvent, DiagnosisReport, InstanceRuntime,
|
||||
InstanceSummary, LogLine, LogSession, Progress, ToolCallView, VersionSummary,
|
||||
};
|
||||
use crate::prefs::UiPrefs;
|
||||
use crate::router::{AiPanelMode, Route, Router};
|
||||
use crate::toast::ToastCenter;
|
||||
|
||||
/// AI 会话状态(右侧栏与独立页共享同一份,切换不丢)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AiSession {
|
||||
/// 会话消息(user / assistant / tool / system)
|
||||
pub messages: Vec<ChatMessage>,
|
||||
/// 是否有流式消息在跑
|
||||
pub streaming: bool,
|
||||
/// YOLO 开关(跳过确认,审计照记)
|
||||
pub yolo: bool,
|
||||
/// 输入框草稿(切形态不丢)
|
||||
pub draft: String,
|
||||
/// 端点标签(显示在栏顶)
|
||||
pub endpoint_label: String,
|
||||
}
|
||||
|
||||
impl Default for AiSession {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl AiSession {
|
||||
/// 默认端点标签(P0 是本地 llama.cpp;P1 由设置页决定)。
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
messages: Vec::new(),
|
||||
streaming: false,
|
||||
yolo: false,
|
||||
draft: String::new(),
|
||||
endpoint_label: "llama.cpp · 本地".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 流式收敛:清掉全部流式标记。
|
||||
pub fn finish_stream(&mut self) {
|
||||
self.streaming = false;
|
||||
for message in &mut self.messages {
|
||||
message.streaming = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 磁贴网格单元:位置由 [`grid_positions`] 算好,Slint 只消费 row/col。
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TileCell<'a> {
|
||||
/// 实例数据
|
||||
pub instance: &'a InstanceSummary,
|
||||
/// 网格行号(0 起)
|
||||
pub row: usize,
|
||||
/// 网格列号(0 起)
|
||||
pub col: usize,
|
||||
}
|
||||
|
||||
/// 纯函数:把 n 个磁贴摊到 `columns` 列的网格上,返回 `(row, col)`。
|
||||
///
|
||||
/// 特意放在 Rust 侧:Slint DSL 里做整数除法会引入隐式浮点,且这段逻辑可以单测。
|
||||
pub fn grid_positions(count: usize, columns: usize) -> Vec<(usize, usize)> {
|
||||
let columns = columns.max(1);
|
||||
(0..count)
|
||||
.map(|index| (index / columns, index % columns))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 应用全局状态。
|
||||
#[derive(Debug)]
|
||||
pub struct AppState {
|
||||
/// UI 偏好(记忆项)
|
||||
pub prefs: UiPrefs,
|
||||
/// 导航栈
|
||||
pub router: Router,
|
||||
/// 实例列表快照
|
||||
pub instances: Vec<InstanceSummary>,
|
||||
/// 当前分类的版本列表
|
||||
pub versions: Vec<VersionSummary>,
|
||||
/// 日志会话列表
|
||||
pub log_sessions: Vec<LogSession>,
|
||||
/// 当前会话日志行
|
||||
pub log_lines: Vec<LogLine>,
|
||||
/// 最近一次诊断结论
|
||||
pub diagnosis: Option<DiagnosisReport>,
|
||||
/// 选中的日志会话
|
||||
pub selected_session: Option<String>,
|
||||
/// AI 会话状态
|
||||
pub ai: AiSession,
|
||||
/// 对话框队列(一次一条)
|
||||
pub dialogs: DialogQueue,
|
||||
/// Toast 中心
|
||||
pub toasts: ToastCenter,
|
||||
/// 实例页搜索词
|
||||
pub instance_query: String,
|
||||
/// 下载页「仅已装」过滤
|
||||
pub installed_only: bool,
|
||||
/// 下载页版本号筛选词
|
||||
pub download_query: String,
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
/// 空状态(数据由后端事件填充,P0 是 mock)。
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
prefs: UiPrefs::default(),
|
||||
router: Router::new(),
|
||||
instances: Vec::new(),
|
||||
versions: Vec::new(),
|
||||
log_sessions: Vec::new(),
|
||||
log_lines: Vec::new(),
|
||||
diagnosis: None,
|
||||
selected_session: None,
|
||||
ai: AiSession::new(),
|
||||
dialogs: DialogQueue::new(),
|
||||
toasts: ToastCenter::new(),
|
||||
instance_query: String::new(),
|
||||
installed_only: false,
|
||||
download_query: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前页面。
|
||||
pub fn route(&self) -> &Route {
|
||||
self.router.route()
|
||||
}
|
||||
|
||||
/// 跳转(一级页替换、子页面压栈;去 AI 独立页时自动展开 AI 栏偏好)。
|
||||
pub fn navigate(&mut self, route: Route) {
|
||||
if route == Route::Agent {
|
||||
self.prefs.ai_collapsed = false;
|
||||
}
|
||||
self.router.navigate(route);
|
||||
}
|
||||
|
||||
/// 回退一层。
|
||||
pub fn back(&mut self) -> bool {
|
||||
self.router.back()
|
||||
}
|
||||
|
||||
/// AI 栏当前形态(跟着路由走)。
|
||||
pub fn ai_mode(&self) -> AiPanelMode {
|
||||
self.router.ai_mode()
|
||||
}
|
||||
|
||||
/// 应用一条事件(唯一状态变更入口)。
|
||||
pub fn apply(&mut self, event: AppEvent) {
|
||||
match event {
|
||||
AppEvent::Core(core) => self.apply_core(core),
|
||||
AppEvent::Agent(agent) => self.apply_agent(agent),
|
||||
AppEvent::DialogRequested(request) => {
|
||||
self.dialogs.push_request(request);
|
||||
}
|
||||
AppEvent::DialogClosed(id) => {
|
||||
self.dialogs.close(id);
|
||||
}
|
||||
AppEvent::Toast(toast) => {
|
||||
self.toasts.push_request(toast);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// core 事件。
|
||||
pub fn apply_core(&mut self, event: CoreEvent) {
|
||||
match event {
|
||||
CoreEvent::InstancesChanged(instances) => self.instances = instances,
|
||||
CoreEvent::InstanceRuntimeChanged { id, runtime } => {
|
||||
if let Some(instance) = self.instances.iter_mut().find(|item| item.id == id) {
|
||||
instance.runtime = runtime;
|
||||
}
|
||||
}
|
||||
CoreEvent::VersionListChanged(versions) => self.versions = versions,
|
||||
CoreEvent::LogSessionsChanged(sessions) => self.log_sessions = sessions,
|
||||
CoreEvent::LogLinesChanged(lines) => self.log_lines = lines,
|
||||
CoreEvent::DiagnosisReady(report) => self.diagnosis = Some(report),
|
||||
}
|
||||
}
|
||||
|
||||
/// agent 事件。
|
||||
pub fn apply_agent(&mut self, event: AgentEvent) {
|
||||
match event {
|
||||
AgentEvent::MessageAppended(message) => {
|
||||
// 流式占位到达即视为「一轮回复进行中」:UI 的发送键/停止键据此切换
|
||||
if message.streaming {
|
||||
self.ai.streaming = true;
|
||||
}
|
||||
self.ai.messages.push(message);
|
||||
}
|
||||
AgentEvent::MessageDelta { index, delta } => {
|
||||
if let Some(message) = self.ai.messages.get_mut(index) {
|
||||
message.text.push_str(&delta);
|
||||
}
|
||||
}
|
||||
AgentEvent::MessageFinished { index } => {
|
||||
if let Some(message) = self.ai.messages.get_mut(index) {
|
||||
message.streaming = false;
|
||||
}
|
||||
self.ai.streaming = false;
|
||||
}
|
||||
AgentEvent::ToolCallStarted { name, summary } => {
|
||||
self.ai.streaming = true;
|
||||
self.ai.messages.push(ChatMessage {
|
||||
role: ChatRole::Tool,
|
||||
text: summary.clone(),
|
||||
tool: Some(ToolCallView {
|
||||
name,
|
||||
ok: false,
|
||||
summary,
|
||||
}),
|
||||
streaming: true,
|
||||
});
|
||||
}
|
||||
AgentEvent::ToolCallFinished { name, ok, summary } => {
|
||||
let target =
|
||||
self.ai.messages.iter_mut().rev().find(|message| {
|
||||
message.tool.as_ref().is_some_and(|tool| tool.name == name)
|
||||
});
|
||||
if let Some(message) = target {
|
||||
message.text.clone_from(&summary);
|
||||
message.streaming = false;
|
||||
if let Some(tool) = &mut message.tool {
|
||||
tool.ok = ok;
|
||||
tool.summary = summary;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按搜索词过滤后的磁贴网格(顺序稳定 = 实例列表顺序)。
|
||||
pub fn tiles(&self) -> Vec<TileCell<'_>> {
|
||||
let query = self.instance_query.trim().to_lowercase();
|
||||
let filtered: Vec<&InstanceSummary> = self
|
||||
.instances
|
||||
.iter()
|
||||
.filter(|instance| query.is_empty() || instance.name.to_lowercase().contains(&query))
|
||||
.collect();
|
||||
let positions = grid_positions(filtered.len(), self.prefs.tile_size.columns());
|
||||
filtered
|
||||
.into_iter()
|
||||
.zip(positions)
|
||||
.map(|(instance, (row, col))| TileCell { instance, row, col })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 运行中的实例(实例页顶部迷你状态条)。
|
||||
pub fn running(&self) -> Vec<&InstanceSummary> {
|
||||
self.instances
|
||||
.iter()
|
||||
.filter(|instance| {
|
||||
matches!(
|
||||
instance.runtime,
|
||||
InstanceRuntime::Running { .. } | InstanceRuntime::Busy { .. }
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 覆盖某实例的启动进度(mock / 真实后端共用同一入口)。
|
||||
pub fn set_progress(&mut self, id: &str, progress: Progress) {
|
||||
if let Some(instance) = self.instances.iter_mut().find(|item| item.id == id) {
|
||||
if let InstanceRuntime::Busy {
|
||||
progress: current, ..
|
||||
} = &mut instance.runtime
|
||||
{
|
||||
*current = progress;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 折叠/展开导航栏。
|
||||
pub fn toggle_nav(&mut self) {
|
||||
self.prefs.nav_collapsed = !self.prefs.nav_collapsed;
|
||||
}
|
||||
|
||||
/// 折叠/展开 AI 栏;若正处在独立页形态则先收回侧栏。
|
||||
pub fn toggle_ai(&mut self) {
|
||||
if self.route() == &Route::Agent {
|
||||
self.router.back();
|
||||
self.prefs.ai_collapsed = false;
|
||||
return;
|
||||
}
|
||||
self.prefs.ai_collapsed = !self.prefs.ai_collapsed;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "state_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,262 @@
|
||||
//! state.rs 的单元测试(拆文件保持单文件 ≤400 行)。
|
||||
|
||||
use super::{grid_positions, AiSession, AppState};
|
||||
use crate::dialogs::{DialogKind, DialogRequest, DialogSource};
|
||||
use crate::dto::{
|
||||
AgentEvent, AppEvent, ChatMessage, ChatRole, CoreEvent, Diagnosis, DiagnosisReport,
|
||||
InstanceRuntime, InstanceSummary, LoaderInfo, LoaderKind,
|
||||
};
|
||||
use crate::prefs::TileSize;
|
||||
use crate::router::Route;
|
||||
use crate::toast::Toast;
|
||||
use crate::toast::ToastKind;
|
||||
|
||||
fn instance(id: &str, name: &str) -> InstanceSummary {
|
||||
InstanceSummary {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
mc_version: "1.20.4".to_string(),
|
||||
loader: LoaderInfo {
|
||||
kind: LoaderKind::Fabric,
|
||||
version: "0.16.5".to_string(),
|
||||
},
|
||||
last_played: None,
|
||||
runtime: InstanceRuntime::Idle,
|
||||
icon: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_positions_wrap_by_column_count() {
|
||||
assert_eq!(grid_positions(0, 4), vec![]);
|
||||
assert_eq!(grid_positions(3, 2), vec![(0, 0), (0, 1), (1, 0)]);
|
||||
// columns == 0 时按 1 列兜底,不允许除零
|
||||
assert_eq!(grid_positions(2, 0), vec![(0, 0), (1, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_follow_tile_size_and_search() {
|
||||
let mut state = AppState::new();
|
||||
state.instances = vec![
|
||||
instance("a", "生存"),
|
||||
instance("b", "创造"),
|
||||
instance("c", "Demo"),
|
||||
];
|
||||
|
||||
assert_eq!(state.tiles().len(), 3);
|
||||
assert_eq!((state.tiles()[2].row, state.tiles()[2].col), (0, 2));
|
||||
|
||||
state.prefs.tile_size = TileSize::Large;
|
||||
assert_eq!((state.tiles()[2].row, state.tiles()[2].col), (0, 2));
|
||||
|
||||
state.prefs.tile_size = TileSize::Small;
|
||||
assert_eq!(state.tiles().len(), 3);
|
||||
|
||||
state.instance_query = "demo".to_string();
|
||||
let tiles = state.tiles();
|
||||
assert_eq!(tiles.len(), 1);
|
||||
assert_eq!(tiles[0].instance.id, "c");
|
||||
assert_eq!((tiles[0].row, tiles[0].col), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_reflow_when_tile_size_shrinks() {
|
||||
let mut state = AppState::new();
|
||||
state.instances = (0..8)
|
||||
.map(|i| instance(&format!("i{i}"), &format!("实例{i}")))
|
||||
.collect();
|
||||
|
||||
state.prefs.tile_size = TileSize::Medium;
|
||||
let medium_rows = state.tiles().iter().map(|cell| cell.row).max();
|
||||
|
||||
state.prefs.tile_size = TileSize::Small;
|
||||
let small_rows = state.tiles().iter().map(|cell| cell.row).max();
|
||||
|
||||
assert_eq!(medium_rows, Some(1)); // 8 / 4 列 = 2 行
|
||||
assert_eq!(small_rows, Some(1)); // 8 / 6 列 = 2 行
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_events_update_the_matching_instance() {
|
||||
let mut state = AppState::new();
|
||||
state.instances = vec![instance("a", "生存"), instance("b", "创造")];
|
||||
|
||||
state.apply(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
|
||||
id: "b".to_string(),
|
||||
runtime: InstanceRuntime::Running { pid: 42 },
|
||||
}));
|
||||
|
||||
assert_eq!(state.instances[0].runtime, InstanceRuntime::Idle);
|
||||
assert_eq!(
|
||||
state.instances[1].runtime,
|
||||
InstanceRuntime::Running { pid: 42 }
|
||||
);
|
||||
assert_eq!(state.running().len(), 1);
|
||||
assert_eq!(state.running()[0].id, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_events_only_touch_busy_instances() {
|
||||
let mut state = AppState::new();
|
||||
state.instances = vec![instance("a", "生存")];
|
||||
state.instances[0].runtime = InstanceRuntime::Busy {
|
||||
stage: crate::dto::LaunchStage::Download,
|
||||
progress: crate::dto::Progress {
|
||||
done: 0,
|
||||
total: 100,
|
||||
},
|
||||
};
|
||||
|
||||
state.set_progress(
|
||||
"a",
|
||||
crate::dto::Progress {
|
||||
done: 50,
|
||||
total: 100,
|
||||
},
|
||||
);
|
||||
match &state.instances[0].runtime {
|
||||
InstanceRuntime::Busy { progress, .. } => {
|
||||
assert!((progress.ratio() - 0.5).abs() < f32::EPSILON);
|
||||
}
|
||||
other => panic!("unexpected runtime: {other:?}"),
|
||||
}
|
||||
|
||||
// 不存在的 id / 非 Busy 状态不改变任何东西
|
||||
state.set_progress("missing", crate::dto::Progress { done: 1, total: 1 });
|
||||
assert_eq!(state.instances.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_stream_deltas_accumulate_and_finish() {
|
||||
let mut state = AppState::new();
|
||||
state.apply(AppEvent::Agent(AgentEvent::MessageAppended(
|
||||
ChatMessage::user("怎么装 1.20.4"),
|
||||
)));
|
||||
state.apply(AppEvent::Agent(AgentEvent::MessageAppended(
|
||||
ChatMessage::assistant_stream(),
|
||||
)));
|
||||
assert_eq!(state.ai.messages.len(), 2);
|
||||
assert!(state.ai.streaming);
|
||||
assert_eq!(state.ai.messages[1].role, ChatRole::Assistant);
|
||||
|
||||
state.apply(AppEvent::Agent(AgentEvent::MessageDelta {
|
||||
index: 1,
|
||||
delta: "先".to_string(),
|
||||
}));
|
||||
state.apply(AppEvent::Agent(AgentEvent::MessageDelta {
|
||||
index: 1,
|
||||
delta: "下载".to_string(),
|
||||
}));
|
||||
state.apply(AppEvent::Agent(AgentEvent::MessageFinished { index: 1 }));
|
||||
|
||||
assert_eq!(state.ai.messages[1].text, "先下载");
|
||||
assert!(!state.ai.messages[1].streaming);
|
||||
assert!(!state.ai.streaming);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_session_finish_stream_clears_every_flag() {
|
||||
let mut session = AiSession::new();
|
||||
session.messages.push(ChatMessage::user("hi"));
|
||||
session.messages.push(ChatMessage::assistant_stream());
|
||||
session.finish_stream();
|
||||
assert!(session.messages.iter().all(|message| !message.streaming));
|
||||
assert!(!session.streaming);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_call_finish_updates_the_last_matching_message() {
|
||||
let mut state = AppState::new();
|
||||
state.apply(AppEvent::Agent(AgentEvent::ToolCallStarted {
|
||||
name: "get_config".to_string(),
|
||||
summary: "读取设置".to_string(),
|
||||
}));
|
||||
state.apply(AppEvent::Agent(AgentEvent::ToolCallFinished {
|
||||
name: "get_config".to_string(),
|
||||
ok: true,
|
||||
summary: "读取到 3 项".to_string(),
|
||||
}));
|
||||
|
||||
let tool = &state.ai.messages[0];
|
||||
assert_eq!(tool.role, ChatRole::Tool);
|
||||
assert_eq!(tool.text, "读取到 3 项");
|
||||
assert!(!tool.streaming);
|
||||
assert!(tool.tool.as_ref().is_some_and(|call| call.ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialogs_and_toasts_flow_through_apply() {
|
||||
let mut state = AppState::new();
|
||||
state.apply(AppEvent::DialogRequested(DialogRequest {
|
||||
id: 42,
|
||||
source: DialogSource::UserAction,
|
||||
title: "AI 想修改内存".to_string(),
|
||||
body: "改为 8G".to_string(),
|
||||
kind: DialogKind::Confirm {
|
||||
primary: "允许".to_string(),
|
||||
secondary: "拒绝".to_string(),
|
||||
},
|
||||
}));
|
||||
state.apply(AppEvent::Toast(Toast {
|
||||
id: 0,
|
||||
kind: ToastKind::Success,
|
||||
text: "下载完成".to_string(),
|
||||
remaining_ms: 0,
|
||||
}));
|
||||
|
||||
assert_eq!(state.dialogs.pending_len(), 0);
|
||||
// id 归生产者:队列原样保留,DialogClosed(42) 才能命中同一条
|
||||
assert_eq!(state.dialogs.current().map(|dialog| dialog.id), Some(42));
|
||||
assert_eq!(state.toasts.len(), 1);
|
||||
|
||||
state.apply(AppEvent::DialogClosed(42));
|
||||
assert!(state.dialogs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigate_to_agent_page_expands_the_ai_panel() {
|
||||
let mut state = AppState::new();
|
||||
state.prefs.ai_collapsed = true;
|
||||
state.navigate(Route::Agent);
|
||||
assert_eq!(state.route(), &Route::Agent);
|
||||
assert_eq!(state.ai_mode(), crate::router::AiPanelMode::Page);
|
||||
assert!(!state.prefs.ai_collapsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_ai_from_the_page_form_docks_it_again() {
|
||||
let mut state = AppState::new();
|
||||
state.navigate(Route::Agent);
|
||||
state.toggle_ai();
|
||||
assert_eq!(state.route(), &Route::Instances);
|
||||
assert_eq!(state.ai_mode(), crate::router::AiPanelMode::Docked);
|
||||
assert!(!state.prefs.ai_collapsed);
|
||||
|
||||
state.toggle_ai();
|
||||
assert!(state.prefs.ai_collapsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_nav_flips_the_pref() {
|
||||
let mut state = AppState::new();
|
||||
state.toggle_nav();
|
||||
assert!(state.prefs.nav_collapsed);
|
||||
state.toggle_nav();
|
||||
assert!(!state.prefs.nav_collapsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnosis_report_lands_on_state() {
|
||||
let mut state = AppState::new();
|
||||
state.apply(AppEvent::Core(CoreEvent::DiagnosisReady(DiagnosisReport {
|
||||
session: "s1".to_string(),
|
||||
diagnosis: Diagnosis {
|
||||
rule: "gpu.driver_old".to_string(),
|
||||
title: "显卡驱动过旧".to_string(),
|
||||
confidence: 92,
|
||||
hint: "升级驱动".to_string(),
|
||||
fix: Some("open_driver_page".to_string()),
|
||||
},
|
||||
})));
|
||||
assert!(state.diagnosis.is_some());
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! 主题与外观的运行期逻辑(从 `ui_bind.rs` 拆出,守住单文件 ≤400 行)。
|
||||
//!
|
||||
//! 全是 `impl Inner` 的方法:配置热切轮询、系统主题对齐、外观令牌下发、背景图/模糊层重建。
|
||||
//! 拆出来的边界是「时间驱动的状态维护」——`ui_bind.rs` 只留「建窗口 + 每拍驱动 + 灌属性」。
|
||||
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use crate::bg_image::{self, BackgroundLayers};
|
||||
use crate::conv;
|
||||
use crate::prefs::{AppearancePrefs, BgFill, ThemeMode};
|
||||
use crate::toast::ToastKind;
|
||||
use crate::ui_bind::{
|
||||
BackgroundKey, Inner, CONFIG_POLL_TICKS, SYSTEM_THEME_POLL_TICKS, TILE_REGENERATE_STEP,
|
||||
};
|
||||
|
||||
impl Inner {
|
||||
pub(crate) fn poll_settings(&self) {
|
||||
if !self.ticks.get().is_multiple_of(CONFIG_POLL_TICKS) {
|
||||
return;
|
||||
}
|
||||
let Some((appearance, theme)) = self.bridge.borrow_mut().reload_if_changed() else {
|
||||
return;
|
||||
};
|
||||
{
|
||||
let mut state = self.state.borrow_mut();
|
||||
state.prefs.appearance = appearance;
|
||||
state.prefs.theme = theme;
|
||||
}
|
||||
self.apply_theme();
|
||||
self.apply_appearance();
|
||||
}
|
||||
|
||||
/// 系统主题对齐:启动时先读一次真实系统主题(避免 auto 首帧按浅色画再翻黑);
|
||||
/// 之后仅在「auto + 后端不认识系统主题」(`Theme.system-theme-known == false`)时兜底轮询。
|
||||
pub(crate) fn poll_system_theme(&self) {
|
||||
let auto = matches!(self.state.borrow().prefs.theme, ThemeMode::Auto);
|
||||
let backend_known = self.ui.get_system_theme_known();
|
||||
let due = !self.system_theme_probed.get()
|
||||
|| (auto && !backend_known && self.ticks.get().is_multiple_of(SYSTEM_THEME_POLL_TICKS));
|
||||
if !due {
|
||||
return;
|
||||
}
|
||||
self.system_theme_probed.set(true);
|
||||
let value = match unlucky_core::platform::theme_probe::probe() {
|
||||
unlucky_core::platform::theme_probe::SystemTheme::Light => 1,
|
||||
unlucky_core::platform::theme_probe::SystemTheme::Dark => 2,
|
||||
unlucky_core::platform::theme_probe::SystemTheme::Unknown => 0,
|
||||
};
|
||||
if self.ui.get_system_theme() != value {
|
||||
self.ui.set_system_theme(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动时的系统主题对齐(首帧前调用一次)。
|
||||
pub(crate) fn align_system_theme(&self) {
|
||||
self.poll_system_theme();
|
||||
}
|
||||
|
||||
/// 主题三态 → 根组件属性;`ui/main.slint` 里的 changed 处理器再赋给 `Theme` 全局
|
||||
/// (auto 时 Theme 内部读系统的 `Palette.color-scheme` 与本进程探测到的系统主题)。
|
||||
pub(crate) fn apply_theme(&self) {
|
||||
let mode = self.state.borrow().prefs.theme;
|
||||
self.ui.set_theme_mode(conv::theme_mode(mode));
|
||||
}
|
||||
|
||||
/// 外观(高级)四件 → 根组件属性(进而写进 `Theme` 全局)。
|
||||
///
|
||||
/// 背景图只在「开关打开 + 路径非空 + 换了输入」时才重新解码/生成模糊层。
|
||||
pub(crate) fn apply_appearance(&self) {
|
||||
let appearance = self.state.borrow().prefs.appearance.clone();
|
||||
self.ui.set_bg_fill(conv::bg_fill(appearance.bg_fill));
|
||||
self.ui.set_bg_dim(appearance.bg_dim.clamp(0.0, 0.9));
|
||||
self.ui
|
||||
.set_panel_alpha(appearance.panel_alpha.clamp(0.4, 1.0));
|
||||
self.ui.set_glass(appearance.glass);
|
||||
self.ui
|
||||
.set_accent_color(conv::accent_color(&appearance.accent_color));
|
||||
self.ui
|
||||
.set_accent_hex(appearance.accent_color.clone().into());
|
||||
self.refresh_background(&appearance);
|
||||
}
|
||||
|
||||
/// 按需重建背景图 + 模糊层。
|
||||
fn refresh_background(&self, appearance: &AppearancePrefs) {
|
||||
if !appearance.bg_active() {
|
||||
let had = self.background_key.borrow_mut().take().is_some();
|
||||
if had {
|
||||
self.background.replace(BackgroundLayers::default());
|
||||
self.ui.set_background_image(slint::Image::default());
|
||||
self.ui.set_background_blur(slint::Image::default());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let key = BackgroundKey {
|
||||
path: appearance.bg_image.clone(),
|
||||
fill: appearance.bg_fill,
|
||||
viewport: self.tile_viewport(appearance.bg_fill),
|
||||
};
|
||||
if self.background_key.borrow().as_ref() == Some(&key) {
|
||||
return;
|
||||
}
|
||||
self.background_key.replace(Some(key.clone()));
|
||||
|
||||
// 模糊层按窗口物理尺寸放大(软件渲染器不做图片缩放插值,见 bg_image::prepare);
|
||||
// tile 之外的模式窗口缩放不重建画布,模糊层被拉伸也无感。
|
||||
let real_viewport = self.window_physical_size();
|
||||
match bg_image::prepare(&key.path, key.fill, real_viewport) {
|
||||
Some(layers) => {
|
||||
self.ui.set_background_image(layers.image.clone());
|
||||
self.ui.set_background_blur(layers.blur.clone());
|
||||
self.background.replace(layers);
|
||||
}
|
||||
None => {
|
||||
// 载入失败(路径不存在 / 不是 PNG):清空图层并提示一次,别留上一张图的残影
|
||||
self.background.replace(BackgroundLayers::default());
|
||||
self.ui.set_background_image(slint::Image::default());
|
||||
self.ui.set_background_blur(slint::Image::default());
|
||||
self.state.borrow_mut().toasts.push(
|
||||
ToastKind::Warn,
|
||||
"背景图载入失败(当前只支持 PNG,且路径需存在)",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// tile 画布的窗口尺寸(量化到 [`TILE_REGENERATE_STEP`],避免拖动窗口时反复重算)。
|
||||
fn tile_viewport(&self, fill: BgFill) -> (u32, u32) {
|
||||
if fill != BgFill::Tile {
|
||||
return (0, 0);
|
||||
}
|
||||
let (width, height) = self.window_physical_size();
|
||||
(
|
||||
width / TILE_REGENERATE_STEP * TILE_REGENERATE_STEP,
|
||||
height / TILE_REGENERATE_STEP * TILE_REGENERATE_STEP,
|
||||
)
|
||||
}
|
||||
|
||||
/// 窗口物理像素尺寸(取不到时 (0, 0),tile 退化为单块)。
|
||||
fn window_physical_size(&self) -> (u32, u32) {
|
||||
let size = self.ui.window().size();
|
||||
(size.width, size.height)
|
||||
}
|
||||
|
||||
/// 落盘当前偏好(主题 + 外观四件)。
|
||||
pub(crate) fn persist_settings(&self) {
|
||||
let state = self.state.borrow();
|
||||
self.bridge
|
||||
.borrow_mut()
|
||||
.persist(&state.prefs.appearance, state.prefs.theme);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Toast 中心:右下角非阻塞提示(下载完成 / 复制成功 / 后台任务结论)。
|
||||
//!
|
||||
//! 与模态对话框队列([`crate::dialogs`])分开:Toast 不阻塞、不排序、可叠加,
|
||||
//! 只做「先进先出 + 上限裁剪 + TTL 到期」。UI 侧由 Rust 定时器每帧调用 [`ToastCenter::expire`]。
|
||||
|
||||
/// Toast 标识。
|
||||
pub type ToastId = u64;
|
||||
|
||||
/// Toast 语义色。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ToastKind {
|
||||
/// 一般信息
|
||||
Info,
|
||||
/// 成功
|
||||
Success,
|
||||
/// 警告
|
||||
Warn,
|
||||
/// 错误
|
||||
Error,
|
||||
}
|
||||
|
||||
/// 一条 Toast;`remaining_ms` 由 [`ToastCenter::expire`] 递减。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Toast {
|
||||
/// 队列内唯一 id(由 [`ToastCenter::push_request`] 重新编号)
|
||||
pub id: ToastId,
|
||||
/// 语义色
|
||||
pub kind: ToastKind,
|
||||
/// 提示文案
|
||||
pub text: String,
|
||||
/// 剩余存活毫秒(0 = 用默认 TTL,入队时补)
|
||||
pub remaining_ms: u64,
|
||||
}
|
||||
|
||||
/// Toast 中心:先进先出,超出上限丢最旧的。
|
||||
#[derive(Debug)]
|
||||
pub struct ToastCenter {
|
||||
items: Vec<Toast>,
|
||||
next_id: ToastId,
|
||||
ttl_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for ToastCenter {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToastCenter {
|
||||
/// 默认 4s 后自动消失。
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
items: Vec::new(),
|
||||
next_id: 0,
|
||||
ttl_ms: 4_000,
|
||||
}
|
||||
}
|
||||
|
||||
/// 同时最多显示的条数。
|
||||
pub const MAX_VISIBLE: usize = 4;
|
||||
|
||||
/// 入队一条 Toast。
|
||||
pub fn push(&mut self, kind: ToastKind, text: impl Into<String>) -> ToastId {
|
||||
self.push_request(Toast {
|
||||
id: 0,
|
||||
kind,
|
||||
text: text.into(),
|
||||
remaining_ms: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// 入队一条已组装好的 Toast(事件通道用);id 重新编号,`remaining_ms == 0` 视为用默认 TTL。
|
||||
pub fn push_request(&mut self, mut toast: Toast) -> ToastId {
|
||||
self.next_id += 1;
|
||||
toast.id = self.next_id;
|
||||
if toast.remaining_ms == 0 {
|
||||
toast.remaining_ms = self.ttl_ms;
|
||||
}
|
||||
let id = toast.id;
|
||||
self.items.push(toast);
|
||||
while self.items.len() > Self::MAX_VISIBLE {
|
||||
self.items.remove(0);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// 当前显示列表(UI 模型来源)。
|
||||
pub fn items(&self) -> &[Toast] {
|
||||
&self.items
|
||||
}
|
||||
|
||||
/// 手动关闭(点了关闭按钮)。
|
||||
pub fn dismiss(&mut self, id: ToastId) -> bool {
|
||||
if let Some(at) = self.items.iter().position(|toast| toast.id == id) {
|
||||
self.items.remove(at);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// 时间推进:移除到期 Toast。
|
||||
pub fn expire(&mut self, elapsed_ms: u64) {
|
||||
for toast in &mut self.items {
|
||||
toast.remaining_ms = toast.remaining_ms.saturating_sub(elapsed_ms);
|
||||
}
|
||||
self.items.retain(|toast| toast.remaining_ms > 0);
|
||||
}
|
||||
|
||||
/// 当前条数。
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
/// 是否没有 Toast。
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ToastCenter, ToastKind};
|
||||
|
||||
#[test]
|
||||
fn toasts_expire_and_cap_the_stack() {
|
||||
let mut center = ToastCenter::new();
|
||||
center.push(ToastKind::Info, "a");
|
||||
center.push(ToastKind::Info, "b");
|
||||
assert_eq!(center.len(), 2);
|
||||
|
||||
for i in 0..10 {
|
||||
center.push(ToastKind::Success, format!("t{i}"));
|
||||
}
|
||||
assert_eq!(center.len(), ToastCenter::MAX_VISIBLE);
|
||||
|
||||
center.expire(3_000);
|
||||
assert_eq!(center.len(), ToastCenter::MAX_VISIBLE);
|
||||
center.expire(1_001);
|
||||
assert!(center.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dismiss_removes_one_toast() {
|
||||
let mut center = ToastCenter::new();
|
||||
let first = center.push(ToastKind::Info, "a");
|
||||
center.push(ToastKind::Warn, "b");
|
||||
assert!(center.dismiss(first));
|
||||
assert!(!center.dismiss(first));
|
||||
assert_eq!(center.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! 绑定层(核心):窗口/状态/后端的持有与同步;回调接线在 [`crate::callbacks`]。
|
||||
//!
|
||||
//! P0 的“后端”是 [`MockBackend`](脚本化假数据);把 `Box<dyn Backend>` 换成真实的 core/agent
|
||||
//! host 时,除本文件、`conv.rs`、`callbacks.rs` 外都不需要改
|
||||
//! (通道语义见 `DevDocs/SubAgentsTalk/app-DTO通道约定.md`)。
|
||||
//!
|
||||
//! 主题与外观(D17 / 09 §101-113):落盘配置由 [`SettingsBridge`] 读写(`config/launcher.json`,
|
||||
//! 与 `ull config set` 同一份),tick 里 1s 一次 `mtime` 热切;系统主题由
|
||||
//! `core::platform::theme_probe` 做启动对齐 + 后端不支持时的兜底轮询。
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{ComponentHandle, ModelRc, VecModel};
|
||||
|
||||
use crate::bg_image::BackgroundLayers;
|
||||
use crate::conv;
|
||||
use crate::dto::{AppCommand, Backend, InstanceId};
|
||||
use crate::mock::MockBackend;
|
||||
use crate::prefs::BgFill;
|
||||
use crate::settings_bridge::SettingsBridge;
|
||||
use crate::state::AppState;
|
||||
use crate::{MainWindow, SettingSection};
|
||||
|
||||
/// 定时器节拍:33ms ≈ 30fps(磁贴进度环 / 流式文本 / Toast TTL 的刷新下限)。
|
||||
const TICK_MS: u64 = 33;
|
||||
|
||||
/// 配置热切轮询间隔(拍数):约 1s 一次 `mtime` 比对,AI/CLI 改完下一拍即生效。
|
||||
pub(crate) const CONFIG_POLL_TICKS: u64 = 30;
|
||||
|
||||
/// 系统主题兜底轮询间隔(拍数):只在 `auto` 且后端不认识系统主题时启动(约 3s)。
|
||||
pub(crate) const SYSTEM_THEME_POLL_TICKS: u64 = 90;
|
||||
|
||||
/// tile 模式重建画布的窗口尺寸粒度(像素):避免拖动窗口时反复重算平铺画布。
|
||||
pub(crate) const TILE_REGENERATE_STEP: u32 = 128;
|
||||
|
||||
/// 应用外壳:持有窗口、状态与后端,把三者缝在一起。
|
||||
pub struct AppUi {
|
||||
inner: Rc<Inner>,
|
||||
timer: slint::Timer,
|
||||
}
|
||||
|
||||
pub(crate) struct Inner {
|
||||
pub(crate) ui: MainWindow,
|
||||
pub(crate) state: RefCell<AppState>,
|
||||
pub(crate) backend: RefCell<Box<dyn Backend>>,
|
||||
/// `config/launcher.json` 读写桥(app 不自己写盘:一律走 core::setting 的 schema API)
|
||||
pub(crate) bridge: RefCell<SettingsBridge>,
|
||||
/// 当前背景图 / 模糊层(避免每次同步都重新解码)
|
||||
pub(crate) background: RefCell<BackgroundLayers>,
|
||||
/// 生成 `background` 时的输入(路径 / 填充模式 / 窗口粒度尺寸)
|
||||
pub(crate) background_key: RefCell<Option<BackgroundKey>>,
|
||||
/// 拍数(轮询节拍)
|
||||
pub(crate) ticks: Cell<u64>,
|
||||
/// 是否已经做过启动时的系统主题对齐
|
||||
pub(crate) system_theme_probed: Cell<bool>,
|
||||
}
|
||||
|
||||
/// 背景图加工输入(值相同就不重新解码)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct BackgroundKey {
|
||||
pub(crate) path: String,
|
||||
pub(crate) fill: BgFill,
|
||||
/// tile 用的窗口尺寸(按 [`TILE_REGENERATE_STEP`] 量化;cover/contain 恒为 (0, 0))
|
||||
pub(crate) viewport: (u32, u32),
|
||||
}
|
||||
|
||||
impl AppUi {
|
||||
/// 建状态 + 假后端、读配置、接全部回调、灌初始事件并做第一次同步。
|
||||
pub fn new(ui: MainWindow) -> Self {
|
||||
// 先读一次落盘配置:主题三态 + 外观四件必须在首帧前就位(否则会闪一下出厂外观)
|
||||
let bridge = SettingsBridge::open();
|
||||
let (appearance, theme) = bridge.load();
|
||||
let mut state = AppState::new();
|
||||
state.prefs.appearance = appearance;
|
||||
state.prefs.theme = theme;
|
||||
|
||||
let inner = Rc::new(Inner {
|
||||
ui,
|
||||
state: RefCell::new(state),
|
||||
backend: RefCell::new(Box::new(MockBackend::new())),
|
||||
bridge: RefCell::new(bridge),
|
||||
background: RefCell::new(BackgroundLayers::default()),
|
||||
background_key: RefCell::new(None),
|
||||
ticks: Cell::new(0),
|
||||
system_theme_probed: Cell::new(false),
|
||||
});
|
||||
|
||||
crate::callbacks::wire(Rc::downgrade(&inner));
|
||||
inner.drain_events();
|
||||
inner.align_system_theme();
|
||||
inner.apply_theme();
|
||||
inner.apply_appearance();
|
||||
inner.sync();
|
||||
|
||||
Self {
|
||||
inner,
|
||||
timer: slint::Timer::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 进入 Slint 事件循环(窗口句柄由本结构持有,直到循环退出)。
|
||||
pub fn run(&self) -> Result<(), slint::PlatformError> {
|
||||
self.inner.ui.run()
|
||||
}
|
||||
|
||||
/// 启动 33ms 节拍(后端 tick → 事件 → 状态 → UI)。
|
||||
pub fn start_timer(&self) {
|
||||
let inner = Rc::clone(&self.inner);
|
||||
self.timer.start(
|
||||
slint::TimerMode::Repeated,
|
||||
Duration::from_millis(TICK_MS),
|
||||
move || inner.tick(),
|
||||
);
|
||||
}
|
||||
|
||||
/// 推进一拍(截图通道用:没有事件循环时手动把 tick 走起来,让 mock 事件灌进状态)。
|
||||
pub fn tick_once(&self) {
|
||||
self.inner.tick();
|
||||
slint::platform::update_timers_and_animations();
|
||||
}
|
||||
|
||||
/// 直接跳到「设置 → 外观」页(截图验收用:证明外观分组的四组控件真的接线了)。
|
||||
pub fn open_settings_appearance(&self) {
|
||||
self.inner
|
||||
.state
|
||||
.borrow_mut()
|
||||
.navigate(crate::router::Route::Settings);
|
||||
self.inner.sync();
|
||||
self.inner
|
||||
.ui
|
||||
.set_settings_section(SettingSection::Appearance);
|
||||
slint::platform::update_timers_and_animations();
|
||||
}
|
||||
|
||||
/// 渲染当前场景并存成 PNG(`--screenshot` 通道;见 `crate::png`)。
|
||||
///
|
||||
/// 为什么要这条通道:验收环境可能没有交互桌面(`CopyFromScreen` 直接失败),
|
||||
/// 而 Slint 的软件渲染器可以把场景渲染进内存像素缓冲(`Window::take_snapshot`),
|
||||
/// 结果与屏幕上看到的逐像素一致,且不需要 GPU。
|
||||
///
|
||||
/// # Errors
|
||||
/// 窗口显示失败、快照失败或写文件失败时返回错误。
|
||||
pub fn render_screenshot(&self, path: &str) -> Result<(), slint::PlatformError> {
|
||||
let ui = &self.inner.ui;
|
||||
ui.show()?;
|
||||
// 固定逻辑尺寸 = main.slint 的默认窗口口径,保证验收图可比
|
||||
ui.window()
|
||||
.set_size(slint::WindowSize::Logical(slint::LogicalSize::new(
|
||||
1180.0, 760.0,
|
||||
)));
|
||||
// 先走几拍:把 mock 事件(实例/版本/日志)与 33ms 节拍的效果灌进去
|
||||
for _ in 0..4 {
|
||||
self.tick_once();
|
||||
std::thread::sleep(Duration::from_millis(TICK_MS));
|
||||
}
|
||||
let buffer = ui.window().take_snapshot()?;
|
||||
let bytes = crate::png::encode_rgba8(&buffer);
|
||||
std::fs::write(path, bytes)
|
||||
.map_err(|error| slint::PlatformError::Other(format!("写截图失败 {path}: {error}")))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 发送一条 AI 提问:**只发指令 + 回流事件**,绝不做本地乐观回显。
|
||||
///
|
||||
/// 契约 §3 规定 host 先发 `MessageAppended(user)`:本地再 push 一次用户消息就会重复;
|
||||
/// 且流式气泡的收敛依赖事件里的 `MessageFinished{index}`,本地多建的占位会变成
|
||||
/// 永不收敛的「幽灵气泡」(review P1-1)。callbacks 与单测都走这一个入口。
|
||||
pub(crate) fn send_agent_message(state: &mut AppState, backend: &mut dyn Backend, text: &str) {
|
||||
backend.dispatch(AppCommand::AskAgent(text.to_string()));
|
||||
for event in backend.drain_events() {
|
||||
state.apply(event);
|
||||
}
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
/// 走一次完整的「提问 → 事件回流」。
|
||||
pub(crate) fn ask_agent(&self, text: &str) {
|
||||
let mut state = self.state.borrow_mut();
|
||||
let mut backend = self.backend.borrow_mut();
|
||||
send_agent_message(&mut state, backend.as_mut(), text);
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch(&self, command: AppCommand) {
|
||||
self.backend.borrow_mut().dispatch(command);
|
||||
self.drain_events();
|
||||
}
|
||||
|
||||
pub(crate) fn drain_events(&self) {
|
||||
let events = self.backend.borrow_mut().drain_events();
|
||||
if events.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut state = self.state.borrow_mut();
|
||||
for event in events {
|
||||
state.apply(event);
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&self) {
|
||||
self.backend
|
||||
.borrow_mut()
|
||||
.tick(Duration::from_millis(TICK_MS));
|
||||
self.drain_events();
|
||||
self.state.borrow_mut().toasts.expire(TICK_MS);
|
||||
self.ticks.set(self.ticks.get() + 1);
|
||||
self.poll_settings();
|
||||
self.poll_system_theme();
|
||||
self.sync();
|
||||
}
|
||||
|
||||
pub(crate) fn sync(&self) {
|
||||
let state = self.state.borrow();
|
||||
let ui = &self.ui;
|
||||
|
||||
ui.set_route(conv::route(state.route()));
|
||||
ui.set_nav_collapsed(state.prefs.nav_collapsed);
|
||||
ui.set_ai_collapsed(state.prefs.ai_collapsed);
|
||||
ui.set_tile_size(conv::tile_size(state.prefs.tile_size));
|
||||
ui.set_instance_view(conv::instance_view(state.prefs.instance_view));
|
||||
ui.set_download_category(conv::category_from(state.prefs.download_category));
|
||||
ui.set_download_installed_only(state.installed_only);
|
||||
ui.set_theme_mode(conv::theme_mode(state.prefs.theme));
|
||||
|
||||
ui.set_tiles(model(conv::tiles(&state)));
|
||||
ui.set_running_tiles(model(conv::running_tiles(&state)));
|
||||
ui.set_versions(model(conv::versions(&state)));
|
||||
ui.set_log_sessions(model(conv::log_sessions(&state)));
|
||||
ui.set_log_lines(model(conv::log_lines(&state)));
|
||||
ui.set_toasts(model(conv::toasts(&state)));
|
||||
|
||||
let (diagnosis, has_diagnosis) = conv::diagnosis(&state);
|
||||
ui.set_diagnosis(diagnosis);
|
||||
ui.set_has_diagnosis(has_diagnosis);
|
||||
ui.set_selected_session(state.selected_session.clone().unwrap_or_default().into());
|
||||
|
||||
ui.set_ai_messages(model(conv::chat(&state)));
|
||||
ui.set_ai_streaming(state.ai.streaming);
|
||||
ui.set_yolo(state.ai.yolo);
|
||||
ui.set_ai_endpoint_label(state.ai.endpoint_label.clone().into());
|
||||
|
||||
let (dialog, open, queued) = conv::dialog(&state);
|
||||
ui.set_dialog(dialog);
|
||||
ui.set_dialog_open(open);
|
||||
ui.set_dialog_queued(queued);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
|
||||
ModelRc::new(VecModel::from(items))
|
||||
}
|
||||
|
||||
/// 停止实例的指令构造(阶段 C 的磁贴「停止」键用;P0 只保留 API)。
|
||||
#[allow(dead_code)]
|
||||
pub fn stop_instance(id: &InstanceId) -> AppCommand {
|
||||
AppCommand::StopInstance(id.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use super::send_agent_message;
|
||||
use crate::dto::{Backend, ChatRole};
|
||||
use crate::mock::MockBackend;
|
||||
use crate::state::AppState;
|
||||
|
||||
/// 集成测试(callbacks→state→mock 全链路):发一次提问后
|
||||
/// ①用户消息恰出现一次(无本地回显重复)②所有 assistant 气泡收敛(无幽灵气泡)。
|
||||
///
|
||||
/// 分层单测漏掉这条正是 review P1-1 的根因,故这里用真实 mock 后端跑完整事件流。
|
||||
#[test]
|
||||
fn send_path_has_no_duplicate_user_message_and_no_ghost_stream() {
|
||||
let mut state = AppState::new();
|
||||
let mut backend = MockBackend::new();
|
||||
// 先灌入种子事件(实例/版本/日志快照)
|
||||
for event in backend.drain_events() {
|
||||
state.apply(event);
|
||||
}
|
||||
|
||||
send_agent_message(&mut state, &mut backend, "装哪个版本");
|
||||
|
||||
fn user_count(state: &AppState) -> usize {
|
||||
state
|
||||
.ai
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|message| message.role == ChatRole::User)
|
||||
.count()
|
||||
}
|
||||
assert_eq!(
|
||||
user_count(&state),
|
||||
1,
|
||||
"用户消息必须恰好一条(本地回显会造成两条)"
|
||||
);
|
||||
assert!(state.ai.streaming);
|
||||
|
||||
// 推进到流式收敛(mock 300ms/片 + 工具调用 + 收尾消息)
|
||||
for _ in 0..12 {
|
||||
backend.tick(Duration::from_millis(400));
|
||||
for event in backend.drain_events() {
|
||||
state.apply(event);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(user_count(&state), 1, "事件回流后用户消息仍应只有一条");
|
||||
assert!(
|
||||
state.ai.messages.iter().all(|message| !message.streaming),
|
||||
"所有气泡必须收敛(幽灵气泡会永久 streaming)"
|
||||
);
|
||||
assert!(!state.ai.streaming);
|
||||
assert!(
|
||||
state
|
||||
.ai
|
||||
.messages
|
||||
.iter()
|
||||
.any(|message| message.role == ChatRole::Assistant && !message.text.is_empty()),
|
||||
"增量应累积到 assistant 正文"
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.ai
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|message| message.role == ChatRole::Assistant)
|
||||
.count(),
|
||||
2,
|
||||
"一轮对话 = 流式回复 + 收尾回复"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
// 右侧 AI 常驻栏(D16 §1):默认 320px 可折叠;可「展开为页面」变成全宽独立页,
|
||||
// 两形态共享同一份会话模型(由 Rust 侧 AiSession 持有,这里只渲染,切换不丢状态)。
|
||||
// 栏顶承载 YOLO 快捷开关(D4 补充)与端点标签。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiChatMessage, ChatRole } from "../models.slint";
|
||||
import { UiText, TextRole } from "label.slint";
|
||||
import { AppIcon, IconKind } from "icons.slint";
|
||||
import { MetroButton, ButtonKind } from "../widgets/button.slint";
|
||||
import { PlainInput } from "../widgets/inputs.slint";
|
||||
import { GlassBase } from "glass.slint";
|
||||
import { ListView } from "std-widgets.slint";
|
||||
|
||||
// 一条会话消息:user 靠右(accent-soft 块)/ assistant 靠左 / tool 用状态边框 / system 居中弱化
|
||||
component ChatBubble inherits Rectangle {
|
||||
in property <UiChatMessage> message;
|
||||
|
||||
property <bool> is-tool: message.role == ChatRole.tool;
|
||||
property <bool> is-system: message.role == ChatRole.system;
|
||||
property <length> text-width: root.width - 2 * Metrics.gap-2;
|
||||
property <length> tool-row: is-tool ? 16px : 0px;
|
||||
|
||||
height: text-node.preferred-height + 2 * Metrics.gap-2 + tool-row;
|
||||
background: message.role == ChatRole.user
|
||||
? Theme.accent-soft
|
||||
: is-tool ? Theme.bg-canvas
|
||||
: is-system ? transparent
|
||||
: Theme.bg-elevated;
|
||||
border-radius: Metrics.radius-md;
|
||||
border-width: is-tool ? 1px : 0px;
|
||||
border-color: message.tool_ok ? Theme.state-success : Theme.state-danger;
|
||||
|
||||
// 工具调用可视化(D4 要求:工具执行在会话里可见)
|
||||
if is-tool : AppIcon {
|
||||
x: Metrics.gap-2;
|
||||
y: Metrics.gap-2 + 1px;
|
||||
icon-size: 12px;
|
||||
kind: message.tool_ok ? IconKind.check : IconKind.error;
|
||||
tint: message.tool_ok ? Theme.state-success : Theme.state-danger;
|
||||
}
|
||||
if is-tool : UiText {
|
||||
x: Metrics.gap-2 + 16px;
|
||||
y: Metrics.gap-2;
|
||||
width: text-width - 16px;
|
||||
height: 14px;
|
||||
role: TextRole.caption;
|
||||
text: "工具 · " + message.tool_name;
|
||||
color: message.tool_ok ? Theme.state-success : Theme.state-danger;
|
||||
}
|
||||
|
||||
text-node := UiText {
|
||||
x: Metrics.gap-2;
|
||||
y: Metrics.gap-2 + tool-row;
|
||||
width: text-width;
|
||||
height: text-node.preferred-height;
|
||||
role: TextRole.body;
|
||||
text: message.text;
|
||||
wrap: word-wrap;
|
||||
overflow: elide;
|
||||
vertical-alignment: top;
|
||||
horizontal-alignment: message.role == ChatRole.user ? right : left;
|
||||
color: is-system ? Theme.fg-secondary : Theme.fg-primary;
|
||||
}
|
||||
|
||||
// 流式未收敛:末尾的 accent 光标块
|
||||
if message.streaming : Rectangle {
|
||||
x: 0;
|
||||
y: root.height - 10px;
|
||||
width: 8px;
|
||||
height: 10px;
|
||||
background: Theme.accent;
|
||||
}
|
||||
}
|
||||
|
||||
export component AiPanel inherits Rectangle {
|
||||
in property <[UiChatMessage]> messages;
|
||||
in-out property <bool> collapsed: false;
|
||||
/// true = 停在右侧栏形态;false = 已拆成独立全宽页
|
||||
in property <bool> docked: true;
|
||||
in property <bool> yolo: false;
|
||||
in property <bool> streaming: false;
|
||||
in property <string> endpoint-label: "llama.cpp · 本地";
|
||||
in-out property <string> draft: "";
|
||||
|
||||
callback toggle-collapsed();
|
||||
callback expand();
|
||||
callback dock();
|
||||
callback toggle-yolo();
|
||||
callback send(string);
|
||||
callback stop();
|
||||
|
||||
// 栏形态用 min/max 钉死宽度(布局里等价于固定宽度),页形态交给父容器铺满
|
||||
min-width: docked ? (collapsed ? Metrics.ai-rail-width : Metrics.ai-panel-width) : 0px;
|
||||
max-width: docked ? (collapsed ? Metrics.ai-rail-width : Metrics.ai-panel-width) : 100000px;
|
||||
horizontal-stretch: docked ? 0 : 1;
|
||||
height: 100%;
|
||||
background: Theme.bg-surface;
|
||||
|
||||
// 玻璃拟态底(D17 高级特性;关闭态不画东西)——排在内容之前,压在最底层
|
||||
GlassBase { card-radius: 0px; }
|
||||
|
||||
// 左边界线
|
||||
Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: 1px;
|
||||
height: root.height;
|
||||
background: Theme.stroke;
|
||||
}
|
||||
|
||||
// ── 折叠态:icon 轨 ─────────────────────────────────────────
|
||||
if docked && collapsed : VerticalLayout {
|
||||
x: 1px;
|
||||
width: root.width - 1px;
|
||||
height: root.height;
|
||||
padding-top: Metrics.gap-2;
|
||||
padding-bottom: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
AppIcon {
|
||||
kind: IconKind.ai;
|
||||
icon-size: 18px;
|
||||
tint: Theme.accent;
|
||||
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.toggle-collapsed(); }
|
||||
}
|
||||
}
|
||||
|
||||
AppIcon {
|
||||
kind: IconKind.expand;
|
||||
icon-size: 14px;
|
||||
tint: Theme.fg-secondary;
|
||||
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.expand(); }
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { vertical-stretch: 1; background: transparent; }
|
||||
|
||||
// YOLO 指示点:开启时实心 accent
|
||||
Rectangle {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: root.yolo ? Theme.accent : Theme.stroke-strong;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 展开态:栏内 / 独立页共用 ────────────────────────────────
|
||||
if !(docked && collapsed) : VerticalLayout {
|
||||
x: 1px;
|
||||
width: root.width - 1px;
|
||||
height: root.height;
|
||||
|
||||
// 头部
|
||||
Rectangle {
|
||||
height: 52px;
|
||||
background: transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-3;
|
||||
padding-right: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
AppIcon { kind: IconKind.ai; icon-size: 16px; tint: Theme.accent; }
|
||||
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
vertical-stretch: 1;
|
||||
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: "AI 助手";
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.endpoint-label;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
|
||||
MetroButton {
|
||||
kind: root.yolo ? ButtonKind.accent : ButtonKind.subtle;
|
||||
text: "YOLO";
|
||||
button-height: 24px;
|
||||
clicked => { root.toggle-yolo(); }
|
||||
}
|
||||
|
||||
if root.docked : MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.expand;
|
||||
icon-only: true;
|
||||
button-height: 24px;
|
||||
clicked => { root.expand(); }
|
||||
}
|
||||
if !root.docked : MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.sidebar;
|
||||
icon-only: true;
|
||||
button-height: 24px;
|
||||
clicked => { root.dock(); }
|
||||
}
|
||||
if root.docked : MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.chevronRight;
|
||||
icon-only: true;
|
||||
button-height: 24px;
|
||||
clicked => { root.toggle-collapsed(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: Theme.stroke; }
|
||||
|
||||
// 对话流(ListView 行虚拟化,research/01 已确认)
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
|
||||
for m in root.messages : ChatBubble {
|
||||
message: m;
|
||||
width: root.width - 2 * Metrics.gap-3;
|
||||
}
|
||||
}
|
||||
|
||||
if root.messages.length == 0 : UiText {
|
||||
role: TextRole.caption;
|
||||
text: "问点什么:装哪个版本、崩溃怎么修、帮我改设置…";
|
||||
horizontal-alignment: center;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: Theme.stroke; }
|
||||
|
||||
// 输入区
|
||||
Rectangle {
|
||||
height: 56px;
|
||||
background: transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
padding: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
input-box := Rectangle {
|
||||
horizontal-stretch: 1;
|
||||
vertical-stretch: 1;
|
||||
background: Theme.bg-input;
|
||||
border-radius: Metrics.radius-sm;
|
||||
border-width: 1px;
|
||||
border-color: input-field.focused ? Theme.accent : Theme.stroke;
|
||||
|
||||
input-field := PlainInput {
|
||||
text-padding: Metrics.gap-2;
|
||||
placeholder: "输入消息,Enter 发送";
|
||||
text <=> root.draft;
|
||||
accepted(t) => {
|
||||
if (t != "") {
|
||||
root.send(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MetroButton {
|
||||
kind: ButtonKind.accent;
|
||||
icon: root.streaming ? IconKind.stop : IconKind.send;
|
||||
icon-only: true;
|
||||
clicked => {
|
||||
if (root.streaming) {
|
||||
root.stop();
|
||||
} else if (root.draft != "") {
|
||||
root.send(root.draft);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// 徽标:MC 版本 / 加载器 / 已装 / 远古版 等短标记。Metro 做法是细边框小方块,不用药丸圆角。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
|
||||
export component Badge inherits Rectangle {
|
||||
in property <string> text: "";
|
||||
in property <color> tint: Theme.fg-secondary;
|
||||
in property <color> fill: transparent;
|
||||
|
||||
height: 18px;
|
||||
width: label.preferred-width + 2 * Metrics.gap-1 + 2px;
|
||||
background: fill;
|
||||
border-width: 1px;
|
||||
border-color: tint;
|
||||
border-radius: Metrics.radius-sm;
|
||||
|
||||
label := UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.text;
|
||||
color: root.tint;
|
||||
font-size: 11px;
|
||||
horizontal-alignment: center;
|
||||
x: Metrics.gap-1 + 1px;
|
||||
width: label.preferred-width;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// 玻璃拟态卡片的公共底座(09 §103:Slint 没有 backdrop-filter,用「预生成模糊背景层」替代)。
|
||||
//
|
||||
// 手法:Rust 侧把背景图降采样成一张极小的图(`Theme.bg-blur`),渲染时被平滑放大 → 天然模糊。
|
||||
// 卡片里把它按 `absolute-position` **反向偏移**画出来,于是卡片显示的是「自己这一块屏幕区域的
|
||||
// 模糊影像」,视觉上就是毛玻璃;再叠一层半透明面板色保证文字可读(对比度优先)。
|
||||
//
|
||||
// 关闭态(`Theme.glass == false` 或无背景图)不画任何东西:卡片保持 Metro 纯色观感。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
|
||||
export component GlassBase inherits Rectangle {
|
||||
/// 卡片圆角(跟随宿主卡片)
|
||||
in property <length> card-radius: Metrics.radius-md;
|
||||
/// 叠在模糊层上的半透明面板色(保证前景对比度)
|
||||
in property <color> tint: Theme.surface-solid;
|
||||
|
||||
out property <bool> active: Theme.glass && Theme.bg-blur.width > 0 && Theme.bg-image.width > 0;
|
||||
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: root.card-radius;
|
||||
clip: true;
|
||||
background: transparent;
|
||||
|
||||
if root.active : Image {
|
||||
// 整窗模糊层 + 反向偏移 = 只露出「卡片所在那一块」。
|
||||
// 必须用 `parent`(本组件自身)的绝对位置:用 `self` 会与自身 x 形成绑定环
|
||||
// (absolute-position 依赖 x,x 又依赖 absolute-position)。
|
||||
source: Theme.bg-blur;
|
||||
x: -parent.absolute-position.x;
|
||||
y: -parent.absolute-position.y;
|
||||
width: Theme.window-width;
|
||||
height: Theme.window-height;
|
||||
image-fit: cover;
|
||||
}
|
||||
|
||||
if root.active : Rectangle {
|
||||
// 暗化层要**重画一次**:模糊层在卡片内部、盖在窗口的暗化层之上,
|
||||
// 不补这一层的话玻璃卡片会比周围亮一大截(05 截图验收时的真实问题)。
|
||||
background: rgba(0, 0, 0, Theme.bg-dim);
|
||||
border-radius: root.card-radius;
|
||||
}
|
||||
|
||||
if root.active : Rectangle {
|
||||
// 玻璃染色:面板底色 55% 不透明,字压得住背景(对比度优先于「更透」)
|
||||
background: root.tint.with-alpha(0.55);
|
||||
border-radius: root.card-radius;
|
||||
}
|
||||
|
||||
if root.active : Rectangle {
|
||||
// 上缘一道细高光,玻璃的「厚度感」
|
||||
y: 0;
|
||||
height: 1px;
|
||||
width: root.width;
|
||||
background: Theme.stroke.with-alpha(0.35);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
// 图标:18×18 viewbox 的矢量绘制(Metro 要求线性几何图标,不用 emoji/位图)。
|
||||
// 只用 M/L/Q/Z 命令 + 直线,避免依赖字体字形;描边图标 stroke,实心图标 fill。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
|
||||
export enum IconKind {
|
||||
instances,
|
||||
download,
|
||||
logs,
|
||||
settings,
|
||||
ai,
|
||||
play,
|
||||
stop,
|
||||
search,
|
||||
plus,
|
||||
close,
|
||||
minimize,
|
||||
maximize,
|
||||
chevronLeft,
|
||||
chevronRight,
|
||||
chevronDown,
|
||||
expand,
|
||||
send,
|
||||
check,
|
||||
warn,
|
||||
error,
|
||||
more,
|
||||
sidebar,
|
||||
restore,
|
||||
}
|
||||
|
||||
export component AppIcon inherits Rectangle {
|
||||
in property <IconKind> kind: IconKind.instances;
|
||||
in property <color> tint: Theme.fg-secondary;
|
||||
in property <length> icon-size: 18px;
|
||||
|
||||
width: icon-size;
|
||||
height: icon-size;
|
||||
background: transparent;
|
||||
|
||||
if kind == IconKind.instances : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 2 2 L 8 2 L 8 8 L 2 8 Z M 10 2 L 16 2 L 16 8 L 10 8 Z M 2 10 L 8 10 L 8 16 L 2 16 Z M 10 10 L 16 10 L 16 16 L 10 16 Z";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
if kind == IconKind.download : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 9 2 L 9 11 M 4 7 L 9 12 L 14 7 M 3 15 L 15 15";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
|
||||
}
|
||||
if kind == IconKind.logs : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 3 4 L 15 4 M 3 9 L 15 9 M 3 14 L 11 14";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
|
||||
}
|
||||
if kind == IconKind.settings : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 3 5 L 15 5 M 3 9 L 15 9 M 3 13 L 15 13";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
if kind == IconKind.settings : Rectangle {
|
||||
x: 5px;
|
||||
width: 5px; height: 5px; y: 3px;
|
||||
border-radius: 2.5px; background: root.tint;
|
||||
}
|
||||
if kind == IconKind.settings : Rectangle {
|
||||
x: 10px; y: 7px; width: 5px; height: 5px;
|
||||
border-radius: 2.5px; background: root.tint;
|
||||
}
|
||||
if kind == IconKind.settings : Rectangle {
|
||||
x: 3px; y: 11px; width: 5px; height: 5px;
|
||||
border-radius: 2.5px; background: root.tint;
|
||||
}
|
||||
if kind == IconKind.ai : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 9 1.5 L 10.7 7.3 L 16.5 9 L 10.7 10.7 L 9 16.5 L 7.3 10.7 L 1.5 9 L 7.3 7.3 Z";
|
||||
fill: root.tint; stroke: transparent; stroke-width: 1px;
|
||||
}
|
||||
if kind == IconKind.play : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 5 3 L 15 9 L 5 15 Z";
|
||||
fill: root.tint; stroke: transparent; stroke-width: 1px;
|
||||
}
|
||||
if kind == IconKind.stop : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 5 5 L 13 5 L 13 13 L 5 13 Z";
|
||||
fill: root.tint; stroke: transparent; stroke-width: 1px;
|
||||
}
|
||||
if kind == IconKind.search : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 8 3 Q 13 3 13 8 Q 13 13 8 13 Q 3 13 3 8 Q 3 3 8 3 Z M 11.5 11.5 L 16 16";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.5px;
|
||||
}
|
||||
if kind == IconKind.plus : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 9 3 L 9 15 M 3 9 L 15 9";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.8px;
|
||||
}
|
||||
if kind == IconKind.close : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 4 4 L 14 14 M 14 4 L 4 14";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
if kind == IconKind.minimize : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 4 9 L 14 9";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
if kind == IconKind.maximize : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 4.5 4.5 L 13.5 4.5 L 13.5 13.5 L 4.5 13.5 Z";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.2px;
|
||||
}
|
||||
if kind == IconKind.chevronLeft : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 11 3 L 6 9 L 11 15";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
|
||||
}
|
||||
if kind == IconKind.chevronRight : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 7 3 L 12 9 L 7 15";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
|
||||
}
|
||||
if kind == IconKind.chevronDown : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 3 7 L 9 13 L 15 7";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
|
||||
}
|
||||
if kind == IconKind.expand : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 3 7 L 3 3 L 7 3 M 11 3 L 15 3 L 15 7 M 15 11 L 15 15 L 11 15 M 7 15 L 3 15 L 3 11";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
if kind == IconKind.send : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 2 9 L 16 9 M 11 4 L 16 9 L 11 14";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
|
||||
}
|
||||
if kind == IconKind.check : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 3 9 L 7 13 L 15 4";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.8px;
|
||||
}
|
||||
if kind == IconKind.warn : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 9 2 L 16 15 L 2 15 Z M 9 6.5 L 9 10.5";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
if kind == IconKind.error : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 9 2 Q 16 2 16 9 Q 16 16 9 16 Q 2 16 2 9 Q 2 2 9 2 Z M 9 5 L 9 10";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.5px;
|
||||
}
|
||||
if kind == IconKind.more : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 4 7 L 6 7 L 6 9 L 4 9 Z M 8 7 L 10 7 L 10 9 L 8 9 Z M 12 7 L 14 7 L 14 9 L 12 9 Z";
|
||||
fill: root.tint; stroke: transparent; stroke-width: 1px;
|
||||
}
|
||||
if kind == IconKind.sidebar : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 3 4 L 15 4 L 15 14 L 3 14 Z M 7 4 L 7 14";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
|
||||
}
|
||||
// 还原(已最大化时的标题栏按钮):两层叠放方框
|
||||
if kind == IconKind.restore : Path {
|
||||
width: root.width; height: root.height;
|
||||
viewbox-width: 18; viewbox-height: 18;
|
||||
commands: "M 6 3 L 15 3 L 15 12 M 3 6 L 12 6 L 12 15 L 3 15 Z";
|
||||
fill: transparent; stroke: root.tint; stroke-width: 1.2px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// 排版角色封装:所有文字都走 UiText,不在页面里散落 font-size/font-family 字面量。
|
||||
// 角色 → 字号/字重/默认前景色由 tokens.slint 的 ramp 决定;外部赋值可覆盖(例如强调色标题)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
|
||||
export enum TextRole {
|
||||
display,
|
||||
title,
|
||||
subtitle,
|
||||
body,
|
||||
bodyStrong,
|
||||
caption,
|
||||
mono,
|
||||
monoSmall,
|
||||
}
|
||||
|
||||
export component UiText inherits Text {
|
||||
in property <TextRole> role: TextRole.body;
|
||||
|
||||
color: role == TextRole.caption ? Theme.fg-secondary : Theme.fg-primary;
|
||||
font-family: (role == TextRole.mono || role == TextRole.monoSmall)
|
||||
? Theme.font-family-mono
|
||||
: Theme.font-family;
|
||||
font-size: (role == TextRole.display) ? Theme.font-size-display
|
||||
: (role == TextRole.title) ? Theme.font-size-title
|
||||
: (role == TextRole.subtitle) ? Theme.font-size-subtitle
|
||||
: (role == TextRole.caption || role == TextRole.monoSmall) ? Theme.font-size-caption
|
||||
: Theme.font-size-body;
|
||||
font-weight: (role == TextRole.bodyStrong || role == TextRole.title || role == TextRole.display)
|
||||
? 600
|
||||
: 400;
|
||||
vertical-alignment: center;
|
||||
wrap: no-wrap;
|
||||
overflow: elide;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// 左侧主导航(D16 §1):图标+文字,选中项 accent 色块;可折叠成纯图标窄条(偏好记忆)。
|
||||
// 折叠宽度/展开宽度取 Metrics,动画时长取 Theme.motion-normal。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { RouteKind } from "../models.slint";
|
||||
import { UiText, TextRole } from "label.slint";
|
||||
import { AppIcon, IconKind } from "icons.slint";
|
||||
|
||||
component NavItem inherits Rectangle {
|
||||
in property <IconKind> icon: IconKind.instances;
|
||||
in property <string> label: "";
|
||||
in property <bool> active: false;
|
||||
in property <bool> collapsed: false;
|
||||
callback clicked();
|
||||
|
||||
height: root.collapsed ? 48px : 64px;
|
||||
background: root.active
|
||||
? Theme.accent-soft
|
||||
: touch.has-hover ? Theme.bg-hover : transparent;
|
||||
animate background { duration: Theme.motion-fast; }
|
||||
|
||||
// 选中态:左侧 accent 竖条(Metro 侧栏语义)
|
||||
Rectangle {
|
||||
visible: root.active;
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: 3px;
|
||||
height: root.height;
|
||||
background: Theme.accent;
|
||||
}
|
||||
|
||||
AppIcon {
|
||||
kind: root.icon;
|
||||
icon-size: 20px;
|
||||
x: (root.width - self.width) / 2;
|
||||
y: root.collapsed ? (root.height - self.height) / 2 : 12px;
|
||||
tint: root.active ? Theme.accent : Theme.fg-secondary;
|
||||
}
|
||||
|
||||
UiText {
|
||||
visible: !root.collapsed;
|
||||
role: TextRole.caption;
|
||||
text: root.label;
|
||||
color: root.active ? Theme.accent : Theme.fg-secondary;
|
||||
horizontal-alignment: center;
|
||||
x: 0;
|
||||
y: 38px;
|
||||
width: root.width;
|
||||
}
|
||||
|
||||
touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
|
||||
accessible-role: button;
|
||||
accessible-label: root.label;
|
||||
}
|
||||
|
||||
export component Nav inherits Rectangle {
|
||||
in property <RouteKind> active: RouteKind.instances;
|
||||
in-out property <bool> collapsed: false;
|
||||
in property <string> account-name: "未登录";
|
||||
in property <color> account-hue: #5C2D91;
|
||||
in property <string> account-initial: "?";
|
||||
callback navigate(RouteKind);
|
||||
callback toggle-collapsed();
|
||||
callback account-clicked();
|
||||
|
||||
width: collapsed ? Metrics.nav-collapsed-width : Metrics.nav-expanded-width;
|
||||
height: 100%;
|
||||
background: Theme.bg-surface;
|
||||
animate width { duration: Theme.motion-normal; easing: ease-in-out; }
|
||||
|
||||
// 右边界线
|
||||
Rectangle {
|
||||
x: root.width - 1px;
|
||||
y: 0;
|
||||
width: 1px;
|
||||
height: root.height;
|
||||
background: Theme.stroke;
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
x: 0;
|
||||
y: Metrics.gap-2;
|
||||
width: root.width;
|
||||
height: root.height - Metrics.gap-2 - Metrics.gap-2;
|
||||
|
||||
NavItem {
|
||||
icon: IconKind.instances;
|
||||
label: "实例";
|
||||
active: root.active == RouteKind.instances || root.active == RouteKind.detail;
|
||||
collapsed: root.collapsed;
|
||||
clicked => { root.navigate(RouteKind.instances); }
|
||||
}
|
||||
NavItem {
|
||||
icon: IconKind.download;
|
||||
label: "下载";
|
||||
active: root.active == RouteKind.download;
|
||||
collapsed: root.collapsed;
|
||||
clicked => { root.navigate(RouteKind.download); }
|
||||
}
|
||||
NavItem {
|
||||
icon: IconKind.logs;
|
||||
label: "日志";
|
||||
active: root.active == RouteKind.logs;
|
||||
collapsed: root.collapsed;
|
||||
clicked => { root.navigate(RouteKind.logs); }
|
||||
}
|
||||
NavItem {
|
||||
icon: IconKind.settings;
|
||||
label: "设置";
|
||||
active: root.active == RouteKind.settings;
|
||||
collapsed: root.collapsed;
|
||||
clicked => { root.navigate(RouteKind.settings); }
|
||||
}
|
||||
|
||||
Rectangle { vertical-stretch: 1; background: transparent; }
|
||||
|
||||
// 底部:账户头像(点击进设置·账户)
|
||||
Rectangle {
|
||||
height: 56px;
|
||||
background: account-touch.has-hover ? Theme.bg-hover : transparent;
|
||||
|
||||
Rectangle {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 14px;
|
||||
background: root.account-hue;
|
||||
x: (root.width - self.width) / 2;
|
||||
y: 8px;
|
||||
|
||||
UiText {
|
||||
text: root.account-initial;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: Theme.fg-on-accent;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
|
||||
UiText {
|
||||
visible: !root.collapsed;
|
||||
role: TextRole.caption;
|
||||
text: root.account-name;
|
||||
horizontal-alignment: center;
|
||||
x: 0;
|
||||
y: 38px;
|
||||
width: root.width;
|
||||
}
|
||||
|
||||
account-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.account-clicked(); }
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠开关(偏好由 Rust 侧持久化到 ui.nav.collapsed)
|
||||
Rectangle {
|
||||
height: 40px;
|
||||
background: toggle-touch.has-hover ? Theme.bg-hover : transparent;
|
||||
|
||||
AppIcon {
|
||||
kind: root.collapsed ? IconKind.chevronRight : IconKind.chevronLeft;
|
||||
icon-size: 16px;
|
||||
x: (root.width - self.width) / 2;
|
||||
y: (root.height - self.height) / 2;
|
||||
tint: Theme.fg-secondary;
|
||||
}
|
||||
|
||||
toggle-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.toggle-collapsed(); }
|
||||
}
|
||||
|
||||
accessible-role: button;
|
||||
accessible-label: root.collapsed ? "展开导航栏" : "折叠导航栏";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// 启动进度环:磁贴「启动中」状态用(下载/校验/启动三个阶段共用一个环)。
|
||||
// 用 std-widgets 的 ProgressIndicator:progress <= 0 时转为不确定态(转圈)。
|
||||
// P1 若要完全贴合 Metro 强调色,需自绘弧线(Slint 无 arc 命令,得用旋转遮罩法)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { ProgressIndicator } from "std-widgets.slint";
|
||||
|
||||
export component ProgressRing inherits Rectangle {
|
||||
/// 0.0~1.0;<= 0 表示未知进度
|
||||
in property <float> progress: 0;
|
||||
in property <length> ring-size: 28px;
|
||||
|
||||
width: ring-size;
|
||||
height: ring-size;
|
||||
background: transparent;
|
||||
|
||||
ProgressIndicator {
|
||||
width: root.ring-size;
|
||||
height: root.ring-size;
|
||||
progress: root.progress;
|
||||
indeterminate: root.progress <= 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// 实例磁贴(G1):图标 / 名字 / MC 版本徽标 / 加载器徽标 / 最后游玩 / 大启动键 + 设置键。
|
||||
// 三档尺寸由 Metrics.tile-* 决定(小磁贴藏徽标与时间,只留名字+启动);
|
||||
// 启动中把底部按钮行替换成「进度环 + 阶段文案 + 停止」。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiTile, RuntimePhase, LoaderKind } from "../models.slint";
|
||||
import { UiText, TextRole } from "label.slint";
|
||||
import { AppIcon, IconKind } from "icons.slint";
|
||||
import { Badge } from "badge.slint";
|
||||
import { ProgressRing } from "progress-ring.slint";
|
||||
import { GlassBase } from "glass.slint";
|
||||
import { MetroButton, ButtonKind } from "../widgets/button.slint";
|
||||
|
||||
component TileIcon inherits Rectangle {
|
||||
in property <UiTile> data;
|
||||
in property <length> box-size: 44px;
|
||||
|
||||
width: box-size;
|
||||
height: box-size;
|
||||
border-radius: Metrics.radius-md;
|
||||
background: root.data.hue;
|
||||
|
||||
if root.data.icon.width > 0 : Image {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: root.width;
|
||||
height: root.height;
|
||||
source: root.data.icon;
|
||||
image-fit: cover;
|
||||
}
|
||||
if root.data.icon.width <= 0 : UiText {
|
||||
text: root.data.initial;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: Theme.fg-on-accent;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
|
||||
export component InstanceTile inherits Rectangle {
|
||||
in property <UiTile> data;
|
||||
in property <bool> compact: false;
|
||||
callback open();
|
||||
callback launch();
|
||||
callback configure();
|
||||
/// 启动中/运行中的停止键(dispatch StopInstance)
|
||||
callback stop();
|
||||
|
||||
height: Metrics.tile-height;
|
||||
background: touch.has-hover ? Theme.bg-elevated : Theme.bg-surface;
|
||||
border-radius: Metrics.radius-md;
|
||||
border-width: 1px;
|
||||
border-color: root.data.phase == RuntimePhase.running ? Theme.accent : Theme.stroke;
|
||||
drop-shadow-blur: touch.has-hover ? 12px : 0px;
|
||||
drop-shadow-color: Theme.shadow;
|
||||
drop-shadow-offset-y: 2px;
|
||||
animate background { duration: Theme.motion-fast; }
|
||||
animate drop-shadow-blur { duration: Theme.motion-normal; }
|
||||
|
||||
// 玻璃拟态底(关闭态什么都不画,卡片就是 Metro 纯色);必须排在最前,否则盖住 accent 细线
|
||||
GlassBase {
|
||||
card-radius: root.border-radius;
|
||||
}
|
||||
|
||||
// 运行中:顶部 accent 细线(Metro 色块语义)
|
||||
Rectangle {
|
||||
visible: root.data.phase == RuntimePhase.running;
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: root.width;
|
||||
height: 2px;
|
||||
background: Theme.accent;
|
||||
}
|
||||
|
||||
// 磁贴主体点击 → 实例详情(G4);按钮的 TouchArea 后声明,命中优先
|
||||
touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.open(); }
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
padding: Metrics.gap-3;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
HorizontalLayout {
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
TileIcon {
|
||||
data: root.data;
|
||||
box-size: Metrics.tile-icon-size;
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
spacing: 2px;
|
||||
vertical-stretch: 1;
|
||||
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: root.data.name;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.last_played;
|
||||
visible: !root.compact;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
visible: !root.compact;
|
||||
spacing: Metrics.gap-1;
|
||||
|
||||
Badge {
|
||||
text: root.data.mc_version;
|
||||
tint: Theme.fg-secondary;
|
||||
}
|
||||
Badge {
|
||||
text: root.data.loader_label;
|
||||
tint: root.data.loader == LoaderKind.vanilla ? Theme.fg-secondary : Theme.accent;
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { vertical-stretch: 1; background: transparent; }
|
||||
|
||||
// 空闲/失败:大启动键 + 设置键
|
||||
HorizontalLayout {
|
||||
visible: root.data.phase == RuntimePhase.idle || root.data.phase == RuntimePhase.failed;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
MetroButton {
|
||||
kind: ButtonKind.accent;
|
||||
text: root.data.phase == RuntimePhase.failed ? "重试" : "启动";
|
||||
show-icon: true;
|
||||
icon: IconKind.play;
|
||||
grow: true;
|
||||
clicked => { root.launch(); }
|
||||
}
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.settings;
|
||||
icon-only: true;
|
||||
clicked => { root.configure(); }
|
||||
}
|
||||
}
|
||||
|
||||
// 启动中:进度环 + 阶段文案 + 停止
|
||||
HorizontalLayout {
|
||||
visible: root.data.phase == RuntimePhase.downloading
|
||||
|| root.data.phase == RuntimePhase.verifying
|
||||
|| root.data.phase == RuntimePhase.launching;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
ProgressRing {
|
||||
progress: root.data.progress;
|
||||
ring-size: 22px;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.phase_label;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.stop;
|
||||
icon-only: true;
|
||||
clicked => { root.stop(); }
|
||||
}
|
||||
}
|
||||
|
||||
// 运行中:状态点 + 停止
|
||||
HorizontalLayout {
|
||||
visible: root.data.phase == RuntimePhase.running;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
Rectangle {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 4px;
|
||||
background: Theme.state-success;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: "运行中";
|
||||
color: Theme.state-success;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.stop;
|
||||
icon-only: true;
|
||||
clicked => { root.stop(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// 自绘无边框标题栏(D16 §1):Metro 一体感 + accent 顶线。
|
||||
// 拖拽/最大化/最小化/关闭只发回调,原生窗口操作由 main.rs 接到 Slint Window 平台上
|
||||
// (Slint DSL 内无法移动原生窗口)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiText, TextRole } from "label.slint";
|
||||
import { AppIcon, IconKind } from "icons.slint";
|
||||
|
||||
component WindowButton inherits Rectangle {
|
||||
in property <IconKind> icon: IconKind.minimize;
|
||||
/// 关闭键:hover 用 Metro 红底白字
|
||||
in property <bool> danger: false;
|
||||
callback clicked();
|
||||
|
||||
width: Metrics.titlebar-button-width;
|
||||
height: Metrics.titlebar-height;
|
||||
background: touch.pressed
|
||||
? (danger ? Theme.state-danger-hover : Theme.bg-pressed)
|
||||
: touch.has-hover ? (danger ? Theme.state-danger : Theme.bg-hover) : transparent;
|
||||
animate background { duration: Theme.motion-fast; }
|
||||
|
||||
AppIcon {
|
||||
kind: root.icon;
|
||||
icon-size: 12px;
|
||||
x: (root.width - self.width) / 2;
|
||||
y: (root.height - self.height) / 2;
|
||||
tint: root.danger && touch.has-hover ? Theme.fg-on-accent : Theme.fg-primary;
|
||||
}
|
||||
|
||||
touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
}
|
||||
|
||||
export component TitleBar inherits Rectangle {
|
||||
in property <string> title: "Unlucky Launcher";
|
||||
in property <string> subtitle: "";
|
||||
in property <bool> maximized: false;
|
||||
|
||||
callback toggle-maximize();
|
||||
callback minimize();
|
||||
callback request-close();
|
||||
|
||||
height: Metrics.titlebar-height;
|
||||
background: Theme.bg-titlebar;
|
||||
|
||||
// accent 顶线(Metro 强调色贯穿)
|
||||
Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: root.width;
|
||||
height: Metrics.accent-line;
|
||||
background: Theme.accent;
|
||||
}
|
||||
|
||||
// 拖拽区:交给原生 `WindowMoveArea`(Slint 1.18 内置,拖过阈值才移动窗口,
|
||||
// 并保持子元素可交互)。只覆盖左侧,右侧三个窗口按钮留出来。
|
||||
// 平台不支持「系统级窗口移动」时该元素退化为无操作(Qt/部分 Wayland 组合),
|
||||
// winit on Windows/macOS/X11 可用——Win7 落在这条路上。
|
||||
WindowMoveArea {
|
||||
x: 0;
|
||||
y: Metrics.accent-line;
|
||||
width: root.width - 3 * Metrics.titlebar-button-width;
|
||||
height: root.height - Metrics.accent-line;
|
||||
}
|
||||
|
||||
// 应用标记 + 标题
|
||||
HorizontalLayout {
|
||||
x: Metrics.gap-3;
|
||||
y: Metrics.accent-line;
|
||||
width: root.width - 3 * Metrics.titlebar-button-width - 2 * Metrics.gap-3;
|
||||
height: root.height - Metrics.accent-line;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
Rectangle {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: Metrics.radius-sm;
|
||||
background: Theme.accent;
|
||||
UiText {
|
||||
text: "U";
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: Theme.fg-on-accent;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.title;
|
||||
font-weight: 600;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.subtitle;
|
||||
color: Theme.fg-secondary;
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
x: root.width - 3 * Metrics.titlebar-button-width;
|
||||
y: Metrics.accent-line;
|
||||
width: 3 * Metrics.titlebar-button-width;
|
||||
height: root.height - Metrics.accent-line;
|
||||
spacing: 0px;
|
||||
|
||||
WindowButton {
|
||||
icon: IconKind.minimize;
|
||||
clicked => { root.minimize(); }
|
||||
}
|
||||
WindowButton {
|
||||
icon: root.maximized ? IconKind.restore : IconKind.maximize;
|
||||
clicked => { root.toggle-maximize(); }
|
||||
}
|
||||
WindowButton {
|
||||
icon: IconKind.close;
|
||||
danger: true;
|
||||
clicked => { root.request-close(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
// Unlucky-Launcher · 主入口窗口(P0 阶段 B 接线)
|
||||
//
|
||||
// 布局真相源:DevDocs/PlanDoc/09-ui-layout.md(D16:左侧固定导航 + 右侧 AI 常驻栏 + 磁贴实例页)。
|
||||
// 本文件只做三件事:①无边框窗口与字体/缩放口径 ②实例化 `AppShell` ③把 AppShell 的全部
|
||||
// 属性/回调原样上抛给 src/main.rs(Slint 只能从根组件访问属性与回调,所以这层转发是必需的)。
|
||||
//
|
||||
// 与 M11 骨架的关系:M11 的 `Metro` palette global(accent/surface/sidebar/tile/text/muted/pad/gap)
|
||||
// 已由 `theme/tokens.slint` 的 `Theme` 继承并扩展——同一「palette global 令牌化」思路,但多了
|
||||
// 亮/暗双套色板(LightPalette/DarkPalette)、主题三态解析、排版 ramp 与字体栈;M11 的占位
|
||||
// NavItem/Tile 组件由 `components/nav.slint` 与 `components/tile.slint` 取代,占位内核不再保留。
|
||||
|
||||
import { AppShell } from "shell.slint";
|
||||
import { Theme } from "theme/tokens.slint";
|
||||
import { Metrics } from "theme/metrics.slint";
|
||||
import {
|
||||
RouteKind, TileSize, InstanceView, SettingSection, DownloadCategory, ThemeMode, BgFillKind,
|
||||
UiTile, UiVersion, UiLogSession, UiLogLine, UiDiagnosis, UiChatMessage, UiDialog, UiToast,
|
||||
} from "models.slint";
|
||||
|
||||
export component MainWindow inherits Window {
|
||||
title: root.app-title;
|
||||
// 默认尺寸取 D16 线框口径;最小尺寸保证 5 列磁贴 + 导航 + AI 栏不挤压
|
||||
width: 1180px;
|
||||
height: 760px;
|
||||
// Metro 一体感:自绘标题栏(components/titlebar.slint)
|
||||
no-frame: true;
|
||||
// 无边框窗口必须显式给边缘缩放热区,否则用户无法拖拽改窗口大小
|
||||
resize-border-width: 4px;
|
||||
default-font-family: Theme.font-family;
|
||||
default-font-size: Theme.font-size-body;
|
||||
// 窗口自身底色必须**不透明**:面板半透明度(panel-alpha)只该透出背景图,不该透到桌面
|
||||
background: Theme.canvas-solid;
|
||||
|
||||
// ── 从 main.rs 灌入的状态 ───────────────────────────────────
|
||||
in-out property <string> app-title: "Unlucky Launcher";
|
||||
in property <RouteKind> route: RouteKind.instances;
|
||||
|
||||
in property <bool> nav-collapsed: false;
|
||||
in property <string> account-name: "未登录";
|
||||
in property <string> account-initial: "?";
|
||||
in property <color> account-hue: #5C2D91;
|
||||
|
||||
in-out property <bool> ai-collapsed: false;
|
||||
in property <[UiChatMessage]> ai-messages;
|
||||
in property <bool> ai-streaming: false;
|
||||
in-out property <bool> yolo: false;
|
||||
in property <string> ai-endpoint-label: "llama.cpp · 本地";
|
||||
in-out property <string> ai-draft: "";
|
||||
|
||||
in property <[UiTile]> tiles;
|
||||
in property <[UiTile]> running-tiles;
|
||||
in property <[UiVersion]> versions;
|
||||
in property <[UiLogSession]> log-sessions;
|
||||
in property <[UiLogLine]> log-lines;
|
||||
in property <UiDiagnosis> diagnosis;
|
||||
in property <bool> has-diagnosis: false;
|
||||
in property <string> selected-session: "";
|
||||
|
||||
in-out property <TileSize> tile-size: TileSize.medium;
|
||||
in-out property <InstanceView> instance-view: InstanceView.tiles;
|
||||
in-out property <string> instance-query: "";
|
||||
in-out property <SettingSection> settings-section: SettingSection.general;
|
||||
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
|
||||
// 系统主题(M41):0 = 未知(回落 Slint 后端),1 = 浅色,2 = 深色
|
||||
in property <int> system-theme: 0;
|
||||
/// 后端是否认得系统主题(`false` 时 Rust 侧才需要轮询探测兜底)
|
||||
out property <bool> system-theme-known: Theme.system-theme-known;
|
||||
|
||||
// ── 外观(高级)P1 四件(09 §101-104,出厂全部关闭)──────────────
|
||||
// 图片由 Rust 灌入(`in`);其余是 in-out:设置页控件会写回,回调里再原样上抛给 Rust。
|
||||
in property <image> background-image;
|
||||
in property <image> background-blur;
|
||||
in-out property <bool> bg-image-enabled: false;
|
||||
in-out property <string> bg-image: "";
|
||||
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
|
||||
in-out property <float> bg-dim: 0.35;
|
||||
in-out property <float> panel-alpha: 1.0;
|
||||
in-out property <bool> glass: false;
|
||||
in-out property <color> accent-color: transparent;
|
||||
/// 设置页「强调色(十六进制)」输入框的内容(Rust 写入规范化后的值)
|
||||
in-out property <string> accent-hex: "";
|
||||
/// 强调色输入是否非法(设置页亮 warn 行)
|
||||
in-out property <bool> accent-invalid: false;
|
||||
in-out property <DownloadCategory> download-category: DownloadCategory.release;
|
||||
in-out property <bool> download-installed-only: false;
|
||||
in-out property <string> download-query: "";
|
||||
|
||||
in property <UiDialog> dialog;
|
||||
in property <bool> dialog-open: false;
|
||||
in property <int> dialog-queued: 0;
|
||||
in property <[UiToast]> toasts;
|
||||
|
||||
// 主题/外观:handler 里整体赋值给 `Theme` 全局(Slint 不允许在组件体内给全局属性做绑定,
|
||||
// 但允许在回调/init 里赋值)。auto 分支由 Theme 自己读系统的 Palette.color-scheme。
|
||||
init => {
|
||||
Theme.theme-mode = root.theme-mode;
|
||||
Theme.system-theme = root.system-theme;
|
||||
Theme.bg-image = root.background-image;
|
||||
Theme.bg-blur = root.background-blur;
|
||||
Theme.bg-dim = root.bg-dim;
|
||||
Theme.panel-alpha = root.panel-alpha;
|
||||
Theme.glass = root.glass;
|
||||
Theme.accent-override = root.accent-color;
|
||||
}
|
||||
changed theme-mode => { Theme.theme-mode = root.theme-mode; }
|
||||
changed system-theme => { Theme.system-theme = root.system-theme; }
|
||||
changed background-image => { Theme.bg-image = root.background-image; }
|
||||
changed background-blur => { Theme.bg-blur = root.background-blur; }
|
||||
changed bg-dim => { Theme.bg-dim = root.bg-dim; }
|
||||
changed panel-alpha => { Theme.panel-alpha = root.panel-alpha; }
|
||||
changed glass => { Theme.glass = root.glass; }
|
||||
changed accent-color => { Theme.accent-override = root.accent-color; }
|
||||
|
||||
// ── 用户操作(main.rs 转成 AppCommand 或纯 UI 偏好)──────────────
|
||||
callback toggle-maximize();
|
||||
callback minimize();
|
||||
callback request-close();
|
||||
|
||||
callback navigate(RouteKind);
|
||||
callback toggle-nav();
|
||||
callback toggle-ai();
|
||||
callback expand-ai();
|
||||
callback dock-ai();
|
||||
callback toggle-yolo();
|
||||
callback ai-send(string);
|
||||
callback ai-stop();
|
||||
|
||||
callback instance-launch(string);
|
||||
callback instance-configure(string);
|
||||
callback instance-stop(string);
|
||||
callback instance-open(string);
|
||||
callback new-instance();
|
||||
callback instance-view-changed(InstanceView);
|
||||
callback tile-size-changed(TileSize);
|
||||
callback instance-query-changed(string);
|
||||
|
||||
callback download-category-changed(DownloadCategory);
|
||||
callback download-install(string);
|
||||
callback installed-only-changed(bool);
|
||||
callback download-query-changed(string);
|
||||
callback ancient-help();
|
||||
|
||||
callback log-select(string);
|
||||
callback log-ask-ai(string);
|
||||
callback log-apply-fix();
|
||||
|
||||
callback settings-section-changed(SettingSection);
|
||||
callback theme-changed(ThemeMode);
|
||||
callback bg-image-enabled-changed(bool);
|
||||
callback bg-image-changed(string);
|
||||
callback bg-fill-changed(BgFillKind);
|
||||
callback bg-dim-changed(float);
|
||||
callback panel-alpha-changed(float);
|
||||
callback glass-changed(bool);
|
||||
callback accent-color-changed(string);
|
||||
callback accent-swatch-picked(int);
|
||||
callback yolo-changed(bool);
|
||||
callback mcp-changed(bool);
|
||||
callback ai-endpoint-changed(int);
|
||||
|
||||
callback dialog-primary();
|
||||
callback dialog-secondary();
|
||||
callback dialog-dismissed();
|
||||
callback toast-dismissed(string);
|
||||
|
||||
AppShell {
|
||||
app-title: root.app-title;
|
||||
// 直接复用 Window 的内建 `maximized`(后端随窗口状态更新,无需自建属性)
|
||||
maximized: root.maximized;
|
||||
route: root.route;
|
||||
nav-collapsed: root.nav-collapsed;
|
||||
account-name: root.account-name;
|
||||
account-initial: root.account-initial;
|
||||
account-hue: root.account-hue;
|
||||
ai-collapsed: root.ai-collapsed;
|
||||
ai-messages: root.ai-messages;
|
||||
ai-streaming: root.ai-streaming;
|
||||
yolo: root.yolo;
|
||||
ai-endpoint-label: root.ai-endpoint-label;
|
||||
ai-draft: root.ai-draft;
|
||||
tiles: root.tiles;
|
||||
running-tiles: root.running-tiles;
|
||||
versions: root.versions;
|
||||
log-sessions: root.log-sessions;
|
||||
log-lines: root.log-lines;
|
||||
diagnosis: root.diagnosis;
|
||||
has-diagnosis: root.has-diagnosis;
|
||||
selected-session: root.selected-session;
|
||||
tile-size: root.tile-size;
|
||||
instance-view: root.instance-view;
|
||||
instance-query: root.instance-query;
|
||||
settings-section: root.settings-section;
|
||||
theme-mode: root.theme-mode;
|
||||
bg-image-enabled: root.bg-image-enabled;
|
||||
bg-image: root.bg-image;
|
||||
bg-fill: root.bg-fill;
|
||||
bg-dim: root.bg-dim;
|
||||
panel-alpha: root.panel-alpha;
|
||||
glass: root.glass;
|
||||
accent-hex: root.accent-hex;
|
||||
accent-invalid: root.accent-invalid;
|
||||
download-category: root.download-category;
|
||||
download-installed-only: root.download-installed-only;
|
||||
download-query: root.download-query;
|
||||
dialog: root.dialog;
|
||||
dialog-open: root.dialog-open;
|
||||
dialog-queued: root.dialog-queued;
|
||||
toasts: root.toasts;
|
||||
|
||||
toggle-maximize => { root.toggle-maximize(); }
|
||||
minimize => { root.minimize(); }
|
||||
request-close => { root.request-close(); }
|
||||
|
||||
navigate(r) => { root.navigate(r); }
|
||||
toggle-nav => { root.toggle-nav(); }
|
||||
toggle-ai => { root.toggle-ai(); }
|
||||
expand-ai => { root.expand-ai(); }
|
||||
dock-ai => { root.dock-ai(); }
|
||||
toggle-yolo => { root.toggle-yolo(); }
|
||||
ai-send(text) => { root.ai-send(text); }
|
||||
ai-stop => { root.ai-stop(); }
|
||||
|
||||
instance-launch(id) => { root.instance-launch(id); }
|
||||
instance-configure(id) => { root.instance-configure(id); }
|
||||
instance-stop(id) => { root.instance-stop(id); }
|
||||
instance-open(id) => { root.instance-open(id); }
|
||||
new-instance => { root.new-instance(); }
|
||||
instance-view-changed(view) => {
|
||||
root.instance-view = view;
|
||||
root.instance-view-changed(view);
|
||||
}
|
||||
tile-size-changed(size) => {
|
||||
root.tile-size = size;
|
||||
root.tile-size-changed(size);
|
||||
}
|
||||
instance-query-changed(query) => { root.instance-query-changed(query); }
|
||||
|
||||
download-category-changed(category) => {
|
||||
root.download-category = category;
|
||||
root.download-category-changed(category);
|
||||
}
|
||||
download-install(id) => { root.download-install(id); }
|
||||
download-query-changed(query) => {
|
||||
root.download-query = query;
|
||||
root.download-query-changed(query);
|
||||
}
|
||||
ancient-help => { root.ancient-help(); }
|
||||
installed-only-changed(only) => {
|
||||
root.download-installed-only = only;
|
||||
root.installed-only-changed(only);
|
||||
}
|
||||
|
||||
log-select(id) => { root.log-select(id); }
|
||||
log-ask-ai(id) => { root.log-ask-ai(id); }
|
||||
log-apply-fix => { root.log-apply-fix(); }
|
||||
|
||||
settings-section-changed(section) => {
|
||||
root.settings-section = section;
|
||||
root.settings-section-changed(section);
|
||||
}
|
||||
theme-changed(mode) => {
|
||||
root.theme-mode = mode;
|
||||
root.theme-changed(mode);
|
||||
}
|
||||
bg-image-enabled-changed(v) => {
|
||||
root.bg-image-enabled = v;
|
||||
root.bg-image-enabled-changed(v);
|
||||
}
|
||||
bg-image-changed(path) => {
|
||||
root.bg-image = path;
|
||||
root.bg-image-changed(path);
|
||||
}
|
||||
bg-fill-changed(fill) => {
|
||||
root.bg-fill = fill;
|
||||
root.bg-fill-changed(fill);
|
||||
}
|
||||
bg-dim-changed(v) => {
|
||||
root.bg-dim = v;
|
||||
root.bg-dim-changed(v);
|
||||
}
|
||||
panel-alpha-changed(v) => {
|
||||
root.panel-alpha = v;
|
||||
root.panel-alpha-changed(v);
|
||||
}
|
||||
glass-changed(v) => {
|
||||
root.glass = v;
|
||||
root.glass-changed(v);
|
||||
}
|
||||
accent-color-changed(text) => {
|
||||
root.accent-hex = text;
|
||||
root.accent-color-changed(text);
|
||||
}
|
||||
accent-swatch-picked(index) => { root.accent-swatch-picked(index); }
|
||||
yolo-changed(enabled) => { root.yolo-changed(enabled); }
|
||||
mcp-changed(enabled) => { root.mcp-changed(enabled); }
|
||||
ai-endpoint-changed(index) => { root.ai-endpoint-changed(index); }
|
||||
|
||||
dialog-primary => { root.dialog-primary(); }
|
||||
dialog-secondary => { root.dialog-secondary(); }
|
||||
dialog-dismissed => { root.dialog-dismissed(); }
|
||||
toast-dismissed(id) => { root.toast-dismissed(id); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// UI 视图模型:Rust 的 dto.rs 做单向转换后喂给 Slint(app 不 import core 内部类型,01c §5)。
|
||||
// 命名一律 kebab-case,Rust 侧 slint-build 会生成 snake_case 字段。
|
||||
// 约定:这里只放「界面要显示什么」,不放领域语义(版本继承链、下载源健康度等留在 core)。
|
||||
|
||||
// ── 共享枚举 ─────────────────────────────────────────────────────
|
||||
export enum RouteKind {
|
||||
instances,
|
||||
download,
|
||||
logs,
|
||||
settings,
|
||||
detail,
|
||||
agent,
|
||||
}
|
||||
|
||||
export enum TileSize {
|
||||
small,
|
||||
medium,
|
||||
large,
|
||||
}
|
||||
|
||||
export enum InstanceView {
|
||||
tiles,
|
||||
list,
|
||||
}
|
||||
|
||||
/// D17 主题三态:auto 跟随系统(Slint Palette.color-scheme 热更),light/dark 钉死。
|
||||
/// 键值 `appearance.theme_mode ∈ {light, dark, auto}`,出厂 auto。
|
||||
export enum ThemeMode {
|
||||
auto,
|
||||
light,
|
||||
dark,
|
||||
}
|
||||
|
||||
/// 背景图填充模式(09 §101:cover / contain / tile)。与 `core::setting::appearance::BgFill` 同序。
|
||||
export enum BgFillKind {
|
||||
cover,
|
||||
contain,
|
||||
tile,
|
||||
}
|
||||
|
||||
export enum LoaderKind {
|
||||
vanilla,
|
||||
fabric,
|
||||
quilt,
|
||||
forge,
|
||||
neoforge,
|
||||
optifine,
|
||||
liteloader,
|
||||
}
|
||||
|
||||
export enum RuntimePhase {
|
||||
idle,
|
||||
downloading,
|
||||
verifying,
|
||||
launching,
|
||||
running,
|
||||
failed,
|
||||
}
|
||||
|
||||
export enum ChatRole {
|
||||
user,
|
||||
assistant,
|
||||
tool,
|
||||
system,
|
||||
}
|
||||
|
||||
export enum DialogKind {
|
||||
confirm,
|
||||
input,
|
||||
progress,
|
||||
error,
|
||||
}
|
||||
|
||||
export enum ToastKind {
|
||||
info,
|
||||
success,
|
||||
warn,
|
||||
error,
|
||||
}
|
||||
|
||||
export enum VersionKind {
|
||||
release,
|
||||
snapshot,
|
||||
ancientClassic,
|
||||
ancientAlpha,
|
||||
ancientBeta,
|
||||
ancientUnlisted,
|
||||
modpack,
|
||||
mod,
|
||||
}
|
||||
|
||||
// 下载页分类侧栏的选中项(远古版把四个子类提升为平级枚值,便于单选高亮)
|
||||
export enum DownloadCategory {
|
||||
release,
|
||||
snapshot,
|
||||
ancientClassic,
|
||||
ancientAlpha,
|
||||
ancientBeta,
|
||||
ancientUnlisted,
|
||||
modpack,
|
||||
mod,
|
||||
}
|
||||
|
||||
export enum LogOutcome {
|
||||
ok,
|
||||
crashed,
|
||||
silentFail,
|
||||
}
|
||||
|
||||
export enum LogLevel {
|
||||
debug,
|
||||
info,
|
||||
warn,
|
||||
error,
|
||||
}
|
||||
|
||||
export enum SettingSection {
|
||||
general,
|
||||
/// D17「外观(高级)」:主题三态 / 背景图 / 半透明度 / 玻璃拟态 / 强调色 / 动画强度
|
||||
appearance,
|
||||
data,
|
||||
download,
|
||||
java,
|
||||
account,
|
||||
ai,
|
||||
proxy,
|
||||
about,
|
||||
}
|
||||
|
||||
// ── 磁贴 ────────────────────────────────────────────────────────
|
||||
// row/col 由 Rust state.rs 的 tile_grid() 按当前磁贴尺寸算好(小 6 / 中 4 / 大 3 列),
|
||||
// 这样 Slint 侧 GridLayout 只消费整数位置,不必在 DSL 里做除法。
|
||||
export struct UiTile {
|
||||
id: string,
|
||||
name: string,
|
||||
mc_version: string,
|
||||
loader: LoaderKind,
|
||||
loader_version: string,
|
||||
/// 加载器徽标文字(「原版」/「Fabric 0.16.5」):由 Rust 侧用 `LoaderInfo::badge()` 拼好,
|
||||
/// DSL 不做枚举→字符串映射(少一处双份真相)。
|
||||
loader_label: string,
|
||||
last_played: string,
|
||||
phase: RuntimePhase,
|
||||
/// 启动中阶段文案(「下载资源」/「校验文件」/「启动中」),idle 时为空。
|
||||
phase_label: string,
|
||||
/// 0.0~1.0;<= 0 表示进度未知(进度环转为不确定态)。
|
||||
progress: float,
|
||||
/// 实例图标;空 image 时退回「名字首字 + hue 底色」占位。
|
||||
icon: image,
|
||||
hue: color,
|
||||
/// 名字首字,无图标时的占位字母(Rust 侧取首个字素)。
|
||||
initial: string,
|
||||
row: int,
|
||||
col: int,
|
||||
}
|
||||
|
||||
// ── 下载页 ──────────────────────────────────────────────────────
|
||||
export struct UiVersion {
|
||||
id: string,
|
||||
kind: VersionKind,
|
||||
released: string,
|
||||
installed: bool,
|
||||
/// 远古版(classic/alpha/beta/unlisted)——列表行带徽标 + 页顶兼容性提示。
|
||||
ancient: bool,
|
||||
}
|
||||
|
||||
// ── 日志页 ──────────────────────────────────────────────────────
|
||||
export struct UiLogSession {
|
||||
id: string,
|
||||
when: string,
|
||||
instance: string,
|
||||
outcome: LogOutcome,
|
||||
duration: string,
|
||||
}
|
||||
|
||||
export struct UiLogLine {
|
||||
text: string,
|
||||
level: LogLevel,
|
||||
}
|
||||
|
||||
/// D8 规则引擎结论(core::diagnose 的 DTO,app 只负责展示)。
|
||||
export struct UiDiagnosis {
|
||||
rule: string,
|
||||
title: string,
|
||||
confidence: int,
|
||||
hint: string,
|
||||
has_fix: bool,
|
||||
}
|
||||
|
||||
// ── AI 栏 ───────────────────────────────────────────────────────
|
||||
export struct UiChatMessage {
|
||||
role: ChatRole,
|
||||
text: string,
|
||||
/// role == tool 时的工具名。
|
||||
tool_name: string,
|
||||
tool_ok: bool,
|
||||
/// 流式未完成时 true(末尾显示光标块)。
|
||||
streaming: bool,
|
||||
}
|
||||
|
||||
// ── 对话框 / Toast ──────────────────────────────────────────────
|
||||
export struct UiDialog {
|
||||
id: string,
|
||||
kind: DialogKind,
|
||||
title: string,
|
||||
body: string,
|
||||
primary: string,
|
||||
secondary: string,
|
||||
progress: float,
|
||||
input_label: string,
|
||||
input_value: string,
|
||||
}
|
||||
|
||||
export struct UiToast {
|
||||
id: string,
|
||||
kind: ToastKind,
|
||||
text: string,
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// G2 下载页(09 §2 P0·G2 / Q24-4 定案):页内独立左侧分类栏(常驻,非 tab)+ 右侧版本列表。
|
||||
// 远古版入口显式可达(ULL 对 HMCL「隐藏」行为的纠偏),下挂 classic/alpha/beta/unlisted 子类树,
|
||||
// 进入远古版分类时顶部提示兼容性 + 每行带「远古版」徽标(防误装)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiVersion, VersionKind, DownloadCategory } from "../models.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
import { Badge } from "../components/badge.slint";
|
||||
import { MetroButton, ButtonKind } from "../widgets/button.slint";
|
||||
import { SearchField, CheckBox } from "../widgets/inputs.slint";
|
||||
import { ListView } from "std-widgets.slint";
|
||||
|
||||
component CategoryRow inherits Rectangle {
|
||||
in property <string> label: "";
|
||||
in property <bool> active: false;
|
||||
in property <bool> sub: false;
|
||||
in property <bool> disabled: false;
|
||||
callback clicked();
|
||||
|
||||
height: 34px;
|
||||
background: root.active ? Theme.accent-soft : (row-touch.has-hover ? Theme.bg-hover : transparent);
|
||||
|
||||
if root.active : Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: 3px;
|
||||
height: root.height;
|
||||
background: Theme.accent;
|
||||
}
|
||||
|
||||
UiText {
|
||||
x: root.sub ? Metrics.gap-5 : Metrics.gap-3;
|
||||
width: root.width - (root.sub ? Metrics.gap-5 : Metrics.gap-3) - Metrics.gap-2;
|
||||
height: root.height;
|
||||
role: TextRole.body;
|
||||
text: root.label;
|
||||
color: root.disabled ? Theme.fg-disabled
|
||||
: root.active ? Theme.accent
|
||||
: Theme.fg-primary;
|
||||
}
|
||||
|
||||
row-touch := TouchArea {
|
||||
mouse-cursor: root.disabled ? default : pointer;
|
||||
clicked => {
|
||||
if (!root.disabled) {
|
||||
root.clicked();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
component VersionRow inherits Rectangle {
|
||||
in property <UiVersion> data;
|
||||
callback install();
|
||||
|
||||
height: Metrics.row-height + 8px;
|
||||
background: row-touch.has-hover ? Theme.bg-hover : transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: root.data.id;
|
||||
width: 160px;
|
||||
}
|
||||
|
||||
Badge {
|
||||
text: root.data.kind == VersionKind.release ? "正式版"
|
||||
: root.data.kind == VersionKind.snapshot ? "预览版"
|
||||
: "远古版";
|
||||
tint: root.data.ancient ? Theme.state-warn : Theme.fg-secondary;
|
||||
}
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.released;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
|
||||
if root.data.installed : HorizontalLayout {
|
||||
spacing: Metrics.gap-1;
|
||||
AppIcon { kind: IconKind.check; icon-size: 12px; tint: Theme.state-success; }
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: "已装";
|
||||
color: Theme.state-success;
|
||||
}
|
||||
}
|
||||
|
||||
MetroButton {
|
||||
kind: ButtonKind.standard;
|
||||
text: root.data.installed ? "重装" : "安装";
|
||||
button-height: 26px;
|
||||
clicked => { root.install(); }
|
||||
}
|
||||
}
|
||||
|
||||
row-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.install(); }
|
||||
}
|
||||
}
|
||||
|
||||
export component DownloadPage inherits Rectangle {
|
||||
in property <[UiVersion]> versions;
|
||||
in-out property <DownloadCategory> category: DownloadCategory.release;
|
||||
in-out property <bool> installed-only: false;
|
||||
in-out property <string> query: "";
|
||||
/// 远古版子类树是否展开(默认展开,显式可达)
|
||||
in-out property <bool> ancient-expanded: true;
|
||||
|
||||
callback category-changed(DownloadCategory);
|
||||
callback install(string);
|
||||
callback installed-only-changed(bool);
|
||||
callback query-changed(string);
|
||||
callback toggle-ancient();
|
||||
/// 远古版兼容性说明(P1 出说明页;当前由 Rust 侧弹 Toast 占位)
|
||||
callback ancient-help();
|
||||
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
HorizontalLayout {
|
||||
// ── 页内分类侧栏(常驻)───────────────────────────────────
|
||||
Rectangle {
|
||||
width: 200px;
|
||||
background: Theme.bg-surface;
|
||||
border-width: 1px;
|
||||
border-color: Theme.stroke;
|
||||
|
||||
VerticalLayout {
|
||||
padding-top: Metrics.gap-2;
|
||||
|
||||
CategoryRow {
|
||||
label: "正式版 release";
|
||||
active: root.category == DownloadCategory.release;
|
||||
clicked => { root.category-changed(DownloadCategory.release); }
|
||||
}
|
||||
CategoryRow {
|
||||
label: "预览版 snapshot";
|
||||
active: root.category == DownloadCategory.snapshot;
|
||||
clicked => { root.category-changed(DownloadCategory.snapshot); }
|
||||
}
|
||||
|
||||
// 远古版:可展开的父节点 + 子类树
|
||||
CategoryRow {
|
||||
label: root.ancient-expanded ? "远古版 ▾" : "远古版 ▸";
|
||||
active: root.category == DownloadCategory.ancientClassic
|
||||
|| root.category == DownloadCategory.ancientAlpha
|
||||
|| root.category == DownloadCategory.ancientBeta
|
||||
|| root.category == DownloadCategory.ancientUnlisted;
|
||||
clicked => { root.toggle-ancient(); }
|
||||
}
|
||||
if root.ancient-expanded : CategoryRow {
|
||||
label: "classic(rd-*)";
|
||||
sub: true;
|
||||
active: root.category == DownloadCategory.ancientClassic;
|
||||
clicked => { root.category-changed(DownloadCategory.ancientClassic); }
|
||||
}
|
||||
if root.ancient-expanded : CategoryRow {
|
||||
label: "old_alpha(a1.*)";
|
||||
sub: true;
|
||||
active: root.category == DownloadCategory.ancientAlpha;
|
||||
clicked => { root.category-changed(DownloadCategory.ancientAlpha); }
|
||||
}
|
||||
if root.ancient-expanded : CategoryRow {
|
||||
label: "old_beta(b1.*)";
|
||||
sub: true;
|
||||
active: root.category == DownloadCategory.ancientBeta;
|
||||
clicked => { root.category-changed(DownloadCategory.ancientBeta); }
|
||||
}
|
||||
if root.ancient-expanded : CategoryRow {
|
||||
label: "unlisted 汇总";
|
||||
sub: true;
|
||||
active: root.category == DownloadCategory.ancientUnlisted;
|
||||
clicked => { root.category-changed(DownloadCategory.ancientUnlisted); }
|
||||
}
|
||||
|
||||
CategoryRow {
|
||||
label: "整合包(P1)";
|
||||
disabled: true;
|
||||
}
|
||||
CategoryRow {
|
||||
label: "Mod(P1)";
|
||||
disabled: true;
|
||||
}
|
||||
|
||||
Rectangle { vertical-stretch: 1; background: transparent; }
|
||||
}
|
||||
}
|
||||
|
||||
// ── 右侧版本列表 ──────────────────────────────────────────
|
||||
VerticalLayout {
|
||||
vertical-stretch: 1;
|
||||
|
||||
Rectangle {
|
||||
height: Metrics.page-header-height;
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
UiText {
|
||||
role: TextRole.subtitle;
|
||||
text: "版本获取";
|
||||
width: 96px;
|
||||
}
|
||||
SearchField {
|
||||
width: 220px;
|
||||
placeholder: "筛选版本号";
|
||||
text <=> root.query;
|
||||
edited(t) => { root.query-changed(t); }
|
||||
}
|
||||
CheckBox {
|
||||
text: "仅已装";
|
||||
checked: root.installed-only;
|
||||
toggled(v) => { root.installed-only-changed(v); }
|
||||
}
|
||||
Rectangle { horizontal-stretch: 1; background: transparent; }
|
||||
}
|
||||
}
|
||||
|
||||
// 远古版兼容性提示条(首次进入显示,显式可达的代价告知)
|
||||
Rectangle {
|
||||
height: 44px;
|
||||
visible: root.category == DownloadCategory.ancientClassic
|
||||
|| root.category == DownloadCategory.ancientAlpha
|
||||
|| root.category == DownloadCategory.ancientBeta
|
||||
|| root.category == DownloadCategory.ancientUnlisted;
|
||||
background: Theme.state-warn-soft;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
AppIcon { kind: IconKind.warn; icon-size: 16px; tint: Theme.state-warn; }
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: "远古版(classic/alpha/beta)需要旧版 Java 与旧启动参数,装完请先看兼容性说明。";
|
||||
wrap: word-wrap;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
text: "说明";
|
||||
button-height: 26px;
|
||||
clicked => { root.ancient-help(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: Theme.stroke; }
|
||||
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
|
||||
for v in root.versions : VersionRow {
|
||||
data: v;
|
||||
install => { root.install(v.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
// G1 实例页(09 §2 P0·G1):顶栏(搜索/新建/视图切换/磁贴尺寸)+ 磁贴网格 + 运行中迷你状态条。
|
||||
// 网格用 GridLayout:列数由 Rust 按磁贴尺寸算好(小 6 / 中 4 / 大 3),row/col 随 UiTile 一起给。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiTile, InstanceView, TileSize, RuntimePhase } from "../models.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
import { MetroButton, ButtonKind } from "../widgets/button.slint";
|
||||
import { SearchField, SegmentedControl } from "../widgets/inputs.slint";
|
||||
import { InstanceTile } from "../components/tile.slint";
|
||||
import { ListView } from "std-widgets.slint";
|
||||
|
||||
// 列表视图的一行(与磁贴共用同一份 UiTile 数据)
|
||||
component InstanceRow inherits Rectangle {
|
||||
in property <UiTile> data;
|
||||
callback open();
|
||||
callback launch();
|
||||
|
||||
height: Metrics.row-height + 8px;
|
||||
background: row-touch.has-hover ? Theme.bg-hover : transparent;
|
||||
|
||||
// 行点击区先声明,按钮后声明 → 按钮命中优先
|
||||
row-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.open(); }
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-3;
|
||||
padding-right: Metrics.gap-3;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
Rectangle {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: Metrics.radius-sm;
|
||||
background: root.data.hue;
|
||||
|
||||
UiText {
|
||||
text: root.data.initial;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: Theme.fg-on-accent;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
|
||||
UiText {
|
||||
role: TextRole.body;
|
||||
text: root.data.name;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.mc_version;
|
||||
width: 88px;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.loader_label;
|
||||
width: 88px;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.last_played;
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
icon: IconKind.play;
|
||||
icon-only: true;
|
||||
enabled: root.data.phase == RuntimePhase.idle
|
||||
|| root.data.phase == RuntimePhase.failed;
|
||||
clicked => { root.launch(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component InstancesPage inherits Rectangle {
|
||||
in property <[UiTile]> tiles;
|
||||
in property <[UiTile]> running;
|
||||
in property <InstanceView> view: InstanceView.tiles;
|
||||
in-out property <TileSize> tile-size: TileSize.medium;
|
||||
in-out property <string> query: "";
|
||||
|
||||
callback launch(string);
|
||||
callback configure(string);
|
||||
callback stop(string);
|
||||
callback open(string);
|
||||
callback new-instance();
|
||||
callback view-changed(InstanceView);
|
||||
callback tile-size-changed(TileSize);
|
||||
callback query-changed(string);
|
||||
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
VerticalLayout {
|
||||
// ── 顶栏 ────────────────────────────────────────────────
|
||||
Rectangle {
|
||||
height: Metrics.page-header-height;
|
||||
background: Theme.bg-surface;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
UiText {
|
||||
role: TextRole.subtitle;
|
||||
text: "实例";
|
||||
width: 72px;
|
||||
}
|
||||
|
||||
SearchField {
|
||||
width: 240px;
|
||||
placeholder: "搜索实例";
|
||||
text <=> root.query;
|
||||
edited(t) => { root.query-changed(t); }
|
||||
}
|
||||
|
||||
Rectangle { horizontal-stretch: 1; background: transparent; }
|
||||
|
||||
SegmentedControl {
|
||||
width: 120px;
|
||||
options: ["磁贴", "列表"];
|
||||
selected: root.view == InstanceView.tiles ? 0 : 1;
|
||||
changed(i) => {
|
||||
root.view-changed(i == 0 ? InstanceView.tiles : InstanceView.list);
|
||||
}
|
||||
}
|
||||
|
||||
SegmentedControl {
|
||||
width: 132px;
|
||||
visible: root.view == InstanceView.tiles;
|
||||
options: ["小", "中", "大"];
|
||||
selected: root.tile-size == TileSize.small ? 0
|
||||
: root.tile-size == TileSize.large ? 2 : 1;
|
||||
changed(i) => {
|
||||
root.tile-size-changed(
|
||||
i == 0 ? TileSize.small : i == 2 ? TileSize.large : TileSize.medium);
|
||||
}
|
||||
}
|
||||
|
||||
MetroButton {
|
||||
kind: ButtonKind.accent;
|
||||
text: "新建实例";
|
||||
show-icon: true;
|
||||
icon: IconKind.plus;
|
||||
clicked => { root.new-instance(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: Theme.stroke; }
|
||||
|
||||
// ── 运行中迷你状态条 ──────────────────────────────────────
|
||||
Rectangle {
|
||||
height: Metrics.running-strip-height;
|
||||
visible: root.running.length > 0;
|
||||
background: Theme.state-info-soft;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
Rectangle {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 4px;
|
||||
background: Theme.state-success;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.running.length + " 个实例运行中";
|
||||
color: Theme.state-success;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
for r in root.running : UiText {
|
||||
role: TextRole.caption;
|
||||
text: r.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 磁贴网格 ─────────────────────────────────────────────
|
||||
body := Flickable {
|
||||
vertical-stretch: 1;
|
||||
visible: root.view == InstanceView.tiles && root.tiles.length > 0;
|
||||
content-width: self.width;
|
||||
content-height: grid-content.height;
|
||||
|
||||
grid-content := Rectangle {
|
||||
width: body.width;
|
||||
height: grid.preferred-height;
|
||||
background: transparent;
|
||||
|
||||
grid := GridLayout {
|
||||
padding: Metrics.gap-4;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
for t in root.tiles : InstanceTile {
|
||||
row: t.row;
|
||||
col: t.col;
|
||||
data: t;
|
||||
compact: root.tile-size == TileSize.small;
|
||||
open => { root.open(t.id); }
|
||||
launch => { root.launch(t.id); }
|
||||
configure => { root.configure(t.id); }
|
||||
stop => { root.stop(t.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 列表视图 ─────────────────────────────────────────────
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
visible: root.view == InstanceView.list && root.tiles.length > 0;
|
||||
|
||||
for t in root.tiles : InstanceRow {
|
||||
data: t;
|
||||
open => { root.open(t.id); }
|
||||
launch => { root.launch(t.id); }
|
||||
}
|
||||
}
|
||||
|
||||
// ── 空态 ────────────────────────────────────────────────
|
||||
VerticalLayout {
|
||||
vertical-stretch: 1;
|
||||
visible: root.tiles.length == 0;
|
||||
alignment: center;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
UiText {
|
||||
role: TextRole.title;
|
||||
text: "还没有实例";
|
||||
horizontal-alignment: center;
|
||||
color: Theme.fg-secondary;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: "新建一个实例,或者先去下载页装个版本";
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
MetroButton {
|
||||
kind: ButtonKind.accent;
|
||||
text: "新建实例";
|
||||
show-icon: true;
|
||||
icon: IconKind.plus;
|
||||
clicked => { root.new-instance(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// G3 日志页(09 §2 P0·G3):左侧会话列表(✓正常 / ✗崩溃 / ⚠静默失败)+ 右侧日志流 + 崩溃诊断卡片。
|
||||
// 诊断卡片 = D8 规则引擎结论(命中规则 + 置信度 + 修复动作 + 跳 AI 栏带上下文)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiLogSession, UiLogLine, UiDiagnosis, LogOutcome, LogLevel } from "../models.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
import { Badge } from "../components/badge.slint";
|
||||
import { MetroButton, ButtonKind } from "../widgets/button.slint";
|
||||
import { SearchField } from "../widgets/inputs.slint";
|
||||
import { ListView } from "std-widgets.slint";
|
||||
|
||||
component SessionRow inherits Rectangle {
|
||||
in property <UiLogSession> data;
|
||||
in property <bool> active: false;
|
||||
callback clicked();
|
||||
|
||||
height: 52px;
|
||||
background: root.active ? Theme.accent-soft : (row-touch.has-hover ? Theme.bg-hover : transparent);
|
||||
|
||||
if root.active : Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: 3px;
|
||||
height: root.height;
|
||||
background: Theme.accent;
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-3;
|
||||
padding-right: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
AppIcon {
|
||||
icon-size: 14px;
|
||||
kind: root.data.outcome == LogOutcome.ok ? IconKind.check
|
||||
: root.data.outcome == LogOutcome.crashed ? IconKind.error
|
||||
: IconKind.warn;
|
||||
tint: root.data.outcome == LogOutcome.ok ? Theme.state-success
|
||||
: root.data.outcome == LogOutcome.crashed ? Theme.state-danger
|
||||
: Theme.state-warn;
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
vertical-stretch: 1;
|
||||
|
||||
UiText {
|
||||
role: TextRole.body;
|
||||
text: root.data.instance;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.when;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.data.duration;
|
||||
width: 56px;
|
||||
horizontal-alignment: right;
|
||||
}
|
||||
}
|
||||
|
||||
row-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
}
|
||||
|
||||
component LogRow inherits Rectangle {
|
||||
in property <UiLogLine> line;
|
||||
|
||||
height: 18px;
|
||||
background: root.line.level == LogLevel.error
|
||||
? Theme.state-danger-soft
|
||||
: transparent;
|
||||
|
||||
UiText {
|
||||
x: Metrics.gap-2;
|
||||
y: 0;
|
||||
width: root.width - 2 * Metrics.gap-2;
|
||||
height: root.height;
|
||||
role: TextRole.monoSmall;
|
||||
text: root.line.text;
|
||||
color: root.line.level == LogLevel.error ? Theme.state-danger
|
||||
: root.line.level == LogLevel.warn ? Theme.state-warn
|
||||
: root.line.level == LogLevel.debug ? Theme.fg-disabled
|
||||
: Theme.fg-primary;
|
||||
}
|
||||
}
|
||||
|
||||
export component LogsPage inherits Rectangle {
|
||||
in property <[UiLogSession]> sessions;
|
||||
in property <[UiLogLine]> lines;
|
||||
in property <UiDiagnosis> diagnosis;
|
||||
in property <bool> has-diagnosis: false;
|
||||
in property <bool> live: false;
|
||||
in-out property <string> selected: "";
|
||||
in-out property <string> query: "";
|
||||
|
||||
callback select(string);
|
||||
callback ask-ai(string);
|
||||
callback apply-fix();
|
||||
callback query-changed(string);
|
||||
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
HorizontalLayout {
|
||||
// ── 左侧会话列表 ─────────────────────────────────────────
|
||||
Rectangle {
|
||||
width: 248px;
|
||||
background: Theme.bg-surface;
|
||||
|
||||
VerticalLayout {
|
||||
Rectangle {
|
||||
height: 44px;
|
||||
background: transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-3;
|
||||
padding-right: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: "会话";
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
if root.live : Rectangle {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: Theme.state-success;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
|
||||
for s in root.sessions : SessionRow {
|
||||
data: s;
|
||||
active: root.selected == s.id;
|
||||
clicked => { root.select(s.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { width: 1px; background: Theme.stroke; }
|
||||
|
||||
// ── 右侧日志流 + 诊断卡片 ────────────────────────────────
|
||||
VerticalLayout {
|
||||
vertical-stretch: 1;
|
||||
|
||||
Rectangle {
|
||||
height: 44px;
|
||||
background: Theme.bg-surface;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-3;
|
||||
padding-right: Metrics.gap-3;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: root.selected == "" ? "未选择会话" : root.selected;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
SearchField {
|
||||
width: 200px;
|
||||
placeholder: "筛选日志行";
|
||||
text <=> root.query;
|
||||
edited(t) => { root.query-changed(t); }
|
||||
}
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
text: "打开目录";
|
||||
button-height: 26px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: Theme.stroke; }
|
||||
|
||||
// 崩溃诊断卡片(D8)
|
||||
Rectangle {
|
||||
height: root.has-diagnosis ? 76px : 0px;
|
||||
visible: root.has-diagnosis;
|
||||
background: Theme.state-danger-soft;
|
||||
|
||||
HorizontalLayout {
|
||||
padding: Metrics.gap-3;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
AppIcon { kind: IconKind.error; icon-size: 20px; tint: Theme.state-danger; }
|
||||
|
||||
VerticalLayout {
|
||||
spacing: 2px;
|
||||
vertical-stretch: 1;
|
||||
|
||||
HorizontalLayout {
|
||||
spacing: Metrics.gap-2;
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: root.diagnosis.title;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
Badge {
|
||||
text: "置信度 " + root.diagnosis.confidence + "%";
|
||||
tint: Theme.state-danger;
|
||||
}
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.diagnosis.hint;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
spacing: Metrics.gap-1;
|
||||
alignment: center;
|
||||
|
||||
if root.diagnosis.has_fix : MetroButton {
|
||||
kind: ButtonKind.standard;
|
||||
text: "修复建议";
|
||||
button-height: 26px;
|
||||
clicked => { root.apply-fix(); }
|
||||
}
|
||||
MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
text: "让 AI 详解";
|
||||
button-height: 26px;
|
||||
clicked => { root.ask-ai(root.selected); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 日志流(行虚拟化)
|
||||
Rectangle {
|
||||
vertical-stretch: 1;
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
ListView {
|
||||
for l in root.lines : LogRow {
|
||||
line: l;
|
||||
width: root.width;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// 设置页「外观」分组(09 §2 G6 + §113 D17 定案):主题三态 + 「外观(高级)」P1 四件。
|
||||
//
|
||||
// 从 pages/settings.slint 拆出来只为守住 400 行门槛;控件语义与设置键一一对应:
|
||||
// theme-mode → appearance.theme_mode / bg-* → appearance.bg_image* / panel-alpha →
|
||||
// appearance.panel_alpha / glass → appearance.glass / accent-color → appearance.accent_color。
|
||||
// 09 §111 硬约束:高级特性全部默认关闭,开启背景图时这里会给出对比度提示(warn 行)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { ThemeMode, BgFillKind } from "../models.slint";
|
||||
import { SettingItem, SettingGroup, ControlKind } from "../widgets/setting-item.slint";
|
||||
|
||||
export component AppearanceSection inherits VerticalLayout {
|
||||
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
|
||||
in-out property <bool> bg-image-enabled: false;
|
||||
in-out property <string> bg-image: "";
|
||||
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
|
||||
in-out property <float> bg-dim: 0.35;
|
||||
in-out property <float> panel-alpha: 1.0;
|
||||
in-out property <bool> glass: false;
|
||||
in-out property <string> accent-color: "";
|
||||
in property <bool> accent-invalid: false;
|
||||
|
||||
callback theme-changed(ThemeMode);
|
||||
callback bg-image-enabled-changed(bool);
|
||||
callback bg-image-changed(string);
|
||||
callback bg-fill-changed(BgFillKind);
|
||||
callback bg-dim-changed(float);
|
||||
callback panel-alpha-changed(float);
|
||||
callback glass-changed(bool);
|
||||
callback accent-color-changed(string);
|
||||
callback accent-swatch-picked(int);
|
||||
|
||||
// ── 外观(D17:主题三态 + 09 §101-104 高级四件)──────
|
||||
SettingGroup { title: "主题"; }
|
||||
SettingItem {
|
||||
label: "主题模式";
|
||||
description: "跟随系统(Auto,随 OS 热切)/ 浅色 / 深色";
|
||||
kind: ControlKind.segmented;
|
||||
options: ["跟随系统", "浅色", "深色"];
|
||||
selected: root.theme-mode == ThemeMode.auto ? 0
|
||||
: root.theme-mode == ThemeMode.light ? 1 : 2;
|
||||
changed(i) => {
|
||||
root.theme-mode = i == 0 ? ThemeMode.auto
|
||||
: i == 1 ? ThemeMode.light : ThemeMode.dark;
|
||||
root.theme-changed(root.theme-mode);
|
||||
}
|
||||
}
|
||||
|
||||
SettingGroup {
|
||||
title: "高级特性(出厂全部关闭,开启后请确认前景可读)";
|
||||
}
|
||||
// ① 自定义窗口背景图(09 §101)
|
||||
SettingItem {
|
||||
label: "自定义窗口背景图";
|
||||
description: "PNG 图片铺满窗口;开启后所有面板半透明处都会透出它";
|
||||
kind: ControlKind.toggle;
|
||||
checked: root.bg-image-enabled;
|
||||
toggled(v) => {
|
||||
root.bg-image-enabled = v;
|
||||
root.bg-image-enabled-changed(v);
|
||||
}
|
||||
}
|
||||
SettingItem {
|
||||
label: "背景图路径";
|
||||
description: root.bg-image == "" ? "尚未选择(绝对路径,例:D:/wall/p.png)" : root.bg-image;
|
||||
kind: ControlKind.text;
|
||||
button-text: "D:/wall/p.png";
|
||||
value <=> root.bg-image;
|
||||
edited(t) => { root.bg-image-changed(t); }
|
||||
}
|
||||
SettingItem {
|
||||
label: "填充模式";
|
||||
description: "铺满(裁切)/ 完整(留底色)/ 平铺";
|
||||
kind: ControlKind.segmented;
|
||||
options: ["铺满", "完整", "平铺"];
|
||||
selected: root.bg-fill == BgFillKind.cover ? 0
|
||||
: root.bg-fill == BgFillKind.contain ? 1 : 2;
|
||||
changed(i) => {
|
||||
root.bg-fill = i == 0 ? BgFillKind.cover
|
||||
: i == 1 ? BgFillKind.contain : BgFillKind.tile;
|
||||
root.bg-fill-changed(root.bg-fill);
|
||||
}
|
||||
}
|
||||
SettingItem {
|
||||
label: "暗化层强度";
|
||||
// 09 §111:开启背景图时自动给对比度提示——暗化太低 + 面板太透会伤可读性
|
||||
description: (root.bg-image-enabled && (root.bg-dim < 0.25 || root.panel-alpha < 0.8))
|
||||
? "⚠ 对比度偏低:建议暗化 ≥ 25% 或面板不透明度 ≥ 80%"
|
||||
: "越大背景越暗、前景越清晰(0% = 不压暗)";
|
||||
warn: root.bg-image-enabled && (root.bg-dim < 0.25 || root.panel-alpha < 0.8);
|
||||
kind: ControlKind.slider;
|
||||
min-value: 0.0;
|
||||
max-value: 0.9;
|
||||
slider-value: root.bg-dim;
|
||||
slid(v) => {
|
||||
root.bg-dim = v;
|
||||
root.bg-dim-changed(v);
|
||||
}
|
||||
}
|
||||
// ② 全局面板半透明度(09 §102)
|
||||
SettingItem {
|
||||
label: "全局面板半透明度";
|
||||
description: "卡片 / 导航 / AI 栏统一透明度(100% = 出厂 Metro 纯色)";
|
||||
kind: ControlKind.slider;
|
||||
min-value: 0.4;
|
||||
max-value: 1.0;
|
||||
slider-value: root.panel-alpha;
|
||||
slid(v) => {
|
||||
root.panel-alpha = v;
|
||||
root.panel-alpha-changed(v);
|
||||
}
|
||||
}
|
||||
// ③ 玻璃拟态卡片(09 §103)
|
||||
SettingItem {
|
||||
label: "玻璃拟态卡片";
|
||||
description: "卡片底铺背景图的预生成模糊层(需先开启背景图)";
|
||||
kind: ControlKind.toggle;
|
||||
checked: root.glass;
|
||||
toggled(v) => {
|
||||
root.glass = v;
|
||||
root.glass-changed(v);
|
||||
}
|
||||
}
|
||||
// ④ 自定义强调色(09 §104)
|
||||
SettingItem {
|
||||
label: "预设强调色";
|
||||
description: root.accent-color == "" ? "当前:出厂 Metro 蓝" : "当前:" + root.accent-color;
|
||||
kind: ControlKind.swatches;
|
||||
swatch-colors: [
|
||||
#0078D4, #0F6CBD, #107C10, #9D5D00,
|
||||
#C42B1C, #8764B8, #C239B3, #00B7C3,
|
||||
];
|
||||
swatch-current: root.accent-color == "" ? #0078D4 : Theme.accent;
|
||||
swatch-picked(i) => { root.accent-swatch-picked(i); }
|
||||
}
|
||||
SettingItem {
|
||||
label: "强调色(十六进制)";
|
||||
description: root.accent-invalid
|
||||
? "⚠ 需要 #RRGGBB 形式,留空恢复出厂蓝"
|
||||
: "留空 = 出厂 #0078D4;影响顶线 / 选中态 / 按钮 / 徽标";
|
||||
warn: root.accent-invalid;
|
||||
kind: ControlKind.text;
|
||||
button-text: "#0078D4";
|
||||
value <=> root.accent-color;
|
||||
edited(t) => { root.accent-color-changed(t); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// G6 设置页(09 §2 P0·G6):左子导航 + 右表单 + 搜索框(设置项多,防迷路)。
|
||||
// 「通用 / 外观(D17 三态 + 09 §101-104 高级四件,实现在 settings-appearance.slint)/ 数据 / AI /
|
||||
// 关于」是真实控件,Java / 账户 / 代理分组仍是入口按钮(等各自 mission 接实现)。
|
||||
// 关于页内嵌 AboutSlint —— Slint RF 2.0 许可义务(01c §8:关于页放官方部件)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { SettingSection, TileSize, ThemeMode, BgFillKind } from "../models.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { SettingItem, SettingGroup, ControlKind } from "../widgets/setting-item.slint";
|
||||
import { AppearanceSection } from "settings-appearance.slint";
|
||||
import { SearchField } from "../widgets/inputs.slint";
|
||||
import { AboutSlint, ScrollView } from "std-widgets.slint";
|
||||
|
||||
component SectionRow inherits Rectangle {
|
||||
in property <string> label: "";
|
||||
in property <SettingSection> section: SettingSection.general;
|
||||
in property <bool> active: false;
|
||||
callback clicked();
|
||||
|
||||
height: 36px;
|
||||
background: root.active ? Theme.accent-soft : (row-touch.has-hover ? Theme.bg-hover : transparent);
|
||||
|
||||
if root.active : Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: 3px;
|
||||
height: root.height;
|
||||
background: Theme.accent;
|
||||
}
|
||||
|
||||
UiText {
|
||||
x: Metrics.gap-3;
|
||||
y: 0;
|
||||
width: root.width - Metrics.gap-3 - Metrics.gap-2;
|
||||
height: root.height;
|
||||
role: TextRole.body;
|
||||
text: root.label;
|
||||
color: root.active ? Theme.accent : Theme.fg-primary;
|
||||
}
|
||||
|
||||
row-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
}
|
||||
|
||||
export component SettingsPage inherits Rectangle {
|
||||
in-out property <SettingSection> section: SettingSection.general;
|
||||
in-out property <string> query: "";
|
||||
|
||||
// 外观(D17:主题三态 + 09 §101-104 高级特性四件)
|
||||
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
|
||||
in-out property <bool> bg-image-enabled: false;
|
||||
in-out property <string> bg-image: "";
|
||||
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
|
||||
in-out property <float> bg-dim: 0.35;
|
||||
in-out property <float> panel-alpha: 1.0;
|
||||
in-out property <bool> glass: false;
|
||||
in-out property <string> accent-color: "";
|
||||
in property <bool> accent-invalid: false;
|
||||
// 通用
|
||||
in-out property <TileSize> tile-size: TileSize.medium;
|
||||
in-out property <bool> close-to-tray: true;
|
||||
|
||||
// 数据
|
||||
in-out property <int> data-mode: 0;
|
||||
in property <string> data-path: "";
|
||||
// 下载
|
||||
in-out property <int> download-concurrency: 1;
|
||||
in property <string> region-label: "未知";
|
||||
// 账户
|
||||
in property <string> account-label: "未登录";
|
||||
// AI
|
||||
in-out property <int> ai-endpoint: 0;
|
||||
in-out property <bool> yolo: false;
|
||||
in-out property <bool> mcp-enabled: false;
|
||||
// 代理
|
||||
in-out property <string> proxy: "";
|
||||
// 关于
|
||||
in property <string> version: "";
|
||||
|
||||
callback section-changed(SettingSection);
|
||||
callback query-changed(string);
|
||||
callback theme-changed(ThemeMode);
|
||||
callback bg-image-enabled-changed(bool);
|
||||
callback bg-image-changed(string);
|
||||
callback bg-fill-changed(BgFillKind);
|
||||
callback bg-dim-changed(float);
|
||||
callback panel-alpha-changed(float);
|
||||
callback glass-changed(bool);
|
||||
callback accent-color-changed(string);
|
||||
callback accent-swatch-picked(int);
|
||||
callback tile-size-changed(TileSize);
|
||||
callback close-to-tray-changed(bool);
|
||||
callback data-mode-changed(int);
|
||||
callback download-concurrency-changed(int);
|
||||
callback ai-endpoint-changed(int);
|
||||
callback yolo-changed(bool);
|
||||
callback mcp-changed(bool);
|
||||
callback proxy-changed(string);
|
||||
callback migrate-data();
|
||||
callback login();
|
||||
callback manage-java();
|
||||
callback open-audit-log();
|
||||
callback detect-region();
|
||||
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
HorizontalLayout {
|
||||
// ── 左子导航 ──────────────────────────────────────────────
|
||||
Rectangle {
|
||||
width: 200px;
|
||||
background: Theme.bg-surface;
|
||||
|
||||
VerticalLayout {
|
||||
padding-top: Metrics.gap-2;
|
||||
|
||||
SectionRow { label: "通用"; section: SettingSection.general; active: root.section == SettingSection.general; clicked => { root.section-changed(SettingSection.general); } }
|
||||
SectionRow { label: "外观"; section: SettingSection.appearance; active: root.section == SettingSection.appearance; clicked => { root.section-changed(SettingSection.appearance); } }
|
||||
SectionRow { label: "数据"; section: SettingSection.data; active: root.section == SettingSection.data; clicked => { root.section-changed(SettingSection.data); } }
|
||||
SectionRow { label: "下载"; section: SettingSection.download; active: root.section == SettingSection.download; clicked => { root.section-changed(SettingSection.download); } }
|
||||
SectionRow { label: "Java"; section: SettingSection.java; active: root.section == SettingSection.java; clicked => { root.section-changed(SettingSection.java); } }
|
||||
SectionRow { label: "账户"; section: SettingSection.account; active: root.section == SettingSection.account; clicked => { root.section-changed(SettingSection.account); } }
|
||||
SectionRow { label: "AI"; section: SettingSection.ai; active: root.section == SettingSection.ai; clicked => { root.section-changed(SettingSection.ai); } }
|
||||
SectionRow { label: "代理"; section: SettingSection.proxy; active: root.section == SettingSection.proxy; clicked => { root.section-changed(SettingSection.proxy); } }
|
||||
SectionRow { label: "关于"; section: SettingSection.about; active: root.section == SettingSection.about; clicked => { root.section-changed(SettingSection.about); } }
|
||||
|
||||
Rectangle { vertical-stretch: 1; background: transparent; }
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { width: 1px; background: Theme.stroke; }
|
||||
|
||||
// ── 右表单 ────────────────────────────────────────────────
|
||||
VerticalLayout {
|
||||
vertical-stretch: 1;
|
||||
|
||||
Rectangle {
|
||||
height: Metrics.page-header-height;
|
||||
background: Theme.bg-surface;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
UiText {
|
||||
role: TextRole.subtitle;
|
||||
text: "设置";
|
||||
width: 72px;
|
||||
}
|
||||
SearchField {
|
||||
width: 240px;
|
||||
placeholder: "搜索设置项";
|
||||
text <=> root.query;
|
||||
edited(t) => { root.query-changed(t); }
|
||||
}
|
||||
Rectangle { horizontal-stretch: 1; background: transparent; }
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: Theme.stroke; }
|
||||
|
||||
ScrollView {
|
||||
vertical-stretch: 1;
|
||||
|
||||
VerticalLayout {
|
||||
padding-bottom: Metrics.gap-5;
|
||||
|
||||
// 外观(D17:主题三态 + 09 §101-104 高级四件;实现在 settings-appearance.slint)
|
||||
if root.section == SettingSection.appearance : AppearanceSection {
|
||||
theme-mode: root.theme-mode;
|
||||
bg-image-enabled: root.bg-image-enabled;
|
||||
bg-image: root.bg-image;
|
||||
bg-fill: root.bg-fill;
|
||||
bg-dim: root.bg-dim;
|
||||
panel-alpha: root.panel-alpha;
|
||||
glass: root.glass;
|
||||
accent-color: root.accent-color;
|
||||
accent-invalid: root.accent-invalid;
|
||||
theme-changed(m) => {
|
||||
root.theme-mode = m;
|
||||
root.theme-changed(m);
|
||||
}
|
||||
bg-image-enabled-changed(v) => {
|
||||
root.bg-image-enabled = v;
|
||||
root.bg-image-enabled-changed(v);
|
||||
}
|
||||
bg-image-changed(t) => {
|
||||
root.bg-image = t;
|
||||
root.bg-image-changed(t);
|
||||
}
|
||||
bg-fill-changed(f) => {
|
||||
root.bg-fill = f;
|
||||
root.bg-fill-changed(f);
|
||||
}
|
||||
bg-dim-changed(v) => {
|
||||
root.bg-dim = v;
|
||||
root.bg-dim-changed(v);
|
||||
}
|
||||
panel-alpha-changed(v) => {
|
||||
root.panel-alpha = v;
|
||||
root.panel-alpha-changed(v);
|
||||
}
|
||||
glass-changed(v) => {
|
||||
root.glass = v;
|
||||
root.glass-changed(v);
|
||||
}
|
||||
accent-color-changed(t) => {
|
||||
root.accent-color = t;
|
||||
root.accent-color-changed(t);
|
||||
}
|
||||
accent-swatch-picked(i) => { root.accent-swatch-picked(i); }
|
||||
}
|
||||
|
||||
// ── 通用 ────────────────────────────────────────
|
||||
if root.section == SettingSection.general : SettingGroup { title: "外观"; }
|
||||
if root.section == SettingSection.general : SettingItem {
|
||||
label: "磁贴尺寸";
|
||||
description: "小 6 列 / 中 4 列(默认)/ 大 3 列";
|
||||
kind: ControlKind.segmented;
|
||||
options: ["小", "中", "大"];
|
||||
selected: root.tile-size == TileSize.small ? 0
|
||||
: root.tile-size == TileSize.large ? 2 : 1;
|
||||
changed(i) => {
|
||||
root.tile-size-changed(
|
||||
i == 0 ? TileSize.small : i == 2 ? TileSize.large : TileSize.medium);
|
||||
}
|
||||
}
|
||||
if root.section == SettingSection.general : SettingItem {
|
||||
label: "关闭窗口时最小化到托盘";
|
||||
description: "避免误关正在运行的游戏";
|
||||
kind: ControlKind.toggle;
|
||||
checked: root.close-to-tray;
|
||||
toggled(v) => { root.close-to-tray-changed(v); }
|
||||
}
|
||||
|
||||
// ── 数据 ────────────────────────────────────────
|
||||
if root.section == SettingSection.data : SettingGroup { title: "数据目录(D6 三模式)"; }
|
||||
if root.section == SettingSection.data : SettingItem {
|
||||
label: "存储模式";
|
||||
description: "便携(运行目录 .ULL/.minecraft)/ 标准(系统应用数据目录)/ 自定义";
|
||||
kind: ControlKind.segmented;
|
||||
options: ["便携", "标准", "自定义"];
|
||||
selected: root.data-mode;
|
||||
changed(i) => {
|
||||
root.data-mode = i;
|
||||
root.data-mode-changed(i);
|
||||
}
|
||||
}
|
||||
if root.section == SettingSection.data : SettingItem {
|
||||
label: "当前路径";
|
||||
description: root.data-path;
|
||||
kind: ControlKind.button;
|
||||
button-text: "迁移…";
|
||||
clicked => { root.migrate-data(); }
|
||||
}
|
||||
|
||||
// ── 下载 ────────────────────────────────────────
|
||||
if root.section == SettingSection.download : SettingGroup { title: "下载(D7)"; }
|
||||
if root.section == SettingSection.download : SettingItem {
|
||||
label: "并发数";
|
||||
kind: ControlKind.segmented;
|
||||
options: ["4", "8", "16"];
|
||||
selected: root.download-concurrency;
|
||||
changed(i) => {
|
||||
root.download-concurrency = i;
|
||||
root.download-concurrency-changed(i);
|
||||
}
|
||||
}
|
||||
if root.section == SettingSection.download : SettingItem {
|
||||
label: "地区判定";
|
||||
description: "当前:" + root.region-label + "(决定是否走国内镜像)";
|
||||
kind: ControlKind.button;
|
||||
button-text: "重新检测";
|
||||
clicked => { root.detect-region(); }
|
||||
}
|
||||
|
||||
// ── Java ────────────────────────────────────────
|
||||
if root.section == SettingSection.java : SettingGroup { title: "Java(D13)"; }
|
||||
if root.section == SettingSection.java : SettingItem {
|
||||
label: "Java 管理";
|
||||
description: "基准 JDK17 自动下载 · 多版本可选 · 不匹配时黄条提示";
|
||||
kind: ControlKind.button;
|
||||
button-text: "管理多版本";
|
||||
clicked => { root.manage-java(); }
|
||||
}
|
||||
|
||||
// ── 账户 ────────────────────────────────────────
|
||||
if root.section == SettingSection.account : SettingGroup { title: "账户(D9)"; }
|
||||
if root.section == SettingSection.account : SettingItem {
|
||||
label: "当前账户";
|
||||
description: root.account-label;
|
||||
kind: ControlKind.button;
|
||||
button-text: "登录 / 切换";
|
||||
clicked => { root.login(); }
|
||||
}
|
||||
|
||||
// ── AI ──────────────────────────────────────────
|
||||
if root.section == SettingSection.ai : SettingGroup { title: "AI 助手(D4)"; }
|
||||
if root.section == SettingSection.ai : SettingItem {
|
||||
label: "模型端点";
|
||||
description: "OpenAI 兼容 / 本地 llama.cpp / Anthropic / 自定义";
|
||||
kind: ControlKind.segmented;
|
||||
options: ["OpenAI", "llama.cpp", "Anthropic", "自定义"];
|
||||
selected: root.ai-endpoint;
|
||||
changed(i) => {
|
||||
root.ai-endpoint = i;
|
||||
root.ai-endpoint-changed(i);
|
||||
}
|
||||
}
|
||||
if root.section == SettingSection.ai : SettingItem {
|
||||
label: "YOLO 模式";
|
||||
description: "跳过全部确认弹窗(审计照记),账户/凭据操作永不 YOLO";
|
||||
kind: ControlKind.toggle;
|
||||
checked: root.yolo;
|
||||
toggled(v) => { root.yolo-changed(v); }
|
||||
}
|
||||
if root.section == SettingSection.ai : SettingItem {
|
||||
label: "MCP server";
|
||||
description: "允许外部客户端(如 Claude Desktop)调用工具集";
|
||||
kind: ControlKind.toggle;
|
||||
checked: root.mcp-enabled;
|
||||
toggled(v) => { root.mcp-changed(v); }
|
||||
}
|
||||
if root.section == SettingSection.ai : SettingItem {
|
||||
label: "审计日志";
|
||||
description: "AI 的所有写操作都有记录";
|
||||
kind: ControlKind.button;
|
||||
button-text: "查看";
|
||||
clicked => { root.open-audit-log(); }
|
||||
}
|
||||
|
||||
// ── 代理 ────────────────────────────────────────
|
||||
if root.section == SettingSection.proxy : SettingGroup { title: "代理"; }
|
||||
if root.section == SettingSection.proxy : SettingItem {
|
||||
label: "HTTP 代理";
|
||||
description: "留空则使用系统代理";
|
||||
kind: ControlKind.text;
|
||||
button-text: "http://127.0.0.1:7890";
|
||||
value <=> root.proxy;
|
||||
edited(t) => { root.proxy-changed(t); }
|
||||
}
|
||||
|
||||
// ── 关于 ────────────────────────────────────────
|
||||
if root.section == SettingSection.about : SettingGroup { title: "关于"; }
|
||||
if root.section == SettingSection.about : SettingItem {
|
||||
label: "版本";
|
||||
description: root.version;
|
||||
}
|
||||
if root.section == SettingSection.about : SettingItem {
|
||||
label: "许可";
|
||||
description: "Apache-2.0(Slint 走 RF 2.0 轨道)";
|
||||
}
|
||||
if root.section == SettingSection.about : Rectangle {
|
||||
height: 120px;
|
||||
AboutSlint { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
// 主窗口框架(D16 §1):无边框标题栏 + 左侧可折叠导航 + 内容区路由 + 右侧 AI 常驻栏 + 对话框/Toast 覆盖层。
|
||||
// 这里只做「组装 + 路由转发」,状态全在 Rust 侧(state.rs),Slint 不持有业务真相。
|
||||
// main.slint(阶段 B 接线)只负责实例化 AppShell 并把 Window 的窗口事件接上。
|
||||
import { Theme } from "theme/tokens.slint";
|
||||
import { Metrics } from "theme/metrics.slint";
|
||||
import {
|
||||
RouteKind, TileSize, InstanceView, SettingSection, DownloadCategory, ThemeMode, BgFillKind,
|
||||
UiTile, UiVersion, UiLogSession, UiLogLine, UiDiagnosis, UiChatMessage, UiDialog, UiToast,
|
||||
} from "models.slint";
|
||||
import { TitleBar } from "components/titlebar.slint";
|
||||
import { Nav } from "components/nav.slint";
|
||||
import { AiPanel } from "components/ai-panel.slint";
|
||||
import { UiText, TextRole } from "components/label.slint";
|
||||
import { MetroButton, ButtonKind } from "widgets/button.slint";
|
||||
import { DialogHost } from "widgets/dialog.slint";
|
||||
import { ToastHost } from "widgets/toast.slint";
|
||||
import { InstancesPage } from "pages/instances.slint";
|
||||
import { DownloadPage } from "pages/download.slint";
|
||||
import { LogsPage } from "pages/logs.slint";
|
||||
import { SettingsPage } from "pages/settings.slint";
|
||||
|
||||
export component AppShell inherits Rectangle {
|
||||
// ── 窗口 ────────────────────────────────────────────────────
|
||||
in property <string> app-title: "Unlucky Launcher";
|
||||
in property <bool> maximized: false;
|
||||
|
||||
// ── 路由 ────────────────────────────────────────────────────
|
||||
in property <RouteKind> route: RouteKind.instances;
|
||||
|
||||
// ── 导航 / 账户 ──────────────────────────────────────────────
|
||||
in property <bool> nav-collapsed: false;
|
||||
in property <string> account-name: "未登录";
|
||||
in property <string> account-initial: "?";
|
||||
in property <color> account-hue: #5C2D91;
|
||||
|
||||
// ── AI 栏(双形态共享同一份会话)──────────────────────────────
|
||||
in property <bool> ai-collapsed: false;
|
||||
in property <[UiChatMessage]> ai-messages;
|
||||
in property <bool> ai-streaming: false;
|
||||
in property <bool> yolo: false;
|
||||
in property <string> ai-endpoint-label: "llama.cpp · 本地";
|
||||
in-out property <string> ai-draft: "";
|
||||
|
||||
// ── 页面数据 ────────────────────────────────────────────────
|
||||
in property <[UiTile]> tiles;
|
||||
in property <[UiTile]> running-tiles;
|
||||
in property <[UiVersion]> versions;
|
||||
in property <[UiLogSession]> log-sessions;
|
||||
in property <[UiLogLine]> log-lines;
|
||||
in property <UiDiagnosis> diagnosis;
|
||||
in property <bool> has-diagnosis: false;
|
||||
in property <string> selected-session: "";
|
||||
|
||||
// ── 偏好(持久化键见 SubAgentsTalk/app-DTO通道约定.md)──────────
|
||||
in-out property <TileSize> tile-size: TileSize.medium;
|
||||
in-out property <InstanceView> instance-view: InstanceView.tiles;
|
||||
in-out property <string> instance-query: "";
|
||||
in-out property <SettingSection> settings-section: SettingSection.general;
|
||||
/// D17 主题三态(auto 跟随系统;light/dark 钉死)。Rust 侧同时写 Theme 全局。
|
||||
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
|
||||
/// 外观(高级)四件的 in-out 通道:MainWindow ↔ SettingsPage(图片本身走 `Theme.bg-image`)
|
||||
in-out property <bool> bg-image-enabled: false;
|
||||
in-out property <string> bg-image: "";
|
||||
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
|
||||
in-out property <float> bg-dim: 0.35;
|
||||
in-out property <float> panel-alpha: 1.0;
|
||||
in-out property <bool> glass: false;
|
||||
/// 设置页编辑的十六进制串(`accent-color` 是解析后的颜色,只给 Theme 用)
|
||||
in-out property <string> accent-hex: "";
|
||||
/// 强调色输入是否非法(设置页亮 warn 行)
|
||||
in-out property <bool> accent-invalid: false;
|
||||
in-out property <DownloadCategory> download-category: DownloadCategory.release;
|
||||
in-out property <bool> download-installed-only: false;
|
||||
/// 下载页版本号筛选词(输入由页面写回,state.download_query 参与过滤)
|
||||
in-out property <string> download-query: "";
|
||||
|
||||
// ── 对话框队列 / Toast ───────────────────────────────────────
|
||||
in property <UiDialog> dialog;
|
||||
in property <bool> dialog-open: false;
|
||||
in property <int> dialog-queued: 0;
|
||||
in property <[UiToast]> toasts;
|
||||
|
||||
// ── 窗口控制(拖拽走 WindowMoveArea,不需要 Rust 参与)────────
|
||||
callback toggle-maximize();
|
||||
callback minimize();
|
||||
callback request-close();
|
||||
|
||||
// ── 导航 / AI ───────────────────────────────────────────────
|
||||
callback navigate(RouteKind);
|
||||
callback toggle-nav();
|
||||
callback toggle-ai();
|
||||
callback expand-ai();
|
||||
callback dock-ai();
|
||||
callback toggle-yolo();
|
||||
callback ai-send(string);
|
||||
callback ai-stop();
|
||||
|
||||
// ── 实例页 ──────────────────────────────────────────────────
|
||||
callback instance-launch(string);
|
||||
callback instance-configure(string);
|
||||
callback instance-stop(string);
|
||||
callback instance-open(string);
|
||||
callback new-instance();
|
||||
callback instance-view-changed(InstanceView);
|
||||
callback tile-size-changed(TileSize);
|
||||
callback instance-query-changed(string);
|
||||
|
||||
// ── 下载页 ──────────────────────────────────────────────────
|
||||
callback download-category-changed(DownloadCategory);
|
||||
callback download-install(string);
|
||||
callback installed-only-changed(bool);
|
||||
callback download-query-changed(string);
|
||||
callback ancient-help();
|
||||
|
||||
// ── 日志页 ──────────────────────────────────────────────────
|
||||
callback log-select(string);
|
||||
callback log-ask-ai(string);
|
||||
callback log-apply-fix();
|
||||
|
||||
// ── 设置页 ──────────────────────────────────────────────────
|
||||
callback settings-section-changed(SettingSection);
|
||||
callback theme-changed(ThemeMode);
|
||||
callback bg-image-enabled-changed(bool);
|
||||
callback bg-image-changed(string);
|
||||
callback bg-fill-changed(BgFillKind);
|
||||
callback bg-dim-changed(float);
|
||||
callback panel-alpha-changed(float);
|
||||
callback glass-changed(bool);
|
||||
callback accent-color-changed(string);
|
||||
callback accent-swatch-picked(int);
|
||||
callback yolo-changed(bool);
|
||||
callback mcp-changed(bool);
|
||||
callback ai-endpoint-changed(int);
|
||||
|
||||
// ── 对话框 / Toast ──────────────────────────────────────────
|
||||
callback dialog-primary();
|
||||
callback dialog-secondary();
|
||||
callback dialog-dismissed();
|
||||
callback toast-dismissed(string);
|
||||
|
||||
// 窗口底色交给 main.slint 的 Window(不透明 `canvas-solid`),这里只铺背景图层
|
||||
background: transparent;
|
||||
|
||||
// 玻璃拟态的对齐基准:整窗逻辑尺寸(components/glass.slint 反向偏移用)
|
||||
init => {
|
||||
Theme.window-width = root.width;
|
||||
Theme.window-height = root.height;
|
||||
}
|
||||
changed width => { Theme.window-width = root.width; }
|
||||
changed height => { Theme.window-height = root.height; }
|
||||
|
||||
// ── ① 自定义窗口背景图(09 §101)────────────────────────────
|
||||
// 只在「开关打开且图片已加载」时才画:空 image 的 width 为 0,出厂态零开销。
|
||||
if Theme.bg-image.width > 0 : Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: root.width;
|
||||
height: root.height;
|
||||
clip: true;
|
||||
background: Theme.canvas-solid;
|
||||
|
||||
Image {
|
||||
source: Theme.bg-image;
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
// tile 模式由 Rust 预平铺成整窗画布,故这里等同 cover
|
||||
image-fit: root.bg-fill == BgFillKind.contain ? contain : cover;
|
||||
}
|
||||
}
|
||||
|
||||
// ── ② 暗化层(09 §111:保证前景可读;0 = 不压暗)─────────────
|
||||
if Theme.bg-image.width > 0 && Theme.bg-dim > 0 : Rectangle {
|
||||
x: 0;
|
||||
y: 0;
|
||||
width: root.width;
|
||||
height: root.height;
|
||||
background: rgba(0, 0, 0, Theme.bg-dim);
|
||||
}
|
||||
|
||||
VerticalLayout {
|
||||
TitleBar {
|
||||
title: root.app-title;
|
||||
subtitle: "P0 骨架 · Metro";
|
||||
maximized: root.maximized;
|
||||
toggle-maximize => { root.toggle-maximize(); }
|
||||
minimize => { root.minimize(); }
|
||||
request-close => { root.request-close(); }
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
// 左侧主导航
|
||||
Nav {
|
||||
active: root.route;
|
||||
collapsed: root.nav-collapsed;
|
||||
account-name: root.account-name;
|
||||
account-initial: root.account-initial;
|
||||
account-hue: root.account-hue;
|
||||
navigate(r) => { root.navigate(r); }
|
||||
toggle-collapsed => { root.toggle-nav(); }
|
||||
account-clicked => { root.navigate(RouteKind.settings); root.settings-section-changed(SettingSection.account); }
|
||||
}
|
||||
|
||||
// 内容区(每页独立滚动,路由切换栈语义在 Rust Router)
|
||||
Rectangle {
|
||||
horizontal-stretch: 1;
|
||||
background: Theme.bg-canvas;
|
||||
|
||||
if root.route == RouteKind.instances : InstancesPage {
|
||||
tiles: root.tiles;
|
||||
running: root.running-tiles;
|
||||
view: root.instance-view;
|
||||
tile-size: root.tile-size;
|
||||
query: root.instance-query;
|
||||
launch(id) => { root.instance-launch(id); }
|
||||
configure(id) => { root.instance-configure(id); }
|
||||
stop(id) => { root.instance-stop(id); }
|
||||
open(id) => { root.instance-open(id); }
|
||||
new-instance => { root.new-instance(); }
|
||||
view-changed(v) => {
|
||||
root.instance-view = v;
|
||||
root.instance-view-changed(v);
|
||||
}
|
||||
tile-size-changed(s) => {
|
||||
root.tile-size = s;
|
||||
root.tile-size-changed(s);
|
||||
}
|
||||
query-changed(q) => { root.instance-query-changed(q); }
|
||||
}
|
||||
|
||||
if root.route == RouteKind.download : DownloadPage {
|
||||
versions: root.versions;
|
||||
category: root.download-category;
|
||||
installed-only: root.download-installed-only;
|
||||
query: root.download-query;
|
||||
install(id) => { root.download-install(id); }
|
||||
query-changed(q) => {
|
||||
root.download-query = q;
|
||||
root.download-query-changed(q);
|
||||
}
|
||||
ancient-help => { root.ancient-help(); }
|
||||
category-changed(c) => {
|
||||
root.download-category = c;
|
||||
root.download-category-changed(c);
|
||||
}
|
||||
installed-only-changed(v) => {
|
||||
root.download-installed-only = v;
|
||||
root.installed-only-changed(v);
|
||||
}
|
||||
}
|
||||
|
||||
if root.route == RouteKind.logs : LogsPage {
|
||||
sessions: root.log-sessions;
|
||||
lines: root.log-lines;
|
||||
diagnosis: root.diagnosis;
|
||||
has-diagnosis: root.has-diagnosis;
|
||||
selected: root.selected-session;
|
||||
select(id) => { root.log-select(id); }
|
||||
ask-ai(id) => { root.log-ask-ai(id); }
|
||||
apply-fix => { root.log-apply-fix(); }
|
||||
}
|
||||
|
||||
if root.route == RouteKind.settings : SettingsPage {
|
||||
section: root.settings-section;
|
||||
theme-mode: root.theme-mode;
|
||||
bg-image-enabled: root.bg-image-enabled;
|
||||
bg-image: root.bg-image;
|
||||
bg-fill: root.bg-fill;
|
||||
bg-dim: root.bg-dim;
|
||||
panel-alpha: root.panel-alpha;
|
||||
glass: root.glass;
|
||||
accent-color: root.accent-hex;
|
||||
accent-invalid: root.accent-invalid;
|
||||
section-changed(s) => {
|
||||
root.settings-section = s;
|
||||
root.settings-section-changed(s);
|
||||
}
|
||||
theme-changed(mode) => {
|
||||
root.theme-mode = mode;
|
||||
root.theme-changed(mode);
|
||||
}
|
||||
bg-image-enabled-changed(v) => { root.bg-image-enabled-changed(v); }
|
||||
bg-image-changed(path) => { root.bg-image-changed(path); }
|
||||
bg-fill-changed(fill) => { root.bg-fill-changed(fill); }
|
||||
bg-dim-changed(v) => { root.bg-dim-changed(v); }
|
||||
panel-alpha-changed(v) => { root.panel-alpha-changed(v); }
|
||||
glass-changed(v) => { root.glass-changed(v); }
|
||||
accent-color-changed(text) => {
|
||||
root.accent-hex = text;
|
||||
root.accent-color-changed(text);
|
||||
}
|
||||
accent-swatch-picked(index) => { root.accent-swatch-picked(index); }
|
||||
yolo-changed(v) => { root.yolo-changed(v); }
|
||||
mcp-changed(v) => { root.mcp-changed(v); }
|
||||
ai-endpoint-changed(i) => { root.ai-endpoint-changed(i); }
|
||||
}
|
||||
|
||||
// AI 拆成独立全宽页:与右侧栏共用同一份 ai-messages(切换无损)
|
||||
if root.route == RouteKind.agent : AiPanel {
|
||||
docked: false;
|
||||
messages: root.ai-messages;
|
||||
collapsed: false;
|
||||
yolo: root.yolo;
|
||||
streaming: root.ai-streaming;
|
||||
endpoint-label: root.ai-endpoint-label;
|
||||
draft <=> root.ai-draft;
|
||||
dock => { root.dock-ai(); }
|
||||
toggle-yolo => { root.toggle-yolo(); }
|
||||
send(t) => { root.ai-send(t); }
|
||||
stop => { root.ai-stop(); }
|
||||
}
|
||||
|
||||
// 实例详情 G4:P0 只留占位(点击磁贴进入)
|
||||
if root.route == RouteKind.detail : VerticalLayout {
|
||||
alignment: center;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
UiText {
|
||||
role: TextRole.title;
|
||||
text: "实例详情(G4)";
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: "P0 骨架未实现:概要与设置 tab 在 G4 补齐";
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
MetroButton {
|
||||
kind: ButtonKind.standard;
|
||||
text: "返回实例页";
|
||||
clicked => { root.navigate(RouteKind.instances); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 右侧 AI 常驻栏(拆成独立页时让位给内容区)
|
||||
AiPanel {
|
||||
visible: root.route != RouteKind.agent;
|
||||
docked: true;
|
||||
collapsed: root.ai-collapsed;
|
||||
messages: root.ai-messages;
|
||||
yolo: root.yolo;
|
||||
streaming: root.ai-streaming;
|
||||
endpoint-label: root.ai-endpoint-label;
|
||||
draft <=> root.ai-draft;
|
||||
toggle-collapsed => { root.toggle-ai(); }
|
||||
expand => { root.expand-ai(); }
|
||||
toggle-yolo => { root.toggle-yolo(); }
|
||||
send(t) => { root.ai-send(t); }
|
||||
stop => { root.ai-stop(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 覆盖层:模态队列(一次一条)+ 右下 Toast
|
||||
DialogHost {
|
||||
current: root.dialog;
|
||||
open: root.dialog-open;
|
||||
queued: root.dialog-queued;
|
||||
primary => { root.dialog-primary(); }
|
||||
secondary => { root.dialog-secondary(); }
|
||||
dismissed => { root.dialog-dismissed(); }
|
||||
}
|
||||
|
||||
ToastHost {
|
||||
toasts: root.toasts;
|
||||
dismissed(id) => { root.toast-dismissed(id); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// 布局度量令牌(D16 定稿的尺寸口径集中在此):
|
||||
// 导航栏折叠宽度、AI 栏宽度、标题栏高度、磁贴三档尺寸与列数。
|
||||
import { TileSize } from "../models.slint";
|
||||
|
||||
export global Metrics {
|
||||
// 间距刻度(4 的倍数,Metro 栅格)
|
||||
out property <length> gap-1: 4px;
|
||||
out property <length> gap-2: 8px;
|
||||
out property <length> gap-3: 12px;
|
||||
out property <length> gap-4: 16px;
|
||||
out property <length> gap-5: 24px;
|
||||
out property <length> gap-6: 32px;
|
||||
|
||||
out property <length> radius-sm: 2px;
|
||||
out property <length> radius-md: 4px;
|
||||
out property <length> radius-lg: 8px;
|
||||
|
||||
// 主窗口骨架
|
||||
out property <length> titlebar-height: 40px;
|
||||
out property <length> titlebar-button-width: 46px;
|
||||
out property <length> accent-line: 2px;
|
||||
out property <length> nav-expanded-width: 88px;
|
||||
out property <length> nav-collapsed-width: 48px;
|
||||
out property <length> ai-panel-width: 320px;
|
||||
out property <length> ai-rail-width: 44px;
|
||||
out property <length> page-header-height: 56px;
|
||||
out property <length> running-strip-height: 32px;
|
||||
out property <length> row-height: 44px;
|
||||
out property <length> control-height: 32px;
|
||||
out property <length> touch-target: 32px;
|
||||
|
||||
// 磁贴三档(Q24-3:默认中磁贴 4 列,设置可调小 6 / 大 3)
|
||||
in-out property <TileSize> tile-size: TileSize.medium;
|
||||
out property <int> tile-columns:
|
||||
tile-size == TileSize.small ? 6
|
||||
: tile-size == TileSize.large ? 3
|
||||
: 4;
|
||||
out property <length> tile-height:
|
||||
tile-size == TileSize.small ? 104px
|
||||
: tile-size == TileSize.large ? 176px
|
||||
: 136px;
|
||||
out property <length> tile-icon-size:
|
||||
tile-size == TileSize.small ? 32px
|
||||
: tile-size == TileSize.large ? 56px
|
||||
: 44px;
|
||||
// 小磁贴只留图标+名字+启动键,藏起徽标与最后游玩时间(空间不足)
|
||||
out property <bool> tile-compact: tile-size == TileSize.small;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// Metro 主题令牌(D14 + D17 主题三态 + 09 §101-104「外观(高级)」):palette + 排版层级 + 字体栈 +
|
||||
// 动效时长 + 外观令牌(背景图 / 面板半透明度 / 玻璃拟态 / 强调色)。
|
||||
//
|
||||
// 结构约定:
|
||||
// - `LightPalette` / `DarkPalette` = 两套完整色板(**不是**一套加条件),换肤只改这两处。
|
||||
// - `Theme` = 解析器:按主题三态(auto/light/dark)挑一套,并持有**共享**的 accent 与字体/排版。
|
||||
// - auto 跟随系统:`Theme.system-theme` 由 Rust 的 `core::platform::theme_probe` 灌入(启动对齐 +
|
||||
// 未知时兜底轮询),后端支持时另有 `Palette.color-scheme` 实时热切;两者都不认识就按浅色。
|
||||
// - 「外观(高级)」四件全部默认关闭:`panel-alpha` 1.0 / `glass` false / `bg-image` 空 /
|
||||
// `accent-override` 透明——出厂观感与 M17 骨架逐像素一致(09 §111 硬约束)。
|
||||
// - 组件只准用 `Theme.*`,不得出现裸色字面量(背景图暗化层是唯一例外,它是「遮罩」而非配色)。
|
||||
|
||||
import { ThemeMode } from "../models.slint";
|
||||
import { Palette } from "std-widgets.slint";
|
||||
|
||||
// ── 亮色色板 ────────────────────────────────────────────────────
|
||||
export global LightPalette {
|
||||
out property <color> bg-canvas: #F3F3F3;
|
||||
out property <color> bg-surface: #FFFFFF;
|
||||
out property <color> bg-elevated: #FFFFFF;
|
||||
out property <color> bg-titlebar: #EDEDED;
|
||||
out property <color> bg-hover: #E9E9E9;
|
||||
out property <color> bg-pressed: #DEDEDE;
|
||||
out property <color> bg-input: #FFFFFF;
|
||||
|
||||
out property <color> fg-primary: #1A1A1A;
|
||||
out property <color> fg-secondary: #5F5F5F;
|
||||
out property <color> fg-disabled: #9A9A9A;
|
||||
|
||||
out property <color> stroke: #E1E1E1;
|
||||
out property <color> stroke-strong: #C8C8C8;
|
||||
out property <color> shadow: #00000026;
|
||||
out property <color> scrim: #00000099;
|
||||
|
||||
out property <color> accent-soft: #E5F1FB;
|
||||
out property <color> accent-hover: #106EBE;
|
||||
out property <color> accent-pressed: #005A9E;
|
||||
|
||||
out property <color> state-success: #107C10;
|
||||
out property <color> state-success-soft: #DFF6DD;
|
||||
out property <color> state-warn: #9D5D00;
|
||||
out property <color> state-warn-soft: #FFF4CE;
|
||||
out property <color> state-danger: #C42B1C;
|
||||
out property <color> state-danger-hover: #A82214;
|
||||
out property <color> state-danger-soft: #FDE7E9;
|
||||
out property <color> state-info-soft: #E7F1FA;
|
||||
}
|
||||
|
||||
// ── 暗色色板 ────────────────────────────────────────────────────
|
||||
export global DarkPalette {
|
||||
out property <color> bg-canvas: #1B1B1B;
|
||||
out property <color> bg-surface: #232323;
|
||||
out property <color> bg-elevated: #2B2B2B;
|
||||
out property <color> bg-titlebar: #161616;
|
||||
out property <color> bg-hover: #2F2F2F;
|
||||
out property <color> bg-pressed: #383838;
|
||||
out property <color> bg-input: #1E1E1E;
|
||||
|
||||
out property <color> fg-primary: #F2F2F2;
|
||||
out property <color> fg-secondary: #A6A6A6;
|
||||
out property <color> fg-disabled: #6B6B6B;
|
||||
|
||||
out property <color> stroke: #3A3A3A;
|
||||
out property <color> stroke-strong: #4A4A4A;
|
||||
out property <color> shadow: #000000CC;
|
||||
out property <color> scrim: #00000099;
|
||||
|
||||
out property <color> accent-soft: #0F2A3F;
|
||||
out property <color> accent-hover: #2B8FE0;
|
||||
out property <color> accent-pressed: #005A9E;
|
||||
|
||||
out property <color> state-success: #4CCB4C;
|
||||
out property <color> state-success-soft: #16321A;
|
||||
out property <color> state-warn: #FFD24C;
|
||||
out property <color> state-warn-soft: #3A2E0F;
|
||||
out property <color> state-danger: #FF6B6B;
|
||||
out property <color> state-danger-hover: #FF8A8A;
|
||||
out property <color> state-danger-soft: #3A1A1A;
|
||||
out property <color> state-info-soft: #10263A;
|
||||
}
|
||||
|
||||
// ── 解析器 ──────────────────────────────────────────────────────
|
||||
export global Theme {
|
||||
// ── 主题三态(D17 设置页「外观」分组,出厂 auto)──────────────────
|
||||
// D17 主题三态(设置页「外观」分组,出厂 auto)
|
||||
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
|
||||
// 系统主题来源(M41):0 = 未知(此时回落到 Slint 后端 `Palette.color-scheme`),
|
||||
// 1 = 浅色 / 2 = 深色。由 Rust 的 `core::platform::theme_probe` 探测后灌入:
|
||||
// 启动时给首帧对齐,之后按需轮询兜底(后端不支持系统主题时 auto 仍可用)。
|
||||
in-out property <int> system-theme: 0;
|
||||
// 后端是否认得系统主题(`unknown` 表示不支持/无 portal)。
|
||||
out property <bool> system-theme-known: Palette.color-scheme != ColorScheme.unknown;
|
||||
// 是否深色:显式钉死(light/dark)优先;auto 时用探测值,探测未知才问后端。
|
||||
out property <bool> dark: theme-mode == ThemeMode.dark
|
||||
|| (theme-mode == ThemeMode.auto
|
||||
&& (system-theme == 2
|
||||
|| (system-theme != 1 && Palette.color-scheme == ColorScheme.dark)));
|
||||
|
||||
// ── 外观(高级)令牌(09 §101-104 / §111:出厂全部关闭)─────────
|
||||
// 全局面板半透明度:`bg-*` 令牌统一按 `panel-alpha` 重建(见下方「面板底色」段),
|
||||
// 组件侧零改动即透出背景图。出厂 1.0 = 完全不透明,Metro 纯色外观与 M17 骨架一致。
|
||||
in-out property <float> panel-alpha: 1.0;
|
||||
// 自定义窗口背景图(空 image = 纯色背景,出厂态)。
|
||||
in-out property <image> bg-image;
|
||||
// 背景图暗化层强度(0~0.95,越大前景越清晰)。Rust 侧夹到 schema 范围。
|
||||
in-out property <float> bg-dim: 0.35;
|
||||
// 玻璃拟态:预生成模糊层(Rust 侧降采样 + box blur),卡片内按 `absolute-position`
|
||||
// 反向偏移对齐整窗,得到 Slint 版「毛玻璃」(无 backdrop-filter 的替代手法)。
|
||||
in-out property <bool> glass: false;
|
||||
in-out property <image> bg-blur;
|
||||
// 玻璃层对齐用的窗口逻辑尺寸(AppShell 在 init/changed 里灌入)。
|
||||
in-out property <length> window-width: 1180px;
|
||||
in-out property <length> window-height: 760px;
|
||||
|
||||
// ── 强调色(accent 令牌全域生效;两套色板共享)──────────────────
|
||||
// `accent-override` 的 alpha == 0 表示「未自定义」,走 D14 出厂 Metro 蓝。
|
||||
// (color 的 `.alpha` 字段是 0~255 整数,不是 0~1 浮点。)
|
||||
in-out property <color> accent-override: transparent;
|
||||
out property <bool> accent-custom: accent-override.alpha > 1;
|
||||
out property <color> accent: accent-custom ? accent-override : #0078D4;
|
||||
// 自定义时由覆盖色派生 hover/pressed/soft(未自定义仍走双色板常量,出场观感不变)。
|
||||
out property <color> accent-hover: accent-custom
|
||||
? (dark ? accent.brighter(0.18) : accent.darker(0.12))
|
||||
: (dark ? DarkPalette.accent-hover : LightPalette.accent-hover);
|
||||
out property <color> accent-pressed: accent-custom
|
||||
? (dark ? accent.brighter(0.28) : accent.darker(0.24))
|
||||
: (dark ? DarkPalette.accent-pressed : LightPalette.accent-pressed);
|
||||
out property <color> accent-soft: accent-custom
|
||||
? accent.mix(surface-solid, 0.82)
|
||||
: (dark ? DarkPalette.accent-soft : LightPalette.accent-soft);
|
||||
out property <color> accent-contrast: #FFFFFF;
|
||||
// accent 上的前景色按相对亮度自动选黑/白(自定义亮黄、浅青时白字会糊)。
|
||||
// 注意:Slint 的 color 通道字段(`.red` 等)是 0~255 的**整数**。
|
||||
out property <float> accent-luma: accent.red * 0.299 + accent.green * 0.587 + accent.blue * 0.114;
|
||||
out property <color> fg-on-accent: accent-luma > 160 ? #1A1A1A : #FFFFFF;
|
||||
|
||||
// ── 面板底色(`panel-alpha` 统一透出背景图)────────────────────
|
||||
// `*-solid` 是不透明原件(窗口自身底色 / accent.mix 的混合基准必须不透明,
|
||||
// 否则浮点叠加会让 accent-soft 随 panel-alpha 一起变淡)。
|
||||
// 半透明色用 `rgba(r, g, b, a)` 重建而不是 `.with-alpha()`:后者返回 Brush,
|
||||
// 赋给 `<color>` 属性会类型不符(Slint 无 Brush → color 隐式回退)。
|
||||
out property <color> surface-solid: dark ? DarkPalette.bg-surface : LightPalette.bg-surface;
|
||||
out property <color> canvas-solid: dark ? DarkPalette.bg-canvas : LightPalette.bg-canvas;
|
||||
out property <color> surface-elevated-solid: dark ? DarkPalette.bg-elevated : LightPalette.bg-elevated;
|
||||
out property <color> titlebar-solid: dark ? DarkPalette.bg-titlebar : LightPalette.bg-titlebar;
|
||||
out property <color> hover-solid: dark ? DarkPalette.bg-hover : LightPalette.bg-hover;
|
||||
out property <color> pressed-solid: dark ? DarkPalette.bg-pressed : LightPalette.bg-pressed;
|
||||
out property <color> input-solid: dark ? DarkPalette.bg-input : LightPalette.bg-input;
|
||||
|
||||
out property <color> bg-canvas: rgba(
|
||||
canvas-solid.red, canvas-solid.green, canvas-solid.blue, panel-alpha);
|
||||
out property <color> bg-surface: rgba(
|
||||
surface-solid.red, surface-solid.green, surface-solid.blue, panel-alpha);
|
||||
out property <color> bg-elevated: rgba(
|
||||
surface-elevated-solid.red, surface-elevated-solid.green, surface-elevated-solid.blue, panel-alpha);
|
||||
out property <color> bg-titlebar: rgba(
|
||||
titlebar-solid.red, titlebar-solid.green, titlebar-solid.blue, panel-alpha);
|
||||
out property <color> bg-hover: rgba(
|
||||
hover-solid.red, hover-solid.green, hover-solid.blue, panel-alpha);
|
||||
out property <color> bg-pressed: rgba(
|
||||
pressed-solid.red, pressed-solid.green, pressed-solid.blue, panel-alpha);
|
||||
out property <color> bg-input: rgba(
|
||||
input-solid.red, input-solid.green, input-solid.blue, panel-alpha);
|
||||
|
||||
out property <color> fg-primary: dark ? DarkPalette.fg-primary : LightPalette.fg-primary;
|
||||
out property <color> fg-secondary: dark ? DarkPalette.fg-secondary : LightPalette.fg-secondary;
|
||||
out property <color> fg-disabled: dark ? DarkPalette.fg-disabled : LightPalette.fg-disabled;
|
||||
|
||||
out property <color> stroke: dark ? DarkPalette.stroke : LightPalette.stroke;
|
||||
out property <color> stroke-strong: dark ? DarkPalette.stroke-strong : LightPalette.stroke-strong;
|
||||
out property <color> shadow: dark ? DarkPalette.shadow : LightPalette.shadow;
|
||||
out property <color> scrim: dark ? DarkPalette.scrim : LightPalette.scrim;
|
||||
|
||||
out property <color> state-success: dark ? DarkPalette.state-success : LightPalette.state-success;
|
||||
out property <color> state-success-soft: dark ? DarkPalette.state-success-soft : LightPalette.state-success-soft;
|
||||
out property <color> state-warn: dark ? DarkPalette.state-warn : LightPalette.state-warn;
|
||||
out property <color> state-warn-soft: dark ? DarkPalette.state-warn-soft : LightPalette.state-warn-soft;
|
||||
out property <color> state-danger: dark ? DarkPalette.state-danger : LightPalette.state-danger;
|
||||
out property <color> state-danger-hover: dark ? DarkPalette.state-danger-hover : LightPalette.state-danger-hover;
|
||||
out property <color> state-danger-soft: dark ? DarkPalette.state-danger-soft : LightPalette.state-danger-soft;
|
||||
out property <color> state-info-soft: dark ? DarkPalette.state-info-soft : LightPalette.state-info-soft;
|
||||
|
||||
// ── 字体 ────────────────────────────────────────────────────
|
||||
// Segoe UI 不可再分发(微软许可)→ Windows 用系统自带,其他平台用 Selawik
|
||||
// (微软官方开源、Segoe UI 度量兼容)+ Open Sans 回退栈(01c §7 第 5 条)。
|
||||
// Slint 的 font-family 只吃单个家族名,回退链由 Rust 侧启动时按平台选择 + 注册字体族实现:
|
||||
// windows → "Segoe UI",macos/linux → "Selawik"(随包)+ "Open Sans" 兜底。
|
||||
in-out property <string> font-family: "Selawik";
|
||||
in-out property <string> font-family-mono: "Cascadia Mono";
|
||||
// 中文回退(思源黑体/微软雅黑由系统字体匹配,这里仅作显式声明)
|
||||
in-out property <string> font-family-cjk: "Microsoft YaHei UI";
|
||||
|
||||
// 排版层级(Metro typography ramp)
|
||||
out property <length> font-size-display: 24px;
|
||||
out property <length> font-size-title: 20px;
|
||||
out property <length> font-size-subtitle: 16px;
|
||||
out property <length> font-size-body: 14px;
|
||||
out property <length> font-size-caption: 12px;
|
||||
out property <length> line-height-body: 20px;
|
||||
out property <length> line-height-caption: 16px;
|
||||
|
||||
// ── 动效(Metro 快速、克制)───────────────────────────────────
|
||||
out property <duration> motion-fast: 90ms;
|
||||
out property <duration> motion-normal: 160ms;
|
||||
out property <duration> motion-slow: 240ms;
|
||||
// D17 动画强度倍率(P0 占位,P1 接设置页滑条与「减少动画」无障碍开关)
|
||||
in-out property <float> motion-scale: 1.0;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Metro 按钮:扁平 + accent 填充,无圆角渐变,hover 只变底色(D14)。
|
||||
// 四种语义:accent(主操作)/ standard(次要)/ subtle(工具条)/ danger(危险确认)。
|
||||
// grow = true 时占满布局剩余宽度(磁贴的启动键),否则保持内容宽度(工具按钮)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
|
||||
export enum ButtonKind {
|
||||
accent,
|
||||
standard,
|
||||
subtle,
|
||||
danger,
|
||||
}
|
||||
|
||||
export component MetroButton inherits Rectangle {
|
||||
in property <ButtonKind> kind: ButtonKind.standard;
|
||||
in property <string> text: "";
|
||||
in property <IconKind> icon: IconKind.plus;
|
||||
/// 是否显示图标(纯文字按钮置 false)
|
||||
in property <bool> show-icon: false;
|
||||
in property <bool> enabled: true;
|
||||
/// 图标按钮:不画文字,尺寸压到正方形
|
||||
in property <bool> icon-only: false;
|
||||
/// 在布局中占据剩余宽度
|
||||
in property <bool> grow: false;
|
||||
in property <length> button-height: Metrics.control-height;
|
||||
callback clicked();
|
||||
|
||||
min-width: icon-only ? button-height : text-layout.preferred-width;
|
||||
height: button-height;
|
||||
horizontal-stretch: grow ? 1 : 0;
|
||||
border-radius: Metrics.radius-sm;
|
||||
border-width: kind == ButtonKind.standard ? 1px : 0px;
|
||||
border-color: Theme.stroke-strong;
|
||||
opacity: enabled ? 1.0 : 0.45;
|
||||
|
||||
background: kind == ButtonKind.accent
|
||||
? (touch.has-hover ? Theme.accent-hover : Theme.accent)
|
||||
: kind == ButtonKind.danger
|
||||
? (touch.has-hover ? Theme.state-danger-hover : Theme.state-danger)
|
||||
: kind == ButtonKind.subtle
|
||||
? (touch.pressed ? Theme.bg-pressed : touch.has-hover ? Theme.bg-hover : transparent)
|
||||
: (touch.pressed ? Theme.bg-pressed : touch.has-hover ? Theme.bg-hover : Theme.bg-surface);
|
||||
animate background { duration: Theme.motion-fast; }
|
||||
|
||||
text-layout := HorizontalLayout {
|
||||
alignment: center;
|
||||
padding-left: icon-only ? 0px : Metrics.gap-2;
|
||||
padding-right: icon-only ? 0px : Metrics.gap-2;
|
||||
spacing: Metrics.gap-1;
|
||||
|
||||
AppIcon {
|
||||
icon-size: Metrics.touch-target / 2;
|
||||
kind: root.icon;
|
||||
visible: root.show-icon || root.icon-only;
|
||||
tint: kind == ButtonKind.accent || kind == ButtonKind.danger
|
||||
? Theme.fg-on-accent
|
||||
: Theme.fg-primary;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.bodyStrong;
|
||||
text: root.text;
|
||||
visible: !root.icon-only;
|
||||
color: kind == ButtonKind.accent || kind == ButtonKind.danger
|
||||
? Theme.fg-on-accent
|
||||
: Theme.fg-primary;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
}
|
||||
|
||||
touch := TouchArea {
|
||||
mouse-cursor: root.enabled ? pointer : default;
|
||||
clicked => {
|
||||
if (root.enabled) {
|
||||
root.clicked();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
accessible-role: button;
|
||||
accessible-label: root.text;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// 对话框宿主:HMCL 队列语义(一次只显示一条,来源排序由 Rust DialogQueue 决定)+ Metro 化外观。
|
||||
// 类型:确认 / 输入 / 进度 / 错误(含诊断入口)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiDialog, DialogKind } from "../models.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
import { MetroButton, ButtonKind } from "button.slint";
|
||||
import { TextField } from "inputs.slint";
|
||||
|
||||
export component DialogHost inherits Rectangle {
|
||||
in property <UiDialog> current;
|
||||
in property <bool> open: false;
|
||||
/// 队列中剩余条数(>0 时卡片底部提示「还有 N 条待处理」,语义上是队列而非堆叠)
|
||||
in property <int> queued: 0;
|
||||
in-out property <string> input-text: "";
|
||||
callback primary();
|
||||
callback secondary();
|
||||
callback dismissed();
|
||||
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: Theme.scrim;
|
||||
visible: open;
|
||||
|
||||
// 吞掉遮罩上的点击,避免误触下层页面
|
||||
TouchArea {
|
||||
clicked => { root.dismissed(); }
|
||||
}
|
||||
|
||||
card := Rectangle {
|
||||
x: (root.width - card.width) / 2;
|
||||
y: (root.height - card.height) / 2;
|
||||
width: 440px;
|
||||
height: content.preferred-height;
|
||||
background: Theme.bg-elevated;
|
||||
border-radius: Metrics.radius-lg;
|
||||
border-width: 1px;
|
||||
border-color: Theme.stroke;
|
||||
drop-shadow-blur: 24px;
|
||||
drop-shadow-color: Theme.shadow;
|
||||
drop-shadow-offset-y: 6px;
|
||||
|
||||
content := VerticalLayout {
|
||||
padding: Metrics.gap-5;
|
||||
spacing: Metrics.gap-3;
|
||||
|
||||
HorizontalLayout {
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
if root.current.kind == DialogKind.error : AppIcon {
|
||||
kind: IconKind.error;
|
||||
icon-size: 20px;
|
||||
tint: Theme.state-danger;
|
||||
}
|
||||
if root.current.kind == DialogKind.confirm : AppIcon {
|
||||
kind: IconKind.warn;
|
||||
icon-size: 20px;
|
||||
tint: Theme.state-warn;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.title;
|
||||
text: root.current.title;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
|
||||
body-text := UiText {
|
||||
role: TextRole.body;
|
||||
text: root.current.body;
|
||||
wrap: word-wrap;
|
||||
overflow: elide;
|
||||
color: Theme.fg-secondary;
|
||||
vertical-alignment: top;
|
||||
height: body-text.preferred-height;
|
||||
}
|
||||
|
||||
if root.current.kind == DialogKind.input : TextField {
|
||||
placeholder: root.current.input_label;
|
||||
text <=> root.input-text;
|
||||
}
|
||||
|
||||
if root.current.kind == DialogKind.progress : track := Rectangle {
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: Theme.bg-pressed;
|
||||
|
||||
Rectangle {
|
||||
width: track.width * Math.min(Math.max(root.current.progress, 0), 1);
|
||||
height: track.height;
|
||||
border-radius: 3px;
|
||||
background: Theme.accent;
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
spacing: Metrics.gap-2;
|
||||
alignment: end;
|
||||
padding-top: Metrics.gap-2;
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.queued > 0 ? "还有 " + root.queued + " 条待处理" : "";
|
||||
horizontal-stretch: 1;
|
||||
horizontal-alignment: left;
|
||||
}
|
||||
|
||||
if root.current.secondary != "" : MetroButton {
|
||||
kind: ButtonKind.subtle;
|
||||
text: root.current.secondary;
|
||||
clicked => { root.secondary(); }
|
||||
}
|
||||
MetroButton {
|
||||
kind: root.current.kind == DialogKind.error ? ButtonKind.danger : ButtonKind.accent;
|
||||
text: root.current.primary;
|
||||
enabled: root.current.kind != DialogKind.progress;
|
||||
clicked => { root.primary(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
// 基础输入件:单行输入(含占位文本)、搜索框、开关、分段控件、复选框。
|
||||
// 一律自绘(Metro 需要方角 + accent 高亮)。占位文本手绘:内置 TextInput 没有
|
||||
// placeholder-text(那是 std-widgets 的 LineEdit,外观不可控)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
|
||||
/// 单行输入:内置 TextInput + 占位文本层(Focus 态由外部读 `focused`)。
|
||||
export component PlainInput inherits Rectangle {
|
||||
in-out property <string> text: "";
|
||||
in property <string> placeholder: "";
|
||||
in property <color> text-color: Theme.fg-primary;
|
||||
in property <length> text-padding: 0px;
|
||||
out property <bool> focused: input.has-focus;
|
||||
callback edited(string);
|
||||
callback accepted(string);
|
||||
|
||||
background: transparent;
|
||||
|
||||
input := TextInput {
|
||||
x: root.text-padding;
|
||||
y: 0;
|
||||
width: root.width - 2 * root.text-padding;
|
||||
height: root.height;
|
||||
color: root.text-color;
|
||||
font-family: Theme.font-family;
|
||||
font-size: Theme.font-size-body;
|
||||
vertical-alignment: center;
|
||||
single-line: true;
|
||||
text <=> root.text;
|
||||
edited => { root.edited(self.text); }
|
||||
accepted => { root.accepted(self.text); }
|
||||
}
|
||||
|
||||
if root.text == "" && root.placeholder != "" : UiText {
|
||||
x: root.text-padding;
|
||||
y: 0;
|
||||
width: root.width - 2 * root.text-padding;
|
||||
height: root.height;
|
||||
role: TextRole.body;
|
||||
text: root.placeholder;
|
||||
color: Theme.fg-disabled;
|
||||
}
|
||||
}
|
||||
|
||||
export component SearchField inherits Rectangle {
|
||||
in-out property <string> text: "";
|
||||
in property <string> placeholder: "搜索";
|
||||
callback edited(string);
|
||||
callback accepted(string);
|
||||
|
||||
height: Metrics.control-height;
|
||||
background: Theme.bg-input;
|
||||
border-radius: Metrics.radius-sm;
|
||||
border-width: 1px;
|
||||
border-color: field.focused ? Theme.accent : Theme.stroke;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-2;
|
||||
padding-right: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
AppIcon { kind: IconKind.search; icon-size: 14px; }
|
||||
|
||||
field := PlainInput {
|
||||
placeholder: root.placeholder;
|
||||
text <=> root.text;
|
||||
edited(t) => { root.edited(t); }
|
||||
accepted(t) => { root.accepted(t); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component TextField inherits Rectangle {
|
||||
in-out property <string> text: "";
|
||||
in property <string> placeholder: "";
|
||||
callback edited(string);
|
||||
|
||||
height: Metrics.control-height;
|
||||
background: Theme.bg-input;
|
||||
border-radius: Metrics.radius-sm;
|
||||
border-width: 1px;
|
||||
border-color: field.focused ? Theme.accent : Theme.stroke;
|
||||
|
||||
field := PlainInput {
|
||||
text-padding: Metrics.gap-2;
|
||||
placeholder: root.placeholder;
|
||||
text <=> root.text;
|
||||
edited(t) => { root.edited(t); }
|
||||
}
|
||||
}
|
||||
|
||||
export component ToggleSwitch inherits Rectangle {
|
||||
in-out property <bool> checked: false;
|
||||
callback toggled(bool);
|
||||
|
||||
width: 40px;
|
||||
height: 20px;
|
||||
border-radius: 10px;
|
||||
background: checked ? Theme.accent : Theme.stroke-strong;
|
||||
animate background { duration: Theme.motion-normal; }
|
||||
|
||||
Rectangle {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
y: 3px;
|
||||
x: root.checked ? root.width - self.width - 3px : 3px;
|
||||
border-radius: 7px;
|
||||
background: Theme.fg-on-accent;
|
||||
animate x { duration: Theme.motion-normal; easing: ease-in-out; }
|
||||
}
|
||||
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => {
|
||||
root.checked = !root.checked;
|
||||
root.toggled(root.checked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 分段控件(视图切换、磁贴尺寸、主题三态共用)
|
||||
export component SegmentedControl inherits Rectangle {
|
||||
in property <[string]> options;
|
||||
in-out property <int> selected: 0;
|
||||
callback changed(int);
|
||||
|
||||
height: Metrics.control-height;
|
||||
background: Theme.bg-canvas;
|
||||
border-radius: Metrics.radius-sm;
|
||||
border-width: 1px;
|
||||
border-color: Theme.stroke;
|
||||
|
||||
HorizontalLayout {
|
||||
padding: 2px;
|
||||
spacing: 2px;
|
||||
for o[i] in options : Rectangle {
|
||||
border-radius: Metrics.radius-sm;
|
||||
background: i == root.selected
|
||||
? Theme.accent
|
||||
: (seg.has-hover ? Theme.bg-hover : transparent);
|
||||
animate background { duration: Theme.motion-fast; }
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: o;
|
||||
horizontal-alignment: center;
|
||||
color: i == root.selected ? Theme.fg-on-accent : Theme.fg-primary;
|
||||
}
|
||||
|
||||
seg := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => {
|
||||
root.selected = i;
|
||||
root.changed(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component CheckBox inherits Rectangle { in-out property <bool> checked: false;
|
||||
in property <string> text: "";
|
||||
callback toggled(bool);
|
||||
|
||||
height: Metrics.touch-target;
|
||||
background: transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
Rectangle {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: Metrics.radius-sm;
|
||||
border-width: 1px;
|
||||
border-color: root.checked ? Theme.accent : Theme.stroke-strong;
|
||||
background: root.checked ? Theme.accent : Theme.bg-input;
|
||||
|
||||
if root.checked : AppIcon {
|
||||
kind: IconKind.check;
|
||||
icon-size: 12px;
|
||||
x: 2px;
|
||||
y: 2px;
|
||||
tint: Theme.fg-on-accent;
|
||||
}
|
||||
}
|
||||
|
||||
UiText { role: TextRole.body; text: root.text; }
|
||||
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => {
|
||||
root.checked = !root.checked;
|
||||
root.toggled(root.checked);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 滑条(09 §102/§101 的「强度滑条」:暗化层强度、面板半透明度共用)。
|
||||
/// 自绘而非 std-widgets 的 Slider:Metro 需要方头轨道 + accent 填充,且要跟主题令牌一起换肤。
|
||||
export component MetroSlider inherits Rectangle {
|
||||
in property <float> minimum: 0.0;
|
||||
in property <float> maximum: 1.0;
|
||||
in-out property <float> value: 1.0;
|
||||
callback changed(float);
|
||||
|
||||
out property <float> ratio: root.maximum > root.minimum
|
||||
? Math.max(0.0, Math.min(1.0, (root.value - root.minimum) / (root.maximum - root.minimum)))
|
||||
: 0.0;
|
||||
|
||||
width: 200px;
|
||||
height: Metrics.touch-target;
|
||||
background: transparent;
|
||||
|
||||
/// 鼠标位置 → 取值(Slint 的 function 不能声明局部变量,所以拆成纯函数;
|
||||
/// 函数名不用 kebab-case:`value-at(...)` 会被当成减法解析)
|
||||
pure function valueForX(x: length) -> float {
|
||||
return root.minimum
|
||||
+ Math.max(0.0, Math.min(1.0, x / root.width)) * (root.maximum - root.minimum);
|
||||
}
|
||||
|
||||
// 轨道 + 已填充段
|
||||
Rectangle {
|
||||
x: 0;
|
||||
y: (root.height - 4px) / 2;
|
||||
width: root.width;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: Theme.stroke-strong;
|
||||
}
|
||||
Rectangle {
|
||||
x: 0;
|
||||
y: (root.height - 4px) / 2;
|
||||
width: root.width * root.ratio;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: Theme.accent;
|
||||
}
|
||||
// 滑块
|
||||
Rectangle {
|
||||
x: (root.width - 14px) * root.ratio;
|
||||
y: (root.height - 14px) / 2;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 7px;
|
||||
background: Theme.accent;
|
||||
border-width: 2px;
|
||||
border-color: Theme.surface-solid;
|
||||
}
|
||||
|
||||
area := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
moved => {
|
||||
root.value = root.valueForX(self.mouse-x);
|
||||
root.changed(root.value);
|
||||
}
|
||||
clicked => {
|
||||
root.value = root.valueForX(self.mouse-x);
|
||||
root.changed(root.value);
|
||||
}
|
||||
}
|
||||
|
||||
accessible-role: slider;
|
||||
}
|
||||
|
||||
/// 预设色板(09 §104 自定义强调色:预设色板 + 取色器,取色器由十六进制输入承担)。
|
||||
export component ColorSwatches inherits Rectangle {
|
||||
in property <[color]> palette;
|
||||
in property <color> current;
|
||||
/// 传**索引**而不是 color:Slint 没有「颜色 → #RRGGBB」的格式化,
|
||||
/// 预设色板的十六进制串由 Rust 侧同一张表给出(一处真相)。
|
||||
callback picked(int);
|
||||
|
||||
width: root.palette.length * 28px;
|
||||
height: 28px;
|
||||
background: transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
spacing: 4px;
|
||||
|
||||
for shade[i] in root.palette : Rectangle {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: Metrics.radius-sm;
|
||||
background: shade;
|
||||
border-width: shade == root.current ? 2px : 1px;
|
||||
border-color: shade == root.current ? Theme.fg-primary : Theme.stroke;
|
||||
|
||||
swatch-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.picked(i); }
|
||||
}
|
||||
|
||||
accessible-role: button;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// 设置项行:左标签+说明,右控件。控件类型用 ControlKind 收敛,避免为每个设置项写一遍布局。
|
||||
// (Slint 没有 slot 机制,所以用 kind 枚举 + 通用属性把控件种类收在一处。)
|
||||
//
|
||||
// M41 增加两种控件:`slider`(强度/透明度滑条)与 `swatches`(预设色板 + 取色器入口),
|
||||
// 它们服务 09 §101-104 的「外观(高级)」四件——高级特性默认关闭,控件本身常显(关着也能调)。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { MetroButton, ButtonKind } from "button.slint";
|
||||
import {
|
||||
ToggleSwitch, SegmentedControl, TextField, MetroSlider, ColorSwatches,
|
||||
} from "inputs.slint";
|
||||
|
||||
export enum ControlKind {
|
||||
none,
|
||||
toggle,
|
||||
segmented,
|
||||
button,
|
||||
text,
|
||||
slider,
|
||||
swatches,
|
||||
}
|
||||
|
||||
export component SettingItem inherits Rectangle {
|
||||
in property <string> label: "";
|
||||
in property <string> description: "";
|
||||
in property <ControlKind> kind: ControlKind.none;
|
||||
in property <[string]> options;
|
||||
in property <string> button-text: "";
|
||||
in-out property <int> selected: 0;
|
||||
in-out property <bool> checked: false;
|
||||
in-out property <string> value: "";
|
||||
// 滑条
|
||||
in property <float> min-value: 0.0;
|
||||
in property <float> max-value: 1.0;
|
||||
in-out property <float> slider-value: 1.0;
|
||||
// 色板
|
||||
in property <[color]> swatch-colors;
|
||||
in property <color> swatch-current: transparent;
|
||||
// 危险/提示色描述(如「对比度偏低」)
|
||||
in property <bool> warn: false;
|
||||
|
||||
callback toggled(bool);
|
||||
callback changed(int);
|
||||
callback clicked();
|
||||
callback edited(string);
|
||||
callback slid(float);
|
||||
callback swatch-picked(int);
|
||||
|
||||
height: root.description == "" ? 44px : 60px;
|
||||
background: transparent;
|
||||
|
||||
HorizontalLayout {
|
||||
padding-left: Metrics.gap-4;
|
||||
padding-right: Metrics.gap-4;
|
||||
spacing: Metrics.gap-4;
|
||||
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
vertical-stretch: 1;
|
||||
|
||||
UiText {
|
||||
role: TextRole.body;
|
||||
text: root.label;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: root.description;
|
||||
visible: root.description != "";
|
||||
color: root.warn ? Theme.state-warn : Theme.fg-secondary;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
|
||||
if root.kind == ControlKind.toggle : ToggleSwitch {
|
||||
checked: root.checked;
|
||||
toggled(v) => {
|
||||
root.checked = v;
|
||||
root.toggled(v);
|
||||
}
|
||||
}
|
||||
|
||||
if root.kind == ControlKind.segmented : SegmentedControl {
|
||||
width: root.options.length * 64px;
|
||||
options: root.options;
|
||||
selected: root.selected;
|
||||
changed(i) => {
|
||||
root.selected = i;
|
||||
root.changed(i);
|
||||
}
|
||||
}
|
||||
|
||||
if root.kind == ControlKind.button : MetroButton {
|
||||
kind: ButtonKind.standard;
|
||||
text: root.button-text;
|
||||
button-height: 28px;
|
||||
clicked => { root.clicked(); }
|
||||
}
|
||||
|
||||
if root.kind == ControlKind.text : TextField {
|
||||
width: 240px;
|
||||
placeholder: root.button-text;
|
||||
text <=> root.value;
|
||||
edited(t) => { root.edited(t); }
|
||||
}
|
||||
|
||||
if root.kind == ControlKind.slider : HorizontalLayout {
|
||||
spacing: Metrics.gap-2;
|
||||
alignment: end;
|
||||
|
||||
UiText {
|
||||
role: TextRole.caption;
|
||||
text: (root.slider-value * 100).round() + "%";
|
||||
width: 40px;
|
||||
horizontal-alignment: right;
|
||||
color: Theme.fg-secondary;
|
||||
}
|
||||
MetroSlider {
|
||||
minimum: root.min-value;
|
||||
maximum: root.max-value;
|
||||
value: root.slider-value;
|
||||
changed(v) => {
|
||||
root.slider-value = v;
|
||||
root.slid(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if root.kind == ControlKind.swatches : ColorSwatches {
|
||||
palette: root.swatch-colors;
|
||||
current: root.swatch-current;
|
||||
picked(i) => { root.swatch-picked(i); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 分组标题
|
||||
export component SettingGroup inherits Rectangle {
|
||||
in property <string> title: "";
|
||||
|
||||
height: 36px;
|
||||
background: transparent;
|
||||
|
||||
UiText {
|
||||
x: Metrics.gap-4;
|
||||
y: 0;
|
||||
width: root.width - 2 * Metrics.gap-4;
|
||||
height: root.height;
|
||||
role: TextRole.caption;
|
||||
text: root.title;
|
||||
color: Theme.fg-secondary;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Toast:右下角非阻塞提示(下载完成 / 复制成功 / 后台任务结论)。
|
||||
// 队列与自动消失时长由 Rust ToastCenter 管理(P0 默认 4s),这里只负责渲染与手动关闭。
|
||||
import { Theme } from "../theme/tokens.slint";
|
||||
import { Metrics } from "../theme/metrics.slint";
|
||||
import { UiToast, ToastKind } from "../models.slint";
|
||||
import { UiText, TextRole } from "../components/label.slint";
|
||||
import { AppIcon, IconKind } from "../components/icons.slint";
|
||||
|
||||
component ToastCard inherits Rectangle {
|
||||
in property <UiToast> data;
|
||||
callback dismissed(string);
|
||||
|
||||
width: 300px;
|
||||
height: body-layout.preferred-height;
|
||||
background: Theme.bg-elevated;
|
||||
border-radius: Metrics.radius-md;
|
||||
border-width: 1px;
|
||||
border-color: Theme.stroke;
|
||||
drop-shadow-blur: 16px;
|
||||
drop-shadow-color: Theme.shadow;
|
||||
drop-shadow-offset-y: 3px;
|
||||
|
||||
// 左侧语义色条:Metro 用色块表达状态,不用图标喧宾夺主
|
||||
Rectangle {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
width: 3px;
|
||||
height: root.height;
|
||||
background: root.data.kind == ToastKind.success ? Theme.state-success
|
||||
: root.data.kind == ToastKind.warn ? Theme.state-warn
|
||||
: root.data.kind == ToastKind.error ? Theme.state-danger
|
||||
: Theme.accent;
|
||||
}
|
||||
|
||||
body-layout := HorizontalLayout {
|
||||
padding-left: Metrics.gap-3;
|
||||
padding-right: Metrics.gap-2;
|
||||
padding-top: Metrics.gap-2;
|
||||
padding-bottom: Metrics.gap-2;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
UiText {
|
||||
role: TextRole.body;
|
||||
text: root.data.text;
|
||||
wrap: word-wrap;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
|
||||
AppIcon {
|
||||
kind: IconKind.close;
|
||||
icon-size: 14px;
|
||||
tint: Theme.fg-secondary;
|
||||
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.dismissed(root.data.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component ToastHost inherits Rectangle {
|
||||
in property <[UiToast]> toasts;
|
||||
callback dismissed(string);
|
||||
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
|
||||
stack-box := Rectangle {
|
||||
x: root.width - stack-box.width - Metrics.gap-4;
|
||||
y: root.height - stack-box.height - Metrics.gap-4;
|
||||
width: 300px;
|
||||
height: stack.preferred-height;
|
||||
background: transparent;
|
||||
|
||||
stack := VerticalLayout {
|
||||
width: stack-box.width;
|
||||
spacing: Metrics.gap-2;
|
||||
|
||||
for t in root.toasts : ToastCard {
|
||||
data: t;
|
||||
dismissed(id) => { root.dismissed(id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user