Unlucky Launcher v0.2.3
CI / fmt (rustfmt --check) (push) Waiting to run
CI / clippy (ubuntu-latest) (push) Waiting to run
CI / clippy (windows-latest) (push) Waiting to run
CI / test (ubuntu-latest) (push) Waiting to run
CI / test (windows-latest) (push) Waiting to run
CI / build release (ubuntu-latest) (push) Waiting to run
CI / build release (windows-latest) (push) Waiting to run
CI / runtime smoke (ubuntu x64, xvfb) (push) Waiting to run
CI / runtime smoke (macos arm64, probe) (push) Skipped
Guards / core 零 UI 守门 (push) Waiting to run
Guards / presenter 零 UI 守门 (push) Waiting to run
Guards / design 零第三方依赖守门 (push) Waiting to run
Guards / unsafe 落点守门(集合必须恰好一个文件) (push) Waiting to run
Guards / 文件行数 ≤400 守门 (push) Waiting to run
Guards / 依赖许可与来源(cargo-deny) (push) Waiting to run
Release guard / 发布标记语义守门(push tag → 稳定版) (push) Waiting to run
Release / 选槽位(默认两个 Windows) (push) Waiting to run

This commit is contained in:
AskaEth committed 2026-11-08 00:15:58 +00:00
commit d616d65ea1
1219 files changed
+237663

No files matched your search

+124
View File
@@ -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();
});
}
}
+370
View File
@@ -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 unlucky_presenter::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(&current);
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);
}
}
+352
View File
@@ -0,0 +1,352 @@
//! 回调接线:把 `ui/main.slint` 暴露的每个回调翻译成「状态变更 + AppCommand + 同步」。
//!
//! 逐条列出而不做通用转发,是为了让「用户能做的每一件事」在这里一目了然;
//! 新增交互时只改这一处 + `.slint` 的 callback 声明。
use std::rc::Weak;
use slint::ComponentHandle;
use crate::conv;
use crate::ui_bind::Inner;
use unlucky_presenter::dto::AppCommand;
use unlucky_presenter::router::Route;
use unlucky_presenter::toast::ToastKind;
/// 接全部回调;闭包持弱引用,避免 `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 };
// G5:打开向导(版本 → 加载器 → 名字 → 确认 → 安装进度)
this.state.borrow_mut().wizard = unlucky_presenter::wizard::WizardState::open();
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();
}
+264
View File
@@ -0,0 +1,264 @@
//! `PageState` global 的回调接线:账户 / Java / 设置 / 通知 / 向导 / 崩溃导入 / 日志刷新。
//!
//! 与 `callbacks.rs` 同一纪律:每个回调 = 「改状态 + 发 AppCommand + 同步 UI」,一处看全。
//! 用 global 而不是逐层转发属性(见 `ui/page_state.slint` 顶部的取舍说明)。
use std::rc::Weak;
use slint::ComponentHandle;
use crate::conv;
use crate::ui_bind::Inner;
use unlucky_presenter::dto::{AppCommand, CreateRequest, LoaderKind};
/// 接全部页面状态回调。
pub(crate) fn wire_pages(weak: Weak<Inner>) {
let Some(inner) = weak.upgrade() else { return };
let page = inner.ui.global::<crate::PageState<'_>>();
// ── 账户 ──────────────────────────────────────────────────
{
let weak = weak.clone();
page.on_account_add_offline(move |name| {
let name = name.to_string();
if name.trim().is_empty() {
return;
}
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::AddOfflineAccount(name));
this.ui
.global::<crate::PageState<'_>>()
.set_offline_name("".into());
this.sync();
});
}
{
let weak = weak.clone();
page.on_account_remove(move |id| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::RemoveAccount(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
page.on_account_switch(move |id| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::SwitchAccount(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
page.on_msa_begin(move || {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::StartDeviceLogin);
this.sync();
});
}
{
let weak = weak.clone();
page.on_msa_browser_begin(move || {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::StartBrowserLogin);
this.sync();
});
}
{
let weak = weak.clone();
page.on_msa_cancel(move || {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::CancelDeviceLogin);
this.sync();
});
}
// ── Java ──────────────────────────────────────────────────
{
let weak = weak.clone();
page.on_java_install(move |vendor| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::InstallJava(vendor.to_string()));
this.sync();
});
}
// ── 设置 ──────────────────────────────────────────────────
{
let weak = weak.clone();
page.on_setting_changed(move |key, value| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::SetSetting {
key: key.to_string(),
value: value.to_string(),
});
this.sync();
});
}
{
let weak = weak.clone();
page.on_setting_action(move |action| {
let Some(this) = weak.upgrade() else { return };
let action = action.to_string();
match action.as_str() {
// 清 24h 地区缓存 → 下次下载重新判定
"detect_region" => this.dispatch(AppCommand::SetSetting {
key: "download.action.detect_region".to_string(),
value: String::new(),
}),
// Java 分组的「安装/管理」→ 按回退链装一个托管 JDK
"install_java" => this.dispatch(AppCommand::InstallJava(String::new())),
_ => {}
}
this.sync();
});
}
{
let weak = weak.clone();
page.on_settings_tab_changed(move |tab| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().settings_tab = tab.to_string();
this.sync();
});
}
// ── 通知 ──────────────────────────────────────────────────
{
let weak = weak.clone();
page.on_notice_dismiss(move |id| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::DismissNotice(id.to_string()));
this.sync();
});
}
// ── 向导 ──────────────────────────────────────────────────
{
let weak = weak.clone();
page.on_wizard_open(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().wizard = unlucky_presenter::wizard::WizardState::open();
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_close(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().wizard.open = false;
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_select_version(move |version| {
let Some(this) = weak.upgrade() else { return };
this.state
.borrow_mut()
.wizard
.select_version(version.as_ref());
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_select_loader(move |index| {
let Some(this) = weak.upgrade() else { return };
let loader = match index {
1 => LoaderKind::Fabric,
2 => LoaderKind::Quilt,
3 => LoaderKind::Forge,
4 => LoaderKind::NeoForge,
_ => LoaderKind::Vanilla,
};
this.state.borrow_mut().wizard.select_loader(loader);
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_name_changed(move |name| {
let Some(this) = weak.upgrade() else { return };
let mut state = this.state.borrow_mut();
state.wizard.name = name.to_string();
state.wizard.error.clear();
drop(state);
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_next(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().wizard.advance();
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_back(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().wizard.step_back();
this.sync();
});
}
{
let weak = weak.clone();
page.on_wizard_confirm(move || {
let Some(this) = weak.upgrade() else { return };
let request = {
let state = this.state.borrow();
let wizard = &state.wizard;
wizard.ready_to_submit().map(|()| CreateRequest {
version: wizard.version.trim().to_string(),
loader: wizard.loader,
loader_version: wizard.loader_version.trim().to_string(),
name: wizard.name.trim().to_string(),
})
};
match request {
Ok(request) => {
this.dispatch(AppCommand::CreateInstance(request));
this.state.borrow_mut().wizard.submitted();
}
Err(error) => {
this.state.borrow_mut().wizard.error = error;
}
}
this.sync();
});
}
{
let weak = weak.clone();
page.on_install_cancel(move || {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::CancelInstall);
this.sync();
});
}
// ── 日志页 ────────────────────────────────────────────────
{
let weak = weak.clone();
page.on_crash_import(move |path| {
let Some(this) = weak.upgrade() else { return };
let path = path.to_string();
if path.trim().is_empty() {
return;
}
this.dispatch(AppCommand::ImportCrashLog(path));
this.sync();
});
}
{
let weak = weak.clone();
page.on_logs_refresh(move || {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::RefreshLogSessions);
this.sync();
});
}
// 设置页分组切换同时刷新一遍分组快照(外部改配置后手点分组即最新)
let _ = conv::setting_groups;
}
+103
View File
@@ -0,0 +1,103 @@
//! AI 页与覆盖层:会话消息、对话框(一次一条)、Toast。
use crate::{ChatRole, DialogKind, UiChatMessage, UiDialog, UiToast};
use unlucky_presenter::dialogs as dlg;
use unlucky_presenter::dto::ChatRole as DtoChatRole;
use unlucky_presenter::state::AppState;
use unlucky_presenter::toast as toast_mod;
/// 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()
}
+163
View File
@@ -0,0 +1,163 @@
//! 实例相关:磁贴外观(相位/进度/徽标/占位色)、运行中列表。
use slint::Color;
use crate::{LoaderKind, RuntimePhase, UiTile};
use unlucky_presenter::dto::{self, InstanceRuntime};
use unlucky_presenter::state::{AppState, TileCell};
/// 头像/图标占位的底色池(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,
dto::LaunchStage::Window => RuntimePhase::Running,
};
(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())), "从未启动");
}
}
+84
View File
@@ -0,0 +1,84 @@
//! 日志页:会话列表、日志行、D8 诊断卡片。
use crate::{LogLevel, LogOutcome, UiDiagnosis, UiLogLine, UiLogSession};
use unlucky_presenter::dto::{LogLevel as DtoLogLevel, LogOutcome as DtoLogOutcome};
use unlucky_presenter::state::AppState;
/// 日志会话列表。
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");
}
}
+26
View File
@@ -0,0 +1,26 @@
//! 状态层 → Slint 视图模型的单向转换(DTO 值 → `models.slint` 结构体)。
//!
//! 只做「领域值 → 展示值」的搬运与格式化,不含业务判断;
//! 这样 `ui_bind.rs` 里的同步逻辑就是纯粹的「状态灌进属性」。
//! 按领域拆子模块:instances / versions / logs / agent / ui,全量 `pub use`,
//! 调用方统一写 `crate::conv::tiles(...)` 这类路径。
mod agent;
mod instances;
mod logs;
mod pages;
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 pages::{
accounts, active_account_name, device, install, java_chain, java_runtimes, java_vendors,
notices, setting_groups, wizard, wizard_versions,
};
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;
+301
View File
@@ -0,0 +1,301 @@
//! 状态 → `page_state.slint` 的视图模型(账户 / Java / 安装 / 设置分组 / 通知 / 向导)。
//!
//! 与 `conv/{instances,versions,logs,agent}.rs` 同一套路:只做「领域值 → 展示值」的搬运,
//! 不含业务判断。`ui_bind::sync` 把这些灌进 `PageState` global。
use slint::{ModelRc, SharedString, VecModel};
use crate::{
AccountKind, InstallStage, JavaStepOutcome, NoticeKind, SettingControl as UiControl, UiAccount,
UiDeviceCode, UiInstallProgress, UiJavaRuntime, UiJavaStep, UiJavaVendor, UiNotice,
UiSettingGroup, UiSettingRow, UiVersion, UiWizard,
};
use unlucky_presenter::dto::{
AccountKind as DtoAccountKind, DeviceLoginPhase, InstallStage as DtoInstallStage,
JavaChainOutcome, NoticeLevel, SettingControl, VersionKind as DtoVersionKind,
};
use unlucky_presenter::state::AppState;
use unlucky_presenter::wizard::WizardStep;
fn strings(items: &[String]) -> ModelRc<SharedString> {
ModelRc::new(VecModel::from(
items
.iter()
.map(|item| SharedString::from(item.as_str()))
.collect::<Vec<_>>(),
))
}
/// 账户行。
pub fn accounts(state: &AppState) -> Vec<UiAccount> {
state
.accounts
.iter()
.map(|account| UiAccount {
id: account.id.as_str().into(),
name: account.name.as_str().into(),
kind: match account.kind {
DtoAccountKind::Offline => AccountKind::Offline,
DtoAccountKind::Microsoft => AccountKind::Microsoft,
DtoAccountKind::Authlib => AccountKind::Authlib,
},
kind_label: account.kind.label().into(),
profile_id: account.profile_id.as_str().into(),
login_name: account.login_name.as_str().into(),
created: account.created.as_str().into(),
active: account.active,
})
.collect()
}
/// 当前启动账户的展示名(导航底部头像)。
pub fn active_account_name(state: &AppState) -> String {
state
.accounts
.iter()
.find(|account| account.active)
.map(|account| account.name.clone())
.unwrap_or_else(|| "未登录".to_string())
}
/// 微软登录面板。
pub fn device(state: &AppState) -> UiDeviceCode {
let view = &state.device_login;
UiDeviceCode {
visible: view.phase.visible(),
busy: view.phase.busy(),
user_code: view.user_code.as_str().into(),
verification_uri: view.verification_uri.as_str().into(),
qr_link: view.qr_link.as_str().into(),
expires: i32::try_from(view.expires_in).unwrap_or(i32::MAX),
message: view.message.as_str().into(),
phase_label: match view.phase {
DeviceLoginPhase::Idle => "空闲",
DeviceLoginPhase::Requesting => "申请中",
DeviceLoginPhase::Waiting => "等待确认",
DeviceLoginPhase::Succeeded => "成功",
DeviceLoginPhase::Failed => "失败",
}
.into(),
}
}
/// Java 发行版行。
pub fn java_vendors(state: &AppState) -> Vec<UiJavaVendor> {
state
.java
.vendors
.iter()
.map(|vendor| UiJavaVendor {
id: vendor.id.as_str().into(),
display: vendor.display.as_str().into(),
rank: i32::try_from(vendor.rank).unwrap_or(0),
majors: vendor.majors.as_str().into(),
sources: vendor.sources.join(" · ").into(),
installed: vendor.installed,
})
.collect()
}
/// Java 回退链。
pub fn java_chain(state: &AppState) -> Vec<UiJavaStep> {
state
.java
.chain
.iter()
.map(|step| UiJavaStep {
vendor: step.vendor.as_str().into(),
outcome: match step.outcome {
JavaChainOutcome::Pending => JavaStepOutcome::Pending,
JavaChainOutcome::Skip => JavaStepOutcome::Skip,
JavaChainOutcome::Failed => JavaStepOutcome::Failed,
JavaChainOutcome::Hit => JavaStepOutcome::Hit,
},
outcome_label: step.outcome.label().into(),
detail: step.detail.as_str().into(),
})
.collect()
}
/// Java 本地运行时。
pub fn java_runtimes(state: &AppState) -> Vec<UiJavaRuntime> {
state
.java
.runtimes
.iter()
.map(|runtime| UiJavaRuntime {
binary: runtime.binary.as_str().into(),
version: runtime.version.as_str().into(),
vendor: runtime.vendor.as_str().into(),
origin: runtime.origin.as_str().into(),
})
.collect()
}
/// 安装进度卡片。
pub fn install(state: &AppState) -> UiInstallProgress {
let Some(progress) = &state.install else {
return UiInstallProgress {
visible: false,
stage: InstallStage::Planning,
..UiInstallProgress::default()
};
};
UiInstallProgress {
visible: true,
version: progress.version.as_str().into(),
instance: progress.instance.as_str().into(),
loader: progress.loader.as_str().into(),
stage: match progress.stage {
DtoInstallStage::Planning => InstallStage::Planning,
DtoInstallStage::Downloading => InstallStage::Downloading,
DtoInstallStage::Installing => InstallStage::Installing,
DtoInstallStage::Registering => InstallStage::Registering,
DtoInstallStage::Done => InstallStage::Done,
DtoInstallStage::Failed => InstallStage::Failed,
DtoInstallStage::Cancelled => InstallStage::Cancelled,
},
stage_label: progress.stage.label().into(),
ratio: progress.ratio(),
known: progress.is_known(),
files_label: progress.files_label().into(),
bytes_label: if progress.bytes_total > 0 {
format!(
"{}/{}",
unlucky_presenter::dto::human_bytes(progress.bytes_done),
unlucky_presenter::dto::human_bytes(progress.bytes_total)
)
} else {
String::new()
}
.into(),
speed: progress.speed_label().into(),
eta: progress.eta_label().into(),
message: progress.message.as_str().into(),
terminal: progress.stage.is_terminal(),
failed: progress.stage == DtoInstallStage::Failed,
}
}
/// 设置分组(行 + 控件)。
pub fn setting_groups(state: &AppState) -> Vec<UiSettingGroup> {
state
.settings_groups
.iter()
.map(|group| UiSettingGroup {
id: group.id.as_str().into(),
title: group.title.as_str().into(),
rows: ModelRc::new(VecModel::from(
group
.rows
.iter()
.map(|row| UiSettingRow {
key: row.key.as_str().into(),
label: row.label.as_str().into(),
description: row.description.as_str().into(),
control: match row.control {
SettingControl::Toggle => UiControl::Toggle,
SettingControl::Choice => UiControl::Choice,
SettingControl::Text => UiControl::Text,
SettingControl::ReadOnly => UiControl::Readonly,
SettingControl::Action => UiControl::Action,
},
flag: row.flag,
selected: row.selected,
options: strings(&row.options),
value_text: row.value_text.as_str().into(),
action: row.action.as_str().into(),
})
.collect::<Vec<_>>(),
)),
})
.collect()
}
/// 横幅通知。
pub fn notices(state: &AppState) -> Vec<UiNotice> {
state
.notices
.iter()
.map(|notice| UiNotice {
id: notice.id.as_str().into(),
kind: match notice.level {
NoticeLevel::Info => NoticeKind::Info,
NoticeLevel::Warn => NoticeKind::Warn,
NoticeLevel::Error => NoticeKind::Error,
},
title: notice.title.as_str().into(),
body: notice.body.as_str().into(),
})
.collect()
}
/// 向导状态。
pub fn wizard(state: &AppState) -> UiWizard {
let wizard = &state.wizard;
let step = wizard.step;
let can_next = match step {
WizardStep::Version => !wizard.version.trim().is_empty(),
WizardStep::Name => unlucky_presenter::wizard::validate_name(&wizard.name).is_ok(),
WizardStep::Loader | WizardStep::Confirm => true,
WizardStep::Progress => false,
};
UiWizard {
open: wizard.open,
step: i32::try_from(step.index()).unwrap_or(0),
step_label: step.title().into(),
step_index: i32::try_from(step.index()).unwrap_or(0),
step_total: 5,
version: wizard.version.as_str().into(),
loader: loader_index(wizard.loader),
loader_label: if wizard.loader == unlucky_presenter::dto::LoaderKind::Vanilla {
"原版".to_string()
} else {
format!("{} {}", wizard.loader.label(), wizard.loader_version.trim())
.trim()
.to_string()
}
.into(),
loader_version: wizard.loader_version.as_str().into(),
name: wizard.name.as_str().into(),
error: wizard.error.as_str().into(),
busy: wizard.submitting,
can_next,
}
}
/// 加载器在向导里的单选序号(与 `wizard.slint` 的 LoaderChoice 顺序一致)。
pub fn loader_index(loader: unlucky_presenter::dto::LoaderKind) -> i32 {
match loader {
unlucky_presenter::dto::LoaderKind::Vanilla => 0,
unlucky_presenter::dto::LoaderKind::Fabric => 1,
unlucky_presenter::dto::LoaderKind::Quilt => 2,
unlucky_presenter::dto::LoaderKind::Forge => 3,
unlucky_presenter::dto::LoaderKind::NeoForge => 4,
unlucky_presenter::dto::LoaderKind::OptiFine
| unlucky_presenter::dto::LoaderKind::LiteLoader => 0,
}
}
/// 向导里的版本列表(正式版 + 快照;远古版走下载页的显式入口)。
pub fn wizard_versions(state: &AppState) -> Vec<UiVersion> {
state
.versions
.iter()
.filter(|version| !version.kind.is_ancient())
.map(|version| UiVersion {
id: version.id.as_str().into(),
kind: match version.kind {
DtoVersionKind::Release => crate::VersionKind::Release,
_ => crate::VersionKind::Snapshot,
},
released: version.released.as_str().into(),
installed: version.installed,
ancient: false,
})
.collect()
}
#[cfg(test)]
#[path = "pages_tests.rs"]
mod tests;
+172
View File
@@ -0,0 +1,172 @@
//! conv/pages.rs 的单测(拆文件守 400 行上限)。
use super::*;
use slint::Model;
use unlucky_presenter::dto::{
AccountView, DeviceLoginView, InstallProgressView, JavaPageView, JavaVendorView, NoticeView,
SettingGroupView, SettingRowView, VersionSummary,
};
use unlucky_presenter::wizard::WizardState;
#[test]
fn accounts_and_device_login_render() {
let mut state = AppState::new();
state.accounts = vec![AccountView {
id: "account:1".to_string(),
name: "Steve".to_string(),
kind: DtoAccountKind::Offline,
profile_id: "0f8f".to_string(),
login_name: String::new(),
created: "2026-10-31 20:12".to_string(),
active: true,
}];
state.device_login =
DeviceLoginView::waiting("ABCD-EFGH", "https://www.microsoft.com/link", 900, "");
let rows = accounts(&state);
assert_eq!(rows.len(), 1);
assert!(rows[0].active);
assert_eq!(rows[0].kind_label, "离线");
assert_eq!(active_account_name(&state), "Steve");
let device = device(&state);
assert!(device.visible && device.busy);
assert_eq!(device.user_code, "ABCD-EFGH");
assert_eq!(device.phase_label, "等待确认");
}
#[test]
fn browser_login_panel_renders_the_authorization_link() {
let mut state = AppState::new();
state.device_login = DeviceLoginView::browser_waiting(
"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id=x",
300,
None,
);
let device = device(&state);
assert!(device.visible && device.busy);
assert_eq!(device.user_code, "", "授权码流没有用户码");
assert!(device.verification_uri.contains("/authorize?client_id=x"));
assert_eq!(device.qr_link, device.verification_uri);
assert_eq!(device.expires, 300);
}
#[test]
fn install_progress_renders_labels_and_terminal_flags() {
let mut state = AppState::new();
state.install = Some(InstallProgressView {
version: "1.20.4".to_string(),
instance: "生存".to_string(),
loader: "Fabric 0.16.5".to_string(),
stage: DtoInstallStage::Downloading,
files_done: 3,
files_total: 6,
bytes_done: 1024,
bytes_total: 4096,
speed_bps: 2048,
eta_secs: 2,
message: "下载中".to_string(),
});
let ui = install(&state);
assert!(ui.visible && !ui.terminal && !ui.failed);
assert!((ui.ratio - 0.5).abs() < f32::EPSILON);
assert_eq!(ui.files_label, "3/6 文件");
assert_eq!(ui.speed, "2.0 KB/s");
assert_eq!(ui.eta, "剩 2s");
state.install = None;
assert!(!install(&state).visible);
}
#[test]
fn java_chain_and_vendors_map_outcomes() {
let mut state = AppState::new();
state.java = JavaPageView {
vendors: vec![JavaVendorView {
id: "temurin".to_string(),
display: "Eclipse Temurin".to_string(),
rank: 1,
majors: "17/21".to_string(),
sources: vec!["BMCLAPI".to_string(), "GitHub".to_string()],
installed: true,
}],
chain: vec![unlucky_presenter::dto::JavaChainStep {
vendor: "temurin".to_string(),
outcome: JavaChainOutcome::Hit,
detail: "21".to_string(),
}],
..JavaPageView::new()
};
let vendors = java_vendors(&state);
assert_eq!(vendors.len(), 1);
assert_eq!(vendors[0].sources, "BMCLAPI · GitHub");
let chain = java_chain(&state);
assert!(matches!(chain[0].outcome, JavaStepOutcome::Hit));
assert_eq!(chain[0].outcome_label, "命中");
}
#[test]
fn settings_groups_map_controls() {
let mut state = AppState::new();
state.settings_groups = vec![SettingGroupView::new("download", "下载")
.with(SettingRowView::toggle("agent.mcp.enabled", "MCP", "", true))
.with(SettingRowView::choice(
"download.region",
"地区",
"",
&["auto", "cn"],
1,
))];
let groups = setting_groups(&state);
assert_eq!(groups.len(), 1);
let rows = groups[0].rows.clone();
assert_eq!(rows.row_count(), 2);
let first = rows.row_data(0).expect("第一行");
let second = rows.row_data(1).expect("第二行");
assert!(first.flag);
assert!(matches!(second.control, UiControl::Choice));
assert_eq!(second.selected, 1);
}
#[test]
fn notices_and_wizard_render() {
let mut state = AppState::new();
state.notices = vec![NoticeView::new(
"isolation:x",
NoticeLevel::Warn,
"隔离档位已切换",
"两侧都有内容",
)];
let notices = notices(&state);
assert!(matches!(notices[0].kind, NoticeKind::Warn));
state.wizard = WizardState::open();
state.wizard.select_version("1.20.4");
let wizard = wizard(&state);
assert!(wizard.open);
assert_eq!(wizard.step_label, "选择版本");
assert!(wizard.can_next);
assert_eq!(wizard.loader, 0);
}
#[test]
fn wizard_versions_skip_ancient_ones() {
let mut state = AppState::new();
state.versions = vec![
VersionSummary {
id: "1.20.4".to_string(),
kind: DtoVersionKind::Release,
released: "2023-12-07".to_string(),
installed: false,
},
VersionSummary {
id: "rd-132211".to_string(),
kind: DtoVersionKind::Ancient(unlucky_presenter::dto::AncientKind::Classic),
released: "2009-05-13".to_string(),
installed: false,
},
];
let rows = wizard_versions(&state);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, "1.20.4");
}
+136
View File
@@ -0,0 +1,136 @@
//! UI 偏好/路由枚举的双向映射(Slint 枚举 ↔ 状态层枚举)。
use crate::{BgFillKind, DownloadCategory, InstanceView, RouteKind, ThemeMode, TileSize};
use unlucky_presenter::dto::{self, VersionCategory};
use unlucky_presenter::prefs;
use unlucky_presenter::router;
/// 路由 → 导航高亮/页面选择。
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),
}
}
+105
View File
@@ -0,0 +1,105 @@
//! 版本列表与下载分类映射(下载页)。
use crate::{UiVersion, VersionKind};
use unlucky_presenter::dto::{
AncientKind, VersionCategory, VersionKind as DtoVersionKind, VersionSummary,
};
use unlucky_presenter::state::AppState;
/// 分类侧栏 → 该分类下的版本(远古版按子类细分)。
pub fn in_category(category: VersionCategory, kind: DtoVersionKind) -> bool {
match (category, kind) {
(VersionCategory::Release, DtoVersionKind::Release) => true,
(VersionCategory::Snapshot, DtoVersionKind::Snapshot) => true,
(VersionCategory::Ancient(expected), DtoVersionKind::Ancient(actual)) => expected == actual,
// 未接线的分类(整合包 / Mod)不显示任何版本,而不是把全部版本倒进去
(VersionCategory::Modpack | VersionCategory::Mod, _) => false,
_ => false,
}
}
/// 版本行(下载页与新建向导共用)。
pub fn version_rows(versions: &[VersionSummary]) -> Vec<UiVersion> {
versions
.iter()
.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()
}
/// 下载页版本行(按当前分类 + 「仅已装」+ 版本号筛选词过滤)。
pub fn versions(state: &AppState) -> Vec<UiVersion> {
let query = state.download_query.trim().to_lowercase();
let filtered: Vec<VersionSummary> = state
.versions
.iter()
.filter(|version| in_category(state.prefs.download_category, version.kind))
.filter(|version| !state.installed_only || version.installed)
.filter(|version| query.is_empty() || version.id.to_lowercase().contains(&query))
.cloned()
.collect();
version_rows(&filtered)
}
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 unlucky_presenter::dto::{VersionKind, VersionSummary};
use unlucky_presenter::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());
}
}
+116
View File
@@ -0,0 +1,116 @@
//! Unlucky-Launcher 桌面壳(`unlucky_app`):Slint UI + Metro 视觉。
//!
//! 边界(决策 D3 / D16):本 crate 是**唯一**允许依赖 UI 框架的 crate;
//! 它只经「快照 + 事件流 + 注入的显示服务」消费 core/agent,不直接触碰其内部类型
//! (P0 的 host 是 `mock` 假后端,`unlucky_presenter::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(`unlucky_presenter::settings_bridge`),AI 可写并且**热切**
//! (tick 里 1s 一次 mtime 比对);系统主题由 `core::platform::theme_probe` 对齐 + 兜底轮询。
//!
//! 一个二进制两种用法(M82):`unlucky-launcher` 不带子命令时起 GUI;带子命令
//! (`instances` / `install` / `launch` / `accounts` / `sessions` / `logs` / `diag` /
//! `config` / `java` / `agent`)时直接转给 `unlucky_cli::run`,**不初始化任何 UI**。
//! 子命令表不在这里抄一份——唯一真相源是 `crates/cli` 的解析器(见
//! `unlucky_cli::cli::looks_like_cli`)。
//! 零 UI 依赖的 `ull` 仍然保留:它连 fontconfig 都不需要,给服务器 / CI / Termux 用。
//!
//! 架构分层(本文件只有一个职责:分发 + 把窗口拉起来):
//! - `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)]
use std::process::ExitCode;
mod appearance_bind;
mod bg_image;
mod callbacks;
mod callbacks_pages;
mod conv;
mod page_sync;
mod png;
mod screenshot;
mod theme_runtime;
mod ui_bind;
slint::include_modules!();
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
if let Some(code) = run_cli_if_requested(&args) {
return code;
}
match run_gui() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("[run] {error}");
ExitCode::FAILURE
}
}
}
/// 把窗口拉起来(分发之后的唯一路径)。
fn run_gui() -> Result<(), slint::PlatformError> {
apply_renderer_flag();
let app = ui_bind::AppUi::with_options(MainWindow::new()?, screenshot::app_options());
// 截图验收通道(M41 视觉验收;无交互桌面/无 GPU 环境下的唯一可靠取图方式:
// 不截屏幕,而是让 Slint 把当前场景渲染进内存像素缓冲再自己编码 PNG)。
// P3 追加页面选择与中间态(安装进度 / 启动事件流),见 `crate::screenshot`。
if let Some(options) = screenshot::shot_options() {
screenshot::capture(&app, &options)?;
return Ok(());
}
app.start_timer();
app.run()
}
/// 子命令命中 CLI 就跑 CLI 并以它的退出码收尾;返回 `None` 表示「这不是 CLI 调用,去开窗」。
///
/// 这条路径上**不构造窗口、不探后端、不扫字体、不依赖任何图形库**(这些库缺失时同一条命令照样
/// 跑完,实测见 packaging/README.md §7.4)。`unlucky-launcher launch …` 的耗时因此与首帧无关——
/// 这句是结构性判断,**没有重量**(原因见 §10-8)。
///
/// 「这条命令行算不算 CLI 调用」的判据不在这里重复:`unlucky_cli::cli::looks_like_cli` 是唯一
/// 一处(M82 复审去重),两个 GUI 二进制都只调它,改语义不会漂。
fn run_cli_if_requested(args: &[String]) -> Option<ExitCode> {
if !unlucky_cli::cli::looks_like_cli(args) {
return None;
}
let mut stdout = std::io::stdout();
let mut stderr = std::io::stderr();
let code = unlucky_cli::run(args, &mut stdout, &mut stderr);
let _ = std::io::Write::flush(&mut stdout);
let _ = std::io::Write::flush(&mut stderr);
Some(ExitCode::from(u8::try_from(code).unwrap_or(2)))
}
/// 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");
}
}
+36
View File
@@ -0,0 +1,36 @@
//! `PageState` global 的状态灌入(从 `ui_bind` 拆出,守 400 行上限)。
//!
//! 一个函数只做「AppState → Slint global 属性」的搬运,同步发生在每一拍末尾
//! (`ui_bind::Inner::sync`)。分文件而不是砍内容:这些字段每一行都对应一个页面元素。
use crate::conv;
use crate::ui_bind::model;
use crate::{MainWindow, PageState};
use slint::ComponentHandle;
use unlucky_presenter::state::AppState;
/// 把页面状态灌进 `PageState`。
pub(crate) fn apply(ui: &MainWindow, state: &AppState) {
// 导航底部账户 + PageState 全量页面状态(账户/Java/安装/设置/通知/向导)
ui.set_account_name(conv::active_account_name(state).into());
let page = ui.global::<PageState<'_>>();
page.set_accounts(model(conv::accounts(state)));
page.set_active_account(conv::active_account_name(state).into());
page.set_device(conv::device(state));
page.set_java_vendors(model(conv::java_vendors(state)));
page.set_java_chain(model(conv::java_chain(state)));
page.set_java_runtimes(model(conv::java_runtimes(state)));
page.set_java_order(state.java.order_text.clone().into());
page.set_java_region(state.java.region.clone().into());
page.set_java_priority_source(state.java.priority_source.clone().into());
page.set_java_message(state.java.message.clone().into());
page.set_java_busy(state.java.busy);
let major = state.java.majors().last().copied().unwrap_or(17);
page.set_java_target_major(i32::try_from(major).unwrap_or(17));
page.set_install(conv::install(state));
page.set_setting_groups(model(conv::setting_groups(state)));
page.set_setting_tab(state.settings_tab.clone().into());
page.set_notices(model(conv::notices(state)));
page.set_wizard(conv::wizard(state));
page.set_wizard_versions(model(conv::wizard_versions(state)));
}
+140
View File
@@ -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"));
}
}
+177
View File
@@ -0,0 +1,177 @@
//! 截图验收通道的参数解析与流程(`--screenshot*` / `--data-dir` / `--mock`)。
//!
//! 为什么用进程内渲染而不是截屏:验收机没有交互桌面(`CopyFromScreen` 直接失败),
//! 而 Slint 的软件渲染器能把场景渲进内存像素缓冲(`Window::take_snapshot`),
//! 结果与屏幕上逐像素一致且不需要 GPU(M41 落地的通道,这里只加页面/中间态参数)。
//!
//! 中间态(安装进度 / 启动事件流)走真实后端:`--screenshot-install <版本>` 会真的发起
//! 一次安装并停若干毫秒后取图,`--screenshot-launch <实例>` 同理。
use std::path::PathBuf;
use crate::ui_bind::AppUi;
use unlucky_presenter::backend::AppOptions;
use unlucky_presenter::dto::AppCommand;
/// 一次截图请求。
#[derive(Debug, Clone, Default)]
pub struct ShotOptions {
/// 输出 PNG 路径
pub path: String,
/// 页面名(instances / download / java / logs / settings / account / appearance / agent)
pub page: Option<String>,
/// 打开新建实例向导
pub wizard: bool,
/// 发起一次真实安装并停 `dwell_ms` 后取图(中间态)
pub install: Option<String>,
/// 安装走哪个加载器(`--screenshot-loader forge`;缺省 = 原版)
pub loader: Option<String>,
/// 发起一次真实启动并停 `dwell_ms` 后取图(中间态)
pub launch: Option<String>,
/// 打开一个日志会话(日志页有数据态:日志行 + 诊断卡片)
pub session: Option<String>,
/// 中间态停留毫秒(默认 2500)
pub dwell_ms: u64,
}
impl ShotOptions {
/// 中间态默认停留时长。
pub const DEFAULT_DWELL_MS: u64 = 2_500;
}
/// 从命令行读启动选项(数据根 / mock)。
pub fn app_options() -> AppOptions {
AppOptions {
data_root: value_of("--data-dir").map(PathBuf::from),
mock: flag("--mock"),
}
}
/// 从命令行读截图请求;没有 `--screenshot` 时返回 `None`。
pub fn shot_options() -> Option<ShotOptions> {
let path = value_of("--screenshot")?;
let page = value_of("--screenshot-page");
let mut options = ShotOptions {
path,
page: if flag("--screenshot-settings") {
Some("appearance".to_string())
} else {
page
},
wizard: flag("--screenshot-wizard"),
install: value_of("--screenshot-install"),
loader: value_of("--screenshot-loader"),
launch: value_of("--screenshot-launch"),
session: value_of("--screenshot-session"),
dwell_ms: value_of("--screenshot-dwell")
.and_then(|value| value.parse().ok())
.unwrap_or(ShotOptions::DEFAULT_DWELL_MS),
};
if options.dwell_ms < 500 {
options.dwell_ms = 500;
}
options.page = options.page.filter(|page| !page.trim().is_empty());
Some(options)
}
/// 执行截图流程:切页 → (可选)中间态 → 渲染 PNG。
///
/// # Errors
/// 窗口显示/快照/写文件失败时返回错误。
pub fn capture(app: &AppUi, options: &ShotOptions) -> Result<(), slint::PlatformError> {
if let Some(page) = &options.page {
app.open_page(page);
// 先给后端一次全量刷新:版本清单要在后台线程里拉(12h 缓存),
// 下载页/Java 页/向导需要它才有「有数据态」。
let warmup = if matches!(page.as_str(), "download" | "java") {
4_000
} else {
1_200
};
app.dispatch_and_run(AppCommand::RefreshAll, warmup);
}
if options.wizard {
app.open_wizard();
}
if let Some(version) = &options.install {
app.dispatch_and_run(
install_command(version, options.loader.as_deref()),
options.dwell_ms,
);
}
if let Some(session) = &options.session {
app.open_session(session);
app.dispatch_and_run(AppCommand::RefreshLogSessions, options.dwell_ms.min(1_000));
}
if let Some(instance) = &options.launch {
app.dispatch_and_run(
AppCommand::LaunchInstance(instance.clone()),
options.dwell_ms,
);
}
app.render_screenshot(&options.path)?;
// 启动中间态截完就把进程收掉:截图进程退出后子进程会变孤儿,
// 所以在取图之后显式 stop(kill_tree),不留给系统。
if let Some(instance) = &options.launch {
app.dispatch_and_run(AppCommand::StopInstance(instance.clone()), 1_500);
}
Ok(())
}
/// 截图通道的安装指令:缺省原版,给了 `--screenshot-loader` 就走向导同一条路
/// (`CreateInstance`),因此 Forge/NeoForge 的中间态也能取图。
fn install_command(version: &str, loader: Option<&str>) -> AppCommand {
match loader.map(unlucky_presenter::dto::LoaderKind::parse) {
Some(Some(kind)) => AppCommand::CreateInstance(unlucky_presenter::dto::CreateRequest {
version: version.to_string(),
loader: kind,
loader_version: String::new(),
name: version.to_string(),
}),
_ => AppCommand::InstallVersion(version.to_string()),
}
}
/// `--flag` 是否存在。
pub fn flag(name: &str) -> bool {
std::env::args().skip(1).any(|arg| arg == name)
}
/// `--key value` / `--key=value` 的取值。
pub fn value_of(name: &str) -> Option<String> {
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if let Some(value) = arg.strip_prefix(&format!("{name}=")) {
return Some(value.to_string());
}
if arg == name {
return args.next();
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_dwell_is_a_visible_mid_state() {
const DEFAULT: u64 = ShotOptions::DEFAULT_DWELL_MS;
let dwell = DEFAULT;
assert!(dwell >= 1_000, "中间态至少要停 1 秒才看得见进度");
}
#[test]
fn options_without_screenshot_are_none() {
// 测试进程没有 --screenshot 参数
assert!(
shot_options().is_none() || std::env::args().any(|arg| arg.contains("--screenshot"))
);
}
#[test]
fn value_of_ignores_absent_flags() {
assert!(value_of("--definitely-not-a-real-flag").is_none());
}
}
+152
View File
@@ -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::ui_bind::Inner;
use unlucky_presenter::prefs::{AppearancePrefs, BgFill, ThemeMode};
use unlucky_presenter::theme::{
config_poll_due, system_theme_poll_due, system_theme_value, BackgroundKey,
};
use unlucky_presenter::toast::ToastKind;
impl Inner {
pub(crate) fn poll_settings(&self) {
if !config_poll_due(self.ticks.get()) {
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 = system_theme_poll_due(
self.system_theme_probed.get(),
auto,
backend_known,
self.ticks.get(),
);
if !due {
return;
}
self.system_theme_probed.set(true);
let value = system_theme_value();
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`,避免拖动窗口时反复重算)。
///
/// 判据在 [`unlucky_presenter::theme::tile_viewport`](两侧 UI 共用一份);这里只负责
/// 提供窗口物理尺寸。
fn tile_viewport(&self, fill: BgFill) -> (u32, u32) {
if fill != BgFill::Tile {
return (0, 0);
}
unlucky_presenter::theme::tile_viewport(fill, self.window_physical_size())
}
/// 窗口物理像素尺寸(取不到时 (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);
}
}
+314
View File
@@ -0,0 +1,314 @@
//! 绑定层(核心):窗口/状态/后端的持有与同步;回调接线在 [`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::{MainWindow, PageState, SettingSection};
use unlucky_presenter::backend::{build_backend, config_path, AppOptions};
use unlucky_presenter::dto::{AppCommand, Backend};
use unlucky_presenter::settings_bridge::SettingsBridge;
use unlucky_presenter::state::AppState;
use unlucky_presenter::theme::BackgroundKey;
/// 定时器节拍:33ms ≈ 30fps(磁贴进度环 / 流式文本 / Toast TTL 的刷新下限)。
const TICK_MS: u64 = 33;
/// 应用外壳:持有窗口、状态与后端,把三者缝在一起。
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>,
}
impl AppUi {
/// 建状态 + 真实后端、读配置、接全部回调、灌初始事件并做第一次同步。
pub fn new(ui: MainWindow) -> Self {
Self::with_options(ui, AppOptions::default())
}
/// 带启动选项装配(数据根覆盖 / 强制 mock)。
pub fn with_options(ui: MainWindow, options: AppOptions) -> Self {
// 先读一次落盘配置:主题三态 + 外观四件必须在首帧前就位(否则会闪一下出厂外观)
let bridge = match &options.data_root {
Some(root) => SettingsBridge::with_path(config_path(root)),
None => SettingsBridge::open(),
};
let (appearance, theme) = bridge.load();
let mut state = AppState::new();
state.prefs.appearance = appearance;
state.prefs.theme = theme;
let backend = build_backend(&options);
let inner = Rc::new(Inner {
ui,
state: RefCell::new(state),
backend: RefCell::new(backend),
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));
crate::callbacks_pages::wire_pages(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(unlucky_presenter::router::Route::Settings);
self.inner.sync();
self.inner
.ui
.set_settings_section(SettingSection::Appearance);
slint::platform::update_timers_and_animations();
}
/// 直接跳到一个页面(截图验收用:每页一张)。
pub fn open_page(&self, page: &str) {
let route = match page {
"download" | "java" => unlucky_presenter::router::Route::Download,
"logs" => unlucky_presenter::router::Route::Logs,
"settings" | "account" | "appearance" => unlucky_presenter::router::Route::Settings,
"agent" => unlucky_presenter::router::Route::Agent,
_ => unlucky_presenter::router::Route::Instances,
};
{
let mut state = self.inner.state.borrow_mut();
state.navigate(route);
match page {
"account" => state.settings_tab = "account".to_string(),
"java" => state.settings_tab = "java".to_string(),
"settings" => state.settings_tab = "download".to_string(),
_ => {}
}
let download_tab = i32::from(page == "java");
self.inner
.ui
.global::<PageState<'_>>()
.set_download_tab(download_tab);
}
match page {
"account" => self.inner.ui.set_settings_section(SettingSection::Account),
"java" => self.inner.ui.set_settings_section(SettingSection::Java),
"appearance" => self
.inner
.ui
.set_settings_section(SettingSection::Appearance),
"settings" => self.inner.ui.set_settings_section(SettingSection::Download),
_ => {}
}
self.inner.sync();
slint::platform::update_timers_and_animations();
}
/// 打开新建实例向导(截图验收用)。
pub fn open_wizard(&self) {
self.inner.state.borrow_mut().wizard = unlucky_presenter::wizard::WizardState::open();
self.inner.sync();
slint::platform::update_timers_and_animations();
}
/// 打开一个日志会话(截图验收:日志行 + 诊断卡片 + 头部标题都要有值)。
pub fn open_session(&self, id: &str) {
self.inner.state.borrow_mut().selected_session = Some(id.to_string());
self.inner
.dispatch(AppCommand::OpenLogSession(id.to_string()));
self.inner.sync();
slint::platform::update_timers_and_animations();
}
/// 派发一条指令并跑若干毫秒(截图中间态:安装进度 / 启动事件流)。
pub fn dispatch_and_run(&self, command: AppCommand, millis: u64) {
self.inner.dispatch(command);
let steps = (millis / TICK_MS).max(1);
for _ in 0..steps {
self.inner.tick();
slint::platform::update_timers_and_animations();
std::thread::sleep(Duration::from_millis(TICK_MS));
}
}
/// 渲染当前场景并存成 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,
)));
// 先走几拍:把后端事件(实例/版本/日志/账户/设置)与 33ms 节拍的效果灌进去
for _ in 0..8 {
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);
// PageState(账户/Java/安装/设置/通知/向导)在独立模块里灌,守 400 行
crate::page_sync::apply(ui, &state);
}
}
/// Slint 列表模型(VecModel → ModelRc)。
pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
ModelRc::new(VecModel::from(items))
}