api修改和更新检查器修改

modrinth_api.dart:拦截器改为只替换 options.baseUrl,path 保持相对 /v2/search、query 留在 queryParameters,避免"整串写回 path"导致的 host 缺失 + query 重复拼接。mirror_service.dart:新增 apiBase getter,返回当前镜像的 API base(official→api.modrinth.com、mcim→modrinth-api.mcimirror.top、custom→自定义 base)

Signed-off-by: driftinblock <3480428251@qq.com>
This commit is contained in:
Ventiの酒 committed 2026-11-04 17:43:57 +08:00
1 parent ddd72c43fb
commit e32125aa8e
35 files changed
+4171 -1325

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
- platform: web
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
+92 -41
View File
@@ -1,88 +1,139 @@
ZV Manager
# ZV Manager
你的手机,就是服务器控制台
> 你的手机,就是服务器控制台
ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。通过 RCON 协议,让你随时随地用手机管理你的服务器,无需打开电脑。
---
功能特性
## 功能特性
| 模块 | 功能 | 状态 |
|------|------|------|
| 服务器管理 | 添加/编辑/删除服务器 |
| 服务器管理 | 多服务器切换 |
| 状态监控 | 实时在线人数 |
| 状态监控 | TPS 监控
| 玩家管理 | 查看玩家列表
| 玩家管理 | 授予/撤销 OP
| 玩家管理 | 踢出/封禁玩家
| 玩家管理 | 批量操作玩家
| 控制台 | RCON 模式 |
| 控制台 | 快速命令预设
| 主题 | 浅色/深色/跟随系统
| 壁纸 | 自定义壁纸
| 数据 | 加密存储 | 模组管理 | SFTP 浏览 mods/plugins 目录 | ✅ v2.0 新增 |
| 服务器管理 | 添加/编辑/删除服务器 | ✅ |
| 服务器管理 | 多服务器切换 | ✅ |
| 状态监控 | 实时在线人数 | ✅ |
| 状态监控 | TPS 监控 | ✅ |
| 玩家管理 | 查看玩家列表 | ✅ |
| 玩家管理 | 授予/撤销 OP | ✅ |
| 玩家管理 | 踢出/封禁玩家 | ✅ |
| 玩家管理 | 批量操作玩家 | ✅ |
| 控制台 | RCON 模式 | ✅ |
| 控制台 | 快速命令预设 | ✅ |
| 主题 | 浅色/深色/跟随系统 | ✅ |
| 壁纸 | 自定义壁纸 | ✅ |
| 数据 | 加密存储 | ✅ |
| 模组管理 | SFTP 浏览 mods/plugins 目录 | ✅ v2.0 新增 |
| 模组管理 | 上传/删除/重命名 jar | ✅ v2.0 新增 |
| 模组管理 | 解析 fabric.mod.json / plugin.yml 元数据(名称/版本/作者/依赖) | ✅ v2.0 新增 |
| 下载中心 | Modrinth 搜索与下载(支持 MC 版本/加载器筛选) | ✅ v2.0 新增 |
| 下载中心 | 多任务并发队列(默认 3)、断点续传、失败指数退避重试 | ✅ v2.0 新增 |
| 下载中心 | 镜像线路(MCIM 国内镜像 / 自定义)+ 一键测速自动选线 | ✅ v2.0 新增 |
| 下载中心 | 镜像线路(MCIM 国内镜像 / 官方 / 自定义)+ 一键测速自动选线,镜像连接失败自动回退官方源 | ✅ v2.0 新增 |
| 下载中心 | 下载完成自动经 SFTP 上传到服务器对应目录 | ✅ v2.0 新增 |
| 终端 | SSH Shell(xterm 终端、快捷键栏、多会话标签、断线自动重连) | ✅ v2.0 新增 |
| UI | Dashboard 卡片式首页 + 底部导航(服务器/控制台/玩家/模组/终端/我的) | ✅ v2.0 新增 |
| UI | 全站 ZL2 风格(分组圆角面板 / 两行式设置行 / 圆形绿底勾选钮 / 透明沉浸顶栏) | ✅ v2.0 新增 |
| UI | 控制台日志级别着色(INFO 绿 / WARN 黄 / ERROR 红) | ✅ v2.0 新增 |
| 依赖仓库 | SQLite 依赖索引 + 增量同步 + 依赖树查询 + 缺失依赖一键补齐 + 重复检测 | ✅ v2.0 新增 |
技术栈
## 技术栈
| 项目 | 说明 |
|------|------|
| **版本** | 2.0.3 |
| **框架** | Flutter 3.x |
| **语言** | Dart 3.x |
| **目标平台** | Android 7.0+ / Web |
| **通信协议** | RCON (Minecraft 远程控制协议) + SSH/SFTP (dartssh2) |
| **本地存储** | Shared Preferences + Flutter Secure Storage + SQLite (依赖索引) |
| **状态管理** | Provider |
| **主题** | Material 3 |
| **主题** | Material 3 + ZL2 风格组件库(`core/widgets/z_widgets.dart`) |
| **网络** | Dio(Modrinth API / 镜像线路 / 下载队列) |
| **国际化** | 轻量 i18n(`core/l10n/strings.dart`,中 / 英) |
---
项目结构
## 项目结构
```
lib/
├── main.dart # 应用入口
├── app.dart # MaterialApp 配置
├── main.dart # 应用入口
├── app.dart # MaterialApp 配置、全局壁纸层
├── core/
│ ├── l10n/
│ │ └── strings.dart # 轻量 i18n(S.t / S.f / T)
│ ├── services/
│ │ ├── dependency_index_service.dart # 依赖索引(SQLite 增量同步 / 依赖树)
│ │ ├── download_manager.dart # 下载队列(并发 / 断点续传 / 退避重试)
│ │ ├── jar_metadata.dart # jar 元数据解析(fabric.mod.json / plugin.yml)
│ │ ├── mirror_service.dart # 镜像线路(MCIM / 官方 / 自定义)+ 测速
│ │ ├── modrinth_api.dart # Modrinth API 客户端(镜像故障回退官方)
│ │ ├── sftp_service.dart # SFTP 文件传输
│ │ └── ssh_shell_service.dart # SSH Shell 会话
│ ├── theme/
│ │ └── app_theme.dart # MD3 主题定义
│ │ └── app_theme.dart # Material 3 主题 + ZL2 配色
│ ├── utils/
│ │ ├── rcon_client.dart # RCON 客户端
│ │ └── update_service.dart # 更新检查
│ │ ├── background_service.dart # 后台保活
│ │ ├── command_preset_service.dart # 控制台命令预设
│ │ ├── rcon_client.dart # RCON 客户端
│ │ ├── rcon_stream_parser.dart # RCON 流解析
│ │ └── update_service.dart # Gitee Release 更新检查 / 安装
│ └── widgets/
│ └── background_widget.dart # 壁纸背景组件
│ ├── background_widget.dart # 全局壁纸背景(交叉淡入防闪)
│ ├── empty_state_page.dart # 空态占位页
│ ├── user_agreement_dialog.dart # 用户守则弹窗
│ └── z_widgets.dart # ZL2 公共组件库(ZPanel / ZRow / ZToggle / ZAppBar / ZSheetRow …)
├── data/
│ └── services/
│ └── secure_storage_service.dart # 加密存储
│ └── secure_storage_service.dart # 加密存储
├── features/
│ ├── server_list/
│ │ ├── server_list_page.dart # 服务器列表
│ │ └── server_form_dialog.dart # 添加/编辑弹窗
│ ├── console/
│ │ └── console_page.dart # 双模式控制台
│ │ └── console_page.dart # RCON 控制台(日志着色 / 预设命令)
│ ├── dashboard/
│ │ ├── dashboard_page.dart # 首页(状态宫格 / 服务器列表 / 快捷入口)
│ │ └── server_picker_bar.dart # 服务器切换条
│ ├── download/
│ │ └── download_page.dart # 下载中心(Modrinth 搜索 + 任务队列)
│ ├── mod_manager/
│ │ ├── dependency_tree_page.dart # 依赖树 / 缺失补齐 / 重复检测
│ │ ├── mod_detail_page.dart # 模组详情
│ │ ├── mod_list_page.dart # 模组 / 插件列表
│ │ └── mod_provider.dart # 模组状态
│ ├── player_management/
│ │ └── player_list_page.dart # 玩家管理
│ └── settings/
│ ├── settings_page.dart # 设置页
│ └── wallpaper_settings.dart # 壁纸设置
│ │ ├── player_list_page.dart # 玩家列表(OP / 踢出 / 封禁 / 批量)
│ │ └── player_service.dart # 玩家数据服务
│ ├── server_list/
│ │ ├── server_card.dart # 服务器卡片
│ │ ├── server_form_dialog.dart # 添加 / 编辑弹窗(含 SSH 配置)
│ │ └── server_list_page.dart # 服务器列表
│ ├── settings/
│ │ ├── about_page.dart # 关于 / 检查更新
│ │ ├── download_settings_page.dart # 下载设置(镜像线路 / 测速 / 并发)
│ │ ├── help_page.dart # 使用教程
│ │ ├── server_log_page.dart # 服务器日志
│ │ ├── settings_page.dart # 设置主页
│ │ └── wallpaper_settings.dart # 壁纸设置
│ ├── shell/
│ │ └── main_shell.dart # 底部导航壳(6 个 Tab)
│ └── terminal/
│ └── terminal_page.dart # SSH 终端(xterm / 多会话 / 快捷键)
└── providers/
├── server_provider.dart # 服务器状态
├── theme_provider.dart # 主题状态
├── wallpaper_provider.dart # 壁纸状态
└── rcon_provider.dart # RCON 状态
├── download_provider.dart # 下载任务状态
├── language_provider.dart # 语言状态
├── rcon_provider.dart # RCON 状态
├── server_provider.dart # 服务器状态
├── theme_provider.dart # 主题状态
└── wallpaper_provider.dart # 壁纸状态
```
顶层目录:
| 目录 | 说明 |
|------|------|
| `android/` `web/` | 各平台工程 |
| `assets/` | 图片 / 图标资源 |
| `docs/` | 用户守则等文档 |
| `test/` | 单元测试 |
| `third_party/dartssh2/` | 本地 dartssh2 副本(pubspec 以 path 依赖引入) |
---
+188 -78
View File
@@ -123,13 +123,14 @@ class S {
// ---- 下载与镜像设置 ----
'镜像线路': 'Mirror',
'MCIM 国内镜像(推荐)': 'MCIM China mirror (recommended)',
'modrinth.mcimirror.top,无需科学上网': 'modrinth.mcimirror.top, no VPN needed',
'mod.mcimirror.top,无需科学上网': 'mod.mcimirror.top, no VPN needed',
'Modrinth 官方': 'Modrinth official',
'直连官方源,适合海外网络': 'Direct official source, best overseas',
'自定义镜像': 'Custom mirror',
'使用自建/第三方镜像地址': 'Use your own/third-party mirror URL',
'一键测速并选择最快线路': 'Speed test & pick fastest',
'自动在官方与镜像之间选择延迟最低的线路': 'Auto-pick lowest latency between official & mirrors',
'自动在官方与镜像之间选择延迟最低的线路':
'Auto-pick lowest latency between official & mirrors',
'下载队列': 'Queue',
'同时下载任务数': 'Concurrent downloads',
'说明:下载完成的文件保存在应用目录 downloads/ 下;':
@@ -152,7 +153,8 @@ class S {
'下载与镜像设置': 'Download & mirror settings',
'镜像线路、测速选线、同时下载任务数': 'Mirror, speed test, concurrent downloads',
'使用教程': 'Tutorials',
'如何开启 RCON / SSH、模组管理、下载与终端': 'How to enable RCON / SSH, mods, downloads & terminal',
'如何开启 RCON / SSH、模组管理、下载与终端':
'How to enable RCON / SSH, mods, downloads & terminal',
'检查更新': 'Check updates',
'关于': 'About',
'开发者:Z有3笔,协作者:venti1112': 'Developer: Z有3笔, Collaborator: venti1112',
@@ -190,7 +192,8 @@ class S {
'该版本没有可用文件': 'No files for this version',
'上次测速:{0}ms({1})': 'Last test: {0}ms ({1})',
'已选择最快线路:{0}({1}ms)': 'Fastest route: {0} ({1}ms)',
'当前:{0} 个(越大越占带宽,建议 1-3)': 'Now: {0} (more uses more bandwidth; 1-3 recommended)',
'当前:{0} 个(越大越占带宽,建议 1-3)':
'Now: {0} (more uses more bandwidth; 1-3 recommended)',
'{0} 个版本共存': '{0} versions coexist',
'同步失败:{0}': 'Sync failed: {0}',
'当前版本: {0}': 'Current version: {0}',
@@ -204,49 +207,85 @@ class S {
'壁纸设置保存失败,请重试': 'Failed to save wallpaper settings, please retry',
'背景已更新': 'Background updated',
' rcon.password=你的RCON密码': ' rcon.password=your RCON password',
'1. SSH 终端拥有服务器完全控制能力,您执行的任何命令(含删除文件、重启系统)后果由您自行承担。': '1. The SSH terminal grants full control of your server. You bear all consequences of any command you run (including deleting files or rebooting the system).',
'1. 下载功能数据来自 Modrinth 公开接口及其镜像线路(如 MCIM)。镜像线路由第三方维护,其可用性与安全性不由开发者控制。': '1. Download data comes from the public Modrinth API and its mirrors (e.g. MCIM). Mirrors are maintained by third parties; the developer does not control their availability or safety.',
'1. 仅管理您有权管理的服务器。严禁连接、探测、控制任何未获授权的第三方服务器——未经授权访问计算机系统属于违法行为。': '1. Only manage servers you are authorized to. Connecting to, probing or controlling any unauthorized third-party server is strictly prohibited — unauthorized access to computer systems is illegal.',
'1. 本软件不收集、不上传您的任何个人数据,全部数据保存在设备本地,卸载即删除。': '1. This app does not collect or upload any personal data. All data is stored locally on your device and removed on uninstall.',
'1. 本软件为免费开源软件,不提供商业担保。在法律允许的最大范围内,开发者不对因使用或无法使用本软件造成的任何直接或间接损失负责(包括数据丢失、服务器宕机、存档损坏、经济损失)。': '1. This software is free and open source, provided without commercial warranty. To the maximum extent permitted by law, the developer is not liable for any direct or indirect loss arising from use or inability to use (including data loss, server downtime, world corruption or financial loss).',
'1. 本软件按开源协议发布,可依协议使用、修改和分发;"ZV Manager"名称与图标版权归作者所有。': '1. This software is released under an open source license and may be used, modified and distributed accordingly. The name and logo "ZV Manager" are copyrighted by the author.',
'1. 连接凭据(RCON 密码、SSH 用户名/密码等)仅保存在您的设备本地(加密存储),本软件无云端账号系统,不会将凭据上传至开发者或任何第三方。': '1. Connection credentials (RCON password, SSH username/password, etc.) are stored only on your device (encrypted). This app has no cloud account system and never uploads credentials to the developer or any third party.',
'2. Minecraft 是 Mojang Studios 的商标,本软件与 Mojang、微软无任何隶属关系。': '2. Minecraft is a trademark of Mojang Studios. This software is not affiliated with Mojang or Microsoft.',
'2. 因第三方服务(Modrinth、镜像源、托管商、网络)变更或故障导致的异常,开发者不承担责任。': '2. The developer is not responsible for issues caused by changes or failures of third-party services (Modrinth, mirrors, hosting providers, networks).',
'2. 应用仅联网检查更新(Gitee 发布页)及访问 Modrinth/镜像接口,无其他网络请求。': '2. The app only connects to the network to check updates (Gitee releases) and access the Modrinth/mirror APIs; there are no other network requests.',
'2. 建议不要以 root 账户长期连接,执行不熟悉的命令前请先确认其作用。': '2. Avoid staying connected as root for long periods, and confirm what a command does before running unfamiliar ones.',
'2. 第三方模组/插件可能影响服务器稳定性,安装前请备份重要数据;"依赖仓库"查询结果仅供参考。': '2. Third-party mods/plugins may affect server stability. Back up important data before installing; "Dependency Index" results are for reference only.',
'2. 请妥善保管设备与凭据,因主动泄露、设备被他人使用、越狱/Root 等造成的损失由您自行承担。': '2. Keep your device and credentials safe. Losses caused by voluntary disclosure, unauthorized device use, jailbreak/Root, etc. are borne by you.',
'2. 遵守《网络安全法》《计算机信息系统安全保护条例》等法律法规及 Minecraft EULA 与服务器规则。': '2. Comply with applicable laws and regulations (e.g. the Cybersecurity Law) as well as the Minecraft EULA and server rules.',
'3. 不得利用本软件传播违法信息、破坏他人服务器、恶意攻击或盗取数据。': '3. Do not use this software to spread unlawful information, sabotage others\' servers, launch attacks or steal data.',
'3. 仅连接您拥有管理权限的服务器,并使用强密码、定期更换。': '3. Only connect to servers you administer, using strong passwords changed regularly.',
'3. 命令历史仅保存在设备本地,可在应用内清除,本软件不做任何云端记录。': '3. Command history is stored locally only, can be cleared in the app, and is never recorded in the cloud.',
'4. 下载中心获取的模组/插件版权归原作者所有,请遵守对应开源协议,不得下载、分发盗版或破解内容。': '4. Mods/plugins obtained from the Download Center belong to their authors. Follow the corresponding licenses; pirated or cracked content must not be downloaded or distributed.',
'Fabric 模组放 mods 目录;Paper/Spigot 插件放 plugins 目录': 'Fabric mods go in the mods directory; Paper/Spigot plugins go in the plugins directory',
'Q:TPS 显示 —?→ 原版服务端不支持 tps 命令,Paper/Purpur 等服务端才支持': 'Q: TPS shows "—"? → Vanilla servers do not support the tps command; only Paper/Purpur and similar do',
'Q:上传模组后不生效?→ 需要重启服务器': 'Q: Mod upload not taking effect? → Restart the server',
'Q:控制台能连但模组页提示无 SSH?→ 编辑服务器开启 SSH 并填好账号密码': 'Q: Console connects but the mods page says no SSH? → Edit the server, enable SSH and fill in the credentials',
'Q:连接失败?→ 检查防火墙是否放行端口、地址端口是否填对、服务器是否在线': 'Q: Connection failed? → Check firewall rules for the port, verify address/port, and confirm the server is online',
'SSH 拥有服务器完全控制权,请勿随意执行不熟悉的命令': 'SSH grants full server control; do not run unfamiliar commands carelessly',
'SSH 是服务器自带的远程管理服务,绝大多数独立服务器默认已开启(端口 22)': 'SSH is a built-in remote management service, enabled by default on most standalone servers (port 22)',
'ZV Manager 是一款 Minecraft 服务器远程管理工具,通过 RCON、SSH/SFTP 等协议连接到您有权管理的服务器,提供服务器控制、玩家管理、模组插件管理、文件下载与远程终端等功能。本软件按"现状"提供。': 'ZV Manager is a remote management tool for Minecraft servers. It connects to servers you are authorized to manage via RCON, SSH/SFTP and other protocols, offering server control, player management, mod/plugin management, file downloads and a remote terminal. The software is provided "as is".',
'ZV Manager:服务器页 → 编辑服务器 → 打开「SSH 连接」开关 → 填端口(默认 22)、用户名、密码 → 保存': 'ZV Manager: Servers → Edit server → enable "SSH Connection" → fill in port (default 22), username and password → Save',
'screen -r 可以进入服务器控制台会话(开服时用了 screen 的话)': 'screen -r reattaches to the server console session (if you started the server inside screen)',
'© 2026 ZV Team · 与 Mojang 无关': '© 2026 ZV Team · Not affiliated with Mojang',
'一、如何开启 RCON(必配,控制台/玩家管理需要)': '1. How to enable RCON (required for console/player management)',
'1. SSH 终端拥有服务器完全控制能力,您执行的任何命令(含删除文件、重启系统)后果由您自行承担。':
'1. The SSH terminal grants full control of your server. You bear all consequences of any command you run (including deleting files or rebooting the system).',
'1. 下载功能数据来自 Modrinth 公开接口及其镜像线路(如 MCIM)。镜像线路由第三方维护,其可用性与安全性不由开发者控制。':
'1. Download data comes from the public Modrinth API and its mirrors (e.g. MCIM). Mirrors are maintained by third parties; the developer does not control their availability or safety.',
'1. 仅管理您有权管理的服务器。严禁连接、探测、控制任何未获授权的第三方服务器——未经授权访问计算机系统属于违法行为。':
'1. Only manage servers you are authorized to. Connecting to, probing or controlling any unauthorized third-party server is strictly prohibited — unauthorized access to computer systems is illegal.',
'1. 本软件不收集、不上传您的任何个人数据,全部数据保存在设备本地,卸载即删除。':
'1. This app does not collect or upload any personal data. All data is stored locally on your device and removed on uninstall.',
'1. 本软件为免费开源软件,不提供商业担保。在法律允许的最大范围内,开发者不对因使用或无法使用本软件造成的任何直接或间接损失负责(包括数据丢失、服务器宕机、存档损坏、经济损失)。':
'1. This software is free and open source, provided without commercial warranty. To the maximum extent permitted by law, the developer is not liable for any direct or indirect loss arising from use or inability to use (including data loss, server downtime, world corruption or financial loss).',
'1. 本软件按开源协议发布,可依协议使用、修改和分发;"ZV Manager"名称与图标版权归作者所有。':
'1. This software is released under an open source license and may be used, modified and distributed accordingly. The name and logo "ZV Manager" are copyrighted by the author.',
'1. 连接凭据(RCON 密码、SSH 用户名/密码等)仅保存在您的设备本地(加密存储),本软件无云端账号系统,不会将凭据上传至开发者或任何第三方。':
'1. Connection credentials (RCON password, SSH username/password, etc.) are stored only on your device (encrypted). This app has no cloud account system and never uploads credentials to the developer or any third party.',
'2. Minecraft 是 Mojang Studios 的商标,本软件与 Mojang、微软无任何隶属关系。':
'2. Minecraft is a trademark of Mojang Studios. This software is not affiliated with Mojang or Microsoft.',
'2. 因第三方服务(Modrinth、镜像源、托管商、网络)变更或故障导致的异常,开发者不承担责任。':
'2. The developer is not responsible for issues caused by changes or failures of third-party services (Modrinth, mirrors, hosting providers, networks).',
'2. 应用仅联网检查更新(Gitee 发布页)及访问 Modrinth/镜像接口,无其他网络请求。':
'2. The app only connects to the network to check updates (Gitee releases) and access the Modrinth/mirror APIs; there are no other network requests.',
'2. 建议不要以 root 账户长期连接,执行不熟悉的命令前请先确认其作用。':
'2. Avoid staying connected as root for long periods, and confirm what a command does before running unfamiliar ones.',
'2. 第三方模组/插件可能影响服务器稳定性,安装前请备份重要数据;"依赖仓库"查询结果仅供参考。':
'2. Third-party mods/plugins may affect server stability. Back up important data before installing; "Dependency Index" results are for reference only.',
'2. 请妥善保管设备与凭据,因主动泄露、设备被他人使用、越狱/Root 等造成的损失由您自行承担。':
'2. Keep your device and credentials safe. Losses caused by voluntary disclosure, unauthorized device use, jailbreak/Root, etc. are borne by you.',
'2. 遵守《网络安全法》《计算机信息系统安全保护条例》等法律法规及 Minecraft EULA 与服务器规则。':
'2. Comply with applicable laws and regulations (e.g. the Cybersecurity Law) as well as the Minecraft EULA and server rules.',
'3. 不得利用本软件传播违法信息、破坏他人服务器、恶意攻击或盗取数据。':
'3. Do not use this software to spread unlawful information, sabotage others\' servers, launch attacks or steal data.',
'3. 仅连接您拥有管理权限的服务器,并使用强密码、定期更换。':
'3. Only connect to servers you administer, using strong passwords changed regularly.',
'3. 命令历史仅保存在设备本地,可在应用内清除,本软件不做任何云端记录。':
'3. Command history is stored locally only, can be cleared in the app, and is never recorded in the cloud.',
'4. 下载中心获取的模组/插件版权归原作者所有,请遵守对应开源协议,不得下载、分发盗版或破解内容。':
'4. Mods/plugins obtained from the Download Center belong to their authors. Follow the corresponding licenses; pirated or cracked content must not be downloaded or distributed.',
'Fabric 模组放 mods 目录;Paper/Spigot 插件放 plugins 目录':
'Fabric mods go in the mods directory; Paper/Spigot plugins go in the plugins directory',
'Q:TPS 显示 —?→ 原版服务端不支持 tps 命令,Paper/Purpur 等服务端才支持':
'Q: TPS shows "—"? → Vanilla servers do not support the tps command; only Paper/Purpur and similar do',
'Q:上传模组后不生效?→ 需要重启服务器':
'Q: Mod upload not taking effect? → Restart the server',
'Q:控制台能连但模组页提示无 SSH?→ 编辑服务器开启 SSH 并填好账号密码':
'Q: Console connects but the mods page says no SSH? → Edit the server, enable SSH and fill in the credentials',
'Q:连接失败?→ 检查防火墙是否放行端口、地址端口是否填对、服务器是否在线':
'Q: Connection failed? → Check firewall rules for the port, verify address/port, and confirm the server is online',
'SSH 拥有服务器完全控制权,请勿随意执行不熟悉的命令':
'SSH grants full server control; do not run unfamiliar commands carelessly',
'SSH 是服务器自带的远程管理服务,绝大多数独立服务器默认已开启(端口 22)':
'SSH is a built-in remote management service, enabled by default on most standalone servers (port 22)',
'ZV Manager 是一款 Minecraft 服务器远程管理工具,通过 RCON、SSH/SFTP 等协议连接到您有权管理的服务器,提供服务器控制、玩家管理、模组插件管理、文件下载与远程终端等功能。本软件按"现状"提供。':
'ZV Manager is a remote management tool for Minecraft servers. It connects to servers you are authorized to manage via RCON, SSH/SFTP and other protocols, offering server control, player management, mod/plugin management, file downloads and a remote terminal. The software is provided "as is".',
'ZV Manager:服务器页 → 编辑服务器 → 打开「SSH 连接」开关 → 填端口(默认 22)、用户名、密码 → 保存':
'ZV Manager: Servers → Edit server → enable "SSH Connection" → fill in port (default 22), username and password → Save',
'screen -r 可以进入服务器控制台会话(开服时用了 screen 的话)':
'screen -r reattaches to the server console session (if you started the server inside screen)',
'© 2026 ZV Team · 与 Mojang 无关':
'© 2026 ZV Team · Not affiliated with Mojang',
'一、如何开启 RCON(必配,控制台/玩家管理需要)':
'1. How to enable RCON (required for console/player management)',
'一、软件性质与用途': '1. Nature and Purpose of the Software',
'七、常见问题': '7. FAQ',
'七、数据与隐私': '7. Data and Privacy',
'三、合法使用(重要)': '3. Lawful Use (Important)',
'三、模组 / 插件管理怎么用': '3. Using Mod / Plugin Management',
'上传后需重启服务器才会加载新模组(可在终端执行,或控制台发 stop 后重开)': 'The server must be restarted after uploading to load new mods (via terminal, or send stop in console and start again)',
'下载完成且配置了 SSH 时,会自动上传到服务器的 mods/plugins 目录': 'When the download finishes and SSH is configured, files upload automatically to the server\'s mods/plugins directory',
'不建议把 25575 端口直接暴露公网,强烈建议设置强密码': 'Do not expose port 25575 directly to the public internet; a strong password is strongly recommended',
'不确定的话:用电脑终端执行 ssh 用户名@服务器IP 试试能否登录': 'If unsure: run ssh user@server-ip in a desktop terminal to test login',
'上传后需重启服务器才会加载新模组(可在终端执行,或控制台发 stop 后重开)':
'The server must be restarted after uploading to load new mods (via terminal, or send stop in console and start again)',
'下载完成且配置了 SSH 时,会自动上传到服务器的 mods/plugins 目录':
'When the download finishes and SSH is configured, files upload automatically to the server\'s mods/plugins directory',
'不建议把 25575 端口直接暴露公网,强烈建议设置强密码':
'Do not expose port 25575 directly to the public internet; a strong password is strongly recommended',
'不确定的话:用电脑终端执行 ssh 用户名@服务器IP 试试能否登录':
'If unsure: run ssh user@server-ip in a desktop terminal to test login',
'九、守则变更': '9. Changes to This Agreement',
'二、如何开启 SSH(模组管理 / 终端 / 下载自动上传需要)': '2. How to enable SSH (required for mod management / terminal / auto upload)',
'二、如何开启 SSH(模组管理 / 终端 / 下载自动上传需要)':
'2. How to enable SSH (required for mod management / terminal / auto upload)',
'二、账号与凭据安全': '2. Account and Credential Security',
'云服务器/虚拟主机需在防火墙或安全组放行 rcon.port 端口': 'For cloud servers/VPS, open rcon.port in the firewall or security group',
'云服务器/虚拟主机需在防火墙或安全组放行 rcon.port 端口':
'For cloud servers/VPS, open rcon.port in the firewall or security group',
'五、模组管理与下载功能说明': '5. Mod Management and Downloads',
'五、远程终端': '5. Remote Terminal',
'保存后重启服务器生效': 'Restart the server after saving for changes to take effect',
@@ -257,44 +296,82 @@ class S {
'前提:该服务器已配置 SSH': 'Prerequisite: SSH is configured for this server',
'十、其他': '10. Miscellaneous',
'同意并进入': 'Agree and Continue',
'命令历史只保存在手机本地,可放心使用': 'Command history is stored on your phone only; use it with confidence',
'命令历史只保存在手机本地,可放心使用':
'Command history is stored on your phone only; use it with confidence',
'四、SSH / 终端功能风险提示': '4. SSH / Terminal Risk Notice',
'四、下载中心与镜像加速': '4. Download Center and Mirror Acceleration',
'回到 ZV Manager:服务器页 → 添加/编辑服务器,填入主机地址、端口(默认 25575)和 RCON 密码': 'Back in ZV Manager: Servers → Add/Edit server, fill in the host, port (default 25575) and RCON password',
'国内网络慢时:点右上角测速图标 →「一键测速并选择最快线路」,或改用自定义镜像地址': 'If the network is slow in China: tap the speed-test icon in the top right → "Test and pick the fastest route", or use a custom mirror URL',
'在服务器目录找到 server.properties 文件(与启动 jar 同目录)': 'Find server.properties in the server directory (same folder as the startup jar)',
'底部快捷键栏:Tab 补全、Ctrl+C 中断、Ctrl+D 退出、↑↓ 调历史,以及 htop / df -h / screen -r 常用命令': 'Bottom shortcut bar: Tab completion, Ctrl+C interrupt, Ctrl+D exit, ↑↓ history, plus htop / df -h / screen -r quick commands',
'开发者可能随版本更新修订本守则并在应用内展示;不同意修订内容请停止使用,继续使用即视为接受。': 'The developer may revise this agreement with version updates and display it in the app. If you disagree, stop using the app; continued use constitutes acceptance.',
'回到 ZV Manager:服务器页 → 添加/编辑服务器,填入主机地址、端口(默认 25575)和 RCON 密码':
'Back in ZV Manager: Servers → Add/Edit server, fill in the host, port (default 25575) and RCON password',
'国内网络慢时:点右上角测速图标 →「一键测速并选择最快线路」,或改用自定义镜像地址':
'If the network is slow in China: tap the speed-test icon in the top right → "Test and pick the fastest route", or use a custom mirror URL',
'在服务器目录找到 server.properties 文件(与启动 jar 同目录)':
'Find server.properties in the server directory (same folder as the startup jar)',
'底部快捷键栏:Tab 补全、Ctrl+C 中断、Ctrl+D 退出、↑↓ 调历史,以及 htop / df -h / screen -r 常用命令':
'Bottom shortcut bar: Tab completion, Ctrl+C interrupt, Ctrl+D exit, ↑↓ history, plus htop / df -h / screen -r quick commands',
'开发者可能随版本更新修订本守则并在应用内展示;不同意修订内容请停止使用,继续使用即视为接受。':
'The developer may revise this agreement with version updates and display it in the app. If you disagree, stop using the app; continued use constitutes acceptance.',
'我已阅读并同意《用户守则》': 'I have read and agree to the User Agreement',
'拿到 SSH 用户名(如 root)和密码': 'Obtain the SSH username (e.g. root) and password',
'断网会自动重连(最多 3 次)': 'Reconnects automatically after network loss (up to 3 times)',
'有的托管商需要先在控制台开启 SSH/SFTP 功能': 'Some hosting providers require enabling SSH/SFTP in their control panel first',
'本守则最终解释权归 ZV Team 所有。如有疑问或发现漏洞,欢迎通过 Gitee 仓库(gitee.com/driftinblock/zvmanager)或官方 QQ 群反馈。': 'The final interpretation of this agreement belongs to ZV Team. For questions or vulnerability reports, reach us via the Gitee repo (gitee.com/driftinblock/zvmanager) or the official QQ group.',
'本页教您一步步开启并使用 ZV Manager 的各项功能。': 'This guide walks you through enabling and using ZV Manager step by step.',
'点「上传 jar」从手机选择文件上传;长按/点菜单可删除、重命名': 'Tap "Upload jar" to pick a file from your phone; long-press/menu to delete or rename',
'点「同步」扫描服务器 mods/plugins,建立本地依赖索引': 'Tap "Sync" to scan the server\'s mods/plugins and build the local dependency index',
'点击任意模组查看:它依赖什么、被谁依赖、缺失哪些依赖': 'Tap any mod to see what it depends on, what depends on it, and which dependencies are missing',
'点击文件名可查看详情:模组名、版本、作者、依赖': 'Tap a file name for details: mod name, version, author, dependencies',
'点右上角重复检测按钮重复安装 / 版本冲突的 jar': 'Tap the duplicate-check button in the top right to find duplicated or conflicting jars',
'点结果选版本即可加入下载队列,支持暂停/继续/取消': 'Tap a result, pick a version and add it to the download queue; pause/resume/cancel supported',
'版本 v2.0 · 下载、安装或使用本软件,即视为您已阅读并同意本守则全部条款。': 'Version v2.0 · By downloading, installing or using this software, you are deemed to have read and agreed to all terms of this agreement.',
'版本要和 MC 版本、加载器匹配,否则服务器起不来': 'Versions must match the MC version and loader, or the server will fail to start',
'断网会自动重连(最多 3 次)':
'Reconnects automatically after network loss (up to 3 times)',
'有的托管商需要先在控制台开启 SSH/SFTP 功能':
'Some hosting providers require enabling SSH/SFTP in their control panel first',
'本守则最终解释权归 ZV Team 所有。如有疑问或发现漏洞,欢迎通过 Gitee 仓库(gitee.com/driftinblock/zvmanager)或官方 QQ 群反馈。':
'The final interpretation of this agreement belongs to ZV Team. For questions or vulnerability reports, reach us via the Gitee repo (gitee.com/driftinblock/zvmanager) or the official QQ group.',
'本页教您一步步开启并使用 ZV Manager 的各项功能。':
'This guide walks you through enabling and using ZV Manager step by step.',
'点「上传 jar」从手机选择文件上传;长按/点菜单可删除、重命名':
'Tap "Upload jar" to pick a file from your phone; long-press/menu to delete or rename',
'点「同步」扫描服务器 mods/plugins,建立本地依赖索引':
'Tap "Sync" to scan the server\'s mods/plugins and build the local dependency index',
'点击任意模组查看:它依赖什么、被谁依赖、缺失哪些依赖':
'Tap any mod to see what it depends on, what depends on it, and which dependencies are missing',
'点击文件名可查看详情:模组名、版本、作者、依赖':
'Tap a file name for details: mod name, version, author, dependencies',
'点右上角重复检测按钮重复安装 / 版本冲突的 jar':
'Tap the duplicate-check button in the top right to find duplicated or conflicting jars',
'点结果选版本即可加入下载队列,支持暂停/继续/取消':
'Tap a result, pick a version and add it to the download queue; pause/resume/cancel supported',
'版本 v2.0 · 下载、安装或使用本软件,即视为您已阅读并同意本守则全部条款。':
'Version v2.0 · By downloading, installing or using this software, you are deemed to have read and agreed to all terms of this agreement.',
'版本要和 MC 版本、加载器匹配,否则服务器起不来':
'Versions must match the MC version and loader, or the server will fail to start',
'用户守则': 'User Agreement',
'等同于电脑上的 SSH 终端,可以执行任意命令': 'Works like a desktop SSH terminal; you can run any command',
'缺失依赖可一键从 Modrinth 下载补齐': 'Missing dependencies can be downloaded from Modrinth with one tap',
'等同于电脑上的 SSH 终端,可以执行任意命令':
'Works like a desktop SSH terminal; you can run any command',
'缺失依赖可一键从 Modrinth 下载补齐':
'Missing dependencies can be downloaded from Modrinth with one tap',
'请仔细阅读守则({0}s)': 'Please read carefully ({0}s)',
'请先滑动阅读至守则底部': 'Please scroll to the bottom of the agreement first',
'请阅读至守则底部': 'Please read to the bottom of the agreement',
'输入关键词搜索 Modrinth 上的模组/插件,可用 MC 版本、加载器筛选': 'Search Modrinth mods/plugins by keyword; filter by MC version and loader',
'进入「服务器」页 → 下载中心(或首页快捷入口)': 'Go to the "Servers" page → Download Center (or the home shortcut)',
'进入「模组」页签 → 右上角依赖仓库': 'Go to the "Mods" tab → Dependency Index in the top right',
'进入「模组」页签,顶部切换 mods(模组)/ plugins(插件)目录': 'In the "Mods" tab, switch between mods and plugins directories at the top',
'进入「终端」页签,点右上角 + 新建会话并选择服务器': 'In the "Terminal" tab, tap + in the top right to create a session and pick a server',
'部分面板服 / 虚拟主机只提供网页面板,不提供 SSH,此时模组和终端功能不可用(入口会提示)': 'Some panel-hosted/virtual hosts offer only a web panel without SSH; mod management and terminal are unavailable then (the entry will tell you)',
'输入关键词搜索 Modrinth 上的模组/插件,可用 MC 版本、加载器筛选':
'Search Modrinth mods/plugins by keyword; filter by MC version and loader',
'进入「服务器」页 → 下载中心(或首页快捷入口)':
'Go to the "Servers" page → Download Center (or the home shortcut)',
'进入「模组」页签 → 右上角依赖仓库':
'Go to the "Mods" tab → Dependency Index in the top right',
'进入「模组」页签,顶部切换 mods(模组)/ plugins(插件)目录':
'In the "Mods" tab, switch between mods and plugins directories at the top',
'进入「终端」页签,点右上角 + 新建会话并选择服务器':
'In the "Terminal" tab, tap + in the top right to create a session and pick a server',
'部分面板服 / 虚拟主机只提供网页面板,不提供 SSH,此时模组和终端功能不可用(入口会提示)':
'Some panel-hosted/virtual hosts offer only a web panel without SSH; mod management and terminal are unavailable then (the entry will tell you)',
'阅读倒计时 {0} 秒…': 'Reading countdown {0}s…',
'默认使用 MCIM 国内镜像,无需科学上网': 'Uses the MCIM China mirror by default; no VPN needed',
'首次使用建议按「一 → 二」顺序配置,其余功能即可解锁。': 'For first use, configure sections 1 → 2 in order to unlock the remaining features.',
'和平难度': 'Peaceful',
'默认使用 MCIM 国内镜像,无需科学上网':
'Uses the MCIM China mirror by default; no VPN needed',
'清空输出': 'Clear output',
'输入命令后按回车执行': 'Type a command and press Enter',
'当前': 'Active',
'运行状态': 'Status',
'搜索 Modrinth 模组,镜像加速下载': 'Search Modrinth mods with mirror acceleration',
'通过 SSH 执行任意命令': 'Run any command over SSH',
'上传、删除、查看依赖': 'Upload, delete, inspect dependencies',
'{0} 个文件': '{0} files',
'排序': 'Sort',
// ---- ZL2 下载页 ----
'共 {0} 个结果': '{0} results',
'共 {0} 个任务': '{0} tasks',
'在上方「搜索下载」页签中选择模组即可开始': 'Pick a mod in the Search tab above to get started',
'在线公告': 'Online notice',
'在线列表': 'Online list',
'晴天': 'Clear weather',
@@ -306,6 +383,19 @@ class S {
'关闭': 'Close',
'更新失败:{0}': 'Update failed: {0}',
'未找到可下载的安装包': 'No downloadable package found',
'版本号': 'Version',
'更新时间': 'Release time',
'当前版本': 'Current version',
'更新发布页': 'Release page',
'更新内容': 'Release notes',
'更新': 'Updates',
'修复': 'Fixes',
'查看发布页': 'View release page',
'忽略': 'Later',
'本次更新暂无详细说明': 'No detailed release notes.',
'完整的更新日志': 'Full changelog',
'更新日志': 'Changelog',
'相关链接': 'Related link',
'正在下载更新': 'Downloading update',
'正在下载,请稍候…': 'Downloading, please wait…',
'立即更新': 'Update now',
@@ -320,7 +410,8 @@ class S {
'服务器控制台': 'Server Console',
'标签': 'Label',
'标签和命令都不能为空': 'Label and command cannot be empty',
'点击标签一键发送,点击右侧按钮编辑': 'Tap a tag to send instantly; tap the button on the right to edit',
'点击标签一键发送,点击右侧按钮编辑':
'Tap a tag to send instantly; tap the button on the right to edit',
'玩家管理': 'Players',
'管理快速命令': 'Manage quick commands',
'输入命令...': 'Enter command...',
@@ -379,7 +470,8 @@ class S {
'自定义 ({0})': 'Custom ({0})',
'SFTP 未连接,请先调用 connect()': 'SFTP not connected; call connect() first',
'RCON 未连接或未认证': 'RCON not connected or not authenticated',
'新增 {0} · 更新 {1} · 未变化 {2} · 共 {3} 条': 'Added {0} · Updated {1} · Unchanged {2} · {3} total',
'新增 {0} · 更新 {1} · 未变化 {2} · 共 {3} 条':
'Added {0} · Updated {1} · Unchanged {2} · {3} total',
'[警告] 连接断开,正在重连...': '[Warning] Connection lost, reconnecting...',
'[信息] 重连成功': '[Info] Reconnected',
'[错误] {0}': '[Error] {0}',
@@ -391,13 +483,16 @@ class S {
'端口不能为空': 'Port cannot be empty',
'端口范围 1-65535': 'Port range 1-65535',
'还没有添加服务器': 'No servers added yet',
'填入主机地址与 RCON 密码,即可在手机上管理': 'Enter the host and RCON password to manage it from your phone',
'填入主机地址与 RCON 密码,即可在手机上管理':
'Enter the host and RCON password to manage it from your phone',
'视频': 'Video',
'图片': 'Image',
'连接凭据已加密保存,仅存于本机': 'Credentials are encrypted and stored on this device only',
'连接凭据已加密保存,仅存于本机':
'Credentials are encrypted and stored on this device only',
'服务器日志': 'Server Logs',
'通过 SSH 查看服务器 logs 目录日志输出': 'View server logs directory output via SSH',
'请先在「服务器」页配置 SSH 连接': 'Configure an SSH connection on the Servers page first',
'请先在「服务器」页配置 SSH 连接':
'Configure an SSH connection on the Servers page first',
'选择服务器(需开启 SSH)': 'Select server (SSH required)',
'日志目录路径': 'Logs directory path',
'例如 /root/logs': 'e.g. /root/logs',
@@ -413,9 +508,20 @@ class S {
'版本、检查更新、创造者与开源许可': 'Version, updates, creators and licenses',
'我知道了': 'Got it',
'创造者': 'Creators',
'ZV Manager 是一款 Minecraft 服务器远程管理工具,本软件与 Mojang、微软无任何隶属关系。': 'ZV Manager is a remote management tool for Minecraft servers. Not affiliated with Mojang or Microsoft.',
'ZV Manager 是一款 Minecraft 服务器远程管理工具,本软件与 Mojang、微软无任何隶属关系。':
'ZV Manager is a remote management tool for Minecraft servers. Not affiliated with Mojang or Microsoft.',
'开发者 · Gitee: DriftinBlock': 'Developer · Gitee: DriftinBlock',
'协作者 · Gitee: venti1112': 'Collaborator · Gitee: venti1112',
// ---- ZL2 版式新增 ----
'在线玩家 {0} 人': '{0} players online',
'选择': 'Select',
'底部': 'Bottom',
'日志目录': 'Logs directory',
'默认按 SSH 用户推导,可手动修改': 'Derived from the SSH user; edit if needed',
'每 5 秒重新读取目录列表': 'Reload the file list every 5 seconds',
'请选择一台已配置 SSH 的服务器': 'Select a server with SSH configured',
'从 Gitee 获取最新版本': 'Fetch the latest version from Gitee',
'查看本应用使用的第三方库许可': 'View third-party licenses used by this app',
};
static String t(String zh) => en ? (_en[zh] ?? zh) : zh;
@@ -438,9 +544,13 @@ class T extends StatelessWidget {
final int? maxLines;
final TextOverflow? overflow;
const T(this.zh, {super.key, this.style, this.textAlign, this.maxLines, this.overflow});
const T(this.zh,
{super.key, this.style, this.textAlign, this.maxLines, this.overflow});
@override
Widget build(BuildContext context) =>
Text(S.t(zh), style: style, textAlign: textAlign, maxLines: maxLines, overflow: overflow);
Widget build(BuildContext context) => Text(S.t(zh),
style: style,
textAlign: textAlign,
maxLines: maxLines,
overflow: overflow);
}
+37 -11
View File
@@ -25,6 +25,28 @@ class MirrorService extends ChangeNotifier {
return builtinMirrors[_current] ?? _current;
}
/// 当前镜像的 API base(含 scheme、无尾斜杠),供请求 baseUrl 使用。
///
/// 仅替换 host,路径与查询串由调用方保持原样,避免与 queryParameters 二次拼接。
/// MCIM 现行规则:Modrinth API 为 `mod.mcimirror.top/modrinth`(带 /modrinth 前缀),
/// 请求路径 `/v2/search` 会拼成 `.../modrinth/v2/search`。
String get apiBase {
switch (_current) {
case 'official':
return 'https://api.modrinth.com';
case 'mcim':
return 'https://mod.mcimirror.top/modrinth';
case 'custom':
if (_customUrl.isEmpty) return 'https://api.modrinth.com';
final trimmed = _customUrl.endsWith('/')
? _customUrl.substring(0, _customUrl.length - 1)
: _customUrl;
return trimmed;
default:
return 'https://api.modrinth.com';
}
}
Future<void> load() async {
final prefs = await SharedPreferences.getInstance();
_current = prefs.getString(_prefKey) ?? 'mcim';
@@ -43,9 +65,10 @@ class MirrorService extends ChangeNotifier {
/// 把 Modrinth 官方域名改写为镜像域名。
///
/// 镜像规则:
/// - MCIM:api.modrinth.com → modrinth-api.mcimirror.top
/// cdn.modrinth.com → modrinth-cdn.mcimirror.top
/// 镜像规则(MCIM 官方 2026 现行规则,已核对 docs.mcimirror.top):
/// - MCIM:api.modrinth.com/v2/... → mod.mcimirror.top/modrinth/v2/...(带前缀)
/// cdn.modrinth.com/... → mod.mcimirror.top/...(仅换 host)
/// 旧的 modrinth-api.mcimirror.top / modrinth-cdn.mcimirror.top 已废弃、DNS 无法解析
/// - official:原样返回
/// - custom:以自定义 base 替换 scheme/host,保留路径与查询串
String rewrite(String url) {
@@ -62,13 +85,16 @@ class MirrorService extends ChangeNotifier {
}
return url;
}
// MCIM
final newHost = uri.host == 'api.modrinth.com'
? 'modrinth-api.mcimirror.top'
: uri.host == 'cdn.modrinth.com'
? 'modrinth-cdn.mcimirror.top'
: uri.host;
return uri.replace(host: newHost).toString();
// MCIM:API 需加 /modrinth 路径前缀,CDN 仅换 host
if (uri.host == 'api.modrinth.com') {
return uri
.replace(host: 'mod.mcimirror.top', path: '/modrinth${uri.path}')
.toString();
}
if (uri.host == 'cdn.modrinth.com') {
return uri.replace(host: 'mod.mcimirror.top').toString();
}
return url;
}
/// 测速:对镜像的 api 域名发 HEAD 请求,返回毫秒数;失败返回 -1。
@@ -78,7 +104,7 @@ class MirrorService extends ChangeNotifier {
Future<int> speedTest(String mirrorId) async {
final String probe = switch (mirrorId) {
'official' => 'https://api.modrinth.com/v2/project/sodium/version?limit=1',
'mcim' => 'https://modrinth-api.mcimirror.top/v2/project/sodium/version?limit=1',
'mcim' => 'https://mod.mcimirror.top/modrinth/v2/project/sodium/version?limit=1',
_ => _customUrl,
};
if (probe.isEmpty) return -1;
+46 -5
View File
@@ -15,8 +15,10 @@ class ModrinthApi {
));
d.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
// 镜像改写:api.modrinth.com / cdn.modrinth.com → 镜像节点
options.path = mirror.rewrite(options.uri.toString());
// 镜像改写:仅替换 base(host + 可选路径前缀),路径与查询串保持原样。
// 原实现把整串写回 options.path,因当时 baseUrl 为空、uri 无 host,
// 最终拼成 ///v2/... 报 "No host specified";且整串回写会与 queryParameters 二次拼接。
options.baseUrl = mirror.apiBase;
// Modrinth 要求标明客户端身份,否则可能被限流
options.headers['User-Agent'] = 'ZVManager/2.0 (gitee.com/driftinblock/zvmanager)';
handler.next(options);
@@ -25,6 +27,45 @@ class ModrinthApi {
return d;
}
/// 官方源 Dio(不经镜像拦截器),用于镜像连接失败时兜底重试。
Dio get _officialDio => Dio(BaseOptions(
baseUrl: 'https://api.modrinth.com',
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 30),
headers: {'User-Agent': 'ZVManager/2.0 (gitee.com/driftinblock/zvmanager)'},
));
/// 统一 GET:按当前镜像请求;若镜像出现连接层故障(DNS 失效/超时/拒连),
/// 自动回退 Modrinth 官方源重试一次。MCIM 为第三方镜像,域名与可用性可能变化,
/// 此兜底保证单点故障不会让搜索直接失败。
Future<Response> _get(String path, {Map<String, dynamic>? queryParameters}) async {
try {
return await _dio.get(path, queryParameters: queryParameters);
} on DioException catch (e) {
if (mirror.currentId == 'official' || !_isConnectionFailure(e)) rethrow;
return await _officialDio.get(path, queryParameters: queryParameters);
}
}
/// 判断是否为「连接层」故障(而非 4xx/5xx 业务响应),仅这类才值得回退。
/// 不引入 dart:io,改用字符串匹配 SocketException 关键字,保证 Web 构建也可用。
bool _isConnectionFailure(DioException e) {
switch (e.type) {
case DioExceptionType.connectionError:
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
return true;
case DioExceptionType.unknown:
final s = '${e.error} ${e.message}';
return s.contains('SocketException') ||
s.contains('Failed host lookup') ||
s.contains('No address associated');
default:
return false;
}
}
/// 搜索项目。facets 例:[["versions:1.20.1"], ["categories:fabric"], ["project_type:mod"]]
///
/// Modrinth 的 facets 是「AND 组合、组内 OR」的结构,
@@ -41,7 +82,7 @@ class ModrinthApi {
];
if (mcVersion != null && mcVersion.isNotEmpty) facets.add(['versions:$mcVersion']);
if (loader != null && loader.isNotEmpty) facets.add(['categories:$loader']);
final resp = await _dio.get('/v2/search', queryParameters: {
final resp = await _get('/v2/search', queryParameters: {
'query': query,
'limit': limit,
'facets': facets,
@@ -52,7 +93,7 @@ class ModrinthApi {
/// 获取项目最新兼容版本列表(按日期倒序)。
Future<List<ModrinthVersion>> versions(String projectId) async {
final resp = await _dio.get('/v2/project/$projectId/version');
final resp = await _get('/v2/project/$projectId/version');
final list = (resp.data as List).map((e) => ModrinthVersion.fromJson(e)).toList();
list.sort((a, b) => b.datePublished.compareTo(a.datePublished));
return list;
@@ -60,7 +101,7 @@ class ModrinthApi {
/// 项目详情(用于依赖信息)。
Future<Map<String, dynamic>> project(String idOrSlug) async {
final resp = await _dio.get('/v2/project/$idOrSlug');
final resp = await _get('/v2/project/$idOrSlug');
return Map<String, dynamic>.from(resp.data);
}
}
+6 -5
View File
@@ -79,7 +79,7 @@ class AppTheme {
centerTitle: false,
elevation: 0,
scrolledUnderElevation: 0,
backgroundColor: scheme.surface,
backgroundColor: Colors.transparent,
surfaceTintColor: Colors.transparent,
titleTextStyle: TextStyle(
fontSize: 22,
@@ -169,7 +169,8 @@ class AppTheme {
elevation: 0,
backgroundColor: isDark ? scheme.surfaceContainer : scheme.surfaceContainerLowest,
surfaceTintColor: Colors.transparent,
indicatorColor: scheme.secondaryContainer,
// ZL2 风格:选中项用主色绿 + 浅绿圆角胶囊指示器
indicatorColor: isDark ? scheme.primary.withOpacity(0.22) : scheme.primaryContainer,
indicatorShape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(16)),
),
@@ -178,15 +179,15 @@ class AppTheme {
final selected = states.contains(WidgetState.selected);
return TextStyle(
fontSize: 12,
fontWeight: selected ? FontWeight.w600 : FontWeight.w500,
color: selected ? scheme.onSurface : scheme.onSurfaceVariant,
fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
color: selected ? scheme.primary : scheme.onSurfaceVariant,
);
}),
iconTheme: WidgetStateProperty.resolveWith((states) {
final selected = states.contains(WidgetState.selected);
return IconThemeData(
size: 24,
color: selected ? scheme.onSecondaryContainer : scheme.onSurfaceVariant,
color: selected ? scheme.primary : scheme.onSurfaceVariant,
);
}),
),
+210
View File
@@ -0,0 +1,210 @@
/// 一条更新日志条目。
class ReleaseNoteItem {
final String text;
/// 是否为列表项(发布说明里以 `*`、`-` 或数字开头)。
final bool bullet;
const ReleaseNoteItem({required this.text, required this.bullet});
}
/// 一个更新日志分组,例如「更新」「修复」或发布者自定义的小标题。
class ReleaseNoteSection {
final String title;
final List<ReleaseNoteItem> items;
const ReleaseNoteSection({required this.title, required this.items});
}
/// 发布说明里提取出的链接。
class ReleaseNoteLink {
final String label;
final String url;
const ReleaseNoteLink({required this.label, required this.url});
}
/// Gitee 发布说明的轻量解析结果。
///
/// 不引入 Markdown 依赖,只处理发布说明里常见的标题、列表、粗体和链接。
class ReleaseNotes {
final List<ReleaseNoteSection> sections;
final List<ReleaseNoteLink> links;
const ReleaseNotes({required this.sections, required this.links});
/// 没有任何可展示的正文条目。
bool get isEmpty => sections.isEmpty;
factory ReleaseNotes.parse(String markdown) {
final sections = <String, ReleaseNoteSection>{};
final links = <ReleaseNoteLink>[];
final seenUrls = <String>{};
var activeTitle = '更新';
ReleaseNoteSection sectionFor(String title) {
return sections.putIfAbsent(
title,
() => ReleaseNoteSection(title: title, items: <ReleaseNoteItem>[]),
);
}
void addLink(String label, String url) {
final cleanedUrl =
url.trim().replaceFirst(RegExp(r'[.,;:!?,。;:!?*_`]+$'), '');
if (cleanedUrl.isEmpty || !seenUrls.add(cleanedUrl)) return;
final cleanedLabel =
_cleanInline(label).replaceFirst(RegExp(r'[::\s]+$'), '').trim();
links.add(
ReleaseNoteLink(
label: cleanedLabel.isEmpty ? '相关链接' : cleanedLabel,
url: cleanedUrl,
),
);
}
final normalized = markdown.replaceAll('\r\n', '\n').replaceAll('\r', '\n');
for (var rawLine in normalized.split('\n')) {
var line = rawLine.trim();
if (line.isEmpty) continue;
if (line.startsWith('```')) continue;
if (RegExp(r'^[-*_]{3,}$').hasMatch(line)) continue;
line = line.replaceFirst(RegExp(r'^>\s?'), '');
final heading = RegExp(r'^#{1,6}\s+(.*)$').firstMatch(line);
if (heading != null) {
final title = _cleanInline(heading.group(1) ?? '');
if (title.isEmpty) continue;
final lower = title.toLowerCase();
if (title.contains('更新') ||
title.contains('新增') ||
lower.contains('feature') ||
lower.contains('change')) {
activeTitle = '更新';
} else if (title.contains('修复') ||
lower.contains('fix') ||
lower.contains('bug')) {
activeTitle = '修复';
} else {
activeTitle = title;
sectionFor(title);
}
continue;
}
final bulletMatch = RegExp(r'^[*+-]\s+(.*)$').firstMatch(line) ??
RegExp(r'^\d+[.)]\s+(.*)$').firstMatch(line);
final isBullet = bulletMatch != null;
var content = bulletMatch?.group(1)?.trim() ?? line;
// 先提取 Markdown 链接,避免 URL 里的字符干扰后面的列表解析。
content = content.replaceAllMapped(
RegExp(r'\[([^\]]+)\]\((https?://[^)\s]+)\)'),
(match) {
addLink(match.group(1) ?? '', match.group(2) ?? '');
return '';
},
);
// 提取裸链接,并从正文中移除,避免日志里出现很长的 URL。
content = content.replaceAllMapped(
RegExp(r'https?://[^\s)<>]+'),
(match) {
final rawUrl = match.group(0) ?? '';
final rest = content.replaceRange(match.start, match.end, '');
addLink(_linkLabel(rest), rawUrl);
return '';
},
);
content = _cleanInline(content);
content = content.replaceFirst(RegExp(r'[\s::]+$'), '').trim();
if (content.isEmpty || _isChangelogLabel(content)) continue;
final prefixMatch = RegExp(
r'^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([^)]*\))?!?:\s*',
caseSensitive: false,
).firstMatch(content);
String? prefix;
if (prefixMatch != null) {
prefix = (prefixMatch.group(1) ?? '').toLowerCase();
content = content.substring(prefixMatch.end).trim();
}
if (content.isEmpty) continue;
final hasPrefix = prefix != null;
final isFix = prefix == 'fix' ||
prefix == 'revert' ||
(!hasPrefix && content.startsWith('修复'));
final String title;
if (hasPrefix) {
title = isFix ? '修复' : '更新';
} else if (activeTitle == '修复') {
title = '修复';
} else if (activeTitle == '更新') {
title = isFix ? '修复' : '更新';
} else {
title = activeTitle;
}
sectionFor(title).items.add(
ReleaseNoteItem(text: content, bullet: isBullet),
);
}
// 固定先展示「更新」和「修复」,再展示发布者自定义的小标题。
final ordered = <ReleaseNoteSection>[];
for (final title in const ['更新', '修复']) {
final section = sections[title];
if (section != null && section.items.isNotEmpty) ordered.add(section);
}
for (final section in sections.values) {
if (section.title != '更新' &&
section.title != '修复' &&
section.items.isNotEmpty) {
ordered.add(section);
}
}
return ReleaseNotes(sections: ordered, links: links);
}
}
String _cleanInline(String text) {
var value = text;
value = value.replaceAllMapped(
RegExp(r'!\[([^\]]*)\]\([^)]*\)'),
(match) => match.group(1) ?? '',
);
value = value.replaceAllMapped(
RegExp(r'\[([^\]]+)\]\([^)]*\)'),
(match) => match.group(1) ?? '',
);
value = value.replaceAll(RegExp(r'<[^>]*>'), '');
value = value.replaceAll('**', '').replaceAll('__', '').replaceAll('`', '');
value = value.replaceFirst(RegExp(r'^\s*>\s?'), '');
return value.trim();
}
String _linkLabel(String text) {
final label = _cleanInline(text).replaceFirst(RegExp(r'[::\s]+$'), '').trim();
if (label.isEmpty) return '相关链接';
if (label.contains('更新日志') ||
label.contains('完整的更新') ||
label.toLowerCase().contains('changelog')) {
return '完整的更新日志';
}
return label.length > 32 ? '${label.substring(0, 32)}…' : label;
}
bool _isChangelogLabel(String text) {
final label = text.replaceAll(RegExp(r'[::\s]+'), '').toLowerCase();
return label == '完整的更新日志' ||
label == '完整更新日志' ||
label == '更新日志' ||
label == 'changelog' ||
label == 'releasenotes' ||
label == 'fullchangelog';
}
+24
View File
@@ -0,0 +1,24 @@
/// 软件更新信息,由 Gitee 发布接口解析而来。
class UpdateInfo {
final String latestVersion;
final String downloadUrl;
final String apkName;
/// Gitee 发布说明(Markdown 原文)。
final String releaseNotes;
/// Gitee 发布接口返回的发布时间。
final DateTime? releasedAt;
/// Gitee 发布页地址。
final String releasePageUrl;
const UpdateInfo({
required this.latestVersion,
required this.downloadUrl,
required this.apkName,
this.releaseNotes = '',
this.releasedAt,
this.releasePageUrl = '',
});
}
+96 -36
View File
@@ -1,26 +1,23 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/l10n/strings.dart';
/// 软件更新信息,由 Gitee 发布接口的 tag_name 与 assets 解析而来
class UpdateInfo {
final String latestVersion;
final String downloadUrl;
final String apkName;
const UpdateInfo({
required this.latestVersion,
required this.downloadUrl,
required this.apkName,
});
}
import '../l10n/strings.dart';
import '../widgets/update_dialog.dart';
import 'update_info.dart';
export 'update_info.dart';
/// 更新检查与安装服务:负责从 Gitee 拉取发布信息、下载并调起系统安装器。
class UpdateService {
const UpdateService._();
/// Gitee 仓库地址
static const _repoUrl = 'https://gitee.com/driftinblock/zvmanager';
/// Gitee 仓库最新发布信息地址
static const _updateInfoUrl =
'https://gitee.com/api/v5/repos/driftinblock/zvmanager/releases/latest';
@@ -59,33 +56,89 @@ class UpdateService {
final json = jsonDecode(body) as Map<String, dynamic>;
// Gitee 发布接口的 tag_name 形如 "v1.3.0",去掉开头的 "v" 用于版本号对比
final tag = json['tag_name'] as String? ?? '';
final latestVersion = tag.startsWith('v') ? tag.substring(1) : tag;
final latestVersion =
tag.startsWith('v') || tag.startsWith('V') ? tag.substring(1) : tag;
if (latestVersion.isEmpty) return null;
// 从 assets 中筛选 APK 安装包,取其直链与文件名
String downloadUrl = '';
String apkName = '';
final assets = json['assets'] as List<dynamic>? ?? [];
for (final item in assets) {
final name = (item as Map<String, dynamic>)['name'] as String? ?? '';
final asset = item as Map<String, dynamic>;
final name = asset['name'] as String? ?? '';
if (name.endsWith('.apk')) {
downloadUrl = (item['browser_download_url'] as String? ??
item['download_url'] as String? ??
downloadUrl = (asset['browser_download_url'] as String? ??
asset['download_url'] as String? ??
'');
apkName = name;
break;
}
}
final htmlUrl = json['html_url'] as String? ?? '';
final releasePageUrl = htmlUrl.isNotEmpty
? htmlUrl
: (tag.isEmpty
? '$_repoUrl/releases'
: '$_repoUrl/releases/tag/${Uri.encodeComponent(tag)}');
return UpdateInfo(
latestVersion: latestVersion,
downloadUrl: downloadUrl,
apkName: apkName,
releaseNotes: json['body'] as String? ?? '',
releasedAt: DateTime.tryParse(json['created_at'] as String? ?? ''),
releasePageUrl: releasePageUrl,
);
} finally {
client.close();
}
}
/// 判断 [latest] 是否比 [current] 新。只有新版本更高时才返回 true,
/// 避免当前版本高于 Gitee 发布版本时误提示更新并引导降级。
static bool isNewerVersion(String latest, String current) {
if (latest.trim().isEmpty) return false;
final latestParts = _parseVersion(latest);
final currentParts = _parseVersion(current);
if (latestParts == null || currentParts == null) {
return latest.trim() != current.trim();
}
final length = latestParts.length > currentParts.length
? latestParts.length
: currentParts.length;
for (var i = 0; i < length; i++) {
final latestPart = i < latestParts.length ? latestParts[i] : 0;
final currentPart = i < currentParts.length ? currentParts[i] : 0;
if (latestPart != currentPart) return latestPart > currentPart;
}
return false;
}
/// 把 "v2.0.3+16" 解析成 [2, 0, 3],忽略 v 前缀、后缀和构建号。
static List<int>? _parseVersion(String version) {
var value = version.trim();
if (value.isEmpty) return null;
if (value.startsWith('v') || value.startsWith('V')) {
value = value.substring(1);
}
final suffixIndex = value.indexOf(RegExp(r'[-+]'));
if (suffixIndex >= 0) value = value.substring(0, suffixIndex);
final parts = value.split('.');
final numbers = <int>[];
for (final part in parts) {
final match = RegExp(r'^\d+').firstMatch(part);
if (match == null) return null;
numbers.add(int.parse(match.group(0)!));
}
return numbers.isEmpty ? null : numbers;
}
/// 展示版本对比结果弹窗;`hasUpdate` 为 false 时若无更新且 `silentOnNoUpdate` 为 true 则直接静默返回。
static void showUpdateDialog(
BuildContext context,
@@ -93,28 +146,33 @@ class UpdateService {
String currentVersion, {
bool silentOnNoUpdate = false,
}) {
final hasUpdate = info.latestVersion != currentVersion;
final hasUpdate = isNewerVersion(info.latestVersion, currentVersion);
if (!hasUpdate && silentOnNoUpdate) return;
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(hasUpdate ? S.t('发现新版本') : S.t('已是最新')),
content: Text(hasUpdate
? '最新版本: ${info.latestVersion}\n当前版本: $currentVersion'
: S.f('当前版本 {0} 已是最新', [currentVersion])),
actions: [
TextButton(
onPressed: () => Navigator.pop(context), child: T('关闭')),
if (hasUpdate)
FilledButton(
onPressed: () {
Navigator.pop(context);
downloadAndInstall(context, info);
},
child: T('立即更新'),
if (!hasUpdate) {
showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(S.t('已是最新')),
content: Text(S.f('当前版本 {0} 已是最新', [currentVersion])),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: T('关闭'),
),
],
],
),
);
return;
}
showDialog<void>(
context: context,
builder: (_) => UpdateDialog(
info: info,
currentVersion: currentVersion,
onUpdate: () => downloadAndInstall(context, info),
onOpenUrl: openUrl,
),
);
}
@@ -171,7 +229,9 @@ class UpdateService {
CircularProgressIndicator(value: value),
const SizedBox(height: 16),
Text(
percent == null ? S.t('正在下载安装包…') : S.f('下载中:{0}%', [percent]),
percent == null
? S.t('正在下载安装包…')
: S.f('下载中:{0}%', [percent]),
style: Theme.of(context).textTheme.bodyMedium,
),
],
+2 -1
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../../core/l10n/strings.dart';
import '../widgets/z_widgets.dart';
/// 统一的「需要先选服务器 / 未配置」引导空状态页。
/// 自带 AppBar 标题栏,避免页面看起来空白、引导文字无处安放。
@@ -24,7 +25,7 @@ class EmptyStatePage extends StatelessWidget {
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: T(title)),
appBar: ZAppBar(title: T(title)),
body: Center(
child: Padding(
padding: const EdgeInsets.all(32),
+306
View File
@@ -0,0 +1,306 @@
import 'package:flutter/material.dart';
import '../l10n/strings.dart';
import '../utils/release_notes.dart';
import '../utils/update_info.dart';
/// 检查更新详情弹窗:版本号、发布时间、发布页和解析后的更新日志。
class UpdateDialog extends StatelessWidget {
final UpdateInfo info;
final String currentVersion;
final VoidCallback onUpdate;
final ValueChanged<String> onOpenUrl;
const UpdateDialog({
super.key,
required this.info,
required this.currentVersion,
required this.onUpdate,
required this.onOpenUrl,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final notes = ReleaseNotes.parse(info.releaseNotes);
final maxHeight = MediaQuery.sizeOf(context).height * 0.82;
return Dialog(
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 560, maxHeight: maxHeight),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(24, 20, 24, 4),
child: Text(
S.t('发现新版本'),
textAlign: TextAlign.center,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
Flexible(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(24, 12, 24, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_InfoRow(label: S.t('版本号'), value: info.latestVersion),
const SizedBox(height: 7),
if (info.releasedAt != null) ...[
_InfoRow(
label: S.t('更新时间'),
value: _formatDateTime(info.releasedAt!),
),
const SizedBox(height: 7),
],
_InfoRow(
label: S.t('当前版本'),
value: currentVersion,
),
if (info.releasePageUrl.isNotEmpty) ...[
const SizedBox(height: 10),
_InfoRow(
label: S.t('更新发布页'),
value: 'Gitee',
link: true,
onTap: () => onOpenUrl(info.releasePageUrl),
),
],
const SizedBox(height: 16),
Divider(height: 1, color: scheme.outlineVariant),
const SizedBox(height: 16),
Text(
S.t('更新内容'),
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
if (notes.isEmpty)
Text(
S.t('本次更新暂无详细说明'),
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
)
else
..._buildSections(context, notes.sections),
if (notes.links.isNotEmpty) ...[
const SizedBox(height: 12),
...notes.links.map(
(link) => _NoteLink(
label: link.label,
onTap: () => onOpenUrl(link.url),
),
),
],
],
),
),
),
Divider(height: 1, color: scheme.outlineVariant),
Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 12),
child: Row(
children: [
if (info.releasePageUrl.isNotEmpty)
TextButton(
onPressed: () => onOpenUrl(info.releasePageUrl),
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
),
child: T('查看发布页'),
),
const Spacer(),
TextButton(
onPressed: () => Navigator.of(context).pop(),
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
),
child: T('忽略'),
),
const SizedBox(width: 4),
FilledButton(
onPressed: () {
Navigator.of(context).pop();
onUpdate();
},
child: T('立即更新'),
),
],
),
),
],
),
),
);
}
List<Widget> _buildSections(
BuildContext context,
List<ReleaseNoteSection> sections,
) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final widgets = <Widget>[];
for (var i = 0; i < sections.length; i++) {
final section = sections[i];
if (i > 0) widgets.add(const SizedBox(height: 14));
widgets.add(
Text(
S.t(section.title),
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
color: scheme.primary,
),
),
);
for (final item in section.items) {
widgets.add(const SizedBox(height: 6));
if (item.bullet) {
widgets.add(
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 1),
child: Text(
'•',
style: TextStyle(
fontSize: 14,
color: scheme.primary,
height: 1.55,
),
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
item.text,
style: theme.textTheme.bodyMedium?.copyWith(height: 1.55),
),
),
],
),
);
} else {
widgets.add(
Text(
item.text,
style: theme.textTheme.bodyMedium?.copyWith(height: 1.55),
),
);
}
}
}
return widgets;
}
}
/// 「版本号:xxx」形式的单行信息。
class _InfoRow extends StatelessWidget {
final String label;
final String value;
final bool link;
final VoidCallback? onTap;
const _InfoRow({
required this.label,
required this.value,
this.link = false,
this.onTap,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final separator = S.en ? ': ' : ':';
final valueStyle = TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w600,
color: link ? scheme.primary : scheme.onSurface,
);
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'$label$separator',
style: TextStyle(fontSize: 13.5, color: scheme.onSurfaceVariant),
),
Expanded(
child: link
? InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(6),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 1),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(value, style: valueStyle),
const SizedBox(width: 2),
Icon(
Icons.open_in_new,
size: 14,
color: scheme.primary,
),
],
),
),
)
: Text(value, style: valueStyle),
),
],
);
}
}
/// 发布说明底部提取出的可点击链接。
class _NoteLink extends StatelessWidget {
final String label;
final VoidCallback onTap;
const _NoteLink({required this.label, required this.onTap});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
onPressed: onTap,
icon: Icon(Icons.link, size: 17, color: scheme.primary),
label: Text(S.t(label)),
style: TextButton.styleFrom(
foregroundColor: scheme.primary,
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
minimumSize: const Size(0, 36),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
);
}
}
String _formatDateTime(DateTime value) {
final local = value.toLocal();
String two(int number) => number.toString().padLeft(2, '0');
if (S.en) {
return '${local.year}-${two(local.month)}-${two(local.day)} '
'${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
}
return '${local.year}年${two(local.month)}月${two(local.day)}日 '
'${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
}
+559
View File
@@ -0,0 +1,559 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../l10n/strings.dart';
import '../../providers/wallpaper_provider.dart';
/// ZL2 风格的通用视觉组件集合。
///
/// 设计要点(与 ZalithLauncher 保持一致的观感):
/// - **分组圆角面板**:一组相关设置包在 18px 圆角容器里,行与行之间用极细
/// 分隔线,而不是每行一张 Card。这样竖屏下信息密度更高、层级更清晰。
/// - **两行行样式**:左侧「粗标题 + 小字灰色说明」,右侧「当前值 / 控件 / 箭头」。
/// 说明文字用较小字号 + 降低不透明度,形成明确的视觉主次。
/// - **圆形勾选钮**:开关不用 Material Switch,而用 46px 圆形按钮,
/// 选中时绿底白勾(ZL2 的标志性元素)。
///
/// 所有组件都接受 [hasWallpaper],在有自定义壁纸时自动切换为半透明深色
/// 浮层 + 白色文字,保证文字在任意背景下都能读清。
/// ZL2 主色:勾选钮/选中态统一使用的绿色。
const Color kZAccent = Color(0xFF4CAF50);
/// ZL2 圆角:分组面板与内部行的圆角。
const double kZRadius = 18.0;
/// 分组面板的着色与文字色工具。
///
/// 把「有壁纸 / 无壁纸」两套配色集中在这里,避免每个页面各写一遍
/// `Colors.black.withOpacity(0.45)` 之类的魔数。
class ZStyle {
final bool hasWallpaper;
final ColorScheme scheme;
const ZStyle({required this.hasWallpaper, required this.scheme});
/// 从 BuildContext 推导(需要外部传入 hasWallpaper)。
factory ZStyle.of(BuildContext context, {required bool hasWallpaper}) =>
ZStyle(hasWallpaper: hasWallpaper, scheme: Theme.of(context).colorScheme);
/// 面板底色:有壁纸时半透明黑浮层,否则用主题的低层容器色。
Color get panelColor =>
hasWallpaper ? Colors.black.withOpacity(0.45) : scheme.surfaceContainerLow;
/// 主文字色。
Color get titleColor => hasWallpaper ? Colors.white : scheme.onSurface;
/// 次要说明文字色。
Color get subColor =>
hasWallpaper ? Colors.white.withOpacity(0.62) : scheme.onSurfaceVariant;
/// 分隔线色。
Color get dividerColor =>
hasWallpaper ? Colors.white.withOpacity(0.10) : scheme.outlineVariant;
/// 面板描边色(浅色主题下几乎不可见,仅用于在深色壁纸上勾出边界)。
Color get borderColor => Colors.white.withOpacity(0.08);
}
/// 分组面板:圆角容器 + 子行纵向排列。
///
/// 用法:把若干 [ZRow] 之间用 [ZDivider] 隔开后放进 children。
class ZPanel extends StatelessWidget {
final List<Widget> children;
final ZStyle style;
const ZPanel({super.key, required this.style, required this.children});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: style.panelColor,
borderRadius: BorderRadius.circular(kZRadius),
border: Border.all(color: style.borderColor, width: 1),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
}
}
/// 面板内的行分隔线(左右各留 16 的缩进)。
class ZDivider extends StatelessWidget {
final ZStyle style;
const ZDivider({super.key, required this.style});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Divider(height: 1, thickness: 1, color: style.dividerColor),
);
}
}
/// 两行式设置行:粗标题 + 灰色说明 + 右侧值/控件/箭头。
///
/// - [onTap] 为空时整行不可点击(纯展示行),也不显示右侧箭头;
/// - [trailing] 与 [value] 可同时存在;都没有且 [onTap] 不为空时显示 chevron。
/// - [leading] 可选,用于在标题左侧放一个小图标(如日志文件行)。
class ZRow extends StatelessWidget {
final String title;
final String? subtitle;
final ZStyle style;
final Widget? leading;
final Widget? trailing;
final String? value;
final VoidCallback? onTap;
/// 标题用主题色的强调样式(如危险操作变红)。
final Color? titleOverride;
const ZRow({
super.key,
required this.title,
required this.style,
this.subtitle,
this.leading,
this.trailing,
this.value,
this.onTap,
this.titleOverride,
});
@override
Widget build(BuildContext context) {
final showChevron = trailing == null && onTap != null;
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(kZRadius),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 12, 14),
child: Row(
children: [
if (leading != null) ...[
leading!,
const SizedBox(width: 12),
],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
S.t(title),
style: TextStyle(
fontSize: 15.5,
fontWeight: FontWeight.w700,
color: titleOverride ?? style.titleColor,
),
),
if (subtitle != null && subtitle!.isNotEmpty) ...[
const SizedBox(height: 3),
Text(
S.t(subtitle!),
style: TextStyle(
fontSize: 12.5,
height: 1.35,
color: style.subColor,
),
),
],
],
),
),
if (value != null) ...[
const SizedBox(width: 8),
Flexible(
child: Text(
value!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right,
style: TextStyle(fontSize: 13, color: style.subColor),
),
),
],
if (trailing != null) ...[
const SizedBox(width: 10),
trailing!,
] else if (showChevron) ...[
const SizedBox(width: 4),
Icon(Icons.chevron_right, size: 20, color: style.subColor),
],
],
),
),
);
}
}
/// ZL2 式圆形勾选开关:选中为绿底白勾,未选中为描边空心圆。
class ZToggle extends StatelessWidget {
final bool value;
final ValueChanged<bool> onChanged;
/// 直径,设置页用 46,列表行内可用 40。
final double size;
/// 未选中时描边颜色(有壁纸时传白色系)。
final Color? borderColor;
const ZToggle({
super.key,
required this.value,
required this.onChanged,
this.size = 46,
this.borderColor,
});
@override
Widget build(BuildContext context) {
final dim = borderColor ?? Colors.white54;
return GestureDetector(
onTap: () => onChanged(!value),
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: size,
height: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: value ? kZAccent : Colors.transparent,
border: Border.all(color: value ? kZAccent : dim, width: 2),
),
child: value
? Icon(Icons.check, size: size * 0.52, color: Colors.white)
: const SizedBox.shrink(),
),
);
}
}
/// 圆形选择钮组:一组互斥选项,选中项显示绿底白勾,未选中显示图标。
///
/// 用于「亮色 / 暗色 / 跟随系统」这类三选一,也可复用到镜像线路等单选场景。
class ZSegmentedCircles<T> extends StatelessWidget {
final List<ZCircleOption<T>> options;
final T value;
final ValueChanged<T> onChanged;
final Color onSurface;
final double size;
const ZSegmentedCircles({
super.key,
required this.options,
required this.value,
required this.onChanged,
required this.onSurface,
this.size = 38,
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
for (final o in options)
GestureDetector(
onTap: () => onChanged(o.value),
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: size,
height: size,
margin: const EdgeInsets.only(left: 6),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: value == o.value ? kZAccent : Colors.transparent,
border: Border.all(
color: value == o.value
? kZAccent
: onSurface.withOpacity(0.35),
width: 2,
),
),
child: Icon(
value == o.value ? Icons.check : o.icon,
size: size * 0.53,
color: value == o.value
? Colors.white
: onSurface.withOpacity(0.7),
),
),
),
],
);
}
}
/// [ZSegmentedCircles] 的单个选项描述。
class ZCircleOption<T> {
final T value;
final IconData icon;
const ZCircleOption({required this.value, required this.icon});
}
/// 小块状态胶囊(在线/离线、下载状态等),比 Chip 更紧凑。
class ZBadge extends StatelessWidget {
final String label;
final Color color;
final bool outlined;
const ZBadge({
super.key,
required this.label,
required this.color,
this.outlined = true,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
decoration: BoxDecoration(
color: color.withOpacity(0.13),
borderRadius: BorderRadius.circular(20),
border: outlined ? Border.all(color: color.withOpacity(0.28)) : null,
),
child: Text(
label,
style: TextStyle(
fontSize: 11.5,
height: 1.3,
fontWeight: FontWeight.w600,
color: color,
),
),
);
}
}
/// ZL2 风格的弹层/列表行:左侧彩色图标块 + 粗标题 + 可选说明 + 右侧控件/箭头。
///
/// 用于替换旧式 [ListTile](底部弹层、对话框、详情页头部、依赖列表等):
/// - [icon] + [iconColor] 决定左侧圆角图标块(默认绿色,危险操作用红色);
/// - [subtitleMono] 让说明文字用等宽字体(如命令、文件名);
/// - 有 [onTap] 且无 [trailing] 时显示右侧 chevron;[danger] 让标题与图标变红。
class ZSheetRow extends StatelessWidget {
final IconData icon;
final Color? iconColor;
final String title;
final String? subtitle;
final bool subtitleMono;
final Widget? trailing;
final VoidCallback? onTap;
final bool danger;
const ZSheetRow({
super.key,
required this.icon,
this.iconColor,
required this.title,
this.subtitle,
this.subtitleMono = false,
this.trailing,
this.onTap,
this.danger = false,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final color = danger ? Colors.red : (iconColor ?? kZAccent);
final showChevron = trailing == null && onTap != null;
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11),
child: Row(
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: color.withOpacity(0.13),
borderRadius: BorderRadius.circular(11),
),
child: Icon(icon, size: 20, color: color),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
S.t(title),
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: danger ? Colors.red : scheme.onSurface,
),
),
if (subtitle != null && subtitle!.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
S.t(subtitle!),
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5,
height: 1.35,
fontFamily: subtitleMono ? 'monospace' : null,
color: scheme.onSurfaceVariant,
),
),
],
],
),
),
if (trailing != null) ...[
const SizedBox(width: 8),
trailing!,
] else if (showChevron) ...[
const SizedBox(width: 4),
Icon(Icons.chevron_right, size: 20, color: scheme.onSurfaceVariant),
],
],
),
),
);
}
}
/// ZL2 风格的顶部搜索框(圆角填充、无边框)。
class ZSearchField extends StatelessWidget {
final TextEditingController controller;
final String hint;
final ValueChanged<String>? onSubmitted;
final ValueChanged<String>? onChanged;
final Widget? trailing;
const ZSearchField({
super.key,
required this.controller,
required this.hint,
this.onSubmitted,
this.onChanged,
this.trailing,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Container(
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(14),
),
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Row(
children: [
Icon(Icons.search, size: 20, color: scheme.onSurfaceVariant),
const SizedBox(width: 10),
Expanded(
child: TextField(
controller: controller,
onSubmitted: onSubmitted,
onChanged: onChanged,
decoration: InputDecoration(
hintText: S.t(hint),
border: InputBorder.none,
isDense: true,
contentPadding: const EdgeInsets.symmetric(vertical: 13),
),
),
),
if (trailing != null) trailing!,
],
),
);
}
}
/// ZL2 风格的沉浸式 AppBar。
///
/// 全局 [appBarTheme] 已把底色设为透明,这里再统一处理「前景色」与「状态栏」,
/// 避免两类问题:
/// 1. 有壁纸时顶栏文字/图标仍是深色 → 看不清;
/// 2. 切页时顶栏在「白不透明 ↔ 透明」之间跳变 → 视觉闪烁。
///
/// 有自定义壁纸时:标题/图标转白、状态栏图标转浅色;无壁纸时跟随主题。
/// 接受与 [AppBar] 同名的常用参数,可直接替换页面里的 `AppBar(`,无需改动其余代码。
class ZAppBar extends StatelessWidget implements PreferredSizeWidget {
final Widget? title;
final String? subtitle;
final List<Widget>? actions;
final PreferredSizeWidget? bottom;
final Widget? leading;
final bool automaticallyImplyLeading;
final Color? backgroundColor;
final Color? foregroundColor;
final SystemUiOverlayStyle? systemOverlayStyle;
final double? elevation;
final double? scrolledUnderElevation;
const ZAppBar({
super.key,
this.title,
this.subtitle,
this.actions,
this.bottom,
this.leading,
this.automaticallyImplyLeading = true,
this.backgroundColor,
this.foregroundColor,
this.systemOverlayStyle,
this.elevation,
this.scrolledUnderElevation,
});
@override
Size get preferredSize =>
Size.fromHeight(kToolbarHeight + (bottom?.preferredSize.height ?? 0));
@override
Widget build(BuildContext context) {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final titleWidget = (subtitle == null || subtitle!.isEmpty)
? title
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (title != null) title!,
const SizedBox(height: 2),
Text(
subtitle!,
style: TextStyle(
fontSize: 12,
height: 1.2,
color: hasWallpaper
? Colors.white.withOpacity(0.72)
: Theme.of(context).hintColor,
),
),
],
);
return AppBar(
leading: leading,
automaticallyImplyLeading: automaticallyImplyLeading,
title: titleWidget,
actions: actions,
bottom: bottom,
elevation: elevation ?? 0,
scrolledUnderElevation: scrolledUnderElevation ?? 0,
backgroundColor: backgroundColor ?? (hasWallpaper ? Colors.transparent : null),
foregroundColor: foregroundColor ?? (hasWallpaper ? Colors.white : null),
systemOverlayStyle: systemOverlayStyle ??
(hasWallpaper
? const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.light,
statusBarBrightness: Brightness.dark,
)
: null),
);
}
}
+144 -68
View File
@@ -3,6 +3,9 @@ import 'package:flutter/services.dart';
import '../../core/utils/command_preset_service.dart';
import '../../core/utils/rcon_client.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/wallpaper_provider.dart';
import 'package:provider/provider.dart';
/// 控制台页:命令输入 + 输出回显 + 命令历史 + Tab 补全 + 快捷指令。
///
@@ -170,38 +173,74 @@ class _ConsolePageState extends State<ConsolePage> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
return Scaffold(
appBar: AppBar(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
title: T('服务器控制台'),
actions: const [],
backgroundColor: hasWallpaper ? Colors.transparent : null,
actions: [
IconButton(
icon: const Icon(Icons.delete_sweep_outlined),
tooltip: S.t('清空输出'),
onPressed: () => setState(_outputLines.clear),
),
],
),
body: Column(
children: [
// ---------- 输出区 ----------
Expanded(
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
color: theme.colorScheme.surfaceContainerHighest.withOpacity(0.3),
child: ListView.builder(
controller: _scrollController,
itemCount: _outputLines.length,
itemBuilder: (_, i) {
final line = _outputLines[i];
return SelectableText(
line.text,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 13,
color: line.isError
? theme.colorScheme.error
: line.isCommand
? theme.colorScheme.primary
// 按日志级别前缀着色:WARN 黄 / ERROR 红 / INFO 绿
: _logLevelColor(line.text) ?? theme.colorScheme.onSurface,
),
);
},
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh.withOpacity(0.55),
borderRadius: BorderRadius.circular(kZRadius),
),
padding: const EdgeInsets.fromLTRB(14, 12, 10, 12),
child: _outputLines.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.terminal_rounded,
size: 32, color: scheme.onSurfaceVariant),
const SizedBox(height: 10),
Text(
S.t('输入命令后按回车执行'),
style: TextStyle(
fontSize: 12.5,
color: scheme.onSurfaceVariant),
),
],
),
)
: ListView.builder(
controller: _scrollController,
itemCount: _outputLines.length,
itemBuilder: (_, i) {
final line = _outputLines[i];
return SelectableText(
line.text,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 13,
height: 1.45,
color: line.isError
? scheme.error
: line.isCommand
? scheme.primary
// 按日志级别前缀着色:WARN 黄 / ERROR 红 / INFO 绿
: _logLevelColor(line.text) ??
scheme.onSurface,
),
);
},
),
),
),
),
@@ -210,39 +249,66 @@ class _ConsolePageState extends State<ConsolePage> {
onSend: _sendCommand,
onManage: _managePresets,
),
// ---------- 输入区 ----------
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(
children: [
Expanded(
child: KeyboardListener(
focusNode: FocusNode(),
onKeyEvent: (event) {
if (event is KeyDownEvent) {
if (event.logicalKey == LogicalKeyboardKey.arrowUp) _onHistoryNavigate(true);
if (event.logicalKey == LogicalKeyboardKey.arrowDown) _onHistoryNavigate(false);
if (event.logicalKey == LogicalKeyboardKey.tab) _onTabPressed();
}
},
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: S.t('输入命令...'),
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
child: Container(
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.only(left: 14, right: 6),
child: Row(
children: [
Icon(Icons.chevron_right_rounded,
size: 18, color: scheme.primary),
const SizedBox(width: 4),
Expanded(
child: KeyboardListener(
focusNode: FocusNode(),
onKeyEvent: (event) {
if (event is KeyDownEvent) {
if (event.logicalKey == LogicalKeyboardKey.arrowUp) _onHistoryNavigate(true);
if (event.logicalKey == LogicalKeyboardKey.arrowDown) _onHistoryNavigate(false);
if (event.logicalKey == LogicalKeyboardKey.tab) _onTabPressed();
}
},
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: S.t('输入命令...'),
hintStyle: TextStyle(
fontSize: 13, color: scheme.onSurfaceVariant),
border: InputBorder.none,
isDense: true,
contentPadding:
const EdgeInsets.symmetric(vertical: 14),
),
style: const TextStyle(
fontFamily: 'monospace', fontSize: 13.5),
onSubmitted: (_) => _executeCommand(),
),
style: const TextStyle(fontFamily: 'monospace', fontSize: 14),
onSubmitted: (_) => _executeCommand(),
),
),
),
const SizedBox(width: 8),
FilledButton.icon(
onPressed: _executeCommand,
icon: const Icon(Icons.send_rounded, size: 18),
label: T('发送'),
),
],
const SizedBox(width: 4),
// 圆形发送钮,与 ZL2 的圆形控件语言一致
GestureDetector(
onTap: _executeCommand,
child: Container(
width: 38,
height: 38,
margin: const EdgeInsets.symmetric(vertical: 6),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: kZAccent,
),
child: const Icon(Icons.arrow_upward_rounded,
size: 20, color: Colors.white),
),
),
],
),
),
),
),
@@ -302,12 +368,26 @@ class _PresetBar extends StatelessWidget {
separatorBuilder: (_, __) => const SizedBox(width: 8),
itemBuilder: (context, i) {
final preset = presets[i];
return ActionChip(
label: Text(preset.label),
labelStyle: TextStyle(fontSize: 13, color: theme.colorScheme.onSecondaryContainer),
visualDensity: VisualDensity.compact,
backgroundColor: theme.colorScheme.secondaryContainer.withOpacity(0.5),
onPressed: () => onSend(preset.command),
return Center(
child: GestureDetector(
onTap: () => onSend(preset.command),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 13, vertical: 7),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
),
child: Text(
preset.label,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurface,
),
),
),
),
);
},
),
@@ -379,15 +459,11 @@ class _PresetManageSheetState extends State<_PresetManageSheet> {
itemCount: _presets.length,
itemBuilder: (context, i) {
final preset = _presets[i];
return ListTile(
leading: const Icon(Icons.bolt_outlined),
title: Text(preset.label),
subtitle: Text(
preset.command,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
),
return ZSheetRow(
icon: Icons.bolt_outlined,
title: preset.label,
subtitle: preset.command,
subtitleMono: true,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
+359 -230
View File
@@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/wallpaper_provider.dart';
import '../../app.dart' show navigatorKey;
import '../../core/theme/app_theme.dart';
import '../../providers/rcon_provider.dart';
import '../../providers/server_provider.dart';
import '../server_list/server_form_dialog.dart';
@@ -12,6 +11,7 @@ import '../mod_manager/mod_list_page.dart';
import '../terminal/terminal_page.dart';
import 'server_picker_bar.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 服务器 Dashboard:卡片式布局展示选中服务器的
/// 在线状态 / 延迟 / 在线人数 / TPS / 磁盘(后续 Shell 采集)+ 快捷入口(M4)。
@@ -158,11 +158,13 @@ class _DashboardPageState extends State<DashboardPage> {
final selected = holder.server ?? (servers.isNotEmpty ? servers.first : null);
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final status = selected != null ? _status[selected.id] : null;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: AppBar(
appBar: ZAppBar(
title: const Text('ZV Manager'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
@@ -176,261 +178,388 @@ class _DashboardPageState extends State<DashboardPage> {
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _addServer,
tooltip: S.t('添加服务器'),
child: const Icon(Icons.add),
),
floatingActionButton: servers.isEmpty
? null
: FloatingActionButton(
onPressed: _addServer,
tooltip: S.t('添加服务器'),
child: const Icon(Icons.add),
),
body: servers.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
? _EmptyDashboard(onAdd: _addServer, style: st)
: RefreshIndicator(
onRefresh: _refreshAll,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 6, 16, 96),
children: [
T('还没有服务器,点击下方按钮添加吧'),
// ---------- 当前服务器 ----------
if (selected != null)
_CurrentServerPanel(
server: selected,
status: status,
servers: servers,
style: st,
onSelect: (s) {
holder.select(s);
setState(() {});
},
),
const SizedBox(height: 16),
FilledButton.icon(
icon: const Icon(Icons.add),
label: T('添加服务器'),
onPressed: _addServer,
_label(S.t('运行状态'), st),
GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
childAspectRatio: 1.95,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: [
_statusTile(
style: st,
icon: status?.online == true
? Icons.wifi_rounded
: Icons.wifi_off_rounded,
color: status?.online == true
? kZAccent
: const Color(0xFFEF5350),
label: status?.online == true ? '在线' : '离线',
sub: status == null ? '—' : '${status.latencyMs}ms',
),
_statusTile(
style: st,
icon: Icons.people_alt_rounded,
color: const Color(0xFF42A5F5),
label: S.t('在线人数'),
sub: '${status?.playerCount ?? 0}',
),
_statusTile(
style: st,
icon: Icons.speed_rounded,
color: const Color(0xFFFFA726),
label: 'TPS',
sub: status?.tps?.toStringAsFixed(1) ?? '—',
),
_statusTile(
style: st,
icon: Icons.storage_rounded,
color: const Color(0xFFAB47BC),
label: S.t('磁盘'),
sub: S.t('需 SSH 终端'),
),
],
),
const SizedBox(height: 20),
_label(S.t('服务器'), st),
ZPanel(style: st, children: [
for (var i = 0; i < servers.length; i++) ...[
if (i > 0) ZDivider(style: st),
_serverRow(servers[i], selected, st),
],
]),
const SizedBox(height: 20),
_label(S.t('快捷入口'), st),
ZPanel(style: st, children: [
ZRow(
title: '下载中心',
subtitle: '搜索 Modrinth 模组,镜像加速下载',
style: st,
leading: _entryIcon(Icons.download_rounded,
const Color(0xFF42A5F5)),
onTap: () => Navigator.push(context,
MaterialPageRoute(builder: (_) => const DownloadPage())),
),
ZDivider(style: st),
ZRow(
title: '远程终端',
subtitle: '通过 SSH 执行任意命令',
style: st,
leading: _entryIcon(
Icons.terminal_rounded, const Color(0xFFFF7043)),
onTap: () => Navigator.push(context,
MaterialPageRoute(builder: (_) => const TerminalPage())),
),
ZDivider(style: st),
ZRow(
title: '模组管理',
subtitle: '上传、删除、查看依赖',
style: st,
leading: _entryIcon(
Icons.extension_rounded, const Color(0xFFAB47BC)),
onTap: () => Navigator.push(context,
MaterialPageRoute(builder: (_) => const ModListPage())),
),
]),
],
),
)
: ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
children: [
// 服务器选择器
Card(
child: ListTile(
leading: const Icon(Icons.dns),
title: Text(selected?.name ?? '未选择'),
subtitle: Text('${selected?.host ?? '-'}:${selected?.port ?? '-'}'),
trailing: DropdownButton<ServerConfig>(
underline: const SizedBox.shrink(),
hint: T('切换'),
items: servers
.map((s) => DropdownMenuItem(value: s, child: Text(s.name)))
.toList(),
onChanged: (s) {
holder.select(s);
setState(() {});
},
),
),
),
const SizedBox(height: 8),
// 状态卡片
GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
childAspectRatio: 1.9,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: [
_statusCard(
icon: status?.online == true ? Icons.circle : Icons.circle_outlined,
color: status?.online == true ? Colors.green : Colors.red,
label: status?.online == true ? '在线' : '离线',
sub: status == null ? '—' : '${status.latencyMs}ms',
),
_statusCard(
icon: Icons.person,
color: Colors.blue,
label: S.t('在线人数'),
sub: '${status?.playerCount ?? 0}',
),
_statusCard(
icon: Icons.speed,
color: Colors.orange,
label: 'TPS',
sub: status?.tps?.toStringAsFixed(1) ?? '—',
),
_statusCard(
icon: Icons.storage,
color: Colors.purple,
label: S.t('磁盘'),
sub: '需 SSH 终端',
),
],
),
const SizedBox(height: 8),
// 服务器卡片列表(点击选中)
Padding(
padding: const EdgeInsets.fromLTRB(4, 16, 4, 8),
child: T('服务器', style: Theme.of(context).textTheme.titleMedium),
),
...servers.map((s) {
final st = _status[s.id];
final isSel = selected?.id == s.id;
return Card(
margin: const EdgeInsets.only(bottom: 8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppTheme.radiusM),
side: isSel
? BorderSide(color: Theme.of(context).colorScheme.primary, width: 1.6)
: BorderSide(
color: Theme.of(context).colorScheme.outlineVariant),
),
color: isSel
? Theme.of(context).colorScheme.primary.withOpacity(0.06)
: null,
child: ListTile(
selected: isSel,
selectedTileColor: Colors.transparent,
leading: Icon(
st?.online == true ? Icons.circle : Icons.circle_outlined,
color: st?.online == true ? Colors.green : Colors.red,
),
title: Text(s.name),
subtitle: Text(
st?.online == true
? S.f('在线 · {0}ms · {1} 人', [st!.latencyMs, st.playerCount]) + (st.tps != null ? ' · TPS ${st.tps!.toStringAsFixed(1)}' : '')
: S.t('离线'),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (isSel) const Icon(Icons.check, color: Colors.green),
PopupMenuButton<String>(
onSelected: (a) => _onServerAction(context, s, a),
itemBuilder: (_) => const [
PopupMenuItem(value: 'edit', child: T('编辑')),
PopupMenuItem(value: 'delete', child: T('删除')),
],
),
],
),
onTap: () {
holder.select(s);
setState(() {});
},
),
);
}),
const SizedBox(height: 8),
// 快捷入口
Padding(
padding: const EdgeInsets.fromLTRB(4, 16, 4, 8),
child: T('快捷入口', style: Theme.of(context).textTheme.titleMedium),
),
Row(
children: [
_quickEntry(
icon: Icons.download_outlined,
color: Colors.blue,
label: S.t('下载中心'),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const DownloadPage()),
),
),
const SizedBox(width: 10),
_quickEntry(
icon: Icons.terminal,
color: Colors.deepOrange,
label: S.t('远程终端'),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const TerminalPage()),
),
),
const SizedBox(width: 10),
_quickEntry(
icon: Icons.extension_outlined,
color: Colors.purple,
label: S.t('模组管理'),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const ModListPage()),
),
),
],
),
],
),
);
}
Widget _statusCard({
/// 面板外的小分组标题。
Widget _label(String text, ZStyle st) {
return Padding(
padding: const EdgeInsets.fromLTRB(6, 0, 6, 8),
child: Text(
text,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
letterSpacing: 0.2,
color: st.subColor,
),
),
);
}
/// 快捷入口左侧的圆角图标块。
Widget _entryIcon(IconData icon, Color color) {
return Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: color.withOpacity(0.16),
borderRadius: BorderRadius.circular(11),
),
child: Icon(icon, size: 18, color: color),
);
}
/// 服务器列表行(点击切换当前服务器,右侧菜单可编辑/删除)。
Widget _serverRow(ServerConfig s, ServerConfig? selected, ZStyle st) {
final online = _status[s.id]?.online == true;
final isSel = selected?.id == s.id;
final dotColor = online ? kZAccent : const Color(0xFFEF5350);
return ZRow(
style: st,
title: s.name,
subtitle: '${s.host}:${s.port}',
leading: Container(
width: 34,
height: 34,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: dotColor.withOpacity(0.16),
),
child: Icon(Icons.dns_rounded, size: 17, color: dotColor),
),
onTap: () => context.read<SelectedServerHolder>().select(s),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (isSel) ...[
ZBadge(label: S.t('当前'), color: kZAccent),
const SizedBox(width: 2),
],
PopupMenuButton<String>(
icon: Icon(Icons.more_vert, size: 20, color: st.subColor),
tooltip: S.t('更多操作'),
onSelected: (a) => _onServerAction(context, s, a),
itemBuilder: (_) => const [
PopupMenuItem(value: 'edit', child: T('编辑')),
PopupMenuItem(value: 'delete', child: T('删除')),
],
),
],
),
);
}
/// 顶部「当前服务器」面板:名称 + 地址 + 运行指标 + 切换入口。
Widget _statusTile({
required ZStyle style,
required IconData icon,
required Color color,
required String label,
required String sub,
}) {
final dark = Theme.of(context).brightness == Brightness.dark;
return Card(
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
return Container(
padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
decoration: BoxDecoration(
color: style.panelColor,
borderRadius: BorderRadius.circular(kZRadius),
border: Border.all(color: style.borderColor, width: 1),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: color.withOpacity(0.16),
borderRadius: BorderRadius.circular(9),
),
child: Icon(icon, color: color, size: 15),
),
const SizedBox(width: 8),
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: style.subColor),
),
),
],
),
const SizedBox(height: 8),
FittedBox(
fit: BoxFit.scaleDown,
child: Text(
sub,
maxLines: 1,
style: TextStyle(
fontSize: 21,
fontWeight: FontWeight.w700,
letterSpacing: -0.3,
color: style.titleColor,
),
),
),
],
),
);
}
}
/// 当前服务器概览面板:名称/地址/状态 + 切换下拉。
class _CurrentServerPanel extends StatelessWidget {
final ServerConfig server;
final ServerStatus? status;
final List<ServerConfig> servers;
final ZStyle style;
final ValueChanged<ServerConfig> onSelect;
const _CurrentServerPanel({
required this.server,
required this.status,
required this.servers,
required this.style,
required this.onSelect,
});
@override
Widget build(BuildContext context) {
final online = status?.online == true;
final color = online ? kZAccent : const Color(0xFFEF5350);
return ZPanel(style: style, children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 12, 16),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(7),
width: 44,
height: 44,
decoration: BoxDecoration(
color: color.withOpacity(0.14),
borderRadius: BorderRadius.circular(10),
color: color.withOpacity(0.16),
borderRadius: BorderRadius.circular(14),
),
child: Icon(icon, color: color, size: 16),
child: Icon(Icons.dns_rounded, color: color, size: 22),
),
const SizedBox(height: 10),
Text(label, style: Theme.of(context).textTheme.bodySmall),
const SizedBox(height: 2),
FittedBox(
fit: BoxFit.scaleDown,
child: Text(
sub,
maxLines: 1,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
server.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: dark ? Colors.white : const Color(0xFF222222),
color: style.titleColor,
),
),
const SizedBox(height: 3),
Text(
'${server.host}:${server.port}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: style.subColor),
),
],
),
),
if (servers.length > 1)
PopupMenuButton<ServerConfig>(
tooltip: S.t('切换'),
icon: Icon(Icons.swap_horiz_rounded,
size: 20, color: style.subColor),
onSelected: onSelect,
itemBuilder: (_) => [
for (final s in servers)
PopupMenuItem(
value: s,
child: Text(
s.name,
style: TextStyle(
fontWeight:
s.id == server.id ? FontWeight.w700 : null,
),
),
),
],
),
ZBadge(label: online ? S.t('在线') : S.t('离线'), color: color),
],
),
),
]);
}
}
/// 无服务器时的引导页。
class _EmptyDashboard extends StatelessWidget {
final VoidCallback onAdd;
final ZStyle style;
const _EmptyDashboard({required this.onAdd, required this.style});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 84,
height: 84,
decoration: BoxDecoration(
color: kZAccent.withOpacity(0.12),
borderRadius: BorderRadius.circular(26),
),
child: const Icon(Icons.dns_rounded, size: 38, color: kZAccent),
),
const SizedBox(height: 18),
Text(
S.t('还没有添加服务器'),
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: style.titleColor,
),
),
const SizedBox(height: 8),
Text(
S.t('填入主机地址与 RCON 密码,即可在手机上管理'),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12.5, height: 1.5, color: style.subColor),
),
const SizedBox(height: 22),
FilledButton.icon(
onPressed: onAdd,
icon: const Icon(Icons.add),
label: T('添加服务器'),
),
],
),
),
);
}
/// 快捷入口:彩色图标 + 标题的方块按钮。
Widget _quickEntry({
required IconData icon,
required Color color,
required String label,
required VoidCallback onTap,
}) {
return Expanded(
child: Material(
color: Theme.of(context).colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(AppTheme.radiusM),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(AppTheme.radiusM),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 14),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppTheme.radiusM),
border: Border.all(color: Theme.of(context).colorScheme.outlineVariant),
),
child: Column(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: color.withOpacity(0.14),
borderRadius: BorderRadius.circular(AppTheme.radiusS),
),
child: Icon(icon, color: color, size: 22),
),
const SizedBox(height: 8),
Text(label, style: Theme.of(context).textTheme.bodySmall),
],
),
),
),
),
);
}
}
+339 -184
View File
@@ -6,6 +6,7 @@ import '../../providers/download_provider.dart';
import '../../core/services/download_manager.dart';
import '../settings/download_settings_page.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 下载中心:Modrinth 搜索 + 镜像线路选择 + 下载任务队列(M2)。
class DownloadPage extends StatefulWidget {
@@ -72,8 +73,9 @@ class _DownloadPageState extends State<DownloadPage> {
length: 2,
child: Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: AppBar(
appBar: ZAppBar(
title: T('下载中心'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
actions: [
IconButton(
icon: const Icon(Icons.settings_outlined),
@@ -96,33 +98,36 @@ class _DownloadPageState extends State<DownloadPage> {
);
}
/// 搜索页签:搜索框 + 版本/加载器筛选 + 结果列表。
/// 搜索页签:圆角搜索框 + 三枚筛选下拉 + 结果面板。
Widget _buildSearchTab() {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Column(
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: TextField(
controller: _searchCtrl,
decoration: InputDecoration(
hintText: S.t('搜索 Modrinth 模组/插件,如 sodium'),
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
isDense: true,
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: ZSearchField(
controller: _searchCtrl,
hint: '搜索 Modrinth 模组/插件,如 sodium',
onSubmitted: (_) => _search(),
trailing: _searching
? const Padding(
padding: EdgeInsets.only(right: 4),
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
)
: IconButton(
icon: const Icon(Icons.arrow_forward_rounded, size: 20),
tooltip: S.t('搜索'),
onPressed: _search,
),
onSubmitted: (_) => _search(),
),
),
const SizedBox(width: 8),
FilledButton(onPressed: _searching ? null : _search, child: T('搜索')),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
padding: const EdgeInsets.fromLTRB(16, 0, 16, 10),
child: Row(
children: [
_dropdown<String>(
@@ -147,28 +152,77 @@ class _DownloadPageState extends State<DownloadPage> {
],
),
),
Expanded(
child: _searching
? const Center(child: CircularProgressIndicator())
: _results == null
? const Center(child: T('输入关键词开始搜索'))
: _results!.isEmpty
? const Center(child: T('没有结果'))
: ListView.builder(
itemCount: _results!.length,
itemBuilder: (context, i) {
final r = _results![i];
return ListTile(
leading: const Icon(Icons.extension),
title: Text(r.title),
subtitle: Text(r.description, maxLines: 2, overflow: TextOverflow.ellipsis),
trailing: Text('${r.downloads}',
style: Theme.of(context).textTheme.bodySmall),
onTap: () => _showVersionSheet(r),
);
},
),
Expanded(child: _buildResults(st)),
],
);
}
/// 搜索结果列表:整块圆角面板,结果行之间用细线分隔。
Widget _buildResults(ZStyle st) {
if (_searching) {
return const Center(child: CircularProgressIndicator());
}
if (_results == null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.travel_explore_outlined, size: 40, color: st.subColor),
const SizedBox(height: 12),
Text(S.t('输入关键词开始搜索'),
style: TextStyle(fontSize: 13, color: st.subColor)),
],
),
);
}
if (_results!.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.search_off, size: 40, color: st.subColor),
const SizedBox(height: 12),
Text(S.t('没有结果'),
style: TextStyle(fontSize: 13, color: st.subColor)),
],
),
);
}
return ListView(
padding: const EdgeInsets.fromLTRB(16, 2, 16, 24),
children: [
Padding(
padding: const EdgeInsets.only(bottom: 10, left: 6),
child: Text(
S.f('共 {0} 个结果', [_results!.length]),
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: st.subColor,
),
),
),
ZPanel(style: st, children: [
for (var i = 0; i < _results!.length; i++) ...[
if (i > 0) ZDivider(style: st),
ZRow(
style: st,
title: _results![i].title,
subtitle: _results![i].description,
value: '${_results![i].downloads}',
leading: Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: st.scheme.primary.withOpacity(0.14),
borderRadius: BorderRadius.circular(11),
),
child: Icon(Icons.extension, size: 18, color: st.scheme.primary),
),
onTap: () => _showVersionSheet(_results![i]),
),
],
]),
],
);
}
@@ -203,23 +257,37 @@ class _DownloadPageState extends State<DownloadPage> {
if (!mounted) return;
showModalBottomSheet(
context: context,
builder: (_) => SafeArea(
child: ListView(
shrinkWrap: true,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(S.f('选择 {0} 的版本', [r.title]), style: Theme.of(context).textTheme.titleMedium),
),
...versions.take(15).map((v) => ListTile(
title: Text(v.versionNumber),
subtitle: Text('${v.loaders.join('/')} · ${v.gameVersions.take(3).join(', ')}'),
trailing: const Icon(Icons.download),
onTap: () => _downloadVersion(v),
)),
],
),
),
builder: (ctx) {
final st = ZStyle.of(ctx, hasWallpaper: false);
final list = versions.take(15).toList();
return SafeArea(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(16),
children: [
Padding(
padding: const EdgeInsets.only(bottom: 12, left: 4),
child: Text(S.f('选择 {0} 的版本', [r.title]), style: Theme.of(context).textTheme.titleMedium),
),
ZPanel(
style: st,
children: [
for (int i = 0; i < list.length; i++) ...[
if (i > 0) ZDivider(style: st),
ZSheetRow(
icon: Icons.history,
title: list[i].versionNumber,
subtitle: '${list[i].loaders.join('/')} · ${list[i].gameVersions.take(3).join(', ')}',
trailing: Icon(Icons.download, color: kZAccent, size: 20),
onTap: () => _downloadVersion(list[i]),
),
],
],
),
],
),
);
},
);
} catch (e) {
if (mounted) {
@@ -246,164 +314,251 @@ class _DownloadPageState extends State<DownloadPage> {
}
}
/// 进度条视图:每个任务一条横向进度条 + 百分比。
Widget _buildBarList(DownloadProvider dp, List tasks) {
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: tasks.length,
itemBuilder: (context, i) {
final t = tasks[i];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
/// 进度条视图:每个任务一条横向进度条 + 百分比,整块放进一个圆角面板。
Widget _buildBarList(DownloadProvider dp, List tasks, ZStyle st) {
return ListView(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 24),
children: [
ZPanel(style: st, children: [
for (var i = 0; i < tasks.length; i++) ...[
if (i > 0) ZDivider(style: st),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 12, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text('${i + 1}. ${t.fileName}',
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyMedium),
Row(
children: [
Expanded(
child: Text(
'${i + 1}. ${tasks[i].fileName}',
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w600,
color: st.titleColor,
),
),
),
const SizedBox(width: 8),
Text(
'${(tasks[i].progress * 100).toStringAsFixed(0)}%',
style: TextStyle(fontSize: 12, color: st.subColor),
),
const SizedBox(width: 6),
_statusBadge(tasks[i].status),
],
),
Text('${(t.progress * 100).toStringAsFixed(0)}%',
style: Theme.of(context).textTheme.bodySmall),
const SizedBox(width: 4),
_statusChip(t.status),
const SizedBox(height: 8),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: tasks[i].status == DownloadStatus.completed
? 1
: tasks[i].progress,
minHeight: 6,
backgroundColor: st.dividerColor,
),
),
const SizedBox(height: 6),
Row(
children: [
Expanded(
child: Text(
'${_fmt(tasks[i].receivedBytes)} / ${_fmt(tasks[i].totalBytes)}'
'${tasks[i].status == DownloadStatus.running ? " · ${_fmt(tasks[i].speed)}/s" : ""}',
style: TextStyle(fontSize: 11.5, color: st.subColor),
),
),
..._taskActions(dp, tasks[i], compact: true),
],
),
if (tasks[i].error != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
tasks[i].error!,
style: TextStyle(
fontSize: 11.5, color: st.scheme.error),
),
),
],
),
const SizedBox(height: 6),
LinearProgressIndicator(
value: t.status == DownloadStatus.completed ? 1 : t.progress,
minHeight: 8,
borderRadius: BorderRadius.circular(4),
),
const SizedBox(height: 4),
Row(
children: [
Text(
'${_fmt(t.receivedBytes)} / ${_fmt(t.totalBytes)}'
'${t.status == DownloadStatus.running ? " · ${_fmt(t.speed)}/s" : ""}',
style: Theme.of(context).textTheme.bodySmall,
),
const Spacer(),
if (t.status == DownloadStatus.running)
IconButton(
icon: const Icon(Icons.pause, size: 20),
tooltip: S.t('暂停'),
onPressed: () => dp.manager.pause(t.id),
),
if (t.status == DownloadStatus.paused)
IconButton(
icon: const Icon(Icons.play_arrow, size: 20),
tooltip: S.t('继续'),
onPressed: () => dp.manager.resume(t.id),
),
if (t.status == DownloadStatus.failed)
IconButton(
icon: const Icon(Icons.replay, size: 20),
tooltip: S.t('重试'),
onPressed: () => dp.manager.retry(t.id),
),
IconButton(
icon: const Icon(Icons.close, size: 20),
tooltip: S.t('取消'),
onPressed: () => dp.manager.cancel(t.id),
),
],
),
if (t.error != null)
Text(t.error!,
style: TextStyle(
color: Theme.of(context).colorScheme.error, fontSize: 12)),
],
),
);
},
),
],
]),
],
);
}
Widget _buildQueueTab(DownloadProvider dp) {
return AnimatedBuilder(
animation: dp.manager,
builder: (context, _) {
final tasks = dp.manager.tasks;
if (tasks.isEmpty) return const Center(child: T('暂无下载任务'));
if (_barView) return _buildBarList(dp, tasks);
return ListView.builder(
itemCount: tasks.length,
itemBuilder: (context, i) {
final t = tasks[i];
return Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Padding(
padding: const EdgeInsets.all(12),
/// 卡片视图:每个任务一张圆角卡片(信息更全,适合单手操作)。
Widget _buildCardList(DownloadProvider dp, List tasks, ZStyle st) {
return ListView(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 24),
children: [
for (final t in tasks)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: ZPanel(style: st, children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 13, 12, 13),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(child: Text(t.fileName, overflow: TextOverflow.ellipsis)),
_statusChip(t.status),
Expanded(
child: Text(
t.fileName,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: st.titleColor,
),
),
),
_statusBadge(t.status),
],
),
const SizedBox(height: 8),
LinearProgressIndicator(value: t.progress),
const SizedBox(height: 10),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: t.progress,
minHeight: 6,
backgroundColor: st.dividerColor,
),
),
const SizedBox(height: 6),
Row(
children: [
Text(
'${_fmt(t.receivedBytes)} / ${_fmt(t.totalBytes)}'
'${t.status == DownloadStatus.running ? " · ${_fmt(t.speed)}/s" : ""}',
style: Theme.of(context).textTheme.bodySmall,
),
const Spacer(),
if (t.status == DownloadStatus.running)
IconButton(
icon: const Icon(Icons.pause),
tooltip: S.t('暂停'),
onPressed: () => dp.manager.pause(t.id),
Expanded(
child: Text(
'${_fmt(t.receivedBytes)} / ${_fmt(t.totalBytes)}'
'${t.status == DownloadStatus.running ? " · ${_fmt(t.speed)}/s" : ""}',
style: TextStyle(fontSize: 11.5, color: st.subColor),
),
if (t.status == DownloadStatus.paused)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: S.t('继续'),
onPressed: () => dp.manager.resume(t.id),
),
if (t.status == DownloadStatus.failed)
IconButton(
icon: const Icon(Icons.replay),
tooltip: S.t('重试'),
onPressed: () => dp.manager.retry(t.id),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: S.t('取消'),
onPressed: () => dp.manager.cancel(t.id),
),
..._taskActions(dp, t, compact: false),
],
),
if (t.error != null)
Text(t.error!, style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12)),
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(t.error!,
style: TextStyle(
fontSize: 11.5, color: st.scheme.error)),
),
],
),
),
);
},
]),
),
],
);
}
/// 任务操作按钮组:按状态决定显示暂停/继续/重试,取消始终可用。
List<Widget> _taskActions(DownloadProvider dp, dynamic t,
{required bool compact}) {
final size = compact ? 19.0 : 20.0;
final scheme = Theme.of(context).colorScheme;
return [
if (t.status == DownloadStatus.running)
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(Icons.pause_rounded, size: size),
tooltip: S.t('暂停'),
onPressed: () => dp.manager.pause(t.id),
),
if (t.status == DownloadStatus.paused)
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(Icons.play_arrow_rounded, size: size),
tooltip: S.t('继续'),
onPressed: () => dp.manager.resume(t.id),
),
if (t.status == DownloadStatus.failed)
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(Icons.replay_rounded, size: size),
tooltip: S.t('重试'),
onPressed: () => dp.manager.retry(t.id),
),
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(Icons.close_rounded, size: size, color: scheme.error),
tooltip: S.t('取消'),
onPressed: () => dp.manager.cancel(t.id),
),
];
}
Widget _buildQueueTab(DownloadProvider dp) {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return AnimatedBuilder(
animation: dp.manager,
builder: (context, _) {
final tasks = dp.manager.tasks;
if (tasks.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.cloud_download_outlined,
size: 40, color: st.subColor),
const SizedBox(height: 12),
Text(S.t('暂无下载任务'),
style: TextStyle(fontSize: 13, color: st.subColor)),
const SizedBox(height: 6),
Text(S.t('在上方「搜索下载」页签中选择模组即可开始'),
style: TextStyle(fontSize: 12, color: st.subColor)),
],
),
);
}
// 顶部任务计数
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(22, 10, 22, 0),
child: Row(
children: [
Text(
S.f('共 {0} 个任务', [tasks.length]),
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: st.subColor,
),
),
],
),
),
Expanded(
child: _barView
? _buildBarList(dp, tasks, st)
: _buildCardList(dp, tasks, st),
),
],
);
},
);
}
Widget _statusChip(DownloadStatus s) {
/// 任务状态胶囊(沿用 ZL2 的小圆角标签样式)。
Widget _statusBadge(DownloadStatus s) {
final (label, color) = switch (s) {
DownloadStatus.queued => ('排队中', Colors.grey),
DownloadStatus.running => ('下载中', Colors.blue),
DownloadStatus.paused => ('已暂停', Colors.orange),
DownloadStatus.completed => ('已完成', Colors.green),
DownloadStatus.failed => ('失败', Colors.red),
DownloadStatus.canceled => ('已取消', Colors.grey),
DownloadStatus.queued => ('排队中', const Color(0xFF90A4AE)),
DownloadStatus.running => ('下载中', const Color(0xFF42A5F5)),
DownloadStatus.paused => ('已暂停', const Color(0xFFFFA726)),
DownloadStatus.completed => ('已完成', kZAccent),
DownloadStatus.failed => ('失败', const Color(0xFFEF5350)),
DownloadStatus.canceled => ('已取消', const Color(0xFF90A4AE)),
};
return Chip(label: Text(label, style: const TextStyle(fontSize: 12)), backgroundColor: color.withOpacity(0.15), visualDensity: VisualDensity.compact);
return ZBadge(label: label, color: color);
}
String _fmt(num bytes) {
@@ -4,6 +4,7 @@ import '../../core/services/dependency_index_service.dart';
import '../../providers/download_provider.dart';
import '../../providers/server_provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 依赖仓库页:服务器本地仓库增量同步 + 依赖树查询 + 缺失依赖一键补齐 + 重复检测。
class DependencyTreePage extends StatefulWidget {
@@ -73,28 +74,26 @@ class _DependencyTreePageState extends State<DependencyTreePage> {
style: Theme.of(context).textTheme.titleMedium),
const Divider(),
T('该模组依赖:'),
...tree.dependsOn.map((m) => ListTile(
dense: true,
leading: const Icon(Icons.link, size: 18),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
...tree.dependsOn.map((m) => ZSheetRow(
icon: Icons.link,
title: '${m.name ?? m.fileName} ${m.version ?? ''}',
)),
if (tree.dependsOn.isEmpty) T('无', style: TextStyle(color: Colors.grey)),
const SizedBox(height: 8),
T('被以下模组依赖:'),
...tree.dependents.map((m) => ListTile(
dense: true,
leading: const Icon(Icons.link, size: 18),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
...tree.dependents.map((m) => ZSheetRow(
icon: Icons.link,
title: '${m.name ?? m.fileName} ${m.version ?? ''}',
)),
if (tree.dependents.isEmpty) T('无', style: TextStyle(color: Colors.grey)),
if (tree.missing.isNotEmpty) ...[
const SizedBox(height: 8),
T('缺失依赖(可一键补齐):',
style: TextStyle(color: Colors.red, fontWeight: FontWeight.w600)),
...tree.missing.map((d) => ListTile(
dense: true,
leading: const Icon(Icons.warning_amber_rounded, color: Colors.red, size: 20),
title: Text(d),
...tree.missing.map((d) => ZSheetRow(
icon: Icons.warning_amber_rounded,
danger: true,
title: d,
trailing: TextButton(
onPressed: () => _fetchMissing(d),
child: T('从 Modrinth 补齐'),
@@ -148,10 +147,10 @@ class _DependencyTreePageState extends State<DependencyTreePage> {
style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.w600)),
subtitle: Text(S.f('{0} 个版本共存', [g.items.length])),
children: g.items
.map((m) => ListTile(
dense: true,
title: Text(m.fileName),
subtitle: Text('${m.version ?? S.t('未知')} · ${m.remotePath}'),
.map((m) => ZSheetRow(
icon: Icons.description_outlined,
title: m.fileName,
subtitle: '${m.version ?? S.t('未知')} · ${m.remotePath}',
))
.toList(),
)),
@@ -164,7 +163,7 @@ class _DependencyTreePageState extends State<DependencyTreePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
appBar: ZAppBar(
title: T('依赖仓库'),
actions: [
IconButton(
@@ -215,13 +214,10 @@ class _DependencyTreePageState extends State<DependencyTreePage> {
itemCount: _mods!.length,
itemBuilder: (context, i) {
final m = _mods![i];
return ListTile(
leading: const Icon(Icons.inventory_2_outlined),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
subtitle: Text(
S.f('{0} · 依赖 {1} · 软依赖 {2}', [m.fileName, m.depends.length, m.softDepends.length]),
),
trailing: const Icon(Icons.account_tree_outlined),
return ZSheetRow(
icon: Icons.inventory_2_outlined,
title: '${m.name ?? m.fileName} ${m.version ?? ''}',
subtitle: S.f('{0} · 依赖 {1} · 软依赖 {2}', [m.fileName, m.depends.length, m.softDepends.length]),
onTap: () => _showTree(m),
);
},
+11 -6
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../mod_manager/mod_provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 模组详情页:展示 jar 元数据(名称 / 版本 / 作者 / 依赖 / 描述)。
class ModDetailPage extends StatelessWidget {
@@ -13,15 +14,19 @@ class ModDetailPage extends StatelessWidget {
Widget build(BuildContext context) {
final meta = file.meta;
return Scaffold(
appBar: AppBar(title: Text(file.fileName)),
appBar: ZAppBar(title: Text(file.fileName)),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
ListTile(
leading: const Icon(Icons.extension),
title: Text(meta.name ?? S.t('未知名称'),
style: Theme.of(context).textTheme.titleLarge),
subtitle: Text(S.f('版本 {0}', [meta.version ?? '未知'])),
ZPanel(
style: ZStyle.of(context, hasWallpaper: false),
children: [
ZSheetRow(
icon: Icons.extension,
title: meta.name ?? S.t('未知名称'),
subtitle: S.f('版本 {0}', [meta.version ?? '未知']),
),
],
),
const Divider(),
_kv('文件名', file.fileName),
+150 -42
View File
@@ -9,6 +9,7 @@ import 'mod_detail_page.dart';
import 'dependency_tree_page.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/empty_state_page.dart';
import '../../core/widgets/z_widgets.dart';
/// 模组/插件管理页:列出服务器 mods / plugins 目录中的 jar 文件,
/// 支持上传 / 删除 / 重命名 / 查看详情(M1)。
@@ -74,10 +75,12 @@ class _ModListPageState extends State<ModListPage>
return ChangeNotifierProvider<ModProvider>.value(
value: p,
child: Consumer<ModProvider>(builder: (context, mod, _) {
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: AppBar(
appBar: ZAppBar(
title: T('模组管理'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
@@ -98,23 +101,25 @@ class _ModListPageState extends State<ModListPage>
),
body: Column(
children: [
// mods / plugins 切换 + 排序
// ---------- 目录切换 + 排序 ----------
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
padding: const EdgeInsets.fromLTRB(16, 6, 16, 10),
child: Row(
children: [
SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'mods', label: Text('mods')),
ButtonSegment(value: 'plugins', label: Text('plugins')),
],
selected: {mod.currentDir},
onSelectionChanged: (s) =>
mod.open(server, dir: s.first),
_DirSwitch(
value: mod.currentDir,
onChanged: (v) => mod.open(server, dir: v),
),
const Spacer(),
if (mod.files.isNotEmpty)
Text(
S.f('{0} 个文件', [mod.files.length]),
style: TextStyle(fontSize: 12, color: st.subColor),
),
PopupMenuButton<ModSortMode>(
icon: const Icon(Icons.sort),
icon: Icon(Icons.sort_rounded,
size: 20, color: st.subColor),
tooltip: S.t('排序'),
onSelected: (m) => mod.setSortMode(m),
itemBuilder: (_) => const [
PopupMenuItem(value: ModSortMode.name, child: T('按名称')),
@@ -125,43 +130,59 @@ class _ModListPageState extends State<ModListPage>
],
),
),
if (mod.loading) const LinearProgressIndicator(),
if (mod.loading) const LinearProgressIndicator(minHeight: 2),
if (mod.error != null)
Padding(
padding: const EdgeInsets.all(12),
child: Text(S.f('加载失败:{0}', [mod.error.toString()]),
style: TextStyle(color: Theme.of(context).colorScheme.error)),
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Row(
children: [
Icon(Icons.error_outline,
size: 16, color: st.scheme.error),
const SizedBox(width: 8),
Expanded(
child: Text(
S.f('加载失败:{0}', [mod.error.toString()]),
style:
TextStyle(fontSize: 12.5, color: st.scheme.error),
),
),
],
),
),
Expanded(
child: mod.files.isEmpty && !mod.loading
? const Center(child: T('目录下没有 .jar 文件'))
: ListView.builder(
itemCount: mod.files.length,
itemBuilder: (context, i) {
final f = mod.files[i];
return ListTile(
leading: const Icon(Icons.extension_outlined),
title: Text(f.fileName),
subtitle: Text(
'${f.meta.name ?? '未知'} ${f.meta.version ?? ''}'
' · ${_fmtSize(f.size)}',
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.extension_off_outlined,
size: 40, color: st.subColor),
const SizedBox(height: 12),
Text(
S.t('目录下没有 .jar 文件'),
style: TextStyle(
fontSize: 13, color: st.subColor),
),
trailing: PopupMenuButton<String>(
onSelected: (a) => _onAction(context, mod, f, a),
itemBuilder: (_) => const [
PopupMenuItem(value: 'detail', child: T('详情')),
PopupMenuItem(value: 'rename', child: T('重命名')),
PopupMenuItem(value: 'delete', child: T('删除')),
],
const SizedBox(height: 16),
FilledButton.tonal(
onPressed: mod.loading
? null
: () => _upload(context, mod),
child: T('上传 jar'),
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ModDetailPage(file: f, provider: mod),
),
),
);
},
],
),
)
: ListView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 96),
children: [
ZPanel(style: st, children: [
for (var i = 0; i < mod.files.length; i++) ...[
if (i > 0) ZDivider(style: st),
_jarRow(context, mod, mod.files[i], st),
],
]),
],
),
),
],
@@ -176,6 +197,46 @@ class _ModListPageState extends State<ModListPage>
);
}
/// 单个 jar 行:文件名 + 元数据(名称/版本/大小)+ 操作菜单。
Widget _jarRow(BuildContext context, ModProvider mod, RemoteJarFile f, ZStyle st) {
final metaLine = [
if (f.meta.name != null) f.meta.name!,
if (f.meta.version != null) f.meta.version!,
_fmtSize(f.size),
].join(' · ');
return ZRow(
style: st,
title: f.fileName,
subtitle: metaLine,
leading: Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: const Color(0xFFAB47BC).withOpacity(0.16),
borderRadius: BorderRadius.circular(11),
),
child: const Icon(Icons.extension_rounded,
size: 18, color: Color(0xFFAB47BC)),
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ModDetailPage(file: f, provider: mod),
),
),
trailing: PopupMenuButton<String>(
icon: Icon(Icons.more_vert, size: 20, color: st.subColor),
tooltip: S.t('更多操作'),
onSelected: (a) => _onAction(context, mod, f, a),
itemBuilder: (_) => const [
PopupMenuItem(value: 'detail', child: T('详情')),
PopupMenuItem(value: 'rename', child: T('重命名')),
PopupMenuItem(value: 'delete', child: T('删除')),
],
),
);
}
Future<void> _upload(BuildContext context, ModProvider mod) async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
@@ -237,3 +298,50 @@ class _ModListPageState extends State<ModListPage>
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
}
}
/// mods / plugins 目录切换:两段等宽圆角按钮,选中段用品牌色。
class _DirSwitch extends StatelessWidget {
final String value;
final ValueChanged<String> onChanged;
const _DirSwitch({required this.value, required this.onChanged});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
Widget seg(String id, String label) {
final selected = value == id;
return GestureDetector(
onTap: () => onChanged(id),
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 7),
decoration: BoxDecoration(
color: selected ? kZAccent : Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: Text(
label,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: selected ? Colors.white : scheme.onSurfaceVariant,
),
),
),
);
}
return Container(
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(22),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [seg('mods', 'mods'), seg('plugins', 'plugins')],
),
);
}
}
@@ -1,5 +1,8 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/utils/rcon_client.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/wallpaper_provider.dart';
import 'player_service.dart';
import '../../core/l10n/strings.dart';
@@ -192,8 +195,11 @@ class _PlayerListPageState extends State<PlayerListPage> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
return Scaffold(
appBar: AppBar(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
backgroundColor: hasWallpaper ? Colors.transparent : null,
leading: _selecting
? IconButton(
icon: const Icon(Icons.close),
@@ -226,7 +232,7 @@ class _PlayerListPageState extends State<PlayerListPage> {
),
],
),
body: _buildBody(theme),
body: _buildBody(theme, hasWallpaper),
bottomNavigationBar: _selecting ? _buildBatchBar(theme) : null,
);
}
@@ -268,73 +274,174 @@ class _PlayerListPageState extends State<PlayerListPage> {
);
}
Widget _buildBody(ThemeData theme) {
Widget _buildBody(ThemeData theme, bool hasWallpaper) {
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
if (_loading) {
return const Center(child: CircularProgressIndicator());
}
if (_error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(S.f('加载失败:{0}', [_error.toString()]), textAlign: TextAlign.center),
const SizedBox(height: 12),
FilledButton(onPressed: _load, child: T('重试')),
],
child: Padding(
padding: const EdgeInsets.all(28),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.cloud_off_outlined, size: 40, color: st.subColor),
const SizedBox(height: 14),
Text(
S.f('加载失败:{0}', [_error.toString()]),
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, height: 1.5, color: st.subColor),
),
const SizedBox(height: 16),
FilledButton.tonal(onPressed: _load, child: T('重试')),
],
),
),
);
}
final players = _players ?? [];
if (players.isEmpty) {
return Center(child: T('暂无在线玩家', style: theme.textTheme.bodyLarge));
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.group_outlined, size: 40, color: st.subColor),
const SizedBox(height: 12),
Text(S.t('暂无在线玩家'),
style: TextStyle(fontSize: 13, color: st.subColor)),
const SizedBox(height: 16),
FilledButton.tonal(onPressed: _load, child: T('刷新')),
],
),
);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView.separated(
padding: const EdgeInsets.all(12),
itemCount: players.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (_, i) {
final p = players[i];
final selected = _selected.contains(p.name);
return ListTile(
leading: _selecting
? Checkbox(
value: selected,
onChanged: (_) => _toggleSelect(p.name),
)
: CircleAvatar(
child: Text(p.name.isNotEmpty ? p.name[0].toUpperCase() : '?'),
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 10, 16, 24),
children: [
// 顶部统计条
Padding(
padding: const EdgeInsets.only(bottom: 12, left: 6),
child: Row(
children: [
Text(
S.f('在线玩家 {0} 人', [players.length]),
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: st.subColor,
),
title: Text(p.name, style: theme.textTheme.titleMedium),
subtitle: p.uuid.isEmpty ? null : Text(p.uuid, style: theme.textTheme.bodySmall),
selected: selected,
onTap: _selecting ? () => _toggleSelect(p.name) : null,
trailing: _selecting
? const SizedBox.shrink()
: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (p.isOp)
Chip(
label: const Text('OP'),
visualDensity: VisualDensity.compact,
),
PopupMenuButton<String>(
tooltip: S.t('操作'),
onSelected: (action) => _handleAction(p, action),
itemBuilder: (_) => [
const PopupMenuItem(value: 'op', child: T('给予 OP')),
const PopupMenuItem(value: 'deop', child: T('取消 OP')),
const PopupMenuItem(value: 'kick', child: T('踢出')),
const PopupMenuItem(value: 'ban', child: T('封禁')),
],
),
],
),
const Spacer(),
if (_selecting)
Text(
S.f('已选 {0} 人', [_selected.length]),
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: kZAccent,
),
),
);
},
],
),
),
// 玩家列表:整块圆角面板,行内用勾选钮表达选中状态
ZPanel(style: st, children: [
for (var i = 0; i < players.length; i++) ...[
if (i > 0) ZDivider(style: st),
_PlayerRow(
style: st,
player: players[i],
selecting: _selecting,
selected: _selected.contains(players[i].name),
onToggle: () => _toggleSelect(players[i].name),
onAction: (a) => _handleAction(players[i], a),
),
],
]),
],
),
);
}
}
}
/// 单个玩家行:头像/勾选钮 + 名字 + UUID + OP 标记 / 操作菜单。
class _PlayerRow extends StatelessWidget {
final ZStyle style;
final PlayerInfo player;
final bool selecting;
final bool selected;
final VoidCallback onToggle;
final ValueChanged<String> onAction;
const _PlayerRow({
required this.style,
required this.player,
required this.selecting,
required this.selected,
required this.onToggle,
required this.onAction,
});
@override
Widget build(BuildContext context) {
final avatar = Container(
width: 38,
height: 38,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: style.scheme.primary.withOpacity(0.16),
),
alignment: Alignment.center,
child: Text(
player.name.isNotEmpty ? player.name[0].toUpperCase() : '?',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: style.scheme.primary,
),
),
);
return ZRow(
style: style,
title: player.name,
subtitle: player.uuid.isEmpty ? null : player.uuid,
leading: selecting
? ZToggle(
value: selected,
size: 34,
borderColor: style.subColor,
onChanged: (_) => onToggle(),
)
: avatar,
onTap: selecting ? onToggle : null,
trailing: selecting
? null
: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (player.isOp) ...[
ZBadge(label: 'OP', color: kZAccent),
const SizedBox(width: 2),
],
PopupMenuButton<String>(
tooltip: S.t('操作'),
icon: Icon(Icons.more_vert,
size: 20, color: style.subColor),
onSelected: onAction,
itemBuilder: (_) => const [
PopupMenuItem(value: 'op', child: T('给予 OP')),
PopupMenuItem(value: 'deop', child: T('取消 OP')),
PopupMenuItem(value: 'kick', child: T('踢出')),
PopupMenuItem(value: 'ban', child: T('封禁')),
],
),
],
),
);
}
}
+19 -54
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 服务器卡片的数据状态。
enum ServerCardState {
@@ -49,7 +50,6 @@ class ServerCard extends StatelessWidget {
this.tps,
});
static const double _radius = 20;
/// TPS 分档着色:≥16 流畅,≥10 偏低,否则卡顿。
static Color tpsColor(double tps) {
@@ -86,11 +86,10 @@ class ServerCard extends StatelessWidget {
final scheme = theme.colorScheme;
final online = state == ServerCardState.online;
// 卡片底色跟随主题表面色,浮一层极淡的品牌色,避免纯白/纯黑显得生硬。
final Color base = Color.alphaBlend(
scheme.primary.withOpacity(online ? 0.06 : 0.02),
scheme.surface,
);
// 在线态用品牌色描边强调,离线态退成中性描边,避免整屏红框太吵
final borderColor = online
? kZAccent.withOpacity(0.45)
: scheme.outlineVariant.withOpacity(0.7);
return Semantics(
button: true,
@@ -99,24 +98,12 @@ class ServerCard extends StatelessWidget {
color: Colors.transparent,
child: Ink(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(_radius),
color: base,
border: Border.all(
color: online
? scheme.primary.withOpacity(0.38)
: scheme.outlineVariant.withOpacity(0.55),
width: online ? 1.4 : 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(online ? 0.08 : 0.04),
blurRadius: online ? 18 : 10,
offset: const Offset(0, 6),
),
],
borderRadius: BorderRadius.circular(kZRadius),
color: scheme.surfaceContainerLow,
border: Border.all(color: borderColor, width: online ? 1.4 : 1),
),
child: InkWell(
borderRadius: BorderRadius.circular(_radius),
borderRadius: BorderRadius.circular(kZRadius),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 8, 14),
@@ -150,41 +137,18 @@ class ServerCard extends StatelessWidget {
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith(
fontSize: 15.5,
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
),
// 状态胶囊
Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
decoration: BoxDecoration(
color: _statusColor.withOpacity(0.13),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: _statusColor.withOpacity(0.28)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_statusLabel,
style: theme.textTheme.labelSmall?.copyWith(
color: _statusColor,
fontWeight: FontWeight.w600,
),
),
if (online && latencyMs != null) ...[
const SizedBox(width: 6),
Text(
'${latencyMs}ms',
style: theme.textTheme.labelSmall?.copyWith(
color: _statusColor.withOpacity(0.75),
fontFeatures: const [FontFeature.tabularFigures()],
),
),
],
],
),
// 状态胶囊(与 ZL2 的标签样式统一)
ZBadge(
label: online && latencyMs != null
? '$_statusLabel · ${latencyMs}ms'
: _statusLabel,
color: _statusColor,
),
_buildMenu(context, scheme),
],
@@ -242,6 +206,7 @@ class ServerCard extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
fontSize: 12,
letterSpacing: 0.1,
),
),
@@ -259,7 +224,7 @@ class ServerCard extends StatelessWidget {
_Pill(
icon: Icons.autorenew_rounded,
label: S.t('正在获取状态'),
color: Color(0xFF94A3B8),
color: const Color(0xFF94A3B8),
),
]);
}
@@ -271,7 +236,7 @@ class ServerCard extends StatelessWidget {
child: _Pill(
icon: Icons.cloud_off_outlined,
label: S.t('无法连接'),
color: Color(0xFFF87171),
color: const Color(0xFFF87171),
),
),
const Spacer(),
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../../providers/server_provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 新增 / 编辑服务器的表单弹窗。
///
@@ -92,6 +93,7 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
@override
Widget build(BuildContext context) {
final st = ZStyle.of(context, hasWallpaper: false);
return AlertDialog(
title: Text(isEditing ? '编辑服务器' : '添加服务器'),
content: SingleChildScrollView(
@@ -137,12 +139,19 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
onFieldSubmitted: (_) => _submit(),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: T('SSH 连接(可选)'),
subtitle: T('用于模组插件管理与远程终端'),
value: _sshEnabled,
onChanged: (v) => setState(() => _sshEnabled = v),
ZPanel(
style: st,
children: [
ZRow(
style: st,
title: 'SSH 连接(可选)',
subtitle: '用于模组插件管理与远程终端',
trailing: ZToggle(
value: _sshEnabled,
onChanged: (v) => setState(() => _sshEnabled = v),
),
),
],
),
if (_sshEnabled) ...[
TextFormField(
@@ -10,6 +10,7 @@ import '../settings/settings_page.dart';
import 'server_card.dart';
import 'server_form_dialog.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
class ServerListPage extends StatefulWidget {
const ServerListPage({super.key});
@@ -192,7 +193,7 @@ class _ServerListPageState extends State<ServerListPage> {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
return Scaffold(
appBar: AppBar(
appBar: ZAppBar(
title: const Text('ZV Manager'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
elevation: hasWallpaper ? 0 : null,
+139 -69
View File
@@ -1,9 +1,16 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/utils/update_service.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/wallpaper_provider.dart';
/// 关于软件页:版本与检查更新 + 开发者信息 + 开源许可。
///
/// 版式:顶部 Logo 区 → 「应用」面板(检查更新 / 开源许可)→
/// 「创造者」面板(头像行)→ 底部免责说明。
class AboutPage extends StatefulWidget {
const AboutPage({super.key});
@@ -55,68 +62,70 @@ class _AboutPageState extends State<AboutPage> {
@override
Widget build(BuildContext context) {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Scaffold(
appBar: AppBar(title: T('关于软件')),
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
title: T('关于软件'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
children: [
const SizedBox(height: 24),
Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.asset('assets/logo.png', width: 96, height: 96),
),
const SizedBox(height: 8),
T('ZV Manager', style: Theme.of(context).textTheme.titleLarge),
Text(S.f('版本 {0}', [_currentVersion]),
style: Theme.of(context).textTheme.bodySmall),
],
),
const SizedBox(height: 16),
const Divider(),
ListTile(
leading: const Icon(Icons.system_update_outlined),
title: T('检查更新'),
trailing: _checkingUpdate
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.chevron_right),
onTap: _checkingUpdate ? null : _checkUpdate,
),
const Divider(),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: T('创造者', style: Theme.of(context).textTheme.titleSmall),
),
const _CreatorTile(
name: 'Z有3笔',
role: '开发者 · Gitee: DriftinBlock',
assetAvatar: 'assets/creator_zavatar.png',
homeUrl: 'https://gitee.com/driftinblock',
),
_CreatorTile(
name: 'Ventiの酒',
role: S.t('协作者 · Gitee: venti1112'),
avatarUrl: 'https://gitee.com/venti1112.png',
homeUrl: 'https://gitee.com/venti1112',
),
const Divider(),
ListTile(
leading: const Icon(Icons.fact_check_outlined),
title: T('开源许可'),
trailing: const Icon(Icons.chevron_right),
onTap: () => showLicensePage(context: context),
),
const Divider(),
Padding(
padding: const EdgeInsets.all(16),
child: Text(
S.t('ZV Manager 是一款 Minecraft 服务器远程管理工具,本软件与 Mojang、微软无任何隶属关系。'),
style: Theme.of(context).textTheme.bodySmall,
textAlign: TextAlign.center,
_Header(version: _currentVersion, style: st),
const SizedBox(height: 20),
ZPanel(style: st, children: [
ZRow(
title: '检查更新',
subtitle: '从 Gitee 获取最新版本',
style: st,
leading: Icon(Icons.system_update_outlined,
size: 20, color: st.subColor),
trailing: _checkingUpdate
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2))
: null,
onTap: _checkingUpdate ? null : _checkUpdate,
),
ZDivider(style: st),
ZRow(
title: '开源许可',
subtitle: '查看本应用使用的第三方库许可',
style: st,
leading: Icon(Icons.fact_check_outlined,
size: 20, color: st.subColor),
onTap: () => showLicensePage(context: context),
),
]),
const SizedBox(height: 14),
_SectionLabel('创造者', style: st),
ZPanel(style: st, children: [
_CreatorRow(
style: st,
name: 'Z有3笔',
role: S.t('开发者 · Gitee: DriftinBlock'),
assetAvatar: 'assets/creator_zavatar.png',
homeUrl: 'https://gitee.com/driftinblock',
),
ZDivider(style: st),
_CreatorRow(
style: st,
name: 'Ventiの酒',
role: S.t('协作者 · Gitee: venti1112'),
avatarUrl: 'https://gitee.com/venti1112.png',
homeUrl: 'https://gitee.com/venti1112',
),
]),
const SizedBox(height: 22),
Text(
S.t('ZV Manager 是一款 Minecraft 服务器远程管理工具,'
'本软件与 Mojang、微软无任何隶属关系。'),
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12, height: 1.6, color: st.subColor),
),
],
),
@@ -124,8 +133,65 @@ class _AboutPageState extends State<AboutPage> {
}
}
/// 创造者条目:头像 + 名称 + 角色,点击打开 Gitee 主页。
class _CreatorTile extends StatelessWidget {
/// 顶部品牌区:Logo + 名称 + 版本号。
class _Header extends StatelessWidget {
final String version;
final ZStyle style;
const _Header({required this.version, required this.style});
@override
Widget build(BuildContext context) {
return Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(22),
child: Image.asset('assets/logo.png', width: 88, height: 88),
),
const SizedBox(height: 12),
Text(
'ZV Manager',
style: TextStyle(
fontSize: 19,
fontWeight: FontWeight.w700,
color: style.titleColor,
),
),
const SizedBox(height: 3),
Text(
S.f('版本 {0}', [version]),
style: TextStyle(fontSize: 12.5, color: style.subColor),
),
],
);
}
}
/// 分组小标题(面板外的灰色小字)。
class _SectionLabel extends StatelessWidget {
final String text;
final ZStyle style;
const _SectionLabel(this.text, {required this.style});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(6, 0, 6, 8),
child: Text(
S.t(text),
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
letterSpacing: 0.2,
color: style.subColor,
),
),
);
}
}
/// 创造者行:头像 + 名称 + 角色,点击打开 Gitee 主页。
class _CreatorRow extends StatelessWidget {
final ZStyle style;
final String name;
final String role;
final String homeUrl;
@@ -134,7 +200,8 @@ class _CreatorTile extends StatelessWidget {
final String? assetAvatar;
final String? avatarUrl;
const _CreatorTile({
const _CreatorRow({
required this.style,
required this.name,
required this.role,
required this.homeUrl,
@@ -144,24 +211,27 @@ class _CreatorTile extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListTile(
return ZRow(
style: style,
title: name,
subtitle: role,
leading: ClipOval(
child: SizedBox(
width: 44,
height: 44,
width: 38,
height: 38,
child: assetAvatar != null
? Image.asset(assetAvatar!, fit: BoxFit.cover)
: Image.network(
avatarUrl!,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => const ColoredBox(
color: Color(0xFFDDDDDD), child: Icon(Icons.person)),
errorBuilder: (_, __, ___) => ColoredBox(
color: style.scheme.surfaceContainerHighest,
child: Icon(Icons.person,
size: 20, color: style.scheme.onSurfaceVariant),
),
),
),
),
title: Text(name),
subtitle: Text(role, overflow: TextOverflow.ellipsis),
trailing: const Icon(Icons.open_in_new, size: 18),
onTap: () => UpdateService.openUrl(homeUrl),
);
}
+141 -86
View File
@@ -1,9 +1,15 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/download_provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/download_provider.dart';
import '../../providers/wallpaper_provider.dart';
/// 下载与镜像设置页:镜像线路选择、测速自动选线、并发数(原下载页内设置移入此处)。
///
/// 版式:两组 ZL2 圆角面板。镜像线路用尾部圆形勾选钮表达单选,
/// 比 RadioListTile 更紧凑,也与其他设置页的选中态语言一致。
class DownloadSettingsPage extends StatefulWidget {
const DownloadSettingsPage({super.key});
@@ -24,87 +30,102 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {
Widget build(BuildContext context) {
final dp = context.watch<DownloadProvider>();
final mirror = dp.mirror;
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Scaffold(
appBar: AppBar(title: T('下载与镜像设置')),
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
title: T('下载与镜像设置'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 28),
children: [
const SectionHeader('镜像线路'),
RadioListTile<String>(
title: T('MCIM 国内镜像(推荐)'),
subtitle: T('modrinth.mcimirror.top,无需科学上网'),
value: 'mcim',
groupValue: mirror.currentId,
onChanged: (v) async {
await mirror.select(v!);
setState(() {});
},
),
RadioListTile<String>(
title: T('Modrinth 官方'),
subtitle: T('直连官方源,适合海外网络'),
value: 'official',
groupValue: mirror.currentId,
onChanged: (v) async {
await mirror.select(v!);
setState(() {});
},
),
RadioListTile<String>(
title: T('自定义镜像'),
subtitle: Text(mirror.currentId == 'custom' && mirror.customUrl.isNotEmpty
? mirror.customUrl
: '使用自建/第三方镜像地址'),
value: 'custom',
groupValue: mirror.currentId,
onChanged: (v) async => {await _editCustomUrl(), setState(() {})},
),
ListTile(
leading: _testing
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.speed),
title: T('一键测速并选择最快线路'),
subtitle: Text(mirror.lastSpeedMs > 0
? S.f('上次测速:{0}ms({1})', [mirror.lastSpeedMs, mirror.currentName])
: '自动在官方与镜像之间选择延迟最低的线路'),
onTap: _testing
? null
: () async {
final messenger = ScaffoldMessenger.of(context);
setState(() => _testing = true);
await mirror.autoSelect();
if (!mounted) return;
setState(() => _testing = false);
messenger.showSnackBar(SnackBar(
content: Text(S.f('已选择最快线路:{0}({1}ms)', [mirror.currentName, mirror.lastSpeedMs])),
));
},
),
const Divider(),
const SectionHeader('下载队列'),
ListTile(
leading: const Icon(Icons.playlist_play),
title: T('同时下载任务数'),
subtitle: Text(S.f('当前:{0} 个(越大越占带宽,建议 1-3)', [dp.concurrency])),
trailing: DropdownButton<int>(
value: dp.concurrency,
underline: const SizedBox.shrink(),
items: const [1, 2, 3, 4, 5, 6]
.map((n) => DropdownMenuItem(value: n, child: Text('$n')))
.toList(),
onChanged: (n) async {
if (n == null) return;
await dp.setConcurrency(n);
// ---------- 镜像线路 ----------
ZPanel(style: st, children: [
_MirrorRow(
style: st,
title: 'MCIM 国内镜像(推荐)',
subtitle: 'mod.mcimirror.top,无需科学上网',
selected: mirror.currentId == 'mcim',
onTap: () async {
await mirror.select('mcim');
setState(() {});
},
),
),
const Divider(),
const Padding(
padding: EdgeInsets.all(16),
ZDivider(style: st),
_MirrorRow(
style: st,
title: 'Modrinth 官方',
subtitle: '直连官方源,适合海外网络',
selected: mirror.currentId == 'official',
onTap: () async {
await mirror.select('official');
setState(() {});
},
),
ZDivider(style: st),
_MirrorRow(
style: st,
title: '自定义镜像',
subtitle: mirror.currentId == 'custom' && mirror.customUrl.isNotEmpty
? mirror.customUrl
: '使用自建/第三方镜像地址',
selected: mirror.currentId == 'custom',
onTap: () async {
await _editCustomUrl();
if (mounted) setState(() {});
},
),
ZDivider(style: st),
ZRow(
title: '一键测速并选择最快线路',
subtitle: mirror.lastSpeedMs > 0
? S.f('上次测速:{0}ms({1})',
[mirror.lastSpeedMs, mirror.currentName])
: '自动在官方与镜像之间选择延迟最低的线路',
style: st,
leading: Icon(Icons.speed, size: 20, color: st.subColor),
trailing: _testing
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2))
: null,
onTap: _testing ? null : _autoSelect,
),
]),
const SizedBox(height: 14),
// ---------- 下载队列 ----------
ZPanel(style: st, children: [
ZRow(
title: '同时下载任务数',
subtitle: S.f('当前:{0} 个(越大越占带宽,建议 1-3)', [dp.concurrency]),
style: st,
leading: Icon(Icons.playlist_play, size: 20, color: st.subColor),
trailing: DropdownButton<int>(
value: dp.concurrency,
underline: const SizedBox.shrink(),
borderRadius: BorderRadius.circular(12),
items: const [1, 2, 3, 4, 5, 6]
.map((n) => DropdownMenuItem(value: n, child: Text('$n')))
.toList(),
onChanged: (n) async {
if (n == null) return;
await dp.setConcurrency(n);
setState(() {});
},
),
),
]),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'说明:下载完成的文件保存在应用目录 downloads/ 下;'
'若服务器配置了 SSH,会自动上传到对应服务器的 mods/plugins 目录。',
style: TextStyle(fontSize: 13),
S.t('说明:下载完成的文件保存在应用目录 downloads/ 下;'
'若服务器配置了 SSH,会自动上传到对应服务器的 mods/plugins 目录。'),
style: TextStyle(fontSize: 12, height: 1.6, color: st.subColor),
),
),
],
@@ -112,6 +133,21 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {
);
}
/// 测速并自动选线:过程中禁用点击,完成后用 SnackBar 告知结果。
Future<void> _autoSelect() async {
final dp = context.read<DownloadProvider>();
final mirror = dp.mirror;
final messenger = ScaffoldMessenger.of(context);
setState(() => _testing = true);
await mirror.autoSelect();
if (!mounted) return;
setState(() => _testing = false);
messenger.showSnackBar(SnackBar(
content: Text(S.f('已选择最快线路:{0}({1}ms)',
[mirror.currentName, mirror.lastSpeedMs])),
));
}
Future<void> _editCustomUrl() async {
final dp = context.read<DownloadProvider>();
final ctrl = TextEditingController(text: dp.mirror.customUrl);
@@ -125,7 +161,9 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {
),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: T('取消')),
FilledButton(onPressed: () => Navigator.pop(context, ctrl.text.trim()), child: T('确定')),
FilledButton(
onPressed: () => Navigator.pop(context, ctrl.text.trim()),
child: T('确定')),
],
),
);
@@ -135,19 +173,36 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {
}
}
class SectionHeader extends StatelessWidget {
final String text;
const SectionHeader(this.text, {super.key});
/// 镜像线路单选行:右侧用圆形勾选钮表示当前生效线路。
class _MirrorRow extends StatelessWidget {
final ZStyle style;
final String title;
final String subtitle;
final bool selected;
final VoidCallback onTap;
const _MirrorRow({
required this.style,
required this.title,
required this.subtitle,
required this.selected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 6),
child: Text(text,
style: Theme.of(context)
.textTheme
.titleSmall
?.copyWith(color: Theme.of(context).colorScheme.primary)),
return ZRow(
style: style,
title: title,
subtitle: subtitle,
onTap: onTap,
trailing: ZToggle(
value: selected,
size: 30,
borderColor: style.subColor,
// 单选:只允许从未选变选中,再点已选项不做取消
onChanged: (_) => onTap(),
),
);
}
}
+163 -71
View File
@@ -1,22 +1,38 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/wallpaper_provider.dart';
/// 使用教程页:教用户如何开启 RCON、SSH、使用模组管理/下载/终端等功能。
///
/// 版式:顶部一段说明块 + 每组教程一个 ZL2 圆角面板(标题行可展开正文)。
/// 展开后步骤按序号排列,末尾的「提示」用浅色说明块与步骤区分开。
class HelpPage extends StatelessWidget {
const HelpPage({super.key});
@override
Widget build(BuildContext context) {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Scaffold(
appBar: AppBar(title: Text(S.t('使用教程'))),
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
title: T('使用教程'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
),
body: ListView(
padding: const EdgeInsets.all(12),
children: const [
_Intro(),
_TutorialCard(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 28),
children: [
_Intro(style: st),
const SizedBox(height: 14),
_TutorialPanel(
style: st,
icon: Icons.settings_ethernet,
title: '一、如何开启 RCON(必配,控制台/玩家管理需要)',
steps: [
steps: const [
'在服务器目录找到 server.properties 文件(与启动 jar 同目录)',
'修改/添加以下三行:',
' enable-rcon=true',
@@ -25,74 +41,79 @@ class HelpPage extends StatelessWidget {
'保存后重启服务器生效',
'回到 ZV Manager:服务器页 → 添加/编辑服务器,填入主机地址、端口(默认 25575)和 RCON 密码',
],
tips: [
tips: const [
'云服务器/虚拟主机需在防火墙或安全组放行 rcon.port 端口',
'不建议把 25575 端口直接暴露公网,强烈建议设置强密码',
],
),
_TutorialCard(
_TutorialPanel(
style: st,
icon: Icons.vpn_key,
title: '二、如何开启 SSH(模组管理 / 终端 / 下载自动上传需要)',
steps: [
steps: const [
'SSH 是服务器自带的远程管理服务,绝大多数独立服务器默认已开启(端口 22)',
'不确定的话:用电脑终端执行 ssh 用户名@服务器IP 试试能否登录',
'拿到 SSH 用户名(如 root)和密码',
'ZV Manager:服务器页 → 编辑服务器 → 打开「SSH 连接」开关 → 填端口(默认 22)、用户名、密码 → 保存',
],
tips: [
tips: const [
'部分面板服 / 虚拟主机只提供网页面板,不提供 SSH,此时模组和终端功能不可用(入口会提示)',
'有的托管商需要先在控制台开启 SSH/SFTP 功能',
'SSH 拥有服务器完全控制权,请勿随意执行不熟悉的命令',
],
),
_TutorialCard(
_TutorialPanel(
style: st,
icon: Icons.extension,
title: '三、模组 / 插件管理怎么用',
steps: [
steps: const [
'前提:该服务器已配置 SSH',
'进入「模组」页签,顶部切换 mods(模组)/ plugins(插件)目录',
'点「上传 jar」从手机选择文件上传;长按/点菜单可删除、重命名',
'点击文件名可查看详情:模组名、版本、作者、依赖',
'上传后需重启服务器才会加载新模组(可在终端执行,或控制台发 stop 后重开)',
],
tips: [
tips: const [
'Fabric 模组放 mods 目录;Paper/Spigot 插件放 plugins 目录',
'版本要和 MC 版本、加载器匹配,否则服务器起不来',
],
),
_TutorialCard(
_TutorialPanel(
style: st,
icon: Icons.download,
title: '四、下载中心与镜像加速',
steps: [
steps: const [
'进入「服务器」页 → 下载中心(或首页快捷入口)',
'输入关键词搜索 Modrinth 上的模组/插件,可用 MC 版本、加载器筛选',
'点结果选版本即可加入下载队列,支持暂停/继续/取消',
'下载完成且配置了 SSH 时,会自动上传到服务器的 mods/plugins 目录',
],
tips: [
tips: const [
'国内网络慢时:点右上角测速图标 →「一键测速并选择最快线路」,或改用自定义镜像地址',
'默认使用 MCIM 国内镜像,无需科学上网',
],
),
_TutorialCard(
_TutorialPanel(
style: st,
icon: Icons.terminal,
title: '五、远程终端',
steps: [
steps: const [
'前提:该服务器已配置 SSH',
'进入「终端」页签,点右上角 + 新建会话并选择服务器',
'等同于电脑上的 SSH 终端,可以执行任意命令',
'底部快捷键栏:Tab 补全、Ctrl+C 中断、Ctrl+D 退出、↑↓ 调历史,以及 htop / df -h / screen -r 常用命令',
'screen -r 可以进入服务器控制台会话(开服时用了 screen 的话)',
],
tips: [
tips: const [
'断网会自动重连(最多 3 次)',
'命令历史只保存在手机本地,可放心使用',
],
),
_TutorialCard(
_TutorialPanel(
style: st,
icon: Icons.account_tree,
title: '六、依赖仓库(查询模组依赖)',
steps: [
steps: const [
'进入「模组」页签 → 右上角依赖仓库',
'点「同步」扫描服务器 mods/plugins,建立本地依赖索引',
'点击任意模组查看:它依赖什么、被谁依赖、缺失哪些依赖',
@@ -100,10 +121,11 @@ class HelpPage extends StatelessWidget {
'点右上角重复检测按钮重复安装 / 版本冲突的 jar',
],
),
_TutorialCard(
_TutorialPanel(
style: st,
icon: Icons.help_outline,
title: '七、常见问题',
steps: [
steps: const [
'Q:连接失败?→ 检查防火墙是否放行端口、地址端口是否填对、服务器是否在线',
'Q:控制台能连但模组页提示无 SSH?→ 编辑服务器开启 SSH 并填好账号密码',
'Q:TPS 显示 —?→ 原版服务端不支持 tps 命令,Paper/Purpur 等服务端才支持',
@@ -116,30 +138,40 @@ class HelpPage extends StatelessWidget {
}
}
/// 顶部说明块。
class _Intro extends StatelessWidget {
const _Intro();
final ZStyle style;
const _Intro({required this.style});
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(14),
return ZPanel(style: style, children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'''${S.t('本页教您一步步开启并使用 ZV Manager 的各项功能。')}\n${S.t('首次使用建议按「一 → 二」顺序配置,其余功能即可解锁。')}''',
style: Theme.of(context).textTheme.bodyMedium,
'${S.t('本页教您一步步开启并使用 ZV Manager 的各项功能。')}\n'
'${S.t('首次使用建议按「一 → 二」顺序配置,其余功能即可解锁。')}',
style: TextStyle(
fontSize: 13.5,
height: 1.6,
color: style.hasWallpaper ? Colors.white : style.scheme.onSurface,
),
),
),
);
]);
}
}
class _TutorialCard extends StatelessWidget {
/// 单组教程:标题行(图标 + 粗标题 + 序号说明)+ 可展开的正文。
class _TutorialPanel extends StatelessWidget {
final ZStyle style;
final IconData icon;
final String title;
final List<String> steps;
final List<String> tips;
const _TutorialCard({
const _TutorialPanel({
required this.style,
required this.icon,
required this.title,
required this.steps,
@@ -148,49 +180,109 @@ class _TutorialCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Card(
margin: const EdgeInsets.symmetric(vertical: 6),
child: ExpansionTile(
leading: Icon(icon),
title: Text(S.t(title), style: theme.textTheme.titleSmall),
childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 14),
expandedCrossAxisAlignment: CrossAxisAlignment.start,
children: [
...steps.asMap().entries.map((e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${e.key + 1}. ',
style: TextStyle(
fontWeight: FontWeight.w600,
color: theme.colorScheme.primary)),
Expanded(child: Text(S.t(e.value))),
],
),
)),
if (tips.isNotEmpty) ...[
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
final scheme = Theme.of(context).colorScheme;
final textColor =
style.hasWallpaper ? Colors.white.withOpacity(0.92) : scheme.onSurface;
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Theme(
// 去掉 ExpansionTile 展开时的默认高亮背景,保持面板底色一致
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
),
child: ZPanel(style: style, children: [
ExpansionTile(
tilePadding: const EdgeInsets.fromLTRB(16, 4, 12, 4),
childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
expandedCrossAxisAlignment: CrossAxisAlignment.start,
iconColor: style.subColor,
collapsedIconColor: style.subColor,
leading: Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: theme.colorScheme.secondaryContainer.withOpacity(0.5),
borderRadius: BorderRadius.circular(8),
color: kZAccent.withOpacity(0.16),
borderRadius: BorderRadius.circular(11),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: tips
.map((t) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Text(S.t(t), style: theme.textTheme.bodySmall),
))
.toList(),
child: Icon(icon, size: 19, color: kZAccent),
),
title: Text(
S.t(title),
style: TextStyle(
fontSize: 14.5,
height: 1.35,
fontWeight: FontWeight.w700,
color: style.titleColor,
),
),
],
],
children: [
...steps.asMap().entries.map((e) {
final raw = S.t(e.value);
// 以空格开头的行是配置片段(如 " enable-rcon=true"),用等宽字体
final isCode = e.value.startsWith(' ');
return Padding(
padding: const EdgeInsets.only(bottom: 7),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${e.key + 1}.',
style: TextStyle(
fontSize: 13,
height: 1.5,
fontWeight: FontWeight.w700,
color: kZAccent,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
isCode ? raw.trim() : raw,
style: TextStyle(
fontSize: 13,
height: 1.5,
color: textColor,
fontFamily: isCode ? 'monospace' : null,
),
),
),
],
),
);
}),
if (tips.isNotEmpty) ...[
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: kZAccent.withOpacity(0.10),
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: tips
.map((t) => Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Text(
S.t(t),
style: TextStyle(
fontSize: 12.5,
height: 1.5,
color: style.subColor,
),
),
))
.toList(),
),
),
],
],
),
]),
),
);
}
+158 -71
View File
@@ -4,6 +4,8 @@ import 'package:provider/provider.dart';
import '../../core/services/sftp_service.dart';
import '../../core/l10n/strings.dart';
import '../../providers/server_provider.dart';
import '../../providers/wallpaper_provider.dart';
import '../../core/widgets/z_widgets.dart';
import '../dashboard/server_picker_bar.dart';
/// 服务器日志页(设置内入口):通过 SFTP 读取服务器 logs 目录,
@@ -157,108 +159,163 @@ class _ServerLogPageState extends State<ServerLogPage> {
@override
Widget build(BuildContext context) {
final servers = context.watch<ServerProvider>().servers;
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final st = ZStyle.of(context, hasWallpaper: hasWallpaper);
return Scaffold(
appBar: AppBar(title: T('服务器日志')),
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
title: T('服务器日志'),
backgroundColor: hasWallpaper ? Colors.transparent : null,
),
body: Column(
children: [
// ---------- 顶部:服务器 + 路径 + 自动刷新 ----------
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: DropdownButtonFormField<ServerConfig>(
value: _server != null && servers.any((s) => s.id == _server!.id)
? _server
: null,
decoration: InputDecoration(
labelText: S.t('选择服务器(需开启 SSH)'),
border: const OutlineInputBorder(),
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
child: ZPanel(style: st, children: [
ZRow(
title: '服务器',
subtitle: _server == null
? S.t('请选择一台已配置 SSH 的服务器')
: '${_server!.name} · ${_server!.sshUser}@${_server!.host}',
style: st,
leading: Icon(Icons.dns_outlined, size: 20, color: st.subColor),
trailing: DropdownButton<String>(
value: _server != null && servers.any((s) => s.id == _server!.id)
? _server!.id
: null,
underline: const SizedBox.shrink(),
borderRadius: BorderRadius.circular(12),
hint: T('选择'),
items: servers
.map((s) => DropdownMenuItem(
value: s.id,
child: SizedBox(
width: 110,
child: Text(s.name,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right),
),
))
.toList(),
onChanged: (id) {
final s = servers.where((e) => e.id == id).firstOrNull;
setState(() {
_server = s;
_files = [];
_error = null;
_pathCtrl.text = _defaultLogsDir(s);
});
},
),
),
items: servers
.map((s) => DropdownMenuItem(value: s, child: Text(s.name)))
.toList(),
onChanged: (s) {
setState(() {
_server = s;
_files = [];
_error = null;
_pathCtrl.text = _defaultLogsDir(s);
});
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Row(
children: [
Expanded(
ZDivider(style: st),
ZRow(
title: '日志目录',
subtitle: '默认按 SSH 用户推导,可手动修改',
style: st,
leading: Icon(Icons.folder_outlined, size: 20, color: st.subColor),
trailing: SizedBox(
width: 150,
child: TextField(
controller: _pathCtrl,
textAlign: TextAlign.right,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
decoration: InputDecoration(
labelText: S.t('日志目录路径'),
hintText: S.t('例如 /root/logs'),
border: const OutlineInputBorder(),
hintStyle: TextStyle(fontSize: 12, color: st.subColor),
border: InputBorder.none,
isDense: true,
),
),
),
const SizedBox(width: 8),
IconButton.filled(
onPressed: _loading ? null : _refresh,
tooltip: S.t('刷新'),
icon: const Icon(Icons.refresh),
),
ZDivider(style: st),
ZRow(
title: '自动刷新',
subtitle: '每 5 秒重新读取目录列表',
style: st,
leading: Icon(Icons.autorenew, size: 20, color: st.subColor),
trailing: ZToggle(
value: _autoRefresh,
size: 40,
borderColor: st.subColor,
onChanged: _toggleAuto,
),
],
),
),
]),
),
SwitchListTile(
title: T('自动刷新(每 5 秒)'),
value: _autoRefresh,
onChanged: _toggleAuto,
),
const Divider(height: 1),
Expanded(child: _buildList()),
// ---------- 文件列表 ----------
Expanded(child: _buildList(st)),
],
),
);
}
Widget _buildList() {
/// 日志文件列表:整块一个圆角面板,文件行之间用细线分隔。
Widget _buildList(ZStyle st) {
if (_loading && _files.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
padding: const EdgeInsets.all(28),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 12),
FilledButton(onPressed: _refresh, child: T('重试')),
Icon(Icons.cloud_off_outlined, size: 40, color: st.subColor),
const SizedBox(height: 14),
Text(_error!,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, height: 1.5, color: st.subColor)),
const SizedBox(height: 16),
FilledButton.tonal(onPressed: _refresh, child: T('重试')),
],
),
),
);
}
if (_files.isEmpty) {
return Center(child: T('目录下没有日志文件'));
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.description_outlined, size: 40, color: st.subColor),
const SizedBox(height: 12),
Text(S.t('目录下没有日志文件'),
style: TextStyle(fontSize: 13, color: st.subColor)),
const SizedBox(height: 16),
FilledButton.tonal(
onPressed: _loading ? null : _refresh,
child: T('刷新'),
),
],
),
);
}
return RefreshIndicator(
onRefresh: _refresh,
child: ListView.builder(
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: _files.length,
itemBuilder: (_, i) {
final f = _files[i];
return ListTile(
leading: const Icon(Icons.description_outlined),
title: Text(f.name, overflow: TextOverflow.ellipsis),
subtitle: Text(
'${_fmtSize(f.size)} · ${f.mtime.toLocal()}',
overflow: TextOverflow.ellipsis,
),
trailing: const Icon(Icons.chevron_right),
onTap: () => _viewFile(f),
);
},
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
children: [
ZPanel(style: st, children: [
for (var i = 0; i < _files.length; i++) ...[
if (i > 0) ZDivider(style: st),
ZRow(
title: _files[i].name,
subtitle: '${_fmtSize(_files[i].size)} · '
'${_files[i].mtime.toLocal().toString().substring(0, 19)}',
style: st,
leading: Icon(Icons.description_outlined,
size: 20, color: st.subColor),
onTap: () => _viewFile(_files[i]),
),
],
]),
],
),
);
}
@@ -342,7 +399,7 @@ class _LogViewerPageState extends State<_LogViewerPage> {
Widget build(BuildContext context) {
final lines = _content.split('\n');
return Scaffold(
appBar: AppBar(
appBar: ZAppBar(
title: Text(widget.title, overflow: TextOverflow.ellipsis),
actions: [
IconButton(
@@ -352,10 +409,36 @@ class _LogViewerPageState extends State<_LogViewerPage> {
),
],
),
bottomNavigationBar: SwitchListTile(
title: T('自动刷新并跟随底部(每 5 秒)'),
value: _autoRefresh,
onChanged: _toggleAuto,
// 底部工具条:自动刷新开关 + 回到底部,两者都是长日志场景的高频操作
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 10),
child: Row(
children: [
Expanded(
child: Text(
S.t('自动刷新并跟随底部(每 5 秒)'),
style: TextStyle(
fontSize: 13,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
TextButton.icon(
onPressed: _jumpBottom,
icon: const Icon(Icons.vertical_align_bottom, size: 18),
label: T('底部'),
),
const SizedBox(width: 6),
ZToggle(
value: _autoRefresh,
size: 40,
borderColor: Theme.of(context).colorScheme.onSurfaceVariant,
onChanged: _toggleAuto,
),
],
),
),
),
body: NotificationListener<ScrollNotification>(
onNotification: (n) {
@@ -367,10 +450,14 @@ class _LogViewerPageState extends State<_LogViewerPage> {
},
child: SingleChildScrollView(
controller: _controller,
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.all(14),
child: SelectableText(
lines.join('\n'),
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 12,
height: 1.45,
),
),
),
),
+191 -157
View File
@@ -7,6 +7,7 @@ import 'package:path_provider/path_provider.dart';
import '../../core/theme/app_theme.dart';
import '../../core/utils/background_service.dart';
import '../../core/widgets/background_widget.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/theme_provider.dart';
import '../../providers/wallpaper_provider.dart';
import 'help_page.dart';
@@ -55,39 +56,49 @@ class _SettingsPageState extends State<SettingsPage> {
void _showBackgroundPicker() {
showModalBottomSheet(
context: context,
builder: (ctx) => SafeArea(
child: Wrap(
children: [
ListTile(
leading: const Icon(Icons.photo, color: Colors.blue),
title: T('选择图片'),
onTap: () {
Navigator.pop(ctx);
_pickImage();
},
builder: (ctx) {
final st = ZStyle.of(ctx, hasWallpaper: false);
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: ZPanel(
style: st,
children: [
ZSheetRow(
icon: Icons.photo,
iconColor: Colors.blue,
title: '选择图片',
onTap: () {
Navigator.pop(ctx);
_pickImage();
},
),
ZDivider(style: st),
ZSheetRow(
icon: Icons.videocam,
title: '选择视频',
onTap: () {
Navigator.pop(ctx);
_pickVideo();
},
),
if (_currentBgPath != null) ...[
ZDivider(style: st),
ZSheetRow(
icon: Icons.delete,
danger: true,
title: '清除背景',
onTap: () {
Navigator.pop(ctx);
_clearBackground();
},
),
],
],
),
ListTile(
leading: const Icon(Icons.videocam, color: Colors.green),
title: T('选择视频'),
onTap: () {
Navigator.pop(ctx);
_pickVideo();
},
),
if (_currentBgPath != null) ...[
const Divider(),
ListTile(
leading: const Icon(Icons.delete, color: Colors.red),
title: T('清除背景', style: TextStyle(color: Colors.red)),
onTap: () {
Navigator.pop(ctx);
_clearBackground();
},
),
],
],
),
),
),
);
},
);
}
@@ -114,18 +125,40 @@ class _SettingsPageState extends State<SettingsPage> {
final provider = context.read<LanguageProvider>();
final mode = await showDialog<LanguageMode>(
context: context,
builder: (_) => SimpleDialog(
title: T('语言 / Language'),
children: [
for (final m in LanguageMode.values)
RadioListTile<LanguageMode>(
title: Text(_languageName(m)),
value: m,
groupValue: provider.mode,
onChanged: (v) => Navigator.pop(context, v),
builder: (ctx) {
final st = ZStyle.of(ctx, hasWallpaper: false);
return Dialog(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 8),
child: T('语言 / Language', style: Theme.of(ctx).textTheme.titleMedium),
),
ZPanel(
style: st,
children: [
for (final m in LanguageMode.values) ...[
if (m != LanguageMode.values.first) ZDivider(style: st),
ZSheetRow(
icon: Icons.language,
title: _languageName(m),
trailing: provider.mode == m
? Icon(Icons.check_circle_rounded, color: kZAccent, size: 22)
: Icon(Icons.circle_outlined, color: st.subColor, size: 22),
onTap: () => Navigator.pop(ctx, m),
),
],
],
),
],
),
],
),
),
);
},
);
if (mode != null) await provider.setMode(mode);
}
@@ -226,133 +259,134 @@ class _SettingsPageState extends State<SettingsPage> {
@override
Widget build(BuildContext context) {
final themeProvider = context.watch<ThemeProvider>();
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final scheme = Theme.of(context).colorScheme;
final st = ZStyle(hasWallpaper: hasWallpaper, scheme: scheme);
return Scaffold(
appBar: AppBar(title: T('设置')),
backgroundColor: hasWallpaper ? Colors.transparent : null,
// 透明 AppBar,让壁纸延伸到顶
appBar: ZAppBar(
title: T('设置'),
backgroundColor: Colors.transparent,
),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
children: [
// ---------- 外观主题 ----------
ListTile(
leading: const Icon(Icons.palette_outlined),
title: T('外观主题'),
trailing: SegmentedButton<AppThemeMode>(
segments: const [
ButtonSegment(value: AppThemeMode.light, icon: Icon(Icons.light_mode, size: 18)),
ButtonSegment(value: AppThemeMode.dark, icon: Icon(Icons.dark_mode, size: 18)),
ButtonSegment(value: AppThemeMode.system, icon: Icon(Icons.brightness_auto, size: 18)),
],
selected: {themeProvider.themeMode},
onSelectionChanged: (v) => themeProvider.setThemeMode(v.first),
style: SegmentedButton.styleFrom(visualDensity: VisualDensity.compact),
ZPanel(style: st, children: [
// ---------- 外观主题 ----------
ZRow(
title: '外观主题',
subtitle: '亮色、暗色或跟随系统',
style: st,
trailing: ZSegmentedCircles<AppThemeMode>(
value: themeProvider.themeMode,
onChanged: (m) => themeProvider.setThemeMode(m),
onSurface: st.titleColor,
options: const [
ZCircleOption(value: AppThemeMode.light, icon: Icons.light_mode),
ZCircleOption(value: AppThemeMode.dark, icon: Icons.dark_mode),
ZCircleOption(
value: AppThemeMode.system, icon: Icons.brightness_auto),
],
),
),
),
const Divider(),
// ---------- 应用背景(新增) ----------
ListTile(
leading: const Icon(Icons.wallpaper),
title: T('应用背景'),
subtitle: Text(
_currentBgPath == null
? '未设置'
: S.f('已设置 {0}', [_currentBgType == 'video' ? S.t('视频') : S.t('图片')]),
ZDivider(style: st),
ZRow(
title: '应用背景',
subtitle: '选择一张图片或一段视频作为应用背景',
style: st,
value: _currentBgPath == null
? S.t('未设置')
: S.f('{0}',
[_currentBgType == 'video' ? S.t('视频') : S.t('图片')]),
onTap: _showBackgroundPicker,
),
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
onTap: _showBackgroundPicker,
),
// ---------- 视频声音开关 ----------
if (_currentBgType == 'video') ...[
SwitchListTile(
secondary: const Icon(Icons.volume_up),
title: T('视频声音'),
subtitle: T('开启后背景视频将播放声音'),
value: _videoSoundEnabled,
onChanged: (value) async {
await BackgroundService.setVideoSound(value);
setState(() => _videoSoundEnabled = value);
// 立即应用到正在播放的背景视频,无需重建图层
backgroundWidgetKey.currentState?.applyVideoSound(value);
},
if (_currentBgType == 'video') ...[
ZDivider(style: st),
ZRow(
title: '视频声音',
subtitle: '开启后背景视频将播放声音',
style: st,
trailing: ZToggle(
value: _videoSoundEnabled,
borderColor: st.subColor,
onChanged: (value) async {
await BackgroundService.setVideoSound(value);
setState(() => _videoSoundEnabled = value);
// 立即应用到正在播放的背景视频,无需重建图层
backgroundWidgetKey.currentState?.applyVideoSound(value);
},
),
),
],
]),
const SizedBox(height: 14),
ZPanel(style: st, children: [
// ---------- 语言 ----------
ZRow(
title: '语言 / Language',
subtitle: '界面显示语言',
style: st,
value: _languageName(context.watch<LanguageProvider>().mode),
onTap: _pickLanguage,
),
],
const Divider(),
// ---------- 语言 ----------
ListTile(
leading: const Icon(Icons.language),
title: T('语言 / Language'),
subtitle: Text(_languageName(context.watch<LanguageProvider>().mode)),
trailing: const Icon(Icons.chevron_right),
onTap: () => _pickLanguage(),
),
const Divider(),
// ---------- 下载与镜像 ----------
ListTile(
leading: const Icon(Icons.download_outlined),
title: T('下载与镜像设置'),
subtitle: T('镜像线路、测速选线、同时下载任务数'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const DownloadSettingsPage()),
ZDivider(style: st),
ZRow(
title: '下载与镜像设置',
subtitle: '镜像线路、测速选线、同时下载任务数',
style: st,
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const DownloadSettingsPage()),
),
),
),
const Divider(),
// ---------- 服务器日志 ----------
ListTile(
leading: const Icon(Icons.receipt_long_outlined),
title: T('服务器日志'),
subtitle: T('通过 SSH 查看服务器 logs 目录日志输出'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const ServerLogPage()),
ZDivider(style: st),
ZRow(
title: '服务器日志',
subtitle: '通过 SSH 查看服务器 logs 目录日志输出',
style: st,
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const ServerLogPage()),
),
),
),
const Divider(),
// ---------- 使用教程 ----------
ListTile(
leading: const Icon(Icons.menu_book_outlined),
title: T('使用教程'),
subtitle: T('如何开启 RCON / SSH、模组管理、下载与终端'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const HelpPage()),
]),
const SizedBox(height: 14),
ZPanel(style: st, children: [
ZRow(
title: '使用教程',
subtitle: '如何开启 RCON / SSH、模组管理、下载与终端',
style: st,
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const HelpPage()),
),
),
),
const Divider(),
// ---------- 用户须知 ----------
ListTile(
leading: const Icon(Icons.gavel_outlined),
title: T('用户须知'),
subtitle: T('查看用户守则全部条款'),
trailing: const Icon(Icons.chevron_right),
onTap: () => showDialog(
context: context,
barrierDismissible: true,
builder: (_) => UserAgreementDialog.readView(),
ZDivider(style: st),
ZRow(
title: '用户须知',
subtitle: '查看用户守则全部条款',
style: st,
onTap: () => showDialog(
context: context,
barrierDismissible: true,
builder: (_) => UserAgreementDialog.readView(),
),
),
),
const Divider(),
// ---------- 关于软件(检查更新 + 创造者 + 开源许可) ----------
ListTile(
leading: const Icon(Icons.info_outline),
title: T('关于软件'),
subtitle: T('版本、检查更新、创造者与开源许可'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AboutPage()),
ZDivider(style: st),
ZRow(
title: '关于软件',
subtitle: '版本、检查更新、创造者与开源许可',
style: st,
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AboutPage()),
),
),
),
]),
],
),
);
}
}
}
@@ -1,10 +1,12 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import '../../providers/wallpaper_provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
class WallpaperSettings extends StatelessWidget {
const WallpaperSettings({super.key});
@@ -15,10 +17,14 @@ class WallpaperSettings extends StatelessWidget {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
appBar: ZAppBar(
title: T('壁纸设置'),
backgroundColor: theme.colorScheme.primary,
foregroundColor: Colors.white,
systemOverlayStyle: const SystemUiOverlayStyle(
statusBarIconBrightness: Brightness.light,
statusBarBrightness: Brightness.dark,
),
),
body: ListView(
padding: const EdgeInsets.all(16),
+52 -12
View File
@@ -12,6 +12,7 @@ import '../player_management/player_list_page.dart';
import '../settings/settings_page.dart';
import '../terminal/terminal_page.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/z_widgets.dart';
/// 主导航壳:底部导航「服务器 · 控制台 · 玩家 · 模组 · 终端 · 我的」(M4)。
class MainShell extends StatefulWidget {
@@ -27,6 +28,7 @@ class _MainShellState extends State<MainShell> {
@override
Widget build(BuildContext context) {
final en = context.watch<LanguageProvider>().isEnglish;
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final labels = en
? ['Servers', 'Console', 'Players', 'Mods', 'Terminal', 'Me']
: ['服务器', '控制台', '玩家', '模组', '终端', '我的'];
@@ -40,18 +42,56 @@ class _MainShellState extends State<MainShell> {
];
return Scaffold(
body: IndexedStack(index: _index, children: pages),
bottomNavigationBar: NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: [
for (var i = 0; i < 6; i++)
NavigationDestination(
icon: _navIcon(i, false),
selectedIcon: _navIcon(i, true),
label: labels[i],
),
],
bottomNavigationBar: _buildNavBar(context, hasWallpaper, labels),
);
}
/// 底部导航栏:无壁纸走主题(绿色选中态);有壁纸时半透明深底 + 白色图标/文字,保持 ZL2 沉浸感。
Widget _buildNavBar(BuildContext context, bool hasWallpaper, List<String> labels) {
final navBar = NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: [
for (var i = 0; i < 6; i++)
NavigationDestination(
icon: _navIcon(i, false),
selectedIcon: _navIcon(i, true),
label: labels[i],
),
],
);
if (!hasWallpaper) return navBar; // 使用 app_theme 中的 ZL2 绿主题
final wallpaperNavTheme = NavigationBarThemeData(
height: 72,
elevation: 0,
backgroundColor: Colors.black.withOpacity(0.38),
surfaceTintColor: Colors.transparent,
indicatorColor: Colors.white.withOpacity(0.18),
indicatorShape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(16)),
),
labelBehavior: NavigationDestinationLabelBehavior.alwaysShow,
labelTextStyle: WidgetStateProperty.resolveWith((states) {
final selected = states.contains(WidgetState.selected);
return TextStyle(
fontSize: 12,
fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
color: selected ? Colors.white : Colors.white.withOpacity(0.62),
);
}),
iconTheme: WidgetStateProperty.resolveWith((states) {
final selected = states.contains(WidgetState.selected);
return IconThemeData(
size: 24,
color: selected ? Colors.white : Colors.white.withOpacity(0.62),
);
}),
);
return Theme(
data: Theme.of(context).copyWith(navigationBarTheme: wallpaperNavTheme),
child: navBar,
);
}
@@ -81,7 +121,7 @@ class _TabScaffold extends StatelessWidget {
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
return Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: AppBar(
appBar: ZAppBar(
title: subtitle == null || subtitle!.isEmpty
? Text(title)
: Column(
+89 -11
View File
@@ -8,6 +8,7 @@ import '../../core/services/ssh_shell_service.dart';
import '../../providers/server_provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/widgets/empty_state_page.dart';
import '../../core/widgets/z_widgets.dart';
/// SSH 终端页:xterm 终端 + 快捷键栏 + 多服务器会话标签(M3)。
@@ -92,7 +93,7 @@ class _TerminalPageState extends State<TerminalPage>
final active = _sessions[_activeId];
return Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: AppBar(
appBar: ZAppBar(
title: T('终端'),
actions: [
PopupMenuButton<ServerConfig>(
@@ -112,14 +113,17 @@ class _TerminalPageState extends State<TerminalPage>
height: 44,
child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
children: _sessions.values.map((s) {
final selected = s.server.id == _activeId;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6),
child: ChoiceChip(
label: Text(s.server.name),
padding: const EdgeInsets.symmetric(
horizontal: 4, vertical: 6),
child: _SessionTab(
label: s.server.name,
selected: selected,
onSelected: (_) => setState(() => _activeId = s.server.id),
onTap: () =>
setState(() => _activeId = s.server.id),
),
);
}).toList(),
@@ -128,7 +132,18 @@ class _TerminalPageState extends State<TerminalPage>
),
),
body: active == null
? const Center(child: T('选择一台服务器开始会话'))
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.terminal_rounded,
size: 36,
color: Theme.of(context).colorScheme.onSurfaceVariant),
const SizedBox(height: 12),
T('选择一台服务器开始会话'),
],
),
)
: Column(
children: [
Expanded(
@@ -150,7 +165,10 @@ class _TerminalPageState extends State<TerminalPage>
Widget _buildQuickBar() {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest.withOpacity(0.5),
color: Theme.of(context).colorScheme.surfaceContainerHigh.withOpacity(0.5),
border: Border(
top: BorderSide(color: Theme.of(context).colorScheme.outlineVariant),
),
),
child: SafeArea(
child: SizedBox(
@@ -179,11 +197,71 @@ class _TerminalPageState extends State<TerminalPage>
/// 生成一个快捷按键按钮。
/// [data] 是实际写入终端的字节(含控制字符或带换行的整条命令)。
Widget _key(String label, String data) {
final scheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: ActionChip(
label: Text(label),
onPressed: () => _sendKey(data),
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Center(
child: GestureDetector(
onTap: () => _sendKey(data),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(20),
),
child: Text(
label,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 12,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
),
),
),
);
}
}
/// 终端会话切换标签:选中的用品牌色填充,未选中为透明描边。
class _SessionTab extends StatelessWidget {
final String label;
final bool selected;
final VoidCallback onTap;
const _SessionTab({
required this.label,
required this.selected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 6),
decoration: BoxDecoration(
color: selected ? kZAccent : Colors.transparent,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: selected ? kZAccent : scheme.outlineVariant,
),
),
child: Center(
child: Text(
label,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: selected ? Colors.white : scheme.onSurfaceVariant,
),
),
),
),
);
}
+1 -1
View File
@@ -1,6 +1,6 @@
name: zv_manager
description: Minecraft服务器管理工具
version: 2.0.1+14
version: 2.0.3+16
environment:
sdk: ">=3.0.0 <4.0.0"
+219
View File
@@ -0,0 +1,219 @@
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:zv_manager/core/theme/app_theme.dart';
import 'package:zv_manager/core/utils/update_info.dart';
import 'package:zv_manager/core/widgets/update_dialog.dart';
/// 预览测试默认跳过,避免普通测试运行时生成图片。
///
/// 运行方式:
/// UPDATE_DIALOG_PREVIEW=1 flutter test test/update_dialog_preview_test.dart
///
/// 生成的文件:
/// build/preview/update_dialog_dark.png
/// build/preview/update_dialog_light.png
final bool _previewEnabled =
Platform.environment['UPDATE_DIALOG_PREVIEW'] == '1';
final _previewKey = GlobalKey();
late final String _cjkFontPath;
const _releaseNotes = '''
## 更新内容
* 同步flutter 3.47变更,更新版本
* docs: 补充页面层与玩家服务的方法级注释
* style: 主题改用 Material 3 tonal 色板与标准形状体系(参考 ZL2)
* style: 全面 UI 美化——统一圆角/配色/间距主题体系
* fix: 模组/终端页空状态改为统一引导页(带标题栏)
* fix: 移除控制台页右上角重复的玩家管理入口(与底部玩家页签重复)
* fix: Gradle 发行包改用腾讯镜像,修复国内下载超时
**完整的更新日志**: https://gitee.com/driftinblock/zvmanager/compare/v2.0.0...v2.0.1
''';
final _info = UpdateInfo(
latestVersion: '2.0.1',
downloadUrl: 'https://example.com/ZVManager-v2.0.1.apk',
apkName: 'ZVManager-v2.0.1.apk',
releaseNotes: _releaseNotes,
releasedAt: DateTime(2026, 10, 27, 21, 56, 7),
releasePageUrl:
'https://gitee.com/driftinblock/zvmanager/releases/tag/v2.0.1',
);
Future<void> _loadFont(String family, String path) async {
final bytes = await File(path).readAsBytes();
final loader = FontLoader(family)
..addFont(Future<ByteData>.value(ByteData.sublistView(bytes)));
await loader.load();
}
String? _firstExisting(List<String> paths) {
for (final path in paths) {
if (File(path).existsSync()) return path;
}
return null;
}
String? _materialIconsPath() {
final flutterRoot = Platform.environment['FLUTTER_ROOT'];
final candidates = <String>[
if (flutterRoot != null)
'$flutterRoot/bin/cache/artifacts/material_fonts/MaterialIcons-Regular.otf',
// 从 Dart 可执行文件反推 Flutter SDK 根目录。
'${File(Platform.resolvedExecutable).parent.parent.parent.parent.parent.path}'
'/bin/cache/artifacts/material_fonts/MaterialIcons-Regular.otf',
];
return _firstExisting(candidates);
}
ThemeData _withPreviewFont(ThemeData base) {
final filledStyle = base.filledButtonTheme.style;
final outlinedStyle = base.outlinedButtonTheme.style;
return base.copyWith(
textTheme: base.textTheme.apply(fontFamily: 'Roboto'),
primaryTextTheme: base.primaryTextTheme.apply(fontFamily: 'Roboto'),
// 按钮的 textStyle 在主题里单独定义,不会自动继承 textTheme 的字体。
filledButtonTheme: FilledButtonThemeData(
style: filledStyle?.copyWith(
textStyle: WidgetStatePropertyAll(
(filledStyle.textStyle?.resolve(<WidgetState>{}) ?? const TextStyle())
.copyWith(fontFamily: 'Roboto'),
),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: outlinedStyle?.copyWith(
textStyle: WidgetStatePropertyAll(
(outlinedStyle.textStyle?.resolve(<WidgetState>{}) ??
const TextStyle())
.copyWith(fontFamily: 'Roboto'),
),
),
),
);
}
Future<void> _pumpAndOpen(
WidgetTester tester, {
required ThemeData theme,
required Color background,
}) async {
tester.view.physicalSize = const Size(824, 1830);
tester.view.devicePixelRatio = 2.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
RepaintBoundary(
key: _previewKey,
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: _withPreviewFont(theme),
home: Scaffold(
backgroundColor: background,
body: Builder(
builder: (context) => Center(
child: FilledButton(
onPressed: () => showDialog<void>(
context: context,
builder: (_) => UpdateDialog(
info: _info,
currentVersion: '2.0.0',
onUpdate: () {},
onOpenUrl: (_) {},
),
),
child: const Text('打开更新弹窗'),
),
),
),
),
),
),
);
await tester.tap(find.text('打开更新弹窗'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
}
Future<void> _savePreview(WidgetTester tester, String path) async {
final boundary =
tester.renderObject<RenderRepaintBoundary>(find.byKey(_previewKey));
// toByteData 依赖真实异步,必须放在 runAsync 里,否则测试会卡住。
await tester.runAsync(() async {
final image = await boundary.toImage(pixelRatio: 2.0);
final data = await image.toByteData(format: ui.ImageByteFormat.png);
final file = File(path);
await file.parent.create(recursive: true);
await file.writeAsBytes(data!.buffer.asUint8List());
// ignore: avoid_print
print('预览图已生成:${file.absolute.path}');
});
}
void main() {
setUpAll(() async {
if (!_previewEnabled) return;
_cjkFontPath = _firstExisting(const [
'/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc',
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
'/usr/local/share/fonts/WindowsFonts/msyh.ttc',
'/usr/local/share/fonts/WindowsFonts/simhei.ttf',
'/System/Library/Fonts/PingFang.ttc',
r'C:\Windows\Fonts\msyh.ttc',
r'C:\Windows\Fonts\simhei.ttf',
]) ??
'';
if (_cjkFontPath.isEmpty) {
fail('没有找到可用的中文字体,无法生成预览图。');
}
// 测试环境默认字体是 Ahem;把中文字体注册成 Roboto/Ahem,
// 这样主题文字和按钮文字都能正常显示中文。
await _loadFont('Roboto', _cjkFontPath);
await _loadFont('Ahem', _cjkFontPath);
final iconsPath = _materialIconsPath();
if (iconsPath != null) {
await _loadFont('MaterialIcons', iconsPath);
}
});
testWidgets(
'生成深色更新弹窗预览图',
(tester) async {
await _pumpAndOpen(
tester,
theme: AppTheme.darkTheme,
background: const Color(0xFF101410),
);
await _savePreview(tester, 'build/preview/update_dialog_dark.png');
expect(tester.takeException(), isNull);
},
skip: !_previewEnabled,
);
testWidgets(
'生成浅色更新弹窗预览图',
(tester) async {
await _pumpAndOpen(
tester,
theme: AppTheme.lightTheme,
background: const Color(0xFFF7FAF5),
);
await _savePreview(tester, 'build/preview/update_dialog_light.png');
expect(tester.takeException(), isNull);
},
skip: !_previewEnabled,
);
}
+96
View File
@@ -0,0 +1,96 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:zv_manager/core/utils/update_info.dart';
import 'package:zv_manager/core/widgets/update_dialog.dart';
void main() {
testWidgets('更新弹窗展示版本、时间和更新日志', (tester) async {
tester.view.physicalSize = const Size(360, 640);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final info = UpdateInfo(
latestVersion: '2.0.1',
downloadUrl: 'https://example.com/app.apk',
apkName: 'app.apk',
releaseNotes: '## 更新内容\n'
'* feat: 新增 A\n'
'* fix: 修复 B\n'
'\n'
'**完整的更新日志**: https://example.com/log',
releasedAt: DateTime.parse('2026-10-27T21:56:07+08:00'),
releasePageUrl:
'https://gitee.com/driftinblock/zvmanager/releases/tag/v2.0.1',
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: UpdateDialog(
info: info,
currentVersion: '2.0.0',
onUpdate: () {},
onOpenUrl: (_) {},
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('发现新版本'), findsOneWidget);
expect(find.text('2.0.1'), findsOneWidget);
expect(find.textContaining('2026'), findsOneWidget);
expect(find.text('2.0.0'), findsOneWidget);
expect(find.text('更新'), findsOneWidget);
expect(find.text('修复'), findsOneWidget);
expect(find.text('新增 A'), findsOneWidget);
expect(find.text('修复 B'), findsOneWidget);
expect(find.text('查看发布页'), findsOneWidget);
expect(find.text('忽略'), findsOneWidget);
expect(find.text('立即更新'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('长更新日志可滚动且不溢出', (tester) async {
tester.view.physicalSize = const Size(360, 640);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final info = UpdateInfo(
latestVersion: '2.0.1',
downloadUrl: 'https://example.com/app.apk',
apkName: 'app.apk',
releaseNotes: '## 更新内容\n${[
for (var i = 1; i <= 40; i++) '* feat: 第 $i 条更新说明',
].join('\n')}',
releasePageUrl:
'https://gitee.com/driftinblock/zvmanager/releases/tag/v2.0.1',
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: UpdateDialog(
info: info,
currentVersion: '2.0.0',
onUpdate: () {},
onOpenUrl: (_) {},
),
),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('第 1 条更新说明'), findsOneWidget);
await tester.drag(
find.byType(SingleChildScrollView),
const Offset(0, -400),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
});
}
+69
View File
@@ -0,0 +1,69 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:zv_manager/core/utils/release_notes.dart';
import 'package:zv_manager/core/utils/update_service.dart';
void main() {
group('UpdateService.isNewerVersion', () {
test('不会把旧版本当成新版本', () {
expect(UpdateService.isNewerVersion('2.0.1', '2.0.3'), isFalse);
});
test('识别更高版本', () {
expect(UpdateService.isNewerVersion('2.0.3', '2.0.1'), isTrue);
expect(UpdateService.isNewerVersion('v2.1.0', '2.0.9'), isTrue);
expect(UpdateService.isNewerVersion('2.0', '2.0.0'), isFalse);
});
test('空版本不会触发更新', () {
expect(UpdateService.isNewerVersion('', '2.0.0'), isFalse);
});
});
group('ReleaseNotes.parse', () {
test('按 feat/fix 前缀分组并提取完整日志链接', () {
final notes = ReleaseNotes.parse(
'## 更新内容\n'
'* feat: 新增 A\n'
'* fix: 修复 B\n'
'* docs: 补充 C\n'
'\n'
'**完整的更新日志**: https://gitee.com/driftinblock/zvmanager/compare/v2.0.0...v2.0.1\n',
);
expect(notes.sections.length, 2);
expect(notes.sections[0].title, '更新');
expect(
notes.sections[0].items.map((item) => item.text),
['新增 A', '补充 C'],
);
expect(notes.sections[1].title, '修复');
expect(
notes.sections[1].items.map((item) => item.text),
['修复 B'],
);
expect(notes.links.single.label, '完整的更新日志');
expect(
notes.links.single.url,
'https://gitee.com/driftinblock/zvmanager/compare/v2.0.0...v2.0.1',
);
});
test('纯文本发布说明回退到更新分组', () {
final notes = ReleaseNotes.parse('卡片式服务器列表 + 壁纸切换闪屏修复');
expect(notes.sections.single.title, '更新');
expect(
notes.sections.single.items.single.text,
'卡片式服务器列表 + 壁纸切换闪屏修复',
);
expect(notes.sections.single.items.single.bullet, isFalse);
});
test('保留自定义小标题', () {
final notes = ReleaseNotes.parse('## 注意事项\n* 更新前请先备份');
expect(notes.sections.single.title, '注意事项');
expect(notes.sections.single.items.single.text, '更新前请先备份');
});
});
}
+30
View File
@@ -0,0 +1,30 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:zv_manager/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const Bootstrap());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}